问:
Conditional formatting on a list on sharepoint 2013 using CSR
I'm trying to get conditional formatting to work on a list on Sharepoint 2013, what i want it do to is to change the colour of the words in the priority field depending on what is inputted e.g. High = red Low = Green Med = orange

I've tried multiple ways of doing this and i've looked at a lot of tutorials but as i only have a basic knowledge of JS and CSR i'm finding it very hard, i understand to make a JS file apply to a web part i have to link the address location of the file in the miscellanious area of the web part editor it's just the code i'm having issues with.

Here's what i have so far

(function () {

    var priorityFiledContext = {};
    priorityFiledContext.Templates = {};
    priorityFiledContext.Templates.Fields = {

        "Priority": { "View": priorityFiledTemplate }
    };

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(priorityFiledContext);

})();

function priorityFiledTemplate(ctx) {

    var priority = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];

    switch (priority) {
        case "(1) High":
            return "" + priority + "";
            break;
        case "(2) Normal":
            return "" + priority + "";
            break;
        case "(3) Low":
            return "" + priority + "";
    }
} ```

答:
The code looks good as long as you're using English standard task lists (if not, you would have to change the priority strings in the switch block to whatever your task list is using).

You can simplify deploying CSR customizations using e.g. the Cisar Chrome browser plugin. It publishes changes written in a browser window in real time to the server attaching an on-the-fly created Javascript file to the list currently opened in the browser (supposing you have permissions to do so).


来源: stackexchange

问:
Update variable value in module
I'm a real newbie in node.js so pls understand my possible stupidity

I'm trying to use a external file to serve as a module so I can use it in other files. The project is bigger than this but let's say my module is:

```<code>var Tools = module.exports = {
  result_arr: [],
  object_data: {
    times  : [],
    temps1 : [],
    temps2 : [],
    temps3 : [],
    temps4 : [],
    levels : [],
    flows  : []
  },
  getLastNRows: function (whereIsData, DB_info, table, NRows) {
    if (whereIsData == "MySQL") {
      function setValue (value) {
        Tools.result_arr = value;
      }
      function dataArray2Object (array_data) {
        Tools.object_data.times  = array_data.map(row => row.timestamp);
        Tools.object_data.temps1 = array_data.map(row => row.temp1);
        Tools.object_data.temps2 = array_data.map(row => row.temp2);
        Tools.object_data.temps3 = array_data.map(row => row.temp3);
        Tools.object_data.temps4 = array_data.map(row => row.temp4);
        Tools.object_data.levels = array_data.map(row => row.level_ice_bank);
        Tools.object_data.flows  = array_data.map(row => row.flow);
      }
      var queryString = "SELECT timestamp, temp1, temp2, temp3, temp4, level_ice_bank, flow FROM " +
                        table + " ORDER BY id DESC LIMIT " + NRows + ";";
      var connnection = mysql.createConnection(DB_info);
      connnection.connect(function(err) {
        console.log("connected");
        if (err) throw err;
      });
      connnection.query(queryString, function (err, rows) {
        console.log("queried");
        if (err) throw err;
        setValue(rows);
        dataArray2Object(Tools.result_arr);
        console.log(Tools.result_arr);
        console.log(Tools.object_data);
      });
    }
    else {
      console.log("Function only accepts data stored in MySQL.\n(u still have to improve...)");
      return;
    }
};
</code>```

The variable object_data is supposed to be used in a main file. This way, whenever I call getLastNRows, I expect object_data to be updated by the operations in getLastNRows. The main file would be:

```<code>var tools = require('./tools');

var where2save = "MySQL";
var info_db = {
  host    : "127.0.0.1",
  user    : "root",
  password: "xxxx",
  database: "mydb",
  port    : 3306
};
var table = "tempdata";
var NRows = 4;

tools.getLastNRows(where2save, info_db, table, NRows);

console.log(tools.object_data);
</code>```

What is observed is that, in fact, tools.object_data is not updated by getLastNRows in the main file, although console.log(Tools.object_data); from the tools.js (module) file logs the updated values. So my question is:

How can I make getLastNRows update tools.object_data (which is empty when created) in the main file?

答:
Is getLastNRows asynchronous?  Cuz it seems to me that is the cause of the problem.

It calls the getLastNRows in main which then calls connection.query, which gets put on a worker thread then immediately continues to the console.log where tools.object_data has not been updated.

Try:

```<code>getLastNRows: function (whereIsData, DB_info, table, NRows, cb) {
    // ...
    connnection.query(queryString, function (err, rows) {
            console.log("queried");
            if (err) throw err;
            setValue(rows);
            dataArray2Object(Tools.result_arr);
            console.log(Tools.result_arr);
            console.log(Tools.object_data);
            cb()
    });
    // ...
}

// in main
tools.getLastNRows(where2save, info_db, table, NRows, function() {
    console.log(tools.object_data);
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Update variable value in module

Body:
I'm a real newbie in node.js so pls understand my possible stupidity

I'm trying to use a external file to serve as a module so I can use it in other files. The project is bigger than this but let's say my module is:

var Tools = module.exports = {
  result_arr: [],
  object_data: {
    times  : [],
    temps1 : [],
    temps2 : [],
    temps3 : [],
    temps4 : [],
    levels : [],
    flows  : []
  },
  getLastNRows: function (whereIsData, DB_info, table, NRows) {
    if (whereIsData == "MySQL") {
      function setValue (value) {
        Tools.result_arr = value;
      }
      function dataArray2Object (array_data) {
        Tools.object_data.times  = array_data.map(row => row.timestamp);
        Tools.object_data.temps1 = array_data.map(row => row.temp1);
        Tools.object_data.temps2 = array_data.map(row => row.temp2);
        Tools.object_data.temps3 = array_data.map(row => row.temp3);
        Tools.object_data.temps4 = array_data.map(row => row.temp4);
        Tools.object_data.levels = array_data.map(row => row.level_ice_bank);
        Tools.object_data.flows  = array_data.map(row => row.flow);
      }
      var queryString = "SELECT timestamp, temp1, temp2, temp3, temp4, level_ice_bank, flow FROM " +
                        table + " ORDER BY id DESC LIMIT " + NRows + ";";
      var connnection = mysql.createConnection(DB_info);
      connnection.connect(function(err) {
        console.log("connected");
        if (err) throw err;
      });
      connnection.query(queryString, function (err, rows) {
        console.log("queried");
        if (err) throw err;
        setValue(rows);
        dataArray2Object(Tools.result_arr);
        console.log(Tools.result_arr);
        console.log(Tools.object_data);
      });
    }
    else {
      console.log("Function only accepts data stored in MySQL.\n(u still have to improve...)");
      return;
    }
};

The variable object_data is supposed to be used in a main file. This way, whenever I call getLastNRows, I expect object_data to be updated by the operations in getLastNRows. The main file would be:

var tools = require('./tools');

var where2save = "MySQL";
var info_db = {
  host    : "127.0.0.1",
  user    : "root",
  password: "xxxx",
  database: "mydb",
  port    : 3306
};
var table = "tempdata";
var NRows = 4;

tools.getLastNRows(where2save, info_db, table, NRows);

console.log(tools.object_data);

What is observed is that, in fact, tools.object_data is not updated by getLastNRows in the main file, although console.log(Tools.object_data); from the tools.js (module) file logs the updated values. So my question is:

How can I make getLastNRows update tools.object_data (which is empty when created) in the main file?

Body:
Is getLastNRows asynchronous?  Cuz it seems to me that is the cause of the problem.

It calls the getLastNRows in main which then calls connection.query, which gets put on a worker thread then immediately continues to the console.log where tools.object_data has not been updated.

Try:

getLastNRows: function (whereIsData, DB_info, table, NRows, cb) {
    // ...
    connnection.query(queryString, function (err, rows) {
            console.log("queried");
            if (err) throw err;
            setValue(rows);
            dataArray2Object(Tools.result_arr);
            console.log(Tools.result_arr);
            console.log(Tools.object_data);
            cb()
    });
    // ...
}

// in main
tools.getLastNRows(where2save, info_db, table, NRows, function() {
    console.log(tools.object_data);
});


问:
MarkLogic Alerting Error: No default permissions for document creation

MarkLogic: Current user does not have default permissions for document creation.

Prerequisite

I have downloaded the MarkLogic sample alerting repository from this link and configured all settings to specification.

Issue

When I try to Create a New Content Post with arbitrary data, as shown below, I get a permissions error.

Content Post:

Permissions Error:

Relevant Information

I am new to MarkLogic, but I am sure I am using the service as an admin (check Permissions Error screenshot for clarification). There isn't much good documentation of the service for new users, so I was not able to find a solution that involved granting further permissions to admin.

Thanks so much in advance!

答:
Not sure exactly what application this is, but there it looks like you'll need to go in through the admin console and add default permissions to the admin role. The app is expecting there to be some, but by default there aren't any.

You can simply create default permissions to the role that give admin read, insert, and update.

The intended use would be to use roles/users other than admin...

To configure default permissions for a role using the administrative console, do the following:

Login to the admin console (usually the HTTP app on port 8001- http://localhost:8001)

In the navigation menu to the left, click on security, then roles, then click the target role (in this case, admin). By default, the configure tab is selected.

Scroll to the bottom of the page to the section titled, "default permissions" and create a set of default permissions by selecting a role/capability pair. In this case, use admin as the role and read, then click "more permissions" and select admin role with insert, and then repeat for admin/update.

Hope this helps!


问:
Translate stored procedure from MS SQL Server to Informix
I do not know how to write a specific stored procedure in Informix, so I had to write the logic in my mind in SQL Server which I know how to write (Microsoft simplicity)... So I will write my stored procedure in the SQL syntax and please any one who know Informix syntax and how to write tell me the equivalent of my stored procedure in Informix with little hints to learn the techniques used in both...

My stored procedure is:

```<code>ALTER PROC [dbo].[DetectFine] @prog_code int
AS
---------------------------------
DECLARE @lect_code int;
DECLARE @prog_code_temp int;
DECLARE @confirm_reg int;
DECLARE @start_date_temp DATE;
---------------------------------
DECLARE Mycursor CURSOR FOR
SELECT l.confirm_reg,p.[start_date],l.lect_code,l.prog_code
FROM cc1lectprog l INNER JOIN cc1progtimes p
ON l.prog_code = p.prog_code
WHERE p.prog_code = @prog_code;
---------------------------------
OPEN Mycursor ;
---------------------------------
FETCH NEXT FROM Mycursor
INTO @confirm_reg,@start_date_temp,@lect_code,@prog_code_temp;
---------------------------------
WHILE @@FETCH_STATUS =0
BEGIN
Select @confirm_reg as Cconfirm_reg, @start_date_temp as Cstart_date ,@lect_code as Clect_code,@prog_code_temp as Cprog_code_temp;
-- This is executed as long as the previous fetch succeeds.
IF @confirm_reg = 0 AND GETDATE()>= DATEADD(DD,-3,@start_date_temp)
-----------------------------------------------------------------------
UPDATE cc1lectprog
SET fine = 0
WHERE lect_code = @lect_code AND prog_code = @prog_code_temp;
-----------------------------------------------------------------------
FETCH NEXT FROM Mycursor
INTO @confirm_reg,@start_date_temp,@lect_code,@prog_code_temp;
-----------------------------------------------------------------------
END
CLOSE Mycursor
DEALLOCATE Mycursor
-----------------------------------------------------------------------
</code>```

Note: this stored procedure is required to be executed every period of time like a job.  Is it possible to execute procedure with parameters every period of time or not? And what are the alternatives if not?

答: Real Informix simplicity vs "Microsoft simplicity" :)</p>

Body:
I do not know how to write a specific stored procedure in Informix, so I had to write the logic in my mind in SQL Server which I know how to write (Microsoft simplicity)... So I will write my stored procedure in the SQL syntax and please any one who know Informix syntax and how to write tell me the equivalent of my stored procedure in Informix with little hints to learn the techniques used in both...

My stored procedure is:

ALTER PROC [dbo].[DetectFine] @prog_code int
AS
---------------------------------
DECLARE @lect_code int;
DECLARE @prog_code_temp int;
DECLARE @confirm_reg int;
DECLARE @start_date_temp DATE;
---------------------------------
DECLARE Mycursor CURSOR FOR
SELECT l.confirm_reg,p.[start_date],l.lect_code,l.prog_code
FROM cc1lectprog l INNER JOIN cc1progtimes p
ON l.prog_code = p.prog_code
WHERE p.prog_code = @prog_code;
---------------------------------
OPEN Mycursor ;
---------------------------------
FETCH NEXT FROM Mycursor
INTO @confirm_reg,@start_date_temp,@lect_code,@prog_code_temp;
---------------------------------
WHILE @@FETCH_STATUS =0
BEGIN
Select @confirm_reg as Cconfirm_reg, @start_date_temp as Cstart_date ,@lect_code as Clect_code,@prog_code_temp as Cprog_code_temp;
-- This is executed as long as the previous fetch succeeds.
IF @confirm_reg = 0 AND GETDATE()>= DATEADD(DD,-3,@start_date_temp)
-----------------------------------------------------------------------
UPDATE cc1lectprog
SET fine = 0
WHERE lect_code = @lect_code AND prog_code = @prog_code_temp;
-----------------------------------------------------------------------
FETCH NEXT FROM Mycursor
INTO @confirm_reg,@start_date_temp,@lect_code,@prog_code_temp;
-----------------------------------------------------------------------
END
CLOSE Mycursor
DEALLOCATE Mycursor
-----------------------------------------------------------------------

Note: this stored procedure is required to be executed every period of time like a job.  Is it possible to execute procedure with parameters every period of time or not? And what are the alternatives if not?

ContentLicense: CC BY-SA 2.5


问:
How do I disambiguate traits in Rust?
I want to use the write_fmt method on two different types of object:

```<code>use std::fmt::Write;
use std::io::Write;

fn main() {
    let mut a = String::new();
    let mut b = std::fs::File::create("test").unwrap();

    a.write_fmt(format_args!("hello"));
    b.write_fmt(format_args!("hello"));
}
</code>```

I get an error when using Write because they are both named the same:

error[E0252]: a trait named `Write` has already been imported in this module
 --> src/main.rs:8:5
  |
7 | use std::fmt::Write;
  |     --------------- previous import of `Write` here
8 | use std::io::Write;
  |     ^^^^^^^^^^^^^^ `Write` already imported
      a.write_fmt(format_args!("hello"));
      b.write_fmt(format_args!("hello"));
```

<p>Or I get an error saying the trait is not available:</p>

<pre class="lang-none prettyprint-override"><code>error[E0599]: no method named `write_fmt` found for type `std::fs::File` in the current scope
  --> src/main.rs:76:4
   |
76 |    b.write_fmt(format_args!("hello"));
   |      ^^^^^^^^^
   |
   = help: items from traits can only be used if the trait is in scope; the following trait is implemented but not in scope, perhaps add a `use` for it:
   = help: candidate #1: `use std::io::Write;`
</code>```

答:
You can specify an alias for use:

```<code>use std::fmt::Write as FmtWrite;
use std::io::Write;

fn main() {
    let mut a = String::new();
    let mut b = std::fs::File::create("test").unwrap();

    a.write_fmt(format_args!("hello"));
    b.write_fmt(format_args!("hello"));
}
</code>```

If you just want to call the traits method, you can even just bring them in scope:

```<code>use std::fmt::Write as _;
use std::io::Write as _;

fn main() {
    let mut a = String::new();
    let mut b = std::fs::File::create("test").unwrap();

    a.write_fmt(format_args!("hello"));
    b.write_fmt(format_args!("hello"));
}
</code>```

Be careful, this solution works when different types implement different traits with the same name. If the same type implements different traits with the same name, you must use Shepmaster's answer:

```<code>mod foo {
    pub trait Trait {
        fn do_something(&self) {}
    }
}

mod bar {
    pub trait Trait {
        fn do_something(&self) {}
    }
}

pub struct Concrete {}
impl foo::Trait for Concrete {}
impl bar::Trait for Concrete {}

fn main() {
    let x = Concrete {};

    {
        use foo::Trait; // use limited to scope

        x.do_something(); // call foo::Trait::do_something
    }
    {
        foo::Trait::do_something(&x); // complete path to disambiguate
        bar::Trait::do_something(&x); // complete path to disambiguate
    }
    {
        use foo::Trait as FooTrait;
        use bar::Trait;

        x.do_something(&x); // ERROR: multiple applicable items in scope
    }
}
</code>```

Title: How do I disambiguate traits in Rust?

Body:
I want to use the write_fmt method on two different types of object:

use std::fmt::Write;
use std::io::Write;

fn main() {
    let mut a = String::new();
    let mut b = std::fs::File::create("test").unwrap();

    a.write_fmt(format_args!("hello"));
    b.write_fmt(format_args!("hello"));
}

I get an error when using Write because they are both named the same:

error[E0252]: a trait named `Write` has already been imported in this module
 --> src/main.rs:8:5
  |
7 | use std::fmt::Write;
  |     --------------- previous import of `Write` here
8 | use std::io::Write;
  |     ^^^^^^^^^^^^^^ `Write` already imported
      a.write_fmt(format_args!("hello"));
      b.write_fmt(format_args!("hello"));

Or I get an error saying the trait is not available:

error[E0599]: no method named `write_fmt` found for type `std::fs::File` in the current scope
  --> src/main.rs:76:4
   |
76 |    b.write_fmt(format_args!("hello"));
   |      ^^^^^^^^^
   |
   = help: items from traits can only be used if the trait is in scope; the following trait is implemented but not in scope, perhaps add a `use` for it:
   = help: candidate #1: `use std::io::Write;`

Body:
You can specify an alias for use:

use std::fmt::Write as FmtWrite;
use std::io::Write;

fn main() {
    let mut a = String::new();
    let mut b = std::fs::File::create("test").unwrap();

    a.write_fmt(format_args!("hello"));
    b.write_fmt(format_args!("hello"));
}

If you just want to call the traits method, you can even just bring them in scope:

use std::fmt::Write as _;
use std::io::Write as _;

fn main() {
    let mut a = String::new();
    let mut b = std::fs::File::create("test").unwrap();

    a.write_fmt(format_args!("hello"));
    b.write_fmt(format_args!("hello"));
}

Be careful, this solution works when different types implement different traits with the same name. If the same type implements different traits with the same name, you must use Shepmaster's answer:

mod foo {
    pub trait Trait {
        fn do_something(&self) {}
    }
}

mod bar {
    pub trait Trait {
        fn do_something(&self) {}
    }
}

pub struct Concrete {}
impl foo::Trait for Concrete {}
impl bar::Trait for Concrete {}

fn main() {
    let x = Concrete {};

    {
        use foo::Trait; // use limited to scope

        x.do_something(); // call foo::Trait::do_something
    }
    {
        foo::Trait::do_something(&x); // complete path to disambiguate
        bar::Trait::do_something(&x); // complete path to disambiguate
    }
    {
        use foo::Trait as FooTrait;
        use bar::Trait;

        x.do_something(&x); // ERROR: multiple applicable items in scope
    }
}

ContentLicense: CC BY-SA 4.0


问:
How can I install a Java JAR library via command line, and compile my program via cli?
I just started learning Java.

Since I know a little Python,I just wanted to "take the measure" of Java, and precisely how can I do something I already know with Python: download a webpage html.

Thanks to a StackOverflow question I discovered Jsoup.
I downloaded the JAR and....what should I do now?

I tried placing it in the same folder as my program, having chmodded +x to it, or placing it to /usr/lib/jvm/java-7-openjdk-amd64/jre/lib/ext

I am trying to run this program

```<code>import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class ParseHTML {
    public static void main(String[] args) throws IOException{
        Document doc = Jsoup.connect("https://www.wikipedia.org/").get();
        String text = doc.body().text();
        System.out.print(text);
    }
}
</code>```

but it gives these errors

```<code>js_dwn_wbp.java:6: error: class ParseHTML is public, should be declared in a file named ParseHTML.java
public class ParseHTML {
       ^
js_dwn_wbp.java:2: error: package org.jsoup does not exist
import org.jsoup.Jsoup;
                ^
js_dwn_wbp.java:3: error: package org.jsoup.nodes does not exist
import org.jsoup.nodes.Document;
                      ^
js_dwn_wbp.java:9: error: cannot find symbol
        Document doc = Jsoup.connect("https://www.wikipedia.org/").get();
        ^
  symbol:   class Document
  location: class ParseHTML
js_dwn_wbp.java:9: error: cannot find symbol
        Document doc = Jsoup.connect("https://www.wikipedia.org/").get();
                       ^
  symbol:   variable Jsoup
  location: class ParseHTML
5 errors
</code>```

Thanks in advance

EDIT 1
Thanks to a comment I was able to compile via terminal, however it gives this error

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/jsoup/Jsoup
    at ParseHTML.main(ParseHTML.java:9)
Caused by: java.lang.ClassNotFoundException: org.jsoup.Jsoup
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 1 more
</code>```

答:
You will also need to add supporting jars i.e. jars used in Jsoup in classpath folder.

Download jar with dependencies from below link..
https://jar-download.com/explore-java-source-code.php?a=jsoup&g=org.jsoup&v=1.9.2&downloadable=1

Body:
I just started learning Java.

Since I know a little Python,I just wanted to "take the measure" of Java, and precisely how can I do something I already know with Python: download a webpage html.

Thanks to a StackOverflow question I discovered Jsoup.
I downloaded the JAR and....what should I do now?

I tried placing it in the same folder as my program, having chmodded +x to it, or placing it to /usr/lib/jvm/java-7-openjdk-amd64/jre/lib/ext

I am trying to run this program

import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class ParseHTML {
    public static void main(String[] args) throws IOException{
        Document doc = Jsoup.connect("https://www.wikipedia.org/").get();
        String text = doc.body().text();
        System.out.print(text);
    }
}

but it gives these errors

js_dwn_wbp.java:6: error: class ParseHTML is public, should be declared in a file named ParseHTML.java
public class ParseHTML {
       ^
js_dwn_wbp.java:2: error: package org.jsoup does not exist
import org.jsoup.Jsoup;
                ^
js_dwn_wbp.java:3: error: package org.jsoup.nodes does not exist
import org.jsoup.nodes.Document;
                      ^
js_dwn_wbp.java:9: error: cannot find symbol
        Document doc = Jsoup.connect("https://www.wikipedia.org/").get();
        ^
  symbol:   class Document
  location: class ParseHTML
js_dwn_wbp.java:9: error: cannot find symbol
        Document doc = Jsoup.connect("https://www.wikipedia.org/").get();
                       ^
  symbol:   variable Jsoup
  location: class ParseHTML
5 errors

Thanks in advance

EDIT 1
Thanks to a comment I was able to compile via terminal, however it gives this error

Exception in thread "main" java.lang.NoClassDefFoundError: org/jsoup/Jsoup
    at ParseHTML.main(ParseHTML.java:9)
Caused by: java.lang.ClassNotFoundException: org.jsoup.Jsoup
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 1 more


问:
PHP session side-effect warning - how to get solve?
I'm fairly new to php, and am sure this is easy, but I'd like to do it the right way. I have this script:

```<code><?php
if ($_POST["username"]=="") {
    include($_SERVER['DOCUMENT_ROOT'] ."/login.inc.php");
} else {
    $username=$_POST["username"];
    $password=$_POST["password"];
    session_start();
    if ($username=="bob" AND $password=="123"){ $permission="yes";}
    $username=$_POST["username"];
    session_register("permission");
    session_register("username");

    if ($permission=="yes"){
        // Show stuff
    }
}
?>
</code>```

Excuse the funky formatting of my code - can't seem to get it to show properly.

So, I keep getting this error:

Warning: Unknown: Your script possibly relies on a session side-effect which existed until PHP 4.2.3. Please be advised that the session extension does not consider global variables as a source of data, unless register_globals is enabled. You can disable this functionality and this warning by setting session.bug_compat_42 or session.bug_compat_warn to off, respectively in Unknown on line 0

Which I'm assuming means I need to change one of my variable names so it doesn't conflict with the session variable right? That's what I read, but I'm not sure which one to change.

Can anyone help / show me please?

Thanks

osu

答:
It is happening because of

```<code>session_register("username");
</code>```

It is not recommended, and deprecated as of PHP 5.3.

If you want your script to work regardless of register_globals, you need to instead use the $_SESSION array as $_SESSION entries are automatically registered. If your script uses session_register(), it will not work in environments where the PHP directive register_globals is disabled.

Source.

As we all know, register_globals is terrible, and should always be off.

The most common way to register a session var is with the $_SESSION superglobal, i.e.

```<code>$_SESSION['username'] = $username;
</code>```

Body:
I'm fairly new to php, and am sure this is easy, but I'd like to do it the right way. I have this script:

<?php
if ($_POST["username"]=="") {
    include($_SERVER['DOCUMENT_ROOT'] ."/login.inc.php");
} else {
    $username=$_POST["username"];
    $password=$_POST["password"];
    session_start();
    if ($username=="bob" AND $password=="123"){ $permission="yes";}
    $username=$_POST["username"];
    session_register("permission");
    session_register("username");

    if ($permission=="yes"){
        // Show stuff
    }
}
?>

Excuse the funky formatting of my code - can't seem to get it to show properly.

So, I keep getting this error:

Warning: Unknown: Your script possibly relies on a session side-effect which existed until PHP 4.2.3. Please be advised that the session extension does not consider global variables as a source of data, unless register_globals is enabled. You can disable this functionality and this warning by setting session.bug_compat_42 or session.bug_compat_warn to off, respectively in Unknown on line 0

Which I'm assuming means I need to change one of my variable names so it doesn't conflict with the session variable right? That's what I read, but I'm not sure which one to change.

Can anyone help / show me please?

Thanks

osu

Body:
It is happening because of

session_register("username");

It is not recommended, and deprecated as of PHP 5.3.

If you want your script to work regardless of register_globals, you need to instead use the $_SESSION array as $_SESSION entries are automatically registered. If your script uses session_register(), it will not work in environments where the PHP directive register_globals is disabled.

Source.

As we all know, register_globals is terrible, and should always be off.

The most common way to register a session var is with the $_SESSION superglobal, i.e.

$_SESSION['username'] = $username;


问:
Javascript click and drag background not working as expected
I'm trying to make a click and drag the background in Javascript, so I made this fiddle. But it has a problem.

When you click and drag to the left, the background moves to the right, so I track the position of the mouse, compare it to the mousedown, and with the difference I scroll the body. But, when it reaches to 0, the difference is negative so if you move past that difference and then move to the right again, you have to move the amount of pixels that you are past, which makes it weird.

So to fix this, I put this code:

```<code>if(difX < 0){
    md.x = mm.x;
}
</code>```

which makes that, if the difference is less than 0 (i.e: reached the edge), the mousedown position is the same as the mousemove, so that when you move to the other side, the difference is no longer negative and can start increasing again.

The problem is that it jumps when you reach the edge.

I did this only with the X position, but I'll do the same for the Y once I solve it. Thanks in advance!

答: Nevermind, solved it out, the problem was the the sl variable didn't change when it reached a negative difference, so it used the one stored on mouseup and it jumped because of the difference between those numbers, here's the solved fiddle

Body:
I'm trying to make a click and drag the background in Javascript, so I made this fiddle. But it has a problem.

When you click and drag to the left, the background moves to the right, so I track the position of the mouse, compare it to the mousedown, and with the difference I scroll the body. But, when it reaches to 0, the difference is negative so if you move past that difference and then move to the right again, you have to move the amount of pixels that you are past, which makes it weird.

So to fix this, I put this code:

if(difX < 0){
    md.x = mm.x;
}

which makes that, if the difference is less than 0 (i.e: reached the edge), the mousedown position is the same as the mousemove, so that when you move to the other side, the difference is no longer negative and can start increasing again.

The problem is that it jumps when you reach the edge.

I did this only with the X position, but I'll do the same for the Y once I solve it. Thanks in advance!


问:
Getting [object HTMLLIElement] instead of text. Javascript function
Hello I have a simple javascript function that chooses a random list item in an unordered list with the press of a button. It works fine, the console spits out a random list item when the button is clicked but when I try to display it on the HTML page all I am getting is this weird [object HTMLLIElement] instead of the text.

The goal is to display the text inbetween the list item. When I click the button it chooses a random list item for example:
5
 but I would like for just the 5 to be displayed.

Here is the HTML:

```<code><ul id="list">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
</ul>

<button id="randomize">randomize</button>

<p id="result">hello</p>
</code>```

and the JS:

```<code>var randomize = document.getElementById("randomize");
var listItems = document.getElementById("list").getElementsByTagName("li");
var result = document.getElementById("result");

randomize.addEventListener("click", randomizeIt);

function randomizeIt () {
    var randomItem = listItems[Math.floor(Math.random() * listItems.length)];
    result.innerHTML = randomItem;
    console.log(randomItem);
}
</code>```

thanks in advance

答:
If you just want the value you need to access the innerHTML of the
.

```<code>result.innerHTML = randomItem.innerHTML;
</code>```

Body:
Hello I have a simple javascript function that chooses a random list item in an unordered list with the press of a button. It works fine, the console spits out a random list item when the button is clicked but when I try to display it on the HTML page all I am getting is this weird [object HTMLLIElement] instead of the text.

The goal is to display the text inbetween the list item. When I click the button it chooses a random list item for example:
5
 but I would like for just the 5 to be displayed.

Here is the HTML:

1

2

3

4

5

6

7

<button id="randomize">randomize</button>

hello

and the JS:

var randomize = document.getElementById("randomize");
var listItems = document.getElementById("list").getElementsByTagName("li");
var result = document.getElementById("result");

randomize.addEventListener("click", randomizeIt);

function randomizeIt () {
    var randomItem = listItems[Math.floor(Math.random() * listItems.length)];
    result.innerHTML = randomItem;
    console.log(randomItem);
}

thanks in advance

Body:
If you just want the value you need to access the innerHTML of the <li>.

result.innerHTML = randomItem.innerHTML;


问:
Gradle Build Failed For Task app:processReleaseResources
```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "com.nusecond.karun.suredeal"
        minSdkVersion 18
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
 signingConfigs {
        release {
            storeFile file("suredealreleasekey.keystore")
            storePassword "suredeal"
            keyAlias "SuredealReleaseKey"
            keyPassword "suredeal"
        }
    }

buildTypes {
        release {
            signingConfig signingConfigs.release
        }
    }
    packagingOptions {
        exclude 'META-INF/ASL2.0'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/notice.txt'
    }
}
repositories {
    mavenCentral()
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:design:23.1.1'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:recyclerview-v7:23.1.1'
    compile 'com.facebook.android:facebook-android-sdk:4.6.0'
    testCompile 'com.android.support:support-annotations:23.1.1'
    androidTestCompile 'com.android.support:support-annotations:23.1.1'

    compile 'com.google.android.gms:play-services-base:8.4.0'
    compile 'com.google.android.gms:play-services-plus:8.4.0'
    compile 'com.google.android.gms:play-services-auth:8.4.0'
    compile 'com.android.support:support-v13:23.1.1'

    /**
     * GSON
     */
    compile 'com.google.code.gson:gson:2.4'

    // UI AutomatorTesting
    androidTestCompile 'com.android.support.test:runner:0.2'
    androidTestCompile 'com.android.support.test:rules:0.2'
    androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.0'
    compile 'com.google.android.gms:play-services-appindexing:8.4.0'

    /**
     * Spring Dependencies
     * compile 'org.springframework.android:spring-android-rest-template:1.0.1.RELEASE'
     * compile 'com.fasterxml.jackson.core:jackson-core:2.4.2'
     * compile 'com.fasterxml.jackson.core:jackson-annotations:2.4.0'
     */
    compile 'org.springframework.android:spring-android-rest-template:2.0.0.M3'
    compile 'com.fasterxml.jackson.core:jackson-databind:2.4.2'

    /**
     * Android Annotation Dependencies
     */
    compile 'org.glassfish.main:javax.annotation:4.0-b33'

    /**
     * Volley Jar
     */
    compile files('libs/volley.jar')
    compile 'com.mcxiaoke.volley:library:1.0.19'

    /**
     * GCM Dependency
     */
    compile 'com.google.android.gms:play-services-gcm:8.4.0'
    /**
     * Universal image Loader
     */
    compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    compile files('libs/urlimageviewhelper-1.0.4.jar')

    compile 'com.squareup.picasso:picasso:2.5.2'
}
repositories {
    maven {
        url 'http://repo.spring.io/milestone'
    }
}
</code>```

This is build.gradle

Here I'm generating signed APK using Gradle Build.(./gradlew assembleRelease).
3.Build Failed for task app:processReleaseResources.

Here the stacktrace:

```<code>----------
./gradlew assembleRelease --stacktrace
:app:preBuild UP-TO-DATE
:app:preReleaseBuild UP-TO-DATE
:app:checkReleaseManifest
:app:preDebugBuild UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72311Library UP-TO-DATE
:app:prepareComAndroidSupportDesign2311Library UP-TO-DATE
:app:prepareComAndroidSupportRecyclerviewV72311Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV132311Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42311Library UP-TO-DATE
:app:prepareComFacebookAndroidFacebookAndroidSdk460Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesAppindexing840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesAuth840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesBase840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesBasement840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesGcm840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesMeasurement840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesPlus840Library UP-TO-DATE
:app:prepareReleaseDependencies
:app:compileReleaseAidl UP-TO-DATE
:app:compileReleaseRenderscript UP-TO-DATE
:app:generateReleaseBuildConfig UP-TO-DATE
:app:generateReleaseAssets UP-TO-DATE
:app:mergeReleaseAssets UP-TO-DATE
:app:generateReleaseResValues UP-TO-DATE
:app:generateReleaseResources UP-TO-DATE
:app:mergeReleaseResources UP-TO-DATE
:app:processReleaseManifest UP-TO-DATE
:app:processReleaseResources FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:processReleaseResources'.
> at index 4

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:processReleaseResources'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:42)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.AbstractTask.executeWithoutThrowingTaskFailure(AbstractTask.java:310)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.executeTask(AbstractTaskPlanExecutor.java:79)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:63)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:51)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:23)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:88)
    at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
    at org.gradle.execution.DefaultBuildExecuter.access$200(DefaultBuildExecuter.java:23)
    at org.gradle.execution.DefaultBuildExecuter$2.proceed(DefaultBuildExecuter.java:68)
    at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:55)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:149)
    at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:106)
    at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:86)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:90)
    at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:28)
    at org.gradle.launcher.exec.DaemonUsageSuggestingBuildActionExecuter.execute(DaemonUsageSuggestingBuildActionExecuter.java:50)
    at org.gradle.launcher.exec.DaemonUsageSuggestingBuildActionExecuter.execute(DaemonUsageSuggestingBuildActionExecuter.java:27)
    at org.gradle.launcher.cli.RunBuildAction.run(RunBuildAction.java:40)
    at org.gradle.internal.Actions$RunnableActionAdapter.execute(Actions.java:169)
    at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:237)
    at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:210)
    at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:35)
    at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:24)
    at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:206)
    at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:169)
    at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:33)
    at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:22)
    at org.gradle.launcher.Main.doAction(Main.java:33)
    at org.gradle.launcher.bootstrap.EntryPoint.run(EntryPoint.java:45)
    at org.gradle.launcher.bootstrap.ProcessBootstrap.runNoExit(ProcessBootstrap.java:54)
    at org.gradle.launcher.bootstrap.ProcessBootstrap.run(ProcessBootstrap.java:35)
    at org.gradle.launcher.GradleMain.main(GradleMain.java:23)
    at org.gradle.wrapper.BootstrapMainStarter.start(BootstrapMainStarter.java:33)
    at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:130)
    at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:48)
Caused by: java.lang.NullPointerException: at index 4
    at com.google.common.collect.ObjectArrays.checkElementNotNull(ObjectArrays.java:240)
    at com.google.common.collect.ObjectArrays.checkElementsNotNull(ObjectArrays.java:231)
    at com.google.common.collect.ObjectArrays.checkElementsNotNull(ObjectArrays.java:226)
    at com.google.common.collect.ImmutableList.construct(ImmutableList.java:303)
    at com.google.common.collect.ImmutableList.copyOf(ImmutableList.java:258)
    at com.android.ide.common.process.ProcessInfoBuilder.createProcess(ProcessInfoBuilder.java:55)
    at com.android.builder.core.AaptPackageProcessBuilder.build(AaptPackageProcessBuilder.java:444)
    at com.android.builder.core.AndroidBuilder.processResources(AndroidBuilder.java:915)
    at com.android.build.gradle.tasks.ProcessAndroidResources.doFullTaskAction(ProcessAndroidResources.java:138)
    at com.android.build.gradle.internal.tasks.IncrementalTask.taskAction(IncrementalTask.java:98)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:75)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.doExecute(AnnotationProcessingTaskFactory.java:243)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:219)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.execute(AnnotationProcessingTaskFactory.java:230)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:208)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)
    ... 49 more

BUILD FAILED

Total time: 6.696 secs
</code>```

I'm stuck here Any solution How to fix this issue plz Help me.

答:
In your build.gradle,

```<code>applicationId "com.company.app"
</code>```

Should match in AndroidManifest.xml:

```<code>package="com.company.app"
</code>```

I was getting this same error because they didn't match.

Body:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "com.nusecond.karun.suredeal"
        minSdkVersion 18
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
 signingConfigs {
        release {
            storeFile file("suredealreleasekey.keystore")
            storePassword "suredeal"
            keyAlias "SuredealReleaseKey"
            keyPassword "suredeal"
        }
    }

buildTypes {
        release {
            signingConfig signingConfigs.release
        }
    }
    packagingOptions {
        exclude 'META-INF/ASL2.0'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/notice.txt'
    }
}
repositories {
    mavenCentral()
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:design:23.1.1'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:recyclerview-v7:23.1.1'
    compile 'com.facebook.android:facebook-android-sdk:4.6.0'
    testCompile 'com.android.support:support-annotations:23.1.1'
    androidTestCompile 'com.android.support:support-annotations:23.1.1'

    compile 'com.google.android.gms:play-services-base:8.4.0'
    compile 'com.google.android.gms:play-services-plus:8.4.0'
    compile 'com.google.android.gms:play-services-auth:8.4.0'
    compile 'com.android.support:support-v13:23.1.1'

    /**
     * GSON
     */
    compile 'com.google.code.gson:gson:2.4'

    // UI AutomatorTesting
    androidTestCompile 'com.android.support.test:runner:0.2'
    androidTestCompile 'com.android.support.test:rules:0.2'
    androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.0'
    compile 'com.google.android.gms:play-services-appindexing:8.4.0'

    /**
     * Spring Dependencies
     * compile 'org.springframework.android:spring-android-rest-template:1.0.1.RELEASE'
     * compile 'com.fasterxml.jackson.core:jackson-core:2.4.2'
     * compile 'com.fasterxml.jackson.core:jackson-annotations:2.4.0'
     */
    compile 'org.springframework.android:spring-android-rest-template:2.0.0.M3'
    compile 'com.fasterxml.jackson.core:jackson-databind:2.4.2'

    /**
     * Android Annotation Dependencies
     */
    compile 'org.glassfish.main:javax.annotation:4.0-b33'

    /**
     * Volley Jar
     */
    compile files('libs/volley.jar')
    compile 'com.mcxiaoke.volley:library:1.0.19'

    /**
     * GCM Dependency
     */
    compile 'com.google.android.gms:play-services-gcm:8.4.0'
    /**
     * Universal image Loader
     */
    compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    compile files('libs/urlimageviewhelper-1.0.4.jar')

    compile 'com.squareup.picasso:picasso:2.5.2'
}
repositories {
    maven {
        url 'http://repo.spring.io/milestone'
    }
}

This is build.gradle

Here I'm generating signed APK using Gradle Build.(./gradlew assembleRelease).
3.Build Failed for task app:processReleaseResources.

Here the stacktrace:

----------
./gradlew assembleRelease --stacktrace
:app:preBuild UP-TO-DATE
:app:preReleaseBuild UP-TO-DATE
:app:checkReleaseManifest
:app:preDebugBuild UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72311Library UP-TO-DATE
:app:prepareComAndroidSupportDesign2311Library UP-TO-DATE
:app:prepareComAndroidSupportRecyclerviewV72311Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV132311Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42311Library UP-TO-DATE
:app:prepareComFacebookAndroidFacebookAndroidSdk460Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesAppindexing840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesAuth840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesBase840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesBasement840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesGcm840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesMeasurement840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesPlus840Library UP-TO-DATE
:app:prepareReleaseDependencies
:app:compileReleaseAidl UP-TO-DATE
:app:compileReleaseRenderscript UP-TO-DATE
:app:generateReleaseBuildConfig UP-TO-DATE
:app:generateReleaseAssets UP-TO-DATE
:app:mergeReleaseAssets UP-TO-DATE
:app:generateReleaseResValues UP-TO-DATE
:app:generateReleaseResources UP-TO-DATE
:app:mergeReleaseResources UP-TO-DATE
:app:processReleaseManifest UP-TO-DATE
:app:processReleaseResources FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:processReleaseResources'.
> at index 4

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:processReleaseResources'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:42)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.AbstractTask.executeWithoutThrowingTaskFailure(AbstractTask.java:310)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.executeTask(AbstractTaskPlanExecutor.java:79)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:63)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:51)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:23)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:88)
    at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
    at org.gradle.execution.DefaultBuildExecuter.access$200(DefaultBuildExecuter.java:23)
    at org.gradle.execution.DefaultBuildExecuter$2.proceed(DefaultBuildExecuter.java:68)
    at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:55)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:149)
    at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:106)
    at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:86)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:90)
    at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:28)
    at org.gradle.launcher.exec.DaemonUsageSuggestingBuildActionExecuter.execute(DaemonUsageSuggestingBuildActionExecuter.java:50)
    at org.gradle.launcher.exec.DaemonUsageSuggestingBuildActionExecuter.execute(DaemonUsageSuggestingBuildActionExecuter.java:27)
    at org.gradle.launcher.cli.RunBuildAction.run(RunBuildAction.java:40)
    at org.gradle.internal.Actions$RunnableActionAdapter.execute(Actions.java:169)
    at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:237)
    at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:210)
    at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:35)
    at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:24)
    at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:206)
    at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:169)
    at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:33)
    at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:22)
    at org.gradle.launcher.Main.doAction(Main.java:33)
    at org.gradle.launcher.bootstrap.EntryPoint.run(EntryPoint.java:45)
    at org.gradle.launcher.bootstrap.ProcessBootstrap.runNoExit(ProcessBootstrap.java:54)
    at org.gradle.launcher.bootstrap.ProcessBootstrap.run(ProcessBootstrap.java:35)
    at org.gradle.launcher.GradleMain.main(GradleMain.java:23)
    at org.gradle.wrapper.BootstrapMainStarter.start(BootstrapMainStarter.java:33)
    at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:130)
    at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:48)
Caused by: java.lang.NullPointerException: at index 4
    at com.google.common.collect.ObjectArrays.checkElementNotNull(ObjectArrays.java:240)
    at com.google.common.collect.ObjectArrays.checkElementsNotNull(ObjectArrays.java:231)
    at com.google.common.collect.ObjectArrays.checkElementsNotNull(ObjectArrays.java:226)
    at com.google.common.collect.ImmutableList.construct(ImmutableList.java:303)
    at com.google.common.collect.ImmutableList.copyOf(ImmutableList.java:258)
    at com.android.ide.common.process.ProcessInfoBuilder.createProcess(ProcessInfoBuilder.java:55)
    at com.android.builder.core.AaptPackageProcessBuilder.build(AaptPackageProcessBuilder.java:444)
    at com.android.builder.core.AndroidBuilder.processResources(AndroidBuilder.java:915)
    at com.android.build.gradle.tasks.ProcessAndroidResources.doFullTaskAction(ProcessAndroidResources.java:138)
    at com.android.build.gradle.internal.tasks.IncrementalTask.taskAction(IncrementalTask.java:98)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:75)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.doExecute(AnnotationProcessingTaskFactory.java:243)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:219)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.execute(AnnotationProcessingTaskFactory.java:230)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:208)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)
    ... 49 more

BUILD FAILED

Total time: 6.696 secs

I'm stuck here Any solution How to fix this issue plz Help me.

Body:
In your build.gradle,

applicationId "com.company.app"

Should match in AndroidManifest.xml:

package="com.company.app"

I was getting this same error because they didn't match.


问:
How to find the files modified under a clearcase branch
I modified and checked-in a bunch of files under my branch. Now I need to get the list of files I modified. Is there any scripts to do so?</p>

答:
try this command</p>

```<code>cleartool find -avo -nxname -element '{brtype(branch_name)}' -print
</code>```

Body:
try this command

cleartool find -avo -nxname -element '{brtype(branch_name)}' -print


问:
I want to get bit of char on MPLAB XC8 but I can't?
My function to get bit is:

```<code>extern volatile unsigned char Temp       @ 0x036;
extern volatile __bit W       @ (((unsigned) &Temp)*8) + 4;

void get_bit(volatile unsigned char *reg, unsigned num) {
    W = (*reg & (1 << num));
}
</code>```

Main function is:

```<code>int main() {
    volatile unsigned char ch = 0b00001000;
    get_bit(&ch, 4);
}
</code>```

When I compile this code of blocks I get an error (error: expression syntax).

What can I do to fix this problem?

答:
Try this code:</p>

```<code>#include <stdio.h>

unsigned char get_bit(unsigned char reg, unsigned num)
{
    return (reg & (1 << num));
}

unsigned char get_bit2(unsigned char reg, unsigned num)
{
    return (reg & (1 << num))?1:0;
}

int main()
{
    volatile unsigned char ch = 0b00001000;

    ch |= (1<<4);   // To set bit 4
    printf("%d\n",get_bit(ch, 4)); // If you try on a PC
    printf("%d\n",get_bit2(ch, 4)); // If you try on a PC

    ch &= (~(1<<4));   // To reset bit 4
    printf("%d\n",get_bit(ch, 4)); // If you try on a PC
    printf("%d\n",get_bit2(ch, 4)); // If you try on a PC

    return 0;
}
</code>```

Body:
My function to get bit is:

extern volatile unsigned char Temp       @ 0x036;
extern volatile __bit W       @ (((unsigned) &Temp)*8) + 4;

void get_bit(volatile unsigned char *reg, unsigned num) {
    W = (*reg & (1 << num));
}

Main function is:

int main() {
    volatile unsigned char ch = 0b00001000;
    get_bit(&ch, 4);
}

When I compile this code of blocks I get an error (error: expression syntax).

What can I do to fix this problem?

Body:
Try this code:

#include <stdio.h>

unsigned char get_bit(unsigned char reg, unsigned num)
{
    return (reg & (1 << num));
}

unsigned char get_bit2(unsigned char reg, unsigned num)
{
    return (reg & (1 << num))?1:0;
}

int main()
{
    volatile unsigned char ch = 0b00001000;

    ch |= (1<<4);   // To set bit 4
    printf("%d\n",get_bit(ch, 4)); // If you try on a PC
    printf("%d\n",get_bit2(ch, 4)); // If you try on a PC

    ch &= (~(1<<4));   // To reset bit 4
    printf("%d\n",get_bit(ch, 4)); // If you try on a PC
    printf("%d\n",get_bit2(ch, 4)); // If you try on a PC

    return 0;
}


问:
What happens if the amount of characters that are entered into your character array is less than the amount of spaces you specified
```<code>char ch_arry[20] = { S, A, L, L, Y};
printf( "%s", ch_arry[] );
</code>```

Will it fill the end of the array with null characters?

答:
The remaining 15 characters are set to \0. This is a useful feature of C.

Note that you need to use

```<code>char ch_arry[20] = { 'S', 'A', 'L', 'L', 'Y'};
</code>```

unless you have some insane macro trickery, and

```<code>printf("%s", ch_arry);
</code>```

Body:
char ch_arry[20] = { S, A, L, L, Y};
printf( "%s", ch_arry[] );

Will it fill the end of the array with null characters?

Body:
The remaining 15 characters are set to \0. This is a useful feature of C.

Note that you need to use

char ch_arry[20] = { 'S', 'A', 'L', 'L', 'Y'};

unless you have some insane macro trickery, and

printf("%s", ch_arry);


问:
SparkR - override default parameters in spark.conf
I am using sparkR (spark 2.0.0, yarn) on cluster with following configuration: 5 machines (24 cores + 200 GB RAM each). Wanted to run sparkR.session() with additional arguments to assign only a percentage of total resources to my job:

```<code>if(Sys.getenv("SPARK_HOME") == "") Sys.setenv(SPARK_HOME = "/...")

library(SparkR, lib.loc = file.path(Sys.getenv('SPARK_HOME'), "R", "lib"))

sparkR.session(master = "spark://host:7077",
               appname = "SparkR",
               sparkHome = Sys.getenv("SPARK_HOME"),
               sparkConfig = list(spark.driver.memory = "2g"
                                 ,spark.executor.memory = "20g"
                                 ,spark.executor.cores = "4"
                                 ,spark.executor.instances = "10"),
               enableHiveSupport = TRUE)
</code>```

The weird thing is that parameters seemed to be passed to sparkContext, but at the same time I end with number of x-core executors which make use of 100% resources (in this example 5 * 24 cores = 120 cores available; 120 / 4 = 30 executors).

I tried creating another spark-defaults.conf with no default paramaters assigned (so the only default parameters are those existed in spark documentation - they should be easily overrided) by:

```<code>if(Sys.getenv("SPARK_CONF_DIR") == "") Sys.setenv(SPARK_CONF_DIR = "/...")
</code>```

Again, when I looked at the Spark UI on http://driver-node:4040 the total number of executors isn't correct (tab "Executors"), but at the same time all the config parameters in tab "Environment" are exactly the same as those provided by me in R script.

Anyone knows what might be the reason? Is the problem with R API or some infrastructural cluster-specific issue (like yarn settings)

答:
I found you have to use the spark.driver.extraJavaOptions, e.g.

```<code>spark <- sparkR.session(master = "yarn",
            sparkConfig = list(
              spark.driver.memory = "2g",
              spark.driver.extraJavaOptions =
              paste("-Dhive.metastore.uris=",
                    Sys.getenv("HIVE_METASTORE_URIS"),
                    " -Dspark.executor.instances=",
                    Sys.getenv("SPARK_EXECUTORS"),
                    " -Dspark.executor.cores=",
                    Sys.getenv("SPARK_CORES"),
                    sep = "")
              ))
</code>```

Alternatively you change the spark-submit args, e.g.

```<code>Sys.setenv("SPARKR_SUBMIT_ARGS"="--master yarn --driver-memory 10g sparkr-shell")
</code>```

Body:
I am using sparkR (spark 2.0.0, yarn) on cluster with following configuration: 5 machines (24 cores + 200 GB RAM each). Wanted to run sparkR.session() with additional arguments to assign only a percentage of total resources to my job:

if(Sys.getenv("SPARK_HOME") == "") Sys.setenv(SPARK_HOME = "/...")

library(SparkR, lib.loc = file.path(Sys.getenv('SPARK_HOME'), "R", "lib"))

sparkR.session(master = "spark://host:7077",
               appname = "SparkR",
               sparkHome = Sys.getenv("SPARK_HOME"),
               sparkConfig = list(spark.driver.memory = "2g"
                                 ,spark.executor.memory = "20g"
                                 ,spark.executor.cores = "4"
                                 ,spark.executor.instances = "10"),
               enableHiveSupport = TRUE)

The weird thing is that parameters seemed to be passed to sparkContext, but at the same time I end with number of x-core executors which make use of 100% resources (in this example 5 * 24 cores = 120 cores available; 120 / 4 = 30 executors).

I tried creating another spark-defaults.conf with no default paramaters assigned (so the only default parameters are those existed in spark documentation - they should be easily overrided) by:

if(Sys.getenv("SPARK_CONF_DIR") == "") Sys.setenv(SPARK_CONF_DIR = "/...")

Again, when I looked at the Spark UI on http://driver-node:4040 the total number of executors isn't correct (tab "Executors"), but at the same time all the config parameters in tab "Environment" are exactly the same as those provided by me in R script.

Anyone knows what might be the reason? Is the problem with R API or some infrastructural cluster-specific issue (like yarn settings)

Body:
I found you have to use the spark.driver.extraJavaOptions, e.g.

spark <- sparkR.session(master = "yarn",
            sparkConfig = list(
              spark.driver.memory = "2g",
              spark.driver.extraJavaOptions =
              paste("-Dhive.metastore.uris=",
                    Sys.getenv("HIVE_METASTORE_URIS"),
                    " -Dspark.executor.instances=",
                    Sys.getenv("SPARK_EXECUTORS"),
                    " -Dspark.executor.cores=",
                    Sys.getenv("SPARK_CORES"),
                    sep = "")
              ))

Alternatively you change the spark-submit args, e.g.

Sys.setenv("SPARKR_SUBMIT_ARGS"="--master yarn --driver-memory 10g sparkr-shell")


问:
SciKit-Learn: JoblibException When Using Random Forest
I'm trying to do a bit of machine learning.  I'm trying to predict engagement time for an article.  I have my X dataset as follows:

```<code>    _text_word_length   _title_char_length  _title_word_length  _text_char_length
0   1306                53                   7                  8056
1   1075                62                   11                 6127
</code>```

and my target Y values are just floats representing engagement time.

I use SciKit-Learn as follows:

```<code>from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import cross_val_score, KFold
import numpy as np
clf = RandomForestRegressor(n_jobs=-1, n_estimators=250, max_features = 0.8, verbose = 2)
score = cross_val_score(estimator = clf, X = X1, y = Y1, cv = KFold(n_splits = 5, random_state = 100), n_jobs = -1, \
                        scoring = "neg_mean_squared_error")
np.mean([np.sqrt(-x) for x in score])
</code>```

Because I'm using verbose mode, it outputs all the trees for the random forest.  It gets through almost all of the trees and then I get this:

```<code>JoblibException: JoblibException
___________________________________________________________________________
Multiprocessing exception:
</code>```

Then there's a ton of text (won't reproduce it here but can upon request).  At the very end, I see this:

```<code>ValueError: I/O operation on closed file
</code>```

I'm totally lost because very similar code worked yesterday so I'm not sure what I'm doing incorrectly.

Any ideas?

Thanks!

答:
Can you try something like the following? So put all your code after if name =='main' with the appropriate indent .

```<code>from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import cross_val_score, KFold
import numpy as np

if __name__ =='main':

    clf = RandomForestRegressor(n_estimators=250, max_features = 0.8, verbose = 2)
    score = cross_val_score(estimator = clf, X = X1, y = Y1, cv = KFold(n_splits = 5, random_state = 100), n_jobs = -1,scoring = "neg_mean_squared_error")
    np.mean([np.sqrt(-x) for x in score])
</code>```

Note that
1) in cross_val_score before scoring=.. there should be a coma and not a slice (/)

2) use only once n_jobs =-1 inside cross_val_score

Body:
I'm trying to do a bit of machine learning.  I'm trying to predict engagement time for an article.  I have my X dataset as follows:

    _text_word_length   _title_char_length  _title_word_length  _text_char_length
0   1306                53                   7                  8056
1   1075                62                   11                 6127

and my target Y values are just floats representing engagement time.

I use SciKit-Learn as follows:

from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import cross_val_score, KFold
import numpy as np
clf = RandomForestRegressor(n_jobs=-1, n_estimators=250, max_features = 0.8, verbose = 2)
score = cross_val_score(estimator = clf, X = X1, y = Y1, cv = KFold(n_splits = 5, random_state = 100), n_jobs = -1, \
                        scoring = "neg_mean_squared_error")
np.mean([np.sqrt(-x) for x in score])

Because I'm using verbose mode, it outputs all the trees for the random forest.  It gets through almost all of the trees and then I get this:

JoblibException: JoblibException
___________________________________________________________________________
Multiprocessing exception:

Then there's a ton of text (won't reproduce it here but can upon request).  At the very end, I see this:

ValueError: I/O operation on closed file

I'm totally lost because very similar code worked yesterday so I'm not sure what I'm doing incorrectly.

Any ideas?

Thanks!

Body:
Can you try something like the following? So put all your code after if name =='main' with the appropriate indent .

from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import cross_val_score, KFold
import numpy as np

if __name__ =='main':

    clf = RandomForestRegressor(n_estimators=250, max_features = 0.8, verbose = 2)
    score = cross_val_score(estimator = clf, X = X1, y = Y1, cv = KFold(n_splits = 5, random_state = 100), n_jobs = -1,scoring = "neg_mean_squared_error")
    np.mean([np.sqrt(-x) for x in score])

Note that
1) in cross_val_score before scoring=.. there should be a coma and not a slice (/)

2) use only once n_jobs =-1 inside cross_val_score


问:
Instant app won't start directly, shows a screen first
I have successfully published a (very simple) Instant App linked to my personal website.

When I click on my website's link, I was expecting the app to start directly, but instead, I first see a screen with 2 buttons: "Open app" and "Open in browser":

Why?

Other instant apps that I tried do not show this screen and open the app directly (the desired behavior).

答: This is designed in my opinion to happen at least once to give the user an opportunity to decide what to use: either browser or the instant apps feature.</p>


问:
Issue with 'Hello Android' tutorial
I am brand new to Eclipse and Android, but somewhat familiar with Java.  That having been said, I tried to follow the 'Hello Android' tutorial from the developer site using the latest Eclipse (Galieo) and the 2.1 Android SDK,  I am on a Macintosh running Snow Leopard (OS X 10.6).  I have a default virtual device (though my target is actually for phones like my own HTC Incredible which has the snapdragon processor and of course all the latest accoutrement in smart phones).

Everything seemed to go okay until I went to RUN>RUN and then selected 'Android Application'.  My computer spins its wheels for a while and then I see two errors.  I have pasted the output from Eclipse below:

```<code>[2010-05-04 01:53:46 - HelloAndroid] ------------------------------
[2010-05-04 01:53:46 - HelloAndroid] Android Launch!
[2010-05-04 01:53:46 - HelloAndroid] adb is running normally.
[2010-05-04 01:53:46 - HelloAndroid] Performing com.example.helloandroid.HelloAndroid activity launch
[2010-05-04 01:53:46 - HelloAndroid] Automatic Target Mode: launching new emulator with compatible AVD 'myAVD'
[2010-05-04 01:53:46 - HelloAndroid] Launching a new emulator with Virtual Device 'myAVD'
[2010-05-04 01:53:58 - HelloAndroid] New emulator found: emulator-5554
[2010-05-04 01:53:58 - HelloAndroid] Waiting for HOME ('android.process.acore') to be launched...
[2010-05-04 01:53:59 - Emulator] 2010-05-04 01:53:59.501 emulator[10398:903] Warning once: This application, or a library it uses, is using NSQuickDrawView, which has been deprecated. Apps should cease use of QuickDraw and move to Quartz.
[2010-05-04 01:54:23 - HelloAndroid] emulator-5554 disconnected! Cancelling 'com.example.helloandroid.HelloAndroid activity launch'!
</code>```

I never do see the text in the emulator and the emulator crashes with a message about it quitting unexpectedly.

The crash report states:

```<code>Process:         emulator [10472]
Path:            /Applications/android-sdk-mac_86/tools/emulator
Identifier:      emulator
Version:         ??? (???)
Code Type:       X86 (Native)
Parent Process:  eclipse [10468]

Date/Time:       2010-05-04 02:25:41.153 -0500
OS Version:      Mac OS X 10.6.3 (10D573)
Report Version:  6

Interval Since Last Report:          2558914 sec
Crashes Since Last Report:           4
Per-App Crashes Since Last Report:   2
Anonymous UUID:                      C5F178C1-5290-4CA9-AD6E-E9C4F5582754

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x000000001fd2f000
Crashed Thread:  3
</code>```

NOTE:  Running the emulator from the command line with:

```<code>iainnitro-Mac:tools iainnitro$ ./emulator -avd myAVD

2010-05-04 02:49:23.011 emulator[10556:903] Warning once: This application, or a library it
uses, is using NSQuickDrawView, which has been deprecated. Apps should cease use of QuickDraw
and move to Quartz.
Segmentation fault
iainnitro-Mac:tools iainnitro$
</code>```

yields a segmentation fault(as noted above from the terminal output).  So the emulator is dying on its own before anything can be shown.

I have tried restarting the ADB processes.

The actual code is line by line from the tutorial and I have never been able to get to the XML part yet.

I am not sure what is wrong with my environment setup or if it is just an incompatibility with Snow Leopard?  I would REALLY appreciate any help in resolving this as I am very interested in developing on this platform.

Thank-you,

Mike N Lawrence, Kansas

答:
This seems to be a timing issue. For some reason Eclipse attempts to load the application on to the emulator before it is "ready". I'm not sure why this occurs but I did find a work around: just start the emulator from the command line before you run the application.

Start clean by closing Eclipse (maybe the OP didn't exit Eclipse before he tried to run via the command line?)

Start the emulator via Terminal by navigating to the android-sdk-mac_86/tools directory and typing:

./emulator -avd my_avd

Open Eclipse and attempt to run the tutorial again using the same steps as before

A dialog box should open asking whether you would like to start a new AVD or use the one that is already running--choose to use the one that is already running.

Title: Issue with 'Hello Android' tutorial

Body:
I am brand new to Eclipse and Android, but somewhat familiar with Java.  That having been said, I tried to follow the 'Hello Android' tutorial from the developer site using the latest Eclipse (Galieo) and the 2.1 Android SDK,  I am on a Macintosh running Snow Leopard (OS X 10.6).  I have a default virtual device (though my target is actually for phones like my own HTC Incredible which has the snapdragon processor and of course all the latest accoutrement in smart phones).

Everything seemed to go okay until I went to RUN>RUN and then selected 'Android Application'.  My computer spins its wheels for a while and then I see two errors.  I have pasted the output from Eclipse below:

[2010-05-04 01:53:46 - HelloAndroid] ------------------------------
[2010-05-04 01:53:46 - HelloAndroid] Android Launch!
[2010-05-04 01:53:46 - HelloAndroid] adb is running normally.
[2010-05-04 01:53:46 - HelloAndroid] Performing com.example.helloandroid.HelloAndroid activity launch
[2010-05-04 01:53:46 - HelloAndroid] Automatic Target Mode: launching new emulator with compatible AVD 'myAVD'
[2010-05-04 01:53:46 - HelloAndroid] Launching a new emulator with Virtual Device 'myAVD'
[2010-05-04 01:53:58 - HelloAndroid] New emulator found: emulator-5554
[2010-05-04 01:53:58 - HelloAndroid] Waiting for HOME ('android.process.acore') to be launched...
[2010-05-04 01:53:59 - Emulator] 2010-05-04 01:53:59.501 emulator[10398:903] Warning once: This application, or a library it uses, is using NSQuickDrawView, which has been deprecated. Apps should cease use of QuickDraw and move to Quartz.
[2010-05-04 01:54:23 - HelloAndroid] emulator-5554 disconnected! Cancelling 'com.example.helloandroid.HelloAndroid activity launch'!

I never do see the text in the emulator and the emulator crashes with a message about it quitting unexpectedly.

The crash report states:

Process:         emulator [10472]
Path:            /Applications/android-sdk-mac_86/tools/emulator
Identifier:      emulator
Version:         ??? (???)
Code Type:       X86 (Native)
Parent Process:  eclipse [10468]

Date/Time:       2010-05-04 02:25:41.153 -0500
OS Version:      Mac OS X 10.6.3 (10D573)
Report Version:  6

Interval Since Last Report:          2558914 sec
Crashes Since Last Report:           4
Per-App Crashes Since Last Report:   2
Anonymous UUID:                      C5F178C1-5290-4CA9-AD6E-E9C4F5582754

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x000000001fd2f000
Crashed Thread:  3

NOTE:  Running the emulator from the command line with:

iainnitro-Mac:tools iainnitro$ ./emulator -avd myAVD

2010-05-04 02:49:23.011 emulator[10556:903] Warning once: This application, or a library it
uses, is using NSQuickDrawView, which has been deprecated. Apps should cease use of QuickDraw
and move to Quartz.
Segmentation fault
iainnitro-Mac:tools iainnitro$

yields a segmentation fault(as noted above from the terminal output).  So the emulator is dying on its own before anything can be shown.

I have tried restarting the ADB processes.

The actual code is line by line from the tutorial and I have never been able to get to the XML part yet.

I am not sure what is wrong with my environment setup or if it is just an incompatibility with Snow Leopard?  I would REALLY appreciate any help in resolving this as I am very interested in developing on this platform.

Thank-you,

Mike N Lawrence, Kansas


问:
Date picker: timezone shift

Problem

If I select a date in a <DateInput>, the datetime is in the user's timezone (e.g. 2017-07-01T00:00:00.000+02:00) but when it's sent to the server, it's transformed to UTC and thus ends up as 2017-06-30T22:00:00.000Z, one day behind.

The underlaying back-end is unaware of the user's timezone and cannot shift the dates back so after stripping the time it ends up with wrong date.

What would solve my problem

Any of these options would work fine:

The datetime is sent with the user's timezone.

The datetime is sent as naive (=without timezone).

The date selected by the user is already treated as UTC.

A date only (2017-07-01) instead of the ISO datetime is sent.

What I tried

I looked at Admin-on-rest's DateInput documentation and haven't found any option to alter the behaviour.

I looked at the related Material-UI's documentation and the only somewhat relevant option appears to be DateTimeFormat but despite a couple of tries I got nowhere.

I checked other answers, e.g Material UI Time Picker UTC but cannot figure out how to apply the suggested solution.

答:
The easiest option is to set a custom function as the parse attribute of <DateInput> which allows to manipulate the value before going into the Redux storage.

```<code>const dateString = v => {
  if (isNaN(v)) return;

  let parsedDate = new Date(v);
  let adjustedDate = new Date(parsedDate.getTime() - parsedDate.getTimezoneOffset() * 60000);

  return adjustedDate;
};

<DateInput source="your_date" parse={dateString} />
</code>```

This is described in the Admin-on-rest documentation and further information can be found in the Redux form documentation on Value Lifecycle Hooks.

NOTE: Credit goes to kunal pareek for his suggestion on how to fix the timezone offset in the other advanced answer.

UPDATE: This might not be working correctly in the current version (as of 08/2018) of Admin-on-rest. See answer by Tomasz Madeyski and/or check the documentation in which the problem has been addressed.

Title: Date picker: timezone shift

Body:
The easiest option is to set a custom function as the parse attribute of <DateInput> which allows to manipulate the value before going into the Redux storage.

const dateString = v => {
  if (isNaN(v)) return;

  let parsedDate = new Date(v);
  let adjustedDate = new Date(parsedDate.getTime() - parsedDate.getTimezoneOffset() * 60000);

  return adjustedDate;
};

<DateInput source="your_date" parse={dateString} />

This is described in the Admin-on-rest documentation and further information can be found in the Redux form documentation on Value Lifecycle Hooks.

NOTE: Credit goes to kunal pareek for his suggestion on how to fix the timezone offset in the other advanced answer.

UPDATE: This might not be working correctly in the current version (as of 08/2018) of Admin-on-rest. See answer by Tomasz Madeyski and/or check the documentation in which the problem has been addressed.


问:
(CMake) PCL + Other libraries
Context : I am following this guide to generate my Visual Studio project with the Point Cloud Library PCL, it seems to be the only way to use it.

Problem : I have realised that with this method I can not include other libraries like the Bitmap_image.hpp or even the string.h

I've tried :

```<code>cmake_minimum_required(VERSION 2.6 FATAL_ERROR)
project(MY_GRAND_PROJECT)
find_package(PCL 1.3 REQUIRED COMPONENTS common io)
include_directories(${PCL_INCLUDE_DIRS})
link_directories(${PCL_LIBRARY_DIRS})
add_definitions(${PCL_DEFINITIONS})
add_executable(pcd_write_test pcd_write.cpp)
target_link_libraries(pcd_write_test ${PCL_COMMON_LIBRARIES} ${PCL_IO_LIBRARIES} ${string})
</code>```

The result:

It generates the project. PCL works perfectly and the line

```<code>#include <string>
</code>```

does not show error.

But

```<code>string a;
</code>```

throws "Error C2065 'string': undeclared identifier"
and the same happens with other libraries.

Any solution?

答:
This is (basic) C++ knowledge and has nothing to do with any part of the build system.

#include <string> pulls in the C++ Standard Library, specifically the container std::string. As long as your compiler knows you are compiling C++ (and Visual Studio knows this from the .cpp file extension), then it will link a version of the C++ Standard Library for you automatically.

All your calls to these parts of the C++ Standard Library need to be prefixed with std:: or you need a using namespace std; somewhere in your code (the second is generally not recommended though).

In other words, remove ${string}, since it was not there in the original CMakeLists.txt file you are following (and also means nothing) and use std::string in your source code etc.

As for Bitmap_image.hpp, you need to indicate where to find it. If it is part of PCL, then that should already be working.

If it is a different library, you will need to learn the basics of CMake to add these libraries. Hint: CMake commands add_library() and target_include_directories() and target_link_libraries(). Also, target_compile_options() and target_compile_definitions() could be useful.

A good modern introduction to CMake is by Daniel Pfeifer.

Title: (CMake) PCL + Other libraries

Body:
Context : I am following this guide to generate my Visual Studio project with the Point Cloud Library PCL, it seems to be the only way to use it.

Problem : I have realised that with this method I can not include other libraries like the Bitmap_image.hpp or even the string.h

I've tried :

cmake_minimum_required(VERSION 2.6 FATAL_ERROR)
project(MY_GRAND_PROJECT)
find_package(PCL 1.3 REQUIRED COMPONENTS common io)
include_directories(${PCL_INCLUDE_DIRS})
link_directories(${PCL_LIBRARY_DIRS})
add_definitions(${PCL_DEFINITIONS})
add_executable(pcd_write_test pcd_write.cpp)
target_link_libraries(pcd_write_test ${PCL_COMMON_LIBRARIES} ${PCL_IO_LIBRARIES} ${string})

The result:

It generates the project. PCL works perfectly and the line

#include <string>

does not show error.

But

string a;

throws "Error C2065 'string': undeclared identifier"
and the same happens with other libraries.

Any solution?


问:
jQuery - How to get an element's class from ajax request
I'm loading my website's pages with ajax by replacing the content inside the main tag.
Problem is, using Wordpress, each page has its own body classes that are useful for styling purposes, so I want to replace the old page's body classes by the next page's classes.

I thought i'd run a new ajax request to get the whole html page, then check for the body element, then use .attr("class") to get the list of class and finally replace the old body classes by the new one...

But the classes always return undefined instead of a list of classes.

EDIT: I tried to use .cd-main-content instead of body and weirdly it works, I get the classes of this element. So I assume now that the problem doesn't come from my syntax but from the element itself.

How can I possibly get it to work on the body element ? (I already tried to replace .find by .filter but it doesn't work either.)

HTML stucture

```<code><body id="body" class="home page-id-number other-classes">
    <main>
        <div class="cd-main-content">
            <!-- inside is the dynamically loaded content-->
        </div>
    </main>
</body>
</code>```

jQuery

```<code>$.ajax({url: url,
    success: function(data){
        var body = $(data).find("#body");
        var classes = body.attr("class");
        console.log(data); //returns the html as expected
        console.log("body : "+body); //returns [object Object]
        console.log("classes : "+classes); //returns undefined
    }
});
</code>```

答:
"body" tag filtering by jQuery when getting from string.

So $(data)[0] will back all content, without body.

Also use filter, not "find"
So you can get classes like that:

```<code>$.ajax({url: url,
    success: function(data){
       //replace body tag
       data = data.replace("<body", "<container").replace("body>", "container>");
       var classes = $(data).filter("container").attr("class");
        $("body").attr("class", classes);
    }
});
</code>```

Body:
I'm loading my website's pages with ajax by replacing the content inside the main tag.
Problem is, using Wordpress, each page has its own body classes that are useful for styling purposes, so I want to replace the old page's body classes by the next page's classes.

I thought i'd run a new ajax request to get the whole html page, then check for the body element, then use .attr("class") to get the list of class and finally replace the old body classes by the new one...

But the classes always return undefined instead of a list of classes.

EDIT: I tried to use .cd-main-content instead of body and weirdly it works, I get the classes of this element. So I assume now that the problem doesn't come from my syntax but from the element itself.

How can I possibly get it to work on the body element ? (I already tried to replace .find by .filter but it doesn't work either.)

HTML stucture

jQuery

$.ajax({url: url,
    success: function(data){
        var body = $(data).find("#body");
        var classes = body.attr("class");
        console.log(data); //returns the html as expected
        console.log("body : "+body); //returns [object Object]
        console.log("classes : "+classes); //returns undefined
    }
});

Body:
"body" tag filtering by jQuery when getting from string.

So $(data)[0] will back all content, without body.

Also use filter, not "find"
So you can get classes like that:

$.ajax({url: url,
    success: function(data){
       //replace body tag
       data = data.replace("<body", "<container").replace("body>", "container>");
       var classes = $(data).filter("container").attr("class");
        $("body").attr("class", classes);
    }
});


问:
MySQL UNION not working
I'm attempting a mysql union but nothing is returned?  Below is an example.  In total there is 16 select queries

```<code>$url_array = array(
   "euro-gbp","euro-aud","euro-usd",
   "euro-jpy","gbp-jpy","euro-cad",
   "usd-cad","usd-jpy","cad-jpy",
   "gbp-usd","aud-usd","gbp-cad",
   "aud-cad","aud-jpy","aud-nzd",
   "euro-nzd","gbp-aud","gbp-nzd",
   "nzd-usd","nzd-cad","nzd-jpy");

foreach($url_array as $urls) {
   $sql[]= "SELECT *
     FROM `data_analysis_child`
     WHERE type='".$urls."'
     ORDER BY id DESC
     LIMIT 2";

}

$sql = implode(" UNION ",$sql);
</code>```

The sql result

```<code>SELECT * FROM `data_analysis_child` WHERE type='euro-gbp' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-aud' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-usd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='usd-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='usd-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='cad-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-usd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='aud-usd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='aud-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='aud-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='aud-nzd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-nzd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-aud' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-nzd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='nzd-usd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='nzd-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='nzd-jpy' ORDER BY id DESC LIMIT 2
</code>```

How do i solve?  Is there a better way to restructure this query?

答:
You could do this:

```<code>SELECT *
FROM (
  SELECT @rank := if (@last_type=type, @rank+1, 1) as type_rank, *
  FROM data_analysis_child
  WHERE type IN ('euro-gbp', 'euro-aud', 'euro-usd'....)
  ORDER BY id DESC
)
WHERE type_rank<=2;
</code>```

But the performance will suck.

Depending on how the indexes are configured and assuming that your id column is unique this might be better:

```<code>SELECT 'first', dac1.*
FROM data_analysis_child dac1
WHERE dac1.id IN (
   SELECT MAX(dac2.id)
   FROM data_analysis_child dac2
   WHERE dac2.type IN ('euro-gbp', 'euro-aud', 'euro-usd'....)
   GROUP BY dac2.type
)
UNION
SELECT 'second', dac3.*
FROM data_analysis_child dac3
WHERE dac3.id IN (
   SELECT MAX(dac4.id)
   FROM data_analysis_child dac4
   WHERE dac4.type IN ('euro-gbp', 'euro-aud', 'euro-usd'....)
   AND dac4.id NOT IN (
      SELECT MAX(dac5.id)
      FROM data_analysis_child dac5
      WHERE dac5.type IN ('euro-gbp', 'euro-aud', 'euro-usd'....)
      GROUP BY dac5.type
   )
   GROUP BY dac4.type
)
</code>```

But it does not scale well to getting the top N values for each type.

A better solution would be to to flag the state of the first or second rank as an attribute on the record and filter directly.

Title: MySQL UNION not working

Body:
I'm attempting a mysql union but nothing is returned?  Below is an example.  In total there is 16 select queries

$url_array = array(
   "euro-gbp","euro-aud","euro-usd",
   "euro-jpy","gbp-jpy","euro-cad",
   "usd-cad","usd-jpy","cad-jpy",
   "gbp-usd","aud-usd","gbp-cad",
   "aud-cad","aud-jpy","aud-nzd",
   "euro-nzd","gbp-aud","gbp-nzd",
   "nzd-usd","nzd-cad","nzd-jpy");

foreach($url_array as $urls) {
   $sql[]= "SELECT *
     FROM `data_analysis_child`
     WHERE type='".$urls."'
     ORDER BY id DESC
     LIMIT 2";

}

$sql = implode(" UNION ",$sql);

The sql result

SELECT * FROM `data_analysis_child` WHERE type='euro-gbp' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-aud' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-usd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='usd-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='usd-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='cad-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-usd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='aud-usd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='aud-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='aud-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='aud-nzd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-nzd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-aud' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-nzd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='nzd-usd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='nzd-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='nzd-jpy' ORDER BY id DESC LIMIT 2

How do i solve?  Is there a better way to restructure this query?

Body:
You could do this:

SELECT *
FROM (
  SELECT @rank := if (@last_type=type, @rank+1, 1) as type_rank, *
  FROM data_analysis_child
  WHERE type IN ('euro-gbp', 'euro-aud', 'euro-usd'....)
  ORDER BY id DESC
)
WHERE type_rank<=2;

But the performance will suck.

Depending on how the indexes are configured and assuming that your id column is unique this might be better:

SELECT 'first', dac1.*
FROM data_analysis_child dac1
WHERE dac1.id IN (
   SELECT MAX(dac2.id)
   FROM data_analysis_child dac2
   WHERE dac2.type IN ('euro-gbp', 'euro-aud', 'euro-usd'....)
   GROUP BY dac2.type
)
UNION
SELECT 'second', dac3.*
FROM data_analysis_child dac3
WHERE dac3.id IN (
   SELECT MAX(dac4.id)
   FROM data_analysis_child dac4
   WHERE dac4.type IN ('euro-gbp', 'euro-aud', 'euro-usd'....)
   AND dac4.id NOT IN (
      SELECT MAX(dac5.id)
      FROM data_analysis_child dac5
      WHERE dac5.type IN ('euro-gbp', 'euro-aud', 'euro-usd'....)
      GROUP BY dac5.type
   )
   GROUP BY dac4.type
)

But it does not scale well to getting the top N values for each type.

A better solution would be to to flag the state of the first or second rank as an attribute on the record and filter directly.


问:
UILabel dynamically change font size and keep position?
I have to change a font size and while I do it :

Keep it centered in the same position

adjust the frame to fit.

When I do number 2, it will not stay centered :

```<code>   label.font = label.font.withSize(max*percentage)
  label.sizeToFit()
</code>```

If I don't, i will have to change frame and find how it fit the font dynamically.
Is there any elegant way of 2 rows ?

答:
Ended doing this :</p>

```<code>let center:CGPoint=editedView.center // first take the center
label.font = label.font.withSize(max*percentage)
label.sizeToFit() // set right size
label.center=center //then set it back
</code>```

Body:
I have to change a font size and while I do it :

Keep it centered in the same position

adjust the frame to fit.

When I do number 2, it will not stay centered :

   label.font = label.font.withSize(max*percentage)
  label.sizeToFit()

If I don't, i will have to change frame and find how it fit the font dynamically.
Is there any elegant way of 2 rows ?

Body:
Ended doing this :

let center:CGPoint=editedView.center // first take the center
label.font = label.font.withSize(max*percentage)
label.sizeToFit() // set right size
label.center=center //then set it back