text:
Q: Show that a graph has a unique MST if all edges have distinct weights
Prove that if all edge-costs are different, then there is only one cheapest tree (minimum spanning tree or MST). (Use contradiction and make sure to keep track of the costs of the different trees involved.)

Here is my attempt:
Proof by contradiction
Assume that there is more than one cheapest tree, A and B. Assume that tree A and B are different and have the same weight. Let says that the smallest difference in edge cost between A and B is 1. Now, change one of the random edge (not contain in B) in A by half. This does not affect the path or order. However, A is cheaper than B now. This is contradiction. Thus, the original statement still hold.
Is this the correct logic? How do I write it out formally?

A: The question is about showing that the minimal spanning tree is unique if all the edges have different weights.
If one goes through any of the greedy algorithms (Prim, Kruskal..) for finding a minimal spanning tree one notices that the weights do not need to be added, just compared, that is, the weights should be elements of a totally ordered set. Moreover, the minimal spanning tree $T$ obtained by the algorithm has the property that for any other spanning tree $T'$, if we consider the weight
in increasing order for $T$, respectively $T'$
$$(w_1, \ldots w_{n-1})$$ and
$$(w'_1, \ldots w'_{n-1})$$
we have
$$w_i \le w'_i$$
for all $i$. This is due to the fact that we can get from $T$ to $T'$ by a sequence of intermediate trees so that at each step the next tree is obtained from the previous one by substituting an edge with another edge of $\ge $ weight.
If all the edges have distinct weights then $T$ thus obtained is strictly better than any other tree since at each step we substitute an edge with another one of a strictly large weight (the weights cannot be the same). Hence the uniqueness.

A: Suppose there are two minimum trees, $A$ and $B$. Let $e$ be the edge in just one of $A,B$ with the smallest cost. Suppose it is in $A$ but not $B$. Suppose $e$ is the edge $PQ$. Then $B$ must contain a path from $P$ to $Q$ which is not simply the edge $e$. So if we add $e$ to $B$, then we get a cycle. If all the other edges in the cycle were in $A$, then $A$ would contain a cycle, which it cannot. So the cycle must contain an edge $f$ not in $A$. Hence, by the definition of $e$ (and the fact that all edge-costs are different) the cost of $f$ must be greater than the cost of $e$. So if we replace $f$ by $e$ we get a spanning tree with smaller total cost. Contradiction.


text:
Q: What is meaning of destroying local variable in function What is the meaning of destroying local variable:
void f()
{
   int x=10;
}

When that function calls, end of function that local variable x will be what?
And for:
void f2()
{
  int a=100;
  int* b=&a;
}

End of f2() what will be that local variable b's value? Will b pointer be a dangling pointer (will have address but no any value in it)?

A:
when that function calls, end of function that local variable x will
  be what?

Nonexistent.  Evaportated.  Vapor.  Gone.
x here is a variable with automatic lifetime.  "Automatic" refers to the fact that when x goes out of scope, it will be destroyed.  (Not exactly deleted, as that term implies calling delete)
The same is true of all automatic variables, wherether they be integrals, strings, floats, or even pointers:
void f2()
{
  int a=100;
  int* b=&a;
}

Here both a and b are automatic variables.  They will both be destroyed at the end of their scope -- the end of f2().  However, all that will be destroyed is the varible itself.  If an automatic variable is a pointer (eg, a raw pointer), then the thing the pointer points to will not be destroyed.  Consider:
void f3()
{
  char* p = new char [256];
}

p here is still an automatic variable, of type pointer-to-char.  The thing p points to is not automatic -- that is dynamically allocated (we used new).
As written above, p will be destroyed but the memory it points to will not.  This is a memory leak.  In order to resolve this, you must delete it:
void f3()
{
  char* p = new char [256];
  delete [] p;
}

Now the memory pointed to by p has been correctly destroyed, and the pointer itself (p) will be destroyed at the end of its scope since it's an automatic.
The lifetime of p and what p points to are not connected in any way.  Just because you delete p doesn't mean that p itself is now also destroyed.  p is still an automatic variable.
An example:
void f3()
{
  char* p = new char [256];
  cout << (void*) p << "\n"
  delete [] p;
  // p still exists, it just points to to nothing useable
  cout << (void*) p << "\n"
}

After the delete, we print the value of p to the screen.  If you run this, you'll see that the value of p doesn't change from before deleteing it.  p itself was unaffected by delete [] p;.  But at f3()'s closing brace }, it will fall out of scope and there be destroyed.

A: The variables x, a, and b are all local variables,  so they cease to exist after the function returns. If you try to ask what the value of any of them is, a debugger would probably say something like "Couldn't find x in this context."
In more detail, the memory for those variables was allocated from the stack,  and is returned to the stack when the function returned. Calling f() essentially placed the value 10 just above the top of the stack; if you then create another int on the stack uninitialized, it will probably start with the value 10 (you shouldn't rely on this behavior, since it isn't guaranteed, but it gives you a basic idea of how the stack works on many systems).

A: *

*The local variable is allocated automatically for you on the stack, and is automatically released (hence destroyed) when you exit the scope of the function.

*b won't be a dangling pointer, since you did not allocate any memory on the heap (using malloc or new, it's merely a pointer to the address of the local variable a (that is destroyed when you exit the scope of the function)

A: The pointer itself will also go out of scope. The pointer f2 gets destroyed at the end of the function, which does in this situation not create a memory leak as the object it's pointing to is on the stack and wasn't created with new.
But if you consider the following situation:
int *global;

void foo()
{
int a = 10;
global = &a;
}

Then the pointer global exists after foo has finished running, but points to a destroyed out-of-scope variable, the value of which is not defined.

A: Once the stack frame for that function is popped…you cannot refer those local variables

A: When f() exits, x won't exist anymore. Technically, the memory that was used for it remains, of course, but the compiler/system is free to use that memory space for whatever it pleases. And it will eventually reuse it for something entirely different.
If you take the address of x and pass it out of the function, dereferencing that pointer is undefined behaviour of the worst kind. Example:
int* f() {
    int a;
    return &a;
}

int main() {
    int* pointer = f();
    //int b = *pointer;    //Undefined behaviour, the compiler could choose to format your harddrive now!
}

A: You're not destroying anything, your variables go out of scope.
Since its not heap allocated, you wouldn't have any issues with respect to memory management.
If you really want to learn the mechanics of such mechanisms, you can always download ollydbg (assuming windows), and step into right before, during and after the execution of this function, in order to understand how modern programming languages & compilers treat local variables.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a sliding drawer widget provided by google? The YouTube app for android has a sliding drawer. Is this a widget provided by the SDK? There seem to be a bunch of opensource ones, but they all behave in different ways. Is there an 'official' one provided by google?

There is a SlidingDrawer widget class, but it's deprecated (and I didn't understand the deprecation message):
http://developer.android.com/reference/android/widget/SlidingDrawer.html
Thanks

A: Google does offer a DrawerView via a widget that is fairly easy to implement in an app. Here is the Google library for it. This is how I implemented the DrawerView in this Sample Code. The CheeseSquare example by Google also implements the DrawerView nicely.

A: Not official. Google doesn't release it.
Here you can find a good library.
https://github.com/jfeinstein10/SlidingMenu


text:
Q: How do I find a document using Mongolab's $oid with pymongo? I'm trying to do this:
event = coll.find_one({"_id": {"$oid": event_id}})

Where event_id is the string from an ObjectId:
event_id='50bbd48eefbdd2a1e83bc440'

but the event ends up empty. I'm certain this is not how you find documents with the ObjectId's in pymongo, but I have searched for a while and have not figured out how. Any help would be appreciated. Thanks!

A: You have to convert event_id to an ObjectId like this:
from bson.objectid import ObjectId
event_id='50bbd48eefbdd2a1e83bc440'
event = coll.find_one({"_id": ObjectId(event_id)})

A: When searching by id with event_id the ObjectId string as you define it, simply do
event = coll.find_one(event_id)


text:
Q: Mouse follower easing in/out There are a lot of mousefollower tutorials out there. Most of them feature a simple formula for easing the motion:
x += (tx - x) / interp;
y += (ty - y) / interp;

(tx = target position, x = actual position, interp > 1)
This makes the follower go very fast in the beginning, then decelerate slowly to the target position.
How do i have to change the formular, so that i can define a custom acceleration, custom deceleration and a maxspeed for the movement in between? For the very beginning i'd be happy with an added acceleration at all.
Thanks!
Hans

A: Acceleration is the change in velocity over time.  So in 1D, to apply a constant velocity, you'd do:
v += a * dt;
x += v * dt;

where:

*

*a is the acceleration (a constant)

*v is the velocity

*x is the x-position

*dt is the timestep, i.e. the time between updates

You'd do something similar for deceleration, except that a would now be negative.
To set a maximum velocity, you simply need to a conditional check on v, maybe:
v = MIN(v_max, v);

where v_max is your maximum allowed velocity (a constant).
In 2D, you'd need to take into account the direction of travel:
x += v * cos(theta);
y += v * sin(theta);

I'll leave it to you to calculate theta...


text:
Q: What's wrong with my transition, using React and Tailwind CSS? const style = {
   transition: "width 1s 0s"
}

const ReusableHeadersNav = ({ show, setShow, children,modalWidth,setModalWidth }: IProps) => {

    if(show){
        setTimeout(() => {
            setModalWidth(20)
        }, 1000)

    }

    if (!show) return null

    return (

 setShow(false)} >

            <div style={style} className={`sm:h-[100vh]  border-r-[1px] border-l-[1px] b  fixed left-16  bg-white  rounded-r-2xl    w-[${modalWidth}%]`} onClick={e => e.stopPropagation()}>

                    {children}

    )
}

At first everything was working, but when I ran npm start again it stopped working. I don't understand whats happened, since I didn't change anything.


text:
Q: iPhone sending POST with NSURLConnection I'm having some problems with sending POST data to a PHP script with NSURLConnection. This is my code:
    const char *bytes = [[NSString stringWithFormat:@"<?xml version=\"1.0\"?>\n<mydata>%@</mydata>", data] UTF8String];

    NSURL *url = [NSURL URLWithString:@"http://myurl.com/script.php"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[NSData dataWithBytes:bytes length:strlen(bytes)]];

    NSURLResponse *response;
    NSError *err;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
    NSLog(@"responseData: %@", responseData);

And my script.php is as simple as this:
<?php
    echo $_POST['mydata'];
?>

This have worked for me in the past, but for some reason the output I get from NSLog(@"responseData: %@", responseData); now is just "<>" instead of "theData".
Probably some lame mistake somewhere but I can't seem to find it? Any ideas?

A:
Ah yeah... cheers. But the responseData output is like "<48656c6c 6f326f72 6c64>", don't you print NSData with %@? – per_pilot Jan 15 '10 at 13:57

that is because you are showing the "bytes" values you should pass it to NSString to see the real message
NSString *string = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(@"responseData: %@", string);

A: NSString *post =[NSString stringWithFormat:@"usertype(%@),loginname(%@),password(%@)",txtuser.text,txtusername.text,txtpassword.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"http://www.dacinci.com/app/tes2/login_verify.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];

A: Your data is wrong. If you expect the data to be found in the $_POST array of PHP, it should look like this:
const char *bytes = "mydata=Hello%20World";

If you want to send XML Data, you need to set a different HTTP Content Type. E.g. you might set
application/xml; charset=utf-8

If you set no HTTP Content Type, the default type
application/x-www-form-urlencoded

will be used. And this type expects the POST data to have the same format as it would have in a GET request.
However, if you set a different HTTP Content Type, like application/xml, then this data is not added to the $_POST array in PHP. You will have to read the raw from the input stream.
Try this:
NSString * str = [NSString stringWithFormat:@"<?xml version=\"1.0\"?>\n<mydata>%@</mydata>", data];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[str dataUsingEncoding:NSUTF8StringEncoding]];

and on the server try the following PHP:
$handle = fopen("php://input", "rb");
$http_raw_post_data = '';
while (!feof($handle)) {
    $http_raw_post_data .= fread($handle, 8192);
}
fclose($handle);

Please note that this only works if the HTTP header of your POST is not application/x-www-form-urlencoded. If it is application/x-www-form-urlencoded then PHP itself reads all the post data, decodes it (splitting it into key/value pairs), and finally adds it to the $_POST array.

A: POST data and XML data are not the same. You can send XML data just as you did, but the PHP code must parse the XML from the request body. PHP's xml_parse (http://php.net/manual/en/function.xml-parse.php) can help you do this.
Alternatively, if you would prefer sending POST data, set the request body like this:
const char *bytes = [[NSString stringWithFormat:@"mydata=%@", data] UTF8String];

A: If you use  NSURLSession then in iOS9 set
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request addValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
request.HTTPMethod = @"POST";

In PHP set
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
  or die("Unable to connect to MySQL");
  echo "Connected to SQL.";

//select a database to work with
$selected = mysql_select_db($db,$dbhandle)
  or die("Could not select anons db");
  echo "Connected to DB sucess.";

mysql_query("SET NAMES 'utf8'");
mysql_query("SET CHARACTER SET 'utf8'");
mysql_query("SET SESSION collation_connection = 'utf8_general_ci'");

In the db (MySql5) set utf-8_generic.


text:
Q: ansible check non-existent service i'm new to ansible, and i would like to check few hosts for exist/no-exist services to do things based on those facts after.
there is ~100 servers with same debian everywhere, but different workload, so i need to check whether any of services is present and running.
example playbook checks zabbix, mysql and postgres (should check, in fact)
- hosts: all
  remote_user: root
  vars:
      zabb: "{{ ansible_facts.services['zabbix-agent']['state'] == 'running' }}"
      mysql: "{{ ansible_facts.services['mariadb']['state'] == 'running' }}"
      postgres: "{{ ansible_facts.services['postgresql']['state'] == 'running' }}"
  tasks:
    - name: populate
      service_facts:

    - name: checking mysql
      # any action here
      when: mysql
      ignore_errors: yes

    - name: checking postgres
      # any action here
      when: postgres
      ignore_errors: yes

how to avoid failures in resolving services? what is the best way to check if service exist?
there is an option with parsing ps|lsof output via ansible's command module, but this is not look like elegant solution.
ansible version is 2.7.4


text:
Q: Android how to achieve this type of layout with rows and col span

Requirement:

*

*I should be able to scroll entire view if left view is visible or not (all components should scroll at a time if i scroll anywhere with in the view).

*By clicking on show/hide left view button button it should be able to hide or show left view.

*In cell (only cell not left view) there is a expand/collapse functionality (i can increase/decrease
cell height)

*And If i change font size in device settings app, it should be effect here also(So supporting dynamic font size)

A: Navigation drawer + Recycler view is a good solution.
Alternatively to the navigation drawer you can just use a ConstraintLayout that contains your header, left and RecyclerView.

I should be able to scroll entire view if left view is visible or not (all components should scroll at a time if i scroll anywhere with in the view).

That will be resolved by the recycler view itself.

By clicking on show/hide left view button button it should be able to hide or show left view.

Just toggle the visibility of your left view when clicking the button, use something like:
public void toggleLeftViewVisible() {
    int visibility = leftView.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE;
    leftView.setVisibility(visibility);
}

In cell (only cell not left view) there is a expand/collapse functionality (i can increase/decrease cell height)

Resolve that by adding a click listener (maybe on a button or on the view itself) inside your recycler view adapter.

And If i change font size in device settings app, it should be effect here also(So supporting dynamic font size)

If you do the right implementation this should be taken care automatically by Android.


text:
Q: What is the fastest way to find a subsequence of a given sequence that every element before is less and every element after is greater What is the fastest way to find a subsequence of a given sequence under the condition that for each element x in the subsequence, every element in the given sequence before x is less than x and every element in the given sequence after x is greater than x?
Sample input
9, 8, 7, 6, 5, 8, 9, 10, 11, 12, 10, 5, 2, 20, 25, 30, 80, 90, 100, 50, 40, 41

Sample output
20, 25, 30

A: Start with your sequence and construct maximums to the left, minimums to the right:
  9,   8,   7,   6,   5,   8,   9,  10,  11,  12,  10,   5,   2,  20,  25,  30,  80,  90, 100,  50,  40,  41
  9,   9,   9,   9,   9,   9,   9,  10,  11,  12,  12,  12,  12,  20,  25,  30,  80,  90, 100, 100, 100, 100
  2,   2,   2,   2,   2,   2,   2,   2,   2,   2,   2,   2,   2,  20,  25,  30,  40,  40,  40,  40,  40,  41

Pull out the ones where the three arrays match.  In this case 20, 25, 30.
This takes time and memory O(n).


text:
Q: Is "non-linear equation" the proper description of y = x*z (where x, y & z are unknown)? For equation $y = x*z$, assuming $x$, $y$, and $z$ are unknown, what is the correct terminology for describing it?
I'm assuming it is not quadratic since there is no squared term (e.g., $x^2$) and not linear since $x$ and $z$ are both unknowns (unless "linearity" is always with respect to a particular variable?), so maybe "non-linear equation" is the best fit?

A: Are you sure you want a name for this? With the same justification you could call the equation "nonlogarithmic".
If it is really important you could explicitly remark that
"The variables $x$, $y$, $z$ are not linearly related."
Here "linearly related" means that there are constants $a$, $b$, $c$, $d$, not all of them $=0$, such that
$$ax+by+cz=d\ .$$


text:
Q: Should we abandon the "if not null" pattern? I've seen that with the Dictionary API now has methods with bool TryGetValue<TKey, TValue>(TKey key, out TValue value) and I like this kind of methods because they're signaling to the other devs that you must not check the value but the output of the Try method.
And now that I've seen this I've a tendency to this for my own methods. Like if I've a method that could be returning nothing, I like to go the way of bool TryGet[blahblah](criteria, out var result) instead of doing the var result = Get[blahblha](criteria) and then check if(result != null){...}
The main advantage that I see with this technic is the drastic reduction of NullPointerException eventualities: If you're using the method as the convention is implying you should do and the fact that the out keyword imposes that the object is initialized before returning, then, when you access the outed value you should be fine. As opposed to just checking for null where if you simply forget to check for null, then you'll end up in a world of pain...
Am I the only one thinking like that ? What are the cons that I don't see with this technique?

A: This has been around since the early days of .Net - e.g., TryParse(string). In that particular case, it was, among other things, a way for the dev to indicate that an exception shouldn't be thrown. Internally, Parse interrupts normal execution flow by throwing an exception and incurs a performance hit, TryParse does not. This doesn't really matter if there's only an occasional Parse call, but if you're calling such a method a lot of times in a tight loop, you'll feel it.
For null checks, try-get-value is more of a band-aid, though - as it is a null check in (an unconvincing) disguise. It serves its band-aid purpose better if the API is in your control and you make it the only way to access the value, but this might be cumbersome, especially if the system is not designed in a "tell don't ask" manner.
It's better if you can make the return type non-nullable, or if you can leverage the null-object pattern (the simplest example of that is returning an empty list instead of null), or if you can leverage the Maybe/Option monad, or even if you focus your null checks on entry points, and write internal code as self-contained classes/functions that assume that the value they get is not null, even though it technically could be (except in cases where it's vital to check). The last one is helped by the presence of tests - which serve to increase your confidence that exceptions are thrown (or that there's some other potentially more appropriate form of handling) at all points where an invalid value can enter your system, and that the system beyond that is well-behaved.
P.S.
What you should be after regarding null handling is not merely to force your future self and other developers to perform null checks to avoid errors. This is a low bar. What you want is to take a more thought out approach to your error handling - you don't want your code to just be littered with checks and log calls. You want to be more deliberate about it. This lets you decluter your domain logic and write code that communicates better what is it that it's actually trying to do. It's not about hiding errors or pushing them under the rug, it's about being able to write more clearly - and if you can do that, then you're in a better possition to check if your overall logic is actually correct.

A: There are a few reasons this has fallen out of favor. Out parameters require mutability, because you have to create a variable in the calling code that the function mutates. Out parameters are better than reference parameters as they at least explicitly notify the caller that the object will change, but out still has a lot of the downsides associated with passing things by reference. Out parameters also break chaining, which can be acceptable in some cases, but if you make  it a pattern in code it makes things harder to follow.
The try get pattern also make it easier to fall into bad practices in code by violating "tell don't ask." Each call is now asking something about it's internal state then deciding to do something based on that state, but all the logic is outside that thing. There are times when this can be acceptable, but it should be avoided as a generally practice. Excessive use of this pattern makes logic harder to follow as objects get used in more places, or bugs to occur when logic gets duplicated.
If the main goal is to avoid null based exceptions, then the better solution is to never let anything be null. This can be achieved with non nullable types and null object patterns. This is also what .Net/C#/Microsoft are starting to encourage with defaulting warnings about possible nulls in new visual studio releases and supporting explicit marking of reference types that may be null.

A: The bool TryXXX() pattern is not designed to avoid nulls. A method could assign null to an out parameter so technically you would still have to check.
It's needed in locking situations, say where you have a ConcurrentDictionary you can't do:
if(dic.ContainsKey(key))
{
  return dic[key]
}

Because your check might return true, but then another thread removes the item. You cant just do dic[key] and check for null due to the ambiguity of having the key and a value of null vs not having the key.
c#8 should be forcing you to declare possible null returns as nullable types and then giving you lots of green underlines if you don't check for null. switch on warnings as errors and you should be good returning null.

A: Another downside is that if later on you want to adopt asynchronous programming into your code base, you can't convert your TryABC(out int i) into TryABCAsync(out int i)
because async method can't have out and ref parameters


text: Q: Getting big number instead of infinity I have a task to plot grafic of function with asymptotes using Sympy, Numpy and Pyplot. My function is f(x) = (x^3 + 3 * x^2 - 2 * x - 2) / (2 - 3 * x^2). I found that vertical asymptotes are in x = -sqrt(6)/3 and x = sqrt(6)/3, that means that f(sqrt(6)/3) = oo. But F(-np.sqrt(6)/3) returns 2451449131743593.0, not infinity. Why? Also, MatLab gives me the same result, but f(-np.sqrt(6)/3) = oo * sqrt(6) = 2451449131743593.


text:
Q: css centering and resizing rotated text I have a web page with a picture scaled to about 60% wide in the middle.
Next to the picture, I have 3 buttons, which are rotated text.

I need for the buttons to be the same size and spaced apart evenly.
I also need the height of the 3 buttons to be about the same size as the height of the picture, which means they will need to resize with the browser size.
This works now, but it seems very clunky to me.
My questions is: I'm doing this now using some CSS and Javascript, but I'm wondering if there is a better way, perhaps with all CSS?

Brenny's Motorcycle Clinic >

Aledo Fire Protection District >

True North >

Operation Threshold >

Sadler >

                JUST AWARDED

                UNDER CONSTRUCTION

                RECENTLY COMPLETED

CSS:
#sideButtons{
    width:50px;
    margin-left:5%;
    float:left;
    top:0;
    position:absolute;
    margin-top:25px;
    overflow:hidden;
}

.sideBtn{
    width:100%;
    background:#44616e;
    float:left;
    height:130px;
    margin-top:10px;
    box-shadow: inset 0 0 100px #1f2d33;
    position:relative;
}

.sbInside{
  position: absolute;
  top: 35%;
  left: -35%;
    color:#f47421;
    font-size:.6em;
    text-align:left;

    -webkit-transform: rotate(-90deg);
    -moz-transform: rotate(-90deg);
    -ms-transform: rotate(-90deg);
    -o-transform: rotate(-90deg);
    filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
}

and the script:

When viewed on mobile, the 3 buttons move below the picture.
@media screen and (max-width: 768px) {
        #sideButtons{
            width:100%;
            margin-left:auto;
            margin-right:auto;
            float:none;
            top:auto;
            position:relative;
            margin-top:auto;
            text-align:center;
        }

        .sideBtn{
            width:31%;
            float:none;
            display:inline-block;
            height:80px;
            margin-top:auto;
            margin-right:5px;
        }

        .sbInside{
          position: absolute;
          top: 40%;
          left: auto;
            color:#f47421;
            font-size:.6em;
            text-align:center;
            width:100%;

            -webkit-transform: none;
            -moz-transform: none;
            -ms-transform: none;
            -o-transform: none;
            filter: none;
        }

}

A: I think you are looking for something like this: https://jsfiddle.net/DIRTY_SMITH/7oe5kh9L/13/
By setting the img div to 80vh you can just do a little math for the button sizes.
Setting the button width like this height: calc((80vh - 20px)/ 3);
The 80vh is to match the image height, the -20px is to acount for the margin in between and you divide by / 3 because there are 3 buttons.


text:
Q: sidebar menu doesnt show up Yii I've been trying now for an hour to figure out how $this->menu works in Yii views. I found that you just put this in view file of controller and it should work, but for me it doesnt appear on web page.
$this->menu=array(
    array('label'=>'create', 'url'=>'/create/')
);

A: In your default layout used in controller for example:
public $layout='//layouts/column2';

You will find this in {appdir}/views/layouts/column2.php path.
In this template you need to have this where you want to show the custom menu:
<?php
    $this->beginWidget('zii.widgets.CPortlet', array(
        'title'=>'',
        'hideOnEmpty'=>true,
    ));
    $this->widget('zii.widgets.CMenu', array(
        'items'=>$this->menu,
        'htmlOptions'=>array('class'=>'operations'),
    ));
    $this->endWidget();
?>


text:
Q: Adding properties until in react-native-countdown-component with react native state i have a problem with adding value with state to properties until in react-native-countdown-component. I already state the waktu with null, and then i setState the variables waktu from fetch data api. when i running with the console log the state, the value show null at 3 times after that the value from setState show. click here for see the value in console log
then my component countdown i set to variable state the value for until read by null and not from data from api. How can i solve this? when the screen appear the countdown will play with value from data not null. here's my code

import React, { Component } from 'react';
import { View, Text, AsyncStorage, ScrollView, TouchableOpacity, Image, Dimensions, StyleSheet } from 'react-native';
import {Container, Content, Header, Left, Right, Button, Icon} from 'native-base'
import HTMLView from 'react-native-htmlview'
import CountDown from 'react-native-countdown-component';
import Footers from '../components/Footers'
const{width, height} = Dimensions.get('window')

export default class TryOut extends Component {
  constructor(props) {
    super(props);
    this.state = {
      getToken : null,
      getNama : null,
      soal : [],
      TotalSoal : null,
      index:0,
      jawaban: [],
      indexJawaban : 0,
      terjawab : [],
      indexTerjawab : 0,
      value :'',

      to_id : null,
      to_nilai : null,
      id_jawab : null,
      // waktu : null
    };
  }

  state ={
    waktu : 0
  }

  componentDidMount = async() =>{
    const nilai = await AsyncStorage.getItem('token')
    this.setState({getToken:nilai})
    fetch('https://api.bintangpelajar.com/api/user/profile_data',{
        method:'post',
        headers:{
            'Accept':'application/json',
            'Content-Type':'application/json'
        },
        body: JSON.stringify({
            token : nilai
        })
    }).then(response => response.json())
        .then(responseJson =>{
            if(responseJson){
                this.setState({getNama: responseJson.data.damping_nama})
            }else{
                console.log('ada yang salah')
            }
        }).catch(error=>{
            console.log(error)
        })
      this.getSoal()
      // this.isNullJawaban
  }

  getSoal =()=>{
    fetch('http://unnamed48.ccug.gunadarma.ac.id:9091/api/user/soal',{
        method:'post',
        headers:{
            'Accept' : 'application/json',
            'Content-Type' : 'application/json'
        },
        body: JSON.stringify({
          token:this.state.getToken,
          studi:"penalaran umum"
        })
    }).then(res => res.json())
      .then(getData =>{
          // console.log(getData.time)
          if(getData){
              this.setState({
                  soal : getData.data,
                  TotalSoal : getData.count,
                  to_id: getData.to_id,
                  to_nilai : getData.to_nilai,
                  id_jawab : getData.id_jawab,
                  waktu : getData.time
              })

              for(let i = 0; i< getData.count; i++){
                const jawab = this.state.soal[i]
                const coba = {
                  no_soal : i+1,
                  id_soal : jawab && jawab.soal_id,
                  jawaban : ''
                }
                this.state.jawaban.splice(i,0,coba)
              }
          }
      }).catch(error =>{
          console.log(error)
      })
}

  submitJawab(index, no, id_soal, jawaban){
    // alert('indeks ke-'+index)
    const coba = {
      no_soal : no,
      id_soal : id_soal,
      jawaban : jawaban
    }
    if(this.state.jawaban[index] === undefined){
    this.state.jawaban.splice(index,0, coba)
    this.setState((state)=>{
      const terBaru = [...state.terjawab]

      terBaru[index] = jawaban
      return{terjawab: terBaru}
    })
    }else{
      this.setState((state)=>{
        const jawabBaru = [...state.jawaban]

        jawabBaru[index] = coba
        return{jawaban: jawabBaru}
      })
      this.setState((state)=>{
        const terBaru = [...state.terjawab]

        terBaru[index] = jawaban
        return{terjawab: terBaru}
      })
    }
  }

  cek = ()=>{
    alert('jawabannya : ' + JSON.stringify(this.state.jawaban))
    console.log(JSON.stringify(this.state.jawaban))
  }

  nextSoal(index, no, id_soal){
    this.setState({
      index:(this.state.index + 1) % this.state.soal.length,
      indexJawaban:(this.state.indexJawaban + 1) % this.state.jawaban.length,
      indexTerjawab:(this.state.indexTerjawab + 1) % this.state.terjawab.length,
    })
}

prevSoal = ()=>{
    this.setState({
      index:(this.state.index - 1) % this.state.soal.length,
      indexJawaban:(this.state.indexJawaban - 1) % this.state.jawaban.length,
      indexTerjawab:(this.state.indexTerjawab - 1) % this.state.terjawab.length,
    })
}

  render() {
    // var time = this.state.waktu * 60
    const {waktu} = this.state
    const item = this.state.soal[this.state.index]
    const a = item && item.soal_opsi_a
    const b = item && item.soal_opsi_b
    const c = item && item.soal_opsi_c
    const d = item && item.soal_opsi_d
    const e = item && item.soal_opsi_e
    const no = this.state.index + 1
    const id_soal = item && item.soal_id
    const jawaban = []
    console.log(waktu)
    // jawaban.splice(0,0,a,b,c,d,e)
    jawaban.splice(0,0,{pg:'A',ket:a},{pg:'B',ket:b},{pg:'C',ket:c},{pg:'D',ket:d},{pg:'E',ket:e})
    return (
      <Container>
        <Header>
            <TouchableOpacity onPress={()=>this.props.navigation.goBack()}>
                <Left>
                    <View style={{flexDirection:'row', marginTop:'5%'}}>
                        <Button transparent>
                            <Icon name="arrow-back" />
                        </Button>
                        <Text style={{color:'white', marginTop:'12%', marginLeft:'5%', fontWeight:'bold', fontSize:14}}>Kembali</Text>
                    </View>
                </Left>
            </TouchableOpacity>
            <Right>
                <Text style={{fontFamily:'Arial', fontWeight:'bold', fontSize:14, margin:'5%', color:'#fff'}}>Halo, {this.state.getNama}</Text>
                {/* a onPress={()=>this.props.navigation.navigate('edit')} */}
                <Button transparent>
                    <Image source={require('../assets/icons/user.png')} style={{width:30, height:30}}/>
                </Button>
            </Right>
        </Header>
        <Content>
          <View style={{justifyContent:'center', alignItems:'center', marginTop:height*0.05}}>
            <CountDown
              size={20}
              until={waktu}
              onFinish={() => alert('Finished')}
              digitStyle={{backgroundColor: '#FFF', borderWidth: 2, borderColor: '#04458F'}}
              digitTxtStyle={{color: '#04458F'}}
              timeLabelStyle={{color: 'red', fontWeight: 'bold'}}
              separatorStyle={{color: '#04458F'}}
              timeToShow={['H', 'M', 'S']}
              timeLabels={{m: null, s: null}}
              showSeparator
            />
          </View>
          <View style={{flexDirection:'row', justifyContent:'space-between', alignItems:'center', marginTop:height*0.03}}>
            <Text style={{fontSize: 16, marginLeft: width*0.04}}>{no}/{this.state.TotalSoal}</Text>
            {/* {this.state.index != this.state.soal.length-1 ? (this.state.index ==0 ? (<Text>lewat</Text>) : (<View><Text>Lewat</Text><Text>Lanjut</Text></View>)) : (<Text>finis</Text>)  } */}

            <View style={{flexDirection:'row', marginRight: width*0.04}}>
            {this.state.index != this.state.soal.length-1 ? (this.state.index ==0 ? (<Text style={{fontSize: 16, textDecorationLine:'underline', color:'#04458F'}} onPress={()=>this.nextSoal(this.state.index, no, id_soal)}>Lewati</Text>) : (<View style={{flexDirection:'row'}}>
              <Text style={{fontSize: 16, marginRight:width*0.02, textDecorationLine:'underline', color:'#04458F'}} onPress={this.prevSoal}>Soal Sebelumnya</Text>
              <Text style={{fontSize: 16, textDecorationLine:'underline', color:'#04458F'}} onPress={()=>this.nextSoal(this.state.index, no, id_soal)}>Lewati</Text>
              </View>)) : (<View style={{flexDirection:'row'}}><Text style={{fontSize: 16, marginRight:width*0.02, textDecorationLine:'underline', color:'#04458F'}} onPress={this.prevSoal}>Soal Sebelumnya</Text>
              <Text style={{fontSize: 16, textDecorationLine:'underline', color:'#04458F'}} onPress={this.cek}>Finish</Text></View>)  }
            {/* {this.state.index ==0 ? (<Text style={{fontSize: 16, textDecorationLine:'underline', color:'#04458F'}} onPress={()=>this.nextSoal(this.state.index, no, id_soal)}>Lewati</Text>) : (<View style={{flexDirection:'row'}}>
              <Text style={{fontSize: 16, marginRight:width*0.02, textDecorationLine:'underline', color:'#04458F'}} onPress={this.prevSoal}>Soal Sebelumnya</Text>
              <Text style={{fontSize: 16, textDecorationLine:'underline', color:'#04458F'}} onPress={()=>this.nextSoal(this.state.index, no, id_soal)}>Lewati</Text>
              </View>) } */}
            </View>
          </View>
          <Text style={{fontSize: 16, marginLeft: width*0.04, marginTop:height*0.03}}>Pertanyaan</Text>
          {/* <Button title='jawaban tersubmit' onPress={this.cek}/> */}
          <ScrollView style={{marginTop:height*0.03}}>
            <View style={{justifyContent:'center', alignSelf:'center'}}>
              <Image source={require('../assets/image/banner2.png')} style={{width:width*0.7, height:height*0.25}} resizeMode='stretch' />
            </View>
            <HTMLView value={item && item.soal_pertanyaan} style={{margin : width*0.1, textAlign:'justify'}}/>
            {/* <Text style={{margin : width*0.1, textAlign:'justify'}}>{item && item.soal_pertanyaan}</Text> */}
            {/* <View style={{flexDirection:'column'}}> */}
              {jawaban.map(opsi=>{
                  return(
                    <TouchableOpacity
                        onPress={()=>this.submitJawab(this.state.index,no, id_soal, opsi.pg)}
                        // style={{backgroundColor:'blue'}}
                      >
                    <View style={styles.buttonContainer}>

                      <View style={{flexDirection:'row', justifyContent:'center', alignItems:'center'}}>
                        <View style={styles.circle}>
                          <Text style={{position:'absolute', fontSize:24}}>{opsi.pg}</Text>
                          {this.state.terjawab[this.state.index] === opsi.pg && <View style={styles.checkedCircle}></View>}
                        </View>
                        <HTMLView value={opsi.ket} style={{justifyContent:'center', alignSelf:'center', marginRight:width*0.2, marginLeft:width*0.05}}/>
                        {/* <Text style={{justifyContent:'center', alignSelf:'center', marginRight:width*0.2, marginLeft:width*0.05}}>{opsi.ket}</Text> */}
                      </View>
                    </View>
                    </TouchableOpacity>
                      // <TouchableOpacity style={{justifyContent:'center', alignItems:'center', flexDirection:'row' }} onPress={()=>this.submitJawab(this.state.index,no, id_soal, opsi)}>
                      //   <View style={styles.circle}></View> {opsi}
                      //   <View style={{flexDirection:'row', margin:10, backgroundColor:'grey', width:width*0.7}} >
                      //   {this.state.terjawab[this.state.index] === opsi && <View style={styles.checkedCircle}></View>}
                      //     <Text style={{justifyContent:'center', alignSelf:'center', marginLeft:width*0.04}}>{opsi}</Text>
                      //   </View>
                      // </TouchableOpacity>
                  )
              })}
            {/* </View> */}
          </ScrollView>
        </Content>
        <Footers/>
      </Container>
    );
  }
}
const styles = StyleSheet.create({
  checkedCircle: {
      width: 48,
      height: 48,
      borderRadius: 24,
      backgroundColor: 'green',
      opacity:0.5
},
circle: {
  height: 48,
  width: 48,
  borderRadius: 24,
  borderWidth: 1,
  borderColor: '#000',
  alignItems: 'center',
  justifyContent: 'center',
  marginLeft:width*0.07,
  marginTop:height*0.02,
  marginBottom:height*0.02
},
buttonContainer: {
  flexDirection: 'row',
  alignItems: 'center',
  margin:width*0.04,
  backgroundColor:'#fff',
  borderRadius:10,
  borderWidth: 1
  // backgroundColor:'grey'
},
})

thank you for helping me.


text:
Q: Do.com OAuth2 won't give response code I'm trying to interface with Do.com's API, which uses OAuth2, but I can't get a redirect/response code.
I have my "identifier" and "secret" from Do.com and am trying to follow the Do.com authentication instructions by making the initial request using this url:
https://www.do.com/oauth2/authorize?response_type=code&client_id=(my "identifier")

When I do that, I'm taken to the login page, and once logged in, I get prompted to grant permission. Once I click "allow", I get taken to this error page:

I thought that this might have to do with the redirect url or the referrer. When I initially set requested the id and secret, I also had to provide a redirect url. So, at the location of this redirect URL, I made a simple page with just the link on it and used that to initiate the request (so that the referer could be the same as the redirect url), but I get the same result

    Authorize

I'm new to OAuth2, so I hope I'm just overlooking something here. I've tried contacting the Do.com support but haven't received a response.

A: There was an issue with our OAuth2 webflow implementation for the case when the redirect_uri is omitted. This has since been fixed as of Oct 8th, 2013 4:00PM PST.
Thanks for the report @netinept


text:
Q: How to get "this" in jQuery event binding I have a function which is called on keyup or change but I'm struggling to get the value of this
CODE
var myNS = myNS || {};

myNS.validate = {
    dobChange: function(elem){
        console.log($(this).val().length); // trying to check length of "this"
    }
}

$('.dob1-day, .dob1-month, .dob1-year').on('keyup change', myNS.validate.dobChange('foo'));

Console error:
Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
How can I get the value of this?
Fiddle

A: You should extract the DOM element out of the event that is passed to the handler:
//getting the element
myNS.validate = {
    dobChange: function(e){
        console.log($(e.target).val().length); // trying to check length of "this"
    }
}
//calling handler
$('.dob1-day, .dob1-month, .dob1-year').on('keyup change', myNS.validate.dobChange)

A: $('.dob1-day').on('keyup change', myNS.validate.dobChange);

A: You can use call() and anonymous function to set relevant context and pass extra param:
$('.dob1-day').on('keyup change', function(){myNS.validate.dobChange.call(this, "foo")});

-jsFiddle-

A: var myNS = myNS || {};

myNS.validate = {
    dobChange: function($element){
        console.log($element.val());
  }
}

$(function () {
    $(".content").on('keyup change','.dob1-day', function(){
                        myNS.validate.dobChange($(this));
                    });
});

<div class="content">
    <input type="text" class="dob1-day">
</div>


text:
Q: Balancing kd-tree any existing algorithm I'm trying to implement kd-tree but I have problem with one operation - balancing. Is any existing way to balance kd-tree? For example:  after inserting new element I'd like to have still balanced tree

A: The usual approach seems to be to collect new elements in a list, and every now and then rebuild the tree with all changes completely.
Fully rebalancing an k-d-tree is clearly infeasible. There probably are some tradeoff solutions.
But usually, if you want a balanced tree, you would go with an R*-tree instead.

A: After some insert and delete, you need rebuild the KD-tree, this is the usual way to make it balanced.
The completely balanced KD-tree is almost imposible. Or maybe you can try KDB-tree.


text:
Q: Python/MongoDB - Update each document with a sample from another collection I am working with pymongo and latest mongo db. I try to create random bulk data for a DB test.
In this scenario I want to update every document of one collection:
We have to set one property of each to a random existing ID of another collection, incl. some filters.
In our example we have a collection courses and persons and want to assign one randomly picked person (whom should be a professor) to our course.
Currently I am doing this manually by getting the IDs and updating every single document. Here the raw "slow" query workflow with python:
def assign_lektor(vorlesungen):
    for vorlesung in vorlesungen:
       prof_id = db_helper.get_random_prof_by_fak_id(vorlesung['FakultaetID'])
       db_helper.update_document(vorlesung['_id'],"LektorID",prof_id,VORLESUNGEN_COLL)

def get_random_prof_by_fak_id(fakultaet_id):
    collection = client[DATABASE][PERSON_COLL]
    record = list(
        collection.aggregate([{"$match": {"FakultaetID": fakultaet_id, "Art": "Professor"}}, {
                             "$sample": {"size": 1}}])
    )[0]
    return record['_id']

This is working fine, but of course it's very slow.
But now we wanted to make the whole thing much more efficient. After hours of trial and error we came to this approach, with which we now only have to make one request per course:
def assign_random_lector(vorlesung):
    collection = client[DATABASE][VORLESUNGEN_COLL]
    record = collection.aggregate([
        {"$match" : {"_id" : vorlesung['_id']}},
        {"$lookup": {
            "from": "Person",
            "pipeline": [
                    {"$match": {"Art" : "Professor","FakultaetID": vorlesung['FakultaetID']}},
                    {"$sample" : {"size" : 1}},
                    {"$project" : {"_id":1}}
            ],
            "as": "random_sample"
        }},
        {"$set" : {"LektorID" : {"$first": "$random_sample._id"}}},
        {"$project" : {"random_sample" : 0}},
        {"$merge" : {
            "into" : "Vorlesungen",
            "on" : "_id",
            "whenMatched" : "replace",
            "whenNotMatched" : "discard"
        }}
    ])

How can you solve this task with one efficient query? Is there any way to iterate with the cursor over the collection and apply this "aggregation" shown above for every element at once.
The whole query should run on the database, to minimize the I/O. We want to avoid any unnecessary client side logic like for loops.


text:
Q: How do I change an existing SharePoint web application to run the https protocol? We have a internet web application that published and running under http protocol, now we want to change to https .

*

*the existing web application running on Port 80

*its url is http://www.example.com
Here:
How I change a SharePoint web application to run HTTP to HTTPs protocol.

*

*Can I extend the existing web application (that is running on port 80)  to port 443?

*in which  Zone should I extend is extranet or internet?
note :this web application is internet faced application

A: You need to configure SSL to open your site through https:// instead of http://,
You may refer links once your web application is on internet zone you cannot extend it to internet zone again you need to extend it either to intranet, extranet or custom,
http://blogs.msdn.com/b/fabdulwahab/archive/2013/01/21/configure-ssl-for-sharepoint-2013.aspx
http://www.sharepointconfig.com/2010/03/configuring-a-sharepoint-website-to-allow-ssl-connections/
https://griffindocs.wordpress.com/2013/03/20/sharepoint-2013-how-to-add-ssl-to-a-web-application/

A: *

*Can I extend the existing web application (that is running on port 80) to port 443? Yes, but usually I just change the AAM to https and change the bindings in IIS to only use https if you are using IIS 5 or 6, you must "Require SSL".

*in which Zone should I extend is extranet or internet? Internet


text:
Q: Explicitly solving for inverse function Consider a mapping $f:\mathbb{R}^2\to \mathbb{R}^2$ given by
$$ f(x,y) = \left(-x+\sqrt{x^2+y^2},-x-\sqrt{x^2+y^2}\right). $$
I want to find an explicit inverse mapping, on the neighborhoods for which $f$ is locally bijective.
A computation shows that the derivative of $f$ is given by
$$ Df(x,y) = \frac{1}{\sqrt{x^2+y^2}}\begin{bmatrix} -\sqrt{x^2+y^2}+x & y \\
 -\sqrt{x^2+y^2}+x & -y \end{bmatrix} $$
so the partial derivative vectors $\partial_1f(x,y)$ and $\partial_2 f(x,y)$ are orthogonal. Also, the derivative has determinant
$$ \det Df(x,y) = \frac{2y}{\sqrt{x^2+y^2}} $$
which is nonzero if and only if $y\neq0$. Hence the inverse function theorem tells us that for each $(x,y)$ with $y\neq0$, the map $f$ is a bijection on some neighborhood of $(x,y)$. However, I am asked to explicitly find an inverse, which I cannot seem to do. I've bashed the problem with algebra for a while, and nothing nice comes out. My professor calls the system of functions $f_1,f_2:\mathbb{R}^2\to \mathbb{R}$ a "parabolic coordinate system". The graphs of the level sets of $f_1$ and $f_2$ make this clear. Can you help me explicitly calculate what the inverse mapping must be, on a neighborhood $U$ where $f|_U$ is a bijection?
(Also, the wikepedia entry and every other page on "parabolic coordinates" uses a very different set of functions to define what they are labeling parabolic coordinates.)
The algebra I've tried: Set
$$ -x+\sqrt{x^2+y^2} = u \text{ and } -x-\sqrt{x^2+y^2}=v$$
like in high-school algebra; we want to express $x$ and $y$ in terms of $u,v$.
Adding the first equation to the second yields
$$ -2x = u + v $$
which implies $ x= -(u+v)/2 $.
Now subtracting the second equation from the first gives
$$ 2\sqrt{x^2+y^2} = u-v $$
so we square both sides and obtain
$$ 4(x^2+y^2) = u^2-2uv+v^2. $$
Now using the formula we derived for $x$ gives
$$ 4(\left(-\frac{u+v}{2}\right)^2+y^2) = u^2-2uv+v^2 $$
which simplifies to
$$ 4y^2 + u^2 + 2uv + v^2 = u^2-2uv+v^2 $$
and again to $ 4y^2 = -4uv $
which means $y=\pm\sqrt{-uv}$.
Is this correct? This attempt, I got further than any other.

A: $$ \begin{cases}u+v=-2x,\\uv=-y^2,\end{cases}$$
so
$$ \begin{cases}x=-\dfrac{u+v}2,\\y=\pm\sqrt{-uv}.\end{cases}$$
Check:
$$ \begin{cases}-x+\sqrt{x^2+y^2}=\dfrac{u+v}2+\left|\dfrac{u-v}2\right|=u,\\-x-\sqrt{x^2+y^2}=\dfrac{u+v}2-\left|\dfrac{u-v}2\right|=v.\end{cases}$$
The last equalities are correct because $u\ge v$. The sign of $y$ is indeterminate. This is no surprise, as $f$ is even in $y$.


text:
Q: How to allow set-cookie to be sent in AWS HTTP API Gateway? Note: This question is not about AWS REST API Gateway, this question is about AWS HTTP API Gateway
My AWS HTTP API Gateway does not allow cookies to be passed.
I am using

*

*express.js app on server hosted on ECS

*Have set cors as follows:

On HTTP API Gateway:

On the express.js server I have configured cors in the following way:
In app.js
const cors = require("cors");
app.use(cors({
    credentials: true
}));

The response to requests are sent in following way:
const options = {
    maxAge: 900000,
    httpOnly: true,
    secure: true,
    sameSite: 'none'
};

res.status(200)
    .cookie("accessToken", accessToken, options)
    .json({});

When I remove HTTP API Gateway from being in between client and server, the client is receiving cookies properly. But when calls are made to API Gateway, response is throwing following error:
**Access to fetch at 'https://api.*****.**/login' from origin 'https://cookie.*****.**' has been blocked by CORS policy: Request header field custom_field_name is not allowed by Access-Control-Allow-Headers in preflight response.**

^ How do I resolve this error?
Here is the preflight request and its response from developer console > network
GENERAL
Request URL: https://api.*****.**/login
Request Method: OPTIONS
Status Code: 204
Remote Address: [64:ff9b::306:a6f7]:443
Referrer Policy: strict-origin-when-cross-origin

RESPONSE HEADERS
access-control-allow-headers: *
Access-Control-Allow-Methods: GET, PUT, POST, DELETE, HEAD, OPTIONS
Access-Control-Allow-Origin: https://cookie.*****.**
access-control-max-age: 0
apigw-requestid: CIlgSiwhBcwEJyQ=
date: Thu, 08 Jul 2021 04:45:02 GMT

REQUEST HEADERS
:authority: api.*****.**
:method: OPTIONS
:path: /login
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
access-control-request-headers: custom_field_name,content-type
access-control-request-method: POST
origin: https://cookie.*****.**
referer: https://cookie.*****.**/
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: same-site
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36

A: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors-console.html
Read point number 5 about Access-Control-Allow-Headers
That field has the list of allowed headers that you can pass through. You just need to add set-cookie to that list
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie


text:
Q: Difference between msysgit and Cygwin + git? What is the difference between msysgit and Cygwin + git?
Now I'm using msysgit, but I don't like the Git Bash (you can't resize or copy/paste) so I'm thinking think about switching to Cygwin, because then I could use mintty.

A: Edit 2018:
Since my 2010-2012-2014 answer, in 2015 Git for Windows uses msys2, as I detail here.
See more in "How are msys, msys2, and msysgit related to each other?".

Edit (2 more years later: October 2014)
Johannes Schindelin just explained (Oct. 2014) that msysgit is phased out:

We now have a light-weight Git for Windows SDK – which is essentially a standard MinGW/MSys system managed through the package manager mingw-get.
We decided to just phase out the name "msysGit" (as well as the GitHub org of the same name) and:

*

*work on Git for Windows (with the corresponding GitHub org),

*using the name "Git for Windows" for the installer aimed at "end-users" and

*using the name "Git for Windows SDK" for the development environment targeting Git for Windows developers).

Update 2 years later: July 2012
Msysgit is here to stay, and unless you need to add a few hundreds of MB for cygwin, you really don't need Cygwin to just use Git on Windows.
And if you want to access GitHub, you get one package ("Git for Windows" + ssh keys registered for you on your GitHub account + a nice GUI) with GitHub for windows.
Both Git and msysgit are on GitHub.
The msysgit.github.com page clearly illustrates the difference between:
 <---------->
"Git for Windows": Pure users of Git |  "MsysGit": for Testers, developers, custom installer maintainers
See also the msysgit FAQ:

What is this "MSys" thing in "MSysGit"?
MSys is an environment for Windows offering a Unix-type shell and a Perl interpreter. Because many parts of Git are still not builtins programmed in C, but instead shell and Perl scripts, Git for Windows needs such an environment.
Therefore we ship Git for Windows with a very minimal version of MSys.
MSys is also required to build Git, as we re-use the same Unix-type setup upstream Git uses. We ship a more complete MSys environment, including GCC, as build environment (which is therefore nick-named ''msysGit'').
We compile Git as a pure MinGW program, though, i.e. a program without any link-dependencies on anything but standard Windows libraries.
  So unless you need to use any parts of Git that are still implemented only as shell or Perl scripts, you can get away with running plain git.exe.

Original answer: June 2010
a/ You can resize and copy-paste in Git bash, like in any other Windows Shell.
b/ You are probably using "Git for windows", and not msysgit. From the wiki:

*

*msysGit is the development environment to compile Git for Windows. It is complete, in the sense that you just need to install msysGit, and then you can build Git. Without installing any 3rd-party software.

*Git for Windows is an installer which installs Git -- and only Git.

  It is easy to see the difference:

*

*the installers for Git have the prefix Git-,

*the msysGit installers have the prefix msysGit-.

  Another telltale is that the msysGit installers come in two flavors: fullinstall and netinstall.
  Further, msysGit does not install to C:\Program Files by default.
  But msysGit comes with gcc, the GNU C Compiler.

c/ From MSysGitHerald10:

Remember:

*

*MinGW is really a very thin compile-time layer over the Microsoft Runtime; MinGW programs are therefore real Windows programs, with no concept of Unix-style paths or POSIX niceties such as a fork() call.

*MSys, in contrast, is a slimmed-down version of Cygwin (an old version at that), whose only purpose is to provide enough of a POSIX layer to run a bash.

And that is not always welcomed:

When working on Windows, I dislike that msysGit, as the name suggests, depends on MSYS and on tools from the Unix world. I believe all programs in the Git distribution should become binaries compiled for a specific platform, and not rely on shell interpreters or third-party languages like Tcl/Tk.

Even though, it is far better than the first Git on Cygwin installations from 2007.

A: cygwin + git was the only way to make git work back in the day. Now that msysgit is around, I don't see any reason to use cygwin.
I agree git bash isn't that good.. so what I do is

*

*Put git in path and use window command prompt when I need command line

*Have tortoise git installed for when I want to have a GUI to my git

A: This is an answer from 2017...
The fundamental technical difference is that all cygwin programs depend on the cygwin1.dll; but that's at the same time the least interesting one for the end user since it should be almost completely transparent. The main differences I found are not between the git versions as much as between the cygwin environment and msys/mingw environment. These are some differences I found:

*

*ACL handling. The way newer (post-2015) cygwins handles NTFS access control lists can be annoying to the point of dangerous. By default, the Windows drives are mounted with the acl option active. Cygwin tries to mimic POSIX permissions by re-shuffling and abusing ACL entries in a way which can make access through native windows programs impossible. Additionally it's possible that file access is slowed down dramatically in multi-user multi-domain (i.e., commercial or institutional) installations due to network access, because determining user and permissions potentially requires domain server queries for each file.
msys mounts with the -noacl option by default. Doing that in cygwin as well seems to avoid those issues.

*Speed. I'm currently working in a repository with 100k files (don't ask). A git status with all relevant disk contents in the cache takes 4.7 seconds with cygwin and 0.4 seconds with msys git. I'm not sure which part of the cygwin compatibility layer is slowing things down -- locks, forks, filesystem, IPC... they all are candidates.

*Potentially filenames. I have not investigated the issue but I would suspect that a git (and the other tools) targeted for windows (like msys git) can handle windows file names better. Under cygwin one must diligently convert file names via cygpath between the two worlds. That will play an important role when scripts etc. interface with Windows programs.

Edit: it is perhaps not obvious that with some minor tweaks it is possible to share common settings for git (but not only for git) between cygwin and Msys2. If I remember correctly a good way is to set the HOME environment variable in the Windows system settings; then both Msys2 and cygwin will use that directory and hence the same dot-files, among them ~/.gitignore. That makes changing between cygwin and Msys2 terminals pretty painless (think ~/.inputrc, ~/.bashrc, ~/.profile...).

A: MSysGit ships with a very old version of SSH. Throughput on my system was around 10 mbit. If you don't care about clone speeds, then this does not affect you. The fix is to either run Cygwin Git or replace the SSH installed in MSysGit.

A: The bash implementation in msysgit is old. However, i use vim when editing and that works great. As for cutting and pasting, I often resort to SHIFT+ALT+[space], E, M or whatever the keys are to get to mark text I want. Not ideal, but does the job well enough as I don't cut and paste too much.
I've now started running Ubuntu on the same machine through VirtualBox. With seamless mode and shared folders, I can take advantage of an up to date bash and fast Git.
I do not use any gui tools for Git except gitk (for gitk --all) to visualize history if I need to.
I've tried cygwin and didn't like it. The virtual box solution is much better if msysgit is not enough for you.

A: The current version of git on cygwin is 1.7.5.1, which is very, very current (May, 2011).
I see no reason (so far) to use anything else, though I am considering giving msysgit (aka "Git for Windows") a try (currently version 1.7.4).

A: Msysgit has received a number of patches to deal with Windows specific issues such as filesystem case insensitivity, file locking etc. It's probably a bad idea to use the cygwin version. If you have cygwin on your system I'd advise not installing git at all, and preferably not sharing msysgit or cygwin environments from the same PATH.

A: cygwin sees your local files in windows format, whereas git-bash sees them in unix format. If you check out files in git-bash then run git status on a cygwin shell, git thinks you have modified every line in the repo, if you run git status in the git-bash shell, then only files you have touched are modified.

A: This is an answer from 2018...
Git for Windows is based on MSYS2.

MSYS2 was started with the idea to restart the MSys project, frequently updating with Cygwin and just keeping the spirit of MSys to provide a very stripped-down POSIX layer, essentially a bare-minimum version of Cygwin. MSYS2 also sports a package manager (pacman) and keeps those packages up-to-date very well.

..

MSYS2's runtime is a stripped-down, slightly modified Cygwin runtime running on top of the Windows kernel, while Linux' runtime is the Linux kernel, running as a separate OS altogether.

https://github.com/git-for-windows/git/wiki

Cygwin provides a runtime library called cygwin1.dll that provides the POSIX compatibility layer where necessary. The MSYS2 variant of this library is called msys-2.0.dll and includes the following changes to support using native Windows programs: How does MSYS2 differ from Cygwin

A: If you plan on doing more than just git commands in git bash, I'd suggest Cygwin with git.
If you plan on not doing anything but git commands in git bash, then a) sure, use git bash, but b) why not just use Git GUI?
Git bash is not that bad, BUT, there's times when I need to use Cygwin for things that simply don't work in git bash. (Perl CPAN, for example. XSL tools, for another.) Which seems really silly to have to use two totally different bash command line implementations.


text:
Q: how to write python concurrent future and retry correctly? Tableau API I am a newbie to concurrent. I am trying to refresh 3 workbooks in Tableau:
    workbook_dict = {"workbook1":"workbook_id1","workbook2":"workbook_id2","workbook3":"workbook_id3"}

    @retry(tries=3, delay=5, backoff=0.2)
    def refresh_workbooks(self, workbook_dict):
        for workbook_name, workbook_id in workbook_dict.items():
            workbook = self.server.workbooks.get_by_id(workbook_id)

            #refresh will fire up the refresh, and return job_id object
            job_id = self.server.workbooks.refresh(workbook)

            #wait_for job will check the status and raise exception if fails or timeout
            #https://tableau.github.io/server-client-python/docs/api-ref#jobswait_for_job

            self.server.jobs.wait_for_job(job_id,timeout=1000)

This base code totally works and each workbook takes 15mins, so totally 45min to complete; And if it fails on the second workbook, it will start over from scratch.
I want to use concurrent to speed up and check wait_for_job. And if any fails then refresh only that workbook, retry a few times before throwing errors.
First question: The below code is my attempt to try concurrent but the printed data object returns None.
I think the code failed to execute the wait_for job
Why is that?

import concurrent.futures
import urllib.request
import tableauserverclient as TSC

def refresh_workbook(self, workbook_id):
    workbook = self.server.workbooks.get_by_id(workbook_id)
    job_id = self.server.workbooks.refresh(workbook)
    return job_id

def refresh_workbooks(self, workbook_dict):
    job_dict = {}
    try:
        for workbook_name, workbook_id in workbook_dict.items():
            workbook = self.server.workbooks.get_by_id(workbook_id)
            job_id = self.server.workbooks.refresh(workbook)
            job_dict[workbook_name] = job_id.id
            print(job_dict)
    except:
        raise

    return job_dict

def wait_workbook(self, job_id, timeout=None):
    self.server.jobs.wait_for_job(job_id, timeout=timeout)

test = TableauServerConnection()
workbook_dict = {"workbook1":"workbook_id1","workbook2":"workbook_id2","workbook3":"workbook_id3"}
jobs = test.refresh_workbooks(workbook_dict)

with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:

    future_to_job = {executor.submit(test.wait_workbook, job_id, 1800): job_id for workbook_name, job_id in jobs.items()}
    for future in concurrent.futures.as_completed(future_to_job):
        job = future_to_job[future]
        try:
            data = future.result()
            #Why did I get None in data?
            print('data',data)
        except Exception as exc:
            #can I spin up new future here and what is the correct syntax?

            print('%s generated an exception: %s' % (job, exc))
        else:
            print('job', job)

Secondly, if I add retry in exception, could I add new future object there?

A: You migth want to try something like this,
I'm using a while loop and getting the lastest result.
Then for each finished task I can now add some new task.
In your case only when a task fails.
But this allow you to to also not submit all the task at the begining. Depending on the number of task you want to run, it might be better to add X task at the begining (Where X > max_workers) and then each time a task finishes you add one more.
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:

future_to_job = {executor.submit(test.wait_workbook, job_id, 1800): job_id for workbook_name, job_id in jobs.items()}
while future_to_job:
    done, _ = concurrent.futures.wait(
            future_to_job, timeout=0.25,
            return_when=concurrent.futures.FIRST_COMPLETED)

    for future in done:

        try:
            data = future.result()
            #Why did I get None in data?
            print('data',data)
        except Exception as exc:
            #can I spin up new future here and what is the correct syntax?
            print('%s generated an exception: %s' % (job, exc))
            # get the jobs id
            job_id = future_to_job[future]
            # clean up the old task
            del future_to_job[future]
            # add the wen one
            future_to_job[executor.submit(test.wait_workbook, job_id, 1800)] = job_id
        else:
            print('job', job)

For the None part, your wait_workbook function should return the result
def wait_workbook(self, job_id, timeout=None):
    return self.server.jobs.wait_for_job(job_id, timeout=timeout)

hope it helps :)


text:
Q: C++, vectors, pointers and objects confusion I am working on a project as a homework for my university course of Systems Programming.
I got really confused with the matter of Pointers, Vectors, stacks and heaps.
Using C++.
I have to get a vector of objects which are courses, and those courses objects have several different fields.
What I did was this:
vector<CoursesObject> coursevector;

and then I created my Courses Object class, which contains the space left in course and name of course fields.
Now I want to add a new course, I do:
CoursesObject *theCourse = new CoursesObject(name, space);

now I want to add it to the handler vector:
coursevector.push_back(*theCourse);

With all I know, I created a vector of Courses objects on the stack, and made a new pointer to a new course that is on the heap, and added to the handler vector the pointer theCourse that points to the course object in the heap. Is what I said correct?
When I try to delete those course objects, I do:
for(int i=0; i<coursevector.size(); i++)
    delete coursevector.at(i);

which gives me an error that it is not a pointer. But haven't I added to the coursevector a POINTER to the course object?
Please somebody explain, I have to handle the memory correctly and it seems that I am not getting it right.

A: This
vector<CoursesObject> coursevector;

is a vector of CourseObjects, so it cannot hold CourseObject pointers. When you do this:
coursevector.push_back(*theCourse);

you get a copy of the CoursesObject pointed at by theCourse stored in the vector. You do not need to delete any entries from the vector. In fact, you can't, because it doesn't hold pointers.
You program would be much simpler if you just avoided the dynamic allocation:
coursevector.push_back(CoursesObject(name, space));

A: You do not need to use new at all.
//This vector stores CoursesObject objects,
//not pointers to CoursesObjects.
vector<CoursesObject> coursevector;
//Construct theCourse with automatic storage
//duration.
CoursesObject theCourse(name, space);
//Copy theCourse into coursevector
coursevector.push_back(theCourse);
//theCourse will be automatically destroyed.
//coursevector (and all the objects that it contains)
//will be automatically destroyed.

A: all of your objects are not dynamically allocated, so you cannot delete them at any time during the program. Remember that you can only delete object once they are dynamically allocated:
int Var1 = 0;  //cannot be deleted, scope and life will exist for the life of program
int * Var2 = new int; //CAN be deleted, dynamically allocated.

delete Var2; //free memory

You can however delete your last object, which is a pointer. I would grab the last element of the vector and call delete on it(which should be your pointer to the class).

A: when you do this:
coursevector.push_back(*theCourse);

actually you are dereferencing the pointer theCourse, so you are adding a copy of the object. You need to declare a vector of CourseObject pointers:
vector<CoursesObject *> coursevector;

Then you add an object:
coursevector.push_back(theCourse);

Now your code to delete the objects should work:
for(int i=0; i<coursevector.size(); i++)
    delete coursevector.at(i);

A: coursevector can hold only CoursesObjects and not pointers to CoursesObjects, so you needn't use the new operator (check @Mankarse's answer). But, if you still want to hold pointers, then change the definition of coursevector to
vector<CoursesObject*> coursevector;

and push_back the value of the pointer as it is:
coursevector.push_back(theCourse);


text:
Q: Elegant way to show corresponding text_field_tag value in Rails 4 So my problem is showing something that a model has in a nice and simpler way.
So what currently works?
In my viewer this works fine:
<%= text_field_tag(:first_name, (current_user.present? ? current_user : '').first_name.present? ? current_user.first_name : '') %>

However this is too long and really hard to maintain, especially when I have several more fields.
So to avoid that I made this in my controller
def user_vals(value)
    if(current_user.present?)
      current_user.value.present? ? current_user.value : ''
    end
    return ''
  end

Within this controller I can call user_vals(:first_name) but get undefined methodvalue'` error. Furthermore I cannot just call
<%= text_field_tag(:first_name, @user_vals(:first_name)) %>

As I am getting some syntax error with brackets but that's not the real issue.
So my ultimate goal is to have something like this:
<%= text_field_tag(:first_name, @user_vals(:first_name)) %>

Rather than the first code I've given above. How can I achieve that?

A: You can use try in this case. Just write:
<%= text_field_tag(:first_name, current_user.try(:first_name)) %>

See: http://apidock.com/rails/Object/try

A: I would recommend to take a step back and try to use Duck Typing to solve this...
What you have right now is a current_user method. This method can return whatever object it wants if the user is not logged in, and that object can respond to whatever it wants. Here's a simplified example:
def current_user
  @user || OpenStruct.new(first_name: "")
end

Note: I'm assuming @user holds the currently-signed in user... but this may be a call to super instead, or whatever else depending on your implementation.
So now, instead of branching based on what type of object is coming back from the current_user method, you can now just use the returned object without regard.
current_user.first_name # => Either the User object's first name or `""`

You can go further with this by creating e.g. a GuestUser class and having GuestUser.new returned instead of the OpenStruct above. Guestuser would be a model that is not data-base backed and could respond to any number of methods as needed.
This idea has been represented by many others as well. And using a class to prevent repeated code switching based on nil actually has a name: The Special Case Pattern. As a quick, free example, see the Guest User RailsCast. Or, if you subscribe to Ruby Tapas, be sure to check out episode 112: Special Case. This topic, and many others, are also covered in depth in Avdi Grimm's excellent book: Confident Ruby, which I highly recommend.


text:
Q: How To Set Ajax Url with Variable i want to add some string to the url in ajax process, but fail every time i access the function.
when i submit the form it only access this url 'Master_data/'
var jenis_submit = document.getElementById('jenis_submit');
var submit_url = '';
if (jenis_submit == '1') {

    submit_url = "func_save_instansi";
} else if (jenis_submit == '2') {

    submit_url = "func_update_instansi";
}

$.ajax({
    url: '<?php echo base_url();?>Master_data/' + submit_url,
    method: 'POST',
    data: dataKirim,
    contentType: false,
    cache: false,
    processData: false,
    success: function(data) {
        // console.log(data);
        $('#notif').html(data);
    }
});

A: Just assign the php value to a js variable and concat both
var url = '<?php echo base_url();?>Master_data/';

and then in ajax
url: url + submit_url,

UPDATED:
I missed one other mistake in your code
var number = document.getElementById("number").value; //in your code `.value` is missing

as mentioned in the above(M.Hemant)'s answer.

A: First, get value by id with javascript like this,
//var number = document.getElementById("number").value; //in your code `.value` is missing

var jenis_submit = document.getElementById('jenis_submit').value;
var submit_url = '';
if (jenis_submit == '1') {

    submit_url = "func_save_instansi";
} else if (jenis_submit == '2') {

    submit_url = "func_update_instansi";
}

then
Replace your code with this
url: "<?php echo base_url('master_data/'); ?>" + submit_url,

A: Try this:
var jenis_submit = document.getElementById('jenis_submit');
var submit_url   = '';

if (jenis_submit == '1') {
    submit_url = "func_save_instansi";
} else if(jenis_submit == '2') {
    submit_url = "func_update_instansi";
}

var post_url = '<?php echo base_url('Master_data'); ?>' + '/' + submit_url;

$.ajax({
     type: "POST",
     url: post_url,
     data: dataKirim,
     beforeSend: function() {
       // you can show a preloader here
     }
 }).done(function(data) {
     // hide the preloader
     // console.log(data);
     $('#notif').html(data);
 }).fail(function() {
   // hide the preloader
   // show an error message
 });


text:
Q: multiple {min,max} quantifiers in regexp In case of using multiple {min,max} quantifiers in a regexp I see that not all the combinations are used.
/[XYZ]{15,20}[WXY]{15,20}/

I tested it on a pretty random string of 11k characters but the results are not what I expected: link
I suppose that the first pair [XYZ]{15}[WXY]{15} is evaluated as TRUE and then it jumps to the next one which is [XYZ]{15}[WXY]{16}. Thus the question:
Why does perl take the first case /[XYZ]{15}[WXY]{15}/ and then moves onto /[XYZ]{16}[WXY]{15}/ instead of /[XYZ]{15}[WXY]{16}/?
Can I control this behaviour or I need to move on and generate all combinations of such patterns and search one by one?
Thanks for any advice.
PS.
This is somewhat linked to my previous post.

A: I think there is a misunderstanding on your side. The regex is not matched completely using at first the min of both quantifiers.
The regex engine tries at first to match the first character as often as possible (Quantifiers are greedy by default), so [XYZ]{15,20} is matched if there are at least 15. Then it looks is there another char, ..., max till it found 20, so when it found between 15 and 20 of [XYZ], then it moves on to check for the rest of the pattern.
Example:
(X{15,20})(X{15,20})

and a String of 35 "X"
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

You will get the first 20 "X" in the first group, and the following 15 "X" in the second group.
See it on Regexr

A: Here is a visual example of how regex performs a match:

As you can see, regex performs matches left to right. This is especially crucial to take into account when using many complex alternations such as (first|second|f1rst|s2cond).
So, the regex engine will completely expand the left {15,20} before it moves onto the character class that follows.


text:
Q: Why switch from HttpClient version 3 to 4 My Java application is developed using HttpClient 3. Is there any advantages of switching to version 4?
Is there a changelog. article, blog entry or something that describes what's new?

A: Here are the release notes: http://www.apache.org/dist/httpcomponents/httpclient/RELEASE_NOTES.txt


text:
Q: Listen field's event within roweditor I'm well aware about how to listen event on roweditor on a controller, which is by using control config to query grid with roweditor plugin inside then fire roweditor event.. but the exact event I want to listen to is actually belongs to the component (textfield, for instance) within that roweditor. I don't think that event relayed to the grid panel.
Is there a way to actually listen field's event within that roweditor by using controller?

A: I somehow managed to succesfully listen event from components within grid roweditor. It's turn out we can not query that components as children of the grid.
Suppose I want to get field component within grid roweditor, this code will return null
Ext.ComponentQuery.query('grid field[id=test]');

instead, query that field as it was not the child of that grid and it works
Ext.ComponentQuery.query('field[id=test]');


text:
Q: Design implications of returning a function with void Consider the following bar functions
#include <iostream>

void foo(){
    std::cout << "Hello" << std::endl;
}
void bar1(){
    return foo();
}
void bar2(){
    foo();
}
void bar3(){
    foo();
    return;
}
int main()
{
    bar1();
    bar2();
    bar3();
    return 1;
}

These functions do exactly the same thing, and actually godbolt produces the same code for all three (as one would hope). The question I have is simply whether there are any software engineering paradigms/guidelines that advocate one form over the other, and if there are any reasons why you would prefer one over the other. They seem to produce the same machine code, but I am imaging that one might be viewed as "easier to maintain", or something like that.

A: This is quite opinion-based. Though I'd say the general consensus is to write it like bar2(). Don't return explicitly unless you have to return early and don't do return func() if func() returns a void, that just confuses readers because you're not actually returning a value.

A: I totally agree with Sombrero Chicken's answer. But I'll also add that the construct like
void bar1(){
    return foo();
}

doesn't make much sense for ordinary functions that return void, but may be useful for template code when you don't know the actual return type, e.g:
template <typename T>
auto SomeTemplateFunction(...)
{
   // do some works
   ...
   return SomeOtherTemplateFunction<T>(...);
}

This will work regardless SomeOtherTemplateFunction<T>'s return type is void or not.

A: It's quite opinion based, what I can say is that (3) is tagged by clang-tidy rules as part of the readibility-redundant-control-flow.
The idea is that the control flow here is already defined, the return is superfluous and should then be removed.


text:
Q: How to prepare a blank website to be dockerized? I have a totally empty debian9 on which I installed docker-ce and nothing else.
My client wants me to run a website (already done locally on my PC) that he can migrate/move rapidly from one server to another moving docker images.
My idea is to install some empty docker image, and then install on it manually all dependencies (ngingrtmp, apache2, nodejs, mysql, phpmyadmin, php, etc...)
I need to install all these dependencies MANUALLY (to keep control)  - not using a ready to go docker images from dockerhub, and then to create an IMAGE of ALL things I have done (including these dependencies, but also files I will upload).
Problem is : I have no idea how to start a blank image, connect to it and then save a modified image with components and dependencies I will run.
I am aware that the SIZE may be bigger with a simple dockerfile, but I need to customize lots of things such as using php5.6, apache2.2, edit some php.ini etc etc..
regards

A: if you don't want to define you're dependencies on the docker file then you can have an approach like this, spin up a linux container with a base image and go inside the docker
sudo docker exec -it <Container ID> /bin/bash

install your dependencies as you install on any other linux server.
sudo apt-get install -y ngingrtmp apache2 nodejs mysql phpmyadmin php

then exit the container by ctrl+p and ctrl+q and now commit the changes you made
sudo docker commit CONTAINER_ID new-image-name

run docker images command and you will see the new image you have created, then you can use/move that image

A: You can try with a Dockerfile with the following content
FROM SCRATCH

But then you will need to build and add the operating system yourself.
For instance, alpine linux does this in the following way:
FROM scratch
ADD rootfs.tar.xz /
CMD ["/bin/sh"]

Where rootfs.tar.xz is a file of less of 2MB available on alpine's github repository (version 3.7 for x86_64 arch):
https://github.com/gliderlabs/docker-alpine/tree/61c3181ad3127c5bedd098271ac05f49119c9915/versions/library-3.7/x86_64
Or you can begin with alpine itself, but you said that you don't want to depend on ready to go docker images.
A good start point for you (if you decide to use alpnie linux), could look like the one available at https://github.com/docker-library/httpd/blob/eaf4c70fb21f167f77e0c9d4b6f8b8635b1cb4b6/2.4/alpine/Dockerfile
As you can see, A Dockerfile can became very big and complex because within it you provision all the software you need for running your image.
Once you have your Dockerfile, you can build the image with:
docker build .

You can give it a name:
docker build -t mycompany/myimage:1.0

Then you can run your image with:
docker run mycompany/myimage:1.0

Hope this helps.


text:
Q: Complex conjugate of the Schrodinger Equation My question is from the mathematical part of Quantum Mechanics, so I will try my best to create enough context.This is the one-dimensional time-dependent Schrodinger Equation:
$$i\hbar \frac{\partial \psi}{\partial t}= -\frac{\hbar^2}{2m}\frac{\partial^2 \psi }{\partial x^2} +\displaystyle {\hat {V}\psi}$$
$i,\hbar,m$ are certain physical constants and $\psi$ is a function of $x$ and $t$.
$\displaystyle {\hat {V}}$ on the other hand is the potential energy operator.
My textbook takes the complex conjugate of this equation(note that $\psi^*$ is the conjugate of $\psi$),
$$-i\hbar \frac{\partial \psi ^*}{\partial t}= -\frac{\hbar^2}{2m}\frac{\partial^2 \psi ^* }{\partial x^2} +\displaystyle {\hat {V}\psi^*}$$and multiplies it by $\psi$
$$-i\hbar\psi \frac{\partial \psi ^*}{\partial t}= -\frac{\hbar^2\psi}{2m}\frac{\partial^2 \psi ^* }{\partial x^2} +\displaystyle {\hat {V}|\psi|^2}$$
My Question:
How can $\psi \displaystyle {\hat {V}\psi^*}= \displaystyle {\hat {V}|\psi|^2}?$Does it not depend on the nature of $\displaystyle {\hat {V}}?$
For example, if $\displaystyle {\hat {V}}$ was $-i\hbar\frac{\partial}{\partial x}$, given that $\psi = e^{i(kx-\omega t)}$($k$ and $\omega$ are constants),
$\psi \displaystyle {\hat {V}\psi^*}=-e^{i(kx-\omega t)} i \hbar(ik e^{-i(kx-\omega t)})=\hbar k$ whereas$\displaystyle {\hat {V}|\psi|^2} = \displaystyle {\hat {V}1}=0!$
Or is $\displaystyle {\hat {V}|\psi|^2}$ just a notation?


text:
Q: Weblogic 12.1.3 error connecting domain with Eclipse (OEPE 12.2.1..2.1) Suddenly I am getting problem connecting Weblogic 12.1.3 with OEPE Mars, When I am trying to run server its giving:

Error Connecting Weblogic Default Domain

However, I have de-installed Weblogic/JDK1.8/Eclipse and did fresh reinstall. Earlier it was working fine with the JDK1.8.
However, again I have de-installed Weblogic/JDK/Eclipse and reinstalled with updated version of Weblogic 12.2.1 with JDK1.8.162 (latest JDK8) and OEPE Oxygen to keep JDK version same in all the environments.
Now while I am trying to create server in Eclipse its giving me message:

The Path C:\Oracle_JDeveloper12.2.1\Middleware\Oracle_Home\wlserver doesn't contain a valid Weblogic Server Install or installed version is

I have installed JDeveloper 12.2.1.3 that comes with integrated Weblogic.
Any help will be appreciated.

A: Create a weblogic domain by using config.cmd
Path: \Oracle\Middleware\Oracle_Home\oracle_common\common\bin\config.cmd
And update JAVA_HOME path in setDomainEnv.cmd at \Oracle\Middleware\Oracle_Home\user_projects\domains\base_domain\bin


text:
Q: Is there a way to undo `git reset --hard HEAD~1`? I have a project where I am using git. My code has not been pushed to a server. It was on my local machine only.
I want to undo the last commit, so I executed git reset --hard HEAD~1 But that command deleted the files from the project instead of undoing the last commit. How can I undo the git reset --hard HEAD~1 command to my work isn't lost?
When I executed the it reset --hard HEAD~1 I got HEAD is now at 7a524b86f not sure

A: Case 1: If your change made only on client, you cannot come back.
Case 2: If your change made has on server, you didn't push, therefore, you can get back.
Case 3: If your change made on server, you pushed, therefore, you can get back.
Case 4: Your commit has exists on another branches, you can git cherry-pick come back.
Trick: If you use IntelliJ IDEA, WebStorm, PyCharm, you can use feature local history to get back.


text:
Q: R Get collapsed counts - ctable and table don't give me what i'm looking for Using mtcars, I'd like to get a collapsed counting of am, gear, and carb.  The first few rows look like this:
am  gear carb
1   4     4
1   4     4
1   4     1
0   3     1
0   3     2
0   3     1
0   3     4
0   4     2
0   4     2

And i want to get output that looks like this:
am  gear carb   Count
0   3     1      2
0   3     2      1
0   3     4      1
0   4     2      2
1   4     1      1
1   4     4      2

Both table and ctable (summarytools) do some weird thing where it runs all the numbers out and that's not what i want.
Thanks

A: We can use count
library(dplyr)
df1 %>%
      count(am, gear, carb)
# A tibble: 6 x 4
#     am  gear  carb     n
#  <int> <int> <int> <int>
#1     0     3     1     2
#2     0     3     2     1
#3     0     3     4     1
#4     0     4     2     2
#5     1     4     1     1
#6     1     4     4     2

Or
df1 %>%
    group_by_all() %>%
    summarise(Count = n())

data
df1 <- structure(list(am = c(1L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L), gear = c(4L,
4L, 4L, 3L, 3L, 3L, 3L, 4L, 4L), carb = c(4L, 4L, 1L, 1L, 2L,
1L, 4L, 2L, 2L)), class = "data.frame", row.names = c(NA, -9L
))

A: With base R, you can also do this:
as.data.frame(table(df1))

And to filter non-occurring combinations:
freqs <- as.data.frame(table(df1))
freqs[freqs$Freq > 0,]