Programs & Examples On #Step through

Asynchronously load images with jQuery

You can use a Deferred objects for ASYNC loading.

function load_img_async(source) {
    return $.Deferred (function (task) {
        var image = new Image();
        image.onload = function () {task.resolve(image);}
        image.onerror = function () {task.reject();}
        image.src=source;
    }).promise();
}

$.when(load_img_async(IMAGE_URL)).done(function (image) {
    $(#id).empty().append(image);
});

Please pay attention: image.onload must be before image.src to prevent problems with cache.

HTML5 best practices; section/header/aside/article elements

<body itemscope itemtype="http://schema.org/Blog">
 <header>
  <h1>Wake up sheeple!</h1>
  <p><a href="news.html">News</a> -
     <a href="blog.html">Blog</a> -
     <a href="forums.html">Forums</a></p>
  <p>Last Modified: <span itemprop="dateModified">2009-04-01</span></p>
  <nav>
   <h1>Navigation</h1>
   <ul>
    <li><a href="articles.html">Index of all articles</a></li>
    <li><a href="today.html">Things sheeple need to wake up for today</a></li>
    <li><a href="successes.html">Sheeple we have managed to wake</a></li>
   </ul>
  </nav>
 </header>
 <main>
  <article itemprop="blogPosts" itemscope itemtype="http://schema.org/BlogPosting">
   <header>
    <h1 itemprop="headline">My Day at the Beach</h1>
   </header>
   <div itemprop="articleBody">
    <p>Today I went to the beach and had a lot of fun.</p>
    ...more content...
   </div>
   <footer>
    <p>Posted <time itemprop="datePublished" datetime="2009-10-10">Thursday</time>.</p>
   </footer>
  </article>
  ...more blog posts...
 </main>
 <footer>
  <p>Copyright ©
   <span itemprop="copyrightYear">2010</span>
   <span itemprop="copyrightHolder">The Example Company</span>
  </p>
  <p><a href="about.html">About</a> -
     <a href="policy.html">Privacy Policy</a> -
     <a href="contact.html">Contact Us</a></p>
 </footer>
</body>

https://www.w3.org/TR/2014/REC-html5-20141028/sections.html#the-nav-element

'ssh' is not recognized as an internal or external command

Actually you have 2 problems here: First is that you don't have ssh installed, second is that you don't know how to deploy

Install SSH

It seems that ssh is not installed on your computer.

You can install openssh from here : http://openssh.en.softonic.com/download

Generate your key

Than you will have to geneate your ssh-key. There's a good tutorial about this here:

https://help.github.com/articles/generating-ssh-keys#platform-windows

Deploy

To deploy, you just have to push your code over git. Something like this:

git push fort master

If you get permission denied, be sure that you have put your public_key in the dashboard in the git tab.

SSH

The ssh command gives you access to your remote node. You should have received a password by email and now that you have ssh installed, you should be asked for a password when trying to connect. just input that password. If you want to use your private ssh key to connect to your server rather then typing that password, you can follow this : http://fortrabbit.com/docs/how-to/ssh-sftp/enable-public-key-authentication

TypeError: 'DataFrame' object is not callable

It seems you need DataFrame.var:

Normalized by N-1 by default. This can be changed using the ddof argument

var1 = credit_card.var()

Sample:

#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
   A  B  C  D  E
0  8  8  3  7  7
1  0  4  2  5  2
2  2  2  1  0  8
3  4  0  9  6  2
4  4  1  5  3  4

var1 = credit_card.var()
print (var1)
A     8.8
B    10.0
C    10.0
D     7.7
E     7.8
dtype: float64

var2 = credit_card.var(axis=1)
print (var2)
0     4.3
1     3.8
2     9.8
3    12.2
4     2.3
dtype: float64

If need numpy solutions with numpy.var:

print (np.var(credit_card.values, axis=0))
[ 7.04  8.    8.    6.16  6.24]

print (np.var(credit_card.values, axis=1))
[ 3.44  3.04  7.84  9.76  1.84]

Differences are because by default ddof=1 in pandas, but you can change it to 0:

var1 = credit_card.var(ddof=0)
print (var1)
A    7.04
B    8.00
C    8.00
D    6.16
E    6.24
dtype: float64

var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0    3.44
1    3.04
2    7.84
3    9.76
4    1.84
dtype: float64

Truncate a SQLite table if it exists?

I got it to work with:

SQLiteDatabase db= this.getWritableDatabase();
        db.delete(TABLE_NAME, null, null);

What is the meaning of "POSIX"?

Some facts about POSIX that are not so bright.

POSIX is also the system call interface or API, and it is nearly 30 years old.

It was designed for serialized data access to local storage, using single computers with single CPUs.

Security was not a major concern in POSIX by design, leading to numerous race condition attacks over the years and forcing programmers to work around these limitations.

Serious bugs are still being discovered, bugs that could have been averted with a more secure POSIX API design.

POSIX expects users to issue one synchronous call at a time and wait for its results before issuing the next. Today's programmers expect to issue many asynchronous requests at a time to improve overall throughput.

This synchronous API is particularly bad for accessing remote and cloud objects, where high latency matters.

LINQ - Full Outer Join

Here is an extension method doing that:

public static IEnumerable<KeyValuePair<TLeft, TRight>> FullOuterJoin<TLeft, TRight>(this IEnumerable<TLeft> leftItems, Func<TLeft, object> leftIdSelector, IEnumerable<TRight> rightItems, Func<TRight, object> rightIdSelector)
{
    var leftOuterJoin = from left in leftItems
        join right in rightItems on leftIdSelector(left) equals rightIdSelector(right) into temp
        from right in temp.DefaultIfEmpty()
        select new { left, right };

    var rightOuterJoin = from right in rightItems
        join left in leftItems on rightIdSelector(right) equals leftIdSelector(left) into temp
        from left in temp.DefaultIfEmpty()
        select new { left, right };

    var fullOuterJoin = leftOuterJoin.Union(rightOuterJoin);

    return fullOuterJoin.Select(x => new KeyValuePair<TLeft, TRight>(x.left, x.right));
}

Passing a local variable from one function to another

Adding to @pranay-rana's list:

Third way is:

function passFromValue(){
    var x = 15;
    return x;  
}
function passToValue() {
    var y = passFromValue();
    console.log(y);//15
}
passToValue(); 

What is your most productive shortcut with Vim?

gi

Go to last edited location (very useful if you performed some searching and than want go back to edit)

^P and ^N

Complete previous (^P) or next (^N) text.

^O and ^I

Go to previous (^O - "O" for old) location or to the next (^I - "I" just near to "O"). When you perform searches, edit files etc., you can navigate through these "jumps" forward and back.

How to loop and render elements in React-native?

render() {
  return (
    <View style={...}>
       {initialArr.map((prop, key) => {
         return (
           <Button style={{borderColor: prop[0]}}  key={key}>{prop[1]}</Button>
         );
      })}
     </View>
  )
}

should do the trick

How to calculate the sum of the datatable column in asp.net?

You can do like..

DataRow[] dr = dtbl.Select("SUM(Amount)");
txtTotalAmount.Text = Convert.ToString(dr[0]);

Getting ssh to execute a command in the background on target machine

First follow this procedure:

Log in on A as user a and generate a pair of authentication keys. Do not enter a passphrase:

a@A:~> ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/a/.ssh/id_rsa): 
Created directory '/home/a/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/a/.ssh/id_rsa.
Your public key has been saved in /home/a/.ssh/id_rsa.pub.
The key fingerprint is:
3e:4f:05:79:3a:9f:96:7c:3b:ad:e9:58:37:bc:37:e4 a@A

Now use ssh to create a directory ~/.ssh as user b on B. (The directory may already exist, which is fine):

a@A:~> ssh b@B mkdir -p .ssh
b@B's password: 

Finally append a's new public key to b@B:.ssh/authorized_keys and enter b's password one last time:

a@A:~> cat .ssh/id_rsa.pub | ssh b@B 'cat >> .ssh/authorized_keys'
b@B's password: 

From now on you can log into B as b from A as a without password:

a@A:~> ssh b@B

then this will work without entering a password

ssh b@B "cd /some/directory; program-to-execute &"

getElementsByClassName not working

If you want to do it by ClassName you could do:

<script type="text/javascript">
function hideTd(className){
    var elements;

    if (document.getElementsByClassName)
    {
        elements = document.getElementsByClassName(className);
    }
    else
    {
        var elArray = [];
        var tmp = document.getElementsByTagName(elements);  
        var regex = new RegExp("(^|\\s)" + className+ "(\\s|$)");
        for ( var i = 0; i < tmp.length; i++ ) {

            if ( regex.test(tmp[i].className) ) {
                elArray.push(tmp[i]);
            }
        }

        elements = elArray;
    }

    for(var i = 0, i < elements.length; i++) {
       if( elements[i].textContent == ''){
          elements[i].style.display = 'none';
       } 
    }

  }
</script>

how to transfer a file through SFTP in java?

Try this code.

public void send (String fileName) {
    String SFTPHOST = "host:IP";
    int SFTPPORT = 22;
    String SFTPUSER = "username";
    String SFTPPASS = "password";
    String SFTPWORKINGDIR = "file/to/transfer";

    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
    System.out.println("preparing the host information for sftp.");

    try {
        JSch jsch = new JSch();
        session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
        session.setPassword(SFTPPASS);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        System.out.println("Host connected.");
        channel = session.openChannel("sftp");
        channel.connect();
        System.out.println("sftp channel opened and connected.");
        channelSftp = (ChannelSftp) channel;
        channelSftp.cd(SFTPWORKINGDIR);
        File f = new File(fileName);
        channelSftp.put(new FileInputStream(f), f.getName());
        log.info("File transfered successfully to host.");
    } catch (Exception ex) {
        System.out.println("Exception found while tranfer the response.");
    } finally {
        channelSftp.exit();
        System.out.println("sftp Channel exited.");
        channel.disconnect();
        System.out.println("Channel disconnected.");
        session.disconnect();
        System.out.println("Host Session disconnected.");
    }
}   

HTML select dropdown list

<select>
    <option value="" disabled="disabled" selected="selected">Please select name</option>
  <option value="Tom">Tom</option>
  <option value="Marry">Marry</option>
  <option value="Jane">Jane</option>
  <option value="Harry">Harry</option>
</select>

Count words in a string method?

This would work even with multiple spaces and leading and/or trailing spaces and blank lines:

String trim = s.trim();
if (trim.isEmpty())
    return 0;
return trim.split("\\s+").length; // separate string around spaces

Hope that helps. More info about split here.

Can a class member function template be virtual?

My current solution is the following (with RTTI disabled - you could use std::type_index, too):

#include <type_traits>
#include <iostream>
#include <tuple>

class Type
{
};

template<typename T>
class TypeImpl : public Type
{

};

template<typename T>
inline Type* typeOf() {
    static Type* typePtr = new TypeImpl<T>();
    return typePtr;
}

/* ------------- */

template<
    typename Calling
    , typename Result = void
    , typename From
    , typename Action
>
inline Result DoComplexDispatch(From* from, Action&& action);

template<typename Cls>
class ChildClasses
{
public:
    using type = std::tuple<>;
};

template<typename... Childs>
class ChildClassesHelper
{
public:
    using type = std::tuple<Childs...>;
};

//--------------------------

class A;
class B;
class C;
class D;

template<>
class ChildClasses<A> : public ChildClassesHelper<B, C, D> {};

template<>
class ChildClasses<B> : public ChildClassesHelper<C, D> {};

template<>
class ChildClasses<C> : public ChildClassesHelper<D> {};

//-------------------------------------------

class A
{
public:
    virtual Type* GetType()
    {
        return typeOf<A>();
    }

    template<
        typename T,
        bool checkType = true
    >
        /*virtual*/void DoVirtualGeneric()
    {
        if constexpr (checkType)
        {
            return DoComplexDispatch<A>(this, [&](auto* other) -> decltype(auto)
                {
                    return other->template DoVirtualGeneric<T, false>();
                });
        }
        std::cout << "A";
    }
};

class B : public A
{
public:
    virtual Type* GetType()
    {
        return typeOf<B>();
    }
    template<
        typename T,
        bool checkType = true
    >
    /*virtual*/void DoVirtualGeneric() /*override*/
    {
        if constexpr (checkType)
        {
            return DoComplexDispatch<B>(this, [&](auto* other) -> decltype(auto)
                {
                    other->template DoVirtualGeneric<T, false>();
                });
        }
        std::cout << "B";
    }
};

class C : public B
{
public:
    virtual Type* GetType() {
        return typeOf<C>();
    }

    template<
        typename T,
        bool checkType = true
    >
    /*virtual*/void DoVirtualGeneric() /*override*/
    {
        if constexpr (checkType)
        {
            return DoComplexDispatch<C>(this, [&](auto* other) -> decltype(auto)
                {
                    other->template DoVirtualGeneric<T, false>();
                });
        }
        std::cout << "C";
    }
};

class D : public C
{
public:
    virtual Type* GetType() {
        return typeOf<D>();
    }
};

int main()
{
    A* a = new A();
    a->DoVirtualGeneric<int>();
}

// --------------------------

template<typename Tuple>
class RestTuple {};

template<
    template<typename...> typename Tuple,
    typename First,
    typename... Rest
>
class RestTuple<Tuple<First, Rest...>> {
public:
    using type = Tuple<Rest...>;
};

// -------------
template<
    typename CandidatesTuple
    , typename Result
    , typename From
    , typename Action
>
inline constexpr Result DoComplexDispatchInternal(From* from, Action&& action, Type* fromType)
{
    using FirstCandidate = std::tuple_element_t<0, CandidatesTuple>;

    if constexpr (std::tuple_size_v<CandidatesTuple> == 1)
    {
        return action(static_cast<FirstCandidate*>(from));
    }
    else {
        if (fromType == typeOf<FirstCandidate>())
        {
            return action(static_cast<FirstCandidate*>(from));
        }
        else {
            return DoComplexDispatchInternal<typename RestTuple<CandidatesTuple>::type, Result>(
                from, action, fromType
            );
        }
    }
}

template<
    typename Calling
    , typename Result
    , typename From
    , typename Action
>
inline Result DoComplexDispatch(From* from, Action&& action)
{
    using ChildsOfCalling = typename ChildClasses<Calling>::type;
    if constexpr (std::tuple_size_v<ChildsOfCalling> == 0)
    {
        return action(static_cast<Calling*>(from));
    }
    else {
        auto fromType = from->GetType();
        using Candidates = decltype(std::tuple_cat(std::declval<std::tuple<Calling>>(), std::declval<ChildsOfCalling>()));
        return DoComplexDispatchInternal<Candidates, Result>(
            from, std::forward<Action>(action), fromType
        );
    }
}

The only thing I don't like is that you have to define/register all child classes.

Regex that accepts only numbers (0-9) and NO characters

Your regex ^[0-9] matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $ to the end:

^[0-9]*$

This accepts any number of digits, including none. To accept one or more digits, change the * to +. To accept exactly one digit, just remove the *.

UPDATE: You mixed up the arguments to IsMatch. The pattern should be the second argument, not the first:

if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))

CAUTION: In JavaScript, \d is equivalent to [0-9], but in .NET, \d by default matches any Unicode decimal digit, including exotic fare like ? (Myanmar 2) and ? (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9] (or supply the RegexOptions.ECMAScript flag).

IIS URL Rewrite and Web.config

Just wanted to point out one thing missing in LazyOne's answer (I would have just commented under the answer but don't have enough rep)

In rule #2 for permanent redirect there is thing missing:

redirectType="Permanent"

So rule #2 should look like this:

<system.webServer>
    <rewrite>
        <rules>
            <rule name="SpecificRedirect" stopProcessing="true">
                <match url="^page$" />
                <action type="Redirect" url="/page.html" redirectType="Permanent" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

Edit

For more information on how to use the URL Rewrite Module see this excellent documentation: URL Rewrite Module Configuration Reference

In response to @kneidels question from the comments; To match the url: topic.php?id=39 something like the following could be used:

<system.webServer>
  <rewrite>
    <rules>
      <rule name="SpecificRedirect" stopProcessing="true">
        <match url="^topic.php$" />
        <conditions logicalGrouping="MatchAll">
          <add input="{QUERY_STRING}" pattern="(?:id)=(\d{2})" />
        </conditions>
        <action type="Redirect" url="/newpage/{C:1}" appendQueryString="false" redirectType="Permanent" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

This will match topic.php?id=ab where a is any number between 0-9 and b is also any number between 0-9. It will then redirect to /newpage/xy where xy comes from the original url. I have not tested this but it should work.

Convert decimal to binary in python

n=int(input('please enter the no. in decimal format: '))
x=n
k=[]
while (n>0):
    a=int(float(n%2))
    k.append(a)
    n=(n-a)/2
k.append(0)
string=""
for j in k[::-1]:
    string=string+str(j)
print('The binary no. for %d is %s'%(x, string))

How to import a jar in Eclipse

Adding external Jar is not smart in case you want to change the project location in filesystem.

The best way is to add the jar to build path so your project will compile if exported:

  1. Create a folder called lib in your project folder.

  2. copy to this folder all the jar files you need.

  3. Refresh your project in eclipse.

  4. Select all the jar files, then right click on one of them and select Build Path -> Add to Build Path

Landscape printing from HTML

My solution:

<style type="text/css" media="print">
    @page { 
        size: landscape;
    }
    body { 
        writing-mode: tb-rl;
    }
</style>

This works in IE, Firefox and Chrome

How can I disable a tab inside a TabControl?

I could not find an appropriate answer to the question. There looks to be no solution to disable the specific tab. What I did is to pass the specific tab to a variable and in SelectedIndexChanged event put it back to SelectedIndex:

//variable for your specific tab 
int _TAB = 0;

//here you specify your tab that you want to expose
_TAB = 1;
tabHolder.SelectedIndex = _TAB;

private void tabHolder_SelectedIndexChanged(object sender, EventArgs e)
{
    if (_TAB != 0) tabHolder.SelectedIndex = _TAB;
}

So, you don't actually disable the tab, but when another tab is clicked it always returns you to the selected tab.

Test if object implements interface

What worked for me is:

Assert.IsNotNull(typeof (YourClass).GetInterfaces().SingleOrDefault(i => i == typeof (ISomeInterface)));

How to convert SSH keypairs generated using PuTTYgen (Windows) into key-pairs used by ssh-agent and Keychain (Linux)

sudo apt-get install putty

This will automatically install the puttygen tool.

Now to convert the PPK file to be used with SSH command execute the following in terminal

puttygen mykey.ppk -O private-openssh -o my-openssh-key

Then, you can connect via SSH with:

ssh -v [email protected] -i my-openssh-key

http://www.graphicmist.in/use-your-putty-ppk-file-to-ssh-remote-server-in-ubuntu/#comment-28603

CSS content generation before or after 'input' elements

Something like this works:

_x000D_
_x000D_
input + label::after {_x000D_
  content: 'click my input';_x000D_
  color: black;_x000D_
}_x000D_
_x000D_
input:focus + label::after {_x000D_
  content: 'not valid yet';_x000D_
  color: red;_x000D_
}_x000D_
_x000D_
input:valid + label::after {_x000D_
  content: 'looks good';_x000D_
  color: green;_x000D_
}
_x000D_
<input id="input" type="number" required />_x000D_
<label for="input"></label>
_x000D_
_x000D_
_x000D_

Then add some floats or positioning to order stuff.

JSON.parse unexpected character error

Not true for the OP, but this error can be caused by using single quotation marks (') instead of double (") for strings.

The JSON spec requires double quotation marks for strings.

E.g:

JSON.parse(`{"myparam": 'myString'}`)

gives the error, whereas

JSON.parse(`{"myparam": "myString"}`)

does not. Note the quotation marks around myString.

Related: https://stackoverflow.com/a/14355724/1461850

Replace an element into a specific position of a vector

See an example here: http://www.cplusplus.com/reference/stl/vector/insert/ eg.:



...
vector::iterator iterator1;

  iterator1= vec1.begin();
  vec1.insert ( iterator1+i , vec2[i] );

// This means that at position "i" from the beginning it will insert the value from vec2 from position i

Your first approach was replacing the values from vec1[i] with the values from vec2[i]

convert from Color to brush

SolidColorBrush brush = new SolidColorBrush( Color.FromArgb(255,255,139,0) )

The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via

To re-cap the question in the OP:

I am connecting [to a WCF service] using WCFStorm which is able to retrieve all the meta data properly, but when I call the actual method I get:

The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via

The WCFStorm tutorials addresses this issue in Working with IIS and SSL.

Their solution worked for me:

  1. To fix the error, generate a client config that matches the wcf service configuration. The easiest way to do this is with Visual Studio.

    • Open Visual Studio and add a service reference to the service. VS will generate an app.config file that matches the service

    • Edit the app.config file so that it can be read by WCFStorm. Please see Loading Client App.config files. Ensure that the endpoint/@name and endpoint/@contract attributes match the values in wcfstorm.

  2. Load the modified app.config to WCFStorm [using the Client Config toobar button].

  3. Invoke the method. This time the method invocation will no longer fail

Item (1) last bullet in effect means to remove the namespace prefix that VS prepends to the endpoint contract attribute, by default "ServiceReference1"

<endpoint ... contract="ServiceReference1.ListsService" ... />

so in the app.config that you load into WCFStorm you want for ListsService:

<endpoint ... contract="ListsService" ... />

RS256 vs HS256: What's the difference?

Both choices refer to what algorithm the identity provider uses to sign the JWT. Signing is a cryptographic operation that generates a "signature" (part of the JWT) that the recipient of the token can validate to ensure that the token has not been tampered with.

  • RS256 (RSA Signature with SHA-256) is an asymmetric algorithm, and it uses a public/private key pair: the identity provider has a private (secret) key used to generate the signature, and the consumer of the JWT gets a public key to validate the signature. Since the public key, as opposed to the private key, doesn't need to be kept secured, most identity providers make it easily available for consumers to obtain and use (usually through a metadata URL).

  • HS256 (HMAC with SHA-256), on the other hand, involves a combination of a hashing function and one (secret) key that is shared between the two parties used to generate the hash that will serve as the signature. Since the same key is used both to generate the signature and to validate it, care must be taken to ensure that the key is not compromised.

If you will be developing the application consuming the JWTs, you can safely use HS256, because you will have control on who uses the secret keys. If, on the other hand, you don't have control over the client, or you have no way of securing a secret key, RS256 will be a better fit, since the consumer only needs to know the public (shared) key.

Since the public key is usually made available from metadata endpoints, clients can be programmed to retrieve the public key automatically. If this is the case (as it is with the .Net Core libraries), you will have less work to do on configuration (the libraries will fetch the public key from the server). Symmetric keys, on the other hand, need to be exchanged out of band (ensuring a secure communication channel), and manually updated if there is a signing key rollover.

Auth0 provides metadata endpoints for the OIDC, SAML and WS-Fed protocols, where the public keys can be retrieved. You can see those endpoints under the "Advanced Settings" of a client.

The OIDC metadata endpoint, for example, takes the form of https://{account domain}/.well-known/openid-configuration. If you browse to that URL, you will see a JSON object with a reference to https://{account domain}/.well-known/jwks.json, which contains the public key (or keys) of the account.

If you look at the RS256 samples, you will see that you don't need to configure the public key anywhere: it's retrieved automatically by the framework.

Declaring array of objects

var ArrayofObjects = [{}]; //An empty array of objects.

Check if element is clickable in Selenium Java

the class attribute contains disabled when the element is not clickable.

WebElement webElement = driver.findElement(By.id("elementId"));
if(!webElement.getAttribute("class").contains("disabled")){
    webElement.click();
}

Finding last occurrence of substring in string, replacing that

Naïve approach:

a = "A long string with a . in the middle ending with ."
fchar = '.'
rchar = '. -'
a[::-1].replace(fchar, rchar[::-1], 1)[::-1]

Out[2]: 'A long string with a . in the middle ending with . -'

Aditya Sihag's answer with a single rfind:

pos = a.rfind('.')
a[:pos] + '. -' + a[pos+1:]

How to find unused/dead code in java projects

IntelliJ has code analysis tools for detecting code which is unused. You should try making as many fields/methods/classes as non-public as possible and that will show up more unused methods/fields/classes

I would also try to locate duplicate code as a way of reducing code volume.

My last suggestion is try to find open source code which if used would make your code simpler.

How to change the type of a field?

Starting Mongo 4.2, db.collection.update() can accept an aggregation pipeline, finally allowing the update of a field based on its own value:

// { a: "45", b: "x" }
// { a:  53,  b: "y" }
db.collection.update(
  { a : { $type: 1 } },
  [{ $set: { a: { $toString: "$a" } } }],
  { multi: true }
)
// { a: "45", b: "x" }
// { a: "53", b: "y" }
  • The first part { a : { $type: 1 } } is the match query:

    • It filters which documents to update.
    • In this case, since we want to convert "a" to string when its value is a double, this matches elements for which "a" is of type 1 (double)).
    • This table provides the codes representing the different possible types.
  • The second part [{ $set: { a: { $toString: "$a" } } }] is the update aggregation pipeline:

    • Note the squared brackets signifying that this update query uses an aggregation pipeline.
    • $set is a new aggregation operator (Mongo 4.2) which in this case modifies a field.
    • This can be simply read as "$set" the value of "a" to "$a" converted "$toString".
    • What's really new here, is being able in Mongo 4.2 to reference the document itself when updating it: the new value for "a" is based on the existing value of "$a".
    • Also note "$toString" which is a new aggregation operator introduced in Mongo 4.0.
  • Don't forget { multi: true }, otherwise only the first matching document will be updated.


In case your cast isn't from double to string, you have the choice between different conversion operators introduced in Mongo 4.0 such as $toBool, $toInt, ...

And if there isn't a dedicated converter for your targeted type, you can replace { $toString: "$a" } with a $convert operation: { $convert: { input: "$a", to: 2 } } where the value for to can be found in this table:

db.collection.update(
  { a : { $type: 1 } },
  [{ $set: { a: { $convert: { input: "$a", to: 2 } } } }],
  { multi: true }
)

Error 'tunneling socket' while executing npm install

An important point to remember is if you're behind a corporate firewall and you get you're corporate proxy settings from a .pac file, then be sure to use the value for global proxy.

Command to get time in milliseconds

I just wanted to add to Alper's answer what I had to do to get this stuff working:

On Mac, you'll need brew install coreutils, so we can use gdate. Otherwise on Linux, it's just date. And this function will help you time commands without having to create temporary files or anything:

function timeit() {
    start=`gdate +%s%N`
    bash -c $1
    end=`gdate +%s%N`
    runtime=$(((end-start)/1000000000.0))
    echo " seconds"
}

And you can use it with a string:

timeit 'tsc --noEmit'

Reverse order of foreach list items

Walking Backwards

If you're looking for a purely PHP solution, you can also simply count backwards through the list, access it front-to-back:

$accounts = Array(
  '@jonathansampson',
  '@f12devtools',
  '@ieanswers'
);

$index = count($accounts);

while($index) {
  echo sprintf("<li>%s</li>", $accounts[--$index]);
}

The above sets $index to the total number of elements, and then begins accessing them back-to-front, reducing the index value for the next iteration.

Reversing the Array

You could also leverage the array_reverse function to invert the values of your array, allowing you to access them in reverse order:

$accounts = Array(
  '@jonathansampson',
  '@f12devtools',
  '@ieanswers'
);

foreach ( array_reverse($accounts) as $account ) {
  echo sprintf("<li>%s</li>", $account);
}

What is IPV6 for localhost and 0.0.0.0?

The ipv6 localhost is ::1. The unspecified address is ::. This is defined in RFC 4291 section 2.5.

byte[] to hex string

Nice way to do this with LINQ...

var data = new byte[] { 1, 2, 4, 8, 16, 32 }; 
var hexString = data.Aggregate(new StringBuilder(), 
                               (sb,v)=>sb.Append(v.ToString("X2"))
                              ).ToString();

How to compile C programming in Windows 7?

MinGW uses a fairly old version of GCC (3.4.5, I believe), and hasn't been updated in a while. If you're already comfortable with the GCC toolset and just looking to get your feet wet in Windows programming, this may be a good option for you. There are lots of great IDEs available that use this compiler.

Edit: Apparently I was wrong; that's what I get for talking about something I know very little about. Tauran points out that there is a project that aims to provide the MinGW toolkit with the current version of GCC. You can download it from their website.


However, I'm not sure that I can recommend it for serious Windows development. If you're not a idealistic fanboy who can't stomach the notion of ever using Microsoft software, I highly recommend investigating Visual Studio, which comes bundled with Microsoft's C/C++ compiler. The Express version (which includes the same compiler as all the paid-for editions) is absolutely free for download. In addition to the compiler, Visual Studio also provides a world-class IDE that makes developing Windows-specific applications much easier. Yes, detractors will ramble on about the fact that it's not fully standards-compliant, but such is the world of writing Windows applications. They're never going to be truly portable once you include windows.h, so most of the idealistic dedication just ends up being a waste of time.

PHP absolute path to root

In PHP there is a global variable containing various details related to the server. It's called $_SERVER. It contains also the root:

 $_SERVER['DOCUMENT_ROOT']

The only problem is that the entries in this variable are provided by the web server and there is no guarantee that all web servers offer them.

Escaping quotes and double quotes

Escaping parameters like that is usually source of frustration and feels a lot like a time wasted. I see you're on v2 so I would suggest using a technique that Joel "Jaykul" Bennet blogged about a while ago.

Long story short: you just wrap your string with @' ... '@ :

Start-Process \\server\toto.exe @'
-batch=B -param="sort1;parmtxt='Security ID=1234'"
'@

(Mind that I assumed which quotes are needed, and which things you were attempting to escape.) If you want to work with the output, you may want to add the -NoNewWindow switch.

BTW: this was so important issue that since v3 you can use --% to stop the PowerShell parser from doing anything with your parameters:

\\server\toto.exe --% -batch=b -param="sort1;paramtxt='Security ID=1234'"

... should work fine there (with the same assumption).

Count number of lines in a git repository

I've encountered batching problems with git ls-files | xargs wc -l when dealing with large numbers of files, where the line counts will get chunked out into multiple total lines.

Taking a tip from question Why does the wc utility generate multiple lines with "total"?, I've found the following command to bypass the issue:

wc -l $(git ls-files)

Or if you want to only examine some files, e.g. code:

wc -l $(git ls-files | grep '.*\.cs')

Vue - Deep watching an array of objects and calculating the change?

The component solution and deep-clone solution have their advantages, but also have issues:

  1. Sometimes you want to track changes in abstract data - it doesn't always make sense to build components around that data.

  2. Deep-cloning your entire data structure every time you make a change can be very expensive.

I think there's a better way. If you want to watch all items in a list and know which item in the list changed, you can set up custom watchers on every item separately, like so:

var vm = new Vue({
  data: {
    list: [
      {name: 'obj1 to watch'},
      {name: 'obj2 to watch'},
    ],
  },
  methods: {
    handleChange (newVal) {
      // Handle changes here!
      console.log(newVal);
    },
  },
  created () {
    this.list.forEach((val) => {
      this.$watch(() => val, this.handleChange, {deep: true});
    });
  },
});

With this structure, handleChange() will receive the specific list item that changed - from there you can do any handling you like.

I have also documented a more complex scenario here, in case you are adding/removing items to your list (rather than only manipulating the items already there).

Email & Phone Validation in Swift

Kirit Modi's response about Email Validation for Swift 3:

func isValidEmail(testStr:String) -> Bool {
    let emailRegEx = "^(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?(?:(?:(?:[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+(?:\\.[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+)*)|(?:\"(?:(?:(?:(?: )*(?:(?:[!#-Z^-~]|\\[|\\])|(?:\\\\(?:\\t|[ -~]))))+(?: )*)|(?: )+)\"))(?:@)(?:(?:(?:[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)(?:\\.[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)*)|(?:\\[(?:(?:(?:(?:(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))\\.){3}(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))))|(?:(?:(?: )*[!-Z^-~])*(?: )*)|(?:[Vv][0-9A-Fa-f]+\\.[-A-Za-z0-9._~!$&'()*+,;=:]+))\\])))(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?$"
    let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
    let result = emailTest.evaluate(with: testStr)
    return result
  }

Android getActivity() is undefined

If you want to call your activity, just use this . You use the getActivity method when you are inside a fragment.

Removing Duplicate Values from ArrayList

list = list.stream().distinct().collect(Collectors.toList());
This could be one of the solutions using Java8 Stream API. Hope this helps.

LINK : fatal error LNK1104: cannot open file 'D:\...\MyProj.exe'

Mine is that if you set MASM listing file option some extra selection, it will give you this error.

Just use

 Enable Assembler Generated Code Listing   Yes/Sg
 Assembled Code Listing $(ProjectName).lst

it is fine.

But any extra you have issue.

How do I watch a file for changes?

If you're using windows, create this POLL.CMD file

@echo off
:top
xcopy /m /y %1 %2 | find /v "File(s) copied"
timeout /T 1 > nul
goto :top

then you can type "poll dir1 dir2" and it will copy all the files from dir1 to dir2 and check for updates once per second.

The "find" is optional, just to make the console less noisy.

This is not recursive. Maybe you could make it recursive using /e on the xcopy.

How to left align a fixed width string?

This version uses the str.format method.

Python 2.7 and newer

sys.stdout.write("{:<7}{:<51}{:<25}\n".format(code, name, industry))

Python 2.6 version

sys.stdout.write("{0:<7}{1:<51}{2:<25}\n".format(code, name, industry))

UPDATE

Previously there was a statement in the docs about the % operator being removed from the language in the future. This statement has been removed from the docs.

How do I choose grid and block dimensions for CUDA kernels?

There are two parts to that answer (I wrote it). One part is easy to quantify, the other is more empirical.

Hardware Constraints:

This is the easy to quantify part. Appendix F of the current CUDA programming guide lists a number of hard limits which limit how many threads per block a kernel launch can have. If you exceed any of these, your kernel will never run. They can be roughly summarized as:

  1. Each block cannot have more than 512/1024 threads in total (Compute Capability 1.x or 2.x and later respectively)
  2. The maximum dimensions of each block are limited to [512,512,64]/[1024,1024,64] (Compute 1.x/2.x or later)
  3. Each block cannot consume more than 8k/16k/32k/64k/32k/64k/32k/64k/32k/64k registers total (Compute 1.0,1.1/1.2,1.3/2.x-/3.0/3.2/3.5-5.2/5.3/6-6.1/6.2/7.0)
  4. Each block cannot consume more than 16kb/48kb/96kb of shared memory (Compute 1.x/2.x-6.2/7.0)

If you stay within those limits, any kernel you can successfully compile will launch without error.

Performance Tuning:

This is the empirical part. The number of threads per block you choose within the hardware constraints outlined above can and does effect the performance of code running on the hardware. How each code behaves will be different and the only real way to quantify it is by careful benchmarking and profiling. But again, very roughly summarized:

  1. The number of threads per block should be a round multiple of the warp size, which is 32 on all current hardware.
  2. Each streaming multiprocessor unit on the GPU must have enough active warps to sufficiently hide all of the different memory and instruction pipeline latency of the architecture and achieve maximum throughput. The orthodox approach here is to try achieving optimal hardware occupancy (what Roger Dahl's answer is referring to).

The second point is a huge topic which I doubt anyone is going to try and cover it in a single StackOverflow answer. There are people writing PhD theses around the quantitative analysis of aspects of the problem (see this presentation by Vasily Volkov from UC Berkley and this paper by Henry Wong from the University of Toronto for examples of how complex the question really is).

At the entry level, you should mostly be aware that the block size you choose (within the range of legal block sizes defined by the constraints above) can and does have a impact on how fast your code will run, but it depends on the hardware you have and the code you are running. By benchmarking, you will probably find that most non-trivial code has a "sweet spot" in the 128-512 threads per block range, but it will require some analysis on your part to find where that is. The good news is that because you are working in multiples of the warp size, the search space is very finite and the best configuration for a given piece of code relatively easy to find.

How do I make a text input non-editable?

if you really want to use CSS, use following property which will make field non-editable.

pointer-events: none;

How to detect Adblock on my website?

Just add small script on your site:

var isAdsDisplayed = true;

With name adsbygoogle.js

Then do following:

<script src="/js/adsbygoogle.js"></script>
<script>
if(window.isAdsDisplayed === undefined ) {
  // AdBlock is enabled. Show message or track custom data here
}
</script>

Found this solution here

Recreate the default website in IIS

I deleted the C:\inetpub folder and reinstalled IIS which recreated the default website and settings.

How exactly does __attribute__((constructor)) work?

Here is another concrete example.It is for a shared library. The shared library's main function is to communicate with a smart card reader. But it can also receive 'configuration information' at runtime over udp. The udp is handled by a thread which MUST be started at init time.

__attribute__((constructor))  static void startUdpReceiveThread (void) {
    pthread_create( &tid_udpthread, NULL, __feigh_udp_receive_loop, NULL );
    return;

  }

The library was written in c.

Git on Mac OS X v10.7 (Lion)

If you do not want to install Xcode and/or MacPorts/Fink/Homebrew, you could always use the standalone installer: https://sourceforge.net/projects/git-osx-installer/

How can I nullify css property?

like say a class .c1 has height:40px; how do I get rid of this height property?

Sadly, you can't. CSS doesn't have a "default" placeholder.

In that case, you would reset the property using

 height: auto;

as @Ben correctly points out, in some cases, inherit is the correct way to go, for example when resetting the text colour of an a element (that property is inherited from the parent element):

a { color: inherit }

ASP.NET MVC5/IIS Express unable to debug - Code Not Running

In my case the issue was that Virtual directory was not created.

  1. Right click on web project file and go to properties
  2. Navigate to Web
  3. Scroll down to Project Url
  4. Click Create Virtual Directory button to create virtual directory

enter image description here

MongoDB: Is it possible to make a case-insensitive query?

Suppose you want to search "column" in "Table" and you want case insenstive search. The best and efficient way is as below;

//create empty JSON Object
mycolumn = {};

//check if column has valid value
if(column) {
    mycolumn.column = {$regex: new RegExp(column), $options: "i"};
}
Table.find(mycolumn);

Above code just adds your search value as RegEx and searches in with insensitve criteria set with "i" as option.

All the best.

Remove rows with all or some NAs (missing values) in data.frame

For your first question, I have a code that I am comfortable with to get rid of all NAs. Thanks for @Gregor to make it simpler.

final[!(rowSums(is.na(final))),]

For the second question, the code is just an alternation from the previous solution.

final[as.logical((rowSums(is.na(final))-5)),]

Notice the -5 is the number of columns in your data. This will eliminate rows with all NAs, since the rowSums adds up to 5 and they become zeroes after subtraction. This time, as.logical is necessary.

Angular: Can't find Promise, Map, Set and Iterator

Since Angular 2 went to RC 0, /angular2/typings/browser.d.ts is no longer part of the Angular 2 distribution. The file can be installed separately.

From here: https://github.com/angular/angular/issues/8513 there are a few options. The one that worked for me was:

typings install es6-shim --ambient --save

// In your app.ts
/// <reference path="typings/browser.d.ts" />

What properties can I use with event.target?

event.target returns the node that was targeted by the function. This means you can do anything you want to do with any other node like one you'd get from document.getElementById

I'm tried with jQuery

var _target = e.target;
console.log(_target.attr('href'));

Return an error :

.attr not function

But _target.attributes.href.value was works.

Going to a specific line number using Less in Unix

From within less (in Linux):

 g and the line number to go forward

 G and the line number to go backwards

Used alone, g and G will take you to the first and last line in a file respectively; used with a number they are both equivalent.

An example; you want to go to line 320123 of a file,

press 'g' and after the colon type in the number 320123

Additionally you can type '-N' inside less to activate / deactivate the line numbers. You can as a matter of fact pass any command line switches from inside the program, such as -j or -N.

NOTE: You can provide the line number in the command line to start less (less +number -N) which will be much faster than doing it from inside the program:

less +12345 -N /var/log/hugelogfile

This will open a file displaying the line numbers and starting at line 12345

Source: man 1 less and built-in help in less (less 418)

Regular expression to return text between parenthesis

import re

fancy = u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')'

print re.compile( "\((.*)\)" ).search( fancy ).group( 1 )

Android SeekBar setOnSeekBarChangeListener

onProgressChanged is called every time you move the cursor.

@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
    textView.setText(String.valueOf(new Integer(progress)));        
}

so textView should show the progress and alter always if the seekbar is being moved.

what is the use of annotations @Id and @GeneratedValue(strategy = GenerationType.IDENTITY)? Why the generationtype is identity?

In a Object Relational Mapping context, every object needs to have a unique identifier. You use the @Id annotation to specify the primary key of an entity.

The @GeneratedValue annotation is used to specify how the primary key should be generated. In your example you are using an Identity strategy which

Indicates that the persistence provider must assign primary keys for the entity using a database identity column.

There are other strategies, you can see more here.

How can I get the intersection, union, and subset of arrays in Ruby?

If Multiset extends from the Array class

x = [1, 1, 2, 4, 7]
y = [1, 2, 2, 2]
z = [1, 1, 3, 7]

UNION

x.union(y)           # => [1, 2, 4, 7]      (ONLY IN RUBY 2.6)
x.union(y, z)        # => [1, 2, 4, 7, 3]   (ONLY IN RUBY 2.6)
x | y                # => [1, 2, 4, 7]

DIFFERENCE

x.difference(y)      # => [4, 7] (ONLY IN RUBY 2.6)
x.difference(y, z)   # => [4] (ONLY IN RUBY 2.6)
x - y                # => [4, 7]

INTERSECTION

x & y                # => [1, 2]

For more info about the new methods in Ruby 2.6, you can check this blog post about its new features

'IF' in 'SELECT' statement - choose output value based on column values

You can try this also

 SELECT id , IF(type='p', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount FROM table

How can I convert an HTML table to CSV?

Just to add to these answers (as i've recently been attempting a similar thing) - if Google spreadsheets is your spreadsheeting program of choice. Simply do these two things.

1. Strip everything out of your html file around the Table opening/closing tags and resave it as another html file.

2. Import that html file directly into google spreadsheets and you'll have your information beautifully imported (Top tip: if you used inline styles in your table, they will be imported as well!)

Saved me loads of time and figuring out different conversions.

Using a batch to copy from network drive to C: or D: drive

Most importantly you need to mount the drive

net use z: \\yourserver\sharename

Of course, you need to make sure that the account the batch file runs under has permission to access the share. If you are doing this by using a Scheduled Task, you can choose the account by selecting the task, then:

  • right click Properties
  • click on General tab
  • change account under

"When running the task, use the following user account:" That's on Windows 7, it might be slightly different on different versions of Windows.

Then run your batch script with the following changes

copy "z:\FolderName" "C:\TEST_BACKUP_FOLDER"

AngularJS does not send hidden field value

Found a strange behaviour about this hidden value () and we can't make it to work.

After playing around we found the best way is just defined the value in controller itself after the form scope.

.controller('AddController', [$scope, $http, $state, $stateParams, function($scope, $http, $state, $stateParams) {

    $scope.routineForm = {};
    $scope.routineForm.hiddenfield1 = "whatever_value_you_pass_on";

    $scope.sendData = function {

// JSON http post action to API 
}

}])

Why use the INCLUDE clause when creating an index?

If the column is not in the WHERE/JOIN/GROUP BY/ORDER BY, but only in the column list in the SELECT clause is where you use INCLUDE.

The INCLUDE clause adds the data at the lowest/leaf level, rather than in the index tree. This makes the index smaller because it's not part of the tree

INCLUDE columns are not key columns in the index, so they are not ordered. This means it isn't really useful for predicates, sorting etc as I mentioned above. However, it may be useful if you have a residual lookup in a few rows from the key column(s)

Another MSDN article with a worked example

Does Spring @Transactional attribute work on a private method?

The Question is not private or public, the question is: How is it invoked and which AOP implementation you use!

If you use (default) Spring Proxy AOP, then all AOP functionality provided by Spring (like @Transactional) will only be taken into account if the call goes through the proxy. -- This is normally the case if the annotated method is invoked from another bean.

This has two implications:

  • Because private methods must not be invoked from another bean (the exception is reflection), their @Transactional Annotation is not taken into account.
  • If the method is public, but it is invoked from the same bean, it will not be taken into account either (this statement is only correct if (default) Spring Proxy AOP is used).

@See Spring Reference: Chapter 9.6 9.6 Proxying mechanisms

IMHO you should use the aspectJ mode, instead of the Spring Proxies, that will overcome the problem. And the AspectJ Transactional Aspects are woven even into private methods (checked for Spring 3.0).

Int to Decimal Conversion - Insert decimal point at specified location

Declare it as a decimal which uses the int variable and divide this by 100

int number = 700
decimal correctNumber = (decimal)number / 100;

Edit: Bala was faster with his reaction

How to set an iframe src attribute from a variable in AngularJS

I suspect looking at the excerpt that the function trustSrc from trustSrc(currentProject.url) is not defined in the controller.

You need to inject the $sce service in the controller and trustAsResourceUrl the url there.

In the controller:

function AppCtrl($scope, $sce) {
    // ...
    $scope.setProject = function (id) {
      $scope.currentProject = $scope.projects[id];
      $scope.currentProjectUrl = $sce.trustAsResourceUrl($scope.currentProject.url);
    }
}

In the Template:

<iframe ng-src="{{currentProjectUrl}}"> <!--content--> </iframe>

How to set NODE_ENV to production/development in OS X

heroku config:set NODE_ENV="production"

How to get the first word in the string

Regex is unnecessary for this. Just use some_string.split(' ', 1)[0] or some_string.partition(' ')[0].

Excel 2013 horizontal secondary axis

You should follow the guidelines on Add a secondary horizontal axis:

Add a secondary horizontal axis

To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.

  1. Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.

  2. On the Layout tab, in the Axes group, click Axes.

    enter image description here

  3. Click Secondary Horizontal Axis, and then click the display option that you want.

enter image description here


Add a secondary vertical axis

You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.

  1. In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:

    • Click the chart.

      This displays the Chart Tools, adding the Design, Layout, and Format tabs.

    • On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.

      enter image description here

  2. On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.

    Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.

  3. On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.

    A secondary vertical axis is displayed in the chart.

  4. To change the display of the secondary vertical axis, do the following:

    • On the Layout tab, in the Axes group, click Axes.

    • Click Secondary Vertical Axis, and then click the display option that you want.

  5. To change the axis options of the secondary vertical axis, do the following:

    • Right-click the secondary vertical axis, and then click Format Axis.

    • Under Axis Options, select the options that you want to use.

How to download python from command-line?

wget --no-check-certificate https://www.python.org/ftp/python/2.7.11/Python-2.7.11.tgz
tar -xzf Python-2.7.11.tgz  
cd Python-2.7.11

Now read the README file to figure out how to install, or do the following with no guarantees from me that it will be exactly what you need.

./configure  
make  
sudo make install  

For Python 3.5 use the following download address:
http://www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz

For other versions and the most up to date download links:
http://www.python.org/getit/

C++ where to initialize static const

Since C++17 the inline specifier also applies to variables. You can now define static member variables in the class definition:

#include <string>

class foo {
public:
   foo();
   foo( int );
private:
   inline static const std::string s { "foo" };
};

How to get the current user's Active Directory details in C#

Add reference to COM "Active DS Type Library"


            Int32 nameTypeNT4               = (int) ActiveDs.ADS_NAME_TYPE_ENUM.ADS_NAME_TYPE_NT4;
            Int32 nameTypeDN                = (int) ActiveDs.ADS_NAME_TYPE_ENUM.ADS_NAME_TYPE_1779;
            Int32 nameTypeUserPrincipalName = (int) ActiveDs.ADS_NAME_TYPE_ENUM.ADS_NAME_TYPE_USER_PRINCIPAL_NAME;

            ActiveDs.NameTranslate nameTranslate = new ActiveDs.NameTranslate();

            // Convert NT name DOMAIN\User into AD distinguished name 
            // "CN= User\\, Name,OU=IT,OU=All Users,DC=Company,DC=com"
            nameTranslate.Set(nameTypeNT4, ntUser);

            String distinguishedName = nameTranslate.Get(nameTypeDN);

            Console.WriteLine(distinguishedName);

            // Convert AD distinguished name "CN= User\\, Name,OU=IT,OU=All Users,DC=Company,DC=com" 
            // into NT name DOMAIN\User
            ntUser = String.Empty;
            nameTranslate.Set(nameTypeDN, distinguishedName);
            ntUser = nameTranslate.Get(nameTypeNT4);
            Console.WriteLine(ntUser);

            // Convert NT name DOMAIN\User into AD UserPrincipalName [email protected]
            nameTranslate.Set(nameTypeNT4, ntUser);
            String userPrincipalName = nameTranslate.Get(nameTypeUserPrincipalName);

            Console.WriteLine(userPrincipalName);

Label on the left side instead above an input field

I managed to fix my issue with. Seems to work fine and means I dont have to add widths to all my inputs manually.

.form-inline .form-group input {
 width: auto; 
}

How to perform a fade animation on Activity transition?

you can also use this code in your style.xml file so you don't need to write anything else in your activity.java

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:windowAnimationStyle">@style/AppTheme.WindowTransition</item>
</style>

<!-- Setting window animation -->
<style name="AppTheme.WindowTransition">
    <item name="android:windowEnterAnimation">@android:anim/fade_in</item>
    <item name="android:windowExitAnimation">@android:anim/fade_out</item>
</style>

How to make --no-ri --no-rdoc the default for gem install?

You just add the following line to your local ~/.gemrc file (it is in your home folder):

gem: --no-document

or you can add this line to the global gemrc config file.

Here is how to find it (in Linux):

strace gem source 2>&1 | grep gemrc

Enabling WiFi on Android Emulator

As of now, with Revision 26.1.3 of the android emulator, it is finally possible on the image v8 of the API 25. If the emulator was created before you upgrade to the latest API 25 image, you need to wipe data or simply delete and recreate your image if you prefer.

Added support for Wi-Fi in some system images (currently only API level 25). An access point called "AndroidWifi" is available and Android automatically connects to it. Wi-Fi support can be disabled by running the emulator with the command line parameter -feature -Wifi.

from https://developer.android.com/studio/releases/emulator.html#26-1-3

No 'Access-Control-Allow-Origin' header is present on the requested resource - Resteasy

Your resource methods won't get hit, so their headers will never get set. The reason is that there is what's called a preflight request before the actual request, which is an OPTIONS request. So the error comes from the fact that the preflight request doesn't produce the necessary headers.

For RESTeasy, you should use CorsFilter. You can see here for some example how to configure it. This filter will handle the preflight request. So you can remove all those headers you have in your resource methods.

See Also:

Know relationships between all the tables of database in SQL Server

Sometimes, a textual representation might also help; with this query on the system catalog views, you can get a list of all FK relationships and how the link two tables (and what columns they operate on).

SELECT
    fk.name 'FK Name',
    tp.name 'Parent table',
    cp.name, cp.column_id,
    tr.name 'Refrenced table',
    cr.name, cr.column_id
FROM 
    sys.foreign_keys fk
INNER JOIN 
    sys.tables tp ON fk.parent_object_id = tp.object_id
INNER JOIN 
    sys.tables tr ON fk.referenced_object_id = tr.object_id
INNER JOIN 
    sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
INNER JOIN 
    sys.columns cp ON fkc.parent_column_id = cp.column_id AND fkc.parent_object_id = cp.object_id
INNER JOIN 
    sys.columns cr ON fkc.referenced_column_id = cr.column_id AND fkc.referenced_object_id = cr.object_id
ORDER BY
    tp.name, cp.column_id

Dump this into Excel, and you can slice and dice - based on the parent table, the referenced table or anything else.

I find visual guides helpful - but sometimes, textual documentation is just as good (or even better) - just my 2 cents.....

Parsing a JSON string in Ruby

That data looks like it is in JSON format.

You can use this JSON implementation for Ruby to extract it.

Root element is missing

If you are loading the XML file from a remote location, I would check to see if the file is actually being downloaded correctly using a sniffer like Fiddler.

I wrote a quick console app to run your code and parse the file and it works fine for me.

How to add items to a spinner in Android?

To add one more item to Spinner you can:

ArrayAdapter myAdapter = 
  ((ArrayAdapter) mySpinner.getAdapter());

myAdapter.add(myValue);

myAdapter.notifyDataSetChanged();

Batch file: Find if substring is in string (not in a file)

Better answer was here:

set "i=hello " world"
set i|find """" >nul && echo contains || echo not_contains

Is there a way to make numbers in an ordered list bold?

If you are using Bootstrap 4:

<ol class="font-weight-bold">
    <li><span class="font-weight-light">Curabitur aliquet quam id dui posuere blandit.</span></li>
    <li><span class="font-weight-light">Curabitur aliquet quam id dui posuere blandit.</span></li>
</ol>

Subtract minute from DateTime in SQL Server 2005

Use DATEPART to pull apart your interval, and DATEADD to subtract the parts:

select dateadd(
     hh,
    -1 * datepart(hh, cast('1:15' as datetime)),
    dateadd(
        mi,
        -1 * datepart(mi, cast('1:15' as datetime)),
        '2000-01-01 08:30:00'))

or, we can convert to minutes first (though OP would prefer not to):

declare @mins int
select @mins = datepart(mi, cast('1:15' as datetime)) + 60 * datepart(hh, cast('1:15' as datetime)) 
select dateadd(mi, -1 * @mins, '2000-01-01 08:30:00')

How to use ? : if statements with Razor and inline code blocks

The key is to encapsulate the expression in parentheses after the @ delimiter. You can make any compound expression work this way.

How to get the width of a react element

Actually, would be better to isolate this resize logic in a custom hook. You can create a custom hook like this:

const useResize = (myRef) => {
  const [width, setWidth] = useState(0)
  const [height, setHeight] = useState(0)

  useEffect(() => {
    const handleResize = () => {
      setWidth(myRef.current.offsetWidth)
      setHeight(myRef.current.offsetHeight)
    }

    window.addEventListener('resize', handleResize)

    return () => {
      window.removeEventListener('resize', handleResize)
    }
  }, [myRef])

  return { width, height }
}

and then you can use it like:

const MyComponent = () => {
  const componentRef = useRef()
  const { width, height } = useResize(componentRef)

  return (
    <div ref={myRef}>
      <p>width: {width}px</p>
      <p>height: {height}px</p>
    <div/>
  )
}

How to check if a string is a valid JSON string in JavaScript without using Try/Catch

_x000D_
_x000D_
var jsonstring='[{"ConnectionString":"aaaaaa","Server":"ssssss"}]';_x000D_
_x000D_
if(((x)=>{try{JSON.parse(x);return true;}catch(e){return false}})(jsonstring)){_x000D_
_x000D_
document.write("valide json")_x000D_
_x000D_
}else{_x000D_
document.write("invalide json")_x000D_
}
_x000D_
_x000D_
_x000D_

POST request with a simple string in body with Alamofire

You can do this:

  1. I created a separated request Alamofire object.
  2. Convert string to Data
  3. Put in httpBody the data

    var request = URLRequest(url: URL(string: url)!)
    request.httpMethod = HTTPMethod.post.rawValue
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    
    let pjson = attendences.toJSONString(prettyPrint: false)
    let data = (pjson?.data(using: .utf8))! as Data
    
    request.httpBody = data
    
    Alamofire.request(request).responseJSON { (response) in
    
    
        print(response)
    
    }
    

How to display a gif fullscreen for a webpage background?

You can set up a background with your GIF file and set the body this way:

body{
background-image:url('http://www.example.com/yourfile.gif');
background-position: center;
background-size: cover;
}

Change background image URL with your GIF. With background-position: center you can put the image to the center and with background-size: cover you set the picture to fit all the screen. You can also set background-size: contain if you want to fit the picture at 100% of the screen but without leaving any part of the picture without showing.

Here's more info about the property:

http://www.w3schools.com/cssref/css3_pr_background-size.asp

Hope it helps :)

How do I find the version of Apache running without access to the command line?

Simply use something like the following - the string should be there already:

<?php
   if(isset($_SERVER['SERVER_SOFTWARE'])){
      echo $_SERVER['SERVER_SOFTWARE'];
   }
?>

How do I check (at runtime) if one class is a subclass of another?

According to the Python doc, we can also use class.__mro__ attribute or class.mro() method:

class Suit:
    pass
class Heart(Suit):
    pass
class Spade(Suit):
    pass
class Diamond(Suit):
    pass
class Club(Suit):
    pass

>>> Heart.mro()
[<class '__main__.Heart'>, <class '__main__.Suit'>, <class 'object'>]
>>> Heart.__mro__
(<class '__main__.Heart'>, <class '__main__.Suit'>, <class 'object'>)

Suit in Heart.mro()  # True
object in Heart.__mro__  # True
Spade in Heart.mro()  # False

How can I make a JPA OneToOne relation lazy

Most efficient mapping of a one-to-one association You can avoid all these problems and get rid of the foreign key column by using the same primary key value for both associated entities. You can do that by annotating the owning side of the association with @MapsId.

@Entity
public class Book {
 
    @Id
    @GeneratedValue
    private Long id;
 
    @OneToOne(mappedBy = "book", fetch = FetchType.LAZY, optional = false)
    private Manuscript manuscript;
 
    ...
}


@Entity
public class Manuscript {
 
    @Id
    private Long id;
 
    @OneToOne
    @MapsId
    @JoinColumn(name = "id")
    private Book book;
 
    ...
}


Book b = em.find(Book.class, 100L);
Manuscript m = em.find(Manuscript.class, b.getId());

More Detail click on this url

Github "Updates were rejected because the remote contains work that you do not have locally."

You may refer to: How to deal with "refusing to merge unrelated histories" error:

$ git pull --allow-unrelated-histories
$ git push -f origin master

Handling exceptions from Java ExecutorService tasks

From the docs:

Note: When actions are enclosed in tasks (such as FutureTask) either explicitly or via methods such as submit, these task objects catch and maintain computational exceptions, and so they do not cause abrupt termination, and the internal exceptions are not passed to this method.

When you submit a Runnable, it'll get wrapped in a Future.

Your afterExecute should be something like this:

public final class ExtendedExecutor extends ThreadPoolExecutor {

    // ...

    protected void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
        if (t == null && r instanceof Future<?>) {
            try {
                Future<?> future = (Future<?>) r;
                if (future.isDone()) {
                    future.get();
                }
            } catch (CancellationException ce) {
                t = ce;
            } catch (ExecutionException ee) {
                t = ee.getCause();
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
            }
        }
        if (t != null) {
            System.out.println(t);
        }
    }
}

To show error message without alert box in Java Script

try this

<html>
  <head>
  <script type="text/javascript">
  function validate() {
  if(myform.fname.value.length==0)
  {
   document.getElementById("error").innerHTML="this is invalid name ";
   document.myform.fname.value="";
   document.myform.fname.focus();
  }
  }
  </script>
  </head>
  <body>
  <form name="myform">
  First_Name
  <input type="text" id="fname" name="fname" onblur="validate()"> </input>
<span style="color:red;" id="error" > </span>
  <br> <br>
  Last_Name
  <input type="text" id="lname" name="lname" onblur="validate()"> </input>

  <br>
  <input type=button value=check> 

  </form>
  </body>
</html>

Chart.js v2 hide dataset labels

You can also put the tooltip onto one line by removing the "title":

this.chart = new Chart(ctx, {
    type: this.props.horizontal ? 'horizontalBar' : 'bar',
    options: {
        legend: {
            display: false,
        },
        tooltips: {
            callbacks: {
                label: tooltipItem => `${tooltipItem.yLabel}: ${tooltipItem.xLabel}`, 
                title: () => null,
            }
        },
    },
});

enter image description here

Force browser to clear cache

I implemented this simple solution that works for me (not yet on production environment):

function verificarNovaVersio() {
    var sVersio = localStorage['gcf_versio'+ location.pathname] || 'v00.0.0000';
    $.ajax({
        url: "./versio.txt"
        , dataType: 'text'
        , cache: false
        , contentType: false
        , processData: false
        , type: 'post'
     }).done(function(sVersioFitxer) {
        console.log('Versió App: '+ sVersioFitxer +', Versió Caché: '+ sVersio);
        if (sVersio < (sVersioFitxer || 'v00.0.0000')) {
            localStorage['gcf_versio'+ location.pathname] = sVersioFitxer;
            location.reload(true);
        }
    });
}

I've a little file located where the html are:

"versio.txt":

v00.5.0014

This function is called in all of my pages, so when loading it checks if the localStorage's version value is lower than the current version and does a

location.reload(true);

...to force reload from server instead from cache.

(obviously, instead of localStorage you can use cookies or other persistent client storage)

I opted for this solution for its simplicity, because only mantaining a single file "versio.txt" will force the full site to reload.

The queryString method is hard to implement and is also cached (if you change from v1.1 to a previous version will load from cache, then it means that the cache is not flushed, keeping all previous versions at cache).

I'm a little newbie and I'd apreciate your professional check & review to ensure my method is a good approach.

Hope it helps.

wkhtmltopdf: cannot connect to X server

I tried to do sudo apt-get install wkhtmltopdf but without any success. Instead I recommend you try:

  1. Download the latest executable (.11 rc1) :

    wget https://wkhtmltopdf.googlecode.com/files/wkhtmltopdf-0.11.0_rc1-static-i386.tar.bz2

  2. uncompress it :

    tar -vxf wkhtmltopdf-0.11.0_rc1-static-i386.tar.bz2

  3. rename it :

    mv wkhtmltopdf-i386 wkhtmltopdf

  4. chmod it to executable :

    chmod a+x wkhtmltopdf

  5. place it into /usr/bin :

    sudo mv wkhtmltopdf /usr/bin

How to use Bootstrap 4 in ASP.NET Core

Try Libman, it's as simple as Bower and you can specify wwwroot/lib/ as the download folder.

Is the ternary operator faster than an "if" condition in Java

Does it matter which I use?

Yes! The second is vastly more readable. You are trading one line which concisely expresses what you want against nine lines of effectively clutter.

Which is faster?

Neither.

Is it a better practice to use the shortest code whenever possible?

Not “whenever possible” but certainly whenever possible without detriment effects. Shorter code is at least potentially more readable since it focuses on the relevant part rather than on incidental effects (“boilerplate code”).

How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

Here's my version that works for multiple pids, logs warnings if execution takes too long, and stops the subprocesses if execution takes longer than a given value.

function WaitForTaskCompletion {
    local pids="${1}" # pids to wait for, separated by semi-colon
    local soft_max_time="${2}" # If execution takes longer than $soft_max_time seconds, will log a warning, unless $soft_max_time equals 0.
    local hard_max_time="${3}" # If execution takes longer than $hard_max_time seconds, will stop execution, unless $hard_max_time equals 0.
    local caller_name="${4}" # Who called this function
    local exit_on_error="${5:-false}" # Should the function exit program on subprocess errors       

    Logger "${FUNCNAME[0]} called by [$caller_name]."

    local soft_alert=0 # Does a soft alert need to be triggered, if yes, send an alert once 
    local log_ttime=0 # local time instance for comparaison

    local seconds_begin=$SECONDS # Seconds since the beginning of the script
    local exec_time=0 # Seconds since the beginning of this function

    local retval=0 # return value of monitored pid process
    local errorcount=0 # Number of pids that finished with errors

    local pidCount # number of given pids

    IFS=';' read -a pidsArray <<< "$pids"
    pidCount=${#pidsArray[@]}

    while [ ${#pidsArray[@]} -gt 0 ]; do
        newPidsArray=()
        for pid in "${pidsArray[@]}"; do
            if kill -0 $pid > /dev/null 2>&1; then
                newPidsArray+=($pid)
            else
                wait $pid
                result=$?
                if [ $result -ne 0 ]; then
                    errorcount=$((errorcount+1))
                    Logger "${FUNCNAME[0]} called by [$caller_name] finished monitoring [$pid] with exitcode [$result]."
                fi
            fi
        done

        ## Log a standby message every hour
        exec_time=$(($SECONDS - $seconds_begin))
        if [ $((($exec_time + 1) % 3600)) -eq 0 ]; then
            if [ $log_ttime -ne $exec_time ]; then
                log_ttime=$exec_time
                Logger "Current tasks still running with pids [${pidsArray[@]}]."
            fi
        fi

        if [ $exec_time -gt $soft_max_time ]; then
            if [ $soft_alert -eq 0 ] && [ $soft_max_time -ne 0 ]; then
                Logger "Max soft execution time exceeded for task [$caller_name] with pids [${pidsArray[@]}]."
                soft_alert=1
                SendAlert

            fi
            if [ $exec_time -gt $hard_max_time ] && [ $hard_max_time -ne 0 ]; then
                Logger "Max hard execution time exceeded for task [$caller_name] with pids [${pidsArray[@]}]. Stopping task execution."
                kill -SIGTERM $pid
                if [ $? == 0 ]; then
                    Logger "Task stopped successfully"
                else
                    errrorcount=$((errorcount+1))
                fi
            fi
        fi

        pidsArray=("${newPidsArray[@]}")
        sleep 1
    done

    Logger "${FUNCNAME[0]} ended for [$caller_name] using [$pidCount] subprocesses with [$errorcount] errors."
    if [ $exit_on_error == true ] && [ $errorcount -gt 0 ]; then
        Logger "Stopping execution."
        exit 1337
    else
        return $errorcount
    fi
}

# Just a plain stupid logging function to be replaced by yours
function Logger {
    local value="${1}"

    echo $value
}

Example, wait for all three processes to finish, log a warning if execution takes loger than 5 seconds, stop all processes if execution takes longer than 120 seconds. Don't exit program on failures.

function something {

    sleep 10 &
    pids="$!"
    sleep 12 &
    pids="$pids;$!"
    sleep 9 &
    pids="$pids;$!"

    WaitForTaskCompletion $pids 5 120 ${FUNCNAME[0]} false
}
# Launch the function
someting
    

Convert a number to 2 decimal places in Java

DecimalFormat df=new DecimalFormat("0.00");

Use this code to get exact two decimal points. Even if the value is 0.0 it will give u 0.00 as output.

Instead if you use:

DecimalFormat df=new DecimalFormat("#.00");  

It wont convert 0.2659 into 0.27. You will get an answer like .27.

Using a dictionary to select function to execute

Often classes are used to enclose methods and following is the extension for answers above with default method in case the method is not found.

class P:

     def p1(self):
         print('Start')

     def p2(self):
         print('Help')

     def ps(self):
         print('Settings')

     def d(self):
         print('Default function')

     myDict = {
         "start": p1,
         "help": p2,
         "settings": ps
     }

     def call_it(self):
         name = 'start'
         f = lambda self, x : self.myDict.get(x, lambda x : self.d())(self)
         f(self, name)


 p = P()
 p.call_it()

Android Studio build fails with "Task '' not found in root project 'MyProject'."

In my case, I meet this problem that compile options in Android Studio is "stacktrace." Modify stacktrace to --stacktrace, the problem solved.

enter image description here

How do I use variables in Oracle SQL Developer?

Simple answer NO.

However you can achieve something similar by running the following version using bind variables:

SELECT * FROM Employees WHERE EmployeeID = :EmpIDVar 

Once you run the query above in SQL Developer you will be prompted to enter value for the bind variable EmployeeID.

Is there a way to make HTML5 video fullscreen?

From CSS

video {
    position: fixed; right: 0; bottom: 0;
    min-width: 100%; min-height: 100%;
    width: auto; height: auto; z-index: -100;
    background: url(polina.jpg) no-repeat;
    background-size: cover;
}

Upload files with FTP using PowerShell

I am not sure you can 100% bullet proof the script from not hanging or crashing, as there are things outside your control (what if the server loses power mid-upload?) - but this should provide a solid foundation for getting you started:

# create the FtpWebRequest and configure it
$ftp = [System.Net.FtpWebRequest]::Create("ftp://localhost/me.png")
$ftp = [System.Net.FtpWebRequest]$ftp
$ftp.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$ftp.Credentials = new-object System.Net.NetworkCredential("anonymous","anonymous@localhost")
$ftp.UseBinary = $true
$ftp.UsePassive = $true
# read in the file to upload as a byte array
$content = [System.IO.File]::ReadAllBytes("C:\me.png")
$ftp.ContentLength = $content.Length
# get the request stream, and write the bytes into it
$rs = $ftp.GetRequestStream()
$rs.Write($content, 0, $content.Length)
# be sure to clean up after ourselves
$rs.Close()
$rs.Dispose()

psql: FATAL: Peer authentication failed for user "dev"

While @flaviodesousa's answer would work, it also makes it mandatory for all users (everyone else) to enter a password.

Sometime it makes sense to keep peer authentication for everyone else, but make an exception for a service user. In that case you would want to add a line to the pg_hba.conf that looks like:

local   all             some_batch_user                         md5

I would recommend that you add this line right below the commented header line:

# TYPE  DATABASE        USER            ADDRESS                 METHOD
local   all             some_batch_user                         md5

You will need to restart PostgreSQL using

sudo service postgresql restart

If you're using 9.3, your pg_hba.conf would most likely be:

/etc/postgresql/9.3/main/pg_hba.conf

Describe table structure

Sql server

DECLARE @tableName nvarchar(100)
SET @tableName = N'members' -- change with table name
SELECT
    [column].*,
    COLUMNPROPERTY(object_id([column].[TABLE_NAME]), [column].[COLUMN_NAME], 'IsIdentity') AS [identity]
FROM 
    INFORMATION_SCHEMA.COLUMNS [column] 
WHERE
    [column].[Table_Name] = @tableName

How to place a div below another div?

You have set #slider as absolute, which means that it "is positioned relative to the nearest positioned ancestor" (confusing, right?). Meanwhile, #content div is placed relative, which means "relative to its normal position". So the position of the 2 divs is not related.

You can read about CSS positioning here

If you set both to relative, the divs will be one after the other, as shown here:

#slider {
    position:relative;
    left:0;
    height:400px;

    border-style:solid;
    border-width:5px;
}
#slider img {
    width:100%;
}

#content {
    position:relative;
}

#content #text {
    position:relative;
    width:950px;
    height:215px;
    color:red;
}

http://jsfiddle.net/uorgj4e1/

How to save RecyclerView's scroll position using RecyclerView.State?

Activity.java:

public RecyclerView.LayoutManager mLayoutManager;

Parcelable state;

    mLayoutManager = new LinearLayoutManager(this);


// Inside `onCreate()` lifecycle method, put the below code :

    if(state != null) {
    mLayoutManager.onRestoreInstanceState(state);

    } 

    @Override
    protected void onResume() {
        super.onResume();

        if (state != null) {
            mLayoutManager.onRestoreInstanceState(state);
        }
    }   

   @Override
    protected void onPause() {
        super.onPause();

        state = mLayoutManager.onSaveInstanceState();

    }   

Why I'm using OnSaveInstanceState() in onPause() means, While switch to another activity onPause would be called.It will save that scroll position and restore the position when we coming back from another activity.

PATH issue with pytest 'ImportError: No module named YadaYadaYada'

I had a similar issue. pytest did not recognize a module installed in the environment I was working in.

I resolved it by also installing pytest into the same environment.

How to test whether a service is running from the command line

Thinking a little bit outside the box here I'm going to propose that powershell may be an answer on up-to-date XP/2003 machines and certainly on Vista/2008 and newer (instead of .bat/.cmd). Anyone who has some Perl in their background should feel at-home pretty quickly.


$serviceName = "ServiceName";
$serviceStatus = (get-service "$serviceName").Status;

if ($serviceStatus -eq "Running") {
    echo "Service is Running";
}
else {
    #Could be Stopped, Stopping, Paused, or even Starting...
    echo "Service is $serviceStatus";
}

Another way, if you have significant investment in batch is to run the PS script as a one-liner, returning an exit code.


@ECHO off
SET PS=powershell -nologo -command
%PS% "& {if((get-service SvcName).Status -eq 'Running'){exit 1}}"

ECHO.%ERRORLEVEL%

Running as a one-liner also gets around the default PS code signing policy at the expense of messiness. To put the PS commands in a .ps1 file and run like powershell myCode.ps1 you may find signing your powershell scripts is neccessary to run them in an automated way (depends on your environment). See http://www.hanselman.com/blog/SigningPowerShellScripts.aspx for details

Questions every good Database/SQL developer should be able to answer

Give an example where denomralization is preferable.

(I like this one because people come rampaging out of college looking to put everything into 3rd normal form)

Customizing the template within a Directive

Here's what I ended up using.

I'm very new to AngularJS, so would love to see better / alternative solutions.

angular.module('formComponents', [])
    .directive('formInput', function() {
        return {
            restrict: 'E',
            scope: {},
            link: function(scope, element, attrs)
            {
                var type = attrs.type || 'text';
                var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
                var htmlText = '<div class="control-group">' +
                    '<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
                        '<div class="controls">' +
                        '<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
                        '</div>' +
                    '</div>';
                element.html(htmlText);
            }
        }
    })

Example usage:

<form-input label="Application Name" form-id="appName" required/></form-input>
<form-input type="email" label="Email address" form-id="emailAddress" required/></form-input>
<form-input type="password" label="Password" form-id="password" /></form-input>

How to view changes made to files on a certain revision in Subversion

With this command you will see all changes in the repository path/to/repo that were committed in revision <revision>:

svn diff -c <revision> path/to/repo

The -c indicates that you would like to look at a changeset, but there are many other ways you can look at diffs and changesets. For example, if you would like to know which files were changed (but not how), you can issue

svn log -v -r <revision>

Or, if you would like to show at the changes between two revisions (and not just for one commit):

svn diff -r <revA>:<revB> path/to/repo

Swift days between two NSDates

Swift 5. Thanks to Emin Bugra Saral above for the startOfDay suggestion.

extension Date {
    
    func daysBetween(date: Date) -> Int {
        return Date.daysBetween(start: self, end: date)
    }
    
    static func daysBetween(start: Date, end: Date) -> Int {
        let calendar = Calendar.current
        
        // Replace the hour (time) of both dates with 00:00
        let date1 = calendar.startOfDay(for: start)
        let date2 = calendar.startOfDay(for: end)
        
        let a = calendar.dateComponents([.day], from: date1, to: date2)
        return a.value(for: .day)!
    }
}

Usage:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let start = dateFormatter.date(from: "2017-01-01")!
let end = dateFormatter.date(from: "2018-01-01")!

let diff = Date.daysBetween(start: start, end: end) // 365
// or
let diff = start.daysBetween(date: end) // 365

Resetting a setTimeout

var myTimer = setTimeout(..., 115000);
something.click(function () {
    clearTimeout(myTimer);
    myTimer = setTimeout(..., 115000);
}); 

Something along those lines!

git repo says it's up-to-date after pull but files are not updated

For me my forked branch was not in sync with the master branch. So I went to bitbucket and synced and merged my forked branch and then tried to take the pull. Then it worked fine.

Kubernetes service external ip pending

I created a single node k8s cluster using kubeadm. When i tried PortForward and kubectl proxy, it showed external IP as pending.

$ kubectl get svc -n argocd argocd-server
NAME            TYPE           CLUSTER-IP      EXTERNAL-IP   PORT(S)                      AGE
argocd-server   LoadBalancer   10.107.37.153   <pending>     80:30047/TCP,443:31307/TCP   110s

In my case I've patched the service like this:

kubectl patch svc <svc-name> -n <namespace> -p '{"spec": {"type": "LoadBalancer", "externalIPs":["172.31.71.218"]}}'

After this, it started serving over the public IP

$ kubectl get svc argo-ui -n argo
NAME      TYPE           CLUSTER-IP     EXTERNAL-IP     PORT(S)        AGE
argo-ui   LoadBalancer   10.103.219.8   172.31.71.218   80:30981/TCP   7m50s

Remove part of a string

Here's the strsplit solution if s is a vector:

> s <- c("TGAS_1121", "MGAS_1432")
> s1 <- sapply(strsplit(s, split='_', fixed=TRUE), function(x) (x[2]))
> s1
[1] "1121" "1432"

How to configure log4j.properties for SpringJUnit4ClassRunner?

I was using Maven in eclipse and I did not want to have an additional copy of the properties file in the root folder. You can do the following in eclipse:

  1. Open run dialog (click the little arrow next to the play button and go to run configurations)
  2. Go to the "classpath" tab
  3. Select the "User Entries" and click the "Advanced" button on the right side.
  4. Now select the "Add External folder" radio button.
  5. Select the resources folder

Bootstrap: adding gaps between divs

The easiest way to do it is to add mb-5 to your classes. That is <div class='row mb-5'>.

NOTE:

  • mb varies betweeen 1 to 5
  • The Div MUST have the row class

How to change permissions for a folder and its subfolders/files in one step?

For already created files:

find . \( -type f -exec chmod g=r,o=r {} \; \) , \( -type d -exec chmod g=rx,o=rx {} \; \)

For future created files:

sudo nano /etc/profile

And set:

umask 022

Common modes are:

  • 077: u=rw,g=,o=
  • 007: u=rw,g=rw,o=
  • 022: u=rw,g=r,o=r
  • 002: u=rw,g=rw,o=r

How to completely uninstall kubernetes

In my "Ubuntu 16.04", I use next steps to completely remove and clean Kubernetes (installed with "apt-get"):

kubeadm reset
sudo apt-get purge kubeadm kubectl kubelet kubernetes-cni kube*   
sudo apt-get autoremove  
sudo rm -rf ~/.kube

And restart the computer.

try/catch with InputMismatchException creates infinite loop

YOu can also try the following

   do {
        try {
            System.out.println("Enter first num: ");
            n1 = Integer.parseInt(input.next());

            System.out.println("Enter second num: ");
            n2 = Integer.parseInt(input.next());

            nQuotient = n1/n2;

            bError = false;
        } 
        catch (Exception e) {
            System.out.println("Error!");
            input.reset();
        }
    } while (bError);

How to fix div on scroll

You can find an example below. Basically you attach a function to window's scroll event and trace scrollTop property and if it's higher than desired threshold you apply position: fixed and some other css properties.

_x000D_
_x000D_
jQuery(function($) {_x000D_
  $(window).scroll(function fix_element() {_x000D_
    $('#target').css(_x000D_
      $(window).scrollTop() > 100_x000D_
        ? { 'position': 'fixed', 'top': '10px' }_x000D_
        : { 'position': 'relative', 'top': 'auto' }_x000D_
    );_x000D_
    return fix_element;_x000D_
  }());_x000D_
});
_x000D_
body {_x000D_
  height: 2000px;_x000D_
  padding-top: 100px;_x000D_
}_x000D_
code {_x000D_
  padding: 5px;_x000D_
  background: #efefef;_x000D_
}_x000D_
#target {_x000D_
  color: #c00;_x000D_
  font: 15px arial;_x000D_
  padding: 10px;_x000D_
  margin: 10px;_x000D_
  border: 1px solid #c00;_x000D_
  width: 200px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="target">This <code>div</code> is going to be fixed</div>
_x000D_
_x000D_
_x000D_

How to convert a structure to a byte array in C#?

        Header header = new Header();
        Byte[] headerBytes = new Byte[Marshal.SizeOf(header)];
        Marshal.Copy((IntPtr)(&header), headerBytes, 0, headerBytes.Length);

This should do the trick quickly, right?

Case insensitive comparison of strings in shell script

All of these answers ignore the easiest and quickest way to do this (as long as you have Bash 4):

if [ "${var1,,}" = "${var2,,}" ]; then
  echo ":)"
fi

All you're doing there is converting both strings to lowercase and comparing the results.

How to set default font family in React Native?

Add

"rnpm": {
  "assets": [
 "./assets/fonts/"
  ]
}

in package.json then run react-native link

How to read all of Inputstream in Server Socket JAVA

int c;
    String raw = "";
    do {
        c = inputstream.read();
        raw+=(char)c;
    } while(inputstream.available()>0);

InputStream.available() shows the available bytes only after one byte is read, hence do .. while

How long is the SHA256 hash?

A sha256 is 256 bits long -- as its name indicates.

Since sha256 returns a hexadecimal representation, 4 bits are enough to encode each character (instead of 8, like for ASCII), so 256 bits would represent 64 hex characters, therefore you need a varchar(64), or even a char(64), as the length is always the same, not varying at all.

And the demo :

$hash = hash('sha256', 'hello, world!');
var_dump($hash);

Will give you :

$ php temp.php
string(64) "68e656b251e67e8358bef8483ab0d51c6619f3e7a1a9f0e75838d41ff368f728"

i.e. a string with 64 characters.

Math functions in AngularJS bindings

Why not wrap the whole math obj in a filter?

var app = angular.module('fMathFilters',[]);


function math() {
    return function(input,arg) {
        if(input) {
            return Math[arg](input);
        }

        return 0;
    }
}

return app.filter('math',[math]);

and to use:

{{ number_var | math:'ceil'}}

Convert row to column header for Pandas DataFrame,

To rename the header without reassign df:

df.rename(columns=df.iloc[0], inplace = True)

To drop the row without reassign df:

df.drop(df.index[0], inplace = True)

bash: mkvirtualenv: command not found

In order to successfully install the virtualenvwrapper on Ubuntu 18.04.3 you need to do the following:

  1. Install virtualenv

    sudo apt install virtualenv
    
  2. Install virtualenvwrapper

    sudo pip install virtualenv
    sudo pip install virtualenvwrapper
    
  3. Add the following to the end of the .bashrc file

    export WORKON_HOME=~/virtualenvs
    export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python
    source ~/.local/bin/virtualenvwrapper.sh
    
  4. Execute the .bashrc file

    source ~/.bashrc
    
  5. Create your virtualenv

    mkvirtualenv your_virtualenv
    

window.print() not working in IE

I am not sure but i think it occurs because of the security rules of the InternetExplorer...

If you call a function like print() it asks the user manually if he wants to permit active scripting, if he clicks on the yellow bar and selects 'Yes', the print dialog appears. If you click 'No' or just don't do anything it is not executing the parts which are considered as active scripting or other security relevant javascript functions.

In your example the window is opened then print() is called, confirmation bar pops up (nothing is selected, in fact nothing can be selected due to the short time), newWin.close() is called, window closes.

You should try adding the page to the trusted sites in InternetExplorer or change security settings.

There may be a way of handling the security policies in the javascript itself but i don't know much about InternetExplorer Security Policies.

Hope this helps

Reading local text file into a JavaScript array

Using Node.js

sync mode:

var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")

async mode:

var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
    var textByLine = text.split("\n")
});

UPDATE

As of at least Node 6, readFileSync returns a Buffer, so it must first be converted to a string in order for split to work:

var text = fs.readFileSync("./mytext.txt").toString('utf-8');

Or

var text = fs.readFileSync("./mytext.txt", "utf-8");

Installing Python 3 on RHEL

Along with Python 2.7 and 3.3, Red Hat Software Collections now includes Python 3.4 - all work on both RHEL 6 and 7.

RHSCL 2.0 docs are at https://access.redhat.com/documentation/en-US/Red_Hat_Software_Collections/

Plus lot of articles at developerblog.redhat.com.

edit

Follow these instructions to install Python 3.4 on RHEL 6/7 or CentOS 6/7:

# 1. Install the Software Collections tools:
yum install scl-utils

# 2. Download a package with repository for your system.
#  (See the Yum Repositories on external link. For RHEL/CentOS 6:)
wget https://www.softwarecollections.org/en/scls/rhscl/rh-python34/epel-6-x86_64/download/rhscl-rh-python34-epel-6-x86_64.noarch.rpm
#  or for RHEL/CentOS 7
wget https://www.softwarecollections.org/en/scls/rhscl/rh-python34/epel-7-x86_64/download/rhscl-rh-python34-epel-7-x86_64.noarch.rpm

# 3. Install the repo package (on RHEL you will need to enable optional channel first):
yum install rhscl-rh-python34-*.noarch.rpm

# 4. Install the collection:
yum install rh-python34

# 5. Start using software collections:
scl enable rh-python34 bash

Declare and assign multiple string variables at the same time

string a = "", b = a , c = a, d = a, e = a, f =a;

How to create a Calendar table for 100 years in Sql

As this is only tagged sql (which does not indicate any specific DBMS), here is a solution for Postgres:

select d::date 
from generate_series(date '1990-01-01', date '1990-01-01' + interval '100' year, interval '1' day) as t(d);

If you need that a lot, it's more efficient to store that in an table (which can e.g. be indexed):

create table calendar 
as
select d::date as the_date
from generate_series(date '1990-01-01', date '1990-01-01' + interval '100' year, interval '1' day) as t(d);

Powershell send-mailmessage - email to multiple recipients

here is a full (gmail) and simple solution... just use normal ; delimiter.. best for passing in as params.

$to = "[email protected];[email protected]"
$user = "[email protected]"    
$pass = ConvertTo-SecureString -String "pass" -AsPlainText -Force

$cred = New-Object System.Management.Automation.PSCredential $user, $pass
$mailParam = @{
    To = $to.Split(';')
    From = "IT Alerts <[email protected]>"
    Subject = "test"
    Body = "test"
    SmtpServer = "smtp.gmail.com"
    Port = 587
    Credential = $cred
}

Send-MailMessage @mailParam -UseSsl

Algorithm to find Largest prime factor of a number

Actually there are several more efficient ways to find factors of big numbers (for smaller ones trial division works reasonably well).

One method which is very fast if the input number has two factors very close to its square root is known as Fermat factorisation. It makes use of the identity N = (a + b)(a - b) = a^2 - b^2 and is easy to understand and implement. Unfortunately it's not very fast in general.

The best known method for factoring numbers up to 100 digits long is the Quadratic sieve. As a bonus, part of the algorithm is easily done with parallel processing.

Yet another algorithm I've heard of is Pollard's Rho algorithm. It's not as efficient as the Quadratic Sieve in general but seems to be easier to implement.


Once you've decided on how to split a number into two factors, here is the fastest algorithm I can think of to find the largest prime factor of a number:

Create a priority queue which initially stores the number itself. Each iteration, you remove the highest number from the queue, and attempt to split it into two factors (not allowing 1 to be one of those factors, of course). If this step fails, the number is prime and you have your answer! Otherwise you add the two factors into the queue and repeat.

Persist javascript variables across pages?

You can persist values using HTML5 storage, Flash Storage, or Gears. The dojo storage library provides a nice wrapper for this.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysql.sock' (2)

Firstly, please confirm mysql-server is installed. I have the same error when mysql-server is installed but corrupted somehow. I do the trick by uninstall mysql completely and reinstall it.

sudo apt-get remove --purge mysql*
sudo apt-get autoremove
sudo apt-get autoclean
sudo apt-get install mysql-server mysql-client

Using only CSS, show div on hover over <a>

From my testing using this CSS:

.expandable{
display: none;
}
.expand:hover+.expandable{
display:inline !important;
}
.expandable:hover{
display:inline !important;
}

And this HTML:

<div class="expand">expand</div>
<div class="expand">expand</div>
<div class="expandable">expandable</div>

, it resulted that it does expand using the second , but does not expand using the first one. So if there is a div between the hover target and the hidden div, then it will not work.

Bootstrap DatePicker, how to set the start date for tomorrow?

If you are talking about Datepicker for bootstrap, you set the start date (the min date) by using the following:

$('#datepicker').datepicker('setStartDate', <DATETIME STRING HERE>);

Dump a list in a pickle file and retrieve it back later

Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.

So, first build a list, then use pickle.dump to send it to a file...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>> 
>>> import pickle
>>> 
>>> with open('parrot.pkl', 'wb') as f:
...   pickle.dump(mylist, f)
... 
>>> 

Then quit and come back later… and open with pickle.load...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
...   mynewlist = pickle.load(f)
... 
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>

Getting list of parameter names inside python function

import inspect

def func(a,b,c=5):
    pass

inspect.getargspec(func)  # inspect.signature(func) in Python 3

(['a', 'b', 'c'], None, None, (5,))

How do I get the computer name in .NET

Well there is one more way: Windows Management Instrumentation

using System.Management;

try
        {
            ManagementObjectSearcher searcher =
                new ManagementObjectSearcher("root\\CIMV2",
                "SELECT Name FROM Win32_ComputerSystem");

            foreach (ManagementObject queryObj in searcher.Get())
            {
                Console.WriteLine("-----------------------------------");
                Console.WriteLine("Win32_ComputerSystem instance");
                Console.WriteLine("-----------------------------------");
                Console.WriteLine("Name: {0}", queryObj["Name"]);
            }
        }
        catch (ManagementException e)
        {
            // exception handling
        }

MSDN

WMI

WMI Code creator

FAQs

Change priorityQueue to max priorityqueue

Using lamda, just multiple the result with -1 to get max priority queue.

PriorityQueue<> q = new PriorityQueue<Integer>(
                       (a,b) ->  -1 * Integer.compare(a, b)
                    );

form with no action and where enter does not reload page

Simply add this event to your text field. It will prevent a submission on pressing Enter, and you're free to add a submit button or call form.submit() as required:

onKeyPress="if (event.which == 13) return false;"

For example:

<input id="txt" type="text" onKeyPress="if (event.which == 13) return false;"></input>

print memory address of Python variable

id is the method you want to use: to convert it to hex:

hex(id(variable_here))

For instance:

x = 4
print hex(id(x))

Gave me:

0x9cf10c

Which is what you want, right?

(Fun fact, binding two variables to the same int may result in the same memory address being used.)
Try:

x = 4
y = 4
w = 9999
v = 9999
a = 12345678
b = 12345678
print hex(id(x))
print hex(id(y))
print hex(id(w))
print hex(id(v))
print hex(id(a))
print hex(id(b))

This gave me identical pairs, even for the large integers.

How to make a JTable non-editable

You can override the method isCellEditable and implement as you want for example:

//instance table model
DefaultTableModel tableModel = new DefaultTableModel() {

    @Override
    public boolean isCellEditable(int row, int column) {
       //all cells false
       return false;
    }
};

table.setModel(tableModel);

or

//instance table model
DefaultTableModel tableModel = new DefaultTableModel() {

   @Override
   public boolean isCellEditable(int row, int column) {
       //Only the third column
       return column == 3;
   }
};

table.setModel(tableModel);

Note for if your JTable disappears

If your JTable is disappearing when you use this it is most likely because you need to use the DefaultTableModel(Object[][] data, Object[] columnNames) constructor instead.

//instance table model
DefaultTableModel tableModel = new DefaultTableModel(data, columnNames) {

    @Override
    public boolean isCellEditable(int row, int column) {
       //all cells false
       return false;
    }
};

table.setModel(tableModel);

Has Facebook sharer.php changed to no longer accept detailed parameters?

Facebook no longer supports custom parameters in sharer.php

The sharer will no longer accept custom parameters and facebook will pull the information that is being displayed in the preview the same way that it would appear on facebook as a post from the url OG meta tags.

Use dialog/feeds instead of sharer.php

https://www.facebook.com/dialog/feed?
  app_id=145634995501895
  &display=popup&caption=An%20example%20caption 
  &link=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2Fdialogs%2F
  &redirect_uri=https://developers.facebook.com/tools/explorer

Official answer from fb team

How to convert array values to lowercase in PHP?

array_map() is the correct method. But, if you want to convert specific array values or all array values to lowercase one by one, you can use strtolower().

for($i=0; $i < count($array1); $i++) {
    $array1[$i] = strtolower($array1[$i]);
}

What to do with branch after merge

I prefer RENAME rather than DELETE

All my branches are named in the form of

  • Fix/fix-<somedescription> or
  • Ftr/ftr-<somedescription> or
  • etc.

Using Tower as my git front end, it neatly organizes all the Ftr/, Fix/, Test/ etc. into folders.
Once I am done with a branch, I rename them to Done/...-<description>.

That way they are still there (which can be handy to provide history) and I can always go back knowing what it was (feature, fix, test, etc.)

How do I enable the column selection mode in Eclipse?

  • Press Alt + Shift + A
  • Observe that the screen zooms out
  • Make selection using the mouse
  • Press Alt + Shift + A to go back to the old mode. enter image description here

How do I choose the URL for my Spring Boot webapp?

In Spring Boot 2 the property in e.g. application.properties is server.servlet.context-path=/myWebApp to set the context path.

https://docs.spring.io/spring-boot/docs/2.0.1.BUILD-SNAPSHOT/reference/htmlsingle/#_custom_context_path

Best way to change font colour halfway through paragraph?

You can also simply add the font tag inside the p tag.

CSS sheet:

<style type="text/css">
   p { font:15px Arial; color:white; }
</style>

and in HTML page:

<p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. 
    <font color="red"> 
          Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris     nisi ut aliquip ex ea commodo consequat. 
    </font>
Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p>

It works for me. But, in case you need modification, see w3schools for more usage :)

Loading local JSON file

_x000D_
_x000D_
json_str = String.raw`[{"name": "Jeeva"}, {"name": "Kumar"}]`;_x000D_
obj = JSON.parse(json_str);_x000D_
_x000D_
console.log(obj[0]["name"]);
_x000D_
_x000D_
_x000D_

I did this for my cordova app, like I created a new javascript file for the JSON and pasted the JSON data into String.raw then parse it with JSON.parse

Java: Reading integers from a file into an array

You might have confusions between the different line endings. A Windows file will end each line with a carriage return and a line feed. Some programs on Unix will read that file as if it had an extra blank line between each line, because it will see the carriage return as an end of line, and then see the line feed as another end of line.

Is it possible to convert char[] to char* in C?

If you have char[] c then you can do char* d = &c[0] and access element c[1] by doing *(d+1), etc.

JavaScript checking for null vs. undefined and difference between == and ===

How do I check a variable if it's null or undefined...

Is the variable null:

if (a === null)
// or
if (a == null) // but see note below

...but note the latter will also be true if a is undefined.

Is it undefined:

if (typeof a === "undefined")
// or
if (a === undefined)
// or
if (a == undefined) // but see note below

...but again, note that the last one is vague; it will also be true if a is null.

Now, despite the above, the usual way to check for those is to use the fact that they're falsey:

if (!a) {
    // `a` is falsey, which includes `undefined` and `null`
    // (and `""`, and `0`, and `NaN`, and [of course] `false`)
}

This is defined by ToBoolean in the spec.

...and what is the difference between the null and undefined?

They're both values usually used to indicate the absence of something. undefined is the more generic one, used as the default value of variables until they're assigned some other value, as the value of function arguments that weren't provided when the function was called, and as the value you get when you ask an object for a property it doesn't have. But it can also be explicitly used in all of those situations. (There's a difference between an object not having a property, and having the property with the value undefined; there's a difference between calling a function with the value undefined for an argument, and leaving that argument off entirely.)

null is slightly more specific than undefined: It's a blank object reference. JavaScript is loosely typed, of course, but not all of the things JavaScript interacts with are loosely typed. If an API like the DOM in browsers needs an object reference that's blank, we use null, not undefined. And similarly, the DOM's getElementById operation returns an object reference — either a valid one (if it found the DOM element), or null (if it didn't).

Interestingly (or not), they're their own types. Which is to say, null is the only value in the Null type, and undefined is the only value in the Undefined type.

What is the difference between "==" and "==="

The only difference between them is that == will do type coercion to try to get the values to match, and === won't. So for instance "1" == 1 is true, because "1" coerces to 1. But "1" === 1 is false, because the types don't match. ("1" !== 1 is true.) The first (real) step of === is "Are the types of the operands the same?" and if the answer is "no", the result is false. If the types are the same, it does exactly what == does.

Type coercion uses quite complex rules and can have surprising results (for instance, "" == 0 is true).

More in the spec:

How to Convert Excel Numeric Cell Value into Words

There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.

  1. press Alt+F11
  2. MENU: (Tool Strip) Insert Module
  3. copy and paste the below code


Option Explicit

Public Numbers As Variant, Tens As Variant

Sub SetNums()
    Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
    Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub

Function WordNum(MyNumber As Double) As String
    Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
    Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
    ' This macro was written by Chris Mead - www.MeadInKent.co.uk
    If Abs(MyNumber) > 999999999 Then
        WordNum = "Value too large"
        Exit Function
    End If
    SetNums
    ' String representation of amount (excl decimals)
    NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
    ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
    For n = 3 To 1 Step -1    'analyse the absolute number as 3 sets of 3 digits
        StrNo = Format(ValNo(n), "000")
        If ValNo(n) > 0 Then
            Temp1 = GetTens(Val(Right(StrNo, 2)))
            If Left(StrNo, 1) <> "0" Then
                Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
                If Temp1 <> "" Then Temp2 = Temp2 & " and "
            Else
                Temp2 = ""
            End If
            If n = 3 Then
                If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
                WordNum = Trim(Temp2 & Temp1)
            End If
            If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
            If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
        End If
    Next n
    NumStr = Trim(Str(Abs(MyNumber)))
    ' Values after the decimal place
    DecimalPosition = InStr(NumStr, ".")
    Numbers(0) = "Zero"
    If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
        Temp1 = " point"
        For n = DecimalPosition + 1 To Len(NumStr)
            Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
        Next n
        WordNum = WordNum & Temp1
    End If
    If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
        WordNum = "Zero" & WordNum
    End If
End Function

Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
    If TensNum <= 19 Then
        GetTens = Numbers(TensNum)
    Else
        Dim MyNo As String
        MyNo = Format(TensNum, "00")
        GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
    End If
End Function

After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)

It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.

Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)

you will see a Words equivalent of the numeric value.

This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel

JTable won't show column headers

The main difference between this answer and the accepted answer is the use of setViewportView() instead of add().

How to put JTable in JScrollPane using Eclipse IDE:

  1. Create JScrollPane container via Design tab.
  2. Stretch JScrollPane to desired size (applies to Absolute Layout).
  3. Drag and drop JTable component on top of JScrollPane (Viewport area).

In Structure > Components, table should be a child of scrollPane. enter image description here

The generated code would be something like this:

JScrollPane scrollPane = new JScrollPane();
...

JTable table = new JTable();
scrollPane.setViewportView(table);

Is there a way to 'pretty' print MongoDB shell output to a file?

Since you are doing this on a terminal and just want to inspect a record in a sane way, you can use a trick like this:

mongo | tee somefile

Use the session as normal - db.collection.find().pretty() or whatever you need to do, ignore the long output, and exit. A transcript of your session will be in the file tee wrote to.

Be mindful that the output might contain escape sequences and other garbage due to the mongo shell expecting an interactive session. less handles these gracefully.

Eclipse C++ : "Program "g++" not found in PATH"

I had a similar problem. The error is raised, but the code is compiled and linked. The error was caused by the Error Parser using a different configuration than the one that is compiled.

The error parser configuration was only valid for the Linux configuration of my software. My active configuration was set for MinGW and Windows.

Solution:

  • In Elipse under Windows->Preferences->C/C++->Indexer set Build Configuration for the indexer to Use active build configuration.
  • Clean and rebuild, otherwise the old errors will remain visible

XPath to select Element by attribute value

As a follow on, you could select "all nodes with a particular attribute" like this:

//*[@id='4']

c++ and opencv get and set pixel color to Mat

I would not use .at for performance reasons.

Define a struct:

//#pragma pack(push, 2) //not useful (see comments below)
struct RGB {
    uchar blue;
    uchar green;
    uchar red;  };

And then use it like this on your cv::Mat image:

RGB& rgb = image.ptr<RGB>(y)[x];

image.ptr(y) gives you a pointer to the scanline y. And iterate through the pixels with loops of x and y

Is there a Pattern Matching Utility like GREP in Windows?

An excellent and very fast file search utility, Agent Ransack, supports regular expression searching. It's primarily a GUI utility, but a command-line interface is also available.

single line comment in HTML

TL;DR For conforming browsers, yes; but there are no conforming browsers, so no.

According to the HTML 4 specification, <!------> hello--> is a perfectly valid comment. However, I've not found a browser which implements this correctly (i.e. per the specification) due to developers not knowing, nor following, the standards (as digitaldreamer pointed out).

You can find the definition of a comment for HTML4 on the w3c's website: http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.4

Another thing that many browsers get wrong is that -- > closes a comment just like -->.

How can I get city name from a latitude and longitude point?

There are many tools available

  1. google maps API as like all had written
  2. use this data "https://simplemaps.com/data/world-cities" download free version and convert excel to JSON with some online converter like "http://beautifytools.com/excel-to-json-converter.php"
  3. use IP address which is not good because using IP address of someone may not good users think that you can hack them.

other free and paid tools are available also

How to post object and List using postman

//backend.

@PostMapping("/")
public List<A> addList(@RequestBody A aObject){
//......ur code
}

class A{
int num;
String name;
List<B> bList;
//getters and setters and default constructor
}
class B{
int d;
//defalut Constructor & gettes&setters
}

// postman

{
"num":value,
"name":value,
"bList":[{
"key":"value",
"key":"value",.....
}]
}
  1. the error is for list there is no default constructor .so we can keep our list of object as a property of another class and pass the list of objects through the postman as the parameter of the another class.

Can't change z-index with JQuery

zIndex is part of javaScript notation.(camelCase)
but jQuery.css uses same as CSS syntax.
so it is z-index.

you forgot .css("attr","value"). use ' or " in both, attr and val. so, .css("z-index","3000");

How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT?

Easiest ways to get file name:

val fileName = File(uri.path).name
// or
val fileName = uri.pathSegments.last()

If they don't give you the right name you should use:

fun Uri.getName(context: Context): String {
    val returnCursor = context.contentResolver.query(this, null, null, null, null)
    val nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
    returnCursor.moveToFirst()
    val fileName = returnCursor.getString(nameIndex)
    returnCursor.close()
    return fileName
}

How should I unit test multithreaded code?

Concurrency is a complex interplay between the memory model, hardware, caches and our code. In the case of Java at least such tests have been partly addressed mainly by jcstress. The creators of that library are known to be authors of many JVM, GC and Java concurrency features.

But even this library needs good knowledge of the Java Memory Model specification so that we know exactly what we are testing. But I think the focus of this effort is mircobenchmarks. Not huge business applications.

Static constant string (class member)

You have to define your static member outside the class definition and provide the initializer there.

First

// In a header file (if it is in a header file in your case)
class A {   
private:      
  static const string RECTANGLE;
};

and then

// In one of the implementation files
const string A::RECTANGLE = "rectangle";

The syntax you were originally trying to use (initializer inside class definition) is only allowed with integral and enum types.


Starting from C++17 you have another option, which is quite similar to your original declaration: inline variables

// In a header file (if it is in a header file in your case)
class A {   
private:      
  inline static const string RECTANGLE = "rectangle";
};

No additional definition is needed.

Starting from C++20 instead of const you can declare it constexpr in this variant. Explicit inline would no longer be necessary, since constexpr implies inline.

How to write multiple conditions of if-statement in Robot Framework

You should use small caps "or" and "and" instead of OR and AND.

And beware also the spaces/tabs between keywords and arguments (you need at least two spaces).

Here is a code sample with your three keywords working fine:

Here is the file ts.txt:

  *** test cases ***
  mytest
    ${color} =  set variable  Red
    Run Keyword If  '${color}' == 'Red'  log to console  \nexecuted with single condition
    Run Keyword If  '${color}' == 'Red' or '${color}' == 'Blue' or '${color}' == 'Pink'  log to console  \nexecuted with multiple or

    ${color} =  set variable  Blue
    ${Size} =  set variable  Small
    ${Simple} =  set variable  Simple
    ${Design} =  set variable  Simple
    Run Keyword If  '${color}' == 'Blue' and '${Size}' == 'Small' and '${Design}' != '${Simple}'  log to console  \nexecuted with multiple and

    ${Size} =  set variable  XL
    ${Design} =  set variable  Complicated
    Run Keyword Unless  '${color}' == 'Black' or '${Size}' == 'Small' or '${Design}' == 'Simple'  log to console  \nexecuted with unless and multiple or

and here is what I get when I execute it:

$ pybot ts.txt
==============================================================================
Ts
==============================================================================
mytest                                                                .
executed with single condition
executed with multiple or
executed with unless and multiple or
mytest                                                                | PASS |
------------------------------------------------------------------------------

How to set the font style to bold, italic and underlined in an Android TextView?

    style="?android:attr/listSeparatorTextViewStyle
  • by making this style, u can achieve underlining

How do I turn off Oracle password expiration?

To alter the password expiry policy for a certain user profile in Oracle first check which profile the user is using:

select profile from DBA_USERS where username = '<username>';

Then you can change the limit to never expire using:

alter profile <profile_name> limit password_life_time UNLIMITED;

If you want to previously check the limit you may use:

select resource_name,limit from dba_profiles where profile='<profile_name>';

How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

This other solution for covert datetime to unixtimestampmillis.

private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

    public static long GetCurrentUnixTimestampMillis()
    {
        DateTime localDateTime, univDateTime;
        localDateTime = DateTime.Now;          
        univDateTime = localDateTime.ToUniversalTime();
        return (long)(univDateTime - UnixEpoch).TotalMilliseconds;
    } 

What does "restore purchases" in In-App purchases mean?

Is it as optional functionality.

If you won't provide it when user will try to purchase non-consumable product AppStore will restore old transaction. But your app will think that this is new transaction.

If you will provide restore mechanism then your purchase manager will see restored transaction.

If app should distinguish this options then you should provide functionality for restoring previously purchased products.

How to give a Blob uploaded as FormData a file name?

For Chrome, Safari and Firefox, just use this:

form.append("blob", blob, filename);

(see MDN documentation)

How do I fix a "Expected Primary-expression before ')' token" error?

showInventory(player); is passing a type as parameter. That's illegal, you need to pass an object.

For example, something like:

player p;
showInventory(p);  

I'm guessing you have something like this:

int main()
{
   player player;
   toDo();
}

which is awful. First, don't name the object the same as your type. Second, in order for the object to be visible inside the function, you'll need to pass it as parameter:

int main()
{
   player p;
   toDo(p);
}

and

std::string toDo(player& p) 
{
    //....
    showInventory(p);
    //....
}

:touch CSS pseudo-class or something similar?

Since mobile doesn't give hover feedback, I want, as a user, to see instant feedback when a link is tapped. I noticed that -webkit-tap-highlight-color is the fastest to respond (subjective).

Add the following to your body and your links will have a tap effect.

body {
    -webkit-tap-highlight-color: #ccc;
}