text:
Q: adding to a list of values in dictionary while iteration I was trying to count divisors of 10 numbers and add them as value to their dictionary but when I was trying to append other divisors to the list of values it didn't happen and got replaced. I wonder why this happens.
a = []
t = dict()
for i in range(10):
    a.append(input())
    a = [int(i) for i in a]
for num in a:
    for x in range (1, num + 1):
        if (num % x) == 0:
            t[num] = []
            t[num].append(x)
print(t)

A: It's because you reinitialize t[num] when you should not:
a = []
t = dict()
for i in range(10):
    a.append(input())
    a = [int(i) for i in a]
for num in a:
    for x in range (1, num + 1):
        if (num % x) == 0:
            if num not in t:  # Here: init t[num] to [] only if it does not yet exist
                t[num] = []
            t[num].append(x)

print(t)

A: defaultdict can make your life easier here since it will take care if the list allocation.
from collections import defaultdict

a = []
t = defaultdict(list)
for i in range(10):
    a.append(input())
    a = [int(i) for i in a]
for num in a:
    for x in range (1, num + 1):
        if (num % x) == 0:
            t[num].append(x)
print(t)


text:
Q: For Loop to pass a Variable through a URL in Python I am very new to Python and I am trying to learn on my own by doing some simple web scraping to get football stats.
I have been successful in getting the data for a single page at a time, but I have not been able to figure out how to add a loop into my code to scrape multiple pages at once (or multiple positions/years/conferences for that matter).
I have searched a fair amount on this and other websites but I can't seem to get it right.
Here's my code:
import csv
import requests
from BeautifulSoup import BeautifulSoup

url = 'http://www.nfl.com/stats/categorystats?seasonType=REG&d-447263-n=1&d-447263-o=2&d-447263-p=1&d-447263-s=PASSING_YARDS&tabSeq=0&season=2014&Submit=Go&experience=&archive=false&statisticCategory=PASSING&conference=null&qualified=false'
response = requests.get(url)
html = response.content

soup = BeautifulSoup(html)
table = soup.find('table', attrs={'class': 'data-table1'})

list_of_rows = []
for row in table.findAll('tr'):
    list_of_cells = []
    for cell in row.findAll('td'):
        text = cell.text.replace('&#39', '')
        list_of_cells.append(text)
    list_of_rows.append(list_of_cells)

#for line in list_of_rows: print ', '.join(line)

outfile = open("./2014.csv", "wb")
writer = csv.writer(outfile)
writer.writerow(["Rk", "Player", "Team", "Pos", "Comp", "Att", "Pct", "Att/G", "Yds", "Avg", "Yds/G", "TD", "Int", "1st", "1st%", "Lng", "20+", "40+", "Sck", "Rate"])
writer.writerows(list_of_rows)

outfile.close()

Here's my attempt at adding a variable into the URL and building a loop:
import csv
import requests
from BeautifulSoup import BeautifulSoup

pagelist = ["1", "2", "3"]

x = 0
while (x < 500):
    url = "http://www.nfl.com/stats/categorystats?seasonType=REG&d-447263-n=1&d-447263-o=2&d-447263-p="+str(x)).read(),'html'+"&d-447263-s=RUSHING_ATTEMPTS_PER_GAME_AVG&tabSeq=0&season=2014&Submit=Go&experience=&archive=false&statisticCategory=RUSHING&conference=null&qualified=false"

    response = requests.get(url)
    html = response.content
    soup = BeautifulSoup(html)
    table = soup.find('table', attrs={'class': 'data-table1'})
    list_of_rows = []
    for row in table.findAll('tr'):
        list_of_cells = []
        for cell in row.findAll('td'):
            text = cell.text.replace('&#39', '')
            list_of_cells.append(text)
    list_of_rows.append(list_of_cells)

    #for line in list_of_rows: print ', '.join(line)

    outfile = open("./2014.csv", "wb")
    writer = csv.writer(outfile)
    writer.writerow(["Rk", "Player", "Team", "Pos", "Att", "Att/G", "Yds", "Avg", "Yds/G", "TD", "Long", "1st", "1st%", "20+", "40+", "FUM"])
    writer.writerows(list_of_rows)
    x = x + 0
    outfile.close()

Thanks much in advance.
Here's my revised code that seems to be deleting each page as it writes to the csv file.
import csv
import requests
from BeautifulSoup import BeautifulSoup

url_template = 'http://www.nfl.com/stats/categorystats?tabSeq=0&season=2014&seasonType=REG&experience=&Submit=Go&archive=false&d-447263-p=%s&conference=null&statisticCategory=PASSING&qualified=false'

for p in ['1','2','3']:
    url = url_template % p
    response = requests.get(url)
    html = response.content
    soup = BeautifulSoup(html)
    table = soup.find('table', attrs={'class': 'data-table1'})

    list_of_rows = []
    for row in table.findAll('tr'):
        list_of_cells = []
        for cell in row.findAll('td'):
            text = cell.text.replace('&#39', '')
            list_of_cells.append(text)
        list_of_rows.append(list_of_cells)

    #for line in list_of_rows: print ', '.join(line)

        outfile = open("./2014Passing.csv", "wb")
        writer = csv.writer(outfile)
        writer.writerow(["Rk", "Player", "Team", "Pos", "Comp", "Att", "Pct", "Att/G", "Yds", "Avg", "Yds/G", "TD", "Int", "1st", "1st%", "Lng", "20+", "40+", "Sck", "Rate"])
        writer.writerows(list_of_rows)

outfile.close()

A: Assuming that you just want to change the page number, you could do something like this and use string formatting:
url_template = 'http://www.nfl.com/stats/categorystats?seasonType=REG&d-447263-n=1&d-447263-o=2&d-447263-p=%s&d-447263-s=PASSING_YARDS&tabSeq=0&season=2014&Submit=Go&experience=&archive=false&statisticCategory=PASSING&conference=null&qualified=false'
for page in [1,2,3]:
  url = url_template % page
  response = requests.get(url)
  # Rest of the processing code can go here
  outfile = open("./2014.csv", "ab")
  writer = csv.writer(outfile)
  writer.writerow(...)
  writer.writerows(list_of_rows)
  outfile.close()

Note that you should open the file in append mode ("ab") instead of write mode ("wb"), as the latter overwrites existing contents, as you've experienced. Using append mode, the new contents are written at the end of the file.
This is outside the scope of the question, and more of a friendly code improvement suggestion, but the script would become easier to think about if you split it up into smaller functions that each do one thing, e.g., get the data from the site, write it to csv, etc..

redpajama_set_name: RedPajamaStackExchange


text:
Q: when run "python setup.py install", I meet "error:[WinError 32] The process cannot access the file because it is being used by another process" I want to install Third-party library "uncertainty-baselines" in my conda virtual environment "uncertainty_bl".I want to run "Batchensemble" example.
C:\Users\70987\Desktop\uncertainty-baselines-main>conda activate uncertainty_BL
(uncertainty_BL) C:\Users\70987\Desktop\uncertainty-baselines-main>python setup.py install
running install
E:\Anaconda\envs\uncertainty_BL\lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
  warnings.warn(
E:\Anaconda\envs\uncertainty_BL\lib\site-packages\setuptools\command\easy_install.py:144: EasyInstallDeprecationWarning: easy_install command is deprecated. Use build and pip and other standards-based tools.
  warnings.warn(
running bdist_egg
running egg_info
writing uncertainty_baselines.egg-info\PKG-INFO
writing dependency_links to uncertainty_baselines.egg-info\dependency_links.txt
writing requirements to uncertainty_baselines.egg-info\requires.txt
writing top-level names to uncertainty_baselines.egg-info\top_level.txt
reading manifest file 'uncertainty_baselines.egg-info\SOURCES.txt'
adding license file 'LICENSE'
writing manifest file 'uncertainty_baselines.egg-info\SOURCES.txt'
installing library code to build\bdist.win-amd64\egg
running install_lib
running build_py
creating build\bdist.win-amd64\egg
creating build\bdist.win-amd64\egg\uncertainty_baselines
creating build\bdist.win-amd64\egg\uncertainty_baselines\datasets
copying build\lib\uncertainty_baselines\datasets\aptos.py -> build\bdist.win-amd64\egg\uncertainty_baselines\datasets
...
byte-compiling build\bdist.win-amd64\egg\uncertainty_baselines\datasets\aptos.py to aptos.cpython-39.pyc
...
creating build\bdist.win-amd64\egg\EGG-INFO
copying uncertainty_baselines.egg-info\PKG-INFO -> build\bdist.win-amd64\egg\EGG-INFO
copying uncertainty_baselines.egg-info\SOURCES.txt -> build\bdist.win-amd64\egg\EGG-INFO
copying uncertainty_baselines.egg-info\dependency_links.txt -> build\bdist.win-amd64\egg\EGG-INFO
copying uncertainty_baselines.egg-info\requires.txt -> build\bdist.win-amd64\egg\EGG-INFO
copying uncertainty_baselines.egg-info\top_level.txt -> build\bdist.win-amd64\egg\EGG-INFO
zip_safe flag not set; analyzing archive contents...
creating 'dist\uncertainty_baselines-0.0.7-py3.9.egg' and adding 'build\bdist.win-amd64\egg' to it
removing 'build\bdist.win-amd64\egg' (and everything under it)
Processing uncertainty_baselines-0.0.7-py3.9.egg
Removing e:\anaconda\envs\uncertainty_bl\lib\site-packages\uncertainty_baselines-0.0.7-py3.9.egg
error: [WinError 32]  Another program is using this file and the process cannot access it。: 'e:\\anaconda\\envs\\uncertainty_bl\\lib\\site-packages\\uncertainty_baselines-0.0.7-py3.9.egg'

Why I meet the error? How to deal with it?


text:
Q: How to Rewrite this R Code in a Single Function This R code searches the exact seed that produces the desired coefficient of a simulated autoregressive of order 1 AR(1) time-series data using the arima.sim() and forecast::auto.arima() functions.
The Problem that Led to the Searching of Exact Seed for arima.sim() Function
If one uses arima.sim() function to simulate an AR(1) time-series data and at the same time want to know the parameter or order of such simulated data, one discovers that the specified parameter ar and the order of the simulated AR(1) is not as specified in the arima.sim() function. Take a look at this.
set.seed(1)
ar1 <- arima.sim(n=10, model=list(ar=0.8, order=c(1, 0, 0)), sd=1)
auto_ar <- forecast::auto.arima(ar1, ic="aicc")
auto_ar

#Series: ar1
#ARIMA(0,0,0) with zero mean

#sigma^2 estimated as 1.008:  log likelihood=-14.23
#AIC=30.46   AICc=30.96   BIC=30.76

When the seed is set at 1, (set.seed(1)) in the above, order and coefficient of autocorrelation is not (1, 0, 0) and 0.8 respectively as it was set in the arima.sim() function compare to when one set the seed to 289805 (set.seed(289805)) instead of 1 or some other seed.
set.seed(289805)
ar1 <- arima.sim(n=10, model=list(ar=0.8, order=c(1, 0, 0)), sd=1)
auto_ar <- forecast::auto.arima(ar1, ic="aicc")
auto_ar

#Series: ar1
#ARIMA(1,0,0) with zero mean

#Coefficients:
         #ar1
      #0.8000
#s.e.  0.1458

#sigma^2 estimated as 1.849:  log likelihood=-17.25
#AIC=38.49   AICc=40.21   BIC=39.1

This R code searched for the set of seeds that print the correct parameter
.
Here is the original function
FUN <- function(i) {
  set.seed(i)
  ar1 <- arima.sim(n=100, model=list(ar=0.8, order=c(1, 0, 0)), sd=1)
  ar2 <- auto.arima(ar1, ic="aicc")
  cf <- ar2$coef
  ## case handling
  if (length(cf) == 0) rep(NA, 2)  ## sometimes result is `character(0)` -> NA
  else if (substr(cf[1], 1, 5) %in% "0.800") c(cf, i)  ## hit, that's what we want
  else rep(NA, 2)  ## all other cases -> NA
}

R <- 1e3  ## this would be your 1e5
seedv <- 1:R  ## or use custom seed vector

library(parallel)
cl <- makeCluster(detectCores() - 1)  ## for all cores remove `- 1`
clusterExport(cl, c("FUN"), envir=environment())
clusterEvalQ(cl, suppressPackageStartupMessages(library(forecast)))

res <- `colnames<-`(t(parSapply(cl, seedv, "FUN")), c("cf", "seed"))

stopCluster(cl)

What I Want
I want to rewrite this R code to be in a single function (though it may be in a composite function) such that all I need to do is to run and call it with its arguments.
Here is what I tried
FUN1 <- function(n, ar, sd, arr, R, FUN2){
  FUN2 <- function(i, n, ar, sd, arr) {
    set.seed(i)
    ar1 <- arima.sim(n=n, model=list(ar=ar, order=c(1, 0, 0)), sd=sd)
    ar2 <- auto.arima(ar1, ic="aicc")
    (cf <- ar2$coef)
    if (length(cf) == 0) {
    rep(NA, 2)
    }
    else if (all(grepl(c("ar1|intercept"), names(cf))) &  ## using `grepl`
             substr(cf["ar1"], 1, 5) %in% "arr") {
      c(cf, seed=i)
    }
    else {
      rep(NA, 2)
    }
  }

  seedv <- 1:R

  library(parallel)
  cl <- makeCluster(detectCores() - 1)
  clusterExport(cl, c("FUN2"), envir=environment())
  clusterEvalQ(cl, suppressPackageStartupMessages(library(forecast)))

  res <- parLapply(cl, seedv, "FUN2")

  res1 <- res[!sapply(res, anyNA)]  ## filter out NAs

  stopCluster(cl)
}
FUN1(n = 10, ar = 0.8, sd = 1, arr = 0.800, R = 1000, FUN2 = FUN2)

*

*n is the sample size.

*ar is the $\phi$ value.

*sd is the value of standard deviation.

*arr is the value of $\phi$ sort for.

*R is maximum number of seed searched starting from 1.


text:
Q: How to prevent the Visual Brush from stretching its content In my project I want to display a small logo on the side of a custom control. Since I have no canvas I thought maybe a Visual Brush would be a good Idea to place the logo in the background.
<VisualBrush>
    <VisualBrush.Visual>
        <Rectangle Width="200" Height="200" Fill="Red" />
    </VisualBrush.Visual>
</VisualBrush>

But the Rectangle I am using right now is not 200x200. It takes the complete available space. Thats not what I want. I also tried a Viewbox and set the stretch property but the result is the same because in the end I don't need a simple Rectangle but a canvas with many path objects as children. A Viewbox supports only one child.
This there any way to get around this problem?

A: You need to set TileMode, Stretch, AlignmentX and AlignmentY properties on your VisualBrush:
<VisualBrush TileMode="None" Stretch="None" AlignmentX="Left" AlignmentY="Top">
    <VisualBrush.Visual>
        <Rectangle Height="200" Width="200" Fill="Red"></Rectangle>
    </VisualBrush.Visual>
</VisualBrush>

A: Add Grid and this Set Vertical alligment to Top and Horizontal alignment to Right
Sample code
  <VisualBrush x:Key="myVisual">
        <VisualBrush.Visual>
            <Grid>
                <Rectangle Height="200" Width="200" Fill="Red" HorizontalAlignment="Right"  VerticalAlignment="Top" ></Rectangle>
            </Grid>
        </VisualBrush.Visual>
    </VisualBrush>

A: For me, I set the following attribute on the VisualBrush, and the VisualBrush now looks exactly like a MediaElement:
Stretch="Uniform"


text:
Q: RSA Algorithm Finding decryption key I am struggling with finding the decryption key in this example i am failing on Back substitution I can get euclidean algorithm, i get 1 reminder at the end but then I cant understand how back substitution works here is my example.
p = 61 , q = 59
n = 61 x 59 = 3599
q(n) = 61-1 x 59-1 = 3480
3480x * 2531y=1

3480 = 2531(1) + 949
2531 = 949(2) + 633
949 = 633(1) + 316
633 = 316(2) + 1

And then i try back substitution
1=633-316(2)
1=633-316(949 - 633)
1=633 - 316(949) + 316(633)

after that I should combine the numbers but i dont know which, I have no problems solving a example with smaller number but once it come to 3k+ i have trouble. Could any one kindly explain if im doing it correctly?
Regards,
Wojtek.


text:
Q: How to count and sum the number of occurences of a type string from a struct? First the poor code:
package main

import (
    "fmt"
)

type rocketship struct {
    passengers     string
    gear           string

func mapper(separators map[string]string) rocketship {
    maps := rocketship{
        passengers:          separators["passengers"],
        gear:                separators["gear"],
    }
    return maps
}

func main() {

// How to pull the string
for _, passer := range passengers {
// count each passenger
sum = passer++
if err != nil {
        fmt.Println("No passengers coming today", err)
        return
          }
   fmt.Println("There are", sum, "passengers onboard today")
}

What are the steps here?

*

*Pull a long name out of a struct (if a passenger is on the ship), can be "John Fitzgerald Kennedy" or "J.F.K" or "JFK".

*Add this passenger in the tally

*Continue till all passengers are counted

*Sum the passengers and print how many there were.

The issue:

*

*How can a string from a struct be converted to one occurrence?

*How can the occurrences be summed together to be printed?

The final print could be "There are 6 passengers onboard today"


text:
Q: allow only logged in user to access private page I am working on a MIS project and currently i am creating a login system for that.
I am using servlet on server side and jquery on client side for ajax calls.
their is a login page which first checks the login status through an ajax call and if user is already logged in then it changes the page location to 'services.html'.
when services.html loads i am again checking the login status and if user is not logged in
 then i am changing the page location to 'Login.html' using
document.location='Login.html';
The code looks like this
$(document).ready(function() {
$("#login").hide();
    $.post("checkLogin",function(xml) {
    var status = $(xml).find("result").text();
    if (status == "yes") {
       document.location='Login.html';
    }
    else{
        // Do Nothing.
    }
});

Now the problem with the services.html page is that it checks the login status after the full page is loaded into the browser.
I don't know any other good way to restrict Non Logged-In users to access 'services.html' page . As this project is quite big , i have to create a large number of private pages similar to 'services.html' Like 'stuInfo.html' For accessing Student Information etc.
Anyone please tell me any good way for this.

A: You should check this in the server side, not in the client side. JavaScript runs at client side and is disableable, hackable and spoofable. You don't want your application to be that weak.
Put all the restricted pages in some folder, e.g. /secured and then create a Filter which is mapped on an <url-pattern> of /secured/* and checks the presence of the logged-in user in the doFilter() method.
An example can be found in the servlet-filters tag info page.

A: Look into Spring Security.
In your case, you're almost certainly going to be using some sort of form-based authentication, but it also supports HTTP authentication.

A: Authentication is something that is best done at the app server or framework level. J2EE containers and frameworks (like Spring mentioned above) do the leg work, so you just configure what pages lie withing and what pages lie outside the authenticated area.
Plain old servlets can be used for authentication etc, but remember there will be issues you will run into as you expand your app. One way to do it using servlets is to have all your privileged pages behind a /loggedin/services.html.
Then you have a servlet defined for /loggedin/... which redirects to the login page if the authentication params cannot be found in the session, or request or however you are doing it.
Hope that helps


text:
Q: Chebyshev Theorm for discrete Variable proof i am an engineering student currently taking a class from a math professor. this far from my expertise and I hoped other than I got the answer to my questions, perhaps I got enlighten by it.
Are there any source I could learn things related to proving Chebyshev Theorm for discrete variables?
It would be great if there's a source I could learn beside the answer to my question.
Thanks


text: Q: Problems positioning tables or sections within a div I hope someone might be able to help. I have a div id="main" with a blue background and a width of 100%. When I try to put a table or a section within the div, they end up overflowing off of the blue background even though I place the closing tag after the table or section. The blue background is not expanding to fit the new content, it is ignoring the table or section.


text:
Q: IBM Integration Desinger 8.x has a plugin for SonarQube I am trying to configure SonarQube Plugin with IBM IID 8 as its based on Eclipse I thought i will  be able to configure it easily with SonarQube, but its not working. I try to find out on IBM website but not have any luck.
Can somebody tell me if there is anyway to do this?

A: IID 8.5.5 runs on Eclipse Helios 3.6.3 .. you need to find a plugin version which is compatible with this Eclipse version.
You can also install Eclipse Market Place into IBM Integration Designer
http://www.eclipse.org/downloads/download.php?file=/mpc/releases/1.0.1/mpc-1.0.1.zip


text:
Q: How to share variable in the views after firing event laravel 5.2 I have this listener class
class NotifyMR
{
/**
 * Create the event listener.
 */
public function __construct()
{

}

public function handle(LeaveRequestWasReviewed $event)
{
    return $event->leaveRequest.'->'.$event->statue;
}
}

so I need to share some variables in the views after firing event , so how to do it ?

A: Via View facade
View::share('key', 'value');


text:
Q: 1800: There was a problem in setting up your access Hello all professionals,
I would like to use SFDC OAuth Tool published by INFORMATICA
(Tool link:https://marketplace.informatica.com/listings/cloud/solutions/sfdc_oauth_tool.html)
The software installed on my AWS virtual machine.
I login with a system admin account to the production instance (http://localhost:8090/salesforce/initiateoauth) due to my developer instance.
The result showed that

We can't authorize you because of an OAuth error. For more information, contact your Salesforce administrator.
1800 : There was a problem in setting up your remote access

I have done some research from the forum:

*

*https://developer.salesforce.com/forums/?id=906F0000000DCHJIA4

*http://www.gavan.in/2021/09/salesforce-oauth-error-we-cant.html

*https://developer.salesforce.com/forums/?id=9060G000000IB6nQAG
Since I am with Admin permission and have checked the profiles settings, still with failed OAuth login result:

*

*View All Data permission

*API Enabled permission

*Modify All Data

*Author Apex

I also check my login history,and I have been login successfully.
The result is really confused.

I would like to ask for help.
Should I create any customized application in SFDC or did I miss anything else in setting?
Please for more suggestions, thanks a lot.


text:
Q: Pull-down resistors on logic gate and decoder inputs? I'm designing a very basic circuit for testing a switch sequence. I'm using a CMOS decoder CD4028B (link to datasheet) and XOR gate (CD74HC86E - link to datasheet). Reading the switch sequence is crucial and therefore I've been thinking whether I should add pull-down resistors to all inputs of the decoder and XOR gate to prevent pin-floating and false readings? I went through the datasheet and there was no recommendation whether pull-downs should be added to prevent pin-floating. Do these logic gates usually provide internal pull-down resistors or is it necessary to add them yourself? What values are recommended? I want to draw as little current as possible. I'm sorry if this is a really basic question. We made quite a few circuits with logic gates in college but never talked about the pin-floating and current draw aspect of these circuits.
Inputs of decoder are wired to the switch that is being tested, outputs of decoder are then wired to XOR gate inputs and XOR gate outputs are then wired to BJTs to drive LEDs.
Any help would be greatly appreciated. :)
Thank you.

A: CD40xx and HC74xx circuits do not include pullups or pulldowns on their inputs.
CD40xx and HC74xx inputs must not be allowed to float. They must always be driven with a defined logic level, from a logic output, from a pullup or pulldown, or a switch to ground or rail.
If CMOS inputs are allowed to float, they could end up in the middle linear region, which at best causes nonsense outputs, and at worst causes oscillation which draws excessive power and causes the chip to fail through overheating.
As CMOS needs very little (nominally zero) (leakage only) current, very large resistors can be used as pullups or pulldowns if speed is not an issue. 1Mohm 100k would draw only a few 10s of uA, and would be more than enough to keep all types of CD40xx inputs biassed properly (WRB says he's found one brand that specifies 5uA leakage max, though I've only seen 1uA in my (admittedly quick) survey of them).


text:
Q: Filter an array by a condition and changer the key name I have a list of objects in an array like this:
[
  {
    "code": "ICh8tTgU",
    "mposMerchantProfileCode": "jjijuhikl",
    "shortLabel": "Pizza 6",
    "description": "Cookies without oil nor butter",
    "priceList": [
      {
        "price": 3.9,
        "currency": "DH",
        "taxes": "11%",
        "formattedPrice": "$"
      },
      {
        "price": 2.9,
        "currency": "YN",
        "taxes": "13%",
        "formattedPrice": "€"
      }
    ],
    "imageFormat": "jpg",
    "isFavorite": false,
    "isSpecial": false,
    "status": "A",
    "statDHate": "2021-01-16T13:11:12.933+0000",
    "imageBase64": "/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAdACEDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwB918NtKsoHnMpijQZLGVqYnhBbe4SCGWYyNF5qp5jA4/Hvz0roNf1ovaogeOO2ceYZA2S4HTafTPOeM9jXlU/ie9uNZdtNeZAMo7IxIIOOM88V5bk5OyPThGyuztVjPnjyL0wI6qRGZhKU653AjBORjAOKfe397aqZILq0aEEH5x95RnPygZ5PHU1wesQXWkXEUsMF2kk2HJVt+7Pt2PboKpvPrgVEeEoHJx0BA9Pr3qPZOWqZtzRWjO7/AOE0P/PkPyorznzbz+7cflRVeyXkRzLsd+dE1XxDqF1Jram3gtsRoscwMjZx09sVan8K6fo+iyCKV7VEPnt53KtgggGuq1DREnInineCcA4kQA8dwc9RXA6vZ3jTyQTXqyjksWiPzfUbqc6ck7LYiFVNXluVdT16zvCLqScS3EnEZXI8pR29MBgT9TWNqHiWMokVsjSSbeZEc9TWlb+GxfmITXjbV+VFCDCgenNdbpPhTTbNVcxmU8fe9zWkaMepM67+yeS/bNY/54/+QzRXv/8AZFh/zw/WituWPYw9rPuf/9k=",
    "qte": 1,
    "isCombo": false
  },
  {
    "code": "9oTjZDRM",
    "mposMerchantProfileCode": "jjijuhikl",
    "shortLabel": "Pizza 5",
    "description": "Cookies without oil nor butter",
    "priceList": [
      {
        "price": 3.9,
        "currency": "DH",
        "taxes": "11%",
        "formattedPrice": "$"
      },
      {
        "price": 2.9,
        "currency": "YN",
        "taxes": "13%",
        "formattedPrice": "€"
      }
    ],
    "imageFormat": "jpg",
    "isFavorite": false,
    "isSpecial": false,
    "status": "A",
    "statDHate": "2021-01-16T13:11:06.843+0000",
    "imageBase64": "/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAdACEDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwB918NtKsoHnMpijQZLGVqYnhBbe4SCGWYyNF5qp5jA4/Hvz0roNf1ovaogeOO2ceYZA2S4HTafTPOeM9jXlU/ie9uNZdtNeZAMo7IxIIOOM88V5bk5OyPThGyuztVjPnjyL0wI6qRGZhKU653AjBORjAOKfe397aqZILq0aEEH5x95RnPygZ5PHU1wesQXWkXEUsMF2kk2HJVt+7Pt2PboKpvPrgVEeEoHJx0BA9Pr3qPZOWqZtzRWjO7/AOE0P/PkPyorznzbz+7cflRVeyXkRzLsd+dE1XxDqF1Jram3gtsRoscwMjZx09sVan8K6fo+iyCKV7VEPnt53KtgggGuq1DREnInineCcA4kQA8dwc9RXA6vZ3jTyQTXqyjksWiPzfUbqc6ck7LYiFVNXluVdT16zvCLqScS3EnEZXI8pR29MBgT9TWNqHiWMokVsjSSbeZEc9TWlb+GxfmITXjbV+VFCDCgenNdbpPhTTbNVcxmU8fe9zWkaMepM67+yeS/bNY/54/+QzRXv/8AZFh/zw/WituWPYw9rPuf/9k=",
    "qte": 1,
    "isCombo": false
  },
  {
    "code": "0GJW16Ql",
    "mposMerchantProfileCode": "jjijuhikl",
    "shortLabel": "Fruit 10",
    "description": "Cookies without oil nor butter",
    "priceList": [
      {
        "price": 3.9,
        "currency": "DH",
        "taxes": "11%",
        "formattedPrice": "$"
      },
      {
        "price": 2.9,
        "currency": "YN",
        "taxes": "13%",
        "formattedPrice": "€"
      }
    ],
    "imageFormat": "jpg",
    "isFavorite": false,
    "isSpecial": false,
    "status": "A",
    "statDHate": "2021-01-16T13:09:59.674+0000",
    "imageBase64": "/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAdACEDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwB918NtKsoHnMpijQZLGVqYnhBbe4SCGWYyNF5qp5jA4/Hvz0roNf1ovaogeOO2ceYZA2S4HTafTPOeM9jXlU/ie9uNZdtNeZAMo7IxIIOOM88V5bk5OyPThGyuztVjPnjyL0wI6qRGZhKU653AjBORjAOKfe397aqZILq0aEEH5x95RnPygZ5PHU1wesQXWkXEUsMF2kk2HJVt+7Pt2PboKpvPrgVEeEoHJx0BA9Pr3qPZOWqZtzRWjO7/AOE0P/PkPyorznzbz+7cflRVeyXkRzLsd+dE1XxDqF1Jram3gtsRoscwMjZx09sVan8K6fo+iyCKV7VEPnt53KtgggGuq1DREnInineCcA4kQA8dwc9RXA6vZ3jTyQTXqyjksWiPzfUbqc6ck7LYiFVNXluVdT16zvCLqScS3EnEZXI8pR29MBgT9TWNqHiWMokVsjSSbeZEc9TWlb+GxfmITXjbV+VFCDCgenNdbpPhTTbNVcxmU8fe9zWkaMepM67+yeS/bNY/54/+QzRXv/8AZFh/zw/WituWPYw9rPuf/9k=",
    "qte": 1,
    "isCombo": false
  },
  {
    "code": "R2ABOTYW",
    "label": "Grilled Chicken + Mango Juice",
    "shortLabel": "Lunch 1",
    "priceList": [
      {
        "price": 6.59,
        "currency": "DH"
      },
      {
        "price": 5.19,
        "currency": "YN"
      }
    ],
    "productList": [
      {
        "productCode": "bKSZqaYa"
      },
      {
        "productCode": "MM3FbWRu"
      }
    ],
    "merchantCode": "jjijuhikl",
    "qte": 2,
    "isCombo": true
  }
]
]

I can filter and separate this array to two array depending the isCombo value
var productList = this.props.currentSale.Data.filter(i => i.isCombo === false)
var comboList = this.props.currentSale.Data.filter(i => i.isCombo === true)

But what I want is two arrays productList and comboList with the same values but not the same key names like this:
    productList=[
        {
            "code": "EvZfNCUL",
            "unitPrice": 5.0,
            "quantity": 2
        },
        {
            "code": "NcWmRo1K",
            "unitPrice": 5.0,
            "quantity": 1
        }
    ];
    comboList= [
        {
            "code": "R2ABOTYW",
            "quantity": 2, // before it was "qte": 2,
            "unitPrice": 6.59
        },
    ];

Keep only code, quantity, unitPrice of each elements (by changing their key names: qte > quantity for example) and delete the other keys

A: You can use a map function to define new objects based on your existing ones with new keys, something like this (I named the array currentSale for local testing). Also I'm not sure which price you need but you should be able to modify the map to get it.

const currentSale = [
    {
      "code": "ICh8tTgU",
      "mposMerchantProfileCode": "jjijuhikl",
      "shortLabel": "Pizza 6",
      "description": "Cookies without oil nor butter",
      "priceList": [
        {
          "price": 3.9,
          "currency": "DH",
          "taxes": "11%",
          "formattedPrice": "$"
        },
        {
          "price": 2.9,
          "currency": "YN",
          "taxes": "13%",
          "formattedPrice": "€"
        }
      ],
      "imageFormat": "jpg",
      "isFavorite": false,
      "isSpecial": false,
      "status": "A",
      "statDHate": "2021-01-16T13:11:12.933+0000",
      "imageBase64": "/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAdACEDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwB918NtKsoHnMpijQZLGVqYnhBbe4SCGWYyNF5qp5jA4/Hvz0roNf1ovaogeOO2ceYZA2S4HTafTPOeM9jXlU/ie9uNZdtNeZAMo7IxIIOOM88V5bk5OyPThGyuztVjPnjyL0wI6qRGZhKU653AjBORjAOKfe397aqZILq0aEEH5x95RnPygZ5PHU1wesQXWkXEUsMF2kk2HJVt+7Pt2PboKpvPrgVEeEoHJx0BA9Pr3qPZOWqZtzRWjO7/AOE0P/PkPyorznzbz+7cflRVeyXkRzLsd+dE1XxDqF1Jram3gtsRoscwMjZx09sVan8K6fo+iyCKV7VEPnt53KtgggGuq1DREnInineCcA4kQA8dwc9RXA6vZ3jTyQTXqyjksWiPzfUbqc6ck7LYiFVNXluVdT16zvCLqScS3EnEZXI8pR29MBgT9TWNqHiWMokVsjSSbeZEc9TWlb+GxfmITXjbV+VFCDCgenNdbpPhTTbNVcxmU8fe9zWkaMepM67+yeS/bNY/54/+QzRXv/8AZFh/zw/WituWPYw9rPuf/9k=",
      "qte": 1,
      "isCombo": false
    },
    {
      "code": "9oTjZDRM",
      "mposMerchantProfileCode": "jjijuhikl",
      "shortLabel": "Pizza 5",
      "description": "Cookies without oil nor butter",
      "priceList": [
        {
          "price": 3.9,
          "currency": "DH",
          "taxes": "11%",
          "formattedPrice": "$"
        },
        {
          "price": 2.9,
          "currency": "YN",
          "taxes": "13%",
          "formattedPrice": "€"
        }
      ],
      "imageFormat": "jpg",
      "isFavorite": false,
      "isSpecial": false,
      "status": "A",
      "statDHate": "2021-01-16T13:11:06.843+0000",
      "imageBase64": "/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAdACEDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwB918NtKsoHnMpijQZLGVqYnhBbe4SCGWYyNF5qp5jA4/Hvz0roNf1ovaogeOO2ceYZA2S4HTafTPOeM9jXlU/ie9uNZdtNeZAMo7IxIIOOM88V5bk5OyPThGyuztVjPnjyL0wI6qRGZhKU653AjBORjAOKfe397aqZILq0aEEH5x95RnPygZ5PHU1wesQXWkXEUsMF2kk2HJVt+7Pt2PboKpvPrgVEeEoHJx0BA9Pr3qPZOWqZtzRWjO7/AOE0P/PkPyorznzbz+7cflRVeyXkRzLsd+dE1XxDqF1Jram3gtsRoscwMjZx09sVan8K6fo+iyCKV7VEPnt53KtgggGuq1DREnInineCcA4kQA8dwc9RXA6vZ3jTyQTXqyjksWiPzfUbqc6ck7LYiFVNXluVdT16zvCLqScS3EnEZXI8pR29MBgT9TWNqHiWMokVsjSSbeZEc9TWlb+GxfmITXjbV+VFCDCgenNdbpPhTTbNVcxmU8fe9zWkaMepM67+yeS/bNY/54/+QzRXv/8AZFh/zw/WituWPYw9rPuf/9k=",
      "qte": 1,
      "isCombo": false
    },
    {
      "code": "0GJW16Ql",
      "mposMerchantProfileCode": "jjijuhikl",
      "shortLabel": "Fruit 10",
      "description": "Cookies without oil nor butter",
      "priceList": [
        {
          "price": 3.9,
          "currency": "DH",
          "taxes": "11%",
          "formattedPrice": "$"
        },
        {
          "price": 2.9,
          "currency": "YN",
          "taxes": "13%",
          "formattedPrice": "€"
        }
      ],
      "imageFormat": "jpg",
      "isFavorite": false,
      "isSpecial": false,
      "status": "A",
      "statDHate": "2021-01-16T13:09:59.674+0000",
      "imageBase64": "/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAdACEDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwB918NtKsoHnMpijQZLGVqYnhBbe4SCGWYyNF5qp5jA4/Hvz0roNf1ovaogeOO2ceYZA2S4HTafTPOeM9jXlU/ie9uNZdtNeZAMo7IxIIOOM88V5bk5OyPThGyuztVjPnjyL0wI6qRGZhKU653AjBORjAOKfe397aqZILq0aEEH5x95RnPygZ5PHU1wesQXWkXEUsMF2kk2HJVt+7Pt2PboKpvPrgVEeEoHJx0BA9Pr3qPZOWqZtzRWjO7/AOE0P/PkPyorznzbz+7cflRVeyXkRzLsd+dE1XxDqF1Jram3gtsRoscwMjZx09sVan8K6fo+iyCKV7VEPnt53KtgggGuq1DREnInineCcA4kQA8dwc9RXA6vZ3jTyQTXqyjksWiPzfUbqc6ck7LYiFVNXluVdT16zvCLqScS3EnEZXI8pR29MBgT9TWNqHiWMokVsjSSbeZEc9TWlb+GxfmITXjbV+VFCDCgenNdbpPhTTbNVcxmU8fe9zWkaMepM67+yeS/bNY/54/+QzRXv/8AZFh/zw/WituWPYw9rPuf/9k=",
      "qte": 1,
      "isCombo": false
    },
    {
      "code": "R2ABOTYW",
      "label": "Grilled Chicken + Mango Juice",
      "shortLabel": "Lunch 1",
      "priceList": [
        {
          "price": 6.59,
          "currency": "DH"
        },
        {
          "price": 5.19,
          "currency": "YN"
        }
      ],
      "productList": [
        {
          "productCode": "bKSZqaYa"
        },
        {
          "productCode": "MM3FbWRu"
        }
      ],
      "merchantCode": "jjijuhikl",
      "qte": 2,
      "isCombo": true
    }
  ];

var productList = currentSale
    .filter(i => i.isCombo === false)
    .map(x => {
        return {
            code: x.code,
            quantity: x.qte,
            unitPrice: x.unitPrice  // which price do you want?
        }
    });

var comboList = currentSale
    .filter(i => i.isCombo === true)
    .map(x => {
        return {
            code: x.code,
            quantity: x.qte,
            unitPrice: x.unitPrice  // which price do you want?
        }
    });

console.log('productList', productList);
console.log('comboList', comboList);

A: you can use map function and do something like that:
comboList = comboList.map(({ code, unitPrice, qte }) => {
  return {
    code,
    unitPrice,
    quantity: qte
  };
});


text:
Q: SetInterval keeps setting when changing pages So, I have a JavaScript issue that is probably as old as time, but I can't seem to figure it out. I have a form that takes up the whole page and has next and back buttons so the user can travel back and forth through the questions. (Single page app, no full refresh. If there was this would be easy!)
One of the requirements is to have a timeout function. So after they are idle after a cretin amount of time it logs them out to protect their information. The issue is that my interval keeps adding a new one every time I flip back and forth new pages. Thus creating multiple timers and insanity.
My code kind of looks like this.
 var idle = 0;
 var idleIntervalTimer = setInterval(timerIncrement, 1000); //This is what keeps being called
 var counter = 0;
 var timeout = 30;
 var count = 20;
 var resetCount = 20;

document.onmousemove = function() {
  if(app.timer.get('available') === 'Yes'){ //I'm just using this to make sure that they have not already been logged out
       count = resetCount;
       idle = 0;
       app.warning.close();
    }
};

function timerIncrement() {
  if(app.timer.get('available') === 'Yes'){
     console.log(idle);
     idle = idle + 1;

     if (idle > 19 && count >= 0) {
        count = count;
        app.warning.show({ //This is just a warning message that shows up at the top of the page counting down before the app closes.
           message: 'Logging out in ' + count + ' seconds.'
        });

      if(count != null || count >= 0){
          count=count-1;

         if (count === 0 && count != 'null'){
             resetTimer();
             app.workflow.resetWorkflow();
         }
       }
     }
   }
 }

function resetTimer(){
   count = resetCount;
   idle = 0;
   clearInterval(counter);
   clearInterval(idleIntervalTimer);
    app.warning.close();
}

I have tried a few different things. One being that I would set a blank variable at the top and use that blank variable to set the interval, but that didn't seem to work. I have also tried to detect if the interval was still active, but I don't really want to clear the interval, just not create another. Some help would be apprenticed very much!

A: I'm assuming that code gets called on every page flip. Don't set the interval timer immediately. You should create a function that will first clear it and then set.
For example do this instead:
var idleIntervalTimer;

function initIdleIntervalTimer(){
 clearInterval(idleIntervalTimer);
 idleIntervalTimer = setInterval(timerIncrement, 1000);
}

initIdleIntervalTimer();

Or try switching it the timer to the global scope, get rid of var idleIntervalTimer and do this:
clearInterval(window.idleIntervalTimer);
window.idleIntervalTimer = setInterval(timerIncrement, 1000);

A: It's a little ugly, but
 window.clearInterval(localStorage['idleInterval'])
 var idleIntervalTimer = setInterval(timerIncrement, 1000); //This is what keeps being called
 window.localStorage['idleInterval'] = idleIntervalTimer;

EDIT: If you dont want to clear, wrap the entire init in a flag, eg
if (!window._intervalInitOccured){
    window._intervalInitOccured = true;
    //continue init


text:
Q: HBase - How to query based on key-timestamp-id? All-
New to HBase and I've finally been able to actually take data I was once storing in MySQL (about 50 million rows) and insert it into my HBase table.
I'm now trying to query this data based on the keys and am running into some problems.
Basically I have a key that is constructed like:

objectname-createdtime-customerid

Now I need to query based on the objectname and a range for the createdtime, does anyone know how I can do this? (I'm using PHP/Thrift, but I don't need it to be a specific answer to this)
I can query if I know the exact row/key, I just need to know how to specify a range now for the middle property.
Thanks in advance!

A: Use a scan where the start row is the one with key objectname-<min created time>-customerid and the stop row has key objectname-<max created time>-customerid.
http://wiki.apache.org/hadoop/Hbase/ThriftApi#Scanner_methods


text:
Q: How to mix different types of views in spring configuration? greetings all
i am using jsp as a view technology in my web app
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
</bean>

and i want to use velocity too as a view technology in sending emails
and i want to configure this in the xml file, but i don't know how ?
any ideas how to do this ?

A: If you want to use Velocity to construct emails, then this is not a "view", as far as Spring MVC is concerned. Views and ViewResolvers are used to render output to the browser.
Spring MVC does provide support for using Velocity as a view layer, but this isn't relevant to what you're trying to do.
However, Spring also provides some support classes to make the clunky Velocity API a bit less awkward to use (see javadocs). These have no relation to the Spring MVC view layer, though.  Just use them directly from your code, building the emails and sending them.


text:
Q: gcc assembly. Discussion about the value in cfa, %ebp, %esp and the number in directive, like 4 in .cfi_def_register 4, 4 Question 1: when the line 8 is going to be performed, I infer both %esp and %ebp are equal to CFA - 4, and they point to the return address stored in stack. Is it right?
    :                 :
    |    whatever     | <--- CFA: the value of the stack pointer at the
    :                 :      call site in the previous frame
    +-----------------+
    | line 43 address | <--- %ebp == CFA - 4?
    +-----------------+

The assembly:
  1         .file   "test_.c"
  2         .text
  3         .globl  fn1
  4         .type   fn1, @function
  5 fn1:
  6 .LFB0:
  7         .cfi_startproc
  8         pushl   %ebp
  9         .cfi_def_cfa_offset 8
 10         .cfi_offset 5, -8
 11         movl    %esp, %ebp
 12         .cfi_def_cfa_register 5
 13         subl    $16, %esp
 14         movl    $1, -8(%ebp)
 15         movl    $2, -4(%ebp)
 16         movl    -4(%ebp), %eax
 17         movl    -8(%ebp), %edx
 18         addl    %edx, %eax
 19         leave
 20         .cfi_restore 5
 21         .cfi_def_cfa 4, 4
 22         ret
 23         .cfi_endproc
 24 .LFE0:
 25         .size   fn1, .-fn1
 26         .section        .rodata
 27 .LC0:
 28         .string "count1 = %d\n"
 29         .text
 30         .globl  main
 31         .type   main, @function
 32 main:
 33 .LFB1:
 34         .cfi_startproc
 35         pushl   %ebp
 36         .cfi_def_cfa_offset 8
 37         .cfi_offset 5, -8
 38         movl    %esp, %ebp
 39         .cfi_def_cfa_register 5
 40         andl    $-16, %esp
 41         subl    $32, %esp
 42         call    fn1
 43         movl    %eax, 28(%esp)
 44         movl    $.LC0, %eax
 45         movl    28(%esp), %edx
 46         movl    %edx, 4(%esp)
 47         movl    %eax, (%esp)
 48         call    printf
 49         movl    $0, (%esp)
 50         call    exit
 51         .cfi_endproc
 52 .LFE1:
 53         .size   main, .-main
 54         .ident  "GCC: (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3"
 55         .section        .note.GNU-stack,"",@progbits

C codes:
#include <stdio.h>
#include <stdlib.h>
int fn1()
{
    int a, b;

   a = 1;
   b = 2;

   return a + b;
}

int main()
{
    int count;

    count = fn1();
    printf("count1 = %d\n", count);

    exit(0);
}

Question 2: I don't know why .cfi_offset 5, -8 should be inserted in the codes, and so do .cfi_def_cfa_register 5, .cfi_restore 5 and .cfi_def_cfa 4, 4. I found how to use these directives:

*

*.cfi_offset register,offset

*Previous value of register is saved at offset, offset from CFA.

*.cfi_def_cfa_register register

*.cfi_def_cfa_register modifes a rule for computing CFA. From now on register will be used instead of the old one. Offset remains the same.

*.cfi_restore register

*.cfi_restore says that the rule for register is now the same as it was at the beginning of the function, after all initial instruction added by .cfi_startprocwere executed.

*.cfi_def_cfa register,offset

*.cfi_def_cfa defines a rule for computing CFA as: take address from register and add offset to it.
So I'd like to know 1#, 2#, 3#... those number represent which register respectively.


text:
Q: Can I share weights between keras layers but have other parameters differ? In keras, is it possible to share weights between two layers, but to have other parameters differ? Consider the following (admittedly a bit contrived) example:
conv1 = Conv2D(64, 3, input_shape=input_shape, padding='same')
conv2 = Conv2D(64, 3, input_shape=input_shape, padding='valid')

Notice that the layers are identical except for the padding. Can I get keras to use the same weights for both? (i.e. also train the network accordingly?)
I've looked at the keras doc, and the section on shared layers seems to imply that sharing works only if the layers are completely identical.

A: To my knowledge, this cannot be done by the common "API level" of Keras usage.
However, if you dig a bit deeper, there are some (ugly) ways to share the weights.
First of all, the weights of the Conv2D layers are created inside the build() function, by calling add_weight():
    self.kernel = self.add_weight(shape=kernel_shape,
                                  initializer=self.kernel_initializer,
                                  name='kernel',
                                  regularizer=self.kernel_regularizer,
                                  constraint=self.kernel_constraint)

For your provided usage (i.e., default trainable/constraint/regularizer/initializer), add_weight() does nothing special but appending the weight variables to _trainable_weights:
    weight = K.variable(initializer(shape), dtype=dtype, name=name)
    ...
        self._trainable_weights.append(weight)

Finally, since build() is only called inside __call__() if the layer hasn't been built, shared weights between layers can be created by:

*

*Call conv1.build() to initialize the conv1.kernel and conv1.bias variables to be shared.

*Call conv2.build() to initialize the layer.

*Replace conv2.kernel and conv2.bias by conv1.kernel and conv1.bias.

*Remove conv2.kernel and conv2.bias from conv2._trainable_weights.

*Append conv1.kernel and conv1.bias to conv2._trainable_weights.

*Finish model definition. Here conv2.__call__() will be called; however, since conv2 has already been built, the weights are not going to be re-initialized.

The following code snippet may be helpful:
def create_shared_weights(conv1, conv2, input_shape):
    with K.name_scope(conv1.name):
        conv1.build(input_shape)
    with K.name_scope(conv2.name):
        conv2.build(input_shape)
    conv2.kernel = conv1.kernel
    conv2.bias = conv1.bias
    conv2._trainable_weights = []
    conv2._trainable_weights.append(conv2.kernel)
    conv2._trainable_weights.append(conv2.bias)

# check if weights are successfully shared
input_img = Input(shape=(299, 299, 3))
conv1 = Conv2D(64, 3, padding='same')
conv2 = Conv2D(64, 3, padding='valid')
create_shared_weights(conv1, conv2, input_img._keras_shape)
print(conv2.weights == conv1.weights)  # True

# check if weights are equal after model fitting
left = conv1(input_img)
right = conv2(input_img)
left = GlobalAveragePooling2D()(left)
right = GlobalAveragePooling2D()(right)
merged = concatenate([left, right])
output = Dense(1)(merged)
model = Model(input_img, output)
model.compile(loss='binary_crossentropy', optimizer='adam')

X = np.random.rand(5, 299, 299, 3)
Y = np.random.randint(2, size=5)
model.fit(X, Y)
print([np.all(w1 == w2) for w1, w2 in zip(conv1.get_weights(), conv2.get_weights())])  # [True, True]

One drawback of this hacky weight-sharing is that the weights will not remain shared after model saving/loading. This will not affect prediction, but it may be problematic if you want to load the trained model for further fine-tuning.


text:
Q: C dealing with variable length string I'm new to C, taking a university course.
In one of the tasks I'm given, I deal with strings. I take strings either entered by user or parsed from a file and then use a function on them to produce an answer (if a specific quality exists).
The string can be of variable length but it is acceptable to assume that their maximum length is 80 characters.
I created the program using a
char s[81];

and then filling up the same array with the different strings each time.
Since the string has to be null-terminated I just added a '\0' at index 80;
s[80] = '\0';

But then I got all kind of weird behaviors - Unrelated characters at the end of the string I entered. I assumed this is because there was space between the end of the 'real' characters and the '\0' character filled with garbage(?).
So what I did is I created a function:
void clean_string(char s[], int string_size) {
    int index = 0;
    while(index < string_size) {
        s[index++] = '\0';
    }
}

What I call clean, is just filling a string up with zero characters. I do this every time I am done dealing with a string and ready to accept a new one. Then I fill up the string again character by character and when ever I'll stop, the following character will be a '\0' for sure.
To not include any magic numbers in code (81 each time I call clean_string) I used the following:
#define STRING_LENGTH 81

That works for me. The strings show no strange behavior. But I wondered if this is considered bad practice. Are there problems with this approach?
Just emphasizing, I'm not asking for help in the assignment itself, but tips on how to approach these kind of situations better.

A: Rather than prefilling the entire array with zeros, it should be simple to just add a single zero after you've read all relevant characters.
For example:
char s[STRING_LENGTH];
int c;
int idx = 0;

while (((c = getchar()) != '\n') && (idx < STRING_LENGTH - 1) && (c != EOF)) {
    s[idx++] = c;
}
s[idx] = 0;


text:
Q: Decrease noise in Disparity map I calculated Disparity map in c# (Emgu). The attached file1 is left and right image, and disparity map. The noise of disparity map is high. How can i decrease noise in disparity map?
Thanks.

A: If you want better result in disparity map you should have good camera calibration. The more accurate camera calibration lead to more accurate disparity map.

A: As tiziran pointed out, good (stereo) calibration is important. Since you usually calibrate each camera retrieving its whole projection matrix, it's difficult to say which of its parameters is the most important.
Stereo calibration involves also the determination of the rotation and traslation of the second camera with respect to the first camera.
In your case, some other things have to be considered:
A) in general noise depends on window correlation size and on the correlation method. Several method exists. The bigger the correlation size, the lower the noise but also the lower the precision.
B) To have disparity, points have to be seen from both your cameras. Half of each image is out the field of view of the other camera, so it would be useless (and tipically noise occurs in areas where disparity couldn't be computated). I think in this case there is too much distance / rotation between the cameras (it does not helps).
C) It is hard to have good disparity where there is no texture at all, or where the texture dimension is too bigger than the correlation window size. In your images there are zones with uniform white color and no texture
D) I think that is hard to have good disparity where the carpet is out of focus. It is my personal consideration but this fact does not help you for sure.


text:
Q: Postfix notation stack C++ I am new to C++ and I want to use a stack to evaluate an expression given as an input (2+3*5+4 for example), containing only numbers, + and *. I wrote this code but it gives me Segmentation fault: 11. Could you please help me solve this or give me a hint about what could be wrong? Thank you! (I noticed there were similar questions on this site, but I couldn't use them to solve my problem)
#include <iostream>
#include <stack>
using namespace std;

bool highPrecedence(char a, char b){
    if((a=='+')&&(b=='*'))
        return true;
    return false;
}

int main()
{
    char c = 'a';
    double x;
    stack<char> stack;
    double v[10];
    int i=0;
    double res;
    while(true)
    {
        c = cin.get();

        if(c=='\n'){
            while(stack.size()!=0){
                if (stack.top()=='*'){
                    double res = v[i]*v[i-1];
                    i--;
                    v[i]=res;
                    stack.pop();
                }
                if (stack.top()=='+'){
                    res = v[i]+v[i-1];
                    i--;
                    v[i]=res;
                    stack.pop();

                }
            }
            break;
        }

        if ( '0'<=c && c<='9' )
        {
            cin.putback(c);
            cin>>x;
            cout<<"Operand "<<x<<endl;
            i=i+1;
            v[i]=x;
        }
        else
        {
            if(c!=' ') cout<< "Operator " <<c<<endl;
            if (stack.size()==0)
                stack.push(c);
            else{
                while((!highPrecedence(stack.top(),c)) && (stack.size()!=0)){
                    if (stack.top()=='*'){
                        double res = v[i]*v[i-1];
                        i--;
                        v[i]=res;
                        stack.pop();
                    }
                    if (stack.top()=='+'){
                        res = v[i]+v[i-1];
                        i--;
                        v[i]=res;
                        stack.pop();

                        }
                    }

                stack.push(c);
                }
            }

        }

    cout<<v[0]<<endl;
}

A: *

*Using stack.top() is illegal if the stack is empty.
Change while((!highPrecedence(stack.top(),c)) && (stack.size()!=0)){
to while((!stack.empty()) && (!highPrecedence(stack.top(),c))){

*The initiali value of i is not good and you are printing uninitialized variable, which has indeterminate value.
Change int i=0; to int i=-1;


text:
Q: Sublime text auto-complete overrides snippet I have a console.log() snippet for Sublime Text that fires when you type 'c' then tab trigger, however if there is code that starts with 'c' somewhere on the page auto-complete overrides the console.log snippet. Is there a way around this or should I just add another modifier for my snippet?
<snippet>
    <content><![CDATA[console.log($1);$0]]></content>
    <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
    <tabTrigger>c</tabTrigger>
    <!-- Optional: Set a scope to limit where the snippet will trigger -->
    <scope>source.js</scope>
    <description>Log</description>
</snippet>

A: On https://sublime-text-unofficial-documentation.readthedocs.org/en/latest/extensibility/completions.html it mentions that snippets always lose against a fuzzy match. Since the buffer contents are included in the auto completion, I'd suggest modifying your snippet to include a few more characters.


text:
Q: Saving serialized ArrayList throws NotSerializableException in Android I want to save ArraList<MyClass> to internal storage. So, I've implemented Serializable to class which has the ArrayList and also to the MyClass. The code looks like this:
public class CustomAdapter extends BaseAdapter implements Serializable {
public ArrayList<TaskItems> taskList = new ArrayList<TaskItems>();
// some fields and variables
// some methods which use below method saveFile()
public void saveFile() {
    try {
      String filename = "daytodaytasks";
        FileOutputStream fileOutputStream = mContext.openFileOutput(filename, Context.MODE_PRIVATE);
//mContext is MainActivity context
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
        objectOutputStream.writeObject(taskList);
        objectOutputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
class TaskItems implements Serializable {
    String smallRectUpText;
    String smallRectDownText;
    String bigRectText;
    }
}

In the class CustomAdapter there are methods which use saveFile() method. All the methods are called from MainActivity onClick() method using class reference. When I run the program and use onClick method by pushing button I get:
java.io.NotSerializableException: com.something.MainActivity

So I tried to implement Serializable to MainActivity, but then I got the same exception from AppCompatAcitvity, which MainActivity extends. Could you help me ?

A: Context objects are not Serializable.
As class TaskItems is not static, it can access CustomAdapter.this i.e. BaseAdapter object, which contains Context Object.
That why when you made BaseAdapter serializable, it started showing
java.io.NotSerializableException: com.something.MainActivity
Java Doc states
When traversing a graph, an object may be encountered that does not support the Serializable interface. In this case the NotSerializableException will be thrown and will identify the class of the non-serializable object.
Make TaskItems a static class, then it will not have access to CustomAdapter.this from its static context.


text:
Q: Perl/bash script to generate a HTML Page I have a text file "font.txt" containing the name of all the fonts in the system (you can use "fc-list" or something to get that list), one font name per line. I want to generate a html page containing a sample world like "Hello World" printed for every font in that list. I know it could be done manually but the list of fonts is over 400 and I'm looking for a bash or perl script for the task. Any help is appreciated.
PS. I haven't attached any code as I'm not sure where I should plug in the html code in a bash script.

A: In the same folder as your font.txt, create the generateHTML.pl script. Run the script in a terminal using "perl generateHTML.pl". It should generate a new file called "output.html" which you can open in a browser.
Example font.txt
verdana
arial
impact

generateHTML.pl
use strict;
use warnings;
open OUTFILE, ">output.html";
open INFILE, "<font.txt";

my @fonts = <INFILE>;

print OUTFILE qq|| . "\n";

foreach (@fonts){
    chomp;
    print OUTFILE qq|
Hello, world
| ."\n";
}

print OUTFILE qq||;

A: I do not think the system fonts from fc-list have anything to do with what will display on a remote system browser.


text:
Q: rewrite a query to have pagination I have a program, where the user provides an sql query that can be executed on a database (the details of the database to run on are also provided by the user). This query is executed on the database and the results processed at a later point.
A new feature requires that the query is executed in a paged fashion i.e. if the user's query would return 20 records normally, and the user had provided a page size of 5, then the query should execute 4 times and retrieve 5 records each time.
I am able to do this for a select query without CTEs, but I am not certain how to handle a general query, which has CTEs in it.
I modify the query for CTEs as shown below:
public static String rewrite(String sql) {
    return "select * from ("
            + "select (row_number() over ()) as generated_row_number, t.* "
            + "from ("
            + sql
            + ") as t"
            + ") "
            + "where generated_row_number < ?"
            + " and generated_row_number >= ?";
}

Where the start index and page size are added later as parameters.
How would I handle similar functionality for a query containing a CTE?
The database can be assumed to be DB2, although a generic solution would be preferred.
The user connecting to the database also does not have privileges to create views.

A: A handy way to query in SQL is by using offset-fetch. I use this often for pagination.
Select StockCode,Description,Quantity from Inventory order by StockCode offset 0 ROWS fetch NEXT 5 ROWS ONLY

So in code it would be something like
public static string(int Page, int PerPage)
{
    return "Select StockCode,Description,Quantity from Inventory order by StockCode offset " + ((Page - 1) * PerPage).ToString() + " ROWS fetch NEXT " + PerPage.ToString() + " ROWS ONLY"
}

If you need a more generic solution you could try a nested select:
public static String rewrite(String sql, int Page, int PerPage)
{
    return "Select * from (" + sql + ") order by 1 offset " + ((Page - 1) * PerPage).ToString() + " ROWS fetch NEXT " + PerPage.ToString() + " ROWS ONLY"
}

A: try this:
public static String rewrite(String sql)
{
    return   "with tmptable as (" + sql + ")"
            + " select * from ("
            + " select row_number() over () as generated_row_number, t.* "
            + " from tmptable t
            + ") tmp"
            + " where tmp.generated_row_number < ?"
            + " and tmp.generated_row_number >= ?";
}


text:
Q: Return HTTP response in Python lambda which performs multiple DynamoDB put items I have a lambda which performs multiple dynamodb puts. This is the handler
def lambda_handler(event, context):
    ddbclient = boto3.client('dynamodb')
    ddbclient.put_item(TableName='Tacticalble', Item={'xxx}})
    ddbclient.put_item(TableName='Tacticalble', Item={'yyy}})
    ddbclient.put_item(TableName='Tacticalble', Item={'zzz}})
    ddbclient.put_item(TableName='Tacticalble', Item={'aaa}})
    ddbclient.put_item(TableName='Tacticalble', Item={'bbb}})

Now I'm looking for the correct way to return an HTTP response.
Do I have to check every reponse like this and check if they are all statuscode 200?:
def lambda_handler(event, context):
    ddbclient = boto3.client('dynamodb')
    resp1 = ddbclient.put_item(TableName='Tacticalble', Item={'xxx}})
    resp2 = ddbclient.put_item(TableName='Tacticalble', Item={'yyy}})
    resp3 = ddbclient.put_item(TableName='Tacticalble', Item={'zzz}})
    resp4 = ddbclient.put_item(TableName='Tacticalble', Item={'aaa}})
    resp5 = ddbclient.put_item(TableName='Tacticalble', Item={'bbb}})

What is the correct way to return a HTTP200 when all put's succeed and return an error code when one of the put fails.
Thanks

A: *

*You can use DynamoDB transactions instead of multiple put requests

*In case of error Exception would be raised. See examples


text:
Q: how to change a dictionary into nested dictionary Hi I'm trying to write a dictionary into a nested form, but after I do some manipulation,  the nested values do not match the form I'm looking for. Can anyone help me figure it out?
The original dictionary is:
mat_dict = {'Sole': 'Thermoplastic rubber 100%',
 'Upper': 'Polyester 100%',
 'Lining and insole': 'Polyester 100%'}

And I want the final form to be:
desired_dict = {'Sole': {'Thermoplastic rubber': 1.0},
 'Upper': {'Polyester':1.0},
 'Lining and insole': {'Polyester':1.0}}

The following is my code. I can make it into be nested dictionary, but python automatically combines the last two Polyester into one, and it repeats the nested zip dic three times. Does anyone know what happens and how to fix it?
for key,val in mat_dict.items():
    print(key)
    split = [i.split(' ') for i in cont_text]
    mat_dict[key] = dict(zip([' '.join(m[:-1]) for m in split],[float(m[-1].strip('%')) / 100.0 for m in split]))

# what I got is the following, which repeat the materials three times, and it didn't map each materials with my original clothing part
{'Sole': {'Thermoplastic rubber': 1.0, 'Polyester': 1.0},
 'Upper': {'Thermoplastic rubber': 1.0, 'Polyester': 1.0},
 'Lining and insole': {'Thermoplastic rubber': 1.0, 'Polyester': 1.0}}

A: You don't need a list comprehension for split. Just split val.
And then you don't need to zip anything when creating the dictionary.
for key, val in mat_dict.items():
    split = val.split()
    mat_dict[key] = {' '.join(split[:-1]): float(split[-1].strip('%'))}

A: If you need a dictionary comprehension solution you can try the follow code:
mat_dict = {'Sole': 'Thermoplastic rubber 100%',
            'Upper': 'Polyester 100%',
            'Lining and insole': 'Polyester 100%'}

mat_dict = {k: {" ".join(v.split()[:len(v.split())-1]): float(v.split()[-1].replace("%", "")) / 100}
            for k, v in mat_dict.items()}

Output:
{'Sole': {'Thermoplastic rubber': 1.0}, 'Upper': {'Polyester': 1.0}, 'Lining and insole': {'Polyester': 1.0}}


text:
Q: How do I host a NodeJS http web server on a raspberry PI/or any linux based PC I've seen people host Apache servers on raspberry PI's and of course on regular computers. I do not wish to or rent a VPS and thought it would be best to set one up on my Raspberry PI 2 B:
(1gb ram/32gb disk/1ghz on overclock)

What is the proper way of setting up a NodeJS http web server on a computer? Can you link me to a tutorial if one exists(Couldn't find any).
I was also wondering if I would be better of renting a VPS with recurring costs and lack of customization/control , or on a working dedicated PC. Keep in mind that I wish to practice some dev ops work over multiple PI's(ex. Chef).
I need this server to be accessible through the internet through an ip or domain. How do I go about setting that up? (I have domains)
Update: I wrote a blog post on this subject.
The tutorial goes through the full installation process. Click the link below

A: Yes, You can use raspberry as your VPS or dedicated server. Just assign static IP address(You need to buy) to your Raspberry and then point your domain name to that static IP address.
Few links below that will be helpful for you,

*

*https://www.modmypi.com/blog/how-to-give-your-raspberry-pi-a-static-ip-address-update

*https://in.godaddy.com/help/point-your-domain-name-to-a-server-19116


text:
Q: How to know what youtube is playing through my android application? I want know what youtube is playing through my application.What should I do??
My app will be just like popup dialog app (floating application) and when I am playing any youtube videos,I want to know its youtube video url.

A: I am not understanding how you are playing YouTube videos in your app. I am assuming you are using a WebView? If so, I recommend using the following code in your app to get the url.
String getUrl = webView.getUrl();
myTextView.setText(getUrl);

or
myTextView.setText(webview.getUrl());


text:
Q: What's the meanning of the options of linux command `uname`? From man uname:
   -a, --all
          print all information [...]
   -m, --machine
          print the machine hardware name
   -p, --processor
          print the processor type or "unknown"
   -i, --hardware-platform
          print the hardware platform or "unknown"

in my computer:
[liwm29@VM-12-11-centos bc_sns]$ uname -p
x86_64
[liwm29@VM-12-11-centos bc_sns]$ uname -m
x86_64
[liwm29@VM-12-11-centos bc_sns]$ uname -i
x86_64

I don't know the difference between them


text:
Q: "Matt was calling while we were having dinner" Is this correct?
*

*Matt ___ while we were having dinner.

A. called  B. was calling  C. has called
I chose B but answer is A.
Could you tell me why answer is A.

A: The best answer is (A).  There is no grammar mistake in (B) but it is unlikely to be used.
The verb "call" has a number of meanings, from "shout" to "guess", but the meaning here is probably "contact by telephone". If you understand this to mean  "Matt made contact with us by telephone..." then this is a single event that occurred at some time while we were eating.  So the simple past tense would be correct.
It you mean "Matt was making repeated attempts to contact someone" or "Matt was making repeated shouts for help" then "was calling" could be correct.  But such a sentence has a very odd meaning, and so is rejected in favour of (A)


text: Q: Rendering interactive PDFs in IOS To render a PDF in Objective C we are calling CGContextDrawPDFPage method. In IOS6, interactive PDFs rendering using this method take large amounts of memory and it leads to memory warning after some time. This is because of the caching mechanism of moved pages inside the application. But the application is crashing due to memory warning. When I profile the application in IOS6 the memory is working perfectly in IOS5 and memory is stable. Anybody know about this issue? Are there any changes in PDF rendering(CoreGraphics & QuartzCore) frameworks in IOS6?


text:
Q: Como evitar que Excel convierta el texto "true" por verdadero No se si esta pregunta puede estar en este foro pero mi problema es que tengo un archivo csv (separado por comas) el cuál modificó desde una macro en otro libro xlsm el archivo contiene varias columnas pero la macro sólo modifica una sola, el problema es que hay columnas que tienen como valor "true" o "false" pero después de ejecutar la macro, mágicamente se convierten a "VERDADERO" Y "FALSO". la macro ni siquiera guarda el csv, solo lo abre y lo modifica, yo lo guardo de manera manual como csv, pero no entiendo porque me modifica todas las columnas booleanas por "verdadero" o "falso", quisiera saber si hay un modo de evitar que Excel haga eso sin tener que indicar manualmente o por código, las columnas que son solo texto, como repito, en la macro solo modifico una columna, todo lo demás quiero que se quede exactamente como está.
Sub actualiza()
Dim wbLista As Workbook
dim wsLista As Excel.Worksheet

Set wbLista = Workbooks.Open(ActiveWorkbook.Path & "\libro.csv")
Application.ScreenUpdating = False
Set wsLista = wbLista.Worksheets("hoja1")
ThisWorkbook.Activate 'la hoja activa es el source
Dim uf As Integer 'ultima fila
Dim fila As Integer 'fila Lista
fila = 2
Dim f As Integer 'fila source
While wsLista.Range("A" & fila).Value <> "" 'recorro lista
    f = 2
    If wsLista.Range("N" & fila).Value <> "" Then 'comprobacion para no leer registros no validos

    While ActiveSheet.Range("A" & f).Value <> "" ' recorro source

        If wsLista.Range("N" & fila).Value = ActiveSheet.Range("A" & f).Value Then ' comparo que los valores coincidan
            wsLista.Range("T" & fila).Value = ActiveSheet.Range("D" & f).Value 'actualizo el valor de la columna "T" en la Lista (solo son valores numericos, ningun valor booleano en la columna "D"
            f = 600 'salgo del bucle
        End If
        f = f + 1
    Wend
End If
fila = fila + 1

Wend
Application.ScreenUpdating = True
End Sub

A: Si lo que deseas es trabajar con archivos CSV desde VBA, prueba esta solución. Con VBA CSV interface puedes:

*

*Importar ficheros CSV filtrando filas y columnas.

*Escribir los datos directamente a una hoja de Excel.

*Cambiar el tipo de datos de cada campo importado.

*Ordenar los datos importados antes de escribirlos en la hoja de Excel.

¡Suerte!


text:
Q: showing divs at random and then moving them down in javascript guys what i want to make is the div appears at random first and then making them falling down ... here is my code

$(document).ready(function(){
$('#test').animate({top: 80 + '%'},900);
});

A: You could use window.settimeout to call a function that creates your div after a random interval, then have the function call call itself again after it is finished.
html:

css
.container{
    width:500px;
    height:500px;
    background-color:lightblue;
}
.droper{
    background:#98bf21;
    height:100px;
    width:100px;
    position:absolute;
}

jquery
var ranInterval = 1000 + Math.floor((Math.random() * 4000) + 1);
window.setTimeout( CreateDiv, ranInterval );

function CreateDiv()
{
    var ranLeft = Math.floor((Math.random() * 400) + 1);
    var ranInterval = 1000 + Math.floor((Math.random() * 4000) + 1);
    jQuery('
').css({top: 0, left: ranLeft }).animate({top: "+=400px"}, 900 ).appendTo('#container' );

    window.setTimeout( CreateDiv, ranInterval );
}

Here is a jsfiddle demonstrating the code.
http://jsfiddle.net/chrustlesstulip/b8qo56j5/


text:
Q: How to avoid replying to a mail when I'm in blind copy I'm working with Microsoft Outlook 2016, and I just received a mail where I've been put in blind copy. This is quite dangerous because the people in the To and CC list should not be able to contact me, and when I reply all to this mail I risk exposing my e-mail address to those people, which I don't want.
In order to avoid this, I'd like some message box to appear whenever I press the Reply all button of an e-mail where I'm in blind copy.
I've just checked the rules and I don't find a way to get this done, and creating a rule for marking such mails in some way also seems not to be possible: here are the relevant conditions for creating rules I've found:
sent only to me
where my name is in the To box
where my name is in the Cc box
where my name is in the To or Cc box
where my name is not in the To box

As you see there is no where my name is in the Bcc box (which would be what I need).
I can invent a workaround, like creating another inbox, using the where my name is in the To or Cc box, redirect all mails to that inbox, so that all messages in blind copy stay in my regular inbox, but I don't like this workaround.
Does somebody have an idea on how to help me?

A: You also have an exception "except if my name is in the To or Cc box", that should work.

The result of such an exception is a rule, which looks as follows:

The message, shown when such a message arrives, looks as follows:

A:
I'd like some message box to appear whenever I press the Reply all button of an e-mail where I'm in blind copy.

I notice this in the last couple of days, I do not know how long it has been deployed.
Currently with Outlooke 2016, if you click reply all to a message you have been blind copied, you get the message.

Your address was hidden when this message was sent.  If you Reply All, everyone will know you received it.


text:
Q: Appending elements to a list based on condition I was trying to append few elements to a list  list_accepted_outsidenestant. When i try to print the list list_accepted_outsidenestant, i get: list_accepted_outsidenestant- [([971, 977, 728, 740], set([728, 977, 971, 740]))]. The list is showing a list and set with same elements. Can anyone pointout the mistake i am doing? Because of this, i am getting an error:
set_accepted_outsidenest_antlist = set(list_accepted_outsidenestant
TypeError: unhashable type: 'list'
I have shown part of code only relevant to the current question.
def leo(tag_data):
    available_ants_outside = []
    ori = []
    for id, (x, y) in tag_data:
        available_ants_outside.append(id)
        if for_coordinates_outside_nest((x, y)) is True:
            ori.append(id)
    return ori

def virgo(tag_data):
    available_ants_inside = []
    list_insidenest_ant_id = []
    set_inside_nest_ant_id = set()
    for id, (x, y) in tag_data:
        available_ants_inside.append(id)
        if for_coordinates_inside_nest((x, y)) is True:
            list_insidenest_ant_id.append(id)
            set_inside_nest_ant_id = set(list_insidenest_ant_id)
            return list_insidenest_ant_id,set_inside_nest_ant_id

 def bambino(ori,list_insidenest_ant_id):
    list_accepted_outsidenestant = []
    set_accepted_outsidenest_antlist = set()
    set_accepted_insidenest_antlist = set()
    if len(list_accepted_outsidenestant) < num_accepted:
        if (len(ori) > 0) or (len(list_insidenest_ant_id) >0):
            list_accepted_outsidenestant.extend(ori[0:min(len(ori),
            num_accepted-len(list_accepted_outsidenestant))])
            set_accepted_outsidenest_antlist = set(list_accepted_outsidenestant)
            print "list_accepted_outsidenestant-" + str(list_accepted_outsidenestant)
            set_accepted_insidenest_antlist  = set(list_insidenest_ant_id)
    return set_accepted_outsidenest_antlist,set_list_outsideant_id,set_accepted_insidenest_antlist

A: The problem is that you're appending a list to a list.
You can either iterate over the list you want to add:
items_to_add = ori[0:min(len(ori),
                   num_accepted-len(list_accepted_outsidenestant))]
for item in items_to_add:
    list_accepted_outsidenestant.append(item)

Or add the lists:
list_accepted_outsidenestant = list_accepted_outsidenestant + ori[0:min(len(ori), num_accepted-len(list_accepted_outsidenestant))]

Or as bruno pointed out (even better), extend the list.
list_accepted_outsidenestant.extend(ori[0:min(len(ori), num_accepted-len(list_accepted_outsidenestant))])

A: append function add whole into other array
extend function extend add array into previous array
In [1]: a = [1,2,3,4]

In [2]: b = [10,9,8,7,6]

In [3]: a.append(b)

In [4]: a
Out[4]: [1, 2, 3, 4, [10, 9, 8, 7, 6]]

In [5]: c = [1,2,3,4]

In [6]: c.extend(b)

In [7]: c
Out[7]: [1, 2, 3, 4, 10, 9, 8, 7, 6]

Hope this code help you


text:
Q: Add Fade-in effect to imageview image [Android] Guys I need help to understand, how to add some animation to static imageview. My project contains this:
layout/drawer_header.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/nav_header_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical" >

    <ImageView
        android:id="@+id/launcher_icon"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_centerInParent="true"
        android:scaleType="fitCenter"
        android:visibility="invisible"

        android:src="@mipmap/ic_launcher" />

    <ImageView
        android:id="@+id/drawer_icon"
        android:flipInterval="3000"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:maxHeight="245dp"
        android:scaleType="centerCrop"
        android:src="@drawable/vert_loading" />

</RelativeLayout>

anim/fadein.xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha android:fromAlpha="0.0" android:toAlpha="1.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:duration="2000"/>

anim/fadeout.xml
<?xml version="1.0" encoding="UTF-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <alpha android:fromAlpha="1.0" android:toAlpha="0.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:duration="2000"/>
</set>

The question is: How to fadein and fadeout image automaticaly:
 android:src="@drawable/vert_loading"

Add something to MainActiviti.java?

A: In you java code you need to startAnimation & to repeat one after another you can listen using setAnimationListener. When onAnimationEnd is called for one you can call another startAnimation.
Following is the example for your use case:
//find imageview
        ImageView image = findViewById(R.id.drawer_icon);

        // get Animation objcets
        Animation fadeIn = AnimationUtils.loadAnimation(this, R.anim.fadein);
        Animation fadeOut = AnimationUtils.loadAnimation(this, R.anim.fadeout);

        //set the initial animation
        image.startAnimation(fadeIn);

        //set fadeIn listener
        fadeIn.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                //when fadeIn ends start the fadeout
                image.startAnimation(fadeOut);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        //set fadeout listener
        fadeOut.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                //when fadeOut ends start the fadeIn
                image.startAnimation(fadeIn);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });


text:
Q: Linq Distinct in one line Im trying to make the following snippet into one line. Im struggling with it but
I always get compiler warning.
Dim puertas As VehiculoType() = From item In ListaVehiculos _
              Select New VehiculoType() With _
              {.Puertas = item.Puertas}

Dim sel As VehiculoType() = (From item In puertas Select item).Distinct

How can I make the linq selection including the distinct in one statement?

A: Just add the Distinct call to the first line:
Dim puertas As VehiculoType() = (From item In ListaVehiculos _
              Select New VehiculoType() With _
              {.Puertas = item.Puertas}).Distinct


text:
Q: Home link or button Is there a way to create a button/link on an html page via html/javascript/... that goes to the url stored as 'homepage'.
  It should do the same as clicking on the home icon in internet explorer.
Regards

A: No, it is not possible.
The users 'homepage' is not accessible due to privacy reasons.


text:
Q: After upgrade to the latest Gatsby, Sass base64 background images are not available in production build I have *.scss file where I have next code
button {
  background-image: url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGcgY2xpcC1wYXRoPSJ1cmwoI2NsaXAwKSI+CjxwYXRoIGQ9Ik04Ljc1IDE3LjYxMjNWMjIuMjUwM0M4Ljc1IDIyLjU3NDMgOC45NTggMjIuODYxMyA5LjI2NiAyMi45NjMzQzkuMzQzIDIyLjk4ODMgOS40MjIgMjMuMDAwMyA5LjUgMjMuMDAwM0M5LjczNCAyMy4wMDAzIDkuOTYgMjIuODkwMyAxMC4xMDQgMjIuNjk0M0wxMi44MTcgMTkuMDAyM0w4Ljc1IDE3LjYxMjNaIiBmaWxsPSIjMzY3MkY4Ii8+CjxwYXRoIGQ9Ik0yMy42ODQ5IDAuMTM5MDg5QzIzLjQ1NDkgLTAuMDIzOTExNCAyMy4xNTI5IC0wLjA0NTkxMTQgMjIuOTAyOSAwLjA4NTA4ODZMMC40MDI5MjIgMTEuODM1MUMwLjEzNjkyMiAxMS45NzQxIC0wLjAyMDA3NzYgMTIuMjU4MSAwLjAwMTkyMjQxIDEyLjU1NzFDMC4wMjQ5MjI0IDEyLjg1NzEgMC4yMjM5MjIgMTMuMTEzMSAwLjUwNjkyMiAxMy4yMTAxTDYuNzYxOTIgMTUuMzQ4MUwyMC4wODI5IDMuOTU4MDlMOS43NzQ5MiAxNi4zNzcxTDIwLjI1NzkgMTkuOTYwMUMyMC4zMzU5IDE5Ljk4NjEgMjAuNDE3OSAyMC4wMDAxIDIwLjQ5OTkgMjAuMDAwMUMyMC42MzU5IDIwLjAwMDEgMjAuNzcwOSAxOS45NjMxIDIwLjg4OTkgMTkuODkxMUMyMS4wNzk5IDE5Ljc3NTEgMjEuMjA4OSAxOS41ODAxIDIxLjI0MTkgMTkuMzYxMUwyMy45OTE5IDAuODYxMDg5QzI0LjAzMjkgMC41ODEwODkgMjMuOTE0OSAwLjMwMzA4OSAyMy42ODQ5IDAuMTM5MDg5WiIgZmlsbD0iIzM2NzJGOCIvPgo8L2c+CjxkZWZzPgo8Y2xpcFBhdGggaWQ9ImNsaXAwIj4KPHJlY3Qgd2lkdGg9IjI0IiBoZWlnaHQ9IjI0IiBmaWxsPSJ3aGl0ZSIvPgo8L2NsaXBQYXRoPgo8L2RlZnM+Cjwvc3ZnPgo=");
}

which is a correct image already in base64 format.
But after I build the project and serve it with gatsby serve the same image is missed (encoded) and in the inspector I see the next code.
button {
  background-image: url("data:image/svg+xml;base64,PHN2ZyBmaWxsPSJub25lIiB2aWV3Qm94PSIwIDAgOCAxNCI+PHBhdGggZmlsbD0iIzIxMkM0RiIgZmlsbC1ydWxlPSJldmVub2RkIiBkPSJNLjI5MyAxLjcwNyA1LjU4NiA3IC4yOTMgMTIuMjkzYTEgMSAwIDEgMCAxLjQxNCAxLjQxNGw2LTZhMSAxIDAgMCAwIDAtMS40MTVsLTYtNkExIDEgMCAwIDAgLjI5MyAxLjcwOHoiIGNsaXAtcnVsZT0iZXZlbm9kZCIvPjwvc3ZnPg==");
}

Should I adjust the plugin somehow, or am I missing something?
UPDATE: Thats because of svgo plugin in gatsby 3.7-3.8. For temporary or permanent fix :) use next code in gatsby-node.js
// TODO: temporary workaround for https://github.com/gatsbyjs/gatsby/issues/31878
exports.onCreateWebpackConfig = ({ actions, plugins, stage, getConfig }) => {
  // override config only during production JS & CSS build
  if (stage === 'build-javascript') {
    // get current webpack config
    const config = getConfig();

    const options = {
      minimizerOptions: {
        preset: [
          `default`,
          {
            svgo: {
              full: true,
              plugins: [
                // potentially destructive plugins removed - see https://github.com/gatsbyjs/gatsby/issues/15629
                // use correct config format and remove plugins requiring specific params - see https://github.com/gatsbyjs/gatsby/issues/31619
                `removeUselessDefs`,
                `cleanupAttrs`,
                `cleanupEnableBackground`,
                `cleanupIDs`,
                `cleanupListOfValues`,
                `cleanupNumericValues`,
                `collapseGroups`,
                `convertColors`,
                `convertPathData`,
                `convertStyleToAttrs`,
                `convertTransform`,
                `inlineStyles`,
                `mergePaths`,
                `minifyStyles`,
                `moveElemsAttrsToGroup`,
                `moveGroupAttrsToElems`,
                `prefixIds`,
                `removeAttrs`,
                `removeComments`,
                `removeDesc`,
                // `removeDimensions`,
                `removeDoctype`,
                `removeEditorsNSData`,
                `removeEmptyAttrs`,
                `removeEmptyContainers`,
                `removeEmptyText`,
                `removeHiddenElems`,
                `removeMetadata`,
                `removeNonInheritableGroupAttrs`,
                `removeOffCanvasPaths`,
                `removeRasterImages`,
                `removeScriptElement`,
                `removeStyleElement`,
                `removeTitle`,
                `removeUnknownsAndDefaults`,
                `removeUnusedNS`,
                `removeUselessStrokeAndFill`,
                // 'removeXMLNS',
                `removeXMLProcInst`,
                `reusePaths`,
                `sortAttrs`,
              ],
            },
          },
        ],
      }
    }
    // find CSS minimizer
    const minifyCssIndex = config.optimization.minimizer.findIndex(
      minimizer => minimizer.constructor.name ===
        'CssMinimizerPlugin'
    );
    // if found, overwrite existing CSS minimizer with the new one
    if (minifyCssIndex > -1) {
      config.optimization.minimizer[minifyCssIndex] =
        plugins.minifyCss(options);
    }
    // replace webpack config with the modified object
    actions.replaceWebpackConfig(config);
  }
};

A: This issue is fixed in gatsby 3.8.1, to fix it you can update to the latest version if gatsby:
npm install gatsby@latest
More information at:
https://github.com/gatsbyjs/gatsby/pull/32123


text:
Q: How to use C10N library to enable a class returning translated Strings I'd like to use the C10N library to manage translations in a Java project, but I don't understand how to use it to enable classes generate translated strings.
Please consider the following single-language example.
public interface Pet {
    public String getBreed();
}

public class Dog implements Pet {

    private String breed;

    public Dog(String breed) {
        this.breed = breed;
    }

    public String getBreed() {
        return this.breed;
    }

}

Then, I'd like to change the previous implementation to support i18n.
So, I could declare some translations using C10N:
public interface DogBreeds{
    @En("dalmatian")
    @It("dalmata")
    String dalmatian();

    @En("poodle")
    @It("barboncino")
    String poodle();
}

Now, I'd like to use one of these methods in a class to return a translated String.
The idea is to pass somehow the method to the class and then call it from a class' method.
In other words, the class should be able to return the correct translation based on the current locale, that may change at runtime.
public class Dog implements Pet {

    public Dog(??) {
        // the class should receive all the translations
        // related to a specific breed
    }

    public String getBreed() {
        // here I want to return the correct breed name translation,
        // based on the current locale
        return ??;
    }

}

The Dog class should not access the DogBreeds interface directly. For example, Dog may be part of a library, whereas DogBreeds may be declared in the main project.
The Dog class shouldn't hold just one translation based on the current locale, but all the available translations, so that it can return the correct one if the locale changes.
Is this feasible is a clean way?
If not, what are the alternatives?

A: I would try:
public class Dog implements Pet {
    private static final DogBreeds BREEDS = C10N.get(DogBreeds.class);

    public Dog() {
        // no need to pass the translations to the constructor
    }

    public String getBreed() {
        // Since you're wanting to specify a message key dynamically,
        // you need to use getString instead of BREEDS.poodle().
        return BREEDS.getString(myBreed);
    }

}

A: If you would like to separate DogBreed(main project) and Dog(library), then considering that your main projects references the library (and not the other way round), you'll need to introduce some other shared interface in the library, let's say, BreedNameProvider.
public interface BreedNameProvider{
  String dalmatian();
  String poodle();
}

Then you can pass that to Dog class constructor:
public class Dog implements Pet {
 private final BreedNameProvider bnp;
 public Dog(BreedNameProvider bnp) {
   this.bnp = bnp;
 }

 public String getBreed() {
   return bnp.poodle();
 }
}

The implementation of BreedNameProvider can be declared in the main project, so can safely access DogBreeds interface.
Edit: You can use a more gerenic BreedNameProvider, to return the translation you need, with working locale switching at runtime:
//Declared in your library
public interface BreedNameProvider{
  String getBreedName();
}

public class Dog implements Pet {
 private final BreedNameProvider bnp;
 public Dog(BreedNameProvider bnp) {
   this.bnp = bnp;
 }

 public String getBreed() {
   return bnp.getBreedName();
 }
}

In your main project, when instantiating different types of Dog you can just pass an implementation of BreedNameProvider that will return the localized string for the breed you want:
public class MainProject{
  private static final DogBreeds breeds = C10N.get(DogBreeds.class);

  public void createDogs(){
    //Create a poodle
    Dog poodle = new Dog(new BreedNameProvider(){
      @Override
      public String getBreedName(){
        return breeds.poodle();
      }
    });

    //Create dalmatian
    Dog dalmatian = new Dog(new BreedNameProvider(){
      @Override
      public String getBreedName(){
        return breeds.dalmatian();
      }
    });
  }
}

In effect, this is equivalent to "passing a method" to Dog constructor, exactly what you asked for in your original post. In java this is pretty much the only way to do it without sacrificing compile-time safety.
One alternative way to implement BreedNameProvider would be like this:
public class MainProject{
  private static final DogBreeds breeds = C10N.get(DogBreeds.class);

  class CodeBreedNameProvider implements BreedNameProvider{
    private final String breedCode;

    CodeBreedNameProvider(String breedCode){
      this.breedCode = breedCode;
    }

    @Override
    public String getBreedName(){
      switch(breedCode){
        case "poodle": return breeds.poodle();
        case "dalmatian": return breeds.dalmatian();
        //... more if needed
      }
      return "unknown breed code " + breedCode;
    }
  }

  public void createDogs(){
    //Create a poodle
    Dog poodle = new Dog(new CodeBreedNameProvider("poodle"));

    //Create dalmatian
    Dog dalmatian = new Dog(new CodeBreedNameProvider("dalmatian"));
  }
}


text:
Q: .htaccess Redirecting All Errors to a PHP file with GET variable I'm trying to figure out how to redirect all errors pages to redirect to/error.php?e={ERROR HERE}.
For example, if the user encountered a 404 error, they will be directed to /error.php?e=404.
Is there a possible way of doing this?

A: You can use apache error document config. Here is the more info
http://httpd.apache.org/docs/2.2/custom-error.html

A: Ideally we would just be able to do:
ErrorDocument 404 /error.php?e=404

However, if the original URL has a query string, it will override any set in the ErrorDocument (I believe).  A solution could be to use a combination of ErrorDocument and a RewriteRule:
ErrorDocument 404 /404
RewriteRule ^([0-9]+)$ /error.php?e=$1 [L]

ErrorDocument sets up the default page that's returned for the various errors.  The RewriteRule sends the request to the actual php file, and passes the number in the query string.

A: A more advanced approach would be to use the custom REDIRECT_ variables Apache creates for you. Refer to this awesome blog post to know more about the environment variable to customize your ErrorDocument
http://www.benhallbenhall.com/2017/01/custom-apache-error-handler-error-url-php/
You might also wanna go over the Apache Documentation on Custom Error Pages at http://httpd.apache.org/docs/2.2/custom-error.html


text:
Q: Why can't we use air pressure to recharge an electric cars battery If we use energy to accelerate a vehicle, a lot of that energy is lost to drag and friction, especially in an electric vehicle. Why can't we harvest some of that energy using an alternator and some sort of fan/turbine, to assist in recharging the batteries?

A: Your suggestion comes close to being a perpetual motion machine, though it's not quite. The idea of using the power of the car's battery to recharge the battery via the slipstream is the sort of stuff perpetual motion machines are made of, and they never work. Putting a fan or windmill in the car's slipstream would reduce the car's aerodynamic efficiency and therefore compel it to use more electricity to achieve the same performance, so there would be no net gain and in fact a very slight loss of energy. The installation of a slipstream windmill would therefore be counterproductive.

A: Electric vehicles already use regenerative braking which is an energy recovery mechanism that slows a vehicle by using the vehicles electric motor as a generator to convert much of the kinetic energy that would otherwise be lost as friction heat in conventional braking systems, into forms that may be used for immediate use or stored for use as needed.
Driving a fan/turbine with the air flow created by motion of the car will increase air drag and ultimately have the car using more energy (electric or fossil fuel) with the fan/turbine than without the fan turbine.
That said, it is possible to use wind to generate and store electrical energy with a turbine on a car when it is stationary, though I doubt it would be practical. That's basically the same thing as land based wind turbines on wind farms.
Hope this helps.

A: Using cold air intakes are used in combustion engines. The same setup can be used for electric cars.  Instead of feeding combustion the air crosses over turbines connected to generator connected to a battery.  No external drag on auto as air is directed to rear of auto.


text:
Q: How to use Spritesheet Animation in qt Creater? I'm new to qt create and I would like to use SpriteSheet Animation
I have used the following code from this article Click Here
and I'm getting the following error Please click here to see the image
    class Sprite
{
public:

    Sprite();

    void draw( QPainter* painter);

    QPoint pos() const;

    void nextFrame();

private:

    QPixmap* mSpriteImage;
    int mCurrentFrame;
    QPoint mPos;
    int mXDir;

};

Sprite::Sprite():mPos(0,0),mCurrentFrame(0)
{
    mSpriteImage = new QPixmap(":dragon.png");
}

void Sprite::draw( QPainter* painter)
{
    painter->drawPixmap ( mPos.x(),mPos.y(), *mSpriteImage,
                                   mCurrentFrame, 0, 100,100 );
}

QPoint Sprite::pos() const
{
    return mPos;
}

void Sprite::nextFrame()
{
    //following variable keeps track which
    //frame to show from sprite sheet
    mCurrentFrame += 100;
    if (mCurrentFrame >= 500 )
        mCurrentFrame = 0;
    mPos.setX( mPos.x() + 10 );
}

A: include QPixmap in your file you should be fine


text:
Q: base64 favicon not working in explorer I have tried to use a base 64 image as a favicon in my site and it works fine in chrome, but not in explorer.
Has anyone made this work in explorer or is it just not possible?
<link href="data:image/x-icon;base64,[encoded data, 20116 characters]" rel="shortcut icon" type="image/x-icon">