Get Android Emojis code

Question: I receive from a webservice emojis like \ud83d  \ude48   \ud83d  and I really don't have any problem to display them or send it between activities using this library (https://github.com/Will5/EMOJITextView)
The thing is that when I type a content with Emojis and the content is sent to a server, I need to send them encoded.
So what I do is to get encoding of each one, but the result is not the expected. (\u263a  \u1f60A   \u1f600  \uDe01 <---  this codes doesn't work)
How I can get the real encoding of an emoji typed in  an EditText?
Answer: You will need a customised EditText for this purpose too. Cause built in editText cannot handle such kind of encoding. The library link you gave already has a custom editText defined as below
<code>public class EmojiEditText extends EditText {

public EmojiEditText(Context context) {
    super(context);
}

public EmojiEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public EmojiEditText(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

public final String getTextWithEmojis() {
    return EmojiHandler.encodeJava(this.getText().toString());
}

public final void setTextWithEmojis(String text) {
    this.setText(EmojiHandler.decodeJava(text));
}

}
</code>
And the emoji handler resides here
So, you can easily use that editText for getting emoji input. Also get encoded emoji from it.
Comment: I use EmojiEditText, but nothing, here is the visual example.

[link](http://i68.tinypic.com/108ck86.jpg)

And the result after get Endoded is  **\u263A\u1F60A\u1F600\u1F601\uDE01**  <--- This codes are nothing and 1 emoji it's been lost...
Comment: i dont get your point.. can you say what s the problem you are facing? why  the term encoded is coming here? whatever you get from edittext u send it. no need to encode

Get Android Emojis code


Call a function if userinteraction is nil for 3 seconds

Question: Guys i need to call a function in such a view that if there is no user interaction for three seconds the function should be called
what should i do?
Can any one pls give a logic or link which help this?
Thanks
Answer: My recommendation is to override - (void)touchesBegan: withEvent: on that view.
When you receive a touch event, set a timer, and make its time 3 seconds. If you receive a touch and there is a timer, change its fire date to be 3 seconds after the touch time. When the timer fires, call the function, and set the timer to nil.
You can play with the movement, removals and cancellation methods to make your timer fire correctly and at the right time for the activity required.
Answer: Use NSTimer as:-
<code>- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
 UITouch *touch = [[event allTouches] anyObject];
 CGPoint location = [touch locationInView:self.view];
 if ([touch view] == self.view)
  {
    NSTimer *updateTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
  }
}

-(void)updateTime
{
NSLog(@"....Update Function Called....");
[self functionName];
}
</code>
Use this for calling function.Check it Hope it helps.Thanks :)
Comment: Note that this is certainly not a good idea from a performance perspective: You are firing a timer 3 times more often than required, and you are firing it even when no user interaction occurs EVEN IF the view is not onscreen. View Did Load is no judge for when the view actually came onscreen. Also note that this code is no-longer tied to the view. The view is not independently aware. This relies on the controller which isn't necessarily the best model. Overall seems a very hacked way to do it.
Comment: Your method when touchesBegan should also check for an existent timer. If one exists, push it back rather than just creating a new one. This ensures that the method does not get called until AFTER it occurs.

Note that this does not take into consideration touches moving as well, which would also need to delay the timer as well.


How do you use alternate costumes?

Question: Looking at the wiki page for any character, they show the sprites for the character in an alternate costume. How are these used or unlocked?
Answer: To use an alternate costume, you first have to beat the game with that character by killing your past.
Once you've done that, the alternate costume will be lying said character when you choose them at the start of the game.  You can just go and use it to switch to it.
Comment: You have to beat the game AND kill your past with that character.
Comment: To be clear, by beating the game - do you mean defeating the High Dragun?
Comment: @QuestionMarks No, I mean by killing your past just like PapaStan said.

How do you use alternate costumes?


Interpolation inequality in sobolev space

Question: Let $U$ be a bounded, connected open subset of $\mathbb R^n$ with $C^1$ boundary $\partial U$. Asume $|\beta| \leq k-1$ and $k$ is a integer. Show that for each $\epsilon >0$ there exists a constant $C_\epsilon$, such that
$||\partial^\beta u||_{L^p(U)} \leq \epsilon \|u\|_{W^{k,p}(U)} + C_\epsilon\|u\|_{L^{p}(U)}$
For each function $u$ in $W^{k,p}(U)$ (sobolev space)
Hint: Argue by contradiction and use Rellich-Kondrachov theorem.
Any ideas?
Answer: We have $\|\partial^\beta u\|_{L^p(U)} \leq \|u\|_{W^{k-1,p}(U)}$
Also, by the theorem, $W^{k,p}(U) \rightarrow W^{k-1,p}(U)$ is compact.
Now, suppose there is no $C_\epsilon$. Then we get a sequence $u_n \in W^{k,p}(U)$ (normalize so these are all norm 1) violating it with $n$ in place of $C_\epsilon$. That is, $\|u_n\|_{W^{k-1,p}} \geq \epsilon + n \|u_n\|_{L^p(U)}$.
There's a subsequence which is convergent in $W^{k-1,p}(U)$. Call the limit $u$.
Now, what can you say about $\|u\|_{L^p(U)}$?
Comment: $\|u\|_{L^p(U)}=0$ because the the relation $\|u\|_{W^{k-1,p}} \geq \epsilon + n \|u\|_{L^p(U)}$. But $u_n$ are norm 1. contradiction?   I have a question, why $W^{k,p}(U) \rightarrow W^{k-1,p}(U)$ is compact? The kondrachov theorem is different.
Comment: Rellich-Kondrachov gives: $L^p$ bounds for (a function and its) derivatives imply convergence of some subsequence in $L^p$, which implies $W^{k,p}(U) \rightarrow W^{k-1,p}(U)$ compact by induction. You don't actually need this for all of $W^{k-1,p}$; you could instead show $W^{k,p}(U) \rightarrow W^{1,p}(U)$ sending $u$ to $\partial^\beta u$ is bounded, then use the theorem to show that included to $L^p(U)$ is compact.
Answer: Actually you can get, for a fixed $\epsilon>0$, that for any $u\in W^{m,p}(\Omega)$
$$
\|{u}\|_{W^{m,p}}\leq \epsilon\|{D^\alpha u}\|_{L^p}+C_{\epsilon}\|{u}\|_{L^q},
$$
where $|{\alpha}|=m$. Usually we just take $q=p$ but if domain is good enough and by embedding we could extend $q$ to where embedding would go.
This theorem states that the extreme term (The highest and lowest) in a sum often already suffice to control the intermediate terms. This is not only true is Sobolev space but also in $C^k$ spcase, Holder space...
Anyhow, the hint by @aes is good enough and here I just give you more information. If you want to find the prove of this, please go to check Adams book, theorem 5.2.
Also, this is actually gives you an equivalent norm for each fixed $\epsilon$.


can't install mbtiles plugin in geoserver

Question: I am trying to install mbtiles plugin for geoserver 2.9. I have successfully installed geoserver in tomcat 7.0 (in windows 10).
I downloaded geoserver from [http://ares.opengeo.org/geoserver/master/] It works fine without any plugin installed.
But when I try to install plugin mbtiles into the lib folder it gives me error message.
HTTP Status 404 - /geoserver
type Status report
message /geoserver
description The requested resource is not available.
Apache Tomcat/7.0.59

I know my tomcat is working fine and geoserver is there in the webapps folder.
I downloaded the mbtiles plugin from: [http://ares.opengeo.org/geoserver/master/community-2015-11-30/]. I know that my version of mbtiles plugin and geoserver is same. That is what was mentioned in geoserver documentation page.
I have 3 files in the mbtiles plugin:
gs-mbtiles-2.9-SNAPSHOT.jar
gt-mbtiles-15-SNAPSHOT.jar
sqlite-jdbc-3.8.6.jar

If I remove those files from lib folder then my geoserver works fine.
Can anyone suggest what am I missing here??
I tried with other versions of geoserver but I get the same error message like above.
Any help is appreciated.
Cheers
Comment: what does the log file say?
Comment: Have you found a solultion? I'm encountering the same problem..
Comment: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mbtilesProcess' defined in URL [jar:file:/C:/Users/Me/Documents/apache-tomcat-7.0.68-windows-x64/apache-tomcat-7.0.68/webapps/geoserver/WEB-INF/lib/gs-mbtiles-2.8-SNAPSHOT.jar!/applicationContext.xml]: Cannot resolve reference to bean 'wpsResourceManager' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'wpsResourceManager' is defined. - @iant
Answer: I had this problem for a while. At first look at log file which is in this directory \logs\wrapper.log it shows the errors and why they prevent running geoserver's service.
One of dependencies which mbtile plug-in has is wps plug-in. This plug-in is not loaded into geoserver by default. So before installing mbtiles plug-in at first install geoserver wps plug-in from this link
Select and download wps
Another thing that I have fount is that some times sqlite-jdbc-3.8.6.jar which is in mbtile's zip file has a bug.It is quite an old version. So if your problem exists replace this file with newest version from here
sqlite-jdbc download link
I hope this helps some one. If yes please vote it up.
Answer: You have to put it on:
/usr/share/opengeo/geoexplorer/WEB-INF/lib

Source: http://suite.opengeo.org/docs/latest/intro/installation/redhat/postinstall.html
Well, since opengeo-geoserver is a custom build from geoserver, it has some modifications that won't let you simply run the original geoserver plugins.
You'll have to open the jars and decompile the class files to modify the code of the plugin to match the structure of opengeo-geoserver...


Displaying Data from DataGridView in TextBox Visual Basic

Question: I am creating a program in Visual Basic where I have a DataGridView connected to an access database and I want to select the row and have the items in the row (firstname and surname) to be displayed in a textbox (txtname) when then button select is pressed. I so far have been able to get one column to display so it either displays first name or last name but it wont display both.
Dim currentCellData As String
    Dim StaffName As String
    For i As Integer = 0 To staffList.SelectedCells.Count - 1
        Dim colindex = staffList.SelectedCells.Item(i).ColumnIndex
        Dim rowindex = staffList.SelectedCells.Item(i).RowIndex
        currentCellData = staffList.Item(colindex, rowindex).Value.ToString
        StaffName = currentCellData
        txtName.Text = StaffName
    Next

Comment: are there 2 columns in total, with one populated with the firstname, and the other populated with the last name?
Comment: @Jaxi yes there are two columns one with the first name and one with the last name
Comment: So you're asking how to concatenate two `Strings`?
Answer: You can use concatenation, and there is no need for the for loop.
This should work if I have understood correctly:
txtName.Text = staffList.Item(0, rowindex).Value.ToString & " " & staffList.Item(1, rowindex).Value.ToString


jQuery - use javascript after loading content with Ajax

Question: I'd like to load the flexslider gallery with jQuery when an anchor element is been clicked.
The gallery shall be loaded in div#slider-loader
The problem is that the HTML is loaded properly, but the Javascript seems not to affect the injected elements even though I read that in this cases I shall use .on().
<code>$(document).on('click', '.cliccami' , function() {
        var href = $(this).attr('href');
        $('#slider-loader').load(href);
        return false;
});
</code>
Thank you in advance!
--

use a call back function to preform action whaen the load is completed like so

Sweet! it worked! although with such solution the .on() event become useless.
Now I came up with this and it works:
<code>$('.cliccami').click(function() {
    var href = $(this).attr('href');
    var gallery_height = $('.flexslider').css('height');
    $('#slider-loader').hide().fadeIn('slow', 'swing').load(href , function(){
        $('.flexslider').flexslider({
            animation: "slide"
        });

    })
    return false;
});
</code>
The only problem is the injection of the code is very scattering.
I would like to make the div container '#slider-loader' adjust its height according to the '.flexslider' height with a smooth animation.
What I've tried to do is:
<code>$(document).ready(function(){
    $('#slider-loader').hide();
});

$(document).on( 'click', '.cliccami', function() {

    var href = $(this).attr('href');
    var gallery_height = $('.flex-viewport').css('height');

    $('#slider-loader').load(href , function(){
        $('.flexslider').flexslider({
                animation: "slide"
        });
        $('#slider-loader').css('height' , gallery_height);
        $('#slider-loader').slideDown(10000);
    });
    return false;
});
</code>
The problem is that once i click the anchor element the #slider-container start to slideDown showing its content but it dosen't do it for the whole .flexslider height which I've set as variable and gave to him with the .css() method. It slideDown for few pixel and then it suddenly became of the entire .flexslider height.
Comment: You should be attaching your `click` event to an anchor element, not the `document`.
Comment: @Aiias No, the event should be bound to the document and delegated to the anchor, such as what he is doing.
Comment: Are you running this Javascript after the page has fully loaded via [$(document).ready()](http://api.jquery.com/ready/) ?
Comment: There's nothing wrong with the code you've provided, the problem must be elsewhere. Check classnames/id names to make sure you're selecting the right elements.
Comment: @Alias I wasn't... But also after I've inserted everything in $(document).ready it still not works.
Answer: use a call back function to preform action whaen the load is completed like so
<code>$(document).on('click', '.cliccami' , function() {
        var href = $(this).attr('href');
        $('#slider-loader').load(href , function(){
                                  // some thing to happen when loading is done
                                });
        return false;
});
</code>
Comment: Sorry, what am I supposed to make happen after loading the html content?
Comment: `Javascript seems not to affect the injected elements even though` , may be apply the javascript to the loaded content ?!
Comment: Sweet! this works! Although with this method the .on() method become useless. So now I have the same script as my original question with callback function.
Comment: then just wrap that in a function and call it in here


Why are expired cookies not removed in Firefox v117.0.1 using nookies package in Next.js?

Question: I'm working on a Next.js project that uses the [nookies] package to set and delete cookies. I have two cookies in my project that have an expire time. I set the cookies using nookies.set(ctx, name, value, options), where options includes the maxAge property. I expect the cookies to be removed from the browser when they expire, but they are not. This only happens in Firefox v117.0.1, other browsers work fine. Here is some sample code of how I set the cookies after login:
export const setUaaCookie = (access: string, refresh?: string): void => {
  const accessExpires = GetTokenExpireTime(access);
  const refreshExpires = GetTokenExpireTime(refresh);

  setCookie('access_token', access, {
    expires: accessExpires,
    path: '/',
    domain: process.env.NEXT_PUBLIC_COOKIE_DOMAIN,
  });
  setCookie('refresh_token', refresh, {
    expires: refreshExpires,
    path: '/',
    domain: process.env.NEXT_PUBLIC_COOKIE_DOMAIN,
  });
  request.setHeader('Authorization', `Bearer ${access}`);
};

And these cookies should be automatically deleted from the browser after they expire.
I have a custom AuthProvider component that wraps around my app and handles the authentication logic. Here is the code of my AuthProvider component:
  const authenticate = (): void => {
    // get browser cookies
    const cookies = parseCookies();
    const hasToken = cookies.refresh_token;
    let isPrivateRoute = true;

    const publicRoutes = [
      '/account/login',
      '/account/otp-login',
      '/account/signup',
      '/account/forget-password',
    ];

    // current route is a public route or a private route
    if (
      publicRoutes.find(item => router.asPath.includes(item)) ||
      router.asPath === '/'
    )
      isPrivateRoute = false;

    if (isPrivateRoute && !hasToken) {
      goToLoginPage();
      setLoading(true);
      return;
    }

    if (!isPrivateRoute && hasToken) {
      const next = router.query.next || '/market-summary';
      router.push(next.toString());
      setLoading(true);
      return;
    }
    setLoading(false);
  };

  useEffect(() => {
    authenticate();
  }, [router]);

After I log out automatically, when I log in again in the AuthProvider file, the token logs are still undefiend, and after logging in, we are redirected to the login page again. And then we can log in a second time. In fact, we have to log in twice to enter the site.
This issue was recently created and did not exist in older versions of Firefox
Why is this happening? How can I fix this issue with nookies package in Next.js and Firefox v117.0.1? How can I make sure that expired or deleted cookies are removed from the browser and do not interfere with my auto logout feature?
Answer: I'm facing the same issue with Firefox and auth tokens. I don't know exactly why Firefox doesn't remove expired cookies but what I saw is that even if you update it, Firefox keep in mind that the cookie is expired. This issue appeared with the Total Cookie Protection mechanism, there is an open bug in Firefox about that ( old one but set back to open now )
The issue

First login => set cookies access_token and refresh_token
Wait for cookie expires => cookie is expired but still present in Firefox storage.
Login => replace cookies access_token and refresh_token
First request => retrieve the cookie access_token that is considered as expired for Firefox so the cookie is not sent in your request.
The response is 401 / 403, then the logout is triggered ( cookie deleted )
Login => set new cookies access_token and refresh_token
First request => retrieve the cookie access_token that is live
Response is 20X, everything is fine

Fixes

Use cookie set by server directly with httpOnly: true (can be hard to implement depending on your architecture, not tried)
Switch to localStorage (easier but not the recommended option, it's still exposed to XSS attacks, same as cookie storage used here)
Usage of in memory token or sessionStorage (but having issue with opening new tab / reload page)

Here is an implementation of localStorage that you can add :
const AUTH_KEY = 'auth';
type AuthStorage = {
  accessToken: string;
  refreshToken: string;
  expires: Date;
};

function getAuthCredential(): AuthStorage | undefined {
    const token = localStorage.getItem(AUTH_KEY);
    if (!token) {
      return undefined
    }
    const parsedToken = JSON.parse(token);
    // This replace the expire of token
    if (new Date(parsedToken.expires) > new Date()) {
      return parsedToken;
    } else {
      return undefined;
    }
  }

function setAuthCredential(): void {
    setAuthCredential({
      accessToken: auth.accessToken,
      refreshToken: auth.refreshToken,
      expires: GetTokenExpireTime(refresh),
    });
}

const hasToken = getAuthCredential();

About security (XSS / CSRF) the current cookie is used in JS so a XSS attack can get it, the usage of localStorage can reduce the risk of CSRF attack (depending on your cookie SameSite parameter), but keep in mind that this  solution is not the best one for this issue.
Related links
OWASP - Token Storage on Client Side
auth0 - Token Storage
I hope it will help you,


How to fix incompatible types: java.lang.Object cannot be converted to java.util.List

Question: I have a hashmap defined like this that I cant change
private Map<String, Object> attributes;

The object is a list of Strings (sometimes size == 1, other times > 1).
I have an instance of the attributes map later on in the execution. I am wanna get the Object as List.
This:
List<String> outputs = attributes.get("keys");

throws this error.
incompatible types: java.lang.Object cannot be converted to java.util.List<java.lang.String>

How can I fix it?
Comment: `List outputs = (List) attributes.get("keys");`
Answer: Use an explicit cast:
List<String> outputs = (List<String>) attributes.get("keys");

Note that this is an unchecked cast and may throw ClassCastException at runtime.
Comment: You should explain that this is an unchecked cast, and what that means for type safety.


Insert line at start of file with Ansible

Question: You can insert a line at the end of a file or before/after some regex with lineinfile. But how do I insert a line at the start of a file?
Answer: From the link to the module manual you included in the question:

insertbefore  Used with state=present. If specified, the line will be inserted before the last match of specified regular expression. A value is available; BOF for inserting the line at the beginning of the file. If specified regular expression has no matches, the line will be inserted at the end of the file. May not be used with backrefs.

So:
- lineinfile:
    path: path/to/file
    insertbefore: BOF
    line: my_line


.replacement.highlight = true in MS Word VBA does not work

Question: I'm working on a larger project in Excel VBA and encountered the following problem. I'm using VBA to make Excel compile a template in MS Word. I wanted to highlight certain phrases in the template yellow. It used to work at some point, but then it stopped, for no apparent reason. When I run the code now, the part gets executed without errors, but the words don't get highlighted, even though I am sure they are there in the template. I used debug.print to find out the values of the .replacement.highlight value, and it shows me 9999999 in the Immediate window, and -1 if I hover the mouse cursor over the expression in break mode.
The relevant fragment of the code is quoted below:
Dim WdApp As Word.Application
Set WdApp = New Word.Application
With WdApp
    .ActiveDocument.Select
    With .Selection.Find
    'the code creating the document and writing the template continues here
        .ClearFormatting
        .Text = "{Optional: Please also confirm the terms of transactions and other key information (for example: rights of return, allowances and rebates, special agreements, payment terms, incoterms, etc.) which may affect the accounting for the transactions.}"
        .Replacement.Highlight = True
        .Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue

        .ClearFormatting
        .Text = PlaceholderAdditionalInfoRequest
        .Replacement.Text = .Text
        .Replacement.Highlight = True
        .Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue

        .ClearFormatting
        .Text = "<<<@@@Client's Letterhead@@@>>>"
        .Replacement.Text = .Text
        .Replacement.Highlight = True
        .Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue

        .ClearFormatting
        .Text = "{Optional: A statement of account with the above invoices marked is attached. ALTERNATIVELY: Copies of the above invoices are attached.}"
        .Replacement.Highlight = True
        .Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue
   End With
End With

Does any one know what's going on? I'd appreciate any pointers, especially if expressed in plain English :) I'm new to VBA and don't have a formal education in programming.
Best regards,
Tyro
Comment: I haven't tried your code but have you tried using ".Replacement.ClearFormatting" as well as .ClearFormatting before you set up .Replacement.Highlight? (Just in case something is "sticking" when it shouldn't)
Answer: Try this:
Options.DefaultHighlightColorIndex = wdYellow

before:
With .Selection.Find

It seems that you are applying the Find function not to the template but to a document activated before the creation of the template.
Try moving these lines:
the code creating the document and writing the template continues here…
before these line:
.ActiveDocument.Select
    With .Selection.Find
Make the Word Application WdApp visible (WdApp.Visible = True) to see what the code is doing and ensure it's closed ( WdApp.Quit) after the task is completed.
Comment: At first it seemed like it would work, but then it stopped. It seems like restarting the system (not just the application) helps, but the issue is rather erratic, I'm finding it hard to pin it down to any particular scenario. Has anyone been experiencing similar issues?
Comment: Hi, not yet. I'v left my laptop in the office so can't give it a try over the weekend, but I'll try it tomorrow and get back to you. Still, I don't think I'm applying the .find function to the wrong document, because if I type .Replacement.Text= "abc" it will get replaced in the appropriate document. I would also prefer not to quit the document at the end of the sub routine to allow the user to edit the template. I do set WdApp to nothing when the sub ends though, I think. I'll try the .Replacement.ClearFormatting and see how that works.
Comment: I guess one of the solutions worked. I haven't had the problem ever since. However, I've not had time to test it extensively, as I was busy with other stuff,too. Anyways, thank for help.


update names based on columns

Question: I would like update the names based on two columns
My example has 3 originial columns
df <- data.frame(name1 = c("a", "a", "a", "a", 'a', NA, NA, NA),
                 name2 = c("b", "b", "b", "b", "c", NA, NA, NA),
                 name3 = c("b", "b", "b", "b", "c", "a", "a", "a"))

df
  name1 name2 name3
1     a     b     b
2     a     b     b
3     a     b     b
4     a     b     b
5     a     c     c
6  <NA>  <NA>     a
7  <NA>  <NA>     a
8  <NA>  <NA>     a

I would like to update column name3 (or even create a new column) saying that if name1 == a, and name2 == NA, then the a character in name3 will be replaced by b in column name2.
My desired output something like
  name1 name2 name3
1     a     b     b
2     a     b     b
3     a     b     b
4     a     b     b
5     a     c     c
6  <NA>  <NA>     b
7  <NA>  <NA>     b
8  <NA>  <NA>     b

So far, i am using this df %>% mutate(name3 = ifelse(name1 == "a" & is.na(name2), "b", name3)), but now NA appeared. Any suggestions for this?
Comment: In your expected output `name1 == "a"` is `FALSE`, both `name1` and `name2` are `NA`, why has `name3` changed?
Comment: I just wanted to change the `b` in `name3` based on the condition that I want from `name1` and `name2`. Since the real dataset is so messy, so I want to split several cases that I think would be nice to solve. Thats why I call `a` and NA from name1 and name2 respectively
Answer: We can replace == with %in% to eliminate the NAs, because R evaluates NA %in% x to FALSE, but NA==x to NA
df %>% mutate(name3 = ifelse(name1 %in% 'a' & is.na(name2), 'b', name3))

Comment: I think it was at same time.+1
Comment: Timmed to the exact same second! +1
Comment: yes, and the outcome taking `a` not `b` is not our expectation, right
Answer: We could use a case_when or ifelse statement:
library(dplyr)
df %>%
  mutate(name3 = case_when(any(name1 %in% "a") &
                             is.na(name2) ~ "b",
                           TRUE ~ name3))

or:
df %>%
  mutate(name3 = ifelse(any(name1 %in% "a") &
                          is.na(name2), "b", name3))

  name1 name2 name3
1     a     b     b
2     a     b     b
3     a     b     b
4     a     b     b
5     a     c     c
6  <NA>  <NA>     b
7  <NA>  <NA>     b
8  <NA>  <NA>     b

Comment: Please see my update!
Comment: I  think the output is `b` will compensate for `a` instead right
Answer: Base R
df$name3 <- ifelse(any(df$name1 == "a") & is.na(df$name2), "b", df$name3)

dplyr
library(dplyr)

df %>%
  mutate(name3 = case_when(
    any(name1 == "a") & is.na(name2) ~ "b",
    TRUE ~ name3
  ))
#  name1 name2 name3
#1     a     b     b
#2     a     b     b
#3     a     b     b
#4     a     b     b
#5     a     c     c
#6  <NA>  <NA>     b
#7  <NA>  <NA>     b
#8  <NA>  <NA>     b

Comment: Many thanks for the `any`!
Comment: anyway, thank you to provide your answer. It worked well, sir.

update names based on columns


How do I install Monodevelop 2.10 or later on 12.04?

Question: sudo apt-get install monodevelop installs MonoDevelop 2.8.x. The official site, http://monodevelop.com/Download, states that "Packages for MonoDevelop 22.214.171.124 not yet available. The latest available version is MonoDevelop 220.127.116.11".
I want to use the F# plugin for MonoDevelop which supposedly is only available for MonoDevelop 2.10.x and latter releases.
How do I install MonoDevelop 2.10.x or latter on my Ubuntu? Or is it not possible at all?
Answer: You can install MonoDevelop 3.0.x (stable) via this PPA.
sudo apt-add-repository ppa:directhex/ppa
sudo apt-get update
sudo apt-get install monodevelop

Please note that Monodevelop 3.0 will be included in Quantal 12.10.

Note: If you are unfamiliar with installing third-party software from PPAs, you may want to refer to these questions:

What are PPAs and how do I use them?
Are PPA's safe to add to my system and what are some "red flags" to watch out for?
Comment: Glad to have helped, happy coding! :)


Unable to play sound with AudioPlayer package

Question: I am trying to play a sound from my asset directory in dart, I have added the required lines of code and also included the asset directory in pubspec.yaml.
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';

void main() {
  return runApp(
    MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child: Center(
            child: TextButton(
                onPressed: () {
                  AudioPlayer player = AudioPlayer();

                  player.play(DeviceFileSource('note1.wav'));
                },
                child: Text('Click Me'),
            ),
          ),
        ),
      ),
    )
  );
}

Answer: Try to change the source of the audio by using AssetSource() and make sure to add the source of your audio in the yaml file
onPressed: () {
    AudioPlayer player = AudioPlayer();
    player.play(AssetSource('audio.mp3'));
},

Answer: You have to use AssetSource for this because as per the documentation of AudioPlayer:

DeviceFileSource: [is used to] access a file in the user's device, probably selected by a file picker
AssetSource: [is used to] play an asset bundled with your app, normally within the assets directory

Don't worry, this gave me some grief too and the answer above pointed me in the right direction. I just wanted to take an extra step to understand why, hope this helps!


Max span on 2x4 truss

Question: I am refitting an old shop above my garage to be an ADU. It was built in the late 70s / early 80s, and the truss system is 2x4 trusses on 22" centers. The trusses are professionally built & engineered trusses, with metal plates at the joints, so it wasn't a "hand-rolled" truss situation.
The span across the truss from end to end is about 28', with no bearing wall or support at midspan. It's held snow load and been fine (no visible sagging etc.) for 40 years, but that span seems pretty wide to me-- I'm concerned that adding 5/8" drywall to the lid will be a lot of additional weight on a truss system that already seems a little marginal.
I know this is more of an engineering question, but I'm wondering if this setup would raise concerns with the experienced builders around here. I had a contractor friend take a look and he didn't mention any issue, but I had an engineer friend say it looked like a pretty big span for that size of truss, though it'd "probably be fine". Any consensus on this or way to check the load?
Comment: It's entirely in how it was designed. The fact that it's made from 2x4 material is normal and not a concern - the strength of a truss is in the overall shape, and if it was designed with 2x4's having adequate strength to do what it was designed to do, then it will do that. - My roof truss is 24 feet, 2x4, designed for a 50 lb snow load (including the case where it all blows off one side and becomes a snow-drift on the other side) and to carry drywall and insulation on the bottom chords. You ***might*** be able to track down documents from an old permit application.
Comment: The 2x4 dimension seems incorrect - 2"x4" or 2"x4'? Are you adding the ceiling panel, or cladding the walls? It makes a lot of differences.
Comment: Trusses are usually installed 24" apart. How are you going to use the space as a room? If you install wallboard between the trusses, how are you going to install ceiling insulation first? (Btw, you know the bottom chord of the trusses are too weak for floor joists.)
Answer: There is no "general" answer here.  Trusses are engineered products and when engineers, architects, or builders select them, the specifications are available to them from the manufacturer.
You're here after-the-fact and trying to get a specification for an unknown (at this time at least) product.  That's not going to happen.
Some suggestions:

Did you get any paperwork with the property that might have such documents included?
Check the trusses and see if they have a manufacturer's label or stamp.  This might help you track down the company and see if they can supply you with the needed information.
Hire an engineer to evaluate the trusses and the structure and give you an answer to your question of whether or not these will handle the additional static load. BTW - unless your friend is a licensed professional engineer in your state and is experienced in this area, his opinion is effectively worthless.
Comment: "unless your friend is a licensed professional engineer in your state and is experienced in this area, his opinion is effectively worthless". Frankly, consider us all friends, none of whom are licensed engineers in your state. #3 is, most likely, the only legit option at this point.

Max span on 2x4 truss


Passing date into NSURL

Question: I m trying to pass date into NSURL but I cant success. if anybody know about that then please tell me...
suppose i have date like January 1, 2000
I m trying to pass it through NSURL but i cant success.
please help me
Thanks....
Answer: Use NSDateFormatter and convert your date to yyyy_MM_DD format

Passing date into NSURL


How to extract a field with Gson?

Question: I have this json code (it's a part of entire json-code):
{
  "numFound": 41,
  "edges": [
    {
      "endLemmas": "albero",
      "context": "/ctx/all",
      "end": "/c/it/albero/v",
      "features": [
        "/c/it/alberatura /r/ConceptuallyRelatedTo -",
        "/c/it/alberatura - /c/it/albero/v",
        "- /r/ConceptuallyRelatedTo /c/it/albero/v"
      ],
      "license": "/l/CC/By-SA",
      "start": "/c/it/alberatura",
      "startLemmas": "alberatura",
      "text": [
        "albero",
        "alberatura"
      ],
      "uri": "/a/[/r/ConceptuallyRelatedTo/,/c/it/alberatura/,/c/it/albero/v/]",
      "weight": 1.0,
      "dataset": "/d/conceptnet/5/combined-sa",
      "sources": [
        "/and/[/s/rule/wiktionary_monolingual_definitions/,/s/web/en.wiktionary.org/]"
      ],
      "score": 7.81056,
      "rel": "/r/ConceptuallyRelatedTo",
      "timestamp": "2013-09-12T16:30:04.157Z",
      "nodes": [
        "/r/ConceptuallyRelatedTo",
        "/c/it/albero/v",
        "/c/it/alberatura"
      ],
      "id": "/e/021aa72c7605d9d2000f0774a0bf9042699fa6ee",
      "surfaceText": "[[alberatura]] ConceptuallyRelatedTo [[albero]]"
    },

How to do I extract the field "features" ?
I can extract some fields, like "context" or "end", but for "features" I can't! :(
My Java code:
   public static void main(String[] args) throws IOException {

   URL url = new URL("http://conceptnet5.media.mit.edu/data/5.1/c/it/albero?get=context");
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      conn.setRequestProperty("Accept", "application/json");
      BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

      String inputLine;

      GsonCNItem gsonCNObj = new Gson().fromJson(br, GsonCNItem.class);

      for (int i = 0; i < 3; i++) {
        try{
          gsonCNObj.getCNThing(i);
        }catch (IndexOutOfBoundsException e) {}
      }
    }

My GsonCNItem class:
public class GsonCNItem {

  private String context;
  private String end;
  private List<GsonCNItem> edges;

  public List<GsonCNItem> getCNedges(){
    return edges;
  }

 public void getCNThing (int i){
    System.out.println(edges.get(i));
  }

  public String toString(){
    return String.format("Context: %s\nend: %s",context,end);
  }
}

Thanks for help!
Comment: No variable defined for `features` in Class `GsonCNItem` may be you can use `String[] features`
Answer: But your class for deserializing JSON is wrong, it should be as following:
public class MyJson {
    private long numFound;
    private ArrayList<GsonCNItem> edges;

    public ArrayList<GsonCNItem> getEdges(){
        return getEdges();
    }

    public class GsonCNItem{
        private String endLemmas;
        private String context;
        private String end;
        private ArrayList<String> features;
        ...
        private ArrayList<String> text;
        ...

        public ArrayList<String> getFeatures(){
            return features;
        }

        public ArrayList<String> getText(){
            return text;
        }

        public String toString(){
            return String.format("Context: %s\nend: %s",context,end);
        }
    }
}

Answer: Add a variable List<String> to your POGO class(GsonCNItem) to parse features array.
public class GsonCNItem {
    private String context;
    private String end;

    private List<String> features;

    //Setters and Getters
}

How to extract a field with Gson?


Using Google Mobile Vision FaceDetector to detect face on onPreviewFrame callback?

Question: I used com.google.android.gms.vision.face.FaceDetector to detect faces in the camera preview callback shown below:
faceDetector = new FaceDetector.Builder(this)
                .setTrackingEnabled(false)
                .setMode(FaceDetector.FAST_MODE)
                .setLandmarkType(FaceDetector.ALL_LANDMARKS)
                .build();

mCamera.setPreviewCallbackWithBuffer(new Camera.PreviewCallback() {
    @Override
    public void onPreviewFrame(final byte[] data, Camera camera) {
        if (faceDetector.isOperational()) {
            int format = camera.getParameters().getPreviewFormat();
            int width = camera.getParameters().getPreviewSize().width;
            int height = camera.getParameters().getPreviewSize().height;

            Frame frame = new Frame.Builder().setImageData(ByteBuffer.wrap(data), width, height, format).build();
            SparseArray<Face> faces = faceDetector.detect(frame);
            Log.d("TEST", "Num faces = " + faces.size());
        }

        mSurfaceView.requestRender();

        camera.addCallbackBuffer(mImageBuffer);
    }
});

However, the output is always Num faces = 0. How can I fix this?
Answer: You made one mistake. Your code must look like this:
faceDetector = new FaceDetector.Builder(this)
                .setTrackingEnabled(false)
                .setMode(FaceDetector.FAST_MODE)
                .setLandmarkType(FaceDetector.ALL_LANDMARKS)
                .build();

mCamera.setPreviewCallbackWithBuffer(new Camera.PreviewCallback() {
    @Override
    public void onPreviewFrame(final byte[] data, Camera camera) {
        if(!faceDetector.isOperational()){
            Log.e("TEST", "Could not set up the face detector!");
        } else {
            int format = camera.getParameters().getPreviewFormat();
            int width = camera.getParameters().getPreviewSize().width;
            int height = camera.getParameters().getPreviewSize().height;

            Frame frame = new Frame.Builder().setImageData(ByteBuffer.wrap(data), width, height, format).build();
            SparseArray<Face> faces = faceDetector.detect(frame);
            Log.d("TEST", "Num faces = " + faces.size());
        }

        mSurfaceView.requestRender();

        camera.addCallbackBuffer(mImageBuffer);
    }
});


What is this weird sword Icon that appears when I use a tool or weapon?

Question: I haven't played Minecraft for a long time, so when I came back, there were a lot of new features. One of them that I don't understand is that sometimes when I swing my pickaxe or my sword, there is a weird sword icon below the crosshair:

I thought is might be a cooldown bar, but it resets every time I swing my sword. What does this icon do and why is it there?
Answer: In minecraft 1.9 you cannot spam weapons. They now have cooldown timers. Weapons make most damage if they are fully charged. So you have to wait some time after you hit.
EDIT:
Note:

In Minecraft 1.9 an axe makes more damage as a sword of same type. It has longer cooldown tho.
The fastest cooldown has a hoe.
Answer: Here's what the Minecraft Wiki says about it:

Combat

New "attack strength" combat mechanic:

A meter shows up after switching items or attacking.

Damage done depends on the fullness of the meter, with a   quadratic reduction (attack does 20%–100% of normal damage as the meter fills).
Fills at different rates depending on the new attack speed attribute (see table on the changes to gameplay section for a complete list).

The haste effect will cause the meter to fill faster

Can be displayed next to the hotbar (left or right based on the player's main hand), under the crosshair or turned off.

Looks like the icon for the strength effect on the side of the hotbar, or like a dagger under the crosshair.
This is controlled in video settings.

A cooldown animation is displayed of the tool slowly being lifted up, when first switching to it.

Plays sounds when attacked strongly, weakly, and parried.

You can also check the Mojang update article.


How can I stop the world from leaking?

Question: My FTB Direwolf20 server is leaking!
2013-04-11 22:29:24 [SEVERE] [ForgeModLoader] Detected leaking worlds in memory. There are 4 worlds that appear to be persisting. A mod is likely caching the world incorrectly
2013-04-11 22:29:24 [SEVERE] [ForgeModLoader] The world 6e929b52 (world) has leaked.
2013-04-11 22:29:24 [SEVERE] [ForgeModLoader] The world 28db4ccf (world) has leaked.
2013-04-11 22:29:34 [WARNING] [Minecraft] Can't keep up! Did the system time change, or is the server overloaded?

This is on a server I've just started up. What can I do?
Comment: I recommend using diapers on the server until they're at least 60 days of uptime old
Comment: Forge added this check recently. Worlds were (memory) leaking before, but now we can at least see it in the logs.
Comment: you can add a single chunkloader in each created dimension so it doesn't unload ;)
Answer: According to this Feed the Beast forum, it is related to the loading and unloading of worlds. This applies to an issue Forge is having with the ChickenChunks mod because of the way it unloads worlds. Try going to your Advanced Java Options in the launcher (options --> Advanced options) and entering -XX:MaxPermSize=256m -XX:PermSize=128M in the Additional Java Perimeters field.
Linking to enough Mystcraft worlds and Twilight Forest multiple times can also be the cause of severe memory leaks. There also exists a semi-rare bug with causes FML (Forge ModLoader) to leak memory no matter what you do. Another common solution is to disable all of the wireless redstone mods, such as RedPower 2 and WRCBE. Basically, if you had made any Twilight Forest and Mystcraft worlds before, it is likely to happen.
Direwolf20 gives his two cents about the problem here:
Answer: Tell the mod author, there's nothing you can do (or should do) about this issue.
When mods work with different dimensions (nether, the end etc.) they often leave certain chunks loaded accidentally. This isn't normally a problem, but if lots of your mods are doing it (and with many dimensions, thanks mystcraft) it can cause quite bad memory leaks.
Just one mod doing this isn't a problem, so ignore it, and maybe bug the mod author to fix their small coding error.

How can I stop the world from leaking?


How to randomly swap shapes' positions in specific locations

Question: HELP! I'm trying to create a memory game and I'm not too sure how to randomize the shapes' positions in set x and y locations. They can't overlap so they must be randomized in 12 different locations every time the user starts the program.
Answer: Store your x and y positions in arrays
var xArray=new Array();
var yArray=new Array();

xArray[0]=50;
yArray[0]=50;
xArray[1]=100;
yArray[1]=50;
xArray[2]=150;
yArray[2]=50;
...

Create an array of values for each of your shapes
var valueArray=new Array(0,1,2.....);

Shuffle the values in this array - as3 random array - randomize array - actionscript 3
Set you shape's positions
shape0.x=xArray[valueArray[0]];
shape0.y=yArray[valueArray[0]];
shape1.x=xArray[valueArray[1]];
shape1.y=yArray[valueArray[1]];
shape2.x=xArray[valueArray[2]];
shape2.y=yArray[valueArray[2]];

Answer: try that:
function randomSort(a:*, b:*):Number
{
    if (Math.random() < 0.5) return -1;
    else return 1;
}

// Push 12 positions as new Point() in an array.
var positions:Array = [ new Point(12, 42), new Point(43, 56), new Point(43,87) ]; // ...add 12 positions
var mcs:Array = [mc1, mc2, mc3]; // ...add 12 mcs

positions.sort(randomSort);

// link randomized position to MovieClips:
for (var i:int = 0, l:int = positions.length; i < l, i++ ) {
    var mc:MovieClip = mcs[i];
    var point:Point = positions[i];
    mc.x = point.x;
    mc.y = point.y;
}


White marks appearing on my popup menu

Question: I've got a popup menu div that is shown and hidden with the following jQuery:
$('#' + mnu).show('slide', { direction: 'down' }, 300);

In IE9 it displays correctly:

...but in IE7, it shows some strange white marks:

Has anybody seen anything like this before? How can I get IE7 to display properly?
Here is the HTML if it helps:

Main menu

Category 1

Item 1

Item 2

Item 3

Category 2

Item 1

Item 2

CSS:
#mainMenu {
    display:none;
    background-color:#fff;
    position:absolute;
    left:0px;
    bottom:40px;
    margin:0;
    padding:0;
    -moz-box-shadow: 0px 0px 10px #959595;
    -webkit-box-shadow: 0px 0px 10px #959595;
    box-shadow: 0px 0px 10px #959595;
    width:350px;
    border: 2px solid #00add0;
    z-index:101;
    font-size:15px;
}
#mainMenu h2 {
    display:block;
    background-color:#00add0;
    margin:0;
    padding:0 3px;
    font-family: 'DIN Next W01 Regular', Helvetica, Arial, sans-serif;
    font-size: 20px;
    text-transform:uppercase;
    font-weight:normal;
    color:#fff;
    vertical-align:middle;
}

#mainMenu nav li h3 {
    font-weight:normal;
    font-size:15px;
    padding: 0 0 0 20px;
    margin:0;
}

#mainMenu nav li {
    display: block;
    list-style:none;
    background-color:#333;
    color:#fff;
    margin:0;
    padding:3px 0;
    cursor:pointer;
    border-top: 1px solid #444444;
    border-bottom: 1px solid #242424;
    background-image:url('../images/twistArrowRight.gif');
    background-repeat:no-repeat;
    background-position:5px 5px;
}

#mainMenu nav li ul {
    padding:3px 0 3px 20px;
    margin:0;
}

#mainMenu nav li ul li {
    display: block;
    list-style:decimal;
    margin:0 0 0 -20px;
    padding:3px 0 3px 0px;
    cursor:pointer;
    border-top:0;
    border-bottom:0;
    background-image:none;

    font-size:12px;
    text-decoration:underline;
}

#mainMenu nav ul li a {
    display:block;
    color:#fff;
    font-size:12px;
    padding:0 0 0 40px;
}

#mainMenu nav ul li a:hover, #mainMenu nav ul li a:focus {
    background-color:#444;
}

Many thanks
Comment: You would need to tell us how you style the elements.. provide the CSS code for the `li` and `ul` elements..
Answer: IE7 does not support HTML5, so nav is not known. I think IE7 wraps the children li elements in an ul and you are seeing the bullets.
But the li elements should not be direct children of nav at all. They have to be in a list, as far sa I know.
Comment: Not to mention that `` is not for containing ``. There is no opening list tag at all.
Comment: Saw that and edited that while you are posting your comment ;-)
Comment: Good of you to actually look at the HTML. I see a CSS question with no CSS code and only screen shots and go into ignore mode.
Comment: Great! Thank you.
I changed the  to a . Not sure why on earth I was treating a nav like a list. Thanks all.

White marks appearing on my popup menu


How to Pass Workflow Variable to Worklet

Question: I have a persistent workflow variable $$COUNTER with a type of integer and default value of 0, and a persistent worklet variable with a type of integer and default value of 0.
In the workflow, I have an assignment task which increment $$COUNTER. I want to pass $COUNTER value to $$COUNTER_WL.
I already add this config on my worklet.

However, it doesn't seem that the workflow variable was passed. Here's some log snippets that I found relevant:
<code>Message: Use persisted repository value [0] for user-defined workflow/worklet variable:[$$COUNTER_WL].
Message Code: LM_36505
Message: Link [wl_Test: Start --> dcs_Counter_Checker]: empty expression string, evaluated to TRUE.
Message Code: LM_36546
Message: Decision task instance [wl_Test]: condition is TRUE for the expression [$$COUNTER_WL=0].
Message Code: LM_36488
Message: Session task instance [wl_Test.s_m_Test] : [VAR_27028 Use override value [0] for user-defined workflow/worklet variable:[$$COUNTER_WL].]
Message Code: VAR_27066
Message: Worklet variable name: [$$COUNTER_WL], run instance name [], persisted value: [0].
Message Code: VAR_27066
Message: Workflow variable name: [$$COUNTER], run instance name [], persisted value: [1].
</code>
How do I pass the workflow variable to my worklet?
Answer: Apparently the settings are already correct.
It seems that if you want to test whether the workflow variable value has been passed to the worklet variable, you need to start your workflow from session placed before the worklet (start workflow from task on session before the worklet). You cannot start task on the worklet session or else your workflow variable won't be passed to the worklet's.


How can I avoid getting poisoned?

Question: Is there any upgrade that might help stop being poisoned, or cause it to do less damage?
Comment: I wouldn't want very much poison immunity. When a Thin Man chooses to spit poison at my soldiers, I'm happy: that means he's not firing his Light Plasma Rifle. 3-4 damage over 3 turns is much less scary than 6-9 per shot!
Answer: There are not any foundry upgrades, perks, or gene mods that provide poison immunity, but you can research several armors and items that provide it
In the base game, the Titan Armor provides poison and fire  immunity. In the Enemy Within expansion, The Titan Armor, Ghost Armor and Archangel Armor all provide poison, fire, and strangulation immunity.
Holding a Medkit also provides poison immunity in both the base game and the expansion. The Respirator Implant, a new item in Enemy Within, confers poison and strangulation immunity.
MEC soldiers are also immune to fire and poison, but MEC troopers are only available in the Enemy Within expansion.
So I should just outfit my whole squad with poison immunity and steamroll everyone, right?
Poison immunity is nice, however enemies will change their tactics if they are unable to poison anyone. This can make it worse for your squad than just allowing someone to get poisoned, especially if your squad is not in the late game armors with extra health. As specifically discussed on the Respirator Implant wiki page:

If all squad members are immune to poison, Thin Men are certain to use their Light Plasma Rifle instead of Poison Spit. This risks a critical hit for up to 10 damage, compared to Poison Spit's guaranteed 3.

And since poison immunity usually comes with strangulation immunity (in Enemy Within):

If all squad members are immune to strangulation, Seekers will use their plasma weapon instead. This can deal up to 6 damage, compared to the strangulation's guaranteed 2 damage.

So feel free to use poison immunity, just be aware of the trade-offs it provides.

How can I avoid getting poisoned?


Does the NS_BLOCK_ASSERTIONS disable both NSAssert and assert() calls?

Question: Does the NS_BLOCK_ASSERTIONS switch off just the NSAssert calls or also the assert() calls. My app crashes in the Release mode on the line with assert(...) statement.
The documentation says only about NSAssert and does not tell if assert() calls are being disabled.
There are a couple questions related to mine that are not answering it. I'm linking them here:
NS_BLOCK_ASSERTIONS in Objective-C
NSAssert vs. assert: Which do you use, and when?
How to know if NSAssert is disabled in release builds?
Comment: we don't need NS_BLOCK_ASSRETIONS in Swift as all the asserts are valid only it Debug mode.
Answer: No, assert() is controlled with the NDEBUG symbol:
#ifdef NDEBUG
#define assert(e)   ((void)0)
#else
...

(see /usr/include/assert.h if you have the Xcode Command Line Tools installed, or elsewhere in the Xcode.app bundle, if not).


Symfony clear cache and Maximum function nesting level of '100' reached

Question: Hello I was trying to run the following console command
console cache:clear --env=prod

but i got the following error
Fatal error: Maximum function nesting level of '100' reached, aborting! in vendor\symfony\symfony\src\Symfony\Bundle\TwigBundle\Loader\FilesystemLoader.php on line 66
executing with --no-debug throw the same error, however when run the following command
console cache:clear --env=prod --no-optional-warmers

the cache is cleared and generated fine, but Twig templates are not generated and will be generated on runtime when some user navigate to the site, causing that the user to wait longer than usual.
What can cause this error?, Seems an error when generating the views, but why and how fix this?, thanks
I have Symfony 2.6 and php 5.5
Comment: Do `$ rm -rf app/cache/*` in your project directory and try clearing the cache again to check for this error maybe?
Comment: Thanks for your fast answer, but deleting the entire cache folder content don't resolve the problem, already try with this and the problem persists. However when I drop the cache folder content and navigate in the browser the cache is generated success without any error log or warning, but the time to wait is too long for customers. Doing the same, drop all cache content, and generating cache with the above command or the following command:
    php console cache:warmup --env=prod
throw the "Maximum function nesting level" error
Answer: This is due to the xdebug.max_nesting_level PHP setting, which defaults to 100.
This directive limits recursion to 100 calls which may not be enough for rendering the form in the template if you render the whole form at once (e.g form_widget(form)). To fix this you can set this directive to a higher value (either via a php.ini file or via ini_set(), for example in app/autoload.php) or render each form field by hand using form_row.


onEditClick = {item.isEditing=true } not working as intended

Question: I encountered a problem: onEditClick is not working:

I tried to fix it by using just one var eItem for edited items of the dataclass.
@Composable
fun all() {
    var showDialog by remember { mutableStateOf(false) }
    var Items by remember { mutableStateOf(listOf<GymContents>()) }

    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center
    ) {
        Button(
            onClick = { showDialog = true },
            modifier = Modifier.align(Alignment.CenterHorizontally)
        ) {
            Text("Add Item")
        }
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp)
        ) {
            items(Items) { item ->
                list(
                    item = item,
                    onEditClick = { item.isEditing = true },
                    onDeleteClick = { Items = Items.filter { it.id != item.id } }
                )
            }
        }
    }
}

@Composable
fun list(
    item: GymContents, onEditClick: () -> Unit, onDeleteClick: () -> Unit
) {
    Row(modifier = Modifier.fillMaxWidth()) {
        IconButton(onClick = onEditClick) {
            Icon(imageVector = Icons.Default.Edit, contentDescription = null)
        }

        IconButton(onClick = onDeleteClick) {
            Icon(imageVector = Icons.Default.Delete, contentDescription = null)
        }
    }
}

So I guess that the problem is how i ve managed how to pass data from edit() to all().
Comment: You need to paste all relevant code parts into your question, do not provide links to your code. Please only copy the *relevant* code parts, not the code in its entirety. You probably need to edit your code first to adhere to the guidelines layed out to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example).
Comment: ok modified hope that is fine now
Comment: That's still way too much irrelevant code. Can you please click the link I posted above and adhere to what it says? And please properly format your code before posting.
Comment: what do u think now?
Comment: There's something missing, it doesn't compile. And it isn't properly formatted. Please press CTRL+ALT+L in Android Studio.
Comment: cleanup code? optimize imports?
Comment: it does;'t compile cuz i removed some code.....
Comment: Seriously, have you read the link from my first comment? It should be *minimal*, as in "everything removed except the necessary parts" and *reproducible*, as in "can be executed and demonstrates the problem you experience". We cannot answer your question otherwise.
Comment: Hello @pizzamarinarasad, I edited your post. Your post should only contain the most relevant code to reproduce the issue, but at the same time, it has to be a well-formed code. You should not truncate your code by deleting closing brackets etc, please keep that in mind when posting question in the future.
Answer: You can't / shouldn't modify an item directly in the items function of a LazyColumn. Instead, modify the item by modifying it in the Items list that you provided to the items function.
Please try the following code:
val Items = remember { mutableStateListOf<GymContents>() }

Then, update your LazyColumn as follows:
LazyColumn(
    //...
) {
    itemsIndexed(Items) { index, item ->
        list(
            item = item,
            onEditClick = {
                // update the item
                Items[index] = Items[index].copy(isEditing = true)
            },
            //...
        )
    }
}

Note that you should have declared GymContents as a data class like this:
data class GymContents(
    val isEditing: Boolean,
    // other val properties
)

Comment: the data class is done correctly. if i copy paste the lazy column as u sent i get:Type mismatch: inferred type is List but Int was expected,Type mismatch: inferred type is LazyItemScope.(Int, Any?) -> Unit but LazyItemScope.(Int) -> Unit was expected,Expected one parameter of type Int,Cannot infer a type for this parameter. Please specify it explicitly,No set method providing array access,Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: public inline operator (index: Int, value: Char): Unit defined in kotlin.text
Comment: I edited my answer, please check again.


playing a playlist created in windows

Question: I had created a playlist in windows 8 which was in .wpl format.
I later converted it to .m3u format.
But i am not being able to play from either of the two on my ubuntu 14.04 which is on the same machine as my windows 8.
Answer: OK, Here's how I did it I replaced this part of my Windows playlist:
C:\Users\username\Music\

with
/home/username/Music/

Then replaced the \ with /, which got the playlist to play in VLC, but not Banshee.
Comment: Welcome to AskUbuntu!
The answer that you provided here could be improved by 1) Providing the details of how you made the edits to the playlists: What program did you use? Where in the file should one look to make the replacements?, etc. and 2) Use the formatting options. You can for example mark the relevant paths as `code`, thus making the post easier to read.
Again, welcome, and thank you for helping your peers!
Comment: Sorry, I don't hang out in forums.

I used open office editor (but most text editors will work)  and used the find-replace command. I did global replace to make the changes. Save in original file format after editing. I find this method works in most players these days.
Answer: use vlc. open a terminal and type
sudo apt-get install vlc

and then open the wpl or m3u with vlc player.
Comment: thank you but it didnt work either
Answer: I know this is quite late, but I'm posting this for other future visitors of this thread:
Apart from downloading VLC
(which has created a bit of a headache for me trying to set the hotkeys only to find out that the hotkeys failed to work after the first time it was set, but that's another story.)
, you can use Video(the Ubuntu built-in movie player).
But note that you need to edit your playlist's text file in gedit/Vim before it can be played properly. Also, you need to make sure that your playlist is in the proper location before it can be played by Video.
Here's the detailed procedures:

Trasnfer the WHOLE music folder from Windows onto your Linux machine. (e.g. say the folder is initially E:\MyWindows\Music on the Windows machine, which includes a sub folder E:\MyWindows\Music\Instrumental)
Transfer your playlist also from Windows to Linux (if it is not already in the file transferred in the previous step), into the same destination file.
Open terminal in the destination directory (e.g. say you have put it in /home/MyUbuntu/Music, then open terminal and type
cd Music)
Once you're in that directory, type gedit [InsertPlaylistNameHere].wpl (or use Vim if you )
Ctrl + H to delete all "E:\MyWindows\Music\" (i.e. the file location appending the song name) and replace all "E:\MyWindows\Music\Instrumental\" to "Instrumental/"
Note the change in the direction of the last slash.

Once you're done just close the gedit and open the .wpl with Video. It should work, although the album arts may not show.
(I have not found a method to make it work with Rhythmbox though.)

playing a playlist created in windows


Running vagrant on two macs

Question: I have Vagrant installed on my iMac but I would also like to install and run it on my MacBook.  Is it possible to run the same Vagrant box across two Macs?
I have done a Vagrant up command within a shared Dropbox folder - so i'm guessing that all I need to do is install vagrant on the second mac and then navigate to the Dropbox shared folder and do vagrant up.
Would this work?
Answer: Vagrant stores the state of the machine and machine id inside the .vagrant folder. The running machine (vm) itself is handled by virtualbox/vmware or any provider your using. Lets say the virtualbox box is stored somewhere else on your system and referenced by Vagrant.
If you access the folder from two systems your basically remote controlling two different machine on two different systems. Not a good solution. Furthermore, you will run into problems if the states are different, e.g. its "up" on system one but "destroyed" on system two.
Additionally to the above solutions I propose the following:

Vagrant Share! Enable Vagrant http-/ssh-Share between your systems.
Vagrant machines should be repeatable and destroyable. Therefore, put your Vagrantfile under version control and checkout on the two systems.
Configure your provider to store the box itself on the dropbox.
Answer: Known solution:

ssh to the host machine

user@MacBook: ssh user@imac

then vagrant up; vagrant ssh.

user@imac: vagrant up; vagrant ssh
vagrant@vagrantvm:

This would be the most straight forward way I can think of.
Another option:

RDP to imac and run vagrant up;vagrant ssh as normal

Yet another option:

If your vagrant file is complete enough you should be able to vagrant up on any host to give you the same vagrant env. This relies on your use case but is how I use vagrant.

Running vagrant on two macs


Permutations with repetition beginning and/or ending with members of a subset

Question: For the sake of this example, take the random letters OOOAEESTMLHHXX. How would I go about finding all of the permutations, accounting for repetition, that start and end with members of a subset, in this case any of the vowels?
I'm aware of the formula for permutations with repetition n!/(n1!n2!...) where n1/n2... are the counts of each item, but I can't figure out how to split up the cases to not include unique permutations multiple times.
I originally wanted to do cases for each vowel where it started at the beginning (O___) or end (___O), add them, then subtract away the cases where the string begins AND ends with the particular vowel (since O___O would be included in each of the added cases, we take one of them out). The problem I see here is that for future vowels, I'm repeating cases like A___O, which I could be counting again but already included when calculating for O.
I also thought about calculating every case that begins and ends with consonants (which I still think is probably the way to go), but I can't see any way other than manually pairing every case of consonants for the front and back of the word, then using the repetition formula, which seems like SO MANY calculations.
Is there something easier that I'm missing?
Appreciated highly.
Comment: Do you want to generate all these permutations (e.g. with a computer program) or just count them (i.e. just come up with some formula for the count)?
Comment: I'm looking for how it's done. I would brute force program this problem if I could, but that's not what I'm looking for right now @peter.petrov
Answer: The key to this problem is to combine elegance and brute force.
The string is "OOOAEESTMLHHXX".
There is one constraint: the first and last letters must each be
either "O", "A", or "E".  Although the string could (for example)
begin and end with "O", since there is only 1 "A", "A" can not
appear at both ends of the string.
This means that there are the letter groups "OOO", "EE", "HH", and "XX".
There are also the single letters "A", "S", "T", "M", and "L".
Therefore, the string can vary in length from 2 through 14, inclusive.
As I see it, you are going to need 6 variables.
Let $L_O \equiv ~$ the number of "O" letters used.
Let $L_E\equiv ~$ the number of "E" letters used.
Let $L_H \equiv ~$ the number of "H" letters used.
Let $L_X \equiv ~$ the number of "X" letters used.
Let $L_Z \equiv ~$ the number of letters used from the group "A", "S", "T", "M", and "L"
Let $T \equiv ~$ the total number of letters used in the string.
The preliminary portion of this analysis will resemble
the following problem.
When you study this problem you will notice a few points.

There are two ways to attack the # of solutions -
[Stars and Bars + Inclusion - Exclusion] or generating functions.

The # of solutions that you generate will actually be a function of $T$, which
represents the variable length of the string (i.e. from 2 through 14 inclusive).

All this analysis is doing is identifying all of the possible non-negative
integer solutions for each of the variables $L_O, L_E, L_H, L_X, L_Z.$

At each possible value for $T$, you must focus on each of the individual
solutions separately.

You then have to compute a formula that represents the number of possible
strings, as a function of the 6 variables.

Note that you have to be very careful to prune away any of the solutions
that do not have at least two vowels.  Since the # of vowels are actually
reflected in the interaction between $L_O, L_E,~$ and whether $a$ makes an
appearance, you have a couple of options here.
You could split "a" off from the other group and make it its own variable.
Or you could decline to split "a" off, and simply ignore any strings that
don't begin and end with a vowel.

Believe it or not, unless someone has a more elegant approach, this is where
the fun starts.  For a given set of values for the variables,
you have to enumerate the # of possible distinct strings that can be formed.
I am going to give you a starter enumeration.  However, you will have to
polish the formula re the first and last letters need to begin with a vowel.
You can think of the # of strings as a fraction which equals
$$\frac{T!}{D\text{(enominaor)}}.$$
Here,
$$D = (L_O!) \times (L_E!) \times (L_H!) \times (L_X!).$$
The reason for this is because (for example) if the "O" appears in a specific
group of $L_O$ slots, you have to compensate for it being counted $(L_O!)$ times.
This approach is the easiest way to adjust for the over-counting.
I emphasize: I am leaving the constraint that both ends of the string
are vowels to you.
Obviously, you are going to have to program your computer very carefully.

There is an obvious alternative.  Since it would be ridiculous to try to
count the number of solutions (without using a computer) using a whole group of
elegant formulas, you have two alternatives.

Come up with a more elegant approach than I have suggested.

Abandon all elegance and simply use brute force to have the computer
spin through all of the various possible strings, seeing which ones satisfy
the constraints.  Here, the # of possible strings would be strictly less than
or equal to the following:

$$\sum_{k=2}^{14} ~\binom{14}{k} \times k!$$.
Addendum
Keep in mind that I am totally ignorant of both generating functions and exponential generating functions.  I suspect that a more elegant approach is available through exponential generating functions.  However, I could be mistaken.
You would have to first study generating functions and then
study exponential generating functions to make this work.  Further, you would somehow have to include the constraint that the string begins and ends with a vowel.


How to Block inspect element on browser

Question: Can I block inspect element on browser ?
I want to block inspect element on my webpage, when a user try to modify code in inspect element, he could not do that.
Comment: Possible duplicate of [firebug, inspect element etc. Is there a way to hide it?](https://stackoverflow.com/questions/13698446/firebug-inspect-element-etc-is-there-a-way-to-hide-it)
Comment: Maybe the new HTML5 DRM standard will make this possible somehow. :-(
Answer: Why would you want to do that?
No, it is not possible. Your server is sending a response on a request, the browser is just an interperter of the code (HTML, CSS, JavaScript) it receives. This means that this code will have to be sent to your computer. When it leaves your server you have no influence on it anymore.

How to Block inspect element on browser


Access secure file on Azure DevOps from pipeline when signing Android apk

Question: How to access .jks file stored in "Azure Secure Files" from "Azure Pipelines" while signing Android apk?
My idea is just to call gradlew assembleRelease to generate and sign apk on Azure Pipeline.
Signing in gradle is configured like this:
<code>    signingConfigs {
    register("release") {
        storeFile(file(System.getenv("APK_KEYSTORE")))
        storePassword(System.getenv("APK_KEYSTORE_PASSWORD"))
        keyAlias(System.getenv("APK_KEY_ALIAS"))
        keyPassword(System.getenv("APK_KEY_PASSWORD"))
    }
}
</code>
It works locally but can't access the APK_KEYSTORE file stored in "secured files" in Azure
What I've already tried and it works is this Android signing task, but I need signing and generating apk locally also, so I need this one example above
Answer:
How to access .jks file stored in "Azure Secure Files" from "Azure
Pipelines" while signing Android apk?

In Azure Pipelines, you couldn't directly use the Secure file from Pipelines -> Library -> Secure files.
You need to add the Download secure file task in the Pipeline. Then the .jks file will be download to $(Agent.TempDirectory). This is the Agent temp folder(e.g. /home/vsts/work/_temp).
Here is an example:

When running the pipeline, the .jks will be downloaded to the local, and then you can find and use it in the temp folder(Path: $(Agent.TempDirectory)/key.jks ).
Comment: you can also give the task a name and then refer to this to find the file task: DownloadSecureFile@1
      name: 'keystore' //$(keystore.secureFilePath)
      inputs:
        secureFile: 'release-key.keystore'


Reversing Y axis in MSChart Control

Question: I am trying to reverse the Y Axis in MSChart
The scale from left to right would be 5 - 1 So if a bar has a value of 2 it will fill from 5 until 2 on the scale with the score to the right of the filled bar.

Is this possible with MS Chart?
Thanks
Answer: One possibility would be adding a second not enabled axis with "is reversed" and displaying the values on this one.
Answer: I don't really have time to fully test this, but perhaps
<code>    objChart.ChartAreas[0].AxisY.IsReversed = true;
</code>
... might be a good place to start?
edit: I've just tried this actually, and it only flips the entire chart. Probably not what you're after.

Reversing Y axis in MSChart Control


PyCharm - how to get rid of "Undefined step reference" warning

Question: I am making a Python BDD testing framework based on https://github.com/spyoungtech/behave-webdriver by using PyCharm Professional IDE. I followed the instruction from README file and the framework IS working. Although I'm getting a very annoying problem. PyCharm is giving me an error/warning in all of my *.feature files which are using step definitions from behave-webdriver, saying "undefined step reference" and what is even more annoying, because of that I cannot use ctrl+click to navigate to the step definition of these steps. Any ideas on how to deal with this?
PS. FYI. My step definition file is basically empty with just one line "from behave_webdriver.steps import *", and PyCharm is marking this line INCORRECTLY as "unused import statement", although without this line my code is not working (I'm getting "undefined step" error).
Comment: PyCharm can't handle step imports, unfortunately. I created a ticket in PyCharms bug tracker https://youtrack.jetbrains.com/issue/PY-35947
Answer: Pycharm makes it very easy to disable/supress inspections.
To disable an inspection, hit ⌘+,, select inspections, then disable the one you want.
To suppress an inspection, which only stops highlighting, hit the arrow displayed next to the inspection, and click "suppress for ___"
Comment: Thank you for the answer but turning off inspection is not satisfying. Probably the title of my problem is misleading... The warning which I'm getting is only a symptom of the real issue, which is: PyCharm cannot bind steps declaration from an external library (behave-webdriver) with steps itself (in *.feature file)
Answer: I reported an issue on behave-webdriver GitHub and they already fixed it in their code. More details about this problem you can find here: https://github.com/spyoungtech/behave-webdriver/issues/75
I suppose that it will be officially added to the next release (0.3.0) so this problem won't occur anymore.


Review of an authentication approach over RMI

Question: I am doing a project wherein, to access the service, the client needs to authenticate itself(client has a username and password) over RMI. I want to achieve this without using SSL(hence, modification and sniffing are the major threats).
Here's a "token" that a client sends every time a service is accessed.
class Token {
    String username;
    byte[] encryptedText;
}

Encrypted Text variable contains a combination of password and timestamp that is encrypted with AES-256 CBC using the password itself as the key.
eg:
encryptedText[0] = AES(20) //encrypt length of password
encryptedText[1] = AES(30) //encrypt length of TimeStamp
encryptedText[2-21] = AES(password) //encrypted password
encryptedText[22-51] = AES(timestamp) //encrypted timestamp

The server on receiving this token retrieves the password for the username and tries to decrypt the encrypted text with the password as the key. If the result is not a combination of password and a recent TimeStamp, it is a wrong attempt.
I know this is not scalable, since every time a service is requested, a record has to be fetched, but is this secure?
From what I can think of:-

Prevents sniffing (encrypted)
Prevents modification attack (wouldn't result in correct authentication)
Prevents replay attacks (non-recent timestamp is an authentication failure)
Comment: Note: there are a lot of standards to do this correctly. See [Password-authenticated key agreement](https://en.wikipedia.org/wiki/Password-authenticated_key_agreement)
Comment: It dosnt prevent sniffing. Once an attacker has the token he can use it himself until the timestamp expires.
Answer: I'm assuming that AES() doesn't just mean the pseudo-random permutation of a block cipher, but rather the block cipher with a mode of operation and a padding.
It would be possible to recover the password through a padding oracle attack if it's possible to distinguish a bad padding from a good padding. This is very likely, because the response is probably finished earlier when there is a BadPaddingException and further computation cannot be done.
The main two problems are that you're

not authenticating the ciphertext itself and
the password that was used to encrypt the plaintext is contained in the plaintext (could be recovered).

This pseudo encryption code is better:
// salt and masterHash can be cached for multiple requests
salt = SecureRandom().nextBytes(8 bytes)

// adjust iterations (65336) according to appropriate performance:
masterHash = pbkdf2(password, salt, 65336)

iv = SecureRandom().nextBytes(16 bytes)
sessionKey = SecureRandom().nextBytes(16 bytes)
encKey = hmacSha256(masterHash, "enc") // crop according to intended AES key size
macKey = hmacSha256(masterHash, "mac")
ciphertext = AES(encKey, iv, sessionKey + ts.length + ts)
tag = hmacSha256(macKey, username + salt + iv + ciphertext)
return salt + iv + ciphertext + tag

Here + means concatenation and AES means AES in CBC mode with PKCS#7 padding.
The receiver must first derive the macKey to then calculate the tag and then check whether the transmitted tag matches with the calculated tag. If it does then decrypt the ciphertext. If this works, then the sessionKey can be used for further communication.
The only thing that an attacker could do, is preventing you from authenticating to the server by manipulating the transmitted request in order to produce a failed authentication on the server.


Input parameter to closure in Swift with brackets

Question: I am going through the following tutorial on RxSwift:
http://adamborek.com/thinking-rxswift/
and having trouble understanding the following pattern:
           searchBar.rx.text.orEmpty
------------> .flatMap { [spotifyClient] query in
                   return spotifyClient.rx.search(query: query)
             }.map { tracks in
                   return tracks.map(TrackRenderable.init)
             }

This square brackets input parameter: [spotifyClient] query seems very weird for me. I looked over official Apple documentation for closures and functions and I can not see any examples of such input parameters. In Objective C this would not bother me much, but it is Swift. Could anyone explain, what this parameter means here?
Comment: Its a capture list to take a copy of an object into its block
Answer: You will need to understand the variable capturing of closure idea.
Consider this example:
struct Calculator {
    var a: Int
    var b: Int

    var sum: Int {
        return a + b
    }
}

Then you use this as:
let calculator = Calculator(a: 3, b: 5)

// You define a closure where you will use this calculator instance
let closure = {
    // closure captures the variables that are declared prior to the declaration of the closure.
    // your calculator instance is being captured here
    // it's default variable capture
    print("The result is \(calculator.sum)")
}

closure() // Prints "The result is 8"

Till now, everything is okay. You get what's expected.
Now consider you declare the calculator instance as var because in some point you need to mutate it's state. This is the case where complexity arises. Look:
var calculator = Calculator(a: 3, b: 5)

let closure = {
    print("The result is \(calculator.sum)")
}

// You change the state of your calculator instance anytime before the closure gets executed
calculator.b = 20
// When the closure actually executes, you will be affected by any changes outside the closure
closure() // Prints "The result is 23"

So, the default variable capture isn't really helping you, instead it's creating problem in your case.

If you want to prevent this behaviour and print 8 even if the properties change after their capturing inside the closure, we can explicitly capture the variable with a capture list like this:
// [calculator] is your capture list
let closure = { [calculator] in
    print("The result is \(calculator.sum)")
}
// change anything with calculator instance
calculator.b = 20
// execute the closure
closure() // Prints "The result is 8"

Capture List keeps immutable copy of the variable(s). Thanks to this copy, further changes to calculator, outside the closure, will not affect the closure.
You can capture multiple variables at once, hence it's called Capture List. Example:
let closure = { [variable1, variable2, variable3] in
    print(variable1)
    print(variable2)
    print(variable3)
}

I recommend you read this article Capturing Values In Swift Closures.

Now, in your case spotifyClient is an instance of a class that may be responsible to make API calls. This instance may need some changes for calling different APIs. So, to prevent the affect of any changes to spotifyClient outside this closure you capture this instance in a Capture List.

Capture List vs. Parameter List:
You are confusing the parameter list with the capture list. The generic syntax is:
{ [capture list] (parameter list) in
    ...
    ...
}

Now take a look at the modified version of the above example:
let closure: (String)-> Void = { [calculator] stringParameter in // When using single parameter, you can always omit the () parentheses
    print("\(stringParameter). The result is \(calculator.sum)")
}

// change anything with calculator instance
calculator.b = 20
// execute the closure
closure("Hey") // Prints "Hey. The result is 8"

Comment: Ok, but what is 'query' parameter doing there? Is it a second parameter? Why there is no comma?
Comment: Your `spotifyClient` is one element of capture list. And `query` is a parameter. They aren't the same. See my newest edit.


How to style a specific page link navbar in Wordpress?

Question: I already finish my layout design. Now I want to include my design in Wordpress themes. I have a little knowledge in Wordpress because I just started learning it for about 1 week.
This is my template (not yet wordpress)

TOP PAGE

COMPANY PROFILE

PRODUCTS

SERVICES

DOWNLOAD

 CONTACT US

And what I did is I created them as a page so I have this code:

    <?php wp_list_pages('title_li='); ?>

And it my last page there will be an envelope icon beside the text link and also it has a different background color.
I created this CSS for this:
#top-links-container .nav li:last-child {
    border: 1px solid #FB7E7E;
    background: #FB7E7E;
}

I got the background color but the text color didn't change.
I also tried this approach but all the text link is affected.
#top-links-container .nav li a:last-child {
    color: #fff;
}

Is there a way that I can style a specific page link? How can I add the icon beside my last page link?
Comment: Do you want to apply diff. css class to specific menu item?
Comment: Yes. And I want to add a span tag on that specific menu item
Comment: That you can do from admin option , for each menu item you have option to apply  **Css Classes**, expand menu and you will have that option. If you don't get that option then from top  **Go to Screen option -> Show advance option -> Css classes** , then again check with menu. Hope now you can apply specific class to specific menu.
Answer: Based on your code:
#top-links-container .nav .contact_us_link a {
    color: #fff;
}

You may also have to style the .fa if it's being overwritten by your other css.


How to append list data to a 'xlsx' template?

Question: I want to list data append in the template xlsx file header that already exists in the template xlsx file, can we add logic if Descrption e.g. (Descrption 1, Descrption 2, Descrption 3 .... Descrption n) came more than 4 than can we create another header Description next number? For next iteration create a column according to the Description.
Template Input Example:-

Expected Output XLSX File:-

If I run the below script then get the output:-

I try below this code:
import pandas as pd

xlsx_file = "input.xlsx"

existing_data = pd.read_excel(xlsx_file)

newData = pd.DataFrame([
    ['Brand A'],
    ['Product Title'],
    ['Description 1', 'Description 2', 'Description 3', 'Descriprion 4'],
    ['Quantity 4']
])

combined_data = pd.concat([existing_data, newData], ignore_index=False)

with pd.ExcelWriter(xlsx_file, engine='openpyxl', mode='a', if_sheet_exists='overlay') as write:
    combined_data.to_excel(write, startcol=0, startrow=0)

Comment: Please clearify, i dont really understand what u want :)
Comment: @Christoph - Thanks for reply, I want to insert the `DataFrame` list data append the  `xlxs` template file `Template Input Example` as template and `Expected Output XLSX File` as expectd xlsx file.
Comment: An whats the issue, what does Not Work ?
Comment: I try but my code is not working.
Comment: What is the Output you must give more Context. Did u get Errors? How does the xlxs looks after U ran your Script ?
Comment: i dont understand what this question seeks.  how to ask a good question:
[how to ask](https://stackoverflow.com/help/how-to-ask)
Comment: @Christoph I updated the question and add the current output, please check.
Comment: @D.L, could you please check my input template `xlsx` and expected `xlsx` file, I want to append list data into template `xlsx` file.
Comment: The main problem is how you define `newData` - it doesn't correlate with your template, so you get an incorrect concatenation. Provide proper headings when filling in new data.
Comment: As @Vitalizzare indicates; Your Dataframe 'newData' will have 4 Columns with Headers '0', '1', '2', '3' which do not relate to the existing 'template'. Hence concat to the Dataframe 'existing_data' will just add as new columns after the last column 'Quantity'.
Comment: I don't understand why you're using Pandas for this at all. Doing this directly in Openpyxl would let you make changes in the headers directly.
Answer: In order for you to get the data as you have shown in the Expected Output XLSX File:- screenshot you'd need to change your code to the following at a basic level;
Note:- the 'newData' Dataframe is modified so it has headers included that match with the template, thus the concat can incorporate the data into the existing columns.
import pandas as pd

xlsx_file = "input.xlsx"

existing_data = pd.read_excel(xlsx_file)

# newData = pd.DataFrame([
#     ['Brand A'],
#     ['Product Title'],
#     ['Description 1', 'Description 2', 'Description 3', 'Descriprion 4'],
#     ['Quantity 4']
# ])

### Dictionary of lists
newData = pd.DataFrame({
    "Brand": ['Brand A'],
    "Product Title": ['Product Title'],
    "Description 1": ['Description 1'],
    "Description 2": ['Description 2'],
    "Description 3": ['Description 3'],
    "Description 4": ['Description 4'],
    "Quantity": ['Quantity 4']
})

combined_data = pd.concat([existing_data, newData], ignore_index=False)

with pd.ExcelWriter(xlsx_file, engine='openpyxl', mode='a', if_sheet_exists='overlay') as write:
    combined_data.to_excel(write, startcol=0, startrow=0, index=False)  # index set to False

What you attempting or wanting to do with the Description fields is unclear.
The first paragraph in the question is confusing. It seems you may be indicating scenarios that have more/less Description fields and perhaps may want to add more columns if there are more than the 4 that exist in the template. However cannot be sure.
Also origin of the list of lists that creates 'newData' is not specified so the reasons for it's structure is not known and therefore how it otherwise might be better integrated cannot be commented on.
Also be careful of spelling. There are a few occasions of misspelling 'description' in the Sheet and code and this will cause mismatch of data to columns.
Additional Information
Inserting a new column in a DataFrame at your desired location is easy enough.
For example, with your sheet as it is; "Description 5" would need to be inserted after location 8 (Column 8 is where "Description 4" resides).
You would probably want to add to the 'existing_data' before combining the dataframes.
What is contained in the double quotes is the value added to all existing columns.
existing_data.insert(8, "Description 5", "")

If you do something like the above example and use a Dictionary of Lists then the additional column "Description 5" value will then slot in before integrating into the 'combined_data' Dataframe.
However you would need to determine there is a new column value in the scraped data. Extract the Header name (e.g. 'Description 5') from the data and determine what its location should be.
Again there is insufficient detail to be more specific on implementation.
Comment: Certainly you can insert a new column at any column location in a dataframe. I have added some additional details in the answer.
Comment: Thanks for giving the solution, here is my question is it possible for `Description 5` to come in a new iteration then how can we add a new column `Description 5` just right side from the `Description 4`? actually I am fetching the details from URL through web scrapping and use `for` loop and first `append` the data into list than list data append into the `xlsx` file.


Structural integrity of new fence on concrete slab

Question: I recently bought a condo with a 11'x13' patio with a wooden privacy fence. The fence is in pretty bad shape so I want redo it with new wood in a more modern design by doing horizontal planks. I posted another question about materials (Rebuilding fence - lumber questions) and from that discussion now have questions about the structural integrity of my design. I sketched out the existing framing and proposed framing with an sky view and front view.

The main difference is that I will be increasing the size of the corner posts to 6x6 so that I can screw the horizontal planks to the framing and the post will still stick out of it. Something like (https://i.pinimg.com/originals/8c/e8/d4/8ce8d43018c740fb1c6b47f8a6a369d8.jpg). I also want to add a 4x6 post in the middle of each side to break up the long stretch of horizontal planks.
Is this plan sound? I am open to all suggestions, thanks in advance!
Answer: You aren't clear on how the posts are anchored. Are you pouring concrete piers or doing metal mounting plates with concrete anchors? Either way, I think your plan is sound but you should also anchor the center posts which are floating in your current plan. That will add considerably more structural integrity to your fencing.
I like the 6x6 posts for strength and aesthetics.
Comment: I will be using a post base bracket with a 5/8" x 10" concrete wedge anchor. I was going to anchor all of the posts originally but was told that would reduce the structural integrity of the fence. See the comments in the linked post if you want to see more about that
Comment: I read the other post. I don't want to recreate the original post but the comment was made that you will "want rigid bases or embedded posts" I didn't see any comment that anchoring all of the posts "would reduce the structural integrity of the fence". Again the issue is lateral strength (wind forces). You have hinge points at the unanchored posts in the center of your fence. Solid fences like yours act like a sail catching wind. I would prefer that the posts were embedded but they're not. The next best thing is to attach all of the posts into the concrete with anchors.
Comment: My understanding of the comments were that using the post base would not be rigid enough and would act more as a hinge point. The current fence doesn't have an attached post in the middle as well so I figured it was true.
Comment: I may be wrong but the hinge point referred to is the vertical hinge point at the center post of each side which is not anchored. Isherwood made the comment that "you'd want continuous rails between the corner posts" which will also help prevent hinging at the center. If I were doing this I would anchor the center post and install continuous rails from corner to corner.
Comment: By a continuous rail, is a 2x4 that goes from one corner post to the next sufficient? By continuous rail I assume that means an uncut piece of wood? Would it be more secure if the wood was screwed in on top of the posts or to the side?
Comment: Continuous means uncut. 2x4s or 2x6s attached to the side of the posts should be sufficient.
Comment: Okay and just to be clear, when I said side to side I mean like one face to the other face (going above the middle post). Do you think this post base is strong enough to add a gate on the left side? https://www.homedepot.com/p/Simpson-Strong-Tie-E-Z-Base-Black-Powder-Coated-Post-Base-for-4x4-Nominal-Lumber-FPBB44/100655350
Comment: I don't see any thing in this post about "side to side" so I don't know what you're asking. Adding in a gate was not in the above post and brings in a whole new dimension regarding stability. The short answer is "no". Adding in a gate without embedded posts or without adding additional structural stability to the fence is not a good idea in my opinion. I'm not sure I can offer any better advice on this topic other than what you've already received. Good luck.


Can't find and remove duplicates in Google Apps Script

Question: I've got two columns with data in them. One of the columns (on a different sheet) is a list of approved clients (approvedClients). The other is a column in the current sheet (currentClients). My goal is to look at the column in the other sheet and the column in this sheet and show the differences in the current sheet.
For example, if [1,2,3,4,5,6] was the current column, and the column on the other sheet was [1,3,5,6], I want my result to be [2,4], since 2 and 4 are the values that are present in the current column but not in the column on the other sheet.
When I run the code below, I get no error, but when I log unknownClients, I get this. What's wrong?
function myFunction() {
 var sheet = SpreadsheetApp.getActiveSheet();
 var ui = SpreadsheetApp.getUi();
 var cell;
 var range;

  switchSheets('Results');
  var currentClients = sheet.getRange('B2:' + sheet.getLastRow()); //gets the clients that are currently connected.
  switchSheets('Approved clients');
  var approvedClients = sheet.getRange('A2:' + sheet.getLastRow()); //gets the clients that are approved to connect.
  switchSheets('Results');
  var unknownClients = new Array();

  for(i in currentClients){
    var row = currentClients[i];
    var duplicate = false;
    for(j in unknownClients){
      if(row == unknownClients[j]){
        duplicate = true;
      }
    }
    if(!duplicate){
      unknownClients.push(row);
    }
  }
  Logger.log(unknownClients);
}

Comment: What is this function `switchSheets()`, can you share the code?
Comment: @JackBrown it's a custom function that changes the active sheet.
Comment: Changing active sheet doesn't retroactively change the sheet variable. It still refers to the first sheet it was assigned to.
Comment: Also, could you double check your paste bin link. It seems wrong!
Comment: Try changing `var unknownClients = new Array();` to `var unknownClients = [];`. You might also want to check [this SO question](https://stackoverflow.com/questions/25735677/remove-duplicates-values-in-array-google-apps-script) as it basically discusses the same thing.
Comment: Do you need to use a script for this? For example, `=filter(A:A, isna(match(A:A, B:B, 0)))`  shows the entries from A that are not in B.
Comment: 1 It seems that changing the sheet does retroactively change the sheet. It is a bad solution, but works. 2 I'm trying to make a 1-dimensional array, to hold only one piece of data. 3 the pastebin link was correct. 4 I want to use a script so I can chain a lot more code.
Answer: Here's my errors:
- I wasn't getting the values of the cells. I was getting a sheet object. It was logging all of the methods of the sheet object.
- I was trying to compare the list of connectedClients to the list of unknownClients, an empty array. I changed two references to unknownClients to approvedClients.
Changes I made are in caps.
I really appreciate the help from this community. I try to answer if I can, and I thank you for doing so.
function myFunction() {
 var sheet = SpreadsheetApp.getActiveSheet();
 var ui = SpreadsheetApp.getUi();
 var cell;
 var range;

  switchSheets('Results');
  var currentClients = sheet.getRange('B2:' + sheet.getLastRow()).getValues(); //ADDED THE GET VALUES
  switchSheets('Approved clients');
  var approvedClients = sheet.getRange('A2:' + sheet.getLastRow()).getValues(); //ADDED THE GET VALUES
  switchSheets('Results');
  var unknownClients = new Array();

  for(i in currentClients){
    var row = currentClients[i];
    var duplicate = false;
    for(j in approvedClients){ //CHANGED UNKNOWN TO APPROVED
      if(row == approvedClients[j]){ //CHANGED UNKNOWN TO APPROVED
        duplicate = true;
      }
    }
    if(!duplicate){
      unknownClients.push(row);
    }
  }
  Logger.log(unknownClients);
}