text:
Q: How to only check for messages after a specific person sent a message ? Discord JS Hello I am trying to use a discord bot to wait for a message from an admin of my server and then check the following messages from users. My code waits for the admin message however it somehow caches it ?? At least it doesnt check the users messages. I made my bot write the message where it got triggered to make it more understandable:
const Discord = require("discord.js");
const bot = new Discord.Client();
const bot_config = require("./settings.json")
var token = bot_config.usertoken
var userid = bot_config.userid
var channel = "940800688219369483"; //

bot.on("ready", () => {
    console.log(`SUCCESSFULLY LOGGED IN AS ${bot.user.tag}!`);
});
let counter = 0
bot.on("message", (msg) => {

//Waiting for mesage from specific admin
if(msg.author == "1011983215650672781"){

if(counter == 0){ // check if message has already been send
    if (msg.channel.id != channel) return; // Checks valid Channel ID

    if (msg.author == userid && msg.author == "703629528454660106" && msg.authot == "255396012045238222" && msg.authot == "142772377047199744" && msg.authot == "235748962103951360") { //CHECK IF NEXT MESSAGE IS NOT AN ADMIN
        console.log("ADMIN MESSGAE");
    }
    else{
        let answer = msg.content
        bot.channels.cache.get(channel).send(answer)
        counter ++
        console.log("SUCCESSFULLY SENT MESSAGE")
        }
}
else{
    console.log("ALREADY SENT MESSAGE - CLOSE BOT")
}
}
})
bot.login(usertoken)

The problem is, the bot still writes the first admin message in the channel and not the onw from the first user

A: You might kick yourself for this, but you have used msg.authot instead of msg.author.id.
You may want to check out the docs, they come in handy when you need to know how to access properties.


text:
Q: Change div color back to normal on seperate div click I'm experiencing the issue of being unable to change the div color back to its original color using JS. The same format of JS works well for other functions, such as moving divs around and showing/hiding other divs. However, when I try to include the changing of colors, it doesn't work.
Below is my JS code, the issue lies under the sidebar (<div2>):

var button = document.getElementById("id_switch");
var div2 = document.getElementById("id_sidebar");
var div = document.getElementById("id_button_switch");
var div3 = document.getElementById("id_sun_icon");
var div4 = document.getElementById("id_lightMode");
var div5 = document.getElementById("id_moon_icon");
var div6 = document.getElementById("id_darkMode");

button.addEventListener("click", function() {
  if (div.style.marginLeft === "20px") {
    div.style.marginLeft = "2.5px";
  } else {
    div.style.marginLeft = "20px";
  };
});
button.addEventListener("click", function() {
  if (div2.style.backgroundColor === "#012342") {
    div2.style.backgroundColor = "#202023";
  } else {
    div2.style.backgroundColor = "#012342";
  };
});
button.addEventListener("click", function() {
  if (div3.style.display === "flex") {
    div3.style.display = "none";
  } else {
    div3.style.display = "flex";
  };
});
button.addEventListener("click", function() {
  if (div5.style.display === "none") {
    div5.style.display = "flex";
  } else {
    div5.style.display = "none";
  };
});
button.addEventListener("click", function() {
  if (div4.style.display === "flex") {
    div4.style.display = "none";
  } else {
    div4.style.display = "flex";
  };
});
button.addEventListener("click", function() {
  if (div6.style.display === "none") {
    div6.style.display = "flex";
  } else {
    div6.style.display = "none";
  };
});
/* Google Font Import - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}
/*---------------------------------------------------------------------------------------------*/
body{
    min-height: 100vh;
    /*background-color: rgb(30, 29, 29)*/;
    background-color: #000000;
    transition: var(--tran-05);
}

/*----------------------------------SIDE BAR--------------------------------*/
 .sidebar{
    position: fixed;
    top: 0;
    left: 0;
    height: 100%;
    width: 19%;
    padding: 10px 14px;
    background-color: #202023;
    transition: var(--tran-05);
    z-index: 100;
}
/*----------------------------------SIDEBAR HEADER--------------------------------*/
.sidebar li{
    height: 50px;
    list-style: none;
    display: flex;
    align-items: center;
    margin-top: 10px;
}

.sidebar header .image,
.sidebar .icon{
    min-width: 60px;
    border-radius: 6px;
}

.sidebar .icon{
    min-width: 60px;
    border-radius: 6px;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
}

.sidebar .text,
.sidebar .icon{
    color: #FFF;
    transition: var(--tran-03);
}

.sidebar .text{
    font-size: 17px;
    font-weight: 500;
    white-space: nowrap;
    opacity: 1;
}
.sidebar .menu{
    margin-top: 40px;
}
.sidebar li a{
    list-style: none;
    height: 100%;
    background-color: transparent;
    display: flex;
    align-items: center;
    height: 100%;
    width: 100%;
    text-decoration: none;
    transition: var(--tran-03);
}
.sidebar .menu-bar{
    height: calc(100% - 55px);
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    overflow-y: scroll;
}
.mode{
    background-color: #303034;
    position: relative;
    transition: var(--tran-05);
}
.sun-moon i.sun,
.mode-textL{
    display: none;
}
.toggle-switch{
    position: absolute;
    right: 0;
    height: 100%;
    min-width: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 0px;
    cursor: pointer;
}
.switch{
    position: relative;
    height: 22px;
    width: 40px;
    border-radius: 0px;
    background-color: #000000;
    transition: var(--tran-05);
}
.button_switch{
    background-color: #FFF;
    position: relative;
    padding: 1px;
    height: 70%;
    width: 40%;
    margin-top: 2.5px;
    margin-left: 2px;
}
/*-----------------------------------------------------------*/
.home{
    position: absolute;
    top: 0;
    top: 0;
    left: 250px;
    height: 100vh;
    width: calc(100% - 250px);
    background-color: var(--body-color);
    transition: var(--tran-05);
}
.home .text{
    font-size: 30px;
    font-weight: 500;
    color: var(--text-color);
    padding: 12px 60px;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="stackoverflowExample.css">

    <link href='https://unpkg.com/boxicons@2.1.1/css/boxicons.min.css' rel='stylesheet'>

                        Logout

Dark mode

Light mode

I have included a JSFiddle version to view the full thing: https://jsfiddle.net/sya1r8x6/

A: the div2.style.backgroundColor returns an rgb color
a simple solution would be to just replace #012342 to rgb(1, 35, 66)

var button = document.getElementById("id_switch");
var div2 = document.getElementById("id_sidebar");
var div = document.getElementById("id_button_switch");
var div3 = document.getElementById("id_sun_icon");
var div4 = document.getElementById("id_lightMode");
var div5 = document.getElementById("id_moon_icon");
var div6 = document.getElementById("id_darkMode");

button.addEventListener("click", function() {
  if (div.style.marginLeft === "20px") {
    div.style.marginLeft = "2.5px";
  } else {
    div.style.marginLeft = "20px";
  };
});
button.addEventListener("click", function() {
console.log(div2.style.backgroundColor);
  if (div2.style.backgroundColor === "rgb(1, 35, 66)") {//here is the change
    div2.style.backgroundColor = "#202023";
  } else {
    div2.style.backgroundColor = "#012342";
  };
});
button.addEventListener("click", function() {
  if (div3.style.display === "flex") {
    div3.style.display = "none";
  } else {
    div3.style.display = "flex";
  };
});
button.addEventListener("click", function() {
  if (div5.style.display === "none") {
    div5.style.display = "flex";
  } else {
    div5.style.display = "none";
  };
});
button.addEventListener("click", function() {
  if (div4.style.display === "flex") {
    div4.style.display = "none";
  } else {
    div4.style.display = "flex";
  };
});
button.addEventListener("click", function() {
  if (div6.style.display === "none") {
    div6.style.display = "flex";
  } else {
    div6.style.display = "none";
  };
});
/* Google Font Import - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}
/*---------------------------------------------------------------------------------------------*/
body{
    min-height: 100vh;
    /*background-color: rgb(30, 29, 29)*/;
    background-color: #000000;
    transition: var(--tran-05);
}

/*----------------------------------SIDE BAR--------------------------------*/
 .sidebar{
    position: fixed;
    top: 0;
    left: 0;
    height: 100%;
    width: 19%;
    padding: 10px 14px;
    background-color: #202023;
    transition: var(--tran-05);
    z-index: 100;
}
/*----------------------------------SIDEBAR HEADER--------------------------------*/
.sidebar li{
    height: 50px;
    list-style: none;
    display: flex;
    align-items: center;
    margin-top: 10px;
}

.sidebar header .image,
.sidebar .icon{
    min-width: 60px;
    border-radius: 6px;
}

.sidebar .icon{
    min-width: 60px;
    border-radius: 6px;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
}

.sidebar .text,
.sidebar .icon{
    color: #FFF;
    transition: var(--tran-03);
}

.sidebar .text{
    font-size: 17px;
    font-weight: 500;
    white-space: nowrap;
    opacity: 1;
}
.sidebar .menu{
    margin-top: 40px;
}
.sidebar li a{
    list-style: none;
    height: 100%;
    background-color: transparent;
    display: flex;
    align-items: center;
    height: 100%;
    width: 100%;
    text-decoration: none;
    transition: var(--tran-03);
}
.sidebar .menu-bar{
    height: calc(100% - 55px);
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    overflow-y: scroll;
}
.mode{
    background-color: #303034;
    position: relative;
    transition: var(--tran-05);
}
.sun-moon i.sun,
.mode-textL{
    display: none;
}
.toggle-switch{
    position: absolute;
    right: 0;
    height: 100%;
    min-width: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 0px;
    cursor: pointer;
}
.switch{
    position: relative;
    height: 22px;
    width: 40px;
    border-radius: 0px;
    background-color: #000000;
    transition: var(--tran-05);
}
.button_switch{
    background-color: #FFF;
    position: relative;
    padding: 1px;
    height: 70%;
    width: 40%;
    margin-top: 2.5px;
    margin-left: 2px;
}
/*-----------------------------------------------------------*/
.home{
    position: absolute;
    top: 0;
    top: 0;
    left: 250px;
    height: 100vh;
    width: calc(100% - 250px);
    background-color: var(--body-color);
    transition: var(--tran-05);
}
.home .text{
    font-size: 30px;
    font-weight: 500;
    color: var(--text-color);
    padding: 12px 60px;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="stackoverflowExample.css">

    <link href='https://unpkg.com/boxicons@2.1.1/css/boxicons.min.css' rel='stylesheet'>

                        Logout

Dark mode

Light mode

redpajama_set_name: RedPajamaStackExchange


text:
Q: https session login/logout with java Just a very simple question.  I have set up a rather simple CMS in JSP.  All I need is a security measure to maintain the system's privacy.  Does anyone know of any tutorials that assist in building https sessions for simple networks??
I have more or less conquered (or grasped) the main portions of building databases, using CRUD, and making the programs interact between the java code and the JSP.  This is basically the final hurdle before I can securely and confidently launch this thing and get it going.
Any and all information is always appreciated.

A: There is a class called SSLSession that you can use:
This is the tutorial
This is the documentation

A: You might want to look into session management closely if your site is critical. In simple terms, make a form to get username/password. If they match, use jsp's
To login :
session.setAttribute("login", "true");

To check if the user is logged in,
boolean logged = session.getAttribute("login") != null


text:
Q: Error when compiling python 3.3.2 I downloaded Python 3.3.2 on Ubuntu 12.04 and I followed the instructions of README to compile the files:
./configure
make
test make
sudo make install

but when I applying the command MAKE I hold the following error:
**FileExistsError: [Errno 17] File exists (mode 775 !=  expected mode 755): 'build/lib.linux-i686-3.3'
make: *** [pybuilddir.txt] Error 1**

The 'build/lib.linux-i686-3.3' is a directory but I can't figure out to what file is refered that FileExistsError

A: Well, you have probably the package with python3.3.1 installed. Unfortunately, the file lib.linux-i686-3.3 has the same major version. Either remove python3.3.1 (which will break oh so many dependencies), or install python in another directory, for example using
./configure --prefix /usr/local


text:
Q: Getting Error when connection to MySQL database I have downloaded the following:

*

*mysql-essential-5.1.65-win32 from this MySQL Dev link

*MySQL Connector mysql-connector-java-5.1.21.zip from this link
Now I have started programming with Eclipse. I have made simple java class like below,
public class MySQLAccess {

      private static Connection connect = null;
      private Statement statement = null;
      private PreparedStatement preparedStatement = null;
      private ResultSet resultSet = null;

      public static void main(String[] args){

          try{
              Class.forName ("com.mysql.jdbc.Driver").newInstance ();

          }catch (Exception e) {
            // TODO: handle exception
              System.out.println("Error : "+e);
        }
      }
}

I have also made a folder "lib" in my Java project and I have put that mysql-connector jar over there. But when I run this program it can't find mysql I get the following error in the console :
Erro : java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

Can someone please tell me where I have made the mistake? Thank you

A: Putting the full jar-file path in your classpath and restarting cmd (if you are running from cmd) should work-
See here- java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

A: If it your java application project then you put jar file into jdk  library path ext folder.
eg:
C:\Program Files\Java\jdk1.6.0_13\jre\lib\ext

you will get path from your project class path .


text:
Q: I need to get a distinct list based on a column in SQL var sqlStatement = string.Format("select * from CardDecks where deckid = {0}", id);
var getcardid = db.CardDecks.SqlQuery(sqlStatement).ToList();
var getDistinct = getcardid.Distinct().ToList();

What I expect from this code is for the last list to only pull distinct values but it still pulls duplicates. I need for it to only pull back the list with unique values based on cardid. What am I missing?

A: I changed the SQL statement to this and it works:
   List<CardDeck> distictList = getcardid.GroupBy(p => p.CardID).Select(g => g.First()).ToList();

A: You could write your query like this:
select distinct column1, column2, column3 from CardDecks where deckid = {0}

... where column1, column2, column3 are the columns that you want to show.


text:
Q: Error when compiling in production mode "is not a function" Vue Laravel Mix I have a Laravel, VueJs, VueRouter, Vuex application using Webpack to compile my assets.
package.json
{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "npm run development -- --watch",
        "watch-poll": "npm run watch -- --watch-poll",
        "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
    },
    "devDependencies": {
        "@fortawesome/fontawesome-free": "^5.14.0",
        "axios": "^0.18",
        "bootstrap": "^4.0.0",
        "laravel-mix": "^3.0.0",
        "lodash": "^4.17.19",
        "popper.js": "^1.12",
        "vue": "^2.5.7"
    },
    "dependencies": {
        "@fullcalendar/core": "^5.11.3",
        "@fullcalendar/daygrid": "^5.11.3",
        "@fullcalendar/interaction": "^5.11.3",
        "@fullcalendar/list": "^5.11.3",
        "@fullcalendar/timegrid": "^5.11.3",
        "@fullcalendar/vue": "^5.11.3",
        "ajv": "^6.12.3",
        "animate.css": "^3.7.2",
        "aos": "^2.3.4",
        "apexcharts": "^3.33.0",
        "chart.js": "^2.7.3",
        "element-ui": "^2.4.8",
        "imagemin": "^6.0.0",
        "jquery": "^3.4.1",
        "moment": "^2.27.0",
        "node-sass": "^4.14.1",
        "numeral": "^2.0.6",
        "simple-keyboard": "^2.29.72",
        "toastr": "^2.1.4",
        "vue-apexcharts": "^1.6.2",
        "vue-chartjs": "^3.4.0",
        "vue-data-tables": "^3.4.5",
        "vue-router": "^3.5.2",
        "vue-touch-keyboard": "^0.3.2",
        "vuedraggable": "^2.24.3",
        "vuex": "^3.5.1",
        "xml-js": "^1.6.11"
    }
}

when i build in production mode npm run prod i get the error s is not a function
but if i build in dev like npm run watch or npm run dev i don't get the error.
How can I debug where the error is in the code so I can fix it? It only shows me in the vue.common.prod line.

vue.common.prod.js:11 TypeError: s is not a function
at e (vue.common.prod.js:11:68600)

my file webpack.mix.js
const mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.js('resources/js/front/app.js', 'public/js')
    .extract(['vue','vuex', 'jquery', 'bootstrap', 'axios', 'element-ui', 'lodash', 'moment', 'popper.js'])
    .version();

mix.webpackConfig({
    resolve: {
        extensions: ['.js', '.json', '.vue'],
        alias: {
            '@': path.join(__dirname, './resources/js'),
            '~': path.join(__dirname, './resources/js/front'),
            '@@': path.join(__dirname, './modules'),
            '@components': path.join(__dirname, './resources/js/components')

        }
    },
    output: {
         filename:'[name].js',
         chunkFilename: 'js/[name].js',
    },
}).sourceMaps()

A: *

*option 01) :
check the function you wrote

This is a standard JavaScript error when trying to call a function before it is defined. This error occurs if you try to execute s function that is not initialized or is not initialized correctly. This means that the expression did not return s function object. So you need to understand that what you are trying to achieve is not s feature.

*

*option 02) :
remove node_module and clear cache npm cache clear --force.
after that reinstall node_module by using npm install.

*option 03) :
check your imported thing forgot the curly braces in an import statement.


text:
Q: ExecuteSqlCommand with DbContext We are using repository and unit of work patterns for our application
I have the below method to execute stored proc:
 /*** Execute stored procedure ***/
        public virtual void ExecuteProcedure(String procedureCommand, params SqlParameter[] sqlParams)
        {
            Ctxt.Database.ExecuteSqlCommand(procedureCommand, sqlParams);
        }

My client repository will invoke the method as below:
 //Check lock conditions for site part vrsm
        public bool CanLock(int spvId)
        {
            SqlParameter output = new SqlParameter("editMode", SqlDbType.Bit);
            output.Direction = ParameterDirection.Output;

        SqlParameter parameter = new SqlParameter("spvId", SqlDbType.Int);
        parameter.Value = spvId;

        ExecuteProcedure("exec [dbo].[prc_SitePartVrsn_CanLock] {0}, @editMode = {1} output", parameter, output);

        return Convert.ToBoolean(output.Value);
    }

However line ExecuteProcedure is failing with

"Incorrect syntax near 0"

I don't have any other information in Innerexception or no clue from stack trace.
The procedure is working fine when I execute it in database.
Can somebody advise what is the problem ???

A: You don't need much of a change, it is only a syntax issue:
ExecuteProcedure("exec prc_SitePartVrsn_CanLock @spvId, @editMode OUTPUT", parameter, output);

And you can either use [dbo].[prc_SitePartVrsn_CanLock] or prc_SitePartVrsn_CanLock

A: have you tried
ExecuteProcedure("exec [dbo].[prc_SitePartVrsn_CanLock] @spvId, @editMode", parameter, output);


text:
Q: Duplicate Zip Entry after Gradle Plugin v0.13.1 I've been using the Gradle Android plugin v0.12 but I decided to upgrade to the new version, because I needed the new functionality (and the improved speed is always a plus).
After updating to the new v0.13.1, I keep getting the "Duplicate Zip Entry" (from Proguard) while everything worked before. The full error:

java.io.IOException: Can't write [/Users/.../classes-proguard/netherlands/release/classes.jar] (Can't read [/Users/.../.gradle/caches/modules-2/files-2.1/org.apache.commons/commons-io/1.3.2/b6dde38349ba9bb5e6ea6320531eae969985dae5/commons-io-1.3.2.jar(;;;;;;!META-INF/MANIFEST.MF)] (Duplicate zip entry [commons-io-1.3.2.jar:org/apache/commons/io/CopyUtils.class])) (CopyUtils was FileUtils before).

I'm using following packaging options: packagingOptions
{
   exclude 'AndroidManifest.xml'
   exclude 'META-INF/DEPENDENCIES'
   exclude 'META-INF/notice.txt'
   exclude 'META-INF/license.txt'
   exclude 'META-INF/LICENSE.txt'
   exclude 'META-INF/NOTICE.txt'
   exclude 'META-INF/MANIFEST.MF'
   exclude '!META-INF/MANIFEST.MF'
   exclude 'META-INF/services/javax.annotation.processing.Processor'
}

As you can tell, I'm excluding the manifest files...
Just to test it, I changed back to version 0.12.0 and everything works again, back to 0.13.* and it breaks (but I need 0.13.*)!
Further, I'm using the following libraries:

*

*Robospice

*Retrofit

*OkHttp

*Dart

*Icepick

*Butterknife

*Crouton

*SmoothProgressBar

*NineoldsAndroid (in library of BetterPickers)

Did anyone encounter this issue too? If so, can anyone please help me out (been breaking my head for 2 days on this issue now!)? Thanks!

A: I had the same issue when updating to Android Gradle plugin 0.13. I managed to fix it by including retrofit this way in my build.gradle file:
compile('com.squareup.retrofit:retrofit:1.6.1') {
    exclude group: 'commons-io', module: 'commons-io'
}

Edit: And can do this on all retrofit and robospice dependcies at once with:
compile('com.octo.android.robospice:robospice-retrofit:1.4.14') {
    exclude group: 'commons-io', module: 'commons-io'
}

It will get all underlying dependencies automatically (retrofit, robospice-core, robospice-cache, ...).

A: I had the same issue. In my case I hadn't done a build for a few months, and found that the dependency  compile 'org.apache.commons:commons-io:1.3.2' is no longer valid (though I guess the jars were still in my local repository).
Once I changed it to  compile 'commons-io:commons-io:1.3.2', proGuard ran fine.

A: By Using CjS answer I was able to solve this. Even Gaetan Answer is also works.
Adding to this
I solved the Issue by Using This, if your compileSdkVersion is 19(IN MY CASE)
compile ('org.apache.httpcomponents:httpmime:4.3'){
    exclude group: 'org.apache.httpcomponents', module: 'httpclient'
}
compile ('org.apache.httpcomponents:httpcore:4.4.1'){
    exclude group: 'org.apache.httpcomponents', module: 'httpclient'
}
compile 'commons-io:commons-io:1.3.2'

else if your compileSdkVersion is 23
then use
android {
useLibrary 'org.apache.http.legacy'
packagingOptions {
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
    }
}

A: The problem is in libs that you're using.
Add in gradle file:
android {
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/MANIFEST.MF'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE'
    }
}


text:
Q: Why is my calc() failing when used in a table in all browsers except Chrome? I'm using calc to specify the width of a table's  cells. This works in Chrome, but no other browsers.
Caniuse doesn't mention any issues relating to calc in other browsers.
HTML:

      One
      Two
      Three
      Four

CSS (though I'm using Sass):
table {
    width: 1200px;
    margin: 20px auto 0;
    table-layout: fixed;
}

th:nth-child(2n) {
    background: grey;
}

th.first {
    width: calc(100% * 0.1);
}

th.second {
    width: calc(100% * 0.4);
}

th.third {
    width: calc(100% * 0.25);
}

th.fourth {
    width: calc(100% * 0.25);
}

As you can see, IE11 resolves all cells to the same width:

There is a CodePen here.


text:
Q: putting a space between the 3rd and 4th characters of postal code in Python I have a df (data frame) in Python with with a postal_code variable that has Canadian  postal codes. All the postal codes are collected in a row such as k1b6j2. But , for me to use the the 'pgeocode' package i need the postal code in a standard form which is like k1b 6j2 (there must be a space between the 3rd and 4th character)
So, is there a way to replace all the postal codes with the modified ones in the df?
Many Thanks,
Ben

A: In pandas, you can use "apply" to achive your require.
df['postal_code'] = df['postal_code'].apply(lambda x:x[:3]+' '+x[-3:])

A: You can simply redefine your column in the format you are expecting:
import pandas as pd
df = pd.DataFrame({'ID':[1,2,3,4],'postal_code':['k1b6j2','k1b6j3','k1b6j4','k1b6j5']}) ##Example dataset

   ID postal_code
0   1      k1b6j2
1   2      k1b6j3
2   3      k1b6j4
3   4      k1b6j5

Redefine the postal_code column in the format you desire:
df['postal_code'] = df['postal_code'].astype(str)
df['postal_code'] = [(x[:3]+" "+x[3:]) for x in df['postal_code']]

Output:
   ID postal_code
0   1     k1b 6j2
1   2     k1b 6j3
2   3     k1b 6j4
3   4     k1b 6j5

Finally compared to some other methods in a 100k length dataframe:
df['postal_code'] = [(x[:3]+" "+x[3:]) for x in df['postal_code']]
First method time:  0.08260965347290039
df['postal_code'] = df["postal_code"].str[:3] + " " + df["postal_code"].str[3:]
Second method time:  0.112518310546875

A: Another way to do this is to use the pandas string support that has a bunch of nice methods to work on strings such as direct slicing of string columns:
>>> import pandas as pd
>>> df = pd.DataFrame({"index": range(10), "code": ["k1b6j2"]*10})
>>> df["postal_code"] = df["code"].str[:3] + " " + df["code"].str[3:]
>>> df
   index    code postal_code
0      0  k1b6j2     k1b 6j2
1      1  k1b6j2     k1b 6j2
2      2  k1b6j2     k1b 6j2
3      3  k1b6j2     k1b 6j2
4      4  k1b6j2     k1b 6j2
5      5  k1b6j2     k1b 6j2
6      6  k1b6j2     k1b 6j2
7      7  k1b6j2     k1b 6j2
8      8  k1b6j2     k1b 6j2
9      9  k1b6j2     k1b 6j2

A: Apply this to all postal codes in the df:
code_with_space = code_without_space[:3] + " " + code_without_space[3:]

A: How about:
pcode = 'k1b6j2'
pcode = pcode[:3] + ' ' + pcode[3:]


text:
Q: Domain and Codomain after adding function I have two functions $H_1,H_2:\mathbb{R} \to \mathbb{R}$ and I want to define a new function $g(x)=H_1(x) + H_2(x)$. Would the domain and codomain off this function still be all the real numbers? Thanks

A: Domain of the sum of two functions is the intersection of the domains of each function, since $H_1(x)+H_2(x)$ only makes sense when both $H_1(x)$ and $H_2(x)$ are defined. In this case, the intersection of $\Bbb R$ and $\Bbb R$ is $\Bbb R$.
Both $H_1,H_2$ are real valued, so $H_1+H_2$ is also real valued. You can keep the codomain as $\Bbb R$ but remember that the codomain can also be a superset of $\Bbb R$ (or sometimes even a proper subset depending upon $H_1,H_2$) since a function does not need to attain all values in its codomain.


text:
Q: Can't delete my first item in shopping basket Currently doing my computing science assignment and I've chosen to make an online shop, I've used a tutorial to make the shopping basket and everything is working except I can only delete every item except the first one added to my cart. I'd really appreciate any help if possible.
This is where items in my cart are displayed (cart.php):
<?php
session_start();
require_once('db.php');
include('common.php');
 ?>

 <?php getHeader(); ?>

            <?php
                $items = $_SESSION['cart'];
                $cartitems = explode(",", $items);
            ?>

            <?php
                $total = '';
                $i=1;
                 foreach ($cartitems as $key=>$id) {
                    $sql = "SELECT * FROM products WHERE id = $id";
                    $res = mysqli_query($con, $sql);
                    $r = mysqli_fetch_assoc($res);
            ?>

                    <?php echo $i; ?>
                    <a href="delcart.php?remove=<?php echo $key; ?>">Remove <?php echo $r['name']; ?>
                    £<?php echo $r['price']; ?>

            <?php
                $total = $total + $r['price'];
                $i++;
                }
            ?>

                Total Price
                £<?php echo $total; ?>
                Checkout

<?php getFooter(); ?>

This is my code that adds an item to my cart(addtocart.php):
    <?php
session_start();
if(isset($_SESSION['cart']) & !empty($_SESSION['cart'])){
    $items = $_SESSION['cart'];
    $cartitems = explode(",", $items);
    $items .= "," . $_GET['id'];
    $_SESSION['cart'] = $items;
    header('location: index.php?status=success');
}else{
    $items = $_GET['id'];
    $_SESSION['cart'] = $items;
    header('location: index.php?status=success');
}

if(in_array($_GET['id'], $cartitems)){
    header('location: index.php?status=incart');
}else{
    $items .= "," . $_GET['id'];
    $_SESSION['cart'] = $items;
    header('location: index.php?status=success');
}
?>

This is my delete item code (delcart.php):
<?php
session_start();
$items = $_SESSION['cart'];
$cartitems = explode(",", $items);
if(($_GET['remove']) & !empty($_GET['remove'])){
    $delitem = $_GET['remove'];
    unset($cartitems[$delitem]);
    $itemids = implode(",", $cartitems);
    $_SESSION['cart'] = $itemids;
}
header('location:cart.php');
?>

A: The problem is this line:
if ($_GET['remove'] & !empty($_GET['remove']))

When you want to remove the first item, $_GET['remove'] is 0, which is falsey and also considered empty, so the code that's supposed to remove it doesn't run. Change it to:
if (isset($_GET['remove']) && is_numeric($_GET['remove']))

Also, throughout your scripts you're using & when you should be using &&. & is bit-wise AND, && is logical AND.

A: When you have only one item in your session,
$cartitems = explode(",", $items);

result is array with "0" index, so if you want to remove last value, $_GET['remove'] should be equal to "0" (example: www.site.loc/?remove=0)
I hope you show us only a sample (not production) code because it is very wrong written and dangerous example:

$sql = "SELECT * FROM products WHERE id = $id"; SHOULD NEVER BE USE!

A: There's a few things wrong with your code:
1) $_SESSION['cart'] appears to be a string of comma-separated ids, i.e. string(10) "1, 2, 3, 4"
Thus, $cartitems = explode(",", $items) would return an array of those ids, i.e. array(4)[ 1, 2, 3, 4 ]
2) Assuming that $_GET['remove'] is a string containing the item id, i.e. 3
Calling unset($cartitems[$delitem]) would remove the last element of my example array, 4, since arrays are zero-indexed.
To remove the value 3 you'd have to call:
$delitem = array_search($_GET['remove'], $cartitems);
unset($cartitems[$delitem]);

(see http://php.net/array_search)
3) May I please suggest using PDO? http://php.net/manual/en/book.pdo.php
Edit: since I can't comment, Barmar:
Given that OP's items are stored in a database, and id is likely a primary key, it's unlikely that he'd have an item with id of 0 so empty() should be perfectly suitable for his needs. To expound on that point, though, OP, Barmar is correct that in if there are in fact 0 based ids, you'd want to use isset($_GET['remove']) not !empty($_GET['remove'])
See http://php.net/isset and http://php.net/empty for differences.

A: Your loop and then usage of the variables is the problem:
                 foreach ($cartitems as $key=>$id) {
...
                      <a href="delcart.php?remove=<?php echo $id; ?>">Remove <?php echo $r['name']; ?>
...
                 }

The $key should be $id
When using foreach this way, the $key var is the array index and the $id is the value (which could be a string, array, object, int...).
http://php.net/manual/en/control-structures.foreach.php
But since you don't care about the array index here, you can simply omit it from the foreach declaration:
                 foreach ($cartitems as $id) {

and it will work identically.


text:
Q: How can I tell if I'm doing a create or an update with django generic views (CreateView vs UpdateView) from my template? I'm sharing the same template for my CreateView and UpdateView using django's generic views. I want the "submit" button in my template to say "Add" when I'm using the CreateView and "Update" when I'm using the UpdateView. Is there any way in my template to distinguish which view is being used (CreateView vs UpdateView)?
I know I could use a separate template using template_name_suffix and put the common stuff in a separate include or something but just wanted to see if there was a way to do it without creating a separate template.

A: Override get_context_data and add a flag in your view:
def get_context_data(self, **kwargs):
    context = super(YourClass, self).get_context_data(**context)
    context['create_view'] = True
    return context

Change YourClass to your Class View name
Then in your template you can:
{% if create_view %}

A: When creating a new object, object will always be None, at the moment the template is rendered. You could check for the existence of {{ object }} in your template:
{% if object %}Update{% else %}Add{% endif %}


text:
Q: Extending a C++ application with embedded scripting I am developing a C++ application that needs to be multiple platform compatible (Windows/Linux) and want to grant users the ability to extend the software to fit their needs exactly without allowing them to change critical parts of the application (so I do not want them in the C++ code).
What I am looking for is to embed a scripting language (I would prefer Python because I am familiar with it already, but it's not mandatory), so scripts put in some plugin folder can manipulate objects of the application if I want these objects to be modifyable.
The most simple example: if someone wants to build their own UI for my application, they should be able to do so with such a script.
The problem however is, that I've never put C++ and any kind of external scripts together, so I really do not know how to start. After looking for material to get started, I found that Lua claims to be a good language to do that, but I could not find good beginner tutorials.
I would really appreciate if someone knew a good place to start, be it online resources, or a good book. I wouldn't mind spending a few bucks on a good book.
As a learner, I tend to learn best from a mix of example code and a few lines explaining those.

A: I would suggest you to read Programming in Lua, this book has an entire section on how to embed Lua in C (and C++).
It is very highly rated by Amazon users.
The language has also pretty good online documentation and a active mailing list.

A: If you want to use Python I would definitely suggest using Boost.Python. It is an incredibly well designed library. Just an example: all you have to do to expose a C++ class to Python is this:
struct World
{
    void set(std::string msg) { this->msg = msg; }
    std::string greet() { return msg; }
    std::string msg;
};

BOOST_PYTHON_MODULE(hello)
{
    class_<World>("World")
        .def("greet", &World::greet)
        .def("set", &World::set)
    ;
}

It handles almost everything automatically: conversions between types, exceptions, it even allows you to use reference counted objects between the two languages with boost::shared_ptr.

A: The article here at linux journal is a good place to start on how to embed a python interpreter in your c/c++ code. This is only half the battle however because when the interpreter is embedded, you then need to publish some part of your software to the scripting environment. The basic API to do so is in C and if most of your code is C++, it might be best to use boost::python since writing C wrappers around your C++ classes might be cumbersome. You can also use Py++ to generate the boost::python binding.
If you only want to use scripting as a door to customization and you can live with the memory footprint of python, it might be a better choice than Lua. Lua is usually good for small environment like game development. There is also a lot more python developers than lua developers as well as more built-ins and third party libraries available.

A: for Python, I guess the boost library is meant to do it. As for Lua, I haven't used it myself, but a quick Google search first led me to debian admin and then to Lua's C interface. Have you looked into those?


text: Q: Pyglet: how to handle heavy resources loading I'm learning pyglet in order to write a game, and I've trying to create a loading screen/scene while loading all game resources (static images and image sprites), to avoid window freeze while loading. I wonder what are the best practices to handle heavy resources loading with pyglet, on window/game startup or between scenes.


text:
Q: Using APEX to assemble HTML Letterhead Emails I am looking to assemble an HTML Letterhead Email Template for an email service integration project.
There are two sObjects that hold this information - EmailTemplate and BrandTemplate.
BrandTemplate.value = broken HTML (styles aren't associated to tags) Letterhead with CDATA tags throughout to hold the email Template info
EmailTemplate.HTMLValue = User-created HTML email template
I've been trying to merge the two (don't need to worry about merge fields / codes) with little success.
I have tried turning both into XML, navigating the BrandTemplate.value field, but Salesforce does not natively support CDATA.  I've also tried the polar opposite - stripping everything into text and doing replaces and substrings to assemble, but that also fails.
My end goal is to have a completed single HTML document consisting of both the BrandTemplate and EmailTemplate values.
Any hints / thoughts / clues?

A: When accessing templates and needing multiple objects I will
 -  select the template from the database
 -  define a merge syntax, use regular expressions "{!([A-z_]+)}" to get a key name
 -  pass a map of data to replace the key (if exists) with data
you now have a template which is just a string. you can push the template to a VF page with
or send an email manually in code.
code example:
public static Map<String,String> merge_template(Map<String,String> obj, EmailTemplate email){
    Map<String,String> data = new Map<String,String>();
    String html = email.HtmlValue;
    if(html!=null){
        html = m(html,obj,Pattern.compile('(\\{![A-Za-z_]+\\})').matcher(html));
        data.put('HtmlValue',html);
    }
    else{
        data.put('HtmlValue','');
    }
    String body = email.Body;
    String subject = email.Subject;
    body = m(body,obj,Pattern.compile('(\\{![A-Za-z_]+\\})').matcher(body));

    data.put('Body',body);

    return data;

}
private static String m(String body,Map<String,String> obj,Matcher m){
    while(m.find()){
      String merge_field = m.group(0);
      String field = merge_field.substring(1,merge_field.length()-1);
      String value;
      try{
        value = (String) obj.get(field);
      }
     catch(Exception e){
        value='';
     }
     if(value!=null){
        body = body.replace(merge_field,value);
     }
     else{
        body = body.replace(merge_field,'');
     }
    }
    return body;
}

public static Map<String,String> build(String template,Map<String,String> data){
    EmailTemplate[] tpls = [SELECT HtmlValue,Body,Subject FROM EmailTemplate WHERE DeveloperName = :template];
    if(tpls.isEmpty() == true){
        return "";
    }
    return merge_template(data,tpls.get(0);
}

A: Salesforce hacking time:
I had this exact requirement, and was stuck for a while because of the weird connection between EmailTemplate and BrandTemplate, and the inability to leverage a merging/parsing function however, I found a solution, this is far from a clean solution, but it seems to be working perfectly.
First what you will do is, create a single email message (like you would send it from apex):
// Here we will build the single email message
Messaging.reserveSingleEmailCapacity(1);
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[]{'invalid@emailaddr.es'};
mail.setToAddresses(toAddresses);
mail.setUseSignature(false);
mail.setSaveAsActivity(false);
mail.setSenderDisplayName('MMPT');
mail.setTargetObjectId(UserInfo.getUserId());
mail.setTemplateId(sendTemplate.Id);

What we will do next is trick salesforce in sending the single email message, by setting a savepoint, sending the message and rolling back. The single email will not be send because of the rollback.
Savepoint sp = Database.setSavepoint();
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
Database.rollback(sp);

But now the beauty comes, because we triggered the sendEmail method, the email template got merged with the brandtemplate and the parsing took place. And you can find the parsed versions of your template components in the next variables (Subject, Text and HTML)
String mailTextBody = mail.getPlainTextBody();
String mailHtmlBody = mail.getHTMLBody();
String mailSubject = mail.getSubject();

This is far from what salesforce meant to do with single email message, and since we cannot leverage the platform parsing and merging functions, this did gave me a solution to this problem unfortunately through some hacking.

A: Summer 16 introduces two new methods that (finally) eliminate the clever hack by @pjcarly:
For VF, HTML, and Plain Text templates:
Messaging.SingleEmailMessage email =
            Messaging.renderStoredEmailTemplate(templateId, whoId, whatId);

To get just the merged results from the templateBody (and any errors)
List<Messaging.RenderEmailTemplateBodyResult> resList =
        Messaging.renderEmailTemplate(String whoId, String whatId, List<String> bodies)

where bodies is a list of strings corresponding to the value of EmailTemplate.body as queried from the database
for (EmailTemplate et: [select Body from EmailTemplate where DeveloperName IN ('foo','bar')])
  bodies.add(et.Body);

A: try to user the setTemplateId field of Mail.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
EmailTemplate et=[SELECT id,name, subject,HtmlValue FROM EmailTemplate where name='xyz'];
mail.setTemplateId(et.id);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

No need to do any custom parsing.

A: You should be able to create a VF Email Template, and embed a VF Component within it to query those sObjects with an Apex controller.

A: I had some other idea to do this.
EmailTemplate template = [
SELECT Id, Name, Subject, Body, HtmlValue
FROM EmailTemplate
WHERE Name = 'My Name'];
templateId = template.Id;

Custom_Object__c obj = [
SELECT Name, Custom_Field_1__c, Custom_Field_2__c
FROM Custom_Object__c
WHERE Id = :my.Id];

Map<String, String> data = new Map<String, String>();
for(String key:new List<String> {'Name', 'Custom_Field_1__c', 'Custom_Field_2__c' })
{
    data.put('{!Custom_Object__c.' + key + '}', (String) obj.get(key) );
    System.debug( LoggingLevel.ERROR,'@@@ key : ' + key );
    System.debug( LoggingLevel.ERROR,'@@@ obj.get(key) : ' + obj.get(key) );

}
data.put('User.FirstName',UserInfo.getFirstName());
data.put('User.LastName',UserInfo.getLastName());
String body = template.HtmlValue;
System.debug(LoggingLevel.ERROR,body);
System.debug(LoggingLevel.ERROR,'@@@  template.HtmlValue: ' +  template.HtmlValue );
System.debug( LoggingLevel.ERROR,'@@@   template.Subject: ' +   template.Subject );

String subj = template.Subject;
for(String key:data.keySet())
{
    body = body.replace(key, data.get(key));
    subj = subj.replace(key, data.get(key));
}

Unfortunately it does not for email templates with letter heads.


text:
Q: How to implement Google's PlaceAutoCompleteFragment into a class that extends Fragment I'm trying to use Google's Place Autocomplete (https://developers.google.com/places/android-api/autocomplete) to implement into a fragment in my app. But I got this error when navigating from this fragment to other fragment and then coming back into this fragment
 Caused by: java.lang.IllegalArgumentException: Binary XML file line #30: Duplicate id 0x7f0f010f, tag null, or parent id 0x7f0f00c0 with another fragment for com.google.android.gms.location.places.ui.PlaceAutocompleteFragment
                  at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2148)

This is the java code
private PlaceAutocompleteFragment mSearchPAF;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.some_layout, container, false);
    mSearchLocationPAF = (PlaceAutocompleteFragment) parentActivity.getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
}

This is the XML file
<RelativeLayout
    android:id="@+id/someRelativeLayout"
    android:layout_width="wrap_content"
    android:layout_height="36dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="30dp"
    android:background="@drawable/some_drawable">
    <fragment
        android:id="@+id/place_autocomplete_fragment"
        android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</RelativeLayout>

I also have another map fragment in this same java and xml file but I managed to solve it by following the answers in this post (Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment) but I can't find any solution for this Place Autocomplete fragment

A: I have solved this problem myself by following one of the answers here
Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment
private PlaceAutocompleteFragment mSearchPAF;
@Override
public void onDestroyView() {
    super.onDestroyView();
    PlaceAutocompleteFragment f = (PlaceAutocompleteFragment) getFragmentManager()
                                     .findFragmentById(R.id.place_autocomplete_fragment);
    if (f != null)
        getFragmentManager().beginTransaction().remove(f).commit();
}

A: I am currently working on my Project and implemented my main activity with multiple fragments(Still a novice in Android Studio). In my Navigation fragment, I used an googleAutocomplete provided by Google.
This code here is implemented inside the OnCreateView().

mPlace_Starting = (PlaceAutocompleteFragment)
        this.getChildFragmentManager().findFragmentById(R.id.place_starting);

AutocompleteFilter countryFilter = new AutocompleteFilter.Builder()
        .setTypeFilter(Place.TYPE_COUNTRY)
        .setCountry("PH")
        .build();

mPlace_Starting.setFilter(countryFilter);

mPlace_Starting.setOnPlaceSelectedListener(new PlaceSelectionListener() {
    @Override
    public void onPlaceSelected(Place place) {
        // TODO: Get info about the selected place:
        Log.i(TAG, "Starting Place:" + place.getName());
        Toast.makeText(getActivity(), "Starting Place: " + place.getName(),
                Toast.LENGTH_SHORT).show();

        double mLongitude = place.getLatLng().longitude;
        double mLatitude = place.getLatLng().latitude;

        mStartingpoint = new Waypoint(mLongitude,mLatitude);
        mStartpoint = new GeoCoordinate(mLongitude,mLatitude);
    }
    @Override
    public void onError(Status status) {
        //TODO: Handle the Error.
        Log.i(TAG, "An error occured: " + status);
    }
});

I inflated my PlaceAutocompleteFragment widget from Google by using getChildFragmentManager() since the widget is a fragment to be inflated inside another fragment(my Navigation Fragment).


text:
Q: Delphi generics invalid cast I'm using Delphi XE3 and
I don't understand why the first cast below does not compile :(
type
  TBase = class
  end;

  TDerived = class(TBase)
  end;

 procedure cast();
 var
   bases : TObjectList<TBase>;
   deriveds : TObjectList<TDerived>;

 begin
   bases := deriveds; // specific to generid, Here !
   deriveds := bases; // generic to specific, ok should not compile as is !
 end;

A: It's simple: These are two different types, and are incompatible. The whole idea of Generics is to make typecasting strict, and the compiler is doing exactly what it's designed to do - prevent you from mixing types up.


text:
Q: How to make the right hand monitor the primary monitor This has been discussed before. I tried similar (older) solutions, without succes.
I am using 14.04 with nvidia proprietary drivers. In the nvidia xcontrol, I can set which display is primary, but this does absolutely nothing. In the system display settings all I can do is move the display orientation around. However, whatever monitor is 'left' or 'primary' makes no difference.
I have tried:

*

*editing and deleting the xml file called 'monitors.xml', which had no effect

*rebooting with one monitor disconnected, which had no effect

*I can set where the launcher is also, but this has no effect on where full screen applications launch.

Not only that, but every time I change my monitor settings, even if its just swapping left/right all my icons move??
If I put a shortcut or icon on the desktop it should stay in the same spot relative to the physical screen no matter what software settings I change.
Also adding this link to another thread Change Primary monitor ; this is mostly what I've tried so far with no effect.

A: Okay, that looks like an old answer and things aren't as bad in 14.04 as they once were. Yes, the monitor on the left is usually the primary monitor and it is set this way by default.
The unity desktop is actually called the ubuntu-desktop and the reason for this is because unity is actually a compiz plugin so you are actually using a compiz desktop. With that said, you can install compizconfig-settings-manager to achieve the settings you desire.
Either look for it in the ubuntu software center or open a terminal and execute the following commands to install it, whatever you prefer:
sudo apt-get update

sudo apt-get install compizconfig-settings-manager

After installation, search for ccsm in your apps or type the command:
ccsm

to start it up.

Now, click on "general options" and navigate to the "Display Settings" tab.
For the setting "Overlaping Output Handling" you can set which output device (monitor) is preferred as the primary monitor. You can set this to "smart mode" to automatically choose the primary monitor, to prefer the "larger output" (bigger screen) or "smaller output" (smaller screen).
Also, you can go down to where it says "outputs" if they are both the same size and you can click on either one of the outputs which will open the option to move the device up or down. You can also choose edit and you should be able to manually edit the dimensions to change one smaller or larger.

ccsm settings and standard desktop settings are sort of like state and federal law in the United States: federal law (ccsm settings) always trumps state law (standard desktop settings).

A: Drag your display/secondary monitor to first place and apply the changes.


text:
Q: Angular 5 routing with query string I am writing my angular 5+ app and using AuthGuardService what I am doing is that I am redirecting from another php application which send me form data in query string
http://localhost:44200/#/users/save?first_name=John&last_name=Doe

the AuthGuardService properly redirect user to login if he is not logged in with following code
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
    if(localStorage.getItem('crmUser')){
      return true;
    }
    this.router.navigate(['/login'], { queryParams: {returnUrl: state.url},queryParamsHandling: 'merge' });
    return false;
}

But after login I can redirect to return url if it has no query string, I want to redirect user to same page with all query string.
Please guide me how to handle it.

A: This is how I did it. In your AuthGuard#canActivate add the following:
@Injectable()
export class AuthGuard implements CanActivate{

  originRoute:ActivatedRouteSnapshot;

  constructor(private authentificationService: AuthChecker,
              private router: Router){}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if(localStorage.getItem('crmUser')){
       return true;
    }
    this.originRoute = route;
    this.router.navigate(['/login'], { queryParams: {returnUrl: state.url},queryParamsHandling: 'merge' });
    return false;

    }
  }

  public hasOriginRoute(): boolean{
    return this.originRoute != null;

  }
}

Now in your LoginComponent when login succeeded add:
if(this.authGuard.hasOriginRoute()){
   this.router.navigate(this.authGuard.originRoute.url.map((x) => x.path));
}


text:
Q: Deserialising JSON into a generic object I have a three classes
public class A<T>
{
    public bool Success {get; set;}
    public string Reason {get; set;}
    public T Data {get; set;}
}

public class B
{
    public string Token {get; set;}
}

public class C
{
    public int SomeInt {get; set;}
    public string SomeString {get; set;}
    public double SomeDouble {get; set;}
}

I call my web service and pass in A or A to deserialise into like this
 async Task<T> MyTask<T>(...) (where T is A<B> or A<C>)

The service works fine and returns some JSON which if I try and to deserialise into a var, I'm getting nothing deserialised
To deserialise, I'm using
 var foo = JsonConvert.DeserializeObject<T>(response.Content);

Is there a limitation to how I can deserialise the object so I can only use a base class rather than this form of class?

A: Yes, you can not just pass A because A is not base class, it is generic class and does not exists on its own.
C# generates generic classes during compile time, which means if you use A<B> in your code, C# will generate something like:
public class generated_A_B
{
    public bool Success { get; set; }
    public string Reason { get; set; }
    public B Data { get; set; }
}

Nothing will be generated for A<C>, if not explicitly used. Reason is obvious, if you generate classes for every single combination of the A, you will bloat your code.
In your current situation it is better to just call them explicitly
void Main()
{
    CallAB();
    CallAC();
}

A<B> CallAB()
{
    return ServiceCall<A<B>>("/api/ab");
}

A<C> CallAC()
{
    return ServiceCall<A<C>>("/api/ac");
}

If you really want to get "generic" A, you should make A an actual base class and have your API to return the type of Data. In my example I just use Name of the type, but you probably should use FullName that includes namespace, to avoid name conflicts.
void Main()
{
    var json = @"
    {
        ""success"": true,
        ""reason"": ""All good"",
        ""type"": ""B"",
        ""data"": {
            ""token"": ""1234-5678""
        }
    }";
    var foo = JsonConvert.DeserializeObject<A>(json);
    var type = Assembly.GetExecutingAssembly().GetTypes().Where(i => i.IsClass && i.Name == foo.Type).FirstOrDefault();
    if (type == null)
    {
        throw new InvalidOperationException(string.Format("Type {0} not found", foo.Type));
    }
    var data = foo.Data.ToObject(type);
}

public class A
{
    public bool Success { get; set; }
    public string Reason { get; set; }
    public string Type { get; set; }
    public JToken Data { get; set; }
}

public class B
{
    public string Token { get; set; }
}

A: I would recommend either to go for the easy solution: create an intermediate merged your classes B and C, to something like
    public class BC
    {
        public string Token { get; set; }
        public int SomeInt { get; set; }
        public string SomeString { get; set; }
        public double SomeDouble { get; set; }

        public bool IsB => !String.IsNullOrEmpty(Token);

        public B ToB() => new B() { Token = Token };

        public C ToC() => new C() { SomeInt = SomeInt, SomeString = SomeString, SomeDouble = SomeDouble };
    }

Then you can call your service, and convert BC either to B or C:
async Task<A<BC>> MyTask<A<BC>>(...)
var abc = await MyTask(...);
if(abc.Data.IsB)
{
    var resB = abc.data.ToB();
}
else
{
    var resC = abc.data.ToC();
}

Or go to the more complicated solution, with some JsonConverter as explained in this answer:
how to implement custom jsonconverter in json net to deserialize a list of base


text:
Q: Get data from md-select I am using Angular Material to make my new web app, I want to get the selected value from an <md-select> and the problem is that I am new to angularjs and how it works. If anyone could help me, it would be really appreciated.
HTML :
<md-input-container>
        Rating
         <md-select ng-model="userRating">
            <md-option>None
            </md-option>
            <md-option ng-repeat="rate in ratings" ng-value="rate.abbrev">
                {{rate.abbrev}}
            </md-option>
        </md-select>
</md-input-container>

A: You can just get the value by using the $scope variable
In controller
console.log($scope.userRating);
Inorder to get the selected value on change , you can pass the selected to a function and display,
<md-select ng-change="Print()" class="inline-flex md-select-down" placeholder="Select" ng-model="model">
      <md-option ng-repeat="item in ratings" value="{{item.value}}">
        {{item.abbrev}}
      </md-option>
 </md-select>

Controller:
$scope.Print = function(){
        alert($scope.model);
}

DEMO


text:
Q: arcpy.da.NumPyArrayToTable() RuntimeError: Unspecified error Using arcpy for ArcGIS Desktop 10.7.1...
In order to append data from a Pandas data frame to an ArcGIS table, I am attempting to create a temporary in-memory table from the Pandas data frame as follows:
tmpTable = "in_memory/tmpTable"
labResults = pandas.read_csv(csvPath, parse_dates=[3], dayfirst=True)

######  If this ONE next line is commented out and the following line is UNCOMMENTED, the error does NOT occur
labResults['ResultQualifier'] = np.where(labResults.Result.str[0].str.isdigit(), None, labResults.Result.str[0])
#labResults['ResultQualifier'] = np.where(labResults.Result.str[0].str.isdigit(), labResults.Result.str[0], labResults.Result.str[0])

labResults['ResultValue'] = pandas.to_numeric(np.where(labResults.Result.str[0].str.isdigit(), labResults.Result, np.where(labResults.Result.str[1].str.isdigit(),
labResults.Result.str[1:], labResults.Result.str[2:])))
del labResults['Result']
labResults.rename(columns={'ResultValue': 'Result'}, inplace=True)

arr = np.array(np.rec.fromrecords(labResults.values))
arr.dtype.names = tuple(labResults.dtypes.index.tolist())
arcpy.da.NumPyArrayToTable(arr, tmpTable)
######  ERROR OCCURS on this next line
arcpy.Append_management(tmpTable, resultsTable, "NO_TEST")

But the arcpy.da.NumPyArrayToTable() fails with the frustratingly generic error:
`RuntimeError: Unspecified error`

I can print the data frame by entering labResults on the Python console, and it prints out the expected data.  And labResults.dtypes produces the expected output also, so I'm confident that the data frame is all OK.
NB:  I get the same error whether tmpTable is a fGDB table (fGDB exists, table does not) or an in_memory table.
How can I get this to work as expected?
Note:  This code is based on:  https://my.usgs.gov/confluence/display/cdi/pandas.DataFrame+to+ArcGIS+Table where there is a full explanation of what it all does.
SAMPLE DATA:
"JobNo","LabNo","SampleID","DateSampled","Method","AnalyteCode","Units","Result"
90529,366330,"site1",15/1/19 10:15:00,"Glyphosate and Glufosinate in Water by LC-MS/MS","Glyphosate","µg/L","<5"
90529,366330,"site1",15/1/19 10:15:00,"Solids, Total Suspended dried at 104 ± 3 °C","TSS","mg/L","21"
90529,366331,"site2",15/1/19 10:35:00,"Glyphosate and Glufosinate in Water by LC-MS/MS","Glyphosate","µg/L","<5"
90529,366331,"site2",15/1/19 10:35:00,"Solids, Total Suspended dried at 104 ± 3 °C","TSS","mg/L","577"
90529,366332,"site3",15/1/19 11:00:00,"Glyphosate and Glufosinate in Water by LC-MS/MS","Glyphosate","µg/L","<5"

UPDATE:
I have found that if I change the labResults['ResultQualifier'] = line to never include NULLs (None's), then the error does NOT occur.  This line is there to create a new column in the data frame that includes either < if the first character of 'Result' is not a digit, or otherwise 'None' (NULL).  I'm not sure why NULL values would be causing such a problem.

A: It appears that arcpy.da.NumPyArrayToTable() fails on NULL (None) values - at least in my case.  This doesn't appear to be universal, as other people report that it converts such values to the strings None or NaN or other such variations.  However, in my case it fails when there are NULL values and works when there are not NULL values.  (Perhaps this is a new problem in 10.7.1, or perhaps there is some other factor at play here.)  I cannot think of any reason why it should not be able to handle NULLs properly, as both Numpy arrays and ArcGIS Tables can handle NULLs (except for in Shapefiles).
So my tried, tested and proven work around is...
Replace the line:
labResults['ResultQualifier'] = np.where(labResults.Result.str[0].str.isdigit(), None, labResults.Result.str[0])

with:
labResults['ResultQualifier'] = np.where(labResults.Result.str[0].str.isdigit(), '', labResults.Result.str[0])

and then AFTER the arcpy.da.NumPyArrayToTable() add the line:
arcpy.CalculateField_management(tmpTable, 'ResultQualifier', "None if !ResultQualifier! == '' else !ResultQualifier!", "Python")

EXPLANATION:
Instead of creating NULL/None values in the Pandas data frame (and Numpy array), create empty strings instead ('').  Then after converting to an ArcGIS table, run a calculate field to convert the empty strings to NULLs (Nones).
UPDATE
It appears that NaN values may also cause a similar problem, although in this case the error was 'Unable to create table'.  Replacing them with -999999999 in Pandas data frame before arcpy.da.NumPyArrayToTable() and then converting these values to NULLs (None) in the GIS table afterwards worked around the issue for me again.


text:
Q: Create subclass with different subclass property Say I have this Class
@interface CustomClass : NSObject

@property (nonatomic, strong) NSArray * nicestArrayEver;

@end

And I want to create a subClass of CustomClass, but here is the catch
@interface ASubClassCustomClass : CustomClass

@property (nonatomic, strong) NSMutableArray * nicestArrayEver;

@end

The issue as you can imagine is that when I initialize ASubClassCustomClass and call it's super initializer (since there is other properties required) the inmutable nicestArrayEver is created.. how can I avoid it's creation so I can set the mutable one?
Note: This is just an example, the real implementation calls a heavy to create and really customized subclass (is not an NSArray).

A: You can make it work, by using different backing variables, when synthesizing it looks like this: @synthesize nicestArrayEver = nicestArrayEverSubClass_;
#import <Foundation/Foundation.h>

@interface CustomClass : NSObject

@property (nonatomic, strong) NSArray * nicestArrayEver;

@end

@implementation CustomClass
@synthesize nicestArrayEver ;

-(id)init
{
    if (self = [super init]) {
        nicestArrayEver = [[NSArray alloc] init];
    }
    return self;
}
@end

@interface ASubClassCustomClass : CustomClass

@property (nonatomic, strong) NSMutableArray * nicestArrayEver;

@end

@implementation ASubClassCustomClass
@synthesize nicestArrayEver = nicestArrayEverSubClass_;

-(id)init{
    if (self = [super init]) {
        nicestArrayEverSubClass_ = [[NSMutableArray alloc] init];
    }
    return self;
}
@end

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        CustomClass *c1 = [[[CustomClass alloc] init] autorelease];
        ASubClassCustomClass *c2 = [[[ASubClassCustomClass alloc] init] autorelease];

        NSLog(@"%@", NSStringFromClass([[c1 nicestArrayEver] class]));
        NSLog(@"%@", NSStringFromClass([[c2 nicestArrayEver] class]));

    }
    return 0;
}

output
2012-05-27 01:59:16.221 NicestArray[2312:403] __NSArrayI
2012-05-27 01:59:16.225 NicestArray[2312:403] __NSArrayM

Another approach could be to have 2 init methods in the base class, one, that will instantiate the property and one, that won't, but leaves that task for the child class — this will prevent you from creating expensive objects just to throw them away.
Now the base class could get instantiated directly with the second init and go to a false state. You can avoid this by checking the self class type with isMemberOfClass:, and throw an error, if the class type is the base class.
@interface CustomClass : NSObject

@property (nonatomic, strong) NSArray * nicestArrayEver;
-(id)initWithoutArray;
@end

@implementation CustomClass
@synthesize nicestArrayEver ;

-(id) initWithoutArray
{
    if (self = [super init]) {
        if ([self isMemberOfClass:[CustomClass class]]) {
            [NSException raise:@"AbstractMethodCall" format:@"%@ should be called only from Subclasses of %@", NSStringFromSelector(_cmd), NSStringFromClass([self class])];
        }
    }
    return self;
}

-(id)init
{
    if (self = [super init]) {
        nicestArrayEver = [[NSArray alloc] init];
    }
    return self;
}
@end

@interface ASubClassCustomClass : CustomClass

@property (nonatomic, strong) NSMutableArray * nicestArrayEver;

@end

@implementation ASubClassCustomClass
@synthesize nicestArrayEver = nicestArrayEverSubClass_;

-(id)init{
    if (self = [super initWithoutArray]) {
        nicestArrayEverSubClass_ = [[NSMutableArray alloc] init];
    }
    return self;
}

@end

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        CustomClass *c1 = [[[CustomClass alloc] init] autorelease];
        ASubClassCustomClass *c2 = [[[ASubClassCustomClass alloc] init] autorelease];

        NSLog(@"%@", NSStringFromClass([[c1 nicestArrayEver] class]));
        NSLog(@"%@", NSStringFromClass([[c2 nicestArrayEver] class]));

        //this works, as it is the subclass
        ASubClassCustomClass *shouldWork = [[[ASubClassCustomClass alloc] init] autorelease];

        // ouch!
        CustomClass *shouldCrash = [[[CustomClass alloc] initWithoutArray] autorelease];

    }
    return 0;
}

A: I don't see the reason why you would want to do that, but I would advise you to do as follows: in your subclass declare a separate NSMutableArray property (let's call it nicestMutableArrayEver) and override the getter for your superclass NSArray property to return the mutableArray instance:
- (NSArray *)nicestArrayEver {
    return [self nicestMutableArrayEver];
}

This way, you could get back your mutableArray whenever you reference the superclass property.
Best,

A: Properties should almost never have mutable type. If they do, then a caller can obtain the pointer and mutate the object's properties behind its back. If a property should be externally mutable, that should be through mutation methods.
Remember that properties define interface, not implementation. @synthesize can create implementation from the property declaration, but if that would do the wrong thing you shouldn't use it.
So, the first step is to define the interface for your class and subclass, without regard for implementation. Only after you know what the interfaces should be should you design the implementation of each.
Whether or not a property is externally mutable, the backing instance variable may need to be mutable. The class may need to mutate its own property purely internally.
You could make the base class have a designated initializer which takes the array object as a parameter (of type id so that the subclass's override doesn't have to cast to treat it as an NSMutableArray*). Then, the class's "normal" initializers would call that designated initializer with the NSArray to use. The subclass's designated initializer would call the superclass's designated initializer, passing in the NSMutableArray to use.
Alternatively, the base class initializer(s) could call out to another method to obtain the array. The base class implementation would return an NSArray. The subclass could override that method to return an NSMutableArray.

A: You can't really do that. Just create CustomClass with NSMutableArray. You could create them as type id and check isKindOfClass: but that's just a chore and not really necessary.
There are really only two reasons I could see to do what you're asking:

*

*To avoid the extra overhead of NSMutableArray

*To prevent CustomClass from modifying the contents of the array unless it is a ASubClassCustomClass.

While these are good goals, I'd say that in this case it's worth it to simplify a bit.


text:
Q: Uncaught (in promise) TypeError: setMessage is not a function I try to fetch data from the server and then send it to the frontend.
function App() {

  const {message, setMessage} = useState("")

  useEffect(() => {
    fetch(`http://localhost:8080/message`)
    .then((res) => res.json())
    // .then((data => console.log(data.message)))  <---- This work just fine
    .then((data) => setMessage(data.message))
  })

  return (

hi there

{message}

  )

}

export default App;

I got this error on the console :
TypeError: setMessage is not a function
Console logging the data and rendering the 'hi there' heading was successful.
I didn't know what went wrong, could anyone help me?
Thank you.
I tried to pass the setMessage an anonymous function, but that didn't work too.
.then((data) => setMessage(() => data.message))

A: Just change this
const {message, setMessage} = useState("")

to this
const [message, setMessage] = useState("")

A: It's just a problem with your destructuring assignment. Given the fact that you need to destructure an array, you need to enclose your variable names into [ and ] instead of { and }, see the snippet below which illustrates the problem you faced.

let foo = ['a', 'b']
const {x1, y1} = foo;
const [x2, y2] = foo;

console.log(x1, y1);
console.log(x2, y2);


text:
Q: "Time" Command in Cygwin in Windows Command Line I want to run a query using db2 in WINDOWS COMMAND LINE:
code:
db2 connect to sample;
db2 "Select * from TB1";

I am currently doing the IBM Lab activity in Data Concurrency and Locking and I want to determine and quantify the waiting time of the executed command using the "time command" in linux.
I have heard of the Cygwin and successfully installed it in my computer to execute UNIX/LINUX command. I test if "Time" Command can be successfully read by windows cmd using "bash"

I tried to execute this command to get the execution time of the query:

I also tried to include the connect to database

but still it keeps on saying

SQL1042N A database connection does not exist. SQLSTATE=08003

I am really new in DB2 and unfamiliar with Linux command... any help would bee greatly appreciated
Thank You

A: I could help you with "time" and DB2, but my recommendation is look into using the command db2batch. It is designed to benchmark, i.e., get timing for SQL commands. There are various options for the output.
When using "time", do you know how the reported numbers need to be interpreted?

A: could you try this;
create script.sql  in  "C:\Program Files\IBM\SQLLIB\BIN\" as below;
connect to sample;
Select * from TB1;

and then run this;
bash -c "time db2 -tvf script.sql"


text:
Q: How to generate Text as Image within Listview ItemTemplate I have listview in which I want to generate my email data as image. Follwing is my code.
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Drawing.Text" %>
<%@ Import Namespace="System.Drawing.Imaging" %>
<%@ Import Namespace="System.Drawing.Drawing2D" %>

 <asp:ListView ID="lvtest" runat="server"
      CellPadding="0"
      RepeatDirection="Horizontal"
      GroupPlaceholderID="itemPlaceholdersp"
      ItemPlaceholderID="itemPlaceholdersp" >
      <LayoutTemplate>
           <asp:PlaceHolder ID="itemPlaceholdersp" runat="server"></asp:PlaceHolder>
      </LayoutTemplate>
      <ItemTemplate>

<%# Eval("UserName") %>

                     <%# Eval("Designation").ToString() == "" ? "" : Eval("Designation") + "
" %>
                     <%# Eval("Qualification").ToString() == "" ? "" : Eval("Qualification")+ "
" %>

                     <%
                          Response.Clear();
                          int height = 100;
                          int width = 200;
                          Random r = new Random();
                          int x = r.Next(75);

                          Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
                          Graphics g = Graphics.FromImage(bmp);

                          g.TextRenderingHint = TextRenderingHint.AntiAlias;
                          g.Clear(Color.Orange);
                          g.DrawRectangle(Pens.White, 1, 1, width-3, height-3);
                          g.DrawRectangle(Pens.Gray, 2, 2, width-3, height-3);
                          g.DrawRectangle(Pens.Black, 0, 0, width, height);
                          g.DrawString(Eval("Email").ToString(), new Font("Arial", 12, FontStyle.Italic),
                          SystemBrushes.WindowText, new PointF(x,50) );

                          bmp.Save(Response.OutputStream, ImageFormat.Jpeg);
                          g.Dispose();
                          bmp.Dispose();
                          Response.End();
                      %>

<%# Eval("Description")%>

    </ItemTemplate>
</asp:ListView>

But it doesn't work.error occured as
Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.

Please help me.

A: The error you described is not caused by your rendering code, but by the lack of a valid data source for your list view. I've simplified your code a little bit. It should cause the same error (if we are looking at the actual markup):
<asp:ListView ID="lvtest" runat="server">
    <ItemTemplate>

<%# Eval("UserName") %>

    </ItemTemplate>
</asp:ListView>

You are trying to evaluate an UserName property but do not specify the source of it. You have to either specify a DataSource directly, or refer to a DataSourceID:
<asp:ObjectDataSource ID="MyDataSource" runat="server"></asp:ObjectDataSource>

<asp:ListView ID="lvtest" runat="server" DataSourceID="MyDataSource">
    <ItemTemplate>

<%# Eval("UserName") %>

    </ItemTemplate>
</asp:ListView>

Note that the above could doesn't do anything and will likely lead to other errors. For further details, you can refer to the official documentation or one of the may tutorials around the web.


text:
Q: How to use internal memory in Android Studio? I have only been making apps on Android Studio for about 3 months, and I am making an app for Higher or Lower. The point is, I would like to make a toast pop up with the high scores whenever the user presses a button. I know how to make an OnClick function, but I want to show the highest scores the user has ever had since the install of the app, not just since the app has been opened. I need these to be displayed when I press a button called "High Score" Anyone know how to do that? If you need any more info, just ask. I am new to stack overflow.
Here's the activity code:
package com.nicorodriguez.yarokshigherorlower;

import androidx.appcompat.app.AppCompatActivity;
import java.util.*;
import java.util.concurrent.TimeUnit;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    int num;

    int guesses = 0;
    int highscore = getSavedHighScore();

    private static final String SAVED_HIGH_SCORE_INT = "high_score";

    private void saveHighScore(int highscore) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor spe = sp.edit();
        spe.putInt(SAVED_HIGH_SCORE_INT, highscore);
        spe.apply();
    }

    private int getSavedHighScore(){
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        return sp.getInt(SAVED_HIGH_SCORE_INT, -1);
    }

    public void mouseClicked (View view) {

        EditText editText = (EditText) findViewById(R.id.guess);

        int guessnum = Integer.parseInt(editText.getText().toString());

        if(guessnum > num){
            Toast.makeText(this, "Guess Lower.", Toast.LENGTH_LONG).show();
            guesses += 1;

        }else if(guessnum < num) {
            Toast.makeText(this, "Guess Higher.", Toast.LENGTH_LONG).show();
            guesses += 1;

        } else {
            Random rand = new Random();
            guesses += 1;
            String guesstring = Integer.toString(guesses);
            String highstring = Integer.toString(highscore);
            Toast.makeText(this, "For your trouble, please try again.", Toast.LENGTH_LONG).show();
            if(guesses < highscore){
                saveHighScore(guesses);
                Toast.makeText(this, "New High Score! \nScore: " + guesstring, Toast.LENGTH_LONG).show();
                if(highscore != 9999999) {
                    Toast.makeText(this, "\nPrevious High Score: " + highstring, Toast.LENGTH_LONG).show();
                }
                highscore = guesses;
            } else if(guesses == highscore) {
                Toast.makeText(this, "Aww... What a shame. You tied the high score! \nScore: " + guesstring, Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "Score: " + guesstring + "\nHigh Score: " + highstring, Toast.LENGTH_LONG).show();
            }
            num = rand.nextInt(1000) + 1;
            int guesses = 0;
        }

        Log.i("Info", Integer.toString(num));
    }

    public void highClick (View view) {
        getSavedHighScore();
        Toast.makeText(this, "Your all-time high score is " + highscore, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Random rand = new Random();
        num = rand.nextInt(1000) + 1;
        getSavedHighScore();

    }
}

Here's the Stacktrace Filter: Error It's really long. I hope this is what you want:
2020-07-17 11:38:34.040 344-344/? E/Zygote: isWhitelistProcess - Process is Whitelisted
2020-07-17 11:38:34.045 344-344/? E/Zygote: accessInfo : 1
2020-07-17 11:38:34.383 344-344/com.nicorodriguez.yarokshigherorlower E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.nicorodriguez.yarokshigherorlower, PID: 344
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.nicorodriguez.yarokshigherorlower/com.nicorodriguez.yarokshigherorlower.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3042)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3282)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1970)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7156)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
        at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:179)
        at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:526)
        at com.nicorodriguez.yarokshigherorlower.MainActivity.getSavedHighScore(MainActivity.java:32)
        at com.nicorodriguez.yarokshigherorlower.MainActivity.<init>(MainActivity.java:20)
        at java.lang.Class.newInstance(Native Method)
        at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
        at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:41)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1219)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3030)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3282)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1970)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7156)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)

A: Add the following to your Activity:
private static final String SAVED_HIGH_SCORE_INT = "high_score";

private void saveHighScore(int highScore) {
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor spe = sp.edit();
    spe.putInt(SAVED_HIGH_SCORE_INT, highScore);
    spe.apply();
}

private int getSavedHighScore() {
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    return sp.getInt(SAVED_HIGH_SCORE_INT, -1);
}

Call saveHighScore(newHighScore) whenever a game is completed.  Call getSavedHighScore in your button click listener's onClick method and use the result in your Toast.


text:
Q: Why do my link not work after adding negative margin to nav? I was make a Jquery function to make the navigation bar stick to the top of the page when scrolled past the header.
To make it look smooth I had to add padding-top:110px to the content div and margin-bottom: -80px to the nav div. Now my links do not work.
Any guesses to why? And how can I fix this to get everything in order?

$(document).ready(function() {
  var stickyNavTop = $('.nav').offset();

  var stickyNav = function() {
    var scrollTop = $(window).scrollTop();

    if (scrollTop > stickyNavTop.top) {
      $('.nav').addClass('sticky');
    } else {
      $('.nav').removeClass('sticky');
    }
  };

  stickyNav();

  $(window).scroll(function() {
    stickyNav();
  });
});
html,
body {
  height: 100%;
  position: relative;
}
#body {
  width: 80%;
  min-height: 100%;
  border: 1pxcenter;
  margin: 0 auto;
}
#header {
  width: 100%;
  height: 40%;
  border: 1px dotted blue;
  margin: auto;
}
.nav {
  margin-bottom: -80px;
  border: 1px solid black;
  width: 100%;
  height: 80px;
  z-index: 1;
  position: -webkit-sticky;
}
a:visited {
  color: black;
}
a:hover {
  color: yellow;
}
a:active {
  color: green;
}
#link {
  height: 100%;
  width: 20%;
  display: inline-block;
  float: left;
  border: 1px dotted green;
  text-decoration: none;
  text-align: center;
  padding: none;
}
.sticky {
  border: 1px solid black;
  position: fixed;
  width: 80%;
  top: 0;
  z-index: 100;
  border-top: 0;
}
.nav div p {
  padding-top: 10px;
  font-size: 1em;
}
#content {
  border: 1px solid green;
  position: relative;
  padding-top: 110px;
  padding-bottom: 100px;
  display: block;
  width: 100%;
  max-height: 100%;
  margin: none;
  text-align: left;
}

FrontYard Fairways

"Fairways at a fair price"

Home

Services

Our Customers

About

Contact

      Blahblahablahahlahablhablahablhaab lahablhablahablahabla hablahBlahblahablaha hlahablhablahablhaablahablhablahablahablahablahBlahb lahablahahlahablhablahablhaablahablhablahablahablahablahBlahblahablahahlahablhablahabl haablahablhab lahablahablahablahBlahblahablahahlahablhablahab
      lhaablahablhablahabl ahablahablahBlahblahabl ahahlaha hablahablhaablahablhablahabla blahablahablah Blahblahablahahlahablhabl ahablhaablahablhablahablahablahablahBlahblahablahahlahablhablahablhaab lahablhablahablahablah ablahBlahbl hablahahlahablhablahablhaablahablha
      blahablahablahablahBlahblahablahahlahablhablahablhaab lahablhablahab lahablahBl ahblahablahahla hablhablahablh aablahablhablahablahablahablahBlahblahablahah lahablhablahablhaablahablhablahablaha blahablahBlahbla hablahahlahablhablahablhaablahablhablahablahablahablahBla
      hblahablahahlahablhablah ablhaablahablhablahablahablahablahBlahblahab ahahlahablhablahablh aablahablhablahablahablahablahBla hblahablaha hlahablhablahablhaablahablhablahab lahablahablahBlahblahablahahlahablhablahablhaa blahablhablahablahablahablahBlahblahablahahlahablhablahablhaablahablhabl
      ahablahablahablahBlahblahablahahlahablhablahablhaablahablhablaha blahablahablahB lahblahablahahlahablhablahablhaablahablhablahablahablahablahBlahblahablahahlahablhablahablhaablahablhablahablahablah ablahBlahblahablahahlah abl ha lahablh aablahablhablahablahablahablahBlahblaha
      blahahlahablhablahablh aablahablhablahablahablahablahBla hblahablahahlahablhablahablhaablahablhablahablahablahablah Blahblahablahahlahablhablahablhaab lahablhablahablahabla hablahBlahblahablaha hlahablhablahablhaablahablhablahablahablahablahBlahb
      lahablahahlahablhablahablhaablahablhablahablahablahablahBlahblahablahahlahablhablahabl haablahablhab lahablahablahablahBlahblahablahahlahablhablahab lhaablahablhablahabl ahablahablahBlahblahabl ahahlaha hablahablhaablahablhablahabla blahablahablah
      Blahblahablahahlahablhabl ahablhaablahablhablahablahablahablahBlahblahablahahlahablhablahablhaab lahablhablahablahablah ablahBlahbl hablahahlahablhablahablhaablahablha blahablahablahablahBlahblahablahahlahablhablahablhaab lahablhablahab lahablahBl
      ahblahablahahla hablhablahablh aablahablhablahablahablahablahBlahblahablahah lahablhablahablhaablahablhablahablaha blahablahBlahbla hablahahlahablhablahablhaablahablhablahablahablahablahBla hblahablahahlahablhablah ablhaablahablhablahablahablahablahBlahblahab
      ahahlahablhablahablh aablahablhablahablahablahablahBla hblahablaha hlahablhablahablhaablahablhablahab lahablahablahBlahblahablahahlahablhablahablhaa blahablhablahablahablahablahBlahblahablahahlahablhablahablhaablahablhabl ahablahablahablahBlahblahablahahlahablhablahablhaablahablhablaha
      blahablahablahB lahblahablahahlahablhablahablhaablahablhablahablahablahablahBlahblahablahahlahablhablahablhaablahablhablahablahablah ablahBlahblahablahahlah abl ha lahablh aablahablhablahablahablahablahBlahblaha blahahlahablhablahablh aablahablhablahablahablahablahBla
      hblahablahahlahablhablahablhaablahablhablahablahablahablah

A: You have overlapping (invisible) elements from your content that covers your links.
The following CSS:
#content{
    padding-top: 110px;
}
forces your content to sit on top of your navigation links blocking them from being clicked.
There are several solutions to this.  One way to confirm that this is the case is to remove
#content{
    padding-top: 110px;
}
and replace it with
#content{
    position:relative;
    top:110px;
}
A better way to debug the issue is to open Chrome DevTools and inspecting the #content div to see where the box model overlaps your links and adjust accordingly.

A: I removed the negative margins applied to the main element, to your nav bar, and removed the height of your header. And also some little other things.

$(document).ready(function() {
  var stickyNavTop = $('.nav').offset();

  var stickyNav = function() {
    var scrollTop = $(window).scrollTop();

    if (scrollTop > stickyNavTop.top) {
      $('.nav').addClass('sticky');
    } else {
      $('.nav').removeClass('sticky');
    }
  };

  stickyNav();

  $(window).scroll(function() {
    stickyNav();
  });
});
html,
body {
  height: 100%;
  position: relative;
}
#body {
  width: 80%;
  min-height: 100%;
  border: 1pxcenter;
  margin: 0 auto;
}
#header {
  width: 100%;
  /* height: 40%; => that makes your header overlapping with your nav bar*/
  border: 1px dotted blue;
  margin: auto;
}
.nav {

  border: 1px solid black;
  width: 100%;
  height: 80px;
  z-index: 1;
  /*
  the support of position:sticky is bad: http://caniuse.com/#feat=css-sticky
  position: -webkit-sticky;
  */
  background: rgba( 255,255,255,0.9);
  transition: width 0.5s;
}
a:visited {
  color: black;
}
a:hover {
  color: yellow;
}
a:active {
  color: green;
}
#link {
  height: 100%;
  width: calc(20% - 1px );;
  display: inline-block;
  float: left;
  border: 1px dotted green;
  border-right-width: 0;

  text-decoration: none;
  text-align: center;
  padding: none;
}
.sticky {
  border: 1px solid black;
  position: fixed;
  width: 80%;
  top: 0;
  border-top: 0;
}
.sticky + #content{
  margin-top:80px
}

.nav div p {
  padding-top: 10px;
  font-size: 1em;
}
#content {
  border: 1px solid green;
  padding-top:1em;
}

FrontYard Fairways

"Fairways at a fair price"

Home

Services

Our Customers

About

Contact

      Blahblahablahahlahablhablahablhaab

lhablahablahabla hablahBlahblahablaha hlahablhablahablhaablahablhablahablahablahablahBlahb lahablahahlahablhablahablhaablahablhablahablahablahablahBlahblahablahahlahablhablahabl haablahablhab lahablahablahablahBlahblahablahahlahablhablahab
      lhaablahablhablahabl ahablahablahBlahblahabl ahahlaha hablahablhaablahablhablahabla blahablahablah Blahblahablahahlahablhabl ahablhaablahablhablahablahablahablahBlahblahablahahlahablhablahablhaab lahablhablahablahablah ablahBlahbl hablahahlahablhablahablhaablahablha
      blahablahablahablahBlahblahablahahlahablhablahablhaab lahablhablahab lahablahBl ahblahablahahla hablhablahablh aablahablhablahablahablahablahBlahblahablahah lahablhablahablhaablahablhablahablaha blahablahBlahbla hablahahlahablhablahablhaablahablhablahablahablahablahBla
      hblahablahahlahablhablah ablhaablahablhablahablahablahablahBlahblahab ahahlahablhablahablh aablahablhablahablahablahablahBla hblahablaha hlahablhablahablhaablahablhablahab lahablahablahBlahblahablahahlahablhablahablhaa blahablhablahablahablahablahBlahblahablahahlahablhablahablhaablahablhabl
      ahablahablahablahBlahblahablahahlahablhablahablhaablahablhablaha blahablahablahB lahblahablahahlahablhablahablhaablahablhablahablahablahablahBlahblahablahahlahablhablahablhaablahablhablahablahablah ablahBlahblahablahahlah abl ha lahablh aablahablhablahablahablahablahBlahblaha
      blahahlahablhablahablh aablahablhablahablahablahablahBla hblahablahahlahablhablahablhaablahablhablahablahablahablah Blahblahablahahlahablhablahablhaab lahablhablahablahabla hablahBlahblahablaha hlahablhablahablhaablahablhablahablahablahablahBlahb
      lahablahahlahablhablahablhaablahablhablahablahablahablahBlahblahablahahlahablhablahabl haablahablhab lahablahablahablahBlahblahablahahlahablhablahab lhaablahablhablahabl ahablahablahBlahblahabl ahahlaha hablahablhaablahablhablahabla blahablahablah
      Blahblahablahahlahablhabl ahablhaablahablhablahablahablahablahBlahblahablahahlahablhablahablhaab lahablhablahablahablah ablahBlahbl hablahahlahablhablahablhaablahablha blahablahablahablahBlahblahablahahlahablhablahablhaab lahablhablahab lahablahBl
      ahblahablahahla hablhablahablh aablahablhablahablahablahablahBlahblahablahah lahablhablahablhaablahablhablahablaha blahablahBlahbla hablahahlahablhablahablhaablahablhablahablahablahablahBla hblahablahahlahablhablah ablhaablahablhablahablahablahablahBlahblahab
      ahahlahablhablahablh aablahablhablahablahablahablahBla hblahablaha hlahablhablahablhaablahablhablahab lahablahablahBlahblahablahahlahablhablahablhaa blahablhablahablahablahablahBlahblahablahahlahablhablahablhaablahablhabl ahablahablahablahBlahblahablahahlahablhablahablhaablahablhablaha
      blahablahablahB lahblahablahahlahablhablahablhaablahablhablahablahablahablahBlahblahablahahlahablhablahablhaablahablhablahablahablah ablahBlahblahablahahlah abl ha lahablh aablahablhablahablahablahablahBlahblaha blahahlahablhablahablh aablahablhablahablahablahablahBla
      hblahablahahlahablhablahablhaablahablhablahablahablahablah


text:
Q: PHP IMAGICK - Conversion from SVG to PNG results in broken images I am trying to convert svg images to png through Imagick. I did it "successfully" and images were converted but they seems broken with different colors. Here is my code sample and image examples before and after conversion.
        $image = new \Imagick();
        $svgImage = file_get_contents($tmpFilePath);
        $image->setImageBackgroundColor(new \ImagickPixel('transparent'));
        $image->readImageBlob($svgImage);
        $image->setImageFormat("png32");
        $pngtmpFileName = pathinfo($tmpFilePath, PATHINFO_FILENAME).'.png';
        $pngtmpFilePath = $this->_directory->getRelativePath($this->downloadDir . '/' .
        $image->writeImage($pngtmpFilePath);
        header('Content-type: image/png');
        $image->clear();
        $image->destroy();

The same code sample is all over the internet and it looks like this is the only way to convert svg to png with php but it is not working.

*

*Example images before and after conversion:

*Example before and after conversion:

Any ideas? Thanks!