Programs & Examples On #Affiliate

Removing space from dataframe columns in pandas

  • To remove white spaces:

1) To remove white space everywhere:

df.columns = df.columns.str.replace(' ', '')

2) To remove white space at the beginning of string:

df.columns = df.columns.str.lstrip()

3) To remove white space at the end of string:

df.columns = df.columns.str.rstrip()

4) To remove white space at both ends:

df.columns = df.columns.str.strip()
  • To replace white spaces with other characters (underscore for instance):

5) To replace white space everywhere

df.columns = df.columns.str.replace(' ', '_')

6) To replace white space at the beginning:

df.columns = df.columns.str.replace('^ +', '_')

7) To replace white space at the end:

df.columns = df.columns.str.replace(' +$', '_')

8) To replace white space at both ends:

df.columns = df.columns.str.replace('^ +| +$', '_')

All above applies to a specific column as well, assume you have a column named col, then just do:

df[col] = df[col].str.strip()  # or .replace as above

How to change Oracle default data pump directory to import dumpfile?

You can use the following command to update the DATA PUMP DIRECTORY path,

create or replace directory DATA_PUMP_DIR as '/u01/app/oracle/admin/MYDB/dpdump/';

For me data path correction was required as I have restored the my database from production to test environment.

Same command can be used to create a new DATA PUMP DIRECTORY name and path.

MySQL CONCAT returns NULL if any field contain NULL

you can use if statement like below

select CONCAT(if(affiliate_name is null ,'',affiliate_name),'- ',if(model is null ,'',affiliate_name)) as model from devices

Strange Characters in database text: Ã, Ã, ¢, â‚ €,

This is surely an encoding problem. You have a different encoding in your database and in your website and this fact is the cause of the problem. Also if you ran that command you have to change the records that are already in your tables to convert those character in UTF-8.

Update: Based on your last comment, the core of the problem is that you have a database and a data source (the CSV file) which use different encoding. Hence you can convert your database in UTF-8 or, at least, when you get the data that are in the CSV, you have to convert them from UTF-8 to latin1.

You can do the convertion following this articles:

Drop-down menu that opens up/upward with pure css

If we are use chosen dropdown list, then we can use below css(No JS/JQuery require)

<select chosen="{width: '100%'}" ng- 
   model="modelName" class="form-control input- 
   sm"
   ng- 
   options="persons.persons as 
   persons.persons for persons in 
   jsonData"
   ng- 
   change="anyFunction(anyParam)" 
   required>
   <option value=""> </option>
</select>
<style>   
.chosen-container .chosen-drop {
    border-bottom: 0;
    border-top: 1px solid #aaa;
    top: auto;
    bottom: 40px;
}

.chosen-container.chosen-with-drop .chosen-single {
    border-top-left-radius: 0px;
    border-top-right-radius: 0px;

    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 5px;

    background-image: none;
}

.chosen-container.chosen-with-drop .chosen-drop {
    border-bottom-left-radius: 0px;
    border-bottom-right-radius: 0px;

    border-top-left-radius: 5px;
    border-top-right-radius: 5px;

    box-shadow: none;

    margin-bottom: -16px;
}
</style>

Setting the MySQL root user password on OS X

I solved this by:

  1. Shutting down my MySQL server: mysql.server stop
  2. Running MySQL in safe mode: mysqld_safe --skip-grant-tables
  3. In another terminal, login with mysql -u root
  4. In the same terminal, run UPDATE mysql.user SET authentication_string=null WHERE User='root';, then FLUSH PRIVILEGES; and then exit with exit;
  5. Stop the safe mode server with mysql.server stop and then start the normal one; mysql.server start

Now you can set your new password with

ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'yourpasswd';

top align in html table?

<TABLE COLS="3" border="0" cellspacing="0" cellpadding="0">
    <TR style="vertical-align:top">
        <TD>
            <!-- The log text-box -->
            <div style="height:800px; width:240px; border:1px solid #ccc; font:16px/26px Georgia, Garamond, Serif; overflow:auto;">
                Log:
            </div>
        </TD>
        <TD>
            <!-- The 2nd column -->
        </TD>
        <TD>
            <!-- The 3rd column -->
        </TD>
    </TR>
</TABLE>

How to store file name in database, with other info while uploading image to server using PHP?

<form method="post" action="addMember.php" enctype="multipart/form-data">
    <p>
              Please Enter the Band Members Name.
            </p>
            <p>
              Band Member or Affiliates Name:
            </p>
            <input type="text" name="nameMember"/>
            <p>
              Please Enter the Band Members Position. Example:Drums.
            </p>
            <p>
              Band Position:
            </p>
            <input type="text" name="bandMember"/>
            <p>
              Please Upload a Photo of the Member in gif or jpeg format. The file name should be named after the Members name. If the same file name is uploaded twice it will be overwritten! Maxium size of File is 35kb.
            </p>
            <p>
              Photo:
            </p>
            <input type="hidden" name="size" value="350000">
            <input type="file" name="photo"> 
            <p>
              Please Enter any other information about the band member here.
            </p>
            <p>
              Other Member Information:
            </p>
<textarea rows="10" cols="35" name="aboutMember">
</textarea>
            <p>
              Please Enter any other Bands the Member has been in.
            </p>
            <p>
              Other Bands:
            </p>
            <input type="text" name="otherBands" size=30 />
            <br/>
            <br/>
            <input TYPE="submit" name="upload" title="Add data to the Database" value="Add Member"/>
          </form>

save it as addMember.php

<?php

//This is the directory where images will be saved
$target = "your directory";
$target = $target . basename( $_FILES['photo']['name']);

//This gets all the other information from the form
$name=$_POST['nameMember'];
$bandMember=$_POST['bandMember'];
$pic=($_FILES['photo']['name']);
$about=$_POST['aboutMember'];
$bands=$_POST['otherBands'];


// Connects to your Database
mysql_connect("yourhost", "username", "password") or die(mysql_error()) ;
mysql_select_db("dbName") or die(mysql_error()) ;

//Writes the information to the database
mysql_query("INSERT INTO tableName (nameMember,bandMember,photo,aboutMember,otherBands)
VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ;

//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{

//Tells you if its all ok
echo "The file ". basename( $_FILES['photo']['name']). " has been uploaded, and your information has been added to the directory";
}
else {

//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>

in the above code one little bug ,i fixed that bug.

How do I "Add Existing Item" an entire directory structure in Visual Studio?

The cleanest way that I've found to do this is to create a new Class Library project in the target folder, and redirect all of its build output elsewhere. It still leaves a .csproj file sitting in that folder, but it does let you see it in Visual Studio and pick which files to include in your project.

How to list records with date from the last 10 days?

My understanding from my testing (and the PostgreSQL dox) is that the quotes need to be done differently from the other answers, and should also include "day" like this:

SELECT Table.date
  FROM Table 
  WHERE date > current_date - interval '10 day';

Demonstrated here (you should be able to run this on any Postgres db):

SELECT DISTINCT current_date, 
                current_date - interval '10' day, 
                current_date - interval '10 days' 
  FROM pg_language;

Result:

2013-03-01  2013-03-01 00:00:00 2013-02-19 00:00:00

Count Vowels in String Python

Another solution with list comprehension:

vowels = ["a", "e", "i", "o", "u"]

def vowel_counter(str):
  return len([char for char in str if char in vowels])

print(vowel_counter("abracadabra"))
# 5

CodeIgniter: "Unable to load the requested class"

I had a similar issue when deploying from OSx on my local to my Linux live site.

It ran fine on OSx, but on Linux I was getting:

An Error Was Encountered

Unable to load the requested class: Ckeditor

The problem was that Linux paths are apparently case-sensitive so I had to rename my library files from "ckeditor.php" to "CKEditor.php".

I also changed my load call to match the capitalization:

$this->load->library('CKEditor');

passing 2 $index values within nested ng-repeat

Just use ng-repeat="(sectionIndex, section) in sections"

and that will be useable on the next level ng-repeat down.

<ul ng-repeat="(sectionIndex, section) in sections">
    <li  class="section_title {{section.active}}" >
        {{section.name}}
    </li>
    <ul>
        <li ng-repeat="tutorial in section.tutorials">
            {{tutorial.name}}, Your section index is {{sectionIndex}}
        </li>
    </ul>
</ul>

How do I check to see if a value is an integer in MySQL?

The best i could think of a variable is a int Is a combination with MySQL's functions CAST() and LENGTH().
This method will work on strings, integers, doubles/floats datatypes.

SELECT (LENGTH(CAST(<data> AS UNSIGNED))) = (LENGTH(<data>)) AS is_int

see demo http://sqlfiddle.com/#!9/ff40cd/44

it will fail if the column has a single character value. if column has a value 'A' then Cast('A' as UNSIGNED) will evaluate to 0 and LENGTH(0) will be 1. so LENGTH(Cast('A' as UNSIGNED))=LENGTH(0) will evaluate to 1=1 => 1

True Waqas Malik totally fogotten to test that case. the patch is.

SELECT <data>, (LENGTH(CAST(<data> AS UNSIGNED))) = CASE WHEN CAST(<data> AS UNSIGNED) = 0 THEN CAST(<data> AS UNSIGNED) ELSE (LENGTH(<data>)) END AS is_int;

Results

**Query #1**

    SELECT 1, (LENGTH(CAST(1 AS UNSIGNED))) = CASE WHEN CAST(1 AS UNSIGNED) = 0 THEN CAST(1 AS UNSIGNED) ELSE (LENGTH(1)) END AS is_int;

| 1   | is_int |
| --- | ------ |
| 1   | 1      |

---
**Query #2**

    SELECT 1.1, (LENGTH(CAST(1 AS UNSIGNED))) = CASE WHEN CAST(1.1 AS UNSIGNED) = 0 THEN CAST(1.1 AS UNSIGNED) ELSE (LENGTH(1.1)) END AS is_int;

| 1.1 | is_int |
| --- | ------ |
| 1.1 | 0      |

---
**Query #3**

    SELECT "1", (LENGTH(CAST("1" AS UNSIGNED))) = CASE WHEN CAST("1" AS UNSIGNED) = 0 THEN CAST("1" AS UNSIGNED) ELSE (LENGTH("1")) END AS is_int;

| 1   | is_int |
| --- | ------ |
| 1   | 1      |

---
**Query #4**

    SELECT "1.1", (LENGTH(CAST("1.1" AS UNSIGNED))) = CASE WHEN CAST("1.1" AS UNSIGNED) = 0 THEN CAST("1.1" AS UNSIGNED) ELSE (LENGTH("1.1")) END AS is_int;

| 1.1 | is_int |
| --- | ------ |
| 1.1 | 0      |

---
**Query #5**

    SELECT "1a", (LENGTH(CAST("1.1" AS UNSIGNED))) = CASE WHEN CAST("1a" AS UNSIGNED) = 0 THEN CAST("1a" AS UNSIGNED) ELSE (LENGTH("1a")) END AS is_int;

| 1a  | is_int |
| --- | ------ |
| 1a  | 0      |

---
**Query #6**

    SELECT "1.1a", (LENGTH(CAST("1.1a" AS UNSIGNED))) = CASE WHEN CAST("1.1a" AS UNSIGNED) = 0 THEN CAST("1.1a" AS UNSIGNED) ELSE (LENGTH("1.1a")) END AS is_int;

| 1.1a | is_int |
| ---- | ------ |
| 1.1a | 0      |

---
**Query #7**

    SELECT "a1", (LENGTH(CAST("1.1a" AS UNSIGNED))) = CASE WHEN CAST("a1" AS UNSIGNED) = 0 THEN CAST("a1" AS UNSIGNED) ELSE (LENGTH("a1")) END AS is_int;

| a1  | is_int |
| --- | ------ |
| a1  | 0      |

---
**Query #8**

    SELECT "a1.1", (LENGTH(CAST("a1.1" AS UNSIGNED))) = CASE WHEN CAST("a1.1" AS UNSIGNED) = 0 THEN CAST("a1.1" AS UNSIGNED) ELSE (LENGTH("a1.1")) END AS is_int;

| a1.1 | is_int |
| ---- | ------ |
| a1.1 | 0      |

---
**Query #9**

    SELECT "a", (LENGTH(CAST("a" AS UNSIGNED))) = CASE WHEN CAST("a" AS UNSIGNED) = 0 THEN CAST("a" AS UNSIGNED) ELSE (LENGTH("a")) END AS is_int;

| a   | is_int |
| --- | ------ |
| a   | 0      |

see demo

Difference between using "chmod a+x" and "chmod 755"

Indeed there is.

chmod a+x is relative to the current state and just sets the x flag. So a 640 file becomes 751 (or 750?), a 644 file becomes 755.

chmod 755, however, sets the mask as written: rwxr-xr-x, no matter how it was before. It is equivalent to chmod u=rwx,go=rx.

Check if a string is a valid date using DateTime.TryParse

Basically, I want to check if a particular string contains AT LEAST day(1 through 31 or 01 through 31),month(1 through 12 or 01 through 12) and year(yyyy or yy) in any order, with any date separator , what will be the solution? So, if the value includes any parts of time, it should return true too. I could NOT be able to define a array of format.

When I was in a similar situation, here is what I did:

  1. Gather all the formats my system is expected to support.
  2. Looked at what is common or can be generalize.
  3. Learned to create REGEX (It is an investment of time initially but pays off once you create one or two on your own). Also do not try to build REGEX for all formats in one go, follow incremental process.
  4. I created REGEX to cover as many format as possible.
  5. For few cases, not to make REGEX extra complex, I covered it through DateTime.Parse() method.
  6. With the combination of both Parse as well as REGEX i was able to validate the input is correct/as expected.

This http://www.codeproject.com/Articles/13255/Validation-with-Regular-Expressions-Made-Simple was really helpful both for understanding as well as validation the syntax for each format.

My 2 cents if it helps....

Crontab Day of the Week syntax

You can also use day names like Mon for Monday, Tue for Tuesday, etc. It's more human friendly.

npm ERR cb() never called

Turns out I was out of space! Deleting files on the drive allowed for normal startup and running.

Updating Anaconda fails: Environment Not Writable Error

Deleting file .condarc (eg./root/.condarc) in the user's home directory before installation, resolved the issue.

Loading existing .html file with android WebView

ok, that was my very stupid mistake. I post the answer here just in case someone has the same problem.

The correct path for files stored in assets folder is file:///android_asset/* (with no "s" for assets folder which i was always thinking it must have a "s").

And, mWebView.loadUrl("file:///android_asset/myfile.html"); works under all API levels.

I still not figure out why mWebView.loadUrl("file:///android_res/raw/myfile.html"); works only on API level 8. But it doesn't matter now.

Move SQL Server 2008 database files to a new folder location

You can use Detach/Attach Option in SQL Server Management Studio.

Check this: Move a Database Using Detach and Attach

How to store an output of shell script to a variable in Unix?

You should probably re-write the script to return a value rather than output it. Instead of:

a=$( script.sh ) # Now a is a string, either "success" or "Failed"
case "$a" in
   success) echo script succeeded;;
   Failed) echo script failed;;
esac

you would be able to do:

if script.sh > /dev/null; then
    echo script succeeded
else
    echo script failed
fi

It is much simpler for other programs to work with you script if they do not have to parse the output. This is a simple change to make. Just exit 0 instead of printing success, and exit 1 instead of printing Failed. Of course, you can also print those values as well as exiting with a reasonable return value, so that wrapper scripts have flexibility in how they work with the script.

Difference between String replace() and replaceAll()

Q: What's the difference between the java.lang.String methods replace() and replaceAll(), other than that the latter uses regex.

A: Just the regex. They both replace all :)

http://docs.oracle.com/javase/8/docs/api/java/lang/String.html

PS:

There's also a replaceFirst() (which takes a regex)

Call method when home button pressed

The Home button is a very dangerous button to override and, because of that, Android will not let you override its behavior the same way you do the BACK button.

Take a look at this discussion.

You will notice that the home button seems to be implemented as a intent invocation, so you'll end up having to add an intent category to your activity. Then, any time the user hits home, your app will show up as an option. You should consider what it is you are looking to accomplish with the home button. If its not to replace the default home screen of the device, I would be wary of overloading the HOME button, but it is possible (per discussion in above thread.)

How can I view a git log of just one user's commits?

My case: I'm using source tree, I followed the following steps:

  1. Pressed CRL+3
  2. Changed dropdown authors
  3. Typed the name "Vinod Kumar"

enter image description here

echo that outputs to stderr

Don't use cat as some have mentioned here. cat is a program while echo and printf are bash (shell) builtins. Launching a program or another script (also mentioned above) means to create a new process with all its costs. Using builtins, writing functions is quite cheap, because there is no need to create (execute) a process (-environment).

The opener asks "is there any standard tool to output (pipe) to stderr", the short answer is : NO ... why? ... redirecting pipes is an elementary concept in systems like unix (Linux...) and bash (sh) builds up on these concepts.

I agree with the opener that redirecting with notations like this: &2>1 is not very pleasant for modern programmers, but that's bash. Bash was not intended to write huge and robust programs, it is intended to help the admins to get there work with less keypresses ;-)

And at least, you can place the redirection anywhere in the line:

$ echo This message >&2 goes to stderr 
This message goes to stderr

Javascript - How to detect if document has loaded (IE 7/Firefox 3)

if(document.readyState === 'complete') {
    DoStuffFunction();
} else {
    if (window.addEventListener) {  
        window.addEventListener('load', DoStuffFunction, false);
    } else {
        window.attachEvent('onload', DoStuffFunction);
    }
}

Update ViewPager dynamically?

After hours of frustration while trying all the above solutions to overcome this problem and also trying many solutions on other similar questions like this, this and this which all FAILED with me to solve this problem and to make the ViewPager to destroy the old Fragment and fill the pager with the new Fragments. I have solved the problem as following:

1) Make the ViewPager class to extends FragmentPagerAdapter as following:

 public class myPagerAdapter extends FragmentPagerAdapter {

2) Create an Item for the ViewPager that store the title and the fragment as following:

public class PagerItem {
private String mTitle;
private Fragment mFragment;


public PagerItem(String mTitle, Fragment mFragment) {
    this.mTitle = mTitle;
    this.mFragment = mFragment;
}
public String getTitle() {
    return mTitle;
}
public Fragment getFragment() {
    return mFragment;
}
public void setTitle(String mTitle) {
    this.mTitle = mTitle;
}

public void setFragment(Fragment mFragment) {
    this.mFragment = mFragment;
}

}

3) Make the constructor of the ViewPager take my FragmentManager instance to store it in my class as following:

private FragmentManager mFragmentManager;
private ArrayList<PagerItem> mPagerItems;

public MyPagerAdapter(FragmentManager fragmentManager, ArrayList<PagerItem> pagerItems) {
    super(fragmentManager);
    mFragmentManager = fragmentManager;
    mPagerItems = pagerItems;
}

4) Create a method to re-set the adapter data with the new data by deleting all the previous fragment from the fragmentManager itself directly to make the adapter to set the new fragment from the new list again as following:

public void setPagerItems(ArrayList<PagerItem> pagerItems) {
    if (mPagerItems != null)
        for (int i = 0; i < mPagerItems.size(); i++) {
            mFragmentManager.beginTransaction().remove(mPagerItems.get(i).getFragment()).commit();
        }
    mPagerItems = pagerItems;
}

5) From the container Activity or Fragment do not re-initialize the adapter with the new data. Set the new data through the method setPagerItems with the new data as following:

ArrayList<PagerItem> pagerItems = new ArrayList<PagerItem>();
    pagerItems.add(new PagerItem("Fragment1", new MyFragment1()));
    pagerItems.add(new PagerItem("Fragment2", new MyFragment2()));

    mPagerAdapter.setPagerItems(pagerItems);
    mPagerAdapter.notifyDataSetChanged();

I hope it helps.

difference between width auto and width 100 percent

  • width: auto; will try as hard as possible to keep an element the same width as its parent container when additional space is added from margins, padding, or borders.

  • width: 100%; will make the element as wide as the parent container. Extra spacing will be added to the element's size without regards to the parent. This typically causes problems.

enter image description here enter image description here

Connect to mysql in a docker container from the host

For conversion,you can create ~/.my.cnf file in host:

[Mysql]
user=root
password=yourpass
host=127.0.0.1
port=3306

Then next time just run mysql for mysql client to open connection.

How do you use a variable in a regular expression?

Instead of using the /regex/g syntax, you can construct a new RegExp object:

var replace = "regex";
var re = new RegExp(replace,"g");

You can dynamically create regex objects this way. Then you will do:

"mystring".replace(re, "newstring");

If statement within Where clause

CASE might help you out:

SELECT t.first_name,
       t.last_name,
       t.employid,
       t.status
  FROM employeetable t
 WHERE t.status = (CASE WHEN status_flag = STATUS_ACTIVE THEN 'A'
                        WHEN status_flag = STATUS_INACTIVE THEN 'T'
                        ELSE null END)
   AND t.business_unit = (CASE WHEN source_flag = SOURCE_FUNCTION THEN 'production'
                               WHEN source_flag = SOURCE_USER THEN 'users'
                               ELSE null END)
   AND t.first_name LIKE firstname
   AND t.last_name LIKE lastname
   AND t.employid LIKE employeeid;

The CASE statement evaluates multiple conditions to produce a single value. So, in the first usage, I check the value of status_flag, returning 'A', 'T' or null depending on what it's value is, and compare that to t.status. I do the same for the business_unit column with a second CASE statement.

How to loop over a Class attributes in Java?

Accessing the fields directly is not really good style in java. I would suggest creating getter and setter methods for the fields of your bean and then using then Introspector and BeanInfo classes from the java.beans package.

MyBean bean = new MyBean();
BeanInfo beanInfo = Introspector.getBeanInfo(MyBean.class);
for (PropertyDescriptor propertyDesc : beanInfo.getPropertyDescriptors()) {
    String propertyName = propertyDesc.getName();
    Object value = propertyDesc.getReadMethod().invoke(bean);
}

Target elements with multiple classes, within one rule

Just in case someone stumbles upon this like I did and doesn't realise, the two variations above are for different use cases.

The following:

.blue-border, .background {
    border: 1px solid #00f;
    background: #fff;
}

is for when you want to add styles to elements that have either the blue-border or background class, for example:

<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>

would all get a blue border and white background applied to them.

However, the accepted answer is different.

.blue-border.background {
    border: 1px solid #00f;
    background: #fff;
}

This applies the styles to elements that have both classes so in this example only the <div> with both classes should get the styles applied (in browsers that interpret the CSS properly):

<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>

So basically think of it like this, comma separating applies to elements with one class OR another class and dot separating applies to elements with one class AND another class.

How do I verify/check/test/validate my SSH passphrase?

Extending @RobBednark's solution to a specific Windows + PuTTY scenario, you can do so:

  1. Generate SSH key pair with PuTTYgen (following Manually generating your SSH key in Windows), saving it to a PPK file;

  2. With the context menu in Windows Explorer, choose Edit with PuTTYgen. It will prompt for a password.

If you type the wrong password, it will just prompt again.

Note, if you like to type, use the following command on a folder that contains the PPK file: puttygen private-key.ppk -y.

Git pushing to remote branch

First, let's note that git push "wants" two more arguments and will make them up automatically if you don't supply them. The basic command is therefore git push remote refspec.

The remote part is usually trivial as it's almost always just the word origin. The trickier part is the refspec. Most commonly, people write a branch name here: git push origin master, for instance. This uses your local branch to push to a branch of the same name1 on the remote, creating it if necessary. But it doesn't have to be just a branch name.

In particular, a refspec has two colon-separated parts. For git push, the part on the left identifies what to push,2 and the part on the right identifies the name to give to the remote. The part on the left in this case would be branch_name and the part on the right would be branch_name_test. For instance:

git push origin foo:foo_test

As you are doing the push, you can tell your git push to set your branch's upstream name at the same time, by adding -u to the git push options. Setting the upstream name makes your git save the foo_test (or whatever) name, so that a future git push with no arguments, while you're on the foo branch, can try to push to foo_test on the remote (git also saves the remote, origin in this case, so that you don't have to enter that either).

You need only pass -u once: it basically just runs git branch --set-upstream-to for you. (If you pass -u again later, it re-runs the upstream-setting, changing it as directed; or you can run git branch --set-upstream-to yourself.)

However, if your git is 2.0 or newer, and you have not set any special configuration, you will run into the same kind of thing that had me enter footnote 1 above: push.default will be set to simple, which will refuse to push because the upstream's name differs from your own local name. If you set push.default to upstream, git will stop complaining—but the simplest solution is just to rename your local branch first, so that the local and remote names match. (What settings to set, and/or whether to rename your branch, are up to you.)


1More precisely, git consults your remote.remote.push setting to derive the upstream half of the refspec. If you haven't set anything here, the default is to use the same name.

2This doesn't have to be a branch name. For instance, you can supply HEAD, or a commit hash, here. If you use something other than a branch name, you may have to spell out the full refs/heads/branch on the right, though (it depends on what names are already on the remote).

What is a lambda (function)?

It refers to lambda calculus, which is a formal system that just has lambda expressions, which represent a function that takes a function for its sole argument and returns a function. All functions in the lambda calculus are of that type, i.e., ? : ? ? ?.

Lisp used the lambda concept to name its anonymous function literals. This lambda represents a function that takes two arguments, x and y, and returns their product:

(lambda (x y) (* x y)) 

It can be applied in-line like this (evaluates to 50):

((lambda (x y) (* x y)) 5 10)

Using CSS to align a button bottom of the screen using relative positions

This will work for any resolution,

button{
    position:absolute;
    bottom: 5%;
    right:20%;
}

http://jsfiddle.net/BUuSr/

What is a .NET developer?

Generally what's meant by that is a fairly intimate familiarity with one (or probably more) of the .NET languages (C#, VB.NET, etc.) and one (or less probably more) of the .NET stacks (WinForms, ASP.NET, WPF, etc.).

As for a specific "formal definition", I don't think you'll find one beyond that. The job description should be specific about what they're looking for. I wouldn't consider a job listing that asks for a ".NET developer" and provides no more detail than that to be sufficiently descriptive.

If strings starts with in PowerShell

$Group is an object, but you will actually need to check if $Group.samaccountname.StartsWith("string").

Change $Group.StartsWith("S_G_") to $Group.samaccountname.StartsWith("S_G_").

Android Button Onclick

It would be helpful to know what code you are trying to execute when the button is pressed. You've got the onClick property set in your xml file to a method called setLogin. For clarity, I'd delete this line android:onClick="setLogin" and call the method directly from inside your onClick() method.

Also you can't just set the display to a new XML, you need to start a new activity with an Intent, a method something like this would be appropriate

 private void setLogin() {

 Intent i = new Intent(currentActivity.this, newActivity.class);
 startActivty(i);

 }

Then set the new Activity to have the new layout.

jquery append div inside div with id and manipulate

You're overcomplicating things:

var e = $('<div style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
e.attr('id', 'myid');
$('#box').append(e);

For example: http://jsfiddle.net/ambiguous/Dm5J2/

Find by key deep in a nested array

If you're already using Underscore, use _.find()

_.find(yourList, function (item) {
    return item.id === 1;
});

What happens when a duplicate key is put into a HashMap?

Yes, this means all the 1 keys with value are overwriten with the last added value and here you add "surely not one" so it will display only "surely not one".

Even if you are trying to display with a loop, it will also only display one key and value which have same key.

Ansible: How to delete files and folders inside a directory?

While Ansible is still debating to implement state = empty https://github.com/ansible/ansible-modules-core/issues/902

my_folder: "/home/mydata/web/"
empty_path: "/tmp/empty"


- name: "Create empty folder for wiping."
  file:
    path: "{{ empty_path }}" 
    state: directory

- name: "Wipe clean {{ my_folder }} with empty folder hack."
  synchronize:
    mode: push

    #note the backslash here
    src: "{{ empty_path }}/" 

    dest: "{{ nl_code_path }}"
    recursive: yes
    delete: yes
  delegate_to: "{{ inventory_hostname }}"

Note though, with synchronize you should be able to sync your files (with delete) properly anyway.

Getting Index of an item in an arraylist;

Rather than a brute force loop through the list (eg 1 to 10000), rather use an iterative search approach : The List needs to be sorted by the element to be tested.

Start search at the middle element size()/2 eg 5000 if search item greater than element at 5000, then test the element at the midpoint between the upper(10000) and midpoint(5000) - 7500

keep doing this until you reach the match (or use a brute force loop through once you get down to a smaller range (eg 20 items)

You can search a list of 10000 in around 13 to 14 tests, rather than potentially 9999 tests.

return string with first match Regex

You can do:

x = re.findall('\d+', text)
result = x[0] if len(x) > 0 else ''

Note that your question isn't exactly related to regex. Rather, how do you safely find an element from an array, if it has none.

How can I change my Cygwin home folder after installation?

Cygwin mount now support bind method which lets you mount a directory. Hence you can simply add the following line to /etc/fstab, then restart your shell:

c:/Users /home none bind 0 0

Sleep for milliseconds

Why don't use time.h library? Runs on Windows and POSIX systems:

#include <iostream>
#include <time.h>

using namespace std;

void sleepcp(int milliseconds);

void sleepcp(int milliseconds) // Cross-platform sleep function
{
    clock_t time_end;
    time_end = clock() + milliseconds * CLOCKS_PER_SEC/1000;
    while (clock() < time_end)
    {
    }
}
int main()
{
    cout << "Hi! At the count to 3, I'll die! :)" << endl;
    sleepcp(3000);
    cout << "urrrrggghhhh!" << endl;
}

Corrected code - now CPU stays in IDLE state [2014.05.24]:

#include <iostream>
#ifdef _WIN32
    #include <windows.h>
#else
    #include <unistd.h>
#endif // _WIN32

using namespace std;

void sleepcp(int milliseconds);

void sleepcp(int milliseconds) // Cross-platform sleep function
{
    #ifdef _WIN32
        Sleep(milliseconds);
    #else
        usleep(milliseconds * 1000);
    #endif // _WIN32
}
int main()
{
    cout << "Hi! At the count to 3, I'll die! :)" << endl;
    sleepcp(3000);
    cout << "urrrrggghhhh!" << endl;
}

Does static constexpr variable inside a function make sense?

The short answer is that not only is static useful, it is pretty well always going to be desired.

First, note that static and constexpr are completely independent of each other. static defines the object's lifetime during execution; constexpr specifies that the object should be available during compilation. Compilation and execution are disjoint and discontiguous, both in time and space. So once the program is compiled, constexpr is no longer relevant.

Every variable declared constexpr is implicitly const but const and static are almost orthogonal (except for the interaction with static const integers.)

The C++ object model (§1.9) requires that all objects other than bit-fields occupy at least one byte of memory and have addresses; furthermore all such objects observable in a program at a given moment must have distinct addresses (paragraph 6). This does not quite require the compiler to create a new array on the stack for every invocation of a function with a local non-static const array, because the compiler could take refuge in the as-if principle provided it can prove that no other such object can be observed.

That's not going to be easy to prove, unfortunately, unless the function is trivial (for example, it does not call any other function whose body is not visible within the translation unit) because arrays, more or less by definition, are addresses. So in most cases, the non-static const(expr) array will have to be recreated on the stack at every invocation, which defeats the point of being able to compute it at compile time.

On the other hand, a local static const object is shared by all observers, and furthermore may be initialized even if the function it is defined in is never called. So none of the above applies, and a compiler is free not only to generate only a single instance of it; it is free to generate a single instance of it in read-only storage.

So you should definitely use static constexpr in your example.

However, there is one case where you wouldn't want to use static constexpr. Unless a constexpr declared object is either ODR-used or declared static, the compiler is free to not include it at all. That's pretty useful, because it allows the use of compile-time temporary constexpr arrays without polluting the compiled program with unnecessary bytes. In that case, you would clearly not want to use static, since static is likely to force the object to exist at runtime.

C# error: "An object reference is required for the non-static field, method, or property"

The Main method is Static. You can not invoke a non-static method from a static method.

GetRandomBits()

is not a static method. Either you have to create an instance of Program

Program p = new Program();
p.GetRandomBits();

or make

GetRandomBits() static.

Shell script to delete directories older than n days

find supports -delete operation, so:

find /base/dir/* -ctime +10 -delete;

I think there's a catch that the files need to be 10+ days older too. Haven't tried, someone may confirm in comments.

The most voted solution here is missing -maxdepth 0 so it will call rm -rf for every subdirectory, after deleting it. That doesn't make sense, so I suggest:

find /base/dir/* -maxdepth 0  -type d -ctime +10 -exec rm -rf {} \;

The -delete solution above doesn't use -maxdepth 0 because find would complain the dir is not empty. Instead, it implies -depth and deletes from the bottom up.

JavaScript CSS how to add and remove multiple CSS classes to an element

Perhaps:

document.getElementById("myEle").className = "class1 class2";

Not tested, but should work.

Specifying trust store information in spring boot application.properties

If you execute your Spring Boot application as a linux service (e.g. init.d script or similar), then you have the following option as well: Create a file called yourApplication.conf and put it next to your executable war/jar file. It's content should be something similar:

JAVA_OPTS="
-Djavax.net.ssl.trustStore=path-to-your-trustStore-file
-Djavax.net.ssl.trustStorePassword=yourCrazyPassword
"

Color theme for VS Code integrated terminal

Simply. You can go to 'File -> Preferences -> Color Theme' option in visual studio and change the color of you choice.

Common elements in two lists

Some of the answers above are similar but not the same so posting it as a new answer.

Solution:
1. Use HashSet to hold elements which need to be removed
2. Add all elements of list1 to HashSet
3. iterate list2 and remove elements from a HashSet which are present in list2 ==> which are present in both list1 and list2
4. Now iterate over HashSet and remove elements from list1(since we have added all elements of list1 to set), finally, list1 has all common elements
Note: We can add all elements of list2 and in a 3rd iteration, we should remove elements from list2.

Time complexity: O(n)
Space Complexity: O(n)

Code:

import com.sun.tools.javac.util.Assert;
import org.apache.commons.collections4.CollectionUtils;

    List<Integer> list1 = new ArrayList<>();
    list1.add(1);
    list1.add(2);
    list1.add(3);
    list1.add(4);
    list1.add(5);

    List<Integer> list2 = new ArrayList<>();
    list2.add(1);
    list2.add(3);
    list2.add(5);
    list2.add(7);
    Set<Integer> toBeRemoveFromList1 = new HashSet<>(list1);
    System.out.println("list1:" + list1);
    System.out.println("list2:" + list2);
    for (Integer n : list2) {
        if (toBeRemoveFromList1.contains(n)) {
            toBeRemoveFromList1.remove(n);
        }
    }
    System.out.println("toBeRemoveFromList1:" + toBeRemoveFromList1);
    for (Integer n : toBeRemoveFromList1) {
        list1.remove(n);
    }
    System.out.println("list1:" + list1);
    System.out.println("collectionUtils:" + CollectionUtils.intersection(list1, list2));
    Assert.check(CollectionUtils.intersection(list1, list2).containsAll(list1));

output:

list1:[1, 2, 3, 4, 5]
list2:[1, 3, 5, 7]
toBeRemoveFromList1:[2, 4]
list1:[1, 3, 5]
collectionUtils:[1, 3, 5]

How to completely remove node.js from Windows

Scenario: Removing NodeJS when Windows has no Program Entry for your Node installation

I ran into a problem where my version of NodeJS (0.10.26) could NOT be uninstalled nor removed, because Programs & Features in Windows 7 (aka Add/Remove Programs) had no record of my having installed NodeJS... so there was no option to remove it short of manually deleting registry keys and files.

Command to verify your NodeJS version: node --version

I attempted to install the newest recommended version of NodeJS, but it failed at the end of the installation process and rolled back. Multiple versions of NodeJS also failed, and the installer likewise rolled them back as well. I could not upgrade NodeJS from the command line as I did not have SUDO installed.

SOLUTION: After spending several hours troubleshooting the problem, including upgrading NPM, I decided to reinstall the EXACT version of NodeJS on my system, over the top of the existing installation.

That solution worked, and it reinstalled NodeJS without any errors. Better yet, it also added an official entry in Add/Remove Programs dialogue.

Now that Windows was aware of the forgotten NodeJS installation, I was able to uninstall my existing version of NodeJS completely. I then successfully installed the newest recommended release of NodeJS for the Windows platform (version 4.4.5 as of this writing) without a roll-back initiating.

It took me a while to reach sucess, so I am posting this in case it helps anyone else with a similar issue.

"Use of undeclared type" in Swift, even though type is internal, and exists in same module

In case someone makes the same silly mistake I did...

I was getting this error because in renaming my source file, I accidentally removed the. from the filename and so the compiler treated the file as a plain text file and not as source to compile.

so I meant to rename the file to MyProtocol.swift but accidently named it MyProtocolswift

It's a simple mistake, but it was not readily obvious that this is what was going on.

printf %f with only 2 numbers after the decimal point?

I suggest to learn it with printf because for many cases this will be sufficient for your needs and you won't need to create other objects.

double d = 3.14159;     
printf ("%.2f", d);

But if you need rounding please refer to this post

https://stackoverflow.com/a/153785/2815227

How to use JavaScript with Selenium WebDriver Java

You can also try clicking by JavaScript:

WebElement button = driver.findElement(By.id("someid"));
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].click();", button);

Also you can use jquery. In worst cases, for stubborn pages it may be necessary to do clicks by custom EXE application. But try the obvious solutions first.

javascript, is there an isObject function like isArray?

You can use typeof operator.

if( (typeof A === "object" || typeof A === 'function') && (A !== null) )
{
    alert("A is object");
}

Note that because typeof new Number(1) === 'object' while typeof Number(1) === 'number'; the first syntax should be avoided.

Apache Cordova - uninstall globally

Try sudo npm uninstall cordova -g to uninstall it globally and then just npm install cordova without the -g flag after cding to the local app directory

fatal: ambiguous argument 'origin': unknown revision or path not in the working tree

Sometimes things might be simpler. I came here with the exact issue and tried all the suggestions. But later found that the problem was just the local file path was different and I was on a different folder. :-)

eg -

~/myproject/mygitrepo/app/$ git diff app/TestFile.txt

should have been

~/myproject/mygitrepo/app/$ git diff TestFile.txt

Navigation Controller Push View Controller

Use this code in your button action (Swift 3.0.1):

let vc = self.storyboard?.instantiateViewController(
    withIdentifier: "YourSecondVCIdentifier") as! SecondVC

navigationController?.pushViewController(vc, animated: true)

How to remove duplicates from a list?

The correct answer for Java is use a Set. If you already have a List<Customer> and want to de duplicate it

Set<Customer> s = new HashSet<Customer>(listCustomer);

Otherise just use a Set implemenation HashSet, TreeSet directly and skip the List construction phase.

You will need to override hashCode() and equals() on your domain classes that are put in the Set as well to make sure that the behavior you want actually what you get. equals() can be as simple as comparing unique ids of the objects to as complex as comparing every field. hashCode() can be as simple as returning the hashCode() of the unique id' String representation or the hashCode().

Search a string in a file and delete it from this file by Shell Script

This should do it:

sed -e s/deletethis//g -i *
sed -e "s/deletethis//g" -i.backup *
sed -e "s/deletethis//g" -i .backup *

it will replace all occurrences of "deletethis" with "" (nothing) in all files (*), editing them in place.

In the second form the pattern can be edited a little safer, and it makes backups of any modified files, by suffixing them with ".backup".

The third form is the way some versions of sed like it. (e.g. Mac OS X)

man sed for more information.

Create MSI or setup project with Visual Studio 2012

To create setup projects in Visual Studio 2012 with InstallShield Limited Edition, watch this video.

The InstallShield limited edition that cannot install services.

"ISLE is by far the worst installer option and the upgraded, read - paid for, version is cumbersome to use at best and impossible in most situations. InnoSetup, Nullsoft, Advanced, WiX, or just about any other installer is better. If you did a survey you would see that nobody is using ISLE. I don't know why you guys continue to associate with InstallShield. It damages your credibility. Any developer worth half his weight in salt knows ISLE is worthless and when you stand behind it we have to question Microsoft's judgment."

By Edward Miller (comments in Visual Studio Installer Projects Extension).

The WiX Toolset, which, while powerful is exceeding user-unfriendly and has a steep learning curve. There is even a downloadable template for installing Windows services (ref. VS2012: Installer for Windows services?).

For Visual Studio 2013, see blog post Creating installers with Visual Studio.

how to set imageview src?

To set image cource in imageview you can use any of the following ways. First confirm your image is present in which format.

If you have image in the form of bitmap then use

imageview.setImageBitmap(bm);

If you have image in the form of drawable then use

imageview.setImageDrawable(drawable);

If you have image in your resource example if image is present in drawable folder then use

imageview.setImageResource(R.drawable.image);

If you have path of image then use

imageview.setImageURI(Uri.parse("pathofimage"));

REST API 404: Bad URI, or Missing Resource?

As with most things, "it depends". But to me, your practice is not bad and is not going against the HTTP spec per se. However, let's clear some things up.

First, URI's should be opaque. Even if they're not opaque to people, they are opaque to machines. In other words, the difference between http://mywebsite/api/user/13, http://mywebsite/restapi/user/13 is the same as the difference between http://mywebsite/api/user/13 and http://mywebsite/api/user/14 i.e. not the same is not the same period. So a 404 would be completely appropriate for http://mywebsite/api/user/14 (if there is no such user) but not necessarily the only appropriate response.

You could also return an empty 200 response or more explicitly a 204 (No Content) response. This would convey something else to the client. It would imply that the resource identified by http://mywebsite/api/user/14 has no content or is essentially nothing. It does mean that there is such a resource. However, it does not necessarily mean that you are claiming there is some user persisted in a data store with id 14. That's your private concern, not the concern of the client making the request. So, if it makes sense to model your resources that way, go ahead.

There are some security implications to giving your clients information that would make it easier for them to guess legitimate URI's. Returning a 200 on misses instead of a 404 may give the client a clue that at least the http://mywebsite/api/user part is correct. A malicious client could just keep trying different integers. But to me, a malicious client would be able to guess the http://mywebsite/api/user part anyway. A better remedy would be to use UUID's. i.e. http://mywebsite/api/user/3dd5b770-79ea-11e1-b0c4-0800200c9a66 is better than http://mywebsite/api/user/14. Doing that, you could use your technique of returning 200's without giving much away.

What is the difference between spark.sql.shuffle.partitions and spark.default.parallelism?

From the answer here, spark.sql.shuffle.partitions configures the number of partitions that are used when shuffling data for joins or aggregations.

spark.default.parallelism is the default number of partitions in RDDs returned by transformations like join, reduceByKey, and parallelize when not set explicitly by the user. Note that spark.default.parallelism seems to only be working for raw RDD and is ignored when working with dataframes.

If the task you are performing is not a join or aggregation and you are working with dataframes then setting these will not have any effect. You could, however, set the number of partitions yourself by calling df.repartition(numOfPartitions) (don't forget to assign it to a new val) in your code.


To change the settings in your code you can simply do:

sqlContext.setConf("spark.sql.shuffle.partitions", "300")
sqlContext.setConf("spark.default.parallelism", "300")

Alternatively, you can make the change when submitting the job to a cluster with spark-submit:

./bin/spark-submit --conf spark.sql.shuffle.partitions=300 --conf spark.default.parallelism=300

Adding items to an object through the .push() method

.push() is a method of the Built-in Array Object

It is not related to jQuery in any way.

You are defining a literal Object with

// Object
var stuff = {};

You can define a literal Array like this

// Array
var stuff = [];

then

stuff.push(element);

Arrays actually get their bracket syntax stuff[index] inherited from their parent, the Object. This is why you are able to use it the way you are in your first example.

This is often used for effortless reflection for dynamically accessing properties

stuff = {}; // Object

stuff['prop'] = 'value'; // assign property of an 
                         // Object via bracket syntax

stuff.prop === stuff['prop']; // true

Getting Java version at runtime

The simplest way (java.specification.version):

double version = Double.parseDouble(System.getProperty("java.specification.version"));

if (version == 1.5) {
    // 1.5 specific code
} else {
    // ...
}

or something like (java.version):

String[] javaVersionElements = System.getProperty("java.version").split("\\.");

int major = Integer.parseInt(javaVersionElements[1]);

if (major == 5) {
    // 1.5 specific code
} else {
    // ...
}

or if you want to break it all up (java.runtime.version):

String discard, major, minor, update, build;

String[] javaVersionElements = System.getProperty("java.runtime.version").split("\\.|_|-b");

discard = javaVersionElements[0];
major   = javaVersionElements[1];
minor   = javaVersionElements[2];
update  = javaVersionElements[3];
build   = javaVersionElements[4];

How to get distinct values from an array of objects in JavaScript?

I picked up random samples and tested it against the 100,000 items as below:

let array=[]
for (var i=1;i<100000;i++){

 let j= Math.floor(Math.random() * i) + 1
  array.push({"name":"Joe"+j, "age":j})
}

And here the performance result for each:

  Vlad Bezden Time:         === > 15ms
  Travis J Time: 25ms       === > 25ms 
  Niet the Dark Absol Time: === > 30ms
  Arun Saini Time:          === > 31ms
  Mrchief Time:             === > 54ms
  Ivan Nosov Time:          === > 14374ms

Also, I want to mention, since the items are generated randomly, the second place was iterating between Travis and Niet.

Using Helvetica Neue in a Website

Assuming you have referenced and correctly integrated your font to your site (presumably using an @font-face kit) it should be alright to just reference yours the way you do. Presumably it is like this so they have fall backs incase some browsers do not render the fonts correctly

CodeIgniter Active Record not equal

This should work (which you have tried)

$this->db->where_not_in('emailsToCampaigns.campaignId', $campaignId);

How to create a sticky left sidebar menu using bootstrap 3?

You can also try to use a Polyfill like Fixed-Sticky. Especially when you are using Bootstrap4 the affix component is no longer included:

Dropped the Affix jQuery plugin. We recommend using a position: sticky polyfill instead.

Where does Hive store files in HDFS?

Hive tables may not necessarily be stored in a warehouse (since you can create tables located anywhere on the HDFS).

You should use DESCRIBE FORMATTED <table_name> command.

hive -S -e "describe formatted <table_name> ;" | grep 'Location' | awk '{ print $NF }'

Please note that partitions may be stored in different places and to get the location of the alpha=foo/beta=bar partition you'd have to add partition(alpha='foo',beta='bar') after <table_name>.

top nav bar blocking top content of the page

you should add

#page {
  padding-top: 65px
}

to not destroy a sticky footer or something else

Resize a large bitmap file to scaled output file on Android

There is a great article about this exact issue on the Android developer website: Loading Large Bitmaps Efficiently

How to get a Docker container's IP address from the host

For windows 10:

docker inspect --format "{{ .NetworkSettings.IPAddress }}"  containerId

onchange event for html.dropdownlist

If you don't want jquery then you can do it with javascript :-

@Html.DropDownList("Sortby", new SelectListItem[] 
{ 
     new SelectListItem() { Text = "Newest to Oldest", Value = "0" }, 
     new SelectListItem() { Text = "Oldest to Newest", Value = "1" }},
     new { @onchange="callChangefunc(this.value)" 
});

<script>
    function callChangefunc(val){
        window.location.href = "/Controller/ActionMethod?value=" + val;
    }
</script>

Most efficient way to map function over numpy array

How about using numpy.vectorize.

import numpy as np
x = np.array([1, 2, 3, 4, 5])
squarer = lambda t: t ** 2
vfunc = np.vectorize(squarer)
vfunc(x)
# Output : array([ 1,  4,  9, 16, 25])

How to change color in circular progress bar?

check this answer out:

for me, these two lines had to be there for it to work and change the color:

android:indeterminateTint="@color/yourColor"
android:indeterminateTintMode="src_in"

PS: but its only available from android 21

Python Finding Prime Factors

This is my python code: it has a fast check for primes and checks from highest to lowest the prime factors. You have to stop if no new numbers came out. (Any ideas on this?)

import math


def is_prime_v3(n):
    """ Return 'true' if n is a prime number, 'False' otherwise """
    if n == 1:
        return False

    if n > 2 and n % 2 == 0:
        return False

    max_divisor = math.floor(math.sqrt(n))
    for d in range(3, 1 + max_divisor, 2):
        if n % d == 0:
            return False
    return True


number = <Number>

for i in range(1,math.floor(number/2)):
    if is_prime_v3(i):
        if number % i == 0:
            print("Found: {} with factor {}".format(number / i, i))

The answer for the initial question arrives in a fraction of a second.

Copy a git repo without history

#!/bin/bash
set -e

# Settings
user=xxx
pass=xxx
dir=xxx
repo_src=xxx
repo_trg=xxx
src_branch=xxx

repo_base_url=https://$user:[email protected]/$user
repo_src_url=$repo_base_url/$repo_src.git
repo_trg_url=$repo_base_url/$repo_trg.git

echo "Clone Source..."
git clone --depth 1 -b $src_branch $repo_src_url $dir

echo "CD"
cd ./$dir

echo "Remove GIT"
rm -rf .git

echo "Init GIT"
git init
git add .
git commit -m "Initial Commit"
git remote add origin $repo_trg_url

echo "Push..."
git push -u origin master

Change default date time format on a single database in SQL Server

For SQL Server 2008 run:

EXEC sp_defaultlanguage 'username', 'british'

How to copy files between two nodes using ansible

If you need to sync files between two remote nodes via ansible you can use this:

- name: synchronize between nodes
  environment:
    RSYNC_PASSWORD: "{{ input_user_password_if_needed }}"
  synchronize:
    src: rsync://user@remote_server:/module/
    dest: /destination/directory/
    // if needed
    rsync_opts:
       - "--include=what_needed"
       - "--exclude=**/**"
    mode: pull
    delegate_to: "{{ inventory_hostname }}"

when on remote_server you need to startup rsync with daemon mode. Simple example:

pid file = /var/run/rsyncd.pid
lock file = /var/run/rsync.lock
log file = /var/log/rsync.log
port = port

[module]
path = /path/to/needed/directory/
uid = nobody
gid = nobody
read only = yes
list = yes
auth users = user
secrets file = /path/to/secret/file

Mysql: Select rows from a table that are not in another

SELECT a.* FROM 
FROM tbl_1 a
MINUS
SELECT b.* FROM 
FROM tbl_2 b

D3 transform scale and translate

I realize this question is fairly old, but wanted to share a quick demo of group transforms, paths/shapes, and relative positioning, for anyone else who found their way here looking for more info:

http://bl.ocks.org/dustinlarimer/6050773

C++ - How to append a char to char*?

Remove those char * ret declarations inside if blocks which hide outer ret. Therefor you have memory leak and on the other hand un-allocated memory for ret.

To compare a c-style string you should use strcmp(array,"") not array!="". Your final code should looks like below:

char* appendCharToCharArray(char* array, char a)
{
    size_t len = strlen(array);

    char* ret = new char[len+2];

    strcpy(ret, array);    
    ret[len] = a;
    ret[len+1] = '\0';

    return ret;
}

Note that, you must handle the allocated memory of returned ret somewhere by delete[] it.

 

Why you don't use std::string? it has .append method to append a character at the end of a string:

std::string str;

str.append('x');
// or
str += x;

What's the best way to join on the same table twice?

The first method is the proper approach and will do what you need. However, with the inner joins, you will only select rows from Table1 if both phone numbers exist in Table2. You may want to do a LEFT JOIN so that all rows from Table1 are selected. If the phone numbers don't match, then the SomeOtherFields would be null. If you want to make sure you have at least one matching phone number you could then do WHERE t2.PhoneNumber IS NOT NULL OR t3.PhoneNumber IS NOT NULL

The second method could have a problem: what happens if Table2 has both PhoneNumber1 and PhoneNumber2? Which row will be selected? Depending on your data, foreign keys, etc. this may or may not be a problem.

importing jar libraries into android-studio

Android Studio 1.0.1 doesn't make it any clearer, but it does make it somehow easier. Here's what worked for me:

1) Using explorer, create an 'external_libs' folder (any other name is fine) inside the Project/app/src folder, where 'Project' is the name of your project

2) Copy your jar file into this 'external_libs' folder

3) In Android Studio, go to File -> Project Structure -> Dependencies -> Add -> File Dependency and navigate to your jar file, which should be under 'src/external_libs'

3) Select your jar file and click 'Ok'

Now, check your build.gradle (Module.app) script, where you'll see the jar already added under 'dependencies'

How do I add a .click() event to an image?

Enclose <img> in <a> tag.

<a href="http://www.google.com.pk"><img src="smiley.gif"></a>

it will open link on same tab, and if you want to open link on new tab then use target="_blank"

<a href="http://www.google.com.pk" target="_blank"><img src="smiley.gif"></a>

installing vmware tools: location of GCC binary?

sudo apt-get install build-essential is enough to get it working.

Swift - iOS - Dates and times in different format

Here is a solution that works with Xcode 10.1 (FEB 23 2019) :

func getCurrentDateTime() {

    let now = Date()
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "fr_FR")
    formatter.dateFormat = "EEEE dd MMMM YYYY"
    labelDate.text = formatter.string(from: now)
    labelDate.font = UIFont(name: "HelveticaNeue-Bold", size: 12)
    labelDate.textColor = UIColor.lightGray

    let text = formatter.string(from: now)
    labelDate.text = text.uppercased()
}

The "Accueil" Label is not connected to the code.

Style child element when hover on parent

Yes, you can definitely do this. Just use something like

.parent:hover .child {
   /* ... */
}

According to this page it's supported by all major browsers.

Regex empty string or email

matching empty string or email

(^$|^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.(?:[a-zA-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)$)

matching empty string or email but also matching any amount of whitespace

(^\s*$|^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.(?:[a-zA-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)$)

see more about the email matching regex itself:

http://www.regular-expressions.info/email.html

How do I pass a unique_ptr argument to a constructor or a function?

To the top voted answer. I prefer passing by rvalue reference.

I understand what's the problem about passing by rvalue reference may cause. But let's divide this problem to two sides:

  • for caller:

I must write code Base newBase(std::move(<lvalue>)) or Base newBase(<rvalue>).

  • for callee:

Library author should guarantee it will actually move the unique_ptr to initialize member if it want own the ownership.

That's all.

If you pass by rvalue reference, it will only invoke one "move" instruction, but if pass by value, it's two.

Yep, if library author is not expert about this, he may not move unique_ptr to initialize member, but it's the problem of author, not you. Whatever it pass by value or rvalue reference, your code is same!

If you are writing a library, now you know you should guarantee it, so just do it, passing by rvalue reference is a better choice than value. Client who use you library will just write same code.

Now, for your question. How do I pass a unique_ptr argument to a constructor or a function?

You know what's the best choice.

http://scottmeyers.blogspot.com/2014/07/should-move-only-types-ever-be-passed.html

Embedding JavaScript engine into .NET

Microsoft's documented way to add script extensibility to anything is IActiveScript. You can use IActiveScript from within anyt .NET app, to call script logic. The logic can party on .NET objects that you've placed into the scripting context.

This answer provides an application that does it, with code:

Android dependency has different version for the compile and runtime

I comment out //api 'com.google.android.gms:play-services-ads:15.0.1' it worked for me after sync

XPath: How to select elements based on their value?

The condition below:

//Element[@attribute1="abc" and @attribute2="xyz" and Data]

checks for the existence of the element Data within Element and not for element value Data.

Instead you can use

//Element[@attribute1="abc" and @attribute2="xyz" and text()="Data"]

Add left/right horizontal padding to UILabel

UIView* bg = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, 70)];
bg.backgroundColor = [UIColor blackColor];
UILabel* yourLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, y, yourWidth, yourHeight)];
[bg addSubview:yourLabel];

[self addSubview:bg];

Visual Studio - How to change a project's folder name and solution name without breaking the solution

go to my start-documents-iisExpress-config and then right click on applicationhost and select open with visual studio 2013 for web you will get into applicationhost.config window in the visual studio and now in the region chsnge the physical path to the path where your project is placed

Running stages in parallel with Jenkins workflow / pipeline

You may not place the deprecated non-block-scoped stage (as in the original question) inside parallel.

As of JENKINS-26107, stage takes a block argument. You may put parallel inside stage or stage inside parallel or stage inside stage etc. However visualizations of the build are not guaranteed to support all nestings; in particular

  • The built-in Pipeline Steps (a “tree table” listing every step run by the build) shows arbitrary stage nesting.
  • The Pipeline Stage View plugin will currently only display a linear list of stages, in the order they started, regardless of nesting structure.
  • Blue Ocean will display top-level stages, plus parallel branches inside a top-level stage, but currently no more.

JENKINS-27394, if implemented, would display arbitrarily nested stages.

Setting public class variables

class Testclass
{
  public $testvar;

  function dosomething()
  {
    echo $this->testvar;
  }
}

$Testclass = new Testclass();
$Testclass->testvar = "another value";    
$Testclass->dosomething(); ////It will print "another value"

jQuery function to get all unique elements from an array?

If anyone is using knockoutjs try:

ko.utils.arrayGetDistinctValues()

BTW have look at all ko.utils.array* utilities.

Bootstrap 3: Keep selected tab on page refresh

This one use HTML5 localStorage to store active tab

$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
    localStorage.setItem('activeTab', $(e.target).attr('href'));
});
var activeTab = localStorage.getItem('activeTab');
if (activeTab) {
   $('#navtab-container a[href="' + activeTab + '"]').tab('show');
}

ref: http://www.tutorialrepublic.com/faq/how-to-keep-the-current-tab-active-on-page-reload-in-bootstrap.php https://www.w3schools.com/bootstrap/bootstrap_ref_js_tab.asp

Fork() function in C

int a = fork(); 

Creates a duplicate process "clone?", which shares the execution stack. The difference between the parent and the child is the return value of the function.

The child getting 0 returned, and the parent getting the new pid.

Each time the addresses and the values of the stack variables are copied. The execution continues at the point it already got to in the code.

At each fork, only one value is modified - the return value from fork.

How to make a Qt Widget grow with the window size?

The accepted answer (its image) is wrong, at least now in QT5. Instead you should assign a layout to the root object/widget (pointing to the aforementioned image, it should be the MainWindow instead of centralWidget). Also note that you must have at least one QObject created beneath it for this to work. Do this and your ui will become responsive to window resizing.

How to retrieve inserted id after inserting row in SQLite using Python?

All credits to @Martijn Pieters in the comments:

You can use the function last_insert_rowid():

The last_insert_rowid() function returns the ROWID of the last row insert from the database connection which invoked the function. The last_insert_rowid() SQL function is a wrapper around the sqlite3_last_insert_rowid() C/C++ interface function.

Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0

WORDPRESS is having this error mostly:
SOLUTION:
Locate your PHP installed directory on Remote live hosting SERVER or "Local Server"
In case of Windows os
for example if you using xampp or wamp webserver. it will be in xammp directory 'c:\xammp\php'
Note: For Unix/Linux OS, locate your PHP directory in Webserver

Find & Edit PHP.INI file
Find 'allow_url_include'
replace it with value 'on'
allow_url_include=On
Save you php.ini & RESTART you web-server.

How to map calculated properties with JPA and Hibernate

JPA doesn't offer any support for derived property so you'll have to use a provider specific extension. As you mentioned, @Formula is perfect for this when using Hibernate. You can use an SQL fragment:

@Formula("PRICE*1.155")
private float finalPrice;

Or even complex queries on other tables:

@Formula("(select min(o.creation_date) from Orders o where o.customer_id = id)")
private Date firstOrderDate;

Where id is the id of the current entity.

The following blog post is worth the read: Hibernate Derived Properties - Performance and Portability.

Without more details, I can't give a more precise answer but the above link should be helpful.

See also:

Bootstrap 3, 4 and 5 .container-fluid with grid adding unwanted padding

Please find the actual css from Bootstrap

.container-fluid {
  padding-right: 15px;
  padding-left: 15px;
  margin-right: auto;
  margin-left: auto;
}
.row {
  margin-right: -15px;
  margin-left: -15px;
}

When you add a .container-fluid class, it adds a horizontal padding of 15px, and the same will be removed when you add a .row class as a child element by the negative margin set on row.

Why is it said that "HTTP is a stateless protocol"?

If protocol HTTP is given as State full protocol,browser window uses single connection to communicate with web server for multiple request given to web application.this gives chance to browser window to engage the connections between browser window and web servers for long time and to keep them in idle state for long time.This may create the situation of reaching to maximum connections of web server even though most of the connections in clients are idle.

How to validate a credit card number

This works: http://jsfiddle.net/WHKeK/

function validate_creditcardnumber()
{
    var re16digit=/^\d{16}$/
    if (document.myform.CreditCardNumber.value.search(re16digit) == -1)
        alert("Please enter your 16 digit credit card numbers");
    return false;    
}

You have a typo. You call the variable re16digit, but in your search you have re10digit.

How can I see the current value of my $PATH variable on OS X?

Use the command:

 echo $PATH

and you will see all path:

/Users/name/.rvm/gems/ruby-2.5.1@pe/bin:/Users/name/.rvm/gems/ruby-2.5.1@global/bin:/Users/sasha/.rvm/rubies/ruby-2.5.1/bin:/Users/sasha/.rvm/bin:

Check if a div exists with jquery

As karim79 mentioned, the first is the most concise. However I could argue that the second is more understandable as it is not obvious/known to some Javascript/jQuery programmers that non-zero/false values are evaluated to true in if-statements. And because of that, the third method is incorrect.

Subset a dataframe by multiple factor levels

Here's another:

data[data$Code == "A" | data$Code == "B", ]

It's also worth mentioning that the subsetting factor doesn't have to be part of the data frame if it matches the data frame rows in length and order. In this case we made our data frame from this factor anyway. So,

data[Code == "A" | Code == "B", ]

also works, which is one of the really useful things about R.

Using ConfigurationManager to load config from an arbitrary location

For ASP.NET use WebConfigurationManager:

var config = WebConfigurationManager.OpenWebConfiguration("~/Sites/" + requestDomain + "/");
(..)
config.AppSettings.Settings["xxxx"].Value;

ViewPager and fragments — what's the right way to store fragment's state?

To get the fragments after orientation change you have to use the .getTag().

    getSupportFragmentManager().findFragmentByTag("android:switcher:" + viewPagerId + ":" + positionOfItemInViewPager)

For a bit more handling i wrote my own ArrayList for my PageAdapter to get the fragment by viewPagerId and the FragmentClass at any Position:

public class MyPageAdapter extends FragmentPagerAdapter implements Serializable {
private final String logTAG = MyPageAdapter.class.getName() + ".";

private ArrayList<MyPageBuilder> fragmentPages;

public MyPageAdapter(FragmentManager fm, ArrayList<MyPageBuilder> fragments) {
    super(fm);
    fragmentPages = fragments;
}

@Override
public Fragment getItem(int position) {
    return this.fragmentPages.get(position).getFragment();
}

@Override
public CharSequence getPageTitle(int position) {
    return this.fragmentPages.get(position).getPageTitle();
}

@Override
public int getCount() {
    return this.fragmentPages.size();
}


public int getItemPosition(Object object) {
    //benötigt, damit bei notifyDataSetChanged alle Fragemnts refrehsed werden

    Log.d(logTAG, object.getClass().getName());
    return POSITION_NONE;
}

public Fragment getFragment(int position) {
    return getItem(position);
}

public String getTag(int position, int viewPagerId) {
    //getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.shares_detail_activity_viewpager + ":" + myViewPager.getCurrentItem())

    return "android:switcher:" + viewPagerId + ":" + position;
}

public MyPageBuilder getPageBuilder(String pageTitle, int icon, int selectedIcon, Fragment frag) {
    return new MyPageBuilder(pageTitle, icon, selectedIcon, frag);
}


public static class MyPageBuilder {

    private Fragment fragment;

    public Fragment getFragment() {
        return fragment;
    }

    public void setFragment(Fragment fragment) {
        this.fragment = fragment;
    }

    private String pageTitle;

    public String getPageTitle() {
        return pageTitle;
    }

    public void setPageTitle(String pageTitle) {
        this.pageTitle = pageTitle;
    }

    private int icon;

    public int getIconUnselected() {
        return icon;
    }

    public void setIconUnselected(int iconUnselected) {
        this.icon = iconUnselected;
    }

    private int iconSelected;

    public int getIconSelected() {
        return iconSelected;
    }

    public void setIconSelected(int iconSelected) {
        this.iconSelected = iconSelected;
    }

    public MyPageBuilder(String pageTitle, int icon, int selectedIcon, Fragment frag) {
        this.pageTitle = pageTitle;
        this.icon = icon;
        this.iconSelected = selectedIcon;
        this.fragment = frag;
    }
}

public static class MyPageArrayList extends ArrayList<MyPageBuilder> {
    private final String logTAG = MyPageArrayList.class.getName() + ".";

    public MyPageBuilder get(Class cls) {
        // Fragment über FragmentClass holen
        for (MyPageBuilder item : this) {
            if (item.fragment.getClass().getName().equalsIgnoreCase(cls.getName())) {
                return super.get(indexOf(item));
            }
        }
        return null;
    }

    public String getTag(int viewPagerId, Class cls) {
        // Tag des Fragment unabhängig vom State z.B. nach bei Orientation change
        for (MyPageBuilder item : this) {
            if (item.fragment.getClass().getName().equalsIgnoreCase(cls.getName())) {
                return "android:switcher:" + viewPagerId + ":" + indexOf(item);
            }
        }
        return null;
    }
}

So just create a MyPageArrayList with the fragments:

    myFragPages = new MyPageAdapter.MyPageArrayList();

    myFragPages.add(new MyPageAdapter.MyPageBuilder(
            getString(R.string.widget_config_data_frag),
            R.drawable.ic_sd_storage_24dp,
            R.drawable.ic_sd_storage_selected_24dp,
            new WidgetDataFrag()));

    myFragPages.add(new MyPageAdapter.MyPageBuilder(
            getString(R.string.widget_config_color_frag),
            R.drawable.ic_color_24dp,
            R.drawable.ic_color_selected_24dp,
            new WidgetColorFrag()));

    myFragPages.add(new MyPageAdapter.MyPageBuilder(
            getString(R.string.widget_config_textsize_frag),
            R.drawable.ic_settings_widget_24dp,
            R.drawable.ic_settings_selected_24dp,
            new WidgetTextSizeFrag()));

and add them to the viewPager:

    mAdapter = new MyPageAdapter(getSupportFragmentManager(), myFragPages);
    myViewPager.setAdapter(mAdapter);

after this you can get after orientation change the correct fragment by using its class:

        WidgetDataFrag dataFragment = (WidgetDataFrag) getSupportFragmentManager()
            .findFragmentByTag(myFragPages.getTag(myViewPager.getId(), WidgetDataFrag.class));

combining two data frames of different lengths

It's not clear to me at all what the OP is actually after, given the follow-up comments. It's possible they are actually looking for a way to write the data to file.

But let's assume that we're really after a way to cbind multiple data frames of differing lengths.

cbind will eventually call data.frame, whose help files says:

Objects passed to data.frame should have the same number of rows, but atomic vectors, factors and character vectors protected by I will be recycled a whole number of times if necessary (including as from R 2.9.0, elements of list arguments).

so in the OP's actual example, there shouldn't be an error, as R ought to recycle the shorter vectors to be of length 50. Indeed, when I run the following:

set.seed(1)
a <- runif(50)
b <- 1:50
c <- rep(LETTERS[1:5],length.out = 50)
dat1 <- data.frame(a,b,c)
dat2 <- data.frame(d = runif(10),e = runif(10))
cbind(dat1,dat2)

I get no errors and the shorter data frame is recycled as expected. However, when I run this:

set.seed(1)
a <- runif(50)
b <- 1:50
c <- rep(LETTERS[1:5],length.out = 50)
dat1 <- data.frame(a,b,c)
dat2 <- data.frame(d = runif(9), e = runif(9))
cbind(dat1,dat2)

I get the following error:

Error in data.frame(..., check.names = FALSE) : 
  arguments imply differing number of rows: 50, 9

But the wonderful thing about R is that you can make it do almost anything you want, even if you shouldn't. For example, here's a simple function that will cbind data frames of uneven length and automatically pad the shorter ones with NAs:

cbindPad <- function(...){
args <- list(...)
n <- sapply(args,nrow)
mx <- max(n)
pad <- function(x, mx){
    if (nrow(x) < mx){
        nms <- colnames(x)
        padTemp <- matrix(NA, mx - nrow(x), ncol(x))
        colnames(padTemp) <- nms
        if (ncol(x)==0) {
          return(padTemp)
        } else {
        return(rbind(x,padTemp))
          }
    }
    else{
        return(x)
    }
}
rs <- lapply(args,pad,mx)
return(do.call(cbind,rs))
}

which can be used like this:

set.seed(1)
a <- runif(50)
b <- 1:50
c <- rep(LETTERS[1:5],length.out = 50)
dat1 <- data.frame(a,b,c)
dat2 <- data.frame(d = runif(10),e = runif(10))
dat3 <- data.frame(d = runif(9), e = runif(9))
cbindPad(dat1,dat2,dat3)

I make no guarantees that this function works in all cases; it is meant as an example only.

EDIT

If the primary goal is to create a csv or text file, all you need to do it alter the function to pad using "" rather than NA and then do something like this:

dat <- cbindPad(dat1,dat2,dat3)
rs <- as.data.frame(apply(dat,1,function(x){paste(as.character(x),collapse=",")}))

and then use write.table on rs.

JQUERY: Uncaught Error: Syntax error, unrecognized expression

try

console.log($("#"+d));

your solution is passing the double quotes as part of the string.

Binary Data in JSON String. Something better than Base64

I ran into the same problem, and thought I'd share a solution: multipart/form-data.

By sending a multipart form you send first as string your JSON meta-data, and then separately send as raw binary (image(s), wavs, etc) indexed by the Content-Disposition name.

Here's a nice tutorial on how to do this in obj-c, and here is a blog article that explains how to partition the string data with the form boundary, and separate it from the binary data.

The only change you really need to do is on the server side; you will have to capture your meta-data which should reference the POST'ed binary data appropriately (by using a Content-Disposition boundary).

Granted it requires additional work on the server side, but if you are sending many images or large images, this is worth it. Combine this with gzip compression if you want.

IMHO sending base64 encoded data is a hack; the RFC multipart/form-data was created for issues such as this: sending binary data in combination with text or meta-data.

Hide axis and gridlines Highcharts

For the yAxis you'll also need:

gridLineColor: 'transparent',

How to clear cache of Eclipse Indigo

It's very simple. Right click inside the internal browser and click "refresh".

Getting request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

Basically, to make a cross domain AJAX requests, the requested server should allow the cross origin sharing of resources (CORS). You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/

In your scenario, you are setting the headers in the client which in fact needs to be set into http://localhost:8080/app server side code.

If you are using PHP Apache server, then you will need to add following in your .htaccess file:

Header set Access-Control-Allow-Origin "*"

How to access ssis package variables inside script component

Strongly typed var don't seem to be available, I have to do the following in order to get access to them:

String MyVar = Dts.Variables["MyVarName"].Value.ToString();

Run Excel Macro from Outside Excel Using VBScript From Command Line

I think you are trying to do this? (TRIED AND TESTED)

This code will open the file Test.xls and run the macro TestMacro which will in turn write to the text file TestResult.txt

Option Explicit

Dim xlApp, xlBook

Set xlApp = CreateObject("Excel.Application")
'~~> Change Path here
Set xlBook = xlApp.Workbooks.Open("C:\Test.xls", 0, True)
xlApp.Run "TestMacro"
xlBook.Close
xlApp.Quit

Set xlBook = Nothing
Set xlApp = Nothing

WScript.Echo "Finished."
WScript.Quit

Target class controller does not exist - Laravel 8

I had this error

(Illuminate\Contracts\Container\BindingResolutionException Target class [App\Http\Controllers\ControllerFileName] does not exist.

Solution: just check your class Name, it should be the exact same of your file name.

How is a CSS "display: table-column" supposed to work?

The CSS table model is based on the HTML table model http://www.w3.org/TR/CSS21/tables.html

A table is divided into ROWS, and each row contains one or more cells. Cells are children of ROWS, they are NEVER children of columns.

"display: table-column" does NOT provide a mechanism for making columnar layouts (e.g. newspaper pages with multiple columns, where content can flow from one column to the next).

Rather, "table-column" ONLY sets attributes that apply to corresponding cells within the rows of a table. E.g. "The background color of the first cell in each row is green" can be described.

The table itself is always structured the same way it is in HTML.

In HTML (observe that "td"s are inside "tr"s, NOT inside "col"s):

<table ..>
  <col .. />
  <col .. />
  <tr ..>
    <td ..></td>
    <td ..></td>
  </tr>
  <tr ..>
    <td ..></td>
    <td ..></td>
  </tr>
</table>

Corresponding HTML using CSS table properties (Note that the "column" divs do not contain any contents -- the standard does not allow for contents directly in columns):

_x000D_
_x000D_
.mytable {_x000D_
  display: table;_x000D_
}_x000D_
.myrow {_x000D_
  display: table-row;_x000D_
}_x000D_
.mycell {_x000D_
  display: table-cell;_x000D_
}_x000D_
.column1 {_x000D_
  display: table-column;_x000D_
  background-color: green;_x000D_
}_x000D_
.column2 {_x000D_
  display: table-column;_x000D_
}
_x000D_
<div class="mytable">_x000D_
  <div class="column1"></div>_x000D_
  <div class="column2"></div>_x000D_
  <div class="myrow">_x000D_
    <div class="mycell">contents of first cell in row 1</div>_x000D_
    <div class="mycell">contents of second cell in row 1</div>_x000D_
  </div>_x000D_
  <div class="myrow">_x000D_
    <div class="mycell">contents of first cell in row 2</div>_x000D_
    <div class="mycell">contents of second cell in row 2</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_



OPTIONAL: both "rows" and "columns" can be styled by assigning multiple classes to each row and cell as follows. This approach gives maximum flexibility in specifying various sets of cells, or individual cells, to be styled:

_x000D_
_x000D_
//Useful css declarations, depending on what you want to affect, include:_x000D_
_x000D_
/* all cells (that have "class=mycell") */_x000D_
.mycell {_x000D_
}_x000D_
_x000D_
/* class row1, wherever it is used */_x000D_
.row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 (if you've put "class=mycell" on each cell) */_x000D_
.row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 */_x000D_
.row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows */_x000D_
.cell1 {_x000D_
}_x000D_
_x000D_
/* row1 inside class mytable (so can have different tables with different styles) */_x000D_
.mytable .row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 of a mytable */_x000D_
.mytable .row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 of a mytable */_x000D_
.mytable .row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows of a mytable */_x000D_
.mytable .cell1 {_x000D_
}
_x000D_
<div class="mytable">_x000D_
  <div class="column1"></div>_x000D_
  <div class="column2"></div>_x000D_
  <div class="myrow row1">_x000D_
    <div class="mycell cell1">contents of first cell in row 1</div>_x000D_
    <div class="mycell cell2">contents of second cell in row 1</div>_x000D_
  </div>_x000D_
  <div class="myrow row2">_x000D_
    <div class="mycell cell1">contents of first cell in row 2</div>_x000D_
    <div class="mycell cell2">contents of second cell in row 2</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In today's flexible designs, which use <div> for multiple purposes, it is wise to put some class on each div, to help refer to it. Here, what used to be <tr> in HTML became class myrow, and <td> became class mycell. This convention is what makes the above CSS selectors useful.

PERFORMANCE NOTE: putting class names on each cell, and using the above multi-class selectors, is better performance than using selectors ending with *, such as .row1 * or even .row1 > *. The reason is that selectors are matched last first, so when matching elements are being sought, .row1 * first does *, which matches all elements, and then checks all the ancestors of each element, to find if any ancestor has class row1. This might be slow in a complex document on a slow device. .row1 > * is better, because only the immediate parent is examined. But it is much better still to immediately eliminate most elements, via .row1 .cell1. (.row1 > .cell1 is an even tighter spec, but it is the first step of the search that makes the biggest difference, so it usually isn't worth the clutter, and the extra thought process as to whether it will always be a direct child, of adding the child selector >.)

The key point to take away re performance is that the last item in a selector should be as specific as possible, and should never be *.

jQuery Show-Hide DIV based on Checkbox Value

`Display

$('#cbxShowHide').click(function(){ this.checked?$('#block').show(1000):$('#block').hide(1000); //time for show });`

Annotation-specified bean name conflicts with existing, non-compatible bean def

I had a similar problem, with two jar libraries (app1 and app2) in one project. The bean "BeanName" is defined in app1 and is extended in app2 and the bean redefined with the same name.

In app1:

package com.foo.app1.pkg1;

@Component("BeanName")
public class Class1 { ... }

In app2:

package com.foo.app2.pkg2;

@Component("BeanName")
public class Class2 extends Class1 { ... }

This causes the ConflictingBeanDefinitionException exception in the loading of the applicationContext due to the same component bean name.

To solve this problem, in the Spring configuration file applicationContext.xml:

    <context:component-scan base-package="com.foo.app2.pkg2"/>
    <context:component-scan base-package="com.foo.app1.pkg1">
        <context:exclude-filter type="assignable" expression="com.foo.app1.pkg1.Class1"/>
    </context:component-scan>

So the Class1 is excluded to be automatically component-scanned and assigned to a bean, avoiding the name conflict.

How many characters can a Java String have?

The heap part gets worse, my friends. UTF-16 isn't guaranteed to be limited to 16 bits and can expand to 32

Ubuntu apt-get unable to fetch packages

If you're having the issue with VirtualBox and a Virtual Machine I fixed it by changing Settings -> Network -> Attached To from NAT to Bridged Adapter

How can I get the assembly file version

UPDATE: As mentioned by Richard Grimes in my cited post, @Iain and @Dmitry Lobanov, my answer is right in theory but wrong in practice.

As I should have remembered from countless books, etc., while one sets these properties using the [assembly: XXXAttribute], they get highjacked by the compiler and placed into the VERSIONINFO resource.

For the above reason, you need to use the approach in @Xiaofu's answer as the attributes are stripped after the signal has been extracted from them.


public static string GetProductVersion()
{
  var attribute = (AssemblyVersionAttribute)Assembly
    .GetExecutingAssembly()
    .GetCustomAttributes( typeof(AssemblyVersionAttribute), true )
    .Single();
   return attribute.InformationalVersion;
}

(From http://bytes.com/groups/net/420417-assemblyversionattribute - as noted there, if you're looking for a different attribute, substitute that into the above)

search in java ArrayList

Others have pointed out the error in your existing code, but I'd like to take two steps further. Firstly, assuming you're using Java 1.5+, you can achieve greater readability using the enhanced for loop:

Customer findCustomerByid(int id){    
    for (Customer customer : customers) {
        if (customer.getId() == id) {
            return customer;
        }
    }
    return null; 
}

This has also removed the micro-optimisation of returning null before looping - I doubt that you'll get any benefit from it, and it's more code. Likewise I've removed the exists flag: returning as soon as you know the answer makes the code simpler.

Note that in your original code I think you had a bug. Having found that the customer at index i had the right ID, you then returned the customer at index id - I doubt that this is really what you intended.

Secondly, if you're going to do a lot of lookups by ID, have you considered putting your customers into a Map<Integer, Customer>?

Hiding an Excel worksheet with VBA

To hide from the UI, use Format > Sheet > Hide

To hide programatically, use the Visible property of the Worksheet object. If you do it programatically, you can set the sheet as "very hidden", which means it cannot be unhidden through the UI.

ActiveWorkbook.Sheets("Name").Visible = xlSheetVeryHidden 
' or xlSheetHidden or xlSheetVisible

You can also set the Visible property through the properties pane for the worksheet in the VBA IDE (ALT+F11).

What exactly do "u" and "r" string flags do, and what are raw string literals?

Let me explain it simply: In python 2, you can store string in 2 different types.

The first one is ASCII which is str type in python, it uses 1 byte of memory. (256 characters, will store mostly English alphabets and simple symbols)

The 2nd type is UNICODE which is unicode type in python. Unicode stores all types of languages.

By default, python will prefer str type but if you want to store string in unicode type you can put u in front of the text like u'text' or you can do this by calling unicode('text')

So u is just a short way to call a function to cast str to unicode. That's it!

Now the r part, you put it in front of the text to tell the computer that the text is raw text, backslash should not be an escaping character. r'\n' will not create a new line character. It's just plain text containing 2 characters.

If you want to convert str to unicode and also put raw text in there, use ur because ru will raise an error.

NOW, the important part:

You cannot store one backslash by using r, it's the only exception. So this code will produce error: r'\'

To store a backslash (only one) you need to use '\\'

If you want to store more than 1 characters you can still use r like r'\\' will produce 2 backslashes as you expected.

I don't know the reason why r doesn't work with one backslash storage but the reason isn't described by anyone yet. I hope that it is a bug.

tap gesture recognizer - which object was tapped?

Define your target selector(highlightLetter:) with argument as

UITapGestureRecognizer *letterTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(highlightLetter:)];

Then you can get view by

- (void)highlightLetter:(UITapGestureRecognizer*)sender {
     UIView *view = sender.view; 
     NSLog(@"%d", view.tag);//By tag, you can find out where you had tapped. 
}

How can I pass variable to ansible playbook in the command line?

Reading the docs I find the section Passing Variables On The Command Line, that gives this example:

ansible-playbook release.yml --extra-vars "version=1.23.45 other_variable=foo"

Others examples demonstrate how to load from JSON string (=1.2) or file (=1.3)

Converting a string to int in Groovy

def str = "32"

int num = str as Integer

stop service in android

onDestroyed()

is wrong name for

onDestroy()  

Did you make a mistake only in this question or in your code too?

Java Mouse Event Right Click

Yes, take a look at this thread which talks about the differences between platforms.

How to detect right-click event for Mac OS

BUTTON3 is the same across all platforms, being equal to the right mouse button. BUTTON2 is simply ignored if the middle button does not exist.

Python - Count elements in list

You can get element count of list by following two ways:

>>> l = ['a','b','c']
>>> len(l)
3

>>> l.__len__() 
3

Make footer stick to bottom of page correctly

This should help you.

* {
    margin: 0;
}
html, body {
    height: 100%;
}
.wrapper {
    min-height: 100%;
    height: auto !important;
    height: 100%;
    margin: 0 auto -155px; /* the bottom margin is the negative value of the footer's height */
}
.footer {
    height: 155px;
}

Multiple Errors Installing Visual Studio 2015 Community Edition

Make sure to check your machine.config files in both locations

C:\Windows\Microsoft.NET\Framework[version]\Config C:\Windows\Microsoft.NET\Framework64[version]\Config

I found out after trying all the solutions on this page.

How do I force a vertical scrollbar to appear?

Give your body tag an overflow: scroll;

body {
    overflow: scroll;
}

or if you only want a vertical scrollbar use overflow-y

body {
    overflow-y: scroll;
}

When I run `npm install`, it returns with `ERR! code EINTEGRITY` (npm 5.3.0)

There are several valid and helpful responses here, but I would like to add that in my case the simplest solution was:

  1. Delete package-lock.json;
  2. Remove folder AppData\Local\npm\cache or AppData\Roaming\npm\cache;
  3. Remove folder node_modules.staging;
  4. Run npm install again.

After that everything ran smoothly.

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

You always need to check for XACT_STATE(), irrelevant of the XACT_ABORT setting. I have an example of a template for stored procedures that need to handle transactions in the TRY/CATCH context at Exception handling and nested transactions:

create procedure [usp_my_procedure_name]
as
begin
    set nocount on;
    declare @trancount int;
    set @trancount = @@trancount;
    begin try
        if @trancount = 0
            begin transaction
        else
            save transaction usp_my_procedure_name;

        -- Do the actual work here

lbexit:
        if @trancount = 0   
            commit;
    end try
    begin catch
        declare @error int, @message varchar(4000), @xstate int;
        select @error = ERROR_NUMBER(),
               @message = ERROR_MESSAGE(), 
               @xstate = XACT_STATE();
        if @xstate = -1
            rollback;
        if @xstate = 1 and @trancount = 0
            rollback
        if @xstate = 1 and @trancount > 0
            rollback transaction usp_my_procedure_name;

        raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
    end catch   
end

How can I download a file from a URL and save it in Rails?

If you're using PaperClip, downloading from a URL is now handled automatically.

Assuming you've got something like:

class MyModel < ActiveRecord::Base
  has_attached_file :image, ...
end

On your model, just specify the image as a URL, something like this (written in deliberate longhand):

@my_model = MyModel.new
image_url = params[:image_url]
@my_model.image = URI.parse(image_url)

You'll probably want to put this in a method in your model. This will also work just fine on Heroku's temporary filesystem.

Paperclip will take it from there.

source: paperclip documentation

Interfaces — What's the point?

You will get interfaces, when you will need them :) You can study examples, but you need the Aha! effect to really get them.

Now that you know what interfaces are, just code without them. Sooner or later you will run into a problem, where the use of interfaces will be the most natural thing to do.

Triangle Draw Method

There is no direct method to draw a triangle. You can use drawPolygon() method for this. It takes three parameters in the following form: drawPolygon(int x[],int y[], int number_of_points); To draw a triangle: (Specify the x coordinates in array x and y coordinates in array y and number of points which will be equal to the elements of both the arrays.Like in triangle you will have 3 x coordinates and 3 y coordinates which means you have 3 points in total.) Suppose you want to draw the triangle using the following points:(100,50),(70,100),(130,100) Do the following inside public void paint(Graphics g):

int x[]={100,70,130};
int y[]={50,100,100};
g.drawPolygon(x,y,3);

Similarly you can draw any shape using as many points as you want.

In-memory size of a Python structure

I've been happily using pympler for such tasks. It's compatible with many versions of Python -- the asizeof module in particular goes back to 2.2!

For example, using hughdbrown's example but with from pympler import asizeof at the start and print asizeof.asizeof(v) at the end, I see (system Python 2.5 on MacOSX 10.5):

$ python pymp.py 
set 120
unicode 32
tuple 32
int 16
decimal 152
float 16
list 40
object 0
dict 144
str 32

Clearly there is some approximation here, but I've found it very useful for footprint analysis and tuning.

How do you do exponentiation in C?

The non-recursive version of the function is not too hard - here it is for integers:

long powi(long x, unsigned n)
{
    long p = x;
    long r = 1;

    while (n > 0)
    {
        if (n % 2 == 1)
            r *= p;
        p *= p;
        n /= 2;
    }

    return(r);
}

(Hacked out of code for raising a double value to an integer power - had to remove the code to deal with reciprocals, for example.)

How do I grab an INI value within a shell script?

one of more possible solutions

dbver=$(sed -n 's/.*database_version *= *\([^ ]*.*\)/\1/p' < parameters.ini)
echo $dbver

ValueError: not enough values to unpack (expected 11, got 1)

For the line

line.split()

What are you splitting on? Looks like a CSV, so try

line.split(',')

Example:

"one,two,three".split()  # returns one element ["one,two,three"]
"one,two,three".split(',')  # returns three elements ["one", "two", "three"]

As @TigerhawkT3 mentions, it would be better to use the CSV module. Incredibly quick and easy method available here.

What are the JavaScript KeyCodes?

Followed @pimvdb's advice, and created my own:

http://daniel-hug.github.io/characters/

Be patient, as it takes a few seconds to generate an element for each of the 65536 characters that have a JavaScript keycode.

Tried to Load Angular More Than Once

I had the same issue, The problem was the conflict between JQuery and Angular. Angular couldn't set the full JQuery library for itself. As JQLite is enough in most cases, I included Angular first in my web page and then I loaded Jquery. The error was gone then.

Can I set text box to readonly when using Html.TextBoxFor?

<%= Html.TextBoxFor(m => Model.Events.Subscribed[i].Action, new {readonly=true})%>

Maximum value of maxRequestLength?

As per MSDN the default value is 4096 KB (4 MB).

UPDATE

As for the Maximum, since it is an int data type, then theoretically you can go up to 2,147,483,647. Also I wanted to make sure that you are aware that IIS 7 uses maxAllowedContentLength for specifying file upload size. By default it is set to 30000000 around 30MB and being an uint, it should theoretically allow a max of 4,294,967,295

Parse JSON object with string and value only

You need to get a list of all the keys, loop over them and add them to your map as shown in the example below:

    String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
    JSONObject jObject  = new JSONObject(s);
    JSONObject  menu = jObject.getJSONObject("menu");

    Map<String,String> map = new HashMap<String,String>();
    Iterator iter = menu.keys();
    while(iter.hasNext()){
        String key = (String)iter.next();
        String value = menu.getString(key);
        map.put(key,value);
    }

VBA Macro On Timer style to run code every set number of seconds, i.e. 120 seconds

In Workbook events:

Private Sub Workbook_Open()
    RunEveryTwoMinutes
End Sub

In a module:

Sub RunEveryTwoMinutes()
    //Add code here for whatever you want to happen
    Application.OnTime Now + TimeValue("00:02:00"), "RunEveryTwoMinutes"
End Sub

If you only want the first piece of code to execute after the workbook opens then just add a delay of 2 minutes into the Workbook_Open event

Swift: Determine iOS Screen size

In Swift 3.0

let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

In older swift: Do something like this:

let screenSize: CGRect = UIScreen.mainScreen().bounds

then you can access the width and height like this:

let screenWidth = screenSize.width
let screenHeight = screenSize.height

if you want 75% of your screen's width you can go:

let screenWidth = screenSize.width * 0.75

Swift 4.0

// Screen width.
public var screenWidth: CGFloat {
    return UIScreen.main.bounds.width
}

// Screen height.
public var screenHeight: CGFloat {
    return UIScreen.main.bounds.height
}

In Swift 5.0

let screenSize: CGRect = UIScreen.main.bounds

Pass Multiple Parameters to jQuery ajax call

            data: JSON.stringify({ "objectnameOFcontroller": data, "Sel": $(th).val() }),

controller object name

Appending an element to the end of a list in Scala

Lists in Scala are not designed to be modified. In fact, you can't add elements to a Scala List; it's an immutable data structure, like a Java String. What you actually do when you "add an element to a list" in Scala is to create a new List from an existing List. (Source)

Instead of using lists for such use cases, I suggest to either use an ArrayBuffer or a ListBuffer. Those datastructures are designed to have new elements added.

Finally, after all your operations are done, the buffer then can be converted into a list. See the following REPL example:

scala> import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ListBuffer

scala> var fruits = new ListBuffer[String]()
fruits: scala.collection.mutable.ListBuffer[String] = ListBuffer()

scala> fruits += "Apple"
res0: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple)

scala> fruits += "Banana"
res1: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple, Banana)

scala> fruits += "Orange"
res2: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple, Banana, Orange)

scala> val fruitsList = fruits.toList
fruitsList: List[String] = List(Apple, Banana, Orange)

How to change RGB color to HSV?

The EasyRGB has many color space conversions. Here is the code for the RGB->HSV conversion.

Where/How to getIntent().getExtras() in an Android Fragment?

What I tend to do, and I believe this is what Google intended for developers to do too, is to still get the extras from an Intent in an Activity and then pass any extra data to fragments by instantiating them with arguments.

There's actually an example on the Android dev blog that illustrates this concept, and you'll see this in several of the API demos too. Although this specific example is given for API 3.0+ fragments, the same flow applies when using FragmentActivity and Fragment from the support library.

You first retrieve the intent extras as usual in your activity and pass them on as arguments to the fragment:

public static class DetailsActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // (omitted some other stuff)

        if (savedInstanceState == null) {
            // During initial setup, plug in the details fragment.
            DetailsFragment details = new DetailsFragment();
            details.setArguments(getIntent().getExtras());
            getSupportFragmentManager().beginTransaction().add(
                    android.R.id.content, details).commit();
        }
    }
}

In stead of directly invoking the constructor, it's probably easier to use a static method that plugs the arguments into the fragment for you. Such a method is often called newInstance in the examples given by Google. There actually is a newInstance method in DetailsFragment, so I'm unsure why it isn't used in the snippet above...

Anyways, all extras provided as argument upon creating the fragment, will be available by calling getArguments(). Since this returns a Bundle, its usage is similar to that of the extras in an Activity.

public static class DetailsFragment extends Fragment {
    /**
     * Create a new instance of DetailsFragment, initialized to
     * show the text at 'index'.
     */
    public static DetailsFragment newInstance(int index) {
        DetailsFragment f = new DetailsFragment();

        // Supply index input as an argument.
        Bundle args = new Bundle();
        args.putInt("index", index);
        f.setArguments(args);

        return f;
    }

    public int getShownIndex() {
        return getArguments().getInt("index", 0);
    }

    // (other stuff omitted)

}

libpng warning: iCCP: known incorrect sRGB profile

You can also just fix this in photoshop...

  1. Open your .png file.
  2. File -> Save As and in the dialog that opens up uncheck "ICC Profile: sRGB IEC61966-2.1"
  3. Uncheck "As a Copy".
  4. Courageously save over your original .png.
  5. Move on with your life knowing that you've removed just that little bit of evil from the world.

How to extract text from an existing docx file using python-docx

you can try this

import docx

def getText(filename):
    doc = docx.Document(filename)
    fullText = []
    for para in doc.paragraphs:
        fullText.append(para.text)
    return '\n'.join(fullText)

How to save data in an android app

Please don't forget one thing - Internal Storage data are deleted when you uninstall the app. In some cases it can be "unexpected feature". Then it's good to use external storage.

Google docs about storage - Please look in particular at getExternalStoragePublicDirectory

How long will my session last?

If session.cookie_lifetime is 0, the session cookie lives until the browser is quit.

EDIT: Others have mentioned the session.gc_maxlifetime setting. When session garbage collection occurs, the garbage collector will delete any session data that has not been accessed in longer than session.gc_maxlifetime seconds. To set the time-to-live for the session cookie, call session_set_cookie_params() or define the session.cookie_lifetime PHP setting. If this setting is greater than session.gc_maxlifetime, you should increase session.gc_maxlifetime to a value greater than or equal to the cookie lifetime to ensure that your sessions won't expire.

PHP: How to get referrer URL?

$_SERVER['HTTP_REFERER'] will give you the referrer page's URL if there exists any. If users use a bookmark or directly visit your site by manually typing in the URL, http_referer will be empty. Also if the users are posting to your page programatically (CURL) then they're not obliged to set the http_referer as well. You're missing all _, is that a typo?

Material Design not styling alert dialogs

UPDATED ON Aug 2019 WITH The Material components for android library:

With the new Material components for Android library you can use the new com.google.android.material.dialog.MaterialAlertDialogBuilder class, which extends from the existing androidx.appcompat.AlertDialog.Builder class and provides support for the latest Material Design specifications.

Just use something like this:

new MaterialAlertDialogBuilder(context)
            .setTitle("Dialog")
            .setMessage("Lorem ipsum dolor ....")
            .setPositiveButton("Ok", /* listener = */ null)
            .setNegativeButton("Cancel", /* listener = */ null)
            .show();

You can customize the colors extending the ThemeOverlay.MaterialComponents.MaterialAlertDialog style:

  <style name="CustomMaterialDialog" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
     <!-- Background Color-->
     <item name="android:background">#006db3</item>
     <!-- Text Color for title and message -->
     <item name="colorOnSurface">@color/secondaryColor</item>
     <!-- Text Color for buttons -->
     <item name="colorPrimary">@color/white</item> 
     ....
  </style>  

To apply your custom style just use the constructor:

new MaterialAlertDialogBuilder(context, R.style.CustomMaterialDialog)

enter image description here

To customize the buttons, the title and the body text check this post for more details.

You can also change globally the style in your app theme:

 <!-- Base application theme. -->
 <style name="AppTheme" parent="Theme.MaterialComponents.Light">
    ...
    <item name="materialAlertDialogTheme">@style/CustomMaterialDialog</item>
 </style>

WITH SUPPORT LIBRARY and APPCOMPAT THEME:

With the new AppCompat v22.1 you can use the new android.support.v7.app.AlertDialog.

Just use a code like this:

import android.support.v7.app.AlertDialog

AlertDialog.Builder builder =
       new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle);
builder.setTitle("Dialog");
builder.setMessage("Lorem ipsum dolor ....");
builder.setPositiveButton("OK", null);
builder.setNegativeButton("Cancel", null);
builder.show();

And use a style like this:

<style name="AppCompatAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
        <item name="colorAccent">#FFCC00</item>
        <item name="android:textColorPrimary">#FFFFFF</item>
        <item name="android:background">#5fa3d0</item>
    </style>

Otherwise you can define in your current theme:

<style name="AppTheme" parent="Theme.AppCompat.Light">
    <!-- your style -->
    <item name="alertDialogTheme">@style/AppCompatAlertDialogStyle</item>
</style>

and then in your code:

 import android.support.v7.app.AlertDialog

    AlertDialog.Builder builder =
           new AlertDialog.Builder(this);

Here the AlertDialog on Kitkat: enter image description here

Selected tab's color in Bottom Navigation View

If you want to change icons' and texts' colors programmatically:

ColorStateList iconsColorStates = new ColorStateList(
            new int[][]{
                    new int[]{-android.R.attr.state_checked},
                    new int[]{android.R.attr.state_checked}
            },
            new int[]{
                    Color.parseColor("#123456"),
                    Color.parseColor("#654321")
            });

    ColorStateList textColorStates = new ColorStateList(
            new int[][]{
                    new int[]{-android.R.attr.state_checked},
                    new int[]{android.R.attr.state_checked}
            },
            new int[]{
                    Color.parseColor("#123456"),
                    Color.parseColor("#654321")
            });

    navigation.setItemIconTintList(iconsColorStates);
    navigation.setItemTextColor(textColorStates);

Html.RenderPartial() syntax with Razor

Html.RenderPartial() is a void method - you can check whether a method is a void method by placing your mouse over the call to RenderPartial in your code and you will see the text (extension) void HtmlHelper.RenderPartial...

Void methods require a semicolon at the end of the calling code.

In the Webforms view engine you would have encased your Html.RenderPartial() call within the bee stings <% %>

like so

<% Html.RenderPartial("Path/to/my/partial/view"); %>

when you are using the Razor view engine the equivalent is

@{Html.RenderPartial("Path/to/my/partial/view");}

jQuery click function doesn't work after ajax call?

Since the class is added dynamically, you need to use event delegation to register the event handler like:

$('#LangTable').on('click', '.deletelanguage', function(event) {
    event.preventDefault();
    alert("success");
});

This will attach your event to any anchors within the #LangTable element, reducing the scope of having to check the whole document element tree and increasing efficiency.

FIDDLE DEMO

Detecting IE11 using CSS Capability/Feature Detection

This worked for me

if(navigator.userAgent.match(/Trident.*rv:11\./)) {
    $('body').addClass('ie11');
}

And then in the css file things prefixed with

body.ie11 #some-other-div

When is this browser ready to die?

C - error: storage size of ‘a’ isn’t known

correct typo of

struct xyz a;

to

struct xyx a;

Better you can try typedef, easy to b

How to insert values in table with foreign key using MySQL?

Case 1: Insert Row and Query Foreign Key

Here is an alternate syntax I use:

INSERT INTO tab_student 
   SET name_student = 'Bobby Tables',
       id_teacher_fk = (
       SELECT id_teacher
         FROM tab_teacher
        WHERE name_teacher = 'Dr. Smith')

I'm doing this in Excel to import a pivot table to a dimension table and a fact table in SQL so you can import to both department and expenses tables from the following:

enter image description here

Case 2: Insert Row and Then Insert Dependant Row

Luckily, MySQL supports LAST_INSERT_ID() exactly for this purpose.

INSERT INTO tab_teacher
   SET name_teacher = 'Dr. Smith';
INSERT INTO tab_student 
   SET name_student = 'Bobby Tables',
       id_teacher_fk = LAST_INSERT_ID()

How can I query a value in SQL Server XML column

if your field name is Roles and table name is table1 you can use following to search

DECLARE @Role varchar(50);
SELECT * FROM table1
WHERE Roles.exist ('/root/role = sql:variable("@Role")') = 1

How to set specific window (frame) size in java swing?

Most layout managers work best with a component's preferredSize, and most GUI's are best off allowing the components they contain to set their own preferredSizes based on their content or properties. To use these layout managers to their best advantage, do call pack() on your top level containers such as your JFrames before making them visible as this will tell these managers to do their actions -- to layout their components.

Often when I've needed to play a more direct role in setting the size of one of my components, I'll override getPreferredSize and have it return a Dimension that is larger than the super.preferredSize (or if not then it returns the super's value).

For example, here's a small drag-a-rectangle app that I created for another question on this site:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MoveRect extends JPanel {
   private static final int RECT_W = 90;
   private static final int RECT_H = 70;
   private static final int PREF_W = 600;
   private static final int PREF_H = 300;
   private static final Color DRAW_RECT_COLOR = Color.black;
   private static final Color DRAG_RECT_COLOR = new Color(180, 200, 255);
   private Rectangle rect = new Rectangle(25, 25, RECT_W, RECT_H);
   private boolean dragging = false;
   private int deltaX = 0;
   private int deltaY = 0;

   public MoveRect() {
      MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
      addMouseListener(myMouseAdapter);
      addMouseMotionListener(myMouseAdapter);
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      if (rect != null) {
         Color c = dragging ? DRAG_RECT_COLOR : DRAW_RECT_COLOR;
         g.setColor(c);
         Graphics2D g2 = (Graphics2D) g;
         g2.draw(rect);
      }
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

   private class MyMouseAdapter extends MouseAdapter {

      @Override
      public void mousePressed(MouseEvent e) {
         Point mousePoint = e.getPoint();
         if (rect.contains(mousePoint)) {
            dragging = true;
            deltaX = rect.x - mousePoint.x;
            deltaY = rect.y - mousePoint.y;
         }
      }

      @Override
      public void mouseReleased(MouseEvent e) {
         dragging = false;
         repaint();
      }

      @Override
      public void mouseDragged(MouseEvent e) {
         Point p2 = e.getPoint();
         if (dragging) {
            int x = p2.x + deltaX;
            int y = p2.y + deltaY;
            rect = new Rectangle(x, y, RECT_W, RECT_H);
            MoveRect.this.repaint();
         }
      }
   }

   private static void createAndShowGui() {
      MoveRect mainPanel = new MoveRect();

      JFrame frame = new JFrame("MoveRect");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

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

Note that my main class is a JPanel, and that I override JPanel's getPreferredSize:

public class MoveRect extends JPanel {
   //.... deleted constants

   private static final int PREF_W = 600;
   private static final int PREF_H = 300;

   //.... deleted fields and constants

   //... deleted methods and constructors

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

Also note that when I display my GUI, I place it into a JFrame, call pack(); on the JFrame, set its position, and then call setVisible(true); on my JFrame:

   private static void createAndShowGui() {
      MoveRect mainPanel = new MoveRect();

      JFrame frame = new JFrame("MoveRect");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

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

Browser Caching of CSS files

Your file will probably be cached - but it depends...

Different browsers have slightly different behaviors - most noticeably when dealing with ambiguous/limited caching headers emanating from the server. If you send a clear signal, the browsers obey, virtually all of the time.

The greatest variance by far, is in the default caching configuration of different web servers and application servers.

Some (e.g. Apache) are likely to serve known static file types with HTTP headers encouraging the browser to cache them, while other servers may send no-cache commands with every response - regardless of filetype.

...

So, first off, read some of the excellent HTTP caching tutorials out there. HTTP Caching & Cache-Busting for Content Publishers was a real eye opener for me :-)

Next install and fiddle around with Firebug and the Live HTTP Headers add-on , to find out which headers your server is actually sending.

Then read your web server docs to find out how to tweak them to perfection (or talk your sysadmin into doing it for you).

...

As to what happens when the browser is restarted, it depends on the browser and the user configuration.

As a rule of thumb, expect the browser to be more likely to check in with the server after each restart, to see if anything has changed (see If-Last-Modified and If-None-Match).

If you configure your server correctly, it should be able to return a super-short 304 Not Modified (costing very little bandwidth) and after that the browser will use the cache as normal.

How do I download a file with Angular2 or greater

Update to Hector's answer using file-saver and HttpClient for step 2:

public downloadFile(file: File): Observable<Blob> {
    return this.http.get(file.fullPath, {responseType: 'blob'})
}

535-5.7.8 Username and Password not accepted

In my case removing 2 factor authentication solves my problem.

How to switch between frames in Selenium WebDriver using Java

You can also use:

driver.switch_to.frame(0)

(0) being the first iframe on the html.

to switch back to the default content:

driver.switch_to.default_content()

How do I resolve a HTTP 414 "Request URI too long" error?

I got this error after using $.getJSON() from JQuery. I just changed to post:

data = getDataObjectByForm(form);
var jqxhr = $.post(url, data, function(){}, 'json')
    .done(function (response) {
        if (response instanceof Object)
            var json = response;
        else
            var json = $.parseJSON(response);
        // console.log(response);
        // console.log(json);
        jsonToDom(json);
        if (json.reload != undefined && json.reload)
            location.reload();
        $("body").delay(1000).css("cursor", "default");
    })
    .fail(function (jqxhr, textStatus, error) {
        var err = textStatus + ", " + error;
        console.log("Request Failed: " + err);
        alert("Fehler!");
    });

Like Operator in Entity Framework?

It is specifically mentioned in the documentation as part of Entity SQL. Are you getting an error message?

// LIKE and ESCAPE
// If an AdventureWorksEntities.Product contained a Name 
// with the value 'Down_Tube', the following query would find that 
// value.
Select value P.Name FROM AdventureWorksEntities.Product 
    as P where P.Name LIKE 'DownA_%' ESCAPE 'A'

// LIKE
Select value P.Name FROM AdventureWorksEntities.Product 
    as P where P.Name like 'BB%'

http://msdn.microsoft.com/en-us/library/bb399359.aspx

Jenkins / Hudson environment variables

1- add to your profil file".bash_profile" file

it is in "/home/your_user/" folder

vi .bash_profile

add:

export JENKINS_HOME=/apps/data/jenkins  
export PATH=$PATH:$JENKINS_HOME

==> it's the e jenkins workspace

2- If you use jetty : go to jenkins.xml file

and add :

<Arg>/apps/data/jenkins</Arg>

PySpark 2.0 The size or shape of a DataFrame

I think there is not similar function like data.shape in Spark. But I will use len(data.columns) rather than len(data.dtypes)

Setting the default active profile in Spring-boot

add --spring.profiles.active=production

Example:

java -jar file.jar --spring.profiles.active=production

Node.js res.setHeader('content-type', 'text/javascript'); pushing the response javascript as file download

Use application/javascript as content type instead of text/javascript

text/javascript is mentioned obsolete. See reference docs.

http://www.iana.org/assignments/media-types/application

Also see this question on SO.

UPDATE:

I have tried executing the code you have given and the below didn't work.

res.setHeader('content-type', 'text/javascript');
res.send(JS_Script);

This is what worked for me.

res.setHeader('content-type', 'text/javascript');
res.end(JS_Script);

As robertklep has suggested, please refer to the node http docs, there is no response.send() there.

Random float number generation

For C++, it can generate real float numbers within the range specified by dist variable

#include <random>  //If it doesnt work then use   #include <tr1/random>
#include <iostream>

using namespace std;

typedef std::tr1::ranlux64_base_01 Myeng; 
typedef std::tr1::normal_distribution<double> Mydist;

int main() { 
       Myeng eng; 
       eng.seed((unsigned int) time(NULL)); //initializing generator to January 1, 1970);
       Mydist dist(1,10); 

       dist.reset(); // discard any cached values 
       for (int i = 0; i < 10; i++)
       {
           std::cout << "a random value == " << (int)dist(eng) << std::endl; 
       }

       return (0);
}

More than 1 row in <Input type="textarea" />

Why not use the <textarea> tag?

?<textarea id="txtArea" rows="10" cols="70"></textarea>

Page unload event in asp.net

There is an event Page.Unload. At that moment page is already rendered in HTML and HTML can't be modified. Still, all page objects are available.

Java program to connect to Sql Server and running the sample query From Eclipse

Just Change the query like this:

SELECT TOP 1 * FROM [HumanResources].[Employee]

where Employee is your table name and HumanResources is your Schema name if I am not wrong.

Hope your problem will be resolved. :)

Array as session variable

Yes, PHP supports arrays as session variables. See this page for an example.

As for your second question: once you set the session variable, it will remain the same until you either change it or unset it. So if the 3rd page doesn't change the session variable, it will stay the same until the 2nd page changes it again.

how to put image in center of html page?

Hey now you can give to body background image

and set the background-position:center center;

as like this

body{
background:url('../img/some.jpg') no-repeat center center;
min-height:100%;
}

Java Minimum and Maximum values in Array

your maximum, minimum method is right

but you don't print int to console!

and... maybe better location change (maximum, minimum) methods

now (maximum, minimum) methods in the roop. it is need not.. just need one call

i suggest change this code

    for (int i = 0 ; i < array.length; i++ ) {
       int next = input.nextInt();
       // sentineil that will stop loop when 999 is entered
       if (next == 999)
       break;
       array[i] = next;
}
System.out.println("max Value : " + getMaxValue(array));
System.out.println("min Value : " + getMinValue(array));
System.out.println("These are the numbers you have entered.");
printArray(array);

continuing execution after an exception is thrown in java

If you throw the exception, the method execution will stop and the exception is thrown to the caller method. throw always interrupt the execution flow of the current method. a try/catch block is something you could write when you call a method that may throw an exception, but throwing an exception just means that method execution is terminated due to an abnormal condition, and the exception notifies the caller method of that condition.

Find this tutorial about exception and how they work - http://docs.oracle.com/javase/tutorial/essential/exceptions/

Remove sensitive files and their commits from Git history

So, It looks something like this:

git rm --cached /config/deploy.rb
echo /config/deploy.rb >> .gitignore

Remove cache for tracked file from git and add that file to .gitignore list

How to load an ImageView by URL in Android?

Hi I have the most easiest code try this

    public class ImageFromUrlExample extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);  
            ImageView imgView =(ImageView)findViewById(R.id.ImageView01);
            Drawable drawable = LoadImageFromWebOperations("http://www.androidpeople.com/wp-content/uploads/2010/03/android.png");
            imgView.setImageDrawable(drawable);

    }

    private Drawable LoadImageFromWebOperations(String url)
    {
          try{
        InputStream is = (InputStream) new URL(url).getContent();
        Drawable d = Drawable.createFromStream(is, "src name");
        return d;
      }catch (Exception e) {
        System.out.println("Exc="+e);
        return null;
      }
    }
   }

main.xml

  <LinearLayout 
    android:id="@+id/LinearLayout01"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
   <ImageView 
       android:id="@+id/ImageView01"
       android:layout_height="wrap_content" 
       android:layout_width="wrap_content"/>

try this

Change remote repository credentials (authentication) on Intellij IDEA 14

This worked for me on Intellij 12:

Open settings -> passwords, select "Do not remember passwords" and apply/ok.

Do your VCS fetch/update/push/whatever and it should ask you for a password.

Check remember password and OK, it should do the VCS thing correctly.

Go back to settings -> passwords and switch it back to "Remember on disk", then apply/ok.

Refused to execute script, strict MIME type checking is enabled?

After searching for a while I realized that this error in my Windows 10 64 bits was related to JavaScript. In order to see this go to your browser DevTools and confirm that first. In my case it shows an error like "MIME type ('application/javascript') is not executable".

If that is the case I've found a solution. Here's the deal:

  1. Borrowing user "ilango100" on https://github.com/jupyterlab/jupyterlab/issues/6098:

I had the exact same issue a while ago. I think this issue is specific to Windows. It is due to the wrong MIME type being set in Windows registry for javascript files. I solved the issue by editing the Windows registry with correct content type:

regedit -> HKEY_LOCAL_MACHINE\Software\Classes -> You will see lot of folders for each file extension -> Just scroll down to ".js" registry and select it -> On the right, if the "Content Type" value is other than application/javascript, then this is causing the problem. Right click on Content Type and change the value to application/javascript

enter image description here

Try again in the browser."

After that I've realized that the error changes. It doesn't even open automatically in the browser anymore. PGAdmin, however, will be open on the side bar (close to the calendar/clock). By trying to open in the browser directly ("New PGAdmin 4 window...") it doesn't work either.

FINAL SOLUTION: click on "Copy server URL" and paste it on your browser. It worked for me!

EDIT: Copying server URL might not be necessary, as explained by Eric Mutta in the comment below.

In jQuery, what's the best way of formatting a number to 2 decimal places?

Maybe something like this, where you could select more than one element if you'd like?

$("#number").each(function(){
    $(this).val(parseFloat($(this).val()).toFixed(2));
});

What's the bad magic number error?

Don't delete them!!! Until..........

Find a version on your git, svn or copy folder that works.

Delete them and then recover all .pyc.

That's work for me.

Hibernate: ids for this class must be manually assigned before calling save()

your id attribute is not set. this MAY be due to the fact that the DB field is not set to auto increment? what DB are you using? MySQL? is your field set to AUTO INCREMENT?