text:
Q: Sum values of an array Good day everyone, I've the following problem, I've some arrays with information about different products, each product has a rating, when I want to take that assessment and make an average to rate the store, it does not recognize the values.
Could someone tell me what I am doing wrong or how I could improve?
Thank you

This is my Typscript
 Review(i, totalReviews) {

      let globalRating = 0;
      let globalReviews = 0;

      setTimeout(function () {

        totalReviews.forEach((review, index) => {

          globalRating += review.length;

          for (const i in review) {

            globalReviews += review[i].review;

            console.log("I", review[i]);

          }
        })
        console.log("Raiting", globalRating);
        console.log("globalReviews", globalReviews);

        let averageReviews = Math.round(globalReviews / globalRating);
        let precentage = Math.round(globalReviews * 100 / (globalRating * 5));
        let averageRating = DinamicReviews.fnc(averageReviews);

        $(".br-theme-fontawesome-stars").html(`

        <select class="ps-rating reviewsOption" data-read-only="true"></select>

        `)

        for (let i = 0; i < averageRating.length; i++) {

          $(".reviewsOption").append(`

          <option value="${averageRating[i]}">${i + 1}</option>

          `)

        }

        Rating.fnc();

      }, i * 100)
  }

A: ES5 introduced the super awesome reduce method for arrays.

The reduce() method executes a user-supplied "reducer" callback
function on each element of the array, passing in the return value
from the calculation on the preceding element. The final result of
running the reducer across all elements of the array is a single
value.
Perhaps the easiest-to-understand case for reduce() is to return the
sum of all the elements in an array.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
It's a little unclear what the global reviews are as well as rating. Where does the number 15 come from?
Anyhow, you could do something like this:

const array = [
    {review: 4, comment: 'Lorem Ipsum' },
    {review: 5, comment: 'Lorem Ipsum' },
    {review: 4, comment: 'Lorem Ipsum' },
    {review: 3, comment: 'Lorem Ipsum' },
    {review: 4, comment: 'Lorem Ipsum' },
    {review: 5, comment: 'Lorem Ipsum' },
    {review: 5, comment: 'Lorem Ipsum' },
    {review: 4, comment: 'Lorem Ipsum' },
    {review: 5, comment: 'Lorem Ipsum' },
    {review: 4, comment: 'Lorem Ipsum' },
    {review: 3, comment: 'Lorem Ipsum' },
    {review: 4, comment: 'Lorem Ipsum' },
    {review: 5, comment: 'Lorem Ipsum' },
    {review: 5, comment: 'Lorem Ipsum' }
];

const getAvrgRating = (arr) => {
    return Math.round(arr.reduce((total, obj) => obj.review + total,0) / arr.length);
};

const getGlobalRating = (arr) => {
    return arr.length;
};

const getPercentage = (partial, total) => {
    if (partial === 0 && total === 0) {
        return 0;
    }

    return Math.round((partial / total) * 100);
};

const rateStore = (arr) => {
    console.log(`Global rating: ${getGlobalRating(arr)}`);
    console.log(`Average rating: ${getAvrgRating(arr)}`);
    console.log(`Percentage: ${getPercentage(getAvrgRating(arr), getGlobalRating(arr))}`);
};

rateStore(array);

The overall logic should be applicable to your case.

*

*How to get an average value of an object key, based on an array of
objects.

*How to calculate percentages.

*Aggregating the values into desired information.

Feel free to adjust the values in order to get your desired results, since some of your values weren't really explained.
If you want your percentages to be more precise, you can remove the Math.round() method.
If you'd like a case with n decimal values in your percent, you could use the toFixed() method. However, note that this will automatically convert the return type to string. If you expect a number, you'd have to convert it into float with the parseFloat() method.

console.log(`string value: ${((4 / 14) * 100).toFixed(2)}`);
console.log(`number value: ${parseFloat(((4 / 14) * 100).toFixed(2))}`);

A: As per the comments in the question, you are using the incorrect properties on the array and doing unnecessary DOM updates that cause reflows in the browser.
Instead, build up the element you need in memory and only append it to the DOM once.
To calculate the total, you can use Array.reduce and use Array.length to determine the number of reviews.
See comments inline:

const reviews = [{
    review: 2,
    comment: 'Lorem Ipsum'
  },
  {
    review: 4,
    comment: 'Lorem Ipsum'
  },
];

const processReviews = (reviews) => {
  const totalRating = reviews.reduce((previousValue, currentValue) => previousValue + currentValue.review, 0);
  const averageRating = Math.round(totalRating / reviews.length); // If the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value.

  // the rest is simply UI
  // create the select element and options
  const fragment = document.createDocumentFragment();

  const select = document.createElement('select');
  select.className = 'ps-rating reviewsOption';
  select.dataset.readOnly = true;

  fragment.appendChild(select);

  for (let i = 0; i < 5; i++) {
    const option = document.createElement('option');
    option.value = option.text = i + 1;
    option.selected = (i + 1) === averageRating;

    select.appendChild(option);
  }

  // update the DOM once
  document.querySelector('.br-theme-fontawesome-stars').appendChild(fragment);

  // debugging
  console.info(`reviews: ${reviews.length}, totalRating: ${totalRating}, average: ${averageRating}`);
}

processReviews(reviews);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="br-theme-fontawesome-stars" />


text:
Q: watchconnectivity not working on device - only simulator I have followed many tutorials online and seen how to connect the watch with the iPhone to be able to send data and have the following code to:
Send:
watchSession.sendMessage(["name":"Maz"], replyHandler: nil) { (error) -> Void in

    }

Receive:
func session(session: WCSession, didReceiveMessage message: [String : AnyObject]) {
    myLabel.setText(message["name"]! as? String)
    //reloadWatchTable()
}

The code works when I use the simulator but not when I'm running on my iPhone and Apple Watch.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to copy files into project with Build action "Content" We have content (files/folders) created outside of VS2010.  Using the project's "BeforeBuild", I'm able to import the files from our temp directory to our project's same directory structure. Once imported, how do we tell VS2010 IDE recognize Build Action as "Content"? In VS2010 IDE, the macro "Include in Project" does this for you. Does it have anything to do with specifying a file's MetaData? Here is what I have so far...
    <Target Name="BeforeBuild" Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' " DependsOnTargets="ImportProperties;CustomImportsTarget" />
  <Target Name="ImportProperties">
    <PropertyGroup>
      <ImportSrcPath>$(temp)\$(MSBuildProjectName)\Imports</ImportSrcPath>
      <!-- File to save project references to -->
      <ImportLogFile>$(ImportSrcPath)\ImportResults.txt</ImportLogFile>
    </PropertyGroup>
  </Target>
  <Target Name="ImportLogger">
    <Delete Files="$(ImportLogFile)" />
    <WriteLinesToFile File="$(ImportLogFile)" Lines="Import Results%09============" />
  </Target>
  <Target Name="CustomImportsTarget" Condition="Exists('$(ImportSrcPath)')" DependsOnTargets="ImportLogger">
    <!--
        ==============================================================
        Allows for dynamically created content (files/folders) to be imported from our temp directory to our project's same
        directory structure as "Compile Include content"
        i.e. move %temp%\scripts\1.1.0\sample.js to <project>\scripts\1.1.0\sample.js
        ==============================================================
        -->
    <Message Text="==============================================================%0aCustomImportsTarget Begin%0a==============================================================" />
    <!-- Create an Item list that contains the files to import. $(ImportSrcPath) is the property that contains the location where
            import source files are placed. -->
    <CreateItem Include="$(ImportSrcPath)\**\*" Exclude="$(ImportLogFile)">
      <Output TaskParameter="Include" ItemName="Files2Import" />
    </CreateItem>
    <!-- For testing purposes, Copy the files into our project. TODO:Should be a Move operation so project file modified dates are not constantly changing.  -->
    <Copy SkipUnchangedFiles="false" SourceFiles="@(Files2Import)" DestinationFolder="$(MSBuildProjectDirectory)\%(Files2Import.RecursiveDir)">
      <Output TaskParameter="CopiedFiles" ItemName="Changed" />
    </Copy>
    <!-- Imported files are now located in our project folders,
        How do we assign properties to the files in @(Changed) so VS2010 IDE recognizes Build Action as "Content"???
        In VS2010 IDE, the macro "Include in Project" does this for you. Does it have anything to do with specifying a file's MetaData???
        -->
    <!-- Now send these values to the logger -->
    <Message Text="Changed:@(Changed->'%(Filename)%(Extension)')" Importance="high" />
    <Message Text="Script:@(Files2Import->'%(Filename)%(Extension)')" Importance="high" />
    <!--<Message Text="MSBuildProjectDirectory:$(MSBuildProjectDirectory)" Importance="high" />-->
    <Message Text="==============================================================%0aCustomImportsTarget End%0a==============================================================" />
  </Target>

A: I don't think you can change project during BeforeBuild steps of the same project. Even if it would be possible it does not sound like a good idea.
You can instead add these files in advance to the project file even if files are not there yet. If you don't know names - just use wildcard like *.cs instead. When build will start it will use files that you've just copied/created in pre-build step.


text:
Q: Graph-tool surprisingly slow compared to Networkx After looking at the impressive performance comparison, I decided that I would give a try to graph-tool. So for comparison, I wrote codes to generate a random tree using both packages.
The graph-tool code:
import numpy as np
import graph_tool.all as gt

# construct an initial graph with two nodes and one link
n = 5000
G = gt.Graph(directed = False)
G.add_edge(0, 1)

for t in range(2, n):
    # connect the new vertex to one of the old vertices randomly
    G.add_edge(np.random.choice(range(t)), t)

The Networkx code:
import networkx as nx
import numpy as np

n = 5000
# initial graph
G = nx.Graph()
G.add_edge(0, 1)

for t in range(2, n):
    G.add_edge(t, np.random.choice(range(t)))

The graph-tool takes around 14 seconds on my 4-core machine whereas networkx takes less than 2 seconds on the same machine! Am I missing something obvious?
Thanks in advance.

A: There is nothing surprising here. graph-tool achieves greater performance by off-loading main loops to C++. If all your main loops are in Python, it offers no advantage. The same is true for other libraries like numpy.
The proper way to achieve fast addition of edges is to let graph-tool perform the main loop. The network you are generating is a simple growth model, and can be achieved in graph-tool by calling:
G = price_network(n, gamma=0, directed=False)

which takes about 15 ms in my computer for n=5000.
Note also that your python code is unnecessarily slow, since you create new lists with all vertices at each iteration. A much faster version would be:
from numpy.random import randint
n = 5000
G = Graph(directed=False)
G.add_vertex(n)
G.add_edge(0, 1)
for i in range(2, n):
    G.add_edge(i, randint(i))

For even larger values of n, it will be even faster to add all edges at once instead of one by one, i.e.
from graph_tool.all import *
from numpy.random import randint
n = 5000
G = Graph(directed=False)
edges = [(0, 1)]
for i in range(2, n):
    edges.append((i, randint(i)))
G.add_edge_list(edges)


text:
Q: Adaptation of SHA2 512 gives incorrect results I am trying to adapt the pure Lua implementation of the SecureHashAlgorithm found here for SHA2 512 instead of SHA2 256. When I try to use the adaptation, it does not give the correct answer.
Here is the adaptation:
--
-- UTILITY FUNCTIONS
--
-- transform a string of bytes in a string of hexadecimal digits
local function str2hexa (s)
    local h = string.gsub(s, ".", function(c)
        return string.format("%02x", string.byte(c))
    end)
    return h
end

-- transforms number 'l' into a big-endian sequence of 'n' bytes
--(coded as a string)
local function num2string(l, n)
    local s = ""
    for i = 1, n do
        --most significant byte of l
        local remainder = l % 256
        s = string.char(remainder) .. s
        --remove from l the bits we have already transformed
        l = (l-remainder) / 256
    end
    return s
end

-- transform the big-endian sequence of eight bytes starting at
-- index 'i' in 's' into a number
local function s264num (s, i)
    local n = 0
    for i = i, i + 7 do
        n = n*256 + string.byte(s, i)
    end
    return n
end

--
-- MAIN SECTION
--

-- FIRST STEP: INITIALIZE HASH VALUES
--(second 32 bits of the fractional parts of the square roots of the first 9th through 16th primes 23..53)

local HH = {}

local function initH512(H)
    H = {0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, 0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179}
    return H
end

-- SECOND STEP: INITIALIZE ROUND CONSTANTS
--(first 80 bits of the fractional parts of the cube roots of the first 80 primes 2..409)

local k = {
    0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, 0x3956c25bf348b538,
    0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, 0xd807aa98a3030242, 0x12835b0145706fbe,
    0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235,
    0xc19bf174cf692694, 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65,
    0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, 0x983e5152ee66dfab,
    0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4, 0xc6e00bf33da88fc2, 0xd5a79147930aa725,
    0x06ca6351e003826f, 0x142929670a0e6e70, 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed,
    0x53380d139d95b3df, 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b,
    0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30, 0xd192e819d6ef5218,
    0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8, 0x19a4c116b8d2d0c8, 0x1e376c085141ab53,
    0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373,
    0x682e6ff3d6b2b8a3, 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec,
    0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b, 0xca273eceea26619c,
    0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, 0x06f067aa72176fba, 0x0a637dc5a2c898a6,
    0x113f9804bef90dae, 0x1b710b35131c471b, 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc,
    0x431d67c49c100d4c, 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817
}

-- THIRD STEP: PRE-PROCESSING (padding)

local function preprocess(toProcess, len)
    --append a single '1' bit
    --append K '0' bits, where K is the minimum number >= 0 such that L + 1 + K = 896mod1024
    local extra = 128 - (len + 9) % 128
    len = num2string(8 * len, 8)
    toProcess = toProcess .. "\128" .. string.rep("\0", extra) .. len
    assert(#toProcess % 128 == 0)
    return toProcess
end

local function rrotate(rot, n)
    return (rot >> n) | ((rot << 64 - n))
end

local function digestblock(msg, i, H)
    local w = {}
    for j = 1, 16 do w[j] = s264num(msg, i + (j - 1)*4) end
    for j = 17, 80 do
        local v = w[j - 15]
        local s0 = rrotate(v, 1) ~ rrotate(v, 8) ~ (v >> 7)
        v = w[j - 2]
        w[j] = w[j - 16] + s0 + w[j - 7] + ((rrotate(v, 19) ~ rrotate(v, 61)) ~ (v >> 6))
    end

    local a, b, c, d, e, f, g, h = H[1], H[2], H[3], H[4], H[5], H[6], H[7], H[8]
    for i = 1, 80 do
        a, b, c, d, e, f, g, h = a , b , c , d , e , f , g , h
        local s0 = rrotate(a, 28) ~ (rrotate(a, 34) ~ rrotate(a, 39))
        local maj = ((a & b) ~ (a & c)) ~ (b & c)
        local t2 = s0 + maj
        local s1 = rrotate(e, 14) ~ (rrotate(e, 18) ~ rrotate(e, 41))
        local ch = (e & f) ~ (~e & g)
        local t1 = h + s1 + ch + k[i] + w[i]
        h, g, f, e, d, c, b, a = g, f, e, d + t1, c, b, a, t1 + t2
    end

    H[1] = (H[1] + a)
    H[2] = (H[2] + b)
    H[3] = (H[3] + c)
    H[4] = (H[4] + d)
    H[5] = (H[5] + e)
    H[6] = (H[6] + f)
    H[7] = (H[7] + g)
    H[8] = (H[8] + h)
end

local function finalresult512 (H)
    -- Produce the final hash value:
    return
    str2hexa(num2string(H[1], 8)..num2string(H[2], 8)..num2string(H[3], 8)..num2string(H[4], 8)..
            num2string(H[5], 8)..num2string(H[6], 8)..num2string(H[7], 8)..num2string(H[8], 8))
end

-- Returns the hash512 for the given string.
local function hash512 (msg)
    msg = preprocess(msg, #msg)
    local H = initH512(HH)

    -- Process the message in successive 1024-bit (128 bytes) chunks:
    for i = 1, #msg, 128 do
        digestblock(msg, i, H)
    end

    return finalresult512(H)
end

Given hash512("a"):
Expect: 1f40fc92da241694750979ee6cf582f2d5d7d28e18335de05abc54d0560e0f5302860c652bf08d560252aa5e74210546f369fbbbce8c12cfc7957b2652fe9a75

Actual: e0b9623f2194cb81f2a62616a183edbe390be0d0b20430cadc3371efc237fa6bf7f8b48311f2fa249131c347fee3e8cde6acfdab286d648054541f92102cfc9c

I know that I am creating a message of the correct bit size (1024 bits) and also working in 1024-bit chunks, or at least I believe I am.
I am not sure if it has to do with the handling of the integers (the standard requires unsigned integers) or whether I made a mistake in one of the utility functions, or both. If it is indeed an issue with the handling of the integers, how would I go about taking care of the problem. I was able to resolve this when working on the 256-bit version of the adaptation by using mod 2^32 when working with numbers in the digestblock method. I attempted to do mod 2^64 and 2^63 with the 512-bit version and it does not correct the problem. I am stumped.
I should mention that I cannot use one of the many library implementations as I am using a sandboxed Lua that does not provide this access, which is why I need a pure lua implementation. Thanks in advance.

A: Unfortunately, after introducing integers in Lua 5.3 writing scripts for Lua becomes a more complicated task.
You must always think about transformations between integers and floating point numbers.
ALWAYS.  Yes, that's boring.
One of your mistakes is an excellent example of this "dark corner of Lua".
  local remainder = l % 256
  s = string.char(remainder) .. s
  --remove from l the bits we have already transformed
  l = (l-remainder) / 256

Your value l is initially a 64-bit integer.
After cutting off its first byte l contains (64-8) = 56 bits, but now it's a floating point-number (with 53-bit precision, of course).
Possible solution: use l = l >> 8 or l = l // 256 instead of l = (l-remainder) / 256

Another mistake is using s264num(msg, i + (j - 1) * 4) instead of s264num(msg, i + (j - 1) * 8)

One more mistake is in the following line:
local extra = 128 - (len + 9) % 128

The correct code is
local extra = - (len + 17) % 128 + 8

(Please note that -a%m+b is not the same as b-a%m due to operator precedence)

After fixing these 3 mistakes your code works correctly.


text:
Q: Is it possible to decrease size of a row in Shiny beyond a certain height I like to adjust height of rows so that the layout "sidebar panel plus main panel (2 rows X 2 columns)" fills the available area of the browser window, thus it allows visualization of all the figures without scrolling down the page.
Under defaults options, one need to scroll down the page to see the second row completely. To fix this, I used 'height'  in 'renderPlot' [i.e., height=200] and 'style' in 'column' [i.e., div(style = "height:100px")].
'height' in renderplot decreased plot size, and row height varied with height values in 'div(style = "height:100px")', however approximately @ height:70px row height is fixed; row height did not decrease any further even though number of pixels decreased; hr() plots an horizontal line and it gives an idea how the row height changes for different values of height in style. The problem is that at this lowest value the bottom plot requires scrolling down the page whereas I want  'sidebar panel plus main panel (with multiple rows)' to be in the available area of the browser window so that I do not need to scroll down the page. Greatly appreciate your help.
The following links were useful to an extent:
Control the height in fluidRow in R shiny and Scale and size of plot in RStudio shiny
Here is the sample code that generates sidebar panel plus main panel of 2 X 1:
library(shiny)
library(ggplot2)

ui<- pageWithSidebar(
  headerPanel('data:Iris'),
  sidebarPanel(
    selectInput('xcol', 'X Variable', names(iris)),
    selectInput('ycol', 'Y Variable (Plot 1)', names(iris),
                selected=names(iris)[[2]]),
    selectInput('ycol2', 'Y Variable (Plot 2)', names(iris),
                selected=names(iris)[[3]])
  ),
  mainPanel(
    fluidRow(
      column(6,plotOutput('plot1'),div(style = "height:100px"))
    ),
    hr(),
    fluidRow(
      column(6,plotOutput('plot2'))
    )
  )
)

server <- function(input, output) {

  # pass data of selected input variables from the dataframe to ggplot

  # Plot 1
  output$plot1 <- renderPlot({
    ggplot(iris,aes_string(input$xcol,input$ycol))+geom_point()
  },height = 200)

  # Plot 2
  output$plot2 <- renderPlot({
    ggplot(iris,aes_string(input$xcol,input$ycol2))+geom_point()
  },height = 200)
}

shinyApp(ui =ui, server = server)

As it is seen here, plot in the second row requires scrolling down of the web page to see it completely.

A: It is actually the plotOutput which has a default height of "400px". Change the line to
column(6,plotOutput('plot1', height="200px"))


text:
Q: Speed up Javascript uglification in Play 2.3.x build for external Webjar sources I'm using Play framework 2.3.6 and Webjars for web lib dependencies.
That is, my build.sbt contains something like "org.webjars" % "angularjs" % "1.2.26".
To uglify my Javascript sources I added pipelineStages := Seq(rjs, uglify, digest, gzip) to my build.sbt.
Now, when running Play's 'stage' or 'dist' tasks it looks like all Javascript files getting uglified, that is, also files from the Webjar libraries.
[info] Uglify2 file: /target/web/rjs/build/lib/angularjs/angular.js
I would have expected that sources from the external Webjar libraries are left untouched as there already is a minified version.
One problem with that is that the uglify process takes way too long.
How can I speed up the uglification process?

A: There are two ways to speed up the Javascript building steps:

*

*Install node.js and set export SBT_OPTS="$SBT_OPTS -Dsbt.jse.engineType=Node" before running the activator. Using node.js instead of the default Javascript engine gives a very significant speedup. More details can be found here: Migration to play 2.3, see section about sbt-web

*Customize the build steps, e.g.

*

*disable minification by adding to build.sbt: RjsKey.optimize := "none"

*limit uglification by adding to build.sbt: e.g. includeFilter in uglify := GlobFilter("myjs/*.js"),
You can find more details about the options on the github site of these plugins:
sbt-uglify
sbt-rjs

A: Even though that the sbt-uglify documentation says that excludeFilter should exclude webjars and public folder, it doesn't.
Follow Martin's reponse customization part, except that he maid y typo, add an S to RjsKeys:
RjsKeys.optimize := "none"


text:
Q: Battery charged percentage not increasing on Lenovo Legion 5 15ACH6 I have recently shifted from Windows 10 to Ubuntu on a Lenovo legion 5 5-15ACH6 with ryzen 7 5800 H and RTX 3050 GPU.
In Windows, I used the Lenovo vantage to limit my charging up to 60%. But after I switched to Ubuntu 20.04, the laptop battery percentage is not increasing. It is showing that it's connected to AC adapter but the percentage is not increasing.
How can I make my battery percentage reach 100?

A: Reinstall Windows, switch the battery saver off within the Vantage Software, now your battery can charge to 100% again, even after wiping windows again and fully installing Ubuntu. I just re enabled the charging threshold in Linux using TLP back to 60%

A: or just use:
find / -type f -name conservation_mode
open the file with nano and change 1 to 0
you can also use my shell script for easy On and Off
https://github.com/MaksBal/LenovoConsMode


text:
Q: Easy way to test nested model forms with Cucumber? I've got a nested model for Departments within a Hospitals form.  The code snippet looks like this:
    <%= f.simple_fields_for :hospital do |h| %>
    .
    .
    .
       <%= h.simple_fields_for :departments do |builder| %>
              <%= render "department_fields", :f => builder %>
            <% end %>
.
.
    <% end %>

The _department_fields partial looks like this:
<div class="fields">
    <%= f.input :name %>
    <%= link_to_remove_fields "remove", f %>
    </span>
</div>

As a result, the bottom of the form has a place for the user to enter up to three department names.
I am using Rails 3, Cucumber, Capybara and Selenium for integration testing.
Is there a simple way to fill in the repeating fields when testing this form in Cucumber?
Ideally, I'd like to be able to write my feature like this:
And I fill in the first "Name" with "Cardiology"
And I fill in the second "Name" with "Radiology"

Is there some way to easily approximate this in Cucumber/Capybara?  Has someone already figured out some steps to address this?

A: Capybara has a way to deal with this by using within. For example:
And I fill in "Name" with "Radiology" within "fields"

For example, if you have divs with ids of 'hospital_fields' and 'department_fields' around both form areas, you could do something like this to differentiate which field you are filling in:
And I fill in "Name" with "Cardiology" within "hospital_fields"
And I fill in "Name" with "Radiology" within "department_fields"

You can also be more specific by using the text field id instead of the field label name. For example, if the first text field has an id of 'hospital_name' and the second has an id of 'hospital_department_name' you could do the following:
And I fill in "hospital_name" with "Cardiology"
And I fill in "hospital_deparment_name" with "Radiology"

UPDATE: You can also add a custom cucumber step to use numbered inputs:
When /^(?:|I )fill in the (\d+)(?:st|nd|rd|th) "([^"]*)" with "([^"]*)"$/ do |num, name, value|
  find(:xpath, ".//form/input[@name='#{name}'][#{num}]").set(value)
end

And I fill in the 1st "name" with "Cardiology"
And I fill in the 2nd "name" with "Radiology"

UPDATE: To match with the label use this expression:
find(:xpath, ".//input[@id=//label[contains(.,'#{name}')]/@for][#{num}]").set(value)

A: It seems Pan is going to help you find the answer to your issue.
However I'd like to add my two cents here. As it has been recommended by many people, including Dan North [1], Ben Mabey [2], Jonas Nicklas [3] and even Aslask Hellesøy recommending you to remove web_steps.rb [4], you should try not to write cucumber scenarios with steps surfacing implementation details.
When I fill in "Name" with "Cardiology"

This is about filling an HTML form input based on its label or ID or whatever... This is implementation.
I guess you could go with steps such as:
When I create a department called "Cardiology"
And I create a department called "Radiology"

Dan North even recommends having only one "event" [5] (a "When" step):
When I create departments called "Cardiology" and "Radiology"

All the form/html handling is then encapsulated within a single step definition. And of course, there you can apply the XPath expression Pan suggested above.

*

*[1] http://dannorth.net/2011/01/31/whose-domain-is-it-anyway/

*[2] http://benmabey.com/2008/05/19/imperative-vs-declarative-scenarios-in-user-stories.html

*[3] http://elabs.se/blog/15-you-re-cuking-it-wrong

*[4] https://github.com/aslakhellesoy/cucumber-rails/commit/e8d8ddb504b11452a0dc8946316faecc26915f17

*[5] http://dannorth.net/whats-in-a-story/


text:
Q: Navbar bootstrap website AM trying to make a website using bootstrap and i want it to have a header on top and navbar where by if is scroll my navbar is fixed with the header shown on the first page when i move to other pages i want to see only navbar fixed at top and all my navbar links are on the same page My code is
<!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">

    <title>Urbanic Home</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="css/style.css">

          00000000000

          @outlook.com

            <button type="button" class=" collapsed navbar-toggle" data-toggle="collapse" data-target="#myNavbar" aria-expanded="false" aria-controls="myNavbar">
              Toggle Navigation

            </button>

HOME

ABOUT

PORTFOLIO

BLOG

EXTERNAL

CONTACT

A: Add .navbar-fixed-top to your nav tag to make it stay fixed at the top.
So change this in your code.

Here is the documentation : navbar-fixed-top


text:
Q: what is the time complexity for that piece of code? what is the time complexity of this code?
how can I improve this code?
import random

n=input('choose one h/t? ')
v=random.randint(0,1)

if n=='h':
    if v==0:
        print('Hurrah!!! You win. Result is Head.')
    else:
        print('alas!!! You lose. Result is Tell.')
elif n=='t':
    if v==1:
        print('hurrah!!! You win. Result is Tell.')
    else:
        print('alas!!! You lose. Result is Head.')

A: I suggest you:

*

*either merge the h and v if to get one if only

*either determine first if it's a h or t case, outside of other if. Then, use a function to test the other parts.

Indeed, just refactor to use functions as you are repeating yourself.


text:
Q: Splash screen & InApp purchases not working on a live app I have recently published an App to the App store.
When testing the app everything was fine (in-app purchases, splash screens etc.).
Now that the app is live I have two major problems:

*

*The splash screen (Default.png) is not showing. I have retested it on my development build and it
works fine but in the live app it is not working.

*The in-app purchases are not working. I have retested it on my development build in sandbox and they
work fine but in the live app they are not working.
I have read that it is possible for in-app purchases not work for up to 36 hours after release but I have never had a problem where the Default.png file did not show.
Does anyone have any experience with this? Is it possible that I am meant to do something specific for the in-app purchases in when the app goes live ?
Thanks.

A: While verification of transaction receipt check the url that u have used (This may be the case).
For an application which is going live: https://buy.itunes.apple.com/verifyReceipt
For testing purpose: https://sandbox.itunes.apple.com/verifyReceipt.
Also check if the AppID that you have used while submitting the binary is Enabled for IAP.


text:
Q: border-box not working on inline-block elements? I have a list of inline-block elements, and I want to add a border to the element you hover over. However, notice how the border offsets the element, even when I use box-sizing: border-box and explicitly define the widths and heights of the elements. I illustrated the behavior below:

* { box-sizing: border-box }

ul { font-size: 0 }

li {
  display: inline-block;
  width: 100px; height: 40px; margin: 10px;
  font-size: 20px; text-align: center;
  background-color: #FFF176;
}

li:hover { border: 5px dashed grey }

hover

over

me!

The best solution I found is to use outline and outline-offset instead of border, but I'd really like to know why my original method doesn't work :/
UPDATE: While BoltClock gave a really great explanation and suggestion (which was all I was asking for), I just wanted to mention that I totally forgot about flexbox, which solved pretty much all the problems I was having with inline elements. I combined it with BoltClock's transparent border trick for my final JSFiddle solution

A: I see the problem now. What's happening is that box-sizing: border-box causes the content box of each element to shrink both horizontally and vertically once you add a border. Because your elements are inline-blocks, the vertical shrinking affects the baseline of the element being hovered, and therefore the baseline of the line it's on, resulting in the other elements on the same line being offset. If you look closely, you'll notice that the text actually stays aligned, which is the goal of offsetting the elements.
Changing the border to an outline works because outlines are designed to have no effect on layout (and also because you then take borders completely out of the picture).
However, it is for this reason that using an outline this way produces a significantly different effect from your original effect with a border. Setting an initial transparent border instead of an outline will ensure that your content stays offset the right amount whether the border is visible against the background (this was shown in a previous answer but it was deleted presumably because it was downvoted):

* { box-sizing: border-box }

ul { font-size: 0 }

li {
  display: inline-block;
  width: 100px; height: 40px; margin: 10px;
  font-size: 20px; text-align: center;
  background-color: #FFF176;
  border: 5px dashed transparent;
}

li:hover { border-color: grey }

hover

over

me!


text:
Q: sharepoint designer workflow: is it possible to trigger actions when a file is minor and when a file becomes major? I know I can achieve this with approval by putting the approval status as a condition, I was wondering if there is a way to say than when the file is 1.2, 3.5 or 6.99 to do an action and when it is 3.0, 5.0, 345.0 to do another.
Interested in knowing if this is possible with Flow instead of SPD

A: Yes to both questions.
In Microsoft Designer, you can use the Set Variable action (or similar actions) to retrieve the "UI Version" Property of the List Item.  Then use the If any value equals ... action to validate if the version ends with ".0", see the following screenshot:

In a Power Automate built Flow, you can do something similar by using a Condition action to check if the the "Version Number" value of a List Item ends with ".0", see the following screenshot:


text:
Q: Accented letters with IM FELL fonts I am having an error compiling the following code with xelatex and lualatex:
** WARNING ** "seac" character deprecated in Type 2 charstring.
** ERROR ** Type2 Charstring Parser: Parsing charstring failed: (status=-1, stack=5)
Output file removed.
\documentclass{article}

\usepackage{xunicode} \usepackage{fontspec}

\setmainfont[Mapping=tex-text,Ligatures={Common}, Numbers={OldStyle}]{IM FELL English PRO} \begin{document}

Buongiorno a tutti. Trallallà.

\end{document}

The error disappears when I omit the accented à.
It also doesn't happen when I use other fonts.
Could you suggest any workaround?
Thank you,
A

A: Try opening the font in FontForge, re-exporting it without any edits, installing the re-exported font file in place of the original and running LaTeX again. On my system the accented letters display successfully after this procedure. I'm not sure why it works, unfortunately.

A: A possible workaround is detailed here, where the problematic character is substituted with the same character from another font. For example:
\documentclass{minimal}

\usepackage{fontspec}
\setmainfont{IM FELL English PRO}

%change this to your preferred alternative font
\newfontfamily\myaltfont{Arial}

\begin{document}

Eleph{\myaltfont\`{a}}nt

\end{document}

In the case of the Fell fonts, some version of Caslon could be used since those typefaces are very closely related. ITC Founder's Caslon (I don't have it to test) might work best since it has irregular characters like Fell, although it probably needs some FakeBold and scaling to match the weight and x-height of the Fell fonts. I concede it's not typographically ideal.

A: I just came across this (xdvipdfmx:fatal: This font using the "seac" command for accented characters...) while testing some TT fonts including commercial fonts bought from Adobe and fonts from the old Bitstream and Fontsite "500-font" CD-ROMs, running XeLaTeX from TL2016 under Ubuntu 16.04.
By process of elimination I tracked it down to the NBSP (non-breaking space) character which was in the sample file immediately before each em rule (to prevent unwanted line-breaks). When I changed this character to TeX's version (tilde) the error went away and everything worked.
It only affected some fonts, for example Adobe Stone Serif Italic. Not sure why.

A: It seems to be a bug in «version 29» of the fonts: if you download them from the fontsquirrel site, they work as expected.


text:
Q: How to handle generically a not found task error within Gradle We're building an archetype pattern using cookiecutter. This essentially means we have a nested structure with an outer build.gradle and an inner build.gradle. Is there a way make the tasks from the inner build.gradle available as tasks on the outer project?
I'm thinking of using a GradleBuild task in the outer build.gradle to invoke the inner tasks but I'm not certain how to parse and load all the tasks from the inner build.gradle within the outer one. What I was thinking was just catching the <task> not found error on the outer build.gradle and then trying to run that task on the inner build.gradle. Does anyone know how to catch the <task> not found exceptions and run some arbitrary task at that point?

A: Did you consider using composite builds?
However, it is not necessary to catch that error as you can simply define a task rule that will create any missing task on the run. Simply register a rule like the one below:
tasks.addRule("Pattern: <task>") { name ->
    task(name, type: GradleBuild) {
        dir = // apply your setup here
        tasks = [name]
    }
}


text:
Q: Why MySQL stops itself? I have AWS micro stance, 612MB RAM. I have Apache, PHP, MySQL and Magento running. But from time to time, mysql stops itself. I don't know why? My mysql log looks:
130815  6:55:58 [Note] Plugin 'FEDERATED' is disabled.
130815  6:55:58 InnoDB: The InnoDB memory heap is disabled
130815  6:55:58 InnoDB: Mutexes and rw_locks use GCC atomic builtins
130815  6:55:58 InnoDB: Compressed tables use zlib 1.2.3.4
130815  6:55:58 InnoDB: Initializing buffer pool, size = 128.0M
InnoDB: mmap(137363456 bytes) failed; errno 12
130815  6:55:58 InnoDB: Completed initialization of buffer pool
130815  6:55:58 InnoDB: Fatal error: cannot allocate memory for the buffer pool
130815  6:55:58 [ERROR] Plugin 'InnoDB' init function returned error.
130815  6:55:58 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
130815  6:55:58 [ERROR] Unknown/unsupported storage engine: InnoDB
130815  6:55:58 [ERROR] Aborting

Thanks in advance

A: The error indicates essentially an out of memory exception, and it's easy to understand why from your description. You're running too many things in too small an amount of memory.
My best guess would be that traffic to Apache increases memory usage (each process can use 50-100mb or more depending on the use and connection limit) to the point where MySQL cannot allocate enough for normal operation, and it dies with the above message.
Now that's just PHP, Apache and MySQL, I have no idea what Magento is, but it's unlikely to make this already bad situation any better.
I realize you're using Micro because it's free, but seriously consider using the DB service separately from the web server.  Apache will use a lot of memory when bursts of traffic come in, or just from normal operation over time.  Generally it's worthwhile to think that Apache will use 100MB per process you allow it, though it will of course use more with PHP and such.

A: This questions is answered in stackoverflow. Adding swap fixed the crash. The link for solution is https://stackoverflow.com/questions/10284532/amazon-ec2-mysql-aborting-start-because-innodb-mmap-x-bytes-failed-errno-12


text:
Q: Prevent accidental deletion on API call I have a web method to delete a Furniture or one of his Properties:
[Authorize]
[Route("api/furniture/{furnitureId}/{property?}")]
public HttpResponseMessage Delete(string furnitureId, string property = null)
{
    try
    {
        if (property != null)
            _furnitureService.DeleteFurnitureProperty(furnitureId, property);
        else
            _furnitureService.DeleteFurniture(furnitureId);
    }
    catch (Exception ex)
    {
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
    }
    return Request.CreateResponse(HttpStatusCode.Accepted);
}

It works as expected, when the proper calls are made:

*

*/api/furniture/id01 - deletes the furniture id01

*/api/furniture/id01/p001 - deletes the property p001 on the furniture id01

*/api/furniture/id01?property=p001 - also deletes the property p001 on the
furniture id01

but I have received some complains due to a bad usage of the API.
For example the following call will delete the furniture:

*

*/api/furniture/id01?prop=p001

Note it is using a wrong prop parameter name, instead of property
I know they are having a call mistake, but deleting a furniture has some impact that requires prevention on my side (it can also be recovered, but needs more steps by the consumer)
So, my question is: can I easily detect and restrict when the caller is using any other parameter than the allowed ones? This way I could return a 400 error instead of deleting the furniture.
If there is no a direct way, please recommend the simpler possible (like Request.Params object regex?)

A: Edited:
Based on the fact that this is in production, I recommend creating an ActionFilterAttribute like below:
public class ValidateQueryParametersFilterAttribute : ActionFilterAttribute
{
    private IEnumerable<string> _validQueryParameters;

    public ValidateQueryParametersFilterAttribute(params string[] validQueryParameters)
    {
        if (validQueryParameters != null)
        {
            _validQueryParameters = validQueryParameters.Where(x => !string.IsNullOrWhiteSpace(x));
        }
    }

    public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
    {
        if (actionContext.Request.GetQueryNameValuePairs().Any(x => !_validQueryParameters.Contains(x.Key)))
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "You sent me an invalid property.");
        }
        return base.OnActionExecutingAsync(actionContext, cancellationToken);
    }
}

If you don't like using params, then you can use a comma delimited string.  A lot of frameworks use comma delimited string instead of params.  In fact, depending on your rules, you may receive a build error on your release.  For simplicity, I just did the params.
Then apply this to the controller like so:
[ValidateQueryParametersFilter("property")]
[Route("api/furniture/{furnitureId}/{property?}")]
public async Task<HttpResponseMessage> Delete([FromUri] string furnitureId, string property = null)
{

    return Request.CreateResponse(HttpStatusCode.Accepted);
}

Best answer is to avoid this type of routing.  I would adjust your route to the below in a future version of your API:
[Route("api/furniture/{furnitureId}/properties/{propertyId}")]

Additionally, I highly recommend using the FromRoute or FromQuery attributes.  Your controller changes to this:
[Authorize]
[Route("api/furniture/{furnitureId}/properties/{propertyId}")]
public HttpResponseMessage Delete([FromRoute] string furnitureId, [FromRoute] string property)
{
    //...
}

This makes the relationship much more clear. Also, you could look at https://www.nuget.org/packages/JsonPatch/ for executing a Patch on the resource.


text:
Q: How to make a sticky Angular Material mat-toolbar? I've been trying to implement a mat-toolbar that is located after the initial navigation bar and I can't seem to get it right. I've tried adding the class "position-fixed."
This would work if the initial position was at the top of the page but it is not. Once the user scrolls past the toolbar, it should "stick" to the top of the page.
Any ideas how to implement this? I've tried combinations of
.stickyBar { position: sticky; }

and the position-fixed but no luck.
Any ideas? Thanks

A: There were parent elements with the css property overflow: hidden which interferes with position: sticky.
Here's the post used to solve my question.

A: It looks like when you set color="primary" to a toolbar, it makes it sticky, but without any color, it's not sticky (how strange btw, and not documented at least for Angular Material 12).
I could make a mat-toolbar sticky even without a color attribute, by adding these styles:
position: sticky;
top: 0;

A: Make the change below:
mat-toolbar{
  display: initial;
}
.stickyBar {
  position: sticky;
  top: 0;
}

As soon as you add the <mat-toolbar> parent with a particular height, the stickybar will only stay stuck for the size of the toolbar. In other-words, if you set the height of the toolbar to 10vh you will see that the sticky-bar stays stuck for the 10vh space. The reason is that the sticky-ness is only applied to the parent container's share of the viewport. Workaround from: Why is my position:sticky not working?


text:
Q: in AWS cloudwatch dashboard, can i select to chart all dimensions of a metric Say, I want to chart CPU usage metric for each pod in my system, with Podname being the dimension. Can I specify a widget in CDK like this, and expect it to get all pods in one widget:
    const podcpumetric = new cloudwatch.Metric({
      namespace: 'chkk',
      metricName: 'CPU Metrics with podName as dimension',
      period: Duration.days(1),
 //   dimensionsMap: {}, // not specified so that all pods are in the widget
      statistic: 'maximum',
    });
    dashboard.addWidgets(
      new GraphWidget({
        title: 'Pod Cpu Usage',
        width: 12,
        left: [podcpumetric],
      }),
    );

I tried something like the above without specifying the dimension and hoping that it will get all pods' data. This does not seem to work.
I can however, declare one metric per pod, and then add it in the left array, but that doesn't seem a comprehensive solution. As I will have to update this widget, if I add a new pod in the future and want to chart its data.

A: I found out that this is possible. Domain is the only dimension in its dimensionSet.

    const CompanyLogins = new MathExpression({
      label: 'NumberOfDailyLoginsPerDomain',
      expression: `SEARCH(' {namespace, Domain} MetricName="NumberOfDailyLoginsPerDomain" ', 'Maximum', 1440)`,
      usingMetrics: {},
    });
    dashboard.addWidgets(
      new GraphWidget({
        title: 'Number of Logins per Domain (sum of logins by all users of the domain)',
        width: 12,
        view: cloudwatch.GraphWidgetView.BAR,
        left: [CompanyLogins],
      }),
    );


text:
Q: TelecomManager.ACTION_CHANGE_DEFAULT_DIALER returns RESULT_CANCELED on huawei P8 Lite I want to change Android default dialer and want to make my own customized dialer. For this purpose I have choose this  GIthub repo as start up project. This works well on all other phone and stops working on huawei p8 lite. The default pop up message does not shows up for setting the app as default.
Here is code block
private fun checkDefaultDialer() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return

    val telecomManager = getSystemService(TELECOM_SERVICE) as TelecomManager
    val isAlreadyDefaultDialer = packageName == telecomManager.defaultDialerPackage
    if (isAlreadyDefaultDialer) return

    val intent = Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER).putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME, packageName)
    startActivityForResult(intent, REQUEST_CODE_SET_DEFAULT_DIALER)
}

private fun checkSetDefaultDialerResult(resultCode: Int) {
    val message = when (resultCode) {
        RESULT_OK -> "User accepted request to become default dialer"
        RESULT_CANCELED -> "User declined request to become default dialer"
        else -> "Unexpected result code $resultCode"
    }
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}

StertActivityforResult returns with RESULT_CANCELED and message
User declined request to become default dialer

Can't find any solution for this. Any help will be greatly appreciated.

A: If you run this code in Android Q or above it will not work. Its just fine for below Q. To get it working in Android Q try the code below:
RoleManager rm = (RoleManager) getSystemService(Context.ROLE_SERVICE);
startActivityForResult(rm.createRequestRoleIntent(RoleManager.ROLE_DIALER), 120);

It will popup the app chooser dialog.

A: You'll also get a RESULT_CANCELED when targeting Android Q or higher, as the PermissionPolicyService removes the Action. You should use RoleManager.createRequestRoleIntent() instead.

A: Try to add some intent filters to your Activity in AndroidManifest.
<intent-filter>
    <action android:name="android.intent.action.VIEW"/>
    <action android:name="android.intent.action.DIAL"/>

    <category android:name="android.intent.category.DEFAULT"/>
    <category android:name="android.intent.category.BROWSABLE"/>

    <data android:scheme="tel"/>
</intent-filter>
<intent-filter>
    <action android:name="android.intent.action.DIAL"/>

    <category android:name="android.intent.category.DEFAULT"/>
</intent-filter>

A: My way:
@SuppressLint("QueryPermissionsNeeded")
@TargetApi(Build.VERSION_CODES.M)
fun launchSetDefaultDialerIntent(activity: AppCompatActivity) {
    Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER).putExtra(
        TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME,
        activity.packageName
    ).apply {
        if (resolveActivity(activity.packageManager) != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                val rm: RoleManager? = activity.getSystemService(RoleManager::class.java)
                if (rm?.isRoleAvailable(RoleManager.ROLE_DIALER) == true) {
                    @Suppress("DEPRECATION")
                    activity.startActivityForResult(
                        rm.createRequestRoleIntent(RoleManager.ROLE_DIALER),
                        REQUEST_CODE_SET_DEFAULT_DIALER
                    )
                }
            } else {
                @Suppress("DEPRECATION")
                activity.startActivityForResult(this, REQUEST_CODE_SET_DEFAULT_DIALER)
            }
        } else {
            activity.toastShort(R.string.no_contacts_found)
        }
    }
}

Then use it directly in Activity.


text:
Q: EF Connection String to SQLLocalDB I installed SQlLocalDB and created default instance "MSSQLLocalDB", after that I used SQL Management Studio to attach a DB to the "MSSQLLocalDB" instance.
I have a C# app that uses EF 6.1.3 and in the connection string for the App.config file I have
  <connectionStrings>
    <add name="MyDBName"
         connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=MyDBName;Integrated Security=True"
         providerName="System.Data.SqlClient"/>
  </connectionStrings>

But is not working... Any thoughts? I tried different combinations but is not working...
The Same Connection String works if I m using a SQL Express instance... and instead of using
Data Source=(LocalDb)\MSSQLLocalDB

I use
Data Source=.\SQLExpress


text:
Q: Decrypt gpg in Java without using Java.Runtime I have a .gpg file and a RSA private key. How can I programatically decrypt it without using operating system? e.g. without using something like Runtime.getRuntime().exec("gpg -decrypt.....");
Libraries I've found all run operating system. Like GnuPG or gnugpg-for-java.

A: As Skyr mentioned: Bouncy Castle is the way to go.
What do you want to do with this key? If your goal is to en- or decrypt files you might want to take a look at bouncy-gpg  (shameless plug: I wrote it).
Using secret keys is actually three steps

*

*Parse the key and put it into a PGPSecretKeyRing

*Extract the secret key from the keyring

*Decrypt it with the password

1. Parsing the exported key
In any case look here for the part that parses keys:
class ...

private PGPSecretKeyRingCollection secretKeyRings = new PGPSecretKeyRingCollection(EMPTY_LIST);

 ...

/**
 * Add a new secret keyring to the public keyrings.
 * .
 * Can read the result of "gpg --export" and "gpg --export -a keyid"
 * .
 * E.g. "gpg --export-secret-key -a keyid":
 * addSecretKey("-----BEGIN PGP PRIVATE KEY BLOCK----- ....".getBytes("US-ASCII")
 * <p>
 * The password is queried via the callback (decryptionSecretKeyPassphraseForSecretKeyId).
 *
 * @param encodedPrivateKey the key ascii armored or binary
 * @throws IOException  IO is dangerous
 * @throws PGPException E.g. this is nor a valid key
 */
public void addSecretKey(byte[] encodedPrivateKey) throws IOException, PGPException {

    if (encodedPrivateKey == null) {
        throw new NullPointerException("encodedPrivateKey must not be null");
    }

    try (
            final InputStream raw = new ByteArrayInputStream(encodedPrivateKey);
            final InputStream decoded = org.bouncycastle.openpgp.PGPUtil.getDecoderStream(raw)
    ) {
        PGPSecretKeyRing pgpPrivate = new PGPSecretKeyRing(decoded, getKeyFingerPrintCalculator());
        this.secretKeyRings = PGPSecretKeyRingCollection.addSecretKeyRing(this.secretKeyRings, pgpPrivate);
    }
}

2. Getting the key from the keyring
       final PGPSecretKeyRingCollection pgpSec = ...
       final PGPSecretKey encryptedKey = pgpSec.getSecretKey(keyID);

3. Decrypting the key
Later you have to decrypt the key using a password like so:
 /**
 * Decrypt an encrypted PGP secret key.
 *
 * @param encryptedKey An encrypted key
 * @param passphrase   The passphrase for the key
 * @return the decrypted secret key
 * @throws PGPException E.g. wrong passphrase
 */
public static PGPPrivateKey extractPrivateKey(PGPSecretKey encryptedKey, final char[] passphrase) throws PGPException {
    LOGGER.debug("Extracting secret key with key ID '0x{}'", Long.toHexString(encryptedKey.getKeyID()));

    PGPDigestCalculatorProvider calcProvider = new JcaPGPDigestCalculatorProviderBuilder()
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build();

    PBESecretKeyDecryptor decryptor = new JcePBESecretKeyDecryptorBuilder(
            calcProvider).setProvider(BouncyCastleProvider.PROVIDER_NAME)
            .build(passphrase);

    return encryptedKey.extractPrivateKey(decryptor);
}

A: The Bouncy Castle library provides (among other features) an OpenPGP implementation. The package org.bouncycastle.openpgp.examples contains several usage examples, one of them showing how to encrypt/decrypt a file using a public/secret key pair (you can have a look at the examples on GrepCode or on the project's Github mirror).

A: there are too many examples that I've tried on Bouncy Castle with PGP.  The common issue is keyID can't be found in KeyRing.
So, I found @Jens' bouncy-gpg (not sure if he still maintains it.)
Here is his documentation from github.io.  It's simple to follow and works!
https://neuhalje.github.io/bouncy-gpg/


text:
Q: Memory leak(?) Python 3.2 Hi I am new to python and I have read enough posts for the specific subject but none has a specific answer. (using py 64-bit 3.2 edition)
I have a big input which I read it inside a loop and as I read the file I create groups which I append to a List . I process the List and then store it inside a file. I unreffer the List (List = None) and I delete it. I even call gc collector manually. Problem is that the memory is still been used. Swap space and Ram go wild.
for line in file: # read line by line
        temp_buffer = line.split() # split elements
        for word in temp_buffer: #enumerate (?)
             if not l1: # list is empty
                 l1.append(str(word)) #store '-' to list
             else:      # list is not empty
                 tempp = l1.pop(0)
                 l1.insert(0,"-0")
                 l1.sort(key=int)
                 l2 = term_compress(l1)

                 l1 = None # delete referrences
                 del l1    # delete struct

                 print(" ".join(str(i) for i in l2) , file=testfile) # print for every term in file
                 l2 = None # delete referrences
                 del l2    # delete struct

                 gc.collect() # run garbagge collector (free RAM)
                 l1 = []
                 l2 = []
                 l1.append(str(word))

What am I doing wrong ?
edit
example input:
-a 1 2 3 4 5 6 7 8 9 10

-n 7 8 9 10 11 12 13 14 15 ...

output
-a 1# 10#

-n 7# 15#

A: It's most likely not a memory/reference leak in the traditional sense of a programming error.  What you're likely seeing is the underlying C runtime aggressively holding on to heap memory that Python allocated on your behalf during the loop. It's anticipating that you might need to use that memory again. Holding onto it is cheaper than giving it back to the OS kernel only to ask for it again and again.
So, in short, even though your objects have been garbage collected in the Python runtime, the underlying C runtime hangs onto the heap memory in case your program needs it again.
From the glibc documentation:

Occasionally, free can actually return memory to the operating system and make the process smaller. Usually, all it can do is allow a later call to malloc to reuse the space. In the meantime, the space remains in your program as part of a free-list used internally by malloc.

In that sense, your memory utilization reported by the OS after the loop is basically your "peak memory utilization".  If you think it's too high, then you have to consider redesigning your program to limit its peak memory usage.  This is typically accomplished using some kind of streaming or buffering design where you're operating on smaller chunks of the data at a time.
Disclaimer, the above is a layman's version and is obviously implementation specific to various flavors of Python, C, and the OS.


text:
Q: How do I append two newlines if text already exists in file? I have looked around and tried different options for a few hours, but I can't get anything to work properly. I have a code that creates a file and appends the user input in rows as designated by the user.
The problem occurs when a second input (list to str, by the way) is appended into the file. The new input always begins on the same row as the last one ended on.
For example, the output to the file will be:
input 1
input 1
input 1input 2
input 2
input 2

The issue is that the second input starts on the last line of the first input, I want it to start on a newline.
I tried various things, like having the code look if readline / read () and (1) exists in the file, but I never got it to work.
Currently, the relevant section of my code looks like this:
os.chdir(os.path.expanduser("~/Desktop/Sam's Calendar"))
with open(str(now.year) + '-' + str(month).zfill(2) + '-' + str(daterange).zfill(2) + '.txt', 'a+') as file:
        file.write('\n'.join(reminderdescriptionfull))

I'd like an answer that's comprehensible to someone who's not very adept at writing code if at all possible.

A: try this:
os.chdir(os.path.expanduser("~/Desktop/Sam's Calendar"))
with open(str(now.year) + '-' + str(month).zfill(2) + '-' + str(daterange).zfill(2) + '.txt', 'a+') as file:
        if reminderdescriptionfull:
             file.write("%s\n"%'\n'.join(reminderdescriptionfull))

A: You are missing a final newline in your write. Just add an extra statement inside the with:
file.write('\n')

and you should find the problem goes away.

A: Join interleaves a newline character between the lines in reminderdescriptionfull, hence, there is no newline at the end of one input or the beginning of the other. To work around around this problem, all you have to do is add a newline character while writing to the file, i.e.,
os.chdir(os.path.expanduser("~/Desktop/Sam's Calendar"))
with open(str(now.year) + '-' + str(month).zfill(2) + '-' + str(daterange).zfill(2) + '.txt', 'a+') as file:
        file.write('{}\n'.format('\n'.join(reminderdescriptionfull)))

A: One way of checking if a file is empty is using os.stat.st_size.
import os
os.stat("file").st_size

But since you alread have the file opened, you could also just try to read the first character and see if there's anything there:
with open("path/to/file", "a+") as file:
    if file.read(1):
        file.write('\n\n')
    # now the rest of your output

You mentioned that you've already tried checking file.read(), but the above snippet (and the os snippet) should get you what you're after.


text:
Q: How to create seperate POST request for imagefield in DRF I need to make a separate API for the image file. How can I achieve this?
models.py
class Organization(models.Model):
    code = models.CharField(max_length=25, null=False, unique=True)
    name = models.CharField(max_length=100, null=False)
    location = models.ForeignKey(Location, on_delete=models.RESTRICT)
    description = models.TextField()
    total_of_visas = models.IntegerField(null=False, default=0)
    base_currency = models.ForeignKey(Currency, on_delete=models.RESTRICT)
    logo_filename = models.ImageField(upload_to='uploads/')

serializers.py
class OrganizationSerializer(serializers.ModelSerializer):
    location = serializers.CharField(read_only=True, source="location.name")
    base_currency = serializers.CharField(read_only=True, source="base_currency.currency_master")
    location_id = serializers.IntegerField(write_only=True, source="location.id")
    base_currency_id = serializers.IntegerField(write_only=True, source="base_currency.id")

    class Meta:
        model = Organization
        fields = ["id", "name", "location", "mol_number", "corporate_id", "corporate_name",
                  "routing_code", "iban", "description", "total_of_visas", "base_currency", "logo_filename",
                  "location_id", "base_currency_id"]

    def validate(self, data):
        content = data.get("content", None)
        request = self.context['request']
        if not request.FILES and not content:
            raise serializers.ValidationError("Content or an Image must be provided")
        return data

    def create(self, validated_data):
        ....

    def update(self, instance, validated_data):
        ....

views.py
class OrganizationViewSet(viewsets.ModelViewSet):
    queryset = Organization.objects.all()
    serializer_class = OrganizationSerializer
    lookup_field = 'id'

urls.py
router = routers.DefaultRouter()
router.register('organization', OrganizationViewSet, basename='organization')
urlpatterns = [
    path('', include(router.urls)),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

I don't have idea how to make POST request for image field from postman. I've been stuck here for a long time. Any help is appreciated.

A: if you want to update the image field separately you just have to create a separate serializer for it
 class OrganizationImageSerializer(serializers.ModelSerializer):
        logo_filename = serializers.ImageField()
        class Meta:
            model = Organization
            fields = ["logo_filename"]

view.py
class OrganizationImageView(generics.UpdateAPIView):# or `generics.RetrieveUpdateAPIView` if you also want to retriev the current one before updating it
    serializer_class = OrganizationImageSerializer
    permission_classes = [IsAuthenticated, ]

    def get_queryset(self):
        queryset = Organization.objects.filter(id=self.kwargs['pk'])
        return queryset

urls.py
from .views import OrganizationImageView

urlpatterns = [
...
 path('update_org/<int:pk>', OrganizationImageView.as_view(), name='OrganizationImageUpdater'),
]


text:
Q: How to round a value from an expression?? VBA I got the following expression that I want it to be rounded by 2 decimal places:
Sub Round_Ex2()
  Dim Pitch_Limit_W As Double

        Pitch_Limit_W = (291 / 20.95)
        Round("Pitch_Limit_W",2)

End Sub

I get an error when trying to run because on the second line it says :" Expected =". I just want to round the decimal value from that expression up to 2 decimal places.
I tried changing the round function by putting some parentheses but still the same issue.

A: Sub Round_Ex2()

  Dim Pitch_Limit_W As Double
  Pitch_Limit_W = (291 / 20.95)
  Pitch_Limit_W_Rounded = Round(Pitch_Limit_W, 2)

End Sub

You have to assign the result to a variable.


text:
Q: Could not delete caches dir when compile Kotlin in Intellij IDE My project use plugin kapt to generate mapper.
When run app then can not compile Kotlin (image below)
If remove plugin kapt then it not happend.
To resolve I must restart Intellij IDE. Take more time.
This error probably only happen on windows

A: This is a Kotlin bug, you can vote and watch it for updates: https://youtrack.jetbrains.com/issue/KT-36253. A workaround is to kill the running Java processes.

A: I have this problem almost every build (Android Studio stable + Artic Fox).
Manual Solution (try this first, if it works continue)
Task manager > Processes > End "OpenJDK Platform Library" tasks
(sometimes it's standalone, sometimes it's under "Android Studio")
OR
Task manager > Details > End "java.exe" tasks
Automated Solution

*

*Create a new end-java.bat file

*Content of .bat file: taskkill /f /IM java.exe

*Right click end-java.bat file > create shortcut

*Right click the shortcut > properties

*Add shortcut key (e.g. ALT + CTRL + 1)

*ALT + CTRL + 1 will now fix the issue

A: Try This :
https://developer.android.com/studio/build/build-cache
Add this code :

    // To re-enable the build cache, either delete the following
// line or set the property to 'true'.
android.enableBuildCache=false

After that clean project and restart android studio

A: Also you can try to use a different JDK (e.g. OpenJDK). It helped me.
File -> Project Structure -> SDK Locations -> JDK Location

A: You can reboot the system, it will help. But this problem will return soon. This is the bag of Android Studio 4.2 https://youtrack.jetbrains.com/issue/KT-36253


text:
Q: javascript add option item I have a requirement to move an Option from one List to a second List, at the same time each item added to the second list should also be added to a drop down list.
I have the following javascript
    $("#MoveRight,#MoveLeft").click(function (event) {
        var id = $(event.target).attr("id");
        var selectFrom = id == "MoveRight" ? "#Items" : "#SelectedCustomFields";
        var moveTo = id == "MoveRight" ? "#SelectedCustomFields" : "#Items";
        var selectedItems = $(selectFrom + " :selected").toArray();

        $.each(selectedItems, function (val, text) {
            createOption(val, text, $('#SortBy'));
            createOption(val, text, $(moveTo));
        });

        selectedItems.remove();
    });

    function createOption(value, text, list) {
        var myList = list;

            myList
                .append($("<option></option>")
                    .val(value).html(text));

    }

The issue with this seems to be that it adds to one of the Select Lists fine. In the above case the second createOption call works fine, the 1st one adds a blank item, if i swap those function calls around it also flips the results. I have also tried changing the createOption function to hard code it to add the same values to the second select list (the drop down) but this gets the same results.
Any help would be appreciated
Thanks.


text:
Q: How to limit checked in OnMultiChoiceClickListener I'm developing an Android app which has Dialog with MultiChoiceItems.
I'd like to limit the checked numbers 3 outof 10 choice.
I wonder when I tap 4th checkbox, cannot check with toast alert is the best way.
Could you help me to realize this?

Thanks!

A: You will have to add an increment to Flag count each time a check box is checked and than on every Check you will have to check the Flag count.

A: try something like this:
 DialogInterface.OnMultiChoiceClickListener MeasuresDialogListener = new DialogInterface.OnMultiChoiceClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which, boolean isChecked) {

           if(isChecked)
            {
              selectedMeasures.add(AvailableMeasures[which]);

                    if(selectedMeasures.size() > 3)
                      {
                         //display toast saying that only three items can be checked.
                           selectedMeasures.remove(AvailableMeasures[which]);
                      }
            }
          else
            {
              selectedMeasures.remove(AvailableMeasures[which]);
            }
         }
       };

Here selectedMeasures is an ob of type ArryaList which can be used to store selected values.


text:
Q: Autodesk Forge modern conversion method IFC 2x3 creates model twice I have a IFC 2x3 format model, that I want to render using Autodesk Forge viewer. When I switched from "legacy" (Navisworks) to "modern" (Revit) conversion, the model needs a long time to finish loading in the viewer and it is rendered twice. Here is a screenshot, how it looks now:

When the model is converted using legacy conversion method, the model is rendered correctly as one. Also, other IFC viewers render the model correctly:

Is there an issue with modern conversion method and IFC 2x3 files? Other 2x3 IFC models are rendered correctly, but as stated in this stackoverflow post, I have issues with another 2x3 IFC file which may be related.
On the supported formats website, there is only stated, that IFC is supported, but not which exact versions.
Thanks for any kind of help!

A: As in the other post, the problem seems to be the IfcSite. After replacing longitude, latitude and elevation with '$', the model is rendered nicely. The modern conversion seems to have issues with the geographic reference point of IfcSite, altough it is only given for informational purposes (Link).


text:
Q: Why Changes are not reflecting in React native? I am changing something in .js file for ex. any text for textfiled placeholder. But after running command react-native run-android nothing is changing in android emulator. only when i run  npm run bundle-android and then run react-native run-android changes are reflecting.
My package.json is like
{
  "name": "xyz",
  "version": "0.0.1",
  "private": true,
  "scripts": {

    "start": "react-native start",
    "bundle-android": "react-native bundle --entry-file index.js --platform android --dev false --bundle-output ./android/app/src/main/assets/index.android.bundle --assets-dest ./android/app/src/main/res/",
    "bundle-ios": "react-native bundle --entry-file index.js --bundle-output ./ios/bundle/index.ios.jsbundle --platform ios --assets-dest ./ios/bundle --dev false",
    "test": "jest",
    "ios": "react-native run-ios --simulator 'iPhone X'",
    "android": "react-native run-android -- --reset-cache",
    "android-ete": "ENVFILE=.env.ete react-native run-android -- --reset-cache",
    "ios-ete": "ENVFILE=.env.ete react-native run-ios",
    "ios-prod": "ENVFILE=.env.prod react-native run-ios",
    "exportcert-ete": "java -jar BKSPubKeyTool.jar --importkeystore keystore_ete.bks --alias oauth.testing --password keystorepwd --exportcert src/keystore/id_rsa_ete.pem --exportjs src/keystore/pubKey_ete.js",
    "exportcert-prod": "java -jar BKSPubKeyTool.jar --importkeystore keystore.bks --alias oauth --password keystorepwd --exportcert src/keystore/id_rsa_prod.pem --exportjs src/keystore/pubKey_prod.js",
    "lint": "eslint ."
  },
  "dependencies": {
    "axios": "^0.19.0",
    "buffer": "^5.2.1",
    "crypto-js": "^3.1.9-1",
    "jetifier": "^1.6.3",
    "jsencrypt": "^3.0.0-rc.1",
    "mobx": "^5.11.0",
    "mobx-react": "^5.4.4",
    "moment": "^2.24.0",
    "native-base": "^2.12.1",
    "prop-types": "^15.7.2",
    "querystring": "^0.2.0",
    "react": "16.8.6",
    "react-native": "0.60.3",
    "react-native-config": "^0.11.7",
    "react-native-date-picker": "^2.7.3",
    "react-native-device-info": "2.3.2",
    "react-native-exception-handler": "^2.10.8",
    "react-native-gesture-handler": "^1.4.0",
    "react-native-keyboard-spacer": "^0.4.1",
    "react-native-linear-gradient": "^2.5.4",
    "react-native-modal": "^11.1.0",
    "react-native-modal-dropdown": "^0.6.2",
    "react-native-picker-select": "^6.3.0",
    "react-native-popup-dialog": "^0.18.2",
    "react-native-reanimated": "^1.4.0",
    "react-native-root-toast": "^3.1.2",
    "react-native-screens": "^2.0.0-beta.10",
    "react-native-scrollable-tab-view": "^0.10.0",
    "react-native-splash-screen": "^3.2.0",
    "react-native-sqlite-storage": "^3.3.11",
    "react-native-tab-view": "^2.8.0",
    "react-native-user-agent": "^1.0.4",
    "react-native-user-inactivity": "^1.0.1",
    "react-native-uuid": "^1.4.9",
    "react-native-wheel-picker-android": "^2.0.5",
    "react-navigation": "^3.11.1"
  },
  "devDependencies": {
    "@babel/core": "^7.5.5",
    "@babel/plugin-proposal-decorators": "^7.4.4",
    "@babel/runtime": "^7.5.5",
    "@react-native-community/eslint-config": "^0.0.5",
    "babel-jest": "^24.8.0",
    "babel-plugin-transform-decorators-legacy": "^1.3.5",
    "babel-preset-react-native": "^4.0.1",
    "eslint": "^6.1.0",
    "jest": "^24.8.0",
    "metro-react-native-babel-preset": "^0.55.0",
    "react-test-renderer": "16.8.6"
  },
  "jest": {
    "preset": "react-native"
  }
}

As i am new to react native please let me know if more information needed in question?
Thank you for help

A: Sometimes it can load an old version of the code and not updating.
For me sometimes just \android\gradlew clean and react-native run-android (from the main folder) works.
I don't know if it solves your problem but it worth a try. A lot of errors in react-native can be solved by gradlew clean and/or restarting your computer.

A: You need to compile the code first..
npm run dev

Or
npm test


text:
Q: You own $19.75 in dimes and quarters - there are 100 coins in all - how many dimes? I have been stuck on this problem for 30+ minutes and I can't seem to get the correct answer; there must be something that I am missing/doing wrong!!

*

*You own $19.75 in dimes and quarters

*There are 100 coins in all

*How many dimes are there?

My variables:
$d$ = dimes,
$q$ = quarters
My equations:
$$19.75 = 10d + 25q$$
$$100 = d + q$$
I have done problems like this before, system of equations, but I cannot, for some unknown reason (to me), find the correct answer.

It always comes out with like 3 decimal places, and numbers that are not divisible.

Any help, even hints, would be truly appreciated!
Thanks!

What I have tried:
$-10(100) = (d + q)-10 [=] -1000 = -10d - 10q$

$19.75 = 10d + 25q$

$+$
$-1000 = -10d - 10q$

A: If all 100 of your coins were quarters, you'd have \$25.00.  That's too much; you're only supposed to have \$19.75, which is \$5.25 less. So you need to replace some of those 100 quarters with dimes.  Every time you replace a quarter with a dime, the amount of money decreases by \$0.15.  How many of these \$0.15 decreases are needed in order to get a total decrease of \$5.25? Well, 5.25 divided by 0.15 is 35, so you'll need 35 quarter-to-dime replacements. The result will be 65 quarters and 35 dimes.  (Since I don't trust my ability to do arithmetic, I should check the answer: $(65\times0.25)+ (35\times0.10)=16.25+3.50=19.75$.)


text:
Q: How to process single update of the resource in given time window I am receiving multiple location updates from the device for a particular resource Id . These location updates can be received at an interval of second or milliseconds as well .
I want to process only one of the update for any particular resource Id in a given time window lets say 10 second .
Currently I am reading the last processed request for that resource Id from redis cluster and checking if the time difference is greater than 30 seconds , then only I am processing the request .
Issue happens when we receive the request at almost same time (milliseconds apart) . And two different machine picks those request to process . When both the machine try to get the last processed request for that resource Id , they both get the same record , because of which both the requests enter into the system .
Is there any technique to prevent this scenario ?

A: You can use setnx (set if not exists). For resource ID 1, at any timestamp do a division of 10000 (10 seconds). For example, timestamp 1583906206000, the value will be 158390620. And construct the key as resource_1_time_158390620. Till the next 10 secs our key will be the same.
setnx resource_1_time_158390620 value

If multiple appservers tries, or multiple requests comes within 10 secs, the value will be set for the first one alone. Also this commands returns 1 meaning the value is set and 0 meaning the value is already present. You can make use of it as well.


text:
Q: I got this error for first attempt to login facebook.How can solve this? I searched very much but I did not see the real solution. Somebody says use ex facebook sdk , is it the real solution?(I use facebook 3.6 but somebody says on stackoverflow use 3.2)
I use proguard,
com.facebook.aq: com.facebook.c.f got an unexpected method signature: public abstract java.lang.Object com.facebook.c.c.e()
at com.facebook.c.h.a(Unknown Source)
at com.facebook.c.f.invoke(Unknown Source)
at $Proxy0.e(Native Method)
at com.facebook.b.al.a(Unknown Source)
at com.facebook.b.al.a(Unknown Source)
at com.facebook.f.run(Unknown Source)
at java.util.Timer$TimerImpl.run(Timer.java:284)

A: You should use the latest facebook sdk and you should login with using
app_secret like this :
  String access_token = sharedPrefs.getString("access_token", app_secret );
        Long expires = sharedPrefs.getLong("access_expires", -1);
    mFacebook.setAccessToken(access_token);
                mFacebook.setAccessExpires(expires);

(I think this solves your problem bacause you have a problem just the first login )

A: There are some settings that you need to set for proguard.
The number of posts can explain the right way.
Check them out.
Some are listed below:-
1) Using Signature - Error-on-using-proguard-with-android-facebook-sdk-3-0.
So you use -
-keepattributes Signature

2) Android-facebook-connect-not-working-in-release-build.-
So, issue can be with your proguard configuration settings:

*

*proguard.cfg (ERROR)

-keep class com.facebook.android.*
-keepclassmembers public class com.facebook.android.Facebook {

    public static final *;
}

*

*proguard.cfg (WITHOUT ERROR)

-keep class com.facebook.android.*
-keep class android.webkit.WebViewClient

-keep class * extends android.webkit.WebViewClient

-keepclassmembers class * extends android.webkit.WebViewClient {
    <methods>;
}

3) Android ProGuard settings for Facebook


text:
Q: Product purchases - if consumer buys product x how likely are they to buy product y I have some data on store level purchases, a random sample of the data looks like the following:
      PANID       WEEK    L1
966 3357632 2011-02-21 PIZZA
352 3357632 2009-11-09 SALTY
68  3357632 2012-06-18  BEER
65  3357632 2012-03-05  BEER
43  3108696 2011-10-31  BEER
672 3144766 2010-03-29 SALTY
70  3357632 2012-06-18  BEER
810 3144766 2012-06-18 SALTY
546 3144766 2008-05-05 SALTY
933 3357632 2009-06-15 PIZZA

(EDIT: This random sample contains 2012 info, the data I provided was filtered from 2007 - 2010 - due to character count)
There are 3 PANIDs across 4 years worth of data for 3 categories of products (BEER, SALTY, PIZZA). I am trying to find out whether people who bought BEER on a given week also bought SALTY / construct a probability that given that PANID: 3144766 bought SALTY in WEEK: 2009-06-15 what is the probability that they will also by BEER. Doing the same for pizza, i.e. given that they bought BEER the probability of them buying PIZZA and finally given that they bought PIZZA the probability of them buying SALTY.
E.G. the person below bought 3 packets of SALTY and one unit of BEER but on a different week they would have just bought BEER and PIZZA or just SALTY.
> data %>%
+   group_by(PANID) %>%
+   filter(WEEK == "2009-06-15") %>%
+   filter(PANID == "3144766")
# A tibble: 6 x 3
# Groups:   PANID [1]
    PANID WEEK       L1
    <int> <date>     <chr>
1 3144766 2009-06-15 BEER
2 3144766 2009-06-15 SALTY
3 3144766 2009-06-15 SALTY
4 3144766 2009-06-15 SALTY
5 3144766 2009-06-15 PIZZA
6 3144766 2009-06-15 PIZZA

Data:
EDIT1: Data removed due to character limit. Can be found here: https://textuploader.com/db1kf
EDIT2:
I run the following code to get the below output:
#Probability of buying BEER or SALTY if PIZZA was bought
dat %>%
  group_by(PIZZA > 0) %>%
  summarise(beer = sum(BEER > 0) / n(), nobeer = sum(BEER == 0) / n(),
            salty = sum(SALTY > 0) / n(), nosalty = sum(SALTY == 0) / n())

#Probability of buying SALTY or PIZZA if BEER was bought
dat %>%
  group_by(BEER > 0) %>%
  summarise(pizza = sum(PIZZA > 0) / n(), nopizza = sum(PIZZA == 0) / n(),
            salty = sum(SALTY > 0) / n(), nosalty = sum(SALTY == 0) / n())

#Probability of buying BEER or PIZZA if SALTY was bought
dat %>%
  group_by(SALTY > 0) %>%
  summarise(pizza = sum(PIZZA > 0) / n(), nopizza = sum(PIZZA == 0) / n(),
            beer = sum(BEER > 0) / n(), nobeer = sum(BEER == 0) / n())

Output:
1)

# A tibble: 2 x 5
  `PIZZA > 0`  beer nobeer salty nosalty
  <lgl>       <dbl>  <dbl> <dbl>   <dbl>
1 FALSE       0.333  0.667 0.833   0.167
2 TRUE        0.257  0.743 0.586   0.414

2)

# A tibble: 2 x 5
  `BEER > 0` pizza nopizza salty nosalty
  <lgl>      <dbl>   <dbl> <dbl>   <dbl>
1 FALSE      0.371   0.629 0.843   0.157
2 TRUE       0.290   0.710 0.532   0.468

3)

# A tibble: 2 x 5
  `SALTY > 0` pizza nopizza  beer nobeer
  <lgl>       <dbl>   <dbl> <dbl>  <dbl>
1 FALSE       0.569   0.431 0.569  0.431
2 TRUE        0.272   0.728 0.219  0.781

Just so my understanding is correct. If I buy PIZZA I have a 0.586 probability of buying SALTY and a 0.414 probability of not buying SALTY (table 1). However if I buy SALTY then I would have a 0.272 probability of buying PIZZA and a 0.728 of not buying PIZZA (table 3)?

A: I'm not 100% sure this is what you're looking for, so let me know if I'm off track.
We start with what I suggested in the comment (slightly adjusted to replace the NAs with 0):
df<- df %>% group_by(PANID, year, WEEK,L1) %>% summarize(n=n()) %>% tidyr::spread(L1, n, fill=0)

This gives us a wide-data format where for each person-week, we see the number of purchases of each of the three food types, e.g.:
> head(df,3)
# A tibble: 3 x 6
# Groups:   PANID, year, WEEK [3]
    PANID  year WEEK        BEER PIZZA SALTY
    <int> <int> <date>     <dbl> <dbl> <dbl>
1 3108696  2007 2007-12-31     2     4     6
2 3108696  2008 2008-01-21     0     2     2
3 3108696  2008 2008-02-04     1     0     2

Now we can create a table that gives the probability for buying either BEER or SALTY (of any amount) if PIZZA (of any amount) was purchased in the same week:
df %>% group_by(PIZZA>0) %>%
  summarise(beer=sum(BEER>0)/n(),nobeer=sum(BEER==0)/n(),
    salty=sum(SALTY>0)/n(),nosalty=sum(SALTY==0)/n())

Result:
# A tibble: 2 x 5
  `PIZZA > 0`  beer nobeer salty nosalty
  <lgl>       <dbl>  <dbl> <dbl>   <dbl>
1 FALSE       0.333  0.667 0.833   0.167
2 TRUE        0.257  0.743 0.586   0.414

So we can see that if Pizza was purchased, the likelihood of both beer and salty goes down compared to weeks when pizza is not purchased.
The same can be done for BEER and SALTY, of course.
An alternative, since we have a numerical variable for each of the three foods, would be to calculate correlation or even regression, but that's not what you asked for.


text:
Q: change of variables for hyperbolic PDE I have the PDE $U_{xx}+2U_{xy}-3U_{yy}+2U_x+6u_y = 0$;
I wish to convert the PDE to canonical form, by a change of variables.
I have computed the discriminant as positive, which tells me that the PDE is hyperbolic, so I think that the wave equation is the canonical form.
How do I proceed?

A: HINT :
Considering only tne main terms $AU_{xx}+BU_{xy}+CU_{yy}$ of the hyperbolic PDE, with $A=1\:,\:B=2\:,\:C=-3$, solving for $r$ the equation $Ar^2+Br+C=0$  gives two roots $r_1=1$ and $r_2=-3$
This draw to the change of variables
$\begin{cases}
s=1\:x+y \\
t=-3\:x+y
\end{cases}$
This will lead to the canonical form, simple to integrate later on.
It should be too long to explain here the method of characteristics for the choice of the change of variables. This can be found in many books or papers.


text:
Q: How to create a process from a coredump? TLDR
I have a coredump which was manually generated rather than as the result of some signal. I would like to execute some function from the executable on a portion of the memory from the original process.
How can I create a process with the same state as the original at the point at which the coredump was taken?
What I've Tried
I tried to dump the particular segment of memory to a file, run the executable again in GDB, and then restore the segment to its original address in the new process, but GDB gives me an error when trying to restore the memory.
$ gdb <program> <core>
> dump binary memory data.bin <start-addr> <end-addr>
> q

$ gdb <program>
> b <addr-at-which-coredump-was-taken>
> r
> restore data.bin binary <start-addr>
Restoring binary file data.bin into memory (<start-addr> to <end-addr>)
warning: restore: memory write failed ((undocumented errno -1)).

I understand that this might be a bug in GDB, and I've googled around to try and find a fix, but I just want this to work, and so I'm reaching out to see if there is an easier way to accomplish what I want to do.
Assume my program has a function like follows, that performs some complex operation on the memory pointed to by its argument...
int do_something(void* data)
{
   // Transform the memory pointed to by 'data' in some complex way...
}

...and assuming I was able to successfully restore memory as I tried, above, I would have then tried to execute do_something(<start-addr>) and retrieve the result like so...
$ gdb <program>
...
> b <addr-at-which-coredump-was-taken>
> r
> restore data.bin binary <start-addr>
Restoring binary file data.bin into memory (<start-addr> to <end-addr>)
Success!  <--  I wish...
> set $rip = do_something
> set $rdi = <start-addr>
> set $rsp = $rsp - 8
> set {void*}$rsp = <addr-at-which-coredump-was-taken>
> r
> dump binary memory data-transformed.bin <start-addr> <end-addr>
> q

At this point, I would have the transformed data like I wanted.
The reason why I can't just copy the memory to a buffer and write a program that will just call do_something(...) on that buffer, like shown below, is because, in reality, the data argument is a complex structure that contains pointers to separately allocated data, and so the entire structure isn't contained in contiguous memory. Therefore, if I were to take this approach, I would need to iterate through the entire structure, updating the value of pointers as I go, which would be a pain...
extern int do_something(void* data);

unsigned char data[] = { /* contents of data.bin */ };

int main(void)
{
    do_something(data);
    // Save transformed data somewhere...
    return 0;
}


text:
Q: Cron Jobs and Background Tasks I am studying about Cron Jobs and Background Tasks in Ruby On Rails. Can anyone tell me which one to use as currently I am using Whenever Gem. Why whenever is better than Sidekiq.

A: It is not comparable entities. As you are studying I will use few simple examples.
whenever is a cron job manager. In simple words it is alarm clock for task execution. Usually you can clean your server tmp nightly with such task.
sidekiq is a background job manager. You can use it to asynchronously process heavy load tasks on demand.
P.S. You cannot replace whenever with sidekiq without changing in approach for task execution and there should one better suitable, not "better, because sidekiq".

A: whenever will generate a cron configuration for you. This is abstracted via the use of a Ruby DSL. This is not necessarily easier, but it may be if you are more familiar with Ruby than with cron. In particular it allows you to schedule jobs to run at specific intervals. These jobs typically run asynchronously and separately from the main ruby web application.
sidekiq provides you with the interface to run asynchronous background tasks. It does not schedule them to run at specific times, as might cron, without further modules i.e. sidekiq-cron or sidekiq-scheduler


text:
Q: wevtutil without admin permissions Is it possible to install a provider without admin permissions?
whenever I try something like wevtutil im MyManifest.man I got 'Access is denied.'.
If I run the same command in an admin command prompt it works.

A: No as stated on the wevtutil documentation, you should have looked at the EventLog SDK here which reads:
This command is limited to members of the Administrators group and must be run with elevated privileges.


text:
Q: Valuations of integer valued polynomials
Consider the ring $R=\text{Int}(\mathbb Z):=\{p(x)\in \mathbb Q[x]\ |\ p(n)\in \mathbb Z, \forall n\in \mathbb Z \}$. Let $K$ denote the fraction field of $R$.
Fix an $a\in \mathbb Z$ and let $P$ be the prime ideal defined by
  $P:=\{q(x)\in R\ | \ q(a)\equiv 0 (\text{mod } p)\}$ and let $R_P$ denote the localization of $R$ at $P$.
Let $\Gamma$ denote the totally ordered group $\mathbb Z \times \mathbb Z$, where the operation is componentwise addition and the order is the lexicographic one.
Find a surjective valuation $v:K\rightarrow \Gamma$ such that its corresponding valuation ring is precisely $R_P$.

Now when trying to find $v\left(\frac{f(x)}{g(x)}\right)=(c_1,c_2)\in \mathbb Z\times \mathbb Z$, I thought of using a similar expression as for the $p$-adic valuation on $\mathbb Q$, namely define $c_2=e_p(f(a))-e_p(g(a))$ for one of the components, however the issue with that is that it yields a positive value even when $\frac{f(x)}{g(x)}$ is not in $R_P$, namely say if $e_p(f(a))=2, e_p(g(a))=1$. I have been trying to find some nice functions $P(X,Y)$ so that $P(X_1+X_2,Y_1+Y_2)=P(X_1,Y_1)+P(X_2,Y_2)$ which would help here, but none of them were surjective on $\mathbb Z$.

A: For simplicity I will take $a=0$. The substitution $x\mapsto x+a$ allows us to handle arbitrary $a$.
I claim that every element of $\mathbb{Q}[x]$ with constant term $1$ is in $R_P$, and in fact is a unit in $R_P$. To see this, take $f(x)\in\mathbb{Z}[x]$ and $n$ a positive integer. Then
$$
A_{f,n}(x):=\frac{(xf(x)+1)\ldots (xf(x)+n)}{n!}
$$
is in $R$, and $A_{f,n}(0)=1$ so $A_{f,n}\not\in P$. Thus $A_{f,n}$ is a unit in $R_P$. Also, we have
$$
\frac{A_{f,n}}{A_{f,n-1}}=1+\frac{xf(x)}{n}\in R_P^\times.
$$
Every polynomial in $\mathbb{Q}[x]$ with constant term $1$ can be written $1+xf(x)/n$ for some $f$ and $n$, so this proves the claim.
Now, every element of $R_P$ is a rational function which is defined and $p$-integral at $x=0$. Conversely, every rational function defined and $p$-integral at $0$ and can be written either in the form
$$
r\frac{a(x)}{b(x)}\hspace{10mm}\text{or}\hspace{10mm}\frac{a(x)-1}{b(x)},
$$
with $r\in\mathbb{Z}_{(p)}$ and $a,b\in\mathbb{Q}[x]$ with constant term $1$. Thus $R_P$ is precisely the set of rational functions $f\in\mathbb{Q}(x)$ which are defined  and $p$-integral at $x=0$.
Finally we can define the valuation $v$. For $\varphi(x)\in\mathbb{Q}(x)=K$, define
$$
v(\varphi(x))=\left( v_x(\varphi), v_p\big(\varphi(x) x^{-v_x(\varphi(x))}\big|_{x=0}\big)\right).
$$
Here $v_x$ is the $x$-adic valuation on $K$. In other words, $v(\varphi)=(c_1,c_2)$ where $c_1$ is the power of $x$ dividing $\varphi$ and $c_2$ is the power of $p$ dividing the leading term in the Laurent series expansion of $\varphi$ centered at $x=0$. For arbitrary $c_1$, $c_2$, we have $v(x^{c_1}p^{c_2})=(c_1,c_2)$, so $v$ is surjective. Additionally, we see that the valuation ring of $v$ is the set of rational functions which are defined and $p$-integral at $x=0$, which is $R_P$.


text:
Q: Parent components gets empty Params from ActivatedRoute I have a main component that has a router-outlet in it.  In the component that is loaded in the router-outlet I grab the url parameter like this:
ngOnInit(): void {
    // _route is injected ActivatedRoute
    this._route.params.subscribe((params: Params) => {
        if(params['url']){
          this.testUrl = params['url'].replace(new RegExp('\%2[fF]', 'g'), '/');

        }

    });
}

This works fine, but when I try it on my top level component the params object is always empty. I don't understand why as the nested components param object has the data in it and I am trying to access it exactly the same way.  There are no errors to go on, the param object is just empty.
Why doesn't my parent component get the right Params object from ActivatedRoute?
edit:
as requested full parent component
import { OnInit, Component, Directive } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
})
export class AppComponent {
  public testUrl: string;
  constructor(private router: Router, private _route: ActivatedRoute) {

  }
  ngOnInit(): void{
    this._route.queryParams.subscribe((params: Params) => {
      console.log(params);

      if (params['url']) {
        this.testUrl = params['url'].replace(new RegExp('\%2[fF]', 'g'), '/');
        alert(params['url']);
      }
    });
  }

}

router code for app.module.ts:
RouterModule.forRoot([
  { path: '', component: CheckMobileComponent },
  { path: '**', component: CheckMobileComponent }
]),

router code for nested module:
RouterModule.forChild([
 { path: 'report', component: MobileReportComponent }

There is no directly specified route for my app.component as it is loaded by a selector in index.html.

A: ActivatedRoute: Contains the information about a route associated with a component loaded in an router outlet. If you would like to access route details outside of it, use the code below.
import { Component } from '@angular/core';
import { Router, ActivatedRoute, Params, RoutesRecognized } from '@angular/router';

export class AppComponent {

    constructor(private route: ActivatedRoute, private router: Router) {

    }

    ngOnInit(): void {
        this.router.events.subscribe(val => {

            if (val instanceof RoutesRecognized) {

                console.log(val.state.root.firstChild.params);

            }
        });

    }
}

There are other ways to share data in between components for example by using a service.
For more details about how you can tackle this as concept, read comments here.

A: If you'd like to access the router parameters via a service, this approach will not work! consider using a service to prevent the replication of the "Route params value extraction logic" (from this Medium article):
@Injectable({
  providedIn: 'root'
})
export class MyParamsAwareService {
  constructor(private router: Router) {
    this.router.events
      .pipe(
        filter(e => (e instanceof ActivationEnd) && (Object.keys(e.snapshot.params).length > 0)),
        map(e => e instanceof ActivationEnd ? e.snapshot.params : {})
      )
      .subscribe(params => {
      console.log(params);
      // Do whatever you want here!!!!
      });
  }
}

A: ActivatedRoute works for components loaded via router-outlet. From docs - it:

Contains the information about a route associated with a component loaded in an outlet.

I don't think you can use it in components that are not loaded in an outlet. It also doesn't work in base classes your component extends.
class A { constructor(public route: ActivatedRoute) }
class B extends A { ngOnInit() { this.route; } }        // not working
class C { constructor(public route: ActivatedRoute) }   // working if loaded in outlet

A: Even better solution from the angular doc.

You can compute all params (or data) in the router state or to get params outside
*  of an activated component by traversing the RouterState tree as in the followin

collectRouteParams(): Record<string, string> {
    let params: Record<string, string> = {};

    const stack: ActivatedRouteSnapshot[] = [
      this.router.routerState.snapshot.root,
    ];

    while (stack.length > 0) {
      const route = stack.pop();
      if (route === undefined) {
        continue;
      }

      params = { ...params, ...route.params };

      stack.push(...route.children);
    }

    return params;
  }

A: The Very simple answer
import { Component } from '@angular/core';
import { Router, ActivatedRoute, Params, RoutesRecognized } from '@angular/router';

export class AppComponent {

    constructor(private actRoute: ActivatedRoute, private router: Router){}

    ngOnInit(): void {
        this.actRoute.firstChild.params.subscribe(
            (params: any) => {
                if (params.hasOwnProperty('<whatever the param name>') != '') {
                    //do whatever you want
                    console.log(params.<whatever the param name>);
                }
            });
    }
}

A: I was having a very similar problem with this mainly due to my misunderstanding of how routes actually worked. I thought I could just go up the chain of path parameters and each one would be a parent/child relationship. However, if a route has more than one element to the path, (e.g. /dashboard and profile/:user_id) it will depend on how you set up the routes in your routing module(s).
To explain a different way that made it click for me:
// If I am trying to access ActivatedRoute from the CheckMobileComponent (say
// through a `router-outlet`), I could get it through something like
// `this._route.firstChild`

{ path: '', component: CheckMobileComponent, children: [

    // If I want to get things from the '' context in MobileReportComponent, it
    // would be through something like `this._route.parent`

    { path: 'report', component: MobileReportComponent }

  ]

}