text:
Q: UnitControl - Block has encountered an error I am trying to use UnitControl in my custom Gutenberg block to define the line-height of text. I receive the "This block has encountered an error and cannot be previewed" when I try to access the block in the WordPress editor. I am unsure what is causing this error. I've even tried removing references to the UnitControl in the return and save such as lineHeight:headlineSpacing to see if it would stop flagging the error. It still gives me the error so I am unsure if I am using UnitControl correctly at all or if perhaps I've made a mistake in the <UnitControl> element.
CODE:
const { registerBlockType } = wp.blocks;
const {
    RichText,
    InspectorControls,
    ColorPalette,
    MediaUpload,
    MediaUploadCheck,
    Button,
    RawHTML,
    FontSizePicker,
    __experimentalUnitControl,
    InnerBlocks
} = wp.blockEditor;

const { PanelBody, IconButton } = wp.components;

registerBlockType('mycustomsite/small-jumbo', {
    //Built-in Attributes
    title: 'Small Jumbo',
    description: 'Block to generate a smaller jumbotron',
    icon: 'align-full-width',
    category: 'design',

    //Custom Attributes
    attributes: {
        title: {
        type: 'string',
        source: 'html',
        selector: 'h1'
        }
    },

    //Built-in Functions
    edit({attributes, setAttributes}) {
        const{
            title,
            headlineSize,
            headlineSpacing,
        } = attributes;

        const headlineSizes = [
            {
                name: '14px',
                slug: 'fourteen',
                size: 14
            },
            {
                name: '16px',
                slug: 'sixteen',
                size: 16
            },
            {
                name: '18px',
                slug: 'eighteen',
                size: 18
            },
            {
                name: '24px',
                slug: 'twentyfour',
                size: 24
            }
        ];

        //Custom Functions

        function onChangeTitle(newTitle) {
            setAttributes( { title: newTitle } );
        }

        function onChangeHeadlineSize( newHeadlineSize ) {
            setAttributes( { headlineSize: newHeadlineSize } );
        }

        function onChangeHeadlineSpacing( newHeadlineSpacing) {
            setAttributes( { headlineSize: newHeadlineSpacing } );
        }

        return ([
            <InspectorControls style={ { marginBottom: '40px' } }>

Customize Top Text

                <PanelBody title={ 'Headline Size' }>
                    <FontSizePicker
                        fontSizes={ headlineSizes }
                        value={ headlineSize }
                        onChange={ onChangeHeadlineSize }
                    />
                    </PanelBody>
                    <PanelBody title={ 'Line Height' }>
                    <UnitControl
                        label="Line Height"
                        isUnitSelectTabbable
                        value={ headlineSpacing }
                        onChange={ onChangeHeadlineSpacing }
                    />
                </PanelBody>
            </InspectorControls>,

            <RichText
                key="editable"
                tagName="h1"
                placeholder="H1 Title"
                value= { title }
                onChange= { onChangeTitle }
                style= { { fontSize:headlineSize, lineHeight:headlineSpacing} }
            />

        ]);
    },

    save({ attributes }) {
        const {
        title,
        headlineSize,
        headlineSpacing,
        } = attributes;

        return (

                <RichText.Content style={ {fontSize:headlineSize, lineHeight:headlineSpacing } } tagName="h1" value={title} />

        );
    }
});

A: The problem in your code is that UnitControl is not actually defined anywhere:
If you look at the example in the documentation, the UnitControl is defined as follows:
import { __experimentalUnitControl as UnitControl } from '@wordpress/components';

I.e. It uses the __experimentalUnitControl component in wp.components and not wp.blockEditor, and secondly, it imports the component as UnitControl.
So you should also do the same.
And the equivalent syntax with the const keyword is:
const { __experimentalUnitControl: UnitControl } = wp.components;
// I.e. const { <actual name>: <alias> }

So you should remove the __experimentalUnitControl, line in your code and import the one in the wp.components (or the @wordpress/components package) instead. I.e.
// Change this:
const { PanelBody, IconButton } = wp.components;

// to this one:
const {
    PanelBody,
    IconButton,
    __experimentalUnitControl: UnitControl
} = wp.components;

And with that, the error "This block has encountered an error" would now be gone.
Additional Issues in your code:
You've made a typo in your onChangeTitle() code: You misspelled setAttributes as etAttributes and it will cause an error because etAttributes is not defined. :)
And secondly, if you return an array of elements, then you should set a key for each of the elements:
return ([ // add a key for each direct child
    <InspectorControls style={ { marginBottom: '40px' } } key="foo-key">
        ...
    </InspectorControls>,

        ...

]);


text:
Q: Dragon Ball Xenoverse 2 - Z Rank I am trying to get Z rank in all quests, but I can't seem to get Z rank in the third training quest for Gotenks (the one where you fight the Cell Juniors).
I can complete the quest with:

*

*More than 80% HP

*Finish with Super Attack

*Kill 10 enemies with 10 Supers

*Hit 10 Supers

*Grab 3 Times

*Destroy 10 objects

*Hit 20 ki blasts

*Hit a 20 combo

And currently I can't remember no more, but even with the above I can't get Z rank. What else can I do to improve my score? Any tips for this quest?
EDIT:
Tried to use the "40 tons weitgh" Z-Soul, but it seems that this only change de experience and not the score itself.
My best score at this mission is around 8600... I'm pretty sure I am close to Z rank, but no luck until now...
EDIT 2: Just managed to complete the mission with 2 more bonuses:

*

*Hit behind 10 times

*Perfect block 3 times

Wans't enough yet: 8900 points... S Rank
Is there any list with all the accolades for this game?
EDIT 3: Complete all the above with:

*

*Finish in the last 10 seconds

9230 points and still S Rank... I'm starting to believe it's not possible to get Z Rank in this mission.

A: Finish with:

*

*10 seconds left Timely

*3 just guards (guard exactly when they hit you)

*20 ki blast repel

Use super soul or item to het your health over 80% before mission ends (get all the accolades that you listed). You don't need to go untouchable in this and even if you do you need to get other accolades also: Good luck!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is the word "bonsai" used both as a noun and a verb? Is it common to use the word "bonsai" as a verb as in the following passage? And what does it mean?

If you've ever crammed into the back of a Toyota with one or more males over the age of seven, you're likely familiar with the phenomenon recently popularized as manspreading.
A target of women's websites and public transit authorities, the practice involves the widening of a man's legs while seated such that those adjacent must bonsai themselves into what little sittable space remains in a bus or airplane row.

Source: "The manspreading epidemic: Is it really an epidemic?", CNN

A: Yes, it can be used as a verb and CNN used it that way.
Verbification in English is common and the linked Wikipedia article explains there are thousands of them:

Examples of verbification in the English language number in the
  thousands, including some of the most common words such as mail and
  e-mail, strike, talk, salt, pepper, switch, bed, sleep, ship, train,
  stop, drink, cup, lure, mutter, dress, dizzy, divorce, fool, merge, to
  be found on virtually every page in the dictionary. Thus,
  verbification is by no means confined to slang and has furnished
  English with countless new expressions: "access", as in "access the
  file", which was previously only a noun, as in "gain access to the
  file". Similar mainstream examples include "host", as in "host a
  party", and "chair", as in "chair the meeting". Other formations, such
  as "gift", are less widespread but nevertheless mainstream.

When a noun like 'bonsai' is used in the linked article, there is no doubt that it is used as a verb as it follows the modal verb must and you should use a verb before the reflexive pronoun themselves to make sense.
The noun 'bonsai' comes from the Japanese noun ' 盆栽 ぼんさい' and it means

a tree or shrub that has been dwarfed, as by pruning the roots and
  pinching, and is grown in a pot or other container and trained to
  produce a desired shape or effect.

[Dictionary.com]

...Those adjacent must bonsai themselves into what little sittable
  space...

could be rephrased to

...those adjacent must cram themselves into what little sittable space...

Related question: "To science the sh*t out of something"

A: Officially it is a noun. The word comes from the combination of two Japanese words:

"Bon" is a dish or thin bowl ("a modified vessel which has been divided or cut down from a deeper form").
"Sai" is a tree or other growing plant which is planted – "planted," as would be a halberd or spear or pike stuck into the ground.
"Bonsai" thus means or denotes "a tree which is planted in a shallow container".
-- Bonsai Empire

However the noun has unofficially been adopted for use as a verb (in much the same way that the verbs to hoover[1] and to google have been adopted from the nouns and phrases to vacuum using a Hoover and to search using the Google search engine) to mean to make small like a bonsai.
The English language is littered with such noun-orientated phrases that have been shortened into a single verb using the noun as the new verb. Is it correct? It's evolution.
So in your quoted phrase, to bonsai oneself would be to make oneself small like a bonsai to fit into a small space (like a Bon) caused by the "manspreading".


text:
Q: NPM fails to update Node on Windows 10 I am actually having trouble installing packages on my machine (Windows 10 Pro) but in the meantime that I am reading various pages on Stackoverflow and Github to resolve the issue, I tried updating Node and NPM with no luck. So if someone knows what is wrong here to do with this, might also help me understand the original problem I had.
In the attached snapshot, you see the current version of Node on my machine is 12.13.0, and when I update it with NPM, it should be 13.1.0 whereas running "node --version" still shows the old version.
I generally have problem with installing any new package on my machine. The user I am logged in with is an Administrator and I have access to anywhere on my machine. I have even tried running these commands in an CMD run as Administrator with no luck. Any help would be appreciated.

C:\>node --version
v12.13.0

C:\>npm install node -g

> node@13.1.0 preinstall C:\Users\***\AppData\Roaming\npm\node_modules\node
> node installArchSpecificPackage

+ node-win-x64@13.1.0
added 1 package and audited 1 package in 2.671s
C:\Users\***\AppData\Roaming\npm\node -> C:\Users\***\AppData\Roaming\npm\node_modules\node\bin\node
+ node@13.1.0
removed 1 package and updated 1 package in 6.004s

C:\>node --version
v12.13.0


text:
Q: python regex match case option I would like to utilize a match case option. I have a piece of code to search a string in a list. I guess there is a more elegant way to do the same.
searchString = "maki"
itemList = ["Maki", "moki", "maki", "Muki", "Moki"]

resultList = []
matchCase = 0

for item in itemList:
    if matchCase:
        if re.findall(searchString, item):
            resultList.append(item)
    else:
        if re.findall(searchString, item, re.IGNORECASE):
            resultList.append(item)

I could use re.findall(searchString, item, flags = 2) because re.IGNORECASE basically an integer (2) but I don't know which number would mean "matchcase" option.

A: You can enforce the case insensitive search inside the comprehension:
searchString = "maki"
itemList = ["Maki", "moki", "maki", "Muki", "Moki"]

resultList =[]
matchCase = 1

if matchCase:
    resultList = [x for x in itemList if x == searchString]
else:
    resultList = [x for x in itemList if x.lower() == searchString.lower()]

print resultList

It will print ['maki'] if matchCase is 1, and ['Maki', 'maki'] if it is set to 0.
See IDEONE demo


text:
Q: Is it possible in Node.js to detect if code executes some other script/file Imagine this code:
const myFunc = () => exec('node foo.js')

Now my library executes myFunc, but it doesn't know if it executes another script. How to make it know it?
P.S. The lib, which is a test runner + coverage tool, needs to know every piece of code that was run by the test.

A: If there's a need to detect API calls that may result in uncontrolled script execution and there's a need to detect calls, APIs have to be patched, e.g.:
const childProcess = require('child_process');
const { exec } = childProcess;
childProcess.exec = function () {
  console.error(new Error('No coverage'));
  return exec.apply(this, arguments);
};

This applies to global.eval, global.Function, all child_process module functions, some vm and worker_threads functions.


text:
Q: Generate id for files based on file content I am using a upload mechanism for users to upload files and the user is suppose to receive 3 different file extracted from the uploaded one in an group which is identified by the uploaded file name.
I am trying to map the output files to it's parent file.
How can generate something unique that can be linked to the files so that they are easily associated to its group.
I am using C# and SQl Server Filestream to store the files in database.
The limitation that i am facing is that I cannot rename the file provided by user.
Can someone help me out here?


text:
Q: Javascript performance improvement in browsers over years i'm a teacher in cartography and i'm preparing a course about client-side webmapping with JS apis and libs.
I searched the web for sources about browsers improvement in javascript performance, but i can't find recent data.
Any ideas ? Thanks !

A: If you're looking for up to date data, you can give jsPerf a go.
http://jsperf.com/
They use a service called BrowserScope, http://code.google.com/p/browserscope/. From their home page, http://www.browserscope.org/:

Browserscope is a community-driven project for profiling web browsers.

They have a history of JavaScript performance in various browsers and is updated frequently.

If you're interested in getting performance throughout the ages of JavaScript you can also run it yourself in Virtual Machines across various browsers.


text:
Q: How to check for outliers and leverage values in SPSS when conducting a multinomial logistic regression? I am conducting a multinomial logistic regression in SPSS. I want to check for the presence of outliers and high leverage values. How do I do that in SPSS?

A: The LOGISTIC REGRESSION procedure provides leverages for binary response models, but none  of the SPSS procedures that will fit multinomial logistic models provide leverage statistics for them.
Nothing fancy is provided in the way of residuals statistics either. It is possible to save actual category probabilities in the NOMREG (Multinomial Logistic Regression) procedure. Small predicted probabilities for the actually occurring group would be indicative of badly mis-predicting cases.


text:
Q: How to Display Multiple Labels in One Line with Python Tkinter? I have a Program that displays text on GUI Screen with Multiple Labels. But all the Labels are showing text in the new line and I want to show text in single line. Code is Below:
from tkinter import *
import tkinter as tk

win = Tk()
win.title("Label Screen")
win.geometry("800x600+50+50")
win.config(bg='white')

label1=Label(win, text="Label 1", font=("Calibri",24,"bold"), bg='white')
label1.pack(pady=15)

label2=Label(win, text="Label 2", font=("Calibri",24,"bold"), bg='white')
label2.pack(pady=15)

label3=Label(win, text="Label 3", font=("Calibri",24,"bold"), bg='white')
label3.pack(pady=15)

win.mainloop()

Output:

A: By default, the pack() method packs to the top, so you'll get a vertical stack of labels by default. You want to pack to the left to easily get all the labels on the same row. To do that, change:
labelX.pack(pady=15)

to
labelX.pack(side=tk.LEFT, pady=15)

Also, it's not ideal to import tkinter twice. Best to import it just once, as
import tkinter as tk

and then make sure to use tk. before all the methods, attributes, and classes.

A: Do this :
label1.pack(side=tk.LEFT,pady=15)
label2.pack(side=tk.LEFT,pady=15)
label3.pack(side=tk.LEFT,pady=15)

Further read : https://effbot.org/tkinterbook/pack.htm


text:
Q: Weird spring boot scheduler behavior - don't work with lazy initialization I have bizarre scheduler behavior in my spring boot application. I run SB 2.6.7 and java 17.
My code
@Configuration
@EnableScheduling
public class SchedulingConfigurerConfiguration implements SchedulingConfigurer {

    @Value("${schedule.pool}")
    private int DYNO_CORES;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        var taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(DYNO_CORES * 4);
        taskScheduler.initialize();
        taskRegistrar.setTaskScheduler(taskScheduler);
    }

    @Bean
    SimpleAsyncTaskExecutor executor() {
        var executor = new SimpleAsyncTaskExecutor("bg_tasks_");
        executor.setConcurrencyLimit(UNBOUNDED_CONCURRENCY);//these jobs are mainly IO-bound, so let's not set a limit for now
        return executor;
    }
}

And my class with one task.
@Slf4j
@Service
public class NoPrimaryServiceTasks {
    @Scheduled(fixedDelay = 1000, initialDelay = 1000 )
    public void checkBacklogSize() {
        log.info("logzzz");
    }
}

And it doesn't work.
But when I paste context.getBean(NoPrimaryServiceTasks.class); in main method everything works.
How to solve it without this workaround?
org.springframework.boot.autoconfigure.task.ScheduledBeanLazyInitializationExcludeFilter - also this class doesn't work

A: someone added into our codebase this code :)
for ( String name : beanFactory.getBeanDefinitionNames() ) {
    beanFactory.getBeanDefinition( name ).setLazyInit( true );
        }


text:
Q: Visualforce => Contacts are not fetching,what am I doing wrong here? Please help me out to solve this issue.I am struggling since a week.Now I think just one bit is missing from the issue. I have done everything but it seems contacts are failing to show.I will be glad if you share some time and help.I will appreicate it.
controller
public with sharing class DisplayAccWithContact1 {

   public contact con{get;set;}

    public DisplayAccWithContact1(ApexPages.StandardController controller) {

    con=new contact();

    }

    public String getContact() {
        return null;
    }

    public String accName {get;set;}

    List<Account> lstacc = new List<Account>();
    List<contact> lstcon = new List<contact>();
    public List<contact> getContacts() {
       lstcon.clear();
       accIds.clear();
       lstacc.clear();
       lstacc=[select id,name from Account where name=:con.accountid];
       for(Integer i=0;i<lstacc.size();i++)
       {
           accIds.add(lstacc[i].Id);
       }

        lstcon =[select id,name,Phone, email,accountId from contact where accountid in : accIds];
        //system.debug('### List of Contacts for Test is ###'+ lstcon);
        return lstcon;
    }

    set<string> accIds = new set<string>();
    public pagereference showContacts() {
       return null;
    }
}

Visualforce
<apex:page standardcontroller="Contact" sidebar="false" extensions="DisplayAccWithContact1">
    <apex:form >
        <apex:inputfield value="{!con.accountid}"/>
        <apex:commandButton value="ShowContacts" action="{!showContacts}" rerender="out" status="mystatus"/>

        <apex:actionstatus id="mystatus" starttext="please wait contacts are loading.......">
            <apex:facet name="stop">
                <apex:outputpanel id="out">
                    <apex:pageBlock >
                        <apex:pageBlockSection >
                            <apex:pageBlockTable value="{!Contacts}" var="c" rendered="{!con.accountid !=null}">
                                <apex:column headerValue="Name">
                                    {!c.Name}
                                </apex:column>
                                <apex:column headerValue="Phone">
                                    {!c.Phone}
                                </apex:column>
                                <apex:column headerValue="Email">
                                    {!c.Email}
                                </apex:column>
                            </apex:pageBlockTable>
                        </apex:pageBlockSection>
                    </apex:pageBlock>
                </apex:outputpanel>
            </apex:facet>
        </apex:actionstatus>
    </apex:form>
</apex:page>

Image:

A: I believe the problem is you are trying to match name to id, which is wrong.
Instead match Id to Id:
public List<contact> getContacts() {
    return [SELECT Name, Phone, Email FROM Contact WHERE AccountId = :con.accountid];
}

Update: standard controller is redundant here.
This is the was how this can be refactored
<apex:page sidebar="false" controller="DisplayAccWithContact1">
    <apex:form >
        <apex:inputfield value="{!con.accountid}"/>
        <apex:commandButton value="ShowContacts" action="{!showContacts}" rerender="out" status="mystatus"/>

        <apex:actionstatus id="mystatus" starttext="please wait contacts are loading.......">
            <apex:facet name="stop">
                <apex:outputpanel id="out">
                    <apex:pageBlock >
                        <apex:pageBlockSection >
                            <apex:pageBlockTable value="{!Contacts}" var="c" rendered="{!con.accountid !=null}">
                                <apex:column headerValue="Name">
                                    {!c.Name}
                                </apex:column>
                                <apex:column headerValue="Phone">
                                    {!c.Phone}
                                </apex:column>
                                <apex:column headerValue="Email">
                                    {!c.Email}
                                </apex:column>
                            </apex:pageBlockTable>
                        </apex:pageBlockSection>
                    </apex:pageBlock>
                </apex:outputpanel>
            </apex:facet>
        </apex:actionstatus>
    </apex:form>
</apex:page>

Controller
public with sharing class DisplayAccWithContact1 {
    public Contact con{get;set;}
    public DisplayAccWithContact1() {
        con=new contact();
    }
    public List<Contact> contacts {get; set;}

    public PageReference showContacts() {
        contacts = [SELECT Name, Phone, Email FROM Contact WHERE AccountId = :con.accountid];
        return null;
    }
}


text:
Q: Checking undefined value not working? I have the following javascript code:
var currentIds = localStorage.getItem('currentPairsIds');

if ((typeof currentIds === "undefined") ||
    (currentIds == null))
        $.myNameSpace.currentIDs = new Array(3);
    else
        $.myNameSpace.currentIDs = currentIds.Split(',');

I'm debugging with Firebug and although currentIds hasn't got any value it always executes else statement.
UPDATE:  I'm getting this value from HTML5 storage.
What am I doing wrong?

A: I would use a direct comparison instead of the notoriously odd "typeof" operator:
if ((currentIds === undefined) || (currentIds === null)) {
  //...

A: It's not working because localStorage.getItem returns null if the item is not defined, it does not return undefined http://dev.w3.org/html5/webstorage/#dom-storage-getitem
Example: http://jsfiddle.net/mendesjuan/Rsu8N/1/
var notStored = localStorage.getItem('ffff');

alert(notStored); // null
alert(typeof notStored); // object, yes, null is an object.

Therefore you should just be testing
alert(notStored === null);

A: This is how I have solved my problem:
var currentIds = localStorage.getItem('currentPairsIds');

if ((currentIds === undefined) ||
    (currentIds == null) || (currentIds == "undefined"))
        $.myNameSpace.currentIDs = new Array(3);
    else
        $.myNameSpace.currentIDs = currentIds.split(',');

localStorage.getItem('currentPairsIds'); returns the string "undefined".
There is another error in Split() function. The right version is without any capital letter.

A:
[Edit Edit Edit Edit :P]

currentIds = "undefined"

implies
typeof currentIds == "String"

Also see, Detecting Undefined, === isn't necessary for string comparison.

A: I think you have to make checking for undefined comparing with == instead of ===.
Example:
typeof currentIds == "undefined"

This will make sure, the variable is really undefined or not.

A: In my case LocalStorage.getItem() was converting it to "undefined" as string.
I also needed to check if it s "undefined" as a string.
var myItem = LocalStorage.getItem('myItem');
if(myItem != "undefined" && myItem != undefined && myItem != null){
    ...
}

A: if( typeof(varName) != "undefined" && varName !== null )

be sure, you use ( " " ) quotes when checking with typeof()


text:
Q: How to record the count of a TaskList I have a process called "Ulti.exe". Due to my project requirements I have more than one copy of it running at any one time. If the number of copies of "Ulti.exe" drop below 3, I need to kill all the processes and restart them again.
How can I save the TaskList count into a variable? Currently, the following command:
TaskList | FIND /C "Ulti.exe"

if typed into cmd.exe returns me the number of "Ulti.exe" processes accurately. How can I incorporate this into a .bat file so I can use this number as a variable?

A: Get the output of a command with a for /f loop:
for /f %%a in ('TaskList ^| FIND /I /C "Ulti.exe"') do set count=%%a
echo %count%

A: While counting you can as well gather the PIDs to ease killing them if needed
:: Q:\Test\2018\11\02\SO_53115422.cmd
@Echo off & SetLocal EnableExtensions EnableDelayedExpansion

Set "Prog=Ulti.exe"
::Set "Prog=firefox.exe"

Set "Count="
Set "PIDs="

for /f "tokens=2" %%A in (
    'TaskList /FI "IMAGENAME eq %Prog%" ^| Findstr /i "%Prog%"'
) do (
    Set /A Count+=1
    Set PIDs=!PIDs! /PID %%A
)

If defined Count (
    If !Count! lss 3 (
         echo taskkill %PIDs%
         echo restart %Prog%
    ) else (
        echo %Prog% running %Count% times [%PIDs%]
    )
) else (
    Echo %Prog% not running
    Echo start %Prog%
)

Sample output:
> SO_53115422
Ulti.exe running 5 times [ /PID 3664 /PID 10332 /PID 3544 /PID 8996 /PID 11192]

> SO_53115422
Ulti.exe not running
start Ulti.exe

> SO_53115422
taskkill  /PID 8056 /PID 2704
restart Ulti.exe

The taskkill command is only echoed while testing


text:
Q: Magento 2 $quote->getAllItems(); set StoreId or Website Try to catch the quote items, it's working fine. But when quote is not in default website, the request is empty. How to change website ID or store ID in quote request?
Did try with:
  $quote->setStore()
  $quote->setStoreId()

But no luck. This is the code:
  $orderId = 123;
  $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
  $quoteToOrder = $objectManager->create('Magento\Quote\Model\Quote\Item\ToOrderItem');
  $order = $objectManager->create('Magento\Sales\Model\Order')->load($orderId);
  $quote = $objectManager->create('\Magento\Quote\Model\Quote')->load($order->getQuoteId());

  $items = $quote->getAllItems();

  foreach ($items as $quoteItem) ...

Thank you so much for any help!


text:
Q: How to label :id in Ruby on Rails apps? I am building my first rails application and I expect it to eventually have many models/controllers.  And of course they each have an ID associated with them.  I can see that they are starting to get confusion already.
In the users controller the field is called id, but in every other controller i label it as user_id.  When a controller is manipulating multiple models or calling actions in other controllers, it seems tedious to keep all the ids straight.
I would like to just prefix them all to be explicit, but am afraid this might cause errors down the road as user does not actually have a user_id field.  This would be an issue when using something like update_attributes!.
Has anyone else experience this problem?  Is it really a problem or am I making this into a bigger issue than it actually is?  Are there any standard best practices for naming the id field?
Thanks!
Dave

A: This is really not a problem. The convention in Rails is to label the primary key of the table as id, and any foreign keys that access that table as table_name_id.
I'd advise against changing this default behaviour as Rails is more about convention over configuration, and this method of naming does actually make your DB schema far easier to understand as complexity grows.
If you do decide to change the primary key name, there is also the chance that you will run into further problems when using other peoples gems and plugins.

A: As far as I know the best name for id field is id.
I have application with about 30 models and almost the same number of controllers. I manipulate many models in single controller and I didn't ever have any problem with id. Maybe we could help you a little more if you paste some code.


text:
Q: Grep with multiple keywords and output multiple lines I want to grep lines contains all 3 different patterns, and output them with 2 previous lines and 1 next line.
This is the command I could grep without multiple line output. Now I want to add 3 additional line mentioned above. Can I put -A and -B together? Or do I have to use -C? Where should I put those options, all in three conditions or first or last?
grep -e Melon -e Banana -e Lemon *txt | grep Tomato | grep Milk

This is sample input
Egg Tomato
Salad Coffee
Melon Tomato Milk
Noodle Salmon
Banana Potato Milk
Salmon Rice

Expected output is
Egg Tomato
Salad Coffee
Melon Tomato Milk
Noodle Salmon

A: A large solution, you want: Two lines above and one line below of pattern: (Melon or Banana or Lemon) and Tomato and Milk
grep -A1 -B2 -E -e "(Tomato.*Milk|Milk.*Tomato).*(Melon|Banana|Lemon)" \
                -e "(Melon|Banana|Lemon).*(Tomato.*Milk|Milk.*Tomato)" \
                -e "Tomato.*(Melon|Banana|Lemon).*Milk" \
                -e "Milk.*(Melon|Banana|Lemon).*Tomato" *txt

Only for fun
Another solution using awk
awk '
    flag{print; flag=0}
    /Melon|Banana|Lemon/ && /Milk/ && /Tomato/{
        printf "%s\n%s\n%s\n",prev[0],prev[1],$0
        flag=1; next
    }
    {prev[0]=prev[1]; prev[1]=$0}' *txt


text:
Q: git rebase, keeping track of 'local' and 'remote' When doing a git rebase, I often have difficulty working out what is happening with the 'local' and 'remote' when resolving conflicts. I sometimes have the impression that they swap sides from one commit to the next.
This is probably (definitely) because I still haven't properly understood.
When rebasing, who is 'local' and who is 'remote'?
(I use P4Merge for resolving conflicts)

A: The bottom line
git rebase

*

*LOCAL = the base you're rebasing onto

*REMOTE = the commits you're moving up on top

git merge

*

*LOCAL = the original branch you're merging into

*REMOTE = the other branch whose commits you're merging in

In other words, LOCAL is always the original, and REMOTE is always the guy whose commits weren't there before, because they're being merged in or rebased on top
Prove it!
Certainly.  Don't take my word for it!  Here's an easy experiment you can do to see for yourself.
First, make sure you have git mergetool configured properly.  (If you didn't, you probably wouldn't be reading this question anyway.)  Then find a directory to work in.
Set up your repository:
md LocalRemoteTest
cd LocalRemoteTest

Create an initial commit (with an empty file):
git init
notepad file.txt  (use the text editor of your choice)
  (save the file as an empty file)
git add -A
git commit -m "Initial commit."

Create a commit on a branch that isn't master:
git checkout -b notmaster
notepad file.txt
  (add the text: notmaster)
  (save and exit)
git commit -a -m "Add notmaster text."

Create a commit on the master branch:
git checkout master
notepad file.txt
  (add the text: master)
  (save and exit)
git commit -a -m "Add master text."

gitk --all

At this point your repository should look like this:

Now for the rebase test:
git checkout notmaster
git rebase master
  (you'll get a conflict message)
git mergetool
  LOCAL: master
  REMOTE: notmaster

Now the merge test.  Close your mergetool without saving any changes, and then cancel the rebase:
git rebase --abort

Then:
git checkout master
git merge notmaster
git mergetool
  LOCAL: master
  REMOTE: notmaster
git reset --hard  (cancels the merge)

Your results should be the same as what's shown up top.

A: TL;DR;
To summarize (As Benubird comments), when:
git checkout A
git rebase   B    # rebase A on top of B

*

*local is B (rebase onto),

*remote is A
And:
git checkout A
git merge    B    # merge B into A

*

*local is A (merge into),

*remote is B
A rebase switches ours (current branch before rebase starts) and theirs (the branch on top of which you want to rebase).

kutschkem points out that, in a GUI mergetool context:

*

*local references the partially rebased commits: "ours" (the upstream branch)

*remote refers to the incoming changes: "theirs" - the current branch before the rebase.

See illustrations in the last part of this answer.

Inversion when rebase
The confusion might be related to the inversion of ours and theirs during a rebase.
(relevant extracts)
git rebase man page:

Note that a rebase merge works by replaying each commit from the working branch on top of the <upstream> branch.

Because of this, when a merge conflict happens:

*

*the side reported as 'ours' is the so-far rebased series, starting with <upstream>,

*and 'theirs' is the working branch.
In other words, the sides are swapped.

Inversion illustrated
On a merge
x--x--x--x--x(*) <- current branch B ('*'=HEAD)
    \
     \
      \--y--y--y <- other branch to merge

, we don't change the current branch 'B', so what we have is still what we were working on (and we merge from another branch)
x--x--x--x--x---------o(*)  MERGE, still on branch B
    \       ^        /
     \     ours     /
      \            /
       --y--y--y--/
               ^
              their

On a rebase:
But on a rebase, we switch side because the first thing a rebase does is to checkout the upstream branch! (to replay the current commits on top of it)
x--x--x--x--x(*) <- current branch B
    \
     \
      \--y--y--y <- upstream branch

A git rebase upstream will first change HEAD of B to the upstream branch HEAD (hence the switch of 'ours' and 'theirs' compared to the previous "current" working branch.)
x--x--x--x--x <- former "current" branch, new "theirs"
    \
     \
      \--y--y--y(*) <- upstream branch with B reset on it,
                       new "ours", to replay x's on it

, and then the rebase will replay 'their' commits on the new 'our' B branch:
x--x..x..x..x <- old "theirs" commits, now "ghosts", available through reflogs
    \
     \
      \--y--y--y--x'--x'--x'(*) <-  branch B with HEAD updated ("ours")
               ^
               |
        upstream branch

Note: the "upstream" notion is the referential set of data (a all repo or, like here, a branch, which can be a local branch) from which data are read or to which new data are added/created.

'local' and 'remote' vs. 'mine' and 'theirs'
Pandawood adds in the comments:

For me, the question still remains, which is "local" and who is "remote" (since the terms "ours" and "theirs" are not used when rebasing in git, referring to them just seems to make an answer more confusing).

GUI git mergetool
kutschkem adds, and rightly so:

When resolving conflicts, git will say something like:

local: modified file and remote: modified file.

I am quite sure the question aims at the definition of local and remote at this point. At that point, it seems to me from my experience that:

*

*local references the partially rebased commits: "ours" (the upstream branch)

*remote refers to the incoming changes: "theirs" - the current branch before the rebase.

git mergetool does indeed mention 'local' and 'remote':
Merging:
f.txt

Normal merge conflict for 'f.txt':
  {local}: modified file
  {remote}: modified file
Hit return to start merge resolution tool (kdiff3):

For instance, KDiff3 would display the merge resolution like so:

And meld would display it too:

Same for VimDiff, which displays:

Invoke Vimdiff as a mergetool with git mergetool -t gvimdiff. Recent versions of Git invoke Vimdiff with the following window layout:

+--------------------------------+
| LOCAL  |     BASE     | REMOTE |
+--------------------------------+
|             MERGED             |
+--------------------------------+

*

*LOCAL:
  A temporary file containing the contents of the file on the current branch.

*BASE:
  A temporary file containing the common base for the merge.

*REMOTE:
  A temporary file containing the contents of the file to be merged.

*MERGED:
  The file containing the conflict markers.

  Git has performed as much automatic conflict resolution as possible and the state of this file is a combination of both LOCAL and REMOTE with conflict markers surrounding anything that Git could not resolve itself.
  The mergetool should write the result of the resolution to this file.

A: I didn't get your problem exactly but I think the following diagram resolves your issue. (Rebase : Remote Repository ---> Workspace)

Source: My Git Workflow

A: I too, was confused for a long time, often making the wrong decision and had to start over.
DISCLAIMER: I'm no git expert so if anything here is wrong, please correct me!
I think I have come to the realization that my confusion was because I pictured a rebase differently than what many draw it. Here are two drawings that commonly are used to describe a rebase:

  --1--2--3--4--5
     \
      6--7--8

and then

  --1--2--3--4--5--6--7--8

And of course that is one way to draw it, but my feeling of what is happening with a rebase is this:

  --1--2--3--4--5
                 \
                  6--7--8

Which of course is exactly the same. But from an "ours/theirs" perspective it is different. In the second case it feels as if "we" are still "on" the branch ("6--7--8") and we want to pick up the changes from the "master". So in this world "ours" is still the "branch". And this is what confused me.
But in the first "world view", which I suppose is Git's view, we move to the master (the commit we want to rebase onto) and from there we pick each of the commits on the branch in turn and apply them. So "ours" becomes the "master", initially 5. After 6 has been applied successfully, "ours" is the 6, but actually the 6' that is "on" the master:

  --1--2--3--4--5--6'
     \
      6--7--8

And then we go on for the same with the "7".
So in a merge you "are on" the 8 and combine the two into a new commit, but in a rebase you move to the 5 and try to apply the diffs in the commits on the branch as new commits there.
So the "true" picture of the end result of a rebase should really be:

  --1--2--3--4--5--6'--7'--8'
     \
      6--7--8

And after the rebase you are on 8'. And so is you branch (I think!). And this could be visualized (in my mind) as:

  --1--2--3--4--5
     \           \
      6--7--8     6'--7'--8'


text:
Q: Database table union result I'm trying to show same table results in one column and it goes well using:
$sql = "(select * from ( select start as date from my_table union all select end from my_table ) tmp WHERE date > SUBDATE(CURDATE(),0) order by date limit 10)";

To imagine what I want to do:

Any ideas?

A: A more efficient way to achieve that result:
( SELECT s.start AS `date`
       , s.name  AS `name`
    FROM my_table s
   WHERE s.start > CURDATE() - INTERVAL 0 DAY
   ORDER BY s.start
   LIMIT 10
)
UNION ALL
( SELECT e.end   AS `date`
       , NULL    AS `name`
    FROM my_table e
   WHERE e.end   > CURDATE() - INTERVAL 0 DAY
   ORDER BY e.end
   LIMIT 10
 )
 ORDER BY `date`
 LIMIT 10

NOTES: Since the maximum number of rows to be returned is 10, we only need to return 10 rows with the start date, and 10 rows with the end date. This will avoid creating an enormous resultset that MySQL will have to sort ("Using filesort") to get them in the right order.
We can also avoid an outer select, using an "implicit" UNION ALL operation. (This is a MySQL extension to the SQL standard, not requiring an outer query.)
We include the value of the name column along with the start dates, and we include a static dummy value for the name column with the end dates. We do this so to satisfy the requirements of the UNION ALL operation (i.e. number of columns and datatypes of the columns has to match.) We could just as easily supply an empty string, or any other literal value, in place of the NULL.
MySQL can satisfy the query very efficiently if a suitable indexes are available, e.g.
... ON my_table (`start`,`name`)
... ON my_table (`end`)

We're assuming that start and end are datatype DATE. If those are stored as VARCHAR, then we want to modify the expression on the right side of the inequality comparisons in the queries, so that they return compatible and comparable datatypes and values.

A: If you only want the name on the "start" times, then do:
select start as thedate, name
from my_table
union all
select end, NULL
from mytable
order by thedate;


text:
Q: How to escape infinite loop in VBA / VB.NET bit of a stupid question, but I couldn't find any answers to it.
Sadly, I made a very shameful error, where I created an endless loop by accident.
Private Sub Textbox1_Change()
    Do While Len(Trim(Textbox1.Text)) > 4
       MsgBox "Please enter your birthyear in format of ####"
    Loop
End Sub

As I wanted to enforce users to type only 4 digits, obviously not
  realising I made an infinite-loop given it's impossible to close
  the MsgBox  as once you reach >4 characters, it keeps on creating
  new MsgBoxes even after you QueryClose/OK the one that popped up.

Is there a way I could cancel it, without closing Excel altogether? Sadly, I can't even pause the code given the MsgBox opened in modal form and I can't click any of the editor elements.

A: Just press Ctrl + Alt + Pause/Break.
This will interrupt your routine.

The Pause/Break button is standardly located above the PageUp button on most keyboards


text:
Q: Determining which variables are used globally I'm trying to refactor some lengthy shell scripts and I'd like to eliminate any variables that are declared within functions, but used globally. Is there a way to quickly find these variables?
Alternatively, is there a way to quickly find out which variables are empty at use? That way I can typeset all variables within functions and quickly see a list of all those globally used variables (with some false positives, but I can weed through those).
Thanks.

A: You might find set -u helpful.  If a variable is unset when used, the shell will error out.  This will not help you find variables that are the empty string when used, but will find variables that are unset.

A: I'm not aware of any real shortcuts here, but there are certainly some steps you can take to explore your script more systematically.

*

*Find exported variables with export -p.

*Grep for the declare keyword in your script.

*Loop through declare -F and grep for declare statements or variable assignment.

*Parse the output of set to exclude variables and functions you know about, and then investigate the remainder.

None of these are comprehensive solutions, I'm afraid. But to get you started:
# Find declare statements in functions.
for func in $( declare -F | awk '{print $NF}' ); do
    type "$func" | fgrep declare
done

Hope that helps!


text:
Q: How to execute multiple queries as bash script I am writing one bash shell script to create connection with postgres and execute multiple queries on one connection. For that I wrote following piece of code.
#!/bin/sh

psql postgresql://$USERNAME:$PASSWORD@$HOST:$PORT -c << EOF
CREATE DATABASE $DB_NAME ;
create user $USER with encrypted password '$PASSWORD';
grant all privileges on database $DB_NAME to $USER;

EOF

But its not working and giving me following error. what's wrong with this syntax.

A: #!/bin/sh

psql postgresql://$USERNAME:$PASSWORD@$HOST:$PORT << EOF
CREATE DATABASE $DB_NAME ;
create user $USER with encrypted password '$PASSWORD';
grant all privileges on database $DB_NAME to $USER;

EOF


text:
Q: How can I export/import subset data from/to Oracle Database? I was wondering what would be the approach to get rid of a lot of records from an Oracle database in order to create a lighter database for developer's laptops.
We aim to reduce the exports from different production environments NOT excluding entities, but reducing the number of records in each table mantaining the referential integrity.
Is there a tool/script around?
I was also wondering if transforming all the FKs on a replica DB to "on delete cascade" and deleting a subset of record from the entities on the top of the relational hierarchy would do the job.
Any suggestion?

A: With Jailer you can export data to an SQL script which can traverse foreign key constraints to include all data needed to maintain referential integrity.
http://jailer.sourceforge.net

A: If you wanted to export/import limit object from/to database, then you could EXCLUDE the objects, which you don't wanted to be part of your dump.
You can exclude any specific table to be exported/imported by specify the object type and object name.
EXCLUDE=TABLE:"='<TABLE_NAME>'"

==Update==
AFAIK, I don't see, if Oracle provides such flexibility to export subset data, but Oracle does have option to export partitioned data from TABLES
TABLES=[schema_name.]table_name[:partition_name] [, ...]


text:
Q: Should I migrate to Manifest v3 because most of the features of my extension depends on persistent background I have a chrome extension which uses WebSocket, webrtc, audio and HTTP connections heavily, also I am using react-redux in the background to keep a state of UI in the background for persisting current users' UI state. Now in Manifest v3, google removed the background and moved to the service worker, which is not feasible for making Websocket, webrtc connections, playing audio and storing redux state because it can terminate at any time and destroy all. There are multiple workarounds to fix all the problems but no solid solutions are there.
Please guide me should I continue with the migration to MV3 with these alternative solutions or just get out of the chrome extension and create a desktop app.

A: In my opinion, they will probably delay the transition until V3 becomes better. The extensions with the most downloads (as far as I can see) all still use V2. Even Google's own extensions still use V2.
If they don't delay it and don't fix any of the major issues you could consider Firefox or a desktop app. I don't think having to use weird solutions all the time to adjust to Chrome's extension nerfs is fun in the long run.


text:
Q: Alignment of input in regression tables (Latex) I have created a regression table using the following commands:
\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}
\begin{adjustbox}{max
width={\textwidth},caption={Cumulative Average Abnormal Return},nofloat=table}
\begin{tabular}{l*{4}{c}}
\hline\hline
                    &\multicolumn{1}{c}{(1)}&\multicolumn{1}{c}{(2)}&\multicolumn{1}{c}{(3)}&\multicolumn{1}{c}{(4)}\\
                    &\multicolumn{1}{c}{Test Model 1}&\multicolumn{1}{c}{Test Model 2}&\multicolumn{1}{c}{Test Model 3}&\multicolumn{1}{c}{Test Model 4}\\
\hline
Window 1:\\
{[0]}               &      0.0254\sym{***}&      0.02565\sym{***}&      0.0431\sym{***}&      0.0495\sym{***}\\
                    &    (0.0024)         &    (0.0065)         &    (0.0098)         &    (0.0024)         \\
Window 2:\\
{[-1,-10]}           &    0.000249         &    0.000230         &    0.000276         &   0.0000194         \\
                    &   (0.00024)         &   (0.00092)         &   (0.00032)         &   (0.000322)         \\
{[-11,-20]}          &   0.0000232         &   -0.000242         &   -0.000242         &   -0.000232         \\
                    &    (0.0019)         &    (0.0019)         &    (0.0019)         &    (0.0023)         \\
Window 3:\\
{[1,10]}             &   -0.000124         &   -0.000436         &   -0.000321         &   -0.000232         \\
                    &    (0.0011)         &    (0.0010)         &    (0.0010)         &    (0.0010)         \\
{[11,20]}            &    0.000124         &    0.000124         &    0.000124         &    0.000124         \\
                    &    (0.0014)         &    (0.0014)         &    (0.0014)         &    (0.0015)         \\

\hline
Observations        &         417         &         417         &         417         &         417         \\
\hline\hline
\multicolumn{5}{p{\textwidth}}{\footnotesize xxxxxxxxxx xxxxxxxxxx xxxxxxxxxx xxxxxxxxxx xxxxxxxxxxxxxxxxxxxx xxxxxxxxxx xxxxxxxxxx xxxxxxxxxx xxxxxxxxxxxxxxxxxxxx xxxxxxxxxx xxxxxxxxxx xxxxxxxxxx xxxxxxxxxxxxxxxxxxxx xxxxxxxxxx xxxxxxxxxx xxxxxxxxxx xxxxxxxxxx xxxxxxxxxx xxxxxxxxxx xxxxxxxxxx xxxxxxxxxx xxxxxxxxxx}\\
\multicolumn{5}{p{\textwidth}}{\footnotesize \sym{*} \(p<0.10\), \sym{**} \(p<0.05\), \sym{***} \(p<0.01\)}\\
\end{tabular}\end{adjustbox}

Text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text

This results in the following output:

My question is, how can I align all the columns in the regression table and at the same the keep the table width equal to the text width. I also want to "link" the caption and the table text to the table so it does not end up on to different pages. Thank you!

A: It is not clear to me how you want to "align all the columns" in the table.
If you want to align the columns to the left, have them of equal width while keeping the overall width of the tabular equal to the textwidth, you can try changing
\begin{tabular}{l*{4}{c}}

to
\begin{tabular}{l*{4}{p{.2\textwidth}}}

or
\begin{tabular}{*{5}{p{.2\textwidth}}}

Please post a comment if this doesn't help!!


text:
Q: How to capture a JTable filter event? I have a JTable and I want to show the visible record count in a JLabel next to it. So whenever I filter on the JTable or do anything that changes the visible row count, I want the JLabel to be updated with the new record count? What kind of listener do I implement to capture these events?

A: Table#getRowCount() actually returns the number of rows in the table view. So you could just call that method in the listener of what ever event causes the row count to change. Unfortunately, I'm unaware of any listener that listener for changes in the table row count change
The most direct listener (for your filter case) you could probably use a RowSorterListener which is "notified of changes to a RowSorter". You could do something like:
private void addListenerToSorter(RowSorter rowSorter,
                           final JTable table,
                           final JLabel rowCountLabel) {

    rowSorter.addRowSorterListener(new RowSorterListener() {
        @Override
        public void sorterChanged(RowSorterEvent e) {
            int newRowCount = table.getRowCount();
            rowCountLabel.setText("Number of view rows: " + newRowCount);
        }
    });
}

Note the RowSorterEvent also allows you to get the previous row count, if you're interested in that.
Here's a complete example:
import java.awt.BorderLayout;
import java.util.Vector;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

public class TestTableSortFilter {

    private JTable jTable = new JTable(createTableModel());
    private JLabel rowCountLabel = new JLabel();

    private TableRowSorter<TableModel> rowSorter
            = new TableRowSorter<>(jTable.getModel());

    private JTextField jtfFilter = new JTextField();
    private JButton jbtFilter = new JButton("Filter");

    public TestTableSortFilter() {
        jTable.setRowSorter(rowSorter);
        addListenerToSorter(rowSorter, jTable, rowCountLabel);

        JPanel panel = new JPanel(new BorderLayout());
        panel.add(new JLabel("Specify a number to match:"),
                BorderLayout.LINE_START);
        panel.add(jtfFilter, BorderLayout.CENTER);
        panel.add(rowCountLabel, BorderLayout.PAGE_END);

        rowCountLabel.setText("Number of view rows: " + jTable.getRowCount());

        jtfFilter.getDocument().addDocumentListener(new DocumentListener(){
            @Override
            public void insertUpdate(DocumentEvent e) { sortRows(); }
            @Override
            public void removeUpdate(DocumentEvent e) { sortRows(); }
            @Override
            public void changedUpdate(DocumentEvent e) {}

            private void sortRows() {
                String text = jtfFilter.getText();

                if (text.trim().length() == 0) {
                    rowSorter.setRowFilter(null);
                } else {
                    rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                }
            }
        });

        JFrame frame = new JFrame();
        frame.add(panel, BorderLayout.PAGE_END);
        frame.add(new JScrollPane(jTable), BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private TableModel createTableModel() {
        String[] cols = {"col1", "col2", "col3", "col4"};
        DefaultTableModel model = new DefaultTableModel(cols, 0);
        int value = 0;
        for (int i = 0; i < 100; i++) {
            Vector row = new Vector();
            for (int j = 0; j < cols.length; j++) {
                row.add(value);
                value++;
            }
            model.addRow(row);
        }
        return model;
    }

    private void addListenerToSorter(RowSorter rowSorter,
                               final JTable table,
                               final JLabel rowCountLabel) {

        rowSorter.addRowSorterListener(new RowSorterListener() {
            @Override
            public void sorterChanged(RowSorterEvent e) {
                int newRowCount = table.getRowCount();
                rowCountLabel.setText("Number of view rows: " + newRowCount);
            }
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                new TestTableSortFilter();
            }
        });
    }
}


text:
Q: TypeError: 'str' object is not callable when trying to click "datepicker" The relevant HTML

My code
self.driver.find_element(By.XPATH('//*[@id="datepicker"]')).click()
dateWidget = self.driver.find_element(By.ID("ui-datepicker-div"))
rows = dateWidget.find_element_by_tag_name("tr")
columns = dateWidget.find_element_by_tag_name("td")
for cell in columns: self.driver.findElement(By.LINK_TEXT("20")).click()

The error I'm getting
self.driver.find_element(By.XPATH('//*[@id="datepicker"]')).click()
TypeError: 'str' object is not callable

How can I make this work?

A: According to the "Location elements" section of the manual, By.XPATH seems to be a string, and the correct usage would be this:
self.driver.find_element(By.XPATH, '//*[@id="datepicker"]')

That also makes sense from the error message, since you are calling By.XPATH. And the current source also confirms this.
Unfortunately, the Selenium API is not really consistent across different platforms. The syntax you are using, calling By.xpath() is used by Java, and in C#, you also have to call By.Xpath(). So it's just naturally that you get confused when you see other examples where it's being called and in Python, you suddenly need to pass it. So you shouldn't blindly trust examples you find on the internet (like this one) but always check for which language they are. And check the documentation and/or the source in doubt.

A: If you want to use the generic find_element() method - pass two arguments - the By locator type and the locator value:
self.driver.find_element(By.XPATH, '//*[@id="datepicker"]')

Though, it would be cleaner to use the specific find_element_by_xpath() method:
self.driver.find_element_by_xpath('//*[@id="datepicker"]')

And, even cleaner in this case would be to use "by id" locator:
self.driver.find_element_by_id("datepicker")

A: So what I've found out from this error, is that sometimes a website will load a frame, which by printing the html -> print(driver.page_source) will give you what the driver can "see". If you can't find your element in page source, then there's your problem.
I fixed this by finding a .php link inside of the frame element and then adding that link to the current url, here's an example: Given www.site.com/login print the page source, and, if this is the issue, there will be a .php link that's inside the frame (ex. /loginPage.php. Click the link, copy it and execute the .get([new url]). This took me to an identical page, but you're able to access your html elements like normal!
Edit: Thank you Stephen for showing me the ropes to adding code for the first time!

A: I had the same problem, removing a bracket is what worked for me.
self.driver.find_element(By.XPATH('// [@id="datepicker"]')).click()

To:
self.driver.find_element(By.XPATH,'//*[@id="datepicker"]').click()


text:
Q: What is the correct pronunciation? Today, I talked with my friend. And we both have different opinion to each other. The subject is
Does British English (native) speaker pronunce the R letter at end of the word.
You only think the case of pronunce any word ending with R.
Please, answer. Thank you.

A: It's less obvious than in AmE, but it's there in some situations, see in this British Dictionary,where the "r" in the British pronunciation is raised.
Also:

Trends in phonological theory until 1975: a historical ... - Page 131
  Eli Fischer-Jørgensen - 1995
An example of latency is final r in British English, e.g. in jar [fa:]. Before a vow'el there is no latency, e.g. 1n far away ['far
  a'wei], but /r/ is latent elsewhere. A latent consonant is also
  assumed to exist in the genitive plural of most English nouns; ...

Also, see "floating consonant" in

A Glossary of Phonology  By Philip Carr
floating consonants Also
  known as latent consonants, these are usually word-final consonants
  which are not realized unless they can occupy the onset position in the following word

Also, see this and this. The latter shows a comparative recording.


text:
Q: Documentation Clarification for Android Layout ID parameter needed I have a doubt in android documentation in the following link.
http://developer.android.com/guide/topics/ui/accessibility/apps.html
Why is nextFocusDown having a "+" id (android:nextFocusDown="@+id/text")?nextFocusUp="@id/edit" is without the "+" id ? shouldn't both be without "+"
<LinearLayout android:orientation="horizontal"
        ... >
    <EditText android:id="@+id/edit"
        android:nextFocusDown="@+id/text"
        ... />
    <TextView android:id="@+id/text"
        android:focusable="true"
        android:text="Hello, I am a focusable TextView"
        android:nextFocusUp="@id/edit"
        ... />
</LinearLayout>

I am referring to this section of the android documentation.
http://developer.android.com/guide/topics/ui/declaring-layout.html#attributes

The plus-symbol (+) means that this is a new resource name that must
  be created and added to our resources (in the R.java file).

A: You are using the XML attribute of android:id, then you are specifying a new id to create a new entry in R.java, that is why you have to include (+) sign.
But in here:
android:nextFocusUp="@id/edit"

you are referring to an id that has already been created above.


text:
Q: Apache 500 Error AllowOverride All If I enable AllowOverride for /var/www, I get an 500 Internal Server Error. The .htaccess File is located in /var/www/html. I have already enabled a2enmod rewrite.

A: Try to restart apache2 service, and check for any error message. If there is any, provide them in the  question, please.


text:
Q: How to use 'find' to return parent directory I am using find to locate a file, but I want to only return the path to the parent directory of the file.
find /home/ -name 'myfile' -type f

That returns a list of the full path to all of the file matches, but I want to

A: If you want to execute something in the directory of the found file you may want to use -execdir action.
find /home/ -name 'myfile' -type f -print -execdir chmod -c 700 . \;

A: one way of many:
find /   -name 'myfile' -type f -exec dirname {} \;

A: The -printf action lets you extract lots of information about the file.  '%h' is the directive to get the path part of the file name.
find /home/ -name 'myfile' -type f -printf '%h\n'

A: find /home/ -name 'myfile' -type f|awk -f"/" '{print $(NF-1), "/",$NF}'

A: find /home/ -name 'myfile' -type f | rev | cut -d "/" -f2- | rev | sort -u

A: cd /home; find . -name 'myfile' -type f | sed "s/\/[^/]*$//" | cut -d "/" -f2- | sort -u


text:
Q: How to implement calendar in sencha touch Can anybody tell how to implement calendar in sencha touch .I am following this link https://github.com/SwarmOnline/Ext.ux.TouchCalendar to bring calendar in application
In index.hmtl I have included
<link rel="stylesheet" type="text/css" href="../resources/css/Ext.ux.TouchCalendarView.css" media="all"/>
        <script src="../Ext.ux.TouchCalendarView.js" type="text/javascript" language="JavaScript"></script>
    <script src="../Ext.ux.TouchCalendar.js" type="text/javascript" language="JavaScript"></script>

In Main.js am calling calendar view
{
                title: 'Details',
                iconCls: 'info',
                **xtype: 'calendar',**
                //style: 'margin-left:25%;',
                cls: 'card dark'
                },

the calendar is not coming in my screen is there any thing am missing please help to solve this problem
Thanks

A: Go to site https://market.sencha.com/extensions and download Calander Pro component example and you can use it. It will completely help you.
For download you need to account on sencha.


text:
Q: Assume that Pr(A ∪ B) = 5/6 and Pr(A`|B`) = 1/3. Determine Pr(B). Assume that Pr(A ∪ B) = 5/6 and Pr(A'|B') = 1/3. Determine Pr(B).
Where A' is A complement and B' is B complement.
Not sure how to approach this one. Appreciate any input

A: hint: $P(A'\mid B')\cdot P(B') = P(A'\cap B')= 1 - P(A\cup B)$. You can find $P(B')$, and then $P(B) = 1- P(B')$.


text:
Q: Add tag  in data source I want to add <b> tag in DataValueField of DropDownList as:
var data = source.Select(a => new A{f12 = <b> + a.f1 + </b> + a.f2, f3 = a.f3}).ToList(); // I want to bolder a.f1 string by <b> tag.

Then:
ddlDropDownList.DataSource = data;
ddlDropDownList.DataTextField = "f12";
ddlDropDownList.DataValueField = "f3";
ddlDropDownList.DataBind();

If I coding like above, I get unexpected results, The TextField displays bold <b> tag

A: You need to add string fragments, so add quotes:
var data = source.Select(a => new A{f12 = "<b>" + a.f1 + "</b>" + a.f2, f3 = a.f3}).ToList();

A: Have you tried to tinker with the Attributes field of the DropDownList? Like:
ddlDropDownList.Attributes.Add("style", "font-weight:bold");


text:
Q: Sound is stopping after a period of time The code of the mediaplayer (which starts under the comment:  //Code of the mediaplayer begins) is every time called when I click a button. After some time when I click the button, the sound is not played anymore.
It is like : I click for 10 times and it is returning the sound when I click again it stops and does not work anymore. Thanks for looking, If there is any solution comment below! :D
Logcat:
E/AudioFlinger: no more track names available
E/AudioFlinger: createTrack_l() initCheck failed -12; no control block?
E/AudioTrack: AudioFlinger could not create track, status: -12
E/AudioSink: Unable to create audio track
E/ExtendedNuPlayerDecoder: error in opening audio sink. Could be fatal!!!
**Code of the main activity'*:
           public class QuizActivity extends AppCompatActivity {

private ActionBarDrawerToggle mToggle;

private QuestionLibrary mQuestionLibrary = new QuestionLibrary();

private TextView mScoreView;
private TextView mQuestionView;
private Button mButtonChoice1;
private Button mButtonChoice2;
private Button mButtonChoice3;
private String mAnswer;
private int mScore = 0;
private int mQuestionNumber = 0;
Dialog dialog;
Dialog dialog2;
TextView closeButton;
TextView closeButton2;
CheckBox checkBoxmp;
private MediaPlayer mp, mp2;

SharedPreferences mypref;
SharedPreferences.Editor editor;

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

    //Dialog 1
    createDialog();
    Button dialogButton = (Button) findViewById(R.id.dialogbtn);
    dialogButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.show();

        }
    });

    closeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
    //end Dialog 1

    //Dialog 2
    createDialog2();
    Button dialogButton2 = (Button) findViewById(R.id.dialogbtn2);
    dialogButton2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog2.show();

        }
    });

    closeButton2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog2.dismiss();
        }
    });
    //end Dialog 2

    SharedPreferences mypref = getPreferences(MODE_PRIVATE);

    final SharedPreferences.Editor editor = mypref.edit();

    checkBoxmp.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
            editor.putBoolean("playSounds", !isChecked);
            editor.commit();
            if (!isChecked){
                mp.setVolume(1,1);
                mp2.setVolume(1,1);
            }else{
                mp.setVolume(0,0);
                mp2.setVolume(0,0);
            }
        }
    })
    ;

    final boolean playSounds = mypref.getBoolean("playSounds", false);
    checkBoxmp.setChecked(!playSounds);
    if(playSounds){

        mp.setVolume(1,1);
        mp2.setVolume(1,1);
    }
    else{

        mp.setVolume(0,0);
        mp2.setVolume(0,0);
    }

    TextView shareTextView = (TextView) findViewById(R.id.share);
    shareTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent myIntent = new Intent(Intent.ACTION_SEND);
            myIntent.setType("text/plain");
            myIntent.putExtra(Intent.EXTRA_SUBJECT, "Hello!");
            myIntent.putExtra(Intent.EXTRA_TEXT, "My highscore in Quizzi is very high! I bet you can't beat me except you are cleverer than me. Download the app now! https://play.google.com/store/apps/details?id=amapps.impossiblequiz");
            startActivity(Intent.createChooser(myIntent, "Share with:"));
        }
    });

    mQuestionLibrary.shuffle();

    setSupportActionBar((Toolbar) findViewById(R.id.nav_action));
    DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
    mDrawerLayout.addDrawerListener(mToggle);
    mToggle.syncState();
    getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Able to see the Navigation Burger "Button"

    ((NavigationView) findViewById(R.id.nv1)).setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.nav_stats:
                    startActivity(new Intent(QuizActivity.this, Menu2.class));
                    break;
                case R.id.nav_about:
                    startActivity(new Intent(QuizActivity.this, Menu3.class));
                    break;
            }

            return true;
        }
    });

    mScoreView = (TextView) findViewById(R.id.score_score);
    mQuestionView = (TextView) findViewById(R.id.question);
    mButtonChoice1 = (Button) findViewById(R.id.choice1);
    mButtonChoice2 = (Button) findViewById(R.id.choice2);
    mButtonChoice3 = (Button) findViewById(R.id.choice3);

    final List<Button> choices = new ArrayList<>();
    choices.add(mButtonChoice1);
    choices.add(mButtonChoice2);
    choices.add(mButtonChoice3);

    updateQuestion();

    //Code of the mediaplayer begins:

    for (final Button choice : choices) {
        choice.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                if (choice.getText().equals(mAnswer)) {
                      try {
                          mp = new MediaPlayer();
                          if (playSounds) {
                              mp.setVolume(1, 1);
                          } else {
                              mp.setVolume(0, 0);
                          }

                        mp.reset();
                        AssetFileDescriptor afd;
                        afd = getAssets().openFd("sample.mp3");
                        mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
                        mp.prepare();

                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer unused) {
                            mp.release();
                            mp = null;
                        }
                    });
                    mp.start();

                    updateScore();
                    updateQuestion();
                    Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();

                } else {
                    try {
                        mp2 = new MediaPlayer();
                        if (playSounds) {
                            mp2.setVolume(1, 1);
                        } else {
                            mp.setVolume(0, 0);
                        }
                        mp2.reset();
                        AssetFileDescriptor afd;
                        afd = getAssets().openFd("wrong.mp3");
                        mp2.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
                        mp2.prepare();

                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mp2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer unused) {
                            mp2.release();
                            mp2 = null;
                        }
                    });
                    mp2.start();

                    Toast.makeText(QuizActivity.this, "Wrong... Try again!", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(QuizActivity.this, Menu2.class);
                    intent.putExtra("score", mScore); // pass score to Menu2
                    startActivity(intent);
                }
            }
        });
    }
}

//End mediaplayer main code
private void updateQuestion() {
    if (mQuestionNumber < mQuestionLibrary.getLength()) {
        mQuestionView.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
        mButtonChoice1.setText(mQuestionLibrary.getChoice1(mQuestionNumber));
        mButtonChoice2.setText(mQuestionLibrary.getChoice2(mQuestionNumber));
        mButtonChoice3.setText(mQuestionLibrary.getChoice3(mQuestionNumber));
        mAnswer = mQuestionLibrary.getCorrectAnswer(mQuestionNumber++);
    } else {
        Toast.makeText(QuizActivity.this, "Last Question! You are very intelligent!", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(QuizActivity.this, Menu2.class);
        intent.putExtra("score", mScore);
        startActivity(intent);
    }
}

private void updateScore() {
    mScoreView.setText(String.valueOf(++mScore));

    SharedPreferences mypref = getPreferences(MODE_PRIVATE);
    int highScore = mypref.getInt("highScore", 0);

    if (mScore > highScore) {
        SharedPreferences.Editor editor = mypref.edit();
        editor.putInt("highScore", mScore);
        editor.apply();
    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    return mToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}

private void createDialog() {
    dialog = new Dialog(this);
    dialog.setTitle("Tutorial");
    dialog.setContentView(R.layout.popup_menu1_1);
    closeButton = (TextView) dialog.findViewById(R.id.closeTXT);
}

private void createDialog2() {
    dialog2 = new Dialog(this);
    dialog2.setTitle("Settings");
    dialog2.setContentView(R.layout.popup_menu1_2);
    closeButton2 = (TextView) dialog2.findViewById(R.id.closeTXT2);
    checkBoxmp = (CheckBox) dialog2.findViewById(R.id.ckeckBox);

}

}

A: You are not releasing MediaPlayers. That could be the reason behind this issue. Without touching most of your logic, one way to do this is:
Make mp and mp2, private members of QuizActivity.
public class QuizActivity extends AppCompatActivity {
    ...
    private MediaPlayer mp, mp2;
    ...
}

Create MediaPlayer whenever required, and release it when playback is done.
mp = new MediaPlayer();
if (playSounds) {
    mp.setVolume(1, 1);
} else {
    mp.setVolume(0, 0);
}

AssetFileDescriptor afd;
...
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer unused) {
        mp.release();
        mp = null;
    }
});
mp.start();

At other places, you will have to perform null checks as shown below, before accessing mp and mp2 to avoid NPE.
if (null != mp && null != mp2) {
    if (!isChecked) {
        mp.setVolume(1, 1);
        mp2.setVolume(1, 1);
    } else {
        mp.setVolume(0, 0);
        mp2.setVolume(0, 0);
    }
}

Other approach would be to add click-listeners only after creating media players.
This link sheds more light on MediaPlayer release.
And the complete source would look as shown below.
public class QuizActivity extends AppCompatActivity {

    private ActionBarDrawerToggle mToggle;

    private QuestionLibrary mQuestionLibrary = new QuestionLibrary();

    private TextView mScoreView;
    private TextView mQuestionView;
    private Button mButtonChoice1;
    private Button mButtonChoice2;
    private Button mButtonChoice3;
    private String mAnswer;
    private int mScore = 0;
    private int mQuestionNumber = 0;
    Dialog dialog;
    Dialog dialog2;
    TextView closeButton;
    TextView closeButton2;
    CheckBox checkBoxmp;
    private MediaPlayer mp, mp2;

    SharedPreferences mypref;
    SharedPreferences.Editor editor;

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

        //Dialog 1
        createDialog();
        Button dialogButton = (Button) findViewById(R.id.dialogbtn);
        dialogButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.show();

            }
        });

        closeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        //end Dialog 1

        //Dialog 2
        createDialog2();
        Button dialogButton2 = (Button) findViewById(R.id.dialogbtn2);
        dialogButton2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog2.show();

            }
        });

        closeButton2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog2.dismiss();
            }
        });
        //end Dialog 2

        SharedPreferences mypref = getPreferences(MODE_PRIVATE);

        final SharedPreferences.Editor editor = mypref.edit();

        checkBoxmp.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                editor.putBoolean("playSounds", !isChecked);
                editor.commit();
                if (null != mp && null != mp2) {
                    if (!isChecked) {
                        mp.setVolume(1, 1);
                        mp2.setVolume(1, 1);
                    } else {
                        mp.setVolume(0, 0);
                        mp2.setVolume(0, 0);
                    }
                }
            }
        });

        final boolean playSounds = mypref.getBoolean("playSounds", false);
        checkBoxmp.setChecked(!playSounds);

        TextView shareTextView = (TextView) findViewById(R.id.share);
        shareTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent myIntent = new Intent(Intent.ACTION_SEND);
                myIntent.setType("text/plain");
                myIntent.putExtra(Intent.EXTRA_SUBJECT, "Hello!");
                myIntent.putExtra(Intent.EXTRA_TEXT, "My highscore in Quizzi is very high! I bet you can't beat me except you are cleverer than me. Download the app now! https://play.google.com/store/apps/details?id=amapps.impossiblequiz");
                startActivity(Intent.createChooser(myIntent, "Share with:"));
            }
        });

        mQuestionLibrary.shuffle();

        setSupportActionBar((Toolbar) findViewById(R.id.nav_action));
        DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
        mDrawerLayout.addDrawerListener(mToggle);
        mToggle.syncState();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Able to see the Navigation Burger "Button"

        ((NavigationView) findViewById(R.id.nv1)).setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                    case R.id.nav_stats:
                        startActivity(new Intent(QuizActivity.this, Menu2.class));
                        break;
                    case R.id.nav_about:
                        startActivity(new Intent(QuizActivity.this, Menu3.class));
                        break;
                }
                return true;
            }
        });

        mScoreView = (TextView) findViewById(R.id.score_score);
        mQuestionView = (TextView) findViewById(R.id.question);
        mButtonChoice1 = (Button) findViewById(R.id.choice1);
        mButtonChoice2 = (Button) findViewById(R.id.choice2);
        mButtonChoice3 = (Button) findViewById(R.id.choice3);

        final List<Button> choices = new ArrayList<>();
        choices.add(mButtonChoice1);
        choices.add(mButtonChoice2);
        choices.add(mButtonChoice3);

        updateQuestion();

        //Code of the mediaplayer begins:

        for (final Button choice : choices) {
            choice.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                    if (choice.getText().equals(mAnswer)) {
                        try {
                            mp = new MediaPlayer();
                            if (playSounds) {
                                mp.setVolume(1, 1);
                            } else {
                                mp.setVolume(0, 0);
                            }

                            AssetFileDescriptor afd;
                            afd = getAssets().openFd("sample.mp3");
                            mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                            mp.prepare();

                        } catch (IllegalStateException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mp) {
                                mp.release();
                            }
                        });
                        mp.start();
                        updateScore();
                        updateQuestion();
                        Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();

                    } else {
                        try {
                            mp2 = new MediaPlayer();
                            if (playSounds) {
                                mp2.setVolume(1, 1);
                            } else {
                                mp2.setVolume(0, 0);
                            }
                            AssetFileDescriptor afd;
                            afd = getAssets().openFd("wrong.mp3");
                            mp2.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                            mp2.prepare();

                        } catch (IllegalStateException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        mp2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mp) {
                                mp.release();
                            }
                        });
                        mp2.start();

                        Toast.makeText(QuizActivity.this, "Wrong... Try again!", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(QuizActivity.this, Menu2.class);
                        intent.putExtra("score", mScore); // pass score to Menu2
                        startActivity(intent);
                    }
                }
            });
        }
    }

    //End mediaplayer main code
    private void updateQuestion() {
        if (mQuestionNumber < mQuestionLibrary.getLength()) {
            mQuestionView.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
            mButtonChoice1.setText(mQuestionLibrary.getChoice1(mQuestionNumber));
            mButtonChoice2.setText(mQuestionLibrary.getChoice2(mQuestionNumber));
            mButtonChoice3.setText(mQuestionLibrary.getChoice3(mQuestionNumber));
            mAnswer = mQuestionLibrary.getCorrectAnswer(mQuestionNumber++);
        } else {
            Toast.makeText(QuizActivity.this, "Last Question! You are very intelligent!", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(QuizActivity.this, Menu2.class);
            intent.putExtra("score", mScore);
            startActivity(intent);
        }
    }

    private void updateScore() {
        mScoreView.setText(String.valueOf(++mScore));

        SharedPreferences mypref = getPreferences(MODE_PRIVATE);
        int highScore = mypref.getInt("highScore", 0);

        if (mScore > highScore) {
            SharedPreferences.Editor editor = mypref.edit();
            editor.putInt("highScore", mScore);
            editor.apply();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return mToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
    }

    private void createDialog() {
        dialog = new Dialog(this);
        dialog.setTitle("Tutorial");
        dialog.setContentView(R.layout.popup_menu1_1);
        closeButton = (TextView) dialog.findViewById(R.id.closeTXT);
    }

    private void createDialog2() {
        dialog2 = new Dialog(this);
        dialog2.setTitle("Settings");
        dialog2.setContentView(R.layout.popup_menu1_2);
        closeButton2 = (TextView) dialog2.findViewById(R.id.closeTXT2);
        checkBoxmp = (CheckBox) dialog2.findViewById(R.id.ckeckBox);
    }
}


text:
Q: Как одним сервлетом передать запрос другому сервлету Как одним сервлетом передать запрос другому сервлету. Если сервлеты лежат в одном пакете какой будет  url.

A: Если я правильно понял Ваш вопрос, можете вызвать из первого сервлета request.getRequestDispatcher("<урл второго сервлета>").forward(request, response);


text:
Q: What's the meaning of "plenty sweet enough"?
"Sweeter than honey" may be plenty sweet enough.

What's the meaning of "plenty sweet enough"?
I guess it means that "sweeter than honey" is too much of sweet.
Am I right? If I'm right, how is it so?
I don't think 'plenty sweet enough' connotes any negative meaning.

A: Plenty sweet enough...
If something is plenty sweet enough, there's no need to make it even sweeter.  It's already quite sweet as it is.
Sweet enough = has sufficient sweetness.
Plenty sweet enough = has more than sufficient sweetness.

Mom, can I put some more honey in my oatmeal?
  -- No, it's plenty sweet enough.

"Plenty" there is an intensifying modifier, modifying "sweet enough".


text:
Q: Ionic 6 + Angular ion-button prevent to clear memory after page change I have a problem with Ionic 6 and ion-button. I use tabs and when I go to nested page and then click on back button page doesn't clear memory and I have memory leaks. I happens if I pass ion-button into ng-content. Such error happens even I just put native html button (just click me). If I pass into ng-content any other element such as ion-icon it works good.
I have the very simple test-component
@Component({
  selector: 'app-test-cmp',
  templateUrl: '<ng-content></ng-content>',
})
export class TestCmp {}

Here is my nested page
@Component({
  selector: 'app-test-page',
  templateUrl: `
    <ion-header>
      <ion-toolbar>
        <ion-buttons slot="start">
          <ion-back-button></ion-back-button>
        </ion-buttons>
        <ion-title>Test</ion-title>
      </ion-toolbar>
    </ion-header>

    <ion-content>
      <app-test-cmp><ion-card>anything here</ion-card></app-test-cmp>
    <ion-content>`,
})
export class TestPage {}

This code works well. Here is my memory snapshot.

But if I put ion-button into ion-card memory doesn't clear.
@Component({
  selector: 'app-test-page',
  templateUrl: `
    <ion-header>
      <ion-toolbar>
        <ion-buttons slot="start">
          <ion-back-button></ion-back-button>
        </ion-buttons>
        <ion-title>Test</ion-title>
      </ion-toolbar>
    </ion-header>

    <ion-content>
      <app-test-cmp><ion-button>Ionic button</ion-button></app-test-cmp>
    <ion-content>`,
})
export class TestPage {}

Here is memory snapshot

Please, any help/ideas/etc. WebView fails on iOS after surfing between pages
Update
It's somehow connected to ion-content
This code works correctly but crash animation, etc.
@Component({
  selector: 'app-test-page',
  templateUrl: `
    <ion-header>
      <ion-toolbar>
        <ion-buttons slot="start">
          <ion-back-button></ion-back-button>
        </ion-buttons>
        <ion-title>Test</ion-title>
      </ion-toolbar>
    </ion-header>

    <app-test-cmp><ion-button>Ionic button</ion-button></app-test-cmp>

    <ion-content>
      ......
    <ion-content>`,
})
export class TestPage {}


text:
Q: Value over threshold for n consecutive minutes Assume I have a table containing a set of data points, each consisting of a timestamp and a value. How would I write a query that returns true (1) if there are at least N consecutive records (ordered by timestamp) that are above a given value X, false (0) otherwise?
The following does this for 3 consecutive records, but does not work for the general case without building a dynamic query and adding more "and exists" cases:
truncate table tblData
insert into tblData values ('1-jul-2013 13:01:00', 64)
insert into tblData values ('1-jul-2013 13:02:00', 13)
insert into tblData values ('1-jul-2013 13:03:00', 7)
insert into tblData values ('1-jul-2013 13:04:00', 17)
insert into tblData values ('1-jul-2013 13:05:00', 7)
insert into tblData values ('1-jul-2013 13:06:00', 18)
insert into tblData values ('1-jul-2013 13:07:00', 9)
insert into tblData values ('1-jul-2013 13:08:00', 20)
insert into tblData values ('1-jul-2013 13:09:00', 12)
insert into tblData values ('1-jul-2013 13:10:00', 21)
insert into tblData values ('1-jul-2013 13:11:00', 22)
insert into tblData values ('1-jul-2013 13:12:00', 3)
insert into tblData values ('1-jul-2013 13:13:00', 22)
insert into tblData values ('1-jul-2013 13:14:00', 20)

declare @x as int = 10

select count(*)
from tblData a
where a.dt in
 (select dt from tblData b where b.value > @x and b.dt >= a.dt and b.dt < DATEADD(minute,1,a.dt)) and exists
 (select dt from tblData b where b.value > @x and b.dt >= DATEADD(minute,1,a.dt) and b.dt < DATEADD(minute,2,a.dt)) and exists
 (select dt from tblData b where b.value > @x and b.dt >= DATEADD(minute,2,a.dt) and b.dt < DATEADD(minute,3,a.dt))

Ideas?

A: Basically, you want a cumulative sum of a flag saying that the column exceeds the value @x.
It turns out that you can do this with some tricks using row_number().  Enumerate all the rows using row_number() (in time order).  Then, enumerate all the rows, partitioning by the flag.  The difference between these will be a constant that identifies a group of consecutive rows.  Then, with aggregation, we can get the longest length of consecutive values where the flag is true (or false):
select seqnum - seqnum_flag, count(*)
from (select d.*,
             row_number() over (order by dt) as seqnum,
             row_number() over (partition by (case when val > @x then 1 else 0 end)
                                order by dt) as seqnum_flag
      from tblData d
     ) d
where val > @x
group by (seqnum - seqnum_flag);

This returns each sequence and the length of it.  This should give you the information you need to proceed.
You can see it work on SQL Fiddle.

A: You can use an over ... rows N preceding clause to calculate the minimum over the last N rows.  For example, this displays 1 if this row and the last 3 rows have a value larger than 10:
select  *
,       case when min(val) over (order by dt rows 3 preceding) > 10 then 1 else 0 end
from    tblData

Example at SQL Fiddle.


text:
Q: How to get input text value I want to get a value in Java ADF using JavaScript. I tried many examples but got undefined or null value.
Do anyone know how to get the inputtext value in ADF using JavaScript?
And what are the configure?

A: To find component you can use method.
To get value from inputText use this.
var input= AdfPage.PAGE.findComponent("it1");
var value = input.getValue();

A:
*

*Read value from inputText

document.getElementById('pt1:r1:0:subform0base:userName::content').value

  notice:
      How to get the id like this "pt1:r1:0:subform0base:userName::content" ?
  just press "F12" and select you inputText in the browser usually,then you will see the id


text:
Q: Meaning of Universal generalization in Gödel's system I'm reading Gödel's famous paper "On Formally Undecidable Propositions of PM" and at one point he gives the following definition:

$c$ is defined to be the immediate consequence of $a$ and $b$ if $a$ is the formula  $\neg b\lor c$ or alternatively if $c$ is the formula $\forall v. a$

The first case is derived from modus ponens and it is also explained in this answer.
My question is:

*

*What is the meaning of using "universal generalization" as a deduction rule? Is it something useful just from a formal standpoint, to make logical proofs easier, or is there a deeper reason for it?

Correct me if I'm wrong, but it seems to me that in conjunction with the other axiom
$$\left(\forall v.a\right) \rightarrow \mathrm{sub}\; a\left( \begin{array}{c} v \\ c\end{array}\right)$$
where $c$ is "suitably chosen", the generalization rule implies that formulas with free variables are allowed to be true, and in fact they have the same truth value as their generalization.
As an example of this, the formula that can be synthesized in
$$x_1=x_1$$
should be logically equivalent to
$$\forall x_1 .\: x_1=x_1$$
in Gödel's system.
So my second complementary part of the question is:

*What would happen if we were to remove this deduction rule? Could everything work regardless without it with some adjustments? Or would it be much more complicated that it seems?  And why are formulas with free variables allowed to be true in the first place?

Formulas with free variables would still exist but will not allowed to be true, I suppose. And I assume you would need other axioms to account for things like deriving $\forall v.\: a\rightarrow c$ from $\forall v.\: a\rightarrow b$ and $\forall v.\: b\rightarrow c$ . Is that really doable in some way or not?
Summing up, I'm asking why universal generalization is used as a deduction rule and whether it is possible to remove it or not in Gödel's system.


text:
Q: Проксирование nginx websocket Как правильно сделать проксирование трафика на вебсокете в конфиге nginx?
http://nginx.org/ru/docs/http/websocket.html
Допустим если сайт у нас расположен на 80 порте, а вебсокет по адресу ws://site.ru:2000

A: Вопрос решался просто:
в http{} дописываем
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

upstream websocket {
  server ваш_ип:2000;
}

в server{} дописываем
location /websocket {
    proxy_pass http://websocket;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

в nginx.conf дописываем
keepalive_timeout 604800;
proxy_connect_timeout 604800;
proxy_send_timeout 604800;
proxy_read_timeout 604800;

вебсокет открываем таким образом
var socket = new WebSocket("ws://ваш_ип_или_домен/websocket");

A: Не работает такой конфиг.
Выдается ошибка в консоли браузера:

WebSocket connection to ws://site.com/ws failed: Error during
  WebSocket handshake: Unexpected response code: 200

По этой ошибке очень-очень много вопросов по всем форумам, но ни одного ответа.
Такое ощущение, что не умеет реально nginx ws проксировать.
Проблема лечится легко, просто надо в js коде соединение с ws устанавливать с явным указанием порта
var socket = new WebSocket("ws://ваш_ип_или_домен:9999");

В этом случае сразу все работает.
Отсюда вопрос: зачем вообще проксировать ws через nginx?
Проверить Origin (хост с которого подключаются к ws) легко может сам ws сервер.
На ум приходит только одно: проксировать надо, чтобы избежать а-ля ddos атак на порт ws, чтобы обращения сначала фильтровал nginx а потом уже ws сервер.
Потому что теоретически ws сервер завалится гораздо быстрее nginx.
Есть ли в этом смысл - защищать таким образом ws сервер? Кто может обосновать?