text:
Q: "Unarm" vs. "disarm" Is there a semantic difference?
I thought unarm was more popular, but Google Ngram shows otherwise.

A: It seems to me the use of unarm as a transitive verb (to deprive someone of weapons, or to lay down one's own weapons) is at the very least archaic usage. Here's an instance from Shakespeare's Troilus and Cressida.
Unarm survives mainly as the past participle unarmed, meaning not carrying any weapons (particularly firearms).
The standard term for taking someone's weapons is to disarm, which carries much the same sense as in disarming a bomb, meaning to disable the detonator mechanism so it won't explode.
There is also the figurative use as in a disarming smile, where the sense is that one's potential hostility melts away in the face of a charming appearance or friendly behaviour.

A: The only dictionary that has "unarm" with the meaning of "To empty or strip of arms" is the OED and it gives it as Obsolete. Another one that has it is the FreeDictionary that defines it as a less common word for disarm and mainly used in the military.
In the OALD and in the NOAD, you can only find the adjective "unarmed" which means "not carrying weapons", used like this:

He was shooting unarmed civilians.

Disarm is the verb that appears in both (see the OALD again) which relatively to this question, means "to take a weapon or weapons away from somebody":

Most of the rebels were captured and disarmed.

A: "Unarm" is when you don't have any weapons on you.

I came to the party unarmed.

"Dismarmed" is when you had weapons, but they made you "unarmed", that is, they took it away.
"Disarmed" has an additional meaning of taking away your defense, as in:

Her smile completely disarmed me...

A: As reported by the NOAD, unarm is a verb meaning "deprive or free (someone) of arms or armour."
One of the meaning of disarm is the following one:

take a weapon or weapons away from (a person, force, or country)
   • (of a country or force) give up or reduce its armed forces or weapons
   • remove the fuse from a bomb, making it safe.


text:
Q: How to serialize a Wagtail Orderable model? I came across a challenge which I also intent to blog about. I found a solution but, since I'm going to write about it, I wonder if there is a better way to serialize an Orderable model.
Context: My LessonPage(Page) model has a LessonPageDocuments(Orderable) model that will allow users to add multiple documents to a particular LessonPage:
class LessonPageDocuments(Orderable):
    page = ParentalKey(LessonPage, on_delete=models.CASCADE,
                       related_name='documents')
    document = models.ForeignKey(
        'wagtaildocs.Document', on_delete=models.CASCADE, related_name='+'
    )
    panels = [
        DocumentChooserPanel('document'),
    ]

Now, due to this projects needs and business requirements, we're creating a custom REST API instead of using Wagtail's API.
And the way I found to serialize the documents field was the following:
class LessonDetailsSerializer(serializers.ModelSerializer):
    content = RichTextSerializer()
    documents = serializers.SerializerMethodField()
    def to_representation(self, instance):
        ret = super().to_representation(instance)
        video_url = ret['video_url']
        ret['video_url'] = get_embed(video_url).html if video_url else ''
        return ret
    def get_documents(self, lesson):
        """Return serialized document fields and file URL"""
        request = self.context.get('request')
        doc_list = []
        for doc_cluster in lesson.documents.all():
            doc_list.append({
                "url": request.build_absolute_uri(doc_cluster.document.file.url),
                "title": doc_cluster.document.title,
                "id": doc_cluster.document.pk,
            })
        return doc_list
    class Meta:
        model = LessonPage
        fields = ['id', 'title', 'slug', 'description',
                  'video_url', 'content', 'documents']

Is there a better approach to serialize this field?
Thank you so much in advance!

A: I think the only way (that I know of) to do it better is to make it reusable:
wagtail_api/serializers.py
from wagtail.documents.api.v2.serializers import DocumentDownloadUrlField
from wagtail.documents.models import Document

class DocumentSerializer(serializers.ModelSerializer):
    _detail_url = serializers.HyperlinkedIdentityField(view_name='api:wagtail:documents:detail')
    download_url = DocumentDownloadUrlField()

    class Meta:
        model = Document
        fields = (
            '_detail_url',
            'id', 'title', 'download_url',
        )

my_app/serializers.py
class SomePageDocumentSerializer(serializers.ModelSerializer):
    description = RichTextAPIField()
    document = DocumentSerializer()

    class Meta:
        model = SomePage
        fields = ('description', 'document')

There is also probably a way to overwrite wagtails DocumentSerializer
from ee_wagtail.apps.wagtail_api.serializers

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to omit columns in react-virtualized MultiGrid? Using react-virtualized MultiGrid with AutoSizer, is there a way to omit a column from the data set dynamically?  I basically copied the example and setup the _cellRenderer to skip over a column on a condition, however it looks as if the column is still in the code:
_cellRenderer({columnIndex, key, rowIndex, style}) {
    let retVal = '';
     if(rowIndex === 1 && columnIndex === 5){
        retVal = null;
    } else {
        retVal = (<div className={styles.Cell} key={key} style={style}>
            {columnIndex}, {rowIndex}
        </div>)
    }

    return (retVal);
}


text:
Q: Fit Amplitude (Frequency response) of a capacitor with lmfit I am trying to fit measured data with lmfit.
My goal is to get the parameters of the capacitor with an equivalent circuit diagram.
So, I want to create a model with parameters (C, R1, L1,...) and fit it to the measured data.
I know that the resonance frequency is at the global minimum and there must also be R1. Also known is C.
So I could fix the parameter C and R1. With the resonance frequency I could calculate L1 too.
I created the model, but the fit doesn't work right.
Maybe someone could help me with this.
Thanks in advance.
from lmfit import minimize, Parameters
from lmfit import report_fit
params = Parameters()

params.add('C', value = 220e-9, vary = False)
params.add('L1', value = 0.00001, min = 0, max = 0.1)
params.add('R1', value = globalmin, vary = False)
params.add('Rp', value = 10000, min = 0, max = 10e20)
params.add('Cp', value = 0.1, min = 0, max = 0.1)

def get_elements(params, freq, data):
    C = params['C'].value
    L1 = params['L1'].value
    R1 = params['R1'].value
    Rp = params['Rp'].value
    Cp = params['Cp'].value

    XC = 1/(1j*2*np.pi*freq*C)
    XL = 1j*2*np.pi*freq*L1
    XP = 1/(1j*2*np.pi*freq*Cp)

    Z1 = R1 + XC*Rp/(XC+Rp) + XL

    real = np.real(Z1*XP/(Z1+XP))
    imag = np.imag(Z1*XP/(Z1+XP))

    model = np.sqrt(real**2 + imag**2)

    #model = np.sqrt(R1**2 + ((2*np.pi*freq*L1 - 1/(2*np.pi*freq*C))**2))
    #model = (np.arctan((2*np.pi*freq*L1 - 1/(2*np.pi*freq*C))/R1)) * 360/((2*np.pi))

    return data - model

out = minimize(get_elements, params , args=(freq, data))

report_fit(out)

#make reconstruction for plotting
C = out.params['C'].value
L1 = out.params['L1'].value
R1 = out.params['R1'].value
Rp = out.params['Rp'].value
Cp = out.params['Cp'].value

XC = 1/(1j*2*np.pi*freq*C)
XL = 1j*2*np.pi*freq*L1
XP = 1/(1j*2*np.pi*freq*Cp)
Z1 = R1 + XC*Rp/(XC+Rp) + XL
real = np.real(Z1*XP/(Z1+XP))
imag = np.imag(Z1*XP/(Z1+XP))

reconst = np.sqrt(real**2 + imag**2)
reconst_phase = np.arctan(imag/real)* 360/(2*np.pi)

'''
PLOTTING
'''

#plot of filtred signal vs measered data (AMPLITUDE)
fig = plt.figure(figsize=(40,15))
file_title = 'Measured Data'
plt.subplot(311)
plt.xscale('log')
plt.yscale('log')
plt.xlim([min(freq), max(freq)])
plt.ylabel('Amplitude')
plt.xlabel('Frequency in Hz')
plt.grid(True, which="both")
plt.plot(freq, z12_fac, 'g', alpha = 0.7, label = 'data')

#Plot Impedance of model in magenta
plt.plot(freq, reconst, 'm', label='Reconstruction (Model)')
plt.legend()

#(PHASE)
plt.subplot(312)
plt.xscale('log')
plt.xlim([min(freq), max(freq)])
plt.ylabel('Phase in °')
plt.xlabel('Frequency in Hz')
plt.grid(True, which="both")
plt.plot(freq, z12_deg, 'g', alpha = 0.7, label = 'data')

#Plot Phase of model in magenta
plt.plot(freq, reconst_phase, 'm', label='Reconstruction (Model)')
plt.legend()

plt.savefig(file_title)
plt.close(fig)

measured data
equivalent circuit diagram (model)
Edit 1:
Fit-Report:
[[Fit Statistics]]
    # fitting method   = leastsq
    # function evals   = 28
    # data points      = 4001
    # variables        = 3
    chi-square         = 1197180.70
    reduced chi-square = 299.444897
    Akaike info crit   = 22816.4225
    Bayesian info crit = 22835.3054
##  Warning: uncertainties could not be estimated:
    L1:  at initial value
    Rp:  at boundary
    Cp:  at initial value
    Cp:  at boundary
[[Variables]]
    C:   2.2e-07 (fixed)
    L1:  1.0000e-05 (init = 1e-05)
    R1:  0.06375191 (fixed)
    Rp:  0.00000000 (init = 10000)
    Cp:  0.10000000 (init = 0.1)

Edit 2:
Data can be found here:
https://1drv.ms/u/s!AsLKp-1R8HlZhcdlJER5T7qjmvfmnw?e=r8G2nN
Edit 3:
I now have simplified my model to a simple RLC-series. With a another set of data this works pretty good. see here the plot with another set of data
def get_elements(params, freq, data):
    C = params['C'].value
    L1 = params['L1'].value
    R1 = params['R1'].value
    #Rp = params['Rp'].value
    #Cp = params['Cp'].value
    #k = params['k'].value

    #freq = np.log10(freq)

    XC = 1/(1j*2*np.pi*freq*C)
    XL = 1j*2*np.pi*freq*L1
    # XP = 1/(1j*2*np.pi*freq*Cp)

    # Z1 = R1*k + XC*Rp/(XC+Rp) + XL

    # real = np.real(Z1*XP/(Z1+XP))
    # imag = np.imag(Z1*XP/(Z1+XP))

    Z1 = R1 + XC + XL
    real = np.real(Z1)
    imag= np.imag(Z1)

    model = np.sqrt(real**2 + imag**2)

    return np.sqrt(np.real(data)**2+np.imag(data)**2) - model

out = minimize(get_elements, params , args=(freq, data))

Report:
Chi-Square is really high...
[[Fit Statistics]]
    # fitting method   = leastsq
    # function evals   = 25
    # data points      = 4001
    # variables        = 2
    chi-square         = 5.0375e+08
    reduced chi-square = 125968.118
    Akaike info crit   = 46988.8798
    Bayesian info crit = 47001.4684
[[Variables]]
    C:   3.3e-09 (fixed)
    L1:  5.2066e-09 +/- 1.3906e-08 (267.09%) (init = 1e-05)
    R1:  0.40753691 +/- 24.5685882 (6028.56%) (init = 0.05)
[[Correlations]] (unreported correlations are < 0.100)
    C(L1, R1) = -0.174

With my originally set of data I get this:
plot original data (complex)
Which is not bad, but also not good. That's why I want to make my model more detailed, so I can fit also in higher frequency regions...
Report of this one:
[[Fit Statistics]]
    # fitting method   = leastsq
    # function evals   = 25
    # data points      = 4001
    # variables        = 2
    chi-square         = 109156.170
    reduced chi-square = 27.2958664
    Akaike info crit   = 13232.2473
    Bayesian info crit = 13244.8359
[[Variables]]
    C:   2.2e-07 (fixed)
    L1:  2.3344e-08 +/- 1.9987e-10 (0.86%) (init = 1e-05)
    R1:  0.17444702 +/- 0.29660571 (170.03%) (init = 0.05)

Please note: I also have changed the input data of the model. Now I give the model complex values and then I calculate the Amplitude. Find this also here: https://1drv.ms/u/s!AsLKp-1R8HlZhcdlJER5T7qjmvfmnw?e=qnrZk1


text:
Q: Action payload undefined when using axios i'm learning react and i'm having issues with the action.payload object because it is not populated after doing a get request with axios.
The method which does the request looks like this:
const searchUsers = async text => {
        setLoading(true);

        const res = await axios.get(`https://api.github.com/search/users?q=${text}&client_id=${process.env.REACT_APP_GITHUB_CLIENT_ID}&client_secret=${process.env.REACT_APP_GITHUB_CLIENT_SECRET}`)

        dispatch({
            type: SEARCH_USERS,
            payload: res.data.items
        })
    }

The reducer:
export default (state, action) => {
    switch (action.type) {
        case SEARCH_USERS:
            return {
                ...state,
                users: action.payload,
                loading: false
            }
        case SET_LOADING:
            return {
                ...state,
                loading: true
            }
        default:
            return state;
    }
}

And the component in which i'm passing the payload:
const Users = () => {
    const githubContext = useContext(GithubContext);

    const {loading, users} = githubContext;

    if (loading) {
        return <Spinner/>
    } else {
        return (
            <div style={userStyle}>
                {users.map(user => (
                    <UserItem key={user.id} user={user}/>
                ))}
            </div>
        );
    }

}

action.payload is undefined and i don't understand why..is it something wrong with the request? i've console.log it and it looks like the request is made successfully

A: Problem in your code is the use of asynchronous action creator without any middleware to handle that async action creator. If your action creator was a synchronous function, your code would have worked fine.
Asynchronous action creators need to be handled differently as compared to the synchronous ones.
There are different NPM packages that allow you to handle asynchronous action creators. One such package is redux-thunk. Its a middleware that allows you to create an action creator that returns a function instead of an action.
To fix the problem, install redux-thunk and then change your action creator to return a function.
const searchUsers = (text) => {
   return async (dispatch) => {
        setLoading(true);

        const res = await axios.get(...);

        dispatch({
            type: SEARCH_USERS,
            payload: res.data.items
        })
    }
}

Some other packages that allow you to handle asynchronous action creators:

*

*redux-promise-middleware

*redux-saga


text:
Q: Migration from Hibernate 3 to 4 slows down startup we are trying to migrate our project from hibernate 3 to hibernate 4. Everything is working fine, but the problem is the startup.
We do not use JPA, we use direct hibernate with the  xml file and mapping files.
 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>

        <property name="hibernate.connection.driver_class">com.informix.jdbc.IfxDriver</property>
        <property name="hibernate.connection.url">jdbc:informix-sqli://xxx:xxx/xxx:INFORMIXSERVER=xxx</property>
        <property name="hibernate.connection.username">xxx</property>
        <property name="hibernate.connection.password">xxx</property>
        <property name="hibernate.dialect">org.hibernate.dialect.InformixDialect</property>
        <property name="hibernate.format_sql">true</property>
        <property name="hibernate.show_sql">false</property>

        <property name="generated.mappingFile">dev.xml</property>
   </session-factory>
</hibernate-configuration>

The property generated.mappingFile is an own property. On startup the file will be loaded (dev.xml). This file looks like this:
        <mapping resource="de/cargosoft/edi/cargoservice/entities/aart/Aart_DEV.hbm.xml" />
        <mapping resource="de/cargosoft/edi/cargoservice/entities/abteilung/Abteilung_DEV.hbm.xml" />
        <mapping resource="de/cargosoft/edi/cargoservice/entities/adr/Adr_DEV.hbm.xml" />
        <mapping resource="de/cargosoft/edi/cargoservice/entities/adraesort/Adraesort_DEV.hbm.xml" />
        <mapping resource="de/cargosoft/edi/cargoservice/entities/adrakte/Adrakte_DEV.hbm.xml" />
        ...
        <mapping resource="de/cargosoft/edi/cargoservice/entities/zollanmtxt/Zollanmtxt_DEV.hbm.xml" />
        <mapping resource="de/cargosoft/edi/cargoservice/entities/sstbasis/Sstbasis_DEV.hbm.xml" />
        <mapping resource="de/cargosoft/edi/cargoservice/entities/sststruktur/Sststruktur_DEV.hbm.xml" />
        <mapping resource="de/cargosoft/edi/cargoservice/entities/ssthandler/Ssthandler_DEV.hbm.xml" />
        <mapping resource="de/cargosoft/edi/cargoservice/entities/sstproperty/Sstproperty_DEV.hbm.xml" />
        <mapping resource="de/cargosoft/edi/cargoservice/entities/sstprophandler/Sstprophandler_DEV.hbm.xml" />
        <mapping resource="de/cargosoft/edi/cargoservice/entities/sstneustart/Sstneustart_DEV.hbm.xml" />

We reduced the number of mapping in this post. we do have more then 500 mappings in the moment.
With hibernate 3 it took 2 seconds to load all mappings. With hibernate 4 it takes over 2 minutes.
Here is the log file from hibernate 3.2.GA:
     07:36:21,293 INFO  [HibernateManager              ] | Verwende Mapping-Collection Datei : /com/cargosoft/csedi/data/mappings_dev.xml
     07:36:21,347 INFO  [HibernateManager              ] | Adding this resource to hibernate now          :  com/cargosoft/csedi/data/aart/Aart_DEV.hbm.xml
     07:36:21,443 INFO  [HibernateManager              ] | Adding this resource to hibernate now          :  com/cargosoft/csedi/data/abteilung/Abteilung_DEV.hbm.xml
     07:36:21,458 INFO  [HibernateManager              ] | Adding this resource to hibernate now          :  com/cargosoft/csedi/data/adr/Adr_DEV.hbm.xml
     07:36:21,495 INFO  [HibernateManager              ] | Adding this resource to hibernate now          :  com/cargosoft/csedi/data/adraesort/Adraesort_DEV.hbm.xml
     07:36:21,523 INFO  [HibernateManager              ] | Adding this resource to hibernate now          :  com/cargosoft/csedi/data/adrakte/Adrakte_DEV.hbm.xml
     ...
     07:36:23,475 INFO  [HibernateManager              ] | Adding this resource to hibernate now          :  com/cargosoft/csedi/data/zollanmtxt/Zollanmtxt_DEV.hbm.xml
     07:36:23,477 INFO  [HibernateManager              ] | Adding this resource to hibernate now          :  com/cargosoft/csedi/data/sstbasis/Sstbasis_DEV.hbm.xml
     07:36:23,479 INFO  [HibernateManager              ] | Adding this resource to hibernate now          :  com/cargosoft/csedi/data/sststruktur/Sststruktur_DEV.hbm.xml
     07:36:23,481 INFO  [HibernateManager              ] | Adding this resource to hibernate now          :  com/cargosoft/csedi/data/ssthandler/Ssthandler_DEV.hbm.xml
     07:36:23,482 INFO  [HibernateManager              ] | Adding this resource to hibernate now          :  com/cargosoft/csedi/data/sstproperty/Sstproperty_DEV.hbm.xml
     07:36:23,484 INFO  [HibernateManager              ] | Adding this resource to hibernate now          :  com/cargosoft/csedi/data/sstprophandler/Sstprophandler_DEV.hbm.xml
     07:36:23,486 INFO  [HibernateManager              ] | Adding this resource to hibernate now          :  com/cargosoft/csedi/data/sstneustart/Sstneustart_DEV.hbm.xml
     07:36:23,488 INFO  [HibernateManager              ] | Create new SessionFactory for: jdbc:informix-sqli://...

With hibernate 4.3.8-Final:
     07:38:04,749 INFO  [HibernateManager              ] | Verwende Mapping-Collection Datei : /de/cargosoft/edi/cargoservice/entities/mappings_dev.xml
     07:38:04,824 INFO  [HibernateManager              ] | Adding this resource to hibernate now          :  de/cargosoft/edi/cargoservice/entities/aart/Aart_DEV.hbm.xml
     07:38:05,249 INFO  [HibernateManager              ] | Adding this resource to hibernate now          :  de/cargosoft/edi/cargoservice/entities/abteilung/Abteilung_DEV.hbm.xml
     07:38:05,527 INFO  [HibernateManager              ] | Adding this resource to hibernate now          :  de/cargosoft/edi/cargoservice/entities/adr/Adr_DEV.hbm.xml
     07:38:05,792 INFO  [HibernateManager              ] | Adding this resource to hibernate now          :  de/cargosoft/edi/cargoservice/entities/adraesort/Adraesort_DEV.hbm.xml
     07:38:06,077 INFO  [HibernateManager              ] | Adding this resource to hibernate now          :  de/cargosoft/edi/cargoservice/entities/adrakte/Adrakte_DEV.hbm.xml
     ...
     07:40:14,119 INFO  [HibernateManager              ] | Adding this resource to hibernate now          :  de/cargosoft/edi/cargoservice/entities/zollanmtxt/Zollanmtxt_DEV.hbm.xml
     07:40:14,499 INFO  [HibernateManager              ] | Adding this resource to hibernate now          :  de/cargosoft/edi/cargoservice/entities/sstbasis/Sstbasis_DEV.hbm.xml
     07:40:14,746 INFO  [HibernateManager              ] | Adding this resource to hibernate now          :  de/cargosoft/edi/cargoservice/entities/sststruktur/Sststruktur_DEV.hbm.xml
     07:40:14,972 INFO  [HibernateManager              ] | Adding this resource to hibernate now          :  de/cargosoft/edi/cargoservice/entities/ssthandler/Ssthandler_DEV.hbm.xml
     07:40:15,211 INFO  [HibernateManager              ] | Adding this resource to hibernate now          :  de/cargosoft/edi/cargoservice/entities/sstproperty/Sstproperty_DEV.hbm.xml
     07:40:15,434 INFO  [HibernateManager              ] | Adding this resource to hibernate now          :  de/cargosoft/edi/cargoservice/entities/sstprophandler/Sstprophandler_DEV.hbm.xml
     07:40:15,657 INFO  [HibernateManager              ] | Adding this resource to hibernate now          :  de/cargosoft/edi/cargoservice/entities/sstneustart/Sstneustart_DEV.hbm.xml
     07:40:15,878 INFO  [HibernateManager              ] | Create new SessionFactory for: jdbc:informix-sqli://...

The method which adds the mapping files look like this:
 for (Node node : nodes) {
      Element element = (Element) node;
      String resource = element.attributeValue("resource");
      logger.info("Adding this resource to hibernate now          :  " + resource);
      configuration.addResource(resource);
 }

The time lack is on addResource.
We also tried it by moving the mapping element directly to the hibernate.cfg.xml file but it takes the same time to startup.
We believe hibernate is validating something what hibernate 3 did not.
Has anyone an idea to fix this issue? We can not wait 2 minutes for each test run.
Thanks a lot and many greetings,
Hauke
UPDATE
I changed the loglevel to "DEBUG" and now it comes this:
I changed to loglevel to debug and this is coming out now:
  11:29:22,781 INFO  [HibernateManager              ] | Adding this resource to hibernate now          :  de/cargosoft/edi/cargoservice/entities/aart/Aart_DEV.hbm.xml
  11:29:22,782 INFO  [Configuration                 ] | HHH000221: Reading mappings from resource: de/cargosoft/edi/cargoservice/entities/aart/Aart_DEV.hbm.xml
  11:29:22,804 DEBUG [DTDEntityResolver             ] | Trying to resolve system-id [http://hibernate.org/dtd/hibernate-mapping-3.0.dtd]
  11:29:23,149 INFO  [HibernateManager              ] | Adding this resource to hibernate now          :  de/cargosoft/edi/cargoservice/entities/abteilung/Abteilung_DEV.hbm.xml
  ...

So it seems that the DTDEntityResolver takes about 200ms - 400ms for each entity. With 500 entities this will sum up.
So the question is, how to disable that?

A: You need to change the DTD of all your HBM configuration files from:
http://hibernate.org/dtd/hibernate-mapping-3.0.dtd

to:
http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd

This is how the DTDEntityResolver tries to locate the DTO:
public class DTDEntityResolver implements EntityResolver, Serializable {

    private static final String HIBERNATE_NAMESPACE = "http://www.hibernate.org/dtd/";
    private static final String OLD_HIBERNATE_NAMESPACE = "http://hibernate.sourceforge.net/";
    private static final String USER_NAMESPACE = "classpath://";

    public InputSource resolveEntity(String publicId, String systemId) {
        InputSource source = null; // returning null triggers default behavior
        if ( systemId != null ) {
            LOG.debugf( "Trying to resolve system-id [%s]", systemId );
            if ( systemId.startsWith( HIBERNATE_NAMESPACE ) ) {
                LOG.debug( "Recognized hibernate namespace; attempting to resolve on classpath under org/hibernate/" );
                source = resolveOnClassPath( publicId, systemId, HIBERNATE_NAMESPACE );
            }
            else if ( systemId.startsWith( OLD_HIBERNATE_NAMESPACE ) ) {
                LOG.recognizedObsoleteHibernateNamespace( OLD_HIBERNATE_NAMESPACE, HIBERNATE_NAMESPACE );
                LOG.debug( "Attempting to resolve on classpath under org/hibernate/" );
                source = resolveOnClassPath( publicId, systemId, OLD_HIBERNATE_NAMESPACE );
            }
            else if ( systemId.startsWith( USER_NAMESPACE ) ) {
                LOG.debug( "Recognized local namespace; attempting to resolve on classpath" );
                String path = systemId.substring( USER_NAMESPACE.length() );
                InputStream stream = resolveInLocalNamespace( path );
                if ( stream == null ) {
                    LOG.debugf( "Unable to locate [%s] on classpath", systemId );
                }
                else {
                    LOG.debugf( "Located [%s] in classpath", systemId );
                    source = new InputSource( stream );
                    source.setPublicId( publicId );
                    source.setSystemId( systemId );
                }
            }
        }
        return source;
    }

   ...

}

Hibernate can't locate the hibernate-mapping-3.0.dtd configuration file in the hibernate-core-4.3.8.Final.jar and so it goes recursevily through all your class-path, and since you have a huge project, that explains why it starts so slow.

A: I have once used a trick to skip the DTD validation when parsing XML files, using the below code. Your case is more complicated as you need to plug this into the Hibernate config parser. But it may get you started.
private boolean skipDtd = true; // TODO make configurable

private EntityResolver dummyDtdResolver = new EntityResolver()
{
    @Override
    public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException
    {
        if (skipDtd && systemId.toLowerCase().endsWith(".dtd"))
            return new InputSource(new StringReader(""));
        return null;
    }
};

A few ways to use it:

*

*From a DocumentBuilder
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = dbf.newDocumentBuilder();
parser.setEntityResolver(dummyDtdResolver);
...
parser.parse(new File(xmlName));

*From an XmlReader
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
saxParserFactory.setNamespaceAware(true);
XMLReader xmlReader = saxParserFactory.newSAXParser().getXMLReader();
xmlReader.setEntityResolver(dummyDtdResolver);
...
new SAXSource(xmlReader, inputSource);


text:
Q: postscript get and put commands How and what format do the "get" and "put" commands in postscript work?
When I see something like this I feel there are too many operand and not enough operators.
    /x exch def
    /temp x x length 1 sub get def

A: put and get only work with composite objects such as arrays and dictionaries. You should get hold of the PostScript Language Reference Manual for details on what operands are expected for each operator.
This and other documents can be found from the Postscript tag info page.


text:
Q: How to write multidimensional NumPy array to disk the same as struct.pack? I have a routine that iteratively appends a 41x55 numpy array to an output file like the following:
fmt = 'ihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh'
for x in range(0, 41):
    vmdata_file.write(struct.pack(fmt, *building_vms[x,:]))

I'm trying to replace this with a call to the ndarray.tofile method but can't get the exact same output:
building_vms.tofile(vmdata_file)

My understanding is that the tofile method writes binary data the same as that struct.pack method as long as the underlying data types in the array are the same.  How can I ensure that the tofile method writes the same binary format as the struct.pack method?

A: One way is to first build the array in memory exactly how you like to have it on disk:
import numpy as np

firstcol = building_vms[:,0].astype('i').view('h').reshape(len(building_vms), -1)
tmp = np.hstack((firstcol , building_vms[:,1:].astype('h')))
tmp.tofile(vmdata_file)

Maybe slightly hackish, but instead of .view('h').reshape(len(building_vms), -1) you could also use .view('2h').


text:
Q: Wordpress NetworkError 403/404 : for /wp-admin/admin-ajax.php on this server admin-ajax.php file not found in registration using userpro plugin.
i check field validation using admin-ajax.php its workind  but click on register button using admin-ajax.php its not working
 NetworkError: 404 Not Found - http://www.example.com/wp-admin/admin-ajax.php


text:
Q: Logo (h1) with absolute position to move above navigation on resize I am creating a website layout which uses a position: absolute for the logo, to allow it to sit over another div below for stylistic reasons. I have been able to do this but doesn't really comply with responsive web design. To the right of this, I have a navigation and the logo and navigation crash when resizing.
How can I move the logo above the navigation when resizing but keep it positioned correctly when on a desktop?
Please find a snippet of my code below as well as jsfiddle link.
https://jsfiddle.net/d9e4gtoj/

.col-12 {
  width: 100%;
}

[class*="col-"] {
    padding: 15px;
    border: 2px solid red;
    display: inline-block;
    vertical-align: top;
    margin-right: -4px;
  }

.container {
    max-width: 99%;
    margin: 22px;
    margin: 0 auto;
    text-align: center;
}

.nav {
    margin-right: -4px;
    font-family: "Lato";
}

.top-nav {
    text-align: right;
    margin-right: 5px;
    padding-top: 52px;
}

.top-nav li {
    display: inline-block;
    vertical-align: top;
    margin: 0 10px;

}

.top-nav {
    text-align: right;
    margin-right: 5px;
    padding-top: 52px;
}
.logo {
    font-size: 82px;
    font-family: 'Suez One', serif;
    color: #3F3A46;
    position: absolute;
    padding-left: 100px;
    margin-top: 40px;
}

ul {
  list-style: none;
}

Logo

Menu1

Menu2

Menu3

Menu4

Tagline text. Tagline text.
 Tagline text. Tagline text.

A: This has resolved my problem:
@media (max-width: 800px) {

  .logo,
  .top-nav {
    margin: 0;
    padding: 0;
  }
  .logo {
    position: relative;
  }

  .top-nav {
    text-align: center;

    }

}


text:
Q: Dependency Injection and Entities I have two classes and have one to many  relationship as shown below
public class User
{
    public string Name{get;set;}
    public IList<Address> Addresses{get;set}
}

public class Address
{
   public string StreetAddress{get;set;}
   public User User{get;set;}
}

To add address to user I need to initiate Addresses property in User constructor as
public User()
{
   this.Addresses=new List<Address>();

}

Is this scenario good candidate to use DI to initiate List or should I initiate the Address list in constructor as shown.

A: If the the address data itself is required to construct an instance of User, it may be a candidate for DI.  But if's just a matter of making sure the list is instantiated, then your code is correct as-is.

A: In this case Dependency Injection would be overkill. Dependency Injection is usually used to initialize complex networks of services. Here you are dealing with a network of data objects that map to the piece of world you are translating into code: a composition between User and Address is therefore sufficient, and you must initialize collections in the constructor.


text:
Q: Enum as key of HashTable I'm writting a Schedule structure in Java.
I have a Hashtable with enum Day as Key and list of timeranges as value.
Like this :
public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY
}

private Hashtable<Day,TimeRanges> _applyCalendar;

where TimeRanges class is ...
public class TimeRanges implements List<TimeRange> {

When I add elements to _appleCalendar I do this :
public void addApplyDay(Day day,TimeRanges trs) {
    if (! _applyCalendar.contains(day)) {
        _applyCalendar.put(day, trs);
    } else {
        for ( TimeRange t : trs) {
            _applyCalendar.get(day).add(t);
        }
    }

}

My problem is method contains() doesn't work right.
HashTable can't be able to found existing element in hashtable,all time enter in the first condition :S
Is there any way to do this without should to declare Day as class and implement comareTo() ??

A: I think you want to use .containsKey() instead of contains(). contains() will search the actual objects whereas containsKey() will search the keys.
public void addApplyDay(Day day,TimeRanges trs) {
    if (! _applyCalendar.containsKey(day)) { // << use containsKey
        _applyCalendar.put(day, trs);
    } else {
        for ( TimeRange t : trs) {
            _applyCalendar.get(day).add(t);
        }
    }

}


text:
Q: Android Push notification- Only show the notification message to user I am trying to include Push Notification in my Hybrid Application.
While doing this, I am able to send the push notification message from rest client and also able to receive the notification in my Android device.
Now I want to the device user to get only the alert message which I send from the server.
For example:
In the body of my Post method,I am sending:
{
       "alert": "Hello android"
}
Then, only "Hello Android" should be visible to him, even if I open the application.
Currently,when I test the above example,
when the user's app is open, he gets an alert message with details related to gcm sender, collapse_key information, apart from the alert message.
I am attaching screenshot here

function processNotification(notification) {
 console.log("Hi! You have received a notification: " + JSON.stringify(notification));
 alert("Hi! You have received a notification: " + JSON.parse(notification));
 if(sap.Push.isPlatformIOS()){
         sap.Push.resetBadge(resetBadgeSuccess);
 }
}

Any Help would be appreciated


text:
Q: Unsupported browser in visual studio 2010 C# I want to display GPS coordinates on Google Maps. For this purpose I chose web browser from the toolbox. But it show an error of unsupported browser. I tried updating my Internet Explorer.
I also set Google Chrome as the Debugging Browser in Visual Studio but it didn't work.
This is the part of code where I am accessing the web browser.
try
{
    StringBuilder queryaddress = new StringBuilder();

    queryaddress.Append("https://maps.google.com/maps?q=");

    if (lat != string.Empty)
    {
        queryaddress.Append(lat + "," + "+");
    }

    webBrowser1.Navigate(queryaddress.ToString());
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message.ToString(), "Error");
}

Error

You seem to be using an unsupported browser. Old browsers can put your
  security at risk, are slow and don't work with newer Google Maps
  features. To access Google Maps, you'll need to update to a modern
  browser.

What is the best way to do this.?

A: You are getting this message since the WebBrowser control is emulating an older version of Internet Explorer on your machine:

By default, this feature is enabled for Windows Internet Explorer and
  for applications hosting the WebBrowser Control. To disable this
  feature by using the registry, add the name of your executable file to
  the following setting.

This can be changed via Registry settings:
HKEY_LOCAL_MACHINE (or HKEY_CURRENT_USER)
   SOFTWARE
      Microsoft
         Internet Explorer
            Main
               FeatureControl
                  FEATURE_BEHAVIORS
                     contoso.exe = (DWORD) <VALUE>

where VALUE is

*

*11001 (0x2AF9) Internet Explorer 11. Webpages are displayed in IE11
edge mode, regardless of the declared !DOCTYPE directive. Failing to
declare a !DOCTYPE directive causes the page to load in Quirks.

*11000 (0x2AF8) IE11. Webpages containing standards-based !DOCTYPE
directives are displayed in IE11 edge mode. Default value for IE11.

*10001 (0x2711) Internet Explorer 10. Webpages are displayed in IE10
Standards mode, regardless of the !DOCTYPE directive.

*10000 (0x02710)    Internet Explorer 10. Webpages containing
standards-based !DOCTYPE directives are displayed in IE10 Standards
mode. Default value for Internet Explorer 10.

*9999 (0x270F)  Windows Internet Explorer 9. Webpages are displayed in
IE9 Standards mode, regardless of the declared !DOCTYPE directive.
Failing to declare a !DOCTYPE directive causes the page to load in
Quirks.

*9000 (0x2328)  Internet Explorer 9. Webpages containing
standards-based !DOCTYPE directives are displayed in IE9 mode.
Default value for Internet Explorer 9. Important  In Internet
Explorer 10, Webpages containing standards-based !DOCTYPE directives
are displayed in IE10 Standards mode.

*8888 (0x22B8)  Webpages are displayed in IE8 Standards mode,
regardless of the declared !DOCTYPE directive. Failing to declare a
!DOCTYPE directive causes the page to load in Quirks.

*8000 (0x1F40)  Webpages containing standards-based !DOCTYPE directives
are displayed in IE8 mode. Default value for Internet Explorer 8
Important  In Internet Explorer 10, Webpages containing
standards-based !DOCTYPE directives are displayed in IE10 Standards
mode.

*7000 (0x1B58)  Webpages containing standards-based !DOCTYPE directives
are displayed in IE7 Standards mode. Default value for applications
hosting the WebBrowser Control.
Follow this article for a more details.


text:
Q: Why does my video from ffmpeg have a variable framerate? I tried stacking 4 3840x2160 mandelbrot sets into a 7680x4320 rectangle using ffmpeg built in filters directly (without producing the y4m as done below) and that produced a variable framerate video.
I speculated that perhaps ffmpeg was being too greedy and the filter was not fast enough, which was causing the variable framerate -- wild speculation I realize.
So, I tried another experiment, but I see the same result in which the output video has a variable framerate of around 25 to 27 fps (I need a constant framerate specified for the container, 60fps):
ffmpeg -f lavfi -i mandelbrot=s=3840x2160:r=60 -pix_fmt yuv420p -r 60 -t 20 mandel.y4m

And then:

ffmpeg -i mandel.y4m
-filter_complex
"[0:v][0:v]hstack=inputs=2[top];
[0:v][0:v]hstack=inputs=2[bottom];
[top][bottom]vstack=inputs=2[out]" -map "[out]"
-c:v libx265 -profile:v main -b:v 200M -minrate 200M -maxrate 200M -bufsize 400M
-pix_fmt yuv420p -r 60 -t 20 -y -pass 1 -an -f null /dev/null &&
ffmpeg -i mandel.y4m -filter_complex
"[0:v][0:v]hstack=inputs=2[top];
[0:v][0:v]hstack=inputs=2[bottom];
[top][bottom]vstack=inputs=2[out]" -map "[out]"
-c:v libx265 -profile:v main -b:v 200M -minrate 200M -maxrate 200M -bufsize 400M
-pix_fmt yuv420p -r 60 -t 20 -y -pass 2 mandel.mp4

EDIT:
The framerate is in fact constant.  But not 60 fps.  It's 24, for some reason.  Here is a simpler example with output:
ffmpeg -f lavfi -i mandelbrot=s=3840x2160:r=60 -f lavfi -i mandelbrot=s=3840x2160:r=60 -f lavfi -i mandelbrot=s=3840x2160:r=60 -f lavfi -i mandelbrot=s=3840x2160:r=60 -filter_complex "[0:v][1:v]hstack=inputs=2[top];[2:v][3:v]hstack=inputs=2[bottom];[top][bottom]vstack=inputs=2[out]" -map "[out]" -c:v libx265 -profile:v main -b:v 200M -minrate 200M -maxrate 200M -bufsize 400M -pix_fmt yuv420p -r 60 -t 20 -y 4MandelSyntheticWithStackFilters.mp4

or w/line breaks for clarity

ffmpeg
-f lavfi -i mandelbrot=s=3840x2160:r=60
-f lavfi -i mandelbrot=s=3840x2160:r=60
-f lavfi -i mandelbrot=s=3840x2160:r=60
-f lavfi -i mandelbrot=s=3840x2160:r=60
-filter_complex
"[0:v][1:v]hstack=inputs=2[top];
[2:v][3:v]hstack=inputs=2[bottom];
[top][bottom]vstack=inputs=2[out]" -map "[out]"
-c:v libx265 -profile:v main -b:v 200M -minrate 200M -maxrate 200M
-bufsize 400M -pix_fmt yuv420p -r 60 -t 20 -y
4MandelSyntheticWithStackFilters.mp4

ffmpeg version 5.1 Copyright (c) 2000-2022 the FFmpeg developers
  built with Apple clang version 13.0.0 (clang-1300.0.29.30)
  configuration: --prefix=/usr/local/Cellar/ffmpeg/5.1 --enable-shared --enable-pthreads --enable-version3 --cc=clang --host-cflags= --host-ldflags= --enable-ffplay --enable-gnutls --enable-gpl --enable-libaom --enable-libbluray --enable-libdav1d --enable-libmp3lame --enable-libopus --enable-librav1e --enable-librist --enable-librubberband --enable-libsnappy --enable-libsrt --enable-libtesseract --enable-libtheora --enable-libvidstab --enable-libvmaf --enable-libvorbis --enable-libvpx --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libxvid --enable-lzma --enable-libfontconfig --enable-libfreetype --enable-frei0r --enable-libass --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libspeex --enable-libsoxr --enable-libzmq --enable-libzimg --disable-libjack --disable-indev=jack --enable-videotoolbox
  libavutil      57. 28.100 / 57. 28.100
  libavcodec     59. 37.100 / 59. 37.100
  libavformat    59. 27.100 / 59. 27.100
  libavdevice    59.  7.100 / 59.  7.100
  libavfilter     8. 44.100 /  8. 44.100
  libswscale      6.  7.100 /  6.  7.100
  libswresample   4.  7.100 /  4.  7.100
  libpostproc    56.  6.100 / 56.  6.100
Input #0, lavfi, from 'mandelbrot=s=3840x2160:r=60':
  Duration: N/A, start: 0.000000, bitrate: N/A
  Stream #0:0: Video: rawvideo (RGB[0] / 0x424752), rgb0, 3840x2160 [SAR 1:1 DAR 16:9], 60 tbr, 60 tbn
Input #1, lavfi, from 'mandelbrot=s=3840x2160:r=60':
  Duration: N/A, start: 0.000000, bitrate: N/A
  Stream #1:0: Video: rawvideo (RGB[0] / 0x424752), rgb0, 3840x2160 [SAR 1:1 DAR 16:9], 60 tbr, 60 tbn
Input #2, lavfi, from 'mandelbrot=s=3840x2160:r=60':
  Duration: N/A, start: 0.000000, bitrate: N/A
  Stream #2:0: Video: rawvideo (RGB[0] / 0x424752), rgb0, 3840x2160 [SAR 1:1 DAR 16:9], 60 tbr, 60 tbn
Input #3, lavfi, from 'mandelbrot=s=3840x2160:r=60':
  Duration: N/A, start: 0.000000, bitrate: N/A
  Stream #3:0: Video: rawvideo (RGB[0] / 0x424752), rgb0, 3840x2160 [SAR 1:1 DAR 16:9], 60 tbr, 60 tbn
Stream mapping:
  Stream #0:0 (rawvideo) -> hstack
  Stream #1:0 (rawvideo) -> hstack
  Stream #2:0 (rawvideo) -> hstack
  Stream #3:0 (rawvideo) -> hstack
  vstack:default -> Stream #0:0 (libx265)
Press [q] to stop, [?] for help
x265 [info]: HEVC encoder version 3.4+31-6722fce1f
x265 [info]: build info [Mac OS X][clang 12.0.0][64 bit] 8bit+10bit+12bit
x265 [info]: using cpu capabilities: MMX2 SSE2Fast LZCNT SSSE3 SSE4.2 AVX FMA3 BMI2 AVX2
x265 [info]: Main profile, Level-6.1 (High tier)
x265 [info]: Thread pool created using 8 threads
x265 [info]: Slices                              : 1
x265 [info]: frame threads / pool features       : 3 / wpp(68 rows)
x265 [info]: Coding QT: max CU size, min CU size : 64 / 8
x265 [info]: Residual QT: max TU size, max depth : 32 / 1 inter / 1 intra
x265 [info]: ME / range / subpel / merge         : hex / 57 / 2 / 3
x265 [info]: Keyframe min / max / scenecut / bias  : 25 / 250 / 40 / 5.00
x265 [info]: Lookahead / bframes / badapt        : 20 / 4 / 2
x265 [info]: b-pyramid / weightp / weightb       : 1 / 1 / 0
x265 [info]: References / ref-limit  cu / depth  : 3 / off / on
x265 [info]: AQ: mode / str / qg-size / cu-tree  : 2 / 1.0 / 32 / 1
x265 [info]: Rate Control / qCompress            : ABR-200000 kbps / 0.60
x265 [info]: VBV/HRD buffer / max-rate / init    : 400000 / 200000 / 0.750
x265 [info]: tools: rd=3 psy-rd=2.00 early-skip rskip mode=1 signhide tmvp
x265 [info]: tools: b-intra strong-intra-smoothing lslices=8 deblock sao
Output #0, mp4, to '4MandelSyntheticWithStackFilters.mp4':
  Metadata:
    encoder         : Lavf59.27.100
  Stream #0:0: Video: hevc (hev1 / 0x31766568), yuv420p(tv, progressive), 7680x4320 [SAR 1:1 DAR 16:9], q=2-31, 200000 kb/s, 60 fps, 15360 tbn
    Metadata:
      encoder         : Lavc59.37.100 libx265
    Side data:
      cpb: bitrate max/min/avg: 200000000/0/200000000 buffer size: 400000000 vbv_delay: N/A
frame= 1200 fps=1.0 q=41.7 Lsize=  500040kB time=00:00:19.95 bitrate=205329.2kbits/s speed=0.0163x
video:500016kB audio:0kB subtitle:0kB other streams:0kB global headers:2kB muxing overhead: 0.004902%
x265 [info]: frame I:      5, Avg QP:26.50  kb/s: 964113.12
x265 [info]: frame P:    236, Avg QP:30.57  kb/s: 577628.54
x265 [info]: frame B:    959, Avg QP:38.13  kb/s: 109097.65
x265 [info]: Weighted P-Frames: Y:0.0% UV:0.0%
x265 [info]: consecutive B-frames: 0.4% 0.0% 0.0% 0.4% 99.2%

encoded 1200 frames in 1220.18s (0.98 fps), 204804.62 kb/s, Avg QP:36.60

Finally, note the framerate is not 60 fps, but instead 24.  Why is that?
ffmpeg -i 4MandelSyntheticWithStackFilters.mp4 -vf vfrdet -an -f null -
ffmpeg version 5.1 Copyright (c) 2000-2022 the FFmpeg developers
  built with Apple clang version 13.0.0 (clang-1300.0.29.30)
  configuration: --prefix=/usr/local/Cellar/ffmpeg/5.1 --enable-shared --enable-pthreads --enable-version3 --cc=clang --host-cflags= --host-ldflags= --enable-ffplay --enable-gnutls --enable-gpl --enable-libaom --enable-libbluray --enable-libdav1d --enable-libmp3lame --enable-libopus --enable-librav1e --enable-librist --enable-librubberband --enable-libsnappy --enable-libsrt --enable-libtesseract --enable-libtheora --enable-libvidstab --enable-libvmaf --enable-libvorbis --enable-libvpx --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libxvid --enable-lzma --enable-libfontconfig --enable-libfreetype --enable-frei0r --enable-libass --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libspeex --enable-libsoxr --enable-libzmq --enable-libzimg --disable-libjack --disable-indev=jack --enable-videotoolbox
  libavutil      57. 28.100 / 57. 28.100
  libavcodec     59. 37.100 / 59. 37.100
  libavformat    59. 27.100 / 59. 27.100
  libavdevice    59.  7.100 / 59.  7.100
  libavfilter     8. 44.100 /  8. 44.100
  libswscale      6.  7.100 /  6.  7.100
  libswresample   4.  7.100 /  4.  7.100
  libpostproc    56.  6.100 / 56.  6.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '4MandelSyntheticWithStackFilters.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2mp41
    encoder         : Lavf59.27.100
  Duration: 00:00:20.00, start: 0.000000, bitrate: 204816 kb/s
  Stream #0:0[0x1](und): Video: hevc (Main) (hev1 / 0x31766568), yuv420p(tv, progressive), 7680x4320 [SAR 1:1 DAR 16:9], 204806 kb/s, 60 fps, 60 tbr, 15360 tbn (default)
    Metadata:
      handler_name    : VideoHandler
      vendor_id       : [0][0][0][0]
      encoder         : Lavc59.37.100 libx265
Stream mapping:
  Stream #0:0 -> #0:0 (hevc (native) -> wrapped_avframe (native))
Press [q] to stop, [?] for help
Output #0, null, to 'pipe:':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2mp41
    encoder         : Lavf59.27.100
  Stream #0:0(und): Video: wrapped_avframe, yuv420p(tv, progressive), 7680x4320 [SAR 1:1 DAR 16:9], q=2-31, 200 kb/s, 60 fps, 60 tbn (default)
    Metadata:
      handler_name    : VideoHandler
      vendor_id       : [0][0][0][0]
      encoder         : Lavc59.37.100 wrapped_avframe
frame= 1200 fps= 24 q=-0.0 Lsize=N/A time=00:00:20.00 bitrate=N/A speed=0.394x
video:553kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: unknown
[Parsed_vfrdet_0 @ 0x7fdf00f27040] VFR:0.000000 (0/1199)


text:
Q: When I upload pdf document on Server. it,s save pdf but pdf size is 0 byte i have to upload pdf on server on his particular folder. but tried upload code as below. after pdf save and load on my site it's show "Failed to load PDF document."
i check uploaded pdf on server it,s size always 0 byte. i also tried to off compression then upload but not work. as the same code perfect work for images and video.
public async Task<string> UploadPDF(IFormFile formFile)
{
    string newFileName =
            UploadExtensions.GetUniqueFileName(formFile.FileName);
            string fileDirectoryPath;

            fileDirectoryPath =
            Path.Combine(_configuration["UploadPath"], "uploads/pdf");

            string savePath = Path.Combine(fileDirectoryPath,
               newFileName);

            await formFile.CopyToAsync(new FileStream(savePath,
              FileMode.Create));

            return newFileName;
}

upload pdf and save on server folder where i create and load in html page

A: You're not flushing the FileStream. You need to do it like:
using (var fileStream = new FileStream(savePath, FileMode.Create))
{
    await formFile.CopyToAsync(fileStream);
}


text:
Q: Android Studio doesn't show up once started I know this is an old very well documented issue with Android Studio but trust me I tried everything I found on Stack Overflow old threads (solutions from 2016, 2017 which quite obviously could not work anymore in 2021).
I installed Android Studio and when I start it, it doesn't run. I tried to set JAVA_HOME, JDK_HOME, STUDIO_JDK to both the JRE folder coming with Android Studio and with the the JDK installation folder under C:\Program Files\Java\jdk-15.0.2. I paid attention to run studio64.exe since my java -version say I'm running a 64bit version
java version "15.0.2" 2021-01-19
Java(TM) SE Runtime Environment (build 15.0.2+7-27)
Java HotSpot(TM) 64-Bit Server VM (build 15.0.2+7-27, mixed mode, sharing)

I can run studio.bat but the IDE doesn't show up, I simply have this
2021-04-13 10:22:21,156 [    438]   WARN - llij.ide.plugins.PluginManager - Problems found loading plugins:
  The Google Sceneform Tools (Beta) (id=google-sceneform-tools, path=~\AppData\Roaming\Google\AndroidStudio4.1\plugins\google-sceneform-tools, version=1.8.0) plugin defines no module dependencies (supported only in IntelliJ IDEA)
2021-04-13 10:22:21,923 [   1205]   WARN - Container.ComponentManagerImpl - Do not use constructor injection (requestorClass=com.android.tools.idea.AndroidInitialConfigurator)
2021-04-13 10:22:23,121 [   2403]   WARN - nSystem.impl.ActionManagerImpl - keymap "ReSharper" not found [Plugin: com.android.tools.ndk]
2021-04-13 10:22:23,398 [   2680]   WARN - nsions.impl.ExtensionPointImpl - Extension to be removed not found: class org.jetbrains.plugins.gradle.execution.test.runner.TestClassGradleConfigurationProducer
2021-04-13 10:22:23,757 [   3039]   WARN - Container.ComponentManagerImpl - Do not use constructor injection (requestorClass=org.jetbrains.android.compose.AndroidComposeAutoDocumentation)
2021-04-13 10:22:23,908 [   3190]   WARN - Container.ComponentManagerImpl - Do not use constructor injection (requestorClass=com.android.tools.idea.apk.ApkProjectComponent)
2021-04-13 10:22:23,909 [   3191]   WARN - Container.ComponentManagerImpl - Do not use constructor injection (requestorClass=com.android.tools.idea.apk.issues.SetupIssueReporter)
2021-04-13 10:22:25,326 [   4608]   WARN - ugins.textmate.TextMateService - Missing builtin bundles, checked:
C:/Users/emanu/AppData/Roaming/Google/AndroidStudio4.1/plugins/textmate/lib/bundles
C:/Program Files/Android/Android Studio/plugins/textmate/lib/bundles
2021-04-13 10:22:26,007 [   5289]   WARN - com.intellij.util.xmlb.Binding - no accessors for class org.jetbrains.kotlin.idea.highlighter.KotlinDefaultHighlightingSettingsProvider
2021-04-13 10:22:26,487 [   5769]   WARN - Container.ComponentManagerImpl - Do not use constructor injection (requestorClass=com.android.tools.idea.gradle.notification.GeneratedFileNotificationProvider)
2021-04-13 10:22:26,522 [   5804]   WARN - Container.ComponentManagerImpl - Do not use constructor injection (requestorClass=com.android.tools.idea.apk.editor.notification.ApkReloadNotificationProvider)
2021-04-13 10:22:26,701 [   5983]   WARN - Container.ComponentManagerImpl - Do not use constructor injection (requestorClass=com.android.tools.idea.apk.ApkWritingAccessProvider)
2021-04-13 10:22:27,007 [   6289]   WARN -            #com.android.ddmlib - * daemon not running; starting now at tcp:5037
2021-04-13 10:22:27,044 [   6326]   WARN -            #com.android.ddmlib - * daemon started successfully
2021-04-13 10:22:27,512 [   6794]   WARN - openapi.wm.impl.ToolWindowImpl - ToolWindow icons should be 13x13. Please fix ToolWindow (ID:  Problems View) or icon jar:file:/C:/Program%20Files/Android/Android%20Studio/lib/icons.jar!/general/warning.svg
2021-04-13 10:22:30,409 [   9691]   WARN - Container.ComponentManagerImpl - Do not use constructor injection (requestorClass=com.android.tools.idea.apk.symbols.DebugSymbolNotifications)
2021-04-13 10:22:31,417 [  10699]   WARN - dering.imagepool.ImagePoolImpl - 0 maxSize for Bucket. This Bucket will not be used.
2021-04-13 10:22:32,088 [  11370]   WARN - Container.ComponentManagerImpl - Do not use constructor injection (requestorClass=com.android.tools.idea.lang.androidSql.room.RoomDependencyChecker)

I see the initial Android Studio splash screen but then the process CPU usage goes down to 0% and the RAM keeps at 1GB. I see a process linked to the "hello_ar_java Android Studio" windows but I don't see this window.
Here a screenshot of the processes linked to Android Studio
So apparently the Android Studio is running, the initial welcome project started but is doesn't show up.

A: It sounds crazy but I finally found the answer to my question. I hope it will be useful o someone having the same issue. You can find it here
Android studio isn't opening on Windows

A: Check task manager for apps Or process  consuming resources and terminate these, if you are not using them, then restart android studio this worked for me.

A: so turns out you can't have your JAVA_HOME environment variable pointing to your own installation of Java. It has to be pointing to the JRE that comes with Android Studio.
Step 1: Delete any JAVA_HOME and JDK_HOME environment variables
Step 2: Copy the path to the jre folder inside your android studio installation
Step 3: Create new JAVA_HOME and JDK_HOME environment variables with the value as the path copied in step 2.
Android Studio should now open. Worked for me.


text:
Q: my scrollbar is hidden behind my fixed div with overflow scroll sorry that the html is so long but here it is. i hope that i can get some insight into what i'm doing wrong from this.

    .navbar {
     background-color: black;
     font-family: 'Bangers', cursive;
     letter-spacing: 5px;
     position: fixed;
     width: 100vw;
     z-index: 101;
       }
    .container {
     overflow: scroll;
     height: 100vh;
     width: 100vw;
     scroll-snap-type: mandatory;
     scroll-snap-points-y: repeat(100vh);
     scroll-snap-type: y mandatory;

     }
     body, html {

     width: 100%;
      height: 100%;
      min-height: 100%;
      margin: 0;
      padding: 0;
     overflow: auto;
     overiflow: initial;

    }
<container>

            Home

            <button class="dropbtn">Watch

            </button>

                Music Videos
                Spotlight Video

            <button class="dropbtn">Listen

            </button>

                Rap
                Beats

            <button class="dropbtn">Read

            </button>

                Blog
                Events
                lyrics
                Mission

            <button class="dropbtn">Submit

            </button>

                Media
                Complaint

            <button class="dropbtn">Connect

            </button>

                Email
                Cause

Lorem ipsum dolor sit amet, consectetur adipisicing.

Lorem ipsum dolor sit amet, consectetur

            Privacy Policy
                Terms and Conditions

</container>

when using overflow: scroll (which i need) my scrollbar is getting hidden behind my fixed div. I seen something about an iframe being the cause to this problem. maybe that could be it.

A: This is what you want:
https://jsfiddle.net/jennifergoncalves/gs1a9xr7/6/
It uses sticky elements.

.navbar {
  background-color: yellow;
  font-family: 'Bangers', cursive;
  letter-spacing: 5px;
  position: -webkit-sticky;
  position: sticky;
  top: 0;
}

.container {
  overflow: scroll;
}

body,
html {
  margin: 0;
  padding: 0;
}
<container>

      Home

      <button class="dropbtn">Watch

            </button>

        Music Videos
        Spotlight Video

      <button class="dropbtn">Listen

            </button>

        Rap
        Beats

      <button class="dropbtn">Read

            </button>

        Blog
        Events
        lyrics
        Mission

      <button class="dropbtn">Submit

            </button>

        Media
        Complaint

      <button class="dropbtn">Connect

            </button>

        Email
        Cause

Lorem ipsum dolor sit amet, consectetur adipisicing.

Lorem ipsum dolor sit amet, consectetur

      Privacy Policy
        Terms and Conditions

</container>

I don't think this is available in all browsers.  Here is some documentation:  https://www.w3schools.com/howto/howto_css_sticky_element.asp


text:
Q: Intermediate value theorem for mean Suppose the function $f:\mathbb{R}\rightarrow\mathbb{R}$ is continuous. For a natural number $k$, let $x_1,x_2,...,x_k$ be points in $[a,b]$. Prove there is a point $z$ in $[a,b]$ at which $$f(z)=(f(x_1)+f(x_2)+...+f(x_k))/k$$.
So I'm thinking about applying  the intermediate value theorem:
If $$a<x_1<b,a<x_2<b,...,a<x_k<b$$, then $$f(a)<f(x_1)<f(b),...,f(a)<f(x_k)<f(b)$$ or $$k.f(a)<f(x_1)+...+f(x_k)<k.f(b)$$ $$f(a)<(f(x_1)+f(x_2)+...+f(x_k))/k<f(b)$$
But I couldn't think of any way to prove that $f(a)<f(x_k)<f(b)$ or is it even true?
EDIT: Thanks everyone for your effort.

A: Hint:
Take $z\in\{x_1,\cdots x_k\}$ such that $f(z)\le f(x_j)$ for any $x_j$.
Take $w\in\{x_1,\cdots x_k\}$ such that $f(w)\ge f(x_j)$ for any $x_j$.
Then $$f(z)\le \frac{f(x_1)+\cdots+f(x_k)}{k}\le f(w)$$
Now, use the intermediate value theorem.

A: $m\le {1\over k}\sum_{i=1}^{k} f(x_i)\le M$ where $M= \max f(x),m=\min f(x)$ on $[a,b]$, Now apply IVT


text:
Q: read tempreture from bluetooth device with web bluetooth I am facing some problems with web Bluetooth API. the problem is that I have a temperature and humidity recorder Bluetooth device, which recorded temperature and humidity data through the sensor. I  want to fetch that data in my web app by using web Bluetooth in javascript. so how can I perform this task?
I have tried web Bluetooth but I only get device name and battery level but I am not able to fetch temperature & humidity data.

A: If the Bluetooth device uses the GATT Environmental Sensing service (GATT Assigned Number 0x181A), you should be able to read and get notified of the  Temperature (0x2A6E) and Humidity (0x2A6F) GATT characteristics.
Here's some code that should* work.
const serviceUuid = 0x181A;

// Requesting Bluetooth Device assuming it advertises
// the GATT Environmental Sensing Service...
const device = await navigator.bluetooth.requestDevice({
    filters: [{services: [serviceUuid]}]});

// Connecting to GATT Server...
const server = await device.gatt.connect();

// Getting Environmental Sensing Service...
const service = await server.getPrimaryService(serviceUuid);

// Getting Humidity Characteristic...
const characteristic = await service.getCharacteristic(0x2A6F);

// Reading Humidity...
const value = await characteristic.readValue();
console.log(value);

The sample at https://googlechrome.github.io/samples/web-bluetooth/notifications.html?characteristic=humidity&service=environmental_sensing may also help you get started.

A: You need to know what Bluetooth GATT service provides the temperature and humidity data. Applications like "nRF Connect" and the about://bluetooth-internals page built into your browser can help you explore the services provided by the device.
Web Bluetooth requires you to pass the UUIDs of the services you want to access to the navigator.bluetooth.requestDevice() function and so you need to figure out which GATT services you want to access before they will be visible on the BluetoothRemoteGATTServer object provided by the API.
If you post the manufacturer and model information for the device as part of the question someone may be able to direct you to documentation from the manufacturer for the GATT services the device provides or someone who has already reverse engineered how to access the data you are looking for.


text:
Q: How to get the filename of dropped file in SwiftUI? I have been trying to find out how to get the filename of an image dropped into a SwiftUI View.
The code fragment is as follows:
struct MainView: View, DropDelegate {

  @ObservedObject var userState : UserState

  var body : some View {
    Group {
      if (self.userState.editing) {
        BlackoutView()
      } else {
        DropView()
      }
    }
    .frame(minWidth: 320, idealWidth: 640, maxWidth: .infinity, minHeight: 240, idealHeight: 480, maxHeight: .infinity, alignment: .center)
    .onDrop(of: [(kUTTypeImage as String), "public.pdf"], delegate: self)
  }

  func dropUpdated(info: DropInfo) -> DropProposal? {
    let proposal = DropProposal.init(operation: .copy)
    return proposal
  }

  func performDrop(info: DropInfo) -> Bool {
    print("perform drop")
    userState.editing = true
    return true
  }

}

When I drop an image onto the app, it runs performDrop. How can one obtain the filename of the image dropped onto the app?
It runs on macOS.

A: Having spent more than an hour struggling with the apis (the documentation is almost nonexistent), here is what worked for me:
// The onDrop registration
.onDrop(of: [(kUTTypeFileURL as String)], delegate: self)

...
func performDrop(info: DropInfo) -> Bool {

    guard let itemProvider = info.itemProviders(for: [(kUTTypeFileURL as String)]).first else { return false }

    itemProvider.loadItem(forTypeIdentifier: (kUTTypeFileURL as String), options: nil) {item, error in
        guard let data = item as? Data, let url = URL(dataRepresentation: data, relativeTo: nil) else { return }
        // Do something with the file url
        // remember to dispatch on main in case of a @State change
    }

    return true
}

Please note that I have omitted any validation, so this code grabs the first url from any dropped files


text:
Q: Angular 1/Ui-router - Pass data from resolve to controller I want to pass a data (contactName) from the state to the controller by the resolves :
.state({
      name: 'contact.detail.overlay',
      abstract: true,
      component: 'overlayContent',
      resolve: {
        contactName: (originalContact, $rootScope, ContactService) => {
          $rootScope.contactName = ContactService.getContactName(originalContact)
          return $rootScope.contactName
        }
      }
    })

on my state all is correct, contactName is also correct, but it is not accessible in my overlayContent controller, do you have a solution to have $rootScope.contactName access in the controller ?
EDIT :
The controller :
class overlayContentComponent {

  constructor($state, $interpolate, $scope) {
    'ngInject'
    this.$scope = $scope
    this.$state = $state
    this.$interpolate = $interpolate
  }

  /**
   *
   * On initialization hook, let's check if an overlay title
   * has been defined for the current state.
   */

  $onInit() {
    const stateData = this.$state.current.data || { title: '' }
    this.overlayTitle = angular.isDefined(stateData.title) ? this.$interpolate(stateData.title)() : ''
  }
}

export const overlayContentComponent = {
  template: require('./overlay-content.html'),
  controller: overlayContentComponent
}

I can access contactName in my controller by this.$scope.$root.contactName but I would like to avoid $scope.$root by another alternative

A: Change your constructor:
constructor($state, $interpolate, $scope, contactName) {
  'ngInject';
  // The variable you want:
  this.contactName = contactName;
  this.$scope = $scope
  this.$state = $state
  this.$interpolate = $interpolate
}

The 'contactName' resolve should be injected now, into the controller for that state (where the resolve resides). This should allow you to access it in the controller, as above.


text:
Q: java stream sort() object to descended set of integers fails I have the following:
List someObjectList (one variable inside is years already ordered as DESC by PosgreSQL)
Let us say from 2018 to 2016 years (I need it as set because many someObject contains the same years value and I need just the unique in DESC order
I put it in Stream as follows:
Set<Integer> yearsSet = someObjectList.stream()
   .map(SomeObject::getYears)
   .collect(Collectors.toSet())

It returns set but with ASC years like 2016, 2017, 2018 not as had in objectsList ([0].getYears()>2018, [1].getYears()> 2017...etc) at the beginning
Also I used following .sort() method in both ways:
someObjectList.stream().map(SomeObject::getYears)
           .sorted(Comparator.comparing(Integer::intValue).reversed())
           .collect(Collectors.toSet())

and
someObjectList.stream().map(SomeObject::getYears)
            .sorted(Comparator.comparing(Integer::intValue))
            .collect(Collectors.toSet())

Both did nothing (maybe I used Integer::intValue incorrectly)?
Then I came to a solution which is ugly (here I get list but it is okey as no dublicated are received):
someObjectList.stream().map(SomeObject::getYears)
            .collect(Collectors.toSet())
            .stream().sorted(Comparator.comparing(Integer::intValue).reversed())
            .collect(Collectors.toList())

It does the job but it is ugly. Any advise where I am doing wrong or how could I replace this "sausage" part?
I read somewhere that Maps can not be easily sorder and maybe it is applied to sets?
Thank you for your time and advise

A: As @axelh did mention, you can not order a set (unless you opt for a TreeSet as an implementation), so here is a solution using TreeSet and providing the comparator in question as the constructor's parameter :
final Set<Integer> yearsSet = someObjectList.stream()
    .map(SomeObject::getYears)
    .collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.reverseOrder())));

A: You can't guarantees the order with a Set (only some implementation do it like SortedSet), see Java Set retain order? to find more information.
And the Collectors.toSet even mention it :

This is an unordered Collector.

You can simply use a List in that case. Using Stream.distinct to remove duplicates.
List<TimeVerification> list = new ArrayList<>();
list.add(new TimeVerification(2016));
list.add(new TimeVerification(2017));
list.add(new TimeVerification(2019));
list.add(new TimeVerification(2016));
list.add(new TimeVerification(2018));
list.add(new TimeVerification(2015));

List<Integer> orderedList = list.stream()
    .map(TimeVerification::getYear)
    .distinct()
    .sorted(Comparator.reverseOrder())
    .collect(Collectors.toList());

System.out.println(orderedList);

[2019, 2018, 2017, 2016, 2015]

Or use other Set to collect the Stream (see marsouf's answer about that).
Example used with :
public class TimeVerification {
    int year;

    public TimeVerification(int year) {
        this.year = year;
    }

    public int getYear() {
        return year;
    }
}

A: I might be wrong but it looks like you want to create a sorted set from the list of someObjects. One of the possible way is to collect to TreeSet with a custom comparator:
Set<Integer> years = someObjectList.stream()
   .map(SomeObject::getYears)
   .collect(Collectors.toCollection(() -> new TreeSet<Integer>()));

I assume that SomeObject::getYears returns an Integer.
if you need years in descent order add Comparator.reverseOrder() to the TreeSet constructor

A: The problem you are facing is that Collectors.toSet() will create a HashSet. So the ordering will depend on the hashCode() value of Integer. When you use Collectors.toList() the order will be based on insert order.


text:
Q: How I can make compatible my BookPDF.class to `Fragment` for `Navigation Drawer`. Q1. How I can make compatible my BookPDF.class to Fragment for Navigation Drawer.
Q2. I wanna use Intent intent = new Intent(MainActivity.this, BookPDF.class); to call BookPDF.class, but it won't work.
I'm using "AndroidPdfViewer" project from https://github.com/barteksc/AndroidPdfViewer

This is my MainActivity

public class MainActivity extends AppCompatActivity {

private static Button new_bookpdf;

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

public void onClickButtonListener() {
    new_bookpdf = (Button) findViewById(R.id.but_book);
    new_bookpdf.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent("ahmer.afzal.books.BookPDF");
            startActivity(intent);
        }
    });
}
}

This is my BookPDF.class

@EActivity(R.layout.activity_pdf)
@OptionsMenu(R.menu.options)
public class BookPDF extends AppCompatActivity implements OnPageChangeListener, OnLoadCompleteListener {
private static final String TAG = BookPDF.class.getSimpleName();
private final static int REQUEST_CODE = 42;
public static final int PERMISSION_CODE = 42042;
public static final String SAMPLE_FILE = "book.pdf";
public static final String READ_EXTERNAL_STORAGE = "android.permission.READ_EXTERNAL_STORAGE";
@ViewById
PDFView pdfView;
@NonConfigurationInstance
Uri uri;
@NonConfigurationInstance
Integer pageNumber = 0;
String pdfFileName;
@OptionsItem(R.id.pickFile)
void pickFile() {
    int permissionCheck = ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE);
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{READ_EXTERNAL_STORAGE}, PERMISSION_CODE);
        return;
    }
    launchPicker();
}

void launchPicker() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("application/pdf");
    try {
        startActivityForResult(intent, REQUEST_CODE);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(this, R.string.toast_pick_file_error, Toast.LENGTH_SHORT).show();
    }
}

@AfterViews
void afterViews() {
    if (uri != null) {
        displayFromUri(uri);
    } else {
        displayFromAsset(SAMPLE_FILE);
    }
    setTitle(pdfFileName);
}

private void displayFromAsset(String assetFileName) {
    pdfFileName = assetFileName;
    pdfView.fromAsset(SAMPLE_FILE)
            .defaultPage(pageNumber)
            .onPageChange(this)
            .enableAnnotationRendering(true)
            .onLoad(this)
            .scrollHandle(new DefaultScrollHandle(this))
            .load();
}
private void displayFromUri(Uri uri) {
    pdfFileName = getFileName(uri);
    pdfView.fromUri(uri)
            .defaultPage(pageNumber)
            .onPageChange(this)
            .enableAnnotationRendering(true)
            .onLoad(this)
            .scrollHandle(new DefaultScrollHandle(this))
            .load();
}
@OnActivityResult(REQUEST_CODE)
public void onResult(int resultCode, Intent intent) {
    if (resultCode == RESULT_OK) {
        uri = intent.getData();
        displayFromUri(uri);
    }
}
@Override
public void onPageChanged(int page, int pageCount) {
    pageNumber = page;
    setTitle(String.format("%s %s / %s", "Page Number", page + 1, pageCount));
}
public String getFileName(Uri uri) {
    String result = null;
    if (uri.getScheme().equals("content")) {
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        try {
            if (cursor != null && cursor.moveToFirst()) {
                result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
    if (result == null) {
        result = uri.getLastPathSegment();
    }
    return result;
}
@Override
public void loadComplete(int nbPages) {
    PdfDocument.Meta meta = pdfView.getDocumentMeta();
    Log.e(TAG, "title = " + meta.getTitle());
    Log.e(TAG, "author = " + meta.getAuthor());
    Log.e(TAG, "subject = " + meta.getSubject());
    Log.e(TAG, "keywords = " + meta.getKeywords());
    Log.e(TAG, "creator = " + meta.getCreator());
    Log.e(TAG, "producer = " + meta.getProducer());
    Log.e(TAG, "creationDate = " + meta.getCreationDate());
    Log.e(TAG, "modDate = " + meta.getModDate());
    printBookmarksTree(pdfView.getTableOfContents(), "-");
}

public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
    for (PdfDocument.Bookmark b : tree) {
        Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));
        if (b.hasChildren()) {
            printBookmarksTree(b.getChildren(), sep + "-");
        }
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
    if (requestCode == PERMISSION_CODE) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            launchPicker();
        }
    }
}
}

This is my Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ahmer.afzal.books">

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="BookPDF_"
        android:screenOrientation="sensor">
        <intent-filter>
            <action android:name="ahmer.afzal.books.BookPDF" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
</application>
</manifest>

Please help me.

A: package ahmer.afzal.books;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener
{
    private ProgressDialog progressDialog;
    DrawerLayout drawer;
    ActionBarDrawerToggle toggle;

    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed()
    {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START))
        {
            drawer.closeDrawer(GravityCompat.START);
        }
        else
        {
            super.onBackPressed();
        }
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState)
    {
        super.onPostCreate(savedInstanceState);
        toggle.syncState();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        if (toggle.onOptionsItemSelected(item))
        {
            return true;
        }

        if(item.getItemId() == R.id.action_settings)
        {
            startActivity(new Intent(this, SettingsActivity.class));
        }
        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item)
    {
        int id = item.getItemId();
        if (id == R.id.vocabulary)
        {
            Intent intent = new Intent("com.ahmer.books.BookPDF");
            startActivity(intent);
        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}


text:
Q: Separate LAN's using 2 Routers - Can ping devices on other LAN so the setup I've got:

*

*Main Router which receives the internet connection and is my primary WIFI network: 192.168.1.0/24

*Secondary Router which I've connected via the following method to create a separate LAN: 10.3.3.0/24. Main Router's LAN port --> Secondary Router's WAN port.

I've got this setup fine and can get internet from the Secondary Router's LAN, no problem.
My question is: Is it normal behavior to be able to ping a device connected to the main router from the secondary router?
I would like to isolate devices on each LAN so that devices connected to the separate LAN's can't communicate and wondering if I'm able to achieve this using 2 consumer grade routers?
Cheers!

A: This is normal behavior because the secondary router knows that IPs in the 192.168.1.0/24 subnet should be forwarded to its WAN port, so it can access hosts connected to that network.
Sadly, you usually can't create 2 segregated subnets with 2 consumer-grade routers, as these only have 2 network interfaces (one for WAN and one for the built-in switch).
I also do not recommend doing this, as double NAT can have unexpected side effects. If you really want to separate devices on your local network, looking into VLANs is a better way. You can use your existing router but will need a compatible switch.

A: If your routers support vlan management you should use separate vlans for both subnets. Otherwise you cant devide your networks.


text:
Q: Unexpected behaviour with HERE Route Match Extension I have a question regarding the Route Match Extension.
Should I expect any gaps in the GPS trace to be snapped to the road network as the most probable route, or to be represented as a straight line from A to B?

A: No, you should not expect any gaps here. The Route Match Extension works well with these locations. I reproduced it on a local demo (same gap between #3 and #4):

You should not use a different map source for displaying.


text:
Q: Mercurial Merge A coworker merged a bunch of files that broke the build.  I need to revert back to a working version and then commit that version in.  I want to do the whole tree.
To get Reversion:
"Hg update 4"  This will retrive the reversion 4 of the files.
I'm not sure how I would commit the changes and erase whatever was checked in.
Note: It would take too long to go to each file and do a merge, so i'm looking to revert the whole tree.
I'm also using tortoise HG.
Any advice would be appreciated.
Thanks,
D

A: hg up -r 4
<some edits>
hg ci -m "This is correct"
hg push -f


text:
Q: TypeScript recursive type with particular depth TypeScript allows you to compose recursive types but gives no insight into how the code changes in lower levels (i.e. depths). The code below, for example, would have the same kind of signature across all levels, and we would have to manually check at each level that there exists a sub property.
type Recurse = { foo: string; sub?: Recurse }

function recurse(depth: number): Recurse {
  if (depth === 0) return { foo: 'hey' }
  return {
    foo: 'hey',
    sub: recurse(depth - 1),
  }
}
const qux = recurse(5)

What I am seeking is a type signature that would give us concrete evidence of what the function returned at a particular depth.
const qux0: { foo: string } = recurse(0)
const qux1: { foo: string, sub: { foo: string } } = recurse(1)
const qux2: { foo: string, sub: {  foo: string, sub: { foo: string }} } = recurse(2)

This way, we would not have to check at every level for the sub property as the type signature already packs that information.
I have a feeling that this might be possible to achieve with conditional types but have no concrete evidence.
Do you have any idea how I could achieve that?

A: Until TS allows basic arithmetic operations for number types, you can use a decrement counter like Decr for all recursive types with particular depth:
type Decr = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] // add to a reasonable amount

type Recurse<N extends number> = N extends 0 ?
  { foo: string } :
  { foo: string; sub: Recurse<Decr[N]> }

function recurse<N extends number>(depth: N): Recurse<N> {
  if (depth === 0) return { foo: 'hey' } as Recurse<N>
  return {
    foo: 'hey',
    sub: recurse(depth - 1),
  } as Recurse<N>
}

type Decr9 = Decr[9] // 8

// compiles now
const qux = recurse(5)
const qux0: { foo: string } = recurse(0)
const qux1: { foo: string, sub: { foo: string } } = recurse(1)
const qux2: { foo: string, sub: { foo: string, sub: { foo: string } } } = recurse(2)

Sample

A: I think you can probably get something to work with recursive conditional types, but I would recommend against using such a solution. After all if someone were to invoke  recurse(5000) the return type would be huge.
You can easily build a solution based on a mapping type, where you add the type of a child for up to a specific depth:
type Recurse<T extends number =  number> = {
  foo: string;
  sub: RecurseChildren extends Record<T, infer C> ? C : Recurse
}

interface RecurseChildren {
  0: undefined;
  1: Recurse<0>
  2: Recurse<1>
  3: Recurse<2>
  4: Recurse<3>
  5: Recurse<4>
  6: Recurse<5>
  7: Recurse<6>
  8: Recurse<7>
  9: Recurse<8>
  10: Recurse<9>
}

function recurse<T extends number>(depth: T): Recurse<T> {
  if (depth === 0) return { foo: 'hey', sub: undefined as any }
  return {
    foo: 'hey',
    sub: recurse(depth - 1) as any,
  }
}
const qux = recurse(5)

qux.sub.sub.sub.sub.sub.sub // last one is undefined

Playground Link

A: The other answers are good but they both working with predefined values and you have to provide the range. However you can use another trick to let TypeScript does the checking for you:
type Recurse<N extends number> = Recurse_<N, []>;
type Recurse_<
    N extends number,
    Depth extends unknown[] = unknown[]
> = N extends Depth['length']
    ? { foo: string }
    : { foo: string; sub: Recurse_<N, [N, ...Depth]> };

function recurse<Depth extends number>(depth: Depth): Recurse<Depth> {
    if (depth <= 0) return { foo: 'hey' } as Recurse<Depth>;
    return {
        foo: 'hey',
        sub: recurse(depth - 1),
    } as Recurse<Depth>;
}

const qux = recurse(40);
const qux0: { foo: string } = recurse(0);
const qux1: { foo: string; sub: { foo: string } } = recurse(1);
const qux2: {
    foo: string;
    sub: { foo: string; sub: { foo: string } };
} = recurse(2);

Check the playground


text:
Q: FFmpeg: Invalid data found when processing input after created a video slideshow from images FFmpeg provides some examples of making slideshow from image(s):
https://trac.ffmpeg.org/wiki/Create%20a%20video%20slideshow%20from%20images
So I 've tried this command:
ffmpeg -loop 1 -t 10 -framerate 24 -i '1.png' -c:v libx264 -crf 36 -vf scale=640:360 -pix_fmt yuv420p -shortest 2.mp4

It is a success generating a MP4 file. Also there's no problem remuxing it into FLV.
FFmpeg gave no no error when I mux the video stream into .h264 .
But when I tried to process this file further, ffmpeg gave me this error:
$ffmpeg -i 2.h264
ffmpeg version 2.4.3 Copyright (c) 2000-2014 the FFmpeg developers
  built on Nov  4 2014 11:01:51 with llvm-gcc 4.2.1 (LLVM build 2336.11.00)
  configuration: --prefix=/Volumes/Ramdisk/sw --enable-gpl --enable-pthreads --enable-version3 --enable-libspeex --enable-libvpx --disable-decoder=libvpx --enable-libmp3lame --enable-libtheora --enable-libvorbis --enable-libx264 --enable-avfilter --enable-libopencore_amrwb --enable-libopencore_amrnb --enable-filters --enable-libgsm --enable-libvidstab --enable-libx265 --arch=x86_64 --enable-runtime-cpudetect
  libavutil      54.  7.100 / 54.  7.100
  libavcodec     56.  1.100 / 56.  1.100
  libavformat    56.  4.101 / 56.  4.101
  libavdevice    56.  0.100 / 56.  0.100
  libavfilter     5.  1.100 /  5.  1.100
  libswscale      3.  0.100 /  3.  0.100
  libswresample   1.  1.100 /  1.  1.100
  libpostproc    53.  0.100 / 53.  0.100
2.h264: Invalid data found when processing input

(OSX 10.10.1, with binary from http://ffmpegmac.net/ )
This problem can be reproduced on another Ubuntu 12.04 x64 machine:
# ffmpeg -i 2.h264 -c copy 2.flv
ffmpeg version 2.3.git Copyright (c) 2000-2014 the FFmpeg developers
  built on Aug  3 2014 13:42:36 with gcc 4.6 (Ubuntu/Linaro 4.6.3-1ubuntu5)
  configuration: --prefix=/root/ffmpeg_build --extra-cflags=-I/root/ffmpeg_build/include --extra-ldflags=-L/root/ffmpeg_build/lib --bindir=/root/bin --enable-gpl --enable-libass --enable-libfdk-aac --enable-libfreetype --enable-libmp3lame --enable-libx264 --enable-nonfree
  libavutil      52. 94.100 / 52. 94.100
  libavcodec     55. 71.100 / 55. 71.100
  libavformat    55. 50.100 / 55. 50.100
  libavdevice    55. 13.102 / 55. 13.102
  libavfilter     4. 11.102 /  4. 11.102
  libswscale      2.  6.100 /  2.  6.100
  libswresample   0. 19.100 /  0. 19.100
  libpostproc    52.  3.100 / 52.  3.100
2.h264: Invalid data found when processing input
So what the problem with this file?


text:
Q: How to configure g-wan to use virtual hosts? Say I have a domain foo.com and a server accessible at 50.60.70.80. I have configured the DNS entries so that foo.com and www.foo.com point to 50.60.70.80. I have g-wan running on the web server. Now I want to host different web sites on foo.com and on www.foo.com.
According to the documentation I have to configure a root host and optionally some virtual hosts. So I choose foo.com to be the root host. www.foo.com is a virtual host. My problems is that g-wan seems to ignore my virtual host. No matter whether I use foo.com or ww.foo.com g-wan always serves the foo.com content.
This is my g-wan "config":
/gwan/0.0.0.0_80/#movq.org
/gwan/0.0.0.0_80/$www.movq.org

What am I doing wrong here?

A: I am not sure but I believe that the www. prefix is hard-coded as an alias already.
You should rather try with something like secure.movq.org (providing that your DNS records are set, and that the client will use this domain name as the "Host: xxx" HTTP header then it should work for you too).
To simplify things you can use the G-WAN aliases feature for different domain names serving a same site and the virtual hosts (or another listener) for different sites.


text:
Q: Entity classes and final keyword From  another thread

By definition, an entity is a class that can be persisted to a
  database, so having a final field would make no sense in the context
  of something that will end up being a record in your database.

Could someone elaborate on why having a final field would make no sense?

A: Generally, persistence providers make proxies of objects using some library like CGLIB or javassist. These proxies are creating runtime subclasses of the entities. That's why they should not be final.
Detailed Explanation:
You can make an Hibernate Entity class final, but that's not a good practice. Since Hibernate uses proxy pattern for performance improvement, so, in case of lazy association, by making an entity final, Hibernate will no longer be able to use proxy, because Java doesn't allow extension of final class, thus limiting your performance improvement options. Though, you can avoid this penalty, if your persistent class is an implementation of interface, which declares all public methods defined in Entity class.
Proxies are created dynamically by sub classing the object(For example Student entity class) at runtime. The subclass overrides all the methods of the parent, and when any of the methods are accessed, the proxy loads the real object from the DB and calls the actual method on that object. If we make entity class as final then that entity class can´t be subclassed because final classes can´t be inherited.

A: You can have them, but they will be excluded from the persistence as a "Transient" field. So they won't be loaded or saved. That's just how JPA works.
static int transient1; // not persistent because of static
final int transient2 = 0;  // not persistent because of final
transient int transient3; // not persistent because of transient
@Transient int transient4; // not persistent because of @Transient

So then because JPA requires a parameterless constructor, you must set the final in that constructor or it's declaration, to a fixed value or something from a static. So it has little value, and would be smelly if it were used like this.


text:
Q: Allow unstable Android Gradle builds on Jenkins Hi I have set up my Android project on Jenkins to provide CI. Its working well, running tests on a connected Android handset. The tests run on the Android Test Framework which extends jUnit3.
Unfortunately, the build is marked as a failure if there are any test failures. I'd like to be able to improve this in two ways:

*

*Allowing unstable builds

*Being able to mark known test failures

For item 1 I tried adding this to the project build.gradle:
connectedCheck {
    ignoreFailures = true
}

But it has no effect. Looking at the build log, I realised the actual test task is called connectedInstrumentTest, but this task is not found:
connectedInstrumentTest {
    ignoreFailures = true
}

causes:

Could not find method connectedInstrumentTest() for arguments [build_4ldpah0qgf0ukktofecsq41r98$_run_closure3@9cd826] on project ':Playtime'.

That am I missing?
Thanks
EDIT: Heres my project build.gradle, nothing special:
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.5.+'
    }
}
apply plugin: 'android'

dependencies {
    compile files('libs/android-support-v4.jar')
}

android {
    compileSdkVersion 17
    buildToolsVersion "18.0.1"

    defaultConfig {
        minSdkVersion 8
        targetSdkVersion 16
        testPackageName "com.bb.pt.test"
        testInstrumentationRunner "android.test.InstrumentationTestRunner"
    }
}

connectedCheck {
    ignoreFailures = true
}

My gradle settings in jenkins:
switches: --stacktrace --info
tasks: :pt:assembleDebug :pt:assembleTest :pt:connectedCheck

EDIT:
I built gradlew and tried that. Same output. I don't want the build to FAIL if there are test failures:
:pt:connectedInstrumentTest FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':pt:connectedInstrumentTest'.
> There were failing tests. See the report at: file:///home/simon/WorkingCopies/bb/code/trunk/pt/pt/build/reports/instrumentTests/connected/index.html

* Try:
Run with --stacktrace option to get the stack trace. Run with --debug option to get more log output.

BUILD FAILED

I tried to qualify the task name in build.gradle:
task connectedCheck {
    ignoreFailures = true
}

But it thinks I am trying to add a new task rather than modify the existing one.
FAILURE: Build failed with an exception.

* Where:
Build file '/home/simon/WorkingCopies/bb/code/trunk/pt/pt/build.gradle' line: 31

* What went wrong:
A problem occurred evaluating project ':pt'.
> Cannot add task ':pt:connectedCheck' as a task with that name already exists.

A: After our conversation I believe that:

*

*the problem is gradle configuration only and not jenkins related. Get it to work in gradle.

*in gradle I believe (though I am not an expert) you should get the connectedInstrumentTest to ignore failures, but your attempt to use the following failed
connectedInstrumentTest {
    ignoreFailures = true
}

*maybe the solution is to wrap this config node like this:
project.gradle.taskGraph.whenReady {
  connectedInstrumentTest {
    ignoreFailures = true
  }
}

https://github.com/stanfy/hotandroid/blob/master/part0/build.gradle


text:
Q: I don't know how to store an array of object with mysql/node correctly I tried to make a table where i can register list of items. Actually everything is working, except array-object storage.
I tried a LOOOT of things on it,
Blob format on my sql- but i can't get the data back in front(nuxt) with .JSON() (.JSON() is not recognized) with this method. Convert Buffer Data
I tried to store it as a JSON format but it's not recognized by mysql.
Now I put it on a TEXT format on my sql (but when i call back the data i only get [object Object]- can't get through it in front or in the back.
I'd like to store something like
[
{"quantity":"2","content":
{"id":21,"reference":"LEG080276","designation":"cadre saillie mozaic blanc 2x6/8 modules 2x3 postes - prof 50mm","description":"sens de montage (horizontal)  nombre de modules (12)"}
},

{"quantity":"2","content":
{"id":6,"reference":"LEG080260L","designation":"voyant 2 modules 0.03w pour support batibox 1 poste ","description":null}
}
]

This is the call route in node.js- The list (array of objects) should be stored in content
router.post('/list', function getApi(req, res) {
    const {user_id, to_uuid, content, message, list_name, status}= req.body;
    db.query(`INSERT INTO list (user_id, to_uuid, content, message, list_name, status) VALUES (?,?,?,?,?,?)`, [user_id, to_uuid, content, message, list_name, status], (err, results) => {
      if (err) {
        res.status(500).send(`Erreur lors de l'enregistrement de la liste`);
        console.log(err);
      }
      res.status(200).send('Liste Enregistrée');
    });
  });

is there someone who's have an idea?
Thanks in advance

A: So i made it!!!
I registered array of objects (which was stringified) as a text format in mysql workbench!
it worked!!
this.$axios.post('http://localhost:3000/api/list/', {
                'user_id': this.$auth.user[0].user_id,
                'to_uuid':  this.$store.state.list.to_user.user_id,
                'content': JSON.stringify(this.$store.state.list.finalList),
                'message': this.message,
                'list_name': this.name,
                'status': "en attente"
                 })

this part is when i post the stringified array on content
async created(){
  const listReceived = await this.$axios.$get(`/api/listReceived/${this.$auth.user[0].user_id}`)
  const usersList = await this.$axios.$get("/api/users")

  listReceived.forEach(element => {
    const userdata=usersList.filter((post)=>post.user_id===element.user_id)
    const userSelected={
      listId:element.list_id,
      listName:element.list_name,
      message:element.message,
      status:element.status,
      content: JSON.parse(element.content),
      nickname:userdata[0].nickname
    }
          this.finalList.push(userSelected)
    })

this part is when i get the stringified array - I JSON.parse it on content