Programs & Examples On #Texmaker

For questions related to programming issues in the TexMaker crossplatform Latex editor.

Confirmation before closing of tab/browser

I read comments on answer set as Okay. Most of the user are asking that the button and some links click should be allowed. Here one more line is added to the existing code that will work.

<script type="text/javascript">
  var hook = true;
  window.onbeforeunload = function() {
    if (hook) {

      return "Did you save your stuff?"
    }
  }
  function unhook() {
    hook=false;
  }

Call unhook() onClick for button and links which you want to allow. E.g.

<a href="#" onClick="unhook()">This link will allow navigation</a>

Install psycopg2 on Ubuntu

This works for me in Ubuntu 12.04 and 15.10

if pip not installed:

sudo apt-get install python-pip

and then:

sudo apt-get update
sudo apt-get install libpq-dev python-dev
sudo pip install psycopg2

Max length for client ip address

If you are just storing it for reference, you can store it as a string, but if you want to do a lookup, for example, to see if the IP address is in some table, you need a "canonical representation." Converting the entire thing to a (large) number is the right thing to do. IPv4 addresses can be stored as a long int (32 bits) but you need a 128 bit number to store an IPv6 address.

For example, all these strings are really the same IP address: 127.0.0.1, 127.000.000.001, ::1, 0:0:0:0:0:0:0:1

How do I set a JLabel's background color?

Use

label.setOpaque(true);

Otherwise the background is not painted, since the default of opaque is false for JLabel.

From the JavaDocs:

If true the component paints every pixel within its bounds. Otherwise, the component may not paint some or all of its pixels, allowing the underlying pixels to show through.

For more information, read the Java Tutorial How to Use Labels.

How to use comparison operators like >, =, < on BigDecimal

Use the compareTo method of BigDecimal :

public int compareTo(BigDecimal val) Compares this BigDecimal with the specified BigDecimal.

Returns:
-1, 0, or 1 as this BigDecimal is numerically less than, equal to, or greater than val.

Logging framework incompatibility

SLF4J 1.5.11 and 1.6.0 versions are not compatible (see compatibility report) because the argument list of org.slf4j.spi.LocationAwareLogger.log method has been changed (added Object[] p5):

SLF4J 1.5.11:

LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
                          String p4, Throwable p5 )

SLF4J 1.6.0:

LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
                          String p4, Object[] p5, Throwable p6 )

See compatibility reports for other SLF4J versions on this page.

You can generate such reports by the japi-compliance-checker tool.

enter image description here

Javascript swap array elements

If need swap first and last elements only:

array.unshift( array.pop() );

Downloading and unzipping a .zip file without writing to disk

I'd like to offer an updated Python 3 version of Vishal's excellent answer, which was using Python 2, along with some explanation of the adaptations / changes, which may have been already mentioned.

from io import BytesIO
from zipfile import ZipFile
import urllib.request
    
url = urllib.request.urlopen("http://www.unece.org/fileadmin/DAM/cefact/locode/loc162txt.zip")

with ZipFile(BytesIO(url.read())) as my_zip_file:
    for contained_file in my_zip_file.namelist():
        # with open(("unzipped_and_read_" + contained_file + ".file"), "wb") as output:
        for line in my_zip_file.open(contained_file).readlines():
            print(line)
            # output.write(line)

Necessary changes:

  • There's no StringIO module in Python 3 (it's been moved to io.StringIO). Instead, I use io.BytesIO]2, because we will be handling a bytestream -- Docs, also this thread.
  • urlopen:

Note:

  • In Python 3, the printed output lines will look like so: b'some text'. This is expected, as they aren't strings - remember, we're reading a bytestream. Have a look at Dan04's excellent answer.

A few minor changes I made:

  • I use with ... as instead of zipfile = ... according to the Docs.
  • The script now uses .namelist() to cycle through all the files in the zip and print their contents.
  • I moved the creation of the ZipFile object into the with statement, although I'm not sure if that's better.
  • I added (and commented out) an option to write the bytestream to file (per file in the zip), in response to NumenorForLife's comment; it adds "unzipped_and_read_" to the beginning of the filename and a ".file" extension (I prefer not to use ".txt" for files with bytestrings). The indenting of the code will, of course, need to be adjusted if you want to use it.
    • Need to be careful here -- because we have a byte string, we use binary mode, so "wb"; I have a feeling that writing binary opens a can of worms anyway...
  • I am using an example file, the UN/LOCODE text archive:

What I didn't do:

  • NumenorForLife asked about saving the zip to disk. I'm not sure what he meant by it -- downloading the zip file? That's a different task; see Oleh Prypin's excellent answer.

Here's a way:

import urllib.request
import shutil

with urllib.request.urlopen("http://www.unece.org/fileadmin/DAM/cefact/locode/2015-2_UNLOCODE_SecretariatNotes.pdf") as response, open("downloaded_file.pdf", 'w') as out_file:
    shutil.copyfileobj(response, out_file)

How can I convert this one line of ActionScript to C#?

There is collection of Func<...> classes - Func that is probably what you are looking for:

 void MyMethod(Func<int> param1 = null) 

This defines method that have parameter param1 with default value null (similar to AS), and a function that returns int. Unlike AS in C# you need to specify type of the function's arguments.

So if you AS usage was

MyMethod(function(intArg, stringArg) { return true; }) 

Than in C# it would require param1 to be of type Func<int, siring, bool> and usage like

MyMethod( (intArg, stringArg) => { return true;} ); 

Escaping Double Quotes in Batch Script

As an addition to mklement0's excellent answer:

Almost all executables accept \" as an escaped ". Safe usage in cmd however is almost only possible using DELAYEDEXPANSION.
To explicitely send a literal " to some process, assign \" to an environment variable, and then use that variable, whenever you need to pass a quote. Example:

SETLOCAL ENABLEDELAYEDEXPANSION
set q=\"
child "malicious argument!q!&whoami"

Note SETLOCAL ENABLEDELAYEDEXPANSION seems to work only within batch files. To get DELAYEDEXPANSION in an interactive session, start cmd /V:ON.

If your batchfile does't work with DELAYEDEXPANSION, you can enable it temporarily:

::region without DELAYEDEXPANSION

SETLOCAL ENABLEDELAYEDEXPANSION
::region with DELAYEDEXPANSION
set q=\"
echoarg.exe "ab !q! & echo danger"
ENDLOCAL

::region without DELAYEDEXPANSION

If you want to pass dynamic content from a variable that contains quotes that are escaped as "" you can replace "" with \" on expansion:

SETLOCAL ENABLEDELAYEDEXPANSION
foo.exe "danger & bar=region with !dynamic_content:""=\"! & danger"
ENDLOCAL

This replacement is not safe with %...% style expansion!

In case of OP bash -c "g++-linux-4.1 !v_params:"=\"!" is the safe version.


If for some reason even temporarily enabling DELAYEDEXPANSION is not an option, read on:

Using \" from within cmd is a little bit safer if one always needs to escape special characters, instead of just sometimes. (It's less likely to forget a caret, if it's consistent...)

To achieve this, one precedes any quote with a caret (^"), quotes that should reach the child process as literals must additionally be escaped with a backlash (\^"). ALL shell meta characters must be escaped with ^ as well, e.g. & => ^&; | => ^|; > => ^>; etc.

Example:

child ^"malicious argument\^"^&whoami^"

Source: Everyone quotes command line arguments the wrong way, see "A better method of quoting"


To pass dynamic content, one needs to ensure the following:
The part of the command that contains the variable must be considered "quoted" by cmd.exe (This is impossible if the variable can contain quotes - don't write %var:""=\"%). To achieve this, the last " before the variable and the first " after the variable are not ^-escaped. cmd-metacharacters between those two " must not be escaped. Example:

foo.exe ^"danger ^& bar=\"region with %dynamic_content% & danger\"^"

This isn't safe, if %dynamic_content% can contain unmatched quotes.

Split pandas dataframe in two if it has more than 10 rows

The method based on list comprehension and groupby, which stores all the split dataframes in a list variable and can be accessed using the index.

Example:

ans = [pd.DataFrame(y) for x, y in DF.groupby('column_name', as_index=False)]***
ans[0]
ans[0].column_name

changing the language of error message in required field in html5 contact form

<input type="text" id="inputName"  placeholder="Enter name"  required  oninvalid="this.setCustomValidity('Your Message')" oninput="this.setCustomValidity('') />

this can help you even more better, Fast, Convenient & Easiest.

How do I check CPU and Memory Usage in Java?

If you are using Tomcat, check out Psi Probe, which lets you monitor internal and external memory consumption as well as a host of other areas.

using wildcards in LDAP search filters/queries

A filter argument with a trailing * can be evaluated almost instantaneously via an index lookup. A leading * implies a sequential search through the index, so it is O(N). It will take ages.

I suggest you reconsider the requirement.

What does -z mean in Bash?

The expression -z string is true if the length of string is zero.

python convert list to dictionary

Using the usual grouper recipe, you could do:

Python 2:

d = dict(itertools.izip_longest(*[iter(l)] * 2, fillvalue=""))

Python 3:

d = dict(itertools.zip_longest(*[iter(l)] * 2, fillvalue=""))

How do you convert a C++ string to an int?

Let me add my vote for boost::lexical_cast

#include <boost/lexical_cast.hpp>

int val = boost::lexical_cast<int>(strval) ;

It throws bad_lexical_cast on error.

How do I join two lists in Java?

I can't improve on the two-liner in the general case without introducing your own utility method, but if you do have lists of Strings and you're willing to assume those Strings don't contain commas, you can pull this long one-liner:

List<String> newList = new ArrayList<String>(Arrays.asList((listOne.toString().subString(1, listOne.length() - 1) + ", " + listTwo.toString().subString(1, listTwo.length() - 1)).split(", ")));

If you drop the generics, this should be JDK 1.4 compliant (though I haven't tested that). Also not recommended for production code ;-)

How to show image using ImageView in Android

shoud be @drawable/image where image could have any extension like: image.png, image.xml, image.gif. Android will automatically create a reference in R class with its name, so you cannot have in any drawable folder image.png and image.gif.

How to change default format at created_at and updated_at value laravel

Laravel 4.x and 5.0

To change the time in the database use: http://laravel.com/docs/4.2/eloquent#timestamps

Providing A Custom Timestamp Format

If you wish to customize the format of your timestamps, you may override the getDateFormat method in your model:

class User extends Eloquent {

    protected function getDateFormat()
    {
        return 'U';
    }

}

Laravel 5.1+

https://laravel.com/docs/5.1/eloquent

If you need to customize the format of your timestamps, set the $dateFormat property on your model. This property determines how date attributes are stored in the database, as well as their format when the model is serialized to an array or JSON:

class Flight extends Model
{
    /**
     * The storage format of the model's date columns.
     *
     * @var string
     */
    protected $dateFormat = 'U';
}

Fragments within Fragments

Nested fragments are supported in android 4.2 and later

The Android Support Library also now supports nested fragments, so you can implement nested fragment designs on Android 1.6 and higher.

To nest a fragment, simply call getChildFragmentManager() on the Fragment in which you want to add a fragment. This returns a FragmentManager that you can use like you normally do from the top-level activity to create fragment transactions. For example, here’s some code that adds a fragment from within an existing Fragment class:

Fragment videoFragment = new VideoPlayerFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.video_fragment, videoFragment).commit();

To get more idea about nested fragments, please go through these tutorials
Part 1
Part 2
Part 3

and here is a SO post which discuss about best practices for nested fragments.

Resizing UITableView to fit content

In case your contentSize is not correct this is because it is based on the estimatedRowHeight (automatic), use this before

tableView.estimatedRowHeight = 0;

source : https://forums.developer.apple.com/thread/81895

Why can't I set text to an Android TextView?

The code should instead be something like this:

TextView text = (TextView) findViewById(R.id.this_is_the_id_of_textview);
text.setText("test");

How to use Switch in SQL Server

    select 
       @selectoneCount = case @Temp
       when 1 then (@selectoneCount+1)
       when 2 then (@selectoneCount+1)
       end

   select  @selectoneCount 

React - How to get parameter value from query string?

export class ClassName extends Component{
      constructor(props){
        super(props);
        this.state = {
          id:parseInt(props.match.params.id,10)
        }
    }
     render(){
        return(
          //Code
          {this.state.id}
        );
}

how to place last div into right top corner of parent div? (css)

 <div class='block1'>
    <p  style="float:left">text</p>
    <div class='block2' style="float:right">block2</div>
    <p  style="float:left; clear:left">text2</p>

 </div>

You can clear:both or clear:left depending on the exact context. Also, you will have to play around with width to get it to work correctly...

Centering the image in Bootstrap

Use This as the solution

This worked for me perfectly..

<div align="center">
   <img src="">
</div>

How to run only one task in ansible playbook?

See my answer here: Run only one task and handler from ansible playbook

It is possible to run separate role (from roles/ dir):

ansible -i stage.yml -m include_role -a name=create-os-user localhost

and separate task file:

ansible -i stage.yml -m include_tasks -a file=tasks/create-os-user.yml localhost

If you externalize tasks from role to root tasks/ directory (reuse is achieved by import_tasks: ../../../tasks/create-os-user.yml) you can run it independently from playbook/role.

Convert char array to string use C

You're saying you have this:

char array[20]; char string[100];
array[0]='1'; 
array[1]='7'; 
array[2]='8'; 
array[3]='.'; 
array[4]='9';

And you'd like to have this:

string[0]= "178.9"; // where it was stored 178.9 ....in position [0]

You can't have that. A char holds 1 character. That's it. A "string" in C is an array of characters followed by a sentinel character (NULL terminator).

Now if you want to copy the first x characters out of array to string you can do that with memcpy():

memcpy(string, array, x);
string[x] = '\0'; 

How to align two elements on the same line without changing HTML

In cases where I use floated elements like that, I usually need to be sure that the container element will always be big enough for the widths of both floated elements plus the desired margin to all fit inside of it. The easiest way to do that is obviously to give both inner elements fixed widths that will fit correctly inside of the outer element like this:

#container {width: 960px;}
#element1  {float:left; width:745px; margin-right:15px;}
#element2  {float:right; width:200px;}

If you can't do that because this is a scaling width layout, another option is to have every set of dimensions be percentages like:

#element1 {float:left; width:70%; margin-right:10%}
#element2 {float:right; width:20%;}

This gets tricky where you need something like this:

#element1 {float:left; width:70%; margin-right:10%}
#element2 {float:right; width:200px;}

In cases like that, I find that sometimes the best option is to not use floats, and use relative/absolute positioning to get the same effect like this:

#container {position:relative;} /* So IE won't bork the absolute positioning of #element2 */
#element1 {margin-right:215px;}
#element2 {display: block; position:absolute; top:0; right:0; height:100%; width:200px;}

While this isn't a floated solution, it does result in side by side columns where they are the same height, and one can remain fluid with while the other has a static width.

Concatenate text files with Windows command line, dropping leading lines

Use the FOR command to echo a file line by line, and with the 'skip' option to miss a number of starting lines...

FOR /F "skip=1" %i in (file2.txt) do @echo %i

You could redirect the output of a batch file, containing something like...

FOR /F %%i in (file1.txt) do @echo %%i
FOR /F "skip=1" %%i in (file2.txt) do @echo %%i

Note the double % when a FOR variable is used within a batch file.

How to merge two sorted arrays into a sorted array?

Here is updated function. It removes duplicates, hopefully someone will find this usable:

public static long[] merge2SortedAndRemoveDublicates(long[] a, long[] b) {
    long[] answer = new long[a.length + b.length];
    int i = 0, j = 0, k = 0;
    long tmp;
    while (i < a.length && j < b.length) {
        tmp = a[i] < b[j] ? a[i++] : b[j++];
        for ( ; i < a.length && a[i] == tmp; i++);
        for ( ; j < b.length && b[j] == tmp; j++);
        answer[k++] = tmp;
    }
    while (i < a.length) {
        tmp = a[i++];
        for ( ; i < a.length && a[i] == tmp; i++);
        answer[k++] = tmp;
    }
    while (j < b.length) {
        tmp = b[j++];
        for ( ; j < b.length && b[j] == tmp; j++);
        answer[k++] = tmp;
    }
    return Arrays.copyOf(answer, k);
}

How to stretch a table over multiple pages

You should \usepackage{longtable}.

Initialize class fields in constructor or at declaration?

Being consistent is important, but this is the question to ask yourself: "Do I have a constructor for anything else?"

Typically, I am creating models for data transfers that the class itself does nothing except work as housing for variables.

In these scenarios, I usually don't have any methods or constructors. It would feel silly to me to create a constructor for the exclusive purpose of initializing my lists, especially since I can initialize them in-line with the declaration.

So as many others have said, it depends on your usage. Keep it simple, and don't make anything extra that you don't have to.

LIKE vs CONTAINS on SQL Server

I think that CONTAINS took longer and used Merge because you had a dash("-") in your query adventure-works.com.

The dash is a break word so the CONTAINS searched the full-text index for adventure and than it searched for works.com and merged the results.

Get HTML source of WebElement in Selenium WebDriver using Python

The other answers provide a lot of details about retrieving the markup of a WebElement. However, an important aspect is, modern websites are increasingly implementing JavaScript, ReactJS, jQuery, Ajax, Vue.js, Ember.js, GWT, etc. to render the dynamic elements within the DOM tree. Hence there is a necessity to wait for the element and its children to completely render before retrieving the markup.


Python

Hence, ideally you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using get_attribute("outerHTML"):

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#my-id")))
    print(element.get_attribute("outerHTML"))
    
  • Using execute_script():

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#my-id")))
    print(driver.execute_script("return arguments[0].outerHTML;", element))
    
  • Note: You have to add the following imports:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

Using awk to print all columns from the nth to the last

There's a duplicate question with a simpler answer using cut:

 svn status |  grep '\!' | cut -d\  -f2-

-d specifies the delimeter (space), -f specifies the list of columns (all starting with the 2nd)

How to check if a file exists in the Documents directory in Swift?

An alternative/recommended Code Pattern in Swift 3 would be:

  1. Use URL instead of FileManager
  2. Use of exception handling

    func verifyIfSqliteDBExists(){
        let docsDir     : URL       = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let dbPath      : URL       = docsDir.appendingPathComponent("database.sqlite")
    
        do{
            let sqliteExists : Bool = try dbPath.checkResourceIsReachable()
            print("An sqlite database exists at this path :: \(dbPath.path)")
    
        }catch{
            print("SQLite NOT Found at :: \(strDBPath)")
        }
    }
    

Detect if the device is iPhone X

To detect any of the devices by using simple methods. like below,

func isPhoneDevice() -> Bool {
    return UIDevice.current.userInterfaceIdiom == .phone
}

func isDeviceIPad() -> Bool {
    return UIDevice.current.userInterfaceIdiom == .pad
}

func isPadProDevice() -> Bool {
    let SCREEN_WIDTH: CGFloat = UIScreen.main.bounds.size.width
    let SCREEN_HEIGHT: CGFloat = UIScreen.main.bounds.size.height
    let SCREEN_MAX_LENGTH: CGFloat = fmax(SCREEN_WIDTH, SCREEN_HEIGHT)

    return UIDevice.current.userInterfaceIdiom == .pad && SCREEN_MAX_LENGTH == 1366.0
}

func isPhoneXandXSDevice() -> Bool {
    let SCREEN_WIDTH = CGFloat(UIScreen.main.bounds.size.width)
    let SCREEN_HEIGHT = CGFloat(UIScreen.main.bounds.size.height)
    let SCREEN_MAX_LENGTH: CGFloat = fmax(SCREEN_WIDTH, SCREEN_HEIGHT)

    return UIDevice.current.userInterfaceIdiom == .phone && SCREEN_MAX_LENGTH == 812.0
}

func isPhoneXSMaxandXRDevice() -> Bool {
    let SCREEN_WIDTH = CGFloat(UIScreen.main.bounds.size.width)
    let SCREEN_HEIGHT = CGFloat(UIScreen.main.bounds.size.height)
    let SCREEN_MAX_LENGTH: CGFloat = fmax(SCREEN_WIDTH, SCREEN_HEIGHT)

    return UIDevice.current.userInterfaceIdiom == .phone && SCREEN_MAX_LENGTH == 896.0
}

and call like this,

if isPhoneDevice() {
     // Your code
}

How to restore/reset npm configuration to default values?

Config is written to .npmrc files so just delete it. NPM looks up config in this order, setting in the next overwrites the previous one. So make sure there might be global config that usually is overwritten in per-project that becomes active after you have deleted the per-project config file. npm config list will allways list the active config.

  1. npm builtin config file (/path/to/npm/npmrc)
  2. global config file ($PREFIX/etc/npmrc)
  3. per-user config file ($HOME/.npmrc)
  4. per-project config file (/path/to/my/project/.npmrc)

what do these symbolic strings mean: %02d %01d?

http://www.cplusplus.com/reference/clibrary/cstdio/printf/

the same rules should apply to Java.

in your case it means output of integer values in 2 or more digits, the first being zero if number less than or equal to 9

single line comment in HTML

No, you have to close the comment with -->.

Java client certificates over HTTPS/SSL

While not recommended, you can also disable SSL cert validation alltogether:

import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

public class SSLTool {

  public static void disableCertificateValidation() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { 
      new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() { 
          return new X509Certificate[0]; 
        }
        public void checkClientTrusted(X509Certificate[] certs, String authType) {}
        public void checkServerTrusted(X509Certificate[] certs, String authType) {}
    }};

    // Ignore differences between given hostname and certificate hostname
    HostnameVerifier hv = new HostnameVerifier() {
      public boolean verify(String hostname, SSLSession session) { return true; }
    };

    // Install the all-trusting trust manager
    try {
      SSLContext sc = SSLContext.getInstance("SSL");
      sc.init(null, trustAllCerts, new SecureRandom());
      HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
      HttpsURLConnection.setDefaultHostnameVerifier(hv);
    } catch (Exception e) {}
  }
}

Laravel migration: unique key is too long, even if specified

for laravel 5.7 write these code in appserviceprovider.php

  use Illuminate\Support\Facades\Schema;

public function boot()
{
  Schema::defaultStringLength(191);
}

Variables declared outside function

The local names for a function are decided when the function is defined:

>>> x = 1
>>> def inc():
...     x += 5
...     
>>> inc.__code__.co_varnames
('x',)

In this case, x exists in the local namespace. Execution of x += 5 requires a pre-existing value for x (for integers, it's like x = x + 5), and this fails at function call time because the local name is unbound - which is precisely why the exception UnboundLocalError is named as such.

Compare the other version, where x is not a local variable, so it can be resolved at the global scope instead:

>>> def incg():
...    print(x)
...    
>>> incg.__code__.co_varnames
()

Similar question in faq: http://docs.python.org/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value

MySQL : ERROR 1215 (HY000): Cannot add foreign key constraint

In my case charset, datatype every thing was correct. After investigation I found that in parent table there was no index on foreign key column. Once added problem got solved.

enter image description here

DataTables warning: Requested unknown parameter '0' from the data source for row '0'

In my weird scenario, I had a different column that didn't always return a value in the 'render' function. return null solved my issue.

Resolving ORA-4031 "unable to allocate x bytes of shared memory"

The following are not needed as they they not fix the error:

  1. ps -ef|grep oracle
  2. Find the smon and kill the pid for it
  3. SQL> startup mount
  4. SQL> create pfile from spfile;

Restarting the database will flush your pool and that solves a effect not the problem.

Fixate your large_pool so it can not go lower then a certain point or add memory and set a higher max memory.

Does Java have a path joining method?

This is a start, I don't think it works exactly as you intend, but it at least produces a consistent result.

import java.io.File;

public class Main
{
    public static void main(final String[] argv)
        throws Exception
    {
        System.out.println(pathJoin());
        System.out.println(pathJoin(""));
        System.out.println(pathJoin("a"));
        System.out.println(pathJoin("a", "b"));
        System.out.println(pathJoin("a", "b", "c"));
        System.out.println(pathJoin("a", "b", "", "def"));
    }

    public static String pathJoin(final String ... pathElements)
    {
        final String path;

        if(pathElements == null || pathElements.length == 0)
        {
            path = File.separator;
        }
        else
        {
            final StringBuilder builder;

            builder = new StringBuilder();

            for(final String pathElement : pathElements)
            {
                final String sanitizedPathElement;

                // the "\\" is for Windows... you will need to come up with the 
                // appropriate regex for this to be portable
                sanitizedPathElement = pathElement.replaceAll("\\" + File.separator, "");

                if(sanitizedPathElement.length() > 0)
                {
                    builder.append(sanitizedPathElement);
                    builder.append(File.separator);
                }
            }

            path = builder.toString();
        }

        return (path);
    }
}

Deprecated: mysql_connect()

Warning "deprecated" in general means that you are trying to use function that is outdated. It doeasnt mean thaqt your code wont work, but you should consider refactoring.

In your case functons mysql_ are deprecated. If you want to know more about that here is good explanation already : Why shouldn't I use mysql_* functions in PHP?

How can I count the number of children?

What if you are using this to determine the current selector to find its children so this holds: <ol> then there is <li>s under how to write a selector var count = $(this+"> li").length; wont work..

How do I POST XML data with curl

-H "text/xml" isn't a valid header. You need to provide the full header:

-H "Content-Type: text/xml" 

Opacity of background-color, but not the text

Use rgba!

.alpha60 {
    /* Fallback for web browsers that don't support RGBa */
    background-color: rgb(0, 0, 0);
    /* RGBa with 0.6 opacity */
    background-color: rgba(0, 0, 0, 0.6);
    /* For IE 5.5 - 7*/
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);
    /* For IE 8*/
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";
}

In addition to this, you have to declare background: transparent for IE web browsers, preferably served via conditional comments or similar!

via http://robertnyman.com/2010/01/11/css-background-transparency-without-affecting-child-elements-through-rgba-and-filters/

Draw a connecting line between two elements

VisJS supports this with its Arrows example, that supports draggable elements.

It also supports editable connections, with its Interaction Events example.

Is it possible to make abstract classes in Python?

Most of the answers inherit the base class to define the abstract methods. But this is not always useful. What if you want to define an abstract method at runtime?

For example in java we can do this

class UserClass { ...

BaseClass f = new BaseClass() {
    public void method() {
        system.out.println( "this is a test" )
    }
};

}

So what to do if we need to implement that, so in that case

class BaseClass:

    def __init__(self, func ):
        self.function = func

    def abstract_function(self ):
        if not self.function:
            raise NotImplementedError("function not implemented") 
        else:
            return self.function()

    def run(self ):
        self.abstract_function()

def func():
    print('this is a test')

bc = BaseClass( func )
bc.run()

should work

How to get system time in Java without creating a new Date

As jzd says, you can use System.currentTimeMillis. If you need it in a Date object but don't want to create a new Date object, you can use Date.setTime to reuse an existing Date object. Personally I hate the fact that Date is mutable, but maybe it's useful to you in this particular case. Similarly, Calendar has a setTimeInMillis method.

If possible though, it would probably be better just to keep it as a long. If you only need a timestamp, effectively, then that would be the best approach.

MySql difference between two timestamps in days?

I know is quite old, but I'll say just for the sake of it - I was looking for the same problem and got here, but I needed the difference in days.

I used SELECT (UNIX_TIMESTAMP(DATE1) - UNIX_TIMESTAMP(DATE2))/60/60/24 Unix_timestamp returns the difference in seconds, and then I just divide into minutes(seconds/60), hours(minutes/60), days(hours/24).

Returning an array using C

C's treatment of arrays is very different from Java's, and you'll have to adjust your thinking accordingly. Arrays in C are not first-class objects (that is, an array expression does not retain it's "array-ness" in most contexts). In C, an expression of type "N-element array of T" will be implicitly converted ("decay") to an expression of type "pointer to T", except when the array expression is an operand of the sizeof or unary & operators, or if the array expression is a string literal being used to initialize another array in a declaration.

Among other things, this means that you cannot pass an array expression to a function and have it received as an array type; the function actually receives a pointer type:

void foo(char *a, size_t asize)
{
  // do something with a
}

int bar(void)
{
  char str[6] = "Hello";
  foo(str, sizeof str);
}

In the call to foo, the expression str is converted from type char [6] to char *, which is why the first parameter of foo is declared char *a instead of char a[6]. In sizeof str, since the array expression is an operand of the sizeof operator, it's not converted to a pointer type, so you get the number of bytes in the array (6).

If you're really interested, you can read Dennis Ritchie's The Development of the C Language to understand where this treatment comes from.

The upshot is that functions cannot return array types, which is fine since array expressions cannot be the target of an assignment, either.

The safest method is for the caller to define the array, and pass its address and size to the function that's supposed to write to it:

void returnArray(const char *srcArray, size_t srcSize, char *dstArray, char dstSize)
{
  ...
  dstArray[i] = some_value_derived_from(srcArray[i]);
  ...
}

int main(void)
{
  char src[] = "This is a test";
  char dst[sizeof src];
  ...
  returnArray(src, sizeof src, dst, sizeof dst);
  ...
}

Another method is for the function to allocate the array dynamically and return the pointer and size:

char *returnArray(const char *srcArray, size_t srcSize, size_t *dstSize)
{
  char *dstArray = malloc(srcSize);
  if (dstArray)
  {
    *dstSize = srcSize;
    ...
  }
  return dstArray;
}

int main(void)
{
  char src[] = "This is a test";
  char *dst;
  size_t dstSize;

  dst = returnArray(src, sizeof src, &dstSize);
  ...
  free(dst);
  ...
}

In this case, the caller is responsible for deallocating the array with the free library function.

Note that dst in the above code is a simple pointer to char, not a pointer to an array of char. C's pointer and array semantics are such that you can apply the subscript operator [] to either an expression of array type or pointer type; both src[i] and dst[i] will access the i'th element of the array (even though only src has array type).

You can declare a pointer to an N-element array of T and do something similar:

char (*returnArray(const char *srcArr, size_t srcSize))[SOME_SIZE]
{
  char (*dstArr)[SOME_SIZE] = malloc(sizeof *dstArr);
  if (dstArr)
  {
    ...
    (*dstArr)[i] = ...;
    ...
  }
  return dstArr;
}

int main(void)
{
  char src[] = "This is a test";
  char (*dst)[SOME_SIZE];
  ...
  dst = returnArray(src, sizeof src);
  ...
  printf("%c", (*dst)[j]);
  ...
}

Several drawbacks with the above. First of all, older versions of C expect SOME_SIZE to be a compile-time constant, meaning that function will only ever work with one array size. Secondly, you have to dereference the pointer before applying the subscript, which clutters the code. Pointers to arrays work better when you're dealing with multi-dimensional arrays.

Finding the mode of a list

For a number to be a mode, it must occur more number of times than at least one other number in the list, and it must not be the only number in the list. So, I refactored @mathwizurd's answer (to use the difference method) as follows:

def mode(array):
    '''
    returns a set containing valid modes
    returns a message if no valid mode exists
      - when all numbers occur the same number of times
      - when only one number occurs in the list 
      - when no number occurs in the list 
    '''
    most = max(map(array.count, array)) if array else None
    mset = set(filter(lambda x: array.count(x) == most, array))
    return mset if set(array) - mset else "list does not have a mode!" 

These tests pass successfully:

mode([]) == None 
mode([1]) == None
mode([1, 1]) == None 
mode([1, 1, 2, 2]) == None 

Get the second highest value in a MySQL table

The simple solution is as given below in query:

select max(salary) as salary from employees where salary<(select max(salary) from employees);

How can I change the version of npm using nvm?

Changing npm versions on linux based OSs isn't a straight forward one command process yet. I have done following to switch back to older version of npm. This should work to get any version of npm working. First install the version of npm you want to use:

sudo npm install -g [email protected]

Remove the sym link in /usr/local/bin/

sudo rm /usr/local/bin/npm

Recreate the sym link using the desired version of npm you have installed

sudo ln -s /usr/bin/[email protected] /usr/local/bin/npm

Initializing IEnumerable<string> In C#

IEnumerable is an interface, instead of looking for how to create an interface instance, create an implementation that matches the interface: create a list or an array.

IEnumerable<string> myStrings = new [] { "first item", "second item" };
IEnumerable<string> myStrings = new List<string> { "first item", "second item" };

How to analyze information from a Java core dump?

IBM provide a number of tools which can be used on the sun jvm as well. Take a look at some of the projects on alphaworks, they provide a heap and thread dump analyzers

Karl

stale element reference: element is not attached to the page document

Use this code:

public class LinkTest 
{   
    public static void main(String[] args) 
    {
        WebDriver driver = new FirefoxDriver();
        driver.navigate().to("file:///C:/Users/vkiran/Desktop/xyz.html");
        List<WebElement> alllinks =driver.findElements(By.xpath("//*[@id='sliding-navigation']//a"));
        String a[]=new String[alllinks.size()];
        for(int i=0;i<alllinks.size();i++)
        {
            a[i]=alllinks.get(i).getText(); 
            if(a[i].startsWith("B"))
            {
                System.out.println("clicking on this link::"+driver.findElement(By.linkText(a[i])).getText());
                driver.findElement(By.linkText(a[i])).click();  

            }
            else
            {
                System.out.println("does not starts with B so not clicking");
            }
        }
}
}

Visual Studio "Could not copy" .... during build

If none of the answers works, try this simple check. Find for any MSbuild.exe running and holding your project EXE. Kill MSBuild.exe and you should be good to go.

How to use jQuery with TypeScript

Most likely you need to download and include the TypeScript declaration file for jQuery—jquery.d.ts—in your project.

Option 1: Install the @types package (Recommended for TS 2.0+)

In the same folder as your package.json file, run the following command:

npm install --save-dev @types/jquery

Then the compiler will resolve the definitions for jquery automatically.

Option 2: Download Manually (Not Recommended)

Download it here.

Option 3: Using Typings (Pre TS 2.0)

If you're using typings then you can include it this way:

// 1. Install typings
npm install typings -g
// 2. Download jquery.d.ts (run this command in the root dir of your project)
typings install dt~jquery --global --save

After setting up the definition file, import the alias ($) in the desired TypeScript file to use it as you normally would.

import $ from "jquery";
// or
import $ = require("jquery");

You may need to compile with --allowSyntheticDefaultImports—add "allowSyntheticDefaultImports": true in tsconfig.json.

Also Install the Package?

If you don't have jquery installed, you probably want to install it as a dependency via npm (but this is not always the case):

npm install --save jquery

How to get the difference between two dictionaries in Python?

Old question, but thought I'd share my solution anyway. Pretty simple.

dicta_set = set(dicta.items()) # creates a set of tuples (k/v pairs)
dictb_set = set(dictb.items())
setdiff = dictb_set.difference(dicta_set) # any set method you want for comparisons
for k, v in setdiff: # unpack the tuples for processing
    print(f"k/v differences = {k}: {v}")

This code creates two sets of tuples representing the k/v pairs. It then uses a set method of your choosing to compare the tuples. Lastly, it unpacks the tuples (k/v pairs) for processing.

Test if element is present using Selenium WebDriver?

This works for me:

 if(!driver.findElements(By.xpath("//*[@id='submit']")).isEmpty()){
    //THEN CLICK ON THE SUBMIT BUTTON
}else{
    //DO SOMETHING ELSE AS SUBMIT BUTTON IS NOT THERE
}

How to avoid soft keyboard pushing up my layout?

Solved it by setting the naughty EditText:

etSearch = (EditText) view.findViewById(R.id.etSearch);

etSearch.setInputType(InputType.TYPE_NULL);

etSearch.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        etSearch.setInputType(InputType.TYPE_CLASS_TEXT);
        return false;
    }
});

How to increment a number by 2 in a PHP For Loop

<?php    
     $x = 1;

     for($x = 1; $x < 8; $x++) {
       $x = $x + 2;
       echo $x;
     };
?>

Recursively find all files newer than a given time

Assuming a modern release, find -newermt is powerful:

find -newermt '10 minutes ago' ## other units work too, see `Date input formats`

or, if you want to specify a time_t (seconds since epoch):

find -newermt @1568670245

For reference, -newermt is not directly listed in the man page for find. Instead, it is shown as -newerXY, where XY are placeholders for mt. Other replacements are legal, but not applicable for this solution.

From man find -newerXY:

Time specifications are interpreted as for the argument to the -d option of GNU date.

So the following are equivalent to the initial example:

find -newermt "$(date '+%Y-%m-%d %H:%M:%S' -d '10 minutes ago')" ## long form using 'date'
find -newermt "@$(date +%s -d '10 minutes ago')" ## short form using 'date' -- notice '@'

The date -d (and find -newermt) arguments are quite flexible, but the documentation is obscure. Here's one source that seems to be on point: Date input formats

What's the best three-way merge tool?

Meld Diff Viewer

I have had only good experiences working with Meld. I use it when I have to do messy code merges between branches. It is simple to use and has a clean interface.

  • Open Source
  • Linux, Windows and MacOS Supported
  • Multiple File Diff
  • Three-way Compare Support

In Ubuntu, install is as simple as: sudo apt-get install meld

enter image description here

Difference between System.DateTime.Now and System.DateTime.Today

DateTime dt = new DateTime();// gives 01/01/0001 12:00:00 AM
DateTime dt = DateTime.Now;// gives today date with current time
DateTime dt = DateTime.Today;// gives today date and 12:00:00 AM time

How to use "Share image using" sharing Intent to share images in android?

I was tired in Searching different options for sharing view or image from my application to other application . And finally i got the solution.

Step 1 : Share Intent handling Block. This will Pop Up your window with list of Applications in you phone

public void share_bitMap_to_Apps() {

    Intent i = new Intent(Intent.ACTION_SEND);

    i.setType("image/*");
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    /*compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] bytes = stream.toByteArray();*/


    i.putExtra(Intent.EXTRA_STREAM, getImageUri(mContext, getBitmapFromView(relative_me_other)));
    try {
        startActivity(Intent.createChooser(i, "My Profile ..."));
    } catch (android.content.ActivityNotFoundException ex) {

        ex.printStackTrace();
    }


}

Step 2 : Converting your view to BItmap

public static Bitmap getBitmapFromView(View view) {
    //Define a bitmap with the same size as the view
    Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(),      view.getHeight(), Bitmap.Config.ARGB_8888);
    //Bind a canvas to it
    Canvas canvas = new Canvas(returnedBitmap);
    //Get the view's background
    Drawable bgDrawable = view.getBackground();
    if (bgDrawable != null)
        //has background drawable, then draw it on the canvas
        bgDrawable.draw(canvas);
    else
        //does not have background drawable, then draw white background on the canvas
        canvas.drawColor(Color.WHITE);
    // draw the view on the canvas
    view.draw(canvas);
    //return the bitmap
    return returnedBitmap;
}

Step 3 :

To get The URI from Bitmap Image

public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

    String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    return Uri.parse(path);
}

Eclipse Indigo - Cannot install Android ADT Plugin

This seems to be fixed in Indigo Eclipse now, there's a video showing someone install android eclipse on youtube?

ERROR: Cannot open source file " "

Just in case there is someone out there who's a bit new like me, double check that you are spelling your header folders correctly.

For example:

<#include "Component/BoxComponent.h"

This will result in the error. Instead, it needs to be:

<#include "Components/BoxComponent.h"

Printing object properties in Powershell

The below worked really good for me. I patched together all the above answers plus read about displaying object properties in the following link and came up with the below short read about printing objects

add the following text to a file named print_object.ps1:

$date = New-Object System.DateTime
Write-Output $date | Get-Member
Write-Output $date | Select-Object -Property *

open powershell command prompt, go to the directory where that file exists and type the following:

powershell -ExecutionPolicy ByPass -File is_port_in_use.ps1 -Elevated

Just substitute 'System.DateTime' with whatever object you wanted to print. If the object is null, nothing will print out.

UTF-8 text is garbled when form is posted as multipart/form-data

To avoid converting all request parameters manually to UTF-8, you can define a method annotated with @InitBinder in your controller:

@InitBinder
protected void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(String.class, new CharacterEditor(true) {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            String properText = new String(text.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            setValue(properText);
        }
    });
}

The above will automatically convert all request parameters to UTF-8 in the controller where it is defined.

Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister

I encountered this error when upgrading from jdk10 to jdk11. Adding the following dependency fixed the problem:

<dependency>
    <groupId>org.javassist</groupId>
    <artifactId>javassist</artifactId>
    <version>3.25.0-GA</version>
</dependency>

'invalid value encountered in double_scalars' warning, possibly numpy

It looks like a floating-point calculation error. Check the numpy.seterr function to get more information about where it happens.

How to create JSON object Node.js

The JavaScript Object() constructor makes an Object that you can assign members to.

myObj = new Object()
myObj.key = value;
myObj[key2] = value2;   // Alternative

How to overplot a line on a scatter plot in python?

import numpy as np
from numpy.polynomial.polynomial import polyfit
import matplotlib.pyplot as plt

# Sample data
x = np.arange(10)
y = 5 * x + 10

# Fit with polyfit
b, m = polyfit(x, y, 1)

plt.plot(x, y, '.')
plt.plot(x, b + m * x, '-')
plt.show()

enter image description here

Installation Issue with matplotlib Python

Problem Cause

In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.

Solution

  • I assume you have installed the pip matplotlib, there is a directory in your root called ~/.matplotlib.
  • Create a file ~/.matplotlib/matplotlibrc there and add the following code: backend: TkAgg

From this link you can try different diagrams.

About the Full Screen And No Titlebar from manifest

In AndroidManifest.xml, set android:theme="@android:style/Theme.NoTitleBar.Fullscreen"in application tag.

Individual activities can override the default by setting their own theme attributes.

How to make an embedded Youtube video automatically start playing?

You have to use

<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/zGPuazETKkI?autoplay=1" frameborder="0" allowfullscreen></iframe>

?autoplay=1

and not

&autoplay=1

its the first URL param so its added with a ?

ListBox vs. ListView - how to choose for data binding

A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.

If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).

AssertionError: View function mapping is overwriting an existing endpoint function: main

If you think you have unique endpoint names and still this error is given then probably you are facing issue. Same was the case with me.

This issue is with flask 0.10 in case you have same version then do following to get rid of this:

sudo pip uninstall flask
sudo pip install flask=0.9

Can I get "&&" or "-and" to work in PowerShell?

Very old question, but for the newcomers: maybe the PowerShell version (similar but not equivalent) that the question is looking for, is to use -and as follows:

(build_command) -and (run_tests_command)

Attach the Source in Eclipse of a jar

  1. Download JDEclipse from http://java-decompiler.github.io/
  2. Follow the installation steps
  3. If you still didn't find the source, right click on the jar file and select "Attach Library Source" option from the project folder, as you can see below.

Drop down option location

Find all elements on a page whose element ID contains a certain text using jQuery

$('*[id*=mytext]:visible').each(function() {
    $(this).doStuff();
});

Note the asterisk '*' at the beginning of the selector matches all elements.

See the Attribute Contains Selectors, as well as the :visible and :hidden selectors.

Crystal Reports 13 And Asp.Net 3.5

I had this same problem and resolved it by making sure all references to the previous version of crystal from the Web Config file, the server, and the publishing workstation were removed. Other than the full trust basically everything that user707217 did, I did and it worked for my upgraded Web application

Seeding the random number generator in Javascript

Math.random no, but the ran library solves this. It has almost all distributions you can imagine and supports seeded random number generation. Example:

ran.core.seed(0)
myDist = new ran.Dist.Uniform(0, 1)
samples = myDist.sample(1000)

How to hide app title in android?

use

<activity android:name=".ActivityName" 
          android:theme="@android:style/Theme.NoTitleBar">

How do I make a LinearLayout scrollable?

Place all your layouts inside a ScrollView with width and height set to fill_parent.

How to skip a iteration/loop in while-loop

You don't need to skip the iteration, since the rest of it is in the else statement, it will only be executed if the condition is not true.

But if you really need to skip it, you can use the continue; statement.

Resize HTML5 canvas to fit window

Setting the canvas coordinate space width and height based on the browser client's dimensions requires you to resize and redraw whenever the browser is resized.

A less convoluted solution is to maintain the drawable dimensions in Javascript variables, but set the canvas dimensions based on the screen.width, screen.height dimensions. Use CSS to fit:

#containingDiv { 
  overflow: hidden;
}
#myCanvas {
  position: absolute; 
  top: 0px;
  left: 0px;
} 

The browser window generally won't ever be larger than the screen itself (except where the screen resolution is misreported, as it could be with non-matching dual monitors), so the background won't show and pixel proportions won't vary. The canvas pixels will be directly proportional to the screen resolution unless you use CSS to scale the canvas.

pass array to method Java

class test
{
    void passArr()
    {
        int arr1[]={1,2,3,4,5,6,7,8,9};
        printArr(arr1);
    }

    void printArr(int[] arr2)
    {
        for(int i=0;i<arr2.length;i++)
        {
            System.out.println(arr2[i]+"  ");
        }
    }

    public static void main(String[] args)
    {
        test ob=new test();
        ob.passArr();
    }
}

How to get cookie expiration date / creation date from javascript?

The information is not available through document.cookie, but if you're really desperate for it, you could try performing a request through the XmlHttpRequest object to the current page and access the cookie header using getResponseHeader().

Update span tag value with JQuery

Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.

    $("legend").each(function() {
        var SoftwareItem = $(this).text();
        itemCost = GetItemCost(SoftwareItem);
        $("input:checked").each(function() {               
            var Component = $(this).next("label").text();
            itemCost += GetItemCost(Component);
        });            
        $(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
    });

How to use the start command in a batch file?

An extra pair of rabbits' ears should do the trick.

start "" "C:\Program...

START regards the first quoted parameter as the window-title, unless it's the only parameter - and any switches up until the executable name are regarded as START switches.

In Python, what happens when you import inside of a function?

Might I suggest in general that instead of asking, "Will X improve my performance?" you use profiling to determine where your program is actually spending its time and then apply optimizations according to where you'll get the most benefit?

And then you can use profiling to assure that your optimizations have actually benefited you, too.

Comparing arrays in JUnit assertions, concise built-in way?

I know the question is for JUnit4, but if you happen to be stuck at JUnit3, you could create a short utility function like that:

private void assertArrayEquals(Object[] esperado, Object[] real) {
    assertEquals(Arrays.asList(esperado), Arrays.asList(real));     
}

In JUnit3, this is better than directly comparing the arrays, since it will detail exactly which elements are different.

How to generate .NET 4.0 classes from xsd?

Along with WSDL, I had xsd files. The above did not work in my case gave error. It worked as follows

wsdl /l:C# /out:D:\FileName.cs D:\NameApi\wsdl_1_1\RESAdapterService.wsdl 
D:\CXTypes.xsd D:\CTypes.xsd 
D:\Preferences.xsd 

Printing list elements on separated lines in Python

print("\n".join(sys.path))

(The outer parentheses are included for Python 3 compatibility and are usually omitted in Python 2.)

UITableView Separator line

Here is an alternate way to add a custom separator line to a UITableView by making a CALayer for the image and using that as the separator line.

// make a CALayer for the image for the separator line

CALayer *separator = [CALayer layer];
separator.contents = (id)[UIImage imageNamed:@"myImage.png"].CGImage;
separator.frame = CGRectMake(0, 54, self.view.frame.size.width, 2);
[cell.layer addSublayer:separator];

Visual C++: How to disable specific linker warnings?

I suspect /ignore is a VC6 link.exe option. for VS2005 and VS2008's linker there's no documented /ignore option available, but the linker looks just ignore the "/ignore:XXX" option, no error and no effect.

How do I test axios in Jest?

For those looking to use axios-mock-adapter in place of the mockfetch example in the Redux documentation for async testing, I successfully used the following:

File actions.test.js:

describe('SignInUser', () => {
  var history = {
    push: function(str) {
        expect(str).toEqual('/feed');
    }
  }

  it('Dispatches authorization', () => {
    let mock = new MockAdapter(axios);
    mock.onPost(`${ROOT_URL}/auth/signin`, {
        email: '[email protected]',
        password: 'test'
    }).reply(200, {token: 'testToken' });

    const expectedActions = [ { type: types.AUTH_USER } ];
    const store = mockStore({ auth: [] });

    return store.dispatch(actions.signInUser({
        email: '[email protected]',
        password: 'test',
      }, history)).then(() => {
        expect(store.getActions()).toEqual(expectedActions);
  });

});

In order to test a successful case for signInUser in file actions/index.js:

export const signInUser = ({ email, password }, history) => async dispatch => {
  const res = await axios.post(`${ROOT_URL}/auth/signin`, { email, password })
    .catch(({ response: { data } }) => {
        ...
  });

  if (res) {
    dispatch({ type: AUTH_USER });                 // Test verified this
    localStorage.setItem('token', res.data.token); // Test mocked this
    history.push('/feed');                         // Test mocked this
  }
}

Given that this is being done with jest, the localstorage call had to be mocked. This was in file src/setupTests.js:

const localStorageMock = {
  removeItem: jest.fn(),
  getItem: jest.fn(),
  setItem: jest.fn(),
  clear: jest.fn()
};
global.localStorage = localStorageMock;

Parsing Query String in node.js

Starting with Node.js 11, the url.parse and other methods of the Legacy URL API were deprecated (only in the documentation, at first) in favour of the standardized WHATWG URL API. The new API does not offer parsing the query string into an object. That can be achieved using tthe querystring.parse method:

// Load modules to create an http server, parse a URL and parse a URL query.
const http = require('http');
const { URL } = require('url');
const { parse: parseQuery } = require('querystring');

// Provide the origin for relative URLs sent to Node.js requests.
const serverOrigin = 'http://localhost:8000';

// Configure our HTTP server to respond to all requests with a greeting.
const server = http.createServer((request, response) => {
  // Parse the request URL. Relative URLs require an origin explicitly.
  const url = new URL(request.url, serverOrigin);
  // Parse the URL query. The leading '?' has to be removed before this.
  const query = parseQuery(url.search.substr(1));
  response.writeHead(200, { 'Content-Type': 'text/plain' });
  response.end(`Hello, ${query.name}!\n`);
});

// Listen on port 8000, IP defaults to 127.0.0.1.
server.listen(8000);

// Print a friendly message on the terminal.
console.log(`Server running at ${serverOrigin}/`);

If you run the script above, you can test the server response like this, for example:

curl -q http://localhost:8000/status?name=ryan
Hello, ryan!

How to detect responsive breakpoints of Twitter Bootstrap 3 using JavaScript?

Bootstrap's CSS for the .container class looks like that:

.container {
    padding-right: 15px;
    padding-left: 15px;
    margin-right: auto;
    margin-left: auto;
}
@media (min-width: 768px) {
    .container {
        width: 750px;
    }
}
@media (min-width: 992px) {
    .container {
        width: 970px;
    }
}
@media (min-width: 1200px) {
    .container {
        width: 1170px;
    }
}

So this means we can safely rely on jQuery('.container').css('width') to detect breakpoints without the drawbacks of relying on jQuery(window).width().

We can write a function like this:

function detectBreakpoint() {
    // Let's ensure we have at least 1 container in our pages.
    if (jQuery('.container').length == 0) {
        jQuery('body').append('<div class="container"></div>');
    }

    var cssWidth = jQuery('.container').css('width');

    if (cssWidth === '1170px') return 'lg';
    else if (cssWidth === '970px') return 'md';
    else if (cssWidth === '750px') return 'sm';

    return 'xs';
}

And then test it like

jQuery(document).ready(function() {
    jQuery(window).resize(function() {
        jQuery('p').html('current breakpoint is: ' + detectBreakpoint());
    });

    detectBreakpoint();
});

How to set the style -webkit-transform dynamically using JavaScript?

Try using

img.style.webkitTransform = "rotate(60deg)"

Internet Explorer 11 detection

I found IE11 is giving more than one user agent strings in different environments.

Instead of relying on MSIE, and other approaches, It's better to rely on Trident version

const isIE11 = userAgent => userAgent.match(/Trident\/([\d.]+)/) ? +userAgent.match(/Trident\/([\d.]+)/)[1] >= 7;

Hope this helps :)

Spark - repartition() vs coalesce()

What follows from the code and code docs is that coalesce(n) is the same as coalesce(n, shuffle = false) and repartition(n) is the same as coalesce(n, shuffle = true)

Thus, both coalesce and repartition can be used to increase number of partitions

With shuffle = true, you can actually coalesce to a larger number of partitions. This is useful if you have a small number of partitions, say 100, potentially with a few partitions being abnormally large.

Another important note to accentuate is that if you drastically decrease number of partitions you should consider using shuffled version of coalesce (same as repartition in that case). This will allow your computations be performed in parallel on parent partitions (multiple task).

However, if you're doing a drastic coalesce, e.g. to numPartitions = 1, this may result in your computation taking place on fewer nodes than you like (e.g. one node in the case of numPartitions = 1). To avoid this, you can pass shuffle = true. This will add a shuffle step, but means the current upstream partitions will be executed in parallel (per whatever the current partitioning is).

Please also refer to the related answer here

jQuery/Javascript function to clear all the fields of a form

Something similar to $("#formId").reset() will not clear form items that have had their defaults set to something other than "". One way this can happen is a previous form submission: once a form has been submitted reset() would "reset" form values to those previously submitted which will likely not be "".

One option to clear all forms on the page, is to call a function such as the following, executing it simply as clearForms():

function clearForms()
{
    $(':input').not(':button, :submit, :reset, :hidden, :checkbox, :radio').val('');
    $(':checkbox, :radio').prop('checked', false);
}

If you want to reset a specific form, then modify the function as follows, and call it as clearForm($("#formId")):

function clearForm($form)
{
    $form.find(':input').not(':button, :submit, :reset, :hidden, :checkbox, :radio').val('');
    $form.find(':checkbox, :radio').prop('checked', false);
}

When I originally came to this page I needed a solution that takes into account form defaults being changed and is still able to clear all input items.

Note that this will not clear placeholder text.

How to convert string to IP address and vice versa

here's easy-to-use, thread-safe c++ functions to convert uint32_t native-endian to string, and string to native-endian uint32_t:

#include <arpa/inet.h> // inet_ntop & inet_pton
#include <string.h> // strerror_r
#include <arpa/inet.h> // ntohl & htonl
using namespace std; // im lazy

string ipv4_int_to_string(uint32_t in, bool *const success = nullptr)
{
    string ret(INET_ADDRSTRLEN, '\0');
    in = htonl(in);
    const bool _success = (NULL != inet_ntop(AF_INET, &in, &ret[0], ret.size()));
    if (success)
    {
        *success = _success;
    }
    if (_success)
    {
        ret.pop_back(); // remove null-terminator required by inet_ntop
    }
    else if (!success)
    {
        char buf[200] = {0};
        strerror_r(errno, buf, sizeof(buf));
        throw std::runtime_error(string("error converting ipv4 int to string ") + to_string(errno) + string(": ") + string(buf));
    }
    return ret;
}
// return is native-endian
// when an error occurs: if success ptr is given, it's set to false, otherwise a std::runtime_error is thrown.
uint32_t ipv4_string_to_int(const string &in, bool *const success = nullptr)
{
    uint32_t ret;
    const bool _success = (1 == inet_pton(AF_INET, in.c_str(), &ret));
    ret = ntohl(ret);
    if (success)
    {
        *success = _success;
    }
    else if (!_success)
    {
        char buf[200] = {0};
        strerror_r(errno, buf, sizeof(buf));
        throw std::runtime_error(string("error converting ipv4 string to int ") + to_string(errno) + string(": ") + string(buf));
    }
    return ret;
}

fair warning, as of writing, they're un-tested. but these functions are exactly what i was looking for when i came to this thread.

How to read the post request parameters using JavaScript

function getParameterByName(name, url) {
            if (!url) url = window.location.href;
            name = name.replace(/[\[\]]/g, "\\$&");
            var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
                results = regex.exec(url);
            if (!results) return null;
            if (!results[2]) return '';
            return decodeURIComponent(results[2].replace(/\+/g, " "));
        }
var formObj = document.getElementById("pageID");
formObj.response_order_id.value = getParameterByName("name");

oracle diff: how to compare two tables?

Try this:

(select * from T1 minus select * from T2) -- all rows that are in T1 but not in T2
union all
(select * from T2 minus select * from T1)  -- all rows that are in T2 but not in T1
;

No external tool. No performance issues with union all.

Find methods calls in Eclipse project

select method > right click > References > Workspace/Project (your preferred context ) 

or

(Ctrl+Shift+G) 

This will show you a Search view containing the hierarchy of class and method which using this method.

How can I compile LaTeX in UTF8?

You needed to iconv your source.

That said, the TEX-based compiler invoked by latex doesn't really support variable-length encodings; it needs big libraries that tell it that certain bytes go together. Xelatex is Unicode-aware and works much better.

How to save an image locally using Python whose URL address I already know?

This can be done with requests. Load the page and dump the binary content to a file.

import os
import requests

url = 'https://apod.nasa.gov/apod/image/1701/potw1636aN159_HST_2048.jpg'
page = requests.get(url)

f_ext = os.path.splitext(url)[-1]
f_name = 'img{}'.format(f_ext)
with open(f_name, 'wb') as f:
    f.write(page.content)

Checking for an empty field with MySQL

This will work but there is still the possibility of a null record being returned. Though you may be setting the email address to a string of length zero when you insert the record, you may still want to handle the case of a NULL email address getting into the system somehow.

     $aUsers=$this->readToArray('
     SELECT `userID` 
     FROM `users` 
     WHERE `userID` 
     IN(SELECT `userID`
               FROM `users_indvSettings`
               WHERE `indvSettingID`=5 AND `optionID`='.$time.')
     AND `email` != "" AND `email` IS NOT NULL
     ');

Import existing Gradle Git project into Eclipse

Usually it is a simple as adding apply plugin: "eclipse" in your build.gradle and running

cd myProject/
gradle eclipse

and then refreshing your Eclipse project.

Occasionally you'll need to adjust build.gradle to generate Eclipse settings in some very specific way.

There is gradle support for Eclipse if you are using STS, but I'm not sure how good it is.

The only IDE I know that has decent native support for gradle is IntelliJ IDEA. It can do full import of gradle projects from GUI. There is a free Community Edition that you can try.

Excel VBA Run-time Error '32809' - Trying to Understand it

In my case, the error occurred executing a macro in: Sheets("own sheet one").Select

copy the sheet into another with other name, ie. "oso", then delete the original sheet and renamed the new one as "own sheet one"

Excel 2013

Setting the Textbox read only property to true using JavaScript

I find that document.getElementById('textbox-id').readOnly=true sometimes doesn't work reliably.

Instead, try:

document.getElementById('textbox-id').setAttribute('readonly', 'readonly') and document.getElementById('textbox-id').removeAttribute('readonly').

A little verbose but it seems to be dependable.

Maximize a window programmatically and prevent the user from changing the windows state

When I do this, I get a very small square screen instead of a maxed screen. Yet, when I only use the FormWindowState.Maximized, it does give me a full screen. Why is that?

        public partial class Testscherm : Form
    {
            public Testscherm()

            {

                    this.WindowState = FormWindowState.Maximized;
                    this.MaximizeBox = false;
                    this.MinimizeBox = false;
                    this.MinimumSize = this.Size;
                    this.MaximumSize = this.Size;
                    this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
                    InitializeComponent();


            }

Fill an array with random numbers

This seems a little bit like homework. So I'll give you some hints. The good news is that you're almost there! You've done most of the hard work already!

  • Think about a construct that can help you iterate over the array. Is there some sort of construct (a loop perhaps?) that you can use to iterate over each location in the array?
  • Within this construct, for each iteration of the loop, you will assign the value returned by randomFill() to the current location of the array.

Note: Your array is double, but you are returning ints from randomFill. So there's something you need to fix there.

JavaScript Array to Set

What levi said about passing it into the constructor is correct, but you could also use an object.

I think what Veverke is trying to say is that you could easily use the delete keyword on an object to achieve the same effect.

I think you're confused by the terminology; properties are components of the object that you can use as named indices (if you want to think of it that way).

Try something like this:

var obj = {
    "bob": "dole",
    "mr.": "peabody",
    "darkwing": "duck"
};

Then, you could just do this:

delete obj["bob"];

The structure of the object would then be this:

{
    "mr.": "peabody",
    "darkwing": "duck"
}

Which has the same effect.

Java socket API: How to tell if a connection has been closed?

I think this is nature of tcp connections, in that standards it takes about 6 minutes of silence in transmission before we conclude that out connection is gone! So I don`t think you can find an exact solution for this problem. Maybe the better way is to write some handy code to guess when server should suppose a user connection is closed.

Streaming via RTSP or RTP in HTML5

There are three streaming protocols / technology in HTML5:

Live streaming, low latency - WebRTC - Websocket

VOD and Live streaming, high latency - HLS

1. WebRTC

In fact WebRTC is SRTP(secure RTP protocol). Thus we can say that video tag supports RTP(SRTP) indirectly via WebRTC.

Therefore to get RTP stream on your Chrome, Firefox or another HTML5 browser, you need a WebRTC server which will deliver the SRTP stream to browser.

2. Websocket

It is TCP based, but with lower latency than HLS. Again you need a Websocket server.

3. HLS

Most popular high-latency streaming protocol for VOD(pre-recorded video).

How to hide underbar in EditText

If you are using the EditText inside TextInputLayout use app:boxBackgroundMode="none" as following:

<com.google.android.material.textfield.TextInputLayout
    app:boxBackgroundMode="none"
    ...
    >

    <EditText
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</com.google.android.material.textfield.TextInputLayout>

Plot Normal distribution with Matplotlib

Note: This solution is using pylab, not matplotlib.pyplot

You may try using hist to put your data info along with the fitted curve as below:

import numpy as np
import scipy.stats as stats
import pylab as pl

h = sorted([186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
     187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
     161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180])  #sorted

fit = stats.norm.pdf(h, np.mean(h), np.std(h))  #this is a fitting indeed

pl.plot(h,fit,'-o')

pl.hist(h,normed=True)      #use this to draw histogram of your data

pl.show()                   #use may also need add this 

enter image description here

DROP IF EXISTS VS DROP?

It is not what is asked directly. But looking for how to do drop tables properly, I stumbled over this question, as I guess many others do too.

From SQL Server 2016+ you can use

DROP TABLE IF EXISTS dbo.Table

For SQL Server <2016 what I do is the following for a permanent table

IF OBJECT_ID('dbo.Table', 'U') IS NOT NULL 
  DROP TABLE dbo.Table; 

Or this, for a temporary table

IF OBJECT_ID('tempdb.dbo.#T', 'U') IS NOT NULL
  DROP TABLE #T; 

OperationalError, no such column. Django

I simple made a careless mistake of forgetting to actually apply the migration (migrate) after making migrations. Writing this just in case anyone might make the same mistake.

Python setup.py develop vs install

Another thing that people may find useful when using the develop method is the --user option to install without sudo. Ex:

python setup.py develop --user

instead of

sudo python setup.py develop

Export P7b file with all the certificate chain into CER file

If you add -chain to your command line, it will export any chained certificates.

http://www.openssl.org/docs/apps/pkcs12.html

How to locate and insert a value in a text box (input) using Python Selenium?

Assuming your page is available under "http://example.com"

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://example.com")

Select element by id:

inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')

Now you can simulate hitting ENTER:

inputElement.send_keys(Keys.ENTER)

or if it is a form you can submit:

inputElement.submit() 

Required attribute HTML5

Note that

<input type="text" id="car" required="true" />

is wrong, it should be one of

<input type="text" id="car" required />
<input type="text" id="car" required="" />
<input type="text" id="car" required='' />
<input type="text" id="car" required=required />
<input type="text" id="car" required="required" />
<input type="text" id="car" required='required' />

This is because the true value suggests that the false value will make the form control optional, which is not the case.

python: Change the scripts working directory to the script's own directory

You can get a shorter version by using sys.path[0].

os.chdir(sys.path[0])

From http://docs.python.org/library/sys.html#sys.path

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter

How to format a phone number with jQuery

Quick roll your own code:

Here is a solution modified from Cruz Nunez's solution above.

// Used to format phone number
function phoneFormatter() {
  $('.phone').on('input', function() {
    var number = $(this).val().replace(/[^\d]/g, '')
    if (number.length < 7) {
      number = number.replace(/(\d{0,3})(\d{0,3})/, "($1) $2");
    } else if (number.length <= 10) {
    number = number.replace(/(\d{3})(\d{3})(\d{1,4})/, "($1) $2-$3");
    } else {
    // ignore additional digits
    number = number.replace(/(\d{3})(\d{1,3})(\d{1,4})(\d.*)/, "($1) $2-$3");
    }
    $(this).val(number)
  });
};

$(phoneFormatter);

JSFiddle

  • In this solution, the formatting is applied no matter how many digits the user has entered. (In Nunes' solution, the formatting is applied only when exactly 7 or 10 digits has been entered.)

  • It requires the zip code for a 10-digit US phone number to be entered.

  • Both solutions, however, editing already entered digits is problematic, as typed digits always get added to the end.

  • I recommend, instead, the robust jQuery Mask Plugin code, mentioned below:

Recommend jQuery Mask Plugin

I recommend using jQuery Mask Plugin (page has live examples), on github.
These links have minimal explanations on how to use:

CDN
Instead of installing/hosting the code, you can also add a link to a CDN of the script CDN Link for jQuery Mask Plugin
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous"></script>

or
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous"></script>

WordPress Contact Form 7: use Masks Form Fields plugin

If you are using Contact Form 7 plugin on a WordPress site, the easiest option to control form fields is if you can simply add a class to your input field to take care of it for you.
Masks Form Fields plugin is one option that makes this easy to do.
I like this option, as, Internally, it embeds a minimized version of the code from jQuery Mask Plugin mentioned above.

Example usage on a Contact Form 7 form:

<label> Your Phone Number (required)
    [tel* customer-phone class:phone_us minlength:14 placeholder "(555) 555-5555"]
</label>

The important part here is class:phone_us.
Note that if you use minlength/maxlength, the length must include the mask characters, in addition to the digits.

Android: Creating a Circular TextView?

I was also looking for a solution to this problem and as easy and comfortable I found, was to convert the shape of a rectangular TextView to cirular. With this method will be perfect:

  1. Create a new XML file in the drawable folder called "circle.xml" (for example) and fill it with the following code:

    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="oval">
    
        <solid android:color="#9FE554" />
    
        <size
            android:height="60dp"
            android:width="60dp" />
    
    </shape>
    

With this file you will create the new form of TextView. In this case, I created a circle of green. If you want to add a border, you would have to add the following code to the previous file:

    <stroke
        android:width="2dp"
        android:color="#FFFFFF" />
  1. Create another XML file ( "rounded_textview.xml") in the drawable folder with the following code:

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@drawable/circle" />
    </selector>
    

This file will serve to change the way the TextView we eligamos.

  1. Finally, in the TextView properties we want to change the way section, we headed to the "background" and select the second XML file created ( "rounded_textview.xml").

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="H"
        android:textSize="30sp"
        android:background="@drawable/rounded_textview"
        android:textColor="@android:color/white"
        android:gravity="center"
        android:id="@+id/mark" />
    

With these steps, instead of having a TextView TextView rectagular have a circular. Just change the shape, not the functionality of the TextView. The result would be the following:

enter image description here

Also I have to say that these steps can be applied to any other component having the option to "background" in the properties.

Luck!!

C++/CLI Converting from System::String^ to std::string

I like to stay away from the marshaller.

Using CString newString(originalString);

Seems much cleaner and faster to me. No need to worry about creating and deleting a context.

Could not connect to React Native development server on Android

In my case the problem was with Android security policies. According to the documentation:

Starting with Android 9.0 (API level 28), cleartext support is disabled by default.

But the application tries to access Metro Bundler through HTTP, right? And that's why it can't. In order to enable cleartext traffic, open your AndroidManifest.xml and add android:usesCleartextTraffic="true" to <application> node.

For example:

<application
    android:name="com.example.app"
    android:allowBackup="false"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme"
    android:usesCleartextTraffic="true">

You can find more solutions in this SO: https://stackoverflow.com/a/50834600/1673320. OP's problem is different, but similar.

What is the common header format of Python files?

The answers above are really complete, but if you want a quick and dirty header to copy'n paste, use this:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Module documentation goes here
   and here
   and ...
"""

Why this is a good one:

  • The first line is for *nix users. It will choose the Python interpreter in the user path, so will automatically choose the user preferred interpreter.
  • The second one is the file encoding. Nowadays every file must have a encoding associated. UTF-8 will work everywhere. Just legacy projects would use other encoding.
  • And a very simple documentation. It can fill multiple lines.

See also: https://www.python.org/dev/peps/pep-0263/

If you just write a class in each file, you don't even need the documentation (it would go inside the class doc).

Can't get private key with openssl (no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY)

On my execution of openssl pkcs12 -export -out cacert.pkcs12 -in testca/cacert.pem, I received the following message:

unable to load private key 140707250050712:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:701:Expecting: ANY PRIVATE KEY`

Got this solved by providing the key file along with the command. The switch is -inkey inkeyfile.pem

How to put text over images in html?

You can try this...

<div class="image">

      <img src="" alt="" />

      <h2>Text you want to display over the image</h2>

</div>

CSS

.image { 
   position: relative; 
   width: 100%; /* for IE 6 */
}

h2 { 
   position: absolute; 
   top: 200px; 
   left: 0; 
   width: 100%; 
}

How to get just the responsive grid from Bootstrap 3?

It's been a while since this question was asked, but maybe now you can forego Bootstrap altogether and use CSS Grid! (it's simpler, neater, more flexible and faster). See this cool article: Stop using Bootstrap — create a practical CSS Grid template for your component based UI

how to change onclick event with jquery?

@Amirali

console.log(document.getElementById("SAVE_FOOTER"));
document.getElementById("SAVE_FOOTER").attribute("onclick","console.log('c')");

throws:

Uncaught TypeError: document.getElementById(...).attribute is not a function

in chrome.

Element exists and is dumped in console;

How can I get double quotes into a string literal?

Thankfully, with C++11 there is also the more pleasing approach of using raw string literals.

printf("She said \"time flies like an arrow, but fruit flies like a banana\".");

Becomes:

printf(R"(She said "time flies like an arrow, but fruit flies like a banana".)");

With respect to the addition of brackets after the opening quote, and before the closing quote, note that they can be almost any combination of up to 16 characters, helping avoid the situation where the combination is present in the string itself. Specifically:

any member of the basic source character set except: space, the left parenthesis (, the right parenthesis ), the backslash , and the control characters representing horizontal tab, vertical tab, form feed, and newline" (N3936 §2.14.5 [lex.string] grammar) and "at most 16 characters" (§2.14.5/2)

How much clearer it makes this short strings might be debatable, but when used on longer formatted strings like HTML or JSON, it's unquestionably far clearer.

Is there a simple way to convert C++ enum to string?

This is a modification to @user3360260 answer. It has the following new features

  • MyEnum fromString(const string&) support
  • compiles with VisualStudio 2012
  • the enum is an actual POD type (not just const declarations), so you can assign it to a variable.
  • added C++ "range" feature (in form of vector) to allow "foreach" iteration over enum

Usage:

SMART_ENUM(MyEnum, ONE=1, TWO, THREE, TEN=10, ELEVEN)
MyEnum foo = MyEnum::TWO;
cout << MyEnum::toString(foo);  // static method
cout << foo.toString();         // member method
cout << MyEnum::toString(MyEnum::TWO);
cout << MyEnum::toString(10);
MyEnum foo = myEnum::fromString("TWO");

// C++11 iteration over all values
for( auto x : MyEnum::allValues() )
{
  cout << x.toString() << endl;
}

Here's the code

#define SMART_ENUM(EnumName, ...)                                   \
class EnumName                                                      \
{                                                                   \
public:                                                             \
    EnumName() : value(0) {}                                        \
    EnumName(int x) : value(x) {}                                   \
public:                                                             \
    enum {__VA_ARGS__};                                             \
private:                                                            \
    static void initMap(std::map<int, std::string>& tmp)                     \
    {                                                               \
        using namespace std;                                        \
                                                                    \
        int val = 0;                                                \
        string buf_1, buf_2, str = #__VA_ARGS__;                    \
        replace(str.begin(), str.end(), '=', ' ');                  \
        stringstream stream(str);                                   \
        vector<string> strings;                                     \
        while (getline(stream, buf_1, ','))                         \
            strings.push_back(buf_1);                               \
        for(vector<string>::iterator it = strings.begin();          \
                                                it != strings.end(); \
                                                ++it)                \
        {                                                           \
            buf_1.clear(); buf_2.clear();                           \
            stringstream localStream(*it);                          \
            localStream>> buf_1 >> buf_2;                           \
            if(buf_2.size() > 0)                                    \
                val = atoi(buf_2.c_str());                          \
            tmp[val++] = buf_1;                                     \
        }                                                           \
    }                                                               \
    int value;                                                      \
public:                                                             \
    operator int () const { return value; }                         \
    std::string toString(void) const {                              \
            return toString(value);                                 \
    }                                                               \
    static std::string toString(int aInt)                           \
    {                                                               \
        return nameMap()[aInt];                                     \
    }                                                               \
    static EnumName fromString(const std::string& s)                \
    {                                                               \
        auto it = find_if(nameMap().begin(), nameMap().end(), [s](const std::pair<int,std::string>& p) { \
            return p.second == s;                                   \
        });                                                         \
        if (it == nameMap().end()) {                                \
        /*value not found*/                                         \
            throw EnumName::Exception();                            \
        } else {                                                    \
            return EnumName(it->first);                             \
        }                                                           \
    }                                                               \
    class Exception : public std::exception {};                     \
    static std::map<int,std::string>& nameMap() {                   \
      static std::map<int,std::string> nameMap0;                    \
      if (nameMap0.size() ==0) initMap(nameMap0);                   \
      return nameMap0;                                              \
    }                                                               \
    static std::vector<EnumName> allValues() {                      \
      std::vector<EnumName> x{ __VA_ARGS__ };                       \
      return x;                                                     \
    }                                                               \
    bool operator<(const EnumName a) const { return (int)*this < (int)a; } \
};         

Note that the conversion toString is a fast has lookup, while the conversion fromString is a slow linear search. But strings are so expensive anyways(and the associated file IO), I didn't feel the need to optimize or use a bimap.

How do I get a list of installed CPAN modules?

perldoc perllocal

Edit: There's a (little) more info about it in the CPAN FAQ

Nth max salary in Oracle

5th highest salary:

SELECT
    * 
FROM
    emp a 
WHERE 
    4 = (
        SELECT 
            COUNT(DISTINCT b.sal) 
        FROM 
            emp b 
        WHERE 
            a.sal < b.sal
    )

Replace 4 with any value of N.

Position of a string within a string using Linux shell script?

I used awk for this

a="The cat sat on the mat"
test="cat"
awk -v a="$a" -v b="$test" 'BEGIN{print index(a,b)}'

Running windows shell commands with python

Refactoring of @srini-beerge's answer which gets the output and the return code

import subprocess
def run_win_cmd(cmd):
    result = []
    process = subprocess.Popen(cmd,
                               shell=True,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)
    for line in process.stdout:
        result.append(line)
    errcode = process.returncode
    for line in result:
        print(line)
    if errcode is not None:
        raise Exception('cmd %s failed, see above for details', cmd)

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

The accepted answer to this question is awesome and should remain the accepted answer. However I ran into an issue with the code where the read stream was not always being ended/closed. Part of the solution was to send autoClose: true along with start:start, end:end in the second createReadStream arg.

The other part of the solution was to limit the max chunksize being sent in the response. The other answer set end like so:

var end = positions[1] ? parseInt(positions[1], 10) : total - 1;

...which has the effect of sending the rest of the file from the requested start position through its last byte, no matter how many bytes that may be. However the client browser has the option to only read a portion of that stream, and will, if it doesn't need all of the bytes yet. This will cause the stream read to get blocked until the browser decides it's time to get more data (for example a user action like seek/scrub, or just by playing the stream).

I needed this stream to be closed because I was displaying the <video> element on a page that allowed the user to delete the video file. However the file was not being removed from the filesystem until the client (or server) closed the connection, because that is the only way the stream was getting ended/closed.

My solution was just to set a maxChunk configuration variable, set it to 1MB, and never pipe a read a stream of more than 1MB at a time to the response.

// same code as accepted answer
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;

// poor hack to send smaller chunks to the browser
var maxChunk = 1024 * 1024; // 1MB at a time
if (chunksize > maxChunk) {
  end = start + maxChunk - 1;
  chunksize = (end - start) + 1;
}

This has the effect of making sure that the read stream is ended/closed after each request, and not kept alive by the browser.

I also wrote a separate StackOverflow question and answer covering this issue.

Minimum rights required to run a windows service as a domain account

Two ways:

  1. Edit the properties of the service and set the Log On user. The appropriate right will be automatically assigned.

  2. Set it manually: Go to Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment. Edit the item "Log on as a service" and add your domain user there.

How to add a boolean datatype column to an existing table in sql?

In SQL SERVER it is BIT, though it allows NULL to be stored

ALTER TABLE person add  [AdminApproved] BIT default 'FALSE';

Also there are other mistakes in your query

  1. When you alter a table to add column no need to mention column keyword in alter statement

  2. For adding default constraint no need to use SET keyword

  3. Default value for a BIT column can be ('TRUE' or '1') / ('FALSE' or 0). TRUE or FALSE needs to mentioned as string not as Identifier

Use of contains in Java ArrayList<String>

Yes, that should work for Strings, but if you are worried about duplicates use a Set. This collection prevents duplicates without you having to do anything. A HashSet is OK to use, but it is unordered so if you want to preserve insertion order you use a LinkedHashSet.

MySQL - UPDATE query based on SELECT Query

UPDATE 
  receipt_invoices dest,
  (
    SELECT 
      `receipt_id`,
      CAST((net * 100) / 112 AS DECIMAL (11, 2)) witoutvat 
    FROM
      receipt 
    WHERE CAST((net * 100) / 112 AS DECIMAL (11, 2)) != total 
      AND vat_percentage = 12
  ) src 
SET
  dest.price = src.witoutvat,
  dest.amount = src.witoutvat 
WHERE col_tobefixed = 1 
  AND dest.`receipt_id` = src.receipt_id ;

Hope this will help you in a case where you have to match and update between two tables.

Relative paths in Python

What worked for me is using sys.path.insert. Then I specified the directory I needed to go. For example I just needed to go up one directory.

import sys
sys.path.insert(0, '../')

Disable LESS-CSS Overwriting calc()

Using an escaped string (a.k.a. escaped value):

width: ~"calc(100% - 200px)";

Also, in case you need to mix Less math with escaped strings:

width: calc(~"100% - 15rem +" (10px+5px) ~"+ 2em");

Compiles to:

width: calc(100% - 15rem + 15px + 2em);

This works as Less concatenates values (the escaped strings and math result) with a space by default.

Display a RecyclerView in Fragment

I faced same problem. And got the solution when I use this code to call context. I use Grid Layout. If you use another one you can change.

   recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),1));

if you have adapter to set. So you can follow this. Just call the getContext

  adapter = new Adapter(getContext(), myModelList);

If you have Toast to show, use same thing above

   Toast.makeText(getContext(), "Error in "+e, Toast.LENGTH_SHORT).show();

Hope this will work.

HappyCoding

How to check if an array element exists?

You can use the function array_key_exists to do that.

For example,

$a=array("a"=>"Dog","b"=>"Cat");
if (array_key_exists("a",$a))
  {
  echo "Key exists!";
  }
else
  {
  echo "Key does not exist!";
  }

PS : Example taken from here.

Python Serial: How to use the read or readline function to read more than 1 character at a time

I use this small method to read Arduino serial monitor with Python

import serial
ser = serial.Serial("COM11", 9600)
while True:
     cc=str(ser.readline())
     print(cc[2:][:-5])

How to get first character of a string in SQL?

LEFT(colName, 1) will also do this, also. It's equivalent to SUBSTRING(colName, 1, 1).

I like LEFT, since I find it a bit cleaner, but really, there's no difference either way.

How to retrieve JSON Data Array from ExtJS Store

Try this:

myStore.each( function (model) {
    console.log( model.get('name') ); 
}); 

font-weight is not working properly?

I removed the text-transform: uppercase; and then set it to bold/bolder, and this seemed to work.

FlutterError: Unable to load asset

if you're developing flutter packages, please add package param after image path like this:

AssetImage('images/heart.png', package: 'my_icons') // my_icons is your plugin name, in flutter plugin is also a package.

Here is the link from flutter docs https://flutter.dev/assets-and-images/#from-packages

Get a list of dates between two dates using a function

Before you use my function, you need to set up a "helper" table, you only need to do this one time per database:

CREATE TABLE Numbers
(Number int  NOT NULL,
    CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Number ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
DECLARE @x int
SET @x=0
WHILE @x<8000
BEGIN
    SET @x=@x+1
    INSERT INTO Numbers VALUES (@x)
END

here is the function:

CREATE FUNCTION dbo.ListDates
(
     @StartDate    char(10)  
    ,@EndDate      char(10)
)
RETURNS
@DateList table
(
    Date datetime
)
AS
BEGIN


IF ISDATE(@StartDate)!=1 OR ISDATE(@EndDate)!=1
BEGIN
    RETURN
END

INSERT INTO @DateList
        (Date)
    SELECT
        CONVERT(datetime,@StartDate)+n.Number-1
        FROM Numbers  n
        WHERE Number<=DATEDIFF(day,@StartDate,CONVERT(datetime,@EndDate)+1)


RETURN

END --Function

use this:

select * from dbo.ListDates('2010-01-01', '2010-01-13')

output:

Date
-----------------------
2010-01-01 00:00:00.000
2010-01-02 00:00:00.000
2010-01-03 00:00:00.000
2010-01-04 00:00:00.000
2010-01-05 00:00:00.000
2010-01-06 00:00:00.000
2010-01-07 00:00:00.000
2010-01-08 00:00:00.000
2010-01-09 00:00:00.000
2010-01-10 00:00:00.000
2010-01-11 00:00:00.000
2010-01-12 00:00:00.000
2010-01-13 00:00:00.000

(13 row(s) affected)

Wait for a process to finish

Had the same issue, I solved the issue killing the process and then waiting for each process to finish using the PROC filesystem:

while [ -e /proc/${pid} ]; do sleep 0.1; done

ES6 exporting/importing in index file

Simply:

// Default export (recommended)
export {default} from './MyClass' 

// Default export with alias
export {default as d1} from './MyClass' 

// In >ES7, it could be
export * from './MyClass'

// In >ES7, with alias
export * as d1 from './MyClass'

Or by functions names :

// export by function names
export { funcName1, funcName2, …} from './MyClass'

// export by aliases
export { funcName1 as f1, funcName2 as f2, …} from './MyClass'

More infos: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export

Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays'

As the error messages stated, ngFor only supports Iterables such as Array, so you cannot use it for Object.

change

private extractData(res: Response) {
  let body = <Afdelingen[]>res.json();
  return body || {};       // here you are return an object
}

to

private extractData(res: Response) {
  let body = <Afdelingen[]>res.json().afdelingen;    // return array from json file
  return body || [];     // also return empty array if there is no data
}

How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?

However, numbering starts at 1, so:

x = arange(5)
y = np.exp(5)
plt.figure(1)
plt.plot(x, y)

z = np.sin(x)
plt.figure(2)
plt.plot(x, z)

w = np.cos(x)
plt.figure(1) # Here's the part I need, but numbering starts at 1!
plt.plot(x, w)

Also, if you have multiple axes on a figure, such as subplots, use the axes(h) command where h is the handle of the desired axes object to focus on that axes.

(don't have comment privileges yet, sorry for new answer!)

How to build an android library with Android Studio and gradle?

Gradle Build Tools 2.2.0+ - Everything just works

This is the correct way to do it

In trying to avoid experimental and frankly fed up with the NDK and all its hackery I am happy that 2.2.x of the Gradle Build Tools came out and now it just works. The key is the externalNativeBuild and pointing ndkBuild path argument at an Android.mk or change ndkBuild to cmake and point the path argument at a CMakeLists.txt build script.

android {
    compileSdkVersion 19
    buildToolsVersion "25.0.2"

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 19

        ndk {
            abiFilters 'armeabi', 'armeabi-v7a', 'x86'
        }

        externalNativeBuild {
            cmake {
                cppFlags '-std=c++11'
                arguments '-DANDROID_TOOLCHAIN=clang',
                        '-DANDROID_PLATFORM=android-19',
                        '-DANDROID_STL=gnustl_static',
                        '-DANDROID_ARM_NEON=TRUE',
                        '-DANDROID_CPP_FEATURES=exceptions rtti'
            }
        }
    }

    externalNativeBuild {
        cmake {
             path 'src/main/jni/CMakeLists.txt'
        }
        //ndkBuild {
        //   path 'src/main/jni/Android.mk'
        //}
    }
}

For much more detail check Google's page on adding native code.

After this is setup correctly you can ./gradlew installDebug and off you go. You will also need to be aware that the NDK is moving to clang since gcc is now deprecated in the Android NDK.

Open S3 object as a string with Boto3

Python3 + Using boto3 API approach.

By using S3.Client.download_fileobj API and Python file-like object, S3 Object content can be retrieved to memory.

Since the retrieved content is bytes, in order to convert to str, it need to be decoded.

import io
import boto3

client = boto3.client('s3')
bytes_buffer = io.BytesIO()
client.download_fileobj(Bucket=bucket_name, Key=object_key, Fileobj=bytes_buffer)
byte_value = bytes_buffer.getvalue()
str_value = byte_value.decode() #python3, default decoding is utf-8

What is the difference between window, screen, and document in Javascript?

Briefly, with more detail below,

  • window is the execution context and global object for that context's JavaScript
  • document contains the DOM, initialized by parsing HTML
  • screen describes the physical display's full screen

See W3C and Mozilla references for details about these objects. The most basic relationship among the three is that each browser tab has its own window, and a window has window.document and window.screen properties. The browser tab's window is the global context, so document and screen refer to window.document and window.screen. More details about the three objects are below, following Flanagan's JavaScript: Definitive Guide.

window

Each browser tab has its own top-level window object. Each <iframe> (and deprecated <frame>) element has its own window object too, nested within a parent window. Each of these windows gets its own separate global object. window.window always refers to window, but window.parent and window.top might refer to enclosing windows, giving access to other execution contexts. In addition to document and screen described below, window properties include

  • setTimeout() and setInterval() binding event handlers to a timer
  • location giving the current URL
  • history with methods back() and forward() giving the tab's mutable history
  • navigator describing the browser software

document

Each window object has a document object to be rendered. These objects get confused in part because HTML elements are added to the global object when assigned a unique id. E.g., in the HTML snippet

<body>
  <p id="holyCow"> This is the first paragraph.</p>
</body>

the paragraph element can be referenced by any of the following:

  • window.holyCow or window["holyCow"]
  • document.getElementById("holyCow")
  • document.querySelector("#holyCow")
  • document.body.firstChild
  • document.body.children[0]

screen

The window object also has a screen object with properties describing the physical display:

  • screen properties width and height are the full screen

  • screen properties availWidth and availHeight omit the toolbar

The portion of a screen displaying the rendered document is the viewport in JavaScript, which is potentially confusing because we call an application's portion of the screen a window when talking about interactions with the operating system. The getBoundingClientRect() method of any document element will return an object with top, left, bottom, and right properties describing the location of the element in the viewport.

How to deal with persistent storage (e.g. databases) in Docker

@tommasop's answer is good, and explains some of the mechanics of using data-only containers. But as someone who initially thought that data containers were silly when one could just bind mount a volume to the host (as suggested by several other answers), but now realizes that in fact data-only containers are pretty neat, I can suggest my own blog post on this topic: Why Docker Data Containers (Volumes!) are Good

See also: my answer to the question "What is the (best) way to manage permissions for Docker shared volumes?" for an example of how to use data containers to avoid problems like permissions and uid/gid mapping with the host.

To address one of the OP's original concerns: that the data container must not be deleted. Even if the data container is deleted, the data itself will not be lost as long as any container has a reference to that volume i.e. any container that mounted the volume via --volumes-from. So unless all the related containers are stopped and deleted (one could consider this the equivalent of an accidental rm -fr /) the data is safe. You can always recreate the data container by doing --volumes-from any container that has a reference to that volume.

As always, make backups though!

UPDATE: Docker now has volumes that can be managed independently of containers, which further makes this easier to manage.

Editor does not contain a main type

You have to make sure that your .java files are in the .src folder in eclipse. I had the same exact problem until I got it figured out.

How to save CSS changes of Styles panel of Chrome Developer Tools?

To answer the last part of your question about any extensions that can save changes, there is hotfix

It allows you to save changes from Chrome Dev Tools directly to GitHub. From there you can set up a post-receive hook on GitHub to automatically update your website.

mingw-w64 threads: posix vs win32

GCC comes with a compiler runtime library (libgcc) which it uses for (among other things) providing a low-level OS abstraction for multithreading related functionality in the languages it supports. The most relevant example is libstdc++'s C++11 <thread>, <mutex>, and <future>, which do not have a complete implementation when GCC is built with its internal Win32 threading model. MinGW-w64 provides a winpthreads (a pthreads implementation on top of the Win32 multithreading API) which GCC can then link in to enable all the fancy features.

I must stress this option does not forbid you to write any code you want (it has absolutely NO influence on what API you can call in your code). It only reflects what GCC's runtime libraries (libgcc/libstdc++/...) use for their functionality. The caveat quoted by @James has nothing to do with GCC's internal threading model, but rather with Microsoft's CRT implementation.

To summarize:

  • posix: enable C++11/C11 multithreading features. Makes libgcc depend on libwinpthreads, so that even if you don't directly call pthreads API, you'll be distributing the winpthreads DLL. There's nothing wrong with distributing one more DLL with your application.
  • win32: No C++11 multithreading features.

Neither have influence on any user code calling Win32 APIs or pthreads APIs. You can always use both.

Find and replace strings in vim on multiple lines

Search and replace

:%s/search\|search2\|search3/replace/gci

g => global search

c => Ask for confirmation first

i => Case insensitive

If you want direct replacement without confirmation, use below command

:%s/search/replace/g

If you want confirmation for each replace then run the below command

:%s/search/replace/gc

Ask for confirmation first, here search will be case insensitive.

:%s/search/replace/gci

Error 'tunneling socket' while executing npm install

Following commands may solve your issue:

npm config set proxy false
npm cache clean

It solved my same issue.

Where's the IE7/8/9/10-emulator in IE11 dev tools?

I posted an answer to this already when someone else asked the same question (see How to bring back "Browser mode" in IE11?).

Read my answer there for a fuller explaination, but in short:

  • They removed it deliberately, because compat mode is not actually really very good for testing compatibility.

  • If you really want to test for compatibility with any given version of IE, you need to test in a real copy of that IE version. MS provide free VMs on http://modern.ie/ for you to use for this purpose.

  • The only way to get compat mode in IE11 is to set the X-UA-Compatible header. When you have this and the site defaults to compat mode, you will be able to set the mode in dev tools, but only between edge or the specified compat mode; other modes will still not be available.

Common sources of unterminated string literal

If you've done any cut/paste: some online syntax highlighters will mangle single and double quotes, turning them into formatted quote pairs (matched opening and closing pairs). (tho i can't find any examples right now)... So that entails hitting Command-+ a few times and staring at your quote characters

Try a different font? also, different editors and IDEs use different tokenizers and highlight rules, and JS is one of more dynamic languages to parse, so try opening the file in emacs, vim, gedit (with JS plugins)... If you get lucky, one of them will show a long purple string running through the end of file.

Facebook development in localhost

You have to choose Facebook product 'facebook login' and enable Client OAuth Login , 'Web OAuth Login' and 'Embedded Browser OAuth Login' then even if you give localhost url It will work enter image description here

How to make a Python script run like a service or daemon in Linux

You should use the python-daemon library, it takes care of everything.

From PyPI: Library to implement a well-behaved Unix daemon process.

How to do an array of hashmaps?

You can use something like this:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class testHashes {

public static void main(String args[]){
    Map<String,String> myMap1 = new HashMap<String, String>();

    List<Map<String , String>> myMap  = new ArrayList<Map<String,String>>();

    myMap1.put("URL", "Val0");
    myMap1.put("CRC", "Vla1");
    myMap1.put("SIZE", "Val2");
    myMap1.put("PROGRESS", "Val3");

    myMap.add(0,myMap1);
    myMap.add(1,myMap1);

    for (Map<String, String> map : myMap) {
        System.out.println(map.get("URL"));
        System.out.println(map.get("CRC"));
        System.out.println(map.get("SIZE"));
        System.out.println(map.get("PROGRESS"));
    }

    //System.out.println(myMap);

}


}

How do I fix PyDev "Undefined variable from import" errors?

My answer doesn't contribute anything new, just a concrete example I encountered.

import gtk.gdk

w = gtk.gdk.get_default_root_window()

PyDev showed the error message "Undefined variable from import: get_default_root_window()"

In the python shell you can see that this is a 'built-in' module as mentioned in a answer above:

>>> import gtk.gdk
>>> gtk.gdk
<module 'gtk.gdk' (built-in)>

Now under Window->Preferences->PyDev->Interpreters->Python Interpreter, I selected the tab 'Forced Builtins' and added 'gtk.gdk' to the list.

Now the error message didn't show anymore.

Android Layout Weight

android:Layout_weight can be used when you don't attach a fix value to your width already like fill_parent etc.

Do something like this :

<Button>

Android:layout_width="0dp"
Android:layout_weight=1

-----other parameters
</Button>

Invalid application of sizeof to incomplete type with a struct

I am a beginner and may not clear syntax. To refer above information, I still not clear.

/*
 * main.c
 *
 *  Created on: 15 Nov 2019
 */

#include <stdio.h>
#include <stdint.h>
#include <string.h>

#include "dummy.h"

char arrA[] = {
        0x41,
        0x43,
        0x45,
        0x47,
        0x00,
};

#define sizeA sizeof(arrA)

int main(void){

    printf("\r\n%s",arrA);
    printf("\r\nsize of = %d", sizeof(arrA));
    printf("\r\nsize of = %d", sizeA);

    printf("\r\n%s",arrB);
    //printf("\r\nsize of = %d", sizeof(arrB));
    printf("\r\nsize of = %d", sizeB);


    while(1);

    return 0;
};

/*
 * dummy.c
 *
 *  Created on: 29 Nov 2019
 */


#include <stdio.h>
#include <stdint.h>
#include <string.h>

#include "dummy.h"


char arrB[] = {
        0x42,
        0x44,
        0x45,
        0x48,
        0x00,
};

/*
 * dummy.h
 *
 *  Created on: 29 Nov 2019
 */

#ifndef DUMMY_H_
#define DUMMY_H_

extern char arrB[];

#define sizeB sizeof(arrB)

#endif /* DUMMY_H_ */

15:16:56 **** Incremental Build of configuration Debug for project T3 ****
Info: Internal Builder is used for build
gcc -O0 -g3 -Wall -c -fmessage-length=0 -o main.o "..\\main.c" 
In file included from ..\main.c:12:
..\main.c: In function 'main':
..\dummy.h:13:21: **error: invalid application of 'sizeof' to incomplete type 'char[]'**
 #define sizeB sizeof(arrB)
                     ^
..\main.c:32:29: note: in expansion of macro 'sizeB'
  printf("\r\nsize of = %d", sizeB);
                             ^~~~~

15:16:57 Build Failed. 1 errors, 0 warnings. (took 384ms)

Both "arrA" & "arrB" can be accessed (print it out). However, can't get a size of "arrB".

What is a problem there?

  1. Is 'char[]' incomplete type? or
  2. 'sizeof' does not accept the extern variable/ label?

In my program, "arrA" & "arrB" are constant lists and fixed before to compile. I would like to use a label(let me easy to maintenance & save RAM memory).

How to get Printer Info in .NET?

This should work.

using System.Drawing.Printing;

...

PrinterSettings ps = new PrinterSettings();
ps.PrinterName = "The printer name"; // Load the appropriate printer's setting

After that, the various properties of PrinterSettings can be read.

Note that ps.isValid() can see if the printer actually exists.

Edit: One additional comment. Microsoft recommends you use a PrintDocument and modify its PrinterSettings rather than creating a PrinterSettings directly.

How to set up a PostgreSQL database in Django

Please note that installation of psycopg2 via pip or setup.py requires to have Visual Studio 2008 (more precisely executable file vcvarsall.bat). If you don't have admin rights to install it or set the appropriate PATH variable on Windows, you can download already compiled library from here.

Vbscript list all PDF files in folder and subfolders

(For those who stumble upon this from your search engine of choice)

This just recursively traces down the folder, so you don't need to duplicate your code twice. Also the OPs logic is needlessly complex.

Wscript.Echo "begin."
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objSuperFolder = objFSO.GetFolder(WScript.Arguments(0))
Call ShowSubfolders (objSuperFolder)

Wscript.Echo "end."

WScript.Quit 0

Sub ShowSubFolders(fFolder)
    Set objFolder = objFSO.GetFolder(fFolder.Path)
    Set colFiles = objFolder.Files
    For Each objFile in colFiles
        If UCase(objFSO.GetExtensionName(objFile.name)) = "PDF" Then
            Wscript.Echo objFile.Name
        End If
    Next

    For Each Subfolder in fFolder.SubFolders
        ShowSubFolders(Subfolder)
    Next
End Sub

How to create a DateTime equal to 15 minutes ago?

 datetime.datetime.now() - datetime.timedelta(minutes=15)

Does uninstalling a package with "pip" also remove the dependent packages?

No, it doesn't uninstall the dependencies packages. It only removes the specified package:

$ pip install specloud
$ pip freeze # all the packages here are dependencies of specloud package

figleaf==0.6.1
nose==1.1.2
pinocchio==0.3
specloud==0.4.5

$ pip uninstall specloud
$ pip freeze

figleaf==0.6.1
nose==1.1.2
pinocchio==0.3

As you can see those packages are dependencies from specloud and they're still there, but not the specloud package itself.

As mentioned below, You can install and use the pip-autoremove utility to remove a package plus unused dependencies.

How to unnest a nested list

Use itertools.chain:

itertools.chain(*iterables):

Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.

Example:

from itertools import chain

A = [[1,2], [3,4]]

print list(chain(*A))
# or better: (available since Python 2.6)
print list(chain.from_iterable(A))

The output is:

[1, 2, 3, 4]
[1, 2, 3, 4]

Convert date to another timezone in JavaScript

Set a variable with year, month, and day separated with '-' symbols, plus a 'T' and the time in HH:mm:ss pattern, followed by +01:00 at the end of the string (in my case the time zone is +1). Then use this string as the argument for the date constructor.

//desired format: 2001-02-04T08:16:32+01:00
dateAndTime = year+"-"+month+"-"+day+"T"+hour+":"+minutes+":00+01:00";

var date = new Date(dateAndTime );

Credit card payment gateway in PHP?

If you need something quick and dirty, you can just use PayPal's "Buy" buttons and drop them on your pages. These will take people off-site to PayPal where they can pay with a PayPal account or a credit card. This is free and super easy to implement.

If you want something a bit nicer where people pay on-site with their credit card, then you would want to look into one of those 3rd part payment providers. None of them (that I'm aware of) are completely free. All will have a per-transaction fee, and most will have a monthly fee as well.

Personally I've worked with Authorize.NET and PayPal Website Payments Pro. Both have great APIs and sample code that you can hook into via PHP easily enough.

What does InitializeComponent() do, and how does it work in WPF?

The call to InitializeComponent() (which is usually called in the default constructor of at least Window and UserControl) is actually a method call to the partial class of the control (rather than a call up the object hierarchy as I first expected).

This method locates a URI to the XAML for the Window/UserControl that is loading, and passes it to the System.Windows.Application.LoadComponent() static method. LoadComponent() loads the XAML file that is located at the passed in URI, and converts it to an instance of the object that is specified by the root element of the XAML file.

In more detail, LoadComponent creates an instance of the XamlParser, and builds a tree of the XAML. Each node is parsed by the XamlParser.ProcessXamlNode(). This gets passed to the BamlRecordWriter class. Some time after this I get a bit lost in how the BAML is converted to objects, but this may be enough to help you on the path to enlightenment.

Note: Interestingly, the InitializeComponent is a method on the System.Windows.Markup.IComponentConnector interface, of which Window/UserControl implement in the partial generated class.

Hope this helps!

How to force maven update?

We can force to get latest update of release and snapshot repository with below command :

mvn --update-snapshots clean install

C# Copy a file to another location with a different name

You may also try the Copy method:

File.Copy(@"c:\work\foo.txt", @"c:\data\bar.txt")