text:
Q: Sqlalchemy. How to set the defaul polymorphic innerjoin? How to set the defaul polymorphic innerjoin?
class Some(Base):
    __tablename__ = 'some'
    @declared_attr
    def __mapper_args__(cls):
        return  {'polymorphic_identity': '%s' % cls.__tablename__,
                 'polymorphic_on': cls._type,
                 'with_polymorphic': '*',
                 'polymorphic_innerjoin': True # how to do it?
        }

A: an INNER join is used if you actually query for that type specifically, no with_polymorphic needed:
sess.query(MySubClass).all()

If you are querying for Some objects (i.e. your base), that means you want objects that are also not of type MySubClass, so an OUTER join is necessary there.

redpajama_set_name: RedPajamaStackExchange


text:
Q: In R Shiny, how to make the unchecking of a checkbox input to cause an action? Below MWE code works as originally intended. When invoking the App, a matrix of checkboxes appears in sidebar panel with the option of show/hide/reset (only show/hide are working for simplicity of illustration) for a 2nd input matrix and a 3rd input matrix (only 2nd input matrix presents for simplicity of illustration), either/both of which appear (or would appear in case of 3rd input matrix) in sidebar panel.
However the hide function is better addressed by simply unchecking "Show", and I would like to eliminate the "Hide" checkbox. Does anyone know how to accomplish this? Check "Show" and 2nd input matrix appears; uncheck it and 2nd input matrix disappears. By default when invoking the App the 2nd input matrix needs to be hidden. (I ended up with show/hide as separate checkboxes because I had switched from action buttons to checkboxes...oops).
This will probably need to be put in a separate post, but for the checkbox matrix in the sidebar panel I'll also need to keep the columns for "Show" and "Reset" the same width and widen the 1st column which currently show "2nd input" and "3rd input".
MWE code:
library(shiny)
library(shinyjs)

### Begin checkbox matrix ###
f <- function(action,i){as.character(checkboxInput(paste0(action,i),label=NULL))}
actions       <- c("show", "hide", "reset")
tbl           <- t(outer(actions, c(1,2), FUN = Vectorize(f)))
colnames(tbl) <- c("Show", "Hide", "Reset")
rownames(tbl) <- c("2nd input", "3rd input")
### End checkbox matrix ###

firstInput <- function(inputId){
  matrixInput(inputId,
              value = matrix(c(5), 1, 1, dimnames = list(c("1st input"),NULL)),
              rows =  list(extend = FALSE, names = TRUE),
              cols =  list(extend = FALSE, names = FALSE, editableNames = FALSE),
              class = "numeric")}

secondInput <- function(inputId,x){
  matrixInput(inputId,
              value = matrix(c(x), 1, 1, dimnames = list(c("2nd input"),NULL)),
              rows =  list(extend = FALSE, names = TRUE),
              cols =  list(extend = FALSE, names = FALSE, editableNames = FALSE),
              class = "numeric")}

ui <- fluidPage(
  tags$head(
    tags$style(HTML(
      "td .checkbox {margin-top: 0; margin-bottom: 0;}
       td .form-group {margin-bottom: 0;}"
    ))
  ),
  br(),
  sidebarLayout(
    sidebarPanel(
      uiOutput("panel"),
      hidden(uiOutput("secondInput")),
    ),
    mainPanel(plotOutput("plot1"))
  )
)

server <- function(input, output){

  input1      <- reactive(input$input1)
  input2      <- reactive(input$input2)

  output$panel <- renderUI({
    tagList(
      useShinyjs(),
      firstInput("input1"),
      strong(helpText("Generate curves (Y|X):")),
      tableOutput("checkboxes")
    )
  })

  ### Begin checkbox matrix ###
  output[["checkboxes"]] <-
    renderTable({tbl},
      rownames = TRUE, align = "c",
      sanitize.text.function = function(x) x
    )
  observe({
    print(input[["show1"]])
    shinyjs::show("secondInput")
  })

  observe({
    print(input[["hide1"]])
    shinyjs::hide("secondInput")
  })
  ### End checkbox matrix ###

  output$secondInput <- renderUI({
    req(input1())
    secondInput("input2",input$input1[1,1])
  })

  outputOptions(output,"secondInput",suspendWhenHidden = FALSE)

  output$plot1 <-renderPlot({
    req(input2())
    plot(rep(input2(),times=5))
  })

  observeEvent(input$show,{
    shinyjs::show("secondInput")
    updateCheckboxInput(session, "hide", value = FALSE)
  })

  observeEvent(input$hide,{
    shinyjs::hide("secondInput")
    updateCheckboxInput(session, "show", value = FALSE)
  })

}

shinyApp(ui, server)

A: You can use observeEvent and a condition:
library(shiny)
library(shinyjs)
library(shinyMatrix)

### Begin checkbox matrix ###
f <- function(action,i){as.character(checkboxInput(paste0(action,i),label=NULL))}
actions       <- c("show", "reset")
tbl           <- t(outer(actions, c(1,2), FUN = Vectorize(f)))
colnames(tbl) <- c("Show", "Reset")
rownames(tbl) <- c("2nd input", "3rd input")
### End checkbox matrix ###

firstInput <- function(inputId){
  matrixInput(inputId,
              value = matrix(c(5), 1, 1, dimnames = list(c("1st input"),NULL)),
              rows =  list(extend = FALSE, names = TRUE),
              cols =  list(extend = FALSE, names = FALSE, editableNames = FALSE),
              class = "numeric")}

secondInput <- function(inputId,x){
  matrixInput(inputId,
              value = matrix(c(x), 1, 1, dimnames = list(c("2nd input"),NULL)),
              rows =  list(extend = FALSE, names = TRUE),
              cols =  list(extend = FALSE, names = FALSE, editableNames = FALSE),
              class = "numeric")}

ui <- fluidPage(
  tags$head(
    tags$style(HTML(
      "td .checkbox {margin-top: 0; margin-bottom: 0;}
       td .form-group {margin-bottom: 0;}"
    ))
  ),
  br(),
  sidebarLayout(
    sidebarPanel(
      uiOutput("panel"),
      hidden(uiOutput("secondInput")),
    ),
    mainPanel(plotOutput("plot1"))
  )
)

server <- function(input, output){

  input1      <- reactive(input$input1)
  input2      <- reactive(input$input2)

  output$panel <- renderUI({
    tagList(
      useShinyjs(),
      firstInput("input1"),
      strong(helpText("Generate curves (Y|X):")),
      tableOutput("checkboxes")
    )
  })

  ### Begin checkbox matrix ###
  output[["checkboxes"]] <-
    renderTable({tbl},
                rownames = TRUE, align = "c",
                sanitize.text.function = function(x) x
    )

  observeEvent(input[["show1"]], {
    if(input[["show1"]]){
      shinyjs::show("secondInput")
    } else {
      shinyjs::hide("secondInput")
    }
  })

  ### End checkbox matrix ###

  output$secondInput <- renderUI({
    req(input1())
    secondInput("input2",input$input1[1,1])
  })

  outputOptions(output,"secondInput",suspendWhenHidden = FALSE)

  output$plot1 <- renderPlot({
    req(input2())
    plot(rep(input2(),times=5))
  })

  observeEvent(input$show,{
    shinyjs::show("secondInput")
    updateCheckboxInput(session, "hide", value = FALSE)
  })

  observeEvent(input$hide,{
    shinyjs::hide("secondInput")
    updateCheckboxInput(session, "show", value = FALSE)
  })

}

shinyApp(ui, server)


text:
Q: SDL Surfaces Randomly Lock I am a newbie to SDL, and starting to learn some of it, and encountered an interesting problem. The window for the program would flash, then disappear forever. Also, there would occasionally be an exec error with SDL_BlitSurface. SDL_GetError() shows it to be a surface locking. However, when checking the screen surface's locks, by using ->locked, the screen surface would always have a random number amount of locks, ranging from positive to negative numbers.
Manager class:
//apply image
if(SDL_BlitSurface(SDLProcess::getInstance().getImage(0), NULL, SDLProcess::getInstance().getScreenSurface(), NULL) < 0)
{

    ErrorManagement::callSDLError();
}

Screen Surface class:
ScreenSurface::ScreenSurface(SDL_Window* window)
{
//std::cout << window << std::endl;
p_screensurface = SDL_GetWindowSurface(window);

assert(p_screensurface != NULL);

//std::cout << p_screensurface << std::endl;
}

ScreenSurface::~ScreenSurface()
{
    printf("screen surface destroyed");
}

SDL_Surface* ScreenSurface::getScreenSurface()
{
//std::cout << p_screensurface << std::endl;
return p_screensurface;
}

Error message in console (the top number is the number of locks and the lower is the error message):
37792424
SDL Error: Surfaces must not be locked during blit

and another example:
42068296
SDL Error: Surfaces must not be locked during blit

A: Fixed it. Was a stupid mistake where SDL init was begin called afterwards.


text:
Q: Does Laravel support return Redirect::back()->withFile()? I'm new to Laravel,
if laravel have a validation on going with input text
<input type="text name="title" />
then when validation fails, it will return the input text value
return Redirect::back()->withInput()
does laravel have this function for file?
<input type="file" name="testfile" />
return Redirect::back()->withFile()
inorder to store the temp file in the input type="file" when validation fails.

A: No, it does not, and it could not.
When Redirect::back() is fired, a new HTTP request is being sent to the server. As HTTP is stateless, Laravel flashes the old input to the session handler and makes it available to you via the Input::old() function. Laravel then uses this information to pre-populate forms and text fields.
For security reasons however, you cannot pre-populate file fields, else a server could set any value it wanted to try and force you to upload any files from your computer!
Depending upon what you need, you would be able to store the file yourself and send the location of the file back using Redirect::back()->with('file_location', '...'). You won't be able to physically pre-populate the file input, but you could show something to the user when they're redirected back to let them know that they don't need to re-upload the file, unless they want to.


text:
Q: What is an optimal way to get parent node for every current node in many-hop Cypher query? I have a graph of files and folders and I essentially want a query - given a folderId - that brings back the entire sub-directory structure recursively, including each node's parentId.
I came up with this solution (note: Cypher 2.0):
match p = (f:folder)-[:CONTAINS*0..]->c
where f._id = 3
return case when c._id = f._id then null
          else nodes(p)[length(p)-1]._id end as parentId, c;

That seems to work. However I feel like there must be a cleaner way. What's the best way to do this?

A: One alternative is to explicitly identify the parent node on the path,
Match f:Folder-[:CONTAINS*0..]->parent-[:CONTAINS]->c
where f._id = 3
Return parent._id as parent, c._id as current

The result would not include the row for the given starting folder f. but since it is a fixed value, if you really need to include that in the query result, you can always append it to the result as follows,
Match f:Folder-[:CONTAINS*0..]->parent-[:CONTAINS]->c
where f._id = 3
Return parent._id as parent, c._id as current
Union
Return null as parent, 3 as current


text:
Q: How to test memory after memory upgrade? I recently upgraded my macbook from 4G to 8G and wonder if there's a tool to test the quality of new memory.
I found memtest 4.22 seems only test about 1G:
$ memtest all 2

Memtest version 4.22 (64-bit)
Copyright (C) 2004 Charles Cazabon
Copyright (C) 2004-2008 Tony Scaminaci (Macintosh port)
Licensed under the GNU General Public License version 2 only

Mac OS X 10.9 (13A603) running in multiuser mode
Memory Page Size: 4096
System has 4 Intel core(s) with SSE
Requested memory: 1048MB (1099390976 bytes)
Available memory: 1048MB (1099390976 bytes)
Allocated memory: 1048MB (1099390976 bytes) at local address 0x0000000101000000
Attempting memory lock... locked successfully
Partitioning memory into 2 comparison buffers...
Buffer A: 524MB (549695488 bytes) starts at local address 0x0000000101000000
Buffer B: 524MB (549695488 bytes) starts at local address 0x0000000121c3b000

==========
UPDATE:
I reboot into single user mode as described in this question, and test again. Works better, about 7G memory tested. So I guess the missing 1G is reserved for the graphics card?

A: I suggest you to install memtester for example with MacPorts:
$ port install memtester

and use it:
$ memtester 2G
memtester version 4.3.0 (64-bit)
Copyright (C) 2001-2012 Charles Cazabon.
Licensed under the GNU General Public License version 2 (only).

pagesize is 4096
pagesizemask is 0xfffffffffffff000
want 2048MB (2147483648 bytes)
got  2048MB (2147483648 bytes), trying mlock ...locked.
Loop 1:
  Stuck Address       : ok
  Random Value        : ok
  Compare XOR         : ok
  Compare SUB         : ok
  Compare MUL         : ok
  Compare DIV         : ok
  Compare OR          : ok
  Compare AND         : ok
  Sequential Increment: ok
[...]

A: To test the whole memory, you need to boot from an external device (USB stick, DVD) with a system that uses the least memory. You can try the Apple Hardware Test by pressing the 'd' key on your keyboard while booting (if it is not working, try with Alt-d to boot the AHT over the Internet). Or you can also try MemTest86 and create a bootable memory stick. I have read some people saying that MemTest86 was better than AHT. However it just happened to me that AHT was able to find a memory failure in my MBP, and MemTest86 did not detect any problem after 4 passes of tests.


text:
Q: No idea how to read in a DF into another DF to make changes I am attempting to solve the problem

1.(10pts) Read the data into a data frameand handle incorrect/inconsistent data typesNote: There are no UTF-8 or special characters in the data.
  Output variables:oraw_df: read the data without colClasses,
  na.strings, orstringsAsFactorsto see how R interprets each column
  movie_df: using the arguments of read.csv()and/or the as()function,
  transform the columns with incorrect data types

For the second part, I have no idea how to reference the data frame "raw_df" to use it to link into the new movie_df
movie_df<-raw_df(as.factor(raw_df$IMBD))

This is what I have tried as it makes the most logical sense, however it says that R can't find function raw_df, and obviously this isn't a function so I have no clue how to even attempt to start this problem.


text:
Q: Make multicolor dynamic text in textarea My question is simple. but didn't get solution.
I have one textarea. like:
<textarea style="height: 70px; width: 99%;"></textarea>

And Jquery like:
var text = 'Hello... \n World \n othertext';
$('textarea').attr('value', text);

Now, i like to make different formatting for Hello , World and othertext.  Suppose Hello with color:red and font-size:15px;, and World has color:yellow and font-size:20px; and so on.
So, how can i set using either css or jquery?
Fiddle Link.

A: I don't know whether it is possible with a text area. Below is my sample code with editable div using java script. JS fiddle Link : http://jsfiddle.net/pckrishnadas88/ec4Lnn22/

$('.editable').each(function(){
    this.contentEditable = true;
});
div.editable {
    width: 300px;
    height: 200px;
    border: 1px solid #ccc;
    padding: 5px;
    color:red;
}
div.editable span{
    color:green;
    font-weight:bold;
    font-size:24px;
}

editable span content


text:
Q: Play2 Framework - Secure Social Session Value at my current Project I'm using the secure social plugin for Play 2 Framework. I wrote a function to count my Products which are stored in the Session.
    public static Integer cntOrderedProductsFromSession(){

    Integer cnt = 0;
    try {
        List<String> KeyList = new ArrayList<String>(session().keySet());
    for (Iterator<String> iterator = KeyList.iterator(); iterator.hasNext();){
        String name = iterator.next();
        if(name.matches("product.[0-9]*")){
            cnt += Integer.parseInt(session(name));
        }
    }
    return cnt;
    } catch (RuntimeException e){
        return 0;
    }
}

I wrapped my secure social login Page in a main.hmtl.scala, here I call my function
<p>@Shop.cntOrderedProductsFromSession()</p>

The problem is, that I get an error, when I try use the cntOrderedProductsFromSession() function. (But only with the secure social login Page)
I get this error
 java.lang.RuntimeException: There is no HTTP Context available from here.
at play.mvc.Http$Context.current(Http.java:30) ~[play_2.10.jar:2.2.3]
at play.mvc.Controller.session(Controller.java:60) ~[play_2.10.jar:2.2.3]
at controllers.Shop.cntOrderedProductsFromSession(Shop.java:236) ~[classes/:na]
at views.html.main$.apply(main.template.scala:173) ~[classes/:na]
at views.html.custom.login$.apply(login.template.scala:50) ~[classes/:na]
at plugins.NekViews.getLoginPage(NekViews.scala:32) ~[classes/:na]
at securesocial.controllers.LoginPage$$anonfun$login$1.apply(LoginPage.scala:56) ~[securesocial_2.10-2.1.3.jar:2.1.3]
at securesocial.controllers.LoginPage$$anonfun$login$1.apply(LoginPage.scala:42) ~[securesocial_2.10-2.1.3.jar:2.1.3]
at play.api.mvc.ActionBuilder$$anonfun$apply$10.apply(Action.scala:221) ~[play_2.10.jar:2.2.3]
at play.api.mvc.ActionBuilder$$anonfun$apply$10.apply(Action.scala:220) ~[play_2.10.jar:2.2.3]
at play.api.mvc.Action$.invokeBlock(Action.scala:357) ~[play_2.10.jar:2.2.3]
at play.api.mvc.ActionBuilder$$anon$1.apply(Action.scala:309) ~[play_2.10.jar:2.2.3]
at play.api.mvc.Action$$anonfun$apply$1$$anonfun$apply$4$$anonfun$apply$5.apply(Action.scala:109) ~[play_2.10.jar:2.2.3]
at play.api.mvc.Action$$anonfun$apply$1$$anonfun$apply$4$$anonfun$apply$5.apply(Action.scala:109) ~[play_2.10.jar:2.2.3]
at play.utils.Threads$.withContextClassLoader(Threads.scala:18) ~[play_2.10.jar:2.2.3]
at play.api.mvc.Action$$anonfun$apply$1$$anonfun$apply$4.apply(Action.scala:108) ~[play_2.10.jar:2.2.3]
at play.api.mvc.Action$$anonfun$apply$1$$anonfun$apply$4.apply(Action.scala:107) ~[play_2.10.jar:2.2.3]
at scala.Option.map(Option.scala:145) ~[scala-library.jar:na]
at play.api.mvc.Action$$anonfun$apply$1.apply(Action.scala:107) ~[play_2.10.jar:2.2.3]
at play.api.mvc.Action$$anonfun$apply$1.apply(Action.scala:100) ~[play_2.10.jar:2.2.3]
at play.api.libs.iteratee.Iteratee$$anonfun$mapM$1.apply(Iteratee.scala:481) ~[play-iteratees_2.10.jar:2.2.3]
at play.api.libs.iteratee.Iteratee$$anonfun$mapM$1.apply(Iteratee.scala:481) ~[play-iteratees_2.10.jar:2.2.3]
at play.api.libs.iteratee.Iteratee$$anonfun$flatMapM$1.apply(Iteratee.scala:517) ~[play-iteratees_2.10.jar:2.2.3]
at play.api.libs.iteratee.Iteratee$$anonfun$flatMapM$1.apply(Iteratee.scala:517) ~[play-iteratees_2.10.jar:2.2.3]
at play.api.libs.iteratee.Iteratee$$anonfun$flatMap$1$$anonfun$apply$13.apply(Iteratee.scala:493) ~[play-iteratees_2.10.jar:2.2.3]
at play.api.libs.iteratee.Iteratee$$anonfun$flatMap$1$$anonfun$apply$13.apply(Iteratee.scala:493) ~[play-iteratees_2.10.jar:2.2.3]
at scala.concurrent.impl.Future$PromiseCompletingRunnable.liftedTree1$1(Future.scala:24) [scala-library.jar:na]
at scala.concurrent.impl.Future$PromiseCompletingRunnable.run(Future.scala:24) [scala-library.jar:na]

Thaks 4 help

A: The error is quite explicit. There is no HTTP Context available from here.
You will have to pass the context to all your views/functions using the context.
Within a template, that can be done as follows :
@(param1:Param1Type)(implicit context:Context)

@main("Title") {
}

Where in the main.scala.html template you will have the following :
@main(title:String)(implicit context:Context)


text:
Q: Spree. No shipping methods available for selected location, please change your address and try again Getting error(msg) when trying to commit the "Billing address" form. (http ://mystore:3000/checkout/address)
msg ->  No shipping methods available for selected location, please change your address and try again.
If I choose in field "Country" as "United States" or "Canada" it works fine, but with other countries It won't commit:)
my Gemfile
source 'http://rubygems.org'

gem 'rails', '3.2.13'

# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'

gem 'sqlite3'

# Gems used only for assets and not required
# in production environments by default.
group :assets do
  gem 'sass-rails',   '~> 3.2.3'
  gem 'coffee-rails', '~> 3.2.1'

  # See https://github.com/sstephenson/execjs#readme for more supported runtimes
  # gem 'therubyracer', :platforms => :ruby

  gem 'uglifier', '>= 1.0.3'
end

gem 'jquery-rails'

# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'

# To use Jbuilder templates for JSON
# gem 'jbuilder'

# Use unicorn as the app server
# gem 'unicorn'

# Deploy with Capistrano
# gem 'capistrano'

# To use debugger
# gem 'debugger'
gem 'spree', '1.3.2'
gem 'spree_gateway', :github => 'spree/spree_gateway', :branch => '1-3-stable'
gem 'spree_auth_devise', :github => 'spree/spree_auth_devise', :branch => '1-3-stable'

Thank you :)

A: Another thing that will cause this annoying, ambiguous error, is not having any stock locations set even if you have config.track_inventory_levels set to false.
Have done more than my fair share of tearing my hair out over this error, since it can be caused by one of 9000 things.

A: Solved :)
Thank you very much NICWN -> https://groups.google.com/forum/?fromgroups=#!searchin/spree-user/No$20shipping$20methods$20available$20for$20selected$20location,$20please$20change$20your$20address$20and$20try$20again/spree-user/-imHA2H9KxI/Z_-EKBhq0twJ

*

*create new zone "Asia"

*add country "Japan"

*in config > states, pick "Japan" and add state "Kanto"

*And of course, I added a new Shipping Method for Asia zone.
{
name -> Japan (JPY)     {you have to specify the currency in the brackets :) & it has to be the same as in the field "CURRENCY:" & if it's not USD you have to change it in "GENERAL SETTINGS" by choosing currency in "CHOOSE CURRENCY"}
}

*Shipping method without choosing any shipping category. "SHIPPING CATEGORY" -->  None.

A: You should check Zone in Admin Portal. You can maintain 2 zones. First option can be "USA" + "Canada" , which is spree default as Domestic shipping. Another default option is EU_VAT for international shipping. For any other country which is not a part of Domestic Shipping should be member of International Shipping. If you are using FedEx then you need to get developers key from fedex for Development Environment also.
One can find solution for how to obtain developers test keys for fedex
http://arvind-ror.blogspot.in/2013/08/how-to-obtain-developers-test-keys-from.html


text:
Q: Keyboard shortcut to delete the current rmd chunk in RStudio There are keyboard shortcuts for inserting and running chunks. Is there a keyboard shortcut to delete the current chunk in R Markdown?

A: I am not sure if such a feature exists. As of now, the trick I use to do it is folding the chunk and deleting the folded chunk.

You can also visit Shortcut: Select all in current R Markdown code chunk to view how to select the whole chunk, as I believe this may help.


text:
Q: wrap() method doesn't seem to work in jQuery

$('input.text-1').wrap('');
.textfield-1 {
  border: 1px solid #d00;
  display: none;
}

<input type="text" class="text text-1" />

Wrap() doesn't seem to work. I don't see s wrapped around input in firebug. If they were wrapped, inputs would be hidden with display: none, but they aren't.
What am I doing wrong here?

A: Works ok for me.  Is it possible that you have a javascript error on the page that is preventing the code from executing?
Here's my test.   Element does become invisible and I can see that it is wrapped in the span.

<input type="text" class="text text-1" />


text:
Q: Database Editing in Session OnEnd Classic ASP I was Creating a website in Classic ASP Project, having a Logout feature.
I want to access the login  database and make changes, when the session ends. The coding is something like:
In global.asa :
Sub Session_OnEnd()
Set studcon = Server.CreateObject("ADODB.Connection")
studcon.Open "Provider = Microsoft.JET.OLEDB.4.0;Data Source = E:\mailfan.mdb"
Set studrec = Server.CreateObject("ADODB.Recordset")
studrec.Open "login", studcon, 1, 3

studrec.movefirst
found = 0
Do While studrec.EOF or found = 1
    If studrec("ID") = Session("uid") Then
    studrec("log") = 0
    studrec.Update
    End If
    studrec.movenext
Loop
studrec.close
studcon.close
Set studrec = Nothing
Set studcon = Nothing
End Sub

But Even After    Session.Abandon    the value of log field Remains the same (It is 1 when session's active).
Small Update: I tried to google it, and did recieve a very similar link having the same question: http://www.justskins.com/forums/problem-with-global-asa-77015.html
But the code is the same as suggested by Aaron Bertrand in the above link. Is it due to IIS 8.0? Because I would be Running it on Win XP sp3 IIS 6. And I Do require it to work there.

A: I can't see an SQL query anywhere in your code.  If  you're intent on using a recordset for your update then in place of
studrec.Open "login", studcon, 1, 3

you should have something like
studrec.Open "select * from login", studcon, 1, 3

This assumes that your database table is called "Login"
Using a recordset is actually an over complex means of doing all this though, An Update query should suffice.  You could remove all your code from
Set studrec = Server.CreateObject("ADODB.Recordset")

to
studrec.close

and replace it with
studcon.Execute("UPDATE Login set log = 0 where id = " & Session("uid"))


text:
Q: AS3 Vectors: using getters and setters? Is there a way to use getters and setters for Vectors?
Say, in my Main class, I would like to write
myVector.push(item);

and in another class, I have written:
public function get myVector():Vector.<int> {
     return _opponentCardList;
}

public function set myVector(myVector:Vector.<int>):void {
     _myVector = myVector;
}

This doesn't really work as you have to set _myVector to a Vector. But what if you just want to push(), pop() or splice?

A: Your getter and setter use different variables - is that intentional?
If the getter/setter myVector is in a different class, you need an instance of that class in your Main class before you can access it from there.
//in the Main class.
var obj:OtherClass = new OtherClass();
//the constructor of OtherClass should initialize _myVector
//otherwise you will get a null pointer error (1009) in the following line
obj.myVector.push(item);


text:
Q: Create Custom product type with Associated products tab I want to create a new Custom product type similar to the Grouped Product esp. which have associated products tab on product page in backend.  I have tried with following tags in my module config.xml file.
  <catalog>
        <product>
            <type>
                <bookable translate="label" module="bookable">
                    <label>Bookable Product</label>
                    <model>bookable/product_type_packet</model>
                    <is_qty>1</is_qty>
                    <composite>0</composite>
                     <allowed_selection_types>
                          <simple/>
                          <grouped/>
                     </allowed_selection_types>
                </bookable>
            </type>
        </product>
    </catalog>

Please advise me how I can achieve this job.
thanks.

A: https://community.magento.com/t5/Building-Extensions/Custom-Product-Type-which-extends-Grouped-Product-Type/td-p/16251
The Associated Products tab is added via XML with a handle that is specific to that product type. You will need to add a similar update for your product type in your own admin layout xml file
app/design/adminhtml/default/default/layout/catalog.xml
<adminhtml_catalog_product_grouped>
    <reference name="product_tabs">
        <action method="addTab"><name>super</name><block>adminhtml/catalog_product_edit_tab_super_group</block></action>
    </reference>
</adminhtml_catalog_product_grouped>

If you're trying to copy grouped pretty much exactly using the grouped handle as an update like below may work best:
<adminhtml_catalog_product_newtypeidhere>
    <update handle="adminhtml_catalog_product_grouped"/>
</adminhtml_catalog_product_newtypeidhere>

Credit to James Anelay


text:
Q: Protecting web application from CSRF attack using Spring Security I am implementing CSRF protection in my web application.
I have used org.springframework.security.web.csrf.CookieCsrfTokenRepository class to generate the X-XSRF token. This token is being sent as cookie in every request's response.
UI component which is a single page application deployed on different server is read this cookie and read the X-XSRF token from cookie and set it as header in all subsequent requests.
Spring validates the received X-XSRF token and allow/deny the request. This works fine.
But their is a constraint this X-XSRF cookie has to be httpOnly is false so that client side JavaScript can read it.
We cannot read a cookie for which httpOnly is true.
Is there any other alternative to protect web application CSRF in an web application where X-XSRF token cookie httpOnly is true.
Using JavaScript method (document.cookie) I can not read the cookies for which httpOnly attribute is set to true, see:

*

*How to read a secure cookie using JavaScript

*Secure and HttpOnly cookies

*Cross-Site Request Forgery Prevention Cheat Sheet
I can not made the changes to make all the cookies as httpOnly is false in Websphere.
Or am I missing something where client side JavaScript can read the cookie which is httpOnly is true.

A: See Spring Security Reference:

CookieCsrfTokenRepository
There can be cases where users will want to persist the CsrfToken in a cookie. By default the CookieCsrfTokenRepository will write to a cookie named XSRF-TOKEN and read it from a header named X-XSRF-TOKEN or the HTTP parameter _csrf. These defaults come from AngularJS
You can configure CookieCsrfTokenRepository in XML using the following:
<http>
    <!-- ... -->
    <csrf token-repository-ref="tokenRepository"/>
</http>
<b:bean id="tokenRepository"
    class="org.springframework.security.web.csrf.CookieCsrfTokenRepository"
    p:cookieHttpOnly="false"/>

The sample explicitly sets cookieHttpOnly=false. This is necessary to allow JavaScript (i.e. AngularJS) to read it. If you do not need the ability to read the cookie with JavaScript directly, it is recommended to omit cookieHttpOnly=false to improve security.
You can configure CookieCsrfTokenRepository in Java Configuration using:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
    }
}

The sample explicitly sets cookieHttpOnly=false. This is necessary to allow JavaScript (i.e. AngularJS) to read it. If you do not need the ability to read the cookie with JavaScript directly, it is recommended to omit cookieHttpOnly=false (by using new CookieCsrfTokenRepository() instead) to improve security.


text:
Q: Distinguish different values in @PostMapping, @GetMapping or @RequestMapping @PostMapping(value = { "/weblogin", "/mobilelogin" })
@ResponseStatus(HttpStatus.OK)
public AccessTokenResponseModel login() { // need to distinguish "/weblogin" or "/mobilelogin" }

In spring boot, How can I distinguish the post request comes from "/weblogin" or "/mobilelogin"
in login() method?

A: You could use the BEST_MATCHING_PATTERN_ATTRIBUTE attribute.
@PostMapping(value = { "/weblogin", "/mobilelogin" })
@ResponseStatus(HttpStatus.OK)
public AccessTokenResponseModel login(HttpServletRequest httpRequest) {
   final String requestMapping = ( String ) httpRequest.getAttribute( HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE );
   final boolean isMobileLogin = requestMapping.contains("/mobilelogin");

   ....
}


text:
Q: How to select jqGrid row on checkbox click? Below is my code for jqGrid, i'd like to select row or highlight the current row, when i check a particular checkbox inside jqgrid row. right now onSelectRow I am making the checkbox get checked.
var xmlDoc = $.parseXML(xml);
         $('#configDiv').empty();
            $('
')
            .attr('id','configDetailsGrid')
            .html('

'+
                    '

'+
                '
')
            .appendTo('#configDiv');

            var grid = jQuery("#list1");

            grid.jqGrid({

              datastr : xml,
              datatype: 'xmlstring',
              colNames:['cfgId','','Name', 'Host', 'Description','Product', 'Type', 'Last Updated Time','Last Updated By',''],
              colModel:[
                  {name:'cfgId',index:'cfgId', width:90, align:"right", hidden:true},
                  {name:'',index:'', width:15, align:"right",edittype:'checkbox',formatter: "checkbox",editoptions: { value:"True:False"},editable:true,formatoptions: {disabled : false}},
                  {name:'cfgName',index:'cfgName', width:90, align:"right"},
                  {name:'hostname',index:'hostname', width:90, align:"right"},
                  {name:'cfgDesc',index:'cfgDesc', width:90, align:"right"},
                  {name:'productId',index:'productId', width:60, align:"right"},
                  {name:'cfgType',index:'cfgType', width:60, align:"right"},
                  {name:'updateDate',index:'updateDate',sorttype:'Date', width:120, align:"right"},
                  {name:'emailAddress',index:'emailAddress', width:120, align:"right"},
                  {name:'absolutePath',index:'absolutePath', width:90, align:"right", hidden:true},
              ],
              pager : '#gridpager',
              rowNum:10,
              scrollOffset:0,
              height: 'auto',

              autowidth:true,
              viewrecords: true,
              gridview: true,
              xmlReader: {
                  root : "list",
                  row: "com\\.abc\\.db\\.ConfigInfo",
                  userdata: "userdata",
                  repeatitems: false
              },
              onSelectRow: function(id,status){
                  var rowData = jQuery(this).getRowData(id);
                  configid = rowData['cfgId'];
                  configname=rowData['cfgName'];
                  configdesc=rowData['cfgDesc'];
                  configenv=rowData['cfgType'];

                  if(status==true)
                  {

                  }

                  rowChecked=1;
                  currentrow=id;
                  },
              onCellSelect: function(rowid, index, contents, event) {
                  if(index==2)
                  {

                        $(xmlDoc).find('list com\\.abc\\.db\\.ConfigInfo').each(function()
                        {
                            //alert($(this).find('cfgId').text()+" "+configid);
                            if($(this).find('cfgId').text()==configid)
                            {
                                configname=$(this).find('cfgName').text();
                                configdesc=$(this).find('cfgDesc').text();
                                configenv=$(this).find('cfgType').text();
                                filename=$(this).find('fileName').text();
                                updatedate=$(this).find('updateDate').text();
                                absolutepath=$(this).find('absolutePath').text();
                                productname=productMap[$(this).find('productId').text()];
                            }
                        });

                  }
               }

            });
            grid.jqGrid('navGrid','#gridpager',{edit:false,add:false,del:false});

So how would I select current row on checkbox selected?

A: Put this at the and of your JS code in order to run selection when clicking a checkbox
$("#list1").find('input[type=checkbox]').each(function() {
    $(this).change( function(){
        var colid = $(this).parents('tr:last').attr('id');
        if( $(this).is(':checked')) {
           $("#list1").jqGrid('setSelection', colid );
           $(this).prop('checked',true);
        }
        return true;
    });
});

example UPDATED AGAIN: http://jsfiddle.net/vCWNP/
edit:
this also should be done every time a new row is added.
let me know if something else is to be fixed ;]

A: It seems to me, that you could solve your problem very easy. What you try to do is already implemented in the jqGrid. If you remove the column name:'',index:'' which has empty name, which is NOT PERMITTED and include an additional jqGrid parameter multiselect:true all will work like you as need.

A: One simple way to do that:
jQuery(".jqgrow td input").each(function () {
    jQuery(this).click(function () {
        $("#grid").jqGrid('setSelection', $(this).parents('tr').attr('id'));
    });
});

A: on  your onSelectRow function add:
var flag = jQuery(this).find('#'+id+' input[type=checkbox]').prop('checked');
if(flag){
      jQuery(this).css('background-color', 'red' )// row will be in red if checkbox is selected, you have to find out the current row here
}


text:
Q: $.getJSON is not saving data into global variable/object, which is local there I have a file data3.json:
{
"street":"Oslo West 555",
"age":33,
"phone":"555 1234567"
}

I want to read this file with JavaScript (and JQuery) and store the values into an object.
I have the HTML file (same directory):
<!DOCTYPE html>

<meta charset="utf-8" />
<title>JSON Sample</title>

Name:

Age:

Address:

Phone:

In Browser I get:
Name: John Johnson
Age: undefined
Address: undefined
Phone: undefined

In console I get:
street: Oslo West 555
Object { street="Oslo West 555"}
age: 33
Object { street="Oslo West 555", age=33}
phone: 555 1234567
Object { street="Oslo West 555", age=33, phone="555 1234567"}

I have tested adding value inside the function with the function add(...), which works fine.
Inside of $.getJSON the variable became local...
How can force $.getJSON to add the data to my variable JSONObject?

A: $.getJSON('data3.json', function(data) {

     JSONObject = data;

     $("#jname").html(JSONObject.name);
     $("#jage").html(JSONObject.age);
     $("#jstreet").html(JSONObject.street);
     $("#jphone").html(JSONObject.phone);

});


text: Q: Is there anyway to find out if an edge is random in a weighted graph? I have a weighted graph with density more than 80%. I know that some of the edges are random, but I don't know how to score edges or nodes. Is there any way to calculate it or compare my graph to random graph in some way? Or any threshold to cut edges with weight less than threshold?


text:
Q: 100 docker containers vs 100 small machines so we have an application which is not thread-safe.
Some of the library it is using is doing a lock on file-system level. Unfortunately, it's not working correctly and will crash and throw an error if there are some concurrent usage of the library. We also can't switch this library away. To achieve concurrency, which one is better? Running 100 containers in one powerful machine or splitting it into 100 small machines?
Since we are using Amazon, I am thinking about 100 X t2.micro instances each running one container VS one c4.8xlarge machine with 100 docker containers. We don't have any problem with memory. The tasks are CPU-bound. But it's also not so heavy that a t2.micro instance is enough to handle it as long as it only processes one at one time.
I got into a discussion with a colleague about which one is better. I prefer the 100 instances because I think the Docker isolation will be a significant overhead. It's like you have only one resource, but it's split into 100 people who needs to use the resource. On the other side, my colleague makes a point which I think might be valid. Creating a Linux namespace is lighter than starting a whole OS. So if we have 100 machines, we have 100 OSes, while with a big machine, we only have 1 OS.
The thing is, I don't know which one is correct. Could someone who have knowledge in this explain which one would be better and give me a concrete reason?
Since I realized I have just asked a bad question, I will try to add more information here. To make the question more precise, I am not really asking which one will be better in my specific use case, or which is cheaper. It's just a curiosity which one will perform better in terms of CPU. Just imagine we have a very big computational problem, and we have to do 100 of them. We want to parallelize them, but they are not thread-safe. Is it better to do them in 100 small machines or 1 powerful machines with 100 containers? Which one will complete faster and why?
If we have only 1 powerful machines, will all these 100 containers not be fighting for resource and slow down the overall process? And if it's 100 small machines, maybe the overall performance will be slower because of the OSes or other factors? In any case, I don't have any experience with this. Of course I could try this, but in the end, since it's not the ideal environment (with a lot of factors), the result won't be authoritative anyway. I was looking for an answer from people who knows how both things work in low level and could argument which environment will complete the task faster.

A: The only "appropriate" answer to your question is: you have to test both options and find out which one is better. The reason for this is: you are running a very specific application, with a very specific workload and very specific requirements. Any recommendation without actual testing is a guess. Maybe an "educated guess", but not more than that.

That said, let me show you what I would consider when doing my analysis for such a scenario.

*

*The docker overhead should be absolutely minimal. The tool "docker" itself is not doing anything -- it's just using regular Linux Kernel features to create an isolated environment for your application.

*After the OS has booted up, it will consume some memory, true. But the CPU consumption by the OS itself should be negligible (even for very small instances). Since you mentioned that you don't have any problems with memory, it seems like we can assume that this "OS overhead" that your colleague mentioned would also probably be negligible.

*If you consider the route "a lot of very small instances", you could also consider using the recently released t2.nano instance type. You need to test if it has enough resources to actually run your application.

*If you consider the route "one single very large instance", you should also consider the c4.8xl instance. This should give you significantly more CPU power than the c3.8xl.

*Cost analysis (prices in us-east-1):

*

*1x c3.8xlarge: 1.68 $/h

*1x c4.8xlarge: 1.675 $/h (roughly the same as c3.8xl)

*100x t2.micro: 1.30 $/h (that is, 100x 0.013$/h = 1.30$/h)

*100x t2.nano: 0.65 $/h. (winner) (that is, 100x 0.0065$/h = 0.65$/h)

*Now let's analyze the amount of resources that you have on each setup. I'm focusing only on CPU and ignoring memory, since you mentioned that your application isn't memory hungry:

*

*1x c3.8xlarge: 32 vCPU

*1x c4.8xlarge: 36 vCPU (each one typically with better performance than the c3.8xl; the chip for c4 was specifically designed by Intel for EC2) (winner)

*100x t2.micro: 100x 10% of a vCPU ~= "10 vCPU" aggregate

*100x t2.nano: 100x 5% of a vCPU ~= "5 vCPU" aggregate

*Finally, let's analyze the cost per resource

*

*1x c3.8xlarge: 1.68$/h / 32 vCPU = 0.0525 $ / (vCPU-h)

*1x c4.8xlarge: 0.0465 $ / (vCPU-h) (winner)

*100x t2.micro: 0.13 $ / (vCPU-h)

*100x t2.nano: 0.13 $ / (vCPU-h)

As you can see, larger instances typically provide higher compute density which is typically less expensive.
You should also consider the fact that the T2 instances are "burstable", in that they can go beyond their baseline performances (10% and 5% as above) for some time, depending on how much "CPU credits" they have. However, you should know that, although they start with some credit balance, it's typically enough for booting up the OS and not much more than that (you'd accrue more CPU credits over time if you don't push your CPU beyond your baseline, but it seems that it won't be the case here, since we are optimizing for performance...). And as we have seen, the "cost per resource" is nearly 3x that of the 8xl instances, so this short burst that you'll get probably wouldn't change this rough estimate.
You might also want to consider network utilization. Is the application network intensive? Either in latency requirements, or bandwidth requirements, or in the amount of packets per second?

*

*The smaller instances have less network performance available, the larger instances have much more. But the network for each smaller instance would be used by one single application, while the powerful network of the larger instance would be shared among all the containers. The 8xl instances come with a 10Gbps network card. The t2 instances have very low network performance compared to that.

Now, what about resiliency? How time-sensitive are these jobs? What would be the "cost of not finishing them in a timely manner"? You might also want to consider some failure modes:

*

*What happens if "one single instance dies"? In the case of 1x c3.8xl or 1x c4.8xl, your whole fleet would be down, and your workers would stop. Would they be able to "recover"? Would they need to "restart" their work? In the case of "a lot of small instances", well, the effect of "one single instance dying" might be much less impactful.

To reduce the effect of "one single instance dying" on your workload, and still get some benefits from higher density compute (ie, large c3 or c4 instances), you could consider other options, such as: 2x c4.4xl, or 4x c4.2xl, and so on. Notice that the c4.8xl costs twice the c4.4xl but it contains more than twice the number of vCPUs. So the analysis above wouldn't be "linear", you'd need to recalculate some costs.
Assuming that you are OK with instances "failing" and your application can somehow deal with that -- another interesting point to consider is using Spot instances. With Spot instances, you name your price. If the "market price" (regulated by offer - demand) is below your bid, you get the instance and pay only the "market price". If the price fluctuates above your bid, then your instances are terminated. It's not uncommon to see up to 90% discounts when compared to On Demand. As of right now, c3.8xl is approximately 0.28$/h in one AZ (83% less than On Demand) and c4.8xl is about the same in one AZ (83% less as well). Spot pricing is not available for t2 instances.
You can also consider Spot Block, in which you say the number of hours you want to run your instances for, you'll pay typically 30% - 45% less than On Demand and there's no risk of getting "out bided" during the period you specified. After the period, your instances are terminated.
Finally, I would try to size my fleet of servers so that they are required for nearly a "full number of hours" (but not exceeding that number) (unless I'm required to finish execution ASAP). That is, it's much better to have a smaller fleet that will finish the jobs in 50 minutes than a larger one capable of finishing the job in 10 minutes. The reason is: you pay by the hour, at the beginning of the hour. Also, it's typically much better to have a larger fleet that will finish the job in 50 minutes than a smaller one that would require 1h05 minutes -- again, because you pay by the hour, at the beginning of the hour.

Finally, you mention that you are looking for "the best performance". What exactly do you mean by that? What is your Key Performance Indicator? Do you want to optimize to reduce the amount of time spent in total? Maybe reduce the amount of time "per unit"/"per job"? Are you trying to reduce your costs? Are you trying to be more "energy efficient" and reduce your carbon footprint? Or maybe optimize for the amount of maintenance required? Or focus on simplifying to reduce the ramp-up period that other colleagues less knowledgeable would require before they would be able to maintain the solution?
Maybe a combination of many of the performance indicators above? How would they combine? There's always a trade off...
As you can see, there isn't a clear winner. At least not without more specific information about your application and your optimization goals. That's why most of the time the best option for any kind of performance optimization is really testing it. Testing is also typically inexpensive: it would require maybe a couple hours of work to setup your environment, and then likely less than $2/h of test.
So, that should give you enough information to start your investigation.
Happy testing!

A: Based on EC2 instances CPU alone

*

*100 t2.micro's have less than a 1/3 of the CPU power of the c4.8xl

*100 t2.small's have less than 2/3's

*50 t2.large's might be getting close.

It's fairly likely the c4.8xl would be a lot quicker but there's no way anyone can authoritatively say that. As Bruno starts with, you need to run your workload through your app on both instance types to see. There are 1000's of variables that could affect the results. There's no immediate reason you can't run 100 containers/processes on a linux host, it's been doing multi core, multi process for a long time. There may be some simple system limits that need to be tuned as you go (ulimit -a and sysctl -a). On the other hand there might be something in your application performs really badly in this setup.
Any Docker overhead pretty much cancels out as you run a container in both your single and multi instance setup. Anything you can improve in this area is going to help limit the issues you run into on the shared host. IBM published a great report An Updated Performance Comparison of Virtual Machines and Linux Containers detailing Docker overheads.

*

*Container overhead will be negligible for CPU/Memory.

*NAT networking includes some overhead so use net=host.

*AUFS disk will incur overhead. For anything write intensive mount your hosts EBS/SSD directly into the container.

One big difference with many Docker containers is the workload on the VM's process scheduler will be completely different. It's not necessarily going to be any worse when running more containers but you are heading into "less tested" territory. You rely less on the Xen hypervisor running on hardware and more on the linux kernel running inside the VM for scheduling which use two completely different algorithms. Again, Linux is capable of running many processes and dealing with contention but you're only going to find the answer for your app by testing it.
So at a complete guess, not taking your application into account in any way, purely on general machine specs and a CPU heavy workload.

*

*The c4.8xl should be quicker than a t2.nano and t2.micro setup.

*t2.smalls might get close.

*50 x t2.larges with 2 containers might be on par.

*100 x m3.mediums would blitz it.

*3 x c4.8xl's would give you the quickest processor hyper thread dedicated to each process/thread of your app.

tl;dr Test them all. Use the quickest.

A: In a general case, I would use docker. Simply because it easier and faster to add/change/remove nodes and do load balancing. I am assuming here that you do not need exactly 100 nodes, but rather a changing number of them.
It is also much faster to setup. There is a thing called docker swarm https://docs.docker.com/swarm/overview/ and I'm sure it's worth looking into. Additionally, if you can't put a 100 or 1000 or 10000 containers on one physical machine (VM even?) you can also distribute it with overlay network https://docs.docker.com/engine/userguide/networking/dockernetworks/#an-overlay-network
EDIT: after re-reading the question it seems that you want a more of a performance-wise answer. It's really hard to say (if not impossible) without testing. With performance there are always caveats and things you can't think of (on a simple account of being human:) ).
Again to set up 100 or 3 or 999999 machines is much more time then setting up the same number of docker containers. I know that container/image terminology still gets mixed up, so just to clarify - you would create one docker image, which is some work, and than run it in N instances (which are containers). Someone please correct me for the terminology thing if I am wrong - this is something that I often discuss with colleagues :)


text:
Q: Subsection with only numbering I'm TeXing the paper Sur un r ́esultat de Waldspurger by Jacquet, and I found that the paper has the following format:

Here (3.2) stands for the subsection 3.2, and the equation numbering 3.1.11 comes from subsection and corresponding number of it. I know how to handle (3.1.11) for the equation, but I have no idea how to do such a numbering for subsection (3.1). I found this answer which remove subsection title, but then I have to manually put the numbers.

Edit: here are some more about what I've done. As I said, I used the solution in the above linked answer
\newcommand{\fakesubsection}[1]{%
  \par\refstepcounter{subsection}% Increase subsection counter
  \subsectionmark{#1}% Add subsection mark (header)
  \addcontentsline{toc}{subsection}{\protect\numberline{\thesubsection}#1}% Add subsection to ToC
  % Add more content here, if needed.
}

and put this for each subsection. This somewhat generate ghost subsection, which does not have titles but still counts well. Now I want to add small numbering as in the picture I uploaded above, like (3.2) in the second paragraph. I'm using article class but it doesn't matter for me to change this to anything else. Just want to have a consistent numbering as the original paper (link).

A: You can use titlesec.
\documentclass[leqno]{article}
\usepackage{amsmath}
\usepackage{titlesec}

\titleformat{\subsection}[runin]
 {\normalfont\normalsize}
 {(\thesubsection)}
 {0pt}
 {}
\titlespacing{\subsection}
 {\parindent}% space before the title
 {\topsep}% vertical space above subsections
 {\fontdimen2\font}% a normal space

\labelformat{equation}{\thesubsection.\theequation}
\counterwithin{equation}{subsection}
\renewcommand{\theequation}{\arabic{equation}}

\begin{document}

\setcounter{section}{2} % just to reproduce your numbers

\section{Test}

\subsection{}
\setcounter{equation}{10} % just to reproduce your numbers

some text for the subsection some text for the subsection
some text for the subsection some text for the subsection
some text for the subsection some text for the subsection
some text before the equation some text before the equation
some text before the equation some text before the equation
some text before the equation some text before the equation
\begin{equation}\label{test}
1=1
\end{equation}

\subsection{}

some text for the subsection with \eqref{test} some text for the subsection
some text for the subsection some text for the subsection
some text for the subsection some text for the subsection
some text for the subsection some text for the subsection

\end{document}

If some of your subsections have a title, it can be managed, but you should point out the desired format.


text:
Q: arch linux hdmi not detected today I started my laptop, but my external display was not working. I ran the command xrandr:
Screen 0: minimum 8 x 8, current 1366 x 768, maximum 32767 x 32767
eDP1 connected primary 1366x768+0+0 (normal left inverted right x axis y axis) 340mm x 190mm
   1366x768      59.97*+
   1280x720      59.74
   1024x768      60.00
   1024x576      60.00    59.90    59.82
   960x540       60.00    59.63    59.82
   800x600       60.32    56.25
   864x486       60.00    59.92    59.57
   640x480       59.94
   720x405       59.51    60.00    58.99
   680x384       60.00
   640x360       59.84    59.32    60.00
VIRTUAL1 disconnected (normal left inverted right x axis y axis)

As you can see, there is no hdmi. When I run this exact same command on my other computer, it shows this:
Screen 0: minimum 8 x 8, current 1366 x 768, maximum 32767 x 32767
eDP1 connected primary 1366x768+0+0 (normal left inverted right x axis y axis) 340mm x 190mm
   1366x768      59.97*+
   1280x720      59.74
   1024x768      60.00
   1024x576      60.00    59.90    59.82
   960x540       60.00    59.63    59.82
   800x600       60.32    56.25
   864x486       60.00    59.92    59.57
   640x480       59.94
   720x405       59.51    60.00    58.99
   680x384       60.00
   640x360       59.84    59.32    60.00
DP1 disconnected (normal left inverted right x axis y axis)
DP2 disconnected (normal left inverted right x axis y axis)
HDMI1 disconnected (normal left inverted right x axis y axis)
HDMI2 disconnected (normal left inverted right x axis y axis)
VIRTUAL1 disconnected (normal left inverted right x axis y axis)

my os: Linux acer-a515 5.7.12-arch1-1 #1 SMP PREEMPT Fri, 31 Jul 2020 17:38:22 +0000 x86_64 GNU/Linux
Can someone help me?

A: I had the exact same issue. No HDMI output on Linux and Windows installation after a full system upgrade on Linux.
It turned out the latest version of GRUB (version 2.04-8) interferes with the HDMI ports on some laptops, so you need to boot into Linux and downgrade it back to 2.04-7 or lower.
On Arch, you can load the old package from the pacman cache:
cd /var/cache/pacman/pkg
sudo pacman -U grub-2:2.04-7-x86_64.pkg.tar.zst


text:
Q: VueJs passing empty Prop Object to sub component I have a UserProfile component with data as follows that works fine:
export default {
  name: 'UserProfile',
  data () {
    return {
      user: {}
    }
  },
...

I have a subcomponent UserItems that I want to call with a prop for this.user
like:
<UserItems :user="this.user" \>

When I hardcode this.user as {id:1}, everything works downstream
However, otherwise, UserItems component is receiving an empty object.
Here is my UserItems component:
<template>

      <NewItem  v-on:item-created="getOwnedItems(user.id)" />

Your Items:

        <Item v-for="(item, i) in items" :key="`${i}-${item.id} `" :item="item" v-on:item-deleted="getOwnedItems"/>

</template>

This is the axios request:
fetchOwnedItems (params) {
    console.log('services params is: ', params)
    return axios.get('items/by_user/' + params)
  },

This is the express route:
router.get('/by_user/:id', auth.required, async (req, res) => {
  console.log('this is params on getOwned items', req.params)
  const items = await Item
    .query()
    .where('users_id', req.params.id)
    .orderBy('title');
  res.json(items);
});

The Vue console shows:
this.user is:  {__ob__: Observer}
How do I pass the same User from UserProfile?


text:
Q: How to define nulls for @Id field in Resultsetmapping? I have a query like this:
SELECT sender, sum(size) AS size,COUNT(*) AS count FROM inmail
WHERE  ( date > '2011.06.01' AND w.l_date < '2011.06.10' )
GROUP BY sender ORDER BY count DESC;

and its corresponding Entity class is this:
@Entity
@Stateless
@Cacheable(false)
@Cache(type = CacheType.NONE,alwaysRefresh=true, shared=false, expiry=1, size=0)
@SqlResultSetMappings({
    @SqlResultSetMapping(name = "ReportsResultMapping",
    entities = {
        @EntityResult(entityClass = ReportsResultMap.class,
        fields = {
            @FieldResult(name = "sender", column = "sender"),
            @FieldResult(name = "size", column = "size"),
            @FieldResult(name = "count", column = "count")
        })})
})
public class ReportsResultMap implements Serializable {

    @Id
    protected String sender;
    protected BigDecimal size;
    protected BigDecimal count;
...
}

Here comes the problem: The sender row in my table sometimes is null and query returns something like this:
sender             size         count
------------------+------------+------------
                  | 3743040708 |  69
 Phrase1          |    1332377 |  13
 Phrase2          |          0 |  1
 Phrase3          |          0 |  1

this causes problem in my EJB mapping because sender field is defined as @Id and as a result server throws null pointer exception (saying that an ID field can not be null).
I am pretty sure this might be a general problem but I don't know how to phrase this problem to google it. Does anyone have a solution or workaround reccommendation for this problem? I tried to define size as @Id but I know this is not a good solution.
Thanks in advance.


text:
Q: Criterion for parabolic Kazhdan-Lusztig polynomials to be monic power of $q$ Let $(W,S)$ be a Coxeter system, $I\subseteq S$, $W^I=\{w\in W: sw>w,\ \forall s\in I\}$, $P^{I,q}_{x,w}(q)$ be the parabolic Kazhdan-Lusztig polynomial of $W^I$ of type $q$.
In KAZHDAN–LUSZTIG AND R-POLYNOMIALS,
YOUNG'S LATTICE, AND DYCK PARTITIONS and PARABOLIC KAZHDAN-LUSZTIG POLYNOMIALS
FOR HERMITIAN SYMMETRIC PAIRS by Francesco Brenti, we have the following result:

I would like to know that whether there is a sufficient and necessary condition of the statement: $P^{I,q}_{x,w}(q)=q^r$ for some $r\ge 0$, without the assumption $(W,W_I)$ is Hermitian symmetric pair.


text:
Q: Can someone help me figure out why my code isn't working properly? #include <iostream>
using namespace std;

int fight();
int lowblow();
int eyes();

int run();
int underground();
int officebuilding();
int main()
{
    int choice1;
    int fchoice2, fchoice3;
    int rchoice2, rchoice3;
    cout << "As you're walking down the street you feel somebody grab your shoulder, when you turn around to see. You notice the person is holding a knife towards you and demanding for your valuables." << endl;
    cout << "Do you fight or run?" << endl;
    cout << "1 - Fight" << endl;
    cout << "2 - Run" << endl;
    cin >> choice1;
    while (choice1 != 1 && choice1 != 2) {
        cout << "Do you fight or run? " << endl;
        cout << "1 - Fight" << endl;
        cout << "2 - Run" << endl;
        cin >> choice1;
    }

    if (choice1 == 1) {
        fchoice2 = fight();
        while (fchoice2 != 1 && fchoice2 != 2) {
            fchoice2 = fight();
        }
        if (fchoice2 == 1) {
            fchoice3 = lowblow();
            while (fchoice3 != 1 && fchoice3 != 2) {
                fchoice3 = lowblow();
            }
        }
        if (fchoice2 == 2) {
            fchoice3 = eyes();
            while (fchoice3 != 1 && fchoice3 != 2) {
                fchoice3 = eyes();
            }

            if (choice1 == 2) {
                rchoice2 = run();
                while (rchoice2 != 1 && rchoice2 != 2) {
                    rchoice2 = run();
                }
                if (rchoice2 == 1) {
                    rchoice3 = underground();
                    while (rchoice3 != 1 && rchoice3 != 2) {
                        rchoice3 = underground();
                    }
                    if (rchoice3 == 1) {
                        officebuilding();
                    }
                }
            }
        }
    }
}

int fight()
{
    system("clear");
    int c2;
    cout << "You choose to fight off the attacker and suddenly all those self-defense classes come rushing into your mind.As you fight to defend yourself, you find yourself getting outmatched and have to try something drastic to survive." << endl;
    cout << "1 - Go for the low blow" << endl;
    cout << "2 - Go for the eyes " << endl;
    cin >> c2;
    return c2;
}
int lowblow()
{
    system("clear");

    cout << "You catch your attacker off guard and land the hit, to your surprise the attack proves ineffective.In retaliation you get hit so hard that you start seeing stars and soon blackout leaves you defenseless.Now you are knocked out and getting your valuables taken." < endl;

    cout << "The End" << endl;
    return 0;
}

int eyes()
{
    system("clear");

    cout << "Using the element of surprise to try fighting back gave you no advantage, so you resort to another tactic. You've seen it in movies and it always worked out there. You decide to go for the eyes and to your surprise it works. You use this opportunity to escape and get to safety, all while keeping your valuables safe. "<< endl;
    cout << "The End" << endl;
    return 0;
}
int run()

{
    system("clear");
    int c2;
    cout << " While running down the street to loose the attacker, you noticed that there was an underground subway a little down the road.Immediately to your left there is an office building you could run into and try to lose your attacker there."<< endl;
    cout << "1 - Underground ?" << endl;
    cout << "2- office building?" << endl;
    cin >> c2;
    return c2;
}

int underground()
{
    system("clear");

    cout << "As you make your way towards the underground subway station you notice rushing out.In a desperate attempt to reach safety,        you run down the stairs while narrowly avoiding others.Upon arriving at the station you look back and notice that you lost your attacker.You are safe now.";
    cout << "The End" << endl;
    return 0;
}
int officebuilding()
{
    system("clear");
    cout << "A spontaneous decision leads you into an office building, while it may look safe, upon entering you notice everything is silent as the building seems to be completely empty.None of it matters however, since you have to escape at any cost in order.While trying to find a good way to lose the attacker you hear footsteps behind you.The attacker has cornered you and has taken your valuables." << endl;
    cout << "The End" << endl;
    return 0;
}

I am suppose to be writing a branching-path story. I am not sure why after I pick a choice it starts flashing and for the other choice it isn't even working. I'm not exactly sure where to fix these errors in the code. I'm not sure if I messed up somewhere in the functions or while loop. I've tried changing some things around but nothing seems to work.

A: You are calling underground() in a while-loop waiting for rchoice3 to be 1 or 2, but underground() always returns 0, so rchoice3 is always 0..
while (rchoice3 != 1 && rchoice3 != 2) {
   rchoice3 = underground();
}

I think you need to change this block:
                if (rchoice2 == 1) {
                    rchoice3 = underground();
                    while (rchoice3 != 1 && rchoice3 != 2) {
                        rchoice3 = underground();
                    }
                    if (rchoice3 == 1) {
                        officebuilding();
                    }
                }

To:
                if (rchoice2 == 1) {
                    underground();
                } else {
                    officebuilding();
                }


text:
Q: Call method in Linq Select() without loading whole object I have the following code using .NET 5 and EF Core:
IQueryable<ExampleViewModel> list = query.Select(x => new ExampleViewModel()
{
  Id = x.Id,
  BindDate = x.BindDate,
  CancellationDate = x.CancellationDate,
  ChangeDate = x.ChangeDate,
  CreateDate = x.CreateDate,
  Description = x.Description,
  PrimaryOffice = x.PrimaryOffice == null
        ? null
        : new GenericComboBox()
        {
          Value = x.PrimaryOffice.Id,
          Text =x.PrimaryOffice.LocationName
          + (x.PrimaryOffice.LocationBusinessName == null ? "" : " (" + x.PrimaryOffice.LocationBusinessName + ") ")
          + "("
          + (x.PrimaryOffice.AddressLine1 != null ? x.PrimaryOffice.AddressLine1 + ", " : null)
          + (x.PrimaryOffice.AddressLine2 != null ? x.PrimaryOffice.AddressLine2 + ", " : null)
          + (x.PrimaryOffice.City != null ? x.PrimaryOffice.City + ", " : null)
          + (x.PrimaryOffice.State != null ? x.PrimaryOffice.State.Name != null ? x.PrimaryOffice.State.Name + ", " : null : null)
          + (x.PrimaryOffice.ZipCode ?? null)
          + ")"
        }
});

The query you see for PrimaryOffice is going to be used for several more objects just as it is. 100% same. So I want to move the query after the

PrimaryOffice =

to method so I can re use it easy. So far so good.
The problem is I cant simply create method which takes x.PrimaryOffice as param and return PrimaryOffice  class ( GenericComboBox ), because that will load my whole 'x' object.
This is NOT an option:
public static GenericComboBox GenericComboBoxCreate(AddressObj x)
{
  if (x != null)
  {
    return new GenericComboBox()
    {
      Value = x.Id,
      Text = x.LocationName
        + ( x.LocationBusinessName == null ? "" : " (" + x.LocationBusinessName + ") " )
        + "("
        + ( x.AddressLine1 != null ? x.AddressLine1 + ", " : null )
        + ( x.AddressLine2 != null ? x.AddressLine2 + ", " : null )
        + ( x.City != null ? x.City + ", " : null )
        + ( x.State != null ? x.State.Name != null ? x.State.Name + ", " : null : null )
        + ( x.ZipCode ?? null )
        + ")"
    };
  }

  return null;
}

And then:
PrimaryAgencyOffice = SomeHelper.GenericComboBoxCreate(x.PrimaryOffice)

I use Odata and I need to take from the DB only the properties I really need.
Because If I use the method above EF loads EVERYTHING and the query is far from optimal.
I think some method with Expression<Func< , >> should be the solution but I can`t figure it out so far.
If it was about the WHOLE Select() statement that would be easy. But it is about one property in the Select.
I guess some method with Expression<Func<AgencyAddress, GenericComboBox>> as param and return type GenericComboBox?

A: Looks like you just need a helper method to format your GenericComboBox.Text. How about a static utility method to do so?

public static string GetAddressString(string locationName, string locationBusinessName, string addressLine1, string addressLine2, string city, string state, string zip)
{
    string txt = "{0}{1}({2}{3}{4}{5}{6})";
    locationBusinessName = string.IsNullOrEmpty(locationBusinessName) ? string.Empty : string.Format(" ({0})", locationBusinessName);
    addressLine1 = string.IsNullOrEmpty(addressLine1) ? string.Empty : string.Format(", {0}", addressLine1);
    addressLine2 = string.IsNullOrEmpty(addressLine2) ? string.Empty : string.Format(", {0}", addressLine2);
    city = string.IsNullOrEmpty(city) ? string.Empty : string.Format(", {0}", city);
    state = string.IsNullOrEmpty(state) ? string.Empty : string.Format(", {0}", state);
    zip = string.IsNullOrEmpty(zip) ? string.Empty : string.Format(", {0}", zip);
    return string.Format(
                txt,
                locationName,
                locationBusinessName,
                addressLine1,
                addressLine2,
                city,
                state,
                zip
            );
}

Then you can just call it like this:
IQueryable<ExampleViewModel> list = query.Select(x => new ExampleViewModel()
{
  .  .  .  .

  PrimaryOffice = x.PrimaryOffice == null ? null : new GenericComboBox()
  {
      Value = x.PrimaryOffice.Id,
      Text = SomeHelper.GetAddressString(
          x.PrimaryOffice.LocationName,
          x.PrimaryOffice.LocationBusinessName,
          x.PrimaryOffice.AddressLine2,
          x.PrimaryOffice.City,
          x.PrimaryOffice.State ? x.PrimaryOffice.State.Name: string.Empty,
          x.PrimaryOffice.ZipCode
       )
    }
});

You can even put the GetAddressString method inside your PrimaryOffice class:
public class PrimaryOffice {
    //... your properties....

    public string GetAddressString()
    {
        string txt = "{0}{1}{2}{3}{4}{5}{6}";
        string locationBusinessName = string.IsNullOrEmpty(this.LocationBusinessName) ? string.Empty : string.Format(" ({0})", this.LocationBusinessName);
        string addressLine1 = string.IsNullOrEmpty(this.AddressLine1) ? string.Empty : string.Format(", {0}", this.AddressLine1);
        string addressLine2 = string.IsNullOrEmpty(this.AddressLine2) ? string.Empty : string.Format(", {0}", this.AddressLine2);
        string city = string.IsNullOrEmpty(this.City) ? string.Empty : string.Format(", {0}", this.City);
        string state = string.IsNullOrEmpty(this.State) ? string.Empty : string.Format(", {0}", this.State.Name);
        string zip = string.IsNullOrEmpty(this.Zip) ? string.Empty : string.Format(", {0}", this.Zip);
        return string.Format(
            txt,
            this.LocationName,
            locationBusinessName,
            addressLine1,
            addressLine2,
            city,
            state,
            zip
        );
    }
}

Then just access it like:
  PrimaryOffice = x.PrimaryOffice == null ? null : new GenericComboBox()
  {
      Value = x.PrimaryOffice.Id,
      Text = x.PrimaryOffice.GetAddressString()
  }

OR you could add a custom Getter for something like PrimaryOfficeName in your PrimaryOffice class:

A: One of the solutions is to use LINQKit for such task.
Enable extension while building options:
builder
    .UseSqlServer(connectionString)
    .WithExpressionExpanding(); // enabling LINQKit extension

Implement your method in the following way:
[Expandable(nameof(GenericComboBoxCreateImpl))]
public static GenericComboBox GenericComboBoxCreate(this AddressObj x)
    => throw new NotImplementedException();

private static Expression<Func<AddressObj, GenericComboBox>> GenericComboBoxCreateImpl()
{
  return x => x == null ? null :
    new GenericComboBox()
    {
      Value = x.Id,
      Text = x.LocationName
        + ( x.LocationBusinessName == null ? "" : " (" + x.LocationBusinessName + ") " )
        + "("
        + ( x.AddressLine1 != null ? x.AddressLine1 + ", " : null )
        + ( x.AddressLine2 != null ? x.AddressLine2 + ", " : null )
        + ( x.City != null ? x.City + ", " : null )
        + ( x.State != null ? x.State.Name != null ? x.State.Name + ", " : null : null )
        + ( x.ZipCode ?? null )
        + ")"
    };
}

And benefits from usage:
IQueryable<ExampleViewModel> list = query.Select(x => new ExampleViewModel()
{
  Id = x.Id,
  BindDate = x.BindDate,
  CancellationDate = x.CancellationDate,
  ChangeDate = x.ChangeDate,
  CreateDate = x.CreateDate,
  Description = x.Description,
  PrimaryOffice = x.PrimaryOffice.GenericComboBoxCreate()
});


text:
Q: How can I create a Model that will take any other model or standard dict as a property using Pydantic's BaseModel? Given a FastAPI Pydantic model MessageWrapper *untested:
class MessageWrapper(BaseModel):
    id: str = ids.get_time_sequential_uuid(datetime.datetime.utcnow())
    body: Union[DataMin, DataMax] = None
    created_by_app: Optional[AnyStr]
    created_by_app_version: Optional[AnyStr]
    created_at_utc: datetime = datetime.datetime.utcnow()

The MessageWrapper.body property expects a DataMin or DataMax model. How can I change this to take either an unvalidated standard Dict or ANY model (not just DataMin or DataMax).
My initial attempts ran into quite a few scenarios where Pydantic threw warnings for not properly defining the type of the body property. I expect to either pass standard dicts or models through this wrapper prior to the data being supplied through an API endpoint.
Ultimately the compiled nested dict would be received by the requestor and they could always expect to access the top level fields, while the body field could be any nested dictionary.
I am interested in functionality similar to Maxwell's Daemon where json data is inserted into a standard dictionary that includes metadata about the message itself.
It seems there would be times when it is OK to designate a property with Type (from typing import Type) to avoid validation, and other times where we'd always validate on all properties.
How can I create a Model that will take any other model or standard dict as a property using Pydantic's BaseModel?


text:
Q: Youtube API: upload a remote video I was able to programmatically upload a local video to youtube using the example at the bottom of https://developers.google.com/youtube/v3/docs/videos/insert.
However, when I try to upload a remote video file, I get the following error message:
"A service error occurred: Failed to parse Content-Range header"
I want to use a full url instead of a path here:
$videoPath = "/path/to/file.mp4";
vs.
$videoPath = "http:www.example.com/path/to/file.mp4";
Is this possible?

A: Not supported as of now. Even the main Youtube channel website asks you to upload a video from your device (PC/mobile) and not from a remote URL.


text:
Q: How to deal with multiple scripts in a single page web application Am new to Web development and i started an application where i have index.php with a menu and a div called #content and i load all the different pages in to the div #content using load(); I need to load the respective java script files along with the files that are being loaded in to the div #content.
Issue: Here in the HTML's that is loaded in to the div, i have some similar class names and id's so when i click on any menu item and perform some action there and go to another menu item and perform same action i get the script of previous menu item is being executed!
Is there a better way to load scripts into the div on the menu item click and on click of another menu item remove the previous scripts and load a fresh scripts from the current menu item clicked?
Script i use to load the div #content:
$('.nav-button').on('click', function(e){
e.preventDefault();
$('#content').load('../scripts/loader.php');
$('#content').load($(this).attr('href'));
});

sample1.php page i load in to the div on menu-item1 clicked:

<input></input>
<input></input>
<input></input>

sample2.php page i load in to the div on menu-item2 clicked:

<input></input>
<input></input>
<input></input>

A: Another way of loading scripts:
var script = document.createElement("script");
script.type = "text/javascript";
script.src = src;
script.onload = callback_function;

document.getElementsById("#scriptContainer")[0].appendChild(script);

Regarding the removal of existing scripts:
Try loading your scripts in a certain container and when you want to replace them just clear out the container content and load your new scripts.
You could also try lazy loading using requirejs. Example here

A: Once a script has been loaded and executed, unless you tidy up your code by yourself, you will still have remnants of that code existing - even if you delete/remove the original script tag. The following points should help:

*

*Whenever you create/import a structure in js, make sure you have coded an unimport / destroy ability.

*Do not rely on script tags inserted via .innerHTML or $().html() - older browsers do not respect them and this can cause unexpected results - i.e. script tags being ignored, or in the case of older Internet explorer, attempted to be loaded from the wrong place.

*Instead do as thedev recommends and build your script tags programmatically.

*Obviously #3 is tricky if you want to have each ajax'd script returning it's associated script tags.

*So instead of returning pure HTML with your ajax request, instead return a JSON object that contains HTML and a list of script paths that need to be loaded.

*If you make sure that each of your loaded scripts keeps all of it's methods exposed via a particularly named object, you can then remove this object the next time you load your next script.

What follows is illustrative code, there are more complicated (and better) ways of handling this (i.e. avoiding storing objects on the window), plus the following code could be improved in many places - it should only serve to give you an idea of what you could do, and how to think about it.
Also it should be noted, when storing objects on the global window object you should use more unique names than one, two or three ;)
markup:

One Link

Two Link

Three Link

  ...

javascript:
/// create a wrapping scope so that our variables can be local
/// to our internal code, but not mess around with the global space.
(function(){

  /// create a remembered lastID var that can store what item was loaded
  var lastID;

  /// an addScripts function that takes a string namespace (can be anything
  /// as long as it obeys usual javascript variable naming rules), and an
  /// array of script URIs.
  var addScripts = function(namespace, scripts){
    var s,i;
    for( i=0; i


text:
Q: Return column 1 if column 2 has one missing match despite other matches I hope this makes better sense when I show the table. I have a table like the below

column1
column2

machine1
KB4534170

machine1
KB4534171

machine1
KB4534172

machine2
KB4534171

machine2
KB4534172

machine3
KB4534171

I want to search for KB4534170 and only return machine machine 2 and 3 where KB4534170 is not present at all. machine1 also have row where KB4534170 is not present so my search keeps returning machine1 as well. Any help would be much appreciated.

A: This is done using a LEFT JOIN:
select m1.*
from mytable1 m1
left join mytable1 m2 on m1.column1=m2.column1
                     and m2.column2='KB4534170'
where m2.column1 is null;

This will return:
+----------+-----------+
| column1  | column2   |
+----------+-----------+
| machine2 | KB4534171 |
| machine2 | KB4534172 |
| machine3 | KB4534171 |
+----------+-----------+

If you only want a list with column1, you can do:
select distinct m1.column1
from mytable1 m1
left join mytable1 m2 on m1.column1=m2.column1
                     and m2.column2='KB4534170'
where m2.column1 is null;

A: Also possible to do it as such:
SELECT column1
 FROM mytable
 GROUP BY column1
HAVING FIND_IN_SET('KB4534170',GROUP_CONCAT(column2))=0;

Basically GROUP_CONCAT(column2) will return something like this:

column1
GROUP_CONCAT(column2)

machine1
KB4534170,KB4534171,KB4534172

machine2
KB4534171,KB4534172

machine3
KB4534171

Then we'll use FIND_IN_SET() function to lookup for KB4534170, which will return something like:

column1
GROUP_CONCAT(column2)
FIND_IN_SET('KB4534170',GROUP_CONCAT(column2))

machine1
KB4534170,KB4534171,KB4534172
1

machine2
KB4534171,KB4534172
0

machine3
KB4534171
0

Whereby 1 means that the value exists in the comma-separated GROUP_CONCAT(column2) result while 0 means otherwise.
Demo fiddle


text:
Q: Does the late 2013 Retina Macbook Pro Support PCI-E SSDs? I'd like to upgrade my late 2013 retina Macbook Pro with a M.2 PCI-E SSD. Is this possible? Do I need an adapter?

A: As you can see in the image below from ifixit, the 2013 Retina Macbook Pro does have a kind of M.2 PCI-E SSD. (It is the black rectangle the person is holding.)

However Apple uses proprietary firmware on those SSDs, so only SPECIFICALLY Mac compatible drives will work such as these these and these.
This Ifixit guide shows you how to install a new drive, and links to a page that lets you purchase a compatible drive.


text:
Q: Can't get my script (jquery) to insert text from frame 1 into textarea in frame 2. I have been trying to get this going without success--performed advanced search unsuccessfully.  Current setup is as follows:   I cannot figure out how to link the frames together so when I click the list in the first frame, the text is inserted and shows up in the second frame text area.  I know there must be an easier way to do this that I am missing.  Thank you!
         index.html (frameset)
              |
              |
            /   \
           /     \
     group_a.html    group_b.html

**index.html**

<frameset cols="60%,40%" FRAMEBORDER=NO FRAMESPACING=0 BORDER=0>>
  <frame src="group_a.html">
  <frame src="group_b.html">
</frameset>

group_a.html
</style>

Text choice 1

Text choice 2

Text choice 3

 group_b.html

    <form>
      <textarea name="alltext" id="alltext" cols="60" rows="30">      </textarea>
  </form>

A: frame1 does not have access to the DOM of frame2. That means you can't manipulate the textarea using jQuery as you expect. instead, use postMessage to send a message between frames, and then in the second frame set up a listener for that message. when you receive it, set the text accordingly. Something like:
Frame 1
var msg = {
   message: "updateText",
   text: $(this).text()
};

top.frames["group_b.html"].postMessage(JSON.stringify(msg), '*');

Frame 2
window.addEventListener("message", receiveMessage, false);

function receiveMessage(event)
{
  if (event.data.message === "updateText"){
    $('#alltext').text(event.data.text);
  }
}

Note you'll have to place the code in places where the jQuery objects are in scope.

A: In a normal html https://jsfiddle.net/Cuchu/shs21jgs/ your javascript code needs to close properly.
$(document).ready(function(){
    $("li").click(function(){
        $('#alltext').append($(this).text());

        $("a").click(function(event){
            event.preventDefault();
            linkLocation = this.href;
          });
          function redirectPage() {
              top.frames["group_b.html"].location = linkLocation;
          };
    });
});


text:
Q: Set custom data- attributes on {{#linkTo}} helper  tag How can I set custom data- attribute on the {{#linkTo}} helper? I want use this:
{{#linkTo "foo" data-toggle="dropdown"}}foo{{/linkTo}}

and the result should look like this:
foo

but it looks like:
foo

How can I do this?

A: @intuitivepixel
Thanks
U helped a lot. With that Information I've played arround with the LinkView and was able to find a generic solution:
Em.LinkView.reopen({
    init: function() {
        this._super();
        var self = this;
        Em.keys(this).forEach(function(key) {
            if (key.substr(0, 5) === 'data-') {
                self.get('attributeBindings').pushObject(key);
            }
        });
    }
});

A: A way you could do this is to extend your Ember.LinkComponent to be aware of the new attribute:
Ember.LinkComponent.reopen({
  attributeBindings: ['data-toggle']
});

And then you can use it in your {{#link-to}} helper:
{{#link-to 'foo' data-toggle="dropdown"}}Foo{{/link-to}}

This will result in:
Foo

And since attributeBindings is an array your can put multiple attributes there that you might need:
attributeBindings: ['data-toggle', 'foo', 'bar']

Hope it helps.


text:
Q: Verify database is indexed by Elasticsearch I'm using Elasticsearch to index and search my db...

*

*How can I verify that the database is indexed?

*If I use the following command:
curl -XGET 'http://localhost:9200/_search?q=whatever'
the results are:
{
  "took": 4,
  "timed_out": false,
  "_shards": {
    "total": 6,
    "successful": 6,
    "failed": 0
  },
  "hits": {
    "total": 0,
    "max_score": null,
    "hits": []
  }
}

How should these results be interpreted?

A: You can get the list of indices present in your database using the command. You can see if your index is present in the list. That shows that index has been created.
curl -XGET 'localhost:9200/_cat/indices?v&pretty'

To check if there are any entries present in your Index. You can get the list of all the documents using this command.
curl -XGET 'localhost:9200/INDEX_NAME/_search?v&pretty'

In the question that you posted.
"_shards" {
    "total" : gives how many entries are present in your index (6 here)
  }
"hits" : {
    "total" : gives you the entries that matched your search with keyword whatever (0 here)
}

A: *

*To check if your db has been indexed, you can try the command:
curl -XGET 'http://localhost:9200/_aliases'?pretty=true
where you can see the list of indices and check if yours has been indexed.

*The command you used basically searches for the keyword "whatever" in all of the indices.
But it was not able to find anything. Hence you get the following output:
The search was successful (depicted by "took":4, "timed_out":false, "_shards":"total":6, "successful":6, "failed":0}) but it did not find anything (depicted by "hits":{"total":0,"max_score":null,"hits":[]})


text:
Q: ¿Como obtengo el valor mas alto en un hash de Ruby? Tengo este hash,
meses_ventas = {'Enero' => 2000, 'Febrero' => 3000, 'Marzo' => 1000, 'Abril' => 5000, 'Mayo' => 4000}

Y necesito obtener el valor mas alto entre todos los valores.
Resulta que intento iterarlo con each, pero no logro hacer que el valor mas alto del hash osea el 5000 del mes de Abril se almacene en una variable.

A: Puedes utilizar max_by que te va a regresar un array parecido a este: [llave, par]. Después llama únicamente el último elemento del array.
meses_ventas.max_by{ |llave, par| par }[-1]
# => 5000

Lo puedes 'leer' de la siguiente forma:
Al hash meses_ventas aplica max_by con los argumentos llave y par, y después regresa el que tenga el par mayor. Sólo llamamos par, pero como es max_by, sabemos que será el par mayor.
Finalmente, lo que regresa es un Array, en dónde el primer objeto es la llave y el último es el par. El [-1] se encarga de regresar el último elemento del array ['Abril', 5000], es decir, 5000.

A: Si solo necesitas obtener el valor más alto del hash (5000), lo mejor que puedes hacer es trabajar directamente con lo valores en vez de los pares clave-valor.
meses_ventas.values.max
# => 5000

values regresa un Array con todos los valores, y como en tu caso todos los values o pares son números (Integer), puedes utilizar el método max que regresa el objeto con el maximo valor.
Importante notar que el método max regresaría un error (ArgumentError) si tuvieras Integers y Strings combinados en los valores.
Saludos.


text:
Q: Fragment A calls fragment B - B does a popbackstack - where does it return in A I cant' find where it returns in Fragment A after a call to fragment B.
Fragment A calls fragment Test as follows:
btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                FragmentTransaction ft = getFragmentManager().beginTransaction();
Test test = new Test();
                ft.replace(R.id.container, test);
                ft.addToBackStack("test");
                ft.commit();
            }
        });

In Test I click on a button to return:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    Button btn = (Button) getActivity().findViewById(R.id.back);
    btn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            getActivity().getFragmentManager().popBackStackImmediate();
        }
    });
}

From there I thought that it was returning to Fragment A in onAttach, onResume but I don't see where it is returning in Fragment A?
   @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

A: PopBackStack() doesn't pop a fragment, it pops a fragment transaction.
So the last fragment transaction is reversed upon being called. If you are moving from FragmentA to FragmentTest then it would replace FragmentA with FragmentTest and add that transaction  to the back stack(not the fragment). If you then hit the back button, it pops the transaction off the back stack, which was "replace this FragmentA with a FragmentTest".
This instruction reverses the last transaction and removes it from the stack of transactions carried out. So onAttach wont be called and since your are replacing the fragment oncreateView will be called.
Edit:Use this function to check backstack is present and has your test fragment.
if (getSupportFragmentManager().getBackStackEntryCount() > 0 && getSupportFragmentManager().findFragmentById(R.id.your_container)!=null) {
     Fragment fragment= getSupportFragmentManager().findFragmentById(R.id.your_container);
      if(fragment.getClass().getSimpleName().equalsIgnoreCase(FragmentTest.class.getSimpleName())){
          getSupportFragmentManager().popBackStackImmediate();
        }
    }

A: Use
Log.d("Fragment", "Fragment A")

in onResume() method of Fragment A class. If control returns to Fragment A then this line will be shown in logcat.


text:
Q: Why does TS infer the type of an inline function but not that of an external function? function hof(cb: (a: string) => string): void {}

// @ts-expect-error
function someFunc(a) {
  return a.toUpperCase();
}

// Here TS has inferred that the inline function is of type
// (a: string) => string
hof((a) => a.toUpperCase());

// But here it doesn't
hof(someFunc);

In the above snippet TS can infer the type of the inline function (a) => a.toUpperCase() but it cannot infer the type of someFunc, why?

A: The inline function definition benefits from contextual typing; the context in which the function is defined gives the compiler a hint that it should be of type (a: string) => string, and thus that the function's first parameter will be of type string.
On the other hand, your someFunc definition has no such associated context.  It is a standalone function statement whose type needs to be determined by the compiler completely independently of whether or not you ever pass it to hof().  You could argue that the mere existence of hof(someFunc) somewhere in your program could be used as context for the definition of someFunc, but such analysis would be incredibly costly as well as surprising, since it would be highly nonlocal.  Thus the someFunc definition has no context for the a parameter, and it is implicitly given the any type (which is an error with the --noImplicitAny compiler option from the --strict suite of compiler features).

A: TypeScript knows that the argument hof tags is (value: string) => string, so when you have an inline function it can infer the argument from the context.
When you separate the function and store it in a variable, it is no longer associated with hof, so it doesn't.

A: The inline function is meant to be used only by hof, so TS can infer it's type safely.
But when the function is defined elsewhere and it's reference is passed to hof, TS cannot assume that the function is only meant to be used by hof because it can be used in other places as well. The only thing TS wants now is that the function that is being passed to hof is type compatible with what hof expects, in other words the type of the function being passed should be compatible with type: (a: string) => string.
And this becomes more clear when you observe the complaint by TS, the complaint is not at all related to hof, even if you remove all the other code and just have the someFunc function definition, TS would still be complaining, so there's no association between someFunc and hof and TS is simply complaining because of the implicit any type that the parameter a gets (refer to the --noImplicitAny compiler option).
If you explicitly state that argument a could be of type any, then there would be no complaints because (a: any) ⇒ string is compatible with (a: string) => string.
Finally, let's consider the following example:
function hof1(cb: (a: string) => string): void {}
function hof2(cb: (a: number) => string): void {}

function someFunc(a: string | number): string {
  return `${a}`;
}

hof1((a) => a.toUpperCase());
hof2((a) => a.toFixed(2));

hof1(someFunc);
hof2(someFunc);

In the example someFunc is being used for both hof1 and hof2, so it makes it more clear why TS wasn't able to make any assumption, because someFunc is more generic as compared to what either hof1 or hof2 accepts. But with that inline function TS knew that it's exactly what hof accepts because that's the only place it can be used.