Programs & Examples On #Hunspell

An open source spell checker, used by OpenOffice, Firefox, Google Chrome and Mac OS X.

Git on Windows: How do you set up a mergetool?

To follow-up on Charles Bailey's answer, here's my git setup that's using p4merge (free cross-platform 3way merge tool); tested on msys Git (Windows) install:

git config --global merge.tool p4merge
git config --global mergetool.p4merge.cmd 'p4merge.exe \"$BASE\" \"$LOCAL\" \"$REMOTE\" \"$MERGED\"'

or, from a windows cmd.exe shell, the second line becomes :

git config --global mergetool.p4merge.cmd "p4merge.exe \"$BASE\" \"$LOCAL\" \"$REMOTE\" \"$MERGED\""

The changes (relative to Charles Bailey):

  • added to global git config, i.e. valid for all git projects not just the current one
  • the custom tool config value resides in "mergetool.[tool].cmd", not "merge.[tool].cmd" (silly me, spent an hour troubleshooting why git kept complaining about non-existing tool)
  • added double quotes for all file names so that files with spaces can still be found by the merge tool (I tested this in msys Git from Powershell)
  • note that by default Perforce will add its installation dir to PATH, thus no need to specify full path to p4merge in the command

Download: http://www.perforce.com/product/components/perforce-visual-merge-and-diff-tools


EDIT (Feb 2014)

As pointed out by @Gregory Pakosz, latest msys git now "natively" supports p4merge (tested on 1.8.5.2.msysgit.0).

You can display list of supported tools by running:

git mergetool --tool-help

You should see p4merge in either available or valid list. If not, please update your git.

If p4merge was listed as available, it is in your PATH and you only have to set merge.tool:

git config --global merge.tool p4merge

If it was listed as valid, you have to define mergetool.p4merge.path in addition to merge.tool:

git config --global mergetool.p4merge.path c:/Users/my-login/AppData/Local/Perforce/p4merge.exe
  • The above is an example path when p4merge was installed for the current user, not system-wide (does not need admin rights or UAC elevation)
  • Although ~ should expand to current user's home directory (so in theory the path should be ~/AppData/Local/Perforce/p4merge.exe), this did not work for me
  • Even better would have been to take advantage of an environment variable (e.g. $LOCALAPPDATA/Perforce/p4merge.exe), git does not seem to be expanding environment variables for paths (if you know how to get this working, please let me know or update this answer)

What is difference between XML Schema and DTD?

DTD can have only two types of data, the CDATA and the PCDATA. But in a schema you can use all the primitive data type that you use in the programming language and you have the flexibility of defining your own custom data types.

The developer building a schema can create custom data types based on the core data types and by using different operators and modifiers.

simple Jquery hover enlarge

Well I'm not exactly sure why your code is not working because I usually follow a different approach when trying to accomplish something similar.

But your code is erroring out.. There seems to be an issue with the way you are using scale I got the jQuery to actually execute by changing your code to the following.

$(document).ready(function(){
    $('img').hover(function() {
        $(this).css("cursor", "pointer");
        $(this).toggle({
          effect: "scale",
          percent: "90%"
        },200);
    }, function() {
         $(this).toggle({
           effect: "scale",
           percent: "80%"
         },200);

    });
});  

But I have always done it by using CSS to setup my scaling and transition..

Here is an example, hopefully it helps.

$(document).ready(function(){
    $('#content').hover(function() {
        $("#content").addClass('transition');

    }, function() {
        $("#content").removeClass('transition');
    });
});

http://jsfiddle.net/y4yAP/

git: undo all working dir changes including new files

For all tracked unstaged files use:

git checkout -- .

The . at the end is important.

You can replace . with a sub-directory name to clear only a specific sub-directory of your project. The problem is addressed specifically here.

Save Dataframe to csv directly to s3 Python

You can directly use the S3 path. I am using Pandas 0.24.1

In [1]: import pandas as pd

In [2]: df = pd.DataFrame( [ [1, 1, 1], [2, 2, 2] ], columns=['a', 'b', 'c'])

In [3]: df
Out[3]:
   a  b  c
0  1  1  1
1  2  2  2

In [4]: df.to_csv('s3://experimental/playground/temp_csv/dummy.csv', index=False)

In [5]: pd.__version__
Out[5]: '0.24.1'

In [6]: new_df = pd.read_csv('s3://experimental/playground/temp_csv/dummy.csv')

In [7]: new_df
Out[7]:
   a  b  c
0  1  1  1
1  2  2  2

Release Note:

S3 File Handling

pandas now uses s3fs for handling S3 connections. This shouldn’t break any code. However, since s3fs is not a required dependency, you will need to install it separately, like boto in prior versions of pandas. GH11915.

Regular Expression to match valid dates

If you're going to insist on doing this with a regular expression, I'd recommend something like:

( (0?1|0?3| <...> |10|11|12) / (0?1| <...> |30|31) |
  0?2 / (0?1| <...> |28|29) ) 
/ (19|20)[0-9]{2}

This might make it possible to read and understand.

CGContextDrawImage draws image upside down when passed UIImage.CGImage

drawInRect is certainly the way to go. Here's another little thing that will come in way useful when doing this. Usually the picture and the rectangle into which it is going to go don't conform. In that case drawInRect will stretch the picture. Here's a quick and cool way to make sure that the picture's aspect ration isn't changed, by reversing the transformation (which will be to fit the whole thing in):

//Picture and irect don't conform, so there'll be stretching, compensate
    float xf = Picture.size.width/irect.size.width;
    float yf = Picture.size.height/irect.size.height;
    float m = MIN(xf, yf);
    xf /= m;
    yf /= m;
    CGContextScaleCTM(ctx, xf, yf);

    [Picture drawInRect: irect];

Count number of days between two dates

I kept getting results in seconds, so this worked for me:

(Time.now - self.created_at) / 86400

error MSB6006: "cmd.exe" exited with code 1

When working with a version control system where all files are read only until checked out (like Perforce), the problem may be that you accidentally submitted into this version control system one of the VS files (like filters, for example) and the file thus cannot be overridden during build.

Just go to your working directory and check that none of VS solution related files and none of temporary created files (like all moc_ and ui_ prefixed files in QT, for example) is read only.

How to make a transparent border using CSS?

You can also use border-style: double with background-clip: padding-box, without the use of any extra (pseudo-)elements. It's probably the most compact solution, but not as flexible as the others.

For example:

<div class="circle">Some text goes here...</div>

.circle{
    width: 100px;
    height: 100px;
    padding: 50px;
    border-radius: 200px;
    border: double 15px rgba(255,255,255,0.7);
    background: rgba(255,255,255,0.7);
    background-clip: padding-box;
}

Result

If you look closely you can see that the edge between the border and the background is not perfect. This seems to be an issue in current browsers. But it's not that noticeable when the border is small.

PHP string concatenation

I think this code should work fine

while ($personCount < 10) {
$result = $personCount . "people ';
$personCount++;
}
// do not understand why do you need the (+) with the result.
echo $result;

EF 5 Enable-Migrations : No context type was found in the assembly

This error getting because of the compiler not getting 'Context' class in your application. So, you can add it manually by Add --> Class and inherit it with 'DbContext' Class For Example :

public class MyDbContext : DbContext
    {
        public DbSet<Customer> Customer { get; set; }
        public MyDbContext()
        {
        }
    }

How to get file name when user select a file via <input type="file" />?

You can use the next code:

JS

    function showname () {
      var name = document.getElementById('fileInput'); 
      alert('Selected file: ' + name.files.item(0).name);
      alert('Selected file: ' + name.files.item(0).size);
      alert('Selected file: ' + name.files.item(0).type);
    };

HTML

<body>
    <p>
        <input type="file" id="fileInput" multiple onchange="showname()"/>
    </p>    
</body>

Add property to an array of objects

It goes through the object as a key-value structure. Then it will add a new property named 'Active' and a sample value for this property ('Active) to every single object inside of this object. this code can be applied for both array of objects and object of objects.

   Object.keys(Results).forEach(function (key){
            Object.defineProperty(Results[key], "Active", { value: "the appropriate value"});
        });

vertical alignment of text element in SVG

attr("dominant-baseline", "central")

How to make HTML code inactive with comments

If you are using Eclipse then the keyboard shortcut is Ctrl + Shift + / to add a group of code. To make a comment line or select the code, right click -> Source -> Add Block Comment.

To remove the block comment, Ctrl + Shift + \ or right click -> Source -> Remove Block comment.

What is the best way to remove the first element from an array?

Keep an index of the first "live" element of the array. Removing (pretending to remove) the first element then becomes an O(1) time complexity operation.

Illegal character in path at index 16

I got this error today and unlike all the above answers my error was due to a new reason.

In my Japanese translation strings.xml file, I had removed a required string.

Some how android mixed up all the other string and this caused an error.

The solution was to include all the strings from my normal, English strings.xml

Including those strings which weren't translated to Japanese.

getString Outside of a Context or Activity

##Unique Approach

##App.getRes().getString(R.string.some_id)

This will work everywhere in app. (Util class, Dialog, Fragment or any class in your app)

(1) Create or Edit (if already exist) your Application class.

import android.app.Application;
import android.content.res.Resources;

public class App extends Application {
    private static App mInstance;
    private static Resources res;


    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        res = getResources();
    }

    public static App getInstance() {
        return mInstance;
    }

    public static Resources getRes() {
        return res;
    }

}

(2) Add name field to your manifest.xml <application tag.

<application
        android:name=".App"
        ...
        >
        ...
    </application>

Now you are good to go. Use App.getRes().getString(R.string.some_id) anywhere in app.

Cannot set property 'innerHTML' of null

Let us first try to understand the root cause as to why it is happening in first place.

Why do I get an error or Uncaught TypeError: Cannot set property 'innerHTML' of null?

The browser always loads the entire HTML DOM from top to bottom. Any JavaScript code written inside the script tags (present in head section of your HTML file) gets executed by the browser rendering engine even before your whole DOM (various HTML element tags present within body tag) is loaded. The scripts present in head tag are trying to access an element having id hello even before it has actually been rendered in the DOM. So obviously, JavaScript failed to see the element and hence you end up seeing the null reference error.

How can you make it work as before?

You want to show the "hi" message on the page as soon as the user lands on your page for the first time. So you need to hook up your code at a point when you are completely sure of the fact that DOM is fully loaded and the hello id element is accessible/available. It is achievable in two ways:

  1. Reorder your scripts: This way your scripts get fired only after the DOM containing your hello id element is already loaded. You can achieve it by simply moving the script tag after all the DOM elements i.e. at the bottom where body tag is ending. Since rendering happens from top to bottom so your scripts get executed in the end and you face no error.

_x000D_
_x000D_
    <!DOCTYPE HTML>_x000D_
    <html>_x000D_
    <head>_x000D_
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">_x000D_
    <title>Untitled Document</title>_x000D_
    </head>_x000D_
    _x000D_
    <body>_x000D_
    <div id="hello"></div>_x000D_
    _x000D_
    <script type ="text/javascript">_x000D_
        what();_x000D_
        function what(){_x000D_
            document.getElementById('hello').innerHTML = 'hi';_x000D_
        };_x000D_
    </script>_x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

  1. Use event hooking: Browser's rendering engine provides an event based hook through window.onload event which gives you the hint that browser has finished loading the DOM. So by the time when this event gets fired, you can be rest assured that your element with hello id already loaded in the DOM and any JavaScript fired thereafter which tries to access this element will not fail. So you do something like below code snippet. Please note that in this case, your script works even though it is present at the top of your HTML document inside the head tag.

_x000D_
_x000D_
<!DOCTYPE HTML>_x000D_
        <html>_x000D_
        <head>_x000D_
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">_x000D_
        <title>Untitled Document</title>_x000D_
        <script type ="text/javascript">_x000D_
            window.onload = function() {_x000D_
            what();_x000D_
            function what(){_x000D_
                document.getElementById('hello').innerHTML = 'hi';_x000D_
            };_x000D_
        }_x000D_
        </script>_x000D_
        </head>_x000D_
        _x000D_
        <body>_x000D_
        <div id="hello"></div>_x000D_
        </body>_x000D_
        </html>
_x000D_
_x000D_
_x000D_

Send auto email programmatically

Sending email programmatically with Kotlin.

  • simple email sending, not all the other features (like attachments).
  • TLS is always on
  • Only 1 gradle email dependency needed also.

I also found this list of email POP services really helpful:

https://support.office.com/en-gb/article/pop-and-imap-email-settings-for-outlook-8361e398-8af4-4e97-b147-6c6c4ac95353

How to use:

    val auth = EmailService.UserPassAuthenticator("yourUser", "yourPass")
    val to = listOf(InternetAddress("[email protected]"))
    val from = InternetAddress("[email protected]")
    val email = EmailService.Email(auth, to, from, "Test Subject", "Hello Body World")
    val emailService = EmailService("yourSmtpServer", 587)

    GlobalScope.launch { // or however you do background threads
        emailService.send(email)
    }

The code:

import java.util.*
import javax.mail.*
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeBodyPart
import javax.mail.internet.MimeMessage
import javax.mail.internet.MimeMultipart

class EmailService(private var server: String, private var port: Int) {

    data class Email(
        val auth: Authenticator,
        val toList: List<InternetAddress>,
        val from: Address,
        val subject: String,
        val body: String
    )

    class UserPassAuthenticator(private val username: String, private val password: String) : Authenticator() {
        override fun getPasswordAuthentication(): PasswordAuthentication {
            return PasswordAuthentication(username, password)
        }
    }

    fun send(email: Email) {
        val props = Properties()
        props["mail.smtp.auth"] = "true"
        props["mail.user"] = email.from
        props["mail.smtp.host"] = server
        props["mail.smtp.port"] = port
        props["mail.smtp.starttls.enable"] = "true"
        props["mail.smtp.ssl.trust"] = server
        props["mail.mime.charset"] = "UTF-8"
        val msg: Message = MimeMessage(Session.getDefaultInstance(props, email.auth))
        msg.setFrom(email.from)
        msg.sentDate = Calendar.getInstance().time
        msg.setRecipients(Message.RecipientType.TO, email.toList.toTypedArray())
//      msg.setRecipients(Message.RecipientType.CC, email.ccList.toTypedArray())
//      msg.setRecipients(Message.RecipientType.BCC, email.bccList.toTypedArray())
        msg.replyTo = arrayOf(email.from)

        msg.addHeader("X-Mailer", CLIENT_NAME)
        msg.addHeader("Precedence", "bulk")
        msg.subject = email.subject

        msg.setContent(MimeMultipart().apply {
            addBodyPart(MimeBodyPart().apply {
                setText(email.body, "iso-8859-1")
                //setContent(email.htmlBody, "text/html; charset=UTF-8")
            })
        })
        Transport.send(msg)
    }

    companion object {
        const val CLIENT_NAME = "Android StackOverflow programmatic email"
    }
}

Gradle:

dependencies {
    implementation 'com.sun.mail:android-mail:1.6.4'
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3"
}

AndroidManifest:

<uses-permission name="android.permission.INTERNET" />

CKEditor, Image Upload (filebrowserUploadUrl)

For those have same problem in Grails ckeditor plugin Give

filebrowserUploadUrl:'/YourAppName/ck/ofm'

to invoke the function that handles image uploade.if you want use your own customized function you can give that file path.

Set Jackson Timezone for Date deserialization

If you really want Jackson to return a date with another time zone than UTC (and I myself have several good arguments for that, especially when some clients just don't get the timezone part) then I usually do:

ObjectMapper mapper = new ObjectMapper();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
dateFormat.setTimeZone(TimeZone.getTimeZone("CET"));
mapper.getSerializationConfig().setDateFormat(dateFormat);
// ... etc

It has no adverse effects on those that understand the timezone-p

How to set default vim colorscheme

You can try too to put this into your ~/.vimrc file:

colorscheme Solarized

sorting a List of Map<String, String>

The following code works perfectly

public Comparator<Map<String, String>> mapComparator = new Comparator<Map<String, String>>() {
    public int compare(Map<String, String> m1, Map<String, String> m2) {
        return m1.get("name").compareTo(m2.get("name"));
    }
}

Collections.sort(list, mapComparator);

But your maps should probably be instances of a specific class.

How to assign the output of a command to a Makefile variable

With GNU Make, you can use shell and eval to store, run, and assign output from arbitrary command line invocations. The difference between the example below and those which use := is the := assignment happens once (when it is encountered) and for all. Recursively expanded variables set with = are a bit more "lazy"; references to other variables remain until the variable itself is referenced, and the subsequent recursive expansion takes place each time the variable is referenced, which is desirable for making "consistent, callable, snippets". See the manual on setting variables for more info.

# Generate a random number.
# This is not run initially.
GENERATE_ID = $(shell od -vAn -N2 -tu2 < /dev/urandom)

# Generate a random number, and assign it to MY_ID
# This is not run initially.
SET_ID = $(eval MY_ID=$(GENERATE_ID))

# You can use .PHONY to tell make that we aren't building a target output file
.PHONY: mytarget
mytarget:
# This is empty when we begin
    @echo $(MY_ID)
# This recursively expands SET_ID, which calls the shell command and sets MY_ID
    $(SET_ID)
# This will now be a random number
    @echo $(MY_ID)
# Recursively expand SET_ID again, which calls the shell command (again) and sets MY_ID (again)
    $(SET_ID)
# This will now be a different random number
    @echo $(MY_ID)

JavaScript to scroll long page to DIV

This worked for me

document.getElementById('divElem').scrollIntoView();

jquery function val() is not equivalent to "$(this).value="?

Note that :

typeof $(this) is JQuery object.

and

typeof $(this)[0] is HTMLElement object

then : if you want to apply .val() on HTMLElement , you can add this extension .

HTMLElement.prototype.val=function(v){
   if(typeof v!=='undefined'){this.value=v;return this;}
   else{return this.value}
}

Then :

document.getElementById('myDiv').val() ==== $('#myDiv').val()

And

 document.getElementById('myDiv').val('newVal') ==== $('#myDiv').val('newVal')

????? INVERSE :

Conversely? if you want to add value property to jQuery object , follow those steps :

  1. Download the full source code (not minified) i.e: example http://code.jquery.com/jquery-1.11.1.js .

  2. Insert Line after L96 , add this code value:"" to init this new prop enter image description here

  3. Search on jQuery.fn.init , it will be almost Line 2747

enter image description here

  1. Now , assign a value to value prop : (Before return statment add this.value=jQuery(selector).val()) enter image description here

Enjoy now : $('#myDiv').value

Resetting remote to a certain commit

Sourcetree: resetting remote to a certain commit

  1. If you have pushed a bad commit to your remote (origin/feature/1337_MyAwesomeFeature) like below picture

Go to Remotes

  1. Go to Remotes > origin > feature > 1337_MyAwesomeFeature
  2. Right click and choose "Delete origin/feature/1337_MyAwesomeFeature" (Or change name of it if you want a backup and skip step 4.)
  3. Click "Force delete" and "OK".

enter image description here enter image description here

  1. Select your older commit and choose "Reset current branch to this commit"
  2. Choose which mode you want to have (Hard if you don't want your last changes) and "OK".

enter image description here enter image description here

  1. Push this commit to a new origin/feature/1337_MyAwesomeFeature enter image description here

  2. Your local feature branch and your remote feature branch are now on the previous (of your choice) commit enter image description here

BackgroundWorker vs background Thread

The basic difference is, like you stated, generating GUI events from the BackgroundWorker. If the thread does not need to update the display or generate events for the main GUI thread, then it can be a simple thread.

How to determine an interface{} value's "real" type?

Here is an example of decoding a generic map using both switch and reflection, so if you don't match the type, use reflection to figure it out and then add the type in next time.

var data map[string]interface {}

...

for k, v := range data {
    fmt.Printf("pair:%s\t%s\n", k, v)   

    switch t := v.(type) {
    case int:
        fmt.Printf("Integer: %v\n", t)
    case float64:
        fmt.Printf("Float64: %v\n", t)
    case string:
        fmt.Printf("String: %v\n", t)
    case bool:
        fmt.Printf("Bool: %v\n", t)
    case []interface {}:
        for i,n := range t {
            fmt.Printf("Item: %v= %v\n", i, n)
        }
    default:
        var r = reflect.TypeOf(t)
        fmt.Printf("Other:%v\n", r)             
    }
}

Java 8 Streams: multiple filters vs. complex condition

A complex filter condition is better in performance perspective, but the best performance will show old fashion for loop with a standard if clause is the best option. The difference on a small array 10 elements difference might ~ 2 times, for a large array the difference is not that big.
You can take a look on my GitHub project, where I did performance tests for multiple array iteration options

For small array 10 element throughput ops/s: 10 element array For medium 10,000 elements throughput ops/s: enter image description here For large array 1,000,000 elements throughput ops/s: 1M elements

NOTE: tests runs on

  • 8 CPU
  • 1 GB RAM
  • OS version: 16.04.1 LTS (Xenial Xerus)
  • java version: 1.8.0_121
  • jvm: -XX:+UseG1GC -server -Xmx1024m -Xms1024m

UPDATE: Java 11 has some progress on the performance, but the dynamics stay the same

Benchmark mode: Throughput, ops/time Java 8vs11

Difference between \b and \B in regex

With a different example:

Consider this is the string and pattern to be searched for is 'cat':

text = "catmania thiscat thiscatmaina";

Now definitions,

'\b' finds/matches the pattern at the beginning or end of each word.

'\B' does not find/match the pattern at the beginning or end of each word.

Different Cases:

Case 1: At the beginning of each word

result = text.replace(/\bcat/g, "ct");

Now, result is "ctmania thiscat thiscatmaina"

Case 2: At the end of each word

result = text.replace(/cat\b/g, "ct");

Now, result is "catmania thisct thiscatmaina"

Case 3: Not in the beginning

result = text.replace(/\Bcat/g, "ct");

Now, result is "catmania thisct thisctmaina"

Case 4: Not in the end

result = text.replace(/cat\B/g, "ct");

Now, result is "ctmania thiscat thisctmaina"

Case 5: Neither beginning nor end

result = text.replace(/\Bcat\B/g, "ct");

Now, result is "catmania thiscat thisctmaina"

Hope this helps :)

AngularJS performs an OPTIONS HTTP request for a cross-origin resource

The same document says

Unlike simple requests (discussed above), "preflighted" requests first send an HTTP OPTIONS request header to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests are preflighted like this since they may have implications to user data. In particular, a request is preflighted if:

It uses methods other than GET or POST. Also, if POST is used to send request data with a Content-Type other than application/x-www-form-urlencoded, multipart/form-data, or text/plain, e.g. if the POST request sends an XML payload to the server using application/xml or text/xml, then the request is preflighted.

It sets custom headers in the request (e.g. the request uses a header such as X-PINGOTHER)

When the original request is Get with no custom headers, the browser should not make Options request which it does now. The problem is it generates a header X-Requested-With which forces the Options request. See https://github.com/angular/angular.js/pull/1454 on how to remove this header

Prevent nginx 504 Gateway timeout using PHP set_time_limit()

Since you're using php-fpm you should take advantage of fastcgi_finish_request() for processing requests you know can take longer.

How to Get the HTTP Post data in C#?

This code will list out all the form variables that are being sent in a POST. This way you can see if you have the proper names of the post values.

string[] keys = Request.Form.AllKeys;
for (int i= 0; i < keys.Length; i++) 
{
   Response.Write(keys[i] + ": " + Request.Form[keys[i]] + "<br>");
}

Using Transactions or SaveChanges(false) and AcceptAllChanges()?

With the Entity Framework most of the time SaveChanges() is sufficient. This creates a transaction, or enlists in any ambient transaction, and does all the necessary work in that transaction.

Sometimes though the SaveChanges(false) + AcceptAllChanges() pairing is useful.

The most useful place for this is in situations where you want to do a distributed transaction across two different Contexts.

I.e. something like this (bad):

using (TransactionScope scope = new TransactionScope())
{
    //Do something with context1
    //Do something with context2

    //Save and discard changes
    context1.SaveChanges();

    //Save and discard changes
    context2.SaveChanges();

    //if we get here things are looking good.
    scope.Complete();
}

If context1.SaveChanges() succeeds but context2.SaveChanges() fails the whole distributed transaction is aborted. But unfortunately the Entity Framework has already discarded the changes on context1, so you can't replay or effectively log the failure.

But if you change your code to look like this:

using (TransactionScope scope = new TransactionScope())
{
    //Do something with context1
    //Do something with context2

    //Save Changes but don't discard yet
    context1.SaveChanges(false);

    //Save Changes but don't discard yet
    context2.SaveChanges(false);

    //if we get here things are looking good.
    scope.Complete();
    context1.AcceptAllChanges();
    context2.AcceptAllChanges();

}

While the call to SaveChanges(false) sends the necessary commands to the database, the context itself is not changed, so you can do it again if necessary, or you can interrogate the ObjectStateManager if you want.

This means if the transaction actually throws an exception you can compensate, by either re-trying or logging state of each contexts ObjectStateManager somewhere.

See my blog post for more.

Evaluate if list is empty JSTL

empty is an operator:

The empty operator is a prefix operation that can be used to determine whether a value is null or empty.

<c:if test="${empty myObject.featuresList}">

How to convert std::string to lower case?

Is there an alternative which works 100% of the time?

No

There are several questions you need to ask yourself before choosing a lowercasing method.

  1. How is the string encoded? plain ASCII? UTF-8? some form of extended ASCII legacy encoding?
  2. What do you mean by lower case anyway? Case mapping rules vary between languages! Do you want something that is localised to the users locale? do you want something that behaves consistently on all systems your software runs on? Do you just want to lowercase ASCII characters and pass through everything else?
  3. What libraries are available?

Once you have answers to those questions you can start looking for a soloution that fits your needs. There is no one size fits all that works for everyone everywhere!

Converting A String To Hexadecimal In Java

Using Multiple Peoples help from multiple Threads..

I know this has been answered, but i would like to give a full encode & decode method for any others in my same situation..

Here's my Encoding & Decoding methods..

// Global Charset Encoding
public static Charset encodingType = StandardCharsets.UTF_8;

// Text To Hex
public static String textToHex(String text)
{
    byte[] buf = null;
    buf = text.getBytes(encodingType);
    char[] HEX_CHARS = "0123456789abcdef".toCharArray();
    char[] chars = new char[2 * buf.length];
    for (int i = 0; i < buf.length; ++i)
    {
        chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
        chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
    }
    return new String(chars);
}

// Hex To Text
public static String hexToText(String hex)
{
    int l = hex.length();
    byte[] data = new byte[l / 2];
    for (int i = 0; i < l; i += 2)
    {
        data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
            + Character.digit(hex.charAt(i + 1), 16));
    }
    String st = new String(data, encodingType);
    return st;
}

Git push error: Unable to unlink old (Permission denied)

Pulling may have created local change.

Add your untracked file:

git add .

Stash changes.

git stash

Drop local changes.

git stash drop

Pull with sudo permission

sudo git pull remote branch

Angular: Cannot Get /

Generally it is a versioning issue. Node.js v8 cannot compile with angular-cli 6.0 or later. angularcli v6 and above will work for lastest node versions. Please make sure if your node version is v8, then you need to install angular-cli upto 1.7.4. enter ng -v command in cmd and check the cli and node versions.

How to catch integer(0)?

if ( length(a <- which(1:3 == 5) ) ) print(a)  else print("nothing returned for 'a'") 
#[1] "nothing returned for 'a'"

On second thought I think any is more beautiful than length(.):

 if ( any(a <- which(1:3 == 5) ) ) print(a)  else print("nothing returned for 'a'") 
 if ( any(a <- 1:3 == 5 ) ) print(a)  else print("nothing returned for 'a'") 

Test if a property is available on a dynamic variable

For me this works:

if (IsProperty(() => DynamicObject.MyProperty))
  ; // do stuff



delegate string GetValueDelegate();

private bool IsProperty(GetValueDelegate getValueMethod)
{
    try
    {
        //we're not interesting in the return value.
        //What we need to know is whether an exception occurred or not

        var v = getValueMethod();
        return v != null;
    }
    catch (RuntimeBinderException)
    {
        return false;
    }
    catch
    {
        return true;
    }
}

Difference between adjustResize and adjustPan in android?

adjustResize = resize the page content

adjustPan = move page content without resizing page content

How can I check if a var is a string in JavaScript?

My personal approach, which seems to work for all cases, is testing for the presence of members that will all only be present for strings.

function isString(x) {
    return (typeof x == 'string' || typeof x == 'object' && x.toUpperCase && x.substr && x.charAt && x.trim && x.replace ? true : false);
}

See: http://jsfiddle.net/x75uy0o6/

I'd like to know if this method has flaws, but it has served me well for years.

Embedding Base64 Images

Most modern desktop browsers such as Chrome, Mozilla and Internet Explorer support images encoded as data URL. But there are problems displaying data URLs in some mobile browsers: Android Stock Browser and Dolphin Browser won't display embedded JPEGs.

I reccomend you to use the following tools for online base64 encoding/decoding:

Check the "Format as Data URL" option to format as a Data URL.

C++11 rvalues and move semantics confusion (return statement)

None of those will do any extra copying. Even if RVO isn't used, the new standard says that move construction is preferred to copy when doing returns I believe.

I do believe that your second example causes undefined behavior though because you're returning a reference to a local variable.

Could not find folder 'tools' inside SDK

If I get you correctly you have just downloaded Android sdk and want to configure it working with Eclipse. I think you miss one step from the installation of the sdk:
1) you download it
2) you extract it somewhere
3) then go to the specified directory and start AndroidManager (or was it just android??). There you specify you need platform-tools and the manager will configure that for you. This will also provide you with the 'adb' executable which is crucial for the Android developement.

After that you install ADT (which I think you already did) and from Eclipse preferences -> Android options you get a place to specify where your android-sdk is. If you specify it after you did the 'step 3' you should be good to go.

I am not 100% sure I got it correctly and what your state is, so please forgive me if my comment is irrelevant. If I am wrong I will be happy to help if you provide some more details.

Something I am completely sure is that you shouldn't need to create the folder 'tools' by yourself.

PS: The description I gave is for newer versions of android sdk, but if you are encountering a problem with older version I will recommend you to start from scratch with newer version. It shouldn't take you that long time.

SQL How to Select the most recent date item

Select Top 1* FROM test_table WHERE user_id = value order by Date_Added Desc

VideoView Full screen in android application

First Method

when you want to open a video in full screen for that Activity you have to set the theme attribute in the Manifest. set this value that is

android:theme="@android:style/Theme.NoTitleBar.Fullscreen"

change theme programmatically here

Second Method

create another fullscreen.xml like below and setContentView(R.layout.fullscreen) on click of the button

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <VideoView android:id="@+id/myvideoview"
        android:layout_width="fill_parent"
        android:layout_alignParentRight="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentBottom="true"
        android:layout_height="fill_parent">
    </VideoView>

</RelativeLayout>

How can I clear an HTML file input with JavaScript?

the input.value = null is a working method, however it will only trigger input's change event if called from an onclick event.

Solution to that would be calling that onchange handler manually whenever you need to reset the input.

function reset_input(input) {
    $(input)[0].value = null;
    input_change_handler();
}
function input_change_handler() {
    // this happens when there's been a change in file selection

    if ($(input)[0].files.length) {
        // file(s) selected
    } else {
        // nothing is selected
    }
}
$(input).on('change', input_change_handler);

How do I run pip on python for windows?

Maybe you'd like try run pip in Python shell like this:

>>> import pip
>>> pip.main(['install', 'requests'])

This will install requests package using pip.


Because pip is a module in standard library, but it isn't a built-in function(or module), so you need import it.

Other way, you should run pip in system shell(cmd. If pip is in path).

C#: Waiting for all threads to complete

With .NET 4.0 I find System.Threading.Tasks a lot easier to work with. Here's spin-wait loop which works reliably for me. It blocks the main thread until all the tasks complete. There's also Task.WaitAll, but that hasn't always worked for me.

        for (int i = 0; i < N; i++)
        {
            tasks[i] = Task.Factory.StartNew(() =>
            {               
                 DoThreadStuff(localData);
            });
        }
        while (tasks.Any(t => !t.IsCompleted)) { } //spin wait

How do you use a variable in a regular expression?

And the coffeescript version of Steven Penny's answer, since this is #2 google result....even if coffee is just javascript with a lot of characters removed...;)

baz = "foo"
filter = new RegExp(baz + "d")
"food fight".match(filter)[0] // food

and in my particular case

robot.name=hubot
filter = new RegExp(robot.name)
if msg.match.input.match(filter)
  console.log "True!"

java.security.cert.CertificateException: Certificates does not conform to algorithm constraints

Using openjdk-7 inside docker I have mounted a file with the content https://gist.github.com/dtelaroli/7d0831b1d5acc94c80209a5feb4e8f1c#file-jdk-security

#Location to mount
/usr/lib/jvm/java-7-openjdk-amd64/jre/lib/security/java.security

Thanks @luis-muñoz

Android Transparent TextView?

To set programmatically:

setBackgroundColor(Color.TRANSPARENT);

For me, I also had to set it to Color.TRANSPARENT on the parent layout.

Check if $_POST exists

  • In that case using method isset is not appropriate.

According to PHP documentation: http://php.net/manual/en/function.array-key-exists.php
(see Example #2 array_key_exists() vs isset())
The method array_key_exists is intended for checking key presence in array.

So code in the question could be changed as follow:

function fromPerson() {
   if (array_key_exists('fromPerson', $_POST) == FALSE) {
        return '';
   } else {
        return '+from%3A'.$_POST['fromPerson'];
   };
}

$newString = fromPerson();


  • Checking presence of array $_POST is not necessary because it is PHP environment global variable since version 4.1.0 (nowadays we does not meet older versions of PHP).

jQuery to retrieve and set selected option value of html select element

$('#myId').val() should do it, failing that I would try:

$('#myId option:selected').val()

Replace values in list using Python

Here's another way:

>>> L = range (11)
>>> map(lambda x: x if x%2 else None, L)
[None, 1, None, 3, None, 5, None, 7, None, 9, None]

C: What is the difference between ++i and i++?

The following C code fragment illustrates the difference between the pre and post increment and decrement operators:

int  i;
int  j;

Increment operators:

i = 1;
j = ++i;    // i is now 2, j is also 2
j = i++;    // i is now 3, j is 2

Showing loading animation in center of page while making a call to Action method in ASP .NET MVC

This is how did it works like a charm.

CSS

#loader {
position:fixed;
left:1px;
top:1px;
width: 100%;
height: 100%;
z-index: 9999;

background: url('../images/ajax-loader100X100.gif') 50% 50% no-repeat rgb(249,249,249);
}  

in _layout file inside body tag but outside the container div. Every time page loads it shows loading. Once page is loaded JS fadeout(second)


<div id="loader">
</div>

JS at the bottom of _layout file


<script type="text/javascript">
// With the element initially shown, we can hide it slowly:
 $("#loader").fadeOut(1000);
</script>  

LINQ with groupby and count

Assuming userInfoList is a List<UserInfo>:

        var groups = userInfoList
            .GroupBy(n => n.metric)
            .Select(n => new
            {
                MetricName = n.Key,
                MetricCount = n.Count()
            }
            )
            .OrderBy(n => n.MetricName);

The lambda function for GroupBy(), n => n.metric means that it will get field metric from every UserInfo object encountered. The type of n is depending on the context, in the first occurrence it's of type UserInfo, because the list contains UserInfo objects. In the second occurrence n is of type Grouping, because now it's a list of Grouping objects.

Groupings have extension methods like .Count(), .Key() and pretty much anything else you would expect. Just as you would check .Lenght on a string, you can check .Count() on a group.

Double precision - decimal places

An IEEE double has 53 significant bits (that's the value of DBL_MANT_DIG in <cfloat>). That's approximately 15.95 decimal digits (log10(253)); the implementation sets DBL_DIG to 15, not 16, because it has to round down. So you have nearly an extra decimal digit of precision (beyond what's implied by DBL_DIG==15) because of that.

The nextafter() function computes the nearest representable number to a given number; it can be used to show just how precise a given number is.

This program:

#include <cstdio>
#include <cfloat>
#include <cmath>

int main() {
    double x = 1.0/7.0;
    printf("FLT_RADIX = %d\n", FLT_RADIX);
    printf("DBL_DIG = %d\n", DBL_DIG);
    printf("DBL_MANT_DIG = %d\n", DBL_MANT_DIG);
    printf("%.17g\n%.17g\n%.17g\n", nextafter(x, 0.0), x, nextafter(x, 1.0));
}

gives me this output on my system:

FLT_RADIX = 2
DBL_DIG = 15
DBL_MANT_DIG = 53
0.14285714285714282
0.14285714285714285
0.14285714285714288

(You can replace %.17g by, say, %.64g to see more digits, none of which are significant.)

As you can see, the last displayed decimal digit changes by 3 with each consecutive value. The fact that the last displayed digit of 1.0/7.0 (5) happens to match the mathematical value is largely coincidental; it was a lucky guess. And the correct rounded digit is 6, not 5. Replacing 1.0/7.0 by 1.0/3.0 gives this output:

FLT_RADIX = 2
DBL_DIG = 15
DBL_MANT_DIG = 53
0.33333333333333326
0.33333333333333331
0.33333333333333337

which shows about 16 decimal digits of precision, as you'd expect.

Class 'App\Http\Controllers\DB' not found and I also cannot use a new Model

I like to do this witch i think is cleaner :

1 - Add the model to namespace:

use App\Employee;

2 - then you can do :

$employees = Employee::get();

or maybe somthing like this:

$employee = Employee::where('name', 'John')->first();

Configuration with name 'default' not found. Android Studio

You are better off running the command in the console to get a better idea on what is wrong with the settings. In my case, when I ran gradlew check it actually tells me which referenced project was missing.

* What went wrong:
Could not determine the dependencies of task ':test'.
Could not resolve all task dependencies for configuration ':testRuntimeClasspath'.
Could not resolve project :lib-blah.
 Required by:
     project :
  > Unable to find a matching configuration of project :lib-blah: None of the consumable configurations have attributes.

The annoying thing was that, it would not show any meaningful error message during the import failure. And if I commented out all the project references, sure it let me import it, but then once I uncomment it out, it would only print that ambiguous message and not tell you what is wrong.

How do I get SUM function in MySQL to return '0' if no values are found?

Use IFNULL or COALESCE:

SELECT IFNULL(SUM(Column1), 0) AS total FROM...

SELECT COALESCE(SUM(Column1), 0) AS total FROM...

The difference between them is that IFNULL is a MySQL extension that takes two arguments, and COALESCE is a standard SQL function that can take one or more arguments. When you only have two arguments using IFNULL is slightly faster, though here the difference is insignificant since it is only called once.

Why am I getting "void value not ignored as it ought to be"?

srand doesn't return anything so you can't initialize a with its return value because, well, because it doesn't return a value. Did you mean to call rand as well?

jQuery scrollTop not working in Chrome but working in Firefox

A better way to solve this problem is to use a function like this:

function scrollToTop(callback, q) {

    if ($('html').scrollTop()) {
        $('html').animate({ scrollTop: 0 }, function() {
            console.log('html scroll');
            callback(q)
        });
        return;
    }

    if ($('body').scrollTop()) {
        $('body').animate({ scrollTop: 0 }, function() {
            console.log('body scroll');
            callback(q)
        });
        return;
    }

    callback(q);
}

This will work across all browsers and prevents FireFox from scrolling up twice (which is what happens if you use the accepted answer - $("html,body").animate({ scrollTop: 0 }, "slow");).

Format date in a specific timezone

Just came acreoss this, and since I had the same issue, I'd just post the results I came up with

when parsing, you could update the offset (ie I am parsing a data (1.1.2014) and I only want the date, 1st Jan 2014. On GMT+1 I'd get 31.12.2013. So I offset the value first.

moment(moment.utc('1.1.2014').format());

Well, came in handy for me to support across timezones

B

Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it?

Answer is YES

<html>
<head>
</head>
<body>
<script language="javascript">
function WriteToFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("C:\\NewFile.txt", true);
var text=document.getElementById("TextArea1").innerText;
s.WriteLine(text);
s.WriteLine('***********************');
s.Close();
}
</script>

<form name="abc">
<textarea name="text">FIFA</textarea>
<button onclick="WriteToFile()">Click to save</Button>  
</form> 

</body>
</html>

How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?

it's well documented here:

https://cwiki.apache.org/confluence/display/TOMCAT/Connectors#Connectors-Q6

How do I bind to a specific ip address? - "Each Connector element allows an address property. See the HTTP Connector docs or the AJP Connector docs". And HTTP Connectors docs:

http://tomcat.apache.org/tomcat-7.0-doc/config/http.html

Standard Implementation -> address

"For servers with more than one IP address, this attribute specifies which address will be used for listening on the specified port. By default, this port will be used on all IP addresses associated with the server."

Read lines from a file into a Bash array

#!/bin/bash
IFS=$'\n' read  -d'' -r -a inlines  < testinput
IFS=$'\n' read  -d'' -r -a  outlines < testoutput
counter=0
cat testinput | while read line; 
do
    echo "$((${inlines[$counter]}-${outlines[$counter]}))"
    counter=$(($counter+1))
done
# OR Do like this
counter=0
readarray a < testinput
readarray b < testoutput
cat testinput | while read myline; 
do
    echo value is: $((${a[$counter]}-${b[$counter]}))
    counter=$(($counter+1))
done

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

I solved the same issue by following steps:

Check the angular version: Using command: ng version My angular version is: Angular CLI: 7.3.10

After that I have support version of ngx bootstrap from the link: https://www.npmjs.com/package/ngx-bootstrap

In package.json file update the version: "bootstrap": "^4.5.3", "@ng-bootstrap/ng-bootstrap": "^4.2.2",

Now after updating package.json, use the command npm update

After this use command ng serve and my error got resolved

Wildcards in jQuery selectors

Try the jQuery starts-with

selector, '^=', eg

[id^="jander"]

I have to ask though, why don't you want to do this using classes?

find the array index of an object with a specific key value in underscore

The simplest solution is to use lodash:

  1. Install lodash:

npm install --save lodash

  1. Use method findIndex:

const _ = require('lodash');

findIndexByElementKeyValue = (elementKeyValue) => {
  return _.findIndex(array, arrayItem => arrayItem.keyelementKeyValue);
}

Month name as a string

Use this :

Calendar cal=Calendar.getInstance();
SimpleDateFormat month_date = new SimpleDateFormat("MMMM");
String month_name = month_date.format(cal.getTime());

Month name will contain the full month name,,if you want short month name use this

 SimpleDateFormat month_date = new SimpleDateFormat("MMM");
 String month_name = month_date.format(cal.getTime());

Set up Python simpleHTTPserver on Windows

From Stack Overflow question What is the Python 3 equivalent of "python -m SimpleHTTPServer":

The following works for me:

python -m http.server [<portNo>]

Because I am using Python 3 the module SimpleHTTPServer has been replaced by http.server, at least in Windows.

String "true" and "false" to boolean

You could consider only appending internal to your url if it is true, then if the checkbox isn't checked and you don't append it params[:internal] would be nil, which evaluates to false in Ruby.

I'm not that familiar with the specific jQuery you're using, but is there a cleaner way to call what you want than manually building a URL string? Have you had a look at $get and $ajax?

Finding first blank row, then writing to it

ActiveSheet.Range("A10000").End(xlup).offset(1,0).Select

mysqldump data only

Would suggest using the following snippet. Works fine even with huge tables (otherwise you'd open dump in editor and strip unneeded stuff, right? ;)

mysqldump --no-create-info --skip-triggers --extended-insert --lock-tables --quick DB TABLE > dump.sql

At least mysql 5.x required, but who runs old stuff nowadays.. :)

What is copy-on-write?

It's also used in Ruby 'Enterprise Edition' as a neat way of saving memory.

Limit the output of the TOP command to a specific process name

Suppose .. if we have more than 20 process running on the server with the same name ... this will not help

top -p pgrep oracle | head -n 20 | tr "\\n" "," | sed 's/,$//'

It will try to list and provide real time output of 20 process where we have good chance of missing other prcesses which consumes more resource ....

I am still looking for better option on this

How to print register values in GDB?

There is also:

info all-registers

Then you can get the register name you are interested in -- very useful for finding platform-specific registers (like NEON Q... on ARM).

Calling a function every 60 seconds

here we console natural number 0 to ......n (next number print in console every 60 sec.) , using setInterval()

var count = 0;
function abc(){
    count ++;
    console.log(count);
}
setInterval(abc,60*1000);

How to get a Char from an ASCII Character Code in c#

You can simply write:

char c = (char) 2;

or

char c = Convert.ToChar(2);

or more complex option for ASCII encoding only

char[] characters = System.Text.Encoding.ASCII.GetChars(new byte[]{2});
char c = characters[0];

Java, List only subdirectories from a directory, not files

You can use the File class to list the directories.

File file = new File("/path/to/directory");
String[] directories = file.list(new FilenameFilter() {
  @Override
  public boolean accept(File current, String name) {
    return new File(current, name).isDirectory();
  }
});
System.out.println(Arrays.toString(directories));

Update

Comment from the author on this post wanted a faster way, great discussion here: How to retrieve a list of directories QUICKLY in Java?

Basically:

  1. If you control the file structure, I would try to avoid getting into that situation.
  2. In Java NIO.2, you can use the directories function to return an iterator to allow for greater scaling. The directory stream class is an object that you can use to iterate over the entries in a directory.

How to write hello world in assembler under Windows?

Unless you call some function this is not at all trivial. (And, seriously, there's no real difference in complexity between calling printf and calling a win32 api function.)

Even DOS int 21h is really just a function call, even if its a different API.

If you want to do it without help you need to talk to your video hardware directly, likely writing bitmaps of the letters of "Hello world" into a framebuffer. Even then the video card is doing the work of translating those memory values into DisplayPort/HDMI/DVI/VGA signals.

Note that, really, none of this stuff all the way down to the hardware is any more interesting in ASM than in C. A "hello world" program boils down to a function call. One nice thing about ASM is that you can use any ABI you want fairly easily; you just need to know what that ABI is.

PDO error message?

Maybe this post is too old but it may help as a suggestion for someone looking around on this : Instead of using:

 print_r($this->pdo->errorInfo());

Use PHP implode() function:

 echo 'Error occurred:'.implode(":",$this->pdo->errorInfo());

This should print the error code, detailed error information etc. that you would usually get if you were using some SQL User interface.

Hope it helps

Creating Dynamic button with click event in JavaScript

<!DOCTYPE html>
<html>
<body>

<p>Click the button to make a BUTTON element with text.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var btn = document.createElement("BUTTON");
    var t = document.createTextNode("CLICK ME");

    btn.setAttribute("style","color:red;font-size:23px");

    btn.appendChild(t);
    document.body.appendChild(btn);

    btn.setAttribute("onclick", alert("clicked"));

}
</script>

</body>
</html>

how to call a variable in code behind to aspx page

You can access a public/protected property using the data binding expression <%# myproperty %> as given below:

    <asp:Label ID="Label1" runat="server" Text="<%#CodeBehindVarPublic %>"></asp:Label>

you should call DataBind method, otherwise it can't be evaluated.

    public partial class WebForm1 : System.Web.UI.Page
    {
     public string CodeBehindVarPublic { get; set; }
      protected void Page_Load(object sender, EventArgs e)
        {
          CodeBehindVarPublic ="xyz";
       //you should call the next line  in case of using <%#CodeBehindVarPublic %>

          DataBind();
        }

}

Move to another EditText when Soft Keyboard Next is clicked on Android

android:inputType="textNoSuggestions"
android:imeOptions="actionNext"
android:singleLine="true"
android:nextFocusForward="@+id/.."

Adding extra field

android:inputType="textNoSuggestions"

worked in my case!

Matplotlib transparent line plots

It really depends on what functions you're using to plot the lines, but try see if the on you're using takes an alpha value and set it to something like 0.5. If that doesn't work, try get the line objects and set their alpha values directly.

Finding last occurrence of substring in string, replacing that

NaĂŻve approach:

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

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

Aditya Sihag's answer with a single rfind:

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

Java - How to access an ArrayList of another class?

You can do this by providing in class numbers:

  • A method that returns the ArrayList object itself.
  • A method that returns a non-modifiable wrapper of the ArrayList. This prevents modification to the list without the knowledge of the class numbers.
  • Methods that provide the set of operations you want to support from class numbers. This allows class numbers to control the set of operations supported.

By the way, there is a strong convention that Java class names are uppercased.

Case 1 (simple getter):

public class Numbers {
      private List<Integer> list;
      public List<Integer> getList() { return list; }
      ...
}

Case 2 (non-modifiable wrapper):

public class Numbers {
      private List<Integer> list;
      public List<Integer> getList() { return Collections.unmodifiableList( list ); }
      ...
}

Case 3 (specific methods):

public class Numbers {
      private List<Integer> list;
      public void addToList( int i ) { list.add(i); }
      public int getValueAtIndex( int index ) { return list.get( index ); }
      ...
}

How to delete all files older than 3 days when "Argument list too long"?

Another solution for the original question, esp. useful if you want to remove only SOME of the older files in a folder, would be smth like this:

find . -name "*.sess" -mtime +100 

and so on.. Quotes block shell wildcards, thus allowing you to "find" millions of files :)

Regular expression negative lookahead

A negative lookahead says, at this position, the following regex can not match.

Let's take a simplified example:

a(?!b(?!c))

a      Match: (?!b) succeeds
ac     Match: (?!b) succeeds
ab     No match: (?!b(?!c)) fails
abe    No match: (?!b(?!c)) fails
abc    Match: (?!b(?!c)) succeeds

The last example is a double negation: it allows a b followed by c. The nested negative lookahead becomes a positive lookahead: the c should be present.

In each example, only the a is matched. The lookahead is only a condition, and does not add to the matched text.

How to hide a mobile browser's address bar?

In my case problem was in css and html layout. Layout was something like html - body - root - ... html and body was overflow: hidden, and root was position: fixed, height: 100vh.

Whith this layout browser tabs on mobile doesnt hide. For solve this I delete overflow: hidden from html and body and delete position: fixed, height: 100vh from root.

CRON job to run on the last day of the month

Some cron implementations support the "L" flag to represent the last day of the month.

If you're lucky to be using one of those implementations, it's as simple as:

0 55 23 L * ?

That will run at 11:55 pm on the last day of every month.

http://www.quartz-scheduler.org/documentation/quartz-1.x/tutorials/crontrigger

Python open() gives FileNotFoundError/IOError: Errno 2 No such file or directory

  • Make sure the file exists: use os.listdir() to see the list of files in the current working directory
  • Make sure you're in the directory you think you're in with os.getcwd() (if you launch your code from an IDE, you may well be in a different directory)
  • You can then either:
    • Call os.chdir(dir), dir being the folder where the file is located, then open the file with just its name like you were doing.
    • Specify an absolute path to the file in your open call.
  • Remember to use a raw string if your path uses backslashes, like so: dir = r'C:\Python32'
    • If you don't use raw-string, you have to escape every backslash: 'C:\\User\\Bob\\...'
    • Forward-slashes also work on Windows 'C:/Python32' and do not need to be escaped.

Let me clarify how Python finds files:

  • An absolute path is a path that starts with your computer's root directory, for example 'C:\Python\scripts..' if you're on Windows.
  • A relative path is a path that does not start with your computer's root directory, and is instead relative to something called the working directory. You can view Python's current working directory by calling os.getcwd().

If you try to do open('sortedLists.yaml'), Python will see that you are passing it a relative path, so it will search for the file inside the current working directory. Calling os.chdir will change the current working directory.

Example: Let's say file.txt is found in C:\Folder.

To open it, you can do:

os.chdir(r'C:\Folder')
open('file.txt') #relative path, looks inside the current working directory

or

open(r'C:\Folder\file.txt') #full path

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

I encountered this error recently and after some brief investigation, found the cause to be that we were running out of space on the disk holding the database (less than 1GB).

As soon as I moved out the database files (.mdf and .ldf) to another disk on the same server (with lots more space), the same page (running the query) that had timed-out loaded within three seconds.

One other thing to investigate, while trying to resolve this error, is the size of the database log files. Your log files just might need to be shrunk.

Optimum way to compare strings in JavaScript?

You can use the comparison operators to compare strings. A strcmp function could be defined like this:

function strcmp(a, b) {
    if (a.toString() < b.toString()) return -1;
    if (a.toString() > b.toString()) return 1;
    return 0;
}

Edit    Here’s a string comparison function that takes at most min { length(a), length(b) } comparisons to tell how two strings relate to each other:

function strcmp(a, b) {
    a = a.toString(), b = b.toString();
    for (var i=0,n=Math.max(a.length, b.length); i<n && a.charAt(i) === b.charAt(i); ++i);
    if (i === n) return 0;
    return a.charAt(i) > b.charAt(i) ? -1 : 1;
}

SMTP error 554

Just had this issue with an Outlook client going through a Exchange server to an external address on Windows XP. Clearing the temp files seemed to do the trick.

How to insert pandas dataframe via mysqldb into database?

This should do the trick:

import pandas as pd
import pymysql
pymysql.install_as_MySQLdb()
from sqlalchemy import create_engine

# Create engine
engine = create_engine('mysql://USER_NAME_HERE:PASS_HERE@HOST_ADRESS_HERE/DB_NAME_HERE')

# Create the connection and close it(whether successed of failed)
with engine.begin() as connection:
  df.to_sql(name='INSERT_TABLE_NAME_HERE/INSERT_NEW_TABLE_NAME', con=connection, if_exists='append', index=False)

Kubernetes Pod fails with CrashLoopBackOff

The issue caused by the docker container which exits as soon as the "start" process finishes. i added a command that runs forever and it worked. This issue mentioned here

C++11 reverse range-based for-loop

If you can use range v3 , you can use the reverse range adapter ranges::view::reverse which allows you to view the container in reverse.

A minimal working example:

#include <iostream>
#include <vector>
#include <range/v3/view.hpp>

int main()
{
    std::vector<int> intVec = {1, 2, 3, 4, 5, 6, 7, 8, 9};

    for (auto const& e : ranges::view::reverse(intVec)) {
        std::cout << e << " ";   
    }
    std::cout << std::endl;

    for (auto const& e : intVec) {
        std::cout << e << " ";   
    }
    std::cout << std::endl;
}

See DEMO 1.

Note: As per Eric Niebler, this feature will be available in C++20. This can be used with the <experimental/ranges/range> header. Then the for statement will look like this:

for (auto const& e : view::reverse(intVec)) {
       std::cout << e << " ";   
}

See DEMO 2

Dark theme in Netbeans 7 or 8

Netbeans 8

Tools -> Options -> Appearance (Look & Feel Tab)

(NetBeans -> Preferences -> Appearance (Look & Feel Tab) on OS X)

Netbeans 7.x

Tools -> Plugins -> Available -> Dark Look and Feel - Install this plugin.

Once this plugin is installed, restarting netbeans should automatically switch to Dark Metal.

There are 2 themes that comes with this plugin - Dark Metal & Dark Nimbus

In order to switch themes, use the below option :

Tools -> Options -> Miscellaneous -> Windows -> Preferred Look & Feel option

enter image description here

Which HTML elements can receive focus?

$focusable:
  'a[href]',
  'area[href]',
  'button',
  'details',
  'input',
  'iframe',
  'select',
  'textarea',

  // these are actually case sensitive but i'm not listing out all the possible variants
  '[contentEditable=""]',
  '[contentEditable="true"]',
  '[contentEditable="TRUE"]',

  '[tabindex]:not([tabindex^="-"])',
  ':not([disabled])';

I'm creating a SCSS list of all focusable elements and I thought this might help someone due to this question's Google rank.

A few things to note:

  • I changed :not([tabindex="-1"]) to :not([tabindex^="-"]) because it's perfectly plausible to generate -2 somehow. Better safe than sorry right?
  • Adding :not([tabindex^="-"]) to all the other focusable selectors is completely pointless. When using [tabindex]:not([tabindex^="-"]) it already includes all elements that you'd be negating with :not!
  • I included :not([disabled]) because disabled elements can never be focusable. So again it's useless to add it to every single element.

The difference between Classes, Objects, and Instances

Class

  • It has logical existence, i.e. no memory space is allocated when it is created.

  • It is a set of objects.

  • A class may be regarded as a blueprint to create objects.

    • It is created using class keyword

    • A class defines the methods and data members that will be possessed by Objects.


Object

  • It has physical existence, i.e. memory space is allocated when it is created.

  • It is an instance of a class.

  • An object is a unique entity which contains data members and member functions together in OOP language.

    • It is created using new keyword

    • An object specifies the implementations of the methods and the values that will be possessed by the data members in the class.

SQL Joins Vs SQL Subqueries (Performance)?

I know this is an old post, but I think this is a very important topic, especially nowadays where we have 10M+ records and talk about terabytes of data.

I will also weight in with the following observations. I have about 45M records in my table ([data]), and about 300 records in my [cats] table. I have extensive indexing for all of the queries I am about to talk about.

Consider Example 1:

UPDATE d set category = c.categoryname
FROM [data] d
JOIN [cats] c on c.id = d.catid

versus Example 2:

UPDATE d set category = (SELECT TOP(1) c.categoryname FROM [cats] c where c.id = d.catid)
FROM [data] d

Example 1 took about 23 mins to run. Example 2 took around 5 mins.

So I would conclude that sub-query in this case is much faster. Of course keep in mind that I am using M.2 SSD drives capable of i/o @ 1GB/sec (thats bytes not bits), so my indexes are really fast too. So this may affect the speeds too in your circumstance

If its a one-off data cleansing, probably best to just leave it run and finish. I use TOP(10000) and see how long it takes and multiply by number of records before I hit the big query.

If you are optimizing production databases, I would strongly suggest pre-processing data, i.e. use triggers or job-broker to async update records, so that real-time access retrieves static data.

What HTTP traffic monitor would you recommend for Windows?

Wireshark if you want to see everything going on in the network.

Fiddler if you want to just monitor HTTP/s traffic.

Live HTTP Headers if you're in Firefox and want a quick plugin just to see the headers.

Also FireBug can get you that information too and provides a nice interface when your working on a single page during development. I've used it to monitor AJAX transactions.

How to programmatically open the Permission Screen for a specific app on Android Marshmallow?

it is not possible to pragmatically get the permission... but ill suggest you to put that line of code in try{} catch{} which make your app unfortunately stop... and in catch body make a dialog box which will navigate the user to small tutorial to enable the draw over other apps permission... then on yes button click put this code...

 Intent callSettingIntent= new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
            startActivity(callSettingIntent);

this intent is to directly open the list of draw over other apps to manage permissions and then from here it is one click to the draw over other apps Permissions ... i know this is Not the answer you're looking for... but Im doing this in my apps...

PowerShell: how to grep command output?

Your problem is that alias emits a stream of AliasInfo objects, rather than a stream of strings. This does what I think you want.

alias | out-string -stream | select-string Alias

or as a function

function grep {
  $input | out-string -stream | select-string $args
}

alias | grep Alias

When you don't handle things that are in the pipeline (like when you just ran 'alias'), the shell knows to use the ToString() method on each object (or use the output formats specified in the ETS info).

Mongoose: Find, modify, save

You could also write it a little more cleaner using updateOne & $set, plus async/await.

const updateUser = async (newUser) => {
  try {
    await User.updateOne({ username: oldUsername }, {
      $set: {
        username: newUser.username,
        password: newUser.password,
        rights: newUser.rights
      }
    })
  } catch (err) {
    console.log(err)
  }
}

Since you don't need the resulting document, you can just use updateOne instead of findOneAndUpdate.

Here's a good discussion about the difference: MongoDB 3.2 - Use cases for updateOne over findOneAndUpdate

How to base64 encode image in linux bash / shell

Single line result:

base64 -w 0 DSC_0251.JPG

For HTML:

echo "data:image/jpeg;base64,$(base64 -w 0 DSC_0251.JPG)"

As file:

base64 -w 0 DSC_0251.JPG > DSC_0251.JPG.base64

In variable:

IMAGE_BASE64="$(base64 -w 0 DSC_0251.JPG)"

In variable for HTML:

IMAGE_BASE64="data:image/jpeg;base64,$(base64 -w 0 DSC_0251.JPG)"

Get you readable data back:

base64 -d DSC_0251.base64 > DSC_0251.JPG 

See: http://www.greywyvern.com/code/php/binary2base64

Removing "NUL" characters

Highlight a single null character, goto find replace - it usually automatically inserts the highlighted text into the find box. Enter a space into or leave blank the replace box.

Delete/Reset all entries in Core Data?

Swift 5.1 Solution

public static func reset() {
    let coordinator = _persistentContainer.persistentStoreCoordinator
    for store in coordinator.persistentStores where store.url != nil {
        try? coordinator.remove(store)
        try? FileManager.default.removeItem(atPath: store.url!.path)
    }
}

Simple Popup by using Angular JS

If you are using bootstrap.js then the below code might be useful. This is very simple. Dont have to write anything in js to invoke the pop-up.

Source :http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Modal Example</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div>

</div>

</body>
</html>

Java and HTTPS url connection without downloading certificate

A simple, but not pure java solution, is to shell out to curl from java, which gives you complete control over how the request is done. If you're just doing this for something simple, this allows you to ignore certificate errors at times, by using this method. This example shows how to make a request against a secure server with a valid or invalid certificate, pass in a cookie, and get the output using curl from java.

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

public class MyTestClass
{
  public static void main(String[] args) 
  {
    String url = "https://www.google.com";
    String sessionId = "faf419e0-45a5-47b3-96d1-8c62b2a3b558";

    // Curl options are:
    // -k: ignore certificate errors
    // -L: follow redirects
    // -s: non verbose
    // -H: add a http header

    String[] command = { "curl", "-k", "-L", "-s", "-H", "Cookie: MYSESSIONCOOKIENAME=" + sessionId + ";", "-H", "Accept:*/*", url };
    String output = executeShellCmd(command, "/tmp", true, true);
    System.out.println(output);
  }

  public String executeShellCmd(String[] command, String workingFolder, boolean wantsOutput, boolean wantsErrors)
  {
    try
    {
      ProcessBuilder pb = new ProcessBuilder(command);
      File wf = new File(workingFolder);
      pb.directory(wf);

      Process proc = pb.start();
      BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
      BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

      StringBuffer sb = new StringBuffer();
      String newLine = System.getProperty("line.separator");
      String s;

      // read stdout from the command
      if (wantsOutput)
      {
        while ((s = stdInput.readLine()) != null)
        {
          sb.append(s);
          sb.append(newLine);
        }
      }

      // read any errors from the attempted command
      if (wantsErrors)
      {
        while ((s = stdError.readLine()) != null)
        {
          sb.append(s);
          sb.append(newLine);
        }
      }

      String result = sb.toString();

      return result;
    }
    catch (IOException e)
    {
      throw new RuntimeException("Problem occurred:", e);
    }
  }


}

What is the difference between Sublime text and Github's Atom

  1. How is Atom different from Sublime?
    • Atom is an open source text editor/IDE, built on JavaScript/HTML/CSS.
    • Sublime Text is a commercial product, built on C/C++ and Python.
    • Comparable to Atom is Adobe Brackets, another open source text editor/IDE built on JavaScript/HTML/CSS. Be minded that this makes Brackets more oriented towards Web development, specially in the front end.
    • Advantages of open source projects are faster rate of development and, of course, price.
  2. Does it include IDE features like build tools, function definition jumps, documentations, etc.?
    • The short answer is yes, yes, and yes. The app is completely modular. Open source will give people the freedom to fill the gaps on several of these features.
  3. Has anyone using Sublime got a Beta invitation to point out the differences?
    • Advantages of Atom is entry-level hackability, since it's built on the same code that powers Web sites.
    • Advantages of Sublime Text is performance, as it doesn't need to run on top of Node.js, and it's a more mature product, about to reach a stable version 3.
    • There are a long list of minor differences that can be included in the comments (I wish this markdown could be able to draw a table for comparisons, but that's another issue).
    • Because of Atom's rapid turnout, I am afraid some of differences I list here will become outdated over time. Per example, at the time of this writing, Atom is only available on the Macintosh while Sublime Text is already multiplatform.
  4. Can I use the themes, schemes and packages from Sublime as is, like Sublime could do with text mate.
    • The short answer is no, but because of Atom's hackability, it will be easy to retool packages from other editors to Atom.

How to insert the current timestamp into MySQL database using a PHP insert query

What error message are you getting?

I'd guess your actual error is because your php variable isn't wrapped in quotes. Try this

$update_query = "UPDATE db.tablename SET insert_time=now() WHERE username='" .$somename . "'"; 

Get the current file name in gulp.src()

You can use the gulp-filenames module to get the array of paths. You can even group them by namespaces:

var filenames = require("gulp-filenames");

gulp.src("./src/*.coffee")
    .pipe(filenames("coffeescript"))
    .pipe(gulp.dest("./dist"));

gulp.src("./src/*.js")
  .pipe(filenames("javascript"))
  .pipe(gulp.dest("./dist"));

filenames.get("coffeescript") // ["a.coffee","b.coffee"]  
                              // Do Something With it 

How to set max and min value for Y axis

window.onload = function(){
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx ,{
          type: 'line',
          data: yourData,
          options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero:true,
                        min: 0,
                        max: 500    
                    }
                  }]
               }
            }
});

I configure with 'options' in v2.

You should read documentation: http://www.chartjs.org/docs/#scales-linear-scale

Get the current time in C

Copy-pasted from here:

/* localtime example */
#include <stdio.h>
#include <time.h>

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;

  time ( &rawtime );
  timeinfo = localtime ( &rawtime );
  printf ( "Current local time and date: %s", asctime (timeinfo) );
  
  return 0;
}

(just add void to the main() arguments list in order for this to work in C)

password for postgres

Set the default password in the .pgpass file. If the server does not save the password, it is because it is not set in the .pgpass file, or the permissions are open and the file is therefore ignored.

Read more about the password file here.

Also, be sure to check the permissions: on *nix systems the permissions on .pgpass must disallow any access to world or group; achieve this by the command chmod 0600 ~/.pgpass. If the permissions are less strict than this, the file will be ignored.

Have you tried logging-in using PGAdmin? You can save the password there, and modify the pgpass file.

jQuery Ajax POST example with PHP

Since the introduction of the Fetch API there really is no reason any more to do this with jQuery Ajax or XMLHttpRequests. To POST form data to a PHP-script in vanilla JavaScript you can do the following:

_x000D_
_x000D_
function postData() {_x000D_
    const form = document.getElementById('form');_x000D_
    const data = new FormData();_x000D_
    data.append('name', form.name.value);_x000D_
_x000D_
    fetch('../php/contact.php', {method: 'POST', body: data}).then(response => {_x000D_
        if (!response.ok){_x000D_
            throw new Error('Network response was not ok.');_x000D_
        }_x000D_
    }).catch(err => console.log(err));_x000D_
}
_x000D_
<form id="form" action="javascript:postData()">_x000D_
    <input id="name" name="name" placeholder="Name" type="text" required>_x000D_
    <input type="submit" value="Submit">_x000D_
</form>
_x000D_
_x000D_
_x000D_

Here is a very basic example of a PHP-script that takes the data and sends an email:

<?php
    header('Content-type: text/html; charset=utf-8');

    if (isset($_POST['name'])) {
        $name = $_POST['name'];
    }

    $to = "[email protected]";
    $subject = "New name submitted";
    $body = "You received the following name: $name";

    mail($to, $subject, $body);

Increment variable value by 1 ( shell programming)

These are the methods I know:

ichramm@NOTPARALLEL ~$ i=10; echo $i;
10
ichramm@NOTPARALLEL ~$ ((i+=1)); echo $i;
11
ichramm@NOTPARALLEL ~$ ((i=i+1)); echo $i;
12
ichramm@NOTPARALLEL ~$ i=`expr $i + 1`; echo $i;
13

Note the spaces in the last example, also note that's the only one that uses $i.

Is the order of elements in a JSON list preserved?

Yes, the order of elements in JSON arrays is preserved. From RFC 7159 -The JavaScript Object Notation (JSON) Data Interchange Format (emphasis mine):

An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

An array is an ordered sequence of zero or more values.

The terms "object" and "array" come from the conventions of JavaScript.

Some implementations do also preserve the order of JSON objects as well, but this is not guaranteed.

Problems after upgrading to Xcode 10: Build input file cannot be found

I ran into this problem soon after upgrading to Xcode 10, but that was not the issue.

I tried changing the build system, but that gave me a separate error that meant the same thing. Generally saying "File X can not be found".

There are multiple things to check when a file can not be found.

  1. Recovered references Folder Apple does this nice thing where if it detects a reference to a file that doesn't exists it will add this reference into a group called "Recovered References"

That is nice of Apple but it doesn't always work.

  1. Build Phases Compile Sources In this list, there could be meta data for a file that the project is suppose to compile, but the file does not actually exists and it's attempting to find the file at the given path. In this list it will be dimmed out, delete them and re-add them by toggling the file's target dependencies or manually removing it and dragging it in.

  2. File's Path Double check the file path that the error is printing out and the file path for the file in finder. You can easily see this by clicking on the file in Xcode and checking the "Show the file inspector" tab (the left most tab). If these paths are correct then you are good!

  3. Dimmed out files in your project that are not in recovered references or red This one pissed me off because it's not obvious about what happened, but basically if you go into finder and move a file to a different location with out updating the reference in the project it will throw the error as the file no longer exists there. The only indication I have found for that is that the file in the "Project Navigator" tab (left most tab) is very slightly dimmed, but when you go to delete this file Xcode doesn't prompt you to delete the reference or send to trash. You can fix this by deleting the file and re-adding it to the project or going to the "File Inspector" tab and click the folder icon next to the path and change it to the proper location.

Either way, the error indicates that it can't find a file, switching to the old build system is a bandaid for a more concrete issue. We as developers understand that a compiler just wants an artifact to be listed at the end of a file path. Somewhere the path is not correct! We have to find where that is!

My issue was resolved with item 4 listed above. Hope this helps somebody.

Keep values selected after form submission

This works for me!

<label for="reason">Reason:</label>
<select name="reason" size="1" id="name" >
    <option value="NG" selected="SELECTED"><?php if (!(strcmp("NG", $_POST["reason"]))) {echo "selected=\"selected\"";} ?>Selection a reason below</option>
    <option value="General"<?php if (!(strcmp("General", $_POST["reason"]))) {echo "selected=\"selected\"";} ?>>General Question</option>
    <option value="Account"<?php if (!(strcmp("Account", $_POST["reason"]))) {echo "selected=\"selected\"";} ?>>Account Question</option>
    <option value="Other"<?php if (!(strcmp("Other", $_POST["reason"]))) {echo "selected=\"selected\"";} ?>>Other</option>

</select>

Execute the setInterval function without delay the first time

To solve this problem , I run the function a first time after the page has loaded.

function foo(){ ... }

window.onload = function() {
   foo();
};

window.setInterval(function()
{
    foo(); 
}, 5000);

set background color: Android

By the way, a good tip on quickly selecting color on the newer versions of AS is simply to type #fff and then using the color picker on the side of the code to choose the one you want. Quick and easier than remembering all the color hexadecimals. For example:

android:background="#fff"

Jquery show/hide table rows

The filter function wasn't working for me at all; maybe the more recent version of jquery doesn't perform as the version used in above code. Regardless; I used:

    var black = $('.black');
    var white = $('.white');

The selector will find every element classed under black or white. Button functions stay as stated above:

    $('#showBlackButton').click(function() {
           black.show();
           white.hide();
    });

    $('#showWhiteButton').click(function() {
           white.show();
           black.hide();
    });

How can I let a table's body scroll but keep its head fixed in place?

I saw Sean Haddy's excellent solution to a similar question and took the liberty of making some edits:

  • Use classes instead of ID, so one jQuery script could be reused for multiple tables on one page
  • Added support for semantic HTML table elements like caption, thead, tfoot, and tbody
  • Made scrollbar optional so it won't appear for tables that are "shorter" than the scrollable height
  • Adjusted scrolling div's width to bring the scrollbar up to the right edge of the table
  • Made concept accessible by
    • using aria-hidden="true" on injected static table header
    • and leaving original thead in place, just hidden with jQuery and set aria-hidden="false"
  • Showed examples of multiple tables with different sizes

Sean did the heavy lifting, though. Thanks to Matt Burland, too, for pointing out need to support tfoot.

Please see for yourself at http://jsfiddle.net/jhfrench/eNP2N/

Is there a better way to iterate over two lists, getting one element from each list for each iteration?

Iterating through elements of two lists simultaneously is known as zipping, and python provides a built in function for it, which is documented here.

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zipped)
>>> x == list(x2) and y == list(y2)
True

[Example is taken from pydocs]

In your case, it will be simply:

for (lat, lon) in zip(latitudes, longitudes):
    ... process lat and lon

How do I migrate an SVN repository with history to a new Git repository?

If you are using SourceTree you can do this directly from the app. Goto File -> New/Clone then do the following:

  1. Enter the remote SVN URL as the "Source Path / URL".
  2. Enter your credentials when prompted.
  3. Enter the local folder location as the "Destination path".
  4. Give it a name.
  5. In the advanced options select "Git" from the dropdown in "Create local repository of type".
  6. You can optionally specify a revision to clone from.
  7. Hit Clone.

Open the repo in SourceTree and you'll see your commit messages have been migrated too.

Now go to Repository -> Repository Settings and add the new remote repo details. Delete the SVN remote if you wish (I did this through the "Edit Config File" option.

Push the code to the new remote repo when you are ready and code freely.

HTML form with side by side input fields

Put style="float:left" on each of your divs:

<div style="float:left;">...........

Example:

<div style="float:left;">
  <label for="username">First Name</label>
  <input id="user_first_name" name="user[first_name]" size="30" type="text" />
</div>

<div style="float:left;">
  <label for="name">Last Name</label>
  <input id="user_last_name" name="user[last_name]" size="30" type="text" />
</div>

To put an element on new line, put this div below it:

<div style="clear:both;">&nbsp;</div>

Of course, you can also create classes in the CSS file:

.left{
  float:left;
}

.clear{
  clear:both;
}

And then your html should look like this:

<div class="left">
  <label for="username">First Name</label>
  <input id="user_first_name" name="user[first_name]" size="30" type="text" />
</div>

<div class="left">
  <label for="name">Last Name</label>
  <input id="user_last_name" name="user[last_name]" size="30" type="text" />
</div>

To put an element on new line, put this div below it:

<div class="clear">&nbsp;</div>

More Info:

How to send file contents as body entity using cURL

In my case, @ caused some sort of encoding problem, I still prefer my old way:

curl -d "$(cat /path/to/file)" https://example.com

Log4j2 configuration - No log4j2 configuration file found

Eclipse will never see a file until you force a refresh of the IDE. Its a feature! So you can put the file all over the project and Eclipse will ignore it completely and throw these errors. Hit refresh in Eclipse project view and then it works.

Timer function to provide time in nano seconds using C++

Minimalistic copy&paste-struct + lazy usage

If the idea is to have a minimalistic struct that you can use for quick tests, then I suggest you just copy and paste anywhere in your C++ file right after the #include's. This is the only instance in which I sacrifice Allman-style formatting.

You can easily adjust the precision in the first line of the struct. Possible values are: nanoseconds, microseconds, milliseconds, seconds, minutes, or hours.

#include <chrono>
struct MeasureTime
{
    using precision = std::chrono::microseconds;
    std::vector<std::chrono::steady_clock::time_point> times;
    std::chrono::steady_clock::time_point oneLast;
    void p() {
        std::cout << "Mark " 
                << times.size()/2
                << ": " 
                << std::chrono::duration_cast<precision>(times.back() - oneLast).count() 
                << std::endl;
    }
    void m() {
        oneLast = times.back();
        times.push_back(std::chrono::steady_clock::now());
    }
    void t() {
        m();
        p();
        m();
    }
    MeasureTime() {
        times.push_back(std::chrono::steady_clock::now());
    }
};

Usage

MeasureTime m; // first time is already in memory
doFnc1();
m.t(); // Mark 1: next time, and print difference with previous mark
doFnc2();
m.t(); // Mark 2: next time, and print difference with previous mark
doStuff = doMoreStuff();
andDoItAgain = doStuff.aoeuaoeu();
m.t(); // prints 'Mark 3: 123123' etc...

Standard output result

Mark 1: 123
Mark 2: 32
Mark 3: 433234

If you want summary after execution

If you want the report afterwards, because for example your code in between also writes to standard output. Then add the following function to the struct (just before MeasureTime()):

void s() { // summary
    int i = 0;
    std::chrono::steady_clock::time_point tprev;
    for(auto tcur : times)
    {
        if(i > 0)
        {
            std::cout << "Mark " << i << ": "
                    << std::chrono::duration_cast<precision>(tprev - tcur).count()
                    << std::endl;
        }
        tprev = tcur;
        ++i;
    }
}

So then you can just use:

MeasureTime m;
doFnc1();
m.m();
doFnc2();
m.m();
doStuff = doMoreStuff();
andDoItAgain = doStuff.aoeuaoeu();
m.m();
m.s();

Which will list all the marks just like before, but then after the other code is executed. Note that you shouldn't use both m.s() and m.t().

JavaScript variable number of arguments to function

Be aware that passing an Object with named properties as Ken suggested adds the cost of allocating and releasing the temporary object to every call. Passing normal arguments by value or reference will generally be the most efficient. For many applications though the performance is not critical but for some it can be.

Find object in list that has attribute equal to some value (that meets any condition)

For below code, xGen is an anonomous generator expression, yFilt is a filter object. Note that for xGen the additional None parameter is returned rather than throwing StopIteration when the list is exhausted.

arr =((10,0), (11,1), (12,2), (13,2), (14,3))

value = 2
xGen = (x for x in arr if x[1] == value)
yFilt = filter(lambda x: x[1] == value, arr)
print(type(xGen))
print(type(yFilt))

for i in range(1,4):
    print('xGen: pass=',i,' result=',next(xGen,None))
    print('yFilt: pass=',i,' result=',next(yFilt))

Output:

<class 'generator'>
<class 'filter'>
xGen: pass= 1  result= (12, 2)
yFilt: pass= 1  result= (12, 2)
xGen: pass= 2  result= (13, 2)
yFilt: pass= 2  result= (13, 2)
xGen: pass= 3  result= None
Traceback (most recent call last):
  File "test.py", line 12, in <module>
    print('yFilt: pass=',i,' result=',next(yFilt))
StopIteration

How can I perform a short delay in C# without using sleep?

Sorry for awakening an old question like this. But I think what the original author wanted as an answer was:

You need to force your program to make the graphic update after you make the change to the textbox1. You can do that by invoking Update();

textBox1.Text += "\r\nThread Sleeps!";
textBox1.Update();
System.Threading.Thread.Sleep(4000);
textBox1.Text += "\r\nThread awakens!";
textBox1.Update();

Normally this will be done automatically when the thread is done. Ex, you press a button, changes are made to the text, thread dies, and then .Update() is fired and you see the changes. (I'm not an expert so I cant really tell you when its fired, but its something similar to this any way.)

In this case, you make a change, pause the thread, and then change the text again, and when the thread finally dies the .Update() is fired. This resulting in you only seeing the last change made to the text.

You would experience the same issue if you had a long execution between the text changes.

Can't load IA 32-bit .dll on a AMD 64-bit platform

Don't worry about you should just change .dll from x64 to x86, in the native library.

for example:- you might have selected this (C:\opencv\build\java\x64).

instead you select this for native library(C:\opencv\build\java\x86).

TSQL CASE with if comparison in SELECT statement

You can try with this:

WITH CTE_A As (SELECT COUNT(*) as articleNumber,A.UserID  as UserID FROM Articles A
           Inner Join Users U
           on  A.userId = U.userId 
           Group By A.userId , U.userId   ),

B as (Select us.registrationDate,

      CASE
         WHEN CTE_A.articleNumber < 2 THEN 'Ama'
         WHEN CTE_A.articleNumber < 5 THEN 'SemiAma' 
         WHEN CTE_A.articleNumber < 7 THEN 'Good'  
         WHEN CTE_A.articleNumber < 9 THEN 'Better' 
         WHEN CTE_A.articleNumber < 12 THEN 'Best'
         ELSE 'Outstanding'
         END as Ranking,
         us.hobbies, etc...
         FROM USERS Us Inner Join CTE_A 
         on CTE_A.UserID=us.UserID)

Select * from B

find first sequence item that matches a criterion

a=[100,200,300,400,500]
def search(b):
 try:
  k=a.index(b)
  return a[k] 
 except ValueError:
    return 'not found'
print(search(500))

it'll return the object if found else it'll return "not found"

Print content of JavaScript object?

You can give your objects their own toString methods in their prototypes.

How can I convert a char to int in Java?

I you have the char '9', it will store its ASCII code, so to get the int value, you have 2 ways

char x = '9';
int y = Character.getNumericValue(x);   //use a existing function
System.out.println(y + " " + (y + 1));  // 9  10

or

char x = '9';
int y = x - '0';                        // substract '0' code to get the difference
System.out.println(y + " " + (y + 1));  // 9  10

And it fact, this works also :

char x = 9;
System.out.println(">" + x + "<");     //>  < prints a horizontal tab
int y = (int) x;
System.out.println(y + " " + (y + 1)); //9 10

You store the 9 code, which corresponds to a horizontal tab (you can see when print as String, bu you can also use it as int as you see above

php: catch exception and continue execution, is it possible?

Sure, just catch the exception where you want to continue execution...

  try
  {
      SomeOperation();
  }
  catch (SomeException $e)
  {
      // do nothing... php will ignore and continue    
  }

Of course this has the problem of silently dropping what could be a very important error. SomeOperation() may fail causing other subtle, difficult to figure out problems, but you would never know if you silently drop the exception.

How to copy commits from one branch to another?

You could create a patch from the commits that you want to copy and apply the patch to the destination branch.

How to delete a certain row from mysql table with same column values?

All tables should have a primary key (consisting of a single or multiple columns), duplicate rows doesn't make sense in a relational database. You can limit the number of delete rows using LIMIT though:

DELETE FROM orders WHERE id_users = 1 AND id_product = 2 LIMIT 1

But that just solves your current issue, you should definitely work on the bigger issue by defining primary keys.

Professional jQuery based Combobox control?

A new fork of the sexy-combo project is now out which looks promising: http://code.google.com/p/ufd/

java.lang.Exception: No runnable methods exception in running JUnits

I faced the same with my parent test setUp class which has annotation @RunWith(SpringRunner.class) and was being extended by other testClasses. As there was not test in the setUpclass , and Junit was trying to find one due to annotation @RunWith(SpringRunner.class) ,it didn't find one and threw exception

No runnable methods exception in running JUnits

I made my parent class as abstract and it worked like a charm .

I took help from here https://stackoverflow.com/a/10699141/8029525 . Thanks for help @froh42.

How to use HTTP GET in PowerShell?

Downloading Wget is not necessary; the .NET Framework has web client classes built in.

$wc = New-Object system.Net.WebClient;
$sms = Read-Host "Enter SMS text";
$sms = [System.Web.HttpUtility]::UrlEncode($sms);
$smsResult = $wc.downloadString("http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$sms&encoding=windows-1255")

How to pass boolean values to a PowerShell script from a command prompt

This is an older question, but there is actually an answer to this in the PowerShell documentation. I had the same problem, and for once RTFM actually solved it. Almost.

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe

Documentation for the -File parameter states that "In rare cases, you might need to provide a Boolean value for a switch parameter. To provide a Boolean value for a switch parameter in the value of the File parameter, enclose the parameter name and value in curly braces, such as the following: -File .\Get-Script.ps1 {-All:$False}"

I had to write it like this:

PowerShell.Exe -File MyFile.ps1 {-SomeBoolParameter:False}

So no '$' before the true/false statement, and that worked for me, on PowerShell 4.0

Reading and writing to serial port in C on Linux

I've solved my problems, so I post here the correct code in case someone needs similar stuff.

Open Port

int USB = open( "/dev/ttyUSB0", O_RDWR| O_NOCTTY );

Set parameters

struct termios tty;
struct termios tty_old;
memset (&tty, 0, sizeof tty);

/* Error Handling */
if ( tcgetattr ( USB, &tty ) != 0 ) {
   std::cout << "Error " << errno << " from tcgetattr: " << strerror(errno) << std::endl;
}

/* Save old tty parameters */
tty_old = tty;

/* Set Baud Rate */
cfsetospeed (&tty, (speed_t)B9600);
cfsetispeed (&tty, (speed_t)B9600);

/* Setting other Port Stuff */
tty.c_cflag     &=  ~PARENB;            // Make 8n1
tty.c_cflag     &=  ~CSTOPB;
tty.c_cflag     &=  ~CSIZE;
tty.c_cflag     |=  CS8;

tty.c_cflag     &=  ~CRTSCTS;           // no flow control
tty.c_cc[VMIN]   =  1;                  // read doesn't block
tty.c_cc[VTIME]  =  5;                  // 0.5 seconds read timeout
tty.c_cflag     |=  CREAD | CLOCAL;     // turn on READ & ignore ctrl lines

/* Make raw */
cfmakeraw(&tty);

/* Flush Port, then applies attributes */
tcflush( USB, TCIFLUSH );
if ( tcsetattr ( USB, TCSANOW, &tty ) != 0) {
   std::cout << "Error " << errno << " from tcsetattr" << std::endl;
}

Write

unsigned char cmd[] = "INIT \r";
int n_written = 0,
    spot = 0;

do {
    n_written = write( USB, &cmd[spot], 1 );
    spot += n_written;
} while (cmd[spot-1] != '\r' && n_written > 0);

It was definitely not necessary to write byte per byte, also int n_written = write( USB, cmd, sizeof(cmd) -1) worked fine.

At last, read:

int n = 0,
    spot = 0;
char buf = '\0';

/* Whole response*/
char response[1024];
memset(response, '\0', sizeof response);

do {
    n = read( USB, &buf, 1 );
    sprintf( &response[spot], "%c", buf );
    spot += n;
} while( buf != '\r' && n > 0);

if (n < 0) {
    std::cout << "Error reading: " << strerror(errno) << std::endl;
}
else if (n == 0) {
    std::cout << "Read nothing!" << std::endl;
}
else {
    std::cout << "Response: " << response << std::endl;
}

This one worked for me. Thank you all!

Remove directory from remote repository after adding them to .gitignore

Blundell's first answer didn't work for me. However it showed me the right way. I have done the same thing like this:

> for i in `git ls-files -i --exclude-from=.gitignore`; do git rm --cached $i; done
> git commit -m 'Removed all files that are in the .gitignore'
> git push origin master

I advise you to check the files to be deleted first by running the below statement:

git ls-files -i --exclude-from=.gitignore

I was using a default .gitignore file for visual studio and I noticed that it was removing all log and bin folders in the project which was not my intended action.

How to change the button text for 'Yes' and 'No' buttons in the MessageBox.Show dialog?

Here is the content of the file MessageBoxManager.cs

#pragma warning disable 0618

using System;

using System.Text;

using System.Runtime.InteropServices;

using System.Security.Permissions;

[assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)]

namespace System.Windows.Forms

{

    public class MessageBoxManager
    {
        private delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
        private delegate bool EnumChildProc(IntPtr hWnd, IntPtr lParam);

        private const int WH_CALLWNDPROCRET = 12;
        private const int WM_DESTROY = 0x0002;
        private const int WM_INITDIALOG = 0x0110;
        private const int WM_TIMER = 0x0113;
        private const int WM_USER = 0x400;
        private const int DM_GETDEFID = WM_USER + 0;

        private const int MBOK = 1;
        private const int MBCancel = 2;
        private const int MBAbort = 3;
        private const int MBRetry = 4;
        private const int MBIgnore = 5;
        private const int MBYes = 6;
        private const int MBNo = 7;


        [DllImport("user32.dll")]
        private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll")]
        private static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);

        [DllImport("user32.dll")]
        private static extern int UnhookWindowsHookEx(IntPtr idHook);

        [DllImport("user32.dll")]
        private static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll", EntryPoint = "GetWindowTextLengthW", CharSet = CharSet.Unicode)]
        private static extern int GetWindowTextLength(IntPtr hWnd);

        [DllImport("user32.dll", EntryPoint = "GetWindowTextW", CharSet = CharSet.Unicode)]
        private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength);

        [DllImport("user32.dll")]
        private static extern int EndDialog(IntPtr hDlg, IntPtr nResult);

        [DllImport("user32.dll")]
        private static extern bool EnumChildWindows(IntPtr hWndParent, EnumChildProc lpEnumFunc, IntPtr lParam);

        [DllImport("user32.dll", EntryPoint = "GetClassNameW", CharSet = CharSet.Unicode)]
        private static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);

        [DllImport("user32.dll")]
        private static extern int GetDlgCtrlID(IntPtr hwndCtl);

        [DllImport("user32.dll")]
        private static extern IntPtr GetDlgItem(IntPtr hDlg, int nIDDlgItem);

        [DllImport("user32.dll", EntryPoint = "SetWindowTextW", CharSet = CharSet.Unicode)]
        private static extern bool SetWindowText(IntPtr hWnd, string lpString);


        [StructLayout(LayoutKind.Sequential)]
        public struct CWPRETSTRUCT
        {
            public IntPtr lResult;
            public IntPtr lParam;
            public IntPtr wParam;
            public uint   message;
            public IntPtr hwnd;
        };

        private static HookProc hookProc;
        private static EnumChildProc enumProc;
        [ThreadStatic]
        private static IntPtr hHook;
        [ThreadStatic]
        private static int nButton;

        /// <summary>
        /// OK text
        /// </summary>
        public static string OK = "&OK";
        /// <summary>
        /// Cancel text
        /// </summary>
        public static string Cancel = "&Cancel";
        /// <summary>
        /// Abort text
        /// </summary>
        public static string Abort = "&Abort";
        /// <summary>
        /// Retry text
        /// </summary>
        public static string Retry = "&Retry";
        /// <summary>
        /// Ignore text
        /// </summary>
        public static string Ignore = "&Ignore";
        /// <summary>
        /// Yes text
        /// </summary>
        public static string Yes = "&Yes";
        /// <summary>
        /// No text
        /// </summary>
        public static string No = "&No";

        static MessageBoxManager()
        {
            hookProc = new HookProc(MessageBoxHookProc);
            enumProc = new EnumChildProc(MessageBoxEnumProc);
            hHook = IntPtr.Zero;
        }

        /// <summary>
        /// Enables MessageBoxManager functionality
        /// </summary>
        /// <remarks>
        /// MessageBoxManager functionality is enabled on current thread only.
        /// Each thread that needs MessageBoxManager functionality has to call this method.
        /// </remarks>
        public static void Register()
        {
            if (hHook != IntPtr.Zero)
                throw new NotSupportedException("One hook per thread allowed.");
            hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, hookProc, IntPtr.Zero, AppDomain.GetCurrentThreadId());
        }

        /// <summary>
        /// Disables MessageBoxManager functionality
        /// </summary>
        /// <remarks>
        /// Disables MessageBoxManager functionality on current thread only.
        /// </remarks>
        public static void Unregister()
        {
            if (hHook != IntPtr.Zero)
            {
                UnhookWindowsHookEx(hHook);
                hHook = IntPtr.Zero;
            }
        }

        private static IntPtr MessageBoxHookProc(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode < 0)
                return CallNextHookEx(hHook, nCode, wParam, lParam);

            CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT));
            IntPtr hook = hHook;

            if (msg.message == WM_INITDIALOG)
            {
                int nLength = GetWindowTextLength(msg.hwnd);
                StringBuilder className = new StringBuilder(10);
                GetClassName(msg.hwnd, className, className.Capacity);
                if (className.ToString() == "#32770")
                {
                    nButton = 0;
                    EnumChildWindows(msg.hwnd, enumProc, IntPtr.Zero);
                    if (nButton == 1)
                    {
                        IntPtr hButton = GetDlgItem(msg.hwnd, MBCancel);
                        if (hButton != IntPtr.Zero)
                            SetWindowText(hButton, OK);
                    }
                }
            }

            return CallNextHookEx(hook, nCode, wParam, lParam);
        }

        private static bool MessageBoxEnumProc(IntPtr hWnd, IntPtr lParam)
        {
            StringBuilder className = new StringBuilder(10);
            GetClassName(hWnd, className, className.Capacity);
            if (className.ToString() == "Button")
            {
                int ctlId = GetDlgCtrlID(hWnd);
                switch (ctlId)
                {
                    case MBOK:
                        SetWindowText(hWnd, OK);
                        break;
                    case MBCancel:
                        SetWindowText(hWnd, Cancel);
                        break;
                    case MBAbort:
                        SetWindowText(hWnd, Abort);
                        break;
                    case MBRetry:
                        SetWindowText(hWnd, Retry);
                        break;
                    case MBIgnore:
                        SetWindowText(hWnd, Ignore);
                        break;
                    case MBYes:
                        SetWindowText(hWnd, Yes);
                        break;
                    case MBNo:
                        SetWindowText(hWnd, No);
                        break;

                }
                nButton++;
            }

            return true;
        }


    }
}

"The POM for ... is missing, no dependency information available" even though it exists in Maven Repository

You will need to add external Repository to your pom, since this is using Mulsoft-Release repository not Maven Central

<project>
   ...
    <repositories>
        <repository>
            <id>mulesoft-releases</id>
            <name>MuleSoft Repository</name>
            <url>http://repository.mulesoft.org/releases/</url>
            <layout>default</layout>
        </repository>
    </repositories>
  ...
</project>

Dependency

Apache Maven - Setting up Multiple Repositories

How to generate a random int in C?

Well, STL is C++, not C, so I don't know what you want. If you want C, however, there is the rand() and srand() functions:

int rand(void);

void srand(unsigned seed);

These are both part of ANSI C. There is also the random() function:

long random(void);

But as far as I can tell, random() is not standard ANSI C. A third-party library may not be a bad idea, but it all depends on how random of a number you really need to generate.

JBoss debugging in Eclipse

You mean remote debug JBoss from Eclipse ?

From Configuring Eclipse for Remote Debugging:

Set the JAVA_OPTS variable as follows:

set JAVA_OPTS= -Xdebug -Xnoagent 
   -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n %JAVA_OPTS%

or:

JAVA_OPTS="-Xdebug -Xnoagent 
  -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n $JAVA_OPTS"

In the Debug frame, select the Remote Java Application node.

In the Connection Properties, specify localhost as the Host and specify the Port as the port that was specified in the run batch script of the JBoss server, 8787.

JBoss Debug

How to determine if a list of polygon points are in clockwise order?

As also explained in this Wikipedia article Curve orientation, given 3 points p, q and r on the plane (i.e. with x and y coordinates), you can calculate the sign of the following determinant

enter image description here

If the determinant is negative (i.e. Orient(p, q, r) < 0), then the polygon is oriented clockwise (CW). If the determinant is positive (i.e. Orient(p, q, r) > 0), the polygon is oriented counterclockwise (CCW). The determinant is zero (i.e. Orient(p, q, r) == 0) if points p, q and r are collinear.

In the formula above, we prepend the ones in front of the coordinates of p, q and r because we are using homogeneous coordinates.

jQuery UI autocomplete with JSON

I understand that its been answered already. but I hope this will help someone in future and saves so much time and pain.

complete code is below: This one I did for a textbox to make it Autocomplete in CiviCRM. Hope it helps someone

CRM.$( 'input[id^=custom_78]' ).autocomplete({
            autoFill: true,
            select: function (event, ui) {
                    var label = ui.item.label;
                    var value = ui.item.value;
                    // Update subject field to add book year and book product
                    var book_year_value = CRM.$('select[id^=custom_77]  option:selected').text().replace('Book Year ','');
                    //book_year_value.replace('Book Year ','');
                    var subject_value = book_year_value + '/' + ui.item.label;
                    CRM.$('#subject').val(subject_value);
                    CRM.$( 'input[name=product_select_id]' ).val(ui.item.value);
                    CRM.$('input[id^=custom_78]').val(ui.item.label);
                    return false;
            },
            source: function(request, response) {
                CRM.$.ajax({
                    url: productUrl,
                        data: {
                                        'subCategory' : cj('select[id^=custom_77]').val(),
                                        's': request.term,
                                    },
                    beforeSend: function( xhr ) {
                        xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
                    },

                    success: function(result){
                                result = jQuery.parseJSON( result);
                                //console.log(result);
                                response(CRM.$.map(result, function (val,key) {
                                                         //console.log(key);
                                                         //console.log(val);
                                                         return {
                                                                 label: val,
                                                                 value: key
                                                         };
                                                 }));
                    }
                })
                .done(function( data ) {
                    if ( console && console.log ) {
                     // console.log( "Sample of dataas:", data.slice( 0, 100 ) );
                    }
                });
            }
  });

PHP code on how I'm returning data to this jquery ajax call in autocomplete:

/**
 * This class contains all product related functions that are called using AJAX (jQuery)
 */
class CRM_Civicrmactivitiesproductlink_Page_AJAX {
  static function getProductList() {
        $name   = CRM_Utils_Array::value( 's', $_GET );
    $name   = CRM_Utils_Type::escape( $name, 'String' );
    $limit  = '10';

        $strSearch = "description LIKE '%$name%'";

        $subCategory   = CRM_Utils_Array::value( 'subCategory', $_GET );
    $subCategory   = CRM_Utils_Type::escape( $subCategory, 'String' );

        if (!empty($subCategory))
        {
                $strSearch .= " AND sub_category = ".$subCategory;
        }

        $query = "SELECT id , description as data FROM abc_books WHERE $strSearch";
        $resultArray = array();
        $dao = CRM_Core_DAO::executeQuery( $query );
        while ( $dao->fetch( ) ) {
            $resultArray[$dao->id] = $dao->data;//creating the array to send id as key and data as value
        }
        echo json_encode($resultArray);
    CRM_Utils_System::civiExit();
  }
}

Create URL from a String

URL url = new URL(yourUrl, "/api/v1/status.xml");

According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:

URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");

Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html

Select multiple rows with the same value(s)

This may work for you:

select t1.*
from table t1
join (select t2.Chromosome, t2.Locus
    from table2
    group by t2.Chromosome, t2.Locus
    having count(*) > 1) u on u.Chromosome = t1.Chromosome and u.Locus = t1.Locus

Replace multiple characters in a C# string

Use RegEx.Replace, something like this:

  string input = "This is   text with   far  too   much   " + 
                 "whitespace.";
  string pattern = "[;,]";
  string replacement = "\n";
  Regex rgx = new Regex(pattern);
  string result = rgx.Replace(input, replacement);

Here's more info on this MSDN documentation for RegEx.Replace

Importing PNG files into Numpy?

According to the doc, scipy.misc.imread is deprecated starting SciPy 1.0.0, and will be removed in 1.2.0. Consider using imageio.imread instead.

Example:

import imageio

im = imageio.imread('my_image.png')
print(im.shape)

You can also use imageio to load from fancy sources:

im = imageio.imread('http://upload.wikimedia.org/wikipedia/commons/d/de/Wikipedia_Logo_1.0.png')

Edit:

To load all of the *.png files in a specific folder, you could use the glob package:

import imageio
import glob

for im_path in glob.glob("path/to/folder/*.png"):
     im = imageio.imread(im_path)
     print(im.shape)
     # do whatever with the image here

MetadataException when using Entity Framework Entity Connection

I had the same error message, and the problem was also the metadata part of the connection string, but I had to dig a little deeper to solve it and wanted to share this little nugget:

The metadata string is made up of three sections that each look like this:

res://
      (assembly)/
      (model name).(ext)

Where ext is "csdl", "ssdl", and "msl".

For most people, assembly can probably be "*", which seems to indicate that all loaded assemblies will be searched (I haven't done a huge amount of testing of this). This part wasn't an issue for me, so I can't comment on whether you need the assembly name or file name (i.e., with or without ".dll"), though I have seen both suggested.

The model name part should be the name and namespace of your .edmx file, relative to your assembly. So if you have a My.DataAccess assembly and you create DataModels.edmx in a Models folder, its full name is My.DataAccess.Models.DataModels. In this case, you would have "Models.DataModels.(ext)" in your metadata.

If you ever move or rename your .edmx file, you will need to update your metadata string manually (in my experience), and remembering to change the relative namespace will save a few headaches.

Datetime current year and month in Python

The question asks to use datetime specifically.

This is a way that uses datetime only:

year = datetime.now().year
month = datetime.now().month

How to return a dictionary | Python

I followed approach as shown in code below to return a dictionary. Created a class and declared dictionary as global and created a function to add value corresponding to some keys in dictionary.

**Note have used Python 2.7 so some minor modification might be required for Python 3+

class a:
    global d
    d={}
    def get_config(self,x):
        if x=='GENESYS':
            d['host'] = 'host name'
            d['port'] = '15222'
        return d

Calling get_config method using class instance in a separate python file:

from constant import a
class b:
    a().get_config('GENESYS')
    print a().get_config('GENESYS').get('host')
    print a().get_config('GENESYS').get('port')

IIS URL Rewrite and Web.config

1) Your existing web.config: you have declared rewrite map .. but have not created any rules that will use it. RewriteMap on its' own does absolutely nothing.

2) Below is how you can do it (it does not utilise rewrite maps -- rules only, which is fine for small amount of rewrites/redirects):

This rule will do SINGLE EXACT rewrite (internal redirect) /page to /page.html. URL in browser will remain unchanged.

<system.webServer>
    <rewrite>
        <rules>
            <rule name="SpecificRewrite" stopProcessing="true">
                <match url="^page$" />
                <action type="Rewrite" url="/page.html" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

This rule #2 will do the same as above, but will do 301 redirect (Permanent Redirect) where URL will change in browser.

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

Rule #3 will attempt to execute such rewrite for ANY URL if there are such file with .html extension (i.e. for /page it will check if /page.html exists, and if it does then rewrite occurs):

<system.webServer>
    <rewrite>
        <rules>
            <rule name="DynamicRewrite" stopProcessing="true">
                <match url="(.*)" />
                <conditions>
                    <add input="{REQUEST_FILENAME}\.html" matchType="IsFile" />
                </conditions>
                <action type="Rewrite" url="/{R:1}.html" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

2D array values C++

int iArray[2][2] = {{1, 2}, {3, 4}};

Think of a 2D array as an array of arrays.

How to load external scripts dynamically in Angular?

Hi you can use Renderer2 and elementRef with just a few lines of code:

constructor(private readonly elementRef: ElementRef,
          private renderer: Renderer2) {
}
ngOnInit() {
 const script = this.renderer.createElement('script');
 script.src = 'http://iknow.com/this/does/not/work/either/file.js';
 script.onload = () => {
   console.log('script loaded');
   initFile();
 };
 this.renderer.appendChild(this.elementRef.nativeElement, script);
}

the onload function can be used to call the script functions after the script is loaded, this is very useful if you have to do the calls in the ngOnInit()

How do I specify the exit code of a console application in .NET?

The enumeration option is excellent however can be improved upon by multiplying the numbers as in:

enum ExitCodes : int
{
  Success = 0,
  SignToolNotInPath = 1,
  AssemblyDirectoryBad = 2,
  PFXFilePathBad = 4,
  PasswordMissing = 8,
  SignFailed = 16,
  UnknownError = 32
}

In the case of multiple errors, adding the specific error numbers together will give you a unique number that will represent the combination of detected errors.

For example, an errorlevel of 6 can only consist of errors 4 and 2, 12 can only consist of errors 4 and 8, 14 can only consist of 2, 4 and 8 etc.

How to install a .ipa file into my iPhone?

You need to install the provisioning profile (drag and drop it into iTunes). Then drag and drop the .ipa. Ensure you device is set to sync apps, and try again.

How to use workbook.saveas with automatic Overwrite

To hide the prompt set xls.DisplayAlerts = False

ConflictResolution is not a true or false property, it should be xlLocalSessionChanges

Note that this has nothing to do with displaying the Overwrite prompt though!

Set xls = CreateObject("Excel.Application")    
xls.DisplayAlerts = False
Set wb = xls.Workbooks.Add
fullFilePath = importFolderPath & "\" & "A.xlsx"

wb.SaveAs fullFilePath, AccessMode:=xlExclusive,ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges    
wb.Close (True)

Saving numpy array to txt file row wise

I know this is old, but none of these answers solved the root problem of numpy not saving the array row-wise. I found that this one liner did the trick for me:

b = np.matrix(a)
np.savetxt("file", b)

How can I create a temp file with a specific extension with .NET?

Easy Function in C#:

public static string GetTempFileName(string extension = "csv")
{
    return Path.ChangeExtension(Path.GetTempFileName(), extension);
}

How to automatically generate unique id in SQL like UID12345678?

CREATE TABLE dbo.tblUsers
(
    ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
    UserID AS 'UID' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED, 
    [Name] VARCHAR(50) NOT NULL,
)

marc_s's Answer Snap

marc_s's Answer Snap

Fastest JavaScript summation

one of the simplest, fastest, more reusable and flexible is:

Array.prototype.sum = function () {
    for(var total = 0,l=this.length;l--;total+=this[l]); return total;
}

// usage
var array = [1,2,3,4,5,6,7,8,9,10];
array.sum()

How to convert list of key-value tuples into dictionary?

Another way using dictionary comprehensions,

>>> t = [('A', 1), ('B', 2), ('C', 3)]
>>> d = { i:j for i,j in t }
>>> d
{'A': 1, 'B': 2, 'C': 3}

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

My solution:

Option Explicit
Public datHora As Date

Function Cronometro(action As Integer) As Integer 
'This return the seconds between two >calls
Cronometro = 0
  If action = 1 Then 'Start
    datHora = Now
  End If
  If action = 2 Then 'Time until that moment
    Cronometro = DateDiff("s", datHora, Now)
  End If
End Function

How to use? Easy...

dummy= Cronometro(1) ' This starts the timer

seconds= Cronometro(2) ' This returns the seconds between the first call and this one

MySQL Multiple Where Clause

You will never get a result, it's a simple logic error.

You're asking your database to return a row which has style_id = 24 AND style_id = 25 AND style_id = 26. Since 24 is niether 25 nor 26, you will get no result.

You have to use OR, then it makes some sense.

CMake not able to find OpenSSL library

If you can use pkg-config: pkg_search_module() can find OpenSSL for you.

# Search OpenSSL
find_package(PkgConfig REQUIRED)
pkg_search_module(OPENSSL REQUIRED openssl)

if( OPENSSL_FOUND )
    include_directories(${OPENSSL_INCLUDE_DIRS})
    message(STATUS "Using OpenSSL ${OPENSSL_VERSION}")
else()
    # Error; with REQUIRED, pkg_search_module() will throw an error by it's own
endif()

target_link_libraries(${YOUR_TARGET_HERE} ${OPENSSL_LIBRARIES})

Why doesn't Python have a sign function?

In Python 2, cmp() returns an integer: there's no requirement that the result be -1, 0, or 1, so sign(x) is not the same as cmp(x,0).

In Python 3, cmp() has been removed in favor of rich comparison. For cmp(), Python 3 suggests this:

def cmp(a, b):
    return (a > b) - (a < b)

which is fine for cmp(), but again can't be used for sign() because the comparison operators need not return booleans.

To deal with this possibility, the comparison results must be coerced to booleans:

 def sign(x):
    return bool(x > 0) - bool(x < 0)

This works for any type which is totally ordered (including special values like NaN or infinities).

Python Selenium accessing HTML source

You need to access the page_source property:

from selenium import webdriver

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

html_source = browser.page_source
if "whatever" in html_source:
    # do something
else:
    # do something else

The filename, directory name, or volume label syntax is incorrect inside batch

set myPATH="C:\Users\DEB\Downloads\10.1.1.0.4"
cd %myPATH%
  • The single quotes do not indicate a string, they make it starts: 'C:\ instead of C:\ so

  • %name% is the usual syntax for expanding a variable, the !name! syntax needs to be enabled using the command setlocal ENABLEDELAYEDEXPANSION first, or by running the command prompt with CMD /V:ON.

  • Don't use PATH as your name, it is a system name that contains all the locations of executable programs. If you overwrite it, random bits of your script will stop working. If you intend to change it, you need to do set PATH=%PATH%;C:\Users\DEB\Downloads\10.1.1.0.4 to keep the current PATH content, and add something to the end.

async await return Task

Adding the async keyword is just syntactic sugar to simplify the creation of a state machine. In essence, the compiler takes your code;

public async Task MethodName()
{
     return null;
}

And turns it into;

public Task MethodName()
{
     return Task.FromResult<object>(null);
}

If your code has any await keywords, the compiler must take your method and turn it into a class to represent the state machine required to execute it. At each await keyword, the state of variables and the stack will be preserved in the fields of the class, the class will add itself as a completion hook to the task you are waiting on, then return.

When that task completes, your task will be executed again. So some extra code is added to the top of the method to restore the state of variables and jump into the next slab of your code.

See What does async & await generate? for a gory example.

This process has a lot in common with the way the compiler handles iterator methods with yield statements.

Disabling the button after once click

Use modern Js events, with "once"!

const button = document.getElementById(btnId);
button.addEventListener("click", function() {
    // Submit form
}, {once : true});

// Disabling works too, but this is a more standard approach for general one-time events

Documentation, CanIUse

Autocompletion in Vim

You can use a plugin like AutoComplPop to get automatic code completion as you type.

2015 Edit: I personally use YouCompleteMe now.

How to detect orientation change in layout in Android?

In case this is of use to some newer dev's because its not specified above. Just to be very explicit:

You need two things if using onConfigurationChanged:

  1. An onConfigurationChanged method in your Activity Class

  2. Specify in your manifest which configuration changes will be handled by your onConfigurationChanged method

The manifest snippet in the above answers, while no doubt correct for the particular app that manifest belongs to, is NOT exactly what you need to add in your manifest to trigger the onConfigurationChanged method in your Activity Class. i.e. the below manifest entry may not be correct for your app.

<activity name= ".MainActivity" android:configChanges="orientation|screenSize"/>

In the above manifest entry, there are various Android actions for android:configChanges="" which can trigger the onCreate in your Activity lifecycle.

This is very important - The ones NOT Specified in the manifest are the ones that trigger your onCreate and The ones specified in the manifest are the ones that trigger your onConfigurationChanged method in your Activity Class.

So you need to identify which config changes you need to handle yourself. For the Android Encyclopedically Challenged like me, I used the quick hints pop-out in Android Studio and added in almost every possible configuration option. Listing all of these basically said that I would handle everything and onCreate will never be called due to configurations.

<activity name= ".MainActivity" android:configChanges="screenLayout|touchscreen|mnc|mcc|density|uiMode|fontScale|orientation|keyboard|layoutDirection|locale|navigation|smallestScreenSize|keyboardHidden|colorMode|screenSize"/>

Now obviously I don't want to handle everything, so I began eliminating the above options one at a time. Re-building and testing my app after each removal.

Another important point: If there is just one configuration option being handled automatically that triggers your onCreate (You do not have it listed in your manifest above), then it will appear like onConfigurationChanged is not working. You must put all relevant ones into your manifest.

I ended up with 3 that were triggering onCreate originally, then I tested on an S10+ and I was still getting the onCreate, so I had to do my elimination exercise again and I also needed the |screenSize. So test on a selection of platforms.

<activity name= ".MainActivity" android:configChanges="screenLayout|uiMode|orientation|screenSize"/>

So my suggestion, although I'm sure someone can poke holes in this:

  1. Add your onConfigurationChanged method in your Activity Class with a TOAST or LOG so you can see when its working.

  2. Add all possible configuration options to your manifest.

  3. Confirm your onConfigurationChanged method is working by testing your app.

  4. Remove each config option from your manifest file one at a time, testing your app after each.

  5. Test on as large a variety of devices as possible.

  6. Do not copy/paste my snippet above to your manifest file. Android updates change the list, so use the pop-out Android Studio hints to make sure you get them all.

I hope this saves someone some time.

My onConfigurationChanged method just for info below. onConfigurationChanged is called in the lifecycle after the new orientation is available, but before the UI has been recreated. Hence my first if to check the orientation works correctly, and then the 2nd nested if to look at the visibility of my UI ImageView also works correctly.

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        // Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            pokerCardLarge = findViewById(R.id.pokerCardLgImageView);

            if(pokerCardLarge.getVisibility() == pokerCardLarge.VISIBLE){
                Bitmap image = ((BitmapDrawable)pokerCardLarge.getDrawable()).getBitmap();
                pokerCardLarge.setVisibility(pokerCardLarge.VISIBLE);
                pokerCardLarge.setImageBitmap(image);
            }

        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
            pokerCardLarge = findViewById(R.id.pokerCardLgImageView);

            if(pokerCardLarge.getVisibility() == pokerCardLarge.VISIBLE){
                Bitmap image = ((BitmapDrawable)pokerCardLarge.getDrawable()).getBitmap();
                pokerCardLarge.setVisibility(pokerCardLarge.VISIBLE);
                pokerCardLarge.setImageBitmap(image);
            }

        }
    }

Resolving MSB3247 - Found conflicts between different versions of the same dependent assembly

Sometime @AMissico answer is not enough. In my case, I couldn't find the error in the Output windows so I decided to create a log file and analyze it, by doing the following steps:

  1. Saving the build log to a file... https://msdn.microsoft.com/en-us/library/ms171470.aspx

    msbuild MyProject.proj /fl /flp:logfile=MyProjectOutput.log;verbosity=detailed

  2. Find the text: warning MS... or the specific warning info: (e.g. line 9293) Found conflicts between different versions... and the full detail of the conflict error will be above of this message (e.g. line 9277) There was a conflicts between... Find the error message

Visual Studio 2013

How to make unicode string with python3

the easiest way in python 3.x

text = "hi , I'm text"
text.encode('utf-8')

How to change Java version used by TOMCAT?

If you use the standard scripts to launch Tomcat (i.e. you haven't installed Tomcat as a windows service), you can use the setenv.bat file, to set your JRE_HOME version.

On Windows, create the file %CATALINA_BASE%\bin\setenv.bat, with content:

set "JRE_HOME=%ProgramFiles%\Java\jre1.6.0_20"

exit /b 0

And that should be it.

You can test this using %CATALINA_BASE%\bin\configtest.bat (Disclaimer: I've only checked this with a Tomcat7 installation).

Further Reading:

How to access nested elements of json object using getJSONArray method

Try this code using Gson library and get the things done.

Gson gson = new GsonBuilder().create();

JsonObject job = gson.fromJson(JsonString, JsonObject.class);
JsonElement entry=job.getAsJsonObject("results").getAsJsonObject("map").getAsJsonArray("entry");

String str = entry.toString();

System.out.println(str);

How to create XML file with specific structure in Java

You can use the JDOM library in Java. Define your tags as Element objects, document your elements with Document Class, and build your xml file with SAXBuilder. Try this example:

//Root Element
Element root=new Element("CONFIGURATION");
Document doc=new Document();
//Element 1
Element child1=new Element("BROWSER");
//Element 1 Content
child1.addContent("chrome");
//Element 2
Element child2=new Element("BASE");
//Element 2 Content
child2.addContent("http:fut");
//Element 3
Element child3=new Element("EMPLOYEE");
//Element 3 --> In this case this element has another element with Content
child3.addContent(new Element("EMP_NAME").addContent("Anhorn, Irene"));

//Add it in the root Element
root.addContent(child1);
root.addContent(child2);
root.addContent(child3);
//Define root element like root
doc.setRootElement(root);
//Create the XML
XMLOutputter outter=new XMLOutputter();
outter.setFormat(Format.getPrettyFormat());
outter.output(doc, new FileWriter(new File("myxml.xml")));