text:
Q: Gson throwing JSON Error "java.lang.IllegalStateException" I have this model: Map<MyObjectA, Set<MyObjectB>> where MyObjectA is a complex object but MyObjectB it's not. Both are Parcelable.
Here's an example:
{
    "my.package.models.MyObjectA@5415636": [{
        "member1": "val",
        "member2": "val",
        "member2": "val",
        ...
    }]
}

This operation works:
private boolean putObject(String key, Object object) {
    ...
    return mPreferences.edit().putString(key, mGson.toJson(object)).commit();
}

But this doesn't:
type = new TypeToken<Map<MyObjectA, Set<MyObjectB>>>() {}.getType());
private <T> T getObject(String key, Type t) {
    ...
    return mGson.fromJson(mPreferences.getString(key, null), type);
}

throwing:

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING
  at line 1 column 3 path $.

I've run debug mode and used a break point at line 810 in Gson.java:
...
try {
      reader.peek();
      isEmpty = false;
      TypeToken<T> typeToken = (TypeToken<T>) TypeToken.get(typeOfT);
      TypeAdapter<T> typeAdapter = getAdapter(typeToken);
      T object = typeAdapter.read(reader);
      return object;
    } catch (EOFException e) {...}
}

typeToken and typeAdapter are correct but typeAdapter.read(reader); will fail...
typeToken = java.util.LinkedHashMap<MyObjectA, java.util.HashSet<MyObjectB>>
typeAdapter class com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter
What am I missing?
Thanks.
EDIT:
public class MyObjectA {
    private List<MyObjectB> list;
    private String a;
    private String b;
    private String c;
    private int one;
    private int two;
...
}

public class MyObjectB {
    private String x;
    private String y;
    private String z;
...
}


text:
Q: Tikz plotting 3d I'm trying to make a 3d plot with tikz, but I was not able to do it. I always get a rubbish messy chaos of lines heading into all directions. I wanted to plot f(x,y) = x^3 / y^2. I was able to do it with gnuplot:
            \begin{gnuplot}
                set terminal epslatex color
                set size 1,1
                set isosamples 100
                unset key
                set grid
                set xrange [-5:5]
                set yrange [-5:5]
                set zrange [-5:5]
                set hidden3d
                set view 62, 308, 1, 1
                splot x**3 / y**2 lt rgb "red"
            \end{gnuplot}

The result looks like this:

This solution still has some problems. E.g. for the area around (0,0,0) there are very litte samples, so there is a lot of white space and the edges are spicky. My question: Is it even possibile to make this plot with tikz? Can the plot be smother and better looking for the area around (0,0,0)? If true, can you help me?

A: With R instead of gnuplot:

\documentclass{article}
\begin{document}
<<echo=F,dev="tikz",message=FALSE>>=
s <- function (x, y) {return (x^3/y^2)}
x <- seq(-1, 1, length= 30)
y <- x
z <- outer(x, y, s)
library(lattice)
library(gridExtra)
trellis.par.set("axis.line", list(col=NA,lty=1,lwd=1))
wireframe(z, drape=T, shade=T, xlab="x", ylab="y",
col.regions=rainbow(150), ylim=c(12,18),
scales = list(arrows = FALSE),
colorkey=F)
@
\end{document}

A: Along the lines of my answer Plotting a 3d surface in tikz, with a limit to the infinity, I combine a computer algebra system, SAGE with LaTeX by way of the sagetex package. First, it helps to know what the plot will look like. Go to a Sage Cell Server and typing in the following lines:
var('y')
plot3d(x^3/y^2,(x,-2,2),(y,-2,2))

followed by enter and rotating around you'll see a picture like:

Now that you know how the surface should look we can see the problem is the values of height spike high in the positive and negative direction. Using a modification of the code posted in my answer referenced above we get:
\documentclass[11pt,border={10pt 10pt 10pt 10pt}]{standalone}
\usepackage{pgfplots}
\usepackage{sagetex}
\begin{document}
\begin{sagesilent}
x = var('x')
y = var('y')
step = .25
x1 = -4
x2 = 4
y1 = -4
y2 = 4
output = ""
output += r"\begin{tikzpicture}[scale=1.0]"
output += r"\begin{axis}[view={-35}{45},xmin=%d, xmax=%d, ymin=%d, ymax=%d]"%(x1,x2,y1,y2-step)
output += r"\addplot3[surf,mesh/rows=%d] coordinates {"%((y2-step-y1)/step+1)
# rows is the number of y values
for y in srange(y1,y2,step):
    for x in srange(x1,x2,step):
        if (x^3/y^2)<200 and (x^3/y^2)>-200:
            output += r"(%f, %f, %f) "%(x,y,x^3/y^2)
        elif (x^3/y^2)<=-10:
            output += r"(%f, %f, %f) "%(x,y,-200)
        else:
            output += r"(%f, %f, %f) "%(x,y,200)
output += r"};"
output += r"\end{axis}"
output += r"\end{tikzpicture}"
\end{sagesilent}
\sagestr{output}
\end{document}

The code replaces every height at least 200 by 20 and every height less than -200 with -200. This gives a cap to the plot. Changing the viewing angle view={-35}{45} to something which illustrates the behavior of the plot better gives us this:

Without using Sage, you have more work to do each time to prevent the edges from being jagged. Sometimes that's easier than others; the accepted answer converted to polar. A recent question had another solution. SAGE is not part of LaTeX so you either have to install it on your computer or you access it through a free Cocalc account. If you're plotting surfaces like this, that might be a good tool to work with. The documentation for sagetex is here on CTAN.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Matplotlib simple case memory leak with pandas I have to plot and saveplot in a loop from 1 to 500 with different data but gives a memory leak due to Matplot lib.
Has someone any idea on how to deal with that ?
Simple case here :
import sys
import gc
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pandas as pd

pdindex = pd.date_range(start='01/01/2013', freq='15min', end='01/01/2019')
df = pd.DataFrame({'test':np.random.normal(0,1,len(pdindex))}, index=pdindex)

def memplot_plot(df, i):
    df.test.plot()
    plt.title('graph' + str(i))
    plt.savefig(str(i) + '.png', dpi=144)
    plt.close()

for i in range(1, 100):
    print '*******************************'
    print 'i : ' + str(i)
    print  len( gc.get_objects())
    print sys.getsizeof(gc.get_objects())
    memplot_plot(df, i)
    gc.collect()

And the output is (memory error as of i=6):
*******************************
i : 1
74682
325680
*******************************
i : 2
290627
1190248
*******************************
i : 3
506420
2145012
*******************************
i : 4
721993
3054204
*******************************
i : 5
937566
3865524
*******************************
i : 6
1153139
4892352
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Anaconda\lib\site- packages\spyderlib\widgets\externalshell\sitecustomize.py",    line 580, in runfile
    execfile(filename, namespace)
  File "C:/PERSO/script_backtesting.py", line 124, in <module>
    memplot_plot(df, i)
  File "C:/PERSO/script_backtesting.py", line 107, in memplot_plot
    plt.savefig(str(i) + '.png', dpi=144)
  File "C:\Anaconda\lib\site-packages\matplotlib\pyplot.py", line 576, in savefig
    res = fig.savefig(*args, **kwargs)
  File "C:\Anaconda\lib\site-packages\matplotlib\figure.py", line 1470, in savefig
    self.canvas.print_figure(*args, **kwargs)
  File "C:\Anaconda\lib\site-packages\matplotlib\backend_bases.py", line 2192, in     print_figure
    **kwargs)
  File "C:\Anaconda\lib\site-packages\matplotlib\backends\backend_agg.py", line 513, in  print_png
    FigureCanvasAgg.draw(self)
  File "C:\Anaconda\lib\site-packages\matplotlib\backends\backend_agg.py", line 461, in     draw
    self.figure.draw(self.renderer)
  File "C:\Anaconda\lib\site-packages\matplotlib\artist.py", line 59, in draw_wrapper
    draw(artist, renderer, *args, **kwargs)
  File "C:\Anaconda\lib\site-packages\matplotlib\figure.py", line 1079, in draw
    func(*args)
  File "C:\Anaconda\lib\site-packages\matplotlib\artist.py", line 59, in draw_wrapper
    draw(artist, renderer, *args, **kwargs)
  File "C:\Anaconda\lib\site-packages\matplotlib\axes\_base.py", line 2092, in draw
    a.draw(renderer)
  File "C:\Anaconda\lib\site-packages\matplotlib\artist.py", line 59, in draw_wrapper
    draw(artist, renderer, *args, **kwargs)
  File "C:\Anaconda\lib\site-packages\matplotlib\axis.py", line 1103, in draw
    ticks_to_draw = self._update_ticks(renderer)
  File "C:\Anaconda\lib\site-packages\matplotlib\axis.py", line 957, in _update_ticks
    tick_tups = [t for t in self.iter_ticks()]
  File "C:\Anaconda\lib\site-packages\matplotlib\axis.py", line 903, in iter_ticks
    self.major.formatter.set_locs(majorLocs)
  File "C:\Anaconda\lib\site-packages\pandas\tseries\converter.py", line 982, in  set_locs
    self._set_default_format(vmin, vmax)
  File "C:\Anaconda\lib\site-packages\pandas\tseries\converter.py", line 966, in  _set_default_format
    format = np.compress(info['maj'], info)
  File "C:\Anaconda\lib\site-packages\numpy\core\fromnumeric.py", line 1563, in  compress
   return compress(condition, axis, out)
MemoryError

Graph of the memory for the computer from launch the script to breack and to kill the console.

A: This is apparently a bug.  In case this question sticks around, the following modifications to the code eliminated the memory leak on my machine:
import sys
import gc
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pandas as pd

pdindex = pd.date_range(start='01/01/2013', freq='15min', end='01/01/2019')
df = pd.DataFrame({'test':np.linspace(0,1,len(pdindex))}, index=pdindex)

fig, ax = plt.subplots()

def memplot_plot(df, i, f, a):
    a.plot(df.index, df.test)
    a.set_title('graph' + str(i))
    f.savefig(str(i) + '.png', dpi=144)
    a.cla()

for i in range(1, 100):
    print '*******************************'
    print 'i : ' + str(i)
    print  len( gc.get_objects())
    print sys.getsizeof(gc.get_objects())
    memplot_plot(df, i, fig, ax)
    gc.collect()

The output now looks like this:
...
*******************************
i : 13
83727
732816
*******************************
i : 14
83727
732816
*******************************
i : 15
83727
732816

...etc


text:
Q: Is it strange to let one user refresh the server cache when it affects all users? I'm displaying a lot of data on a website that won't change often.  Because of this, I'm caching the data in HttpRuntime.Cache, which I understand to cache data for all users of the website.
However, I also want to offer the ability to force a refresh in case cache data becomes stale.  Since the data is cached for all users, this means that if a few people are using the site at once, it'll affect everyone.  Is this a common pattern?  It seems like strange behavior for a site to display, especially since one user could slow everyone down by constantly forcing cache refreshes.  It still doesn't make sense to do clientside caching since the data will be the same for all users.

A: I think it would be careless of you to allow a normal user to have the ability to invoke a "clear cache" operation.. your cache-able data should have some sort of dependency defined. See: Cache Expiration Policies

A: Caching data visible to all users is extremely common, and is a good practice.  However giving users the ability to refresh the cache is pretty rare.  The better path would be to expire your cache when data is saved that would change the contents of a cached page.
Smart cache invalidation means that your users always see the freshest data, but they also get the benefits of your caching efforts.  Ideally, you're only expiring the pages affected by a change - not your entire cache.


text:
Q: 2-D barcode detection and image spliting I am working on 2d-barcode reader java ZXing library. Is it possible to identify 2d-barcode from an image which has multiple barcodes? I have to first split the detected 2d-barcodes into matrix form and then decode that. For example we have an image which has 16 different barcodes like 4*4 matrix and the desired output from that image will be:
        ROW      Column       Barcode output

(1,1)    1          1           784AS877
(1,2)    1          2           74AS5774
..
..
..

Thanks in advance

A: Certainly. You can always tell the normal Reader to just look at one region of the image by using the crop parameters in LuminanceSource. If you know where the boxes are, that's the best thing -- loop over the areas to scan and examine them one at a time.
But you will also find support for automatically trying to find several barcode in an image in the com.google.zxing.multi package. Use the specialized Reader wrappers there to try to find them automatically. It makes some assumptions about where the barcodes are that may not let it work in this grid case, but you could try.


text:
Q: Java GUI MasterMind I am going to make a game in Java which is Number Mastermind.
Now the AI generates 4 numbers from 1-6 and then the user has to guess it.
Now I've got 20 mins of GUI interface and I'm struggling on how to best approach this and the use of the layouts.
But my question is this:
If a random number is 1122 how do I compare it to a guess and output values according to the users input.
For example 1122 and the user guesses 1133 how can I output RRWW r means correct number and location and W means wrong?
Not been doing java too long so kinda new to me.

A: You could make the int to a String, then to a char[] and compare each of the values and put them into a boolean[] array which tells whether they got it right or wrong E.g:
boolean[] howManyRight(int number, int guess, int length){
    char[] n = String.valueOf(number).toCharArray();
    char[] g = String.valueOf(guess).toCharArray();
    boolean[] rightAnswers = new boolean[length];

    for(int i = 0; i < length; i++){
        boolean[i] = n[i] == g[i];
    }

    return rightAnswers;
}

A: Not sure how familiar you are with Mastermind, but typically the result for your example would just be RR.  Completely incorrect numbers technically don't need to be discussed. Instead, W could represent numbers that are in the code, but in the wrong place. So if we change your example slightly (Generated code can still be 1122, but guess from user is now 1234), it would generate a result of R W. (1 right, and 1 in the wrong spot) To achieve this looks something like this:
public String compareGuessToCode(String guess,String code) {
    //Variable to store result to show the user
    String result = "";
    //Necessary variables for code comparison
    //These xxxCharCount variables are used to keep track of how many of each possible
    // character are used in the guess and the code.
    int[] guessCharCount = new int[6];
    int[] codeCharCount  = new int[6];
    //These variables are used for bookkeeping during the evaluation process
    int   guessCharVal   = 0;
    int   guessValPos    = 0;
    int   codeCharVal    = 0;
    int   codeValPos     = 0;
    //Variables to keep track of perfectly correct and wrong position characters
    int   r              = 0;
    int   w              = 0;
    //Set all positions in xxxCharCount to 0
    for (int i = 0; i < 6; i++) {
        guessCharCount[i] = 0;
        codeCharCount[i]  = 0;
    }
    //Analyze the code
    for (int i = 0; i < code.length(); i++) {
        codeCharVal = (int) code.charAt(i);
        codeValPos  = codeCharVal - 1;
        codeCharCount[codeValPos] += 1;
    }
    //Analyze the guess
    for (int i = 0; i < guess.length(); i++) {
        guessCharVal = (int) guess.charAt(i);
        guessValPos  = guessCharVal - 1;
        //Compare guess characters to code characters
        if (guess.charAt(i) == code.charAt(i)) {
            //Show the position as correct
            r++;
            //Increment the appropriate slot in the character counter
            guessCharCount[guessValPos]++;
        }
    }
    //We want to check if the any guess characters are in the code, but we also want
    //to ensure that we haven't already accounted for all occurrences of the
    //guessed character in the code.
    for (int i = 0; i < guess.length(); i++) {
        guessCharVal = (int) guess.charAt(i);
        if (code.contains(String.valueOf(guess.charAt(i))) && guessCharCount[guessValPos] < codeCharCount[guessValPos]) {
            //Show the character as present, but in the wrong spot
            w++;
            //Increment the appropriate slot in the character counter
            guessCharCount[guessValPos]++;
        }
    }
    //Build the result string...perfect first...
    for (int i = 1; i <= p; i++) {
        if (result.isEmpty()) {
            result += "P";
        } else {
            result += " P";
        }
    }
    //...wrong spot last
    for (int i = 1; i <= p; i++) {
        if (result.isEmpty()) {
            result += "X";
        } else {
            result += " X";
        }
    }
    return result;
}


text:
Q: how to use AssertString() Addrouter() functions in CLIPS's dll of C++? i have used CLIPSWIN32.DLL in my program,and the functions in the dll is so limited.I even can not find the AssertString() Addrouter() functions in the dll.
the question is :
if there is a dll that contains the factions?
if not,is there a function that can repalce the twos above?

A: If you download clipsnet from the CLIPS SourceForge Files area (http://sourceforge.net/projects/clipsrules/), there are examples included that utilize the AssertString and AddRouter methods. Search the project to find the methods.


text:
Q: How to change the Devexpress TextEdit current text on focus I've a Devexpress TextEdit control that displays a string something like "24 year." I want the text "years" to disappear every time the user clicks inside the text box (for editing purpose). And, I want the text to reappear when the focus is lost. How can i do this?
Thanks in advance

A: I believe you're working with the TextEdit. Thus you can use the following code snippet:
textEdit.Properties.DisplayFormat.FormatString = "{0:d2} Year";
textEdit.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
textEdit.Properties.Mask.EditMask = "\\d{1,2}";
textEdit.Properties.Mask.IgnoreMaskBlank = false;
textEdit.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Regular;
textEdit.Properties.NullText = "Type your age here";

Here are related help topics:

*

*Mask Editors Overview

*Formatting


text:
Q: Why is protected keyword not preserved for abstract properties in typescript I'm not sure if this is a possible bug in TypeScript or if it's working by design.
I have an Angular project in which I have 3 classes. 1 abstract service, 1 service implementing the abstract service and 1 component using the implementing service.
Simplified, my classes look like this:
export abstract class BaseApiService {
  constructor() { }
  protected abstract baseUrl: string;

export class LogApiService extends BaseApiService {
  baseUrl = environment.apiBaseUrl;
  constructor() { }
}

export class LogPageComponent implements OnInit {

  constructor(private logApiService: LogApiService) { }

  ngOnInit(): void {
    this.logApiService.baseUrl = 'why can I change this?';
  }

}

Since i have added the protected keyword to the baseUrl property in BaseApiService, I'd expect the property to be mutable in LogApiService, but immutable in LogPageComponent. This is not the case. The code above in LogPageComponent's ngOnInit function compiles and runs without issue.
I can prevent LogPageComponent from being able to change LogApiService's baseUrl property by adding the protected keyword inside LogApiService like so: protected baseUrl = environment.apiBaseUrl;.
It feels like a bug to me that I have to add the protected keyword in both BaseApiService and LogPageComponent, but might of course be by design. Is there a reason for this behavior, or should I report it as a bug on Github in the TypeScript repo?

A: That's the normal behavior and it occurs  because you are changing the visibility of the inherited and protected member:
// here you are removing the protected keywork and making it public
baseUrl = environment.apiBaseUrl;

You can make a protected field public because protected  allows a derived class to read and write a field. The derived class can choose to use its ability to read and write the field to allow others to read and write the field.
In the same way, You can not make a private field protected or public because you don't have read or write access to that field.
UPDATE:
if you don't want to set the protected keyword  each time then you have to not override the field and manipulate it directly in the constructor like this:
export class LogApiService extends BaseApiService {
   // remove this => baseUrl = environment.apiBaseUrl;
  constructor() {
   super();
   this.baseUrl = environment.apiBaseUrl;
 }
}


text:
Q: Displaying all multindex labels in pandas dataframe as html Whenever multiline index is used, pandas merges same value indexes during export with to_html. I am looking for a solution to unmerge it or disable merging, so even if values are repeated in index, they are not merged
Currently pandas displays data as

Whereas I require it to be as

A: When you export with to_html, use the sparsify=False option:
df.to_html('output.html', sparsify=False)

sparsify: bool, optional, default True
Set to False for a DataFrame with a hierarchical index to print every multiindex key at each row.


text:
Q: java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.search.cfg.Environment I'm getting following error, while deploying my Spring Application
On My local machine It is working fine.
How do I trace my Problem ?
I was using Spring version 4.1 and Hibernate 5.0.
I have tried changing my Spring version from 4.1 to 4.3.7.
root cause

java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.search.cfg.Environment
org.hibernate.search.spi.SearchIntegratorBuilder.createCleanFactoryState(SearchIntegratorBuilder.java:280)
org.hibernate.search.spi.SearchIntegratorBuilder.buildNewSearchFactory(SearchIntegratorBuilder.java:186)
org.hibernate.search.spi.SearchIntegratorBuilder.buildSearchIntegrator(SearchIntegratorBuilder.java:117)
org.hibernate.search.hcore.impl.HibernateSearchSessionFactoryObserver.sessionFactoryCreated(HibernateSearchSessionFactoryObserver.java:73)
org.hibernate.internal.SessionFactoryObserverChain.sessionFactoryCreated(SessionFactoryObserverChain.java:35)
org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:541)
org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:372)
org.springframework.orm.hibernate4.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:454)
org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:439)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1120)
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1044)
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1120)
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1044)
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1120)
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1044)
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:722)

My project-servlet.xml file Code Snippet is
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd">

<context:annotation-config />
<context:component-scan base-package="project" />

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
<mvc:annotation-driven>
    <mvc:path-matching suffix-pattern="false" />
</mvc:annotation-driven>
<mvc:resources mapping="/resources/**" location="/" />
<mvc:resources mapping="/**" location="/" />

<mvc:view-controller path="/" view-name="index"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="jspViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
    <property name="prefix" value="/"></property>
    <property name="suffix" value=".jsp"></property>
</bean>
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    <property name="url" value="jdbc:mysql://localhost:3306/mydb"></property>
    <property name="username" value="root"></property>
    <property name="password" value="root"></property>
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <!-- <property name="configLocation" value="/WEB-INF/classes/hibernate.cfg.xml" /> -->
    <property name="annotatedClasses">
        <list>
               <value>project.model.User</value>
               <value>project.model.Blogs</value>
               <value>project.model.ContactUs</value>
               <value>project.model.Subscriber</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
            <!-- <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> -->
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
            <prop key="connection.pool_size">10</prop>
        </props>
    </property>
</bean>

I have following jars added
Spring Jars
Hibernate Jars


text:
Q: AppCompat - Item not showing in action bar for API levels v8-13 I have one item I want to always display in the action bar using the AppCompat library. It's just a sub menu using the default overflow image.
This is not working for me on API levels v8-13 and I've done everything the developer guide says, including adding my own namespace.
I'm using a custom style which has Theme.AppCompat as its parent (below).
This is my first post so I don't have enough reputation points to post an image of the activity, but the item is missing from the action bar and the menu appears on the bottom when I press the menu button.
Any feedback would be greatly appreciated!!
AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.myproject"
    android:installLocation="auto"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:debuggable="true"
        android:icon="@drawable/my_app_icon"
        android:label="@string/app_name"
        android:theme="@style/CustomActionBarTheme" >
        <uses-library android:name="com.google.android.maps" />

        <activity
            android:name=".ui.MainActivity"
            android:label="@string/app_name"
            android:launchMode="singleTop" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:MyApp="http://schemas.android.com/apk/res-auto" >

    <item
        android:id="@+id/overflow"
        MyApp:icon="@drawable/abc_ic_menu_moreoverflow_normal_holo_dark"
        MyApp:showAsAction="always"
        android:icon="@drawable/abc_ic_menu_moreoverflow_normal_holo_dark"
        android:showAsAction="always">
        <menu>
            <item
                android:id="@+id/action_about"
                android:icon="@drawable/about_icon"
                android:title="About"/>
            <item
                android:id="@+id/action_feedback"
                android:icon="@drawable/feedback_icon"
                android:title="Feedback"/>
            <item
                android:id="@+id/action_settings"
                android:icon="@drawable/settings_icon"
                android:title="@string/action_settings"/>
        </menu>
    </item>

</menu>

styles.xml
<resources>
    <style name="CustomActionBarTheme" parent="@style/Theme.AppCompat">
        <item name="android:actionBarStyle">@style/MyActionBar</item>
        <item name="actionBarStyle">@style/MyActionBar</item>
    </style>

    <style name="MyActionBar" parent="@style/Widget.AppCompat.ActionBar">
        <item name="android:titleTextStyle">@style/TitleTextStyle</item>
        <item name="android:background">@drawable/abc_ab_bottom_solid_dark_holo</item>
        <item name="titleTextStyle">@style/TitleTextStyle</item>
        <item name="background">@drawable/abc_ab_bottom_solid_dark_holo</item>
    </style>

    <style name="TitleTextStyle" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
        <item name="android:textStyle">bold</item>
    </style>
</resources>

MainActivity.java
package com.myproject;
...
public class MainActivity extends BaseActivity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreateEqually(savedInstanceState);
        ActivityHelper.setLayoutTitle(this, R.layout.main, R.string.main, getSupportActionBar());
    }

    ...

}

BaseActivity.java
package com.myproject;

import android.support.v7.app.ActionBarActivity;
...

public class BaseActivity extends ActionBarActivity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }

    public boolean onPrepareOptionsMenu(Menu menu) {
        return MenusHelper.displayMenu(this, menu);
    }

    ...
}

MenusHelper.java
package com.myproject;
...

public final class MenusHelper {

    ...

    public static boolean displayMenu(BaseActivity currentActivity, Menu menu) {
        // clear former menus
        menu.clear();
        MenuInflater inflater = new MenuInflater(currentActivity);
        inflater.inflate(R.menu.menu, menu);

        return true;
    }

    ...
}

ActivityHelper.java
package com.myproject;

import android.support.v7.app.ActionBar;
...

public final class ActivityHelper {
    ...

    public static void setLayoutTitle(Activity activity, int layoutId, String titleStr, ActionBar actionBar) {
        activity.setContentView(layoutId);
        actionBar.setTitle(titleStr);
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

}

A: the problem is this
android:showAsAction="always"

that needs to be
youpackagename:showAsAction="always"

actually looking over it again you declared that twice
android:icon="@drawable/abc_ic_menu_moreoverflow_normal_holo_dark"
android:showAsAction="always"

remove that bit

A: Try to put the code for MenusHelper.displayMenu(this, menu); into the onCreateOptionsMenu() rather than onPrepareOptionsMenu() and also do the necessary modification.
@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.menu, menu);

    // In case you have an item
    MenuItem shareItem = menu.findItem(R.id.menu_share);

    // To retrieve the Action Provider
    mActionProvider = (ShareActionProvider)
    MenuItemCompat.getActionProvider(shareItem);

    return super.onCreateOptionsMenu(menu);
}

Make sure your Menu in your XML looks like this:
<item
    android:id="@+id/share"
    android:title="@string/menu_share"
    yourapp:actionProviderClass="android.support.v7.widget.ShareActionProvider"
    yourapp:showAsAction="ifRoom|withText"/>


text:
Q: Run selenium webdriver over adb I'm just getting started with the Selenium Python bindings and can successfully perform basic functionality using my computer's browser.  I'd now like to use the Chrome browser on an Android phone which I'm connected to via adb.
I've looked online and have seen references to remote web drivers and Selenium grid.  However, I don't know if this is what I need or, if so, what is needed to set this up.
Is there some web driver equivalent of gdb-server?


text:
Q: How to track down the exact php files that contains specific html? I have a wordpress site up and running and I like to play around with firebug or web developer (another firefox extension). Whenever I want to change something I can easily inspect that element and change it live in the browser, but consider that wordpress is a modular platform with hundreds of files. So, lets say I press on a  element on the sidebar and I can see that the styles are from style.css file, but how to find out on what exact .php (or .html) this specific  element is embedded?
Thanks.

A: I think your best bet is to read the WordPress Theme Development Docs and familiarize yourself with how the different theme files work together to create a page.  Once you know the basic mechanics, you'll know pretty much exactly which file to go to.

A: The php files operate on server-side, firebug works on client-side so you won't be able to see ALL the php files in use from firebug.  On the other hand you can see javascript, and css files since they are accessible to the client in Firebug.
You can use your ftp or ssh client to access your server and take a look to the php files, by browsing the directories.

A: "but how to find out on what exact .php (or .html) this specific element is embedded"
After much research I don't believe it can be done in Firebug - directly. What worked for me was to inspect an element, note something unique about it (or nearby), then use FileSeek to search the theme you are using. If you installed the theme direct from the web, just download a copy to your computer and use FileSeek to search it (the program will quickly search for text withing files - and is free).
Hope this helps.


text:
Q: python webscraping results in block I want to webscrape german real estate website immobilienscout24.de. It is not intended for commercial use or publication and I do not intend on spamming the site, it is merely for coding practice. I would like to write a python tool that automatically downloads the HTML of given immobilienscout24.de sites. I have tried to use beautifulsoup for this, however, the parsed HTML doesn't show the content but asks if I am a robot etc., meaning my webscraper got detected and blocked (I can access the site in Firefox just fine). I have set a referer, a delay and a random user agent. What else can I do to avoid being detected (i.e. rotating proxies, random clicks, headless chrome, this script, other webscraping tools that don't get detected...)?
Things I found online that might be the reason for the block:

*

*missing/wrong cookies

*missing javascript support/other javascript issues

*no mouse clicks/movements

*incomplete/unrealistic header

*SSL/TLS fingerprints and other things to exotic for me to understand

If someone has a working solution with which one can scrape the site, say, 10 times without being blocked, I would be very thankful. Here is my code so far:
from bs4 import BeautifulSoup
import numpy
import time
from fake_useragent import UserAgent

def get_html(url, headers): #scrapes and parses the HTML of a given URL while using custom header
    r = requests.get(url, headers=headers)
    soup = BeautifulSoup(r.text, 'html.parser')
    return soup

ua = UserAgent()
headers = {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    "Accept-Encoding": "gzip, deflate",
    "Accept-Language": "de,de-DE;q=0.8,en;q=0.6",
    "Dnt": "1",
    "Host": "https://www.immobilienscout24.de/",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": ua.random,
  }
delays = [3, 5, 7, 4, 4, 11]
time.sleep(numpy.random.choice(delays))
test = get_html("https://www.immobilienscout24.de/Suche/de/baden-wuerttemberg/heidelberg/wohnung-kaufen?enteredFrom=one_step_search", headers)```

A: this code still need more work but my guess for the import requests doesn't work because it need to run js code but if you use something like selenium it should work cause it could run js code .Also request_html has puppeteer is similar to selenium .

from requests_html import HTMLSession
import re
#from fake_useragent import UserAgent
#create the session
#ua = UserAgent()
session = HTMLSession()

#define our URL
url = 'https://www.immobilienscout24.de/Suche/de/baden-wuerttemberg/heidelberg/wohnung-kaufen'

#use the session to get the data
r = session.get(url)

#Render the page, up the number on scrolldown to page down multiple times on a page
r.html.render(sleep=1,timeout = 30, keep_page=True, scrolldown=1)
r.html.page.screenshot({'C:/Users/program/Desktop/help': 'example.png'})

print(r.text)
session.close()


text:
Q: Meteor: how to put client code in cordova block I'm developing a hybrid application which gets an ID from a nfc tag and then show the data (taken from server side) in the app.
How do I actually load a template (defined in client/view/template.html) since the following code is run only on mobile?
if (Meteor.isCordova){
    Meteor.startup(function(){

        var onNfc = function(nfcEvent) {
            var tag = nfcEvent.tag,
                ndefMessage = tag.ndefMessage;

            var strMessage = JSON.stringify(ndefMessage);
            alert(strMessage); // show the gathered data

            messagePayload= JSON.parse(strMessage)[0].payload;
            msgPayloadStr = nfc.bytesToString(messagePayload); // decode payload
            // alert(msgPayloadStr); // show the gathered data

            // show the data on client side
            // TODO
        };

        nfc.addNdefListener(
            onNfc,
            function(){}, // success
            function(){} // failure
        );
    })
}


text:
Q: Unable to map collection in onetomany mapping JPA Model/Entity 1: PriceListItemTest.Java
package com.Pricing.Pricing_App.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonPropertyOrder({"pricingUOMCode","lineTypeCode","primaryPricingUOMFlag","priceListId","itemId","priceListItemId"})

@Entity
@Table(name = "QP_PRICE_LIST_ITEMS")
public class PriceListItemTest implements Serializable{

//  @Id
    @Column(name = "price_list_item_id")
    private String priceListItemId;

    @Column(name = "pricing_uom_code")
    private String pricingUOMCode;

    @Column(name = "line_type_code")
    private String lineTypeCode;

    @Column(name = "primary_pricing_uom_flag")
    private String primaryPricingUOMFlag;

    @Id
    @Column(name = "item_id")
    private String itemId;

    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "item_id", referencedColumnName = "inventory_item_id")
//    @JoinColumn(name = "inventory_item_id", referencedColumnName = "item_id")
    private List<ItemDetailTest> itemDetailsTest;

    public List<ItemDetailTest> getItemDetailsTest() {
        return itemDetailsTest;
    }

    public void setItemDetailsTest(List<ItemDetailTest> itemDetailsTest) {
        this.itemDetailsTest = itemDetailsTest;
    }

    public String getPricingUOMCode() {
        return pricingUOMCode;
    }

    public void setPricingUOMCode(String pricingUOMCode) {
        this.pricingUOMCode = pricingUOMCode;
    }

    public String getLineTypeCode() {
        return lineTypeCode;
    }

    public void setLineTypeCode(String lineTypeCode) {
        this.lineTypeCode = lineTypeCode;
    }

    public String getPrimaryPricingUOMFlag() {
        return primaryPricingUOMFlag;
    }

    public void setPrimaryPricingUOMFlag(String primaryPricingUOMFlag) {
        this.primaryPricingUOMFlag = primaryPricingUOMFlag;
    }

    public String getItemId() {
        return itemId;
    }

    public void setItemId(String itemId) {
        this.itemId = itemId;
    }

    public String getPriceListItemId() {
        return priceListItemId;
    }

    public void setPriceListItemId(String priceListItemId) {
        this.priceListItemId = priceListItemId;
    }
}

Model/Entity 2: ItemDetailTest.java
package com.Pricing.Pricing_App.model;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonPropertyOrder({"itemNumber","inventoryItemId","organizationId"})

@Entity
@Table(name = "egp_system_items_b")
public class ItemDetailTest implements Serializable {
    @Id
    @Column(name = "inventory_item_id")
    private String inventoryItemId;

    @Column(name = "item_number")
    private String itemNumber;

    @Column(name = "organization_id")
    private String organizationId;

    public String getItemNumber() {
        return itemNumber;
    }

    public void setItemNumber(String itemNumber) {
        this.itemNumber = itemNumber;
    }

    public String getInventoryItemId() {
        return inventoryItemId;
    }

    public void setInventoryItemId(String inventoryItemId) {
        this.inventoryItemId = inventoryItemId;
    }

    public String getOrganizationId() {
        return organizationId;
    }

    public void setOrganizationId(String organizationId) {
        this.organizationId = organizationId;
    }
}

I am not able to start the local server and getting below error:
    Exception encountered during context initialization - cancelling refresh
    attempt: org.springframework.beans.factory.BeanCreationException: Error
    creating bean with name 'entityManagerFactory' defined in class path
    resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]
   : Invocation of init method failed; nested exception is
    org.hibernate.AnnotationException: Unable to map collection
    com.Pricing.Pricing_App.model.PriceListItemTest.itemDetailsTest

I think there is some problem in mapping, Can some one help with it ?
If I change the relation to OneToOne it is working fine. But the expectation is to make it onetomany

A: Look at your mapping. You are trying to map a FK in the element table.
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "item_id", referencedColumnName = "inventory_item_id")
//    @JoinColumn(name = "inventory_item_id", referencedColumnName = "item_id")
private List<ItemDetailTest> itemDetailsTest;

You have the "name" and "referencedColumnName" the wrong way around. Remove your current @JoinColumn and uncomment the other one, and also remove the referencedColumnName because you only have 1 PK field in the owner, hence that specification is the default (i.e just specify the "name" ... the name of the FK column in the element table). All of that is found in any decent JPA docs.

A: One to Many side:
@Entity
public class PriceListItem {
    @OneToMany(mappedBy = "listItem", cascade = ALL)
    private List<ItemDetail> itemDetails;
    // getters, setters, other fields
}

Many to One side:
public class ItemDetail {
    @ManyToOne
    private PriceListItem listItem;
    // getters, setters, other fields
}


text:
Q: How to filter objects by objects in Js My First object is:
 {Color: [
         {display: "RED", value: "5433", count: "12"}
         {display: "Black", value: "5446", count: "37"}
        ]
        Brand: [
         {display: "NIKAVI", value: "5458", count: "58", brand: }
         {display: "BOSCH", value: "5570", count: "7",}
         {display: "REPLAY", value: "5497", count: "132",}
        ]
        Category: [
         {display: "Motorbike Horns", value: "1320", count: "8"}
         {display: "LED Lamps", value: "1325", count: "3"}
        ]
    }

My Second object is:
{Brand: "5458", Color: "5446",Category:[1320,75]}

I have to filter the first object value using the second objects values. I have tried a lot but couldn't find great ideas. I'm working in reactJs.

A: You can try this;

firstObj = {Color: [
  {display: "RED", value: "5433", count: "12"},
  {display: "Black", value: "5446", count: "37"}
 ],
 Brand: [
  {display: "NIKAVI", value: "5458", count: "58",},
  {display: "BOSCH", value: "5570", count: "7",},
  {display: "REPLAY", value: "5497", count: "132",}
 ]
};

secondObj={Brand: "5458", Color: "5446"}

// solution:
const result =Object.keys(secondObj).map(sk => firstObj[sk].filter(fo => fo.value === secondObj[sk]))

    console.log(result)

A: You can simply iterate over key-value pairs over the second object and then use Array#find method(or use Array#filter method if you need an array or there is multiple) to get the result.

const obj1 = {Color: [
         {display: "RED", value: "5433", count: "12"},
         {display: "Black", value: "5446", count: "37"}
        ],
        Brand: [
         {display: "NIKAVI", value: "5458", count: "58", brand: ''},
         {display: "BOSCH", value: "5570", count: "7",},
         {display: "REPLAY", value: "5497", count: "132",}
        ],
        Category: [
         {display: "Motorbike Horns", value: "1320", count: "8"},
         {display: "LED Lamps", value: "1325", count: "3"}
        ]
    };

;
const obj2={Brand: "5458", Color: "5446",Category:[1320,75]};

const res = {};

for (let [key, value] of Object.entries(obj2)) {
  res[key] = obj1[key].filter(o => Array.isArray(value) ? value.some(v => v == o.value) : o.value === value)
}

console.log(res);


text:
Q: How do you get the warm doublet? I've just started playing Legend of the Zelda BOTW, but I can't get the paraglider because I need four spirit orbs, which means I need to complete 4 shrines. I've found all 4 but could only get to and complete 2, the other 2 couldn't be reached because they were blocked by dangerously cold lands.The only way to get past the place was the warm doublet. As far as I know, the only way to get the warm doublet is from the old man. However, there seems to be no way to get the warm doublet from the old man. He didn't give me a quest or anything like that. How do you get the warm doublet?

A: There are 3 ways to get it from the Old Man:

*

*Read the diary in his hut on the Great Plateau, then cook a meal using a spicy pepper, meat and a Hyrule bass. Show him the meal, and he will give you the warm doublet.

*Climb to the top of Mount Hylia on the Great Plateau (before you complete the trials on the Great Plateau). He will appear and give you the warm doublet as a reward.

*After completing the Great Plateau, he will leave a warm doublet in his hut.

Once you obtain it from one method, you can't obtain it from the other 2. But you can still buy it from Hateno Village later in the game for 80 rupees.

A: You don't have to have the warm doublet to travel through the cold areas. Hint: try cooking.

 The Spicy Meat and Seafood Fry dish will give you low-level cold resistance.

A number of sites, including shacknews and gamesradar, have guides on this topic. It's also possible to just buy the Warm Doublet, after you leave The Great Plateau.


text:
Q: git add does not stage changes to commit So I'm having this:

Changes not staged for commit:

modified:   submodules/TIMER (modified content)

When I try to do "git add ." nothing happens. How do I set this change to push to my git repository?

A: You don't, because that's not a file.
More specifically, if you see (modified content)—and you do—you have a submodule.  A submodule is a separate Git repository.  We take one of these two Git repositories, which we call a superproject, and place it in control over another otherwise-independent Git repository, which we call a submodule.
When you work in the superproject—which is what you are doing now—the superproject commit says only one thing about the submodule: that the submodule, in this case, submodules/TIMER, should have commit ______ checked out.  This blank gets filled in when you run git add:
git add submodules/TIMER

tells your superproject Git to run:
(cd submodules/TIMER; git rev-parse HEAD)

to get the raw hash ID of the commit that is checked out in the submodule (usually as a "detached HEAD").  That hash ID, whatever it is, fills in the blank.
So what is there to do about this?
What's going on here is that in the other Git repository—the submodule—there are some modified files that have not been put into any commit.  This cannot be handled or fixed in the superproject.  It must be handled in the submodule.
Therefore, you need to:
cd submodules/TIMER

(perhaps in another window so that you don't disturb your work in the superproject; or, if you like, just cd back to the superproject once you're done).  You can now work in the submodule as a normal everyday Git repository—except for one problem, that is: the superproject Git forced your submodule Git to go into "detached HEAD" mode.  This is not a normal mode in which you should do any work.
Unfortunately, someone or something has already done some work, producing this "modified content" as viewed from above (from the superproject).  But at least, if you run git status now, in the submodule Git repository, you can see what is modified and figure out what to do.  I cannot tell you what to do because I do not have this information.
In any case, once you figure out what to do, you can then:

*

*make a new commit, if that's appropriate;

*erase the changes here (e.g., git reset --hard), if that's appropriate; and/or

*do whatever it is that's appropriate.

Let's assume for now that making a new commit is appropriate, and you figured out which branch to use or made a new branch or whatever it was that was appropriate, and did actually make the new commit.  So, having made a new commit, you can now push or pull-request the new commit.  Once the new commit is available to everyone, it's now safe to return to working in the superproject.
You can return to working in the superproject earlier, but note that once you make a new commit in the superproject that refers to your new submodule commit, if no one else can get that submodule commit, no one else can use the new superproject commit either.  So it's often advisable to wait until any new submodule commit is actually available to everyone.
So, now you return to the superproject.  The submodule is on the new correct commit hash, so now you just run:
git add submodules/TIMER

and now you can git commit as usual (see also Alyson Maia's answer).

A: By the name of the folder I'll suppose it's a Git Submodule. So it is a different repository from the source and you need to commit and push the changes inside first, then push the outside project to update the submodule reference.
Changes inside submodule
$ cd submodules/TIMER
$ git add .
$ git commit -m "my submodule changes..."
$ git push

Update submodule on parent repo
$ cd ../..
$ git add submodules/TIMER
$ git commit -m "updating submodule reference..."
$ git push


text:
Q: Android Intent Sharing From Gridview Creating an a app, where I store bunch of photos in the drawable folder, When the user longpress on a photo brings up a menu, one of the options is to share.I can get the contextmenu up, but have no clue how to share from the grid menu.
I also have the expand it is bring up single image in own view and can share from there.
But when the user selects the Image from the gridview I have no Idea how to share that one.
this is the method i call when user selects share option
public Intent intentShare() {
        Intent share = new Intent(Intent.ACTION_SEND);
        share.setType("image/jpeg");
        share.putExtra(Intent.EXTRA_STREAM, Uri.parse("android.resource://your.package.here/drawable/"+share.putExtra("id", lastPosition)));
        startActivity(Intent.createChooser(share, "Share Image"));
        return share;
}

I have seen this possible option/solution on a couple of other questions
Bitmap icon = mBitmap;
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
try {
    f.createNewFile();
    FileOutputStream fo = new FileOutputStream(f);
    fo.write(bytes.toByteArray());
} catch (IOException e) {
        e.printStackTrace();
}
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/temporary_file.jpg"));
startActivity(Intent.createChooser(share, "Share Image"));

But I have no idea how to initialize mBitmap if that works ?
The entire code can be found here:  http://pastie.org/private/gdpyn2t55h0gp1vp1kika

A: You can convert the Bitmap from resource using code like this:
Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), mThumbIds[lastPosition]);

now you can share it as you share in Expanded view.


text:
Q: PHP saves the png file as a 0 byte to disk My intention is save the generated qr code image on my local.
I have already checked out whole stackoverflow question about it. However they didn't help me to solve this bug.
<?php
    header('Content-type: image/png');

    $filename = "./qrs/qr-6234/qr.png";
    $link = "https://stackoverflow.com";
    $size = 250;
    $url = urlencode ( $link );
    $qr_url = "http://chart.googleapis.com/chart?chs=$sizex$size&cht=qr&chld=L|0&chl=$url&choe=UTF-8";
    $qr = file_get_contents($qr_url);
    $imgIn = imagecreatefrompng ($qr);
    $imgOut = imagecreate ( $size, $size );
    imagecopy ( $imgOut, $imgIn, 0, 0, 0, 0, $size, $size );
    imagepng ( $imgOut, $filename, 9);
    imagedestroy ( $imgIn );
    imagedestroy ( $imgOut );
?>

I don't know why but, it gives me zero byte png file.
Edit: Thanks to ishagg, I got my error logs. These are ;
Warning: file_get_contents(): http:// wrapper is disabled in the server configuration by allow_url_fopen=0 in ./qr/qr_txt_test.php on line 10

Warning: file_get_contents(http://chart.googleapis.com/chart?chs=250&cht=qr&chld=L|0&chl=https%3A%2F%2Fstackoverflow.com&choe=UTF-8): failed to open stream: no suitable wrapper could be found in ./qr/qr_txt_test.php on line 10

Warning: imagecreatefromstring(): Empty string or invalid image in ./qr/qr_txt_test.php on line 11

Warning: imagecopy() expects parameter 2 to be resource, boolean given in ./qr/qr_txt_test.php on line 13

Warning: imagepng(): gd-png error: no colors in palette in ./qr/qr_txt_test.php on line 14

Warning: imagedestroy() expects parameter 1 to be resource, boolean given in ./qr/qr_txt_test.php on line 15

A: If you remove the header() call, you'll be able to see the errors in the script.
In yours, there are two:

*

*Variable $sizex, used in $qr_url is undefined.

*To create a new image from an external resource, you need to use imagecreatefromstring().

With these two mistakes fixed, the code works correctly:
<?php
header('Content-type: image/png');
$filename = "qr.png";
$link = "https://stackoverflow.com";
$size = 250;
$url = urlencode ( $link );
$qr_url = "http://chart.googleapis.com/chart?chs=$size&cht=qr&chld=L|0&chl=$url&choe=UTF-8";
$qr = file_get_contents($qr_url);
$imgIn = imagecreatefromstring($qr);
$imgOut = imagecreate ( $size, $size );
imagecopy ( $imgOut, $imgIn, 0, 0, 0, 0, $size, $size );
imagepng ( $imgOut, $filename, 9);
imagedestroy ( $imgIn );
imagedestroy ( $imgOut );

Result:


text: Q: Error while using Google Place Picker in IOS I'm following the google place picker method for getting the place while click on a button. I have added frameworks and follow same pattern as it is described by google using objective-c language. But when I run the app I got an error , its very difficult to find out where the actual location of it is, I'm confused how I can get rid from this. The error is shown in a screen shot down.


text:
Q: ionic capcitor environment.prod doesn't override capacitor config I have this environment.prod.ts file:
export const environment = {
production: true,
appName: 'PROD',
appId: 'com.prod', };

But when I launch: ionic capacitor build android --prod, capacitor.config.ts in android folder is still the same with my environment values:
export const environment = {
production: false,
appName: 'Dev',
appId: 'com.dev',
};

Anyone has a solution ? please
[EDIT] angular.json: There are fileRemplacements but it doesn't work...
{

        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "www",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "assets": [
              {
                "glob": "**/*",
                "input": "src/assets",
                "output": "assets"
              },
              {
                "glob": "**/*.svg",
                "input": "node_modules/ionicons/dist/ionicons/svg",
                "output": "./svg"
              }
            ],
            "styles": [
              "src/theme/variables.scss",
              "src/global.scss"
            ],
            "scripts": [],
            "aot": false,
            "vendorChunk": true,
            "extractLicenses": false,
            "buildOptimizer": false,
            "sourceMap": true,
            "optimization": false,
            "namedChunks": true
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "./src/environments/environment.ts",
                  "with": "./src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                }
              ]
            },
            "ci": {
              "progress": false
            }
          },
          "defaultConfiguration": ""
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "app:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "app:build:production"
            },
            "ci": {
              "progress": false
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "app:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "codeCoverage": true,
            "styles": [],
            "scripts": [],
            "assets": [
              {
                "glob": "favicon.ico",
                "input": "src/",
                "output": "/"
              },
              {
                "glob": "**/*",
                "input": "src/assets",
                "output": "/assets"
              }
            ]
          },
          "configurations": {
            "ci": {
              "progress": false,
              "watch": false
            }
          }
        },
        "lint": {
          "builder": "@angular-eslint/builder:lint",
          "options": {
            "lintFilePatterns": [
              "src/**/*.ts",
              "src/**/*.html"
            ]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "app:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "app:serve:production"
            },
            "ci": {
              "devServerTarget": "app:serve:ci"
            }
          }
        },
        "ionic-cordova-build": {
          "builder": "@ionic/angular-toolkit:cordova-build",
          "options": {
            "browserTarget": "app:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "app:build:production"
            }
          }
        },
        "ionic-cordova-serve": {
          "builder": "@ionic/angular-toolkit:cordova-serve",
          "options": {
            "cordovaBuildTarget": "app:ionic-cordova-build",
            "devServerTarget": "app:serve"
          },
          "configurations": {
            "production": {
              "cordovaBuildTarget": "app:ionic-cordova-build:production",
              "devServerTarget": "app:serve:production"
            }
          }
        }
      }
    }
  },
  "cli": {
    "defaultCollection": "@ionic/angular-toolkit"
  },
  "schematics": {
    "@ionic/angular-toolkit:component": {
      "styleext": "scss"
    },
    "@ionic/angular-toolkit:page": {
      "styleext": "scss"
    }
  }
}

If you need some details, please tell me.


text:
Q: How to create a fully styled Notebook with a Mathematica expression? I want to create a new notebook by evaluating an expression, not from the front-end GUI, and I want to specify all styles for the notebook in the expression, using only stylesheets supplied with the Mathematica installation. The use case is zero-touch installations on fresh machines, no interactions with the style GUI and no installations of user-supplied style sheets in special, magical directories. The new user walks up to the fresh machine, gets a single notebook with a single expression from me, evaluates that expression, and al-a-khazam gets a new notebook with all the styles that I specify.
EDIT:
Here is an example use-case scenario (not my actual one, but very very close):
My scenario is similar to a classroom: IT department installs stock
Mathematica on stock operating systems on stock PCs, and they will not do
user-specific installations. The user accounts are network accounts and the
user folders don't even exist until the users log on the first time.
The stock styles supplied by Mathematica are unacceptable for a variety of
reasons. For example, Arial and Helvetica fonts are banned by our staff
because their spacing on narrow letters is too condensed; but there are lots
of little things like this. I got really tired of setting the styles
manually in the GUI and then propagating the style sheets to the students
and then teaching them about the canonical, magical, user-specific directory
structure and then dealing with their mistakes on installing and using the
style sheets.
I decided to automate the distribution of notebooks with customized notebook
styles. My requirements on the automation scenario are:

*

*Users must be able to create new notebooks in a style supplied by me
on fresh machines that have the stock operating system and the stock
installation of Mathematica, with no user-specific  customizations of any
kind.

*Users must NOT be required to learn and use the style GUI ("Format > Edit
Stylesheet...") and must not be required to install and use a stylesheet.

*Users receive a single file from me (say from a gist or from a Dropbox
folder) with the smallest possible instructions for creating properly
styled notebooks. In particular, they can put this file any place they
want in their folders; they don't have to put it in a special place.
Users complete their assignments by filling out some work in the properly-styled notebooks and returning them to me.

A: Here is a Mathematica expression in a meta-notebook, based on the
Wolfram-supplied "StandardReport" style, as an example that creates another
Notebook with all the styles set up the way I want them. I store this
meta-notebook in the same place I store all my other notebooks instead of in a
magical directory on my path, so it gets backed up and survives machine wipes.
It could be distributed to users in a similar way, say through a gist or a
Dropbox folder.
To adapt this to your own needs, just edit and evaluate the expression! A
good way to figure out how to change the expression is to create and style a notebook
in the usual way, through the GUI, open it up with an ordinary text editor
like vim or emacs, and find the bits that you want to copy over to your meta-notebook.  I've endeavored to include samples of every element that has a style so that the newly created notebooks can be visually checked.
Much
easier (at least for me) than messing around with a GUI and magical directories.
Here is a gist https://gist.github.com/rebcabin/0b9ddf27e1354cbded215594d6f59056
Here is another gist with a functional refactoring (installs MMA symbols and has multiple expressions, but is a little more flexible; the gist above and the code below is just a single expression and installs only the symbol myNotebook in the MMA context):
https://gist.github.com/rebcabin/6ba697716ea2bcbfbe9a3253be4d1a01
Module[{myNotebook, myCells, myStyles, myDemoIntegral, myDemoSolution,
    myMathGroup, myItemGroup, myNumberedGroup, myCode, myProgramText,
   myMeatyContentGroup, mySectionGroup, myDocumentGroup,
   myFontFunction, myDefaultStyles, myNonDefaultStyles},
  myDemoIntegral = RowBox[{
     RowBox[{"\[Integral]",
       RowBox[{"x", RowBox[{"\[DifferentialD]", "x"}]}]}],
     "+", SqrtBox["z"]}];
  myDemoSolution = RowBox[{
     FractionBox[SuperscriptBox["x", "2"], "2"],
     "+", SqrtBox["z"]}];
  myMathGroup = CellGroupData[{
     Cell[BoxData[myDemoIntegral], "Input"],
     Cell[BoxData[myDemoSolution], "Output"]},
    Open];
  myItemGroup = CellGroupData[{
     Cell["Item", "Item"],
     Cell["ItemParagraph", "ItemParagraph"],
     Cell[CellGroupData[{
        Cell["Subitem", "Subitem"],
        Cell["SubitemParagraph", "SubitemParagraph"],
        Cell[CellGroupData[{
           Cell["Subsubitem", "Subsubitem"],
           Cell["SubsubitemParagraph", "SubsubitemParagraph"]},
          Open]]},
       Open]]},
    Open];
  myNumberedGroup = CellGroupData[{
     Cell["ItemNumbered", "ItemNumbered"],
     Cell["ItemParagraph", "ItemParagraph"],
     Cell[CellGroupData[{
        Cell["SubitemNumbered", "SubitemNumbered"],
        Cell["SubitemParagraph", "SubitemParagraph"],
        Cell[CellGroupData[{
           Cell["SubsubitemNumbered", "SubsubitemNumbered"],
           Cell["SubsubitemParagraph", "SubsubitemParagraph"]},
          Open]]},
       Open]]},
    Open];
  myCode = RowBox[{RowBox[{"fun", "[", "x_", "]"}], ":=", "1"}];
  myProgramText =
   "\<DLLEXPORT int fun(WolframLibraryData libData, mreal A1, mreal \
*Res)
   {
    mreal R0_0;
    mreal R0_1;
    R0_0 = A1;
    R0_1 = R0_0 * R0_0;
    *Res = R0_1;
    funStructCompile->WolframLibraryData_cleanUp(libData, 1);
    return 0;
   }\>";
  myMeatyContentGroup = CellGroupData[{
     Cell["Subsubsection", "Subsubsection"],
     Cell["Text", "Text"],
     Cell[myMathGroup],
     Cell[myItemGroup],
     Cell[myNumberedGroup],
     Cell["DisplayFormula", "Text"],
     Cell[BoxData[FormBox[myDemoIntegral, TraditionalForm]],
      "DisplayFormula"],
     Cell[TextData[{
        "InlineFormula: ",
        Cell[BoxData[FormBox[myDemoSolution, TraditionalForm]]],
        "."}],
      "Text"],
     Cell["NumberedDisplay", "Text"],
     Cell[BoxData[FormBox[myDemoIntegral, TraditionalForm]],
      "DisplayFormulaNumbered"],
     Cell["Code", "Text"],
     Cell[BoxData[myCode], "Code"],
     Cell["Program", "Text"],
     Cell[myProgramText, "Program"]},
    Open];
  mySectionGroup = CellGroupData[{
     Cell["Section", "Section"],
     Cell[CellGroupData[{
        Cell["Subsection", "Subsection"],
        Cell[myMeatyContentGroup]},
       Open]]},
    Open];
  myDocumentGroup = CellGroupData[{
     Cell["Title", "Title"],
     Cell["Subtitle", "Subtitle"],
     Cell["Subsubtitle", "Subsubtitle"],
     Cell["Author", "Author"],
     Cell["Department", "Department"],
     Cell["Date", "Date"],
     Cell["Chapter", "Chapter"],
     Cell["Subchapter", "Subchapter"],
     Cell[mySectionGroup]},
    Open];
  myCells = {Cell[myDocumentGroup]};
  myFontFunction[siz_, fam_: "Candara", wgt_: "Plain",
    slt_: "Plain"] := {FontFamily -> fam, FontSize -> siz,
    FontWeight -> wgt, FontSlant -> slt};
  myDefaultStyles = {
    {"Title", 44}, {"Subtitle", 24}, {"Subsubtitle", 16},
    {"Author", 14}, {"Department", 11}, {"Date", 11},
    {"Chapter", 34}, {"Subchapter", 28},
    {"Section", 28}, {"Subsection", 20}, {"Subsubsection", 19},
    {"Text", 14},
    {"Item", 15}, {"ItemParagraph", 14},
    {"Subitem", 13.5}, {"SubitemParagraph", 13.5},
    {"Subsubitem", 13}, {"SubsubitemParagraph", 13},
    {"ItemNumbered", 15}, {"SubitemNumbered",
     13.5}, {"SubsubitemNumbered", 13},
    {"DisplayFormula", 14}, {"DisplayFormulaNumbered", 14}};
  myNonDefaultStyles = {
    {"InlineFormula", 12.6, "Palatino", "Plain"},
    {"Code", 12, "Inconsolata", "Bold"},
    {"Program", 12, "Courier", "Plain"},
    {"Input", 13, "Inconsolata", "Bold"},
    {"Output", 13, "Inconsolata", "Plain"}};
  myStyles = {
    Cell[StyleData[
      StyleDefinitions ->
       FrontEnd`FileName[{"Report"}, "StandardReport.nb",
        CharacterEncoding -> "UTF-8"]]],
    Sequence @@ MapThread[
      Cell[StyleData[#1], myFontFunction[#2]] &,
      Transpose[myDefaultStyles]],
    Sequence @@ MapThread[
      Cell[StyleData[#1], myFontFunction[#2, #3, #4]] &,
      Transpose[myNonDefaultStyles]]};
  CreateDocument[
   myNotebook = Notebook[
     myCells,
     StyleDefinitions -> Notebook[
       myStyles,
       Visible -> False]]]];


text:
Q: use ngIf as dynamically show template and hide template in Angular 5 i am using div tag in html
<div *ngIf="mydummy">hi</div>

and in ts file  and by default  this.mydummy is true(now div tag is visible)
but i do set-timeout function to make value  equal to false
the ngIf not working it acts like one time use. so is  there  any option to achieve this simple task
setTimeout(function(){

      this.mydummy =  false

    }, 10000);

A: You need to use arrow Function inside setTimeout.
ngOnInit(){
    setTimeout(()=>{
      this.mydummy = false;
    }, 4000);
  }

https://stackblitz.com/edit/angular-k3knqs


text:
Q: In .NET, does a parent class' constructor call its child class' constructor first thing? public class Parent
{
    Child child1;

    public Parent()
    {
        child1.Name = "abc";
    }
    ...
}

Gets a NullReferenceException. I thought the Parent() constructor calls the Child() constructor first, so that it is possible to access child1 object later in the Parent() constructor???

A: You need to create an instance of the child; either initialize it as you define it:
Child child1 = new Child();

Or in the Parent constructor:
public Parent(){
    child1 = new Child();
    child1.Name = "Andrew";
}

A: The parent class's constructor doesn't call constructors for its members. When the member is a reference, it's just set to null. You need to explicitly allocate it by calling child1 = new Child

A: Members are not implicitly constructed. They're initialized with their default values (i.e. null for reference type members), which is why your child1 member is null.
You need to create an instance of child1:
public Parent
{
  child1 = new Child();
}

On a sidenote, I think you are being confused by constructor call rules for inherited classes. If your Child class inherited your Parent class, the Parent class' default (i.e. parameterless) constructor would be implicitly called (if it existed):
class Parent
{
  protected string member;
  public Parent()
  {
    member = "foo";
  }
}

class Child : Parent
{
  public Child()
  {
    // member is foo here; Parent() is implicitly called
  }
}


text:
Q: Understanding "select X where Y = ..." in a google sheets QUERY function I'm trying to figure out how to parse this google sheets function:
=IFERROR(QUERY($A$2:$F$1000, "select F where A="&A4&" "),"")

I'm having trouble understanding the "select F where A="&A4&" part. The function is applied to an entire column. For some of the rows, this function returns a number, for others it returns a blank. The A column which it is referencing is entirely composed of 6-digit numbers.
What is going on such that sometimes the function returns a number and sometimes a blank?
Also, why are the ampersands important? If I take away the ampersands, the function returns an error.

A: You should try the following:
=arrayformula(if(eq(F2:F,A2:A),F2:F,))

It is hard to suggest the right formula without seeing what you are working with or what the expected result looks like, so if this doesn't work, please share your sample spreadsheet.

A: You need to fix the quotes around A4.
=IFERROR(QUERY($A$2:$F$1000, "select F where A='"&A4&"'"),"")

A: '"&A4&"'
means what is in cell A4
The & means to concatenate.
In this case the literal contents of A4 into the query formula.
Notice that the query has 4 "s. ie ""
"&""
The single quotes are to make the contents of A4 a string.
where A=
so where contents of A2 to A1000 matches the contents of A4.
It would definitely match on A4, (and any other Col A cell that had the same contents.)
in which case it would return F4 because of the
"select F"
means show/return column F in the results


text:
Q: mounting a truecrypt file across network If I have a truecrypt file on a shared drive, if I mount it by using the shared path does my password data get sent in plain text across the network? Basically my question: is it safe to mount a truecrypt file across a network without copying the file to your local machine first.

A: Your password data is not sent across the network, because the cryptographic operations takes place on your computer, in the TrueCrypt driver. The password is used to derive a key that is used on your computer to decrypt the encrypted sectors sent across the network.
TrueCrypt FAQ has a section on this. I beleive item 2 is what you want to acheive. Their warning is that someone looking at the encrypted trafic could get some side-channel information, like the amount of data read and written, and the offset in the encrypted file.
Unless you want protection from your government or other well funded attacker, I beleive you should be ok, password wise. You might test what happens when a network failur occurs while writing a large file. It might corrupt the file system you mounted.

A: What I did:

*

*mounted the TrueCrypt Drive and a TrueCrypt-Container with VeraCrypt (is newer)

*created a windows (samba) and mac (afp) share of the drive and container with a password in the share settings (whatever software you use)

Mounting the container prevented it from being overwritten from some one else opening the container directly.


text:
Q: Ideal MySQL settings I have an affiliate webshop with a large products database. 3.000.000+ records and it uses 4,3 GiB (InnoDB type).
I want to expand the database but i'm looking for the most optimal MySQL configuration.
Server information:
Operating system    Debian Linux 7.4
Real memory 5.57 GB used, 31.39 GB total
Local disk space    198.34 GB used, 707.74 GB total
Virtual memory  29.35 MB used, 1021.99 MB total
Apache2 webserver
MySQL version 5.5.35

.
This is my MySQLTuner result:
MySQLTuner 1.3.0
[OK] Logged in using credentials from debian maintenance account.
[OK] Currently running supported MySQL version 5.5.35-0+wheezy1
[OK] Operating on 64-bit architecture

-------- Storage Engine Statistics --------
[--] Status: +ARCHIVE +BLACKHOLE +CSV -FEDERATED +InnoDB +MRG_MYISAM
[--] Data in MyISAM tables: 40M (Tables: 288)
[--] Data in InnoDB tables: 2G (Tables: 22)
[--] Data in PERFORMANCE_SCHEMA tables: 0B (Tables: 17)
[!!] Total fragmented tables: 58

-------- Security Recommendations  --------
[OK] All database users have passwords assigned

-------- Performance Metrics --------
[--] Up for: 3d 20h 4m 45s (17M q [52.042 qps], 418K conn, TX: 19B, RX: 3B)
[--] Reads / Writes: 52% / 48%
[--] Total buffers: 3.2G global + 24.4M per thread (151 max threads)
[OK] Maximum possible memory usage: 6.8G (21% of installed RAM)
[OK] Slow queries: 0% (49/17M)
[OK] Highest usage of available connections: 30% (46/151)
[OK] Key buffer size / total MyISAM indexes: 3.0G/20.9M
[OK] Key buffer hit rate: 100.0% (726M cached / 10K reads)
[OK] Query cache efficiency: 72.3% (8M cached / 12M selects)
[!!] Query cache prunes per day: 3831
[OK] Sorts requiring temporary tables: 0% (399 temp sorts / 690K sorts)
[!!] Joins performed without indexes: 4229
[OK] Temporary tables created on disk: 14% (2K on disk / 18K total)
[OK] Thread cache hit rate: 99% (119 created / 418K connections)
[!!] Table cache hit rate: 0% (413 open / 153K opened)
[OK] Open file limit used: 29% (646/2K)
[OK] Table locks acquired immediately: 99% (9M immediate / 9M locks)
[!!] InnoDB  buffer pool / data size: 128.0M/2.9G
[OK] InnoDB log waits: 0

-------- Recommendations --------
General recommendations:
Run OPTIMIZE TABLE to defragment tables for better performance
Enable the slow query log to troubleshoot bad queries
Adjust your join queries to always utilize indexes
Increase table_open_cache gradually to avoid file descriptor limits
Read this before increasing table_open_cache over 64: http://bit.ly/1mi7c4C

Variables to adjust:
query_cache_size (> 64M)
join_buffer_size (> 128.0K, or always use indexes with joins)
table_open_cache (> 1024)
innodb_buffer_pool_size (>= 2G)

I can change most of the variables to adjust, but i don't know what the most optimal setting is. Is here a database expert among us who can advise me?
I already set indexes for queries and joins properly.


text:
Q: jQuery: get each key value pair from a JSON? so I got a JSON like
{key:value, key2:value2, key3:value3...}

I want to loop over each entry and get it's key and value so I can construct something like this
{list:[{key:value}, {key2:value2}, {key3:value3}]}

should I be using underscore instead?

A: Try
var list = $.map(data, function(val, key){
    var o = {};
    o[key] = val;
    return o;
})
var obj = {
    list: list
}

Demo: Fiddle

A: you can use jQuery.each function like below
var data = [
 {"Id": 10004, "PageName": "club"},
 {"Id": 10040, "PageName": "qaz"},
 {"Id": 10059, "PageName": "jjjjjjj"}
];

$.each(data, function(i, item) {
    alert(data[i].PageName);
});

$.each(data, function(i, item) {
    alert(item.PageName);
});

A: There is no need to use a library in this situation.  This can be done with native JS:
var json = {key:"1", key2:"2", key3:"3"};

var result = {list:[]};
for(var field in json){
    if(json.hasOwnProperty(field)){
        var obj = {}
        obj[field] = json[field];
        result.list.push(obj);
    }
}

//result contains the desired array

JS Fiddle: http://jsfiddle.net/ygrG8/


text:
Q: Is there a gem or solution to Inviting users from benelux social network site ""hyves.nl" Are there any GEMS or solutions for inviting users from the dutch/Benelux socialnetwork Hyves?
They supply some PHP code for this wich ofcourse could be converted and after searching for a long time I dont think anything exists yet for ruby but still.
www.hyves.nl is the site for reference
Anyone has a solution to connect to this and invite people with there API?

A: There's hyves_oauth, but I'm not sure about the status of that project (at version 0.0.2 from july 2011).
Instead, try Omniauth with Omniauth-oauth: https://github.com/intridea/omniauth-oauth. Hyves talks OAuth AFAIK.


text:
Q: How does this direct digital synthesis accumulator work? So, I grabbed some code online and morphed it to work with my DE2-115 board, and now I need some help understanding exactly how it works.
DDS_accum <= DDS_accum + 32'h16FC7BBC +
    ((256+((message[15]==0)? message[15:7]+256 : message[15:7]-256))<<15) ; // "audio input"

I need help understand exactly why the above Verilog HDL line exists.
The large block of code shown below is to show you where it's implemented.
This is the main block of my Senior Design Project, but, my major at college teaches me about software and hardware, not so much Frequency Modulation. So, a lot of this is going right over my head.
I've read through this and some wikipedia pages and some youtube videos, but, I just don't understand the point of the constant and playing with the message signal in the line above.
//make a direct digital synthesis accumulator
// and output a 10-bit sine wave to the VGA plug
// set carrier frequency to 1 MHz DDS_incr = 32'h51EB84C = 85,899,340
// 11 MHz 32'h3851DCA8 = 944889000
// 9 MHz 2DF8F778 (771291000) : 4.5 16FC7BBC (385,645,500)
// 7 Mhz 274AF224 (659223076)
// set modulation to 400 Hz 85E7

// This outputs at 146.0 MHz.

always @ (posedge CLOCK_50) begin
    //generate 4.5 Mhz square wave carrier with FM modulation
// 32'h16FC7BBC = 385645500
    DDS_accum <= DDS_accum + 32'h16FC7BBC +
    ((256+((message[15]==0)? message[15:7]+256 : message[15:7]-256))<<15) ; // "audio input"
    end

    //hook up the ROM table for carrier
    sqwave sqTable(CLOCK_50, DDS_accum[31:24], sq_out);

    //use the VGA DAC for an FM modulated RF signal
    assign VGA_R = sq_out;
    assign VGA_SYNC = 1 ;
    assign VGA_BLANK = 1 ;
endmodule

//////////////////////////////////////////////////
// Square wave table for the DDS
module sqwave (clock, address, sq);
    input clock;
    input [7:0] address;
    output [7:0] sq; // changed to 7:0
    reg [7:0] sq;    // changed to 7:0
    always @ (posedge clock)
    begin
        sq <= (address<128)? 8'h7f : 8'h01 ; // changed
    end
endmodule
///////////////////////////////////////////////////

I apologize for the large block of code, but that's the heart of this FM Transmitter. This code modulates a 24-bit input audio signal from the Line In port and out the VGA_R port as an FM signal at around 146.0 MHz.

A: Frequency modulation basically means that the frequency of the carrier is changed depending on the magnitude of the message (the audio signal).  If the magnitude is positive, the frequency is increased.  If the magnitude is negative, the frequency is decreased.  Hence 'frequency modulation' because the frequency is being changed instead of the amplitude (AM) or the phase (PM).
In this case, a DDS is being used to generate the carrier wave.  Direct digital synthesis basically involves outputting samples of a waveform from a lookup table at a specific rate.  The rate is determined by a counter, called the phase accumulator.  At every clock cycle, the counter is incremented by a little bit - the 'phase' accumulated by the carrier wave over the clock period.  Generally DDS counters have a number of fractional bits so that the counter can accumulate a more accurate phase step on each clock period.  It looks like this one does not have any fractional bits, probably because of the modulation and relatively high output frequency.  After that, the output of the counter is fed to the lookup table, selecting a sample.  A constant phase step will produce a constant frequency.  However, adjusting the phase step by adding the message data will vary the frequency in lockstep with the message, forming an FM modulated signal.
This line looks like it is adding the audio message data to the phase step, but with some extra work to rescale it properly and deal with the sign bit.
Edit: Never mind, it does have 24 fractional bits.  The lowest 24 bits of the accumulator are not used in the table lookup.


text:
Q: PHP Notice: Undefined index although using try\catch This is my try/catch block in PHP:
try
{
    $api = new api($_GET["id"]);
    echo $api -> processRequest();
} catch (Exception $e) {
    $error = array("error" => $e->getMessage());
    echo json_encode($error);
}

When there is nothing in the $_GET["id"], I still get the notice error.
How can I avoid getting this error?

A: If you want a fast and "dirty" solution, you can use
$api = new api(@$_GET["id"]);

Edit:
Since PHP 7.0 there is a much better and accepted solution: using the null coalescing operator (??). With it you can shorten your code to
$api = new api($_GET["id"] ?? null);

and you don't get a notice because you defined what should happen in the case the variable is not defined.

A: use isset function to check if the variable is set or not:
if( isset($_GET['id'])){
    $api = new api($_GET["id"]);
    echo $api -> processRequest();
}

A: You have to catch Throwable not Exception:
} catch (Throwable $e) {

A: If the absence of id means nothing should then be processed, then you should be testing for the absence of the id, and managing the failure gracefully.
if(!isset($_GET['id'] || empty($_GET['id']){
// abort early
}

THEN go on and do you try/catch.
Unless of course you were to add some smartness to api() so that is responded with a default id, that you'd declare in the function
function api($id = 1) {}

So, it "all depends", but try and fail early if you can.

A: Try checking if the $_GET was set
try
{
    if(isset($_GET["id"]))
    {
      $api = new api($_GET["id"]);
      echo $api -> processRequest();
    }
} catch (Exception $e) {
    $error = array("error" => $e->getMessage());
    echo json_encode($error);
}

A: As of PHP 7, we now have the Null Coalescing Operator.
try
{
    $api = new \Api($_GET['id'] ?? null);
}
catch (\Exception $e)
{
    $error = ["error" => $e->getMessage()];
    return json_encode($error);
}

A: Structure of try...catch
 <?php

try {
    // perform some task
} catch (Exception $ex) {
    // jump to this part
    // if an exception occurred
}

You Can Use isset
     <?php
    if(isset($_GET['id'])){
         $api = new api($_GET["id"]);
         echo $api -> processRequest();
     }else{
          $error = array("error" => $e->getMessage());
          echo json_encode($error);
     }
    ?>

Bonus
Example:
<?php
if(isset($_GET['name'])){
      $name = $_GET['name'];
 }else{
      $name = "Name not set in GET Method";
 }
if(isset($_GET['age'])){
      $name = $_GET['age'];
 }else{
      $name = "<br>Age not set in GET Method";
 }
echo $name;
echo $age;
?>


text:
Q: A monolithic group (singular agreement) I downloaded the old ielts test and its keys, one of the questions asked you to describe a bar chart, and there were 3 different pieces of data given on the chart:

*

*Cars owners

*Internet users

*Apartment renters

In its key for this question, there was a line which I thought it was weird.

The line stated:

"Internet users was the highest statistic."

Is it supposed to use the word "were" instead?
Or "Internet users" was some kind of singular agreement for this case?

A: One way of describing such language use is to wrap a word or phrase:

*

*{Internet users} is...

*{Internet user}s are...

So while the data is describing the number of individual Internet users etc., the statistics compare three singular groups that happen to be labelled 'car owners', 'Internet users' and 'Apartment renters'.
A classic example of such verb use involves "the family is" and "the family are", depending on whether we consider the family as a single unit or a group of individuals.


text:
Q: When working with socket library in python,why am I getting this error? ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

A: Connection refused occurs due to some issues.
1- Firewall- please make sure that both machines have a disabled firewall.
2- SocketServer- your socket server may be closed or disposed of.
3- Antivirus - make you disabled all antivirus because antivirus always blocks the NAT traffic.


text:
Q: Physics body size not changing with SKSpriteNode size change in Touch moved method I am trying to create a spring launcher where when touch is moved on scene the spring will coil as much the touch is dragged down and thn launch the item above the spring on touch end method. For that i changed the size and position of SKSpriteNode in touch move method as -
launcher.position               =   CGPointMake(frame.size.width*0.97, launcher.position.y-1)
launcher.size                   =   CGSizeMake(frame.size.width*0.05, launcher.frame.size.height-2)

But the Physics body of SKSpriteNode not changing it comes like this -
Please help.. And if a change physics body of SKSpriteNode than it lags on device too much..
let springTexture    =   SKTexture(imageNamed: "spring-wire")
launcher.physicsBody = SKPhysicsBody(texture: springTexture, size: launcher.size)
launcher.physicsBody?.dynamic = false

Is there any way to change size of Physics body after creating it once?

A: I fixed it by changing the yScale of SKSpriteNode insteade of changing its size in touchesMoved method
launcher.yScale =   launcher.yScale-0.008
launcher.position  =   CGPointMake(frame.size.width*0.97, launcher.size.height/2)

I don't know if this is the right approach or not but by this SKSpriteNode's physics body change accordingly.


text:
Q: structuring an api endpoint I have an endpoint like the following to get resource by id:
/api/ticket/{id}

Now I want to list tickets by user id. I thought of the following:
/api/ticket/user/{userId}

But I just feel the above doesn't sound ok. I could use the following, but again it makes userId optional, which is not an intention.
/api/ticket?userId=x

Another option I can think of is,
/api/user/{userId}/ticket

But again, I just feel the above is taking the resources out of my /api/ticket service, and appear disguising in the eyes of consumers and api maintainers.
How do you people go about this?