text:
Q: Is there a reason to use a real serialVersionUID? This question is an exact duplicate of:

Why generate long serialVersionUID instead of a simple 1L?

Ironically, answered by Michael Bogswardt as well.

Michael Bogswardt's answer to generating a serialVersionUID got me thinking. Is there any reason to generate a proper serialVersionUID like eclipse and IDEA (or just plain serialver)? Or is plugging in a 1L just as good?

A: The only use of a "real" serialVersionUID is for backword compatibility.  If it is a new class, use whatever numbering system you want.
Personally I think using a simple number scheme will make it easier to read and compare changes of that number between versions.  The hash value creating by the tooling is fine for a machine, but not human friendly.  A simple one up numbering scheme works great for both, after all, the machine doesn't care one way or the other.

A: Once you write a number (any number) in there, it's your responsability to bump it when you make compatibility-breaking changes to the class (e.g. changing a JavaDoc doesn't break it, adding a property definitely does).
If you avoid specifying a serialVersionUID, javac will put there something unique like the hash of the class.
When does it matter? When you serialize stuff to disk and want to load it later with a different version of your program.
Or when two instances which may be of different versions need to exchange serialized data over the wire.
If you don't use actual serialization and your class is Serializable just because it inherits that interface, then avoiding a serialVersionUID is the easiest and most safe thing to do. Same if you do serialize but don't really need to be compatible with the past, also in that case avoiding the value is the safest thing to do.
If, on the other hand, you need to load stuff produced with past revisions (either remotely or by yourself, from a long-forgotten file on disk) then you need to have that value and take much care to bump the number when (and only when) you do actually break the compatibility.
ADDED after second comment (by Robin):

Doesn't answer the actual question.

Err, right. I guess that's a: no as far as I know the actual number means nothing, it only has to be different from all previous value it had in previous times, when it is no more compatible with them.

Also, you should always declare a serialVersionUID for your Serializable classes

As a general suggestion, I think avoiding it is a better solution: most of the time you don't need to talk with JVM of different vendors, you don't need to de-serialize data from long past or actually need that compatibility check, most of the times serialized object are very short-lived.
Of course that can be very different for different projects and when you do have long-lived serialized object, well, you have to take the burden of defining those UID, and maintaining them correctly.
But as an absent UID means "fail fast, catch errors", while using 1L (or any other constant number) usually means "the class changes, you didn't remember to update it, problems arise later", then as a general suggestion, I think the first is a better default.


text:
Q: Forward non-www to www except for specific subdomain I am routing all non-www requests to the www-domain by using this RewriteCond and RewriteRule:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.mydomain.tld/$1 [R=301,L]

But there is one certain subdomain that I want to exclude, e.g. blog.mydomain.tld. How do I have to modify my condition and rule in order to achieve this?

A: You can just add that subdomain in regex of your RewriteCond:
RewriteEngine On

RewriteCond %{HTTP_HOST} !^(www|blog)\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L,NE]

A: Did you try adding
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} !^blog\.
RewriteRule ^(.*)$ http://www.mydomain.tld/$1 [R=301,L]

redpajama_set_name: RedPajamaStackExchange


text:
Q: setInterval() function not working as expected I'm trying to switch the background color from rgb(255,255,255) to rgb(0,0,0) and going through all the possibilities with setInterval between every two colors, but for some reason, at the moment that I activate the function start(), the background color immediately becomes black. does anyone know how to fix this?
I don't have any idea for a solution, so I'm open to any idea.
    function start() {

        var red = 255;
        var green = 255;
        var blue = 255;

        var id = setInterval(colorful(), 1000);

        function colorful() {

            document.body.style.backgroundColor = "rgb(" + [red,green,blue].join(",") + ")";

            if (blue == 0) {blue = 0; green--;}

            if (green == 0) {green = 0; red--;}

            if (red == 0) {clearInterval(id);}

            blue--;

        }
    }

I expected to see the background color change and go through all the rgb() colors from 0 to 255, but instead when I run the start() function the screen turns immediately black.

A: There is a issue in your code, once fixed it works as expected.
Remove the brackets from the method passed to setInterval and check the boundaries of your color variables in order to avoid negative values:
var id = setInterval(colorful, 100);

Working snippet:

 function start() {

    var red = 255;
    var green = 255;
    var blue = 255;

    var id = setInterval(colorful, 10);

    function colorful() {
        document.body.style.backgroundColor = "rgb(" + [red,green,blue].join(",") + ")";

        if (blue === 0 && green > 0) {green--;}

        if (green === 0 && red > 0) {red--;}

        if (red === 0) {clearInterval(id);}

        if (blue > 0) blue--;
}}

start();

A: It works with your code, if you change the colorful() to colorful inside the setTimeout call. And you need to change the interval duration from 1000 to 5
But be aware: 5ms is a really short time, it is not guaranteed that it will work that fast.

function start() {

  var red = 255;
  var green = 255;
  var blue = 255;

  var id = setInterval(colorful, 5);

  function colorful() {
    document.body.style.backgroundColor = "rgb(" + [red, green, blue].join(",") + ")";

    blue--;
    if (blue <= 0) {
      blue = 0;
      green--;
    }

    if (green <= 0) {
      green = 0;
      red--;
    }

    if (red <= 0) {
      clearInterval(id);
    }

  }
}

start()

You would be better of with a CSS animation.

@keyframes animate-bg-fade-white-to-black {
  0% {
    background-color: #fff;
  }
  33% {
    background-color: #ff0;
  }
  67% {
    background-color: #f00;
  }
  100% {
    background-color: #000;
  }
}

body {
  animation: animate-bg-fade-white-to-black 2s linear both;
}


text:
Q: How can i get first 100 rows , then next 100 rows , until you get all the records in cassandra? I am having a table that has millions of records. I would like to purge the old data from these cassandra table.
the following is my table definition.
CREATE TABLE "Openmind".mep_notification (
    id uuid PRIMARY KEY,
    campaign uuid,
    created timestamp,
    flight uuid,
    read boolean,
    type text,
    user uuid
);

CREATE INDEX mep_notification_user_idx ON "Openmind".mep_notification (user);

how I can get first X number of rows at a time using cql. then the next X number and so on till i get all the rows from the table.
appreciate if you can help
thank you

A: You can use the limit to get X numbers of rows. See the example bellow:
SELECT *
FROM cycling.rank_by_year_and_name
PER PARTITION LIMIT 2;

DataStax documentation:
https://docs.datastax.com/en/dse/5.1/cql/cql/cql_using/useQueryColumnsSort.html
If you trying to do a pagination, you can use the Pagin. Depending the program language you are using, you can check the rigth application to the Pagin.
DataStax documentation:
https://docs.datastax.com/en/cql-oss/3.3/cql/cql_reference/cqlshPaging.html

*

*In CQL prompt: https://docs.datastax.com/en/dse/6.8/cql/cql/cql_using/search_index/cursorsDeepPaging.html

*In Java:
https://docs.datastax.com/en/developer/java-driver/3.11/manual/paging/

*In PHP : https://datastax.github.io/php-driver/features/result_paging/

*In Spring Boot :
https://docs.spring.io/spring-data/cassandra/docs/current/reference/html/#reference


text:
Q: Ver codigo fuente html, seguridad Tengo en mi código html esta instrucción:
style="display:none;
El problema es que desde la inspección de código fuente pueden modificarlo y así poder ver el div en el que se encuentra la instrucción.
¿Hay alguna forma para que no puedan modificar esto?

A: Lamentablemente, una vez que la información es presentada en la interfaz (ya sea en elementos visibles o no visibles), no hay forma de controlar lo que un usuario hará con ella. Si es información confidencial o restringida, lo mejor es que:

*

*No la mostrés; o

*La mostrés cifrada o ilegible, de forma que solamente la aplicación pueda usar la información que estás mostrando.

Recordá que ningún método de ocultar información que es accesible a la interfaz es del todo confiable, ya que con un poco de interacción con la consola, se puede acceder a cualquier información que ya fue mostrada en la página.
Las validaciones para los valores que no querés que se modifiquen en la interfaz deben estar a nivel del controlador (o quien vaya a recibir el contenido que querés mantener íntegro).

A: Ocultar cosas en el html da una falsa sensación de seguridad, no hace falta consola para descubrirlas.
Desde un marcador (bookmark/favorito) podes ejecutar javascript en el contexto de la página actual.
En este caso busco los divs y les pongo display block, podes cambiar el color del texto /fondo etc...
Algo mas elaborado sería tomar info y enviarla a un servidor con el cors promiscuo para análisis posterior, recorrer el DOM y recrearlo en un div fixed para ver todas las clases y contenidos, etc...
Para crear un marcador con javascript le pones javascript: como protocolo en la url, o arrastrando un enlace que ya tenga la url armada a la barra de marcadores/favoritos.
Darle ejecutar al snippet y arrastrar el link a la barra de marcadores para futuros usos. (ojo que rompe visualmente todo el layout).

d.style.display='block')})();">averche

no me veeen

Esto es un ejemplo básico, un atacante mas profesional armaría una extensión de navegador.
Así que mi consejo es... replantear el esquema de seguridad.


text:
Q: how to setup multiple paths in user environmental variables in windows 10 I want to set up multiple paths in the user environmental variables in windows 10. but can only set a single path, how to overcome this issue?

A: If you want to add user defined environment variable then use react-native-config library. So in short if there are variables defined in .env file then you can use it anywhere in the react-native app like below:-
.env file

API_URL = "https://baseurl/endpoint"

//To use the above environment variable

import config react-native-config
function apiCall() {   axios(config) }

With the help of react-native-config you can use environment variable in native code also and vise-versa.
For better use define .env.staging file. By default config lib finds .env file. To run the application with .env.staging file see below command.

$ ENVFILE=.env.staging react-native run-ios           # bash
$ SET ENVFILE=.env.staging && react-native run-ios    # windows
$ env:ENVFILE=".env.staging"; react-native run-ios    # powershell

For more information checkout :- https://github.com/luggit/react-native-config
Happy coding mate :)

A: to add multiple paths for a single environment variable, list them all with a semicolon(";") in between like that:
C:\Cpp_Headers\pybind11;C:\Cpp_Headers\cpython\Include;C:\Users\admin\Cpp_Headers\cpython\PC
(and so forth). From this input Windows will automatically recognize multiple definitions.


text:
Q: Closing a Scanner throws java.util.NoSuchElementException I'm writing an RPG combat system from scratch in Java, ambitious right? Well, I'm having some trouble. This is my code:
void turnChoice() {
    System.out.println("What will you do? Say (Fight) (Run) (Use Item)");
    Scanner turnChoice = new Scanner(System.in);
    switch (turnChoice.nextLine()) {
        case ("Fight"):
            Combat fighting = new Combat();
            fighting.fight();
        default:
    }

    turnChoice.close();
}

When it hits that point in the code I get:

What will you do? Say (Fight) (Run) (Use Item)
         Exception in thread "main" java.util.NoSuchElementException: No line found
            at java.util.Scanner.nextLine(Unknown Source)
            at Combat.turnChoice(Combat.java:23)

The class is called Combat, I just want it to give an option to fight or run or use items, I'm trying just the fight method first. Please help, I'm kind of new to Java so don't make things too complicated if possible.

A: When you are reading using Scanner from System.in, you should not close any Scanner instances because closing one will close System.in and when you do the following, NoSuchElementException will be thrown.
Scanner sc1 = new Scanner(System.in);
String str = sc1.nextLine();
...
sc1.close();
...
...
Scanner sc2 = new Scanner(System.in);
String newStr = sc2.nextLine();      // Exception!


text:
Q: adding rows in jtable  this.tModel.insertRow(rowCount,new Object[]  {"","","",""});
 this.table.setRowSelectionAllowed(true);
 this.table.changeSelection(0, 0, false, false);

 this.table.addKeyListener(new KeyListener() {
      @Override
      public void keyPressed(KeyEvent e) {
          if (e.getKeyCode()==KeyEvent.VK_ENTER) {
               rowCount = this.table.getSelectedRow() + 1;
               tModel.insertRow(rowCount,new Object[]{"", "","",""});
          }
      }
 });

I am trying to create a jtable adding rows at run time on mouse click. i alredy added a default row. but i cant get selection on that row. and i want to change the selection to newly added row when added on the key pressed action?
please suggest an answer? thanks in advance

A: Firstly, I would encourage you to use the key bindings API, KeyListener is a low level API and events can be consumed before you ever see them.
To change/set the row selection in a JTable, you should use JTable#setRowSelectionInterval
InputMap im = getInputMap(WHEN_FOCUSED);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter");
ActionMap am = getActionMap();
am.put("enter", new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
        int rowCount = table.getSelectedRow() + 1;
        tModel.insertRow(rowCount,new Object[]{"", "","",""});
        table.setRowSelectionInterval(rowCount, rowCount);
    }
});

A: To select the last entry in a table, you could use a method like this:
private void selectLastPossibleEntry() {
    final int rowCount = tableModel.getRowCount();
    final int selectedRowCount = jTable.getSelectedRowCount();
    if (rowCount > 0 && selectedRowCount <= 1) // we do not want do destroy multiple selected lines by the user
        jTable.setRowSelectionInterval(rowCount - 1, rowCount - 1);
}

or more general:
private void selectLastPossibleEntryForJTable(final JTable jTable) {
    final int rowCount = jTable.getModel().getRowCount();
    final int selectedRowCount = jTable.getSelectedRowCount();
    if (rowCount > 0 && selectedRowCount <= 1) // we do not want do destroy multiple selected lines by the user
        jTable.setRowSelectionInterval(rowCount - 1, rowCount - 1);
}

Hint: This does not take care of different sortings


text:
Q: accessing static variables in method I have static variables declared outside class and i am instantiating the variables in one method and access the same value in other method.But in spite of variable being set to static its still giving me null.
Public Class PolicyHolderDetails {

Public Static ID PolId{get;set;}
Public Static ID Nameid{get;set;}
Public void CheckInsurance(){

Policy__c Pid=[select id from policy__c where Policy_Name__c='Health Insurance'][0];
     PolId=Pid.id;//setting the values..
     system.debug(PolId);
}
Public void Save(){
Account aa=[Select id from Account where name=:Name][0];
 Nameid=aa.id;
 system.debug(Nameid);
}
Public PageReference SaveAgreement() {
PolicyHolderDetails pobj=new PolicyHolderDetails();
//pobj.CheckInsurance();
//pobj.Save();
id pid=PolicyHolderDetails.PolId;//accessing the variables here..
id Nid=PolicyHolderDetails.Nameid;
}
}

A: When a page invokes a method the view state - the values of the fields of the class - are automatically re-populated immediately before the method runs. But static variables are not part of that mechanism (by design). Removing Static from the declarations and referencing them as normal non-static variables in SaveAgreement should address the problem.
More detail in e.g. An Introduction to Visualforce View State.
PS
The simplest solution is to just do everything in the SaveAgreement method:
Public PageReference SaveAgreement() {

   Policy__c Pid=[select id from policy__c where Policy_Name__c='Health Insurance'][0];
   Id PolId = Pid.id;
   Account aa = [Select id from Account where name=:Name][0];
   Id Nameid = aa.id;

   ... just use the PolId and Nameid local variables here ...
}

but if you need to keep the logic spread across the 3 mthods:
Public Class PolicyHolderDetails {

    Public ID PolId{get;set;}
    Public ID NameId{get;set;}

    Public void CheckInsurance(){
        Policy__c Pid=[select id from policy__c where Policy_Name__c='Health Insurance'][0];
        PolId = Pid.id;
    }

    Public void Save(){
        Account aa=[Select id from Account where name=:Name][0];
        NameId = aa.id;
    }

    Public PageReference SaveAgreement() {
        ... reference the PolId and NameId fields here ...
    }
}


text:
Q: match and search in struct and mark true or false C I'm building a system of 2 servers and 1 client for reservations.
I found an obstacle, now I'll explain:
-server A
-server B
-client
Once the client selects from a menu what he wants to book and when,
server B must look in the struct for the date and check if it is available, if it is send an ok, if it is not send a no as an answer.
To do it I had thought of the following way, but it does not work:
bool search(int bet2,  bool flag)
    {
     int i=0;

      for(i=0; i < 11; i++){
        if(strcmp(content[i].date, content[bet2].date) == 0)
        {
           if (content[i].mark == true)
           {
               printf("Date Busy");
               return false;
           } else {
               content[i].mark = true;
               printf("Date booked day: %s",content[i].date);
               return true;
            }}
      }
    }

in the prototypes I declare it so:
bool search (int bet2, bool flag);

in the main I declare it so:
search (bet2, flag);

the struct is this:
typedef struct choice {
    char name [40];
    char date [40];
    bool mark;
} Choice;

Choice content [10];

now I have a doubt, but the type bool exists in C?
anyway, where am I wrong?
sorry but I'm writing lines of code this morning and I'm stuck here, probably I do not see it.
this code return ever that date is good, where am i wrong?

A: content [i] .mark = true

will be
content [i] .mark == true

To avoid this kind of problem you can use the comparison like this
true == content [i] .mark

In this case even if you forget the == and use = the compiler will complain.
And yes even better is to use simple and easy to read
  if( content [i] .mark )

Also there is no keyword called Else in C. It will be else.
Remove the extra } in the code where you have written }}. The scoping changes for that and it is wrong.
Also why use return flag = false it's useless here. Just do return false or return true. Because flag's changed value won't be used anywhere.


text:
Q: FTP file name and path error while uploading and downloading using PHP I'm trying to implement file transfer using PHP.
I'm getting the following errors:-

*

*Using Html form to upload a file. PHP file to fetch the file using
$_files. How do I get the original file name with extension from the
php object? basename method gives a different name.
I tried uploading a .txt file. It gets converted into php file and gets
uploaded on the server.

*On the download part, I'm using ftp_get. I want the file to get
    downloaded to my laptop. However it is getting saved on the server
    itself with the whole path which i specify in $fileToy. No error
    displayed, also file doesn't get downloaded. Here for simplicity
    I've given the path directly considering I've uploaded a .txt file.
Please help for general case(any file format).
Here is my code
if ((isset($_FILES['myfile']['tmp_name'])))
    $myfile = $_FILES['myfile']['tmp_name'];
else echo "upload not possible";

$fileFrom = $myfile;
$fileTo = 'photos/'. basename($myfile);     //photos is directory created on server
echo $fileTo;

$ftpObj -> uploadFile($fileFrom, $fileTo);

$fileFrom = $fileTo ;                            # The location on the server
$fileToy = 'Downloads\techppr.txt' ;            # Local dir to save to

// *** Download file
$ftpObj->downloadFile($fileFrom, $fileToy);

public function uploadFile ($fileFrom, $fileTo)
{
    // *** Set the transfer mode
    $asciiArray = array('txt', 'csv');
    $extension = end(explode('.', $fileFrom));
    if (in_array($extension, $asciiArray)) {
       $mode = FTP_ASCII;
    } else {
    $mode = FTP_BINARY;
    }

    // *** Upload the file
    $upload = ftp_put($this->connectionId, $fileTo, $fileFrom, $mode);
}

public function downloadFile ($fileFrom, $fileTo)
{

    // *** Set the transfer mode
    $asciiArray = array('txt', 'csv');
    $extension = end(explode('.', $fileFrom));
    if (in_array($extension, $asciiArray)) {
        $mode = FTP_ASCII;
    } else {
        $mode = FTP_BINARY;
    }
    if (ftp_get($this->connectionId, $fileTo, $fileFrom, $mode, 0)) {
        return true;
        $this->logMessage(' file "' . $fileTo . '" successfully downloaded');
    } else {
         return false;
        $this->logMessage('There was an error downloading file "' . $fileFrom . '" to "' . $fileTo . '"');
     }
}


text:
Q: BackBone collection takes array of models as a single model? In this below code
 var productcollection = new Products([this.$results]);
 alert(productcollection.length);

here this.$results holds a string more like this
{"ProdID":"98","ProdName":"product1","ProdPic":"null","ProdGist":"null","ProdDesc":"null","ProdCat":"","ProdTech":"","LastModified":""},{"ProdID":"928","ProdName":"product21","ProdPic":"null","ProdGist":"null","ProdDesc":"null","ProdCat":"","ProdTech":"","LastModified":""}

But the length of the collection is returned as "1" . what correction should i make to the  models data that i am giving to the collection . So that it returns "2".

A: If you really have a string in this.$results try this:
var array = JSON.parse('['+this.$results+']');
var productcollection = new Products( array );

Your code was creating an Array containing one large string, like:
new Products( ["text"] );


text:
Q: them vs. there, which of the two fits in better in the sentence?
Selina Walker, publisher of Century and Arrow, attributed the recent
  rise of psychological thrillers to __________ being "a sort of
  'melding' of the women's relationship and detective genres".

their or them?? Please provide the explanation as well.
edit : replaced "there" by "their"

A: It should be them.
Because it refers to the thrillers. The sentence further talks about the genres giving us a hint that 'a sort of 'melding'' is being a type of those thrillers.

A: It should be:

Selina Walker, publisher of Century and Arrow, attributed the recent rise of psychological thrillers to there being "a sort of 'melding' of the women's relationship and detective genres".

where there introduces some reasoning regarding the previous clause.

A: It depends on what you want the subject of the last part to be. If you're saying that in general there has been a sort of melding then the correct word would be "there". If you're saying that psychological thrillers are a sort of melding then you should use "them".

A: It truly depends on the meaning intended.
If what is intended is something like:
attirbuted the recent rise of psychological thrillers to the general rise in melding the traditional genres about women's emotional relationships and the detective story,
then there would be a vague way to convey the idea that psychological thrillers are one specific manifestation of a more general phenomenon.
If what is intended is something like:
attributed the rise of the psychological thriller to that genre's combining the appeals of stories about emotional relationships and stories about who-done-it,
then them would be a vague way to convey the idea that the genre of the psychological thriller appeals to two different but compatible interests.
The problem is that, at least out of context, the quoted language is very muddy. Having experience giving interviews, I am well aware that it can be difficult to give clear answers to hard questions on the spur of the moment. The person quoted may have had a clear thought and failed to express it well. Or she may have not had time to articulate a cogent answer to an unanticipated question.

A: there or their, but probably not them
Does the phase "a sort of 'melding' of the women's relationship and detective genres" describe something that exists separately from the thrillers or does it describe something essential to the thrillers in question?
A case for there

Selina Walker attributed the recent rise of psychological thrillers to there being a "melding" (i.e., the existence of a "melding" that's external to the psychological thrillers).

A case for their

Selina Walker attributed the recent rise of psychological thrillers to their being a "melding" (i.e., the "melding" is a quality or aspect of the recent thrillers themselves).

see also this ELU question "of their being" vs "of there being"
Why formal English does not use them in this case
As the subject of a gerund phrase, the possessive form is traditionally used in formal writing.  The distinction is whether you're discussing the noun itself or a quality or aspect of that noun.  This rule is often ignored in informal writing and conversations.
see also this ELL question When to use an object pronoun or a possessive adjective before a gerund
and getitwriteonline.com Using Possessives with Gerunds


text:
Q: Change the ticklabel orientation and legend position of plot I am plotting a bar graph by reading data from a CSV using pandas in Python. I read a CSV into a DataFrame and plot them using matplotlib.
Here is how my CSV looks like:
SegmentName    Sample1   Sample2   Sample3

Loop1          100       100       100

Loop2          100       100       100

res = DataFrame(pd.read_csv("results.csv", index_col="SegmentName"))

I plot and set the legend to be outside.
plt.figure()
ax = res.plot(kind='bar')
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))

plt.savefig("results.jpg")

However, the x-axis ticklabels are orientated vertically and hence I can't read the text. Also my legend outside is cut off.
Can I change the orientation of the ticklabels to be horizontal, and then adjust the entire figure so that the legend is visible?

A: You should use the matplotlib API and call ax.set_xticklabels(res.index, rotation=0) like so:
index = Index(['loop1', 'loop2'], name='segment_name')
data = [[100] * 3, [100] * 3]
columns = ['sample1', 'sample2', 'sample3']
df = DataFrame(data, index=index, columns=columns)

fig, ax = subplots()
df.plot(ax=ax, kind='bar', legend=False)
ax.set_xticklabels(df.index, rotation=0)
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
fig.savefig('results.png', bbox_inches='tight')

to get the resulting plot:

Alternatively you can call fig.autofmt_xdate() for a nice tilted effect, which you can of course tinker with with the above (and more general) ax.set_xticklabels():
fig, ax = subplots()
df.plot(ax=ax, kind='bar', legend=False)
fig.autofmt_xdate()
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
fig.savefig('results-tilted.png', bbox_inches='tight')

A: For the rotation of the labels, you can simply tell pandas to rotate it for you by giving the number of degrees to the rot argument.
The legends being cut off is answered elsewhere as well, like here:
df = pd.DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6])],
                              orient='index', columns=['one', 'two', 'three'])
ax = df.plot(kind='bar', rot=90)
lgd = ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
fig.savefig("results.jpg", bbox_extra_artists=(lgd,), bbox_inches='tight')

A: Try using the 'rotation' keyword when you set the label. E.g.:
plt.xlabel('hi',rotation=90)

Or if you need to rotate the tick labels, try:
plt.xticks(rotation=90)

As for the positioning of the legend etc., it is probably worth taking a look at the tight layout guide


text:
Q: Arquitetura MVC de Rotas e Controllers com várias versões usando Spark Estou implementando uma API Rest em Java utilizando o framework Spark. Preciso dividir as rotas em duas versões ou mais: v1 e v2. Eu sei que o Spark fornece o path(), acredito não ser difícil.
Minha dúvida está em como realizar a estrutura das pastas com base no modelo MVC.
Obs.: Comentei o Spark por motivo de contextualização do framework que estou usando.


text:
Q: How Flexible are the WordPress Coding Standards for PHPCS? In my WordPress workflow I use Gulp and have a task that runs my PHP files through PHPCS using the WordPress coding standards tests (https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards).
While writing my comments.php file, I have run across the following error:

Expected next thing to be an escaping function (see Codex for 'Data Validation'), not '_x'

This is being generateds by the following line of code:
printf( _x( '1 Comment on "%s"', 'Comments Title', 'jldc' ), get_the_title() );

I pretty much reused the same line from the Twenty Sixteen theme that ships with WordPress. Out of curiosity I ran PHPCS against Twenty Sixteen's comments.phpfile and got the same errors.
Now, I can easily use esc_html_x() instead of _x as I presume that is what the guidelines want me to use. But what about this line:
printf(
   _nx(
      '%1$s Comment on "%2$s"',
      '%1$s Comments on "%2$s"',
      $comment_count,
      'Comments Title',
      'theme-text-domain'
      ),
      number_format_i18n( $comment_count ),
      get_the_title()
   );

Or can I simply ignore the error?

A: Consider something like the following:
echo esc_html(
      sprintf(
         _nx(
               '%1$s Comment on "%2$s"',
               '%1$s Comments on "%2$s"',
               $comment_count,
               'Comments Title',
               'theme-text-domain'
         ),
         number_format_i18n( $comment_count ),
         get_the_title()
      )
);

Where you build the entire string with sprintf and escape that.
The coding standards are clear that you should always escape output, and do so as late as possible. As you've noticed, however, even the default theme doesn't adhere to them exactly.

A: WordPress do not have an enforceable coding standards. There are core coding standards, there are wordpress.com VIP coding standards etc. None of them come directly from god and since they are based on the idea that you are developing for PHP 5.2 they might not even be the best thing to follow if you don't have an explicit requirement to follow them.
Use them as a guidelines, something that people put a lot of time into thinking about should not be ignored, but when it doesn't meet your specific situation don't feel bound by them.
In your specific example it is a bug in the 2016 theme as it is core guideline that translations should not escape, and the escaping should be done after the translation (translation might introduce things like quotes). You should keep this in mind and follow the same route unless you want to make the life of translators harder.


text:
Q: Complexity of multiplying two polynomials with different degree I am aware that we can use the Fast Fourier Transform to multiply two polynomials of degree n in O(n log n) time. This is a big savings from the brute force approach in O(n^2) time. Is it possible to generalize this result to two polynomials of different degree?
Clearly, it can be done in O(n log n) where n is the larger number, but I'm looking for an answer that depends on both n and m.


text:
Q: Android String to Double Decimal Points I am parsing A String value from the DB which has values like:
9.00, 9.44,
90.00, 90.44,
180.00, 180.44
as Double and Storing it in a List Adapter and Inflate in a dialog box
This is the piece of code I am using for converting it to Double.
DecimalFormat decimalFormat = new DecimalFormat("0.00");
double tmp = Double.parseDouble(decimalFormat.format(Double
                .parseDouble(string)));

But, when it converts into Double I can only get one Decimal Point. Where I am wrong?

A: This code
String string = "9.44";
DecimalFormat decimalFormat = new DecimalFormat("0.00");

double tmp = Double.parseDouble(decimalFormat.format(Double
                .parseDouble(string)))

assings exactly the same value to tmp as shorter and simpler code
...

double tmp = Double.parseDouble(string);

You should use BigDecimal instead of double if you need exact number of decimal points and the value has to be exact. If you store 1.00 as double you actually have 0.999...7 not 1.00

A: Try like this
DecimalFormat decimalFormat = new DecimalFormat("#.00");
double tmp = Double.parseDouble(decimalFormat.format(string));

or
DecimalFormat("##.##")

Modify as per your requirement with #


text:
Q: How do I print all unique keys among dictionaries within a list? After reading from a JSON file (Abbreviated example JSON file), I have a list named "liveData.plays.allPlays" containing many dicts with key-value pairings. The keys are similar across the dicts but some have additional keys. I want to print all unique keys with the eventual goal of using these as fieldnames when I write a header row in a CSV file. I will also need to write the corresponding values as rows underneath in the CSV file.
I am able to print all keys within any single dict with the following code and manipulation of the integer 0:
with open('nhlbigtest2.json', 'r') as read_file:
        data = json.load(read_file)
        for k in data["liveData.plays.allPlays"][0].keys():
            print(k)

This yields:
about.dateTime
about.eventId
about.eventIdx
about.goals.away
about.goals.home
about.ordinalNum
about.period
about.periodTime
about.periodTimeRemaining
about.periodType
result.description
result.event
result.eventCode
result.eventTypeId

Can I manipulate integer 0 to be a range or does this task require a different approach? (using Python 3.7)

A: A set is a data structure intended to hold unique values. You could iterate over your list of dictionaries, and update a set with the keys from each one:
unique_keys = set()
for game_dict in data["liveData.plays.allPlays"]:
    unique_keys.update(game_dict.keys())

When you go to writing your data out as a CSV file, I'd suggest using the csv.DictWriter class. You can pass it a sequence of fieldnames (e.g. the set of keys, from above, perhaps reordered and put into a list) and it will write out columns for each one. If a given dictionary doesn't have a specific key, its row in the CSV file will have a blank for that column, though you can customize that using the restval parameter (to put 'N/A' or something else if you prefer).


text:
Q: Create require js plugin that listens for a backbone js global event Is it possible to create a require js plugin that listens for a backbone global event and if that event is fired require js kicks in?
This is the scenario I would like to reproduce with require js http://jsfiddle.net/u2aej/
I'm thinking that this would look something like this.
require(['views/SubModule', 'editorLoaded!'], function (SubModule, editorLoaded) {
    //This function is called once the Editor is loaded.
    var view = new SubModule({el: '#sub-view' });
});

I'm not so familiar with require so maybe I'm totally wrong about this but I would like to here from you if you think this is a good idea and if it's possible?

A: It might be simpler to decouple the module from the event, and load the module explicitly using require().
Borrowing from this answer for Backbone global events - Backbone.js global events. Create the vent:
vent = _.extend({}, Backbone.Events);

vent.trigger("some:event");

Then load the module when the event is fired:
vent.on("some:event", function(){
    require(["myModule"], function(myModule) {
        myModule.doItsThing();
    });
});

But if you do want to write a plugin, then the best example to follow is probably - https://github.com/requirejs/domReady/blob/master/domReady.js.
Take a look at that, and replace with a version that calls the callbacks when a particular global event is fired, rather than when the DOM is ready.
However, I suspect that your dependency would look like this:
require(["globalEvent!editorLoaded"], function() { ... });

rather than this:
require(["editorLoaded!"], function() { ... });

(assuming your plugin is called globalEvent)
See the text plugin, https://github.com/requirejs/text, for how to pass parameters to the plugin.


text:
Q: What is H264Layer profile and level? I am not familiar with video encoding, so this could be a silly question:
What does the H264 layer "profile" and "level" means?
To be exact, I am trying to use Azure Media service to encode some videos, and I noticed these settings in its configure. In its own page, https://msdn.microsoft.com/en-us/library/azure/mt269962.aspx, it doesn't really explain anything. For example, for "profile", it simply says "Auto, Baseline, Main, High".
My goal is to encode the video in a way that can be played back on most platforms (Windows, iOS, Android), so I want to see if I can find some settings that work for all of them - from Azure's own document, https://msdn.microsoft.com/library/azure/mt269960.aspx, it hints that for different platforms, I'd better encode / generate different output files. Is that the case? (does YouTube have different video files for different platforms, for the same input content file?)
Thanks!

A: I think I figured it out: looks like profile baseline or main, level 3.1, is a good bet that fits most devices. Of course, I may need different bitrates.


text:
Q: Android Bluetooth Connectivity I have posted a question but no one has answered yet. may be I have asked in a wrong way. so I am here to ask again.
here the link to my previous question
IXXAT CANBlue II - Bluetooth java.io.IOException: Permission denied
Question:
why is it problem while connecting to Bluetooth device from android via Bluetooth.
Log Says Permission Denied. I am posting my Log here. my device works fine with PC Bluetooth terminal but when I tried to connect the device from my phone through app it pairs successfully but it cannot connect. and yes there is no problem in code as the code is Demo App provided by device makers and proper permissions are also added in manifest.. it was tested with android 3.2. and it worked well. but I Configured it on android studio 2.3.1 with following details.
android {
    compileSdkVersion 19
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "ixxat.adk.demo"
        minSdkVersion 13
        targetSdkVersion 19
        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_5
            targetCompatibility JavaVersion.VERSION_1_5
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
    productFlavors {
    }
}

Android Device with Android 4.0.2. and 4.4.2. but both have same problem.
Please help me out in this regard.
here are my log details.
04-27 13:57:54.859 6434-6434/ixxat.adk.demo W/System.err: java.io.IOException: Permission denied
04-27 13:57:54.859 6434-6434/ixxat.adk.demo W/System.err:     at android.bluetooth.BluetoothSocket.connectNative(Native Method)
04-27 13:57:54.859 6434-6434/ixxat.adk.demo W/System.err:     at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:266)
04-27 13:57:54.859 6434-6434/ixxat.adk.demo W/System.err:     at API.ADK.Driver$CANDevice.connectDevice(Driver.java:645)
04-27 13:57:54.859 6434-6434/ixxat.adk.demo W/System.err:     at API.ADK.API_ADK$Device.connectDevice(API_ADK.java:270)
04-27 13:57:54.859 6434-6434/ixxat.adk.demo W/System.err:     at ixxat.adk.demo.Demo_ADKActivity.onCreate(Demo_ADKActivity.java:91)
04-27 13:57:54.859 6434-6434/ixxat.adk.demo W/System.err:     at android.app.Activity.performCreate(Activity.java:4465)
04-27 13:57:54.882 6434-6434/ixxat.adk.demo W/System.err:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
04-27 13:57:54.890 6434-6434/ixxat.adk.demo W/System.err:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
04-27 13:57:54.890 6434-6434/ixxat.adk.demo W/System.err:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
04-27 13:57:54.890 6434-6434/ixxat.adk.demo W/System.err:     at android.app.ActivityThread.access$600(ActivityThread.java:123)
04-27 13:57:54.898 6434-6434/ixxat.adk.demo W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
04-27 13:57:54.898 6434-6434/ixxat.adk.demo W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:99)
04-27 13:57:54.898 6434-6434/ixxat.adk.demo W/System.err:     at android.os.Looper.loop(Looper.java:137)
04-27 13:57:54.898 6434-6434/ixxat.adk.demo W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:4424)
04-27 13:57:54.898 6434-6434/ixxat.adk.demo W/System.err:     at java.lang.reflect.Method.invokeNative(Native Method)
04-27 13:57:54.898 6434-6434/ixxat.adk.demo W/System.err:     at java.lang.reflect.Method.invoke(Method.java:511)
04-27 13:57:54.898 6434-6434/ixxat.adk.demo W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-27 13:57:54.898 6434-6434/ixxat.adk.demo W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-27 13:57:54.898 6434-6434/ixxat.adk.demo W/System.err:     at dalvik.system.NativeStart.main(Native Method)

Here is the manifest file as requested
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="ixxat.adk.demo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="13" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".Demo_ADKActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
Q: trying an example from rise4fun / z3 / tutorial / strategies some example from the rise4fun-site:
(declare-const x Int)
(declare-const y Int)
(declare-const z Int)
(declare-const a Int)        ;  this is added

(assert (= a 3 ))            ; this is added:  a := 3
(assert (< 0 x  10))         ; rewritten, but same constraint
(assert (< 0 y  10))
(assert (< 0 z  10))

(assert (= (+ (* 3 y) (* 2 x)) z))        ; plain function from rise4fun
;(assert (= (+ (* a y) (* 2 x)) z))       ; here literal 3 is replaced by a

(check-sat-using (then (using-params simplify :arith-lhs true :som true)
                       normalize-bounds
                       lia2pb
                       pb2bv
                       bit-blast
                       sat))
(get-model)
(get-info :version)

when i comment the plain function from rise4fun and uncomment my function, the solver will fail to produce a result and respond with 'unknown'  (tried with 4.8.0). Isn't the solver or some preprocessor smart enough to see that 'a' is just a constant with fixed value 3?

A: That's right, the simplify tactic is not smart enough to propagate values because it would be too expensive in general. However, ctx-simplify or propagate-values do the job. For instance:
(check-sat-using (then (using-params simplify :arith-lhs true :som true)
                       propagate-values
                       normalize-bounds
                       lia2pb
                       pb2bv
                       bit-blast
                       sat))


text:
Q: How can we have global Expand/Collapse for JQGrid when we have rows grouped on some field? How can we have global Expand/Collapse for JQGrid when we have rows grouped on some field?
On expanding, it should expand all groups and on collapsing all groups should be collapsed.

A: You can set default value of the groupCollapse property of the groupingView parameter of jqGrid in the same way like you set any other default parameter:
$.extend($.jgrid.defaults, {
    groupingView: {
        groupCollapse: true
    }
});

UPDATED: After additional explanation in the comments I can me imagine that in some cases it can has the behavior when all groups will be expanded/collapsed if any from the groups will be expanded/collapsed.
var $grid = $("#list"), inOnClickGroup = false;

$grid.jqGrid({
    // ... other options
    grouping: true,
    onClickGroup: function (hid) {
        var idPrefix = this.id + "ghead_", id, i, l,
            groups = this.p.groupingView.sortnames[0];

        if (!inOnClickGroup && hid.length > idPrefix.length &&
                hid.substr(0, idPrefix.length) === idPrefix) {
            id = Number(hid.substr(idPrefix.length));
            if (typeof (groups[id]) !== "undefined") {
                inOnClickGroup = true; // set to skip recursion
                for (i = 0, l = groups.length; i < l; i++) {
                    if (i !== id) {
                        $(this).jqGrid('groupingToggle', this.id + 'ghead_' + i);
                    }
                }
                inOnClickGroup = false;
            }
        }
    }
});

See the demo.

A: $('#grid-expand-collapse').change(function () {

    var idPrefix = "MyGridghead_", index, length, tarspan;
    var groups = $(options.gridElement)[0].p.groupingView.sortnames[0];

    if ($(this).is(':checked')) {

        for (index = 0, length = groups.length; index < length; index++) {

            tarspan = $("#MyGridghead_" + index + " span." + "tree-wrap-" + $(options.gridElement)[0].p.direction);
                if (!tarspan.hasClass($(options.gridElement)[0].p.groupingView.minusicon)) {
                    $(options.gridElement).jqGrid('groupingToggle', 'MyGridghead_' + index);
                }
        }
    }
    else {
        for (index = 0, length = groups.length; index < length; index++) {

            tarspan = $("#MyGridghead_" + index + " span." + "tree-wrap-" + $(options.gridElement)[0].p.direction);
            if (tarspan.hasClass($(options.gridElement)[0].p.groupingView.minusicon)) {
                $(options.gridElement).jqGrid('groupingToggle', 'MyGridghead_' + index);
            }
        }
    }

});

A: $('#jqxGrid').jqxGrid({
    groupsexpandedbydefault: true
});

worked like a charm for me (source).


text:
Q: OpenGL ES2.0 - After restarting the App, everything looks.. weird EDIT:
More debugging led me to the fact that glGetAttribLocation returns -1, except for the first start of the Application. Program ID is valid (I guess?), it was 12 in my testing right now. I also tried to retrieve attribute location right before drawing again, but this did not work out neither.
My shader "architecture" now looks like this:
I've turned the shader into a singleton. I.e. only one instance. Using it:
public void useProgram() {
    GLES20.glUseProgram(iProgram);
    getUniformLocations();
    getAttributeLocations();
}

I.e. program will be sent to OpenGL, afterwards I'm retrieving uniform and attribute locations for all my variables, they are stored within a HashMap (one for each shader):
@Override
protected void getAttributeLocations() {
    addToGLMap(A_NORMAL, GLES20.glGetAttribLocation(iProgram, A_NORMAL));
    addToGLMap(A_POSITION, GLES20.glGetAttribLocation(iProgram, A_POSITION));
    addToGLMap(A_COLOR, GLES20.glGetAttribLocation(iProgram, A_COLOR));
}

I don't understand, why the program's ID is for example 12, but all the attribute locations are non-existent in the second and the following run of my Application...

In my Application, I am loading a Wavefront object, as well as I am drawing several lines and cubes, just to try something. After starting the Application "clean", i.e. after rebooting or installing it, everything looks as intended. But if I close the Application and re-open it, it looks weird, screenshot is at the bottom.
What I'm currently doing:
onSurfaceCreated:
Taking care of culling, clear color, etc, etc.
Clear all loaded objects (just for testing, will of course not delete memory in later phase).
Reload objects (threaded).
My objects are stored like this:
public class WavefrontObject {
    private FloatBuffer mPositionBuffer = null;
    private FloatBuffer mColorBuffer = null;
    private FloatBuffer mNormalBuffer = null;
    private ShortBuffer mIndexBuffer = null;
}

*

*Buffers are filled upon creation of the element.

They are drawn:
mColorBuffer.position(0);
mNormalBuffer.position(0);
mIndexBuffer.position(0);
mPositionBuffer.position(0);

GLES20.glVertexAttribPointer(mShader.getGLLocation(BaseShader.A_POSITION), 3, GLES20.GL_FLOAT, false,
        0, mPositionBuffer);

GLES20.glEnableVertexAttribArray(mShader.getGLLocation(BaseShader.A_POSITION));

// etc...

GLES20.glDrawElements(GLES20.GL_TRIANGLES, mIndexBuffer.capacity(), GLES20.GL_UNSIGNED_SHORT, mIndexBuffer);

*

*Do I need to disable the VertexAttribArrays after drawing them? I am currently overwriting the buffer for each drawing loop, but do they maybe interact with other models being drawn?

The model I am loading displays a small toy-plane. After restarting the Application, it looks like this (loading the object, all colors are set to white (for testing)):

So to me it looks like the buffers either have left-over stuff in them? What's the "best practice" for using these buffers? Disable the arrays? Does OpenGL ES2.0 offer some sort of "clear buffer" method that I can use before putting my values in them?
What was expected to be drawn: At the point where the "weird triangles" and colors origin from, there should be the plane-model. All in white.

A: When your application loses context its OpenGL context is destroyed.
So all objects (programs and its uniform/attribute handles, etc) are invalidated.
During reopening you have to clear/invalidate all singleton objects like yours...


text:
Q: Custom date format iseries access odbc for SSRS How to resolve my issue below?
1. I am pulling data from AS/400 DB2 using (iseries access odbc driver) to SSRS.
2. I want to format the column stores in integer to date format.
Sample = 20180612 below is the SQL Query.
Using below query,
SELECT  CHAR(DATE(SUBSTR(DIGITS(20180612),1,4)||'-'||
        SUBSTR(DIGITS(20180612),5,2)||'-'||
        SUBSTR(DIGITS(20180612),7,2)),ISO) AS RESULTSDATE

Output = 2018-06-02
Question: How can I produce a below custom date format like d/m/yyyy
I have used, ISO, USA, LOCAL, JIS, EUR but no yield.
Example: 2/6/2018

A: If you want to do it in SQL Server, the closest you can CONVERT it to is the USA 110 (mm-dd-yyyy) in SQL Server.
If the your dataset has a field with the 2018-06-02, you can use the CDATE function is SSRS to convert it to a date and then format the text box the way you want with the FORMAT property or the FORMAT function.
Format Function:
=FORMAT(CDATE("2018-06-02"), "M/d/yyyy")

Format Property of Text Box:

A: /* this is as close as I can come to the desired results there is a leading zero */
select
varchar_format(
timestamp_format(char(20180612), 'YYYYMMDD')
, 'DD/MM/YYYY') as resultdate
  from my8digitdatetable

/* for export IRL send out a date */
select
cast(
timestamp_format(char(20180612), 'YYYYMMDD')
as date) as resultdate
  from my8digitdatetable

A: I got it already. I just format it to the date without formatting.
SELECT DATE(SUBSTR(DIGITS(MIN(DTAHRS.HREMCP.EMREDT)),1,4)||'-'||
        SUBSTR(DIGITS(MIN(DTAHRS.HREMCP.EMREDT)),5,2)||'-'||
        SUBSTR(DIGITS(MIN(DTAHRS.HREMCP.EMREDT)),7,2)) AS RESULTSDATE

After that, I put this as sub-query so that I can pass this to the parameter.
Below is my whole query, then at SSRS I can use date/time parameter control to compare with the results.
SELECT x.RESULTSDATE
FROM (  SELECT DATE(SUBSTR(DIGITS(MIN(DTAHRS.HRLVTP.LTLDTE)),1,4)||'-'||
        SUBSTR(DIGITS(MIN(DTAHRS.HRLVTP.LTLDTE)),5,2)||'-'||
        SUBSTR(DIGITS(MIN(DTAHRS.HRLVTP.LTLDTE)),7,2)) AS RESULTSDATE
    ) as x
WHERE x.RESULTSDATE >= ? AND x.RESULTSDATE <= ?

I hope it will help you too.


text:
Q: Function receiving null string I have the following problem: I pass a string to a function, however, when it receives the string, it receives a null value and does nothing, I've been trying to solve it for days and nothing, I'm thinking it's a error in main() function
Here is my code:
void main(){
   clear_screen();
   print_string("Hello World!");
}

void print_string(const char *string){
   int offset = get_cursor();
   int i = 0;
   while (string[i] != 0) {
      if(offset >= ROWS * COLS * 2) {
         offset = scroll_line(offset);
      }
      if(string[i] == '\n') {
         offset = move_offset_to_new_line(offset);
      }else{
         print_char(string[i], offset);
         offset += 2;
      }
      i++;
   }
   set_cursor(offset);
}

What can be happening in my code?
Note: I'm following the example on this site: https://dev.to/frosnerd/writing-my-own-boot-loader-3mld

A: Summarizing discussion from comments:
The bootloader code in this example (not in the question but in the linked site) is hardcoded to load the kernel by reading 2 sectors from the disk.  So this will only work if the kernel image is less than 1 KB in size.  With your modified code, your image turned out to be more than 1 KB (8 KB in fact).  So you weren't loading all of it, and in particular you weren't loading the part of the image that contained your string literal.  Thus when you accessed it, you got the contents of uninitialized memory, which apparently began with a zero byte, giving you the equivalent of an empty string.
You'll need to keep track of the size of your kernel image as you write more code and keep the bootloader in sync: look at the mov dh, 2 following load_kernel and replace 2 by the appropriate number of 512-byte sectors.  For a more serious project, you'd want to come up with a more robust mechanism: e.g. the first sector of the kernel image could contain a header which specifies how many more sectors to read.
Most compiler and linker setups will place string literals into a read-only data section (e.g. .rodata), separate from the code section (.text), and will arrange for each section to occupy a second set of 4 KB pages, so that page-granular memory permissions can be set accordingly (read and execute for .text, read and no execute for .rodata).  So even if your code and data could have fit in 1 KB, the need to put the code and data on separate pages is likely what accounts for the 8 KB file size (2 * 4 KB).  If you add read-write data (e.g. a global variable which isn't const), you'll probably see another 4 KB increase.


text:
Q: How to fix, ReferenceError: localStorage is not defined from my code import { useEffect, useState } from 'react';

function useBookmarks() {
  const [bookmarks, setBookmarks] = useState(() => {
    const ls = localStorage.getItem('bookmarks');
    if (ls) return JSON.parse(ls);
    else return [];
  });

  const toggleItemInLocalStorage = (id) => () => {
    const isBookmarked = bookmarks.includes(id);
    if (isBookmarked) setBookmarks((prev) => prev.filter((b) => b !== id));
    else setBookmarks((prev) => [...prev, id]);
  };

  useEffect(() => {
    localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
  }, [bookmarks]);

  return [bookmarks, toggleItemInLocalStorage];
}

export default useBookmarks;

Please tell me why the localStorage is not defined.
when I use localStorage why always, ReferenceError: localStorage is not defined.
is there something wrong with my code.
Please help me

A: You can add another conditional to check if the window object is defined, before calling localStorage:
if (typeof window !== 'undefined') {
    const ls = localStorage.getItem('bookmarks');
}

A: The standard localStorage API should be available in browsers. No need to specifically declare it.
But when you're rendering on the server, you do not have a browser and thus you do not have access to all the APIs that the browser provides, including localStorage.
In JavaScript code that is running both on the server and on the client (browser), it is common practice to guard against with an if clause that checks if window is defined. window is the root object provided by the browser for all the APIs that are provided by the browser.
For example:
if (typeof window !== 'undefined') {
    localStorage.setItem('myMouse', 'Jerry');
}

In your case, you may want to change your code to below:
import { useEffect, useState } from 'react';

function useBookmarks() {
  const [bookmarks, setBookmarks] = useState(() => {
    let ls;
    if (typeof window !== 'undefined') {
      ls = localStorage.getItem('bookmarks');
    }
    if (ls) return JSON.parse(ls);
    else return [];
  });

  const toggleItemInLocalStorage = (id) => () => {
    const isBookmarked = bookmarks.includes(id);
    if (isBookmarked) setBookmarks((prev) => prev.filter((b) => b !== id));
    else setBookmarks((prev) => [...prev, id]);
  };

  useEffect(() => {
    if (typeof window !== 'undefined') {
      localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
    }
  }, [bookmarks]);

  return [bookmarks, toggleItemInLocalStorage];
}

export default useBookmarks;


text:
Q: symfony doctrine:generate:entities cannot auto-load annotations I run Symfony 3.1.5, PHP 7.0.12 and composer 1.2.1.
I have a simple entity:
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Class Event
 * @package AppBundle\Entity
 * @ORM|Entity
 * @ORM|Table(name="event")
 */
class Event
{
    /**
     * @ORM|Column(type="integer")
     * @ORM|Id
     * @ORM|GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM|Column(type="guid")
     */
    private $uuid;

    /**
     * @ORM|Column(type="string", length=100)
     */
    private $name;

    /**
     * @ORM|Column(type="text")
     */
    private $description;

    /**
     * @ORM|Column(type="datetimetz")
     */
    private $startDate;

    /**
     * @ORM|Column(type="datetimetz")
     */
    private $endDate;

    /**
     * @ORM|Column(type="text")
     */
    private $location;
}

The documentation states that I can run
php bin/console doctrine:generate:entities AppBundle/Entity/Event

in order to create getters and setters for my private attributes. I run into the following error there:
  [Doctrine\Common\Annotations\AnnotationException]
  [Semantical Error] The annotation "@Doctrine\ORM\Mapping" in class AppBundle\Entit
  y\Event does not exist, or could not be auto-loaded.

As the annotation exists as alias @ORM I guessed it is an autoloading problem.
I googled around and found some old post which linked to this plugin, which also does not work.
All posts seem to be related to the fact that the Doctrine\ORM\Mapping class is not autoloaded in the conventional way, but needs to be loaded separately. But I cannot find a definite guide on how to get this up and running for the console. Could you please help?

A: You should replace your annotations with the following :
/**
 * EntityName
 *
 * @ORM\Table(name="table_name")
 * @ORM\Entity(repositoryClass="PATH TO REPO")
 */

use \ instead of |


text:
Q: OpenGL sRGB configuration on Android I am trying to understand how to enable sRGB profile for default frame buffers on Android.Android SDK is not clear about how to do it practically.For example,here a guy states that it is enough to set texture internal format to sRGB. But he is clearly wrong,because I tried that and it changes nothing.
Khronos provides this extension as a part of EGL.I have tried to add these flags to surface configs:
    final int EGL_GL_COLORSPACE_KHR = 0x309D;
    final int EGL_GL_COLORSPACE_SRGB_KHR = 0x3089;
    int attribs[] = {
            EGL10.EGL_LEVEL, 0,
            EGL10.EGL_RENDERABLE_TYPE,EGLExt.EGL_OPENGL_ES3_BIT_KHR,
            EGL10.EGL_COLOR_BUFFER_TYPE, EGL10.EGL_RGB_BUFFER,
            EGL10.EGL_RED_SIZE, 8,
            EGL10.EGL_GREEN_SIZE, 8,
            EGL10.EGL_BLUE_SIZE, 8,
            EGL10.EGL_DEPTH_SIZE, maxDepth,
            EGL10.EGL_SAMPLE_BUFFERS, 1,
            EGL10.EGL_SAMPLES, 4,
            EGL_GL_COLORSPACE_KHR ,EGL_GL_COLORSPACE_SRGB_KHR //<--
            EGL10.EGL_NONE
    };

But in this case the devices I am testing on (Google NEXUS 6) crashes the app.
Running OpenGL extension viewer I see the device doesn't support

EGL_KHR_gl_colorspace

extension.
In fact,I found here and on other online demos,that this setup is actually used.Also,iOS allows to configure default FBO to be sRGB with a flag :

kEAGLColorFormatSRGBA8

Is there another way to turn on sRGB on a Android device than that extension?(Of course another alternative is to gamma correct in shader,but that's exactly what I don't wanna do)

A: No, there is unfortunately no other way to create an sRGB default framebuffer.
What you could do is use a workaround: render to a texture with internal format GL_SRGB8_ALPHA8 and treat that as your framebuffer, then at the end draw a full-screen quad to the default framebuffer, using the aforementioned texture and a gamma correction shader. (You will get values in linear RGB when reading from the texture, so you need to compress them back to sRGB when writing out to the default framebuffer; the framebuffer is ostensibly linear, but the values in it will be interpreted as sRGB by the display.)
"The other guy" was entirely correct, but the default framebuffer is not a texture and you can't directly set its internal format.


text:
Q: How to use a single math symbol, in medium and bold, from Latin Modern? I use newtx and newtxmath in pdflatex with TeXLive, but I would like to use the \mathcal{O} symbol from Latin Modern. Following this answer, I am able to access the medium-series version. In the preamble, I add
 \DeclareSymbolFont{LMletters}{OMS}{lmsy}{m}{n}
 \DeclareMathSymbol{\lmO}{\mathbin}{LMletters}{79}

And then in the document, I can use e.g. $\lmO (N^{2})$.
But I would also like to use the boldface version of that symbol. Preferably it should work automatically with \bm, but if that is too hard, I wouldn't mind having simply a macro for it, e.g. \lmBO. However, the following attempt
  \DeclareSymbolFont{LMBletters}{OMS}{lmbsy}{b}{n}

returns the warning
   LaTeX Font Warning: Font shape `OMS/lmbsy/b/n' undefined
   (Font)              using `OMS/cmsy/m/n' instead on input line 30.

Note that \fonttable{lmbsy10} does print out, on my system, all the expected symbols, including the boldfaced mathcal O.
How do I access the boldfaced mathcal O from Latin Modern (while usingnewtxmath for all other math)? If possible, how to make this Latim Modern mathcal O work with \bm?

A: Use \SetSymbolFont to declare the font for math version bold.
\documentclass{article}
\usepackage{amsmath}
\usepackage{newtxtext, newtxmath}

\DeclareSymbolFont{LMletters}{OMS}{lmsy}{m}{n}
\SetSymbolFont{LMletters}{bold}{OMS}{lmsy}{b}{n}
\DeclareMathSymbol{\mscrO}{\mathalpha}{LMletters}{79}

\begin{document}
\[ O \quad \mathcal{O} \quad \mscrO \quad \boldsymbol{\mscrO}
\]
\end{document}

You might also declare \newcommand\mbfscrO{\boldsymbol{\mscrO}} for convenience and compatibility.  I'm not sure whether giving this symbol the spacing of a binary operator was intentional, but if it was, you can easily change it back.  You can optionally \usepackage{bm} after all your other math commands.
In unicode-math, you can override this symbol for both \mathcal and \mathbfcal with the range= option of \setmathfont, so:
\setmathfont{TeX Gyre Termes Math}[Scale=MatchUppercase]
\setmathfont{Latin Modern Math}[Scale=MatchUppercase,
                                range={\mscrO,\mbfscrO}]

You can then use \mbfscrO, \mathbfcal{O}, and a few other synonyms.


text:
Q: ListView - Center Cell Views Horizontally w/o ListView Height Wrap_Content I am currently having some formatting issues with Android's ListView. After looking through several questions on SO I did not find any proper solutions.
I have a ListView (used for navigation) including one or more views (actual navigation items). What I want to achieve is - the ListView uses up the whole vertical space (heigth set to match_parent) and the cells are centered vertically in this ListView.

Simply setting the gravity to center_vertical for the ListView does not do the trick. I currently can only achieve this look if I wrap the ListView in another view (which has set the gravity to center_vertical) and change the ListView's height to wrap_content. But this seems not to be the perfect solution as the resulting measuring operations (the adapter's getView method is called multiple times for the same position) have a performance impact, even if applying a proper holder concept for the navigation items. Is there any solution to this issue?
ListView (gravity does not work):
<ListView android:id="@+id/lvNavigation"
        android:layout_width="@dimen/navWidth"
        android:layout_height="match_parent"
        android:gravity="center_vertical" />

ListView with workaround (bad performance):
<LinearLayout android:layout_width="@dimen/navWidth"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="center_vertical">

    <ListView android:id="@+id/lvNavigation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

</LinearLayout>

Navigation item:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_height="wrap_content"
        android:layout_weight="match_parent"
        android:gravity="center_vertical"
        android:orientation="vertical"
        android:paddingLeft="@dimen/horizontalMargin"
        android:paddingRight="@dimen/horizontalMargin">

    ...

</LinearLayout>

A: Listview is probably a bad thing to use for this purpose. I think what you should do is use a recycler view with a custom Layout Manager
In particular you probably want to override onLayoutChildren
I did a quick search and could not find a library that does this for you already.
Alternatively, if you have elements where you can predict the height you can add a header view that is blank and set the height so that the list items will appear centered.
So something like
ListView lv = getListView();
LayoutInflater inflater = getLayoutInflater();
ViewGroup header = (ViewGroup)inflater.inflate(R.layout.header, lv, false);
header.setLayoutParams(new AbsListView.LayoutParams(<width>, <height>));
lv.addHeaderView(header, null, false);


text:
Q: AWS codebuild: CODEBUILD_BUILD_SUCCEEDIN is still 1 even build step failed Step 65/154 : RUN  apt-get install -y python3-pip
 ---> Running in 29f078573813
Reading package lists...
Building dependency tree...
Reading state information...
E: Unable to locate package python3-pip
The command '/bin/sh -c apt-get install -y python3-pip' returned a non-zero code: 100

[Container] 2022/04/20 02:31:18 Phase complete: BUILD State: SUCCEEDED
[Container] 2022/04/20 02:31:18 Phase context status code:  Message:
[Container] 2022/04/20 02:31:18 Entering phase POST_BUILD
[Container] 2022/04/20 02:31:18 Running command echo check CODEBUILD_BUILD_SUCCEEDING $CODEBUILD_BUILD_SUCCEEDING
check CODEBUILD_BUILD_SUCCEEDING 1

As above build log, I am using the AWS code pipeline and I try to install python3-pip in the docker but failed. It returns code 100. But the BUILD State is still SUCCEEDED. And when I echo the value of CODEBUILD_BUILD_SUCCEEDING in the post_build step, its value is still 1 which means the building succeeded. I think the CODEBUILD_BUILD_SUCCEEDING should be set as 0 automatically. I want to exit if the CODEBUILD_BUILD_SUCCEEDING is not 1.
Could you please help me to figure out why the CODEBUILD_BUILD_SUCCEEDING is still 1 even the exit code is 100?
In case you want to check my buildspec.yml:
version: 0.2

phases:
  install:
    runtime-versions:
      docker: 18
  pre_build:
    commands:
      - echo Logging in to Amazon ECR...
      - aws --version
      - echo $AWS_DEFAULT_REGION
      - eval $(aws ecr get-login --region $AWS_DEFAULT_REGION --no-include-email)
      - REPOSITORY_URI=xxxxxxxxx.dkr.ecr.us-east-1.amazonaws.com/test-farget-ecr-t
      - COMMIT_HASH=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7)
      - IMAGE_TAG=${COMMIT_HASH:=latest}
      ############################
      # Pull the previous docker image
      - docker pull $REPOSITORY_URI:latest
  build:
    commands:
      - echo Build started on `date`
      - echo Building the Docker image...
      - |
        if [[ $NEED_BUILD == "yes" ]]
        then
            docker build --cache-from $REPOSITORY_URI:latest -t $REPOSITORY_URI:latest .
            docker tag $REPOSITORY_URI:latest $REPOSITORY_URI:$IMAGE_TAG
        fi
  post_build:
    commands:
      - echo "check CODEBUILD_BUILD_SUCCEEDING $CODEBUILD_BUILD_SUCCEEDING"
      - bash -c "if [ "$CODEBUILD_BUILD_SUCCEEDING" == "0" ]; then exit 1; fi"
      - echo Build completed on `date`
      - echo Pushing the Docker images...
      - |
        if [[ $NEED_BUILD == "yes" ]]
        then
            docker push $REPOSITORY_URI:latest
            docker push $REPOSITORY_URI:$IMAGE_TAG
        fi
      - echo Writing image definitions file...
      - printf '{"name":"fargate-test-api-ecr","ImageURI":"%s"}' $REPOSITORY_URI:latest > imageDetail.json
artifacts:
    files:
      - imageDetail.json
      - taskdef.json
      - appspec.yaml

A: CodeBuild only gets the exit code of the last command in each build step. In the buildstep
if [[ $NEED_BUILD == "yes" ]]
then
    docker build --cache-from $REPOSITORY_URI:latest -t $REPOSITORY_URI:latest .
    docker tag $REPOSITORY_URI:latest $REPOSITORY_URI:$IMAGE_TAG
fi

your last command is docker tag whose exit code is independent of the previous docker build command. You should combine these commands with && to short circuit in the case of a failed docker build.

A: had to add this image :
?
Privileged mode is activated in codebuild?


text:
Q: iOS UserDefaults falls behind saved content This situation is a bit too elaborate to describe in mere words, so I've created a minimal demo project for you to download and run:
https://github.com/mattneub/DefaultsDemo
You will need Xcode 10 to test. This is what the project looks like when it runs:

The project code will appear to have quite a bit of unnecessary kerfuffle, but that is because I've included the minimum material from my real app (a card game) to reproduce the issue I'm seeing. There's a deck of cards and a layout of cards, and the idea is when the user clicks the Home button, we get a notification that the app will resign active, and we save the deck and the card layout into UserDefaults. When we relaunch, we retrieve the deck and the card layout and the user can resume playing.
But it's not working correctly, as I shall explain. And actually testing to see the phenomenon is very simple:

*

*Run the project on the simulator.

*Hit the Shuffle button three to five times or so. (If you start to run out of cards, hit the New Deck button. But in my testing, that's not usually necessary.)

*Hit the Home button on the simulator. This causes us to save into UserDefaults. Look at the Xcode console; it tells you have many cards are in the deck that was just saved into UserDefaults. Remember that number!

*Back in Xcode, stop the project and run it again, starting again at Step 1. As we launch, you are told how many cards are in the deck that was just retrieved from UserDefaults.
Keep repeating those four steps. What happens to me is that after about two or three cycles, the number in step 4 differs from the number in step 3. We are not getting back from UserDefaults the same deck that we saved into UserDefaults a moment ago!
Moreover, I can say something more about this wrong number: it is the number of cards in the deck that we saved into UserDefaults on some earlier occasion. It is as if UserDefaults has become corrupt silently in some way and has stopped accepting new versions of the deck.
To illustrate, I have just cleaned the simulator and opened the project, and I'll run it and tell you what I see in the console (with comments explaining what I did):
81 // launch
65
starting fresh 65
62 // shuffle
59 // shuffle
56 // shuffle
saving 56 // Home button

Okay, let's launch again from Xcode:
retrieving 56 // launch
53 // shuffle
50 // shuffle
47 // shuffle
44 // shuffle
saving 44 // Home button

Fine, so let's launch again from Xcode:
retrieving 56 // launch

That's the bug! We've fallen behind; we're retrieving the deck from the previous save, not the one from the save we just did. (I can actually prove this by printing out the deck; it has a description property for just this purpose, and I can actually see that it's the deck from the previous save.)
So the question is: why? I know how to work around it; save into files instead of UserDefaults. But I'd like to know what's up with UserDefaults here that's causing this problem. I suspect that one of the objects I'm saving into UserDefaults is causing some sort of silent corruption, but I don't see how that can be, as they are just Data objects.
(By the way, calling synchronize changes nothing, and in any case it is deprecated according to the header, even though not yet formally so.)

A: I'm going to suggest this entire project is a red herring and that the problem is your testing procedure.
I theorize that UserDefaults saves slowly: it just takes a really long time for a change to UserDefaults to "take", even after every signal has occurred that the change has happened (synchronize has returned, the didChange notification has arrived, and so on).
Thus, I'm betting that you're just not allowing enough time between hitting the Home button and running the app again. To see that this might be so, make the following change: Instead of going directly from Step 3 to Step 4, interpose Step 3a, where you count to 10, slowly. Now the bug doesn't manifest itself.
(One could also argue that saving at willResignActiveNotification time is just wrong. The time to save is when the relevant data changes! Thus, in the test example, we should be saving at the end of every shuffle-and-deal operation — not when the user hits the Home button.)


text:
Q: Fetch first two elements from map I have to read only the first two elements from an std::map.
Here's my code:
#include<iostream>
#include<map>
#include<iterator>
using namespace std;
int main() {
    map<int,int> a;
    map<int,int>:: iterator itr;
    itr = a.begin();
    cout<<itr->first<<" "<<itr->second<<endl;
    next(itr);
    cout<<itr->first<<" "<<itr->second<<endl;
    return 0;
}

I'm getting this error:

next was not declared in the scope

what am I missing here and if there is a better way to do it?

A: For using std::next, you need to have at least C++11 compliant compiler.
std::next returns a new incremented iterator. So, you need to use its return value to get the incremented iterator i.e.:
itr = next( itr );

Right now, itr is pointing to the same element because the return value is not used.
If you meant to increment the itr without a new iterator then std::advance is a better candidate here i.e.:
std::advance( itr, 1 );

If you're using a pre-C++11 compiler then you can use increment operator like this:
itr++;

Or,
++itr;

Here's a live demo.

In addition, the map is uninitialized/empty and you're trying to access its elements that are not there and this would result in Undefined Behavior.
Relevant read:

*

*Why is "using namespace std;" considered bad practice?

*C++: "std::endl" vs "\n"

A: you should use itr++ to move itr forward to point next set of pairs. and you can access them by map->first; and map->second;


text:
Q: sencha touch android app not working on android 4 (D/chromium( 3938): Unknown chromium error: -6) i have build a android app with sencha 2.3 ,cmd 4 and phonegap 3. it is working fine in android 2.x devices but not able to make jsonp calls in android 4.x devices.
adb logcat show some D/chromium( 3938): Unknown chromium error: -6
http://imgur.com/l8F9uiN
E/Web Console( 4232): Uncaught ReferenceError: Ext is not defined at file:///and
roid_asset/www/index.html:7
I/ActivityManager(  694): Displayed rd.yadav.riteyouth/.riteyouth: +1s427ms
I/Web Console( 4232): Could not find cordova.js script tag. Plugin loading may f
ail. at file:///android_asset/www/phonegap.js:1511
E/Genymotion(  694): Could not open '/sys/class/power_supply/genymotion_fake_pat
h/present'
D/chromium( 4232): Unknown chromium error: -6
D/chromium( 4232): Unknown chromium error: -6
I/Web Console( 4232): this is a store at file:///android_asset/www/app.js:1
D/chromium( 4232): Unknown chromium error: 0
D/chromium( 4232): Unknown chromium error: -6
E/Genymotion(  694): Could not open '/sys/class/power_supply/genymotion_fake_pat
h/present'

I also try to add
Ext.Loader.setConfig({
    enabled: true,
    disableCaching: false
});

Ext.Ajax.setDisableCaching(false);

these lines in index.html but then this error is generated:
E/Web Console( 4232): Uncaught ReferenceError: Ext is not defined at file:///android_asset/www/index.html:7

A: my problem is solve after whitelisting the domain.
http://docs.phonegap.com/en/3.3.0/guide_appdev_whitelist_index.md.html#Whitelist%20Guide


text:
Q: How to notify if a class property of a class property has changed? Let's say I have two classes in my WPF application:
public class Radio
{
    public int Volume { get; set; }
}

public class Vehicle
{
    public Radio MusicRadio { get; set; }

    private void Explode()
    {
        if (MusicRadio.Volume == 10)
        {
           Application.Shutdown();
        }
    }
}

...where Vehicle has a property which is an instance of the Radio class. In my code behind, I want to set the volume of that radio class when a button is clicked:
private void startButton_Click(object sender, TextChangedEventArgs e)
{
    Vehicle Xterra = new Vehicle() { MusicRadio = new Radio() };

    for (int i = 0; i < 666; i++)
    {
        Xterra.MusicRadio.Volume = i;
    }
}

In the above code, the application should shutdown via the Explode() method once the for loop reaches 10 iterations.
I want my Vehicle class to execute its private function Explode() every time the volume the MusicRadio property changes. How can I make sure it is alerted to this change?

A: One way to do this would be to add a VolumeChanged event to your Radio class. Then in your Vehicle class, you can subscribe to the event and call Explode from there. Note I haven't worked with wpf, I am just assuming it will work there. Happy to delete the answer if that's not the case.
First, add the event to the Radio class:
public class Radio
{
    private int volume;

    public int Volume
    {
        get { return volume; }
        set
        {
            if (value == volume) return;
            volume = value;
            OnVolumeChanged(new EventArgs());
        }
    }

    public event EventHandler VolumeChanged;

    protected virtual void OnVolumeChanged(EventArgs e)
    {
        VolumeChanged?.Invoke(this, e);
    }
}

Then, subscribe to it in the Vehicle class, and call Explode from there (or move the Explode code into the event directly):
public class Vehicle
{
    private Radio musicRadio;

    public Radio MusicRadio
    {
        get { return musicRadio; }
        set
        {
            musicRadio = value;
            if (musicRadio != null)
            {
                // In the unlikely event that the same radio is assigned more than once,
                // we only want to subscribe to the event one time, so remove it first.
                musicRadio.VolumeChanged -= MusicRadio_VolumeChanged;
                musicRadio.VolumeChanged += MusicRadio_VolumeChanged;
            }
        }
    }

    private void MusicRadio_VolumeChanged(object sender, EventArgs e)
    {
        Explode();
    }

    private void Explode()
    {
        if (MusicRadio.Volume == 10)
        {
            Application.Shutdown();
        }
    }
}

A: WPF MVC
ViewModel:
public abstract class ObservableObject : INotifyPropertyChanged, INotifyDataErrorInfo
    {
        public void OnPropertyChanged<T>(Expression<Func<T>> property)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(property.GetMemberInfo().Name));
            }
        }
}

public class TankModel : ObservableObject
{
  public float Level
        {
            get { return level; }
            set
            {
                try
                {
                    if (level != value)
                    {
                        level = value;
                        OnPropertyChanged(() => Level);
                    }
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }
            }
        }
}


text:
Q: Unable to boot after boot repair using live usb After a kernel update in ubuntu 16.04 system, I restarted and unable to login. It says No bootable disc found. So i repaired the boot using boot-repair. If the live usb stick is connected, ubuntu is listed in the boot options. Even though I logged in using that entry I am unable to connect internet. Ubuntu boot entry is not appearing if the live usb is removed.
Here is the report
http://paste.ubuntu.com/p/ybKpfGRMbK/
Can someone look into the report and help me solving the problem?
Thanks


text:
Q: how to fix occasional return data when uploading file with ajax I have a problem with my code. I created upload file with ajax in Laravel. I am using tutorial from here, and yes it is working. But, it working sometimes.
I have no idea where the problem is. But I have changing max_execution_time in php.ini into 0 value. I also included csrf_token() in ajax headers
I wish there somebody help me with this code. I don't know, but the code looks good for me. Here is the code
blade view
 <form class="form-main"  enctype="multipart/form-data" method="post" id="formbank" >

       <input type="file" id="myfile" name="myfile" accept="image/*">
           Select File

        <button class="but-main">Submit</button>

 </form>

JS script
$(document).ready(function(e){

    $('#formbank').on('submit',function(e){
    e.preventDefault();
    var fd = new FormData(this);
    fd.append('myfile',$('#myfile')[0].files[0]);

    $.ajax({
        async: true,
        type:'post',
        data:fd,
        contentType: false,
            cache:false,
        processData: false,
        headers: {
            'X-CSRF-TOKEN' : "{{ csrf_token() }}"
        },
        url: "{{ route('post.bank') }}",
        success:function(data){
            console.log(data);

        },
        error:function(data){
            console.log(data);
        }
    });
});

});

post.bank controller
public function createBank(Request $request){
   if ($request->hasFile('myfile')) {

     $file = $request->file('myfile');

     return $file->getClientOriginalName();

    }
   else {
     $text = 'empty';
     return $text;
}

In this case, I only try to return name of uploaded file. Here is the result.
https://drive.google.com/file/d/1zK5YmO8f8cGR110X-oi2bTVMiaMCXYi9/view?usp=sharing "result"

A: Thank you for all suggestion. Many thanks. After several trial and errors, I find a trick to resolve it by calling main function with setTimeOut(). And i put _token validation in controller. When token is empty, it will return a value that let setTimeOut() do the rest of time until token is loaded correctly.
I guess that way is suited for me. And I will be happy if there is a better answer to resolve it in a better way. Thank you anyway..


text:
Q: msgpack c++ packing and go unpacking I was trying out msgpack, with c++ and go versions, however I run into a problem of not being able to produce identical binaries when marshalling/packing data...
here is the cpp version
struct Data {
    int X, Y, Z;
    std::string Msg;
    double Value1, Value2;

    MSGPACK_DEFINE(X, Y, Z, Msg, Value1, Value2);
};

void test0() {
    Data data {
        1, 1, 1,
        std::string{"value"},
        1.1, 2.2
    };

    std::stringstream buf;
    ::msgpack::pack(buf, data);
    auto str = buf.str();
    fmt::print("size = {}\n", str.size());
    for (int i=0; i<str.size(); i++) {
        if (i % 20 == 0) fmt::print("\n");
        fmt::print("{0:02x} ", (unsigned char)str[i]);
    }
    fmt::print("\n");
}

here is the go version
package main

import (
    "fmt"

    msgpack "github.com/vmihailenco/msgpack/v5"
)

type Data struct {
    X, Y, Z int
    Msg string
    Value1, Value2 float64
}

func main() {
    bytes, err := msgpack.Marshal(&Data {
        X: 1,
        Y: 1,
        Z: 1,
        Msg: "value",
        Value1: 1.1,
        Value2: 2.2,
    })
    if err != nil {
        panic(err)
    }

    fmt.Println(len(bytes))
    for i, b := range bytes {
        if i % 20 == 0 {
            fmt.Println()
        }
        fmt.Printf("%02x ", b)
    }
    fmt.Println()

    var data Data
    err = msgpack.Unmarshal(bytes, &data)
    if err != nil {
        panic(err)
    }
    fmt.Println(data)
}

Dumping arrays of bytes for both cases i get different results. I suspect i'm doing something wrong... but i do not quite see it
VK


text:
Q: Pass FILE_ATTRIBUTE constants to C runtime functions I am trying to optimize a legacy application written in C which makes uses of regular stdio.h resp. fcntl.h functions. For special uses, I would like to inject a few extra hints from
https://learn.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants to newly opened file handles.
But those are available only to low-level Win32 APIs. Is there a way to pass the FILE_ATTRIBUTE_... options to the open() call somehow? Or is there somewhere a sane wrapper which would open a file handle "win32 way" with custom options and hand it over as integer file descriptor just like open() would do it?

A: There are two functions that convert between Win32 file handles and file descriptors:

*

*intptr_t _get_osfhandle(int fd); will get you a HANDLEfrom a given fd

*int _open_osfhandle(intptr_t osfhandle, int flags); will get you an fd from a HANDLE
Note that for both:

The _open_osfhandle call transfers ownership of the Win32 file handle
to the file descriptor. To close a file opened by using
_open_osfhandle, call _close

To close a file whose operating system (OS) file handle is obtained by
_get_osfhandle, call _close on the file descriptor fd. Never call CloseHandle on the return value of this function. ...

If you want to set the attributes at creation time, you would need to use CreateFile and then convert to a fd, because afaics there is no API to set attributes on a given HANDLE, there's only SetFileAttributes which operates on a name.
If you just wanna query the attributes, you can use GetFileInformationByHandle.


text:
Q: Call to a member function ERROR PHP I am trying to use this tutorial to populate a Select2 drop down with data from a MySQL Database: http://www.southcoastweb.co.uk/jquery-select2-ajax-tutorial/
This is the PHP script I am using (Slightly modified from original):
<?php
    // setup databse connection
    require("../scripts/connect.php");

    // i have set the limit to 40 to speed up results
    $result = $db->prepare("SELECT id,model FROM vehicles WHERE model LIKE :term ORDER BY model ASC LIMIT 0,40");

    // bind the value for security with the wildcard % attached.
    $result->bindvalue(':term','%'.$_GET["q"].'%',PDO::PARAM_STR);
    $result->execute();

    // make sure there are some results else a null query will be returned
    if($result->rowcount() != 0) {
        while($row = $result->fetch(PDO::FETCH_ASSOC)){
            $answer[] = array("id"=>$row['id'],"text"=>$row['id']." - ".$row['model']);
            // the text I want to show is in the form of option id - option
        }
    } else {
    // 0 results send a message back to say so.
        $answer[] = array("id"=>"0","text"=>"No Results Found..");
    }

    // finally encode the answer to json and send back the result.
    echo json_encode($answer);

This is the DB layout:
CREATE TABLE `vehicles` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `carline` varchar(125) NOT NULL,
    `model` varchar(255) NOT NULL,
    `year` varchar(12) NOT NULL,
    `engine` varchar(255) NOT NULL,
    `airconditioning` enum('Yes','No') NOT NULL,
    `transmission` enum('Automatic','Manual') NOT NULL,
    `drive` enum('2WD','4WD') NOT NULL,
    `designation` enum('Passenger','Commercial') NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=14 ;

And this is the Error I am recieving:

[08-Feb-2014 18:28:06 Pacific/Auckland] PHP Notice: Undefined
  variable: db in /Users/.../app/scripts/serviceplan_values.php on line
  6 [08-Feb-2014 18:28:06 Pacific/Auckland] PHP Fatal error: Call to a
  member function prepare() on a non-object in
  /Users/.../app/scripts/serviceplan_values.php on line 6

Any Ideas?

A: The error is most probably in connect.php, where you need to set the $db variable.


text:
Q: How to capture the selection:toggle event fired by wp.media I can't figure out the proper syntax for listening in on this event. I just don't know where it exists. I know that this is the name of the event because I'm logging every single wp.media event using a function I've seen a few times on Stack.
I can capture the event when it occurs on the Feature Image selection screen because I actually know the syntax:
wp.media.featuredImage.frame().on('selection:toggle', function() {
    console.log('image selected');
});

I need to know what property name to use for the regular Insert Media frame, in place of featuredImage. You would think this would be easy to find, but most of the info out there about wp.media deals with constructing and extending.
Update - The only appearance this event makes in the source code is in media-views.js:
toggleSelectionHandler: function( event ) {
    ...
    this.controller.trigger( 'selection:toggle' );
},

This resides in wp.media.view.Attachment. I've tried traversing it inside the console, and firing .on('all') events but the only thing i get returned  is ready.
The more I look into wp.media, it would seem like all this event is doing is announcing itself to be made available to a handler, if that's the right term, and as far as I can tell there is no handler doing anything with it, at least not in the wp.media global namespace.
From the limited examples available online, it seems like one would have to create an entirely new instance of the media library popup using the wp.media() constructor and then specify an on.select() method... or possibly extend the existing media library functionality somehow, if you could find where to do so. It all seems foreign to me.
Alternatively...
If there is a globally-available event for when the attachment details form frame opens up, that would likely work for my particular scenario. So please share if you know the syntax for this event.

A: I was able to cobble something together. I feel like there is a better approach to solving this, but that it might help to share my progress anyway.
The main trick came from this answer by @Vladimir Lukyanov.
My main concern with this solution is that the unselect event, "selection:unsingle", is triggered twice. I was unable to prevent this from happening.
The other concern is just that there is probably a cleaner way of accomplishing this. However, after lots of searching and experimenting, this is the closest I came to a solution.
add_action( 'admin_print_footer_scripts', 'wpse_media_library_selection_toggle' );
function wpse_media_library_selection_toggle() { ?>
<script type="text/javascript">
    ( function( $ ) {
        $( document ).ready( function() {

            // Ensure the wp.media object is set, otherwise we can't do anything.
            if ( wp.media ) {

                wp.media.featuredImage.frame().on('selection:toggle', function() {
                        console.log( 'image selected' );
                });

                // Ensure that the Modal is ready.
                wp.media.view.Modal.prototype.on( "ready", function() {
                    // console.log( "media modal ready" );

                    // Execute this code when a Modal is opened.
                    wp.media.view.Modal.prototype.on( "open", function() {
                        // console.log( "media modal open" );

                        // The sidebar boxes get deleted and recreated on each select - hack into this to do the same.
                        var selection = wp.media.frame.state().get( "selection" );
                        selection.on( "selection:single", function ( event ) {
                            console.log( "selection:single" );
                        } );

                        // Not sure why, but this fires twice...
                        selection.on( "selection:unsingle", function ( event ) {
                            console.log( "selection:unsingle" );
                        } );

                    });

                    // Execute this code when a Modal is closed.
                    wp.media.view.Modal.prototype.on( "close", function() {
                         // console.log( "media modal close" );
                    });
                });
            }

        });
    })( jQuery );
</script><?php
}


text:
Q: Querying "extension tables" using Hibernate I am having a querying issue in Hibernate.  I have a table, 'test', with existing data.  I have a requirement where I can not modify the schema of the test table, so I created another table, 'testExtension', whose primary key is a foreign key to the primary key of Test.  Data in testExtension is a subset of the data in test. i.e. There will be less rows in 'testExtension' than in 'test'.
I have defined this relationship in a configuration file as follows:
<class name="Test" table="test">
<id name="testId" column="test_id">
    <generator class="sequence">
        <param name="sequence">test_id_seq</param>
    </generator>
</id>

<property name="name"/>

<joined-subclass name="TestExtension" table="testExtension">
    <key column="test_id"/>

    <property name="summary" />
    <property name="homepage"/>
</joined-subclass>

With this setup, I am able to create a TestExtension object in my Java program, populate it with data, 'save' it via Hibernate, and commit the transaction.  And it correctly saves data in both Test and TestExtension.
My problem is occurring when I am trying to query data from these tables.  Right now if I query for a particular test_id using the TestExtension.class to QBE, it will only return a row if that id exists in both Test and TestExtension.  If I use the Test.class to QBE, it will return the row but I will not have access to any of the data stored in TestExtension.
My question is: how can I query these tables so that the results are based off a 'left outer join' of both Test and TestExtension? Any solution is appreciated, whether it's query by example, HQL, or something else (though preferably not raw SQL).
Thanks!

A: HQL is probably the easiest way to do this.  Docs are here:
http://docs.jboss.org/hibernate/stable/core/reference/en/html/queryhql-joins.html
Sounds like what you might want to do is remap your relationships so that Test and TestExtension use a one-to-one relationship instead of inheritance. Then you can query for Test and TestExtension using a left outer join across the one-to-one.

A: If you use HQL to write a query for the Test class, it should do what you want. I assume QBE is effectively adding the class of your example entity as one of the query parameters.
So sth like:
from Test t where t.property = :value

should return either Test or TestExtension entities. Note that (at least with the versions of Hibernate I've used). In this case, Hibernate should immediately give you back the actual entities rather than a proxy too--- be aware that TestExtension entities can sometimes be returned as plain Test lazy-loading proxies.


text:
Q: SophosLabs Intelix - 16MB restriction According to the documentation and experiment with actual code, it is found that file larger than 16MB cannot be scanned by SophosLabs Intelix. Reference: https://api.labs.sophos.com/doc/changelog.html
Short video files, such as MP4, can usually be in the size of 100MB etc. It looks like such file types shall be processed by Static Analysis. What are the alternatives, given such restriction?
Attempted scanning a 50MB video and fails.