text:
Q: StaleElementReferenceException in Selenium WebDriver java test org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up
Command duration or timeout: 30.02 seconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '2.18.0', revision: '15704', time: '2012-01-27 17:37:17'
System info: os.name: 'Windows XP', os.arch: 'x86', os.version: '5.1', java.version: '1.6.0_17'
Driver info: driver.version: RemoteWebDriver
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:147)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:113)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:439)
    at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:231)
    at org.openqa.selenium.remote.RemoteWebElement.click(RemoteWebElement.java:72)
    at com.harleydavidson.modelyear.selenium2.testcase.ImageTest.checkColor(ImageTest.java:79)
    at com.harleydavidson.modelyear.selenium2.testcase.ImageTest.chooseModel(ImageTest.java:62)
    at com.harleydavidson.modelyear.selenium2.testcase.ImageTest.testImage(ImageTest.java:28)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.openqa.selenium.remote.ErrorHandler$UnknownServerException: Element not found in the cache - perhaps the page has changed since it was looked up
Build info: version: '2.18.0', revision: '15704', time: '2012-01-27 17:37:17'
System info: os.name: 'Windows XP', os.arch: 'x86', os.version: '5.1', java.version: '1.6.0_17'
Driver info: driver.version: unknown
    at .(resource://fxdriver/modules/atoms.js:9557)
    at .(resource://fxdriver/modules/atoms.js:10153)
    at .(file:///C:/DOCUME~1/npolic/LOCALS~1/Temp/anonymous3371533678733192941webdriver-profile/extensions/fxdriver@googlecode.com/components/command_processor.js:10200)
    at .(file:///C:/DOCUME~1/npolic/LOCALS~1/Temp/anonymous3371533678733192941webdriver-profile/extensions/fxdriver@googlecode.com/components/command_processor.js:10219)
    at .(file:///C:/DOCUME~1/npolic/LOCALS~1/Temp/anonymous3371533678733192941webdriver-profile/extensions/fxdriver@googlecode.com/components/command_processor.js:10026)

Mycode has been written like this. It is for consecutive actions. First action is working fine inside loop for first time. when second loop started, it is throwing StaleElementReferenceException . So please help me , how to perform multiple actions one by one..
List<WebElement> colorButtons = driver.findElements(By.xpath("/html/body/div[4]/div[2]/div/div[4]/div[2]/div/img"));

for(WebElement colorButton : colorButtons)
{
    colorButton.click();
}

Regards
Narsi

A: Basically the StaleElementReferenceException happens when the page is still loading, or changing the content - so some element was there, but something happened and that element ios no more in the DOM.
What happens on the page when you manually click the colorButton? I expect that the page starts loading, or shows something.
You should probably add some waiting, or clicking somewhere else on the page

A: You can try this:
List<WebElement> elements = driver.findElements(By. xpath abc));

for(int i=0; i<elements.size(); i++){

    WebElement ele = null;

    if(i<3){

    List<WebElement> elements2 = driver.findElements(By. xpath abc);
    ele = elements2.get(i);
}


text:
Q: jQuery Lite Accordion Image Positioning I am looking at jQuery LiteAccordion V2. I use everything as default set up as they can be downloaded from: https://github.com/nikki/liteAccordion, as well as the images. I am kind of learning for this plug in.
However, I have encountered a problem where the image is not sitting at the right place. Please take a look at below screen shot:

I am using Firefox. So with the element inspector, you can see that the image is going a little bit to the bottom and to the right. I do not change all settings. They are still the same. I have followed guide provided in the website.
I did try to look at css file, I could not find one that control the image position.
Please, any thoughts would be very helpful for me.
Thank you so much in advance for help.
Edit - Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Lite Accordion Test Lab</title>

        <link href="css/liteaccordion.css" rel="stylesheet" type="text/css" />

Slide One

Slide 1

Slide Two

Slide 2

Please enable JavaScript to get the full experience.

The css can be found here: https://github.com/nikki/liteAccordion/blob/master/css/liteaccordion.css
I don't change the css code, it's still the same as it is.
You can check the sample at: http://jsfiddle.net/aJhYk/1/

A: You haven't compensated for the
's default margin.  Easiest thing to do would be to remove the
 element.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using only pull to refresh functionality from ionic I built a Chrome App with Angular Material Design and ported it to android using Cordova for Chrome Apps tool. I included ionic framework into my app and the "pull to refresh" functionality works like a charm with just a couple of lines of changes to my template.
Since ionic is a mobile first framework for developing hybrid mobile apps, it is interfering with the back button actions and scroll bars on android as well as my Chrome App, which is a bit of a problem.
I have tried other plug-ins available on github, but nothing beats ionic's pull-to-refresh.
Like jquery-ui, is it possible to custom download pieces of ionic framework? I just need the ion-refresher component. I am trying to avoid doing a custom hand-rolled one at this point of time.
Any direction regarding this would be really helpful.

A: for Ion-refresh component you have use $cachefactory function which is defined in angularJS


text:
Q: Re: select which PHP variables to emit for android I use HttpResponse to capture a JSON from a PHP script (call it script #1). The script emits the JSON via print_r().
Problem : the PHP incldues a script (call it script #2) which also uses print_r to emit a variable. I also use this script independently in another part of my program.
The issue is that my httpResponse function in android captures the print_r emission in script #2 rather than the print_r in script #1. How can I work around this?
Here is the outline of what's happening:
Script #2 (contains a print_r)-> script #1 (uses data in #2 and emits a print_r)-> Android HttpResponse collects print_r from #2 instead of from #1.


text:
Q: pandas and numpy: TypeError: cannot unpack non-iterable int object Please help me solve this, I tried many solution but it doesn't work. In the Jupyter Notebook the Output I want are getting display but in Streamlit its getting error. I am newbie practicing ML.
`
    df = pd.read_csv("book1.csv")
    corrMatrix = df.corr(method='pearson')
    corrMatrix.head(17)

    def get_similar(question, rating):
        similar_ratings = corrMatrix[question] * (rating - 2.5)
        similar_ratings = similar_ratings.sort_values(ascending=False)
        return similar_ratings

    ratings = [(q1), (q2), (q3), (q4), (q5), (q6), (q7), (q8), (q9), (q10),
               (q11), (q12), (q13), (q14), (q15), (q16), (q17)]

    similar = pd.DataFrame()

    for question, rating in ratings:
         similar.append(get_similar(question, rating), ignore_index=True)

         similar.head(10)

         similars = similar.sum().sort_values(ascending=False).head(3)

         df1 = pd.DataFrame(similar)

    st.write(df1)`

This is the Error I get.
Traceback (most recent call last):
File "c:\users\admin\desktop\thesissys\venv\lib\site-
packages\streamlit\scriptrunner\script_runner.py", line 554, in _run_script
exec(code, module.__dict__)
File "C:\Users\admin\Desktop\ThesisSys\venv\app.py", line 71, in <module>
show_predict()
File "C:\Users\admin\Desktop\ML\venv\predict_page.py", line 386, in show_predict
for question, rating in ratings:
TypeError: cannot unpack non-iterable int object


text:
Q: Problem with Postgresql, LIKE gives double results I am currently working with Postgresql and I am facing a problem.
I have two tables "question" and "question_detail" in which there are codes. In "question_detail" are the codes including subcode so e.g. TB01Q07, TB01Q07a, TB01Q08_SQ002. Now I wanted to use the command LIKE to see if the table "question" also contains these records. But in "question.code" there are only codes without the following underscore. This is a table that was given to me, I find this somehow very stupid.
The problem is that when I search with LIKE the value TB01Q07a is listed twice. This is also understandable to me, since searching for TB01Q07% also returns the value TB01Q07a.
Does anyone know of a way to search only for TB01Q07a without it resulting in TB01Q07% as TB01Q07a?
Command
SELECT qd.code, qd.label, q.type
FROM public.question q,
     public.question_detail qd
where CASE
         WHEN qd.code = q.code THEN qd.code = q.code
         ELSE qd.code like CONCAT(q.code,'%')
      END;

question
| code     | type    |
| ---------|-------- |
| TB01Q07  | comment |
| TB01Q07a | comment |
| TB01Q08  | option  |

**question_detail**

```none
| code           | label |
| -------------- | ------|
| TB01Q07        | AB01 |
| TB01Q07a       | AB02 |
| TB01Q08_SQL002 | AB03 |

I ran the SQL and wanted the TB01Q07a value to appear only once and not be listed twice.

A: I think I have found a solution with distinct on.
SELECT distinct on (qd.code) q.id_question,qd.code, q.question, q.question_type
FROM public.question q, public.question_detail qd
where qd.code like CONCAT(q.code,'%');

A: like('TB01Q07%') matches both TB01Q07 and TB01Q07a, so you get two rows for TB01Q07 and one row for TB01Q07a.
You need to be more precise and include the underscore. Also make sure it's escaped, _ means any one character in a like.
There is no need for a case, use or. Avoid using multiple from statements, use an explicit join with an explicit on. This is clearer and gives you more control over the join.
select qd.*, q.*
from public.question q
join public.question_detail qd
  on qd.code = q.code OR qd.code like q.code || '\_%'

Demonstration.

Note: this problem doesn't exist if you use foreign keys. Assign unique IDs to question and reference them in question_detail. This is faster, shields you from changes to the question code, and ensures the referred to question exists.


text:
Q: set class ignoring defined comp fn and errors on default comparison I am using a custom Set class that is basically the same as the STL Set class
The problem is that I am somehow implementing it incorrectly and the default comparison function is used rather than a comparison I defined.
Set<Lexicon::CorrectionT> Lexicon::suggestCorrections(Lexicon::MatchesT & matchSet)
{
    Set<CorrectionT> suggest(compareCorr); //ordered Set
    suggestCorrectionsHelper(root, suggest, 0, matchSet.testWord, 0, matchSet.testTime);
    return suggest;
}

int compareCorr(Lexicon::CorrectionT a, Lexicon::CorrectionT b)
{
    if (a.editDistance < b.editDistance)
        return -1;
    else if (a.editDistance == b.editDistance)
            return 0;
    else
        return 1;
}

struct CorrectionT {
    int editDistance; //stackItems
    string suggestedWord; //stackItems
};

Some research:

*

*The class library

*An issue with the same class - suggested that the STL Set class is used, in this case I might still need help understanding how to define the comparison function, so posting question

I have 19 C2784 errors all relating to some form of "error C2784: 'bool std::operator ==(const std::_Tree<_Traits> &,const std::_Tree<_Traits> &)' : could not deduce template argument for 'const std::_Tree<_Traits> &' from 'Lexicon::CorrectionT'
and referencing this code
template <typename Type>
int OperatorCmp(Type one, Type two) {
    if (one == two) return 0;
    if (one < two) return -1;
    return 1;
}

My question: how do you suggest correcting this?
Attempt at changing default definition type:
#include "lexicon.h"

//template <typename Type>
int OperatorCmp(Lexicon::CorrectionT one, Lexicon::CorrectionT two) {
    if (one.editDistance == two.editDistance) return 0;
    if (one.editDistance < two.editDistance) return -1;
    return 1;
}

#endif

A: The comparison function for STL set must be a Strict Weak Ordering, so that class is not the same as an STL set.
The error indicates the default OperatorCmp is being used, I don't know why, but you could make that default one work by defining operator< and operator== for your CorrectionT type.


text:
Q: Is "A Moveable Feast" more than home catering? I read Hemingway's A Moveable Feast before I knew the term describing moveable feast days on the calender. Comparing Hemingway's famous quote about Paris:

"If you are lucky enough to have lived in Paris as a young man, then wherever you go for the rest of your life, it stays with you, for Paris is a moveable feast."

with what happens in the liturgical calender, I can't see what he's talking about.
So, a feast date is chosen because of where it falls in relation to some other annually changing dates; thus it "moves" every year. How is Paris like one of these feast dates, in the way Hemingway describes it? I understand him to mean that you may leave Paris, but Paris never leaves you. But that doesn't mean it stays the same. You don't stay the same. And other places stay with you too. Easter stays the same--same celebration for the same reason, no matter what you do.
Phrase finder traces its figurative usage back to 1882, before Hemingway, to a newspaper from Bismarck, North Dakota:

The most sublime creation of modern times is the ideal woman of the average man. She is a migratory bird, a sort of movable feast as it were.

But that doesn't have much bearing on holidays that occur on different days from year to year either. The ideal woman is different for every man, and this quote makes her sound fleeting, out of reach. True, the piece hedges with "as it were", but it seems that they are using the expression somewhat idiomatically--the "as it were" suggests that.
From 2000, a book called Spirituality, Healing and Medicine: Return to Silence states:

"Indeed, maybe the reason that we fail to categorize health is just that we do not wish to locate it, it is a moveable feast."

This idiomatic usage of the term suggests that health is hard to codify or pin down, which, again, doesn't relate with a religious holiday that is classifiable, though it moves.
A radio broadcaster was talking about a Christmas party here in Barcelona that would be at the beach this year. It was on a hotel roof last year. He called it "a moveable feast". He's right; it is a moveable feast, but not by any relationship to the idiomatic use of the term. I'm italicizing idiomatic because, I can't grasp the sense of the idiom, though it exists. In fact, the free dictionary defines it and then discounts its figurative usage.

*

*Lit. a religious holiday that is on a different date from year to year. Easter is the best known movable feast.

*Fig. a meal that is served in motion or with different portions of the meal served at different locations. (Jocular or a complete misunderstanding of {1} but in wide use.) We enjoyed a real movable feast on the train from Washington to Miami.

This definition seems to be the least like the other usages, but googling "a moveable feast catering" shows that people around the anglophone world are jocularly using the term this way.
My question isn't to do with understanding Hemingway's use of the expression, but what the expression "A Moveable Feast" means at all. Is it right to call it an expression or phrase or idiom? Or did Hemingway just hoodwink us into using some clever bit of liturgical jargon whenever we wanted to say something is constantly changing? If not, if it describes something, what does it describe?

A: Thank you for this inquiry. It is rich in meaning.
Movable feast was historically liturgical, with Easter, as you pointed out, being its most famous example. Hemingway probably appropriated it in his notes for his heady cultural experiences in Paris, but in fact, it was his wife Mary who named the book which was published posthumously. The story behind it is charming.
It probably started out as a liturgical appellation, but was taken over by the public to mean all the things you mentioned, including progressive dinners. Its recent use has most commonly been in magazines, explaining why it is used with abandon for any purpose desired.
Therefore, you are correct to say it is not an idiom. I would say it was first an appellation for a feast day which has been appropriated by the secular public as a phrase serving a number of possible uses.

A: The phrase has an odd poetry to it, and the dictionary usage isn't part of most people's general conversation, so people have freely adapted it based on the words themselves rather than by strict analogy to the actual definition.
In addition, the secondary definition of a traveling meal --sometimes also called a progressive dinner --quite possibly rivals the original definition in wideness of usage.
As far as Hemingway's usage, it reminds me of another quote --I'm afraid I couldn't track down the speaker or exact phrasing --to the effect that "childhood is the meal that we feast on for the rest of our lives," meaning that the experiences of our youth continue to nurture us spiritually even as we travel away from them, a moveable feast.
EDIT:  I found the quote I mentioned above, it is Leon Uris, from his book Trinity: "If you're lucky enough to fall in love, that's one thing. Otherwise all that was ever truly beautiful to me was boyhood. It's the meal we sup on for the rest of our lives. Love puts the icing on life. But if you don't find it...you must call on your childhood memories over and over till you do."


text:
Q: facebook user & friend permission not showing up on scopes I have a simple login app to utilize oAuth for facebook.
I will need to access a few things about the user so i added a few parameters in theUser & Friend Permissions

I waited over 24 hours for the servers to propagate but when i debug the token, i dont see these permissions added to the scope

I grabbed the token by:
<?php
require '../src/facebook.php';
$facebook = new Facebook(array(
        'appId'  => '**************',
    'secret' => '**********************************'
));

// Get User ID
$user = $facebook->getUser();

$token = $facebook->getAccessToken();
echo $token;

if ($user) {
    try {
        $facebook->setFileUploadSupport(true);

        $album = $facebook->api('/me/albums ');
        print_r($album);

    } catch (FacebookApiException $e) {
        error_log($e);
        $user = null;
    }
}

?>
<!doctype html>

        <title>php-sdk</title>

php-sdk

        <?php if ($user): ?>
            <a href="<?php echo $logoutUrl; ?>">Logout
        <?php else: ?>

                Login using OAuth 2.0 handled by the PHP SDK:
                <a href="<?php echo $loginUrl; ?>">Login with Facebook

        <?php endif ?>

PHP Session

<?php print_r($_SESSION); ?>

        <?php if ($user): ?>

You

            <img src="https://graph.facebook.com/<?php echo $user; ?>/picture">

Your User Object (/me)

<?php print_r($user_profile); ?>

        <?php else: ?>
            You are not Connected.
        <?php endif ?>

        <?php //echo $naitik['name']; ?>

What am I missing?
any help please, thank you.

A: Changing needed permission after user installed make you need to ask for the new permission.
So you can uninstall and install again, or make a JS to check if your user have the necessary permission and, if not, ask using FB.ui


text:
Q: PHP Curl not executing I am trying to retrieve the HTML from a user profile on Instagram using cURL.
I am new to cURL so do not know the cause of this error.
Nothing happens when the cURL is executed , the page seems to refresh?
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.instagram.com/zohebchaudhry1/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookiess.txt');
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookiess.txt');
curl_setopt($ch ,CURLOPT_TIMEOUT , 10);
curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36" );
$html = curl_exec($ch);
curl_close($ch);
echo $html;

above is the PHP cURL code.

A: It appears that cURL is working, however you're unable to see the output because printing HTML may not be desired.

I suggest replacing echo $html; with echo htmlentities($html);

Read more: php.net/htmlentities


text:
Q: "What I feel [is] more important" - should I include "is"? "What I feel more important is for you to go home right now."
"What I feel is more important is for you to go home right now."
Which sentence is correct? Also, is there a rule that is being followed here? I am pretty sure I've heard people use the first form. Is that a slang? or is the "is" in the second sentence redundant?

A: For a speaker of British English, the correct sentence is definitely the second. I have never heard the first sentence spoken, find it quite jarring to read, and have tried and failed to think of any context (slang or otherwise) in which it wouldn't sound totally wrong.

A: In American English, the second is the correct and idiomatic sentence. The first is wrong. You could say the first if you dropped "what" from it, which would require twisting the sentence a little bit. For example,

I feel more important when I am with her.

A: How about the following:

"To me, what is more important is that you go home now."

Or,

"That you go home now is more important to me [than ____ ]."

Or,

"I feel it is more important for you to go home now."

Or,

"I think your going home is more important than ____."

Or,

"What I feel to be more important is that you go home now."

A: The reason why the first sentence "What I feel more important is for you to go home right now" appears ungrammatical is quite complex and has to do with the expletive (or dummy) it and cleft sentences.
The expletive it has the function of anticipating what follows:

I find it useful to take notes while reading.
I believe it necessary that I know who I'm talking to.
I think it important for you to go now.

If you wish to emphasise what you find useful, important, etc., you can make a cleft sentence as follows:

What I find useful is to take notes while reading.
What I believe necessary is that I know who I'm talking to.
What I think important is for you to go now.

On this basis, the OP's cleft sentence is derived from the sentence:

I feel it more important for you to go home right now.

But for me, the expletive it does not sound right with feel, and hence the cleft sentence based on it also does not sound right. The more usual starting point would be:

I feel (that) it is more important for you to go home right now

resulting in the cleft sentence (and second OP example):

What I feel is more important is for you to go home right now.


text:
Q: Garbage collection when using anonymous delegates for event handling UPDATE
I have combined various answers from here into a 'definitive' answer on a new question.
Original question
In my code I have an event publisher, which exists for the whole lifetime of the application (here reduced to bare essentials):
public class Publisher
{
    //ValueEventArgs<T> inherits from EventArgs
    public event EventHandler<ValueEventArgs<bool>> EnabledChanged;
}

Because this publisher can be used all over the place, I was quite pleased with myself for creating this little helper class to avoid re-writing the handling code in all subscribers:
public static class Linker
{
    public static void Link(Publisher publisher, Control subscriber)
    {
         publisher.EnabledChanged += (s, e) => subscriber.Enabled = e.Value;
    }

    //(Non-lambda version, if you're not comfortable with lambdas)
    public static void Link(Publisher publisher, Control subscriber)
    {
         publisher.EnabledChanged +=
             delegate(object sender, ValueEventArgs<bool> e)
             {
                  subscriber.Enabled = e.Value;
             };
    }
}

It worked fine, until we started using it on smaller machines, when I started getting the occasional:
System.ComponentModel.Win32Exception
Not enough storage is available to process this command

As it turns out, there is one place in the code where subscribers controls are being dynamically created, added and removed from a form. Given my advanced understanding of garbage collection etc (i.e. none, until yesterday), I never thought to clear up behind me, as in the vast majority of cases, the subscribers also live for the lifetime of the application.
I've fiddled around a while with Dustin Campbell's WeakEventHandler, but it doesn't work with anonymous delegates (not for me anyway).
Is there anyway out of this problem? I really would like to avoid having to copy-paste boiler-plate code all over the shop.
(Oh, and don't bother with asking me WHY we are creating and destroying controls all the time, it wasn't my design decision...)
(PS: It's a winforms application, but we've upgraded to VS2008 and .Net 3.5, should I consider using the Weak Event pattern?)
(PPS: Good answer from Rory, but if anyone can come up with an equivalent to the WeakEventHandler which avoids me having to remember to explicitly UnLink/Dispose, that would be cool...)
EDIT I must admit that I worked around this problem by "recycling" the controls in question. However the workaround has come back to haunt me as the 'key' I was using is apparently non-unique (sob). I've just discovered other links here (tried this - seems to be a bit too weak - GC clears delegates even if target is still alive, same problem with s,oɔɯǝɹ answer below), here (forces you to modify publisher, and doesn't really work with anonymous delegates) and here (cited-as-incomplete by Dustin Campbell).
It occurs to me that what I'm looking for may be semantically impossible - closures are designed to 'hang around even after I'm gone'.
I've found another workaround, so I'll stick with that, pending a voice from the gods.

A: If you retain a reference to the anonymous delegate and then remove it when the controls are removed from the form that should allow both the controls and the anonymous delegates to be garbage collected.
So something like this:
public static class Linker
{

    //(Non-lambda version, I'm not comfortable with lambdas:)
    public static EventHandler<ValueEventArgs<bool>> Link(Publisher publisher, Control subscriber)
    {
         EventHandler<ValueEventArgs<bool>> handler = delegate(object sender, ValueEventArgs<bool> e)
             {
                  subscriber.Enabled = e.Value;
             };
         publisher.EnabledChanged += handler;
         return handler;
    }

    public static void UnLink(Publisher publisher, EventHandler<ValueEventArgs<bool>> handler)
    {
        publisher.EnabledChanged -= handler;
    }

}

See Unsubscribe anonymous method in C# for an example of removing delegates.

A: I know that this question is ancient, but hell - I found it, and I figure that others might as well. I'm trying to resolve a related issue, and might have some insight.
You mentioned Dustin Campbell's WeakEventHandler - it indeed cannot work with anonymous methods by design. I was trying to fiddle something together that would, when I realized that a) in 99% of cases I'd need something like this his original solution would be safer, and b) in those few cases where I have to (note: have to, not "want to because lambdas are so much prettier and concise") it's possible to make it work if you get a little clever.
Your example seems like exactly the kind of one-off case where getting a little tricky can result in a fairly concise solution.

public static class Linker {
    public static void Link(Publisher publisher, Control subscriber) {
        // anonymous method references the subscriber only through weak
        // references,so its existance doesn't interfere with garbage collection
        var subscriber_weak_ref = new WeakReference(subscriber);

        // this instance variable will stay in memory as long as the  anonymous
        // method holds a reference to it we declare and initialize  it to
        // reserve the memory (also,  compiler complains about uninitialized
        // variable otherwise)
        EventHandler<ValueEventArgs<bool>> handler = null;

        // when the handler is created it will grab references to the  local
        // variables used within, keeping them in memory after the function
        // scope ends
        handler = delegate(object sender, ValueEventArgs<bool> e) {
            var subscriber_strong_ref = subscriber_weak_ref.Target as Control;

            if (subscriber_strong_ref != null)
                subscriber_strong_ref.Enabled = e.Value;
            else {
                // unsubscribing the delegate from within itself is risky, but
                // because only one instance exists and nobody else has a
                // reference to it we can do this
                ((Publisher)sender).EnabledChanged -= handler;

                // by assigning the original instance variable pointer to null
                // we make sure that nothing else references the anonymous
                // method and it can be collected. After this, the weak
                //  reference and the handler pointer itselfwill be eligible for
                // collection as well.
                handler = null;
            }
        };

        publisher.EnabledChanged += handler;
    }
}

The WPF Weak Event pattern is rumored to come with a lot of overhead, so in this particular situation I wouldn't use it. Furthermore, referencing the core WPF library in a WinForm app seems a little heavy as well.

A: Some sample code i made recently, based on WeakReference:
// strongly typed weak reference
public class WeakReference<T> : WeakReference
    where T : class
{
    public WeakReference(T target)
        : base(target)
    { }

    public WeakReference(T target, bool trackResurrection)
        : base(target, trackResurrection)
    { }

    public new T Target
    {
        get { return base.Target as T; }
        set { base.Target = value; }
    }
}

// weak referenced generic event handler
public class WeakEventHandler<TEventArgs> : WeakReference<EventHandler<TEventArgs>>
    where TEventArgs : EventArgs
{
    public WeakEventHandler(EventHandler<TEventArgs> target)
        : base(target)
    { }

    protected void Invoke(object sender, TEventArgs e)
    {
        if (Target != null)
        {
            Target(sender, e);
        }
    }

    public static implicit operator EventHandler<TEventArgs>(WeakEventHandler<TEventArgs> weakEventHandler)
    {
        if (weakEventHandler != null)
        {
            if (weakEventHandler.IsAlive)
            {
                return weakEventHandler.Invoke;
            }
        }

        return null;
    }
}

// weak reference common event handler
public class WeakEventHandler : WeakReference<EventHandler>
{
    public WeakEventHandler(EventHandler target)
        : base(target)
    { }

    protected void Invoke(object sender, EventArgs e)
    {
        if (Target != null)
        {
            Target(sender, e);
        }
    }

    public static implicit operator EventHandler(WeakEventHandler weakEventHandler)
    {
        if (weakEventHandler != null)
        {
            if (weakEventHandler.IsAlive)
            {
                return weakEventHandler.Invoke;
            }
        }

        return null;
    }
}

// observable class, fires events
public class Observable
{
    public Observable() { Console.WriteLine("new Observable()"); }
    ~Observable() { Console.WriteLine("~Observable()"); }

    public event EventHandler OnChange;

    protected virtual void DoOnChange()
    {
        EventHandler handler = OnChange;

        if (handler != null)
        {
            Console.WriteLine("DoOnChange()");
            handler(this, EventArgs.Empty);
        }
    }

    public void Change()
    {
        DoOnChange();
    }
}

// observer, event listener
public class Observer
{
    public Observer() { Console.WriteLine("new Observer()"); }
    ~Observer() { Console.WriteLine("~Observer()"); }

    public void OnChange(object sender, EventArgs e)
    {
        Console.WriteLine("-> Observer.OnChange({0}, {1})", sender, e);
    }
}

// sample usage and test code
public static class Program
{
    static void Main()
    {
        Observable subject = new Observable();
        Observer watcher = new Observer();

        Console.WriteLine("subscribe new WeakEventHandler()\n");
        subject.OnChange += new WeakEventHandler(watcher.OnChange);
        subject.Change();

        Console.WriteLine("\nObserver = null, GC");
        watcher = null;
        GC.Collect(0, GCCollectionMode.Forced);
        GC.WaitForPendingFinalizers();

        subject.Change();

        if (Debugger.IsAttached)
        {
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
    }
}

Generates the following output:
new Observable()
new Observer()
subscribe new WeakEventHandler()

DoOnChange()
-> Observer.OnChange(ConsoleApplication4.Observable, System.EventArgs)

Observer = null, GC
~Observer()
DoOnChange()
~Observable()
Press any key to continue . . .

(Note that unsubscribing (-=) doesn't work)

A: Building further on Egor's answer, I wanted to try and build a version where I didn't have to determine in advance which event I want to attach to.
I've only managed to make it work with generic event handlers: for 'standard' event handlers (eg. FormClosingEventHandler), it's a bit tricky, because you can't have a type constraint where T : delegate (unless your name ends with Pony).
private static void SetAnyGenericHandler<S, T>(
     Action<EventHandler<T>> add,     //to add event listener to publisher
     Action<EventHandler<T>> remove,  //to remove event listener from publisher
     S subscriber,                    //ref to subscriber (to pass to consume)
     Action<S, T> consume)            //called when event is raised*
         where T : EventArgs
         where S : class
{
    var subscriber_weak_ref = new WeakReference(subscriber);
    EventHandler<T> handler = null;
    handler = delegate(object sender, T e)
    {
        var subscriber_strong_ref = subscriber_weak_ref.Target as S;
        if(subscriber_strong_ref != null)
        {
            Console.WriteLine("New event received by subscriber");
            consume(subscriber_strong_ref, e);
        }
        else
        {
            remove(handler);
            handler = null;
        }
    };
    add(handler);
}

(*I did try EventHandler<T> consume here, but the calling code gets ugly because you have to cast s to Subscriber in the consume lambda.)
Calling code example, taken from example above:
SetAnyGenericHandler(
    h => publisher.EnabledChanged += h,
    h => publisher.EnabledChanged -= h,
    subscriber,
    (Subscriber s, ValueEventArgs<bool> e) => s.Enabled = e.Value);

Or, if you prefer
SetAnyGenericHandler<Subscriber, ValueEventArgs<bool>>(
    h => publisher.EnabledChanged += h,
    h => publisher.EnabledChanged -= h,
    subscriber,
    (s, e) => s.Enabled = e.Value);

It would be nice to be able to pass in the Event as just one parameter, but you can't access add/remove from an event any more than you can access get/set from a property (without doing yucky reflexion stuff, I think).


text:
Q: Infinite geodesic rays leaving a K-quasiconvex subgroup stay K-close to it. I am going through some basic properties of $\delta$-hyperbolic spaces and groups and I am having some difficulties proving precisey some things that are anyway intuitively clear to me.
Let $G$ be a $\delta$-hyperbolic group and $H \subset G$ a $K$-quasiconvex subgroup, i.e. geodesics joining points of $H$ lie in the $K$-neighbourhood of $H$. I want to prove a similar statement for infinite geodesics starting at some element of $H$ and converging at infinity to some limit point of $H$.
More precisely let $\partial G$ denote the Gromov boundary of $G$ and $\Lambda (H)$ the limit set of $H$, i.e. the subset of $\partial G$ of accumulation points for sequences from $H$. Now take a geodesic ray $\gamma : [0,+\infty [ \to G$ such that $\gamma (0)=h\in H$ and $\gamma \to \xi \in \Lambda (H)$ at infinity. I want to prove that $\gamma$ lies in the $K$-neighbourhood of $H$.
What I understand: I can approximate $\gamma$ with finite-length geodesics $\gamma_n$ leaving $h$ and coming back to $H$ at some $h_n \in H$, where $\{ h_n \}$ are a sequence in $H$ converging at infinity to $\xi$. By $K$-quasiconvexity, $\gamma_n$ lies in the $K$-neighbourhood of $H$ for every $n$, so this should remain true passing to the limit $n\to \infty$.
To make this hand-waving precise, we need a notion of convergence for geodesic rays in $\overline{G}=G \cup \partial G$ (which of course we have), but I would like to see a more elementary proof of this fact, maybe something that builds a convenient geodesic polygon and then uses nothing more than the definitions of hyperbolicity and quasiconvexity.

A: As stated, your result is in fact false. For example, take $G= \mathbb{Z} \times \mathbb{Z}_2$ and $H= \mathbb{Z} \times \{0\}$; with respect to $\{(1,0),(0,1)\}$, the Cayley graph of $G$ looks like a ladder $$\mathbb{R} \times \{0,1\} \cup \bigcup\limits_{n \in \mathbb{Z}} \{ n \} \times [0,1]$$ and $H$ is a $0$-quasiconvex (ie. convex) subgroup, and of course $G$ is hyperbolic (it is quasi-isometric to $\mathbb{Z}$). Now let $\gamma$ be the geodesic whose points are
$$(0,0), (0,1), (1,1), (2,1), (3,1), (4,1), \dots$$
Clearly, the ray $\gamma$ converges to a point of $\Lambda(H)= \partial G$, but it does not belong to the $0$-neighborhood of $H$. However, it belongs to the $1$-neighborhood, and indeed your result becomes true with a little modification:
Property: Let $G$ be a $\delta$-hyperbolic group, $H$ a $K$-quasiconvex subgroup and $\gamma$ a ray with $\gamma(0) \in H$ converging to some $\xi \in \Lambda(H)$. Then $\gamma$ belongs to the $(K+8\delta)$-neighborhood of $H$.
Sketch of proof. Let $(h_n) \subset H$ be a sequence converging to $\xi$, with $h_0= \gamma(0)$. Choose a sequence of geodesic segments $[h_0,h_1], [h_0,h_2], \dots$ and use Ascoli theorem to find a subsequence converging to some ray $r$. Now, $r$ is in the $K$-neighborhood of $H$; because $r$ and $\gamma$ converges to the same end, $\sup\limits_{t \geq 0} d(r(t),\gamma(t)) \leq 8 \delta$[1] and the conclusion follows. $\square$
The bound $K+8\delta$ is probably not optimal.
[1] I think it is a classical result. Unfortunately, the only reference I know is in French: P. de la Harpe et E. Ghys, Sur les groupes hyperboliques, chapitre 7, corollaire 3.


text:
Q: How to synchronise writes from multiple containers to the same volume on a swarm? Is it safe / possible to use flock in a docker swarm?
I'm looking for a safe way for multiple containers to write to the same file (on the same volume).  I know that on a single host docker will bind mount.  What I'm not certain about is how this works when spinning up containers via docker-compose on a swarm.
If I have multiple instances of the same image in a service and these all share a volume then when I start this on a swarm will the containers be started on separate hosts?  If so how will the the volume be shared at an OS level?  What synchronisation options do I have for controlling concurrent writes?

A: Create a NFS volume
Example:
  # create a reusable volume
  $ docker volume create --driver local \
      --opt type=nfs \
      --opt o=nfsvers=4,addr=192.168.1.1,rw \
      --opt device=:/path/to/dir \
      foo

  # inside a docker-compose file
  ...
  volumes:
    nfs-data:
      driver: local
      driver_opts:
        type: nfs
        o: nfsvers=4,addr=192.168.1.1,rw
        device: ":/path/to/dir"

A: docker volumes are local to the node on which they are created, they are not shared between docker swarm nodes.
When running in a multi-node swarm cluster (or in Kubernetes) the container can end up on any of the nodes inside the cluster. For shared access to a docker volume (or PVC in the case of Kubernetes) the volume must be backed by something like a Network File System that can be accessed from each of the nodes inside the cluster.
NFS version 4 implements close-to-open consistency. Full details of what NFS v4 implements are available in "9.3. Data Caching" of RFC 3530:

Share reservations and record locks are the facilities the NFS
version 4 protocol provides to allow applications to coordinate
access by providing mutual exclusion facilities.

Tip: named docker volumes are bind-mounts, the volumes are created on disk in (by default) /var/lib/docker/volumes and bind-mounted during the docker run -v <named_docker_volume>:<container_mount_path> ....


text:
Q: IIS is not installing in windows Home Basic I try to install iis in my windows home basic when i try to select features of iis only few displayed.And I try to install iis but it is not installed.Pls anyone help me to overcome this issue.

A: Unfortunately, due to the limitations of Home Basic, you will be unable to install all of the components within IIS, which explains why some of the features fail to appear. However, you could try downloading IIS Express, which is a lightweight version of IIS.
The following link provides a brief overview, comparing IIS and IIS Express:
http://www.iis.net/learn/extensions/introduction-to-iis-express/iis-express-overview


text:
Q: how to add drop down in list menu in HTML web page I have web page i want to add the drop down menu On Reference button i am using following code for css
I want like this website given template I am new to css please help
http://www.psdgraphics.com/templates/black-horizontal-html-and-css-dropdown-menu/
This is the CSS File
   .menu {
float:right;
margin: 39px 18px 0 0;
height:47px;
background-repeat:no-repeat;
   }

    .menu ul li {
list-style:none;
float:left;
    }

   menu.sub-menu {
visibility: hidden;
position: absolute;
padding:10px;
top: 48px;
left: 0;
z-index: 598;
background: #353535 url(images/dropdown-list-bg.gif) repeat-x left top;
border-right: 1px solid #000;
border-bottom: 1px solid #000;
border-left: 1px solid #000;
 }

    .menu ul li a {
text-decoration:none;
display:block;
    }

    .menu .active {
text-decoration:none;
background-image:url();
    }

   .menu .stix {
width:2px;
font-size:0px;
background-image:url(image/seperator.gif);
background-repeat:no-repeat;
padding:0;
height:47px;
    }

below is my HTML code

DRAXXIN

A: HTML

Products

Link 1

Link 2

Link 3

Link 4

Link 5

Link 6

Products

Link 1

Link 2

Link 3

Link 4

Link 5

Link 6

CSS
#navMenu{
    margin:0;
    padding:0;
}
#navMenu ul{
    margin:0;
    padding:0;
    line-height:30px;
}
#navMenu li{
    margin:0;
    padding:0;
    list-style:none;
    float:left;
    position:relative;
    background:#3A4956;
}
#navMenu ul li a{
    text-align:center;
    color:black;
    text-decoration:none;
    font-family:"Comic Sans MS";
    height:30px;
    width:150px;
    display:block;
    border-bottom:1px black solid;
}
#navMenu ul li a:hover{
    color:white;
}
#navMenu ul ul{
    position:absolute;
    visibility:hidden;
}
#navMenu ul li:hover ul{
    visibility:visible
}
#wrapper1{
    border-radius:8px 0 0 0;
    border-right:1px black solid

}
#wrapper4{
    border-radius:0 8px 0 0;
}


text:
Q: Pandas map by index value without dummy column I have a DataFrame df with 100 rows and two columns, RowId and Probability. Now df is sorted in descending order according to Probability (e.g. 0.997, 0.973, 0.960, etc), and the index of df is in ascending order (0, 1, 2, etc).
I would like to map the values in the Probability column to 's' for 'success' for the first 10 values, and 'f' for 'fail' for the rest. To do this, I create a dummy column called Index, apply a transformation, and then drop the dummy column.
df['Index'] = range(0, 100)
df['Probability'] = df[['Probability', 'Index']].apply(lambda x:
                                                       's' if x['Index'] < 10
                                                       else 'f', axis=1)
df_result.drop(['Index'], axis=1)

Is there a way that I can do this without creating the dummy column?

A: If the index is already 0...n then this would work:
df['Probability'] = np.where(df.index < 10, 's', 'f')

If you're not sure the index is in order, something like this?
 df.loc[df.index[:10], 'Probability'] = 's'
 df.loc[df.index[10:], 'Probability'] = 'f'

A: You could use iloc it uses the actual location index as opposed to the index column:
a = pandas.DataFrame([[1,2],[3,4],[5,6],[7,8]], columns=['a','b'])
a['c'] = 'f'
>>> a
   a  b  c
0  1  2  f
1  3  4  f
2  5  6  f
3  7  8  f

a.iloc[0:2, a.columns.get_loc('c')] = 's'
>>> a
   a  b  c
0  1  2  s
1  3  4  s
2  5  6  f
3  7  8  f

The down side of iloc is that you can't provide column names as strings, you have to give their position as an int, which is why I use a.columns.get_loc.


text:
Q: Can't send HID feature reports of more than 64 bytes on Mac I have a device which exposes MaxFeatureReportSize = 263. The protocol for communicating with the device requires me to send feature reports with length of exactly 263 bytes. This works fine on Windows, but I ran into a strange problem on Mac - IOHIDDeviceSetReport on OS X 10.11 and 10.12 returns cryptic error 0xe0005000 which I couldn't deduce from IOKit headers, and code for corresponding driver (IOUSBHostHIDDevice) is closedsource.
Further investigation showed that

*

*The error doesn't appear when sending requests of 64 bytes or less. Unfortunately, this doesn't really help because the protocol is set in stone and I cannot change it - I have to send 263 bytes.

*On OS X 10.10 which uses old IOUSBHIDDriver instead of 0xe0005000 I get 0xe000404f error. This is kIOUSBPipeStalled, but I still get it every time I try to send more than 64 bytes.

This is as far as I got. I'm now considering downloading OS X 10.8 and debugging IOUSBFamily to see why it can't handle more than 64 byte reports. It's a shame that Apple chose to remove IOUSBFamily sources from OS X 10.9 and above.

A: IOKit/usb/IOUSBHostFamily.h (should be inside Xcode.app) defines the error 0xe0005000 to be kUSBHostReturnPipeStalled.

*

*Do you have a hardware protocol analyzer to see what's happening on the wire?

*Apple used to have "log releases" of IOUSBFamily (downloadable here) that allowed further debugging. The last version was for 10.9.4, it might be helpful to get 10.9 and install it.

*The lists.apple.com site has been down for a few days, but someone on the USB list may be able to help. You may be able to join the list now by emailing "help" in the subject or body to Usb-request@lists.apple.com

*I was searching and found this thread that might be useful (although it's operating below the HID Manager level): Stall reported by ReadPipe, but no stall in USB Protocol Capture

A: The hardware protocol analyzer finally uncovered what was wrong with Mac packets. All Mac packets were 263 bytes long (exactly what I set them to be), while some Windows packets were truncated to 64 bytes (by the system!). As soon as I added a hack to truncate these packets on Mac it worked flawlessly.
I don't know why Windows decided to truncate them - maybe because of a specific report ID (something in a descriptor?), or maybe because the actual packet length never exceeded 20 bytes and everything else was padding. But this weird behavior was actually the one that device was expecting.


text:
Q: Docker command with build / run / etc. "too many open files" Im installed Docker on server machine (with Ubuntu 16.04), but trying run any commands, I get this error:

"Error response from daemon: Get https://registry-1.docker.io/v2/: dial tcp: lookup registry-1.docker.io: too many open files"

Please, who know how solve this issue?
Docker Info:
Containers: 18
Running: 0
 Paused: 0
 Stopped: 18
Images: 4
Server Version: 17.03.0-ce
Storage Driver: aufs
 Root Dir: /var/lib/docker/aufs
 Backing Filesystem: extfs
 Dirs: 76
 Dirperm1 Supported: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
 Volume: local
 Network: bridge host macvlan null overlay
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Init Binary: docker-ini
containerd version: 977c511eda0925a723debdc94d09459af49d082a
runc version: a01dafd48bc1c7cc12bdb01206f9fea7dd6feb70
init version: 949e6fa
Security Options:
 apparmor
 seccomp
  Profile: default
Kernel Version: 4.4.0-59-generic
Operating System: Ubuntu 16.04 LTS
OSType: linux
Architecture: x86_64
CPUs: 2
Total Memory: 1.953 GiB
Name: web.renderdeal.com
ID: LXNZ:I6HH:ZVBB:KS3V:3WCT:ADWY:C2MZ:QJ37:VZUU:EZ6T:PYWO:66WQ
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): false
Username: animarender
Registry: https://index.docker.io/v1/
WARNING: No swap limit support
Experimental: false
Insecure Registries:
 127.0.0.0/8
Live Restore Enabled: false

/Docker Info
docker version

Client:
 Version:      17.03.0-ce
 API version:  1.26
 Go version:   go1.7.5
 Git commit:   60ccb22
 Built:        Thu Feb 23 11:02:43 2017
 OS/Arch:      linux/amd64

Server:
 Version:      17.03.0-ce
 API version:  1.26 (minimum version 1.12)
 Go version:   go1.7.5
 Git commit:   60ccb22
 Built:        Thu Feb 23 11:02:43 2017
 OS/Arch:      linux/amd64
 Experimental: false

/ docker version

A: Considering Docker status seems OK, check if the issue is on your side (as in this ticket)

Let's check on the current open files

lsof | grep "rclone" | wc -l
returns 6458

Now, Check on current ulimit

ulimit -n
returns 1024

Set that to 9000 and Check again

ulimit -n 9000 && ulimit -n
returns 9000

To make the ulimit more persistent you can either edit /etc/security/limits.conf
  and add :

* soft nofile 9000 + reboot

or write it into your user's .bashrc


text:
Q: Wordpress Contact Form does not work THe code below does not work. This is the code inside my contact page (page-kontakt.php) :

Send Us Mail

    <?php
if ($_GET[msg_sent]=='true' ) {
    echo '
Your message has been sent!
';
}elseif ($_GET[msg_sent]=='false') {
    echo '
An error occurred sending your message.
';
}else{
?>

             <form method="post" action="<?php echo LEARNINGWORDPRESS_THEME_URL ?>functions.php">
            Name
            <input name="name" placeholder="Type Here">

            Email
            <input name="email" type="email" placeholder="Type Here">

            Message
            <textarea name="message" placeholder="Type Here"></textarea>

            *What is 2+2? (Anti-spam)
            <input name="human" placeholder="Type Here">

            <input id="submit" name="submit" type="submit" value="Submit">

        </form>

        <?php } ?>

This is the code inside my functions page (functions.php) :
// KONTAKT - MESSAGE SENDING FUNCTIONS FOR page-kontakt.php

    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: http://muzykablog.pl/';
    $to = 'piterdeja@gmail.com';
    $subject = 'Hello';
    $human = $_POST['human'];

    $body = "From: $name\n E-Mail: $email\n Message:\n $message";

    if(mail($to, $subject, $body, $from)){
    header('Location:page-kontakt.php?msg_sent=true');
}else{
    header('Location:page-kontakt.php?msg_sent=false');
}

In my wordpress site I want to be able to enter muzykablog.pl/kontakt where my contact form is (right now url muzykablog.pl/kontakt does not work) and after filling all the input windows like 'email' 'message' and clicking 'submit' I want to receive email message to the email address which I specified. Notice that I specified absolute path:
             <form method="post" action="<?php echo LEARNINGWORDPRESS_THEME_URL ?>functions.php">

Maybe it is necessary to specify absolute path in
Location:page-kontakt.php?msg_sent=true

...as well, but how to specify absolute path in functions.php ?

A: You should change the code like this. Change the form action to blank

 <form method="post" action="">
            Name
            <input name="name" placeholder="Type Here">

            Email
            <input name="email" type="email" placeholder="Type Here">

            Message
            <textarea name="message" placeholder="Type Here"></textarea>

            *What is 2+2? (Anti-spam)
            <input name="human" placeholder="Type Here">

            <input id="submit" name="contactSubmit" type="submit" value="Submit">

        </form>

in functions.php you need to do the following code.

add_action('init','contact_submit');

function contact_submit(){
//contactSubmit is name of submit input field
  if($_POST['contactSubmit']){
    you submit code will be here
  }
}

A: Since You are using wordpress why don't you use some premade solutions such as contact form 7. you could simply grab the plugin from repository and use shortcodes to insert in your page. you Could even style it if you require


text:
Q: Why do I have to click my event handler target twice before the DOM is updated? I am making a time tracking dashboard site, it has 3 links (Daily, Weekly, and Monthly) and I want the content to change based on which link is clicked. I am setting hash values for all 3 links as #daily, #weekly, and #monthly and in my jQuery script I am hiding and showing divs by adding if conditions that uses location.hash property to hide and show specific. The script is working somewhat but the content changes only when I double click on a link, I don't know what is wrong with my script. I have made a repository and also enabled GitHub pages for it, GitHub Repository and GitHub Pages Link.

let daily = document.getElementsByClassName('daily');
let weekly = document.getElementsByClassName('weekly');
let monthly = document.getElementsByClassName('monthly');

window.onload = function() {
  $(weekly).hide();
  $(monthly).hide();
};

function hideAndShow() {
  if (location.hash === '#daily') {
    $(daily).show();
    $(weekly).hide();
    $(monthly).hide();
  } else if (location.hash === '#weekly') {
    $(daily).hide();
    $(weekly).show();;
    $(monthly).hide();
  } else if (location.hash === '#monthly') {
    $(daily).hide();
    $(weekly).hide();
    $(monthly).show();
  }
};

let frequency = document.querySelectorAll('.user__frequency__link');
for (let i = 0; i < frequency.length; i++) {
  frequency[i].addEventListener('click', function(_event) {
    hideAndShow(this);
  });
}
@import url('https://fonts.googleapis.com/css2?family=Rubik:wght@300;400;500&display=swap');
*,
*::after,
*::before {
  box-sizing: border-box;
}

:root {
  --clr-neutral: hsl(0, 100%, 100%);
  --clr-primary-100: hsl(236, 100%, 87%);
  --clr-primary-200: hsl(235, 45%, 61%);
  --clr-primary-300: hsl(246, 80%, 60%);
  --clr-primary-400: hsl(235, 46%, 20%);
  --clr-primary-500: hsl(226, 43%, 10%);
  --clr-work: hsl(15, 100%, 70%);
  --clr-play: hsl(195, 74%, 62%);
  --clr-study: hsl(348, 100%, 68%);
  --clr-exercise: hsl(145, 58%, 55%);
  --clr-social: hsl(264, 64%, 52%);
  --clr-self-care: hsl(43, 84%, 65%);
}

body {
  font-family: 'Rubik', sans-serif;
  background-color: var(--clr-primary-500);
  color: var(--clr-neutral);
}

h1 {
  margin: 0;
}

a {
  text-decoration: none;
  color: var(--clr-neutral);
}

.bg-primary-400 {
  background-color: var(--clr-primary-400);
  margin-top: 2.8rem;
  border-radius: 1.25rem 1.25rem 0 0;
}

.user__frequency__link {
  font-size: 22px;
  font-weight: 400;
  opacity: .5;
}

.user__frequency__link:visited,
.user__frequency__link:focus,
.user__frequency__link:hover,
.user__frequency__link:active {
  opacity: 1;
}

.container {
  margin: 5rem 1rem;
}

.rounded-box {
  border-radius: 1.5rem;
  overflow: hidden;
}

.rounded-box+.rounded-box {
  margin-top: 1.6rem;
}

.box-padding {
  padding: 1rem 2rem;
}

.box-padding1 {
  padding: 3.4rem 2rem;
}

.box-padding2 {
  padding: 1rem 2rem 2rem 2rem;
}

.user__name {
  background-color: var(--clr-primary-300);
  border-radius: 0 0 1.25rem 1.25rem;
  display: flex;
  gap: 2rem;
  align-items: center;
  justify-content: center;
}

.user__img {
  border: 2px solid var(--clr-neutral);
  border-radius: 50%;
  width: 125px;
  height: 125px;
}

.user__frequency {
  display: flex;
  justify-content: space-around;
}

.user {
  background-color: var(--clr-primary-400);
}

.row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.heading-neutral {
  font-size: 1.125rem;
  font-weight: 500;
  margin-bottom: 0.846rem;
}

.ellipsis {
  color: var(--clr-neutral);
}

.work {
  background-color: var(--clr-work);
  background-image: url(../images/icon-work.svg);
  background-repeat: no-repeat;
  background-position: 95% -7%;
}

.play {
  background-color: var(--clr-play);
  background-image: url(../images/icon-play.svg);
  background-repeat: no-repeat;
  background-position: 95% -2%;
}

.study {
  background-color: var(--clr-study);
  background-image: url(../images/icon-study.svg);
  background-repeat: no-repeat;
  background-position: 95% -7%;
}

.exercise {
  background-color: var(--clr-exercise);
  background-image: url(../images/icon-exercise.svg);
  background-repeat: no-repeat;
  background-position: 95% 0%;
}

.social {
  background-color: var(--clr-social);
  background-image: url(../images/icon-social.svg);
  background-repeat: no-repeat;
  background-position: 95% -7%;
}

.self-care {
  background-color: var(--clr-self-care);
  background-image: url(../images/icon-self-care.svg);
  background-repeat: no-repeat;
  background-position: 95% -7%;
}

.daily,
.weekly,
.monthly {
  display: flex;
  flex-grow: 1;
  align-items: center;
}

.current {
  font-size: 2rem;
  font-weight: 300;
}

.previous {
  margin-left: auto;
  opacity: 0.6;
}

/* .weekly,
.monthly {
   display: none;
} */

.attribution {
  font-size: 11px;
  text-align: center;
}

.attribution a {
  color: hsl(228, 45%, 44%);
}

Daily

Weekly

Monthly

Work

5hrs

Yesterday - 7hrs

32hrs

Last Week - 36hrs

103hrs

Last Month - 128hrs

Play

1hr

Yesterday - 2hrs

10hrs

Last Week - 8hrs

23hrs

Last Month - 29hrs

Study

0hrs

Yesterday - 1hr

4hrs

Last Week - 7hrs

13hrs

Last Month - 19hrs

Exercise

1hr

Yesterday - 1hr

4hrs

Last Week - 5hrs

11hrs

Last Month - 18hrs

Social

1hr

Yesterday - 3hrs

5hrs

Last Week - 10hrs

21hrs

Last Month - 23hrs

Self Care

0hrs

Yesterday - 1hr

2hrs

Last Week - 2hrs

7hrs

Last Month - 11hrs

  Challenge by Frontend Mentor. Coded by Your Name Here.

A: The problem really is just a race condition basically... You check the location hash before it gets updated by the click on the a. But, is that really what you'd like to do? Change the display according to the hash value, on a user click? Wouldn't you be better to just listen to hash changes, and act accordingly?
window.addEventListener("hashchange", hideAndShow);

Every time the hash changes, hideAndShow will trigger and do the changes needed... That way you do not have to remember to add X or Y events on every click that changes the hash value.

A: Your click handler is running before the location is updated. A quick way to resolve that is to wrap the function call in a zero-delay timeout, which forces it into the next execution cycle.
Learn more about other possible solutions.

let daily = document.getElementsByClassName('daily');
let weekly = document.getElementsByClassName('weekly');
let monthly = document.getElementsByClassName('monthly');

window.onload = function() {
  $(weekly).hide();
  $(monthly).hide();
};

function hideAndShow() {
  if (location.hash === '#daily') {
    $(daily).show();
    $(weekly).hide();
    $(monthly).hide();
  } else if (location.hash === '#weekly') {
    $(daily).hide();
    $(weekly).show();;
    $(monthly).hide();
  } else if (location.hash === '#monthly') {
    $(daily).hide();
    $(weekly).hide();
    $(monthly).show();
  }
};

let frequency = document.querySelectorAll('.user__frequency__link');

for (let i = 0; i < frequency.length; i++) {
  frequency[i].addEventListener('click', function(_event) {
    setTimeout(function() {
      hideAndShow(this);
    }); // no delay for you!
  });
}
@import url('https://fonts.googleapis.com/css2?family=Rubik:wght@300;400;500&display=swap');
*,
*::after,
*::before {
  box-sizing: border-box;
}

:root {
  --clr-neutral: hsl(0, 100%, 100%);
  --clr-primary-100: hsl(236, 100%, 87%);
  --clr-primary-200: hsl(235, 45%, 61%);
  --clr-primary-300: hsl(246, 80%, 60%);
  --clr-primary-400: hsl(235, 46%, 20%);
  --clr-primary-500: hsl(226, 43%, 10%);
  --clr-work: hsl(15, 100%, 70%);
  --clr-play: hsl(195, 74%, 62%);
  --clr-study: hsl(348, 100%, 68%);
  --clr-exercise: hsl(145, 58%, 55%);
  --clr-social: hsl(264, 64%, 52%);
  --clr-self-care: hsl(43, 84%, 65%);
}

body {
  font-family: 'Rubik', sans-serif;
  background-color: var(--clr-primary-500);
  color: var(--clr-neutral);
}

h1 {
  margin: 0;
}

a {
  text-decoration: none;
  color: var(--clr-neutral);
}

.bg-primary-400 {
  background-color: var(--clr-primary-400);
  margin-top: 2.8rem;
  border-radius: 1.25rem 1.25rem 0 0;
}

.user__frequency__link {
  font-size: 22px;
  font-weight: 400;
  opacity: .5;
}

.user__frequency__link:visited,
.user__frequency__link:focus,
.user__frequency__link:hover,
.user__frequency__link:active {
  opacity: 1;
}

.container {
  margin: 5rem 1rem;
}

.rounded-box {
  border-radius: 1.5rem;
  overflow: hidden;
}

.rounded-box+.rounded-box {
  margin-top: 1.6rem;
}

.box-padding {
  padding: 1rem 2rem;
}

.box-padding1 {
  padding: 3.4rem 2rem;
}

.box-padding2 {
  padding: 1rem 2rem 2rem 2rem;
}

.user__name {
  background-color: var(--clr-primary-300);
  border-radius: 0 0 1.25rem 1.25rem;
  display: flex;
  gap: 2rem;
  align-items: center;
  justify-content: center;
}

.user__img {
  border: 2px solid var(--clr-neutral);
  border-radius: 50%;
  width: 125px;
  height: 125px;
}

.user__frequency {
  display: flex;
  justify-content: space-around;
}

.user {
  background-color: var(--clr-primary-400);
}

.row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.heading-neutral {
  font-size: 1.125rem;
  font-weight: 500;
  margin-bottom: 0.846rem;
}

.ellipsis {
  color: var(--clr-neutral);
}

.work {
  background-color: var(--clr-work);
  background-image: url(../images/icon-work.svg);
  background-repeat: no-repeat;
  background-position: 95% -7%;
}

.play {
  background-color: var(--clr-play);
  background-image: url(../images/icon-play.svg);
  background-repeat: no-repeat;
  background-position: 95% -2%;
}

.study {
  background-color: var(--clr-study);
  background-image: url(../images/icon-study.svg);
  background-repeat: no-repeat;
  background-position: 95% -7%;
}

.exercise {
  background-color: var(--clr-exercise);
  background-image: url(../images/icon-exercise.svg);
  background-repeat: no-repeat;
  background-position: 95% 0%;
}

.social {
  background-color: var(--clr-social);
  background-image: url(../images/icon-social.svg);
  background-repeat: no-repeat;
  background-position: 95% -7%;
}

.self-care {
  background-color: var(--clr-self-care);
  background-image: url(../images/icon-self-care.svg);
  background-repeat: no-repeat;
  background-position: 95% -7%;
}

.daily,
.weekly,
.monthly {
  display: flex;
  flex-grow: 1;
  align-items: center;
}

.current {
  font-size: 2rem;
  font-weight: 300;
}

.previous {
  margin-left: auto;
  opacity: 0.6;
}

/* .weekly,
.monthly {
   display: none;
} */

.attribution {
  font-size: 11px;
  text-align: center;
}

.attribution a {
  color: hsl(228, 45%, 44%);
}

Daily

Weekly

Monthly

Work

5hrs

Yesterday - 7hrs

32hrs

Last Week - 36hrs

103hrs

Last Month - 128hrs

Play

1hr

Yesterday - 2hrs

10hrs

Last Week - 8hrs

23hrs

Last Month - 29hrs

Study

0hrs

Yesterday - 1hr

4hrs

Last Week - 7hrs

13hrs

Last Month - 19hrs

Exercise

1hr

Yesterday - 1hr

4hrs

Last Week - 5hrs

11hrs

Last Month - 18hrs

Social

1hr

Yesterday - 3hrs

5hrs

Last Week - 10hrs

21hrs

Last Month - 23hrs

Self Care

0hrs

Yesterday - 1hr

2hrs

Last Week - 2hrs

7hrs

Last Month - 11hrs

  Challenge by Frontend Mentor. Coded by Your Name Here.


text:
Q: AsyncStorage access in Material Top Tab Navigator React Native I want to the change user profile pic, when user log into the system. User avator in left side corner in the Material Tab navigator. When user log in to the system I store the image url in AsyncStorage as profilePic.
I want to access AsyncStorage and get the profile pic here.
 <Image
            source={{
              uri:
                'https://cdn.apparelconnects.com/users_2_a34456c8-6d69-4b80-98f2-d184ff9f504d_img.png',
            }}

I try to many ways. but I can not do this. Here I attached my code. Anyone know the access AsyncStorage here, please help me..
const TabNavigator = createMaterialTopTabNavigator(
  {
    Profile: {
      screen: Logout,
      navigationOptions: {
        title: 'Home',
        tabBarIcon: ({tintColor}) => (
          <Image
            source={{
              uri:
                'https://cdn.apparelconnects.com/users_2_a34456c8-6d69-4b80-98f2-d184ff9f504d_img.png',
            }}
            style={{
              width: tabBarConfiguration.icon_size,
              height: tabBarConfiguration.icon_size,
              borderRadius: 40 / 2,
              overflow: 'hidden',
              borderWidth: tintColor == colors.orange ? 2 : 0,
              borderColor: tintColor,
            }}
          />
        ),
      },
    },
    Home: {
      screen: Home,
      navigationOptions: {
        title: 'Home',
        tabBarIcon: ({tintColor}) => (
          <Image
            source={require('../asserts/images/home_icon.png')}
            style={{
              width: tabBarConfiguration.icon_size,
              height: tabBarConfiguration.icon_size,
              tintColor: tintColor,
            }}
          />
        ),
      },
    },

  {
    initialRouteName: 'Home',
    activeColor: '#f0edf6',
    inactiveColor: '#3e2465',
    barStyle: {backgroundColor: '#694fad'},
    tabBarPosition: 'top',
    swipeEnabled: true,
    lazy: true,
    tabBarOptions: {
      showIcon: true,
      showLabel: false,
      activeTintColor: colors.orange,
      inactiveTintColor: '#a1a1a1',
      style: {
        backgroundColor: '#ffffff',
        height: hp('10%'),
      },
      labelStyle: {
        textAlign: 'center',
        fontWeight: 'bold',
      },
      indicatorStyle: {
        backgroundColor: 'transparent',
      },
    },
    defaultNavigationOptions: ({navigation}) => ({
      tabBarOnPress: ({navigation, defaultHandler}) => {
        if (
          navigation.state.routeName === 'Profile' ||
          navigation.state.routeName === 'More'
        ) {
          return null;
        }
        defaultHandler();
      },
    }),
  },
);

export default createAppContainer(TabNavigator);


text:
Q: ionic how to get the click event on oktext I have a select button on ionic that has two options okText and cancelText, my problem is that when I click the okText, my menu closes which is intended for this attribute. However, I would like to know how do I work it via click events. This is my code:
<ion-select okText="Okay" cancelText="Dismiss">
  ...
</ion-select>

I would like to figure out how do I push another page when I declare a function in my .ts file.

A: You can use ionCancel to trigger cancel click event and ionChange trigger ok click event.
Example:
HTML
<ion-select [(ngModel)]="employee"
    (ionChange)="onModelChange()"
    (ionCancel)="onCancelClick()">

   <ion-option
       *ngFor="let employee of employees"
       [value]="employee"></ion-option>
  </ion-select>

TS
export class ExamplePage {

  employees = ['A', 'B', 'C', 'D'];
  employee;

  constructor() {

    this.employee = this.employees[0];
  }

  onModelChange() {

    console.log(this.employee);
  }

   onCancelClick () {
    console.log('handle onCancelClick');
  }

}

A: You can use below methods for cancel click event and ok click event.
<ion-select (cancel)="onCancelClick()" (change)="onOkClick()">
   ...
</ion-select>


text:
Q: jQuery AJAX HTTP error codes not being picked up in Safari I'm using jQuery.ajax() to send data to my own PHP file for adding subscribers to a MailChimp list.  The Javascript looks like this:
$.ajax({
  url: url,
  method: 'POST',
  data: params, // the data is working so here is just the variable I'm using
  error: function(response) {
    console.error($.parseJSON(response));
    // show some response text through DOM manipulation
  }, success: function (response) {
    console.log($.parseJSON(response));
    // show some response text through DOM manipulation
  }
});

The PHP looks like this (at least just for the HTTP status code response):
// All my PHP code, which is working is above this
$result = curl_exec($ch);
echo $result; // This is for the response text in the ajax call
http_response_code(intval(json_decode($result)->status)); // This should be sending a success code or triggering errors

On Chrome, if I get a good response (a HTTP status in the 200s), the success function will run.  If I trigger an error (in my testing, a HTTP status in the 400s), the error function will run.  All is good.
However, on Safari, whether it is a 200 or a 400 code, the success function runs.  There seems to be no detection in my Javascript of error codes when using the Safari browser.  How can I fix this?  Why is it different between Chrome and Safari?
In case it matters, I'm working locally with CodeKit and MAMP PRO to run my project.  Thanks.

A: You need to send the response code before the actual response, i.e.,
$result = curl_exec($ch);
http_response_code(intval(json_decode($result)->status)); // This should be sending a success code or triggering errors
echo $result; // This is for the response text in the ajax call

This is because http_response_code is essentially running a header("HTTP/1.0 $code $codeMessage") and the header needs to be sent before the response.


text:
Q: Relaunch a program when error detected I am currently making a simple program about reading a file. I have a try and catch block showed as below. What I want to do is if the program detected error (exception), it will relaunch the entire program 3 times. After that, if the error still occur, the program terminated by itself and then print out the exception message. I got the file part working, but now I have no idea how to do the relaunch part. Help will be appreciated, thanks
Here is my code:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

 public class Test {

        public static void main(String args[]){

             try {
                    // constructor may throw FileNotFoundException
                    FileReader reader = new FileReader("someFile.txt");
                    int i=0;
                    while(i != -1){
                        //reader.read() may throw IOException
                        i = reader.read();
                        System.out.println((char) i );
                    }

                    reader.close();
                    System.out.println("--- File End ---");
                }

                //Relaunch program
                    retry();

                 catch (FileNotFoundException e) {
                    //do something clever with the exception
                    System.out.println("File not found");
                    e.printStackTrace();
                } catch (IOException e) {
                    //do something clever with the exception
                    e.printStackTrace();
                }

        }

        private static void retry() {

        }

    }

A: Here's my solution:
private static int attempts = 1;
synchronized private static void retry() {
    if(attempts == 3)
        return;

    new Thread() {
        main(null);
    }.start();

    attempts++;
}

A: You can try following way,
public class Test {//Start class name with capital case

     public static void main(String args[]){
          int counter = 1;
          while(counter <= 3) {//try until counter reaches 3
              boolean isSuccess = readFile(counter++);
              if(isSuccess) {
                  break;
              }
          }
     }

     private static boolean readFile(int attempt) {
          try {
             //read file here
             return true;
           } catch(Exception e) {
             if(attempt == 3) {
                 e.printStackTrace();
             }
             return false;
          }
     }
}


text:
Q: SPARQL string RANGE I am trying to extract a part of a string by using index numbers.
When having
"OEIUFHWOIEFWNFOPQWJFHQWOIHFEB..."

and I need string from 5:10 (FHWOIE) I found out that it is not possible via REGEX as that returns only boolean and not groups. However, I did not manage to find a region selection on strings via positions. Now I am wondering if there is any?
I found out that it is partly possible via...
BIND(REPLACE(?sequence, '^.{100}', "") AS ?sequencestrip1)

but not
BIND(REPLACE(?sequence, '^.{?start}', "") AS ?sequencestrip1)

I think this does it for anyone who is interested:
BIND(REPLACE(?sequence, "^.{"+str(?start)+"}", "") AS ?sequencestrip1)

and of course to remove the area behind what you are interested in
BIND(REPLACE(?region, ".{"+str(strlen(?region)-10)+"}$", "") AS ?upstream)

A: In the first SPARQL Query Language for RDF, this would be rather difficult, because there are not many string manipulation functions.  However, in your question, you've used replace which appeared in SPARQL 1.1 Query Language.  This is good for you because, in addition to replace, SPARQL 1.1 includes more string manipulation functions.  One of these, substr, does exactly what you need. For instance, here's a query in which ?string is bound to the string you mentioned, and substr is used to extract the substring you're looking for and bind it as ?substring.
select * where {
  values ?string { "OEIUFHWOIEFWNFOPQWJFHQWOIHFEB..." }
  bind( substr( ?string, 5, 6 ) as ?substring )
}

The results are:
--------------------------------------------------
| string                             | substring |
==================================================
| "OEIUFHWOIEFWNFOPQWJFHQWOIHFEB..." | "FHWOIE"  |
--------------------------------------------------

Note that the second argument to substr is the starting position (where the first index is 1), and the third is the length of the substring, not the final position.  You wanted a substring, FHWOIE, that has six characters, to the third argument is 6.


text:
Q: How to compare the modified dates of 3 or more files I'm trying to write a bash script that accepts 3 or more filenames as arguments and outputs the newest file. I'm finding it hard to compare the arguments since essentially each argument has to be compared to all the others.
I've tried creating a for loop but I'm stuck on how to get the next value in the loop. i.e the next argument
Does anyone have any way to successfully compare all the arguments

A: ls -c file1 file2 file3... | head -n 1 does the trick.

-c sort by ctime, newest first
-t sort by modification time, newest first
-u sort by access time, newest first

The newest file will be at line 1. Depending on your need, you may choose the desired one.


text:
Q: How zlib headers are stored in multiple IDAT chunks in png I am learning how png works and trying to create a simple PNG decoder with "pure" C++.
My problem is that I don't know how zlib headers are stored in multiple IDAT-PNG chunks. The first IDAT chunk looks fine - a normal "CM" and "CINFO", but when I read the next IDAT chunk the zlib header looks strange, the "CM" can be a random number - not 8 as default and the "CINFO" can be above 7 - I readed that "CINFO" with a number above 7 is marked as corrupted/not acceptable. So where can I find some information about this? -I didn't find anything about handling multiple IDAT chunks on the web. (Uh, I find something here - in "StackOverFlow", but it doesn't seem to describe how zlib headers are stored in multiple IDAT chunks so it doesn't answer my question)
I read the RFC 1950 about zlib.
https://www.rfc-editor.org/rfc/rfc1950

A: There is only one zlib header, in the first chunk. The series of IDAT chunks is a single zlib stream, broken up into pieces.
You need to read the PNG spec more carefully.


text:
Q: How do you specify a database column that contains a space in a linq statement I thought this would have been quite common but can't find anything on this.  I'm trying to query columns that have spaces immbedded within them.  For the life of me I don't see a way of selecting them when I'm trying to assign them to an alias when creating an anonymous type result.  Here's the code, but not sure how to go from here:
Dim joinedRows = (From r1 In ds.Tables(ETGAtSfdcTableName.Snapshot1) Group Join r2In ds.Tables
                 (ETGAtSfdcTableName.Snapshot2) On r1.Field(Of String)("idAT") Equals
                 r2.Field(Of String)("idAT") Into j() _
                        From c In j.DefaultIfEmpty() _
                                        Select New With _
                                        { _
                                             r1.idAT, _
                                             .status = r1.status, _
                                             ......
                                             .Change = r2.amtProdUSD - r1.amtProdUSD, _
                                             .ChangeABS = Abs(r2.amtProdUSD - r1.amtProdUSD), _
                                             r1.id, _
                                             amStatus = r1."Opportunity Status",
                                             ......

As you can see the column  "opportunity status" doesn't lend itself to be referenced this way.  is there something I'm missing?

A: I think LINQ to SQL will convert the space in the column name to an underscore: Opportunity_Status

A: Try this:
amStatus = r1.Field<string>("Opportunity Status")


text:
Q: I need to put parentheses and numbering before the values in the array I try to put parentheses at the beginning and end of the line
Input:
First Iteration
1 1 1
2 2 2
3 3 3

Second Iteration
4 4 4
5 5 5
6 6 6

I need to put before each value in the field, a number from 1 to 3 in the first iteration, in the next 4-6 and thus continue after the iterations.
As shown below
(11 21 31)
(12 22 32)
(13 23 33)

(44 54 64)
(45 55 65)
(46 56 66)

I tried adding it but it was not effective for my program
This is my full code:
f = open("demofile.txt", "r")
lines = f.readlines()
for i in list(lines):
    w = i[3:]
    w = ', '.join(w.split())
    #print(w)
    #time.sleep(1)
    y = i[2]
    y=int(y)+1
    #print(y)
    c1=np.array([w])
    c1 = [int(i) for i in c1[0].replace(" ", "").split(",")]
    c1=np.array([c1]*3)
    c1=np.transpose(c1)
    a=str(c1).replace("[",'')
    a=str(a).replace("]",'')
    a=str(a).replace("\n ",'\n')
    print('\n')
    print(a)

demofile.txt is:
<=1 1 2 3
<=1 4 5 6

A: something like so?
num = 50

#plain lists
x = [[ [x+i]*3 for i in range(3)] for x in range(0,num, 3)]

print(x)

#with tuples
x = [tuple([ tuple([x+i]*3) for i in range(3)]) for x in range(0,num, 3)]

print(x)

[[[0, 0, 0], [1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4], [5, 5, 5]], [[6, 6, 6], [7, 7, 7], [8, 8, 8]], [[9, 9, 9], [10, 10, 10], [11, 11, 11]], [[12, 12, 12], [13, 13, 13], [14, 14, 14]], [[15, 15, 15], [16, 16, 16], [17, 17, 17]], [[18, 18, 18], [19, 19, 19], [20, 20, 20]], [[21, 21, 21], [22, 22, 22], [23, 23, 23]], [[24, 24, 24], [25, 25, 25], [26, 26, 26]], [[27, 27, 27], [28, 28, 28], [29, 29, 29]], [[30, 30, 30], [31, 31, 31], [32, 32, 32]], [[33, 33, 33], [34, 34, 34], [35, 35, 35]], [[36, 36, 36], [37, 37, 37], [38, 38, 38]], [[39, 39, 39], [40, 40, 40], [41, 41, 41]], [[42, 42, 42], [43, 43, 43], [44, 44, 44]], [[45, 45, 45], [46, 46, 46], [47, 47, 47]], [[48, 48, 48], [49, 49, 49], [50, 50, 50]]]

[((0, 0, 0), (1, 1, 1), (2, 2, 2)), ((3, 3, 3), (4, 4, 4), (5, 5, 5)), ((6, 6, 6), (7, 7, 7), (8, 8, 8)), ((9, 9, 9), (10, 10, 10), (11, 11, 11)), ((12, 12, 12), (13, 13, 13), (14, 14, 14)), ((15, 15, 15), (16, 16, 16), (17, 17, 17)), ((18, 18, 18), (19, 19, 19), (20, 20, 20)), ((21, 21, 21), (22, 22, 22), (23, 23, 23)), ((24, 24, 24), (25, 25, 25), (26, 26, 26)), ((27, 27, 27), (28, 28, 28), (29, 29, 29)), ((30, 30, 30), (31, 31, 31), (32, 32, 32)), ((33, 33, 33), (34, 34, 34), (35, 35, 35)), ((36, 36, 36), (37, 37, 37), (38, 38, 38)), ((39, 39, 39), (40, 40, 40), (41, 41, 41)), ((42, 42, 42), (43, 43, 43), (44, 44, 44)), ((45, 45, 45), (46, 46, 46), (47, 47, 47)), ((48, 48, 48), (49, 49, 49), (50, 50, 50))]


text:
Q: ClassNotFoundException of com.mysql.jdbc.Driver, when using servlets this wierd problem is very interrupting me for a long time. I have a class name Connector inside dynamic web application in eclipse, with these code:
public class Connector {

    private static final String dbURL = "jdbc:mysql://localhost:3306/";

    private Connection con;

    public Connector(String userName, String password) {
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con = DriverManager.getConnection(dbURL, userName, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
            catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        catch (Exception e) {
            System.err.print("Unidentified exception has acurred!");
            e.printStackTrace();
        }
    }

when I'm using it from different Class in the same package, named portal, it works fine, but when I'm trying to use it from servlet in package servlets, named LoginHandle.java, I get ClassNotFoundException.
The Class is in the build path of all classes, and I checked it by trying to import it from the servlet, but when I create new instance, it is not being recognized. I tried to move the servlet to the package of the connector, and vise versa, and it didn't affect. Here is the servlet's code:
    package servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import portal.Connector;
import portal.UserTableAnalyzer;

@WebServlet("/LoginHandle")
public class LoginHandle extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public LoginHandle() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String referer = request.getHeader("Referer");
        String pageName = referer.substring(referer.lastIndexOf('/') + 1);
        if(pageName.equals("Login.jsp"))
        {
            HttpSession session = request.getSession(false);
            Connector c = new Connector("root", "16180339887");

            c.executeUpdate("USE Main");
            String id = request.getParameter("id"), password = request.getParameter("password");
            String query = "SELECT FROM Users WHERE id ='" + id + "' AND password = '" + password + "'";
            String[][] result = c.executeQuery(query);

            UserTableAnalyzer uta = new UserTableAnalyzer(result);
            if(result.length > 0)
            {
                session.setAttribute("userID", uta.getID(0));
                session.setAttribute("role", uta.getRole(0));
                response.sendRedirect("Main.jsp");
            }
            else
            {
                request.setAttribute("wrongDetails", new Boolean(true));
                response.sendRedirect("Login.jsp");
            }
        }
        else
            response.getWriter().print(pageName);
    }

}

sorry if my english is bad, or if details are missing

A: Your driver is not in the server classpath, build path has nothing to do with that.
You didn't write which application server are you using. You also should use DataSource in servlets, rather than DriverManager. Here is sample configuration for Tomcat.
UPDATE
For Tomcat 7 you need to do the following:
Put mysql jar in the $CATALINA_HOME/lib
Configure Datasource in context
 <Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
                       maxActive="100" maxIdle="30" maxWait="10000"
                       username="user" password="pass"
                       driverClassName="com.mysql.jdbc.Driver"
                       url="jdbc:mysql://localhost:3306/databaseName"/>

Use Datasource in servlet (pseudo code)
@WebServlet("/LoginHandle")
public class LoginHandle extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Resource(lookup="jdbc/testDB")
    private DataSource ds;

    ...

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

   Connection c = ds.getConnection();
   ...


text:
Q: Why i can't use variable name other then "value" to save my selected value in Combobox (Lightning Web Component) I'm working on lightning Web Component and i have a combobox.
In the Template file i have @track value='' to save my selected value
when i change the variable name from @track value='' to
@track selectedValue='' my combobox it's not working...
can anyone know why i should only use @track value as variable name to save the selected value in the combobox

A: There is no such restriction to use only the name value. You will need to make sure if you change the name in the JS, the same is updated in the HTML as well.
As an example the below works perfectly fine:
HTML
<lightning-combobox
        name="status"
        label="Status"
        placeholder="Choose Status"
        value={selectedValue} // make sure you update the variable name here as well
        onchange={handleChange}
        options={statusOptions}>
</lightning-combobox>

JavaScript
@track
statusOptions = [
    {value: 'new', label: 'New'},
    {value: 'in-progress', label: 'In Progress'},
    {value: 'finished', label: 'Finished'}
];

@track
selectedValue = 'new';

handleChange(event) {
    this.selectedValue = event.detail.value;
    alert(`Option selected with selectedValue: ${this.selectedValue}`);
}


text:
Q: Alternatives to point to GitLab private registry for Scala (Play) projects?
*

*What's the easiest way to publish ~10 public packages (like mockito-scala,java-jwt, ...) into the GitLab private registry? "https://gitlab.com/api/v4/projects/SOME_PROJECT_ID/packages/maven"
(mvn deploy:deploy-file?)

*So the Scala Play project can point to the private registry?
(Came across this https://github.com/gilcloud/sbt-gitlab. Are there other solutions?)

A: In order to publish artifact to Gitlab private registry, the general command is:
mvn deploy:deploy-file \
  -Durl=https://gitlab.com/api/v4/groups/xxxxxx/-/packages/maven/ \
  -DrepositoryId=gitlab-maven \
  -Dfile=target/jar/ID-1.0.0-SNAPSHOT.jar \
  -DgroupId=ID \
  -DartifactId=ID \
  -Dversion=1.0.0-SNAPSHOT \
  -Dpackaging=jar \
  -DgeneratePom=true

And you can see an settings.xml/pom.xml example here.
But only with maven:3.8.3-jdk-11 or more.


text:
Q: Bitmap saved in internal storage doesn't show on Gallery I created a simple app to save a bitmap in internal storage and be able to show this bitmap in the android gallery like any other image.
The problem is: it isn't showing in the gallery after is saved... and I don't know what I am doing wrong. (I'm testing this on emulator)
Here is my class that handles the save of the Bitmap. This Saver class is used in my main activity when I click on a button saves the bitmap.
public class Saver {

private Context mContext;
private String mNameOfFolder = "Storager";
private String mNameOfFile = "Quote";

public void saveImage(Context context, Bitmap imageToSave) {
    mContext = context;

    // Create the directory
    File dir = mContext.getDir(mNameOfFolder, Context.MODE_PRIVATE);
    String filePath = dir.getAbsolutePath();

    // Get the current date and time to attach to the name of the image
    String currentDateAndTime = getCurrentDateAndTime();

    if(!dir.exists()) {
        dir.mkdirs();
    }

    File file = new File(dir, mNameOfFile + currentDateAndTime + ".jpg");

    try {
        FileOutputStream out = new FileOutputStream(file);
        imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);

        out.flush();
        out.close();

        galleryAddPic(file);

        successSave();
    } catch (FileNotFoundException e) {
        Log.d("d", "file not found");
        unableToSave();
    } catch (IOException e) {
        Log.d("d", "IO Exception");
        unableToSave();
    }
}

private void galleryAddPic(File file) {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    Uri contentUri = Uri.fromFile(file);
    mediaScanIntent.setData(contentUri);
    mContext.sendBroadcast(mediaScanIntent);
}

private String getCurrentDateAndTime() {
    Calendar calendar = Calendar.getInstance();
    // Setting format of the time
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
    // Getting the formated date as a string
    String formattedDate = dateFormat.format(calendar.getTime());

    return formattedDate;
}

}
I even added the method galleryAddPic() that is provided by android developer site here to be able to add the image to Media Provider's database, making it available in the Android Gallery application and to other apps.

A: Third-party apps, including the MediaStore, have no access to your app's internal storage. If you want third-party apps to have access to the file, use external storage.
Also, I have no idea why you are creating a ContextWrapper here. If you have methods that require a Context (e.g., getDir() in your current code), call them on the Context that is passed into your method.


text:
Q: Removing extra whitespaces from a string - C programming The task is to remove all of the extra whitespaces in a string, for example if a string looks like this:
   volim      OR

after the program is done it should look like this:
volim OR

so the program has to remove all the whitespaces before and after the strings, and those in between the words, so in the end there is just one between each word.
This what I have so far :
#include <stdio.h>

char *IzbaciViskaRazmake (char *Str)
{
    char *p = Str;
    char *p2 = Str;
    while(*p!='\0')
    {
        if(*p==' ')
            p++;
        else if(*p!=' ')
        {
            *p2 = *p;
            p2++;
            p++;
        }
    }
    *p2='\0';
    return Str;
}

int main() {
    char tekst[] = "        volim      OR      ";
    IzbaciViskaRazmake(tekst);
    printf("'%s'",tekst);
    return 0;
}

The problem with my code is that it removes all of the whitespaces so it gives the output
volimOR

How can I repare my code, so it keeps the whitespaces between the words.
PS- The use of pointers is a must.

A: You can do this by adding the first (whitespace) to *p2 and skipping the rest  (whitespace) using a while-loop.
Try this modified code , This will work :-
#include <stdio.h>

char *IzbaciViskaRazmake(char *Str)
{
    char *p = Str;
    char *p2 = Str;
    while (*p != '\0')
    {
        if (*p == ' ')
        {
            if (*p != *Str) // Not begining
            {
                *p2 = *p; // adding the first ' '
                p2++;
                p++;
            }
            while (*p == ' ') // skipping the rest ' '
            {
                p++;
            }
        }
        else
        {
            *p2 = *p;
            p2++;
            p++;
        }
    }
    if (*(p2 - 1) == ' ') //ends with space
    {
        p2--;
    }
    *p2 = '\0';

    return Str;
}

int main()
{
    char tekst[] = "        volim      OR      ";
    IzbaciViskaRazmake(tekst);
    printf("'%s'", tekst);
    return 0;
}

Output :-
'volim OR'

A: Anoopknrs code gave me an idea how this code actually works, so I have managed to quickly fix it. Here is the fully working, hopefully it can help some other people.
#include <stdio.h>
#include <string.h>

    char *IzbaciViskaRazmake (char *Str)
    {
        char *p = Str;
        char *p2 = Str;
        while(*p!='\0')
        {
            if(*p==' ')
                p++;
            else if(*p!=' ')
            {
                *p2 = *p;
                p2++;
                p++;
                if(*p==' ')
                    {
                        *p2=*p;
                        p2++;
                        p++;
                    }
            }
        }
        *(p2-1)='\0';
        return Str;
    }

    int main() {
        char tekst[] = "        volim      OR      ";
        IzbaciViskaRazmake(tekst);
        printf("'%s'",tekst);
        return 0;
    }

A: I think you should divide this into three separate tasks:

*

*Remove all whitespaces before first non-whitespace character

*Remove all whitespaces after last non-whitespace character

*Remove all whitespaces between words

This is three pretty separate tasks, and a reasonable assumption in your case seems to be to only count ' ' as whitespace. However, functions like this should i general return a NULL pointer on failure.
So we can declare this function:
char * trimSpaces(char *str) {
    if(!str) return NULL; // If we get a NULL pointer as input
    if((str = trimInitialSpaces(str)) == NULL) return NULL;
    if((str = trimEndingSpaces(str)) == NULL) return NULL;
    if ((str = trimSuperfluousSpaces(str)) == NULL) return NULL;
    return str;
}

Now you have three functions to write, but each of these is simpler than your original  function.
The implementation of trimIntitialSpaces could then look like this:
char * trimInitialSpaces(char *str) {
    if(!str) return NULL;
    char * ptr = str;
    int len = strlen(str); // Get length of string
    if(len == 0) return str; // If len is 0, there's nothing to do
    while(*ptr == ' ' && *ptr != '\0') ptr++; // Find first non-space
    // memmove can handle overlapping arrays, which memcpy cannot
    memmove(str, ptr, len-(ptr-str)+1);
    return str;
}

You have two functions left to write now. trimEndingSpaces(str) is slightly trickier, but all in all almost the same as trimInitialSpaces(str). And then you only have trimSuperfluosSpaces(str) left, which is the trickiest one. But now you can debug all these three separate. Good luck.


text:
Q: VS 2015 update 3 installation block I am trying install VS 2015 update 3 in my computer. and I am getting Error like this.

I have already install VS 2019 and 2017 professional.
Visual Studio 2015 Update 3 - Setup Blocked
won't work for me.
I have tried to install both LTR and update 3 version. same error getting.
Is that cause be the VS 2019 & VS 2017 prior installation?
Any Idea?

A: You asked:

Is that cause be the VS 2019 & VS 2017 prior installation?

The answer is probably yes.
First clean the installation of any other VS versions and then reinstall VS 2015 Update 3.
To clean VS, open command prompt as admin and run the following commands:
C:\> cd "Program Files (x86)\Microsoft Visual Studio\Installer"

C:\Program Files (x86)\Microsoft Visual Studio\Installer>InstallCleanup.exe