text:
Q: How to set constraints from the bottom of a collectionView to the top of Input Accessory View in Swift 4 so I am having a bit of a trouble getting one of my constraints right.Basically I am using storyboard to put two views on the screen. One is a UITextView and the other is a collectionView. CollectionView is underneath UItextView. I want my collectionView's bottom constraint to be connected to the top of my Input Accessory View which pops up everytime keyboard appears.
By doing this I am essentially making the textview height dynamic. Is there any way I can do this?
Here is a picture
 The two circles are part of Input Accessory View. I want the collectionview which is the priority levels to be connected to the top of the input accessory view.
Here is another picture with detailed labeling and markup:
Detailed markup
Please help!

A: You can add the constraint programatically with something like this:
Option 1:
let bottomContraint = NSLayoutConstraint(item: self.collectionView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.textField, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 8.0)

self.view.addConstraint(bottomContraint)

Option 2:
Using the storyboard, hold down the control key and drag from the textfield to the collection view, then click on vertical spacing. You can then tap edit the constraint and check the first item is textField.Top and second item is collectionView.Bottom. You can then change the constant, including using a negative number is need be.

A: First, create a constraint from your accessory to the bottom of the screen.

And then link it to an IBOutlet in your view controller:

You have to react to events of keyboard shown and hide. So you register for notifications from the UIKit about that. Upon this events you dynamically change your height.
Add this to your implementation of the view controller:
@IBOutlet weak var constraintToChange: NSLayoutConstraint!

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    NotificationCenter.default.removeObserver(self)
}
//other methods skipped

@objc func keyboardWillShow(_ notification: Notification) {
    guard let userInfo = notification.userInfo else {
        return //no info to get keyboard size from
    }
    guard let keyboardSize =  (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue else {
        return //no keyboard size to determine height
    }

    constraintToChange.constant = keyboardSize.height //+ your desired height above keyboard
}

@objc func keyboardWillHide(_ notification: Notification){
    constraintToChange.constant = 0.0 //+ your desired height above bottom of the screen
}

Now the most important bit. Your text view has to satisfy to conditions:

*

*It's height constraint has to be set to "less than or equal" to allow it to shrink.

*It's content hugging priority has to be of highest value among all of your views. This enables shrinking.

*It' content compression resistance priority has to be low. This guarantees that it won't block shrinking.

here is a proper tab (the one with ruler) visible when you click on the height constraint of your text view:

and what you should see when you open text view (again ruler tab) in interface builder:

The effect is as shown here:


text:
Q: Getting percentile values from gamlss centile curves This question is related to: Selecting Percentile curves using gamlss::lms in R
I can get centile curve from following data and code:
age = sample(5:15, 500, replace=T)
yvar = rnorm(500, age, 20)
mydata = data.frame(age, yvar)
head(mydata)
  age      yvar
1  12  13.12974
2  14 -18.97290
3  10  42.11045
4  12  27.89088
5  11  48.03861
6   5  24.68591

h = lms(yvar, age , data=mydata, n.cyc=30)
centiles(h,xvar=mydata$age, cent=c(90), points=FALSE)

How can I now get yvar on the curve for each of x value (5:15) which would represent 90th percentiles for data after smoothening?
I tried to read help pages and found fitted(h) and fv(h) to get fitted values for entire data. But how to get values for each age level at 90th centile curve level? Thanks for your help.
Edit: Following figure show what I need:

I tried following but it is correct since value are incorrect:
mydata$fitted = fitted(h)
aggregate(fitted~age, mydata, function(x) quantile(x,.9))
   age    fitted
1    5  6.459680
2    6  6.280579
3    7  6.290599
4    8  6.556999
5    9  7.048602
6   10  7.817276
7   11  8.931219
8   12 10.388048
9   13 12.138104
10  14 14.106250
11  15 16.125688

The values are very different from 90th quantile directly from data:
> aggregate(yvar~age, mydata, function(x) quantile(x,.9))
   age     yvar
1    5 39.22938
2    6 35.69294
3    7 25.40390
4    8 26.20388
5    9 29.07670
6   10 32.43151
7   11 24.96861
8   12 37.98292
9   13 28.28686
10  14 43.33678
11  15 44.46269

A: See if this makes sense. The 90th percentile of a normal distribution with mean and sd of 'smn' and 'ssd' is qnorm(.9, smn, ssd):  So this seems to deliver (somewhat) sensible results, albeit not the full hack of centiles that I suggested:
 plot(h$xvar, qnorm(.9, fitted(h), h$sigma.fv))

(Note the massive overplotting from only a few distinct xvars but 500 points. Ande you may want to set the ylim so that the full range can be appreciated.)

The caveat here is that you need to check the other parts of the model to see if it is really just an ordinary Normal model. In this case it seems to be:
> h$mu.formula
y ~ pb(x)
<environment: 0x10275cfb8>
> h$sigma.formula
~1
<environment: 0x10275cfb8>
> h$nu.formula
NULL
> h$tau.formula
NULL

So the model is just mean-estimate with a fixed-variance  (the ~1) across the range of the xvar, and there are no complications from higher order parameters like a Box-Cox model. (And I'm unable to explain why this is not the same as the plotted centiles. For that you probably need to correspond with the package authors.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: jquery dataTable change pages everyone! I need to change pagination in dataTable. I got this
And I need to change to that

I tried to change css like this
  .dataTables_wrapper .dataTables_paginate .paginate_button.disabled{
    margin-left:100px;
}

but I failed. Have you got any ideas?
Thanks for any help!

A: If you have a table with pagingType as full_numbers
var table = $('#example').DataTable({
  pagingType: "full_numbers"
});

you can hide the first and prev buttons this way
$('#example').on('draw.dt', function() {
  $('.paginate_button.previous,.paginate_button.first').hide();
});

and it looks like your image above - demo -> http://jsfiddle.net/n5dyy8px/


text:
Q: How do I make 1 "oninput" field yield multiple "output" fields? What I mean is, I want someone to be able to enter a number into an input box, and it have it yield a range. So if they enter the number 2, it shows an output of 2*300-2*400 (600-800).
I have been using
 <form oninput="x.value=parseInt(a.value)*parseInt(300)">

 <input type="text" name="a" value="">

 <output name="x" for="a b"></output>

However that only yields the variable*300. How do I get a second output box directly after the first with the variable*400?

A: <form oninput="x.value=parseInt(a.value)*parseInt(300);y.value=parseInt(a.value)*parseInt(400);">

<input type="text" name="a" value="">

<output name="x" for="a b"></output>
<output name="y" for="a b"></output>


text:
Q: Lpc1347 halfword access I am reading lpc1347 manual (GPIO section) and I have seen one sentence which I don't understand. The problem is WORD register which controls pin states. Quotation:
"Each GPIO pin has a word register in this address range. Any byte, balfword or word read in this range will be all zeros if the pin is low or all ones if the pin is high..."
I can access WORD register via
pGPIO->B[0]

It's word access but how can I read it via halfword or byte? Should I make a own pointer and read value from memory? If yes, should I start read from LSB or MSB?

A: You can read a half-word or byte by defining a variable of the appropriate size at the appropriate address (or via a pointer, which has the same effect).
But why would you? Reading a byte or half-word is not faster than reading a full word, maybe even slower. If it were any use, it would probably be in the (mbed or similar) interface definition.


text:
Q: Exception handling to detect input String vs. Integer I need to write code where the program fails and throws an exception if the second input on a line is a String rather than an Integer. I am confused as to how to compare if the input is a string or an int and I am also struggling on how to use a try/catch statement.
import java.util.Scanner;
import java.util.InputMismatchException;

public class NameAgeChecker {
public static void main(String[] args) {
  Scanner scnr = new Scanner(System.in);

  String inputName;
  int age;

  inputName = scnr.next();
  while (!inputName.equals("-1")) {
     // FIXME: The following line will throw an InputMismatchException.
     //        Insert a try/catch statement to catch the exception.
     age = scnr.nextInt();
     System.out.println(inputName + " " + (age + 1));

     inputName = scnr.next();
  }

}

A: Instead of
age = scnr.nextInt();

Try
try {
    age = scnr.nextInt();
    System.out.println(inputName + " " + (age + 1));
}
catch(InputMismatchException e) {
    System.out.println("Please enter a valid integer");
}


text:
Q: Skip identity server 4 login page and put IDP & resource server on the same domain When using identity server4 authorization code flow, does it have to be redirected to a IDP domain to get authenticated?
For example,

*

*angular client side app runs at localhost:4200

*IDP identity server 4 runs at localhost:5000

*resource api server runs at localhost:3000

*

*Can I just use my client side login page instead of being redirected to IDP and use their login page?

*Is it possible to put IDP identity 4 & resource server in one place? so they can be run at the same port (ex: localhost:3000)

I don't think it's reasonable to deploy three times (client, IDP, resource) on a separate domain when my app is relatively small and auth will not be shared by other client apps.
What's the best approach for my case?

A: I agree with LucaBNW that keeping IdentitySerer as a separate service is a good idea, becuase it get much harder to reason about what is happening when things break when they are in the same service.
If you have them on a separate domain or on the same domain but with separate ports does not matter (security-wise) because they are still considered different origins when the port are not the same.
if you do want to use OAuth/OpenID-Connect/IdentityServer, you should never ever use your own login screen. You should always redirect to the IDP. It's a big no-no, security wise. Because as a user you don't know where you actually login-to, and how well your UI handles the username/password.

A: It is possible to login on the client side by using the resource owner password credentials grant, which is something you should never ever do. Read here why.
Combining the IDP and the resource API on the same port is also something you should not even try to do. The IDP, Clients and Resources are all separate entities. If you wish to use Identity Server, and use it correctly, what you currently have is correct: a client using Identity Server for user auth, and a resource which the client is granted use of by the IS. If you wish to only have a client with a login page and a API, you can make that, in which case you don't need Identity Server.


text:
Q: Vue lifecycle hook typescript error when invoking method I'm having trouble referencing a method in a Vue root component from a lifecycle method in typescript. I've been able to reproduce this behaviour with a toy example below:
import Vue from "vue";

class Game {
    a: number;
    b: number;
    constructor() {
        this.a = 3;
        this.b = 4;
    }
}

new Vue({
    el: "#calculator",
    data: {
        game: null
    },
    methods: {
        // bound to a button
        reset: function() {
            this.game = new Game();
        },
        // bound to a button
        add: function() {
            this.game.a += 1;
        }
    },
    beforeCreate() {
        this.reset();
    }
});

I am getting the following typescript compilation error:

src/test.ts:28:8 - error TS2339: Property 'reset' does not exist on
  type 'Vue'.
28    this.reset();

My IDE is telling me that typescript only interprets the properties defined in data as part of this, not those defined in methods. Have other folks run into this, and if so what did you do to fix it?
Note that this would work just fine in javascript

A: Regardless of whether or not you have already solved this yourself considering it has been a few weeks:
Since you are using TypeScript, you do not need to define the methods inside the "methods" object. You can just define them directly on the class.


text:
Q: convert date and time from textbox into timestamp in php I currently have a date/time picker that puts the current date and time the user selected into a textbox.
The format is like the following :
22-04-2018 17:34
d-m-Y H:i
I am wondering if there is a way to convert that into a PHP timestamp?

A: As I wrote in comments, the best option is to choose a "Y-m-d" format as that can easily be converted to timestamp with strtotime().
But if you can't do that you can use datetime class to convert it.
$time = "22-04-2018 17:34";
$format = "d-m-Y H:i";

$dt = date_create_from_format ($format , $time);
Echo date_timestamp_get($dt);

https://3v4l.org/eWdWN


text:
Q: How to use values from if else statements I created global variables lyk int scor = 3, int fail = 0, then turned them to strings using Integer.toString() method. I created an array of 10 buttons and used if statements to access their actions. My problem is that I used the variables scor, fail in each if statement. I want to at the end grab all the values of scor, fail for each button and add them up. My code is so large I could not paste it here. I need your help.

A: You could just simply make an array list of scores and fails and push back however many buttons. Then you can iterate through each button and set the distinctive values of both container elements using an index.
This will also solve your large block of if statements problem.
DrStrange.


text:
Q: Immediately add a new source file to an Eclipse project This question is a follow-up to
open .java file in specified eclipse project from command line, specifically to this part (see the original question for more background):

I am actually trying to create a source file automatically and want to edit it just like I created it by default way in eclipse.

In short, I need to open an externally generated .java file in the Eclipse editor.
Eclipse's auto-refresh takes up to 5 seconds to find the new file but I want to open it in maximum of 1-2 seconds.
Any pointers / ideas towards this would be great.

A: Maybe the FileSync plugin for eclipse is the right thing for you. If it is not fast enough, you could take a look at the source and tweak it for your needs.


text:
Q: how to create submenus in drupal 7 I have a module that adds a link to main menu. When I click on that link the requested page gets loaded (a .js and .html file).
My main menu looks like this:

*

*My link

My code looks like this:
<?php

/**
 * Implements hook_menu()
 */
function kl_menu(){
  $items = array();

  $items['simple_link'] = array(
   'title'            => t('my link'),
   'page callback'    => 'build_page',
   'access arguments' => array('access content'),
   'menu_name' => 'main-menu',
   'type' => MENU_NORMAL_ITEM,
  );

/*
 * build_page
 */
function build_page() {
  drupal_add_js(drupal_get_path('module', 'kl') . '/mypage.js', 'file');
   return  ( file_get_contents( drupal_get_path('module', 'kl').'/mypage.html') );
}

Now I would like add a submenu instead of a simple plain link so that my main menu would look like this:

*

*My submenu

*

*my sublink1

*my sublink2

I would like that when I click on  "my submenu" then this sub menu expands displaying more links. Then when I reclick on my submenu I would like it to collapse.
I am pretty new to drupal php etc.
How can I acheive that. I am using garland theme.
Thanks
baba

A: /**
 * Implements hook_menu().
 */
function kl_menu() {
  $items['simple_link'] = array(
    'title'            => t('my link'),
    'page callback'    => 'kl_build_page',
    'access arguments' => array('access content'),
    'menu_name' => 'main-menu',
    'type' => MENU_NORMAL_ITEM,
  );
  $items['simple_link/my_sublink_1'] = array(
    'title'            => t('my sub link 1'),
    'page callback'    => 'mymodule_sub_page_1',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );
  $items['simple_link/my_sublink_2'] = array(
    'title'            => t('my sub link 2'),
    'page callback'    => 'mymodule_sub_page_1',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

/**
 * Implements hook_theme().
 */
function kl_theme() {
  $template_path = drupal_get_path('module', 'kl') . '/templates';

  return array(
    // File would be <module path>/templates/kl-build-page.tpl.php
    'kl_build_page' => array(
      'path' => $template_path,
      'template' => 'kl-build-page')
    ),
    // File would be <module path>/templates/kl-sub-page-1.tpl.php
    'sub_page_1' => array(
      'path' => $template_path,
      'template' => 'kl-sub-page-1')
    ),
    // File would be <module path>/templates/kl-sub-page-2.tpl.php
    'sub_page_2' => array(
      'path' => $template_path,
      'template' => 'kl-sub-page-2')
    ),
  );
}

/**
 * Callback for main build page.
 */
function kl_build_page() {
  drupal_add_js(drupal_get_path('module', 'kl') . '/mypage.js', 'file');
  return  theme('kl_build_page');
}

/**
 * Page callback for sub page 1
 */
function kl_sub_page_1() {
  return theme('kl_sub_page_1');
}

/**
 * Page callback for sub page 2
 */
function kl_sub_page_2() {
  return theme('kl_sub_page_2');
}


text:
Q: How to get only a response boolean in curl php I have the following code
$handle = curl_int();
$i = '123456';
curl_setopt_array(
    $handle,
    array(
        CURLOPT_URL =>'localhost/unnamed/loginpage.php',
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => "uname=birat&pword=$i",
        CURLOPT_RETURNTRANSFER => true,
    )
);

$response = curl_exec($handle);

//This if statement doesnot work
if($response == 1) {
    echo 'Password is '. $i;
}

}
curl_close($handle);

The problem is that I always get the whole html page instead of just '1' or '0' indicating me that the username and password matches. Also the last if statement does not work. If i don't use this if statement, I get the good result i.e '1' at the top and the html data of the page below it. I don't want that html data. I just want '1' or '0' and I want this if clause to work. What do I do?

A: CUrl just performing requests for you and, in your case, returns contents of target page. You need to output only 1 or 0 on target page and check like this:
if ( trim($result)=='1' ) {
    // do something
}

A: You need to check the http code as well. This might help you.
$httpcode = curl_getinfo($handle,CURLINFO_HTTP_CODE);
if ($httpcode == '200')
{
    //logged in
}
else
{
    //not logged in
}

In most cases HTTP code 200 is a valid authentication.


text:
Q: How to refresh the Console in the same line in real time, Python I'm trying to do the text refresh to be able to display some information in the same line, basically rewriting the old text.
code sample:
from time import sleep

def countdown(n):
    if n > 0 :
        print(n)
        sleep(0.3)
        countdown(n-1)
    else :
        print("Blastoff!")
countdown(3)

If I use the "\r" in the print statement, it does \n two times.
I tried the carriage return "\r" and the cls clear() function, everything on stack, but nothing works for Mac.
code sample:
from time import sleep

def countdown(n):
    if n > 0 :
        print(n)
        sleep(0.3)
        countdown(n-1)
    else :
        print("Blastoff!")
countdown(6)

If I use the "\r" in the print statement, it does \n two times.
this is the current output:
3
2
1
Blastoff!
in the same window.
i'd like to have the output as follows:
3     # in the first line
2     # in the same spot that 3 was.. and so on.
.
.
Blastoff!   # at the end will be the only thing on the screen.

A: The print statement appends a new line at the end of your output by default.
To prevent this you want to add end="" as parameter. Now your output will always be on the same line.
In addition to this you want to use "\r" at the beginning of you output.
If you would add "\r" at the end of the output some consoles might overwrite your output while doing the carriage return and you would end up with a blank line.
I'd also avoid using recursion here, iteration is usually the faster way and unless it over complicates your code I - personally - would prefer it.
def countdown(n):
    while 0 < n:
        # add some spaces after the number to make sure we overwrite the entire last output
        print("\r%d   " % n, end="")
        n -= 1
        sleep(0.3)
    print("\rBlastoff!")

Edit
Taken from here: Overwrite printed line in python 3.x on mac
Replace print(...) with sys.stdout.write(...) aswell as
def countdown(n):
    while 0 < n:
        sys.stdout.write("\r%d   " % n)
        sys.stdout.flush()
        n -= 1
        sleep(0.3)
    sys.stdout.write("\rBlastoff!")
    sys.stdout.flush()

You will also need to import sys


text:
Q: Does storing Faceook's social graph in our database violate the terms of service? We are creating an application that will ask the user for permission to their friends, and then will store their friends_ids in our database, does this violate the terms of service?  If so, where can we find this violation cause I couldnt seem to find it.

A: See the Platform Policy, section II.
You can store the data, but be sure to make it clear to the user. You can't use the data outside of the application or sell it (obviously). For friends list, you should update the list every 24 hours to account for new / removed friends.


text:
Q: Assigning a value to an dynamic array element results in subscript out of range error Sub ArrTest()
Dim Arr() As Variant

    Arr(1, 1) = "Test"

End Sub

I did not dimension the array as I do not know what size it will need to be.  I will eventually be writing this array to a spreadsheet.  I was attempting to assign the upper left hand corner of the cells that would be written in the future as "test".
Now if I understand correctly dynamic arrays start to index at 0, so the first element is really Arr(0,0).  I tried Arr(0,0) and got the same error.
I guess the real question is:
How to assign a value to an element of an undefined dynamic array?

A: You'll have to dim the array to a size before you use it. This is pretty simple though:
Sub ArrTest()
    Dim Arr() As Variant

    redim Arr(0 to 1, 0 to 1)
    Arr(1, 1) = "Test"

    redim preserve Arr(0 to 2, 0 to 1)
    Arr(2, 1) = "Test2"

End Sub

The redim method will redimension your array. Using the keyword Preserve will insure that the data stored in the array is not lost during the redimensioning.


text:
Q: iOS Core Graphic, how to calculate CGAffineTransform(scaleX offset? While I am learning Core Graphic by ray wenderlich,
one step is to transform UIBezierPath, var transform = CGAffineTransform(scaleX: 0.8, y: 0.8),
I do not know why the step after is right,which is transform = transform.translatedBy(x: 15, y: 30)?
I don't know how the x and y position is calculated out.
By printing the UIBezierPath currentPoint print(medallionPath.currentPoint), I thought the width should be (x1 - x2) * 0.5, the height should be y1 - y2, I really don't know why it is
(x: 15, y: 30)
The whole code is following , tested in Playground
let size = CGSize(width: 120, height: 200)
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
let context = UIGraphicsGetCurrentContext()!

//Gold colors
let darkGoldColor = UIColor(red: 0.6, green: 0.5, blue: 0.15, alpha: 1.0)
let midGoldColor = UIColor(red: 0.86, green: 0.73, blue: 0.3, alpha: 1.0)

let medallionPath = UIBezierPath(ovalIn: CGRect(x: 8, y: 72, width: 100, height: 100))

print(medallionPath.currentPoint)
//  (108.0, 122.0)
print(medallionPath.bounds)
//  (8.0, 72.0, 100.0, 100.0)
context.saveGState()
medallionPath.addClip()

darkGoldColor.setFill()
medallionPath.fill()

context.restoreGState()
// question
var transform = CGAffineTransform(scaleX: 0.8, y: 0.8)

// transform = transform.translatedBy(x: 15, y: 30)
medallionPath.lineWidth = 2.0

//apply the transform to the path
medallionPath.apply(transform)
print(medallionPath.currentPoint)
//  (86.4, 97.6)
print(medallionPath.bounds)
//  (6.4, 57.6, 80.0, 80.0)
medallionPath.stroke()

//This code must always be at the end of the playground
let image = UIGraphicsGetImageFromCurrentImageContext()!

UIGraphicsEndImageContext()

A: transform = transform.translatedBy(x: 15, y: 30)

is a translation.  It shifts the entire path to the right by 15 and down by 30.  Your question is where did the magic numbers 15 and 30 come from.

The medallion drawing has a circle with dimensions 100 x 100 starting at position (8, 72) as established by this line of code:
let medallionPath = UIBezierPath(ovalIn: CGRect(x: 8, y: 72, width: 100, height: 100))

The code then adds an inner ring by scaling the original path by 0.8, so it will be an 80 x 80 circle.  So that the center of this smaller ring lines up with the center of the bigger circle, it will need to be offset an additional 10 in both the horizontal and vertical directions.  (The smaller circle is 20 smaller horizontally and vertically, so shifting it by 1/2 of 20 gets it to align properly).  The goal then is to have it positioned at (18, 82) with width: 80, height: 80.
So, we need to apply a translation (a shift) in the X and Y directions, such that when the path is scaled we end up with a path anchored at (18, 82).  The tricky bit is that the scaling gets applied to the shift values, so that has to be accounted for as well.
So, we are starting with an X position of 8, and we want to apply some translation value dx so that when the result is scaled by 0.8 we end up with the value 18:
(8 + dx) * 0.8 = 18

solving for dx:
dx = (18 / 0.8) - 8
dx = 14.5

Similarly for Y, we are starting with a Y position of 72 and want to apply a translation dy such that when it is scaled by 0.8 we end up with 82:
(72 + dy) * 0.8 = 82

solving for dy:
dy = (82 / 0.8) - 72
dy = 30.5

So, the mathematically correct translation is (14.5, 30.5):
transform = transform.translatedBy(x: 14.5, y: 30.5)

Ray Wenderlich rounded those to (15, 30) for some reason known only to them (because the round numbers look better in the code perhaps?).  It's possible that they didn't bother to do the math and just tried values until it looked right.

A: here scale is 0.8 means 80% of the current so its x, y, width and height all reduce to 80%
so new scale difference is
scaleDifference = ((1/ 0.8) - 1.0) * 100 = 25%

now total size difference is 0.25, here inner circle is in centre so centre point does not change so its x and y position change to calculate x and y
here path rect is (8, 72, 100, 100)
so formula to calculate
circle reduce 10% from both side, to keep it in centre needs to increase 10% x and y and reduce 10% in width and height so circle will be in centre
here scale is set to 80% so what ever x and y translation we are giving all will be calculated to 80%, for example if we give translate x = 10 and y = 10 system converts to its 80% so x = 8 and y = 8.
we have to add width difference to the x and y to keep it in centre
width and height is 100 so
100 * (scaleDifference / 2.0)
100 * (0.25 / 2.0) = 12.5

and due to scaling x and y also reduce to 0.8% so to make it 100% is
xDifference = 8 * scaleDifference = 2.0
yDifference = 72 * scaleDifference = 18.0

to keep circle in centre we have to add width difference with dx and height difference with dy to get final x and y translation value
dx = xDifference + widthDifference = 2.0 + 12.5 = 14.5
dy = yDifference + heightDifference = 18.0 + 12.5 = 30.5


text:
Q: Dashed baseline in Google Line chart In a Google line chart I am using the option
vAxis: {baseline: 'const',
        gridlines: {count: 0}}

to draw the horizontal line y=const into a chart. Is there a way to make this line dashed?


text:
Q: Flink best way to group records by field id I'm setting up Apache Flink connected with Kafka broker.
I got a the following messages in random order:

*

*message(timestamp=[..], index=1, someData=[..])

*message(timestamp=[..], index=2, someData=[..])

*message(timestamp=[..], index=3, someData=[..])

*message(timestamp=[..], index=2, someData=[..])

*message(timestamp=[..], index=3, someData=[..])

*message(timestamp=[..], index=1, someData=[..])

My records coming from Kafka got a index field.
In my application, i need to compute last two of these records that have a same id and then immediately send the response.
For example, these two:

*

*message(timestamp=[..], index=1, someData=[..])

*message(timestamp=[..], index=1, someData=[..])

Whats the best way to store and compute last two records with the same index field? Could you tell me some tips?

A: Your requirements aren't entirely clear, but the mechanisms you probably want to understand are using keyBy(e -> e.index) to group/partition the stream by the index field, and keyed state for remembering the last event (or two) for each value of the index.
If you need to take the timestamps into account, and the event stream is out-of-order, even within a single value of the index, then you will need to first sort the stream by the timestamps. In that case you'll have a much easier time if you use Flink SQL to do the sorting, and then you could use match_recognize to do the pattern recognition, though that's perhaps overkill for such a simple pattern. Here's an example of how to do the sorting.


text:
Q: Increase Performance of SSIS DFT Im loading 13 cr rows of data from DB2 to SQL server.
currently I have implemented fast load option and set up batch and commit size. thus improved some performance. Please suggest to improve further.
Current version : ssis 2012 and SQL server : 2014
CREATE TABLE tbl(
    [ID] [bigint] NULL,
    [CTYPE] [bigint] NULL,
    [A_ID] [bigint] NULL,
    [AC_TYPE] [bigint] NULL,
    [ASS_TYPE] [nvarchar](400) NULL,
    [t_ID] [bigint] NULL,
    [A_T_ID] [bigint] NULL,
    [FLAG] [int] NULL,
    [REGION] [nvarchar](50) NULL,
    [CHANGEDATE] [datetime] NULL,
    [FLAG2] [nvarchar](50) NULL
) ON [PRIMARY]

GO


text:
Q: WP_Query arguments dropped by "posts_where" filter <?php
        $cat = get_query_var('cat');
        $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
        function filter_where( $where = '' ) {
            // posts for March 1 to March 15, 2010
            $where .= " AND post_date >= '2010-03-01' AND post_date < '2010-03-16'";
            return $where;
        }
        $args = array(
            'cat' => 4,
            'posts_per_page' => 30,
            'paged' => $paged
        );

        add_filter( 'posts_where', 'filter_where');
        $my_query = new WP_Query($args);
        remove_filter( 'posts_where', 'filter_where' );
        if ($my_query->have_posts()):
            /* Start the Loop */
            while ($my_query->have_posts()) : $my_query->the_post();

                get_template_part('single', 'bandi');

            endwhile;
        endif; ?>

Here is my code.
Im trying to display posts from specific category, within date range.
Without filter query work fine, return posts from provided category. Adding filter makes query return posts within date range, but remove category id, and query return posts from whole site.
Any help?
Thanks


text:
Q: When does the standard errors of OLS estimates decreases when we have more explanatory variables? So far my understanding is that standard errors of $\hat\beta_j$ increase when we have more independent variables in the regression model because variation among those independent variables will increase ($\rightarrow R^2_j \uparrow$). But I saw the opposite thing happened when I add more explanatory variables in the RHS of the simple difference-in-differences model:
$$y_t=\beta_0+\delta_0x_1+\beta_1 x_2+\delta_1x_1x_2+u $$
I can't understand how this could be possible?

A: This can happen for a few reasons.  One scenario is as follows:
Consider a model
$$ y = \beta_0 + \beta_1x + \beta_2 w + \beta_3 z + \epsilon $$
Suppose that the covariate $x$ is randomly assigned to units in the population.  Hence $x$ is uncorrelated with any other variables $w, z$ considered for adjustment by construction.
If $w$ and $z$ can explain variation in $y$, then the standard error for $\beta_1$ (the coefficient for the randomly allocated $x$) can decrease as compared to the model $y = \beta_0 + \beta_1 x$.
This happens because the estimate of the residual variation $\sigma$ will decreases (due to variation in from $w$ and $z$ explaining away variation in $y$) and the covariance for beta is a function of $\sigma$.
We can very easily see this if we just simulate the model
set.seed(0)
N <- 1000
x <- rbinom(N, 1, 0.5)
w <- rnorm(N)
z <- rnorm(N)
y <- 1 + x + w + z + rnorm(N, 0, 0.5)

# model without w, z
vcov(lm(y~x))['x', 'x']
#> [1] 0.009220088
# Look at the residual variance, nearly thrice as big as it should be
sd(resid(lm(y~x)))
#> [1] 1.516374

# Model with w, x
vcov(lm(y~x + w + z))['x', 'x']
#> [1] 0.0008677971
# Look at the residual variance, much closer to the true value
sd(resid(lm(y~x+w+z)))
#> [1] 0.4643699

Created on 2022-11-24 by the reprex package (v2.0.1)

A: There are competing by factors. You've identified the variance inflation factor (VIF), and you are right that adding more variables can increase the VIF. However, another factor is how large the residual variance is. After all, a major factor in the standard of your parameter estimates is the residual variance.
Consequently, the standard error of your parameter estimates decreases when the decrease in residual variance overwhelms whatever increases to VIF occur due to adding in new features.

A: Let's do the math.
Consider zero-mean variables, and the following two regressions:
$$y = \beta x + u$$
$$y = \gamma x + \delta z + v$$
In the first model, we have
$${\rm Var}(\hat \beta) = \frac{\hat \sigma^2_u}{\sum{x^2}}   \tag{1}$$
In the second model we have
\begin{align}{\rm V}(\hat \gamma, \hat \delta) &= \hat \sigma^2_u \left[\begin{matrix} \sum x^2 & \sum xz\\ \sum xz & \sum z^2\end{matrix}\right]^{-1} \\
\\
 &= \frac{\hat \sigma^2_u}{\left(\sum x^2\right)\left(\sum z^2\right) - \left(\sum xz\right)^2}\left[\begin{matrix} \sum z^2 & -\sum xz\\ -\sum xz & \sum x^2\end{matrix}\right].
\end{align}
The "strange" behavior is when
\begin{align}
{\rm Var}(\hat \gamma) < {\rm Var}(\hat \beta) &\implies \frac{\hat \sigma^2_v\sum z^2}{\left(\sum x^2\right)\left(\sum z^2\right) - \left(\sum xz\right)^2}< \frac{\hat \sigma^2_u}{\sum{x^2}}\\
\\
&\implies \frac{\hat \sigma^2_v}{\hat \sigma^2_u} < \frac{\left(\sum x^2\right)\left(\sum z^2\right) - \left(\sum xz\right)^2}{\left(\sum x^2\right)\left(\sum z^2\right)}\\
&\implies \frac{\hat \sigma^2_v}{\hat \sigma^2_u} < 1- \hat \rho^2_{xz}.
\end{align}
We know that the estimated error variance in the augmented model, $\hat \sigma_v^2$ will be smaller than the corresponding estimate in the short model $\hat \sigma_u^2$.
So if this reduction is bigger (as a percentage and in absolute terms) than the squared correlation of the two variables, we will observe reduced standard error in the larger model.
If the squared correlation is zero ($x$ and $z$ are uncorrelated), then we will certainly get smaller standard deviation of the coefficient of $x$ in the augmented model.
But wait, didn't we just add a lot of independent variation in the model (but presumably related to the dependent variable)? Indeed we did, and this is exactly why "certainty" increased. It is variation that explains.

A: This happens mostly with misspecified models that have large residuals because of a misspecified model and that can be reduced by adding more variables.
As simple illustration can be made with simple linear regression.

*

*The linear model fit $x=a+bx$ in the upper left corner is more precise in the estimate at x=0. The estimate for the standard error is small because the residuals are small.

*The model that uses only an intercept $x=a$ indicates a larger error. The reason is that the residuals are much larger. With the linear model fit these residuals are a lot reduced.

*The lower right image: to our eye it seems weird that the model $y=a$ is doing bad but that is because our brain sees the linear relationship and we imagine a line going through 0. The model doesn't see this and includes no information about $x$. For the model it looks like the $x$ data are scrambled.

Another illustration that shows it dramatically is from Why is the intercept in multiple regression changing when including/excluding regressors?
A smaller model can have bias which increases the error.


text:
Q: gl-react-native not displaying image on physical iOS device I'm trying to get the saturation example from gl-react:
Contrast/Saturation/Brightness example
working on an iphone, but for some reason the image only displays on an iOS simulator and not a real device.
This is what is shown on an iphone SE simulator running iOS 10.3 (Everything works perfectly, as in the example).

This is what is shown on an actual iphone SE running iOS 10.3

And this is the code
 /**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import { Shaders, Node, GLSL } from 'gl-react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  Slider
} from 'react-native';
import { Surface } from 'gl-react-native';

const shaders = Shaders.create({
  Saturate: {
    frag: GLSL`
  precision highp float;
  varying vec2 uv;
  uniform sampler2D t;
  uniform float contrast, saturation, brightness;
  const vec3 L = vec3(0.2125, 0.7154, 0.0721);
  void main() {
    vec4 c = texture2D(t, uv);
    vec3 brt = c.rgb * brightness;
    gl_FragColor = vec4(mix(
      vec3(0.5),
      mix(vec3(dot(brt, L)), brt, saturation),
      contrast), c.a);
  }
  `
  }
});

export const Saturate = ({ contrast, saturation, brightness, children }) =>
  <Node
    shader={shaders.Saturate}
    uniforms={{ contrast, saturation, brightness, t: children }}
  />;

export default class App extends Component<{}> {
  state = {
    contrast: 1,
    saturation: 1,
    brightness: 1
  }

  render() {
    const { contrast, saturation, brightness } = this.state;

    const filter = {
      contrast,
      brightness,
      saturation
    }

    return (
      <View>
        <Text style={styles.header}>
          SaturateGL
        </Text>
        <Surface style={{ width: 300, height: 300 }}>
          <Saturate {...filter}>
            {{ uri: "https://i.imgur.com/uTP9Xfr.jpg" }}
          </Saturate>
        </Surface>
        <Slider
          minimumValue={0}
          maximumValue={4}
          step={0.01}
          value={ contrast }
          onValueChange={ contrast => this.setState({ contrast }) }>
        </Slider>
        <Slider
          minimumValue={0}
          maximumValue={4}
          step={0.01}
          value={ saturation }
          onValueChange={ saturation => this.setState({ saturation }) }>
        </Slider>
        <Slider
          minimumValue={0}
          maximumValue={4}
          step={0.01}
          value={ brightness }
          onValueChange={ brightness => this.setState({ brightness }) }>
        </Slider>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  header: {
    fontSize: 24,
    textAlign: 'center',
    padding: 10,
  },
});

Repo Here
I'm running

*

*gl-react@3.13.0

*gl-react-native@3.13.0

*react-native-webgl@0.70

and react-native-webgl is set up properly (I've linked the libRNWebGL.a and removed the libGPUImage.a in xcode as per the install instructions).
I'm quite new to react-native, so probably I've done (or worse yet, not done) something, which is a bit daft.  But if anyone can help point out why this is happening, I'd be most grateful.  This is really annoying me.
Thanks

A: Try to change {{ uri: "https://i.imgur.com/uTP9Xfr.jpg" }} to {{ image : { uri: "https://i.imgur.com/uTP9Xfr.jpg" }}} or {{ image: "https://i.imgur.com/uTP9Xfr.jpg" }}

A: Hi may be you forgot to style the surface ? It took me long days to recognize that mistake


text:
Q: Simplification of $\sum \limits_{a=0}^{m} \sum \limits_{b=0}^{n} x^{|a-b|}$ I was trying to determine a simplification of $f(x) = \sum \limits_{a=0}^{m} \sum \limits_{b=0}^{n} x^{|a-b|}$. One approach I considered was using a case bash, but this was quite inelegant so I tried to find a more elegant method. Another method was to consider the expression for $f(x) + f \left ( \frac{1}{x} \right )$. This seemed better as it was much easier to sum, resulting in the below expression:
$$f(x) + f \left ( \frac{1}{x} \right ) = \left ( \frac{x^{m+1}-1}{x-1} \right ) \left ( \frac{x^{n+1}-1}{x-1} \right ) \left ( \frac{1}{x^m} + \frac{1}{x^n} \right ) = \frac{(x^{m+1}-1)(x^{n+1}-1)(x^m+x^n)}{x^{m+n}(x-1)^2}$$
Now the issue is to isolate $f(x)$ from this. Any help would be great.


text:
Q: Unexpected result when moving bytes between buffers I am working on a function in c++ where the intent is to move num_bytes from one vector to another.
This is the relevent portion of my function
// Grab a pointer to the vector currently in use
std::vector<unsigned char> *bytes = &currentBuffer();

// Calculate un-parsed data in current vector
size_t num_bytes = static_cast<size_t>(currentBuffer().size() - pos_);

// Added in to test that it is working
std::cout << "Byte before: " << (*bytes)[pos_] << std::endl;

// Move num_bytes from pos_ in currentVector to [0] in otherBuffer
if (num_bytes) {
   memmove(&(otherBuffer()[0]), &((*bytes)[pos_]), num_bytes);
}

// I now want to use otherBuffer as currentBuffer
bytes = &otherBuffer();

// Reset size of new buffer
bytes->resize(num_bytes);

// Reset position of new buffer
pos_ = 0;

// Added in to test that it is working
std::cout << "Byte after: " << (*bytes)[pos_] << std::endl;

When I run this using real data I am getting two different results from the two cout statments, where ideally the byte value at currentVector[pos_] and otherVector[0] should be the same after the memmove.
Any clue what could be going wrong? I think the error is within memmove however I cannot figure out what it could be.
Thanks!

A:
You need to resize the buffer before you copy data to it, otherwise you risk writing beyond the internally allocated buffer of your other vector.
You'd be better off, however, using a classic C++ approach:
otherBuffer().assign(currentBuffer().begin() + pos, currentBuffer().end());

All you need - no resize, no memmove (memcpy would probably have been more efficient in this case anyway...).

A: You need to call resize() before the memmove(), not after.
Try this:
// Move num_bytes from pos_ in currentVector to [0] in otherBuffer
if (num_bytes) {
   otherBuffer().resize(num_bytes);
   memmove(&(otherBuffer()[0]), &((*bytes)[pos_]), num_bytes);
}


text:
Q: Is there any way to have Emacs save your undo history between sessions? Is there any way to have EMACS save your undo history between sessions?
I'm aware of the savehist lib, the saveplace lib, the desktop lib, and the windows lib, these all provide some session control but none seem to save the undo history.

A: desktop-save-mode does not save buffer-undo-list by default. You just have to tell him!
(add-to-list 'desktop-locals-to-save 'buffer-undo-list)

A: From version 0.4 onwards, undo-tree supports persistent storage of undo-tree data between sessions "out of the box". (Note that there are significant bug-fixes related to this feature in more recent versions; the latest version at the time of writing is 0.6.3.)
Simply enable the undo-tree-auto-save-history customization option to automatically save and load undo history in undo-tree buffers. Or use the undo-tree-save/load-history commands to save and load undo history manually.
You need at least Emacs version 24.3 for this to work reliably, but with a recent enough Emacs it works very well.

A: Add the following to your .emacs file :
(global-undo-tree-mode)
(setq undo-tree-auto-save-history t)
(setq undo-tree-history-directory-alist '(("." . "~/.emacs.d/undo")))

Explanation

*

*(global-undo-tree-mode) enables undo tree.

*(setq undo-tree-auto-save-history t) enables auto save of undo history.

*(setq undo-tree-history-directory-alist '(("." . "~/.emacs.d/undo"))) so that your project does not get littered with undo-history savefiles.

A: Emacs Session appears to support this:
(add-to-list 'session-locals-include 'buffer-undo-list)

A: Here's some code I wrote which seems to do the trick.  It isn't bullet-proof, as in, it doesn't handle all the file handling intricacies that Emacs does (e.g. overriding where auto-save files are put, symlink handling, etc.).  But, it seemed to do the trick for some simple text files I manipulated.
(defun save-undo-filename (orig-name)
  "given a filename return the file name in which to save the undo list"
  (concat (file-name-directory orig-name)
          "."
          (file-name-nondirectory orig-name)
          ".undo"))

(defun save-undo-list ()
  "Save the undo list to a file"
  (save-excursion
    (ignore-errors
      (let ((undo-to-save `(setq buffer-undo-list ',buffer-undo-list))
            (undo-file-name (save-undo-filename (buffer-file-name))))
        (find-file undo-file-name)
        (erase-buffer)
        (let (print-level
              print-length)
          (print undo-to-save (current-buffer)))
        (let ((write-file-hooks (remove 'save-undo-list write-file-hooks)))
          (save-buffer))
        (kill-buffer))))
  nil)

(defvar handling-undo-saving nil)

(defun load-undo-list ()
  "load the undo list if appropriate"
  (ignore-errors
    (when (and
           (not handling-undo-saving)
           (null buffer-undo-list)
           (file-exists-p (save-undo-filename (buffer-file-name))))
      (let* ((handling-undo-saving t)
             (undo-buffer-to-eval (find-file-noselect (save-undo-filename (buffer-file-name)))))
        (eval (read undo-buffer-to-eval))))))

(add-hook 'write-file-hooks 'save-undo-list)
(add-hook 'find-file-hook 'load-undo-list)

A: I have managed to get the undo history working by using the information provided here: http://emacs.stackexchange.com/q/3725/2287
Instead of patching the original file desktop.el.gz I created an advice that temporarily overrides (buffer-local-variables) then I use it together with the function that gathers information about the buffer.
(defun +append-buffer-undo-list-to-buffer-local-variables-advice (orig-fn &rest args)
  "Override `buffer-local-variables' and call ORIG-FN with ARGS.
There is a bug in Emacs where the `buffer-undo-list' data is
missing from the output of `buffer-local-variables'. This
advice temporarily overrides the function and appends the
missing data."
  (let ((orig-buffer-local-variables-fn (symbol-function 'buffer-local-variables)))
    (cl-letf (((symbol-function 'buffer-local-variables)
               #'(lambda () (append (funcall orig-buffer-local-variables-fn)
                               `(,(cons 'buffer-undo-list buffer-undo-list))))))
      (apply orig-fn args))))

(advice-add #'desktop-buffer-info :around #'+append-buffer-undo-list-to-buffer-local-variables-advice)
(push 'buffer-undo-list desktop-locals-to-save)
(desktop-save-mode 1)

I hope this helps someone else.


text:
Q: how to convert select statement to update statement I'm unable to convert the select query to the update statement.
SELECT (SELECT DECODE(building_1, 'No', '0', building_1) +
               COALESCE(building_2, '0') + COALESCE(Building_3, '0') +
               COALESCE(Building_4, '0') + COALESCE(Building_5, '0') +
               COALESCE(Building_6, '0') + COALESCE(Building_7, '0')
          FROM tb2
         WHERE marsha_CODE = SUBSTR(OMT.PROPERTY_NAME, 1, 5)) ROOMS
  FROM tb1 ALR, tb3 OMT
 WHERE 1 = 1
   and work_Order_id = OMT.Request_id
   AND ADDRESS = OMT.PROPERTY_ADDRESS

I need below part of the select statement be the set value in update statement
( SELECT DECODE(building_1, 'No', '0', building_1) +
         COALESCE(building_2, '0') + COALESCE(Building_3, '0') +
         COALESCE(Building_4, '0') + COALESCE(Building_5, '0') +
         COALESCE(Building_6, '0') + COALESCE(Building_7, '0')
    FROM tb2
   WHERE marsha_CODE = SUBSTR(OMT.PROPERTY_NAME, 1, 5) )

and the where clause for the update statement where condition
WHERE 1=1
  AND work_Order_id = OMT.Request_id
  AND ADDRESS = OMT.PROPERTY_ADDRESS

Below is what I've tried out:
UPDATE tb1
   SET room_number =
           (SELECT DECODE(building_1, 'No', '0', building_1)
                   + COALESCE (building_2, '0')
                   + COALESCE (Building_3, '0')
                   + COALESCE (Building_4, '0')
                   + COALESCE (Building_5, '0')
                   + COALESCE (Building_6, '0')
                   + COALESCE (Building_7, '0')
              FROM tb2,
                   tb3 OMT
             WHERE marsha_CODE = SUBSTR(OMT.PROPERTY_NAME, 1, 5))
 WHERE work_Order_id =
              (SELECT Request_id
                 FROM tb3
                WHERE tb3.request_id =
                         tb1.WORK_ORDER_ID)
   AND address =
              (SELECT PROPERTY_ADDRESS
                 FROM tb3
                WHERE tb3.PROPERTY_ADDRESS =
                         tb1.ADDRESS)

A: You can use such an Update statement containing with .. as clause :
UPDATE tb1 t
   SET room_number =
       (
        WITH tt as
        (
        SELECT DECODE(building_1, 'No', '0', building_1) +
               COALESCE(building_2, '0') + COALESCE(Building_3, '0') +
               COALESCE(Building_4, '0') + COALESCE(Building_5, '0') +
               COALESCE(Building_6, '0') + COALESCE(Building_7, '0') as r_number,
               t3.request_id,
               t3.property_address
          FROM tb2 t2
          JOIN tb3 t3
            ON t2.marsha_code = SUBSTR(t3.property_name, 1, 5)
         )
         SELECT tt.r_number
           FROM tt
          WHERE tt.request_id = t.work_order_id
            AND tt.property_address = t.address
       )

even a Merge statement might be used :
MERGE INTO tb1 t
    USING
        (
        SELECT DECODE(building_1, 'No', '0', building_1) +
               COALESCE(building_2, '0') + COALESCE(Building_3, '0') +
               COALESCE(Building_4, '0') + COALESCE(Building_5, '0') +
               COALESCE(Building_6, '0') + COALESCE(Building_7, '0') as r_number,
               omt.request_id,
               omt.property_address
          FROM tb2 t2
          JOIN tb3 t3
            ON t2.marsha_code = SUBSTR(t3.property_name, 1, 5)
         ) tt
      ON (tt.request_id = t.work_order_id AND tt.property_address = t.address)
    WHEN MATCHED THEN UPDATE SET t.room_number = tt.r_number;


text:
Q: Reset radio button and checking using jQuery Im having 2 issue in reset radio button and check.
1 st Issue.

*

*I check or select the (1st row) radio button through this buttons
Check Option 1, Check Option 2, Check Option 3

*Its working fine for 1st time only, For example if i click the button Check Option 1, Check Option 2, Check Option 3 it will check radio button correctly according to its value.

*If again i click the button Check Option 1, Check Option 2, Check Option 3 its not working.
2 nd Issue.

*

*I need to reset to its default checked value by clicking Reset button.  For example see 2nd row.

*Reset is not working if i checked it through Check Option 1, Check Option 2, Check Option 3. If i checked through manually its working fine.

*But im using $('input[name=rdoSample][value=' + value.Rdovalue + ']').attr('checked', 'checked'); because im getting value from database and i have to check according to its value.
FIDDLE DEMO

<title>Testing</title>

                1)

                <input type="radio" name="rdoSample" value="a" checked="checked" />
                a
                <input type="radio" name="rdoSample" value="b" />
                b
                <input type="radio" name="rdoSample" value="c" />
                c

                <input type="button" value="Check Option 1" id="btnCheck1" />
                <input type="button" value="Check Option 2" id="btnCheck2" />
                <input type="button" value="Check Option 3" id="btnCheck3" />

                2)

                <input type="radio" name="rdoSample1" value="11" checked="checked" />
                11
                <input type="radio" name="rdoSample1" value="22" />
                22
                <input type="radio" name="rdoSample1" value="33" />
                33

                <input type="button" value="Reset" id="btnReset" />

A: use prop instead of attr to change the checked property like this.
$('input[name=rdoSample][value="a"]').prop('checked', 'checked');

Js Fiddle

A: You should replace .attr("checked",... with .prop("checked,....
There is a difference between an attribute and a property. Quoting the jQuery docs:

Nevertheless, the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does.

So, using something like this, would make everything work:
$("input[name=<name>][value=<value>]").prop(
        "checked", true);

See, also, this short demo.


text:
Q: Duplicating items in DataGridView c# I have this code where I put data to the DataTable from where I show everything on DataGridView.
But when I look it contains information which supposed to be in file but its repeated twice.
Code to retrieve data from mysql database:
MySqlDataAdapter mySqlDataAdapter;
    DataSet DS0 = new DataSet();
    DataTable DT0;
    string gender;
private void Filter()
{
     ViewG.DataSource = null;
     ViewG.Rows.Clear();
     command.CommandText = "SELECT * FROM `table2` WHERE s1q2 = @gender";
     command.Parameters.Add("@gender", MySqlDbType.VarChar);
     command.Parameters["@gender"].Value = gender;
     DT0 = DS0.Tables.Add("1Filter");
     mySqlDataAdapter = new MySqlDataAdapter(command.CommandText, connection);

     connection.Open();
     mySqlDataAdapter.SelectCommand = command;
     mySqlDataAdapter.Fill(DS0.Tables["1Filter"]);
     ViewG.DataSource = DS0.Tables["1Filter"];
     connection.Close();
}

Initially, on the start it retrieves all information from the database code (SELECT * FROM table) and displays on the DataGridView. And it works fine, but when I try to use filters to retrieve only for example "Females" problem occurs.
For full data I use:
mySqlDataAdapter.Fill(DS0.Tables["Full"]);
ViewG.DataSource = DS0.Tables["Full"];

For Filtered data:
mySqlDataAdapter.Fill(DS0.Tables["1Filter"]);
ViewG.DataSource = DS0.Tables["1Filter"];

If I run query used for filter on the application startup it does not duplicate and show correctly.

EDIT: SOLVED

A: From the code posted here, gender string is not assigned any value. So, your query be applying any filter that you want.

A: Thanks for you effort I found where the problem was. I used temp table on MySql and for some reason server did not dropped this table after connection is closed. So on the new query it added same items on the same table....


text:
Q: using DataTable with php and dynamic columns i'm trying to get my head around DataTables, but finding it difficult.
I have a form where the user can paste 1+ rows of data with 1+ columns of information.
This could look like the following:
a   b   c   d   e   f   g   h   i   j
443 39  70  10  38  11  161 15  477 318
99  452 229 11  63  23  38  104 190 100

After i have processed and validated it, it is available as the following (PHP var_dump() ):
array (size=2)
  1 =>
    array (size=10)
      0 => string '443' (length=3)
      1 => string '39' (length=2)
      2 => string '70' (length=2)
      3 => string '10' (length=2)
      4 => string '38' (length=2)
      5 => string '11' (length=2)
      6 => string '161' (length=3)
      7 => string '15' (length=2)
      8 => string '477' (length=3)
      9 => string '318' (length=3)
  2 =>
    array (size=10)
      0 => string '99' (length=2)
      1 => string '4s52' (length=4)
      2 => string '22s9' (length=4)
      3 => string '11' (length=2)
      4 => string '63' (length=2)
      5 => string '23' (length=2)
      6 => string '38' (length=2)
      7 => string '104' (length=3)
      8 => string '190' (length=3)
      9 => string '100' (length=3)

or
array (size=2)
  1 =>
    array (size=10)
      'a' => string '443' (length=3)
      'b' => string '39' (length=2)
      'c' => string '70' (length=2)
      'd' => string '10' (length=2)
      'e' => string '38' (length=2)
      'f' => string '11' (length=2)
      'g' => string '161' (length=3)
      'h' => string '15' (length=2)
      'i' => string '477' (length=3)
      'j' => string '318' (length=3)
  2 =>
    array (size=10)
      'a' => string '99' (length=2)
      'b' => string '4s52' (length=4)
      'c' => string '22s9' (length=4)
      'd' => string '11' (length=2)
      'e' => string '63' (length=2)
      'f' => string '23' (length=2)
      'g' => string '38' (length=2)
      'h' => string '104' (length=3)
      'i' => string '190' (length=3)
      'j' => string '100' (length=3)

I say "or" because i can output either way - if the json is better with the column names, i'll do it the second way.
my HTML code (using Twig) is:

My Output rendered is:

My questions are:

*

*how do i correctly handle a PHP array?

*Do i need to use mData ?

*Do i need to use columnDefs ?

*In columns, do i need "title" and "data" ?

A: Solved! i've changed my javascript to the following:


text:
Q: Creating new element on dynamicly created button So the question is, I get a json, from that json lenght I generate a list of devices with names and buttons next to them, the button has unique id name by device name, so the thing is, if I press button it has to open options window just for that device name so I can send it data to database for that device name, how do I create unique element for that dynamic button that every each button opens other options, without needing to create shit ton of divs with "display:none" because that just overloads page and slows it down. Tried doing with childElements, getting id and shit, but the same button press script doesnt open different options, I just cant get the head around it.
function a() {
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;
var dataFilt = new Array(4);
dataFilt[1] = "tenant=1";
dataFilt[2] = "tenant=2";
dataFilt[3] = "tenant=3";
dataFilt[4] = "option=all";

$.getJSON('"jsonIphere"?' + dataFilt[strUser]).done(function (devices) {
    // console.log(devices);
    $('.info').html('');
    $(window).scrollTop(0);
    // for (i = 0; i < devices.length; i++) {
    //
    //     $('.info').append('');
    // }

    //cycle to add as many divs as array of devices lenght is
    for (i = 0; i < devices.length; i++) {

        $('.info').append('
\n' +
            '                    \n' +
            '                    \n' +
            '                    \n' +
            '
\n' +
            '
\n' +
            '
\n' +
            '
\n' +
            '
\n' +
            '                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>\n' +
            '
Icon Picker
\n' +
            '
\n' +
            '
\n' +
            '
\n' +
            '
\n' +
            '
\n' +
            '                                                    {{item}}\n' +
            '                                                    \n' +
            '
\n' +
            '
\n' +
            '
\n' +
            '
\n' +
            '
\n' +
            '                                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel\n' +
            '                                        </button>\n' +
            '
\n' +
            '
\n' +
            '
\n' +
            '
\n' +
            '                        <button class="btn iconButton" data-placement="right" data-iconset="fontawesome"\n' +
            '                                data-icon="fa-cog" role="iconpicker">\n' +
            '                        </button>\n' +
            '                        \n' +
            '
\n' +
            '
\n' +
            '
' + devices[i].name + '
\n' +
            '
\n' +
            '
\n' +
            '                        <button class="btn iconButton" id="'+ devices[i].name +'">\n' +
            '                            \n' +
            '                            \n' +
            '                        </button>\n' +
            '
\n' +
            '\n' +
            '
');
        // $('#optionsHere').append('
\n' +
        //     '
\n' +
        //     '\n' +
        //     '
\n' +
        //     '
\n' +
        //     '\n' +
        //     '
\n' +
        //     '
'
        // );

    }

});

}
a();
so this code gets json, and creates as much elements with cycle as there is array objects inside with those object names inside, the commented part is that creates option window with display none for each device name


text:
Q: Enable directory listing on valet installed server I have installed valet-linux. It disables browsing other projects that I need by running
localhost/project

It displays Valet not found.
I tried
autoindex on;

in both valet and nginx configuration and restarted server. Still I cannot access the project using localhost/project.
I'm currently using following versions:
Nginx : 1.14.0 PHP : 7.0 Valet : 2.0.24


text:
Q: How to convert saved string file to texture2D without loss in quality? When converting a texture2D to string and then from string back to texture2D I've noticed a drop in quality and for the colours to be lighter.
My current setup (during play-mode) is as follows:

*

*Take screenshot of whatever object is in front of the camera

*Set the sprite of an image as the screenshot (screenshot appear fine here)

*Convert screenshot (texture2D) to string (this is so that it can be saved)

*Convert string back to texture2D

*Set the sprite of an image to the converted texture2D (this is were the image is appearing lighter and is of a lower quality)

Here is the code I am using for the conversion:
// Convert texture2D to string and return
public static string Texture2DToBase64(Texture2D texture)
{
    byte[] data = texture.EncodeToPNG();
    return Convert.ToBase64String(data);
}

// Convert string to texture2D and return
public static Texture2D Base64ToTexture2D(string encoded)
{
    byte[] data = Convert.FromBase64String(encoded);

    int width, height;
    GetImageSize(data, out width, out height);

    Texture2D texture = new Texture2D(width, height, TextureFormat.ARGB32, false, true);

    texture.hideFlags = HideFlags.HideAndDontSave;
    texture.filterMode = FilterMode.Point;
    texture.LoadImage(data);

    return texture;
}

static void GetImageSize(byte[] imageData, out int width, out int height)
{
    width = ReadInt(imageData, 3 + 15);
    height = ReadInt(imageData, 3 + 15 + 2 + 2);
}

static int ReadInt(byte[] imageData, int offset)
{
    return (imageData[offset] << 8) | imageData[offset + 1];
}

Here is an example of what a screenshot looks like before conversion:

Here is an example of the same screenshot after conversion:

how I can convert the screenshot (texture2D) to string and then back to texture2D without the quality of the image changing? (or if that is even possible)

A: Modifying the "linear" parameter in our Texture2D call to false fixed the issue for us:
Texture2D texture = new Texture2D(width, height, TextureFormat.ARGB32, false, false);


text:
Q: DependencyProperty and DataBinding - Why property setter isn't called when UserControl loads? I want to model the behavior of a RangeSlider, using a class RangeSliderModel with properties describing the sizes (widths) for a given set of values.
Then, I created an UserControl where the position and size of some rectangles should represent those properties, and some instances of Thumb from which the DragDelta events are used to resize these rectangles and enable the calculation of a new value for a RangeSliderModel.
At last, this UserControl has a  DependencyProperty of type RangeSliderModel:
    public RangeSliderModel Model
    {
        get
        {
            return (RangeSliderModel)GetValue(RangeSliderModelProperty);
            // or instead calculate a RangeSliderModel from children sizes.
        }
        set
        {
            // this IS NOT called when UserControl loads
            SetValue(RangeSliderModelProperty, value);
            // here I could take the value and calculate new sizes for the children.
        }
    }

    public static readonly DependencyProperty RangeSliderModelProperty =
        DependencyProperty.Register("RangeSliderModel",
                                    typeof(RangeSliderModel),
                                    typeof(MyUserControl),
                                    new PropertyMetadata(ModelPropertyChanged));

    private static void ModelPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        // this IS called when UserControl loads.
        RangeSliderModel model = e.NewValue as RangeSliderModel;
    }

I was expecting to override the SetValue and GetValue properties, but even when I bind this DependencyProperty to a corresponding Source in ViewModel, the setter is never called! And I can't quite understand why PropertyChangedHandler is called instead, and much less what I should do with this information - I was expecting to use just GetValue and SetValue in a way similar to a ValueConverter.

A: Dependency properties don't work that way when you set them through bindings. DependencyObject.SetCurrentValue is called. The Binding is calling (in essence):
yourObject.SetCurrentValue(YourClassName.RangeSliderModelProperty, someValue);

So, yeah, SetCurrentValue vs SetValue. SetValue will overwrite any binding on the dependency property; SetCurrentValue won't. IIRC this has to do with the way Style Triggers in XAML can't override values set by attributes. It's not directly relevant to what you're doing here, fortunately.
The bottom line is that your ModelPropertyChanged handler is where you put code that needs to get called when the value changes. Dependency properties and regular .NET CLR properties are two independent mechanisms.
I have had dependency properties bind correctly in XAML if I left out the public property entirely; I just tested that again and found it to be the case for my test example. In comments you mention that you did not find this to be the case with your code, so clearly I need to do some more reading.
If you need to have subclasses respond to changes, you can either write a virtual method they can override, and call it in ModelPropertyChanged, or else write a ModelChanged event and raise that in ModelPropertyChanged.
They could add a ValueChanged handler via a DependencyPropertyDescriptor, but it'd be right neighborly of you to spare them the trouble of googling how to that, by writing a virtual method or event.


text:
Q: notifyPropertyChange does not notify bound property chain I have an object that gets updated that ember is unable to notice a change since it's updating a nested attribute. I am letting it know that a change has in fact happened by calling notifyPropertyChange. However, my parent view is not getting the notification that its bound attribute changed.
Example:
http://emberjs.jsbin.com/qesemahi/3/edit

I have a bad hack to get around this but I am hoping there is a reason ember does not notify the entire bound chain. Currently I have a bad clone the object: http://emberjs.jsbin.com/qesemahi/4/edit

A: Because data is a reference inside of your component, it's telling the reference in your component that it's changed.  Honestly it seems like you are trying to manually handle property changes, despite the fact that Ember has this built in.
App.IndexController = Ember.ObjectController.extend({
  display: function() {
    return this.get('data.underneath');
  }.property('data.underneath')
});

App.MyComponentComponent =  Ember.Component.extend({
  display: function() {
    return this.get('data.underneath');
  }.property('data.underneath'),
  actions: {
    insideClick: function(){
      this.set('data.underneath', 'foo bar');
    }
  }
});

http://emberjs.jsbin.com/qesemahi/6/edit
This can be even cleaner using computed aliases..
App.IndexController = Ember.ObjectController.extend({
  display: Ember.computed.alias('data.underneath')
});

App.MyComponentComponent =  Ember.Component.extend({
  display: Ember.computed.alias('data.underneath'),
  actions: {
    insideClick: function(){
      this.set('data.underneath', 'foo bar');
    }
  }
});


text:
Q: What happens when transportation of antimatter is attempted? Star Trek transporters are said to be incapable of transporting antimatter. What does this really mean? What would be the result if one tried to transport a magnetically contained piece of antimatter:

*

*The transporter will fail to lock on the entire object?

*The entire object will dematerialize, but only the matter parts will material on the other side (the antimatter being lost in the buffer)?

*The matter dematerializes, leaving the antimatter in contact with the environment, which will result in its annihilation and the destruction of the surroundings?

*Something altogether different?

A: In the TOS episode "Obsession", Kirk and Ensign Garrovick beam down to Tycho IV with an ounce of antimatter held in suspension.  Kirk detonates it to destroy a gaseous creature that feeds on hemoglobin.

Also, in the TNG episode "Peak Performance", Wesley beams his science project from Enterprise to Hathaway in order to use the antimatter within it to give Hathaway warp capability.

Since we've seen that the transporter can transport antimatter, I cannot accept the premise of the question.

A: First off, from Wiki:

According to the TNG Technical Manual, the transporter cannot move antimatter, but in the VOY episode "Dark Frontier" Voyager transported a live photon torpedo equipped with antimatter onto a Borg ship.
  The animated series episode "One of Our Planets is Missing" has the Enterprise beaming a chunk of antimatter into a stasis box.

As for why Technical Manual says so:
In order to do the transportation, the object needs to be analyzed to figure out and store its molecular structure. If the analysis is done with normal particles (say, electron scanning, to get to required resolutions): POOF!
Even if the scanning would be possible (say, able to switch to positrons), how are you going to generate antimatter particles for re-materialization? I don't think transporter technology is able to generate antimatter in large quantities.
And even if you plugged it into an antimatter particle storage unit, your option #3 happens, unless you beam something into a complete magnetically sealed vacuum.
But standard issue transporters would likely fail on the first step.


text:
Q: Find possible values of $|z|$ if both the real and imaginary parts of $(\bar z)^2+\frac{1}{z^2}$ are integers Let $\bar z$ denote the complex conjugate of a complex number $z$. If $z$ is a non-zero complex number for which both real and imaginary parts of $$(\bar z)^2+\frac{1}{z^2}$$ are integers, then which of the following is/are possible value(s) of $\left|z\right|$
(A) $\left(\frac{43+3\sqrt{205}}{2}\right)^{\frac{1}{4}}$
(B) $\left(\frac{7+\sqrt{33}}{4}\right)^{\frac{1}{4}}$
(C) $\left(\frac{9+\sqrt{65}}{4}\right)^{\frac{1}{4}}$
(D) $\left(\frac{7+\sqrt{13}}{6}\right)^{\frac{1}{4}}$
My Attempt
Taking $z=x+iy$ we get $(\bar z)^2+\frac{1}{z^2}=(x^2-y^2)(1+\frac {1}{(x^2+y^2)^2})+i(2xy)(1+\frac{1}{(x^2+y^2)^2})$.
The calculation is appearing very arduous. Can there be a simple approach

A: Let $r = |z|$ be a possible value of the modulus. We claim that the above condition is equivalent to
$$
\frac{(|z|^4 +1)^2}{|z|^4} = a^2 + b^2; \ \ a,b \in \mathbb{Z}
$$
It is clear that the condition is necesary, because this the left side is just $|f(z)|^2$. To prove the other implication, consider the map $f(z) = \bar{z}^2 + \frac{1}{z^2} = \frac{1 + |z|^4}{z^2}$. Let $z = |z|e^{\frac{iarg(a-ib)}{2}}$. Then, $f(z) = a + ib$. Then $|f(z)| = \sqrt{a^2 + b^2}$ and $arg(f(z)) = arg(a +ib)$, so $f(z) = a + ib$. Thus, the condition is sufficient.


text:
Q: How does %%configure -f work in jupyterhub? Here is some piece of code I run before connection to spark in Jupyter:
    %%configure -f
      {
          "conf" : {
                   "spark.driver.memory":"8G",
                    some other config
                   },
          "name": my_spark_application_name,
          "queue":yarn_source_queue_to use
      }

I have some question about this usage:

*

*what does magic command %%configure -f do,could anyone please explain this command?I cannot find ralated document

*Is this configure contents designed by other engineers to act as a template to start a pyspark session,or something provided by JupyterHub?What runs behind the whole command?


text:
Q: Boost spirit 2.5.2 standalone Has there been a standalone package for Spirit for version 2 and above? The last standalone found on spirit's website has been 1.8.5. Or is there a way I can extract only the required dependencies for Spirit from the latest version?

A: You can use BCP to extract the Spirit library (and it's dependencies).
However, it wouldn't gain you much. Spirit libraries are already header-only as they are (although if you enable thread-safety, it will require boost-thread too).
So you don't actually gain much from "removing" the unused headers. It's not like the header files are large and the ones that aren't used are... unused anyways.


text:
Q: Im making a calculater in python 3.4 and have an error my problem
Thx in advance! And whats a unident?

A: It looks like you have too many spaces before the elif. It should line up with the if above it and it does not. However, since it's an image and you're using a proportional font, it's hard to tell for certain. It might be a case where you're mixing tabs and spaces for indenting. You should use 4 spaces, and only 4 spaces, with Python.
An indent signifies that you're adding a level of indentation. An unindent means you're removing a level of indentation. For example, going from 8 spaces of indent to 4 is an unindent.


text:
Q: Drawing a custom progressbar inside of a listview row column? So I am currently making a program the uploads files and I am displaying the upload progress and details in a Windows Forms ListView component with 3 columns:

*

*Filename

*To

*Progress

I want to draw a ProgressBar component inside of the third column to show the current progress of the upload instead of just having a text form of say "5%". Here is my code for displaying the upload details:
foreach (Uploader up in Uploads)
{
    if (!up.Bdone)
    {
        int progress = up.progress; //current progress
        //this is where I want to draw progressbar inside row column
        count++;
    }
    else
    {
        to_remove.Add(up);
    }
}


text:
Q: Three.js camera lookAt object freeze the rotation Currently i have:

        <title>Collision Detection (Three.js)</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

This example will feel like a FPS (use with keys WASD, QE). Im trying the figure out, how i can follow an object with the camera without rotating the camera, in the current sample you see:
     this.camera.lookAt( this.player.position );
     this.camera.rotateOnAxis( new THREE.Vector3(0,1,0), 0 );

After looking at the "player", i want the camera to follow the object but without rotation. this is currently not working, any ideas?
**Edit: solved:
if ( this.keyboard.pressed("D") )
    this.player.rotateOnAxis( new THREE.Vector3(0,1,0), -rotateAngle);

/*
var relativeCameraOffset = new THREE.Vector3(0,150,400);
var cameraOffset = relativeCameraOffset.applyMatrix4( this.player.matrixWorld );

this.camera.position.x = cameraOffset.x;
this.camera.position.y = cameraOffset.y;
this.camera.position.z = cameraOffset.z;
*/

this.camera.position.x = this.player.position.x;
this.camera.position.y = this.player.position.y+150;
this.camera.position.z = this.player.position.z+400;

this.camera.lookAt( this.player.position );

//this.controls.update();
this.stats.update();


text:
Q: Any way to escape a Go string in a regular expression? I'm wanting to match ^(@|\s)*{{string}}:? whereas {{string}} is dynamically defined. It may have periods and dashes and any number of things in it and I really need for it to be escaped.
PHP provides a preg_quote method that escapes all special characters safely. I was wondering if Go provides any sort of analog.

A: regexp.QuoteMeta does the deed.


text:
Q: boost::serialization throwing "input stream error" on base class ptr XML serialization Am I doing something wrong here? If I take the comments out that serialize the base first it works, otherwise I get the error:
terminate called after throwing an instance of 'boost::archive::archive_exception'
    what():  input stream error
Aborted

Here is the code:
struct A
{
    virtual ~A() {};

    int i1 = 10;

    friend class boost::serialization::access;
    template <class Archive>
    void serialize(Archive& ar, const unsigned int version)
    {
        ar & make_nvp("int", i1);
    }
};
struct B : A
{
    virtual ~B() {};

    float f1 = 5.0F

    friend class boost::serialization::access;
    template <class Archive>
    void serialize(Archive& ar, const unsigned int version)
    {
        ar & boost::serialization::base_object<A>(*this);
        ar & make_nvp("float", f1);
    }
};
struct C : A
{
    virtual ~C() {};

    long l1 = 24;

    friend class boost::serialization::access;
    template <class Archive>
    void serialize(Archive& ar, const unsigned int version)
    {
        ar & boost::serialization::base_object<A>(*this);
        ar & make_nvp("long", l1);
    }
};

//Why do these need to be wrappers??
namespace boost
{
namespace serialization
{
template<> struct is_wrapper<A*> : mpl::true_ {};
template<> struct is_wrapper<A> : mpl::true_ {};
template<> struct is_wrapper<const A> : mpl::true_ {};
}
}

BOOST_SERIALIZATION_ASSUME_ABSTRACT(A);
BOOST_CLASS_EXPORT(B)
BOOST_CLASS_EXPORT(C)

int main(int argc, char** argv)
{
    //A* a = new A();
    A* b = new B();
    A* c = new C();
    //A* a1 = nullptr;
    A* a2 = nullptr;
    A* a3 = nullptr;

    ostringstream ostream;
    xml_oarchive oarchive(ostream);

    oarchive << /*BOOST_SERIALIZATION_NVP(a) <<*/ BOOST_SERIALIZATION_NVP(b) << BOOST_SERIALIZATION_NVP(c);

    istringstream istream(ostream.str());
    xml_iarchive iarchive(istream);

    iarchive >> /*BOOST_SERIALIZATION_NVP(a1) >>*/ BOOST_SERIALIZATION_NVP(a2) >> BOOST_SERIALIZATION_NVP(a3);

    //delete a;
    delete b;
    delete c;
    //delete a1;
    delete a2;
    delete a3;
}

The same code works in both cases for the text and binary archives...
EDIT: This is using Boost 1.53 and GCC 4.8 w/ std=c++11


text:
Q: Manipulation of an Image in Node.js I want to change the orientation of an image as from portrait to landscape or vice-versa.
I tried doing it using many of the available npm packages :
* rotate-image
* image-rotate
* jpegorientation
* gm
* rad
But each of these is one way or other not working as I want to do it or each has some or other limitations.
I tried to find a possible solution and search for it as much as I could.
Most of the times,it has been done using gm.
I tried doing the image manipulation using gm :

Code:

var gm = require('gm');
gm('path/filename.jpg')
    .autoOrient()
   .write('path/destinationfile.jpg', function (err) {
        if (err) {
            console.log(err);
        } else
            console.log("Orientation changed successfully!");
    })

But I am getting an error as :

Error: Could not execute GraphicsMagick/ImageMagick: gm "identify"
  "-ping" "-verbose" "path/filename.jpg" this most likely means the
  gm/convert binaries can't be found.

This error will be resolved only by using external binary libraries.I don't want to involve any kind of dependencies on 3rd party libraries. Can someone please help me out as of how to do it without pre-installing any of the external binary libraries (brew etc.) or how to use any of the existing package in a better way.

A: You could use the contain method from lwip - Light Weight Image Processor for NodeJS
Here is an example:
// obtain an image object:
require('lwip').open('Example.jpg', function(err, image){
  // check err...
  // define a batch of manipulations and save to disk as JPEG:
  image.batch()
    .contain(image.height(), image.width(), 'black')
    .writeFile('output.jpg', function(err){
      // check err...
      console.log(err || 'Done');
    });
});

This swaps the orientation and fills the gaps in black.
I just tried it, and i only needed to install the lwip module into my application.
npm install lwip --save

A: Mostly likely is the PATH problem (of CentOS). So I would try this:
sudo ln -s /usr/local/bin/gm /usr/bin/gm
sudo ln -s /usr/local/bin/convert /usr/bin/convert

Hope it could help.

A: $ sudo apt-get install graphicsmagick


text:
Q: Laravel 8 || Hostgator Buen día, estoy trabajando en mi portafolio en el servicio de dominio hostgator (no usa control de versiones), tengo una aplicacion web, aclaro que en mi localhost funciona todo al 100. Adjunté mi aplicación en una carpeta del servidor, la conecté a la base de datos, etc.
Al entrar por la url parkinglot.fabianromero.net me recupera los datos con éxito pero al intentar realizar un post me sale el siguiente error.
Me hes extraño porque en mi localhost funciona todo bien. La comunicación con la base de datos funciona porque me trae todo el GET, al añadir un dato es el problema, adjunto imagenes del error.

De ésta manera se encuentra mi modelo:
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Car extends Model
{
    use HasFactory;

    public function typeCar()
    {
        return $this->belongsTo('App\Models\TypeCar');
    }
}

Así importo los modelos en el controlador:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Support\Facades\DB;
//models
use App\models\Car;

Así se encuentra la funcion mi controlador
public function addCar($idType, Request $request){
    try{
        $flag;
        $msg;

        $car = new Car();
        $car->driver = $request->nameDriver;
        $car->type_id = $idType;
        $car->save();
        $car->refresh();

        $flag = 1;
        $msg = "The vehicle was successfully created.";

    }catch(Exception $e){
        $flag = 3;
        $msg = "Error when adding vehicle. Please try again";
    }
    return response($this->notificationCar($flag, $msg));
}

Uso comunicacion AJAX
 $.ajax({
        type:'POST',
        url:"addCar/" + $('#selectTypeCar').val(),
        data: obj,
        success:function(data){
            contentNotification(data.status, data.titulo, data.message);
        }
    });

Mi ruta:
Route::post('/addCar/{idType}', [CarController::class, 'addCar'])->name('addCar');

Espero puedan ayudarme, recalco hostgator no usa control de versiones.


text:
Q: calling a jquery function through button_to in ruby on rails Below is the code of a button i n ruby on rails
<%= button_to "btnAdd"%>

and below is the jquery function:

I want to call jquery function through button. But its not going into the jquery function, why. Kindly reply me. Thanks

A: button_to generates a form with a input type="submit" button like:
<%= button_to "btnAdd"%>
# => "<form method="post" action="" class="button_to">
#
<input value="btnAdd" type="submit" />

#    </form>"

So try this:
$(document).ready(function() {
     $("input[value='btnAdd']").click(function(e) {
      e.preventDefault();
      alert("Hassan");
    }
});

DEMO

A: The problem is you haven't set an id for your button.Try this:

  <%= button_to "btnAdd" %>

#=> <input type="submit" value="btnAdd" id="btn" />

Change your Jquery like this:
$(document).ready(function() {
     $("#btn").click(function(event) {
         event.preventDefault();
      alert("Hassan");
    });
});

Fiddle


text:
Q: Definition of dev_attrs used in gpiolib-sysfs.c I try to understand what's going on in linux kernel driver code, especially how virtual files in /sys/class/gpio/... are created. When inspecting drivers/gpio/gpiolib-sysfs.c I stumbled about these definitions at the bottom of the file:
static struct attribute *gpio_attrs[] = {
    &dev_attr_direction.attr,
    &dev_attr_edge.attr,
    &dev_attr_value.attr,
    &dev_attr_active_low.attr,
    NULL,
};

My question is: Where are these referenced objects (dev_attr_direction, dev_attr_edge, dev_attr_value, dev_attr_active_low) defined? I searched the whole kernel code, but could not find any definitions...

A: I think I've found a possible definition, e.g.
static DEVICE_ATTR(edge, 0644, gpio_edge_show, gpio_edge_store);

could be a precompiler macro that generates one of the doubtful definitions.
Just an idea.


text:
Q: Marketing Cloud Engagement Split Email Clicks Are link clicks trackable if they contain an AmpScript field in them? (within Journey Builder)
Currently have a URL that looks like this:
https://teamlocker.squadlocker.com/#/lockers/%%SL_Store_Id%%
When I look at the engagement split and select 'clicks', it doesn't show any of the links that contain AmpScript.

A: Short Answer : Yes
Explanation:
 Links with ampscript do not show up on the click activity report. To overcome this, you would either have to use alias tags or the ImpressionRegion Ampscript (See Begin Impression Region & End Impression Region function to make these available in your click activity report.
In addition to this, I would advise you place add a redirectTo and a Concat around it like this:
%%=redirectTo(Concat('https://teamlocker.squadlocker.com/#/lockers/',@SS_Store_Id))=%%

A: IF your URL will be

https://www.google.com/conen-AU?email=%%Contact_Value%%&cid=%%CustomerID%%&al=Y&token_required&title=What%20you%20need%20to%20know%20about%20patients%20with%20Type%202%20Diabetes%20and%20established%20CVD&url=https://www.google.com.au/callback/036?isUpnext=false&playlist=false&q=812e2354-ed4f-4f5d-a184-d85315ea04cc&series=false&utm_source=google&utm_medium=Mass%20E-mail&utm_campaign=PLY%20James-%5BAU-TR-NA-NA-VI-LO-EN-2021%5D

Use the Ampscript in the Email:
%%[
    SET @URL1 = "https://www.google.com/conen-AU??email="

    SET @Contact_Value = [Contact_Value]

    SET @CustomerID = [CustomerID]

    SET @Final_URL = Concat(@URL1,@Contact_Value,'&cid=',@CustomerID,'&al=Y&token_required&title=What%20you%20need%20to%20know%20about%20patients%20with%20Type%202%20Diabetes%20and%20established%20CVD&url=https://www.google.com.au/callback/036?isUpnext=false&playlist=false&q=812e2354-ed4f-4f5d-a184-d85315ea04cc&series=false&utm_source=google&utm_medium=Mass%20E-mail&utm_campaign=PLY%20James-%5BAU-TR-NA-NA-VI-LO-EN-2021%5D')

]%%

href="RedirectTo(@Final_URL)"


text:
Q: In ag-grid, is there a known issue with filter values for dateFrom, dateTo, dateFromCondition, and dateToCondition? I want to allow users to filter a grid, and then save the filtering options they have chosen so they can then use that filter subsequently.
I am able to extract the current filter data by using
optionObject.api.getFilterInstance(field_name_for_column);

I see different values in the returned object based on whether the column is a text column, a number column or a date column.
The text columns seem to use filterText and filterConditionText for the 2 allowed filter values.
The number columns seem to use filterNumber, filterNumberTo, filterNumberCondition and filterNumberConditionTo for the allowed filters, where the "To" values are used for range checks.
The date columns seem to have the same sort of setup (dateFrom, dateTo, dateConditionFrom, dateConditionTo) as the numbers.
However, when I print the values, dateFromCondition and dateToCondition seem to have the values from dateFrom and dateTo.
For example, if I do 2 date ranges:
01/01/2004 to 02/01/2004 OR
02/01/2004 to 03/01/2004

The values returned in the filter are:
dateFrom = 01/01/2004
dateTo = 02/01/2004
dateFromCondtion = 01/01/2004
dateToCondition = 02/01/2004

Am I misunderstanding how these values are intended to be used? Or is this a known issue in ag-grid?
I am using the standard agDateColumnFilter setting for filter and have provided a dateFilter routine to do the comparator (per the documentation).

A:
Am I misunderstanding how these values are intended to be used? Or is this a known issue in ag-grid?

ConditionalFilter - configured via getFilterInstance and setModel functions, so - you are be able to retrieve conditionalValue from filter instance.
let dateFilterInstance = this.gridApi.getFilterInstance("yourDateField");
console.log(dateFilterInstance.conditionValue);


text:
Q: How to disable a form on submit using jQuery I want to disable a form once I submit it. I tried this but it doesn't disable the form:
$( "#myform" ).prop("disabled", true);

I am using jQuery/php/ajax. When the user clicks submit the submit button is disabled and a spinner displays in the button. Server side validation is done and errors are displayed or an email is sent and success message is displayed. In that time when the spinner is going, I don't want the user to be able to change anything on the form like click another radio button for example. The form is pretty quick but you never know..

A: I don't think you can "disable" a <form> element.  But if its contents are wrapped in a <fieldset> then you can easily disable that:
<form id="myform" method="POST" action="test.php">
    <fieldset>
        <input type="text">
        <textarea></textarea>
        <input type="submit">
    </fieldset>
</form>

And:
$( "#myform fieldset" ).prop("disabled", true);

Example


text:
Q: Target dimension mismatch I am trying to learn deep learning for a school project. I used ESNet as the network architecture and as of the moment, I am using a simple dataset (cats vs dogs) just to test how the architecture performs. I first saved my dataset in a separate file and later loaded it to my model. Since my dataset is a NumPy array, I converted it to tensors and then resized it. When trying to train, I got the following error:
RuntimeError: only batches of spatial targets supported (3D tensors) but got targets of dimension: 2
Based on the suggestions I found online, the error points out to my target not having the right shape. My input has the shape [batch_size, 3, 100, 100].
Based on this shape the output would have the shape [batch_size, 2, 104, 104] and thus the target should have the shape [batch_size, 104, 104] and contain values in [0, 1]. Yet, whenever i try to train in and try to print what shape my target's shape I got [batch_size, 2].
and this is my training code:
BATCH_SIZE = 10
EPOCHS = 1

for epoch in range(EPOCHS):
    for i in tqdm(range(0, len(train_x), BATCH_SIZE)):
        batch_x = train_x[i:i+BATCH_SIZE].view(-1, 1, 100, 100)
        batch_y = train_y[i:i+BATCH_SIZE]

        print(batch_y.shape)

        model.zero_grad()

        outputs = model(batch_x)
        print(outputs.shape)
        loss = loss_function(outputs, batch_y)
        loss.backward()
        optimizer.step()    # Does the update

    print(f"Epoch: {epoch}. Loss: {loss}")

I've tried every suggestion I found online but found no success. Can anyone help me out? Thank you so much.


text:
Q: Will Google+ APIs shutting down affect signing in into Stack Exchange sites? According to this article, Google+ APIs will shut down on March 7, 2019. Since I am using Google to provide authentication for several web sites (SE sites included), I am wondering if SE network will be affected by this.
Question: Will Google+ APIs shutting down affect signing in into Stack Exchange sites?

A: The Google+ API shutdown will not affect our login system at all. We have already been using the generic Google OAuth2 API for some time, which is a completely independent API and is not being discontinued. We've also already updated our system to grab user info from the generic Google user profile rather than the Google+ profile. Users can continue using the Google login option without interruption.


text:
Q: How could a bulb light up if aĺl the voltage is lost in the resistor? I recently came up with this slight confusion about voltage loss in resistors/resistance. So for example My circuit has a 12V battery, a 2 Ohms resistor and a Bulb. If we use the V=I.R formula then a current of 6A(amperes) will flow through the circuit, then i remembered that V=I.R is the voltage loss due to a certain resistance, if we try to insert this formula to the resistor, then 12V will be lost in the resistor(6A×2 ohms), so how would the bulb turn on if all the voltage is wasted in the resistor?
*I'm still new to this topic, so please give me a clear simplified explanation, any answers would be appreciated.

A:
My circuit has a 12V battery, a 2 Ohms resistor and a Bulb. If we use the V=I.R formula then a current of 6A(amperes) will flow through the circuit

The confusion comes from your first assumption. You start by calculating your current based on the assumption that all the voltage will drop across your 2-ohm resistor.
Take the resistance of your bulb into the equation and you'll get a different answer.
Example:
If your bulb has a resistance of 10 ohms, the current flowing through your circuit will be:
I = V / R = 12V / (2+10) ohms = 1 A.
With this, you can find how much voltage is dropped across your resistor:
V = I * R = 1A * 2 ohms = 2V
So 2V drop across your resistor and the other 10V across your bulb.

A:
if we try to insert this formula to the resistor, then 12V will be lost in the resistor(6A×2 ohms),

Voltage is

Voltage is electric potential energy per unit charge, measured in joules per coulomb ( = volts). It is often referred to as "electric potential", which then must be distinguished from electric potential energy by noting that the "potential" is a "per-unit-charge" quantity.

So the loss of volts means that energy has been deposited on the resistor.This energy following the quantum mechanical behavior of the specific resistor will become heat or light , if it is an incandescent lamp.

A: Voltage isn't "lost" in the resistor.  Voltage provides the driving force to cause electrons to flow through the circuit.  The resistance does what it says: it resists the flow of electrons by using atoms in the resistor to temporarily stop the electrons that are accelerating under the electric field that is in the circuit, and that electric field is measured in voltage drop per meter of length.  When these accelerating electrons hit atoms in their path, they impart their kinetic energy onto the atom that stopped them, leading to heat in the resistor.  The electron is then accelerated again by the electric field, and it continues until it strikes another atom in its path.
For a light bulb, the heat produces an increase in temperature that is high enough to cause the bulb's filament to glow.  The power produced by the bulb is given by the voltage drop across the bulb multiplied by the current flowing through the bulb, or $P=IV$.


text:
Q: React Native iOS "Safari cannot open the page because the address is invalid" after valid login Getting the following after successful login.  The login flow is working as expected on Android, and correctly returns token, refresh, etc...
"Safari cannot open the page because the address is invalid"
Screen Recording of Error
Auth0 Callback Config

Info.plist
...
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleTypeRole</key>
        <string>None</string>
        <key>CFBundleURLName</key>
        <string>auth0</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
        </array>
    </dict>
</array>
...

AppDeligate.m
...
#import <React/RCTLinkingManager.h>
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
  return [RCTLinkingManager application:application openURL:url
                      sourceApplication:sourceApplication annotation:annotation];
}
...

A: I ran into the same issue (while working with Auth0, and the answer sort of depends on the solution they have provided here - https://auth0.com/docs/quickstart/native/react-native)
Also, some inputs from another answer from here - "Safari cannot open the page because the address is invalid" appearing when accessing Branch link with app uninstalled
Eventually, it boils down to this

*

*Starting from iOS 9.2, Apple no longer officially supports URI schemes for deep linking, and developers are strongly advised to implement Universal Links in order to get equivalent functionality on iOS

*To get over this, you have to enable this app linking to work. One option is that (check the linked stack answer) the service provider who wants this to happen will provide a universal link.

Another option (code snippets below) is to add a 'URLScheme'
#import <React/RCTLinkingManager.h>

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
  return [RCTLinkingManager application:app openURL:url options:options];
}

Step Two
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleTypeRole</key>
        <string>None</string>
        <key>CFBundleURLName</key>
        <string>auth0</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
        </array>
    </dict>
</array>

That is what fixed the issue for me (when working with Auth0 library, but whatever library you are using should have something similar to work with). This essentially overcomes the apple/iOS limitation of app links which is the reason you got the original safari error.