text:
Q: Copy and paste files through clipboard in Powershell In the folder E:\Files there are 2 files, which I want to copy and paste into D:\Dest:
E:\Files\

*

*File1.txt

*File2.txt

Using the keyboard I would simply select the 2 files, push ctrl+c, and in the destination folder D:\Dest\ I then push ctrl+v.
Now I want to achieve this using Powershell. So I copy the files into the clipboard:
Set-Clipboard -Path E:\Files\*

But how to paste those files now into the destination folder? Obviously, I will need Get-Clipboard. But it's not quite clear to me, how to use it, in order to paste the files.
I know I could copy the contents of these 2 files and then by using Set-Content create those files in D:\Dest\ on my own and copy the content into them. But is there any direct way? Because with Set-Clipboard those files already are in the clipboard. They just need to be pasted. I can use ctrl+v and it works. But I want to paste them through Powershell. Any ideas?

A: Here's the script I use to paste files/directories:
$fileDrop = get-clipboard -Format FileDropList
if($fileDrop -eq $null)
{
    write-host "No files on the clipboard"
    return
}

foreach($file in $fileDrop)
{
    if($file.Mode.StartsWith("d"))
    {
        $source = join-path $file.Directory $file.Name
        $e = "copy-item -Recurse $source $($file.Name)"
        $e
        Invoke-Expression $e
    }
    else
    {
        $file.Name
        $file | copy-item
    }
}

A: You could use the .NET Clipboard class:
Add-Type -AssemblyName System.Windows.Forms

$files = [System.Collections.Specialized.StringCollection]::new()
$files.Add('YOUR_FILE_PATH_HERE')

[System.Windows.Forms.Clipboard]::SetFileDropList($files)

This copies YOUR_FILE_PATH_HERE to the local clipboard.
You could use this, for example, when you're in a local terminal and need to copy file(s) to a remote session without PowerShell remoting (e.g., RDP or Citrix) without opening the directory in Explorer.
It's a little unwieldy, so if I used it a lot, I'd probably put it in a function like Copy-FileToClipboard and add it to my PowerShell profile.

A: Inspired by the other comment in this thread, but refactored, and supporting both move and copy actions (moving is the default action, while copying is achieved with the -c parameter). The script pastes clipboard files and folders into the current directory (I have placed it in a PATH directory and use it as paste).
$data = Get-Clipboard -Format FileDropList

if ($data -ne $null)
{
    foreach ($file in $data)
    {
        if ($args[0] -eq "-c")
        {
            $action = "Copied:"
            Copy-Item -Recurse -LiteralPath $file
        }
        else
        {
            $action = "Moved:"
            Move-Item -LiteralPath $file
        }

        $action
        "- from: $(Join-Path $file.Directory $file.Name)"
        "- into: $(Join-Path "$(Get-Location)" $file.Name)"
    }
}

The -LiteralPath parameter was needed to handle filenames containing square brackets.


text:
Q: Replace Non-Alphanumeric Characters in Oracle I am trying to convert a string in Oracle into a modified string that is compatible with a specific API.
I would like to leave all alphanumeric characters intact, replace all spaces with the + character, and replace all special characters with % plus their hex code.
For example,
Project 1: Nuts & Bolts
should become
Project+1%3A+Nuts+%26+Bolts
Is there any way to do this using only SQL?

A: I don't think you can get there with plain SQL without nested replace calls. You can get your sample value with the utl_url.escape() function, but because you have to pass it a second parameter and that is a boolean, you have to do it in an PL/SQL block:
set define off
begin
  dbms_output.put_line(replace(utl_url.escape('Project 1: Nuts & Bolts', true),
    '%20', '+'));
end;
/

Project+1%3A+Nuts+%26+Bolts

The url_utl.escape function converts the spaces to %20:
Project%201%3A%20Nuts%20%26%20Bolts

... and the single replace call converts those to +.
As Ed Gibbs said, you can make that a function so you can at least call it from plain SQL:
create or replace function my_escape(str in varchar2) return varchar2 is
begin
    return replace(utl_url.escape(str, true), '%20', '+');
end;
/

set define off
select my_escape('Project 1: Nuts & Bolts') from dual;

MY_ESCAPE('PROJECT1:NUTS&BOLTS')
--------------------------------
Project+1%3A+Nuts+%26+Bolts

You probably need to check the legal and reserved character lists to see if there's anything else that needs special handling.
(I've used set define off to stop my client treating the ampersand as a substitution variable; your client or application might not need that, e.g. if calling over JDBC).

A: apex_util.url_encode should work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Finding the index row numbers of all common dates between two columns in Python I have a set of 2 dataframes that I have imported via excel. Basically, I have a list of dates and stock prices which are different for both of these dataframes (one starts in 1990, the other in 2007). I want to find the common dates between both of these dataframes and concatenate so that I have one column of dates and the appropriate stock prices from dataframe 1 and 2.
ff = pd.read_excel('Europe_5_Factors_Daily.xlsx',sheet_name='Factors')
pp = pd.read_excel('Europe_5_Factors_Daily.xlsx',sheet_name='Sheet1')
ff =ff.iloc[:,0:4]
idx = ff['Date'].reset_index(drop=True) == pp["Date"].reset_index(drop=True).tolist()
print(idx)

I get the following error message : ValueError: ('Lengths must match to compare', (8132,), (3457,)). Does anyone know what went wrong here?
Essentially, I'm trying to find the index row numbers of the common dates so that I can then get the equivalent rows.

A: import pandas as pd

ff = pd.read_excel('Europe_5_Factors_Daily.xlsx',sheet_name='Factors')
pp = pd.read_excel('Europe_5_Factors_Daily.xlsx',sheet_name='Sheet1')

def find_common_dates(df1,df2):
    df1_dates = df1['Date'].tolist()
    df2_dates = df2['Date'].tolist()
    common_dates = list(set(df1_dates) & set(df2_dates))
    return common_dates

Then run
find_common_dates(ff,pp)


text:
Q: sort of Include in an include - php Here is what we have :-
We currently have a file system like this
$price = '3.00'; - this in turn is then included into a different file for use within the template system.
what we want to do may seem a bit long winded but it seems the easiest to us to get around.
what we are going to have is one file which will static price and will be updated via a .net application so all the .php contains is 3.00
then... we come back to the main file and this is where we are getting stuck
we have tried methods like this
<?
$file = file_get_contents('/home/habbo/www/order/pricex2.php');
echo $file;
$price = '$file';
?>

we have tried to put an include within the = ' '; bit and that doesnt seem to work and im not too sure how we are meant to add it , i thought the $file might of worked but it just simple outputs the $file
is there much i am doing wrong

A: Erm, I think you need:
$price = $file;

or (slower):
$price = "$file";

Since PHP variables are not interpolated within single-quoted strings.
You can convert it into a floating point number like this:
$price = floatVal($file);

// or
$price = (float)$file;

// or (icky, but..)
$price = $file + 0.0;


text:
Q: test class for wrapper class in apex   public with sharing class ResponseWrapper{
    public String Id;
    public String Time;
    public String lobType;
    public String businessContextId;
    public Information[] document;

    public class Information{
    public String id;
    public String type;
    public String context;
    public ErrorInformation[] errors;
    public Data data;
  }

  public class ErrorInformation{
    public String code;
    public String description;
  }

  public class Data Data {
    public PersonDetail[] person;
  }

  public class PersonDetail{
    public String firstName;
    public String lastName;
    public Integer age;
    public String gender;
  }

above is my wrapper class i want to write a test class for the same, as my wrapper class don't have any method/constructor the covering lines are coming 0%
so for writting test class for this i have created a method that is returing instance of this class is this approach is fine, or i should try something else?
 public with sharing class ResponseWrapper{
    public String Id;
    public String Time;
    public String lobType;
    public String businessContextId;
    public Information[] document;

    public class Information{
    public String id;
    public String type;
    public String context;
    public ErrorInformation[] errors;
    public Data data;
  }

 public class ErrorInformation{
    public String code;
    public String description;
 }

 public class Data Data {
    public PersonDetail[] person;
 }

 public class PersonDetail{
    public String firstName;
    public String lastName;
    public Integer age;
    public String gender;
 }

 public static ResponseWrapper getInstance(){
    return new ResponseWrapper();
 }

A: Your class is not covered because it contains no executable lines of code. There is nothing to cover.
It is not necessary to add a constructor for the purpose of simulating coverage. Code coverage is defined as a percentage is executable lives covered, so your wrapper class requires no test class and does not impact your org's coverage.


text:
Q: Javascript chunk path has colons https://example.com/js/chunk-vendors.b3792e11.js:18:16400 I have build a Vue application with npm run build and uploaded the dist folder to Apache server.
Apache isn't able to find the file when this part is there (:18:16400) which is being requested from the app.
what is causing this issue ?
should it be solved from npm or from the web server ?

A: The problem was that there was an infinite loop which tells about the timeout issue. Vue seems to stops the infinite loop in development but it remains there in build for production


text:
Q: AJAX Response Wrapper I wrote a small web request response wrapper to print out data from the backend, but I was hoping to find a better way as I am passing this to some developers and want to make their life easier.
This is my current wrapper
class Req {
    static log(req){
       return req()
          .done(function(data){
              console.log(data);
          })
          .fail(function(err){
              console.log(err);
          });
    }
}

All of my backend commands are static functions of some class. In order to send the funtion to Req.log I must use bind
Req.log(BackendRoute.someCommand.bind(BackendRoute, {param1:1, param2:2}));
Is there any way to send the function BackendRoute.someCommand without having to bind BackendRoute to the function?
This is what BackendRoute looks like
class BackendRoute {
    static someCommand(params){
       return BackendRoute.post(params);
    }
}

A: You can use the fat arrow. It is a new function you are creating but it is clearer and still short:
Req.log(() => BackendRoute.someCommand({param1:1, param2:2}));


text:
Q: How to upload a photo to Facebook in MVC3? I am trying to upload a photo to a Facebook wall in MVC3 C#. I have tried several ways without results.
I'm not sure if this is achievable or not in MVC3. I have searched a lot on Google and Stackoverflow, but I didn't find a proper solution.
Could anyone help me? Please send your controller code and view page, with how to call this button to post images on Facebook wall.
I am stuck with my work, because of this upload photo to Facebook.

A: this will work
var attachment = new JsonObject();
var media = new[]{
    new{
        type="jpeg",
        src = filePath,
        title= "title",
        artist= "art",
        album= "album"
    }
};
//var mediaArray = new JsonArray { media };
attachment.Add("name", "sfs");
attachment.Add("href", "http://www.google.com");
attachment.Add("caption", " asdas");
attachment.Add("description", description);
attachment.Add("target_id", "1231231");
attachment.Add("media", media);

var sb = new StringBuilder("https://api.facebook.com/method/stream.publish?");
sb.Append("message="); sb.Append(description + "&");
sb.Append("attachment=");
sb.Append(attachment);
sb.Append("&access_token=");
sb.Append(accessToken);
var req = WebRequest.Create(sb.ToString());
req.GetResponse();


text:
Q: $N$ dice are rolled, find the probability of the following events The probability that $n$ dice are rolled is $1/2^n$. Let $S_N$ denote the sum of the numbers shown
on $N$ dice. Find the probability of the following events:
a) $S_N = 4$, knowing that $N$ is even;
b) $N = 2$, given that $S_N = 3$;
c) $N = 2$, given that $S_N = 4$ and the rst die showed the number $1$;
d) the largest number shown on any die is $4$, knowing that $N = 3$.
Can somebody please help me with this?
For point a, we have two cases: $N=2$ and $N=4$.
When $N=2$ we can get $(1,3)$, $(2,2)$, and $(3,1)$ and $N=4$ $(1,1,1,1)$ for favourable cases.
However, I don't know where the $1/2^n$ part comes in? The total number of cases should be $6^N$, right? So $6^2 + 6^4 = 1332$. Then, the number of favorable cases/total number of cases should give $6/1332$?
I think I'm missing something important here, please help me out! Thanks

A: The first sentence means that the number of dice rolled is a random variable $N$ such that $\Bbb P(N=n)$, the probability of rolling $n$ dice, is $\frac1{2^n}$. Thus, the probability of rolling one die is $\frac12$, the probability of rolling two dice is $\frac1{2^2}=\frac14$, and so on. Since $\sum_{n\ge 1}\frac1{2^n}=1$, this makes sense.
(a) If $S_n=4$, we can't possibly have more then $4$ dice, so if $n$ is even, $n$ must (as you said) be $2$ or $4$, and the favorable rolls are exactly the ones that you specified. We want $\Bbb P(S_N=4\mid N\text{ is even})$, which by definition is
$$\Bbb P(S_N=4\mid N\text{ is even})=\frac{\Bbb P(S_N=4\text{ and }N\text{ is even})}{\Bbb P(N\text{ is even})}\;,$$
so we should try to calculate the probabilities on the righthand side.
$$\begin{align*}
\Bbb P(N\text{ is even})&=\sum_{k\ge 1}\Bbb P(N=2k)=\sum_{k\ge 1}\frac1{2^{2k}}\\
&=\sum_{k\ge 1}\frac1{4^k}=\frac{\frac14}{1-\frac14}\\
&=\frac13\;.
\end{align*}$$
If $X_k$ is the random variable representing the number on the $k$-th die,
$$\begin{align*}
\Bbb P(S_N=4\text{ and }N\text{ is even})&=\Bbb P(S_N=4\text{ and }N=2)+\Bbb P(S_N=4\text{ and }N=4)\\
&=\Bbb P\big(N=2\text{ and }X_1+X_2=4\big)\\
&\qquad+\Bbb P(N=4\text{ and }X_1=X_2=X_3=X_4=1)\\
&=\frac1{2^2}\cdot\left(3\left(\frac16\right)^2\right)+\frac1{2^4}\cdot\left(\frac16\right)^4\\
&=\frac14\cdot\frac3{36}+\frac1{16}\cdot\frac1{1296}\\
&=\frac1{48}+\frac1{20736}\\
&=\frac{433}{20736}\;.
\end{align*}$$
Thus, $$\Bbb P(S_N=4\mid N\text{ is even})=\frac{\frac{433}{20736}}{\frac13}=\frac{433}{6912}\approx0.0626\;.$$
This should get you started; I'll add a bit more later.
Added: For (b) we want $\Bbb P(N=2\mid S_N=3)$. If $S_N=3$, there are three possibilities: $N=1$ and $X_1=3$; $N=2$ and either $X_1=1$ and $X_2=2$, or $X_1=2$ and $X_2=1$; or $N=3$ and $X_1=X_2=X_3=1$. Thus,
$$\begin{align*}
\Bbb P(S_N=3)&=\Bbb P(N=1\text{ and }S_N=3)+\Bbb P(N=2\text{ and }S_N=3)+\Bbb P(N=3\text{ and }S_N=3)\\
&=\frac12\cdot\frac16+\frac1{2^2}\cdot\frac2{36}+\frac1{2^3}\left(\frac16\right)^3\\
&=\frac{169}{1728}\;.
\end{align*}$$
The term $\dfrac1{2^2}\cdot\dfrac2{36}=\dfrac1{72}$ corresponds to the cases in which $N=2$: it's the probability that $S_N=3$ and $N=2$. It's share of the total probability of the event $S_N=3$ is therefore
$$\Bbb P(N=2\mid S_N=3)=\frac{\frac1{72}}{\frac{169}{1728}}=\frac{1728}{72\cdot169}=\frac{24}{169}\approx0.1420\;.$$
I'll leave the other two to you, but feel free to ask questions if you get completely stuck.

A: Hints:  For a, assuming $n$ and $N$ are the same, the statement about the number of dice rolled says there was $\frac 12$ chance that one die was rolled, $\frac 14$ chance that two were rolled, $\frac 18$ that three were rolled and so on. Then we are told that $N$ is even.  The a priori probability of that is $\sum_{i=1}^\infty \frac 1{2^{2i}}=\frac 13$, so now the chance that two were rolled is $\frac 34$, the chance that four were rolled is $\frac 3{16}$, and so on.  Now the chance we got $4$ is $\frac 34 P(\text{get 4 given we rolled two dice})+\frac 3{16}P(\text{get 4 given we rolled four dice})$
For b, there are only three choices for $S_N=3$, you can roll a single 3 or roll two dice and get (1,2) or (2,1)
For d, you can ignore the probability distribution on the number of dice, as we are given it.


text:
Q: How to compile GnuTLS for every posix operating system I want to create secure server and client which use GnuTLS for encrypting the network communication. I want to deploy the clients on many Unix operating systems and many Linux distributions. I found that for example in Centos 5 and 6 the versions of GnuTLS which are by default installed are different versions. Maybe in other operating systems the version of GnuTLS is always different. One solutions will be to compile GnuTLS every time from source in order to have always the same version.
Is it possible to compile it into one monolithic(including all dependent libraries) executable program and use it in every Posix operating system?

A: No, because POSIX does not specify binary compatibility, only source compatibility. You'll have to (cross-)compile GNU TLS for every OS you're targeting that does not have the required version.


text:
Q: Angular 2 execute observable with interval Assuming I have the following code:
let sub = Observable.interval(1000).map((x) => {
           let date1= Math.floor(new Date().getTime()/1000);
            this.diff = date2 - date1;
    }).subscribe((x) => {
    });

The observable works great and executed every second, but my problem is that it's watiting one second even when it's the first execute.
I need to execute the observable, then appeal the 1 sec interval. How I can do that with angular 2?

A: This might work (not sure):
let sub = Observable.interval(1000).startWith(0).map((x) => {
    let date1= Math.floor(new Date().getTime()/1000);
        this.diff = date2 - date1;
    }).subscribe((x) => {
});


text:
Q: hostname --fqdn on Azure Ubuntu server has unique domain name ending in .internal.cloudapp.net. How to change to my own domain? I have added my first Azure server for production use on my domain.  Azure assigned a domain name in their DNS, I created a CNAME entry in my domain to forward there.  Works great.
When I enter the command hostname --fqdn, I get myvmname.[someuniquechars].bx.internal.cloudapp.net
Now I am using email on the Ubuntu server, and by default, emails are from myuser@[someuniquechars].bx.internal.cloudapp.net
I am using a smarthost to send all email through my corporate email system, and it doesn't forward emails from users on other domains.
I would like to do whatever is proper and acceptable such that when I type hostname --fqdn I see myvmname.mycompany.com
And when I send emails, the from address is myuser@mycompany.com
I'm a little concerned that if I set the domain to mycompany.com that emails to others @mycompany.com will attempt to get delivered here on this box, rather than sent through the corporate smarthost...
Perhaps I should abandon linking my corporate email suffix to emails generated on this box, and instead create a working subdomain for this machine, complete with valid MX records etc.  So emails sent from a user on this machine would be from user@myvmname.mycompany.com.
I'm moderately capable in Linux, but not a Linux/Ubuntu wiz.  I've done some research but there are several responses I've seen that are either contradictory, or overly simplistic.  Some utilize a tool (resolvconf) that worked in 16.04 but is not installed by default in 18.04, perhaps it conflicts with something else?  It was all confusing enough to ask this question on the forum.

A: I'll answer my own question...
It was actually simple to do - just edit /etc/hosts and add the second line shown below underneath the first.
In this example, the host name is now "myservername" and the fqdn for the server is "myservername.mydomain.com"
When using sendmail, sending an email from user1, the from address becomes "user1@myservername.mydomail.com"
This actually resolved the issue I had. It would be possible to send mail @mydomain.com (removing the hostname from the email address) using Masquerade features of sendmail, but it turns out I have no need to do so, and it would lead to more complications to deal with.
127.0.0.1 localhost
127.0.0.1 myservername.mydomain.com myservername


text:
Q: subsetting within magrittr pipelines without affecting the overall object Currently the way magrittr's pipes work there's no way to mix vector-level and table-level operations. For example str_sub() only takes a vector, while mutate() only takes a table.
If you want to use both in the same pipeline the only options are splitting up the pipeline or nesting, both of which kind of defeat the point of piping:
##Multiple short operations and assignments:

iris$Species %<>% str_sub(.,1,-3)
iris %<>% mutate(., compliments=str_c("pretty"," ",Species))

##Multiple layers of nested functions

iris%>%mutate(.,
  compliments=str_c(
    "pretty",
    " ",
    str_sub(Species,1,-3)
  )
)

What I want is to do something like the below (non-working) example. The closest approximation I've found is lots of superfluous calls to mutate:
iris %>%
str_sub(.$Species,1,-3) %>%
mutate(., compliments=str_c("pretty"," ",Species))

A: You need to remember that you miss out the first argument of functions in the pipe, so your first example should look like this:
library(magrittr)
library(dplyr)

iris %<>% mutate(Species = str_sub(Species, 1, -3),
                 compliments = str_c("pretty", " ", Species))

head(iris)
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species compliments
#> 1          5.1         3.5          1.4         0.2    seto pretty seto
#> 2          4.9         3.0          1.4         0.2    seto pretty seto
#> 3          4.7         3.2          1.3         0.2    seto pretty seto
#> 4          4.6         3.1          1.5         0.2    seto pretty seto
#> 5          5.0         3.6          1.4         0.2    seto pretty seto
#> 6          5.4         3.9          1.7         0.4    seto pretty seto

(Also, you forgot to capitalize Species!)


text:
Q: Viewing a sequence as a function on the space of positive integers I see the following lines in a book :
" Consider a bounded sequence of real or complex numbers $\{\eta_n\}$. Such a sequence $\{\eta_n\}$ defines a function $x(n) = \{\eta_n\}$ defined on the discrete space $S=\{1,2,3,\dots \}$ "
Does it trying to say that because the sequence is bounded it can define the function. Why is that ? consider the sequence of natural numbers.

A: Every sequence indexed by positive integers is a function on the space of positive integers. This is usually  taken as the definition of what "sequence" means.
As Jeppe Stig Nielsen said, it appears that the authors will need the sequence to be bounded at some stage of the proof. So they assumed it to be bounded right at the beginning. This assumption has nothing to do with the sequence being treated as a function.


text:
Q: How solve this logarithms equation What relationship between a,b and c ?

A: From Lucian's suggestion to transform $\log_a u=\frac{\ln u}{\ln a}$ etc. we find, using $x=\ln a, y=\ln b, z=\ln c$ and cancelling the common $\log u$ factor, that
$$\frac1x+\frac1y+\frac1z-\frac{1}{x+y+z}=0.\tag{1}$$
The left side factors into
$$\frac{(x+y)(x+z)(y+z)}{xyz(x+y+z)}.\tag{2}$$
Now since we are working with $a,b,c$ being the base of logs, we are assuming each is positive and not $1$, so that $x,y,z$ are nonzero. We also know $x+y+z \neq 0$ since it is the log of $abc$ which also appears as a logarithm base in the original equation.
So the top of $(2)$ must be zero, which means some two of the three logs add to zero, which in turn means that at least one of the three possibilities $ab=1,ac=1,bc=1$ must hold. It is then easy to check that on the other hand provided one of the three products is $1$ then the statement holds for all $u$.


text:
Q: Ecto: column v0.availabilites does not exist One of my actions fails with
(Postgrex.Error) ERROR (undefined_column): column v0.availabilites does not exist

Looking in the Phoenix logs, I found the query that generated the error:
[debug] SELECT v0.id, v0.event_id, v0.availabilites, v0.inserted_at, v0.updated_at
FROM votes AS v0 WHERE (v0.event_id IN ($1)) ORDER BY v0.event_id [1] ERROR query=185.8ms

The absurd thing is that the mentioned column exists! Here is the output of psql:
    Table "public.votes"
     Column     |            Type             |                     Modifiers
----------------+-----------------------------+----------------------------------------------------
 id             | integer                     | not null default nextval(votes_id_seq::regclass)
 availabilities | jsonb                       |
 inserted_at    | timestamp without time zone | not null
 updated_at     | timestamp without time zone | not null
 event_id       | integer                     |
Indexes:
    "votes_pkey" PRIMARY KEY, btree (id)
    "votes_event_id_index" btree (event_id)
Foreign-key constraints:
    "votes_event_id_fkey" FOREIGN KEY (event_id) REFERENCES events(id) ON DELETE CASCADE

As you can see, the column is there! Here are the two relevant models:
defmodule LetsPlan.Vote do
  use LetsPlan.Web, :model

  schema "votes" do
    belongs_to :event, LetsPlan.Event
    embeds_many :availabilites, LetsPlan.Availability

    timestamps
  end

  @required_fields ~w(availabilites event_id)
  @optional_fields ~w()

  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
  end
end

defmodule LetsPlan.Availability do
  use LetsPlan.Web, :model

  embedded_schema do
    field :from, Ecto.Date
    field :to, Ecto.Date
  end
end

A: You have a typo:
embeds_many :availabilites, LetsPlan.Availability

Should be:
embeds_many :availabilities, LetsPlan.Availability


text:
Q: How can I display UTF-8 characters in knitr chunk outputs? In short, my issue is that I have custom classes which print nicely in the RStudio console, but look horrible in R Markdown since special characters are shown as UTF8 codes. As an example, in the RStudio console you get this behaviour:
cat("\U2713")
#> ✓

Whereas, rendering this using knitr you get:
---
title: "test"
output: html_document
---

```{r}
cat("\U2713")
```

Is there a way to effectively get the same behaviour in knitr chunk outputs as in the RStudio console? Including the inline code `r "\U2713"` in markdown documents correctly renders as '✓', so I feel like this should be easy to achieve.


text:
Q: Tensorflow distributed inference I have a large model (GPT-J 6B) and two 16G GPUs (V100 with no NVLink). I would like to do inference (generation). GPT-J needs 24G memory, so I need to split the model across my two GPUs.
For me, simplicity is much more important than maximizing utilization/throughput.
What is the easiest way to distribute the network?  Is it possible to put first half of the network on one GPU and the second half on the other? (pipeline-parallel essentially)


text:
Q: A way to have a static backgound in an Android Activity Is there a way to have an Activity with a background which can't rotate, but where its children can rotate?
By exemple, I have a relativeLayout with an image background (l1), on this relative layout I have an other relative layout (l2) which contain TextViews, ...
If I'm in Landscape and then I switch in Portrait, I just want l2 rotate with the changement Landscape->Portrait.

A: to rotate a view you can use rotate animation:
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <rotate android:fromDegrees="0"
        android:toDegrees="360"
        android:pivotX="50%"
        android:pivotY="50%"
        android:duration="600"
        android:repeatCount="infinite"
        android:interpolator="@android:anim/cycle_interpolator"/>

</set>


text:
Q: Area level security for asp.net mvc I know it is possible to decorate a controller with the Authorize attribute to control access, what I don't know is the accepted or proper way to enforce security across all the controllers/views in an Area.
Is there something in web.config, area registration or some other place to apply authorization security?

A: A convenient way is to create a new base class
[Authorize]
public abstract class AuthorizeBaseController :  Controller
{
}

and make sure that all of your controllers for which you require authorization (in your case, everything in the area that you're concerned about) descend from AuthorizeBaseController.
public class HomeController : AuthorizeBaseController
{
  public ActionResult Index()
  {
    return View();
  }
}

The [Authorize] attribute should affect all of the descendents of the new base class.
Edit The issue that I have with using the <location path="" > approach is that, since the routing engine makes it's possible for any route to call any controller, setting authorization based on the url (and thus a specific route) instead of the controller actions makes it possible to call a controller that should be protected and skip the authorization. That wasn't an issue in webforms since a page was a page (and not a method call), but the separation between page/path and code in MVC makes this a huge security hole.

A: The only safe way of doing this in an MVC application is to do what David suggests - attributing a base controller and having all controllers in the area subclass that base controller.
Using a <location> tag for authorization in MVC will open security holes in your application.  You're not interested in securing URLs or routes.  You want to secure the controllers themselves, since they're the actual resources you're trying to protect.  Therefore the protections need to be placed directly on the controllers.
Furthermore, remember that an area is really just a fancy way of grouping routes, not controllers.  Trying to use fancy logic to detect the current area and infer authorization settings will also open security holes in your application.

A: As was already suggested, you can make use of the <location /> element in your web.config. Otherwise, you can use a base controller class per-area and decorate that with the AuthorizeAttribute so that all controllers which inherit from it are also filtered.

A: you can always use
<location path="" >
<system.web>
<authorization>
deny or allow
</authorization>
</system.web>
</location>


text:
Q: Use Frege List from Java code I would like to understand how Frege List works and how is it possible to use it from Java. While I downloaded the Frege compiler code, I found difficult to understand what a Frege List is from the Frege code.
Doing some tests I saw that a Frege List is an instance of the TList class in Java with a special method, called _Cons(), that returns a DCons object. DCons is, as expected, a pair where the first element of the pair corresponds to the head of the list while the second element is the tail, thus another TList. When _Cons() is called on an empty lists, the return value is null. Therefore, to implement a Java iterator over Frege TList, one could write:
public class TListIterator implements Iterator<Object> {
    DCons elem;
    public TListIterator(TList list) {
      this.elem = list._Cons();
    }

    @Override
    public boolean hasNext() {
      return this.elem != null;
    }

    @Override
    public Object next() {
      final Object head = Delayed.<Object>forced( this.elem.mem1 );
      this.elem = this.elem.mem2.<TList>forced()._Cons();
      return head;
    }

    @Override
    public void remove() {
      throw new RuntimeException( "Remove is not implemented" );
    }
}

My questions are:

*

*Is my explanation of TList correct?

*Is TListIterator correct?

*where can I find more informations on what TList, DList and DCons are in the Frege compiler source code? Are they documented?

*A more generic question on best practices in Frege: when you want Java code to use a Frege value, is it better to return Java "standard" Objects from Frege code or is it better to directly use Frege classes from Java? My opinion is that the former is easier to write than the latter but has a little conversion overhead. For instance, a TListIterator can always be avoided by converting the TList into a Java LinkedList from Frege.

A: First of all, the ultimate guide for calling into Frege from Java is this wiki page.
It explains, among others, how frege data declarations appear in Java code.
The only special thing about lists is that there is no explicit Frege declaration of it anywhere, but we can assume that it looks like:
data List a = List | Cons a (List a)

Note that the identifier List after the equal sign is the constructor for empty lists, usually called Nil. The reason that it is called List (the same as the type) is because the routine for mangling frege names into valid java names translates [] into List. And in Frege source code we use [] as the type name and the constructor name as well.
Here is the outline of the Java code corresponding to the above:
public interface TList extends frege.runtime.Value, frege.runtime.Lazy {
  public TList.DCons _Cons() ;
  public TList.DList _List() ;
  final public static class DCons extends frege.runtime.Algebraic implements TList {
    private DCons(final java.lang.Object arg$1, final frege.runtime.Lazy arg$2) {
      mem1 = arg$1; mem2 = arg$2;
    }
    final public static TList mk(final java.lang.Object arg$1, final frege.runtime.Lazy arg$2) {
      return new DCons(arg$1, arg$2);
    }
    final public DCons _Cons() { return this; }
    final public TList.DList _List() { return null; }
    final public java.lang.Object mem1 ;
    final public frege.runtime.Lazy mem2 ;
  }
  final public static class DList extends frege.runtime.Algebraic implements TList {
    private DList() {}
    final public static TList mk() { return it; }
    final public static DList it = new DList();
    final public DList _List() { return this;}
    final public TList.DCons _Cons() { return null; }
  }
}

As you see, the overall type is an interface TList. The only thing you can do with a list is to check the variant, for this we have the methods _List() and _Cons(). As you correctly observed, _Cons() returns null for the empty list, and a TLIst.DCons instance for a non-empty list. From there you can extract the head (mem1) and the tail (mem2).
As far as I can see, your list iterator should work fine.
Observe the simple encoding to avoid duplicate names in Java:

*

*Frege type Foo gets the name TFoo in Java.

*Frege data constructor Bar gets the name DBar

*The method that checks if we have a DBar is _Bar. (Note that there is no explicit field that encodes the constructor, this way we use the JVM object header for our purpose where this is encoded anyway)

The naming is, of course, a bit cryptic at first sight. But it is also not exactly intended for the average user. In fact, I didn't think that calling Frege from Java would be interesting at all for anyone. But now I think differently, and we are designing a way to make it possible to implement a Java interface in Frege (it looks like this would serve your purpose here also).
For your last question, I'd say it depends. It is surely the best if you can return just int or double or string. If that doesn't work and you need a list, then your approach with a custom Iterator is preferrable, IMHO. The alternative would be to create a Java List, but this is not pure because List would have to be declared mutable in Frege. In addition, you would be wasting space by effectively duplicating the list.
Yet another possibility would be to return an Array. For example, as you can see in the REPL, the following
foo a b c = arrayFromList [a,b,c] :: JArray Int

would get a signature like:
final public static int[] foo(...


text:
Q: what is not making that my code render the collection? I'm having a hard time trying to figre out what's wong with my code?
the thing that i'm tryng to make is get a collection o models and display them
here are my models
var MessageModel = Backbone.Model.extend({
  defaults : {
    id: "",
    from:"",
    titleMessage:"",
    bodyMessage:"",
    bodyMessageTrim:""
  }
});

My Collection
var MessageListCollection = Backbone.Collection.extend({
  url: '../js/dataDummy/populateJsonMessages.json',
  model: MessageModel
});

My Views
var MessageListItemView = Backbone.View.extend({//view for a row in the message list
  template: _.template($('#tpl-message-item-list').html()),
  render: function(eventName){
    this.$el.html(this.template(this.model.toJSON() ));
    return this;
  },
});

var MessageListView =  Backbone.View.extend({//view por all messages listed
  className:'messages',
  render: function(){
    this.collection.each(function(model){
      var msgListAll = new MessageListItemView({model:model});
      console.log(msgListAll.el);
      this.$el.append(msgListAll.render().el);
    }, this);
    return this;
});

Finally my Routes
//global model variables so i can interact with the different views
var myMessageModelAction = new MessageModel();//whole message information
var myMessageListAction = new MessageListCollection();//all the messages to be listed

var AppRouter = Backbone.Router.extend({
  routes:{
    "messages": "messagesList"
  },
  messagesList: function(){
    var myMessageList = new MessageListCollection();
    myMessageList.fetch();
    console.log(myMessageList);
    var myMessageListView = new MessageListView({collection:myMessageList});
    console.log(myMessageListView);
    myMessageListView.render();
    console.log("dame esto");
    console.log(myMessageListView.el);
    $('#rendered').html(myMessageListView.render().el);
  }
});
var appRouter = new AppRouter();
Backbone.history.start();

The File that is been called inside the collection code is just a json plain text but if it helps here it is
[
  {"id": "1", "from":"user1", "titleMessage":"Welcome to the Team", "bodyMessage":"Congratulations you passed the selection tests", "bodyMessageTrim": "Congratulations you passed..."},
  {"id": "2", "from":"user2", "titleMessage":"First Task", "bodyMessage":"Hello you have to make some changes in the UI", "bodyMessageTrim": "Hello you have to..."},
  {"id": "3", "from":"user2", "titleMessage":"Re:Welcome to the Team", "bodyMessage":"No problem if it's anything you might need just let me know", "bodyMessageTrim": "No problem if it's..."},
  {"id": "4", "from":"user2", "titleMessage":"Re:First Task", "bodyMessage":"Ok i am going to talk to the design team to give you all the assets", "bodyMessageTrim": "Ok i am going to talk..."},
  {"id": "5", "from":"user2", "titleMessage":"Re:Re:First Tak", "bodyMessage":"Ok that is it great work", "bodyMessageTrim": "Ok that is it..."},
  {"id": "6", "from":"user1", "titleMessage":"Meeting Tomorrow", "bodyMessage":"Hi this is just a notice that tomorrow we will have a meet with all new members", "bodyMessageTrim": "Hi this is just a..."}
]

The index looks like this
<!DOCTYPE HTML>

      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
      <title>test</title>
      <link rel="stylesheet" href="../assets/bootstrap.min.css">
      <link rel="stylesheet" href="../assets/index.css">

Looks like you are in the wrong place run now to a safe place

Any help is good due i'm lost and i have like 3 days playing with backbone
and all that i'm having in response is a blank screen where it should be loaded my data.
Also the collections is reached and all the data is in place just the problem is the render of it

A: The reason is that Backbone View, by default, expects an el parameter when you initialize it. meaning the render will write the stuff inside that el.
if you already have some div in html page, then you can initialize backbone view like this:
var messageItemView=new MessageItemView({model:model,el:'#somediv'});

Then when render, it will write to that div.
However, it looks like you are creating a view without an element in the page, which makes sence if you do render().el, this will return the html text, and you append to main html.
while this makes sense, the backbone constructor does not know this. if you see this fiddle, you can see, after you initialize the MessageListItemView, the $el is null. It needs to be constructed before you do
this.$el.html(xxxx);

A hacky fix is to add a
render: function(eventName){
    this.$el=$(this.el);// this create the $el element;
    this.$el.html(this.template(this.model.toJSON() ));
    return this;
},

A more standard is to do it by overwrite the initialize function and do setElement();
Same thing needs to be done for MessageListView too

A: You are calling colleciton.fetch but not waiting for it to get data before you create collectionView.
var def = myMessageList.fetch(); return  a deferred. def.done(function(){ /* rest  of the code here */}) should fix the problem.


text:
Q: JPA merge is inserting instead of updating I have a database with a field NAME and I need to upload a picture as blob type to a field PICTURE on every entity whose NAME is equal to the file name. However, upon running the code creates a bunch of new entities with duplicated NAME fields and PICTURE fields.
Here is my code:
Main:
public static void main(String[] args) {
    File currentDir = new File("C:\\Users\\luccaskammer\\Desktop\\Imagens\\"); // Define o diretorio a ser lido
    displayDirectoryContents(currentDir);
}

public static void displayDirectoryContents(File dir) {
    try {

        ImagensParaDBController contr = new ImagensParaDBController();
        File[] files = dir.listFiles();
        DeletePng del = new DeletePng();
        //ConvertData conv = new ConvertData();

        for (File file: files) {

            ImagensParaBD img = new ImagensParaBD();
            ImagensParaBD name = new ImagensParaBD();
            ImagensParaBD picture = new ImagensParaBD();

            if (file.isDirectory())
            {
                System.out.println("directory:" + file.getCanonicalPath());
                displayDirectoryContents(file);
            }

            else if (file.isFile()) {
                System.out.println("     file:" + file.getCanonicalPath());
                img.setName(del.deletePng(file.getName()));
                java.nio.file.Path filelocation = Paths.get(file.getCanonicalPath());
                img.setPicture(Files.readAllBytes(filelocation));
                contr.insertImageDB(img, picture, name);
            }

            else {
                System.out.println("invalid");
            }
        }

        contr.disconnect();

    }
    catch(IOException e) {}
}

Bean
@Entity
@Table(name = "planegeo")

public class ImagensParaBD implements Serializable {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    //private String pathFolder;
    private String name;@Lob
    private byte[] picture;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public byte[] getPicture() {
        return picture;
    }

    public void setPicture(byte[] picture) {
        this.picture = picture;
    }
}

Controller:
public class ImagensParaDBController {

    EntityManagerFactory mf = Persistence.createEntityManagerFactory("mySQLPU");
    EntityManager em = mf.createEntityManager();

    public void insertImageDB(ImagensParaBD img, ImagensParaBD name, ImagensParaBD picture) {

        em.getTransaction().begin();
        em.merge(img);
        em.getTransaction().commit();

    }

    public void disconnect() {

        em.close();
    }

    public void insertImageDB(ImagensParaBD img) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}

A: The problem is you create new instances. Instead you have to retrieve from DB all the ImagensParaBD  where name=required.
Your newly created instances have no id so hibernate just inserts them.
List<ImagensParaBD> all = em.createQuery("Select a From ImagensParaBD a where name=:name",
ImagensParaBD.class)
.setParameter("name", theNameTOFind)
.getResultList();

and then iterate the instances adding the info and merging them

A: JPA will try to find database row object from ID.
if the your Id is same as Database ID the only JPA merge the row.
Here your are passing only picture object.
So first Try to find object from database.
If it exist in database then fetch ID and setID in your object.
I will work.
Sample code:
Query queryName= em.createQuery(from table_name where picture = :picture);
queryName.setParameter("picture",your picture Object);

list<ImagensParaBD> result = queryName.getResultList();
ImagensParaBD imagensParaBD = new ImagensParaBD();
imagensParaBD = result.get(0);
em.merge(imagensParaBD);


text:
Q: Why cannot delete a container with lock immutable policy using Powershell but it is allowed from azure portal? I have a container with locked immutable policy:

There is already no any blobs within this container. I tried to delete this container with below powershell command:
Remove-AzStorageContainer -Name $containerName -Force

But got below error:
The requested operation is not allowed as the container has a locked immutability policy. HTTP Status Code: 409

However, I can delete this container from azure portal successfully.
My question is, why I can delete from portal but cannot using powershell? Is there a way to automatic remove the container with locked immutable policy?

A: Storage accounts can be interacted with in two different ways - via the data plane REST API (ie. myaccount.blob.core.windows.net) and through ARM (ie. management.azure.com) via the Storage Resource Provider.
The Powershell cmdlets in the form of xxx-AzStoragexxx use data plane.  The Powershell cmdlets in the form of xxx-AzRmStoragexxx use ARM.
Managing immutable policies must be done through ARM rather than through the data plane.  When interacting with storage accounts via the portal you are using ARM so it works as you would expect.  With Powershell, in order to delete a container that has an immutable policy, you must use the AzRmStorage cmdlets.
To programmatically delete a container with an immutable policy you first have to delete all blobs in the container, then use one of the following:

*

*Powershell: Remove-AzRmStorageContainer

*CLI: az storage container-rm delete

*REST API: https://learn.microsoft.com/en-us/rest/api/storagerp/blob-containers/delete?tabs=HTTP

A: Powershell can also delete container with management plane cmdlet:
login Azure account, not needed if you have done so before
Connect-AzAccount

Remove container
Remove-AzRmStorageContainer -ResourceGroupName $rgname -StorageAccountName $accountName -Name $containerName

You may also refer to the suggestion mentioned in this thread and let me know the status of the issue
Note: Please make sure you are  using the control plane cmdlet "Remove-AzRmStorageContainer" to delete the share .
If still fail, please add "-debug" and share the debug log to investigate. (hide if any credential.)

A: *

*As per this MSFT document, Call the Set-AzRmStorageContainerImmutabilityPolicy command, specifying the retention interval in days, to set up a time-based retention policy on a container with powershell. Make sure  to substitute your own values for the placeholder values in the angle brackets:

Set-AzRmStorageContainerImmutabilityPolicy -ResourceGroupName <resource-group> `
    -StorageAccountName <storage-account> `
    -ContainerName <container> `
    -ImmutabilityPeriod 10

*

*An unlocked time-based retention policy can be changed to change the retention period's length or allow more writes to append blobs to the container. An unlocked policy can also be deleted.

*A time-based retention policy can be locked after testing is complete. In accordance with SEC 17a-4(f) , a locked insurance is compliant. A locked policy's retention period may be increased up to five times, but it cannot be decreased.

*Once a policy has been locked, it cannot be deleted. However, after the retention period has passed, you can delete the blob.

References:

*

*Delete containers based on container name prefix

*Blob Containers - Delete Immutability Policy


text:
Q: Enable button only if text is filled in (NO SPACES) I've looked around for an answer to my question, but all the solutions I have found do not take into account that spaces also work as input.
I have a join function, and the button shouldn't be enabled if a user only enters space. It should need actual text. Anyone has a solution to this?
Here's my function:
$("#join").click(function(){
        var name = $("#name").val();
        if (name != "") {
            socket.emit("join", name);
            $("#login").detach();
            $("#UsersOnline").show();
            $("#msg").show();
            $("#messaging").show();
            $("#msg").focus();
            ready = true;
        }

A: you could use jquery trim()
var name = $.trim($("#name").val());

https://api.jquery.com/jQuery.trim/
EDIT:
As @David Thomas pointed out, we can also use String.prototype.trim()
var name = $("#name").val().trim();

function updateResult() {
  var before = $("#name").val().replace(/\s/g,'SPACE');
  var name = $("#name").val().trim();

   $('#result').text('Before:' + before + "\nAfter:" + name);

}

$(document).ready(function(){

  updateResult();

  $('body').on('keyup','#name',function(){

    updateResult();

  });

});

By default value i left left a space for the name

Name : <input type="text" id="name" value=" ">

Value of name :
empty


text:
Q: Tabular, parbox, vertical alignment What i want to achieve is really simple:
I want to be able to align cell content at the top (which is the default behavior of tabular) while being able to manually break lines (and anything you could normally do in a paragraph environment). For instance:

I would expect this to work:
\begin{tabular}{|r|l|}
    \hline
    \parbox{3cm}{\raggedleft First Line\\SecondLine} &
    \parbox{5cm}{\textbf{First line goes here}\\
                 Second line would be here\\
                 And so on, ...\\
                 ... until the very end.} \\
    \hline
\end{tabular}

However this produces the following result:

The left parbox is vertically centered. During the past two days, I've searched the whole LaTeX community in vain for a solution to this problem. I've come across solutions consisting in the use of raisebox that force you to manually grope for the right difference value depending on the content of the two cells. That is no solution to me. I want this to be automatic as it is in any document editor... I would be very surprised if LaTeX didn't allow this kind of construction!
Regards

A: This is a duplicate of a question posted at LaTeX Community. I'll post the same thing I did there:
\documentclass{article}
\usepackage{array}
\begin{document}
\begin{tabular}{|>{\raggedleft}p{3cm}|>{\raggedright\arraybackslash}p{5cm}|}
\hline
First line\\ Second line
&
\textbf{First line goes here}\newline
Second line would be here\newline
And so on, \ldots \newline
\ldots\ until the very end. \\
\hline
\end{tabular}
\end{document}

But there is more discussion there.

A: You can adjust the inner-text using the optional parameters for parbox
\parbox[position][height][inner-pos]{width}{text}

Here is a minimal example.
\documentclass{article}
\begin{document}
\begin{tabular}{|r|l|}
    \hline
    \parbox[t][][t]{3cm}{\raggedleft First Line\\SecondLine} &
    \parbox[t][][t]{5cm}{\textbf{First line goes here}\\
                 Second line would be here\\
                 And so on, ...\\
                 ... until the very end.} \\
    \hline
\end{tabular}
\end{document}

You can read more at TUG's LaTeX tutorial

A: \documentclass{article}
\usepackage{array,ragged2e}

\begin{document}
\begin{tabular}{|>{\RaggedLeft}p{3cm}|>{\RaggedRight}p{5cm}|}\hline
 First Line\newline
 SecondLine
&
 \textbf{First line goes here}\newline
  Second line would be here\newline
  And so on, ...\newline
  ... until the very end. \tabularnewline\hline
\end{tabular}
\end{document}


text:
Q: How to handle this thread? In My application there is one thread running in activity A while it is call. Now i am going to another activity B with doing nothing to that thread.
There are also another thread on activity B.
Now after finishing on activity on activity B. I come back to the activity A.
At that time i got error that the thread on activity A is already running.
So, what should i have to do to handle this error ???
Every time my application get crashed while i come back from activity B to A.
Thanks.
In this Error log Drawing surface is my Activity A as said above.
Error Log:
11-10 15:08:24.730: ERROR/AndroidRuntime(1145): FATAL EXCEPTION: main
11-10 15:08:24.730: ERROR/AndroidRuntime(1145): java.lang.IllegalThreadStateException: Thread already started.
11-10 15:08:24.730: ERROR/AndroidRuntime(1145):     at java.lang.Thread.start(Thread.java:1322)
11-10 15:08:24.730: ERROR/AndroidRuntime(1145):     at com.example.drawing.DrawingSurface.surfaceCreated(DrawingSurface.java:113)
11-10 15:08:24.730: ERROR/AndroidRuntime(1145):     at android.view.SurfaceView.updateWindow(SurfaceView.java:532)
11-10 15:08:24.730: ERROR/AndroidRuntime(1145):     at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:206)
11-10 15:08:24.730: ERROR/AndroidRuntime(1145):     at android.view.View.dispatchWindowVisibilityChanged(View.java:3891)
11-10 15:08:24.730: ERROR/AndroidRuntime(1145):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:719)
11-10 15:08:24.730: ERROR/AndroidRuntime(1145):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:719)
11-10 15:08:24.730: ERROR/AndroidRuntime(1145):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:719)
11-10 15:08:24.730: ERROR/AndroidRuntime(1145):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:719)
11-10 15:08:24.730: ERROR/AndroidRuntime(1145):     at android.view.ViewRoot.performTraversals(ViewRoot.java:744)
11-10 15:08:24.730: ERROR/AndroidRuntime(1145):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
11-10 15:08:24.730: ERROR/AndroidRuntime(1145):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-10 15:08:24.730: ERROR/AndroidRuntime(1145):     at android.os.Looper.loop(Looper.java:123)
11-10 15:08:24.730: ERROR/AndroidRuntime(1145):     at android.app.ActivityThread.main(ActivityThread.java:4627)
11-10 15:08:24.730: ERROR/AndroidRuntime(1145):     at java.lang.reflect.Method.invokeNative(Native Method)
11-10 15:08:24.730: ERROR/AndroidRuntime(1145):     at java.lang.reflect.Method.invoke(Method.java:521)
11-10 15:08:24.730: ERROR/AndroidRuntime(1145):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-10 15:08:24.730: ERROR/AndroidRuntime(1145):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-10 15:08:24.730: ERROR/AndroidRuntime(1145):     at dalvik.system.NativeStart.main(Native Method)

DrawingSurface class where i got Error:
public class DrawingSurface extends SurfaceView implements SurfaceHolder.Callback {
private Boolean _run;
protected DrawThread thread;
public Canvas canvas = null;
private CommandManager commandManager;
//private Bitmap myBitmap;
private Bitmap mBitmap;

public DrawingSurface(Context context, AttributeSet attrs) {
    super(context, attrs);

    getHolder().addCallback(this);

    commandManager = new CommandManager();
    thread = new DrawThread(getHolder());
}

class DrawThread extends Thread{
    private SurfaceHolder mSurfaceHolder;

    public DrawThread(SurfaceHolder surfaceHolder){
        mSurfaceHolder = surfaceHolder;

    }

    public void setRunning(boolean run) {
        _run = run;
    }

    @Override
    public void run() {
        //Canvas canvas = null;
        while (_run){

            try{
                canvas = mSurfaceHolder.lockCanvas(null);
                if(mBitmap == null){
                    mBitmap =  Bitmap.createBitmap (1, 1, Bitmap.Config.ARGB_8888);
                }

                final Canvas c = new Canvas (mBitmap);
                //canvas.drawColor(0, PorterDuff.Mode.CLEAR);
                c.drawColor(0, PorterDuff.Mode.CLEAR);
                canvas.drawColor(Color.WHITE);
//             Bitmap kangoo =   BitmapFactory.decodeResource(getResources(),R.drawable.icon);

                if(!(DrawingActivity.imagePath==null)){
                    c.drawBitmap(DrawingActivity.mBitmap, 0, 0, null);
                }
                commandManager.executeAll(c);
                canvas.drawBitmap (mBitmap, 0,  0,null);
            } finally {

                mSurfaceHolder.unlockCanvasAndPost(canvas);
            }
        }

    }
}

public void addDrawingPath (DrawingPath drawingPath){
    commandManager.addCommand(drawingPath);
}

public boolean hasMoreRedo(){
    return commandManager.hasMoreRedo();
}

public void redo(){
    commandManager.redo();
}

public void undo(){
    commandManager.undo();
}

public boolean hasMoreUndo(){
    return commandManager.hasMoreRedo();
}

public Bitmap getBitmap(){
    return mBitmap;
}

public void surfaceChanged(SurfaceHolder holder, int format, int width,  int height) {
    // TODO Auto-generated method stub
    mBitmap =  Bitmap.createBitmap (width, height, Bitmap.Config.ARGB_8888);;
}

public void surfaceCreated(SurfaceHolder holder) {
    // TODO Auto-generated method stub
        thread.setRunning(true);
        thread.start(); // error at this line
        if(!thread.isAlive())
             thread.start();
}

public void surfaceDestroyed(SurfaceHolder holder) {
    // TODO Auto-generated method stub
    boolean retry = true;
    thread.setRunning(false);
    while (retry) {
        try {
            thread.join();
            retry = false;
        } catch (InterruptedException e) {
            // we will try it again and again...
        }
    }
}

}

A: Instead of using Thread and Runnable, if you go with AsyncTask, they will close themselves automatically after you navigate away from an activity.
or if you want to use Thread only, you'll have to use t.interrupt() to stop any running Thread t before moving away from the activity.
so, I guess put t.interrupt() in onPause() method of the activity to stop the Thread
Edit: this line is redundunt
if(!thread.isAlive())
             thread.start();

and i dont understand what you are trying to do with this,
thread.setRunning(true);

this might be creating some problems remove this and try again
i.e. try this
public void surfaceCreated(SurfaceHolder holder) {
    // TODO Auto-generated method stub
        thread.start(); // error at this line
}

A: This won't work (most of the time -> race condition):
   thread.start(); // error at this line
   if(!thread.isAlive()) thread.start();

Don't do that. A thread may only be started once and there is definitely no reason to re-try starting it.
thread.start(); is really all you will ever need to start a thread.
EDIT:
while (retry) {
  thread.join();
  retry = false;
}

does not make any sense. Just join() and possibly relay the interruption to your thread.


text:
Q: Error setting variable to the length of an array in bash I have the snippet below in a larger script to basically take my balances out of ledger into two arrays so I can print them the way I want to view them.
#!/bin/bash
assets=("assets:checking" "assets:google wallet" "assets:savings" "assets:cash")
assets-bal=()

num=${#assets[@]}
for $i in {0..${num}}
do
  read -a tmp <<< `ledger -f finances balance "${assets[${i}]}"`
  assets-bal[${i}]=tmp[0]
  echo "${assets[${i}]}   ${assets-bal[${i}]}"
done

Every time I try runnning the script I get the error:
syntax error near unexpected token `num=${#assets[@]}'
`num=${#assets[@]}'

From my searching, there should be nothing wrong with that line and I just keep coming up empty trying to find a reason why it won't work.
Can anybody point out where I'm wrong?

A: The problem is probably
assets-bal=()

Variable names must not contain a dash. You are limited to underscores.
I don't know how bash interprets assets-bal=() but it considers that an incomplete command which has to be finished on another line. Just run that line in a shell to see what I mean.

A: Brace expansion does not support variables since it is done before variables are expanded. Use seq instead, if you absolutely must:
for i in $(seq 0 ${num})

Or (much more preferable) get the array keys directly:
for i in "${!assets[@]}"

(Also, for i in .., not for $i in ...)

Hauke Laging got the first error. Once you fix that, this will probably be the next error.

And instead of
read -a tmp <<< `ledger -f finances balance "${assets[${i}]}"`

Consider using:
tmp=($(ledger -f finances balance "${assets[${i}]}"))

The () outside the command substitution converts it into an array.

A: You have a syntax ERROR : you can't use a - in the name of a variable.
assets-bal

should be replaced by
 assets_bal

For the loop, you can use a for loop in the C style :
for ((i=0; i<${num}; i++)); do

A: I think maybe you're relying a little too heavily on array types there - and variables in general. If I understand what you're doing up there correctly, I suspect this should do much of the same:
for a in checking google\ wallet savings cash
do  a=assets:$a
    printf "$a\t%d\n" "$(ledger -f finances balance "$a")"
done

That could probably be improved upon a great deal by somehow getting a reading of all values for $a above at once in a stream and then arranging it with a scripted editor like sed or similar. In general a shell variable is a pretty awful place to keep information of any value - or of any significant size for that matter. A shell variable should store only enough information to make retrieving actual information from a file more manageable.
Written as a shell function, the above might look like:
assets() if   [ "$#" -gt 0 ]
         then while [ "$#" -gt 0 ]
              do    printf "assets:%s\t%d\n" "$1" "$(
                    ledger -f finances balance "assets:$1")"
              shift;done
         else assets checking google\ wallet savings cash
         fi

...and could be called like:
assets

...for your default list, or like...
assets cash checking

...for a different list without every setting a single shell variable value at all.


text:
Q: Fast up Nested Loop I am researching a topic on inflation and currently have the problem that part of my code takes over 20 hours to complete because I have a nested loop.
The code looks like this:
avg_timeseries <- function(start_date, end_date, k){
  start_date = microdata_sce$survey_date[i]
  end_date = microdata_sce$prev_survey[i]
  mean(subset(topictimeseries, survey_date <= start_date & survey_date >= end_date)[[k]])
}

start.time <- Sys.time()

for (i in 1:nrow(microdata_sce)){
  for(k in 2:ncol(topictimeseries)){
    microdata_sce[[i, paste(k-1, 'topic', sep="_")]] <- avg_timeseries(start_date, end_date, k)
  }

}
end.time <- Sys.time()
time.taken <- end.time - start.time
time.taken

What do I want/what do I have:
I have a panel dataset (microdata_sce) with a total of 130,000 observations. Each userid has a start date and an end date, which are the survey date and the last survey date respectively. I want to take both dates and calculate the average between the two dates separately for each column in the timeseries dataframe (70 columns). Afterwards, the average between the two dates is to be attached to the microdata_sce data set as a column.
My idea was to loop through each row, take the survey data, create a subset from which the average is calculated. I loop through the k different time series.
Unfortunately, the code takes an eternity. Is there a way to speed this up using apply?
Thank you!
Kind regards


text:
Q: How to change Dimensions of an SwiftUI Default Button on MacOS? I want to change the behaviour of an SwiftUI Button so that two of them automatic get the same size.
But somehow I always only affect an ParentView of my View.
import SwiftUI

struct ContentView: View {
    var body: some View {
        HStack {
            Button("ABC", action: {return}).frame(maxWidth: .infinity).background(Color.green)
            Button("EFCHHSJFJSJDNJS", action: {return}).buttonStyle(MorePaddingButtonStyle()).frame(maxWidth: .infinity).background(Color.yellow)
        }.frame(maxWidth: .infinity)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

And it should be sized like this:

The example is located here in an GitHub repo.
Hope someone can help me to resize them with their background/shape (most likely for the default Button).

A: Use button with label
struct ContentView: View {
    var body: some View {
        HStack {
            Button(action: { print("ABC") }) {
                Text("ABC").frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
            }.buttonStyle(PlainButtonStyle()).background(Color.green)

            Button(action: { print("EFCHHSJFJSJDNJS") }) {
                Text("EFCHHSJFJSJDNJS").frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
            }.buttonStyle(MorePaddingButtonStyle()).background(Color.yellow)
        }
    }
}

The default button style can not set the width. It automatically set the width according to the button contains. So use PlayStyle or your own MorePaddingButtonStyle.


text:
Q: Google Script to Copy Cell to Another Cell I am looking for a script that only runs when a cell in column 7 is edited.  There are multiple sheets so I want to specify which sheet it runs on.  When the user edits a cell in column 7, there is a popup asking a Yes/No questions.  If they answer No, the script runs.  I need the script to copy the data in that cell to column 9.  If they answer Yes, the script does not run.  Here is what I have so far...I can get the popup to work; however, I do not know how to get the "copyData" formula to work and I am hoping for help on that.  Thanks!
function onEdit2(){
  var s = SpreadsheetApp.getActiveSheet();
  if( s.getName() == "Current Seniority" ) {
    var r = s.getActiveCell();
    if( r.getColumn() == 7) {
 var ui = SpreadsheetApp.getUi();
 var response = ui.alert('Is employee being placed on leave?',
ui.ButtonSet.YES_NO);
 // Process the user's response.
 if (response == ui.Button.YES) {
   Logger.log('The user clicked "Yes."');
 } else {
      copyData();
   Logger.log('The user clicked "No" or the close button in the dialog\'s title bar.');
 }
    }
  }
}

A: Try this:
function onMyEdit(e) {
  e.source.toast("Entry")
  const sh = e.range.getSheet();
  const ns = ["Current Seniority","Sheet0"];
  const idx = ns.indexOf(sh.getName());
  if (~idx && e.range.columnStart == 7 && e.range.rowStart > 1 && e.value) {
    e.source.toast("Gate");
    let resp = SpreadsheetApp.getUi().alert('Is employee being placed on leave?', SpreadsheetApp.getUi().ButtonSet.YES_NO);
    if (resp == SpreadsheetApp.getUi().Button.NO) {
      //copyData();
      Logger.log(`The user clicked "No" or the close button in the dialog's title bar.`);
    } else {
      Logger.log('The user clicked no')
    }
  }
}

A: Try the following code:
function onEdit2(){
  var s = SpreadsheetApp.getActiveSheet();
  if( s.getName() == "Current Seniority" ) {
    var r = s.getActiveCell();
    if( r.getColumn() == 8) {
      var ui = SpreadsheetApp.getUi();
      var response = ui.alert('Is employee being placed on leave?',
      ui.ButtonSet.YES_NO);
      // Process the user's response.
      if (response == ui.Button.YES) {
        Logger.log('The user clicked "Yes."');
      }
      else {
        copyData(r, s);
        Logger.log('The user clicked "No" or the close button in the dialog\'s title bar.');
      }
    }
  }
}

function copyData(data, ss)
{
  var val = data.getValues();
  var newColumn = ss.getRange(data.getRow(), data.getColumn()+3);
  newColumn.setValue(val);
}

Make sure to add the trigger to the function so it runs on an edit or a change.
This is how it works:

References:

*

*setValue()

*Installable triggers


text:
Q: Is there such a thing as a shared web page library? I have a number of sites that I need to share things with. I have a business core framework library and I can share code with all of my sites using that via nuget. What I need to know is if there is something like this were I can share asp.net pages (aspx) with multiple sites pulled down via a nuget package like my business library is. I want certain pages to be included in all of my sites without having to go and add them each one by one. I would like to just add a nuget package and have them exist in the project. Is this possible?

A: You can either compile pages into an assembly and distribute it via NuGet. See  How do I compile an ASP.NET website into a single DLL file?.
Alternatively you can add those pages as "content" in NuGet and they will get copied into each project. Sample - nuspec contentFiles Example.
You need to decide whether ability to modify files in each project is desired/acceptable - adding files as "content" makes them regular items in a project and hence people can customize them (possibly unintentionally).


text:
Q: Vspackage development, how to get code elements in a file or in a class I can add code to a file by using codeModel.
Now I want to add code elements like variables to a specified class.
So the first thing I need to do is to get the class I want to modify.
Following is my code:
IVsProject project = YHMExtensionHelper.GetSelectedProject();
int found;
uint itemId;
VSDOCUMENTPRIORITY[] pdwPriority = new VSDOCUMENTPRIORITY[1];
project.IsDocumentInProject("TEST.h", out found, pdwPriority, out itemId);
if (found == 0 || itemId == 0)
    return;
Microsoft.VisualStudio.OLE.Interop.IServiceProvider oleSp = null;
project.GetItemContext(itemId, out oleSp);
if (oleSp == null)
   return;
ServiceProvider sp = new ServiceProvider(oleSp);
EnvDTE.ProjectItem item = sp.GetService(typeof(EnvDTE.ProjectItem)) as EnvDTE.ProjectItem;
var codeModel = item.FileCodeModel;
var eles = codeModel.CodeElements;
for (int i = 0; i < eles.Count; i++)
{
    var singleItem = eles.Item(i);
    var str = singleItem.Name;
}

But this doesn't work, I can get the eles.Count, I can't get any item by eles.Item(i).
In TEST.h there are a simple c++ class.
Please tell my how to do.

A: problem solved, I can use to enum all code element in a element.
foreach (CodeElement element in eles)
{
   if(element.Kind == vsCMElement.vsCMElementClass)
   {
      CodeClass cl = element as CodeClass;
      ...
   }
   ...
}


text:
Q: Multiprocessing: AttributeError: 'Imported' object has no attribute '__private_method' I faced with this problem in my work code, so I can't show it. But I wrote some short example, which exactly reproduce error and cuts off redundant logic.
Example have two files: Example.py & ImportedExample.py.
Example.py
from multiprocessing import Process
from ImportedExample import Imported

class Example:
    def __init__(self, number):
        self.imported = Imported(number)

def func(example: Example):
    print(example)

if __name__ == "__main__":
    ex = Example(3)

    p = Process(target=func, args=(ex,))
    p.start()

ImportedExample.py
class Imported:
    def __init__(self, number):
        self.number = number
        self.ref = self.__private_method

    def __private_method(self):
        print(self.number)

And Traceback looks like this:
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File"C:\Python\Python36\lib\multiprocessing\spawn.py", line 105, in spawn_main
exitcode = _main(fd)
  File "C:\Python\Python36\lib\multiprocessing\spawn.py", line 115, in _main
self = reduction.pickle.load(from_parent)
AttributeError: 'Imported' object has no attribute '__private_method'

The main detail is that when I make __private_method() non-private (renaming to private_method()), all works fine.
I don't understand why this happens. Any suggestions?

A: multiprocessing module uses pickle for transferring object between processes.
For an object to be pickable, it has to be accessible by name. Thanks to private name mangling, referenced private methods don't fall in that category.
I suggest making the method protected – that is naming the method with only one leading underscore. From a global point of view, protected methods shoud be treated just as private methods, but they are not subject of name mangling.


text:
Q: JavaFX and CSS Syntax I am trying out JavaFX to see how it is like, but I am having a lot of trouble with the css aspect of it. I know css, but I can;t figure out how JavaFX uses it. For example, if I wanted to style buttons on my page, some online resources say .button{} some say .Button{} and etc. I can't get a consistent basic guide on how todo it. I tried looking at the guide here
http://docs.oracle.com/cd/E17802_01/javafx/javafx/1.3/docs/api/javafx.scene/doc-files/cssref.html
The point being is, there is no guide that explains it clearly that I can find, so could anyone help?

A:
some online resources say .button{} some say .Button{}

CSS is NOT case sensitive. So I don't think .button{} or .Button{} should matter.
When you write:
.button{
-fx-text-fill: rgb(49, 89, 23);
-fx-border-color: rgb(49, 89, 23);
-fx-border-radius: 5;
-fx-padding: 3 6 6 6;
}

you're overriding a style.
The code below will be a custom style:
.custom-button {
-fx-font: 16px "Serif";
-fx-padding: 10;
-fx-background-color: #CCFF99;
}

This tutorial might be helpful. They've created a good CSS, gives look of Metro app. I suggest you use theirs and make changes to it according to your use, instead of creating from scratch.
Here is the Java 8 version of the JavaFX CSS Reference Guide.


text: Q: Can I force to use only one register in register allocation phase in gcc/clang? I am learning about register allocation and want to see the code generated by the compilers in the stress condition. I wonder if there's an option to force them only to use one or two registers to generate code?


text:
Q: How to check only folders inside the folder? I'm trying to find out the proper solution to check only folders inside the folder and read only XML files.
My code:
data= os.listdir('./home/')
for packs in data:
    file=open('./home/' + packs + '/files' + 'data.xml', 'r') #i have 100's of folders inside home
    all_file=file.read()

Output: It reads all the folders as per requirement but I have 3 csv and 2 text files in the folder home. My code is also reading those files and gives an error. I don't want to read those, is there any methods to read only XML files.


text:
Q: Windows Server 2012 R2 in Virtualbox error I'm trying to install Windows Server 2012 R2 on Virtualbox but I get this error all the time:

Proccessor: Intel(R) Core(TM) i5 CPU
System type: 64-bit
ISO file: en_windows_server_2012_x64_dvd_915478.iso

I've tried many things and had no result, I tried on another computer but got the same error.
When creating a new VirtualMachine I used "Windows > Other Windows" and created a new VDI

A: Common problem. You have to activate virtualization in your bios. If doesn't matter if you have a 64 bits CPU if you don't have the virtualization activated. This is an example.


text:
Q: Ext4 for Linux and Fuse with OS X? System: El-Capitan 10.11.5, Macbook Air 2013-Mid, SSD 128 GB. I would like do a new partition in my SSD. Install Ubuntu on it side-by-side with OS X. I have documents which I would like to use by both systems.
Proposal 1 with SSD

*

*OSX in OSX Extended.

*Linux in ext4.

*Use fuse if need files of Linux in OSX. Not sure how well this works.

I am unsure how you can create a symlink from Linux-ext4 to OSX-extended through fuse.
Proposal 2 with SSD + big HD in memory card slot

*

*OS X in OSX Extended.

*Linux in ext4.

*Big HD in ntfs. Both systems should be able to read it. However, possible conflicts with Linux permissions.

How well will symlinks work to 2nd HD from OSX and Linux? Can both systems use ntfs format?
Is there any better format which both systems (Linux and OSX) can use?

How can you initiate ext4 for OS X's Linux partition and use it with OS X?


text:
Q: Storing data from Matlab GUI components I am creating GUI in Matlab. I am using 4 sliders, 4 static texts and axes for plotting. I ran into a problem with storing value from sliders.
I set sliders for default value. When I move one slider, everything plots as supposed. When I  move with another slider, the value from first slider restores to default and value from second set as supposed.
For example I use slider that defines radius of a Cycloid. Then i call for function that set value for slider and then I call for function that plots results.
It looks like this :
% setting slider

slider(1)=uicontrol(container_1,'Style','slider','Min',0.1,'Max',10,'Value',1,'Tag','r');

% setting slider value

set(slider(:),'callback',{@obj.setValue});

% function to set value and store it as obj.r = value

function    setValue(obj,handle,~)
            obj.(handle.Tag)=handle.Value;
            myPlot(obj);
end

This is just a cut piece from whole code. Whole code is in my pasterbin:
https://pastebin.com/XqYYAxRP
Sum up:
What I need is that Value of slider will not restore to default, but will stay after moving with slider.

A: The issue is that you are using a value class (MATLAB's default) rather than a handle class. With the value class, any modifications to the object (in your callback) are not going to be present in other copies of the object since they are independent copies therefore your callback will seem to have no effect. When you use a handle class instead, assignment will create a new reference to the same object and changes will persist across all references.
classdef Cykloida < handle

See a detailed discussion of the two types of classes in the MATLAB documentation


text:
Q: Android: Notification Shows in Delay And Stops Updating When App Closed for 30 Seconds (on OnePlus 8T) Google has its clock app, which includes its stopwatch. I'm currently trying to create in my app a (count-up) timer, or you can call it a stopwatch, that will be able to run in the background, and when it runs in the background I want it to also show a notification, that displays the time it counts and a "Stop" button (all of this happens in google clock app (see here)). For the timer in my app, I'm using a Handler that posts a Runnable, which is posting itself. I'm writing my app in Java.
the code defining the 'timer' (Handler and Runnable):
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
    @Override
    public void run() {
        long millis = System.currentTimeMillis() - startTime;
        seconds = (millis / 1000) + PrefUtil.getTimerSecondsPassed();
        timerHandler.postDelayed(this, 500);
    }
};

my onPause function:
@Override
public void onPause() {
    super.onPause();

    if (timerState == TimerState.Running) {
        timerHandler.removeCallbacks(timerRunnable);
        //TODO: start background timer, show notification
    }

    PrefUtil.setTimerSecondsPassed(seconds);
    PrefUtil.setTimerState(timerState);
}

How can I implement the background service and the notification in my app?
Edit
I've managed to succeed in creating a foreground service that runs my timer, but I have two problems:

*

*When I run the app after something like 5 minutes, the notification shows up in a 10-second delay.

*the notification stops updating after around 30 seconds from the time it starts/resumes (The timer keeps running in the background, but the notification won't keep updating with the timer).

Here's my Services code:
public class TimerService extends Service {

    Long startTime = 0L, seconds = 0L;
    boolean notificationJustStarted = true;
    Handler timerHandler = new Handler();
    Runnable timerRunnable;
    NotificationCompat.Builder timerNotificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID);
    public static final String TIMER_BROADCAST_ID = "TimerBroadcast";
    Intent timerBroadcastIntent = new Intent(TIMER_BROADCAST_ID);

    @Override
    public void onCreate() {
        Log.d(TAG, "onCreate: started service");
        startForeground(1, new NotificationCompat.Builder(this, CHANNEL_ID).setSmallIcon(R.drawable.timer).setContentTitle("Goal In Progress").build());
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String goalName = intent.getStringExtra(PublicMethods.getAppContext().getString(R.string.timer_notification_service_current_goal_extra_name));
        startTime = System.currentTimeMillis();
        notificationJustStarted = true;
        timerRunnable = new Runnable() {
            @Override
            public void run() {
                long millis = System.currentTimeMillis() - startTime;
                seconds = (millis / 1000) + PrefUtil.getTimerSecondsPassed();
                updateNotification(goalName, seconds);
                timerHandler.postDelayed(this, 500);
            }
        };
        timerHandler.postDelayed(timerRunnable, 0);

        return START_STICKY;
    }

    public void updateNotification(String goalName, Long seconds) {
        try {
            if (notificationJustStarted) {
                Intent notificationIntent = new Intent(this, MainActivity.class);
                PendingIntent pendingIntent = PendingIntent.getActivity(this,
                        0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
                timerNotificationBuilder.setContentTitle("Goal In Progress")
                        .setOngoing(true)
                        .setSmallIcon(R.drawable.timer)
                        .setContentIntent(pendingIntent)
                        .setOnlyAlertOnce(true)
                        .setOngoing(true)
                        .setPriority(NotificationCompat.PRIORITY_MAX);
                notificationJustStarted = false;
            }

            timerNotificationBuilder.setContentText(goalName + " is in progress\nthis session's length: " + seconds);

            startForeground(1, timerNotificationBuilder.build());
        } catch (Exception e) {
            Log.d(TAG, "updateNotification: Couldn't display a notification, due to:");
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        timerHandler.removeCallbacks(timerRunnable);
        PrefUtil.setTimerSecondsPassed(seconds);
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

And here is how I start it in my fragment:
private void startTimerService() {
        Intent serviceIntent = new Intent(getContext(), TimerService.class);
        serviceIntent.putExtra(getString(R.string.timer_notification_service_current_goal_extra_name), "*Current Goal Name Here*");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Objects.requireNonNull(getContext()).startForegroundService(serviceIntent);
        }
}

UPDATE
When I run the app on google pixel emulator, I don't face any of the issues listed

A: There are 2 issues. I will try to solve both of them.
First issue

When I run the app after something like 5 minutes, the notification shows up in a 10-second delay.

For this, you need to update the notification with its code. Now, because it takes time to show up, show it in the activity where you start the service and then, pass the notification id to the service using its constructor. Using that id, update it in the service.
Let's hope that solves the first issue.
Second issue

the notification stops updating after around 30 seconds from the time it starts/resumes (The timer keeps running in the background, but the notification won't keep updating with the timer).

To solve that, you can clear the previous notification after 10 seconds by it's id. Then you can make a new random key for the notification( I'd prefer new Random().nextInt()) and then show it. But then you or anyone would say that there is so much sound when a notification comes. Just disable it this way when creating a channel:
notificationChannel.setSound(null, null);

NOTE: You might want to reinstall your app for it to work
If that seems complicated, see this:
Runnable running -> When 10 seconds done from previous notification display -> Clear the notification -> Make a new notification id -> show notification with that id -> Repeat

EDIT

This is the working code for me:
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import java.util.concurrent.TimeUnit;

public class TimerService extends Service {

    Long startTime = 0L, seconds = 0L;
    boolean notificationJustStarted = true;
    Handler timerHandler = new Handler();
    Runnable timerRunnable;
    private final String CHANNEL_ID = "Channel_id";
    NotificationManager mNotificationManager;

    NotificationCompat.Builder timerNotificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID).setContentTitle(CHANNEL_ID);

    @SuppressLint("InlinedApi")
    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(this, "created", Toast.LENGTH_SHORT).show();
        String TAG = "Timer Service";
        Log.d(TAG, "onCreate: started service");
        startForeground(1, new NotificationCompat.Builder(TimerService.this, createChannel()).setContentTitle("Goal In Progress").setPriority(NotificationManager.IMPORTANCE_MAX).build());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String goalName = "Sample Goal";
        Toast.makeText(this, "started", Toast.LENGTH_SHORT).show();
        startTime = System.currentTimeMillis();
        notificationJustStarted = true;
        timerRunnable = new Runnable() {
            @Override
            public void run() {
                long millis = System.currentTimeMillis() - startTime;
                seconds = (millis / 1000) + PrefUtil.getTimerSecondsPassed(TimerService.this);
                updateNotification(goalName, seconds);
                Log.d("timerCount", seconds + "");
                timerHandler.postDelayed(this, 1000);
            }
        };
        timerHandler.postDelayed(timerRunnable, 0);

        return Service.START_STICKY;
    }

    @SuppressLint("NewApi")
    public void updateNotification(String goalName, long seconds) {
        if (notificationJustStarted) {
            Intent notificationIntent = new Intent(this, MainActivity.class);
            @SuppressLint("InlinedApi") PendingIntent pendingIntent = PendingIntent.getActivity(this,
                    0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
            timerNotificationBuilder.setContentTitle("Goal In Progress")
                    .setOngoing(true)
                    .setContentIntent(pendingIntent)
                    .setOnlyAlertOnce(true)
                    .setOngoing(true)
                    .setPriority(NotificationCompat.PRIORITY_MAX)
                    .setSmallIcon(R.drawable.ic_launcher_foreground);
            notificationJustStarted = false;
        }

        long minutes = TimeUnit.SECONDS.toMinutes(seconds);
        String time = minutes + ":" + (seconds - TimeUnit.MINUTES.toSeconds(minutes));

        timerNotificationBuilder.setContentText(goalName + " is in progress\nthis session's length: " + time);

        mNotificationManager.notify(1, timerNotificationBuilder.build());

        startForeground(1, timerNotificationBuilder.build());
    }

    @Override
    public void onDestroy() {
        timerHandler.removeCallbacks(timerRunnable);
        PrefUtil.setTimerSecondsPassed(this, seconds);
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @NonNull
    @TargetApi(26)
    private synchronized String createChannel() {
        mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

        String name = "STOPWATCH";
        int importance = NotificationManager.IMPORTANCE_LOW;

        NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);

        mChannel.setName("Notifications");

        if (mNotificationManager != null) {
            mNotificationManager.createNotificationChannel(mChannel);
        } else {
            stopSelf();
        }

        return CHANNEL_ID;
    }
}

You can also view my repo on this here. It is a complete stop watch app

A: I've found the reason why my notification stops updating after 30 seconds! Apparently,(according to this thread) on some devices running Android versions higher than 9 there are background restrictions.
These restrictions are the ones stopping my notifications from updating after 30 seconds from the moment the app gets closed, or in other words - from the moment they're becoming background activities (even though they are called through startForeground()).

There is no way around this setting. You cannot programmatically disable it. Your only option is to programmatically check if it's enabled using ActivityManager.isBackgroundRestricted() and display a pop-up informing your users on how to disable this setting

Says the user from the accepted answer in the thread.
And so, the issue of the notification not updating as expected is solved. The issue of the delay to show the first notification though remains unsolved, and there's another issue - every time the notification gets updated, the whole notification panel freezes for a second fraction.

A: Solution would work much better, even with enabled battery restrictions, if you will replace recursive postDelayed with scheduleAtFixedRate in your TimerService inside onStartCommand function. Something like this:
        TimerTask timerTaskNotify = new TimerTask() {
            @Override
            public void run() {
                // add a second to the counter
                seconds++;

                //update the notification with that second
                updateNotification(goalName, seconds);

                //Print the seconds
                Log.d("timerCount", seconds + "");

                //Save the seconds passed to shared preferences
                PrefUtil.setTimerSecondsPassed(TimerService.this,seconds);
            }
        };
        Timer timerNotify = new Timer();
        timerNotify.scheduleAtFixedRate(timerTaskNotify, 0, 1000);

P.S. I can update your git repository if you will grant permission)


text:
Q: Navigation menu not working in admin panel of Wordpress My Wordpress menu bar is not working. i am creating a new menu but when i add some pages or categories into the menu it does not get reorder. Please help to sort it out I am using the woo-commerce in which it has given me inbuilt menus that is not getting reorder.

A: I got this bug. this was because of the plugins.
i had installed
1. Rich Tax Description Editor
2. Turns Description field on Taxonomy pages into the full scale Rich Text Editor.
3. Rich Text Widget
That was creating problem in menu. when i deactivated them all i got it back. my menu ordering was working fine.


text:
Q: Inserting a signature automatically into an Outlook Calendar meeting request Is there a way to automatically have a signature inserted into a Microsoft Outlook Calendar request, as one can do with emails?

A: From everything that I've been reading it is not possible.  Why Microsoft has not added this functionality is beyond me.  It's so basic and they already have the format for the email.  All they would have to do is add a check box on the signature creation page so you can select where you want the signature to default.

A: Are you familiar with outlook VBA macros?
You can write a macro in Application_ItemSend function so that it will be triggered every time you hit send button.
In the macro, check if the item type is a calender request and if it is, just insert the signature.

A: Once you have clicked "invite attendees" an option then appears in "insert" to insert a signature. This option does not show before you click "invite attendees"

A: There is an easy alternative. Create a new signature that you need for meetings. When creating a new meeting go to Insert->Signature and select the signature created.

A: I just clicked on the APPS icon along the top next to Scheduling Assistant and panel pops up on the right hand side of the page. Click + New Template, and I added a new template which contains my signature copied from my email and clicked SAVE. Then you just have to select that template and it will populate your message box. Hope that saves you some time trying to figure it out yourself like I just did.

A: To insert the signature you most likely already use for Outlook Email Messages, into a Calendar invite:
When you create a new invite, go to "Insert", then "Signature".  It gives you the option to use an existing signature, or create a new one.
I don't see a way to permanently save that signature, but you can still add it to every appointment fairly easily using the steps I offered.
Hope this helps!


text:
Q: Where does the Module Manager in zf2 gets registered as a Service of the Service Manager? i'm reading the code of Zendframework 2, in order to understand it better. I can't find the place in the code where the Module Manager gets registered in the Service Manager as a service. Any help is much appreciated.
Greetings,
Todor

A: \Zend\Mvc\Application::init() creates the service manager, passing in a ServiceManagerConfig, which by default defines a few factories.
So in a typical \Zend\Mvc\Application, the module manager get wired into the ServiceManager via that factory.  The factory is responsible for creating the ModuleManager the first time it's requested.


text:
Q: Накапливаются ли полученные данные в сокете? Накапливаются ли где-то данные до вызова recv()? То есть если это сервер и после успешной установки соединения клиент шлет ему данные, но сервер не сразу вызывает recv(), а с определенной задержкой, то какие данные получит в итоге буфер, указанный в аргументах recv()?
Последовательно все данные получит? Или только те, которые в момент запуска recv() пришли? Если все, значит есть какой-то буфер в операционной системе? Тогда какой его размер и как долго там хранятся данные ожидая вызова recv()?
A: @xinakapu, уточните, Вы говорите о tcp (SOCK_STREAM) или udp (SOCK_DGRAM).
В любом случает первые пришедшие хранятся. В случае tcp все "склеивается" в один поток. При заполнении системного буфера (для простоты назовем эту структуру ядра так) прием прекращается (отправитель тормозится).
Для udp пришедшие данные хранятся в виде полученных "пакетов" (datagram) c соблюдением границ. Не помещающиеся в буфер отбрасываются без уведомления отправителя (и получателя). При recv() читается один пакет за один  вызов (первые байты, помещающиеся в буфер recv).
A: Данные склеиваются. Принимающая сторона получит всё одним куском. Максимальный размер этого куска не может превышать размер буфера сокета.


text:
Q: Sybase Case Statement syntax error Im trying to run a case statement query in sysbase but i keep running into a error. The query is here
CASE WHEN table.TYPPAYT is '04' then 'Cash on delivery'
ELSE table.TYPPAYT
END

I have also tried it like this.
CASE WHEN table.TYPPAYT is '04' then 'Cash on delivery'
ELSE table.TYPPAYT
END

Both of these return syntax error near '04'
When i run it like this it works but its not what i want
CASE WHEN table.TYPPAYT is  then 'Cash on delivery'
ELSE table.TYPPAYT
END

Any ideas?

A: Try this way using = operator
CASE WHEN table.TYPPAYT = '04' then 'Cash on delivery'
ELSE table.TYPPAYT
END

or using in
CASE WHEN table.TYPPAYT in ('04') then 'Cash on delivery'
ELSE table.TYPPAYT
END


text:
Q: Recent progress on Bochner-Riesz conjecture Consider the family of operators $T_\delta$, $\delta \geq 0$, defined on $\mathbb{R}^n$ by
$
\widehat{T_\delta f}(\xi) = (1-|\xi|^2)_+^\delta \widehat{f}(\xi).
$
($(1-|\xi|^2)_+^\delta$ are known as Bochner-Riesz multipliers.) We are interested in the $L^p$ boundedness of $T_\delta$. The case $\delta = 0$ has been solved since 1971, once Fefferman provided a proof that $L^p$ boundedness fails in dimension $n \geq 2$ when $p \neq 2$. For general $\delta > 0$, a Theorem due to Herz shows that a necessary condition for boundedness is that
$
|\frac{1}{p}-\frac{1}{2}| < \frac{2\delta + 1}{2n}.
$
It's thus natural for one to conjecture that this is also a sufficient condition.
Here's what I think I know about current progress, from jotted down notes:

*

*Holds for $n \leq 2$

*Holds for $p = 2$

*$T_\delta$ is bounded when $\delta > \frac{n-1}{2}$ (by Young's inequality)

*$T_\delta$ is bounded when $|\frac{1}{p}-\frac{1}{2}| < \frac{\delta}{n-1}$

*Holds if $\delta > \frac{n-1}{2(n+1)}$ (Can't remember the reference)

*Holds for $n \geq 3$ when $p \geq \frac{2(n+2)}{n}$ or $p \leq \frac{2(n+2)}{n+4}$ (Found in Tao's Recent progress on the Restriction conjecture)

Question: What is the most recent
  progress on this conjecture? I'm
  curious about the general case and
  also specific values of $n$, such as
  $n = 3$.

A: The results stated in your post are improved in the recent work of Bourgain and Guth, in dimensions 5 and higher. The numerology is the same as for the restriction problem for the sphere (see the statement of theorem 1 in that paper).  In the case of the restriction problem for the sphere Bourgain and Guth improved the 3 dimensional result to $p > 3 + 3/10=3.3$, which is slightly better than the $p>10/3=3.333...$ from Tao's bilinear estimates (which, combined with Lee's work, gives the corresponding result for Bochner-Riesz.) This is the "same" $p>10/3$ you mention in your post. It seems likely that Bourgain and Guth's argument will give a similar improvement for the 3 dimensional Bochner-Riesz problem, but they do not work this out in the paper. They do write (page 5) "Thus in principle, one could expect the proof of Theorem 2 to carry over and lead to the validity of the Bochner-Riesz conjecture for $max(p, p′) ≥ 3 +3/10$ , if n = 3. We do not pursue the details of this matter here."