text:
Q: What kind of syntactic sugar is available in Perl to reduce code for l/rvalue operators vs. if statements? There's a bunch out there, as Perl is a pretty sugary language, but the most used statements in any language is the combination of if statements and setting values.  I think I've found many of them, but there's still a few gaps.  Ultimately, the goal would be to not have to write a variable name more than once:
Here's what I have so far:
$r ||= $s;          # $r = $s unless ($r);
$r //= $s;          # $r = $s unless (defined $r);
$r &&= $s;          # $r = $s if ($r);
$r = $c ? $s : $t;  # if ($c) { $r = $s } else { $r = $t }
$c ? $r : $s = $t;  # if ($c) { $r = $t } else { $s = $t }
$r = $s || $t;      # if ($s) { $r = $s } else { $r = $t }
$r = $s && $t;      # if ($s) { $r = $t } else { $r = $s = undef, 0, untrue, etc. }
$c and return $r;   # return $r if ($c);
$c or  return $r;   # return $r unless ($c);
$c and $r = $s;     # $r = $s if ($c);
@$r{qw(a b c d)}    # ($r->{a}, $r->{b}, $r->{c}, $r->{d})

Somebody also had a really interesting article on a "secret operator", shown here:
my @part = (
    'http://example.net/app',
    ( 'admin'  ) x!! $is_admin_link,
    ( $subsite ) x!! defined $subsite,
    $mode,
    ( $id      ) x!! defined $id,
    ( $submode ) x!! defined $submode,
);

However, what I've found to be missing from the list is:
$r <= $s;                 # read as "$r = min($r, $s);" except with short-circuiting
$r = $s if (defined $s);  # what's the opposite of //?
$r and return $r          # can that be done without repeating $r?

Is there anything else worth adding?  What other conditional set variables are available to reduce the code?  What else is missing?

A: These structures from your question could be written a little bit more clearly using the low precedence and and or keywords:
$c and return $r;    # return $r if ($c);
$c or return $r;     # return $r unless ($c);
$c and $r = $s;      # $r = $s if ($c);

The nice thing about and and or is that unlike the statement modifier control words, and and or can be chained into compound expressions.
Another useful tool for syntactic sugar is using the for/foreach loop as a topicalizer over a single value.  Consider the following:
$var = $new_value if defined $new_value;

vs
defined and $var = $_ for $new_value;

or things like:
$foo = "[$foo]";
$bar = "[$bar]";

$_ = "[$_]" for $foo, $bar;

the map function can also be used in this manner, and has a return value you can use.

A: There's also the left hand side ternary operator:
$cond ? $var1 : $var2 = "the value";

is equivalent to:
if ($cond) {
    $var1 = "the value";
} else {
    $var2 = "the value";
}

A: $r = $r < $s ? $r : $s;:
    $r = $s if $r > $s;

or
    use List::Util qw( min );

    $r = min($r, $s);

or:
    sub min_inplace {
       my $min_ref = \shift;
       for (@_) { $$min_ref = $_ if $$min_ref > $_; }
    }

    min_inplace($r, $s);

$r = $s if (defined $s);:
    $r = $s // $r;

$r = $t; $r = $s if (defined $s);:
    $r = $s // $t;

$r = !$s ? $s : $t;:
    $r = $s && $t;

A: One of the biggest called for features in Perl was the switch statement. This finally appeared in Perl 5.10. I'm just using the example from the documentation:
use feature qw(say switch);  #My preference
#use feature ":5.10";        #This does both "say" and "switch"

[...]

given($foo) {
    when (undef) {
        say '$foo is undefined';
    }
    when ("foo") {
        say '$foo is the string "foo"';
    }
    when ([1,3,5,7,9]) {
        say '$foo is an odd digit';
        continue; # Fall through
    }
    when ($_ < 100) {
        say '$foo is numerically less than 100';
    }
    when (\&complicated_check) {
        say 'a complicated check for $foo is true';
    }
    default {
        die q(I don't know what to do with $foo);
    }
}

Why o' why did they go with given/when and not switch/case like you find in most languages is a mystery to me. And, why if the statement is given/when, do you specify it in use features as switch?
Alas, the people who made these decisions are at a higher plane than I am, so I have no right to even question these luminaries.

I avoid the more exotic stuff, and stick with the easiest to understand syntax. Imagine the person who has to go through your code and find a bug of add a feature, which would be easier for that person to understand:
$r &&= $s;

or
if ($r) {
    $r = $s;
}

And, maybe I might realize that I really meant:
if (not defined $r) {
    $r = $s;
}

And, in this case, I might even say:
$r = $s if not defined $r;

Although I don't usually like post-fixed if statements because people tend to miss the if part when glancing through the code.
Perl is compiled at runtime, and the compiler is fairly efficient. So, even though it's way cooler to write $r &&= $s and it earns it earns you more geek points and is less to type, it doesn't execute any faster. The biggest amount of time spent on code is on maintaining it, so I'd rather skip the fancy stuff and go for readability.
By the way, when I think of syntactic sugar, I think of things added to the language to improve readability. A great example is the -> operator:
${${${$employee_ref}[0]}{phone}}[0];

vs.
$employee_ref->[0]->{phone}->[0];

Of course, if you're storing data as a reference to a list to a hash to a list, you are probably better off using object oriented coding.

A: There's also:
$hash{$key||'foo'} = 1;  # if($key) { $hash{$key} = 1 } else { $hash{'foo'} = 1 }


text:
Q: Create sine wave and sample it in python So, I want to create a 1.95Khz signal, that is simple.
N=1024

signal=[np.sin(2*np.pi*i/512)*20000+30000 for i in np.arange(0,N,1)]
to have at least 2 periods.
How can I simulate that I am reading it back, using a sample frequency of 96Khz. I want 1024 samples.
Also when I send it out, each point is send every 1040ns( Each element of the signal array is send each 1040ns).

A: N = 1024
ix = np.arange(N)
signal = np.sin(2*np.pi*ix/float(N/2))*20000+30000
time = ix/96e3

Then the vector time contains your sampling times, and signal contains your signal at these times.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Count dithered string in vector
PROBLEM STATEMENT
Sometimes when computer programs have a limited number of colors to use, they use a technique called dithering.  Dithering is when you use a pattern made up of different colors such that when the colors are viewed together, they appear like another color.  For example, you can use a checkerboard pattern of black and white pixels to achieve the illusion of gray.
You are writing a program to determine how much of the screen is covered by a certain dithered color.  Given a computer screen where each pixel has a certain color, and a list of all the solid colors that make up the dithered color, return the number of pixels on the screen that are used to make up the dithered color.  Each pixel will be represented by a character in screen.  Each character in screen and in dithered will be an uppercase letter ('A'-'Z') representing a color.
Assume that any pixel which is a color contained in dithered is part of the dithered color.
DEFINITION
Class: ImageDithering
  Method: count
  Parameters: string, vector <string>
  Returns: int
  Method signature: int count(string dithered, vector <string> screen)
CONSTRAINTS

*

*dithered will contain between 2 and 26 upper case letters ('A'-'Z'), inclusive.

*There will be no repeated characters in dithered.

*screen will have between 1 and 50 elements, inclusive.

*Each element of screen will contain between 1 and 50 upper case letters ('A'-'Z'), inclusive.

*All elements of screen will contain the same number of characters.

  EXAMPLES
0)
"BW"
{ "AAAAAAAA",
  "ABWBWBWA",
  "AWBWBWBA",
  "ABWBWBWA",
  "AWBWBWBA",
  "AAAAAAAA"}

Returns: 24
Here, our dithered color could consist of black (B) and white (W) pixels, composing a shade of gray.  In the picture, there is a dithered gray square surrounded by another color (A).
1)
"BW"
{ "BBBBBBBB",
  "BBWBWBWB",
  "BWBWBWBB",
  "BBWBWBWB",
  "BWBWBWBB",
  "BBBBBBBB"}

Returns: 48
Here is the same picture, but with the outer color replaced with black pixels.  Although in reality, the outer pixels do not form a dithered color, your algorithm should still assume they are part of the dithered pattern.
2)
"ACEGIKMOQSUWY"
{ "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWX",
  "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWX",
  "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWX",
  "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWX",
  "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWX",
  "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWX"}

Returns: 150
A picture of vertical stripes, every other stripe is considered part of the dithered color.
3)
"CA"
{"BBBBBBB",
 "BBBBBBB",
 "BBBBBBB"}

Returns: 0
The dithered color is not present.
4)
"DCBA"
{"ACBD"}

Returns: 4
The order of the colors doesn't matter.

I don't understand how to count those dithered string in those vector.
Like the example 0, the line "ABWBWBWA" with have 3 "BW" counting from the left and 2 "BW" counting from the right as well. How should I count it?

A: You don't count instances of the entire string (e.g. "BW"), you count instances of the individual characters (e.g. "B" or "W"). See the spec (my emphasis):

Given a computer screen where each pixel has a certain color, and a list of all the solid colors that make up the dithered color, return the number of pixels on the screen that are used to make up the dithered color. Each pixel will be represented by a character in screen. Each character in screen and in dithered will be an uppercase letter ('A'-'Z') representing a color.
Assume that any pixel which is a color contained in dithered is part of the dithered color.

Example 0 has 24 instances of "B" and "W" characters across the set of screens; example 1 has 48 "B" or "W" characters total; etc. You should be able to deduce this from the examples, as example 2 contains zero instances of the target string "ACEGIKMOQSUWY", but the return value is nonzero.


text:
Q: Difference between JavaScript classes introduced in ECMAScript 2015 and JavaScript's existing prototype-based inheritance? What is the difference between JavaScript classes introduced in ECMAScript 2015 and JavaScript's existing prototype-based inheritance? Why to choose one over other?

A: They function almost exactly the same.
From MDN:

JavaScript classes introduced in ECMAScript 2015 are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax is not introducing a new object-oriented inheritance model to JavaScript.

ES2015 classes are simply an easier way to write JavaScript's traditional prototype-based inheritance.
Some people feel that class isn't a good idea since JS doesn't have classes in the traditional sense. However, there's no denying that class makes your code much shorter when compared to using the traditional prototype method.
One small difference to note: functions are hoisted. classes are not. For example:
let p = new Rectangle(); // ReferenceError

class Rectangle {}


text:
Q: Domain Logic in an Entity Component System Where to put the domain logic in an Entity Component System?
For sure you will not put it onto the Entity (number) itself but you can implement it as method on the Component but also as Method on the System. However, if put on the Component there might be the problem of validating across several Components and on the other hand when applied as System part there is the issue of possible duplication due to having multiple Systems adressing the same set of Entities.
This leads me to the point that there is some kind of domain logic handler required but who is calling it? It must be ensured to be called. Any Architecutral proposals/patterns here?


text:
Q: Question regarding first theorem of isomorphism?
Question  regarding the first theorem of isomorphism ?
$b)\ $$\frac{GL_n(\mathbb{Z}) }{SL_n(\mathbb{Z})} \cong  \ ?$
$d)\ $$\frac{GL_n(\mathbb{R}) }{SL_n(\mathbb{R})} \cong  \ ?$

My  atttempt  :
For option  $d$, the map $f: GL_n(\mathbb{R})\to \{-1,1\}$ given by $f(A) = \mathrm{sign}(\det A)$ is a surjective homomorphism with $\ker f = SL_n(\mathbb{R})$, and so by the first isomorphism theorem, $GL_n({\mathbb{R}})/SL_n(\mathbb{R})\cong \{-1,1\}$.
I don't  know the  other option $ b)$.

A: For part b), you could see $GL_2(\mathbb{Z})=\{X|\det(X)=\pm1\}$. Thus if you take your homomorphism $\varphi:GL_2(\mathbb{Z})\to\{1,-1\}$ as $\varphi(X)=\det(X)$ (you don't really need the sign function here since its determinant is a sign...). Now, by proving $\varphi$ is an isomorphism with a kernel $SL_2(\mathbb{Z})$, you could see that
$$GL_2(\mathbb{Z})/SL_2(\mathbb{Z})\cong\varphi(GL_2(\mathbb{Z}))=\{+1,-1\}$$
For d), you could consider a more general case $GL_n(\mathbb{F})/SL_n(\mathbb{F})$, where $\mathbb{F}$ is an arbitrary field.
Let the homomorphism, $\varphi:GL_n(\mathbb{F})\to\mathbb{F}$, be $\varphi(X)=\det(X)$ in which you replace all operations in $\mathbb{R}$ with corresponding operations in $\mathbb{F}$. You could see that $\varphi$ has a kernel $SL_n(\mathbb{F})$ since $\forall X\in SL_n(\mathbb{F})$, $\det(X)=1_F$ according to the definition of special linear groups.
Now by the first isomorphism theorem, it follows that
$$GL_n(\mathbb{F})/\ker\varphi\cong\varphi(GL_n(\mathbb{F}))$$
Because $\varphi(X)$ can take any value except $0$, we could see $\varphi(\mathbb{F})=\mathbb{F}^\times$ which means
$$GL_n(\mathbb{F})/SL_n(\mathbb{F})\cong\mathbb{F}^{\times}$$
or in part d)
$$GL_2(\mathbb{R})/SL_n(\mathbb{R})\cong\mathbb{R}\backslash\{0\}$$
Note that $\mathbb{Z}^\times=\{+1,-1\}$, though maybe this notation is not valid since $\mathbb{Z}$ is not a field.


text:
Q: Upload image to Database from Swift through Php I'm trying to upload an image to my localhost Sever and saving the path to a database. I already have some other code, where I upload a new Object. Is it possible to upload the image in the same function as shown below. I have not found any good tutorials on how to do this with other uploads in the same function (in the same sql request). The Spot object has an element image, which is the UIImage, that has to be uploaded.
The Swift code:
if let url = URL(string: "http://localhost:8080/add.php") {
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.timeoutInterval = 20.0
    var dataString = "secretWord=235ghzjg35" // starting POST string with a secretWord

    dataString = dataString + "&name=\(spot.name!)"
    dataString = dataString + "&lat=\(spot.lat!)"
    dataString = dataString + "&long=\(spot.long!)"

    let dataD = dataString.data(using: .utf8)

    do{
        let uploadJob = URLSession.shared.uploadTask(with: request, from: dataD) { data, response, error in
            if error != nil {
                DispatchQueue.main.async {
                    print("No connection")
                }
            }
            else {
                if let unwrappedData = data {
                    let returnedData = NSString(data: unwrappedData, encoding: String.Encoding.utf8.rawValue)
                    if returnedData == "1"{
                        DispatchQueue.main.async {
                            print("Upload completed")
                        }
                    }
                    else {
                        DispatchQueue.main.async {
                            print(returnedData ?? "no data back'")
                        }
                    }
                }
            }
        }
        uploadJob.resume()
    }
}

The Php code:
<?php
$secret = $_POST["secretWord"];
if ("235ghzjg35" != $secret) exit;

$name = $_POST["name"];
$lat = $_POST["lat"];
$long = $_POST["long"];

//$img0 = $_FILES['img0'];
//$target0 = "spotImages/" . $name;
//$target0 = $target0 . basename($img0);

// Create connection
$con=mysqli_connect("localhost", "user", "pass", "db");

// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

//then adding here the image
$sql = "INSERT INTO `table` (`id`, `name`,  `long`, `lat`) VALUES (NULL, '". $name ."', '". $long ."', '". $lat  ."');";

$result = mysqli_query($con, $sql);
echo $result;
mysqli_close($con);?>

Furthermore I wanted to know if there are any better solutions on how to manage a Database with Swift for my App. I have read some things about Firebase and Realm.io. Has anyone had any experiences? And if so, what are the pros and cons? Should I consider using that instead of my approach?

A: A couple of observations:

*

*The code in your question is building a application/x-www-form-urlencoded request. To upload an image, you generally would not use this type of request. The problem is that you can't include binary image data in it. You could, theoretically, base64-encode the image data when building the request and base64-decode it on the server, but that's going to make the request 33% bigger and adds unnecessary work on both client and server side.

*Also, if you use application/x-www-form-urlencoded, you have to percent-escape your values you send to your server (e.g., if your "name" had spaces or other reserved characters in it, the request would be malformed if not percent-escaped). See HTTP Request in Swift with POST method.

*All that having been said, when sending images, you'd generally use multipart/form-data as outlined in Upload image with parameters in Swift, eliminating the above concerns. You can send the image and these fields in a single request.
While I've tried to show how one would build multipart/form-data requests in that other answer, you might consider using libraries like Alamofire get you out of the weeds of building these complicated requests.

*When parsing the multipart/form-data request in PHP, you'd use $_FILES as outlined in Handling File Uploads.

*You should never just take the fields from a request and build a SQL statement from them. At worst, it leaves you susceptible to SQL injection attacks. At best, it will just fail if a user sends a string that, for example, contains the SQL string delimiter character.
You should either bind the values to ? placeholders in your SQL using mysqli_stmt::bind_param or, if building the SQL manually, make sure to use mysqli::real_escape_string before inserting them into your SQL statement.

*You asked:

Furthermore I wanted to know if there are any better solutions on how to manage a Database with Swift for my App. I have read some things about Firebase and Realm.io. Has anyone had any experiences? And if so, what are the pros and cons? Should I consider using that instead of my approach?

This is probably too broad of a question to reasonably answer here, but in short, sure, if you want to get out of the world of writing your own server code, then, yes, you should consider those solutions. These get you out of the weeds of backend development. Re Firebase vs Realm.io, that's a matter of opinion and, as such, is considered off topic for Stack Overflow. But both are mature solutions which, as your app scales, involve some costs.
For what it's worth, if you decide you want to write your own PHP code, I might advise considering a PHP framework, such as Laravel. It offers scaffolding for authentication, abstraction away from SQL statements, etc.


text:
Q: jQuery clone div with replaced values I am trying to clone a div that looks like this:

        <input type="text" name="step_name_1" id="step_name_1">

A simple clone works but I have no idea about how can I clone it and replace "_1" with "_2".
Here is what I've tried but it doesn't work:
var newStep = $( "#step_1" );
newStep = text.replace("_1", "_2");
newStep.prependTo( "#multipleSteps" );

A: Using this code your id step "step_1" counter is set dynamicaly.

var newStep = $( "#step_1" ).prop('outerHTML');
count = $('#multipleSteps').length;
newStep = newStep.replace("_1", "_"+(count+1));
$(newStep).appendTo("#multipleSteps");

        <input type="text" name="step_name_1" id="step_name_1">

A: first you need to get the html of step_1 as a text then replace "_1" by "_2" and then append the new html to multipleSteps div :
var html = $("#step_1").prop('outerHTML').replace(/_1/g, '_2')
var newStep = $(html);
newStep.appendTo("#multipleSteps");

prop('outerHTML') is used to get the html of an element including it self
replace(/_1/g, '_2') is used to replace all "_1"
https://jsfiddle.net/ao92wrtz/


text:
Q: Botmaster with socket.io and watson-conversation-ware I'm developing a chatbot using masterbot, socket.io, watson-conversation. The problem is that I wasn't able to understand what I need to do to recive the watson welcome message before I begin to send messages. Now I just recive messages after send some text, what I need is recive the first message before send any messager. Is it possible to have it using botmaster?

const SessionWare = require('botmaster-session-ware');
const WatsonConversationWare = require('botmaster-watson-conversation-ware');
const express = require('express');
const port = process.env.PORT || 3000;
const app = express();

// Rota para index.html
app.use(express.static(__dirname + '/public'));

const server = app.listen(port, '0.0.0.0', () => {
    console.log('Server listening at port %d', port);
});

const Botmaster = require('botmaster');
const SocketioBot = require('botmaster-socket.io');

const botmaster = new Botmaster({
  server,
});

const socketioSettings = {
  id: 'SOME_BOT_ID_OF_YOUR_CHOOSING',
  server,
};

const socketioBot = new SocketioBot(socketioSettings);
botmaster.addBot(socketioBot);

const watsonConversationWareOptions = {
  settings: {
    username: ,
    password: ,
    url: 'https://gateway.watsonplatform.net/conversation/api/',
    version: 'v1',
    version_date: '2018-02-16'
  },
  workspaceId:
}

// declaring middleware
const watsonConversationWare = WatsonConversationWare(watsonConversationWareOptions);
botmaster.use(watsonConversationWare);

botmaster.use({
  type: 'incoming',
  name: 'watson-middleware',
  controller: (bot, update) => {
    return bot.sendTextCascadeTo(update.watsonUpdate.output.text, update.sender.id);
  }
});

// This will make our context persist throughout different messages from the
// same user
const sessionWare = new SessionWare();
botmaster.useWrapped(sessionWare.incoming, sessionWare.outgoing);

botmaster.on('error', (bot, err) => {
  console.log(err.stack);
});

var socket = io('?botmasterUserId=wantedUserId');

var form = document.getElementById('form');
var textInput = document.getElementById('text-input');
var messages = document.getElementById('messages');

form.onsubmit = function(event) {
  event.preventDefault();
  if (!textInput.value) {
    return;
  }
  messages.insertAdjacentHTML('beforeend',
    `<li class="user-message">${textInput.value}</li>`);

  const update = {
    message: {
      text: textInput.value
    }
  };
  socket.send(update);
  textInput.value = '';
};

socket.on('message', function(botmasterMessage){
  var textMessage = botmasterMessage.message.text;

  messages.insertAdjacentHTML('beforeend',
    `<li class="botmaster-message">${textMessage}</li>`);
});

A: as you can see you need to send an empty message to receive the Welcome message.
POST Example with a empty message:

Response:

Obs.: My server expects one JSON like my example, this config will depend of your code in your back-end side, like your example will be the inputValue.value inside the message object, try to use inputValue.value || "".

*

*See more about the method send Message with Watson Conversation here.


text:
Q: IntlDateFormatter php japanese year convertion return false for 2019 I want to convert
令和元年8月 = 2019年8月

Ref https://www.conservapedia.com/Japanese_dates
Here I get these

For this I tried code like below here "平成31年8月" returning 2019 but according to ref it should 令和元年8月
Please suggest me is there any solution so I can set my code like reference..
$formatter = new IntlDateFormatter(
    'ja_JP@calendar=japanese',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'Europe/Madrid',
    IntlDateFormatter::TRADITIONAL,
    'Gy年M月'
);
$ts = $formatter->parse('令和元年8月');
//$ts = $formatter->parse('平成31年8月');
var_dump($ts, date('Y-m', $ts));

___FIDDLE___

A: There seem to be two issues.

*

*Japanese era system does not switch by year, but by a date in a year

平成(Heisei) ended at 2019-04-30, 令和(Reiwa) began at 2019-05-01, so the year-to-year table you referred is not complete if you need to convert specific date in a switching year such like 2019.
For example, both January 平成31 and December 令和1 are AD 2019. So when you only convert year part, they would show the same result.

*PHP does not always have up-to-date table inside

On my local, "$formatter->parse('令和元年8月');" returned me 1970-01, the Unix epoch time probably coming from null value. This happens because my using PHP yet does not know that Japanese era changed to 令和.
IntlDateFormatter is in pecl php_intl extension, which calls ICU library. ICU library supports the new era name 令和 at its verion 64.2.
You may check your phpinfo() with "ICU version" and if that is smaller than 64.2, it won't convert 令和 properly.
$ php --info | grep "ICU version"
ICU version => 61.1

If you can not find 64.2+ on your latest available PHP, you may have to compile intl extension with later ICU library yourself.


text:
Q: USB devices missing from /proc/acpi/wakeup I'm currently running Ubuntu 14.04 (specifically the Kodibuntu port) on a Gibabyte NUC like mini pc. My kernel version is 3.13.0-55-generic.
I'm having trouble enabling wake-up from suspend via my usb remote keyboard. I have no USB entries in /proc/acpi/wakeup.
This is my current configuration:
root@romulus:~# lsusb
Bus 002 Device 002: ID 1058:1078 Western Digital Technologies, Inc.
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 004: ID 400c:107a
Bus 001 Device 003: ID 13d3:3410 IMC Networks
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

My keyboard is the 400c:107a device running un bus 1 device 4.
root@romulus:~# cat /sys/bus/usb/devices/usb1/1-4/power/wakeup
enabled

Yet, even after trying to add USB1 to acpi wakeup i still can't see the USB devices in /proc/acpi/wakeup:
root@romulus:~# echo USB0 > /proc/acpi/wakeup
root@romulus:~# cat /proc/acpi/wakeup
Device  S-state   Status   Sysfs node
XHC1      S4    *enabled   pci:0000:00:14.0
PXSX      S4    *disabled
PXSX      S4    *disabled  pci:0000:02:00.0
PXSX      S4    *enabled   pci:0000:03:00.0
PXSX      S4    *disabled
PWRB      S0    *enabled
root@romulus:~#

Can someone explain me why there are no USB devices here? I've searched the interwebs for answers but most people solve the problem after echoing the usb device to /proc/acpi/wakeup of ater setting the power/wakeup file to enabled for the specific device.
Thanks in advance for you help!


text:
Q: How can I get help with Stack Overflow addiction?
My Stack Overflow addiction is beginning to hurt productivity.
Have you ever found yourself in this situation regarding some site?
Any advice on how to deal with the problem?

A: If you want you can flag one of your posts and ask a moderator to be banned for a period of time you specify; maybe this will help.

A: I wish I could say more, but all I really have is that I've trained myself to always care about what I'm getting out of activities, so sooner or later, I end up realizing "Wait... this is a pointless grind" and losing interest... it's already happened with TV, video games, and most reading.
I'm currently evaluating whether my "10 points per day, minimum" goal on SO main is worth the time spent finding questions I can answer.


text:
Q: Mask some part of devices in schematic I have a question about working with Altium Designer Software. I put some devices in schematic, but I do not want all of them importing to PCB. I mean I want to mask some part of schematic in such way that software does not import those parts into PCB. Would you please tell me how to do it?
Thanks in advance

A: Right-click on the component and select properties. Set the characteristic you want in the drop-down box on the dialog:

Mechanical parts will not show up on the PCB but will be included in the BOM.

A: Double click the part in the schematic (or select multiple parts and use the inspector). Change the "Type" of the part to Graphical (or to Mechanical if you want it on the BOM even though it doesn't have a footprint on the PCB).
For more info on the options available, see here.


text:
Q: selecting max value from each row I have to compare three COLUMNS for each row and get the MAX data from these columns. My sample data is:
create table sept18 ( t1 number, t2 number, t3 number );

insert all
  into sept18 values (1,2,3)
  into sept18 values (-1,-2,3)
  into sept18 values (1,null,13)
  into sept18 values (-1,-2,-3)
  into sept18 values (-1,0,0)
select * from dual;

My operation should show the three columns and a field with the maximum value from each row. For instance,  for the first and second rows it is 3, for the third it is 13, -1 for the fourth and 0 for the fifth.
How can I achieve this? Do I have to use partition?

A: No, you don't have to use an analytic query (I assume that's what you mean by partition?). An analytic function is used to compute an aggregate amount, of some description. You're not looking to aggregate anything across a column; you want to find the maximum in a row.
For this you need to use the greatest() function, the opposite of least().
select a.*, greatest(t1, t2, t3)
  from sept18 a

Be warned; both of these functions will return null if a single column is null. How you deal with this is your decision. My normal tactic is to use nvl() with a completely ridiculous value. This can be dangerous, as the "ridiculous" value you choose might become correct so ensure you understand your data.
select a.*, greatest(nvl(t1,-9999), nvl(t2, -9999), nvl(t3, -9999))
  from sept18 a

Here's a little SQL Fiddle to demonstrate both queries.
If all columns are null then you can descend even further into ridiculousness. Either you have to nullif() the greatest(), or, more simply, just use WHERE to exclude rows where all columns are null.
One little extra point. The existence of a table sept18 seems a little suspicious. If you actually have one table per day then you should consider normalising your database and creating, for instance, a temporal table, which has a created_date column.


text:
Q: Serving express static files issue I am having issues w/ serving static files in my current Express app, although I've done a similar setup in a bunch of other apps.. My folder structure is as follows:
/rootfolder/
    /app
        package.json
        /client
            /dist
                /static
                index.html

        /server
            /src
                index.js

Relevant part of my server/src/index.js:
app.use(express.static(path.join(__dirname, "client", "dist")));
Where __dirname = /rootfolder/app/server/src
And when the user hits the / endpoint:
app.get("/", (req, res) => {
  res.sendFile(appRoot.path + "/client/dist/index.html");
});

Where appRoot.path = /rootfolder/app
When I hit the / endpoint, I get a status 200 with the following text:
/rootfolder/app/client/dist/index.html
From what I can tell, the files are coded relative to each other correctly.. Does anyone know what I might be doing wrong?
Thanks in advance!

A: Try
app.use(express.static(path.join(__dirname,'client','dist')));

It basically gets the root directory and combines it with /client+ /dist + /static to give you the full route, without being relative path.
Now Let's call rootdirectory/client/dist X. That is the main directory for static files
If you have other files that are static but not in the same folder, you will have to give relative path from the X directory
Example:
app.get('/',function(req,res){
res.sendFile('/static/data.txt');
}

In the example above you indicate that the static file(data.txt) is located in the X/static directory.
Therefore => rootDirectory/client/dist/static/data.txt
2nd Example:
Let's say you have a folder in dist called images which you want to only store images.
when you are giving routes, you MUST use /images/filename.extention

A: You're using res.send() instead of res.sendFile()
Also I suggest resolving your path via the path module, instead of concatenating a string.
const path = require('path')

app.use(express.static(path.join(__dirname, 'client', 'dist', 'static')))

And for the response of /:
res.sendFile(path.join(__dirname, 'client', 'dist', 'index.html')))


text:
Q: Is there a Python ORM framework for interacting with data via XML-RPC? I am working on a webapp that interacts with data via XML-RPC rather than with a direct connection to a database.  I can execute SQL queries via an XML-RPC methods.
I would like to interact with the data in an ORM framework fashion that has lazy/eager fetching, etc., although I can't seem to figure out how that would be possible with Python or even Django's libraries.

A: You would have to write your own database backend. Take a look at existing backends for how to do this.

A: Check out XML Models.  It's REST rather than XML-RPC, but much of it is probably reusable.


text:
Q: How to modify Androidx Preference data outside of PreferenceFragment? I am trying to implement a custom Radio-style Preference where the user can click an option which is then assigned as the new value of the Preference:

Here is my layout:
preferences.xml
<Preference
    android:layout="@layout/preference_gender"
    android:key="seeking"
    android:title="Seeking"/>

preference_gender.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout>

<RadioGroup
    android:id="@+id/gender_group"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.appcompat.widget.AppCompatTextView
        ...
        android:text="@string/seeking"/>

    <androidx.appcompat.widget.AppCompatRadioButton
        android:id="@+id/male"
        android:text="Male"
        />

    <androidx.appcompat.widget.AppCompatRadioButton
        android:id="@+id/female"
        android:text="Female"
        />

    <androidx.appcompat.widget.AppCompatRadioButton
        android:id="@+id/both"
        android:text="Both"
        />

</RadioGroup>

</androidx.constraintlayout.widget.ConstraintLayout>

Because Preference.OnPreferenceClickListener can't detect specific clicks inside the Preference (only the preference as a whole), I've resorted to adding an onClick() function in the xml which is then passed to my activity:
then to my preferences fragment:
class PreferencesFragment : PreferenceFragmentCompat(), View.OnClickListener, RadioGroup.OnCheckedChangeListener {

    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        setPreferencesFromResource(R.xml.preferences, rootKey)
    }

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    gender_group.setOnCheckedChangeListener(this) // null pointer exception
}

}

however I get a NullPointerException on my findPreference("seeking")!!.
Is there any way around this?

A: preference_gender.xml has no Preference keys at all. A styled RadioGroup & 3 RadioButton might rather be suitable to represent those buttons below a single Preference key; nodes alike that AppCompatTextView might be rendered - but won't be treated alike a Preference would be.


text:
Q: How to ensure computer is power on always? I would like to have my computer to turn on in all cases wall socket electricity is on. I know there is a BIOS setting for it,

but I am not sure I can rely on this: battery can discharge or induction can happen so that BIOS set to factory default.
Can I configure it in hardware, may be some jumpers or short circuit power on switch?

I want to do the same as can be done with BIOS on screenshot, but without relying on BIOS.


text:
Q: How to create this specific map in my areas I used following code for creating the specific map. Unfortunately i couldn't make the required map since many attempts. Therefore, i am asking to help me to create this map.  The required map is attached here  and the following code gives the map is here . which changings are required to make required map. please, noted that i dont have error in attached code i want modification in code that give me required map.
library(tidyverse)
 library(raster)

#obtain map from GADM.org
pak <- getData('GADM', country='Pakistan', level=1)

map <- ggplot(pak) + geom_sf()

#Object for ggplot
#Need a name for joins
pak$name = pak$NAME_1
pak_ggplot <- map_data(pak)
#map_data transform name in region

#I create a random variable for color in map
zone <- data.frame(region = unique(pak$NAME_1))
zone$other_name = runif(nrow(zone),1,10)

#Join ggplot object with variable for color
pak_ggplot <- left_join(pak_ggplot, zone)

dist <- c('Astore','Bunji','Gupis','Chilas','Gilgit','Skardu')
lat <- c(35.357,35.6431,36.2274,35.4222,35.8819,35.3247)
long <- c(74.8624,74.6342,73.4421,74.0946,74.4643,75.551)

points <- cbind.data.frame(dist,lat,long)

mapa <- ggplot(data = pak_ggplot, aes(x = long, y = lat, group = group)) +
  geom_polygon(aes(fill = other_name)) +
  scale_fill_continuous(low="white",high="red")  +
  labs(title = "Pakistan Map")

mapa + geom_point(data=points,aes(x=long, y=lat, group=1)) +
  geom_text(data=points, aes(x=long, y=lat,label=dist, group=1), size=2)

pak2 <- pak_ggplot %>% filter(region=='Northern Areas')

mapa2 <- ggplot(data = pak2, aes(x = long, y = lat, group = 1)) +
  geom_polygon() +
  scale_fill_continuous(low="white",high="red")  +
  labs(title = "Pakistan Map")

mapa2 + geom_point(data=points,aes(x=long, y=lat, group=1)) +
  geom_text(data=points, aes(x=long, y=lat,label=dist, group=1), size=2)


text:
Q: xscreensaver sometimes unlocks locked screen automatically, after returning from monitor standby mode I am using xscreensaver to lock my screen. Additionally to that, my monitor goes to "standby" , i.e turn display off, after 30 minutes of inactivity.
It has happened to me twice now, that I have locked my screen, using  xscreensaver-command --lock and when I came back after few hours and moved my mouse, the monitor came back from standby but instead of the expected xscreensaver login window, I was dropped directly into my desktop session - without having to authenticate.
I don't know whether there is any correlation with the power management feature, but it did not happen to me before when I was not using automatic monitor suspend.
Also, I don't have any .Xauthority file in my home, but again not sure whether that is relevant.
I am using Debian Wheezy and LXDE
Can somebody please suggest how to investigate this problem ?
$ xdpyinfo
name of display:    :0.0
version number:    11.0
vendor string:    The X.Org Foundation
vendor release number:    11204000
X.Org version: 1.12.4
maximum request size:  16777212 bytes
motion buffer size:  256
bitmap unit, bit order, padding:    32, LSBFirst, 32
image byte order:    LSBFirst
number of supported pixmap formats:    7
supported pixmap formats:
    depth 1, bits_per_pixel 1, scanline_pad 32
    depth 4, bits_per_pixel 8, scanline_pad 32
    depth 8, bits_per_pixel 8, scanline_pad 32
    depth 15, bits_per_pixel 16, scanline_pad 32
    depth 16, bits_per_pixel 16, scanline_pad 32
    depth 24, bits_per_pixel 32, scanline_pad 32
    depth 32, bits_per_pixel 32, scanline_pad 32
keycode range:    minimum 8, maximum 255
focus:  window 0x1e00004, revert to Parent
number of extensions:    26
    BIG-REQUESTS
    Composite
    DAMAGE
    DOUBLE-BUFFER
    DPMS
    DRI2
    Generic Event Extension
    MIT-SCREEN-SAVER
    MIT-SHM
    RANDR
    RECORD
    RENDER
    SECURITY
    SHAPE
    SYNC
    X-Resource
    XC-MISC
    XFIXES
    XFree86-DGA
    XFree86-VidModeExtension
    XINERAMA
    XInputExtension
    XKEYBOARD
    XTEST
    XVideo
    XVideo-MotionCompensation
default screen number:    0
number of screens:    1

screen #0:
  dimensions:    1920x1080 pixels (508x285 millimeters)
  resolution:    96x96 dots per inch
  depths (7):    24, 1, 4, 8, 15, 16, 32
  root window id:    0x6f
  depth of root window:    24 planes
  number of colormaps:    minimum 1, maximum 1
  default colormap:    0x20
  default number of colormap cells:    256
  preallocated pixels:    black 0, white 16777215
  options:    backing-store NO, save-unders NO
  largest cursor:    64x64
  current input event mask:    0x7a003c
    ButtonPressMask          ButtonReleaseMask        EnterWindowMask
    LeaveWindowMask          StructureNotifyMask      SubstructureNotifyMask
    SubstructureRedirectMask FocusChangeMask          PropertyChangeMask
  number of visuals:    3
  default visual id:  0x21
  visual:
    visual id:    0x21
    class:    TrueColor
    depth:    24 planes
    available colormap entries:    256 per subfield
    red, green, blue masks:    0xff0000, 0xff00, 0xff
    significant bits in color specification:    8 bits
  visual:
    visual id:    0x22
    class:    DirectColor
    depth:    24 planes
    available colormap entries:    256 per subfield
    red, green, blue masks:    0xff0000, 0xff00, 0xff
    significant bits in color specification:    8 bits
  visual:
    visual id:    0x6d
    class:    TrueColor
    depth:    32 planes
    available colormap entries:    256 per subfield
    red, green, blue masks:    0xff0000, 0xff00, 0xff
    significant bits in color specification:    8 bits

A: I would definitely say this sounds like a bug. My suggestion, if you're going to use xscreensaver allow it to handle power management. At the command line type xscreensaver-demo, and in the GUI go to the Advanced tab and make sure 'Power Management Enabled' is checked (also tweak the settings how you'd like them to be).
As well, start xscreensaver from the command-line with xscreensaver -log ~/xscreensaver.log and see what the log says when this happens.


text:
Q: Nondegenerate 2-forms exist on even-dimensional manifolds Let $M$ be a smooth manifold. Recall that a 2-form $\omega$ on $M$ is called nondegenerate if for each $p\in M$ and $v\in T_pM-\{0\}$, there exists a $w\in T_pM$ with $\omega(v,w)\neq 0$. By linear algebra it can be seen that existence of a nondegenerate form implies that $
\dim M=n$ is even. Is it true that the following converse holds?: if $M$ is even-dimensional then there is a nondegenerate $2$-form on $M$.
First I thought that this can be shown by an elementary partition-of-unity argument, but I realized that sum of nondegenerate forms need not be nondegenerate..

A: The comment proves only that there exist manifolds without closed nondegenerate 2-forms. Dropping the closed condition results in a structure called an "almost symplectic structure".
Not every manifold admits an almost symplectic structure. In fact, if you admit an almost symplectic structure you (non-obviously) also admit an almost complex structure, and vice versa. It is a well-known result (of Bott? please forgive my historical ignorance) that the only spheres admitting an almost complex structure are $S^2$ and $S^6$, so $S^4$ gives a counterexample to your question.
In fact you can read in the book of Gompf and Stipsicz a complete characterization of which simply connected closed 4-manifolds admit almost complex structures. $\Bbb{CP}^2 \# \Bbb{CP}^2$, for instance, does not.


text:
Q: Solving the Numberlink puzzle with prolog I have an assignment that seems out of scope of my class (I say this because they barely taught us anything about prolog), I have to write a prolog program to solve the game "Flow Free" on android. In the assignment it is called Numberlink. I could solve this in C++ in a hour but because I'm not too familiar with prolog it is giving me trouble. Here's what I would like to do:

*

*Make a list that holds a boolean to indicate whether it has been visited or used.

*Recursively search all possible paths from a given starting point to
the end point using a breadth first search to find the shortest
paths.

*Go from there I guess.

My attempt included searching the web on how to make a list. Of course prolog is not documented well at all anywhere so I came up blank and gave up. A friend told me to use maplist which I don't understand how I would use it to make a list including what I need.
Thanks in advance.
EDIT:
Thanks for the link, but I was looking to make a 2D list to represent the board being played on. Function would look like this:
makeList(size, list):-
Where size is an integer representing the size of one dimension in the square list ex. (7x7).

A: Here's an implementation of @CapelliC's solution. The code is self-explanatory. 2 blocks are connected if they are adjacent and have the same color, or adjacent to another connected block of the same color. (I used X and Y instead of row and column, it made writing the conditions at the end a little confusing.)
Solving in SWI-Prolog

https://flowfreesolutions.com/solution/?game=flow&pack=green&set=5&level=1
connected(P1, P2, M, Visited) :-
    adjacent(P1, P2),
    maplist(dif(P2), Visited),
    color(P1, C, M),
    color(P2, C, M).
connected(P1, P2, M, Visited) :-
    adjacent(P1, P3),
    maplist(dif(P3), Visited),
    color(P1, C, M),
    color(P3, C, M),
    connected(P3, P2, M, [P3|Visited]).

adjacent(p(X,Y1), p(X,Y2)) :- Y2 is Y1+1.
adjacent(p(X,Y1), p(X,Y2)) :- Y2 is Y1-1.
adjacent(p(X1,Y), p(X2,Y)) :- X2 is X1+1.
adjacent(p(X1,Y), p(X2,Y)) :- X2 is X1-1.

color(p(X,Y), C, M) :-
    nth1(Y, M, R),
    nth1(X, R, C).

sol(M) :-
    M = [[1,_,_,_,1],
         [2,_,_,_,_],
         [3,4,_,4,_],
         [_,_,_,_,_],
         [3,2,5,_,5]],
    connected(p(1,1), p(5,1), M, [p(1,1)]),
    connected(p(1,2), p(2,5), M, [p(1,2)]),
    connected(p(1,3), p(1,5), M, [p(1,3)]),
    connected(p(2,3), p(4,3), M, [p(2,3)]),
    connected(p(3,5), p(5,5), M, [p(3,5)]).

Sample query:
?- sol(M).
M = [[1, 1, 1, 1, 1],
     [2, 2, 2, 2, 2],
     [3, 4, 4, 4, 2],
     [3, 2, 2, 2, 2],
     [3, 2, 5, 5, 5]].

A: The declarative Prolog 'modus operandi' is based on non determinism,  implemented by depth first search. Let's apply to this puzzle: M is the playground, a list of lists of free cells (variables) or integers (colors)
one_step(M) :-
  cell(M, X,Y, C),
  integer(C), % the selected cell is a color
  delta(X,Y,X1,Y1),
  cell(M, X1,Y1, C). % bind adjacent to same color - must be free

cell(M, X,Y, C) :- nth1(Y,M,R), nth1(X,R,C).

% moves
delta(X,Y,X1,Y) :- X1 is X+1. % right
delta(X,Y,X1,Y) :- X1 is X-1. % left
delta(X,Y,X,Y1) :- Y1 is Y-1. % up
delta(X,Y,X,Y1) :- Y1 is Y+1. % down

what this does ? let's try on a 3x3 playground
?- M=[[_,9,_],[_,0,_],[_,_,9]],one_step(M).
M = [[_G1824, 9, 9], [_G1836, 0, _G1842], [_G1848, _G1851, 9]] ;
M = [[9, 9, _G1830], [_G1836, 0, _G1842], [_G1848, _G1851, 9]] ;
M = [[_G1824, 9, _G1830], [_G1836, 0, 0], [_G1848, _G1851, 9]] ;
M = [[_G1824, 9, _G1830], [0, 0, _G1842], [_G1848, _G1851, 9]] ;
M = [[_G1824, 9, _G1830], [_G1836, 0, _G1842], [_G1848, 0, 9]] ;
M = [[_G1824, 9, _G1830], [_G1836, 0, _G1842], [_G1848, 9, 9]] ;
M = [[_G1824, 9, _G1830], [_G1836, 0, 9], [_G1848, _G1851, 9]] ;
false.

No need to declare grid size, check index boundaries, etc... when one_step/1 succeeds it has instantiated a free cell to an adjacent same color...


text:
Q: Where can I get cookies of Chrome web browser in Ubuntu 14.04? I am using Ubuntu 14.04 and want to know the location of cookies of the Chrome web browser. Does anyone know the directory of Chrome web browser cookies?

A: The directory is here:
~/.config/google-chrome/Default

For chromium users, the file is here instead:
~/.config/chromium/Default

The actual file is:
~/.config/google-chrome/Default/Cookies

A: Settings > Search for "cookies" > Content Settings > All cookies and site data
Here you can clear your cookies or see their values.

A: In newer versions (at least since 16.04) you have access through the Inspect Element. You can use the right mouse button to open the console or use F12.
Go to the Network tab. There you should see a Cookies option. It will show you the list of cookies sent/returned for that very specific request. In most cases, you are interested in the cookies of the GET used to load the HTML page. The other entries may be for other websites (google for fonts, for example) and they probably don't have the cookies you're interested in.

A: On Ubuntu 19.10+, Chromium now uses snap instead of coming from a deb. The new location is
~/snap/chromium/common/chromium/Default


text:
Q: A function returns another function in php I dont know whether the question (the way I asked) is correct or not. I'm open for your suggestion. I want to know how exactly the following code works. If you want any details I can provide as much I want.
public function processAPI() {
    if (method_exists($this, $this->endpoint)) {
        return $this->_response($this->{$this->endpoint}($this->args));
    }
    return $this->_response("No Endpoint: $this->endpoint", 404);
}

private function _response($data, $status = 200) {
    header("HTTP/1.1 " . $status . " " . $this->_requestStatus($status));
    return json_encode($data);
}
private function _requestStatus($code) {
    $status = array(
        200 => 'OK',
        404 => 'Not Found',
        405 => 'Method Not Allowed',
        500 => 'Internal Server Error',
    );
    return ($status[$code])?$status[$code]:$status[500];
}
/**
 * Example of an Endpoint
 */
 protected function myMethod() {
    if ($this->method == 'GET') {
        return "Your name is " . $this->User->name;
    } else {
        return "Only accepts GET requests";
    }
 }

Here $this->endpoint is 'myMethod' (a method I want to execute)
I pass the method which I want to execute in the url. The function catches the request process then call the exact method. I want to how it's works. Especially this line.
return $this->_response($this->{$this->endpoint}($this->args));

A: PHP Supports both variable functions and variable variables.
When it reaches you statement within processApi
return $this->_response($this->{$this->endpoint}($this->args));

PHP will resolve your endpoint variable, we'll replace it with myMethod which is in your example:
return $this->_response($this->myMethod($this->args));

As you can see, we're now calling a method which exists on your class. If you set the endpoint to something which didn't exist, it would throw an error.
If myMethod returns a string such as my name is bob then once $this->myMethod($this->args) executes PHP will resolve that value as the argument for $this->_response() resulting in:
return $this->_response('my name is bob');

Following that chain of events, the processAPI() method will finally return that string JSON encoded as that's what the _response method does.


text:
Q: How can I produce 3 centered columns, with the middle one fitting the width of its content? How can I produce a document similar to this, but cause the middle column to take up only as much space as it needs (rather than explicitly specifying a width), such that as much space as possible is available to the left and right columns?
\documentclass{article}

\begin{document}
\noindent
\fbox{\parbox{0.333\textwidth}{\centering Left content centered \\ between margin and title }}
\fbox{\parbox{0.333\textwidth}{\centering \Huge Title }}
\fbox{\parbox{0.333\textwidth}{\centering Right content \\ also centered }}

\end{document}

A: You can calculate the width for the contents and store it in an auxiliary length; then you can calculate the other two widths using this value (you need to take into account also \fboxsep and \fboxrule):
\documentclass{article}

\newlength\mylen
\newcommand\MyCont{\Huge Title}
\settowidth\mylen{\MyCont}

\begin{document}
\noindent
\fbox{\parbox{\dimexpr0.5\textwidth-0.5\mylen-3\fboxsep-3\fboxrule\relax}{\centering Left content centered \\ between margin and title }}%
\fbox{\parbox{\mylen}{\centering\MyCont}}%
\fbox{\parbox{\dimexpr0.5\textwidth-0.5\mylen-3\fboxsep-3\fboxrule\relax}{\centering Right content \\ also centered }}

\end{document}

Of course, if you are inetrested in producing tabular material, the best approach would be to use the tabularx package (as in zeroth's answer), or the tabu package. A little example with the latter:
\documentclass{article}
\usepackage{tabu}

\begin{document}
\noindent
\begin{tabu}{|X[c]|c|X[c]|}
Left content centered between margin and title &  \Huge Title &
    Right content  also centered
\end{tabu}
\end{document}

A: The package you can use for this is the tabularx. This lets you specify a tabular environment which needs a width argument. Furthermore a new column specifier, X, is introduced.
This new column type will take up the rest of the space available and divide that space amongst the X columns.
In your case this amounts to:
% \usepackage{tabularx}
\begin{tabularx}{\textwidth}{|>{\centering}X|c|>{\centering\arraybackslash}X|}
  o & o & o
  \\
  o & o & o
\end{tabularx}

The \arraybackslash is a work around for the \cr which is not correctly interpreted. See the manual for more information.
This will yield:


text:
Q: SQL Query Help - Select non null values for each ID (multiple rows) I have a table in BigQuery where each ID has multiple rows, many with Null values. I want to combine the rows to create a complete set.
Here is a sample set of data:
ID    Address      CreatedDate     City
1    1 1st Street      NULL     New York City
1      NULL          8/18/17      NULL
2      NULL          8/13/17     Boston
2    2 2nd Street    NULL         NULL
3    3 3rd Street    8/1/17      Los Angeles
3     NULL             NULL       NULL
3     NULL           8/7/17       NULL

Here is the expected Output:
ID    Address      CreatedDate     City
1    1 1st Street    8/18/17    New York City
2    2 2nd Street    8/13/17     Boston
3    3 3rd Street    8/1/17      Los Angeles

Honestly I'm not sure this is even possible, but any suggestions would be greatly appreciated!

A: Group by the column you want to be unique and use max() to get the results containing something for each id
select ID, max(Address), max(CreatedDate), max(City)
from your_table
group by ID

A: aggregation is the key here.  assuming you want the max/min value for each group if multiple exist.  looking at the date column on ID 3 it's min.
SELECT ID
     , min(address) as Address
     , min(createdDate) as createdDate
     , min(city) as City
FROM table
GROUP BY ID

A: As another possibility, you could solve this one using the function ARRAY_AGG available in the Standard SQL version of BigQuery (highly recommended that you use standard).
As for the query:
#standardSQL
SELECT
  ID,
  ARRAY_AGG(Address IGNORE NULLS LIMIT 1) Address,
  ARRAY_AGG(CreatedDate IGNORE NULLS LIMIT 1) CreatedDate,
  ARRAY_AGG(City IGNORE NULLS LIMIT 1) City
from
  `your_table`
GROUP BY
  ID

You can test with simulated data:
#standardSQL
WITH data AS(
  SELECT 1 ID, '1 1st Street1' Address, NULL CreatedDate, 'New York City' City UNION ALL
  SELECT 1, NULL, '8/18/17', NULL UNION ALL
  SELECT 2, NULL, '8/13/17', 'Boston' UNION ALL
  SELECT 2, '2 2nd Street', NULL, NULL UNION ALL
  SELECT 3, '3 3rd Street', '8/1/17', 'Los Angeles' UNION ALL
  SELECT 3, NULL, NULL, NULL UNION ALL
  SELECT 3, NULL, '8/7/17', NULL
)

SELECT
  ID,
  ARRAY_AGG(Address IGNORE NULLS LIMIT 1) Address,
  ARRAY_AGG(CreatedDate IGNORE NULLS LIMIT 1) CreatedDate,
  ARRAY_AGG(City IGNORE NULLS LIMIT 1) City
from
  data
GROUP BY
  ID
ORDER BY
  ID

You may find that queries once exceeding resources will be processed in seconds just by using ARRAY_AGG properly.


text:
Q: Business Objects - query with parameter based on a variable I'm writing a report in Business Objects, and need to select data dating 10 weeks from the current reporting date to the current reporting date.
I have a query element telling me the current reporting date, and I have created a variable holding the date 10 weeks ago.
=RelativeDate([Current Date];-10;WeekPeriod)

I'm now editing the data provider, and add a query filter for the date range. However, I'm not able to select the variable as an object available in the query.
I feel that I'm missing something basic. How can I select my dates based on a database object date and a predefined range of dates?

A: Document variables cannot be used in the Query Panel. After your query is executed and a report has been generated, you can then filter it by using this variable.


text:
Q: Multiple, layered elements inside pattern-element I am currently trying to reproduce some patterns from images in SVG. Currently, the patterns reference an image:
<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" style="contain: strict;">
    <defs>
        <pattern id="pattern-frontend" patternUnits="userSpaceOnUse" width="6" height="6">
            <image href="/assets/img/pattern/frontend.png" x="0" y="0" width="6" height="6">
        </pattern>
    </defs>
</svg>

Now I'm starting to replace them, but I am running into an issue where it looks like I can only place a single element inside the pattern element. Whatever Element is the first child element will be used and everything else gets ignored:
<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" style="contain: strict;">
    <defs>
        <pattern id="pattern-frontend" patternUnits="userSpaceOnUse" width="4" height="4">
            <rect x="3" y="3" width="1" height="1" fill="green">
            <rect x="0" y="0" width="2" height="2" fill="currentcolor" style="fill: var(--color-accent-300)">
        </pattern>
    </defs>
</svg>

This will make the green rect visible, but not the other one. If I change the order of the elements, it will make the other one visible and the green one will not be visible.
I feel like I misunderstand something about this, ultimately I would like to be able to set an entire <rect> that spans the entirety of the pattern and serve as a background, but that doesn't work at all because it only ever shows one element at a time. And later on I'll need to use multiple elements to create some more complex patterns.
What am I not understanding here? Thankful for any input!

A: It is like @enxaneta pointed out, that I just had a syntax error. The <rect>'s need to be self-closing.


text:
Q: how to handle horizontal ellipsis (three dots) character in XML output through PHP As mentioned in the question, I am trying to generate an XML output( for an iPhone app) using PHP which is reading the data from MySQL's text field.
Whenever there is a horizontal ellipsis character in the field... the XML is not generated properly.
I have tried a few ways to escape it like shown below, but none seems to work...
$row['detail'] = str_replace("&", "&", $row['detail']);
$row['detail'] = str_replace("…", "…", $row['detail']); //<-- prob is here
$row['detail'] = str_replace("<", "&lt", $row['detail']);
$row['detail'] = str_replace("\'", "'", $row['detail']);
$row['detail'] = str_replace(">", ">", $row['detail']);
$row['detail'] = str_replace("\"", """, $row['detail']);

I have 2 questions basically,

*

*How do I handle horizontal ellipsis chracter?

*Are there more such characters which could cause such problem? Any reference to this list and its solution would be great!
Thanks

A: It is possible (and the recommended way) to use the literal, actual character in  XML output. Don't use HTML entity based workarounds - it's unnecessary.
The reason why it doesn't work for you is probably because the ellipsis characters's encoding doesn't match the encoding of the XML file that is being generated.
You just need to make sure they match. So for example, if you're generating an UTF-8 XML file, the ellipsis character needs to be UTF-8 as well.

A: Raw XML does not know about any named entities except >, < and `&. All other entities need to either be declared as numeric character codes, or else you need to specify the entities in the Doctype or DTD.
The … entity is defined in the HTML DTD, which is understood by all browsers, but it isn't defined in most other XML DTDs.
In general, if you're working with a DTD, most of the time it will be a third party DTD that you have no control over, so you can't go adding entities to them. You also don't want to be adding entities ad-hoc to your own DTDs either.
I would avoid putting entity declarations into the doctype header as well. It's unnecessary fluff that doesn't really add much unless you're repeating the same entity over and over in a document.
Therefore my recommendation would be simply to use numeric entities.
So instead of …, you would use the character code entity … or …. The same would apply for any other non-ascii character.
The other option, of course, is to output the XML using UTF-8 or UTF-16 character encoding, which negates the need for any entities at all. That may or may not be an option for you, but if it is possible, it may be the best way to go.
If you have a specific character which you need to find the numeric entity codes for, there are plenty of places on the web to find references for them. Here is the one from Wikipedia: http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
Hope that helps.

A: XML understands only a few character entities, '"&<>. Anything is will cause the document to be invalid. You can try adding the entity to the DTD with
 <!DOCTYPE text [ <!ENTITY hellip "…"> ]>


text:
Q: Calculate ratio of an element in a list efficiently The following code works with small lists, however it takes forever with long lists, I suppose it's my double use of length that is the problem.
ratioOfPrimes :: [Int] -> Double
ratioOfPrimes xs = fromIntegral (length (filter isPrime xs))/ fromIntegral(length xs)

How do I calculate the ratio of an element in longer lists?

A: The double use of length isn't the main problem here. The multiple traversals in your implementation produce a constant factor and with double length and filter you get the avg complexity of O(3n). Due to Stream Fusion it's even O(2n), as already mentioned by Impredicative. But in fact since the constant factors don't have a dramatic effect on performance, it's even conventional to simply ignore them, so, conventionally speaking, your implementation still has the complexity of O(n), where n is the length of the input list.
The real problem here is that the above would all be true only if isPrime had the complexity of O(1), but it doesn't. This function performs a traversal thru a list of all primes, so it itself has the complexity of O(m). So the dramatic performance decrease here is caused by your algorithm having the final complexity of O(n*m), because on each iteration of the input list it has to traverse the list of all primes to an unknown depth.
To optimize I suggest to first sort the input list (takes O(n*log n)) and itegrate a custom lookup on a list of all primes, which will drop the already visited numbers on each iteration. This way you'll be able to achieve a single traversal on the list of all primes, which theoretically could grant you with the complexity of O(n*log n + n + m), which again, conventionally can be thought of as simply O(n*log n), by highlighting the cost center.

A: So, there's a few things going on there. Let's look at some of the operations involved:

*

*length

*filter

*isPrime

*length
As you say, using length twice isn't going to help, since that's O(n) for lists. You do that twice. Then there's filter, which is also going to do a whole pass of the list in O(n). What we'd like to do is do all this in a single pass of the list.
Functions in the Data.List.Stream module implement a technique called Stream Fusion, which would for example rewrite your (length (filter isPrime xs)) call into a single loop. However, you'd still have the second call to length. You could rewrite this whole thing into a single fold (or use of the State or ST monads) with a pair of accumulators and do this in a single pass:
ratioOfPrimes xs = let
  (a,b) = foldl' (\(odd,all) i -> if (isPrime i) then (odd +1, all+1) else (odd, all+1)) (0,0) xs
in a/b

However, in this case you could also move away from using a list and use the vector library. The vector library implements the same stream fusion techniques for removing intermediate lists, but also has some other nifty features:

*

*length is O(1)

*The Data.Vector.Unboxed module lets you store unboxable types (which primitive types such as Int certainly are) without the overhead of the boxed representation. So this list of ints would be stored as a low-level Int array.

Using the vector package should let you write the idiomatic representation you have above and get better than the performance of a single-pass translation.
import qualified Data.Vector.Unboxed as U

ratioOfPrimes :: U.Vector Int -> Double
ratioOfPrimes xs = (fromIntegral $ U.length . U.filter isPrime $ xs) / (fromIntegral $ U.length xs)

Of course, the thing that hasn't been mentioned is the isPrime function, and whether the real problem is that it's slow for large n. An unperformant prime checker could easily blow concerns over list indexing out of the water.


text:
Q: Is it possible to calculate a degree in css with vw? I'm trying to make my Skew responsive with view-width.
$SkewXBar: calc(5deg + 10vw);
I've searched online already, but found nothing regarding calculating a degree with vw.
If somebody knows an alternative, I'd be pleased to know.

A: A quick thought. The simplest way would be using a JavaScript logic. Something like the following:
function calculate() {
  const deviceWidth = screen.width;
  const viewportWidth = window.innerWidth;
  const currentRatio = viewportWidth / deviceWidth;
  const angle = currentRatio * 360;
  document.querySelector('.rotating-bar').style.transform = `rotate(${angle}deg)`;
}

window.addEventListener('resize', calculate);

... which assumes an HTML structure like the following:
<div class="rotating-bar">
  This rotates
</div>

CodePen example at https://codepen.io/baadaa/full/MWYMLwE


text:
Q: ImageButton is not filing out is Linearlayout In below code there are some of the ImageButton having ImageButton out of which hotel_english and weather images are not proper in linearlayout. Here I am applying scaletype fillXY so please help me out.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:background="@drawable/background"
    android:orientation="vertical">
<LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"

                    android:layout_centerHorizontal="true"
                    android:orientation="vertical"
                    android:weightSum="3">
                    <LinearLayout
                        android:id="@+id/hotelslayout"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        >
                        <ImageView
                            android:scaleType="fitXY"
                            android:adjustViewBounds="true"
                            android:id="@+id/hotelsbtn"
                            android:layout_width="wrap_content"
                            android:layout_height="match_parent"
                            android:background="@drawable/hotels_english"/>

                    </LinearLayout>
                    <LinearLayout
                        android:id="@+id/weatherlayout"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"

                        android:layout_weight="2">
                        <Button
                            android:scaleType="fitXY"
                            android:id="@+id/weatherbtn"
                            android:layout_below= "@+id/hotelsbtn"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:background="@drawable/weather_english"/>
                    </LinearLayout>
                    <LinearLayout
                        android:id="@+id/trackerlayout"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight=".29">
                        <ImageButton
                            android:id="@+id/tackerbtn"
                            android:layout_below= "@+id/trackerbtn"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:background="@drawable/tracker_english"/>
                    </LinearLayout>

                </LinearLayout>
  </RelativeLayout>

A: For Linear Layout to have definite positioning, you should always include android:orientation = "<value>" in it.


text:
Q: Cake PHP site working fine on localhost but error when on server So here is the case .
I have baked the cake php application normally . The site runs fine on a local server .
But when migrated to bluehost server it starts having issues in hasmany and belongs to associations .
The issue i found was basically in the array containing the data.
E.g
$comments usually has the data

Array ( [Comment] => Array ( [id] => 46 [name] => asddasd [email] => sdaa [website] => asdasd [commentdata] => asdasd [postdate] => 2012-04-27 08:20:00 [post_id] => 2 ) [Post] => Array ( [id] => 2 [title] => Fighter Aircraft [category] => Military [description] => asddasdasdasdasdasd [body] => Hello this is second [created] => 2012-04-10 18:41:43 [modified] => 2012-04-27 13:25:33 [user_id] => 0 ) )

but on the webserver it looks like

Array ( [Comment] => Array ( [id] => 8 [name] => ddasdasdsdasd [email] => asdasd [website] => asdasd [commentdata] => adasdasdasdad [postdate] => 2012-04-23 23:15:00 [post_id] => 8 ) )

Thus ending up showing following error
Undefined index: Post [APP/View/Comments/index.ctp, line 24]
The line 24 is
    <?php echo $this->Html->link($comment['Post']['title'], array('controller' => 'posts', 'action' => 'view', $comment['Post']['id']));

Please tell a fix for this ?

A: Have a look at this tutorial: http://ad7six.com/2007/08/24/Production-setup-revisited.html.  I have seen this question posted quite a lot on this site, namely: here: Cakephp Install on Bluehost and here: Setting up cakephp 2.0 on bluehost


text:
Q: При прокрутке сайта на айфон происходят залипания https://jardaxion.github.io/eeaar - при скорлле сайта на айфон происходят залипания на слайдерах(Сделаны на slick slider), так же там имеются position absolute элементы
section.sliderMain
        .sliderMain__inner
            .sliderMain__leftArrow.sliderMain__arrow
                svg(width='14' height='16' viewbox='0 0 14 16' fill='none' xmlns='http://www.w3.org/2000/svg')
                    path(d='M0.292893 7.29289C-0.0976315 7.68342 -0.0976315 8.31658 0.292893 8.70711L6.65685 15.0711C7.04738 15.4616 7.68054 15.4616 8.07107 15.0711C8.46159 14.6805 8.46159 14.0474 8.07107 13.6569L2.41421 8L8.07107 2.34315C8.46159 1.95262 8.46159 1.31946 8.07107 0.928932C7.68054 0.538408 7.04738 0.538408 6.65685 0.928932L0.292893 7.29289ZM14 7L1 7V9L14 9V7Z' fill='#414141')
            .sliderMain__content
                -for(let i=0; i<4; i++)
                    .slide__wrapper
                        .slider__slide
                            .slide__left
                                p.slide__title Авторский курс "Сертификация от 0 до успеха!"
                                p.slide__descirption Оставьте заявку и получите скидку на любой пакет
                                a.button.slide__button.js-open-modal(href="#", data-modal="request") Оставить заявку
                            .slide__right
                                .slider__first
                                    svg(width='154' height='154' viewbox='0 0 154 154' fill='none' xmlns='http://www.w3.org/2000/svg')
                                        circle(cx='77' cy='77' r='77' fill='#F3E7D6')
                                .slider__second
                                    svg(width='107' height='107' viewbox='0 0 107 107' fill='none' xmlns='http://www.w3.org/2000/svg')
                                        path(d='M107 53.5C107 83.0472 83.0472 107 53.5 107C23.9528 107 0 83.0472 0 53.5C0 23.9528 23.9528 0 53.5 0C83.0472 0 107 23.9528 107 53.5ZM16.05 53.5C16.05 74.1831 32.8169 90.95 53.5 90.95C74.1831 90.95 90.95 74.1831 90.95 53.5C90.95 32.8169 74.1831 16.05 53.5 16.05C32.8169 16.05 16.05 32.8169 16.05 53.5Z' fill='#CD474A')
                                .slide__img-wrp
                                    img.slide__img(src='img/woman.png', alt="")
                                    .slide__backcircle
                                        svg(width='357' height='357' viewbox='0 0 357 357' fill='none' xmlns='http://www.w3.org/2000/svg')
                                            circle(cx='178.5' cy='178.5' r='178' stroke='#CD474A')
            .sliderMain__rightArrow.sliderMain__arrow
                svg(width='14' height='16' viewbox='0 0 14 16' fill='none' xmlns='http://www.w3.org/2000/svg')
                    path(d='M13.7071 8.70711C14.0976 8.31658 14.0976 7.68342 13.7071 7.29289L7.34315 0.928933C6.95262 0.538408 6.31946 0.538408 5.92893 0.928933C5.53841 1.31946 5.53841 1.95262 5.92893 2.34315L11.5858 8L5.92893 13.6569C5.53841 14.0474 5.53841 14.6805 5.92893 15.0711C6.31946 15.4616 6.95262 15.4616 7.34315 15.0711L13.7071 8.70711ZM-8.74228e-08 9L13 9L13 7L8.74228e-08 7L-8.74228e-08 9Z' fill='#414141')

/* Сам блок и стрелки */
.sliderMain{
    &__inner{
        padding: 94px 114px 75px 186px;
        position: relative;
    }

    &__arrow{
        padding: 16px 18px 15px 18px;
        background: rgba(211, 211, 211, 0.6);
        border-radius: 50%;
        cursor: pointer;
        position: absolute;
        @include verCenterAbsol;
    }

    @include LRea('&__leftArrow', 169px, '&__rightArrow', 140px);

    .slick-dots{
        display: flex;
        @include flexCenter;
        margin-top: 74px;
        li{
            &:not(:last-of-type){
                margin-right: 10px;
            }

            &.slick-active{
                .slider__dots{
                    transform: scale(1.5);
                    background: black;
                }
                + li{
                    .slider__dots{
                        transform: scale(1.2);
                        background: rgba(0, 0, 0, 0.7);
                    }
                }
            }
        }
    }
}

/* Настройки внутри самого слайдера */
.slider{
    &__slide{
        display: flex;
        justify-content: space-between;
        margin: 0 126px;
        padding-top: 71px;
        padding-bottom: 12px;
    }

    &__dots{
        @include box(7px, 50%);
        background: rgba(0, 0, 0, 0.35);
        @include transition;
    }

    &__first{
        position: absolute;
        @include TLa(-70px, -49px);
        z-index: 3;
    }

    &__second{
        position: absolute;
        @include BRa;
        z-index: 3;
    }
}

/* Слайд */
.slide{
    &__title{
        color: #0D2938;
        font-size: 48px;
        margin-bottom: 25px;
        font-weight: 500;
        max-width: 763px;
        line-height: 60px;
    }

    &__left{
        margin-bottom: 23px;
    }

    &__right{
        position: relative;
    }

    &__descirption{
        color: #A6A6A6;
        margin-bottom: 69px;
        font-weight: 400;
    }

    &__button{
        padding: 20px 90px;
        font-size: 18px;
    }

    &__img{
        width: 351px;
        height: 348px;
        object-fit: scale-down;
        border-radius: 50%;
        position: relative;
        z-index: 2;
        &-wrp{
            position: relative;
            svg{
                position: absolute;
                @include BRa(-9px, -12px)
            }
        }
    }
}

$('.sliderMain__content').slick({
        nextArrow: '.sliderMain__rightArrow',
        prevArrow: '.sliderMain__leftArrow',
        customPaging : function(slider, i) {
            return '

';
        },
        dots: true,
        autoplay: true,
        speed: 650,
        autoplaySpeed: 5000,
        slidesPerRow: 1,
        infinite: true,
        swipe: false
    });


text:
Q: How to give animation to container when no height and width is defined I want to give animation to my container, I want to increase the size from a low width and height of the container up to the default size that it is taking now.
    Container(
                        decoration: BoxDecoration(
                            image: DecorationImage(
                              fit: BoxFit.cover,
                              colorFilter:ColorFilter.mode(Colors.pink, BlendMode.color),
                              image: AssetImage(
                                'lib/images/Alone.jpg',
                              ),
                            ),
                            borderRadius: BorderRadius.circular(10),
                            gradient: LinearGradient(
                                colors: <Color>[
                                  Colors.yellowAccent,
                                  Colors.blueAccent,
                                ]
                            )
                        ),
                        child: FlatButton(
                          onPressed: (){
                            Navigator.push(
                                context,
                                MaterialPageRoute(builder: (context)=>Alone())
                            );
                          },
                          child: Padding(
                            padding: const EdgeInsets.all(24.0),
                            child: Text(
                              'Alone',
                              style: TextStyle(
                                fontWeight: FontWeight.bold,
                                color: Colors.white,
                                fontSize: 20,
                              ),
                            ),
                          ),
                        ),
                      ),

A: Use an AnimatedContainer.
There's a lot of stuff you can achieve doing this.
Animated Container

A:  AnimatedContainer(
                  height: isIncreaseSize ? 300 : 200,
                  width: isIncreaseSize ? 300 : 200,
                  duration: Duration(milliseconds: 200),
                        decoration: BoxDecoration(
                            image: DecorationImage(
                              fit: BoxFit.cover,
                              colorFilter:ColorFilter.mode(Colors.pink, BlendMode.color),
                              image: AssetImage(
                                'lib/images/Alone.jpg',
                              ),
                            ),
                            borderRadius: BorderRadius.circular(10),
                            gradient: LinearGradient(
                                colors: <Color>[
                                  Colors.yellowAccent,
                                  Colors.blueAccent,
                                ]
                            )
                        ),
                        child: FlatButton(
                          onPressed: (){
                            Navigator.push(
                                context,
                                MaterialPageRoute(builder: (context)=>Alone())
                            );
                          },
                          child: Padding(
                            padding: const EdgeInsets.all(24.0),
                            child: Text(
                              'Alone',
                              style: TextStyle(
                                fontWeight: FontWeight.bold,
                                color: Colors.white,
                                fontSize: 20,
                              ),
                            ),
                          ),
                        ),
                      )

u need a boolean to change size like as isIncreaseSize. duration: Duration(milliseconds: 200) animation duration. that all


text:
Q: How do CUDA devices handle immediate operands? Compiling CUDA code with immediate (integer) operands, are they held in the instruction stream, or are they placed into memory? Specifically I'm thinking about 24 or 32 bit unsigned integer operands.
I haven't been able to find information about this in any of the CUDA documentation I've examined so far. So references to any documents on specific uarch details like this would be perfect, as I don't currently have a good model for how CUDA works at this level.

A: NVIDIA doesn't release any information about how the devices work at this level.  There is a tool called decuda that can decompile cubins, so you can see the machine code.  If I recall, immediates go into the instruction stream, at least as far a decuda is able to deduce.  The problem with decuda is that it only works for CUDA 2.3 or lower.  They changed the executable format to elf in CUDA 3.0, and decuda hasn't been maintained in a long time.
The best official documentation is the PTX documentation, but that documents a virtual machine isa, not the real device.

A: If I recall correctly integer division (for example) is very costly, some while floating point operations (like sinf(..)) are completely implemented in hardware and therefore fast.
This talk gave me some insight:  "CUDA Tricks for Computational Physics" http://physics.bu.edu/~kbarros/talks/


text:
Q: Website Login Using PHP So a project in my class is to create a website that incorporates a database. I'm having trouble getting the login function to work. I've written the login and login-script in php. All that happens when I login is the page just refreshes to "localhost/login.php?" instead of "index.php" Any help is appreciated, thanks in advance.
My login.php
<?php
 include 'nav.php';
?>

<!DOCTYPE html>

  <title>UCF Events</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="css/login.css">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

  <link rel="stylesheet" href="css/navstuff.css">

  <?php
    include 'setUniversityColors.php';
    setColors();
  ?>

<?php
    displayNav('login.php' ,'Login');
?>

   <form class="form-signin">
        Email address
        <input type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
        Password
        <input type="password" id="inputPassword" class="form-control" placeholder="Password" required>

        <button class="btn btn-lg btn-primary btn-block" onClick="call();">Sign in</button>
      </form>

My login-script.php
    <?php

    //sets the following variables:
    $mysqluser = 'root';
    $mysqlpassword = '';
    $mysqldbname = 'db';

    //now connect to the database
    $mysqli = new mysqli("localhost", $mysqluser, $mysqlpassword, $mysqldbname);

    //here we can extract information from the client's POST request
    //  this was submitted by the jQuery function
    //always use mysql_real_escape_string when taking in user input
    //  this prevents SQL injection
    $email = $mysqli->real_escape_string($_POST['UserEmail']);
    $password = $mysqli->real_escape_string($_POST['Password']);

    $success = " ";
    $message = " ";

    $sql = "SELECT Password, isAdmin, isSuperAdmin, UserID FROM user WHERE UserEmail='$email'";

    //run the query and check if it was successful
    $result = $mysqli->query( $sql );
        if($result){

        //get an associative array from the result
        //retrieve specific attribute values by $row['tableAttribute']
        $row = $result->fetch_assoc();

        //check entered password against the hash
        if (password_verify($password, $row['Password'])) {

          $message = "Login Successful, redirecting...";
          $success = "success";

          //start the session and set some identifying variables
          //these are save across pages
          //we will end the session when the user logs out
          session_start();
          $_SESSION['UserEmail'] = $email;
          $_SESSION['isAdmin'] = $row['isAdmin'];
          $_SESSION['isSuperAdmin'] = $row['isSuperAdmin'];
          $_SESSION['id'] = $row['UserID'];

        } else {
          $message = "There was a problem with your user name or password.";
          $success = "fail";
        }
    } else {
        $message = "Error accessing database: " . $mysqli->error;
        $success = "fail";
    }

    $return = array('message' => $message, 'success' => $success);

    echo json_encode($return);

?>

A: Your code is very weird.
I see that you use jquery, so an example.
$.ajax({
  url: "your.php",
  method: "POST",
  data: { email : $('#email').val(), password: $('#pass').val() }
});

Now, in your php
$_POST['email'];
$_POST['password'];

Now with JSON.
//Prepare your JSON
var myJson = {};
myJson['email'] = $('#email').val();
myJson['password'] = $('#pass').val();
$.ajax({
 url: "your.php",
 method: "POST",
 data: { email : $('#email').val(), password: $('#pass').val() },
 dataType: "json"
});

In your PHP
 echo "The array ".print_r($_POST['paramet'],1);
 $data = json_decode($_POST['paramet']);
 echo $data['email'];
 echo $data['password'];


text:
Q: How to remove credentials from URLCredentialStorage I'm able to store and retrieve credentials but I'm unable to remove them. I've created a simple wrapper here but the clear method doesn't work. The credentials seem to persist after I call clear. What do I need to do to clear the credentials?
class PasswordManager {
    static let shared = PasswordManager() // singleton instance

    private lazy var protectionSpace: URLProtectionSpace = {
        return URLProtectionSpace(host: "somehost.com",
                                  port: 0,
                                  protocol: "http",
                                  realm: nil,
                                  authenticationMethod: nil)
    }()

    private init() { }

    func password(for userID: String) -> String? {
        guard let credentials = URLCredentialStorage.shared.credentials(for: protectionSpace) else { return nil }
        return credentials[userID]?.password
    }

    func set(password: String, for userID: String) {
        let credential = URLCredential(user: userID, password: password, persistence: .permanent)
        URLCredentialStorage.shared.set(credential, for: protectionSpace)
    }

    func clear(for userID: String) {
        if let password = password(for: userID) {
            let credential = URLCredential(user: userID, password: password, persistence: .permanent)
            URLCredentialStorage.shared.remove(credential, for: protectionSpace)
        }
    }
}

A: For the win:
func clear(for userID: String) {
    guard let creds = URLCredentialStorage.shared.credentials(for: protectionSpace) else { return }
    guard let cred = creds[userID] else { return }
    URLCredentialStorage.shared.remove(cred, for: protectionSpace)
}

A: To remove credentials that are synchronizable, you'll have to provide an option in the remove function.
URLCredentialStorage.shared.remove(cred, for: protectionSpace, options: [NSURLCredentialStorageRemoveSynchronizableCredentials: true])

This removed credentials for me that weren't removed otherwise.


text:
Q: date range validation in magento 2 ui comonent I have created a custom module to mark order as delivered , In my ui component file located at
app/code/Namespace/Modulename/view/adminhtml/ui_component/namespace_delivery_form.xml
i have the following code
        <field name="pickup_date" formElement="date" sortOrder="10">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="source" xsi:type="string">proofofdelivery</item>
            </item>
        </argument>
        <settings>
            <dataType>text</dataType>
            pickup_date
            <dataScope>pickup_date</dataScope>
            <validation>
                <rule name="required-entry" xsi:type="boolean">false</rule>
            </validation>
        </settings>
    </field>
    <field name="delivery_date" formElement="date" sortOrder="20">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="source" xsi:type="string">proofofdelivery</item>
            </item>
        </argument>
        <settings>
            <dataType>text</dataType>
            delivery_date
            <dataScope>delivery_date</dataScope>
            <validation>
                <rule name="required-entry" xsi:type="boolean">false</rule>
            </validation>
        </settings>
    </field>

i have 2 dates , order pickup date and delivery date , the thing is pickup date and delivery date that the admin select should be greater than the order created date , all previous dates need to be disabled .
i cannot find anywhere , where can i put date-range validation for this ui-component , i also need to fetch order created date which would be different for each order , so need a dynamic solution to the problem .
Thanks


text:
Q: Ошибка с библиотекой pyowm начал изучать новый для себя модуль (pyowm)
Я работаю в Pycharm
Там уже установил его (preferences -> Project interprets)
А потом такая вот ошибка:
import pyowm

owm = pyowm.OWM("my-key")

mg = owm.weather_manager()
obs = mg.weather_at_place('Kyiv')
print(obs.weather)

AttributeError: module 'pyowm' has no attribute 'OWM'

Не могу понять в чем проблема ведь в оф.документации именно такой код
Буду очень благодарен за помощь

A: В примере указано from pyowm import OWM:
from pyowm import OWM

owm = OWM('00ad12fa26bc6e66e81161714cea4170')

mgr = owm.weather_manager()
observation = mgr.weather_at_place('Москва')

w = observation.weather
print(w, w.wind())

>>> <pyowm.weatherapi25.weather.Weather - reference_time=2020-06-04 10:51:31+00, status=rain, detailed_status=light intensity shower rain> {'speed': 4, 'deg': 180}

причём забавно выходит. выше я писал комментарий, что получаю ошибку:

pyowm.commons.exceptions.InvalidSSLCertificateError: ('Connection
  aborted.', ConnectionResetError(10054, 'Удаленный хост принудительно
  разорвал существующее подключение', None, 10054, None))

стал копать, выяснил что api рабочее, ошибка возникала именно на методе получения погоды at_place, проверил по id, coord всё в порядке, вернулся к at_place и оно заработало. мистика


text:
Q: fix34 codingbat java —why wouldn't this work?
Return an array that contains exactly the same numbers as the given array, but rearranged so that every 3 is immediately followed by a 4. Do not move the 3's, but every other number may move. The array contains the same number of 3's and 4's, every 3 has a number after it that is not a 3, and a 3 appears in the array before any 4. Here is the link
  .

Below is my code.
public int[] fix34(int[] nums) {
  for(int k = 0; k<nums.length; k++)
  {
    if(nums[k] == 3)
    {
      int jay = nums[k+1];
      for(int j = 0; j<nums.length; j++)
      {
        if(nums[j] == 4)
        {
          nums[k+1] = nums[j];
          nums[j] = jay;
        }
      }
    }
  }
  return nums;

I wanted to make it so that if we find the number 3, we go on to look for a 4 (which may be coming before or after 3), and switch the 4 with the number immediately behind 3. However, since it doesn't work for all cases, I'm guessing my code doesn't exactly do that. Or else, is it a logical error? Any help would really be appreciated! (I know there are some other solutions to this out there, but I want to understand what's wrong with mine, exactly.)

A: I keep your logic and make some changes.
The inner loop needs a break after the 4 is found and the swap is made.
Also while looking for a 4, bypass any 4s that are after a 3:
public static int[] fix34(int[] nums) {
    for(int k = 0; k < nums.length; k++) {
        if(nums[k] == 3) {
            int jay = nums[k+1];
            if (jay != 4) {
                for (int j = 1; j < nums.length; j++) {
                    if (nums[j] == 4 && nums[j - 1] != 3) {
                        nums[k + 1] = 4;
                        nums[j] = jay;
                        break;
                    }
                }
            }
        }
    }
    return nums;
}

public static void main(String[] args) {
    int[] array1 = {1, 3, 1, 4};
    int[] array2 = {1, 3, 1, 4, 4, 3, 1};
    int[] array3 = {3, 2, 2, 4};

    System.out.println(Arrays.toString(array1) + "-->" + Arrays.toString(fix34(array1)));
    System.out.println(Arrays.toString(array2) + "-->" + Arrays.toString(fix34(array2)));
    System.out.println(Arrays.toString(array3) + "-->" + Arrays.toString(fix34(array3)));
}

will print
[1, 3, 1, 4]-->[1, 3, 4, 1]
[1, 3, 1, 4, 4, 3, 1]-->[1, 3, 4, 1, 1, 3, 4]
[3, 2, 2, 4]-->[3, 4, 2, 2]

A: You restart j at 0 each time you find a 3. Instead, you need to keep track of where the last 4 you handles was, and start looking for the next one after it:
public int[] fix34(int[] nums) {
    int last4 = 0;
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] == 3) {
            while (nums[last4] != 4) {
                ++last4;
            }
            nums[last4] = nums[i + 1];
            nums[i + 1] = 4;
            ++last4;
        }
    }
    return nums;
}

A: There is a logical error in your code. Every time you check if nums[k] == 3, you run the inner loop which swaps the element right after the 3 with the first 4 that it finds in the array. If I illustrate it (albeit very poorly):
We just continue through the loop if nums[k] != 3 since it doesn't do anything.
Your example array = {1,3,2,5,3,4,4}
when k == 1, then nums[k] == 3 is true.
So it runs the inner loop and the array changes to this:
It swaps the 2 at index 2 and 4 at index 5 since the first element 4 is found at index 5
Array after first execution of inner loop: {1,3,4,5,3,2,4}
Then it doesn't do anything until it gets to k == 4
when it gets to k == 4 then nums[k] == 3 is true
So it runs the inner loop and the array changes to this:
Resulting array after second execution of inner loop: {1,3,2,5,3,4,4}
As you can see, it swapped the first 4 (at index 2) with the 2 at index 5. But the first 4 was already placed correctly (by the first execution of inner loop) and should not move. So you need to keep track of the last element that is 4 that you have placed correctly and set the start of your inner loop to be after that last element. Let me know if this makes sense.
Right now as it stands, your program is doing this: find the first element that is 4 and place it after the last element that is 3 (and some elements in the middle is swapped).

A: you can do it in one while loop also , cheers !
public int[] fix34(int[] nums) {

  int start = 0;
  int end = nums.length-1;

  boolean is3 = false;
  boolean is4 = false;

  while( start < nums.length-1 ){

    if(nums[start] == 3){
      is3 = true;
    }

    if(nums[end] == 4){
      is4 = true;
    }

    if(is3 && is4){
      int temp = nums[start+1];
      nums[start+1] = nums[end];
      nums[end] = temp;

      is3 = false;
      is4 = false;
    }

    if(is3){
      end--;
      continue;
    }

    start++;
  }
  return nums;

}


text:
Q: Specific position for tooltip I have a layer which opens up as a tooltip everytime I hover a button. I simply did that by creating a JS function which displays or hides the layer.
Now, I am not a pro in JavaScript. My problem is the following:  when the button is scrolled towards the top oft he screen I want the tooltip opening below – and if the button is near the bottom of the screen I want the tooltip opening above. Right now I just did it with absolute positioning. But obviously that doesnt do the trick.
Who can help? Thanks!

A: Absolute position for the tip I think it's the right choice!
When you open it (i.e. when you go over the button), check if its Y offsetTop is <= of the Y median (imaginary) line of the page (window.innerHeight or (IE case) document.body.clientHeight divided by 2).
For example a solution could be (more or less):
Edited: check this fiddle example (set "expand" height to see how it works ;))
Edited(2): Now works on IE too
when the page is scrolled (and you want to maintain the tooltip opened -> you don't use mouseout), you can recheck opened tips and arrange them again