text:
Q: obtener el nombre de un archivo pdf que esta en el servidor Necesito descargar un pdf desde mi app android pero sin pisar el nombre, es decir, cuando ingreso la "url /.../.../valortiempo" para generar la petición al servidor, este me va a responder con un pdf con su nombre,que hace referencia a ese tiempo que le envío.
La cuestión es que en mi código me pide que ingrese un nombre para renombrar a mi archivo, y lo que necesito es el nombre original del pdf:
String url = "";
    try {
        byte[] todo = null;
        byte[] parte = new byte[1024];
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        URL newurl = new URL(url);
        HttpURLConnection con =
                          (HttpURLConnection)newurl.openConnection();
        con.connect();
        int cont =0;
        while ((cont = con.getInputStream().read(parte)) != -1) {
            bos.write(parte, 0, cont);
            bos.flush();
            publishProgress(cont);
        }
        todo = bos.toByteArray();

        File file;
        String fileName = Uri.parse(url).getLastPathSegment();
        file = File.createTempFile(fileName,null,getApplicationContext().getFilesDir());

        FileOutputStream fos = new FileOutputStream(file);
        BufferedOutputStream bost = new BufferedOutputStream(fos);
        bost.write(todo);
        listaDeArchivos.add(file);
        bost.close();

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

A: En realidad estas obteniendo el nombre del archivo original de la url mediante:
 String fileName = Uri.parse(url).getLastPathSegment();

por ejemplo si tu url es :
String url = "http://www.example.com/some/path/to/a/file.pdf"

Mediante Uri.parse(url).getLastPathSegment() se obtiene
file.pdf

Pero el método para guardar usado para guardar el archivo es createTempFile()
file = File.createTempFile(fileName,null,getApplicationContext().getFilesDir());

el cual requiere de un prefijo, un sufijo y el path destino.

createTempFile(String prefix, String Sufijo , File Directorio)

*

*Prefix - La cadena de prefijo que se utilizará para generar el nombre del archivo; Debe tener al menos tres caracteres.

*Sufijo - La cadena de sufijo que se utilizará para generar el nombre del archivo; Puede ser nulo, en cuyo caso se utilizará el sufijo
  ".tmp"

*Directorio - El directorio en el que se va a crear el archivo, o null si se va a usar el directorio de archivos temporales por defecto

En este caso no es posible cambiar el nombre del "archivo temporal" a crear, únicamente agregar un prefijo y un sufijo:

como ejemplo, tengo una aplicación que usa este método y puedes notar defino un prefijo ("android_tutorial") y un sufijo (".pdf"):
 file = File.createTempFile("android_tutorial", ".pdf", getApplicationContext().getFilesDir());

por lo tanto se agregan se agrega el prefijo y sufijo pero no hay manera de cambiar el nombre del archivo temporal que crea el sistema operativo:


text:
Q: Sort grouped nodes by taxonomy weight in views I have one vocabulary with 4 taxonomy terms
- Term A
- Term B
- Term C
- Term D

and there are some nodes which I grouped in views by taxonomy term, so the result looks
like this:
- Term 1
  - Node 1
  - Node 2
- Term B
  - Node 3
  - Node 4
... and so on...

Then I reordered terms, but there is no change when I look on the views page. Still the same order. So, please, what are the steps to make them ordered by weight?

A: I'll answer this question myself.. hope, that it helps some people..
In views just add 'Relationship' -> Content: Taxonomy terms on node and then You can add in 'Sort criteria' -> (term) Taxonomy term: Weight (asc)
That's all

A: For me even after adding the "'Relationship' -> Content: Taxonomy terms on node"  the "'Sort criteria' -> (term) Taxonomy term: Weight " was still not available.
I found out that after checking "disable views data caching"  under admin/structure/views/settings/advanced  it became available (as well as a lot of other sort and filter criterias).
I noticed that checking "disable views data caching" was only necessary on remote host not on localhost.
I have no idea why this is so (I am not a drupal expert), but maybe it can help someone.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ember Handling 401s Revisited in 2015 I can find a ton of old questions asking/answering how to handle 401s from the Rails backend in Ember/Ember Data. Many, if not all, seem to be outdated at this point. I have tried everything I could find. (Ember-Data handling 401's)
But no matter what I do I just keep getting 401 errors in the console while the 401s are never caught in my code. All I want to do is add a redirect to '/' if a 401 is ever encountered in any place/model/anything. I don't need any checking for authentication or anything else.
I have tried adding this to the Application Route actions as well as to to the Router itself.
error: function (error, transition) {
  console.log("err: " + error.status);
  if (error && error.status === 401) {
    return this.transitionToRoute('/');
  }
}

I've also tried several variations of this https://stackoverflow.com/a/19063009/1850353.
App.ApplicationAdapter = DS.RESTAdapter.extend({
  ajaxError: function(jqXHR) {
    var error = this._super(jqXHR);
    console.log("jqXHR: " + jqXHR.status);
    if (jqXHR && jqXHR.status === 401) {
      #handle the 401 error
    }
    return error;
  }
});

I'm obviously a noob so maybe I'm missing something simple here. None of my console.log's are getting triggered unless it's for a new error I've introduced trying to get this to work. Is there a current, 'best practice' style way of doing this?

A: Both of the two other answers here are good and will work fine, but have a few undesirable caveats IMHO.
I would strongly recommend implementing an Ember.onerror hook. Any unhandled promise rejections will end up at that hook. You can implement it with an initializer if you're using Ember-CLI.
// app/initializers/on-error.js
export default {
  name: 'on-error',
  initialize: function(container, app) {
    Ember.onerror = function(error) {
      if(error && error.status === 401) {
        // Ember 2.1 adds a public lookup function. Older versions
        // need to use the container.
        var router = app.lookup ? app.lookup('router:main') :
                     app.__container__.lookup('router:main');
        // Even future versions of ember are likely to have an
        // accessible router service to do this work.
        router.transitionTo('sign-in');
      }

      if(error && error.stack) {
        // Uncaught exception - Log stacktrace to server
      }
    };
  }
}

As mentioned above, this will handle all uncaught promise rejections. So this still provides you with a good bit of flexibility to handle promises locally in a component. For example:
export default Ember.Component.extend({
  actions: {
    saveChanges: function() {
      this.get('model').save().then(null, (reason) => {
        if(/* reason is validation error */) {
          this.set('validationError', reason.errorMsg);
        } else {
          throw reason;
        }
      })
    }
  }
 });

Take notice that in the promise rejection handler above if we couldn't handle the error, we rethrow it. This is very important. Rethrowing the error will give any additional chained promise handlers the chance to deal with it. And ultimately it will make it's way up to Ember.onerror if left unhandled.

A: Using Ember 1.13.8 & Ember Data 1.13.9, my authenticated routes use:
actions: {
  error: function(reason, transition) {
    if (reason.errors[0].status === '401') {
      this.transitionTo('sign-in');
    }
  }
}

A: Controllers and Routes
With logic that is executed in a controller or route, you generally have an error action attached to the route. If an action is triggered on a controller and the controller doesn't handle that action (e.g. there is no error action in the controllers actions hash) then it is automatically passed to the route to get a chance to handle - if the current route doesn't handle the action either it bubbles to parent routes until it hits the ApplicationRoute.
The way I handle it is have an AuthenticatedRoute that any route that needs to handle a 401 extends from. Also, in the example you've linked to - it has events whereas it's now actions.
Something like this should work for you:
    App.AuthenticatedRoute = Ember.Route.extend({

        actions: {
        error: function(error) {
            if (!error || error.status !== 401) {
                // returning true bubbles the error to parent routes
                return true;
            }

                // put your logic here
                console.log('this is a 401 error.');
            }
        }

    });

    App.IndexRoute = App.AuthenticatedRoute.extend({
        //logic
    });

    App.FooRoute = App.AuthenticatedRoute.extend({
        //logic
    });

    App.BarRoute = App.AuthenticatedRoute.extend({
        //logic
    });

Components
Ember is moving more and more towards components - the thing with logic executed in components is that it's completely isolated from everything else. Generally the only things available to you in your components are the things you pass into them.
This means that if you're executing some logic in a component none of the logic above - the logic that exists on the routes to handle errors - is used unless you explicitly use it yourself.
If your making calls like store.find('person', 1) or person.save() in a component you need to handle the errors explicitly using the .catch() function or passing a second function to the .then(). For example the following two statements would do the same thing:
    store.find('person', 1).then(function(person) {
        console.log('found person 1:', person);
    }, function(err) {
        console.log('error finding person 1:', err);
    });

    store.find('person', 1).then(function(person) {
        console.log('found person 1:', person);
    }).catch(function(err) {
        console.log('error finding person 1:', err);
    });

And so would these two statements:
    person.save().then(function() {
        console.log('successfully saved person');
    }, function(err) {
        console.log('error saving person:', err);
    });

    person.save().then(function() {
        console.log('successfully saved person');
    }).catch(function(err) {
        console.log('error saving person:', err);
    });

Reusing the Route Error Logic in Components
If you want to pass the error handling in your components onto your routes to deal with the best way to do that is have the component fire an action and have the calling template/view/controller handle it.
app/components/my-component.js
    Ember.Component.extend({
        'on-error': null,
        model: null,
        actions: {
            save: function() {
                var component = this;
                var model = this.get('model');

                mode.save().then(function() {
                    console.log('saved');
                }).catch(function(err) {
                    component.sendAction('on-error', err);
                });
            }
        }
    });

app/templates/components/my-component.hbs
    <button {{action 'save'}}>Save</button>

app/templates/index.hbs
    <!--
        Passing the 'error' action to the components 'on-error' property links the 'on-error'
        action on the component with the 'error' action on the controller - if the controller
        doesn't handle it, it's bubbled up to the route to handle
    -->

    {{my-component model=model on-error='error'}}


text:
Q: ReSharper formatting: align equal operands
Note to Googlers, this question is somewhat out of date as the requested feature is now supported in the current version of ReSharper 2017.3.1

I like to formatting my code to align right side of equal operands.
Like here:
bool    canRead     = false;
bool    canReadClass    = true;
string  className   = boType.Name;

I've switch to ReSharper recently and found it very useful but cannot find option allowing me format code in described way.
Do you know if there is such option / plugin?
Maybe you know other than ReSharp solution allowing that?
EDIT:
How to decide what part of code shall be aligned?
My convention is aligning all variables in same block.
 By "block" I meant part of code not divided by empty lines.
eg
// First block
int      count     = 10;
string   name      = "abc";
bool     calculate = true;
.....
.....
// Second block
MyOwnType    myType   = new MyOwntype();
int          count    = 10;

EDIT -2
I've opened R# ticket for this. If anyone interested please vote!

A: You can try this: Code Alignment
It supports

*

*Align by... (Dialog)

*Align by position... (Dialog)

*Align by Equals

*Align by m_

*Align by "

*Align by .

*Align by Space

A: Productivity Power Tools 2012 also has a command for this: ctrl-alt-]
Other goodies are obviously there as well.

A: There is (currently) no way to do this out of the box in ReSharper. Fortunately, ReSharper has a very rich extensibility API (albeit poorly documented). I've spent a lot of time with Reflector trying to figure things out.
We use a similar alignment guideline for class members in a company I work for (to the extreme, we also align method parameters). I wrote a plugin for ReSharper to help me do just that. It's a "Code Cleanup" module, which runs sometime during the code cleanup (Ctrl-E, Ctrl-F) and aligns the code for you. It also makes the class sealed, if possible.
Some examples:
Method parameters:
public void DoSomething(string      name,
                        int         age,
                        IEnumerable coll)

(you will need to change Wrap formal parameters to Chop always in Options->Formatting Style->Line Breaks and Wrapping for this to work properly)
Constants:
private const int    RESOURCEDISPLAYTYPE_DOMAIN = 0x00000001;
private const int    CONNECT_COMMANDLINE        = 0x00000800;
private const int    CONNECT_INTERACTIVE        = 0x00000008;
private const string RESOURCE_NAME              = "Unknown";

You can download the source code from my SkyDrive.
Edit I seem to have lost access to that SkyDrive, and lost the files too. This was before github :(

Please note that you'll need several things to compile/debug it:

*

*Update the Command Line Arguments
in Debug tab in Project
Properties with the correct path of
the output DLL:

/ReSharper.Plugin
"X:\<projects>\MyCompany.CodeFormatter\MyCompany.CodeFormatter\bin\Debug\MyCompany.CodeFormatter.dll"

This allows debugging the plugin via
F5, and it will be
automatically installed in
ReSharper's Plugins in the new
Visual Studio instance which will
open.

*The plugin is for ReSharper 4.5 and it references the DLLs of this version. If you installed ReSharper anywhere else except C:\Program Files\JetBrains\ReSharper, you will have to fix the references.

*This does not align variables inside methods, but it shouldn't be hard to add :)

After you install this, just run Code Cleanup to fix your alignment (I never got a reply from JetBrains about how to do this during brace/semicolon formatting, unfortunately).
Assembly was renamed to protect the innocent :)
Good luck!

A: I think it is worth noting that the Visual Studio Productivity Power Tools have an Align Assignments feature.
Here's a link to the Visual Studio 2013 Productivity Power Tools.

A: As far as I know, this is unfortunately not possible using Resharper.

A: Years late, but further to the comment from @MickyD, Resharper can do this for you, see Resharper blog. Go to Resharper/ Options/ Code Editing/ C#/ Tabs, Indents, Alignment. Scroll to the bottom of the options in the right hand window pane to find "Align Similar Code in Columns", click things, enjoy.


text:
Q: How to create multiple DBAccss databases in ios App? How can I use multiple dbaccess database in one app?
For example: If I have two database namely "database1" and "database2". Now, How can I store data in specific database and retrieve from it?

A: DBObjects have a method on them called, storageDatabaseForClass.  If you respond to this method then another database will be created of that name, and that class will be created and persisted within it.
+ (NSString *)storageDatabaseForClass {
    return @"database2";
}

There is a caveat, that being that queries are not optimised across the different storage bases, you will also not be able to perform JOIN operations across them, and if you are using subqueries would will not be able to perform them inline but will have to perform them outside and pass the results into the query as a parameter.
Thanks
Adrian


text:
Q: Fetch data from a SQLite View with CoreData Is it possible with Core-Data to fetch data from a view ? (I mean a SQLite View)
On the first launch of my iOS app, I load data from a single SQLite file into my Core-Data store, but in this sqlite file, I also have a view.
How can I handle this with Core-Data ?
I would like to be able to fetch data from this view.

A: A view is really nothing but a select statement. Just sync these separately using simple SQL strings. You can store them as FetchRequestTemplates in your Core Data model.


text:
Q: Generate warning message on R Shiny Dashboard Sidebar using "SelectizeInput" I would like to add a warning message, in my shiny dashboard sidebar, if user enters something that is not recognized. I found something very informative: Check Shiny inputs and generate warning on sidebar layout
But it is not exactly what I need, and would like to hear what you think. Below is my code
library(shiny)
ui <- dashboardPage(

  dashboardHeader(),
  dashboardSidebar(
    selectizeInput('email', 'Email', c("NYC@gmail.com", "LA@gmail.com","SF@gmail.com"), multiple = FALSE,
                   options = list(
                     placeholder = 'Email addresss',
                     onInitialize = I('function() { this.setValue(""); }')
                   )),
    uiOutput('email_text')
  ),
  dashboardBody()
)

server <- function(input, output) {
  output$email_text <-
    renderUI({
      if(input$email == ""){
        return(p("Please add your gmail e-mail address."))
      }

      #Update: Below checks for "gmail" - I would something to search list and return.
      if(!grepl("gmail", input$email)){
        return(p("Your email is not a gmail e-mail address!"))
      }

    })
}

shinyApp(ui = ui, server = server)

Current sidebar selection performs well to recognize email format, as long as I select from the dropdown list

However, what I also want to add in is, if I enter something that is not expected (not in the list given), the system can capture that and warn me (E.g. "Your email is not an expected email address!"). Currently, if I just enter some something not in the list, the system does not do anything:

I feel that comparing with post I mentioned above, my version has issue with "selectizeInput" function. It is designed to intake elements from the list, not everything user enters. Is there a way to work around it? I try to use validate() but had no luck.
Thanks so much in advance for your help!

A: By default selecticizeInput does not allow the user to enter new values. You have to enable this with options = list(create = TRUE). Once you have this option, you can check whether the newly created email is in the pre-defined list of emails using %in% and report a custom error message in the sidebar.
Here is the updated code:
library(shiny)
library(shinydashboard)

list_of_emails <- c("NYC@gmail.com", "LA@gmail.com", "SF@gmail.com")

ui <- dashboardPage(dashboardHeader(),
                    dashboardSidebar(
                      selectizeInput(
                        'email',
                        'Email',
                        c("NYC@gmail.com", "LA@gmail.com", "SF@gmail.com"),
                        multiple = FALSE,
                        options = list(
                          create=TRUE,
                          placeholder = 'Email addresss',
                          onInitialize = I('function() { this.setValue(""); }')
                        )
                      ),
                      uiOutput('email_text')
                    ),
                    dashboardBody())

server <- function(input, output) {
  output$email_text <-
    renderUI({
      # print the input email to the console to help with debugging
      message(input$email)
      if (input$email == "") {
        return(p("Please add your gmail e-mail address."))
      }

      #Update: Below checks for "gmail" - I would something to search list and return.
      if (!input$email %in% list_of_emails) {
        return(p("Your email is not in the list of emails!"))
      }

    })
}

runApp(list(ui = ui, server = server))


text:
Q: 10 divs in a row 10% each This seems so simple. I'm trying to get 10 divs inside a parent div all 10% wide. The parent div is 960px and centered on the page with margin:0 auto and had a red background. It does not matter if I make the with of .tenPercent 10% or 96px. The result is the same, only 9 fit and the 10th wraps. There looks to be a left margin (or padding maybe) on them but what would cause this?

1

2

3

4

5

6

7

8

9

10

A: You have 2 problems in your CSS:

*

*The space between the divs is because the inline-blocks are separated by a white space. You can remove the space with font-size: 0;.

*The 2nd problem is the width of the elements, which is effected by
the border. box-sizing: border-box; will fix that.

.container {
  width: 960px;
  background-color: Red;
  margin: 0 auto;
  font-size: 0; /** this removes the space between the divs **/
}
.tenPercent {
  box-sizing: border-box; /** this adds the borders into the width **/
  color: Black;
  display: inline-block;
  border: 1px solid black;
  width: 10%;
  font-size: 14px;
}

1

2

3

4

5

6

7

8

9

10

A: You should use float: left instead of display: inline-block.
In addition, the border is excluded in the width calculation, so actually your elements are 10% + 2 pixels (1px on the left and 1px on the right). You should add a box-sizing property:
.tenPercent {
    color: #000;
    float: left;
    border: 1px solid black;
    width: 10%;

    -webkit-box-sizing: border-box;
       -moz-box-sizing: border-box;
            box-sizing: border-box;
}

Since you're now using float for the child elements, you'll also need to add a clearfix to the container. It's probably best to add a class to the container (something semantic like container), and then use the following CSS:
.container {
    width: 960px;
    background: red;
    margin: 0 auto;
}
    .container:after {
        display: table;
        content: '';
        clear: both;
    }

jsFiddle Demo

A: You have other options than float and display:inline-block;
flexbox can do that very easily...no clearfixing, no whitespace...simple.
Support: IE10+ per CanIUse.com

* {
  box-sizing: border-box;
  margin: 0;
}
.parent {
  background-color: plum;
  text-align: center;
  margin: 0 auto;
  display: flex;
}
.tenPercent {
  flex: 0 0 10%;
  /* restricted to 10% width */
  border: 1px solid grey;
}

1

2

3

4

5

6

7

8

9

10

A: Your css for should look like this:
.tenPercent {
    color:Black;
    float:left;
    box-sizing: border-box;
    display:inline-block;
    border:1px solid black;
    width:10%;
}

Notice the additions of float: left and box-sizing. float: left will get rid of the spacing, while box-sizing: border-box; will take care of the pixels added from the borders.
Here's a fiddle to play with: http://jsfiddle.net/0ztoe6tk/

A: Add the float:left; to the .tenPercent class.
It's from display: inline-block. If you float your columns to the left they will work as expected.
When you use display: inline-block spaces/returns etc between the elements that have inline-block applied to them will be taken into account and rendered. You can think of it as adding a single space between each inline-block element.
This is the main downside of using display: inline-block over floats in my humble opinion.

A: It is because display:inline-block takes into account white-space in the html. If you remove the white-space between the div's it works as expected. from here

*,
*:before,
*:after {
  box-sizing: inherit;
}
html {
  box-sizing: border-box;
}
html,
body {
  height: 100%;
  width: 100%;
  padding: 0;
  margin: 0;
}

.Row {
}
.Row__item {
  color: #000;
  display: inline-block;
  border: 1px solid black;
  width: 10%;
  margin: 0;
}

1

2

3

4

5

6

7

8

9

10


text:
Q: Pygame mask collisions not detected I know there are several questions about collisions but I can't understand how to do it, the mask of the two objects are created correctly (if I show the two rects, they are in the right place) I think I'm having troubles with the offset, I know that in the offset we have to put the distance between the top left corners of the images ex:
offset = (character_x - collisionrect_x), (charcater_y - collisionrect_y)

and I did it but:

*

*I can't get how the offset works, I searched online but I didn't
find anything clear 2

*even if I put the right values, I always
return no collisions.

Here is the function to detect collisions (simplified):
#inizialize collisions with room
collisionsroom1 = pygame.transform.scale(originalcollisionsroom1, (ROOTwidth/2.3, ROOTheight))

def collision_room1():
    #room 1 collision
    collisionsroom1_mask = pygame.mask.from_surface(collisionsroom1)

    #character hitbox
    characterhitbox_width = characterhitbox.get_width()
    characterhitbox_height = characterhitbox.get_height()
    characterhitbox_mask = pygame.mask.from_surface(characterhitbox)

    offset = ((playermovement.playertopx + sprite_width/2 - characterhitbox_width/2.2) - (ROOTwidth/2 - room1_width/2), (playermovement.playertopy + sprite_height/2 - characterhitbox_height/2.2))

    collision = characterhitbox_mask.overlap(collisionsroom1_mask, offset)

the values in the offset are correct, if I blit the two collisions in that position they are correct, I did (character_x - collisionrect_x), (charcater_y - collisionrect_y)
I return collision only if I go in the top - left, I don't know that to do


text:
Q: CD- and USB-less install of Linux Mint 14...from Haiku and/or BeOS I have a system that boots BeOS and Haiku nightly, and has a spare partition which I used to have PC-BSD booting on.  (I use Haiku's BootManager on .../master/raw.)  I want to try Linux Mint 14, but I don't have a spare USB stick and my drive only burns CDs and the Mint download was 800-900MB.
While the BSD partition was still marked as FreeBSD-type, I had used this (in Haiku) to copy the iso overtop of it:
dd if=/boot/home/Desktop/linuxmint-14-xfce-dvd-32bit.iso of=/dev/disk/ata/0/master/3 bs=1M oflag=direct

When I try to boot to it, the first thing it says is something about a missing or corrupt isolinux.bin, even though under Haiku I can mount the new partition and see that file just fine.  (It says it once and then looks like it tries to network boot--I'm not sure if that's Mint's bootloader trying that or my BIOS.)
I then tried using BeOS' DriveSetup to reinitialize the partition to FAT32 and copy over it again with the above dd command in Haiku (I would have used dd in BeOS but it didn't support oflag.)  Exact same result.
How can I get this working from just this system, without a USB stick nor burning anything?


text:
Q: How to check to see if a string has three words in row? I am a beginner programer and I am working on a programming problem. My program is supposed to split a string into the separate words/numbers and then check to see if there are three words in a row within the string. Some of the inputs are yielding a False return when it should return true.
def words(words):
    count = 0
    for phrase in words.split():
        if phrase.isalpha():
            count +=1
        else:
            count = 0
    while (count <3):
        return False
    return True

words("Hello World hello")#True
words("He is 123 man")#False
words("1 2 3 4")#False
words("bla bla bla bla")#True
words("Hi") #False
words("one two 3 four five six 7 eight 9 ten eleven 12") #True

A: Need to check the count within the iteration, otherwise you're only checking if the LAST 3 phrases are words.
def words(words):
    count = 0
    for phrase in words.split():
        if phrase.isalpha():
            count +=1
            if count == 3:
                return True
        else:
            count = 0
    return False

A: Instead of checking after the for loop completes, you should return in the middle of the for loop as soon as count reaches 3, otherwise it could get reset to 0 after a 3-count has already been found.
def words(words):
    count = 0
    for phrase in words.split():
        if phrase.isalpha():
            count +=1
        else:
            count = 0
        if count == 3:
            return True
    return False

A: if i understand your problem correctly, you wanna get True for last input "one two 3 four five six 7 eight 9 ten eleven 12" because there is four five six in a row.
the problem in your code is because it will continue the for loop until end of words. For input above, count end up as 0 because the words endswith 12.
code below will return True whenever it hit 3 words in a row. Otherwise, continue the for loop.
def words(words):
    count = 0
    for phrase in words.split():
        if phrase.isalpha():
            count +=1
        else:
            count = 0
        if count >= 3:
            return True
    return False


text:
Q: Multiple directives asking for template I know this might be a common problem but i havent been able to find a viable solution to the issue.
Say i have the following directive:
    angular.module('Api').directive('contentSpinner', function (responseInterceptor,$timeout) {
    return {
        restrict: 'AE',
        templateUrl: 'js/helpers/Api/directives/content-spinner/content-spinner.html',
        scope: {
            boundRoute: '@',
            timeout: '=',
            timeoutms: '@'
        },
        link: function (scope, element, attr) {
            scope.shouldSpin = true;
            if (scope.boundRoute) {
                responseInterceptor.subScribeToRoute(scope.boundRoute, function () {
                    //Route has been completed and the spinner is ready to stop!
                    scope.shouldSpin = false;
                })
            }
            if (scope.timeout) {
                $timeout(function () {
                    scope.shouldSpin = false;
                }, scope.timeoutms);
            }

        }
    }
});

Please do note the AE restriction.
Then i have another directive:
    angular.module('LBTable').directive('lbTable', ['$state', 'alertService', 'usSpinnerService', function ($state, alertService,usSpinnerService) {
    return {
        restrict: 'E',
        roles: 'all',
        templateUrl: 'js/helpers/LBTable/directives/lb-table/lb-table.html',
        scope: {
            tableData: '=',
            tableFields: '=',
            actionElement: '=',
            search: '=',
            tableDataFilter: '='
        },
        link: function (scope, element, attrs) {

        }
    }
}]);

As you can see both directives has a template.
Now on all of my <lb-table> elements i wish to add the attribute content-spinner (my other directive) so that it prepends the template of contentSpinner.
However this poses the following error:
 Error: [$compile:multidir] Multiple directives [contentSpinner (module: Api), lbTable] asking for template on: <lb-table

Which is theory makes sence it doesnt know which template to use.
However is there a way to come around this without wrapping one directive around the other like:
<content-spinner><lb-table></lb-table></content-spinner>


text:
Q: PHP Keeping a PDO ATTR_PERSISTENT connection alive I am running an endless PHP Script with PDO Persistent Connection like this:
$conn=new PDO(
  'mysql:host=127.0.0.1','user','pass', array(PDO::ATTR_PERSISTENT => true)
);

The mySQL wait_timeout variable is set to 28800 and I left the script on idle for 12 hours for test purposes; and the connection is dropped automatically so I presume the PDO::ATTR_PERSISTENT attribute is superseded by the system variable wait_timeout.
So I was wondering whether theres a setting or another PHP method to keep the connection breathing as long as the PHP script is running and whether or not that would be a good practice.
My plan B would be executing a resource-less mySQL query every 60 minutes to reset the clock.
OS: 4GB RAM VPS Debian 64 Bit SSD

A: I would suggest you another way to handle such situations. Whenever you need to run a query in your long-lasting script ensure that there is a connnection. Otherwise reconnect.
    try {
        echo "Testing connection...\n";
        $old_errlevel = error_reporting(0);
        self::$pdo->query("SELECT 1");
    } catch (PDOException $e) {
        echo "Connection failed, reinitializing...\n";
        self::init();
    }

You can find the full class example here.
I also suggest you to explicitly close the connection in your script when you know you will not use it for a long period.


text:
Q: is it better to use intent to add xml layouts than using addview()? Im new to android development and I am using addView() and removeViewAt() for switching between my xml layouts.
I saw my friend using Intents to do this and saw that each of his xml layout has its own activity class that calls setContentView() to display the views.
So I am wondering of which method would be better to use?

A: If I understand correctly, you are using a single activity, and dynamically changing the layout displayed via java code. your friend, uses multiple activities and "jumps" from one to another using Intents.
I think using intents to change activities is the most correct way to do so. If you are using plain activities (I mean, you don't use fragments), you might want to create different activities for each screen of your app.
If you plan to use fragments, the normal procedure is to create an activity that contains the fragments, and dynamically change the fragments.
I'm not sure if there are any security or performance implications in doing it the way you do, but the "official" way, the one you see in every book and tutorial, is the one with different activities and intents.
Hope it helps

A: In Android you usually seperate your application to activities. Each activity does something.
For example in the gmail application the (usually) first activity shows you the incoming emails. From the navigation drawer (The menu in the left) you can jump to other activities. If you press on the "New Mail" button in the action bar it opens a new activity to write an email.
This is how android applications should work. Each activity does something and has its own life. When you press on the back button you go back to the previous activity if nothing else was specified.
When android is out of resources he is killing the active activities, while saving their state. That means that he takes them off the memory but saves their state so it can start them again later. It has a list of the most not used activities and kills them first. When the user navigates back to that activity, android uses the existing instance and if it was killed he makes a new one using the saved state.
Another reason to use activities is that they can be called when certain events occur. Your main activity is probably started by an intent with an action MAIN. You can see it in the android manifest file. There are other actions like SEND. When another app wants to share data with other apps (For example if the user presses on the share button) it sends an intent with the SEND action and the user can choose from all the activities that deal with that action (you can add it to the android manifest).
There is a lot of information about activities in android developers. here's the link: http://developer.android.com/guide/components/activities.html

A: You are just removing all the views and placing new views in the same Activity(Activity in simple word is single screen in which user interacts). But this is the wrong way of doing.
(Because you can not take use of Activity life cycles).
The same thing you can do by creating activities for all screen (For switching between the activities we use Intent). Every Activity has its own life cycle. so you can achieve lot of things.
Since You are in android so I will suggest you to go through these Links -
Activity
Starting Another Activity


text:
Q: why doesn't this work on python 3.2.3
Possible Duplicate:
Python 3.2.3 programming…Almost had it working

x = float(input("What is/was the cost of the meal?"))
y = float(input("What is/was the sales tax?"))
z = float(input("What percentage tip would you like to leave?"))

print ("Original Food Charge: ${}"
.format(x)))
print ("Sales Tax: ${}"
.format((y/100)*x)))
print ("Tip: ${}"
.format(x*(z/100)))
print ("Total Charge For Food: ${}"
.format(x+((y/100)*x)+((z/100)*x)))

output error:
line 10, in
Syntax Error: .format(x))):line 1015
Someone report that this worked in their earlier version of python (v2.6 I think). I'm using the later 3.2.3 and racking my darn brain as to why this is not working to this version. It makes sense to me someone please ENLIGHTEN me.

A: You missed an end bracket after the third print: .format(x*(z/100)))
Here is what appears to be a working version after I fixed the brackets:
x = float(input("What is/was the cost of the meal?"))
y = float(input("What is/was the sales tax?"))
z = float(input("What percentage tip would you like to leave?"))

print("Original Food Charge: ${}".format(x))
print("Sales Tax: ${}".format((y/100)*x))
print("Tip: ${}".format(x*(z/100)))
print("Total Charge For Food: ${}".format(x+((y/100)*x)+((z/100)*x)))

Also there is no need for newlines if the line width is less than 79.

A: You're missing a close paren on the preceding line:
.format(x*(z/100))

A: There is a parentheses missing after .format(x*(z/100)) that belongs to the preceding print.
It should be:
print ("Tip: ${}".format(x*(z/100)))

UPDATE: Not sure if you got it working or not yet, here is the complete code after fixing your unbalanced parentheses...
x = float(input("What is/was the cost of the meal?"))
y = float(input("What is/was the sales tax?"))
z = float(input("What percentage tip would you like to leave?"))

print ("Original Food Charge: ${}"
.format(x))
print ("Sales Tax: ${}"
.format((y/100)*x))
print ("Tip: ${}"
.format(x*(z/100)))
print ("Total Charge For Food: ${}"
.format(x+((y/100)*x)+((z/100)*x)))


text:
Q: I can't Get my hyperlinkListener to give the URL; It's NULL value I have a Java Swing application that I'm building.
In it I have created a JTextPane (displayPane) that I've set to take in text in HTML Format.
I wanted the HTML to be a bit dynamic whereby a user can click on one of the embedded images and have an event fire (in this case view the image full-screen).
So I built the HTML and set the Text of the pane and it works fine.
Then I added a HyperlinkListener to the pane to listen to the desired event.
The HyperlinkEvent has a .getURL() that keeps returning NULL even though the image appears in the JTextPane.
I really want the getURL() to actually work so that I can throw that to a "popWindow" That I've created (just makes a large dialog that shows an image - but I need to get that image from the HyperlinkEvent)
Thanks in advance for any help.
Java CODE:

private static void ShowAirportInfo(Airport airport) throws IOException {
        HTMLEditorKit htmlKit = new HTMLEditorKit();
        displayPane.setEditorKit(htmlKit);
        displayPane.setEditable(false);
        displayPane.setText(buildHTMLAirportInfo(airport).toString());
        displayPane.setCaretPosition(0); //makes the pane go back to the top of the page after rendering the HTML.

        displayPane.addHyperlinkListener(new HyperlinkListener() {

        @Override
        public void hyperlinkUpdate(HyperlinkEvent he) {
          EventType eType= he.getEventType();
          URL url = he.getURL();

            if(eType.equals(EventType.ACTIVATED)){
                try {
                        popWindow.setImage(url.getPath());
                    } catch (IOException ex) {
                        Logger.getLogger(Phaero.class.getName()).log(Level.SEVERE, null, ex);
                    }
                popWindow.displayPane();
            }
        }
    });
}

HTML that is put into the JTextPane:

General Info

ICAO:</>VHHH</>

Name:</>Hong Kong Intl</>

Location:</> HK</>

Elevation:</>29</>

Longest Runway:</>12469</>
Lat:</>22.30891944</>

Lon:</>113.91460278</>

AQP Status

Mountainous terrain.

Airport Comms

TWR - 118.4,118.2,118.7,null,null

DEP - 123.8,124.05,null,null,null

CLD - 129.9,124.65,null,null,null

ATIS - 128.2,127.05,null,null,null

APP - 119.1,119.35,null,null,null

AFIS - 122.4,121,null,null,null

GND - 122.55,121.6,null,null,null

CAC - 120.6,null,null,null,null

RDR - 133.7,null,null,null,null

Runways

Runway 07R/25L

Dimensions: 12466 x 197

Surface: PERMANENT

Runway Condition: GOOD.

LCN: 87

Max demstrated Wingspan: null

Runway: 07R	Runway: 25L

Heading: null	Heading: null

Slope: 0	Slope: 0

Latitude: 22.296202019999999	Latitude: 22.30743056

Longitude: null	Longitude: null

A - ALSF-2

VASI Type: null

Runway 07L/25R

Dimensions: 12469 x 197

Surface: PERMANENT

Runway Condition: GOOD.

LCN: 87

Max demstrated Wingspan: null

Runway: 07L	Runway: 25R

Heading: null	Heading: null

Slope: 0	Slope: 0

Latitude: 22.31040556	Latitude: 22.32163611

Longitude: null	Longitude: null

A - ALSF-2

VASI Type: null

Remarks

Bird haz.

Rwy 07R/25L clsd Mon, Wed, Thu fr 1730-2359Z. Rwy 07L/25R clsd Tue, Fri, Sat, Sun fr 1730-2359Z.

All rwy are grooved. Ctc Apron Ctl (121.755) for Gnd Emerg.

IFR TAKE-OFF MINIMUMS AND DEPARTURE PROCEDURES:  Diverse departure not authorized.

All oil grades avbl.

A1 (Chevron USA C852-25113-380) SP0600-09-D.

A: Ok, I feel dumb ...
I just read the documentation better....
and noticed this:
getDescription
public String getDescription()
Get the description of the link as a string. This may be useful if a URL can't be formed from the description, in which case the associated URL would be null.

REF::
http://docs.oracle.com/javase/1.4.2/docs/api/javax/swing/event/HyperlinkEvent.html#HyperlinkEvent%28java.lang.Object,%20javax.swing.event.HyperlinkEvent.EventType,%20java.net.URL,%20java.lang.String%29
So instead of getting the URL, I can get the description... like so:
he.getDescription();


text:
Q: How to use Latex to create 3 sets of equations with brackets Could anyone can help me how to type the following equations in latex?

Thank you very much

A:
\documentclass{article}

\usepackage{amsmath,bm,eqparbox}
\newcommand{\tsum}{\textstyle\sum}

\begin{document}

\begin{subequations}
\begin{align}
  \left\{
    \begin{aligned}
      \epsilon\, \dot{z}^i  &= \eqmakebox[RHS][l]{$-(z^i + u^i) - \sum_{i = j}^N \bm{L}_{ij} (z^j + \nu^j)$,} \\
      \eqmakebox[LHS][r]{$\epsilon\, \dot{\nu}^i$} &= \tsum_{j = 1}^N \bm{L}_{ji} z^j,
    \end{aligned}
  \right.\kern-\nulldelimiterspace \\
  \left\{
    \begin{aligned}
      \epsilon\, \dot{y}^i  &= \eqmakebox[RHS][l]{$-(y^i + \dot{u}^i) - \sum_{i = j}^N \bm{L}_{ij} (y^j + \mu^j)$,} \\
      \eqmakebox[LHS][r]{$\epsilon\, \dot{\mu}^i$} &= \tsum_{j = 1}^N \bm{L}_{ji} y^j,
    \end{aligned}
  \right.\kern-\nulldelimiterspace \\
  \eqmakebox[LHS][r]{$\dot{x}^i$} = \eqmakebox[RHS][l]{$-\beta^i x^i - \beta^i z^i - y^i$.}
\end{align}
\end{subequations}

\end{document}

eqparbox ensures that we can place content in boxes that will be the same width. This helps with alignment across the structures (aligned) within align. Minor removal of \kerning as a result of a blank \right. delimiter aligns the equations as needed.
One could also have used a cases environment to achieve the braces sub-equations.


text:
Q: Safari URL encoding behaves strange I have an Elixir/Phoenix crud app that serves some static files.
The file names are likely to contain (german) umlauts and I want to preserve them.
First I just responded with the file to the :show route of the upload but this had the unwanted effect that the filename at the downloading client would be the uploads id (e.g. 1 or 123).
To change that I switched to serving the files via a static plug. That worked well on Chrome and Firefox but today I noticed that it doesn't on Safari. On Safari I just get Page not found.
For me it seems like Safari doesn't encode the umlauts. Is this a bug in Safari? How do I work around that?
Here is a link to a page of the app that contains such a link: https://sozialoekonomie.klausurenarchiv.de/courses/21/instructors/25/uploads
On Safari the link of the file is: https://sozialoekonomie.klausurenarchiv.de/data/Makroökonomie/Pfannkuche/1474905178102463842/Makroökonomie%20Pfannekuche%20SoSe%2015%20mit%20Lösung%201,3.pdf
While on Chrome/Firefox the file uri is:
https://sozialoekonomie.klausurenarchiv.de/data/Makro%C3%B6konomie/Pfannkuche/1474905178102463842/Makroo%CC%88konomie%20Pfannekuche%20SoSe%2015%20mit%20Lo%CC%88sung%201,3.pdf


text:
Q: SQL Server Cross Domain Transcational Replication Has anyone got any documentation for doing/implementing Cross Domain SQL Server 2012/2008R2/2008 transactional replication document or steps (with screenshot or without screenshot)?

A: Replication across non-trusted domains or workgroups can be done using Push Subscriptions in conjunction with SQL Authentication for the replication agent process accounts. Alternatively, you can also use Windows Authentication by configuring pass-through authentication.
To use pass-through authentication, create a local Windows account on both the Publisher and Subscriber that has the same username and password. Use this account for the replication agent process account and have the connections to the publisher, distributor, and/or subscriber impersonate this account. Ensure the account has the permissions required in Replication Agent Security Model.
This approach is covered in the section Use Windows Authentication to Set Up Replication Between Two Computers Running SQL Server in Non-Trusted Domains in HOW TO: Replicate Between Computers Running SQL Server in Non-Trusted Domains or Across the Internet.
If you have anymore questions, please let me know.  I hope this helps.


text:
Q: Not able to set Firebase Image Uri in Image View I am trying to set Image from FIrebase to Imageview using Glide but it is showing Error
Task<Uri> riversRef = storageReference.child(user.getUid() + "/profile.jpg").getDownloadUrl()
                    .addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri uri) {
                            if (uri == null) {
                                Toast.makeText(getApplicationContext(), "URI IS NULL", Toast.LENGTH_LONG).show();
                            }
                            Glide.with(getContext()).load(uri).centerCrop().into(imageView);
                        }
                    });

And the error is:

Process: com.root.firebase, PID: 3875
                                                                   java.lang.NullPointerException: Attempt to invoke virtual method
  'boolean android.app.Activity.isDestroyed()' on a null object
  reference
                                                                       at
  com.bumptech.glide.manager.RequestManagerRetriever.assertNotDestroyed(RequestManagerRetriever.java:133)
                                                                       at
  com.bumptech.glide.manager.RequestManagerRetriever.get(RequestManagerRetriever.java:125)
                                                                       at com.bumptech.glide.Glide.with(Glide.java:641)
                                                                       at
  com.root.firebase.UploadActivity$2.onSuccess(UploadActivity.java:72)
                                                                       at
  com.root.firebase.UploadActivity$2.onSuccess(UploadActivity.java:65)
                                                                       at com.google.android.gms.tasks.zzj.run(Unknown Source)
                                                                       at android.os.Handler.handleCallback(Handler.java:751)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                       at android.os.Looper.loop(Looper.java:154)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

A: Task<Uri> riversRef = storageReference.child(user.getUid() + "/profile.jpg").getDownloadUrl()
                .addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        Toast.makeText(getApplicationContext(), "GET IMAGE SUCCESSFUL", Toast.LENGTH_LONG).show();
                        if (uri == null) {
                            Toast.makeText(getApplicationContext(), "URI IS NULL", Toast.LENGTH_LONG).show();
                        }
               else{         Glide.with(getContext()).load(uri).centerCrop().into(imageView);}
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        Toast.makeText(getApplicationContext(), "GET IMAGE FAILED", Toast.LENGTH_LONG).show();
                        // Handle any errors
                    }
                });


text:
Q: How can I force outlook to interpret and display an html file correctly From linux, I send this file to an outlook account...

HELLO

It appears just as you see, plain text.
How can I get this to display on Outlook as it appears when I run it through firefox on liunux ?
In linux, I sent it as plain test using a system call in a perl script....
mail -s 'the title' 'recipient' < the_file.html.

'which mail' eventually ends up being mailx
The thinking is that outlook would recognize the "html" (between the < and > which won't display here) as line 1 and do the right thing.

A: You need to set the correct ContentType in the header.
e.g.:
 Content-Type: text/html; charset=UTF-8
Here is an old example in Perl that might help you:
How can I send an HTML email with Perl?

A: As it turns out, we also had "mutt" installed and I was able to use that.
E.g.
my $cmd = "mutt -e 'set content_type=text/html' -s '${title}' '${to_list}' < ${email_file}"
my $stat = system($cmd);


text:
Q: How to filter column with values without NULL or blanks using python I am looking to filter out the rows with values only, I have tried using several methods but it doesn't works. Processing the values further i need to have the dataframe without values without having any Null or blank rows.
Input Data:
Col 1
U_a65839_Jan87Apr88
U_b98652_Feb88Apr88
NaN
Q_d15634_Apr90Apr91
S_e15336_may91Apr93
NaN

Expected Output:
Input Data:
Col 1
U_a65839_Jan87Apr88
U_b98652_Feb88Apr88
Q_d15634_Apr90Apr91
S_e15336_may91Apr93

Code i have been using :
df['Col 1'] = df[~df['Col 1'].isnull()]

ValueError: Wrong number of items passed 60, placement implies 1


text:
Q: Deploy war file fails I am working on a system with two servers. When updating a site i deploy a war file to each server. It worked on one but on the other when i go through the process the war file creates the ROOT folder but its owner and group is root whereas on the other server owner was tomcat.
I changed ownership and group back but when i go to load the site it doesnt load. Looked through the ROOT folder and noticed the WEB-INF/public folder which contains the site content wasnt created. Does anyone have any idea why this would be the case.

A: Check the user in which tomcat is started and who owns the process on each server.


text:
Q: Setting up and saving connection profile in SQL Workbench/j from command line/batch Using the guide https://www.sql-workbench.eu/manual/commandline.html#commandline-connect-noprofile
 to set up as profile and save the profile for future use.
 This is possible manually via "7.2. Managing profile groups"
https://www.sql-workbench.eu/manual/profiles.html#profile-workbench-settings
Is it possible to save a profile via the command line?
SQLWorkbench64.exe -username=user -password=pass -url=jdbc.. -driver=Redshift driverJar=filepath

A: There is no direct support for this.
But you can use the WbStoreProfile command to store the currently active connection as a profile.
You can do this through the -command parameter.
SQLWorkbench64.exe  -command="WbStoreProfile -name=test" -username=user -password=pass -url=jdbc.. -driver=Redshift driverJar=filepath

That will connect to the database, then run the WbStoreProfile command and exit again.
The profile will be saved under the name "test" in wb-profiles.properties.
But it's probably easier to edit wb-profiles.properties manually.


text:
Q: Compile C app with Visual Studio 2012 I plan to write application in C using Microsoft Visual Studio 2012.
The problem is that I can't find a way to compile it right in the editor. I found this solution http://msdn.microsoft.com/en-us/library/bb384838.aspx but I dont like it.
Can you recommend me a way to compile C program right in the Visual Studio 2012?

A: It is a little bit tricky to compile plain C90 and C++x0 (only partially supported) projects in VS2010 (and probably Visual Studio 11, I haven't tried native development in it yet).
What you have to do is to create a new C++ project without precompiled header -- this is the primary requirement if you want to compile a platform-independent code (library, console application).
There are several ways to do it. One way is to create a normal Win32 C++ console application, in the opened wizard you should go to the second page (by clicking "Next") and then uncheck the option "Include precompiled header". Then you can compile C++ (and C) projects directly in VS.

A: Also check "properties -> c/c++ -> advanced -> Compile as" make sure it says "c code"
or on the command line use /TC

A: Create an empty C++ project in Visual Studio (File -> New Project -> Visual C++ -> Empty Project), then add a source file with a .c extension to it (right click the project, select Add -> New Item -> C++ File (.cpp), and change the name of the file).
When you build, the compiler will compile it as C code (note that Visual C++ supports only C90, not C99, so newer C language features are not usable).

A:
By default, the Visual C++ compiler treats all files that end in .c as C source code, and all files that end in .cpp as C++ source code. To force the compiler to treat all files as C regardless of file name extension, use the /Tc compiler option.

Source: MSDN Visual Studio 2013, http://msdn.microsoft.com/en-us/library/bb384838.aspx walkthrough
Go to Menu command to open "Project -> Properties" dialogue. Then in "Configuration Properties" select "C/C++ -> Advanced" pane. Change "Compile As" drop-down box from "Default" to "Compile as C Code (/TC). Click on "Apply" button and then "OK" to close the dialogue.

A: select new project,win 32console application ,uncheck precompiled header,select empty project.. Then add a new item,select..cpp file then rename the file with .c.extension and you're done to compile c codes..

A: It's also same for newer VS versions, what you have to do is as mentioned by @Alexander Galkin,

*

*Right Click to Project Properties

*C/C++

*Advanced

*Set "Compile As" to "Compile as C Code(/TC)"

To demonstrate it visually, check the screen-shot below;
Steps


text:
Q: Serving different Container Registry images for dev, test, prod within one GAE project I deploy my Docker image to default GAE by gcloud app deploy --image-url=us.gcr.io
I have successfully mapped my custom domain to this application with custom runtime and flex env.
My dispatch.yaml sends requests to its sub-domain:
dispatch:
  - url: "dev.domain.com/*"
    service: default

Now I want to use different images from Container Registry for test.domain.com and domain.com
While having all these images sharing same Cloud Storage and Firebase credentials.
Being new to GCP I wanted to learn any simple approach to organize such basic structure without going into services and versions (just by assigning proper images to serve relevant domains).
Is it even possible to do within one GAE project or I should create separate projects for it?

A: Mapping custom domains can only be done at the service level, so if you don't want to go into services separate projects is your only choice.
Actually using separate projects instead of services (or service versions) for implementing different environments has some advantages, I'd choose separate projects, too. See Advantages of implementing CI/CD environments at GAE project/app level vs service/module level?
I'm not sure if sharing the storage and credentials between production and other environments is a good idea (what if something goes wrong?). I'd keep them separate, too (maybe with some jobs to populate non-production projects with production data, if you need to). But if you do want to share them across projects you'll probably need to make some extra steps.


text:
Q: 403 rate limit after only 1 insert per second My app is occasionally (once per day) running a bulk insert of around 1,000 files. After a handful of inserts I start getting 403 rate limit responses. Since my app does the inserts sequentially, my attempted insert rate is never higher than 1 per second.
I've checked that I have billing enabled and that my quota limits are 100+ per second, so I don't understand why I'm getting throttled so aggressively. The consequence is that the insert is taking over an hour which isn't a great advert for Drive :-(

A: Seems the answer is that Drive will allow up to 30 or so inserts before rejecting with 403 errors. The precise figure, and the rate at which the rate limit is de-restricted are not made public. See also 403 rate limit on insert sometimes succeeds

A: You need to implement exponential backoff as Google describes in their documentation.

A: You can change the rate in the api console. Set it to a larger value like 10000/sec.


text:
Q: Is a perfect game of Set always possible? For anyone not familiar with the game of Set, I'll refer you to the description on this question.
My question is this: The game ends when there are no more cards remaining in the deck and there are no sets visible on the table.  I will define a "Perfect Game" as one in which there are no cards at all on the table at the end, i.e. all 81 cards have been removed as part of a set.  Can any ordering of cards result in a Perfect Game?
Now, in practice, this is a fairly rare occurrence.  Games typically end with 6, 9, or 12 cards remaining.  They can even end with as many as 15 (this seems to be even less common than a 0-card ending, but I have seen it happen).  18+ I believe to be impossible.  I think that 16 is the maximum number of cards that can be showing without making a set, and there must always be a multiple of 3, so that rules out anything > 15. (Edit: Apparently up to 18 is possible.)  A 3-card ending is also impossible, per the question I linked above.  (The last 3 must form a set, so this would result in a Perfect Game.)
Now, in a normal game, there are often times where more than one set is visible, and which one you pick can affect the outcome of the game at the end, and you have no way of knowing what those outcomes would be.  But let's say that we are given full knowledge ahead of time about the exact order of cards in the deck.  Let's say we also have the ability to perfectly predict the outcomes of each choice, or alternatively to "hit Undo" and backtrack all the way to the beginning as often as needed.  Could we with this knowledge ensure that any ordering of cards can result in a Perfect Game?
I suspect that this would be easier to disprove than to prove - Simply find a contrived deck ordering which at no time gives you multiple choices of visible sets or which we can trace the game through to all possible endings if there are choices, and prove that they all must leave some cards on the table.  Proving that any deck order can end perfectly would be quite the challenge...
Edit: I just noticed this question, but it is not a duplicate since it does not consider the possibility of knowing the order of cards ahead of time.


text:
Q: Sort array without redrawing content I'm trying to sort users by online property:
var userViewModel = function(data){
    var self = this;
    self.name = ko.observable(data.name);
    self.online = ko.observable(data.online);
};

var mainViewModel = function(data){
    var self = this;
    self.users = ko.observableArray(data.users.map(function(user){
        var model = new userViewModel(user);
        model.online.subscribe(function(){
            self.users.sort(function (a, b) { return b.online() - a.online(); });
        });
        return model;
    }));

    self.users.subscribe(function(){
        console.log('users have changed');
    });
};

HTML:

    Online:

Everything is working fine, but when changing online property, users are sorted and "users have changed" is logged. I understand it happens because I'm changing original array. What I want is - not to change original array, just display it sorted (like angular does it)

A: Just create a new computed that populates a sorted list of user.
var mainViewModel = function(data){
    var self = this;
    self.users = ko.observableArray(data.users.map(function(user){
        var model = new userViewModel(user);
        return model;
    }));
    self.sortedUsers = ko.computed(function(){
        var users = self.users();
        users.sort(function (a, b) { return b.online() - a.online(); });
        return users;
    });
};

I hope it helps.


text: Q: VS theme question - white text over white background for input fields I've been using Visual Studio's "Dark with Light Editor" theme forever and have never been able to figure out how to fix the white text over white input field bug. In the screenshot below, there's actually search text the first field. Can anyone shed some light on which property in Environment > Fonts and Colors changes this?  Many thanks in advance!


text:
Q: DBMS_AQADM.PURGE_QUEUE_TABLE with the error ORA-01001: invalid cursor and ORA-06512: at "SYS.DBMS_AQ_INV" While attempting to manually execute the command below with user APPS (owner of WF_BPEL_QTAB queue) the error informed is occurring.
We did all the necessary research and the queue has no indexes (as some solutions suggest).
Command:
declare
  l_purge_options dbms_aqadm.aq$_purge_options_t;
begin
l_purge_options.Block := False;
DBMS_AQADM.PURGE_QUEUE_TABLE(queue_table => 'APPS.WF_BPEL_QTAB'
                            ,purge_condition => 'ENQ_TIME < trunc(sysdate) - 3
                            ,purge_options => l_purge_options);
end;

Error:
ORA-00604: error occurred at recursive SQL level 1
ORA-01001: invalid cursor
ORA-06512: at "SYS.DBMS_AQ_INV", line 208
ORA-00918: column ambiguously defined
ORA-06512: at "SYS.DBMS_AQADM", line 1668
ORA-06512: at line 5

A: When using criteria from the queue table, you need to use the alias 'qtview'.  Hence
declare
  l_purge_options dbms_aqadm.aq$_purge_options_t;
begin
  l_purge_options.Block := False;
  DBMS_AQADM.PURGE_QUEUE_TABLE(queue_table => 'APPS.WF_BPEL_QTAB'
                              ,purge_condition => 'qtview.ENQ_TIME < trunc(sysdate) - 3
                              ,purge_options => l_purge_options);
end;


text:
Q: How to remove a list that contains certain element from a list a = [['yes','no'],['riding','0']['riding',1],['yes','no'],['yes','no'],['riding',2]]

needs to remove all the list that contains riding
so it would give me
a = [['yes','no'],['yes','no'],['yes','no']]

I have a big list , and the list that contains riding are in no predictable sequence
how do i remove them ?
thanks everyone

A: Using a simple for loop:
for l in a.copy():
    if "riding" in l:
        a.remove(l)


text:
Q: Append values to array items Can anyone please provide me a more efficient way to do the following:
int[] result = { 0, 0 };
foreach(var group in operatorsGroups)
{
    int[] added = { 0, 0 };
    added = somefunction(group);
    result[0] += added[0];
    result[1] += added[1];
}
return result;

Something like the following:
int[] result = { 0, 0 };
foreach(var group in operatorsGroups)
{
    result += somefunction(group);
}
return result;

A: Reducing lines of code using LINQ:
List<int> items = activeList.Split(',').Select(n => Convert.ToInt32(n)).ToList();
int itemToAdd = ddlDisabledTypes.SelectedValue.ToInt(0);
items.Add(itemToAdd);

// If you want to see it as an actual array you can still use ToArray
int[] itemsAsArray = items.ToArray();

A: If you are performing some heavier work on each iteration then you can use multi threaded or async await concept.
    int[] result = { 0, 0 };
     Parallel.ForEach(operatorsGroups, group =>
        {
            int[] added = { 0, 0 };
            added = somefunction(group);
            result[0] += added[0];
            result[1] += added[1];
        });
   return result;


text:
Q: How can I setState of the current index of an array being used in a carousel which autoplays, to be passed into another component as a prop? I am using this npm package for a background carousel. https://github.com/u2ix/react-background-slider
It takes in an array of images from props to autoplay the slideshow in a loop.
I have another component of Cards being mapped and rendered that needs to take in the current index of the carousels images array in order to change the cards state in sequence of the images. I had this working in a previous carousel but the previous carousel had a built in function for capturing the activeIndex so it was easily passed. The goToSlide function also came with the previous carousel package, so I am trying to rewrite it to continue working with my FeatureCards Component.
class HomeLanding extends Component {
    constructor(props) {
        super(props);
        this.state = {
            images: [
                MockExtension,
                image1,
                image2,
                image3
            ],
            activeIndex: 0
        };
    }

goToSlide = i => {

}

    render() {
        return (
            <div>
                <HomeCard />
                <CardGroup className="CardWrap">
                    {
                        FeaturesInfo.map((item, index) => {
                            return <FeatureCard key={index} isActive={this.state.activeIndex === index} goToSlide={() => this.goToSlide(index)} icon={require(`../../Assets/FeaturesImages/${item.icon}`)} title={item.title} description={item.description} />
                        })
                    }
                </CardGroup>
                <BackgroundSlider
                    images={this.state.images}
                    duration={8}
                    transition={2}
                />
            </div>
        )
    }
}

A: I haven't worked with this library before but from what i understand, you could capture the index and image url from a callback function props.onChange(). I think you should capture the index and then fast forward the slide show until the index is met then slow the slide show down.
Without further code i cant help but i guess that you are trying to use a package in a way that it wasn't created for.


text:
Q: How do I use innerHTML with createTextNode? I'm trying to create a chrome extension and im doing this by parsing an RSS feed with XMLHttpRequest and then storing the tokens parsed, such as title & description, into an array.
After parsing the feed and storing the tokens into an array, I then loop through the array and display them onto the chrome extension popup using DOM. It works but the problem is that each description has HTML tags and shows up something like this:

Even in lean times, the $400 billion business of higher education is booming. Nowhere is this more true than in one of the fastest-growing — and most controversial — sectors of the industry: for-profit colleges and universities that cater to non-traditional students, often confer degrees over the Internet, and, along the way, successfully capture billions [...]
The HTML tags come from the feed and I have no problem with them all I want to do is get them to be actually interpreted as HTML rather than as text. I believe this is because im using createTextNode? I should be using innerHTML? I'm not sure how to use innerHTML in the following example?
   var descriptionNode = document.createElement("div");
   descriptionNode.setAttribute("class", "description");
   descriptionNode.appendChild(document.createTextNode(item["description"]));
   detail.appendChild(descriptionNode);

I can post more of my code up if that will help?

A: Try:
var descriptionNode = document.createElement("div");
descriptionNode.className = "description";
descriptionNode.innerHTML = item["description"];
detail.appendChild(descriptionNode);

createTextNode creates a text node, the string passed to it is treated as plain text and assigned to the node's data property. The string assigned to the innerHTML property is treated as markup and is parsed by the browser's HTML parser (or XML parser in very recent browsers in the case of an XML document) and turned into DOM elements.


text:
Q: ng-options filter based on selected value I've to write a directive to edit labels for an app.
Each culture (eg: en-US) can have maximum 4 labels per property which are contained into a table :
 $scope.suffixes = ["DisplayName", "Description", "Hint", "Help"];

 <div class="clear" ng-repeat="label in labelModel | filter:cultureFilter">
      <select ng-options="suffix as suffix for suffix in suffixes | filter:suffixFilter(suffix, label.suffix)" ng-model="label.suffix" />

 </div>

and here are my controller functions :
    $scope.cultureFilter = function (label) {
        return (label.culture == $scope.labelState.culture);
    }

    $scope.suffixFilter = function (suffix, selectedValue) {

        //arguments are now : [undefined, "DisplayName"]

        return true; // :-(
    }

So far, I've been able to filter the ng-repeat based on the culture.
But for my ng-options, I have to filter the strings that are already used. But I also have to keep the current value selected. How can I tell my filter that some value shouldn't be filtered because it's the current selected value?
edit
Now, I'm able to receive the selected value, but I can't receive my suffix anymore

A: You are almost there with using a filter function, but in your case, I think what you really need is a custom filter. They are actually trivial to write.
A filter is just a factory function registered with the .filter() helper.
You just need one that takes in the parameters you care about.
//Outer factory function
function SuffixFilter(){

  //Inner function which is our filter
  return function(items, ignoredItem){
     var filteredItems = [];

     angular.forEach(items, function(item){
        //Your filtering logic may be more complex
        // than this. It's only an example
        if(item == someCriteria || item == ignoredItem){
           filteredItems.push(item);
        }
     });

     return filteredItems;
  }
}

angular.module('myModule')
   .filter('suffixFilter', SuffixFilter);

And once you have your suffix filter registered, you can simply call it in your markup with the parameter you care about. Angular handles the rest.
<!-- Pass in the current selection to ignore -->
suffixes | suffixFilter:label.suffix

Update - Based on comment below:
The function parameter doesn't really work that way. It's expecting to evaluate to a function that can be called.
Technically you could return a function and use closures to accomplish what you want. Something like this:
<!-- In your markup -->
filter:suffixFilter(label.suffix)

//In your controller
$scope.suffixFilter = function (selectedValue) {

   //this is your actual filter here
   return function(item){

      //You have access to 'selectedValue' via
      // a closure
      return item == someCriteria || item === selectedValue;
   }
}

So again, while this is certainly possible, I think a custom filter is semantically cleaner.


text:
Q: Silverlight & events namespace SilverlightApplication1
    {
        public partial class MainPage : UserControl
        {
            public MainPage()
            {
                InitializeComponent();
            datePicker1.SelectedDateChanged -= datePicker1_SelectedDateChanged;
            datePicker1.SelectedDate = DateTime.Today;
            datePicker1.SelectedDateChanged += datePicker1_SelectedDateChanged;
        }

        private void datePicker1_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            MessageBox.Show("datePicker1_SelectedDateChanged");
        }
    }
}

Why message box appears?

A: datePicker1.SelectedDateChanged -= datePicker1_SelectedDateChanged;
//Defines  you use the RemoveHandler function. you might want to remove event handlers during the application lifetime
datePicker1.SelectedDate = DateTime.Today;
// You are Assigning to Datepicker Selected date
datePicker1.SelectedDateChanged += datePicker1_SelectedDateChanged;
// the event handlers on the relevant object are ready for user-initiated events at run time.
So The Message Box Came .
Third Line You Have Call The Eventhadler That Y it will come


text:
Q: Can't start Git in OS X El Capitan I upgrated my os x from mavericks to EL Capitan and when want to use git in android studio, i got this error:
xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun

Anyone have a solution?

A: Faced this after upgrading to El-Capitan
xcode-select --install

didn't work for me even after 'Finding Software' and Downloading. I don't have Xcode.app installed (Didn't want to install it) so i fixed it by downloading Command Line Tools from https://developer.apple.com/downloads/ (requires Apple SignIn) and installed it manually.
After installation i was able to run git commands again

A: xcode-select --install run on your terminal
it works for  me

A: See this solution:
After updating Mac OS X to 'El Capitan', my local git command was not working anymore. When using the git command, the command line returns:
xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun
The solution to fix this is to reinstall the command line developer tools using this command:
xcode-select --install


text:
Q: Spaghetti plot in R, with different measurement times I have a data matrix called scores.csv that looks something like this:
ID      score   age

1       23       12
1       50       16
2       25       13
2       67       16

I've used the following code:
scores<-read.table("scores.csv",sep=",", header=T)
interaction.plot(scores$age,scores$id, scores$score, xlab="age",ylab="score", legend=F)

This works fine if for all ID's the ages are the same so (12 & 16 for both) however once these are different I get an empty spaghetti plot.

A: Just for the fun of it, here's with ggplot2
Be sure you're using a data.frame, not a data.table
library("ggplot2")
df <- data.frame(ID=c(1,1,2,2,3,3), Score=c(23,50,25,67,22,55), Age=c(12,16,13,16,12,17))
    ggplot(df,aes(x=Age,y=Score,
             group=ID,color=factor(ID)))+
         geom_point()+geom_line()

And lattice (ekstroem deserves the credit for this one)
library(lattice); xyplot(Score ~ Age, group=ID, data=df, type="l")

2
I have used default aesthetics for this plots, you might want to customize adding other parameters.


text:
Q: QGIS 2.0 Python API: Layer vector style loaded from file, marker symbology is respected, labels are not Im loading a QgsVectorLayer and showing it on map. I load the style i prepared with desktop QGIS 2.0.1 using the layer.loadNamedStyles(path) function in the API and it seems to work, kind of, because the markers are shown on map canvas the way i specified, however the labels are not shown even though the labels styling is defined in the .qml style file (looked at it in notepad). Is there something else i need to do, to display the labels for a vector layer?
Result is the same if i save the style as .sld then load it via layer.loadSldStyle(path)
I think the issue is the rendering engine/settings used. The style files assumes 'pal' rendering in the custom properties, so it could be something with the way Pal related objects are (not) initialized for the layer
This seems to have enable the labels, but it just displays "label" for every feature:
layer.enableLabels(True)

I still think the style i prepared is being ignored for some reason. There must be a simpler/better way to do this!
If i use a qml file, generated with qgis 1.8, labels show up without me doing anything other than loading the layer. Must be 2.0.1 related.
UPDATE: I finally know what the issue is: .qml style file. Despite the fact that it was generated with qgis 2.0.1 it seems that when style file is loaded into my stand alone app, it tries to load the label styling information from the legacy part of the file, which is not filled out:
  <displayfield>name</displayfield>
  <label>0</label>
  <labelattributes>
    <label fieldname="" text="Label"/>
    <family fieldname="" name="MS Shell Dlg 2"/>
    <size fieldname="" units="pt" value="12"/>
    <bold fieldname="" on="0"/>
    <italic fieldname="" on="0"/>
    <underline fieldname="" on="0"/>
    <strikeout fieldname="" on="0"/>
    <color fieldname="" red="0" blue="0" green="0"/>
    <x fieldname=""/>
    <y fieldname=""/>
    <offset x="0" y="0" units="pt" yfieldname="" xfieldname=""/>
    <angle fieldname="" value="0" auto="0"/>
    <alignment fieldname="" value="center"/>
    <buffercolor fieldname="" red="255" blue="255" green="255"/>
    <buffersize fieldname="" units="pt" value="1"/>
    <bufferenabled fieldname="" on=""/>
    <multilineenabled fieldname="" on=""/>
    <selectedonly on=""/>
  </labelattributes>

If i changed the file by hand accordingly, the style now works. But the questions is: how do i force, or properly use custom properties where the style i saved was actually saved?

A: I had the same problem in a C++ application.
this sounds like the mapRenderer's labelingEngine of your canvas is not defined.
here is what i have done (in C++) :
#include <qgspallabeling.h>
...
QgsPalLabeling *labelingEngine = new QgsPalLabeling();
mCanvas->mapRenderer()->setLabelingEngine(labelingEngine);

I think you could do something like this in python :
from qgis.core import QgsPalLabeling
...
labelingEngine = QgsPalLabeling()
yourCanvas.mapRenderer().setLabelingEngine(labelingEngine)

with this, i have labels loaded properly using customProperties from qml.


text:
Q: How to convert multiple xls files to csv using powershell? I'm trying to convert multiple Excel files (xls) to csv using the following powershell script:
$excel = new-object -ComObject "Excel.Application"
$excel.DisplayAlerts=$True
$excel.Visible =$false
foreach ($file in get-childitem $src_dir) {
    $wb = $excel.Workbooks.Open($file.FullName)
    $wb.SaveAs($dst_dir + $file.Name + ".csv", 6)# 6 -> csv
    $wb.Close($True)
}
$excel.Quit()
[void][System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)

In principle this works e.g. I get csv files. However, for a few files (varying per run) I get an exception:
Exception calling "SaveAs" with "2" argument(s): "Microsoft Office Excel cannot access the file 'C:\Users\...\AppData\Local\Temp'. ...

Additionally, I get a message box asking if I want to save the changes to the source xls.
Once I call SaveAs, $wb references the new file. So how do I save or discard the changes to the source file? Why does this happen only for a few files? Are there any other problems with this script?
Update
I divided the input files (ca. 200) arbitrarily (i.e. don't know the size of the groups) into 10 groups and processed each group in its own run. That worked so it is somewhat inconvenient.
thanks in advance

A: Try moving the code to launch and quit excel INSIDE your loop.
Yeah, it's slower that way, but it'll encourage Excel to clean up its temp files between each operation.
It won't be as slow as you think because Windows and COM are smart enough to keep Excel mostly in memory even after you quit for a few seconds so that the next time you create an Excel object it'll happen fast, exactly for situations like this.

A: Maybe you can implement a timer to wait a while? Or you have a look inside the direcotry while you script is running and then remove the temp files after each cycle (one xls file conversion).

A: I believe you can avoid the message box asking if you want to save by using $wb.Close($False) instead of $wb.Close($True). That's what I use normally and I don't get any message boxes.

A: My updated script with timer - may not be exact answer but will help someone looking for a script:
$excel = new-object -ComObject "Excel.Application"
$excel.DisplayAlerts=$True
$excel.Visible =$false
$src_dir='D:\folderwithxlsx\'
$dst_dir='D:\folderwithcsv\'
Get-ChildItem $src_dir -Filter *.xlsx |
Foreach-Object{
  'processing '+$_.FullName
  $wb = $excel.Workbooks.Open($_.FullName)
  $dst_file=$dst_dir + $_.BaseName + ".csv"
  $wb.SaveAs($dst_file, 6)# 6 -> csv
  'saved '+$dst_file
  $wb.Close($True)
  Start-Sleep -Seconds 2
 }
$excel.Quit()
[void][System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)


text:
Q: Finding host address range in C I write a simple C program that prints all the usable host addresses in a network.
Input
We provide the IP address of our network and the subnet mask.
Output
We print all the usable ip addresses that corresponds to the network.
Example
If we give the Ip 192.168.3.0 and the subnet 255.255.255.0 (/24 at CIDR) we get the following output:
192.168.3.1
192.168.3.2
192.168.3.3
192.168.3.4
...etc until 254

Problem
I don't get the results correctly.
Suppose we provide 192.168.3.0 and 255.255.255.0. I currently use bpf_u_int32 type from pcap lib to save both the ip and the subnet mask variables.
If I run the bellow code this is what I get as output:
0.3.168.193
0.3.168.194
0.3.168.195
0.3.168.196
0.3.168.197
0.3.168.198
0.3.168.199
0.3.168.200
0.3.168.201
0.3.168.202
0.3.168.203
0.3.168.204
0.3.168.205
0.3.168.206
0.3.168.207
0.3.168.208
0.3.168.209
0.3.168.210
0.3.168.211
0.3.168.212
0.3.168.213
0.3.168.214
0.3.168.215
0.3.168.216
0.3.168.217
0.3.168.218
0.3.168.219
0.3.168.220
0.3.168.221
0.3.168.222
0.3.168.223
0.3.168.224
0.3.168.225
0.3.168.226
0.3.168.227
0.3.168.228
0.3.168.229
0.3.168.230
...etc

Actual code
// suppose we have declare ip and subnet mask variables and passed values to it.
// bpf_u_int32 subnet_mask;
// bpf_u_int32 ip_address;

bpf_u_int32 x = subnet_mask;
  int numbits; // get the CIDR Prefix
  for (numbits = 0; x != 0; x >>= 1) {
    if (x & 0x01) {
      numbits++;
    }
  }

  // determine maximum and minimum host values.
  // we exclude the host and the broadcast (should we?)
  unsigned long hoststart;
  unsigned long hostend;
  hoststart = 1;
  hostend = (1 << (32 - numbits)) - 1;

  // mask off the network
  uint32_t network = ip_address & subnet_mask;

  // Calculate all host addresses in the range
  for (unsigned i = hoststart; i <= hostend; i++) {
    uint32_t hostip;
    int b1, b2, b3, b4;
    char ipstr[16];

    hostip = network + i;
    b1 = (hostip & 0xff000000) >> 24;
    b2 = (hostip & 0x00ff0000) >> 16;
    b3 = (hostip & 0x0000ff00) >> 8;
    b4 = (hostip & 0x000000ff);
    snprintf(ipstr, sizeof(ipstr), "%d.%d.%d.%d", b1, b2, b3, b4);
    printf("%s\n", ipstr);
  }

A: Looks like an endianness issue.
The IP address and subnet mask are being stored in little endian format, which means the least significant byte is first.  You need to swap the bytes using htonl.
uint32_t network = htonl(ip_address & subnet_mask);

Then the bytes will be in the correct order.


text:
Q: Can I filter table row content but ignore one element? I want to filter this table's rows on content in every  except for what's inside the . Is it possible?
With this script, if I search for "John", I want to return only the row with john@example.com. I want to ignore the the  that contains "john".
I can't seem to make it work.

$(document).ready(function() {
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#myTable tr").filter(function() {
      $(this).toggle($(this).not('.demolist').text().toLowerCase().indexOf(value) > -1)
    });
  });
});

<input id="myInput" type="text" placeholder="Search..">

      Firstname
      Lastname
      Email

      John
      Doe
      john@example.com

      Mary
      Moe
      mary@mail.com

john

A: Maybe there's another way to this, but I got using the function $(this).detach() for the divs with class "demolist" to remove from the DOM, then the search doesn't reach there. But to put it in the DOM again you have to tell where (by id or class), so I create another DIV beteween the "demolist" called "append" to use the function $(this).append(elem[index]) . I used jQuery each to list all elements in the class. Like this:
HTML
<input id="myInput" type="text" placeholder="Search..">

      Firstname
      Lastname
      Email

      John
      Doe
      john@example.com

Mary

      Mary
      Moe
      mary@mail.com

John

JavaScript
$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    var elem = $(".demolist");
    var ap = $(".append");
    elem.each(function(index, el) {
        $(this).detach();
    });
    $("#myTable tr").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
    });
    ap.each(function(index, el) {
        $(this).append(elem[index]);
    });
  });
});

You can see the working example in this fiddle: https://jsfiddle.net/cm3ns1wx/


text:
Q: Compare Dates from Rails to JavaScript I'm working on a feature of a project that changes the color of an element based on the date a record was created. I'm using a Rails Backend and React Frontend.
I'm trying to make sure the color goes with the appropriate day and not the day before or after.
In Rails, I have a record where the created_at attribute is "2020-07-29 17:38:00.437423" (PST)
In React, that same record shows its created_at attribute as "2020-07-29T17:38:00.437Z"
1.
new Date("2020-07-29 17:38:00.437423")
//=> Wed Jul 29 2020 17:38:00 GMT-0700 (Pacific Daylight Time)

*

new Date("2020-07-29T17:38:00.437Z")
//=> Wed Jul 29 2020 10:38:00 GMT-0700 (Pacific Daylight Time)

I've noticed that when I remove the 'Z' in the second version, the time matches up as I expect, but why do these strings return date objects that show a 7-hour difference?

A: In the browser when you create a date without any timezone information it will actually assume that its in the system time zone:
new Date("2020-07-29 17:38:00.437423")
> Date Wed Jul 29 2020 17:38:00 GMT+0200 (Central European Summer Time)

In my case its GMT+0200 because I'm in Denmark. Ooops.
2020-07-29T17:38:00.437Z is actually a ISO8601 timestamp with a time zone designation which is a lot less ambiguous.

If the time is in UTC, add a Z directly after the time without a
space. Z is the zone designator for the zero UTC offset. "09:30 UTC"
is therefore represented as "09:30Z" or "0930Z". "14:45:15 UTC" would
be "14:45:15Z" or "144515Z".
ISO8601 - Wikipedia

JavaScript's handling of dates and times is notoriously bad. When Brendan Eich rushed to create the language in 10 days back during the browser wars he just outright ripped off the date/time objects from java and the browser vendors created differing (awful) implementations. The result is a mess that still haunts us 25 years later.
There are multiple libraries like moment.js which fixes the problems and inconsistencies of the language as well as the lack of ways to convert from one TZ to another or manipulate dates.
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>

I would really recommend Thoughtbot's excellent article It's About Time (Zones) for the backend-side of things.

A: max's answer is correct. I just wanted to offer clarification that Javascript can parse ISO8601 timestamps with a UTC offset, he just forgot a "0".
new Date("2020-07-29T17:38:00.437-07:00")
2020-07-30T00:38:00.437Z

Here is the specification for reference: https://tc39.es/ecma262/#sec-date-time-string-format
I would've just commented on his answer, but I don't have the reputation.


text:
Q: How do I write html for form with multiple questions that use radio input type? I have this quiz in multiple choice format where users can select one option per question and submit their answers at the end. This example shows what I'm trying achieve: [Example code w3school][1]
The problem I'm having is that selecting an option on a question de-selects any previous selection, meaning only one option can be selected for the entire quiz.
This is a section of my form template:
<form @submit.prevent="submit">

 <jet-label :for="question.question" :value="question.question" class="font-bold text-lg" />

        <jet-label :for="option.option" :value="option.option" />
        <input :id="option.id" type="radio" :value="option.option"
        :name="option.question_id" v-model="form.options" />

    <jet-button class="ml-4" :class="{ 'opacity-25': form.processing }"
     :disabled="form.processing">
       Submit
     </jet-button>

</form>

And this is the JS to handle user selection binding:

The issue probably is that inputs are seen as belonging to one group. How can I group the inputs based on the question id so that the select/deselect radio action is per question?
[1]: https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_radio

A: v-model="form.options" seems to be the problem, all inputs have the same model.
Everytime a radio is selected it overwrites the this.options with the option value.
Try:
v-model="form.options[option.question_id]"

if that dosen't work try to add a custom event handler with @change
BTW: option.question_id is a weird data structure it meight be better to have the id in the question object, because it seems the options lay in an array inside the question object


text: Q: Нет кнопки "скачать товар" у виртуального\скачиваемого товара Woocommerce Есть интернет-магазин на woocommerce. Есть разделение товаров. Одни, соответственно можно купить, а вторые идут в рубрике "бесплатные предложения". На товарах, которые приобретаются, кнопка "в корзину" есть, всё работает. На первых же, кнопки никакой нет. В чём может быть дело ? как это решить ?


text:
Q: Receiving an error in Conda prompt when trying to install jira I'm new to Python and Anaconda. Trying to install the jira package through conda using "conda install jira" and here's the output I get. I've also tried the pip install in the command prompt.
(C:\Program Files\Anaconda2) C:\Windows\system32>conda install jira
Fetching package metadata ...Could not connect to https://repo.continuum.io/pkgs/pro/win-64/
Could not connect to https://repo.continuum.io/pkgs/free/win-64/
..Could not connect to https://repo.continuum.io/pkgs/free/noarch/
.Could not connect to https://repo.continuum.io/pkgs/pro/noarch/
.
Solving package specifications: .
Error: Package missing in current win-64 channels:
  - jira

You can search for packages on anaconda.org with

    anaconda search -t conda jira

(C:\Program Files\Anaconda2) C:\Windows\system32>


text:
Q: Is that safe when setName for java thread I have a java web service app. The web method has one parameter is requestId from the client. My web service app has to process multiple requests concurrent, so it must have some way to trace the log because request's log are mixed. I plan to rename the thread name to requestId and print out the thread name for getting easy to trace the log. My question is: would it be safe if I rename the thread name?

A: If you're using log4j, checkout their Nested Diagnostic Context (NDC) and Mapped Diagnostic Context (MDC) concepts which allows you to put unstructured data like that into all log outputs.
Other libraries probably have similar concepts.

A: Yes. You can rename the thread name anytime.


text:
Q: HP keyboard seriously misbehaving, presses additional keys. How to fix? Some keys on the keyboard on my HP Pavilion 2000-428DX press another key at the same time, which renders it unusable.
If I press   I get
----------   -------
ESC or Q     ESC + Q
G or R       G + R
E or F4      E + F4
H or U       H + U
Backspace    Backspace + something else (don't know what, it's not a character)

This happened after installing the spanish MUI language for Windows 7 x64 SP1. I don't know if it has any relation, through.
Anyone knows how can I fix this? I'm unable to send it to service support, since I bought it abroad.
Also, if this is not the right place to ask this question, would you point me to the right place? Thanks!
UPDATE: Just booted the machine with a live Ubuntu cd, and problem still persists, so I can confirm it's a hardware problem.

A: Go to control panel > Region and Language > Keyboards and Languages > Change Keyboards and make sure that the setting there match your keyboard.

A: The only sane alternative; get a new keyboard.
The fact is that logitech MK120 keyboard and mouse combo will put you back some 12€ (about the same in $) here in Sweden (with high VAT and other taxes!).
And that is a quite decent keyboard and mouse in my opinion. I have had far pricier ones and "complained" about them.
Or save the mouse:
https://www.amazon.com/dp/B003ELVLKU/


text:
Q: Two different INSERT INTO statements that do the same thing I'm digging into a legacy code (C++/Qt) which uses SQL(uses Oracle 11g) a lot. I've come with this piece of code(just changed variables name and write it in multiple lines for a better readability):
insert into FOO_TABLE (BEGIN, FIRST_VALUE, SECOND_VALUE, VALUE, BAR) select
999,
D.FIRST,
(select O.SECOND from TABLE_TWO O where O.ID=555),
333,
444
from TABLE_ONE D where D.ID=666

This in the form of INSERT INTO ... SELECT ...
Now it seems here "select" is used together with insert to retreive and create a row with a single line. However the syntax seems awkward. I changed it to:
insert into FOO_TABLE (BEGIN, FIRST_VALUE, SECOND_VALUE, VALUE, BAR) values (
999,
(select D.FIRST from TABLE_ONE D where D.ID=666),
(select O.SECOND from TABLE_TWO O where O.ID=555),
333,
444)

And this one works without any problem. This is in the form of INSERT INTO ... VALUES ...
Is there any difference in terms of performance or anything else? Because the second line seems more natural to me.

A: The difference is the cardinality of the result sets.
The first statement will work regardless of how many rows in TABLE_ONE match D.ID=666.  Whereas the second statement will fail if more than one row is returned.
For completeness there is a third variation:
insert into FOO_TABLE (BEGIN, FIRST_VALUE, SECOND_VALUE, VALUE, BAR) select
999,
D.FIRST,
O.SECOND,
333,
444
from TABLE_ONE D
    cross join TABLE_TWO  O
where O.ID=555
and D.ID=666

The Oracle optimizer is clever enough to know whether TABLE_TWO is matching on a unique key and will draw up an execution plan accordingly.

With regards to relative performance all variations ought to be the same.  Certainly this is what I woudl expect if both queries return a single row each.  There might be differences if TABLE_ONE returns multiple rows.  As always, when it comes to tuning queries, you would have to benchmark each approach, as execution times are sensitive to data volumes and skew.


text:
Q: `\foreach` does not understand constants in `declare function`: a bug? In relation with an answer, I see that \foreach does not understand a constant (n) in declare function. Is it a bug? or there is another proper way of code for this situation?

\documentclass[border=5mm]{standalone}
\usepackage{tikz}
\begin{document}

\begin{tikzpicture}
\def\n{7}    % number of sides of a heptagon
\pgfmathsetmacro{\k}{360/\n}
\pgfmathsetmacro{\r}{2}
\draw[cyan] (90:\r) foreach \i in {1,...,\n}  {--({90+\k*\i}:\r)}--cycle;
\end{tikzpicture}

% This does not work! Uncomment this tikzpicture to get a MWE
\begin{tikzpicture}[declare function={n=7;r=2;k=360/n;}]
\draw (90:r) foreach \i in {1,...,n} {--({90+k*\i}:r)}--cycle;
\end{tikzpicture}

% This works, but not natural! Is that a bug of \foreach ?
\begin{tikzpicture}[declare function={n=7;r=2;k=360/n;}]
\pgfmathsetmacro\m{n}
\draw (90:r) foreach \i in {1,...,\m} {--({90+k*\i}:r)}--cycle;
\end{tikzpicture}

\end{document}

A: Since PGF 3.1.2 (I think) you can use the parse=true option of \foreach.

In this situation you have to wrap n in parentheses so that \foreach parses it as a mathematical expression. Without parentheses \foreach will assume that you want an alphabetical loop a,...,n but since the lower limit is not alphabetical it will break.
\documentclass{article}
\usepackage{tikz}
\begin{document}

\begin{tikzpicture}[declare function={n=7;r=2;k=360/n;}]
  \draw (90:r) foreach \i [parse=true] in {1,...,(n)} { -- ({90+k*\i}:r) } --cycle;
\end{tikzpicture}

\end{document}


text:
Q: Best Method to Present a Many to Many Form to User I have a questions about how to best present a form based off a many to many relationship to a user.  I'll explain my models to help give an idea of what data I need to present.
Models and Relationships
   Shipment  has_many :products :through => :shipment_products
   Product   has_many :shipments :through => :shipment_products
   ShipmentProducts belongs_to :shipment,  belongs_to :product

So basically I have A shipment form that has the necessary data to create a bill of lading.  In addition to that form,  I need to select multiple products and their quantities.  I've had a similar issue in the past where I used drag and drop, but I was unhappy with the experience being a little cumbersome.  In this case I believe there would be too many products to list in a container to be able to drag and drop.
So what I need is a form that will allow me to fill out the shipment data, search for a product, select the product,  add the quantity, and associate that with a shipment.  What is the most effective way of designing my form so these items are presented clearly to my end user?

A: A popula solution fpor that is TokenInput thats a jQuery plugin that comunicates with your application via JSON. You can get it here: http://loopj.com/jquery-tokeninput/
Theres also a railscast dealing with that problem....
http://railscasts.com/episodes/258-token-fields
Hope this works for you,...