text:
Q: Will this optical drive work with my MacBook 13in mid 2010 Hi I have a 13" MacBook mid 2010 and the optical drive went out so I've been looking for a new one. I found one that I'm interested in but was needing to know if it will work with my MacBook I provided the link to the one I'm looking at.
http://www.ebay.com/itm/2nd-9-5mm-SATA-SSD-Hard-Drive-Caddy-Bay-for-MacBook-CD-DVD-ROM-Optical-Bay-/131975475287?hash=item1eba59f057:g:IdkAAOSwpLNYBwIq

A: Unless I misunderstood your question, this is not actually a replacement Optical Drive. What you're linking to is a caddy that allows you to add a second HDD/SSD to your 13" MacBook by using the space your original Optical Drive was in.
Based on your question, you need something like this.
Anyone looking to replace one in a MacBook Pro (13" mid-2010) would need something like this.


text:
Q: Propel match email validator is wrong? Im try use a Propel match validators. In this case a email string.
I use the example from Propel Docs:
/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9])+(\.[a-zA-Z0-9_-]+)+$/

But, this regex fails always.
Ex: pepe@mail.com, ramiro@gmail.com, messi.10@barsa.ca, js_veron@hotmail.com.ar
Any idea ?

A: The problem was that never assign a email value u.u
Thanks !

redpajama_set_name: RedPajamaStackExchange


text:
Q: JavaFX: How to correctly color background of the selected TableCell? I want to change the row background color into green when to select a row. However, although the selected row was changed color, the additionally wrong row was also changed color.
I can't figure out why??
This is a JavaFX program coding in Intellij of Windows 10.
TestFXML.java:
public class TestFXML implements Initializable {
    @FXML
    TableView<ItemLog> table;
    @FXML
    TableColumn<ItemLog,String> column1,column2,column4;
    @FXML
    TableColumn<ItemLog,Number> column3;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        ObservableList<ItemLog> root=FXCollections.observableArrayList();
        root.addAll(
                new ItemLog("E0001","2.5㎟ XLPE", 1.2,"m"),
                new ItemLog("E0002","4㎟ XLPE",1.5,"m"),
                new ItemLog("E0003","6㎟ XLPE",2.0,"m"),
                new ItemLog("E0004","10㎟ XLPE",4.0,"m"),
                new ItemLog("E0005","16㎟ XLPE",6.2,"m"),
                new ItemLog("E0006","25㎟ XLPE",9.1,"m"),
                new ItemLog("E0007","35㎟ XLPE",14.5,"m"),
                new ItemLog("E0008","50㎟ XLPE",20.6,"m"),
                new ItemLog("E0009","70㎟ XLPE",31.2,"m"),
                new ItemLog("E00010","120㎟ XLPE",40.5,"m"),
                new ItemLog("E00011","150㎟ XLPE",55.3,"m"),
                new ItemLog("E00012","185㎟ XLPE",78.8,"m"),
                new ItemLog("E00013","240㎟ XLPE",96.0,"m"),
                new ItemLog("E0101","2.5㎟ PVC", 1.2,"m"),
                new ItemLog("E0102","4㎟ PVC",0.8,"m"),
                new ItemLog("E0103","6㎟ PVC",1.2,"m"),
                new ItemLog("E0104","10㎟ PVC",2.1,"m"),
                new ItemLog("E0105","16㎟ PVC",4.3,"m"),
                new ItemLog("E0106","25㎟ PVC",6.8,"m"),
                new ItemLog("E0107","35㎟ PVC",9.5,"m"),
                new ItemLog("E0108","50㎟ PVC",12.8,"m"),
                new ItemLog("E0109","70㎟ PVC",16.9,"m"),
                new ItemLog("E01010","120㎟ PVC",21.5,"m"),
                new ItemLog("E01011","150㎟ PVC",27.6,"m"),
                new ItemLog("E01012","185㎟ PVC",38.4,"m"),
                new ItemLog("E01013","240㎟ PVC",52.9,"m")
                );
        table.setItems(root);
        column1.setCellValueFactory(param -> param.getValue().code);
        column2.setCellValueFactory(param -> param.getValue().description);
        column3.setCellValueFactory(param -> param.getValue().price);
        column4.setCellValueFactory(param -> param.getValue().unit);
        //To change selected row color into green
        table.getFocusModel().focusedCellProperty().addListener((observable, oldValue, newValue) -> {
            if(newValue.getTableColumn() != null){
                newValue.getTableColumn().setCellFactory(param -> new TableCell(){
                    @Override
                    protected void updateItem(Object item, boolean empty) {
                        super.updateItem(item, empty);
                        if (empty) {
                            setText(null);
                            setGraphic(null);
                        }else{
                            setText(item.toString());
                            if(this.getIndex()==newValue.getRow()){
                                this.getTableRow().setStyle("-fx-background-color:green");
                            }
                        }
                    }
                });
            }
        });
    }
    private class ItemLog {
        StringProperty code=new SimpleStringProperty();
        StringProperty description=new SimpleStringProperty();
        DoubleProperty price=new SimpleDoubleProperty();
        StringProperty unit=new SimpleStringProperty();
        ItemLog(String code, String description, Double price, String unit) {
            this.code.set(code);
            this.description.set(description);
            this.price.set(price);
            this.unit.set(unit);
        }
    }
}

TestFXML.fxml:
<Pane prefHeight="414.0" prefWidth="602.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.TestFXML">
    <children>
       <TableView fx:id="table" maxHeight="1.7976931348623157E308" prefHeight="421.0" prefWidth="602.0">
         <columns>
           <TableColumn fx:id="column1" editable="false" prefWidth="100.0" text="A" />
           <TableColumn fx:id="column2" editable="false" prefWidth="300.0" text="B" />
             <TableColumn fx:id="column3" editable="false" prefWidth="100.0" text="C" />
             <TableColumn fx:id="column4" editable="false" prefWidth="100.0" text="D" />
        </columns>
      </TableView>
    </children>
</Pane>

I expected when I select 1st row, only 1st row changes in to green color.
Actual result is when I selected 1st row, 1st and 19th rows changed in to green color.

A: There are 3 issues with your approach:

*

*You never reset the look of the cell, if the cell becomes empty or the item is changed to a different one.

*TableView usually does not recreate the cells, if the cellFactory changes. Each cellFactory chooses to highlight a cell based on the focused cell at the time the cellFactory creating the cell was created. Even if cells were recreated, you'd still see highlighted cells in other columns, since you never change back to a cellFactory not highlighting cells.

*Focused and selected cells may differ.

Doing those modifications is much simpler, if you use a CSS stylesheet, since TableCells get assigned a pseudo class when they get focused allowing you to only define the style of focused cells without the need to worry about cellFactorys:
style.css
.table-cell:selected {
    -fx-background-color: green;
}

fxml
<Pane stylesheets="style.css" prefHeight="414.0" prefWidth="602.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.TestFXML">
    ...
</Pane>

Remove the cellFactory assignments from your java code for the above approach to work.
To only style specific TableViews this way you could e.g. add a style class to the TableView and select it based on the style class of the TableView, e.g.
.my-tableview .table-cell:selected {
    -fx-background-color: green;
}

Also it becomes much simpler to combine different criteria, e.g.
/* style for selected and hovered cell */
.table-cell:selected:hover {
    -fx-background-color: yellow;
}

A: I got the solution by myself. To Modify that:
if(this.getIndex()==newValue.getRow()){
    this.getTableRow().setStyle("-fx-background-color:green");
}

into:
if(this.getIndex()==newValue.getRow()){
    this.getTableRow().setStyle("-fx-background-color:green");
}else{
    this.getTableRow().setStyle("");
}


text:
Q: Change height of bootstrap carousel - keeping it responsive I have implemented a bootstrap carousel without overriding any styles. I want it to respond the way it does at the moment, so carousel and image respond down together without the image being cropped or distorted - but I would like the starting height of the carousel to be shorter.
It responds like the one on this page:
http://www.suug.co.uk/
So at the moment when the browser is full width it is 650px high, I can see a height attribute hasn't been set, so I am wondering if I can keep the way it responds but change the starting height to say, 550px.
My code:

        Previous
         Next

A: My solution was the following:
.carousel img {
    max-height: 300px;
    margin: 0 auto;
}

You can also set the max-height to relative measures :)

A: Here is a JSFiddle that may help you: http://jsfiddle.net/gh4Lur4b/140/
You can change the height of your carousel in the class of .carousel-inner, however the html structure is a bit different from yours, you can adjust it to fit your requirements.
.carousel-inner{
    height: 550px;
}

With only adjusting the height of the carousel may cause your images to be squashed, so I quite recommend to customize the responsiveness of your carousel using media queries (according to Bootstrap's documentation):
/* Extra small devices (phones, less than 768px) */
/* No media query since this is the default in Bootstrap */

/* Small devices (tablets, 768px and up) */
@media (min-width: @screen-sm-min) { ... }

/* Medium devices (desktops, 992px and up) */
@media (min-width: @screen-md-min) { ... }

/* Large devices (large desktops, 1200px and up) */
@media (min-width: @screen-lg-min) { ... }

Hope that the answer can help you!

A: You only have to add below line in your css
.bx-wrapper img{height: 550px; background-position: center; background-size: cover;}

Hope its working :)


text:
Q: Should a internal C# app be compiled with business logic? [background]
So, I've got a C# application that was written before I got here.  I'm not in the dev org, at this time, but I am the tech lead in my sub-group within the internet marketing org.  My responsibility is process automation, minimal desktop support, and custom apps that make our lives easier.
[/background]
[app details]
We've got an app that creates a custom database file from a list of URLs.  It was designed to have one input file, and two output files for the two applications that use these sort of db files.  The rule for the difference between the two output files is compiled into the code.
[/app details]
Should an internal C# app be compiled with business logic that can't be changed without it being re-built?

A: If the logic is changed on a regular basis, you should avoid building it into the program. On the other hand, since it is internal, I'm guessing that the process required to rebuild the app is minimal or non-existent, so it may not make much of a difference.

A: *

*How long does it take to alter business logic and then recompile?

*How long will it take to alter business logic without recompiling in new version?

*How long will it take to recode it?

*How will this affect maintainence in terms of extra hours spent in the future?

*Are any of the people who need the app unable to alter the business logic because it is in code form?

Answering those 5 questions will yield an answer.

A: Internal applications have one goal: support the process.
If the rules for creating the output are simple, change every day and are put down by a user, compiling it into the binary is totally wrong and an investment into a GUI and a new set of programmers could do much good. If the rules are complex, change once a year and are mandated by the management, having them compiled into the binary is a simple, cost-effective way to maintain them and keep users from fiddling with the internals.
As always, the answer has to be "it depends".

A: If the logic does not need to be changed then yes it should probably be compiled along with the code.
On the other hand if there are certain factors that could change the behavior of this business logic then you should probably provide a mean of changing it such as xml configuration files that alter its behavior.

A: Sure, if you know that the utility will only be used within your organization and for a single purpose there is nothing wrong with mixing your business rules with the logic.  Over-designing (in this case making code reusable when it will never be reused) would not be an efficient use of resources.

A: I usually employ multiple configuration strategies based on probability of change.
First of all never put business rules in code without documenting it in some-way. Code has a lot of variables and only some of them can be changed safely while still maintaining the correct behaviour. I Normally put a constant at the start of class to identify what behaviour can be changed, i.e.
// Prefer this
const int AllowDownloadAttempts = 2;
if (AttemptDownload() > AllowDownloadAttempts) RegisterAndAllowDownload();

// Over this
if (AttemptDownload() > 2) RegisterAndAllowDownload();

A basic rule I follow is anything other than [-1, 0, 1] must be documented.
If it's not critical and not likely to change often than I would place it in the applications configuration file (e.g. App.config) and access it via a strongly-typed configuration class so you can keep track of its usages to know when its safe to remove or change.
If it needs to be changed frequently or changed by business users then I would store it in a database and provide a simple GUI to edit it then load it into a strongly-typed configuration class when the application loads.


text:
Q: *ngIf not working as expected with observable So I have these 2 buttons:

  Login

  Logout

And the logout button works perfectly, as soon as the user is logged in the button appears. But the login button never appears.
This is the code behind the isLoggedIn$:
isLoggedIn$: Observable<boolean>;

ngOnInit() {
  this.isLoggedIn$ = this.authService.isLoggedIn;
}

AuthService:
private loggedIn = new BehaviorSubject<boolean>(false);

get isLoggedIn() {
  return this.loggedIn.asObservable();
}

Hope this is enough information and the problem is clear, thanks in advance!

A: Put the async pipe in parenthesis.

  Login

  Logout

A: I like the answer with *ngIf and Else approach, but your version can also be optimized to prevent double subscription.
<ng-container *ngIf="{ isLoggedIn: (isLoggedIn$ | async) } as observables">

    Login

  Logout

</ng-container>

A: You can also refactor to use the else part of ngIf directive:

    Logout

<ng-template #loginBlock>

        Login

</ng-template>

You can see more examples in the docs.

A: In Angular version 14, this works for me:

  Login

  Logout


text:
Q: set! global from Scheme macro? I am trying to write a wrapper for define, that stores the values passed to it.  I've been approaching it in baby steps (being new to Lisp in general, and even newer to Scheme) but have run into a wall.
In Racket, I'm starting with:
> (require (lib "defmacro.ss"))
> (define-macro (mydefine thing definition)
      `(define ,thing ,definition))
> (mydefine a 9)
> a
9

Okay, that works.  Time to do something in the macro, prior to returning the s-exprs:
> (define-macro (mydefine thing definition)
    (display "This works")
    `(define ,thing ,definition))
> (mydefine a "bob")
This works
> a
"bob"

Nice.  But I can't for the life of me get it to set a global variable instead of displaying something:
> (define *myglobal* null)
> (define-macro (mydefine thing definition)
    (set! *myglobal* "This does not")
    `(define ,thing ,definition))
> (mydefine a ":-(")
set!: cannot set identifier before its definition: *myglobal*

Any suggestions on how to accomplish this would be greatly appreciated.
I suspect that I'm trying to swim against the current here, either by fiddling with globals from a macro in Scheme, or by using define-macro instead of learning the Scheme-specific syntax for macro creation.

A: You're running against Racket's phase separation -- which means that each phase (the runtime and the compile-time) operate in different worlds.  As Vijay notes, one way to solve this is to do what you want at runtime, but that will probably not be what you need in the long run.  The thing is that trying these things usually means that you will want to store some syntactic information at the compile-time level.  For example, say that you want to store the names of all of your defined names, to be used in a second macro that will print them all out.  You would do this as follows (I'm using sane macros here, define-macro is a legacy hack that shouldn't be used for real work, you can look these things up in the guide, and then in the reference):
#lang racket
(define-for-syntax defined-names '())
(define-syntax (mydefine stx)
  (syntax-case stx ()
    [(_ name value)
     (identifier? #'name)
     (begin (set! defined-names (cons #'name defined-names))
            #'(define name value))]
    ;; provide the same syntactic sugar that `define' does
    [(_ (name . args) . body)
     #'(mydefine name (lambda args . body))]))

Note that defined-names is defined at the syntax level, which means that normal runtime code cannot refer to it.  In fact, you can have it bound to a different value at the runtime level, since the two bindings are distinct.  Now that that's done, you can write the macro that uses it -- even though defined-names is inaccessible at the runtime, it is a plain binding at the syntax level, so:
(define-syntax (show-definitions stx)
  (syntax-case stx ()
    [(_) (with-syntax ([(name ...) (reverse defined-names)])
           #'(begin (printf "The global values are:\n")
                    (for ([sym (in-list '(name ...))]
                          [val (in-list (list name ...))])
                      (printf "  ~s = ~s\n" sym val))))]))

A: The statement (set! *myglobal* "This does not") is executed in the transformer environment, not the normal environment. So it's not able to find *myglobal. We need to get both the expressions executed in the environment where *myglobal* is defined.
Here is one solution:
(define *defined-values* null)

(define-macro (mydefine thing definition)
  `(begin
     (set! *defined-values* (cons ,definition *defined-values*))
     (define ,thing ,`(car *defined-values*))))

> (mydefine a 10)
> (mydefine b (+ 20 30))
> a
10
> b
50
> *defined-values*
(50 10)
> (define i 10)
> (mydefine a (begin (set! i (add1 i)) i)) ;; makes sure that `definition`
                                           ;; is not evaluated twice.
> a
11

If the Scheme implementation does not provide define-macro but has define-syntax, mydefine could be defined as:
(define-syntax mydefine
  (syntax-rules ()
    ((_ thing definition)
     (begin
       (set! *defined-values* (cons definition *defined-values*))
       (define thing (car *defined-values*))))))


text:
Q: xcscope key rebinding in in conflict with emacs default I have the following in my init.el but c-\ in emacs binds to input method. I don't use input method anyways so is there a way to disable c-\ not to bind to input method?
(add-to-list 'load-path "~/.emacs.d")

(require 'xcscope)

(setq cscope-do-not-update-database t)

(define-key cscope:map "\C-\\s" 'cscope-find-this-symbol)

(define-key cscope:map "\C-\\g" 'cscope-find-global-definition)

(define-key cscope:map "\C-\\d" 'cscope-find-called-functions)

(define-key cscope:map "\C-\\c" 'cscope-find-functions-calling-this-function)

(define-key cscope:map "\C-\\t" 'cscope-find-this-text-string)

(define-key cscope:map "\C-\\e" 'cscope-find-egrep-pattern)

(define-key cscope:map "\C-\\f" 'cscope-find-this-file)

(define-key cscope:map "\C-\\i" 'cscope-find-files-including-file)

(define-key cscope:map "\C-\\b" 'cscope-display-buffer)

(define-key cscope:map "\C-\\B" 'cscope-display-buffer-toggle)

(define-key cscope:map "\C-\\n" 'cscope-next-symbol)

(define-key cscope:map "\C-\\N" 'cscope-next-file)

(define-key cscope:map "\C-\\p" 'cscope-prev-symbol)

(define-key cscope:map "\C-\\P" 'cscope-prev-file)

(define-key cscope:map "\C-\\u" 'cscope-pop-mark)

(define-key cscope:map "\C-\\v" 'cscope-history-backward)

(define-key cscope:map "\C-\\V" 'cscope-history-forward)

A: Try this:
(global-unset-key (kbd "C-\\"))


text:
Q: How to set the base class property of a generic class I have a base class:
public abstract class MyBaseClass
{
    public string  MyProperty { get; set; }
}

and then a class that gets passed a Generic class  that get passed a TViewModel that inherits from MyBaseClass
public abstract class MyGenericController<TViewModel> : Controller
    where TViewModel :  MyBaseClass
{
    public virtual async Task<IActionResult> Index()
    {
        object viewModel = Activator.CreateInstance(typeof(TViewModel));
        viewModel.MyProperty="test";
        return View(viewModel);
    }
}

This works like I want it. However as soon as I try set the base class property I get a compile error:

object does not contain a definition for MyProperty
  on the line

viewModel.MyProperty="test";

How do I set the property?

A: Use the generic Activator.CreateInstance<T> instead:
public virtual async Task<IActionResult> Index()
{
    TViewModel viewModel = Activator.CreateInstance<TViewModel>();
    viewModel.MyProperty="test";
    return View(viewModel);
}

An alternative can also be to constraint the generic type parameter (which saves you the overhead of reflection) to contain a default constructor via TViewModel : MyBaseClass, new(), and then:
public virtual async Task<IActionResult> Index()
{
    TViewModel viewModel = new TViewModel();
    viewModel.MyProperty="test";
    return View(viewModel);
}


text:
Q: Есть ли возможность вызывать функции с делегата по одной?         Action  D_For_reproduct_Functions;

        D_For_reproduct_Functions += ReproductExp;
        D_For_reproduct_Functions += ReproductArcSin;
        D_For_reproduct_Functions += ReproductNormal;
        D_For_reproduct_Functions += ReproductLaplasa;
        D_For_reproduct_Functions += ReproductReley;
        D_For_reproduct_Functions += ReproductVeibula;

Мне нужно что-то вроде такого
        for (int i = 0; i < D_For_reproduct_Functions.Length; i++)
        {
            D_For_reproduct_Functions[i]();

            KSKolvogorov();

            //и тут в будущем KSPirsona
        }

A: Вы можете разобрать ваш делегат на составные части при помощи GetInvocationList(). Вот пример:
Action combined = () => Console.WriteLine("Func 1");

combined += () => Console.WriteLine("Func 2");
combined += () => Console.WriteLine("Func 3");

var actions = combined.GetInvocationList().Cast<Action>();
foreach (var a in actions)
{
    a();
    Console.WriteLine("-----");
}

Но раз вам такое понадобилось, возможно, вы делаете что-то неправильно. Думаю, вам реально вместо Action  D_For_reproduct_Functions нужно List<Action> D_For_reproduct_Functions, и ваш код будет иметь вид
List<Action> D_For_reproduct_Functions = new List<Action>();

D_For_reproduct_Functions.Add(ReproductExp);
D_For_reproduct_Functions.Add(ReproductArcSin);
D_For_reproduct_Functions.Add(ReproductNormal);
D_For_reproduct_Functions.Add(ReproductLaplasa);
D_For_reproduct_Functions.Add(ReproductReley);
D_For_reproduct_Functions.Add(ReproductVeibula);

for (int i = 0; i < D_For_reproduct_Functions.Count; i++)
{
    D_For_reproduct_Functions[i]();
    KSKolvogorov();
}


text:
Q: onClick function - automatically copies data from spreadsheets' static field I'd be very glad for help with some ideas for code of extension that, on pressing on the icon in chrome, automatically copies a text from static field in spreadsheet, like this:
http://tinyurl.com/bwfumls
I have tried many times to play with onClick function, but it didn't work for me. Thanks a million for your help or for some hints on the materials I could read to learn it.
damian

A: You need to run a content script within your extension that captures the onclick event of the table cell in Google Docs. This is the HTML source for the area you are interested in.

EXAMPLE OF TEXT THAT WOULD BE COPIED ON CLICK

Here's some JQuery you can embed in your script to isolate the contents of the cell.
$(".cell-input").click(function(){
   var cellContents = $(".cell-input").text();
});

You could then store this in a background page and pull it out on the pop-up page that would appear when you click the Chrome extension icon. This is just the general methodology so you'll need to do a bit more research on the mechanisms I have mentioned here.
Content Scripts (to interact with the Google Docs page):
http://developer.chrome.com/extensions/content_scripts.html
Message Passing (to get the variable from the page into the popup via a background.js):
http://developer.chrome.com/extensions/messaging.html


text:
Q: How to convert an array with data objects to just an array with strings with javascripts? How to convert an array with data objects to just an array with strings with javascripts.
This is the data set below
const Cars = [
      { carTypes: 'Cadillac' },
      { carTypes: 'Jaguar' },
      { carTypes: 'Audi' },
      { carTypes: 'Toyota' },
      { carTypes: 'Honda' },
    ];

This is the results i would like to get const models = ['Cadillac', 'Jaguar', 'Audi', 'Toyota', 'Honda'];
I tried this below but it didn't work
 function OnFucTap() {
    const Cars = [
      { carTypes: 'Cadillac' },
      { carTypes: 'Jaguar' },
      { carTypes: 'Audi' },
      { carTypes: 'Toyota' },
      { carTypes: 'Honda' },
    ];

    const models = Cars.carTypes.split(',');

    console.log(models);
    alert(models);
  }

A: Use map() to access each object's carTypes element.
const models = Cars.map(car => car.carTypes);

If carTypes could contain a comma-separated list of manufacturers, you can use split() on the property and flatMap() to concatenate all of them.
const models = Cars.flatMap(car => car.carTypes.split(','));

BTW, names like Toyota and Honda are makes. Models are Camry and Accord.


text:
Q: Using Flurry in iOS to track user's event, but I can only log the event defined in AppDelegate.m file. I'm trying to make some logs using Flurry to track user's action. For example, I have 5 tabs in my main tabviewcontroller, when a user switch from one tab to another, I want to log the action. My code is like [Flurry logEvent:@"user is visiting tab1"]
in the viewDidLoad function. In the AppDelegate.m file, I add a similar line in the "application didFinishLaunchingWithOptions" function,
[Flurry logEvent:@"MyAPP just started."]

When I try to check the log event online, it only shows 1 event "MyApp just started". It seems that other events are not logged.
BTW, I start a session in the AppDelegate.m file, like
[Flurry startSession:@"my api key"];
[Flurry logEvent:@"MyApp just started"];

Any ideas? Thanks.


text:
Q: what the best way for escape html with rails 4: gsub('<', '<') OR CGI.escapeHTML I want escape html for data in controller, I found 2 ways:
text.gsub('<', '<').gsub('>', '>')

OR
CGI.escapeHTML(text)

What is the best, why?

A: The best way is probably to just assign the data to instance variables and then output them in the view, which will handle encoding automatically:
controller:
def something
  @foo = "<test>"
end

something.html.erb
<%= @foo %>

Will output:
<test>

The view will do the right thing in most cases.


text:
Q: Magento 2.3 wrong image cache generation I have upgraded my Magento EE store from 2.2.7 to 2.3.2. An issue occurred of images not showing on product pages.
I debugged a bit and ran the command "catalog:image:resize" and images appeared. But when I flush catalog images cache from admin, the issue appeared again.
I think the images cache is not generating. The permission for pub/media are also 777.
Also the product images are appearing on category page but not on product page.

A: After intense searching and debugging, issue appeared to be of missing htaccess file in pub/media/ folder. Added the file from magento 2.3.2 git. Because the images cache folders weren't generating due to missing htaccess.


text:
Q: How to understand the notation of area element vector I've already known that the area element of vector surface integral can be written as $dA = \frac{\partial \textbf{r}}{\partial s}\times\frac{\partial \textbf{r}}{\partial t}dsdt$, where r(s,t) is a parameterization of the surface. However, the area element can also be written as $dA=dxdy \hat k + dydz \hat i + dxdz \hat j$. So, do these two forms equal? How to derive(and understand) the latter form?

A: Intro
(This section was largely copied from my answer to the related question A doubt regarding change of variables in Double Integrals..)
There are two main types of ways to think about things like $\mathrm{d}x\mathrm{d}y$ in multivariable calculus, and we often switch between them depending on the context. (This clarification was inspired in part by Terry Tao's preprint on "differential forms and integration".) $\mathrm{d}x$ can either act kind of like a positive number representing a small length, or act kind of like a vector with a direction/orientation baked in.
For the "number" interpretation, there are things like limit arguments in analysis or infinitesimals in nonstandard analysis to make things rigorous. For the "vector" interpretation, there are things like "differential forms" or "geometric calculus" to make things rigorous. But I'm going to gloss over those details because there are many ways to make things formal, and the exact choices don't affect the intuition here.
Orientation
If you care about the direction of the normal area vector $\mathrm d\mathbf A$ (e.g. because you would like to integrate $\mathbf F\cdot\mathrm d\mathbf A$ for some vector field $\mathbf F$), then we're in a situation where orientation matters.
Background
For instance, maybe $\dfrac{\partial\mathbf{r}}{\partial s}\times\dfrac{\partial\mathbf{r}}{\partial t}$ goes in the correct direction, but swapping $s$ and $t$ would give $\dfrac{\partial\mathbf{r}}{\partial t}\times\dfrac{\partial\mathbf{r}}{\partial s}$ which goes in the wrong direction. But this is a little weird, because an integral shouldn't care about how you labeled the parameters of the surface, as long as $\mathrm d\mathbf A$ points in the right direction in the end.
There are many ways to address this. One approach is to think about orientation also mattering in the parameter domain in the $st$-plane. For comparison, with regular $1$-d integrals, you can write things like $\int_4^3f(x)\,\mathrm dx$ to signify something like "integrate over $[3,4]$, but give a negative sign because we're doing it backwards". Similarly, if you think about the domain in the $st$-plane, it could be oriented positively (imagine something like $\mathrm ds\times\mathrm dt$) or negatively (imagine something like $-\mathrm ds\times\mathrm dt=\mathrm dt\times\mathrm ds$). And if $\mathrm ds\mathrm dt$ secretly meant something similar in spirit to $\mathrm ds\times\mathrm dt$ that swaps signs when the order swaps (unlike regular multiplication of numbers), then $\mathrm d\mathbf A=\dfrac{\partial\mathbf{r}}{\partial s}\times\dfrac{\partial\mathbf{r}}{\partial t}\,\mathrm ds\mathrm dt=\dfrac{\partial\mathbf{r}}{\partial t}\times\dfrac{\partial\mathbf{r}}{\partial s}\,\mathrm dt\mathrm ds$ since the two minus signs cancel out!
Across multiple different ways of formalizing things, a symbol used for this non-commutative multiplication is $\wedge$. Note that $\mathrm ds\wedge\mathrm ds=-\mathrm ds\wedge\mathrm ds$ by swapping the two factors, so that  $\mathrm ds\wedge\mathrm ds=\boldsymbol 0$, and similarly for $\mathrm dt$.
Verification
Let's say $\mathbf r(s,t)=\left\langle x(s,t),y(s,t),z(s,t)\right\rangle$. With this noncommutative multiplication $\wedge$ and orientation mattering, we can justify a version of your formula by using formulas like you might have seen for linear approximations of multivariable functions: e.g. $\mathrm dx=\dfrac{\partial x}{\partial s}\mathrm{d}s+\dfrac{\partial x}{\partial t}\mathrm{d}t$. Then we have:
\begin{align}
\mathrm d\mathbf A &=\dfrac{\partial\mathbf{r}}{\partial s}\times\dfrac{\partial\mathbf{r}}{\partial t}\,\mathrm ds\wedge\mathrm dt\\
&=\det\begin{bmatrix}\hat{\boldsymbol{\imath}} & \hat{\boldsymbol{\jmath}} & \hat{\boldsymbol{k}}\\
\dfrac{\partial x}{\partial s} & \dfrac{\partial y}{\partial s} & \dfrac{\partial z}{\partial s}\\
\dfrac{\partial x}{\partial t} & \dfrac{\partial y}{\partial t} & \dfrac{\partial z}{\partial t}
\end{bmatrix}\,\mathrm{d}s\wedge\mathrm{d}t\\
&=\left(\left(\dfrac{\partial y}{\partial s}\dfrac{\partial z}{\partial t}-\dfrac{\partial z}{\partial s}\dfrac{\partial y}{\partial t}\right)\hat{\boldsymbol{\imath}}+\left(\dfrac{\partial z}{\partial s}\dfrac{\partial x}{\partial t}-\dfrac{\partial x}{\partial s}\dfrac{\partial z}{\partial t}\right)\hat{\boldsymbol{\jmath}}+\left(\dfrac{\partial x}{\partial s}\dfrac{\partial y}{\partial t}-\dfrac{\partial y}{\partial s}\dfrac{\partial x}{\partial t}\right)\hat{\boldsymbol{k}}\right)\mathrm{d}s\wedge\mathrm{d}t
\end{align}
And we also have (making sure to switch the order of the "$dxdz$" product into $\mathrm dz\wedge\mathrm dx$):
\begin{align}
&\phantom{=}\mathrm{d}x\wedge\mathrm{d}y\hat{\boldsymbol{k}}+\mathrm{d}y\wedge\mathrm{d}z\hat{\boldsymbol{\imath}}+\mathrm{d}z\wedge\mathrm{d}x\hat{\boldsymbol{\jmath}}\\&=\left(\dfrac{\partial x}{\partial s}\mathrm{d}s+\dfrac{\partial x}{\partial t}\mathrm{d}t\right)\wedge\left(\dfrac{\partial y}{\partial s}\mathrm{d}s+\dfrac{\partial y}{\partial t}\mathrm{d}t\right)\hat{\boldsymbol{k}}+\cdots\\&=\left(\dfrac{\partial x}{\partial s}\dfrac{\partial y}{\partial s}\mathrm{d}s\wedge\mathrm{d}s+\dfrac{\partial x}{\partial t}\dfrac{\partial y}{\partial s}\mathrm{d}t\wedge\mathrm{d}s+\dfrac{\partial x}{\partial s}\dfrac{\partial y}{\partial t}\mathrm{d}s\wedge\mathrm{d}t+\dfrac{\partial x}{\partial t}\dfrac{\partial y}{\partial t}\mathrm{d}t\wedge\mathrm{d}t\right)\hat{\boldsymbol{k}}+\cdots\\&=\left(\dfrac{\partial x}{\partial s}\dfrac{\partial y}{\partial s}*0+\dfrac{\partial x}{\partial t}\dfrac{\partial y}{\partial s}\mathrm{d}t\wedge\mathrm{d}s+\dfrac{\partial x}{\partial s}\dfrac{\partial y}{\partial t}\mathrm{d}s\wedge\mathrm{d}t+\dfrac{\partial x}{\partial t}\dfrac{\partial y}{\partial t}*0\right)\hat{\boldsymbol{k}}+\cdots\\&=\left(\dfrac{\partial x}{\partial t}\dfrac{\partial y}{\partial s}\mathrm{d}t\wedge\mathrm{d}s+\dfrac{\partial x}{\partial s}\dfrac{\partial y}{\partial t}\mathrm{d}s\wedge\mathrm{d}t\right)\hat{\boldsymbol{k}}+\cdots\\&=\left(\dfrac{\partial x}{\partial t}\dfrac{\partial y}{\partial s}\left(-\mathrm{d}s\wedge\mathrm{d}t\right)+\dfrac{\partial x}{\partial s}\dfrac{\partial y}{\partial t}\mathrm{d}s\wedge\mathrm{d}t\right)\hat{\boldsymbol{k}}+\cdots\\&=\left(\dfrac{\partial x}{\partial s}\dfrac{\partial y}{\partial t}-\dfrac{\partial y}{\partial s}\dfrac{\partial x}{\partial t}\right)\hat{\boldsymbol{k}}\,\mathrm{d}s\wedge\mathrm{d}t+\cdots=\mathrm{d}\mathbf{A}\checkmark
\end{align}
A version of this formula is mentioned in Spivak's Calculus on Manifolds and quoted in the question Calculating Surface Area using Differential Forms.
Numbers
If you don't care the direction of the normal area vector $\mathrm d\mathbf A$ (e.g. because you would like to integrate $\mathbf f\Vert\mathrm d\mathbf A\Vert$ for some scalar field $\mathbf f$), then orientation doesn't matter, and we really just care about the length of $\mathrm d\mathbf A$.
Background
If you just cared about volume under the graph of a scalar function, you might imagine adding up volumes of rectangular boxes, and you'd always write single integrals in an iterated integral with increasing bounds (like $\int_{0}^5\int_{-1}^1f(x,y)\,\mathrm dy\,\mathrm dx$ since \int_{5}^0 would obviously give the wrong sign). In this sort of context, something like $\mathrm dx$ would represent a small length, and $\mathrm dx\mathrm dy$ would be the area of small rectangle in (or parallel to) the $xy$-plane.
With this kind of setup, we have to give up on an idea like $\mathrm dx=\dfrac{\partial x}{\partial s}\mathrm{d}s+\dfrac{\partial x}{\partial t}\mathrm{d}t$ since the expression on the right couldn't represent a length if the partials were negative. And $\mathrm{d}x\mathrm{d}y\hat{\boldsymbol{k}}+\mathrm{d}y\mathrm{d}z\hat{\boldsymbol{\imath}}+\mathrm{d}x\mathrm{d}z\hat{\boldsymbol{\jmath}}$ would have three positive components, and so it would always point towards the first octant, even if that's not either direction of $\pm\mathrm d\mathbf A$. But it turns out that we can show that it has the right length under this interpretation anyway.
Verification
Let's say $\mathbf r(s,t)=\left\langle x(s,t),y(s,t),z(s,t)\right\rangle$.
First, let's consider the simple case when $z(s,t)$ is a constant $z_0$. Then $\mathrm dA=\left(\dfrac{\partial x}{\partial s}\dfrac{\partial y}{\partial t}-\dfrac{\partial y}{\partial s}\dfrac{\partial x}{\partial t}\right)\hat{\boldsymbol{k}}$ with length $\left(\dfrac{\partial x}{\partial s}\dfrac{\partial y}{\partial t}-\dfrac{\partial y}{\partial s}\dfrac{\partial x}{\partial t}\right)^2$.
Since $z(s,t)$ is constant, $\mathrm dz$ (a small change in the $z$ coordinate as we move along the surface) is $0$, so the candidate vector reduces to $\mathrm{d}x\mathrm{d}y\hat{\boldsymbol{k}}$. Now, if we had to integrate $f(x,y,z)$  along the surface, we could substitute in $z=z_0$ and worry about $\int f\left(x,y,z_0\right)\,\mathrm dx\mathrm dy$ for $(x,y)$ in the projection of the surface. By multivariable substitution/change of variables, we could use a Jacobian determinant to rewrite $$\int f\left(x,y,z_0\right)\,\mathrm dx\mathrm dy=\int f\left(x(s,t),y(s,t),z_0\right)\,\left|\det\begin{bmatrix}\dfrac{\partial x}{\partial s}&\dfrac{\partial x}{\partial t}\\\dfrac{\partial y}{\partial s}&\dfrac{\partial y}{\partial t}\end{bmatrix}\right|\mathrm ds\mathrm dt\text{.}$$
In other words, $$\mathrm dx\mathrm dy=\left|\det\begin{bmatrix}\dfrac{\partial x}{\partial s}&\dfrac{\partial x}{\partial t}\\\dfrac{\partial y}{\partial s}&\dfrac{\partial y}{\partial t}\end{bmatrix}\right|\mathrm ds\mathrm dt=\left|\dfrac{\partial x}{\partial s}\dfrac{\partial y}{\partial t}-\dfrac{\partial y}{\partial s}\dfrac{\partial x}{\partial t}\right|\mathrm ds\mathrm dt\text{.}$$ Thus, $\mathrm{d}x\mathrm{d}y\hat{\boldsymbol{k}}=\pm\mathrm d\mathbf A$ and the length is still $\left(\dfrac{\partial x}{\partial s}\dfrac{\partial y}{\partial t}-\dfrac{\partial y}{\partial s}\dfrac{\partial x}{\partial t}\right)^2$.$\checkmark$
Now, consider the general case. Assuming $\mathbf r$ is nice and $\Delta s$ and $\Delta t$ are small, the four points $\mathbf r(s,t)$, $\mathbf r(s+\Delta s,t)$, $\mathbf r(s,t+\Delta t)$, and $\mathbf r(s+\Delta s,t+\Delta t)$ will approximate the vertices of a parallelogram.
It's a geometric fact that I won't reprove here that the square of the area of a parallelogram in 3D space is the sum of the squares of the areas of the projections onto the three coordinate planes. (A natural generalization is proven in Beyond Monge's Theorem: A Generalization of the Pythagorean Theorem. And this specific case is mentioned in Mikhail Katz's answer to Is it true that $d\textbf{S} = dy dz\textbf{ i }+ dx dz\textbf{ j }+ dx dy\textbf{ k }$. A closely related fact is shown in this answer to Area of projected parallelogram onto a plane.)
For each coordinate plane, an argument like the one I gave for the constant $z(s,t)$ case applies in discussing the area element of the projection onto that plane. So the three components of $\mathrm{d}x\mathrm{d}y\hat{\boldsymbol{k}}+\mathrm{d}y\mathrm{d}z\hat{\boldsymbol{\imath}}+\mathrm{d}x\mathrm{d}z\hat{\boldsymbol{\jmath}}$ have the right squares for the length to equal the length of $\mathrm d\mathbf A$, as desired.


text:
Q: Looking for guidance on writing tutorials for users We are developing a desktop application.We are writing tutorials for users in a wiki.I was looking for some guidance ..good practices when writing such tutorials.
regards

A: I think some basic rules are ok

*

*include as many screenshots as you can

*don't use too much technical wording

*structure your pages/documents that it is easy to navigate inside

*don't make the user looks stupid, i.e. way of writing that would say the user is not capable of doing anything

Also it could be a good idea if you make your wiki and ask one typical user to review it with you. Getting the opinion of the user would probably show you million of things you have forgotten.

A: make sure your app is intuitive first. then when your sure it is, make it more intuitive.
see :
http://www.discoapp.com/
http://www.utorrent.com/
http://handbrake.fr/
http://www.nethack.org/
dont see:
http://www.adobe.com/
Windows songsmith

A: *

*Have a FAQ

*Tips and Tricks Section.

*Have short videos about "How to..."

A: A few tips for technical documents:
1- Assume everyone reading the document is the dumbest person you've ever met who has never seen a computer in their entire life.
2- Don't skip a single step.  Even if it's clicking a well-known button, etc.  If your instruction doesn't start with "click" or "type", it's not granular enough.
3- There are never too many screenshots... unless you can't read the text between them, or fail to notice it entirely.  Leave enough spaces between screenshots and text, and make the text one size larger if need be.
4- Do it yourself, multiple times.  Make others follow your directions.  Make your grandmother follow them.  If she can, your manager probably can.  Maybe.

A: Figure out the key features that users will use most often and provide a cheat sheat. Download any one refcards from dzone.com as an example.

A: I think the best tutorials are those that guide the students in an incremental, step-wise manner. Clearly describe prerequisites at the top and tell the readers 1, 2, 3 this is what you have to do.

A: *

*Choose your tasks thoughtfully (and stick to them). Each tutorial should cover a single task and stay focused on the goal throughout, with only the briefest digressions to introduce new terms or concepts. Start with the very first step a user needs to take to do something useful with the software. With a well designed app, a sequence of introductory tutorials is likely to start with a very short, simple one ("Creating a New Project") and proceed through intermediate ("Importing INTERCAL-72 Files") to advanced topics ("Customizing the Compiler Toolchain") so that the tutorials become more involved as the user becomes more involved with the app.

*Use numbered lists. Describe specific procedures that can be followed by anyone who can read.

*Use consistent styles for program and interaction elements, like bold text for buttons and menu items and monospace fonts for user input. The specific styles you choose matter less than their consistent application. If we're talking Windows apps, the Microsoft Manual of Style for Technical Publications might come in handy.

*Verify your procedures relentlessly. If a user needs a tutorial to figure out how to use the application, she's probably already frustrated. If she follows it to the letter and it doesn't work, everyone's a lot worse off, including you and your support rep.

*Use screenshots as signposts. Include one screenshot of each window and dialog box referenced by the procedure. Don't label them or otherwise doll them up. They're there to provide visual reinforcement that the user is following the procedure correctly and getting to the right places.

*Respect different learning styles. Keep in mind that most people are visual and/or auditory learners, so text isn't the best way to reach them. In practice, that means screenshot videos with voiceover. The written tutorial is the script.


text:
Q: При запуске процедуры из пакета исключение ORA-06508: PL/SQL: could not find program unit being called Есть пара пакетов с процедурами.
Вызываю процедуру, она завершается с ошибкой:

ORA-06508: PL/SQL: could not find programm unit called

Если захожу в процедуру в PL/SQL Developer через Debug по шагам, то процедура выполняется нормально и отрабатывает корректно. Все используемые пакеты имеют статус VALID.
Подскажите, в чем может быть проблема?

A: Это поведение свазано с состоянем пакета. Обратимся к подглаве Package State:

The values of the variables, constants, and cursors that a package declares (in either its specification or body) comprise its package state.
If a PL/SQL package declares at least one variable, constant, or cursor, then the package is stateful; otherwise, it is stateless.

Если в пакете определена как минимум одна переменная, константа или курсор, то пакет после инициализаци получает состояние, которое сохраняется до окончания сессии. Состояние пакета может стать недействительным, одной из причин этого является рекомпиляция пакета:

The package body is recompiled.
If the body of an instantiated, stateful package is recompiled (either explicitly, with the "ALTER PACKAGE Statement", or implicitly), the next invocation of a subprogram in the package causes Oracle Database to discard the existing package state and raise the exception ORA-04068.

After PL/SQL raises the exception, a reference to the package causes Oracle Database to re-instantiate the package, which re-initializes it. Therefore, previous changes to the package state are lost.

После возникновения ошибки, пакеты автоматически реинициализируются, старое их состояние теряется и появляется новое.
Возможное решение, пересмотреть дизайн кода и убрать все переменные, константы или курсоры, объявленные вне функций или процедур, другими словами создать пакет без состояния. Но ничего страшного, если это не предоставляется возможным, при повторном запуске ошибка не должна возникнуть.
Воспроизводимый пример:
create or replace package pack1 as
    val varchar2 (8) := 'pack';
end;
/
create or replace package pack2 as
    function foo return varchar2;
end;
/
create or replace package body pack2 as
    function foo return varchar2 is
    begin
        return pack1.val||'2';
    end;
end;
/
select pack2.foo from dual;

FOO
--------
pack2

В другой сессии заново скомпилируем пакет:
alter package pack1 compile;

Package altered.

Теперь, в первой сессии вызов вызовет ошибку, так как состояние пакета pack1 потеряно:
select pack2.foo from dual;

Error report -
ORA-04068: existing state of packages has been discarded
ORA-04061: existing state of package "DB.PACK1" has been invalidated
ORA-04065: not executed, altered or dropped package "DB.PACK1"
ORA-06508: PL/SQL: could not find program unit being called: "DB.PACK1"
ORA-06512: at "DB.PACK2", line 4

select pack2.foo from dual;

FOO
--------
pack2

A: Такая ошибка возникает когда в сессии номер 1 было обращение к пакету, потом другая сессия перекомпилила пакет, и снова сессия номер 1 запустила его. То есть суть в том что посторонняя сессия инициализировала для себя пакет, но после перекомпиляции эта инициализация не может считаться валидной, поскольку пакет мог быть изменен до степени не соответствия параметров инициализации с новой структурой\логикой пакета.
Помогает запуск процедуры в новой сессии.


text:
Q: OnLeScan continue firing after bluetooth is switched off It is teoretical question.
One of the customer devices(android 8 htc 10 ) continue firing OnLeScan callback after he dissables bluetooth module in settings. He could reproduse it only on  the htc 10 device.
Steps

*

*start app with bluetooth on

*app discovers beacons

*swith off bluetooth

*app continue firing OnLeScan
I understand that it is not possible(i can't reproduce it on other devices), but I get this situation.
Now I'm planning disable ble scanning when Bluetooth state is changed, so I think this will help me to fix this problem...
But still I don't understand why it is works like this. Do you have any ideas what can be wrong?

A: I think should write some code to stop the leScan.
Try to update a boolean flag like "blutooh_enabled" to keep a watch if the bluetooth is on or off and then write some code i.e,
mBluetoothAdapter.stopLeScan(mLeScanCallback);
I think this will help you.


text:
Q: How to say the total amount? I'm not sure if the saying of the total amount USD 23,428.32 is correct below (esp. the 'cent' part after the dot):

Say U.S. dollars twenty-three thousand four hundred and twenty-eight and thirty-two cents.

And if it is 23,428.00, do I say

Say U.S. dollars twenty-three thousand four hundred and twenty-eight only.

A: If I was saying them,
bearing in mind I am a native Brit:

Twenty-three thousand, four hundred and twenty-eight dollars, and
  thirty-two cents

(with that first 'and' being used in speech, but not in writing eg on a cheque, although interestingly in the UK you can use that first 'and')
and

Twenty-three thousand, four hundred and twenty-eight dollars

A: On a check – which is one of the few places where you see such numbers written out in their long form – you might see any of the following conventions used:

*

*Twenty-three thousand four hundred twenty-eight dollars &
thirty-two cents

*Twenty-three thousand four hundred twenty-eight dollars and 32
cents

*Twenty-three thousand four hundred twenty-eight dollars and 32/100
I don't believe too many people would use the top one, though – not when they were writing out the number in longhand – although you might see the number of cents spelled out on a computer-printed check.
In the case where the dollar amount is even, you might see:

*

*Twenty-three thousand four hundred twenty-eight dollars and no cents

*Twenty-three thousand four hundred twenty-eight dollars and no/100

*Twenty-three thousand four hundred twenty-eight dollars & 0/100

*Twenty-three thousand four hundred twenty-eight dollars only
I think the last one is relatively uncommon, although I've personally used it for decades.  (I first saw it as a teenager, thought it was a cool, quirky way to write checks in even amounts, and so I adopted the practice.)  Sometimes I'll even use the word exactly, when the dollar amount is more even:

*

*Twenty-three thousand four hundred dollars exactly
although I don't usually write checks in that large an amount.

A: In US English and is used only to separate Dollars and cents.
101 is written One hundred one with no and.
US$ 101.50 would be written as US Dollar One hundred One and Fifty cents
Where the amount is a whole number (no cents), it is terminated by the word Only:
Dollars One hundred One only.

A: Probably your answer is true. But i can write USD 23,428.32 as " U. S. DOLLARS TWENTY-THREE THOUSAND FOUR HUNDRED TWENTY-EIGHT AND THIRTY-TWO HUNDREDTHS".


text:
Q: what is alternative for AuthActions.LOAD_USER_TOKEN_FAIL in sparatcus v3.x I am using AuthActions.LOAD_USER_TOKEN_FAIL
action for 2.0 but when I migrate to 3.3.0 I am getting error on this as this has been removed.
can you please let me know what is the alternative for this one if I have to track the HTTP error code like v2.0
thanks in advance.

A: If you are using the standard "credentials" authentication.
You could extend the OOTB AuthService and overirde the loginWithCredentials, keep the same logic but add some additional logic in the catch which is called if the login failed.
I you don't want to add the logic there directly you could create your own LOAD_USER_TOKEN_FAIL and dispatch it from there. Alternatively, you can use the built in Event mechanism to create a new event an observe it elsewhere in the code.


text:
Q: Tap and Drag events not working on objects inside a clipped layer I have a layer->group->shape. The group and shape are both draggable and I have also applied a tap event on the shape.
I can drag around the group but the touch events don't work on the shape if I clip the layer. The mouse events work fine on the shape, everything works on the PC browser, even with the clipped layer. What could be wrong here?
Update: This happens only on iPad retina. It works on iPad Non-Retina.


text:
Q: Opening only a part of AWS-hosted web API to public I have a web API application running in AWS. Access to it is restricted to certain IP addresses using security groups.
I need to make available to public only one specific URL of that application. At the first glance API Gateway can do the job. However, I cannot find any settings which allow traffic coming from API Gateway.
Am I looking in the right direction?


text:
Q: Extract/subset minute values from each hour My data frame contains date values in the format YYYY-MM-DD HH-MM-SS across 125000+ rows, broken down by the minute (each row represents a single minute).
1 2018-01-01 00:04:00
2 2018-01-01 00:05:00
3 2018-01-01 00:06:00
4 2018-01-01 00:07:00
5 2018-01-01 00:08:00
6 2018-01-01 00:09:00
...
124998 2018-03-29 05:07:00
124999 2018-03-29 05:08:00
125000 2018-03-29 05:09:00

I want to subset the data by extracting all of the minute values within any given hour and saving the results into individual data frames.
I have used subset() combined with grepl() to no avail.  I have tried setting start = and stop = parameters but also to no avail.
What I want to do is for every HH value, I want to extract all rows with corresponding HH values and then create a new data frame for each respective HH value.
For example, I would like to have a data frame that corresponds to every minute's values (the full hour's worth of data), resulting in data frames such as:

*

*2018-01-01 00:00:00 (contains data from 2018-01-01 00:00:00 to 2018-01-01 00:59:00 (inclusive))

*2018-01-01 01:00:00 (contains data from 2018-01-01 01:00:00 to 2018-01-01 01:59:00 (inclusive))

and so on.
Is there a quick way to achieve this or is it a more laborious task?
Note: I am aware that my desired result will produce a lot of data frames, and that is fine for my particular project as I will only be working on a single one-hour block at any one time.

A: This will produce a list of data frames grouped by each hour, assuming your data frame is called data and your first column is V1
split(data, format(data$V1, "%Y-%m-%d %H"))

A: I have come up with a solution which extracts every minute (MM) value/row from the main data frame:
df <- buckets[grepl("00:\\d+:00$", buckets$time), ]

To separate it for each hour, I will simply change the first 00 depending on which hour I want to focus on and I can then perform a similar function to extract each individual date value.

A: If you want to access each individual date value, lubridate has default functions for that.
library(lubridate)
data %>% mutate(year = year(x), month = month(x), day = day(x), hour = hour(x))

So you can get the same splits (but in a more cumbersome manner) by doing:
data %>% mutate(year = year(x), month = month(x), day = day(x), hour = hour(x))  %>%
  group_by(year, month, day, hour) %>%
  split(list(.$year, .$month, .$day, .$hour))

The dummy data
x <- seq(as.POSIXct("2018-01-01 00:00:00"), as.POSIXct("2018-01-04 59:59:59"), length.out = 1000)
data <- data.frame(x)


text:
Q: What is default encryption policy that is used to perform encryption/decryption of Azure blobs I am using azure-storage sdk version: 8.3.0
com.microsoft.azure.storage.blob.BlobRequestOptions has a field 'encryption policy' (BlobEncryptionPolicy encryptionPolicy). BlobEncryptionPolicy needs implementation of IKey and IKeyResolver.
Does azure provide any implementation of IKey and IkeyResolver or default BlobEncryptionPolicy that I can use?

A: azure-keyvault-core contains the IKey and IKeyResolver. It is a small package with no dependencies. The storage client library for Java defines it as a dependency.Create a BlobEncryptionPolicy object and set it in the request options (per API or at a client level by using DefaultRequestOptions). Everything else will be handled by the client library internally.
https://learn.microsoft.com/en-us/azure/storage/common/storage-client-side-encryption-java?toc=%2fazure%2fstorage%2fblobs%2ftoc.json
You may also refer the suggestion mentioned in this link
Kindly let us know if the above helps or you need further assistance on this issue.


text:
Q: Convergence of Lebesgue measurable sets I've been working on the following result:
Let $f$ be Lebesgue measurable on $[0,1]$ with $f(x)>0$ almost everywhere on $[0,1]$. Assume there are measurable sets $E_k \in [0,1]$ with $\int_{E_k} f(x)\to 0$ as $k \to \infty$. Then $m(E_k) \to 0$ as $k \to \infty$.
I've been attempting to bound $f$ in some way as then the result follows quickly, but it doesn't seem that I can do this as the values of $f$ range over $[0,1]$.

A: Define
$$
A_k = \left\{x\in[0,1] : f(x)>\frac{1}{k}\right\} .
$$
Then $A_1 \subseteq A_2 \subseteq A_3 \subseteq \cdots$  and
$m(A_k) \to 1$ since $f$ is positive a.e.
We want to show $m(E_n) \to 0$ as $n \to \infty$.  Let $\epsilon > 0$ be given.
Choose $k$ so that $m(A_k) > 1-\epsilon/2$, so that
$m([0,1]\setminus A_k) < \epsilon/2$.  Then choose $N$ so large that
for all $n \ge N$ we have
$$
\int_{E_n} f(x)\;dx < \frac{\epsilon}{2k} .
$$
For any $n$ with $n \ge N$, compute
$$
\frac{\epsilon}{2k} > \int_{E_n} f(x)\;dx \ge \int_{E_n\cap A_k}f(x)\;dx
\ge \int_{E_n\cap A_k}\frac{1}{k}\;dx = \frac{1}{k}m(E_n\cap A_k)
$$
Then
$$
m(E_n\cap A_k) < \cfrac{\epsilon}{2} ,
$$
and therefore
$$
m(E_n) \le m(E_n \cap A_k) + m([0,1]\setminus A_k) <
\frac{\epsilon}{2}+\frac{\epsilon}{2} = \epsilon
$$

A: There exist $k_1,k_2<...$ such that $\int_{E_{k_j}} f(x)dx <\frac  1 {2^{j}}$. Hence $\int \sum_j 1_{E_{k_j}} f(x)dx <\infty$. This implies that $\sum_j 1_{E_{k_j}} f(x) <\infty$ almost everywhere. Since $f(x) >0$ a.e. this gives $\sum_j 1_{E_{k_j}}  <\infty$ almost everywhere. Hence $\lim \sup E_{k_j}$ has measure $0$.  Now apply Fatou's Lemma to $1_{E_{k_j}^{c}}$. You get  $1-m( \lim\sup E_{k_j}) \leq 1-\lim \sup m(E_{k_j})$ which shows that $m(E_{k_j}) \to 0$.
So far we have proved that $m(E_{k_j}) \to 0$ for some subsequence $(k_j)$. But we can prove that $m(E_k) \to 0$ by applying this argument to subsequences of $(E_k)$. [A sequence of real numbers tends to $0$ iff every subsbequence of it has  a further subsequence which tends to $0$].

A: How about: Suppose $m(E_k)$ doesn't tend to zero. (The following holds a.e.)
$$
\int_{E_k} f(x) \ dx = \int_{[0,1]} \chi(E_k) f(x) \ dx > \int_{[0,1]} \chi(E_k) \ dx = m(E_k)
$$
with the inequality since $f > 0$ a.e. on $[0,1]$. Then take limits as $k \to \infty$ to derive a contradiction.


text:
Q: populate dropdown on selection of other dropdown I have  two drop-down boxes. I want to populate second drop-down box on selection in the first drop-down box. My values are retrieving from database. Is this possible without using php or I need intermediate ajax and php file to get values from first drop-down and populate values file. Or this is possible without using php I mean only using Jquery. Please give me hint to do that.
Suppose I have 2 countries. First is INDIA and second is USA. ON first drop-down I am selecting countries and if first dropdown is selected than second dropdown populate its respective states.

A: if you encode your data into JSON format, then you can do something like this:
for HTML:
<select name='country' id='country'>
    <option value='india'>India</option>
    <option value='usa'>USA</option>
</select>
<select name='dates' id='dates'>
</select>

jQuery:
data = {
    india: ['2011-03-11','2010-02-01'],
    usa: ['2006-03-11','2009-02-01']
}

$('#country').change(function(){
    var dateopts = ''
    $.each(data[$(this).val()],function(i,v){
        dateopts += "<option value='"+v+"'>"+v+"</option>"
    })
    $('#dates').html(dateopts)
})

Which when the country is changed, will build and populate the options for the second select box.
See the working example here: http://jsfiddle.net/xHxcD/

The above method requires all data to be sent to client side with the initial page request. If you have lots of data, it would be better to receive the data via AJAX. It would be simplest to do this by building an object in PHP with the same data structure as your client side, then use json_encode to convert it into as JSON string and echo it out.
Reading this into your client side would then be as simple as this:
$.ajax('myJsonData.php?country=india',function(jsonData){ data.india = jsonData })

A: You could do it either way. If you dont want to use ajax, just load every single option into an object. Then when you select something from select #1, populate #2 with the assoicated array of data from your object.
If I were doing it, I wouldn't do it with ajax unless there was a TON of data.

A: Lets take an easy example, I'm using this for the same purpose that you want and it works perfectly fine.
This is the country dropdown:
<?php
        $countrylist=mysql_query("SELECT * FROM country ORDER BY name ASC");
        echo "<select name='country' id='country' onchange=\"reload(this.form)\" title='Country e:g; United Kingdom,Pakistan'><option value='0'>Select Country</option>";
        while($clist=mysql_fetch_array($countrylist))
        {
          echo "<option value='$clist[Name]'>$clist[Name]</option>"."<br/>";
        }
        echo "</select>";
 ?>

This is the region dropdown:
<select name="region" id="region" ></select>

Now make a seperate file named crlist.js and include it in the page having above code like this:
<script  type="text/javascript" src="crlist.js"> </script>

code for crlist.js:
var request = false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
request = false;
}
}
@end @*/
function fillSelect(country,path) {
var url = path+"crlist.php?country=" + country;
request.open("GET", url, true);
request.onreadystatechange = go;
request.send(null);
}

function go() {
if (request.readyState == 4) {
//if (request.status == 200) {

var response = request.responseText;

var list=document.getElementById("region");
            for (i = list.length - 1; i>=0; i--) {
                list.remove(i);
            }
var records=response.split('|');
for (i=1; i<records.length; i++) {
    //alert("rcord="+records[i]);
    var record=records[i].split('*');
    var region=record[0];
    //alert("region="+region);
    var regionid=record[1];
    //alert("regionid="+regionid);
    var x=document.createElement('option');
    //var y=document.createTextNode(region);
    x.text=region;
    //x.value=region;
    //alert(x.text);
   //x.appendChild(y);
   //list.appendChild(x);
   list.options.add(x);
   }
  //}
 }
}

function initCs(path) {

if (!request && typeof XMLHttpRequest != 'undefined') {
request = new XMLHttpRequest();
}
var country=document.getElementById('country');
    country.onchange=function() {

        if(this.value!="Select") {

            var list=document.getElementById("region");
            for (i = list.length - 1; i>=0; i--) {
                list.remove(i);
            }
        //while (list.childNodes[0]) {
        //list.removeChild(list.childNodes[0]);
        //}
        }
        fillSelect(this.value,path);
        //alert(this.value);

    }
//fillSelect(country.value);
}

Now make a seperate file named crlist.php.
Code for crlist.php:
<?php
require_once 'yourconfigfile.php';

$cname = $_GET['country'];

$query="select ID,Name from city where CountryCode=(select code from country where name='$cname') Order By Name ASC";
$res = mysql_query($query) or die(mysql_error());
while($region = mysql_fetch_array($res)){
    echo "<option value='".$region['Name']."'>".$region['Name']."</option>";
}
?>

Now add following script on the page having dropdowns:
<script  type="text/javascript" src="crlist.js"> </script>
<script>
$(document).ready(function() {

    initCs("");

});
</script>

This is my own script, and i've assumed that you have created country and region tables. But you need to tweak the queries and above code according to your db structure.
Reference to my answer: Cascade Dropdown List using jQuery/PHP
Hope this helps.

A: Yes you can do it without using php. For that you've to assign two different states list in Javascript array and base on the selection just change the options in the other select box. As simple as that.
You can assign the javascript array using your serverside scripting language while loading the page if you're using database to store the states.
But do not do this unless you've very small amount data. In your case you've only 2 countries so you can go ahead with it.


text:
Q: Reading lines from an input file? Hi I have a few errors that are puzzling me. One of them is huge and the other is just bothering me.
So just a few things before you suggest I make other functions: The prototypes I made were specified by my teacher. I'm not allowed to use any functions other than the ones he instructed me to use. So I'm not allowed to make up any functions to fix my problems.
In my COPY function, I'm using a linebuffer reading into an input file to take each line from my input text and printing it onto my output file. My problem is that if I don't add a null newline in my input, the function reads 1 less line.
for example if I have 5 lines of text in my input file, and don't press enter after my last line, it will only print 4 lines of text.
Second, I'm getting these errors:
Error   2   error LNK2019: unresolved external symbol "int __cdecl calcFactorial(void)" (?calcFactorial@@YAHXZ) referenced in function _main    C:\Users\UserName\Documents\CS161\Atilla\main\main\main.obj main

Error   3   error LNK1120: 1 unresolved externals   C:\Users\UserName\Documents\CS161\Atilla\main\Debug\main.exe    1   1   main

And this warning:
Warning 1   warning C4996: 'strerror': This function or variable may be unsafe. Consider using strerror_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.    c:\users\UserName\documents\cs161\atilla\main\main\main.cpp 127 1   main

Then from time to time, all my "cout"s get errors saying "cout is ambiguous"
Any suggestions to fixing my errors? Sorry if there's a lot. I searched for solutions online but I don't quite understand how to fix it. Can someone explain for a newbie like me? Thanks
Oh and heres my code:
#include <iostream>
#include <string>
#include <fstream>
#include <cmath>

using namespace std;

int getUserOption();
void copyFiles();
string getFileName();
int calcFactorial();
void countWords();
void countBytes();

int main()
{
    //List of main variables
    int option;
    int userFactorialInt;

    do {
        option = getUserOption();
        switch (option) {
        case 0:
            break;
        case 1:
            cout << "\n\nYou Chose COPY\n" << endl;
            copyFiles();
            break;
        case 2:
            cout << "\n\nYou Chose FACTORIAL\n" <<
                "\nPlease type an integer number between 1 and 12: ";
            cin >> userFactorialInt;
            cin.ignore(8192, '\n');
            if (userFactorialInt >= 1, userFactorialInt <= 12)
            {
                cout << userFactorialInt << "'s factorial is: " << calcFactorial() << endl << endl;
            }
            else
            {
                cout << "Error, the number must be between 1 and 12" << endl;
            }
            break;
        case 3:
            cout << "\n\nYou Chose COUNT WORDS\n";
        case 4:
            cout << "\n\nYou Chose COUNT BYTES\n";
        case -1:
            cout << "\n\n*Invalid option entered.* Did you remember to type the word"<<
                "\nin full caps? A valid option is demonstrated below:"<<
                "\n(example) \nEnter Option: COUNT WORDS \n\n" << endl;
            getUserOption();
            break;
        }
    } while (option != 0);
    cout << "Program ending" << endl;

    return 0;
}

int getUserOption() {
    string userInput;
    cout << "-------------------------------------------------------------------------------\n"<<
        "Enter one of the following options in full capital letters as it appears:\n\n" <<
        "QUIT - Exit the program\n" <<
        "COPY - Copy the contents of a .txt file\n" <<
        "FACTORIAL - Calculate the factorial of an integer between 1 and 12\n" <<
        "COUNT WORDS - Count the number of words in a .txt file\n" <<
        "COUNT BYTES - Count the number of bytes in a .txt file\n" <<
        "Enter option: ";

    getline(cin, userInput);
    if (userInput == "COPY") {
        return 1;
    }
    else if (userInput == "FACTORIAL") {
        return 2;
    }
    else if (userInput == "COUNT WORDS") {
        return 3;
    }
    else if (userInput == "COUNT BYTES") {
        return 4;
    }
    else if (userInput == "QUIT") {
        return 0;
    }
    else {
        return -1;
    }
    return 0;
}

string getFileName()
{
    string inFileName;
    cout << "Enter input file address: ";
    getline(cin, inFileName);
    return inFileName;
}

void copyFiles()
{
    ifstream inFile;
    ofstream outFile;

    string inputFileName, outputFileName, lineBuffer;

    cout << "Enter output file name: ";
    getline(cin, outputFileName);

    do
    {
        inputFileName = getFileName();
        inFile.open(inputFileName.c_str());    //Try the open inputFileName
        if (inFile.good() != true) { // If "it works" is not true,
            cout << "Error: Invalid input file address. \n" //tell the user it doesn't work.
                 << strerror(errno) << endl; //If open did not work tell why
            cout << "Please type a valid file address\n" <<
                "eg: C:\\Users\\ThisUnit\\Documents\\CS161\n";
        }
    } while (inFile.good() != true);             //Loop as long as the open fails

    outFile.open(outputFileName.c_str());        //Open the output
    do {
        getline(inFile, lineBuffer);            //Read a line of input
        if (inFile.eof() != true) {
            outFile << lineBuffer << endl;    //If read worked, write to output
        }
    } while (inFile.eof() != true);            //Repeat for all lines in the file

    inFile.clear();
    inFile.close();
}

**Thanks for the edits

A: You must learn about the difference between declaring and defining.
With int calcFactorial() you've just declared that a function called calcFactorial exists. This enables you to use it in the code after the declaration, as in the line
cout << userFactorialInt << "'s factorial is: " << calcFactorial() << endl << endl;

The problem you are getting is a linker error. The linker (the program in charge of putting together all the components of your program) is complaining that you've said you are using a function that it cannot find a definition for.
The definition, i.e. something of the sort:
int calcFactorial() {

   // Do things to calculate the factorial

   return theComputedFactorial;
}

Must be present somewhere in your program:

*

*Either on the same compilation unit (your main.cpp) that it is using it.

*Or on a different compilation unit (other *.cpp... that you can link into the program, or packed into a library that you will link into the program.

There must be only one definition.

About the warning on strerror. This functions returns a pointer to an internal buffer and it is not thread-safe. See more at Why can't I use strerror?

Not sure what the problem is with your cout is ambiguous


text:
Q: Dinner party combinatorics (meeting each other once) I am hosting a meet-and-greet dinner party but am having troubles with some elementary combinatorics. I got 20 people for a dinner party and they can only sit at tables in groups of 4. What is the minimum number of table arrangements required so that everyone gets to meet each other at least once?
Intuitively, the upper bound is going to be 20 choose 4 = 4845, as these are the total number of ways to choose sub-groups of 4 from a group of 20. However, this number seems too high but I don't know exactly how to work from here.
For a simpler case, if I have 5 people and have tables for 4, it seems I only need 3 different rounds of table arrangements to get my result: (1,2,3,4)5; 1(2,3,4,5); (1)2(3,4,5). Everyone has met everyone now. Clearly 5 choose 4 = 5 > 3. But I'm having troubles finding the exact principle here. The furthest I've gone is that we have 5 choices for the 1st member of a group of 4, 4 choices for the 2nd member, 3 choices for the 3rd, and 2 choices for the 4th. But I am not sure what number to divide this by to get the result we want.
Thanks in advance.

A: Here's your party schedule in $7$ rounds:
14 16  1  0    11  5  9  8    10 12  2  7    19 17 15 13    18  3  6  4
11  7 17 16    15 12  0  6     1 18  8 10    13  9 14  3     5  4  2 19
 3 11  0  2    17 14 10  4    18 15  9  7     6  8 19 16    13  5  1 12
10  9  0 19    13  4 15 16     2 11 18  1    14  7  6  5    12  8  3 17
 3  7  1 19    11 13 10  6     9 12 16  4     5  0 18 17    14 15  2  8
 1 17  6  9    12 11 14 19    15  5 10  3     7  8  0  4    18 13  2 16
16 10  3  5    18 14 19 12     8  7 13  0     2  6  9 17     1 15  4 11

Here's the simulated annealing code I wrote to find it.
Since everyone needs to meet $19$ people and can only meet $3$ new people per round, this is optimal.

A: You must cover $\binom{20}{2}$ pairs, and each round covers $5 \binom{4}{2}$ pairs, so a lower bound is $$\left\lceil\frac{\binom{20}{2}}{5 \binom{4}{2}}\right\rceil = 7$$ rounds.
8 is an upper bound:
1
{1,2,3,4}
{5,6,7,8}
{9,10,11,12}
{13,14,15,16}
{17,18,19,20}
2
{1,7,15,20}
{3,6,16,18}
{9,12,14,17}
{4,5,10,11}
{2,8,13,19}
3
{8,9,12,20}
{4,16,17,19}
{3,11,13,15}
{1,5,7,18}
{2,6,10,14}
4
{7,10,15,19}
{3,4,8,14}
{5,6,12,16}
{2,11,17,20}
{1,9,13,18}
5
{10,14,18,20}
{1,6,11,19}
{5,8,15,17}
{3,4,12,13}
{2,7,9,16}
6
{1,12,14,19}
{4,6,9,15}
{3,7,10,17}
{2,5,13,20}
{8,11,16,18}
7
{7,11,12,14}
{1,8,10,16}
{6,13,15,17}
{3,5,9,19}
{2,4,18,20}
8
{3,6,16,20}
{1,8,17,19}
{5,9,11,14}
{2,12,15,18}
{4,7,10,13}


text:
Q: Why does the formula for $\tan 3\theta$ work at $\theta=\frac\pi4$ even though its proof involves cancelling $1-\tan^2\theta$? Here's a proof for the $\tan 3\theta$ formula:

According to the procedure for the proof, when we cancel out $1-\tan^2\theta$, the value of $1-\tan^2\theta$ should not be equal to $0$ (in particular, $\theta$ should not be $\frac{\pi}{4}$) as $\frac{ax}{bx}=\frac{a}{b}$ only if $x$ isn't $0$.
But, when we substitute $\theta=\frac{\pi}{4}$ in the final formula, we still get the correct answer:
$$\frac{3\tan\frac{\pi}{4}-\tan^3\frac{\pi}{4}}{1-3\tan^2\frac{\pi}{4}}=\tan\frac{3\pi}{4}=-1$$
How is this possible?

A: This question has been answered in a comment but an important point to make here is that proving something is true for a smaller set of values does not say anything about whether it is true on a larger set of values.
Consider the theorem "For $m,n\in \mathbb{Z}$, $m+n$ is even if $m$ and $n$ are odd".
Suppose $m=2a+1, n=2b+1$. Then $m+n=2(a+b+1)$ which is even.
This theorem is of course true when both $m$ and $n$ are  even, but the proof is not identical.
EDIT: Also it is slightly overkill to use continuity here. Having $\tan^2 x=1$ be the only problematic value here, we can verify the case $x=\frac{\pi}{4}$ then use identities.

A: You could also first compute the triple angle formulas for sine and cosine,
$$
\sin(3x)=\frac1{2i}(e^{i3x}-e^{-i3x})=\sin(x)(e^{i2x}+1+e^{-i2x})=\sin(x)(-4\sin^2(x)+3)\\
\cos(3x)=\frac12(e^{i3x}+e^{-i3x})=\cos(x)(e^{i2x}-1+e^{-i2x})=\cos(x)(4\cos^2(x)-3)\\
$$
so in consequence
$$
\tan(3x)=\tan x\,\frac{3\cos^2x-\sin^2x}{\cos^2x-3\sin^2x}=\tan x\,\frac{3-\tan^2x}{1-3\tan^2x}
$$


text:
Q: How do I move a client side script call over to the server? (Google Drive Spreadsheet Feed) I'm working with Google drive sheets and using them as a simple data store.  Google makes it very friendly to obtain a feed from a public sheet via a client side script call in the browser.
<script type="text/javascript">
    function useJSONdata(root) {
        var feed = root.feed;
        var entries = feed.entry || [];
        var html = [''];
        for (var i = 0; i < entries.length; i++) {
            var entry = entries[i];
            (process the data, etc...)
        }
    }
</script>

<body>
    <script src='https://spreadsheets.google.com/feeds/list/xxxxxxxxxxxxxxxx/od6/public/full?alt=json-in-script&callback=useJSONdata'></script>
</body>

There is a lot of info available on this technique.  Old technique here, and here.  Here's a link to a handy flash card tool I wrote, code all visible in your browser's dev tools.
But in my current use case, I'd like access to the Google spreadsheet data from node.js in the server.  I'm not seeing the best translation of <script src='https://...&callback=...'></script> from document client code to valid server code.
I've been attempting to make this work using https requests, both GET and POST.  I can see that those requests are obtaining data, but the returned data is bizzare.  I'm looking at 7000 lines of returned info on a spreadsheet with ten lines of content.
here is a curl command to look at my test spreadsheet data:
curl https://spreadsheets.google.com/feeds/list/1s9-AyqYqp25s2OeGiglCSNF2UcvJJm50Ipvm8v0Mgo0/od6/public/full?alt=json-in-script
Data returned from a browser <script src=... request:
encoding:"UTF-8"
feed:
    author:[{…}]
    category:[{…}]
    entry:(167) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, …]
    id:{$t: "https://spreadsheets.google.com/feeds/list/xxxxxxxx/od6/public/full"}
    link:(4) [{…}, {…}, {…}, {…}]
    openSearch$startIndex:{$t: "1"}
    openSearch$totalResults:{$t: "167"}
    title:{type: "text", $t: "Sheet1"}
    updated:{$t: "2015-04-04T19:31:32.089Z"}
    xmlns:"http://www.w3.org/2005/Atom"
    xmlns$gsx:"http://schemas.google.com/spreadsheets/2006/extended"
    xmlns$openSearch:"http://a9.com/-/spec/opensearchrss/1.0/"
__proto__:Object

I've been looking at the returned data from my node.js https GET server request (via chrome debugger tools) and that data is unusable.  A POST request nets me a statusCode 405 error.
response: IncomingMessage
    client:TLSSocket {_tlsOptions: {…}, _secureEstablished: true, _securePending: false, _newSessionPending: false, _controlReleased: true, …}
    complete:false
    connection:TLSSocket {_tlsOptions: {…}, _secureEstablished: true, _securePending: false, _newSessionPending: false, _controlReleased: true, …}
    domain:null
    headers:{content-type: "application/atom+xml; charset=UTF-8", x-robots-tag: "noindex, nofollow, nosnippet", expires: "Wed, 27 Dec 2017 02:50:15 GMT", date: "Wed, 27 Dec 2017 02:50:15 GMT", cache-control: "private, max-age=0, must-revalidate, no-transform", …}
    httpVersion:"1.1"
    httpVersionMajor:1
    httpVersionMinor:1
    method:null
    rawHeaders:(38) ["Content-Type", "application/atom+xml; charset=UTF-8", "X-Robots-Tag", "noindex, nofollow, nosnippet", "Expires", "Wed, 27 Dec 2017 02:50:15 GMT", "Date", "Wed, 27 Dec 2017 02:50:15 GMT", "Cache-Control", "private, max-age=0, must-revalidate, no-transform", "Vary", "Accept, X-GData-Authorization, GData-Version", "GData-Version", "1.0", "Last-Modified", "Tue, 26 Dec 2017 20:36:41 GMT", "Transfer-Encoding", "chunked", "P3P", "CP="This is not a P3P policy! See g.co/p3phelp for more info."", "P3P", "CP="This is not a P3P policy! See g.co/p3phelp for more info."", "X-Content-Type-Options", "nosniff", "X-Frame-Options", "SAMEORIGIN", "X-XSS-Protection", "1; mode=block", "Server", "GSE", "Set-Cookie", "NID=120=CFx_iglHazKNNR7tH33m4UkGABss7TV9bB03EVnZrH…=/;Expires=Thu, 28-Jun-2018 02:50:15 GMT;HttpOnly", "Set-Cookie", "NID=120=W3n0zQ1UWJz6pmTOjKjAxuMtG5WOLx2D3OiQca5R9A…=/;Expires=Thu, 28-Jun-2018 02:50:15 GMT;HttpOnly", "Alt-Svc", "hq=":443"; ma=2592000; quic=51303431; quic=5130333…03335,quic=":443"; ma=2592000; v="41,39,38,37,35"", "Connection", "close"]
    rawTrailers:[]
    read:ƒ (n)
    readable:true
    req:ClientRequest {domain: null, _events: {…}, _eventsCount: 2, _maxListeners: undefined, output: Array(0), …}
    socket:TLSSocket {_tlsOptions: {…}, _secureEstablished: true, _securePending: false, _newSessionPending: false, _controlReleased: true, …}
    statusCode:200
    statusMessage:"OK"
    trailers:{}
    upgrade:false
    url:""
    _consuming:true
    _dumped:false
    _events:{end: ƒ, data: ƒ}
    _eventsCount:2
    _maxListeners:undefined
    _readableState:ReadableState {objectMode: false, highWaterMark: 16384, buffer: BufferList, length: 0, pipes: null, …}
    destroyed:(...)
    readableHighWaterMark:(...)
    __proto__:Readable

Is there a better way to convert that <script src=... code to a server request for data from a Google Drive Spreadsheet??  Anybody been here before?

A: So I was able to figure this one out. I ended up using the 'request' tool, in lieu of an HTTPS format.
var request = require('request');
request.get(
    'https://spreadsheets.google.com/feeds/list/1s9-AyqYqp25s2OeGiglCSNF2UcvJJm50Ipvm8v0Mgo0/od6/public/full?alt=json',
    function(error, response, body) {
        console.log('error: ', error); // print the error if one occurred.
        console.log('statusCode: ', response && response.statusCode, "\n\n\n"); // Print the response status code if a response was received
        console.log("response.body: ", response.body, "\n\n\n");
    }
}

This worked easily enough.  There was one trick, the use of ?alt=json in the feed address.
Do note, this technique seems to be superseded with version 4 of the Google Sheets Api, which now includes OAuth tokens / credentials.  The use of that API makes sense for all new work going forward.


text:
Q: MySQL on delete cascade, FK in source table I have 2 tables, customer and address. Customer has column address with FK referencing to table address.
Table customer
create table customer
(
    id int(11) not null primary key,
    ...
    address    int(11) null,
    constraint fk_customer_address
        foreign key (address) references address (id)
        on update cascade on delete cascade,
)

Table address
create table address
(
id int(11) not null primary key,
...
)

I want to have address id in customer table, because in future there will be more tables referencing to address table (Users.address, Business.address, etc) and one table for all addresses because of the same format.
When I delete row in customer table, address row stays in DB.
Is it possible to use this FK relation to delete row in address table, or do I have to delete it manually (programmatically)?
Does this mean that when I delete row from address, customer row is deleted as well?
Edit:
Yes, it does.

A: You probably don't want customer rows deleted when an address row is deleted. I think the fk would be correct if it was defined as "on delete restrict" or "on delete set null".
So that if you wanted to delete the address record:

*

*on delete set null ➞ All references to that address would be set as null

*on delete restrict ➞ You should manually update the address_id it on ALL child tables to some other value (or null) and then delete the parent row

You could somehow avoid the programatic deletion by defining the fk the opposite (that is: address table has a foreign key to customer table, and others)
However, for me this feels somewhat unnatural since you would have to add a new column on the address table for each other table you want to reference. It feels more natural for each table to have the fk of the address.
Another drawback is that it would not allow you to reuse same address on the same table. For example, if two customers would share the same address, you would need to create a row for each of those customers.
With the first solution you would just need a single row on the address table, that could be referenced multiple times on the customer table by different customers.
Of course, your requirements may be a 1:1 relationship. But remember that requirements can change :). And if they do, and you later require to share same address between different rows, you are ready to go with the first solution.
I would use your original approach with a "on delete set null" constraint.


text:
Q: Calling member procedure NULL SELF argument Oracle I have a type myType declared with a member procedure insert_obj.
When i try this code, i get the following error:
declare
   v_obj myType;
begin
   v_obj.insert_obj(1,2,3);
end;

ORA-30625: method dispatch on NULL SELF argument is disallowed

I am assuming this is because i have no object on which to call the method...
but i cannot do
select value(a) into v_obj from myTable

because the table is empty (and i want to insert into it).
How then do i get an object to call my method on?
Thanks

A: You can use a constructor:
v_obj myType := new myType();


text:
Q: Is update by select atomic for READ_COMMITED in postgres? Is following query atomic within READ_COMMITED transaction?
update my_table
 set
   owner = ?,
 where id = (
   select id from my_table
   where owner is null
   limit 1
 ) returning *

I run tests on local postgres instance and it seems to be atomic, but is this always the case?

A: Each SQL statement in READ COMMITTED isolation level takes a snapshot of the database, so it and all its subqueries see a consistent version of the database.
But you are not safe from "lost updates": it is possible that a concurrent transaction modifies a row between the start of the statement and the time the row is updated, so it could be that the row that is actually updated does not have owner set to NULL any more.
If you need to avoid that, add a FOR UPDATE clause in the subquery.


text:
Q: Complicated sorting in Python I need to sort a list of strings.
However, I do not want to sort it using the first character, so I cannot use .sort()
I have a list:
records = ["Bibble - 1300 / 2000",
"Jim Foo - 900 / 2000",
"Bibble - 1600 / 2000",
"Bibble - 1000 / 2000"]

I want to sort by their score out of 2000.
I want an output that looks something like this:
>>> Jim Foo - 900 / 2000
Bibble - 1000 / 2000
Bibble - 1300 / 2000
Bibble - 1600 / 2000

In the example above, I sorted it by smallest to largest. I also want to know how I would sort this list biggest score to smallest score.
I've tried .sort(), but It's nothing like what I want. .sort() sorts it with the first character which I do not want:
>>> records.sort()
>>> records
['Bibble - 1000 / 2000', 'Bibble - 1300 / 2000', 'Bibble - 1600 / 2000', 'Jim Foo - 900 / 2000']
>>>

Is there anyway of doing this, possibly in regular expression?
Is it also possible, so if i were to add more scores into the list I would still be able to sort it this way?

A: You can use sorted function with a proper key and use re.split :
>>> import re
>>> sorted(records,key=lambda x:int(re.split(r'[-/]',x)[1].strip()))
['John Smith - 900 / 2000',
 'Bob Foo - 1000 / 2000',
 'Bob Foo - 1300 / 2000',
 'Bob Foo - 1600 / 2000']

The sorted function sort your list based on its key function, and your key split your elements with re.split with function as following :
re.split(r'[-/]',x)

the pattern [-/] split your string based on - or /.
for example :
>>> re.split(r'[-/]',"Bob Foo - 1600 / 2000")
['Bob Foo ', ' 1600 ', ' 2000']

and then you need to strip() to remove the leading and trailing spaces. then convert to int and sort your list based on that value!

A: def f(e):
    a, b = map(float, e.split('-')[1].split('/'))
    return a / b

records.sort(key=f)

A: Use the key attribute of the sort method:
import re
records.sort(key = lambda x: int(re.split('[-/]', x)[1]))

re.split splits x into parts whenewer it encounters a - or / character - that's what the [-/] expression stands for. Then we select the second part, convert it to an integer and use this value for sorting.

A: >>> import re
>>> records = ["Bob Foo - 1300 / 2000",
"John Smith - 900 / 2000",
"Bob Foo - 1600 / 2000",
"Bob Foo - 1000 / 2000"]
>>> def get_score(s):
    m = re.match(r'.* - (\d+) / 2000', s)
    return 0 if m is None else int(m.group(1))

>>> sorted(records, key=get_score)
['John Smith - 900 / 2000', 'Bob Foo - 1000 / 2000', 'Bob Foo - 1300 / 2000', 'Bob Foo - 1600 / 2000']

get_score will calculate the key of each record, and sort or sorted will sort records according to this value.

A: *

*sort accepts optional key parameter. E.g. if you want to sort int list by power of number you can do something like [-3, 2, 1].sort(key=lambda x: x *x)

*I'm pretty sure you can write function which extracts number 1000 from "Boo Foo - 1000 / 2000". Hint: use split.


text:
Q: check if value greater than a number exists in 2D array I have a 2d array in the format
emi_309 | weak   | 16
emi_310 | strong | 9
emi_319 | medium | 8
emi_315 | weak   | 5

I want to check if a value greater that a certain number (e.g > 5) exists in the 3rd column using a simple function like the following:
  ($.inArray( conditions greater than 5 here, $.map(myArray, function(v) { return v[2]; })) > -1)

How do I include the condition (>5) in the above function?
Thanks a lot for your help

A: It is better to use $.grep in this case:
if ($.grep(myArray, function(v) { return v[2] > 5; }).length) {
    // values > 5 exist
}

A: The $.inArray only tests against a specific value (checks equality) so it will not help you in this case.
you could change the inArray to be able to handle a predicate as it's first argument.
Changing "base libraries" like this should be done carefully and you might want to create a different function. However in this specific case I feel that the ability to pass a function resembles that of other jQuery functions
var org_inArray = $.inArray
$.inArray = function(value, array, fromIndex){
  if($.isFunction(value)){

      var start = fromIndex || 0,
          matches = $.grep(myArray.slice(start), function(e,i) {
         if(value(e,i)) return i;
      }
      return matches ? matches[0] : -1;
  } else {
     arguments.length > 2 ?
             org_inArray.call($,value,array,fromIndex) :
             org_inArray.call($,value,array)
  }
}

you would then be able to use it like
if($.inArray( function(e) { return e[2] > 5;}, myArray) !== -1){
}

A: Something like this is pretty simple:
var firstMatch = function(arr, cond) {
    for (var i = 0, len = arr.length; i < len; i++) {
        if (cond(arr[i])) {return i;}
    }
    return -1;
};

if (firstMatch(myArray, function(v) { return v[2] > 5; }) > -1) { ... }

If you really want this in the jQuery namespace, just attach it to jQuery:
jQuery.firstMatch = function(Arr, cond) { ...

and call it like
if ($.firstMatch(myArray, function(v) { return v[2] > 5; }) > -1) { ... }


text:
Q: When a large block of memory is requested on the heap, if contiguous space is not available on the RAM, is it allocated on the disk(swap)? In Linux, when memory is requested (using calloc / malloc), if a contiguous block of the requested size is not available does the kernel map multiple separate pieces of memory into one single virtual block and hand it over to the application or is it allocated on disk?
If it is allocated on disk, when a large enough block becomes free, is it automatically moved to the RAM or does it live on the disk for its life?

A: In all Virtual Memory capable OS's, nowadays all, the kernel uses a pool of different strategies together to manage the memory.
The processor guarantees to programs that memory exists up to the nominal addressing capability of the processor, or something less depending on specs. So you're allowed to allocate memory up to MAX legal memory amount for that OS.
The resources used are the physical memory installed in the system and disk storage.
Depending on program requests, the MM (memory manager) allocates virtual space: the OS creates a data structure that describes the requested memory (generally referred to as creating paging directories), but no real memory is allocated. The next stage is called commitment, you get into this stage when trying to access the memory previously allocated. If there is any physical memory available, the MM, called through the exception generated by the attempt to access the memory, commits pages of real memory, inserting their address in the page directory, then control flows back to user code. Now the memory exists!
And if we try to access memory not allocated? This is the case of invalid memory access that generates an exception, in Linux a SegFault.
Going back to the physical memory commitment, what if there is no more physical memory available? The MM use different algorithms to look for physical memory not accessed for a long time, no more requested or discardable. Even other things get involved such as task priority, task state (suspended tasks are good candidates for memory recollecting), etc. All this physical memory can be recollected, its contents saved in a swap file on disk (paging file), and physical storage can then be mapped into the new process.
The reverse process is made when a program tries to access its memory currently cached on disk. The MM recollects physical memory from other processes (using the same techniques described above), commits it in process space, copies data from the disk cache and then gives back control to user code.
All these processes are completely transparent to the user, and you don't have to worry about it.
If you want to read more search for memory management, paging files, GDT (Global Descriptor Tables) and LDT (Local Descriptor Tables) here for X86 architectures, other processor use different structures and registers, but the principle is the same.


text:
Q: Beginner question about proof reading and intuition So I have a soft beginner question about reading proofs. Proof is provided below.
For some reason I may stumble over expressions like this, finding it hard to accept their truth.

The equation $a=qd+r$ yields
\begin{align*} r&= a-qd\\  &= a-q(ak+b\ell)\\  &= a(1-qk)+b(-q\ell) \\
 \end{align*} ...and until the end of the paragraph.

I mean I can see from the algebra that $r$ turns out to be of the form sufficient to place it in the set A, but nothing clicks in my mind, there's no intuition for me behind it, and so I find it hard to accept that $r$ is in $A$ (and, for that reason, the rest of the paragraph explaining how $r$ must be $0$), which is what I'm concerned about.
I wonder what should be the subjective feeling as you read through proofs like these? Do you just accept things as true because you accept algebra works (or  that axioms, definitions, etc. are true) and you don't question it/them at that moment. You see that algebraic operations lead you to the expression and you accept the end result?

A: From the division algorithm we know that $r$ is an integer such that $0 \leq r < d$. Right?
Now, given this information about $r$, we also know that we have chosen $d$ to be the smallest positive element in the set $A$.
So, once we (manage to) show that $r$ is also in $A$, then from the information we have at our disposal we can conclude that $r$ cannot be positive and so must be zero.
Thus everything boils down to showing that $r$ is in $A$. For this, we solve the division algorithm equation for $r$, and finally substitute the expression for $d$ and then collect terms, thereby arriving at our desired form for "placing" $r$ into set $A$.
Does this help you?

A: My subjective feeling in the case of stumbling would be that the proof, though perfectly correct, is not well-written. Well-written proof should be designed in such a way that the reader could understand ideas behind it and maybe understand how it was possible to come up with such a proof. In this particular case the proof failed to do this: it is written in a way that it is difficult to imagine how it was constructed. However, in general it is not always the case: it may as well mean that the statement is just tough to comprehend at your current level in math.
Of course, you shouldn't question the validity of a proof if you checked reasoning. But if you don't understand the deep logic behind some proof, consider googling the proof of the same statement in another place. However, note that math is hard and it is common that almost every proof in some book calls the same reaction. This may point out that you use a wrong book.
Anyway, if the topic is hard it is usually not a big problem if you don't understand ideas while understanding reasoning, as soon as you manage to do the provided exercises on the topic.
P.S. I'm an undergraduate student who has some experience in math and reading math books. So my feelings can be wrong, and probably you can get a much better answer on the topic from people who teach math.


text:
Q: RecyclerView make item span multiple rows I have a collection of photos, and I'm using a RecyclerView to display them. I want to have the first element in my RecyclerView span 2 columns AND 2 rows:

How can i achive that , i know that using GridLayoutManager you can do this
  GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
    @Override
    public int getSpanSize(int position) {
        if (position == 0) {
            return 2;
        } else {
            return 1;
        }
    }
});

but this only take columns not rows , So How can i achieve this layout in RecyclerView  ? ,, Note : this layout is used in instagram and Google Photos.
this question has been asked befor but with no solution "Good solution"


text:
Q: Transform Dot Notation to JSON - javascript How to convert dot notation to JSON? Below sample dot that getting from BE & I need to convert it to JSON, example -
digraph {
"Stream|4a150498-7f00-430b-861d-88d3ea381f66" [name=Stream,inputs="
['']",Properties="{}",Position="[50,50]"]
"From|6624da0b-7b2d-4381-a2c3-4f00c9cf9e0b" [name=From,inputs="
['']",Properties="{'Database':['cloudDB'],'Measurement':
['sensorData'],'RetentionPolicy':['oneUnit']}",Position="[317,49]"]
}

Is there a method or npm library in Javascript that will help me to achieve the above. Guys pls share ..


text:
Q: Change White to transparent in Imagick for PHP I'm trying to create a map of the United States that updates as US presidential candidates are declared the winner of different states. To do this I have a bunch of state pictures in various colors (red, blue, striped, etc..) which I will stitch together to create the full map and save it as an image.
The state images are all jpegs and I don't have the ability to turn them into a format that supports transparency. My question is how do I make the white background of these .jpg images transparent once I have pulled them into Imagick?
I have the following code which only shows the last image that was added to the map because its white background is covering the rest.
$us_map = new Imagick();
$us_map->newImage(
  self::MAP_WIDTH,
  self::MAP_HEIGHT,
  new ImagickPixel('none'),
);
$us_map->setFormat('png');
foreach ($curls as $curl) {
  $state = new Imagick();
  $state->readImageBlob($curl->getBody());
  // What do I do here to change all white in $state to transparent?
  $us_map->addImage($state);
}
$file_name = '/tmp/pic.US_MAP.'.request_time().'.png';
$us_map->writeImage($file_name);