Programs & Examples On #Typetraits

Type traits are syntactic extensions that allow the developer to determine at compile time various characteristics of a type. C++ support is provided by a combination of compiler support and a set of library templates. Access to the type traits is provided via the header

Get checkbox value in jQuery

Just to clarify things:

$('#checkbox_ID').is(":checked")

Will return 'true' or 'false'

Android Fragment handle back button press

if you overide the onKey method for the fragment view you're gonna need :

    view.setFocusableInTouchMode(true);
    view.requestFocus();
    view.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                Log.i(tag, "keyCode: " + keyCode);
                if( keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
                    Log.i(tag, "onKey Back listener is working!!!");
                    getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                    return true;
                } 
                return false;
            }
        });

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

When I used policy before I set the default authentication scheme into it as well. I had modified the DefaultPolicy so it was slightly different. However the same should work for add policy as well.

services.AddAuthorization(options =>
        {
            options.AddPolicy(DefaultAuthorizedPolicy, policy =>
            {
                policy.Requirements.Add(new TokenAuthRequirement());
                policy.AuthenticationSchemes = new List<string>()
                                {
                                    CookieAuthenticationDefaults.AuthenticationScheme
                                }
            });
        });

Do take into consideration that by Default AuthenticationSchemes property uses a read only list. I think it would be better to implement that instead of List as well.

'module' object has no attribute 'DataFrame'

There may be two causes:

  1. It is case-sensitive: DataFrame .... Dataframe, dataframe will not work.

  2. You have not install pandas (pip install pandas) in the python path.

ERROR 1044 (42000): Access denied for 'root' With All Privileges

The reason i could not delete some of the users via 'drop' statement was that there is a bug in Mysql http://bugs.mysql.com/bug.php?id=62255 with hostname containing upper case letters. The solution was running following query:

DELETE FROM mysql.user where host='Some_Host_With_UpperCase_Letters';

I am still trying to figure the other issue where the root user with all permissions are unable to grant privileges to new user for particular database

Frequency table for a single variable

for frequency distribution of a variable with excessive values you can collapse down the values in classes,

Here I excessive values for employrate variable, and there's no meaning of it's frequency distribution with direct values_count(normalize=True)

                country  employrate alcconsumption
0           Afghanistan   55.700001            .03
1               Albania   11.000000           7.29
2               Algeria   11.000000            .69
3               Andorra         nan          10.17
4                Angola   75.699997           5.57
..                  ...         ...            ...
208             Vietnam   71.000000           3.91
209  West Bank and Gaza   32.000000               
210         Yemen, Rep.   39.000000             .2
211              Zambia   61.000000           3.56
212            Zimbabwe   66.800003           4.96

[213 rows x 3 columns]

frequency distribution with values_count(normalize=True) with no classification,length of result here is 139 (seems meaningless as a frequency distribution):

print(gm["employrate"].value_counts(sort=False,normalize=True))

50.500000   0.005618
61.500000   0.016854
46.000000   0.011236
64.500000   0.005618
63.500000   0.005618

58.599998   0.005618
63.799999   0.011236
63.200001   0.005618
65.599998   0.005618
68.300003   0.005618
Name: employrate, Length: 139, dtype: float64

putting classification we put all values with a certain range ie.

0-10 as 1,
11-20 as 2  
21-30 as 3, and so forth.
gm["employrate"]=gm["employrate"].str.strip().dropna()  
gm["employrate"]=pd.to_numeric(gm["employrate"])
gm['employrate'] = np.where(
   (gm['employrate'] <=10) & (gm['employrate'] > 0) , 1, gm['employrate']
   )
gm['employrate'] = np.where(
   (gm['employrate'] <=20) & (gm['employrate'] > 10) , 1, gm['employrate']
   )
gm['employrate'] = np.where(
   (gm['employrate'] <=30) & (gm['employrate'] > 20) , 2, gm['employrate']
   )
gm['employrate'] = np.where(
   (gm['employrate'] <=40) & (gm['employrate'] > 30) , 3, gm['employrate']
   )
gm['employrate'] = np.where(
   (gm['employrate'] <=50) & (gm['employrate'] > 40) , 4, gm['employrate']
   )
gm['employrate'] = np.where(
   (gm['employrate'] <=60) & (gm['employrate'] > 50) , 5, gm['employrate']
   )
gm['employrate'] = np.where(
   (gm['employrate'] <=70) & (gm['employrate'] > 60) , 6, gm['employrate']
   )
gm['employrate'] = np.where(
   (gm['employrate'] <=80) & (gm['employrate'] > 70) , 7, gm['employrate']
   )
gm['employrate'] = np.where(
   (gm['employrate'] <=90) & (gm['employrate'] > 80) , 8, gm['employrate']
   )
gm['employrate'] = np.where(
   (gm['employrate'] <=100) & (gm['employrate'] > 90) , 9, gm['employrate']
   )
print(gm["employrate"].value_counts(sort=False,normalize=True))

after classification we have a clear frequency distribution. here we can easily see, that 37.64% of countries have employ rate between 51-60% and 11.79% of countries have employ rate between 71-80%

5.000000   0.376404
7.000000   0.117978
4.000000   0.179775
6.000000   0.264045
8.000000   0.033708
3.000000   0.028090
Name: employrate, dtype: float64

Android: How can I validate EditText input?

Updated approach - TextInputLayout:

Google has recently launched design support library and there is one component called TextInputLayout and it supports showing an error via setErrorEnabled(boolean) and setError(CharSequence).

How to use it?

Step 1: Wrap your EditText with TextInputLayout:

  <android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/layoutUserName">

    <EditText
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:hint="hint"
      android:id="@+id/editText1" />

  </android.support.design.widget.TextInputLayout>

Step 2: Validate input

// validating input on a button click
public void btnValidateInputClick(View view) {

    final TextInputLayout layoutUserName = (TextInputLayout) findViewById(R.id.layoutUserName);
    String strUsername = layoutLastName.getEditText().getText().toString();

    if(!TextUtils.isEmpty(strLastName)) {
        Snackbar.make(view, strUsername, Snackbar.LENGTH_SHORT).show();
        layoutUserName.setErrorEnabled(false);
    } else {
        layoutUserName.setError("Input required");
        layoutUserName.setErrorEnabled(true);
    }
}

I have created an example over my Github repository, checkout the example if you wish to!

What is the C# Using block and why should I use it?

From MSDN:

C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible.

The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.

In other words, the using statement tells .NET to release the object specified in the using block once it is no longer needed.

Apply CSS rules to a nested class inside a div

You use

#main_text .title {
  /* Properties */
}

If you just put a space between the selectors, styles will apply to all children (and children of children) of the first. So in this case, any child element of #main_text with the class name title. If you use > instead of a space, it will only select the direct child of the element, and not children of children, e.g.:

#main_text > .title {
  /* Properties */
}

Either will work in this case, but the first is more typically used.

Replace all whitespace with a line break/paragraph mark to make a word list

The portable way to do this is:

sed -e 's/[ \t][ \t]*/\
/g'

That's an actual newline between the backslash and the slash-g. Many sed implementations don't know about \n, so you need a literal newline. The backslash before the newline prevents sed from getting upset about the newline. (in sed scripts the commands are normally terminated by newlines)

With GNU sed you can use \n in the substitution, and \s in the regex:

sed -e 's/\s\s*/\n/g'

GNU sed also supports "extended" regular expressions (that's egrep style, not perl-style) if you give it the -r flag, so then you can use +:

sed -r -e 's/\s+/\n/g'

If this is for Linux only, you can probably go with the GNU command, but if you want this to work on systems with a non-GNU sed (eg: BSD, Mac OS-X), you might want to go with the more portable option.

javascript unexpected identifier

Either remove one } from end of responseText;}} or from the end of the line

Pandas - Plotting a stacked Bar Chart

Maybe you can use pandas crosstab function

test5 = pd.crosstab(index=faultdf['Site Name'], columns=faultdf[''Abuse/NFF''])

test5.plot(kind='bar', stacked=True)

Python 3 print without parenthesis

The AHK script is a great idea. Just for those interested I needed to change it a little bit to work for me:

SetTitleMatchMode,2         ;;; allows for a partial search 
#IfWinActive, .py           ;;; scope limiter to only python files
:b*:print ::print(){Left}   ;;; I forget what b* does
#IfWinActive                ;;; remove the scope limitation

How do I force make/GCC to show me the commands?

Use make V=1

Other suggestions here:

  • make VERBOSE=1 - did not work at least from my trials.
  • make -n - displays only logical operation, not command line being executed. E.g. CC source.cpp

  • make --debug=j - works as well, but might also enable multi threaded building, causing extra output.

How to calculate the bounding box for a given lat/lng location?

Since I needed a very rough estimate, so to filter out some needless documents in an elasticsearch query, I employed the below formula:

Min.lat = Given.Lat - (0.009 x N)
Max.lat = Given.Lat + (0.009 x N)
Min.lon = Given.lon - (0.009 x N)
Max.lon = Given.lon + (0.009 x N)

N = kms required form the given location. For your case N=10

Not accurate but handy.

Iterating over all the keys of a map

https://play.golang.org/p/JGZ7mN0-U-

for k, v := range m { 
    fmt.Printf("key[%s] value[%s]\n", k, v)
}

or

for k := range m {
    fmt.Printf("key[%s] value[%s]\n", k, m[k])
}

Go language specs for for statements specifies that the first value is the key, the second variable is the value, but doesn't have to be present.

How to stop event propagation with inline onclick attribute?

Use separate handler, say:

function myOnClickHandler(th){
//say let t=$(th)
}

and in html do this:

<...onclick="myOnClickHandler(this); event.stopPropagation();"...>

Or even :

function myOnClickHandler(e){
  e.stopPropagation();
}

for:

<...onclick="myOnClickHandler(event)"...>

Iterate all files in a directory using a 'for' loop

Try this to test if a file is a directory:

FOR /F "delims=" %I IN ('DIR /B /AD "filename" 2^>^&1 ^>NUL') DO IF "%I" == "File Not Found" ECHO Not a directory

This only will tell you whether a file is NOT a directory, which will also be true if the file doesn't exist, so be sure to check for that first if you need to. The carets (^) are used to escape the redirect symbols and the file listing output is redirected to NUL to prevent it from being displayed, while the DIR listing's error output is redirected to the output so you can test against DIR's message "File Not Found".

How to fluently build JSON in Java?

I am using the org.json library and found it to be nice and friendly.

Example:

String jsonString = new JSONObject()
                  .put("JSON1", "Hello World!")
                  .put("JSON2", "Hello my World!")
                  .put("JSON3", new JSONObject().put("key1", "value1"))
                  .toString();

System.out.println(jsonString);

OUTPUT:

{"JSON2":"Hello my World!","JSON3":{"key1":"value1"},"JSON1":"Hello World!"}

What is a race condition?

What is a race condition?

The situation when the process is critically dependent on the sequence or timing of other events.

For example, Processor A and processor B both needs identical resource for their execution.

How do you detect them?

There are tools to detect race condition automatically:

How do you handle them?

Race condition can be handled by Mutex or Semaphores. They act as a lock allows a process to acquire a resource based on certain requirements to prevent race condition.

How do you prevent them from occurring?

There are various ways to prevent race condition, such as Critical Section Avoidance.

  1. No two processes simultaneously inside their critical regions. (Mutual Exclusion)
  2. No assumptions are made about speeds or the number of CPUs.
  3. No process running outside its critical region which blocks other processes.
  4. No process has to wait forever to enter its critical region. (A waits for B resources, B waits for C resources, C waits for A resources)

Batch file include external file for variables

Note: I'm assuming Windows batch files as most people seem to be unaware that there are significant differences and just blindly call everything with grey text on black background DOS. Nevertheless, the first variant should work in DOS as well.

Executable configuration

The easiest way to do this is to just put the variables in a batch file themselves, each with its own set statement:

set var1=value1
set var2=value2
...

and in your main batch:

call config.cmd

Of course, that also enables variables to be created conditionally or depending on aspects of the system, so it's pretty versatile. However, arbitrary code can run there and if there is a syntax error, then your main batch will exit too. In the UNIX world this seems to be fairly common, especially for shells. And if you think about it, autoexec.bat is nothing else.

Key/value pairs

Another way would be some kind of var=value pairs in the configuration file:

var1=value1
var2=value2
...

You can then use the following snippet to load them:

for /f "delims=" %%x in (config.txt) do (set "%%x")

This utilizes a similar trick as before, namely just using set on each line. The quotes are there to escape things like <, >, &, |. However, they will themselves break when quotes are used in the input. Also you always need to be careful when further processing data in variables stored with such characters.

Generally, automatically escaping arbitrary input to cause no headaches or problems in batch files seems pretty impossible to me. At least I didn't find a way to do so yet. Of course, with the first solution you're pushing that responsibility to the one writing the config file.

Replace multiple strings with multiple other strings

by using prototype function we can replace easily by passing object with keys and values and replacable text

_x000D_
_x000D_
String.prototype.replaceAll=function(obj,keydata='key'){
 const keys=keydata.split('key');
 return Object.entries(obj).reduce((a,[key,val])=> a.replace(`${keys[0]}${key}${keys[1]}`,val),this)
}

const data='hids dv sdc sd ${yathin} ${ok}'
console.log(data.replaceAll({yathin:12,ok:'hi'},'${key}'))
_x000D_
_x000D_
_x000D_

SQL Server 2000: How to exit a stored procedure?

i figured out why RETURN is not unconditionally returning from the stored procedure. The error i'm seeing is while the stored procedure is being compiled - not when it's being executed.

Consider an imaginary stored procedure:

CREATE PROCEDURE dbo.foo AS

INSERT INTO ExistingTable
EXECUTE LinkedServer.Database.dbo.SomeProcedure

Even though this stord proedure contains an error (maybe it's because the objects have a differnet number of columns, maybe there is a timestamp column in the table, maybe the stored procedure doesn't exist), you can still save it. You can save it because you're referencing a linked server.

But when you actually execute the stored procedure, SQL Server then compiles it, and generates a query plan.

My error is not happening on line 114, it is on line 114. SQL Server cannot compile the stored procedure, that's why it's failing.

And that's why RETURN does not return, because it hasn't even started yet.

Must declare the scalar variable

If someone else comes across this question while no solution here made my sql file working, here's what my mistake was:

I have been exporting the contents of my database via the 'Generate Script' command of Microsofts' Server Management Studio and then doing some operations afterwards while inserting the generated data in another instance.

Due to the generated export, there have been a bunch of "GO" statements in the sql file.

What I didn't know was that variables declared at the top of a file aren't accessible as far as a GO statement is executed. Therefore I had to remove the GO statements in my sql file and the error "Must declare the scalar variable xy" was gone!

Python List vs. Array - when to use?

For almost all cases the normal list is the right choice. The arrays module is more like a thin wrapper over C arrays, which give you kind of strongly typed containers (see docs), with access to more C-like types such as signed/unsigned short or double, which are not part of the built-in types. I'd say use the arrays module only if you really need it, in all other cases stick with lists.

ModelState.IsValid == false, why?

Sometimes a binder throwns an exception with no error message. You can retrieve the exception with the following snippet to find out whats wrong:

(Often if the binder is trying to convert strings to complex types etc)

 if (!ModelState.IsValid)
            {
var errors = ModelState.SelectMany(x => x.Value.Errors.Select(z => z.Exception));

// Breakpoint, Log or examine the list with Exceptions.

  }

How do I escape a single quote ( ' ) in JavaScript?

Since the values are actually inside of an HTML attribute, you should use &apos;

"<img src='something' onmouseover='change(&apos;ex1&apos;)' />";

Differences between time complexity and space complexity?

First of all, the space complexity of this loop is O(1) (the input is customarily not included when calculating how much storage is required by an algorithm).

So the question that I have is if its possible that an algorithm has different time complexity from space complexity?

Yes, it is. In general, the time and the space complexity of an algorithm are not related to each other.

Sometimes one can be increased at the expense of the other. This is called space-time tradeoff.

Changing datagridview cell color dynamically

Considere use DataBindingComplete event for update the style. The next code change the style of the cell:

    private void Grid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        this.Grid.Rows[2].Cells[1].Style.BackColor = Color.Green;
    }

Fix height of a table row in HTML Table

my css

TR.gray-t {background:#949494;}
h3{
    padding-top:3px;
    font:bold 12px/2px Arial;
}

my html

<TR class='gray-t'>
<TD colspan='3'><h3>KAJANG</h3>

I decrease the 2nd size in font.

padding-top is used to fix the size in IE7.

How to get "wc -l" to print just the number of lines without file name?

Best way would be first of all find all files in directory then use AWK NR (Number of Records Variable)

below is the command :

find <directory path>  -type f | awk  'END{print NR}'

example : - find /tmp/ -type f | awk 'END{print NR}'

JavaFX and OpenJDK

According to Oracle integration of OpenJDK & javaFX will be on Q1-2014 ( see roadmap : http://www.oracle.com/technetwork/java/javafx/overview/roadmap-1446331.html ). So, for the 1st question the answer is that you have to wait until then. For the 2nd question there is no other way. So, for now go with java swing or start javaFX and wait

Parse string to DateTime in C#

As I am explaining later, I would always favor the TryParse and TryParseExact methods. Because they are a bit bulky to use, I have written an extension method which makes parsing much easier:

var    dtStr = "2011-03-21 13:26";
DateTime? dt = dtStr.ToDate("yyyy-MM-dd HH:mm");

Or more simply, if you want to use the date patterns of your current culture implicitly, you can use it like:

 DateTime? dt = dtStr.ToDate();

In that case no specific pattern need to be specified.

Unlike Parse, ParseExact etc. it does not throw an exception, and allows you to check via

if (dt.HasValue) { // continue processing } else { // do error handling }

whether the conversion was successful (in this case dt has a value you can access via dt.Value) or not (in this case, it is null).

That even allows to use elegant shortcuts like the "Elvis"-operator ?., for example:

int? year = dtStr?.ToDate("yyyy-MM-dd HH:mm")?.Year;

Here you can also use year.HasValue to check if the conversion succeeded, and if it did not succeed then year will contain null, otherwise the year portion of the date. There is no exception thrown if the conversion failed.


Solution:  The   .ToDate()   extension method

Try it in .NetFiddle

public static class Extensions
{
    /// <summary>
    /// Extension method parsing a date string to a DateTime? <para/>
    /// </summary>
    /// <param name="dateTimeStr">The date string to parse</param>
    /// <param name="dateFmt">dateFmt is optional and allows to pass 
    /// a parsing pattern array or one or more patterns passed 
    /// as string parameters</param>
    /// <returns>Parsed DateTime or null</returns>
    public static DateTime? ToDate(this string dateTimeStr, params string[] dateFmt)
    {
      // example: var dt = "2011-03-21 13:26".ToDate(new string[]{"yyyy-MM-dd HH:mm", 
      //                                                  "M/d/yyyy h:mm:ss tt"});
      // or simpler: 
      // var dt = "2011-03-21 13:26".ToDate("yyyy-MM-dd HH:mm", "M/d/yyyy h:mm:ss tt");
      const DateTimeStyles style = DateTimeStyles.AllowWhiteSpaces;
      if (dateFmt == null)
      {
        var dateInfo = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat;
        dateFmt=dateInfo.GetAllDateTimePatterns();
      }
      var result = DateTime.TryParseExact(dateTimeStr, dateFmt, CultureInfo.InvariantCulture,
                   style, out var dt) ? dt : null as DateTime?;
      return result;
    }
}

Some information about the code

You might wonder, why I have used InvariantCulture calling TryParseExact: This is to force the function to treat format patterns always the same way (otherwise for example "." could be interpreted as decimal separator in English while it is a group separator or a date separator in German). Recall we have already queried the culture based format strings a few lines before so that is okay here.

Update: .ToDate() (without parameters) now defaults to all common date/time patterns of the thread's current culture.
Note that we need the result and dt together, because TryParseExact does not allow to use DateTime?, which we intend to return. In C# Version 7 you could simplify the ToDate function a bit as follows:

 // in C#7 only: "DateTime dt;" - no longer required, declare implicitly
 if (DateTime.TryParseExact(dateTimeStr, dateFmt,
     CultureInfo.InvariantCulture, style, out var dt)) result = dt;

or, if you like it even shorter:

 // in C#7 only: Declaration of result as a "one-liner" ;-)
 var result = DateTime.TryParseExact(dateTimeStr, dateFmt, CultureInfo.InvariantCulture,
              style, out var dt) ? dt : null as DateTime?;

in which case you don't need the two declarations DateTime? result = null; and DateTime dt; at all - you can do it in one line of code. (It would also be allowed to write out DateTime dt instead of out var dt if you prefer that).

The old style of C# would have required it the following way (I removed that from the code above):

  // DateTime? result = null;
  // DateTime dt;
  // if (DateTime.TryParseExact(dateTimeStr, dateFmt,
  //    CultureInfo.InvariantCulture, style, out dt)) result = dt;

I have simplified the code further by using the params keyword: Now you don't need the 2nd overloaded method any more.


Example of usage

var dtStr="2011-03-21 13:26";    
var dt=dtStr.ToDate("yyyy-MM-dd HH:mm");
if (dt.HasValue)
{
    Console.WriteLine("Successful!");
    // ... dt.Value now contains the converted DateTime ...
}
else
{
    Console.WriteLine("Invalid date format!");
}

As you can see, this example just queries dt.HasValue to see if the conversion was successful or not. As an extra bonus, TryParseExact allows to specify strict DateTimeStyles so you know exactly whether a proper date/time string has been passed or not.


More Examples of usage

The overloaded function allows you to pass an array of valid formats used for parsing/converting dates as shown here as well (TryParseExact directly supports this), e.g.

string[] dateFmt = {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
                     "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", 
                     "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", 
                     "M/d/yyyy h:mm", "M/d/yyyy h:mm", 
                     "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
var dtStr="5/1/2009 6:32 PM"; 
var dt=dtStr.ToDate(dateFmt);

If you have only a few template patterns, you can also write:

var dateStr = "2011-03-21 13:26";
var dt = dateStr.ToDate("yyyy-MM-dd HH:mm", "M/d/yyyy h:mm:ss tt");

Advanced examples

You can use the ?? operator to default to a fail-safe format, e.g.

var dtStr = "2017-12-30 11:37:00";
var dt = (dtStr.ToDate()) ?? dtStr.ToDate("yyyy-MM-dd HH:mm:ss");

In this case, the .ToDate() would use common local culture date formats, and if all these failed, it would try to use the ISO standard format "yyyy-MM-dd HH:mm:ss" as a fallback. This way, the extension function allows to "chain" different fallback formats easily.

You can even use the extension in LINQ, try this out (it's in the .NetFiddle above):

var strDateArray = new[] { "15-01-2019", "15.01.2021" };
var patterns=new[] { "dd-MM-yyyy", "dd.MM.yyyy" };
var dtRange = strDateArray.Select(s => s.ToDate(patterns));
dtRange.Dump(); 

which will convert the dates in the array on the fly by using the patterns and dump them to the console.


Some background about TryParseExact

Finally, Here are some comments about the background (i.e. the reason why I have written it this way):

I am preferring TryParseExact in this extension method, because you avoid exception handling - you can read in Eric Lippert's article about exceptions why you should use TryParse rather than Parse, I quote him about that topic:2)

This unfortunate design decision1) [annotation: to let the Parse method throw an exception] was so vexing that of course the frameworks team implemented TryParse shortly thereafter which does the right thing.

It does, but TryParse and TryParseExact both are still a lot less than comfortable to use: They force you to use an uninitialized variable as an out parameter which must not be nullable and while you're converting you need to evaluate the boolean return value - either you have to use an ifstatement immediately or you have to store the return value in an additional boolean variable so you're able to do the check later. And you can't just use the target variable without knowing if the conversion was successful or not.

In most cases you just want to know whether the conversion was successful or not (and of course the value if it was successful), so a nullable target variable which keeps all the information would be desirable and much more elegant - because the entire information is just stored in one place: That is consistent and easy to use, and much less error-prone.

The extension method I have written does exactly that (it also shows you what kind of code you would have to write every time if you're not going to use it).

I believe the benefit of .ToDate(strDateFormat) is that it looks simple and clean - as simple as the original DateTime.Parse was supposed to be - but with the ability to check if the conversion was successful, and without throwing exceptions.


1) What is meant here is that exception handling (i.e. a try { ... } catch(Exception ex) { ...} block) - which is necessary when you're using Parse because it will throw an exception if an invalid string is parsed - is not only unnecessary in this case but also annoying, and complicating your code. TryParse avoids all this as the code sample I've provided is showing.


2) Eric Lippert is a famous StackOverflow fellow and was working at Microsoft as principal developer on the C# compiler team for a couple of years.

java.io.IOException: Server returned HTTP response code: 500

I had this problem i.e. works fine when pasted into browser but 505s when done through java. It was simply the spaces that needed to be escaped/encoded.

A 'for' loop to iterate over an enum in Java

If you don't care about the order this should work:

Set<Direction> directions = EnumSet.allOf(Direction.class);
for(Direction direction : directions) {
    // do stuff
}

What is the "hasClass" function with plain JavaScript?

This 'hasClass' function works in IE8+, FireFox and Chrome:

hasClass = function(el, cls) {
    var regexp = new RegExp('(\\s|^)' + cls + '(\\s|$)'),
        target = (typeof el.className === 'undefined') ? window.event.srcElement : el;
    return target.className.match(regexp);
}

[Updated Jan'2021] A better way:

hasClass = (el, cls) => {
  [...el.classList].includes(cls); //cls without dot
};

Multiple actions were found that match the request in Web Api

Without using actions the options would be:

  1. move one of the methods to a different controller, so that they don't clash.

  2. use just one method that takes the param, and if it's null call the other method from your code.

How can we run a test method with multiple parameters in MSTest?

MSTest has a powerful attribute called DataSource. Using this you can perform data-driven tests as you asked. You can have your test data in XML, CSV, or in a database. Here are few links that will guide you

How do I loop through or enumerate a JavaScript object?

After looking through all the answers in here, hasOwnProperty isn't required for my own usage because my json object is clean; there's really no sense in adding any additional javascript processing. This is all I'm using:

for (var key in p) {
    console.log(key + ' => ' + p[key]);
    // key is key
    // value is p[key]
}

Getting execute permission to xp_cmdshell

To expand on what has been provided for automatically exporting data as csv to a network share via SQL Server Agent.

(1) Enable the xp_cmdshell procedure:

-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO

-- Enable the xp_cmdshell procedure
EXEC sp_configure 'xp_cmdshell', 1
RECONFIGURE
GO

(2) Create a login 'Domain\TestUser' (windows user) for the non-sysadmin user that has public access to the master database. Done through user mapping

(3) Give log on as batch job: Navigate to Local Security Policy -> Local Policies -> User Rights Assignment. Add user to "Log on as a batch job"

(4) Give read/write permissions to network folder for domain\user

(5) Grant EXEC permission on the xp_cmdshell stored procedure:

GRANT EXECUTE ON xp_cmdshell TO [Domain\TestUser]

(6) Create a proxy account that xp_cmdshell will be run under using sp_xp_cmdshell_proxy_account

EXEC sp_xp_cmdshell_proxy_account 'Domain\TestUser', 'password_for_domain_user'

(7) If the sp_xp_cmdshell_proxy_account command doesn't work, manually create it

create credential ##xp_cmdshell_proxy_account## with identity = 'Domain\DomainUser', secret = 'password'

(8) Enable SQL Server Agent. Open SQL Server Configuration Manager, navigate to SQL Server Services, enable SQL Server Agent.

(9) Create automated job. Open SSMS, select SQL Server Agent, then right-click jobs and click "New Job".

(10) Select "Owner" as your created user. Select "Steps", make "type" = T-SQL. Fill out command field similar to below. Set delimiter as ','

EXEC master..xp_cmdshell 'SQLCMD -q "select * from master" -o file.csv -s "," 

(11) Fill out schedules accordingly.

e.printStackTrace equivalent in python

There is also logging.exception.

import logging

...

try:
    g()
except Exception as ex:
    logging.exception("Something awful happened!")
    # will print this message followed by traceback

Output:

ERROR 2007-09-18 23:30:19,913 error 1294 Something awful happened!
Traceback (most recent call last):
  File "b.py", line 22, in f
    g()
  File "b.py", line 14, in g
    1/0
ZeroDivisionError: integer division or modulo by zero

(From http://blog.tplus1.com/index.php/2007/09/28/the-python-logging-module-is-much-better-than-print-statements/ via How to print the full traceback without halting the program?)

Reading a cell value in Excel vba and write in another Cell

I have this function for this case ..

Function GetValue(r As Range, Tag As String) As Integer
Dim c, nRet As String
Dim n, x As Integer
Dim bNum As Boolean

c = r.Value
n = InStr(c, Tag)
For x = n + 1 To Len(c)
  Select Case Mid(c, x, 1)
    Case ":":    bNum = True
    Case " ": Exit For
    Case Else: If bNum Then nRet = nRet & Mid(c, x, 1)
  End Select
Next
GetValue = val(nRet)
End Function

To fill cell BC .. (assumed that you check cell A1)

Worksheets("Übersicht_2013").Cells(i, "BC") = GetValue(range("A1"),"S")

console.log showing contents of array object

I warmly recommend this snippet to ensure, accidentally left code pieces don't fail on clients browsers:

/* neutralize absence of firebug */
if ((typeof console) !== 'object' || (typeof console.info) !== 'function') {
    window.console = {};
    window.console.info = window.console.log = window.console.warn = function(msg) {};
    window.console.trace = window.console.error = window.console.assert = function(msg) {};
}

rather than defining an empty function, this snippet is also a good starting point for rolling your own console surrogate if needed, i.e. dumping those infos into a .debug Container, show alerts (could get plenty) or such...

If you do use firefox+firebug, console.dir() is best for dumping array output, see here.

In Git, how do I figure out what my current revision is?

below will work with any previously pushed revision, not only HEAD

for abbreviated revision hash:

git log -1 --pretty=format:%h

for long revision hash:

git log -1 --pretty=format:%H

Pandas DataFrame concat vs append

So what are you doing is with append and concat is almost equivalent. The difference is the empty DataFrame. For some reason this causes a big slowdown, not sure exactly why, will have to look at some point. Below is a recreation of basically what you did.

I almost always use concat (though in this case they are equivalent, except for the empty frame); if you don't use the empty frame they will be the same speed.

In [17]: df1 = pd.DataFrame(dict(A = range(10000)),index=pd.date_range('20130101',periods=10000,freq='s'))

In [18]: df1
Out[18]: 
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 10000 entries, 2013-01-01 00:00:00 to 2013-01-01 02:46:39
Freq: S
Data columns (total 1 columns):
A    10000  non-null values
dtypes: int64(1)

In [19]: df4 = pd.DataFrame()

The concat

In [20]: %timeit pd.concat([df1,df2,df3])
1000 loops, best of 3: 270 us per loop

This is equavalent of your append

In [21]: %timeit pd.concat([df4,df1,df2,df3])
10 loops, best of 

 3: 56.8 ms per loop

How to remove &quot; from my Json in javascript?

var data = $('<div>').html('[{&quot;Id&quot;:1,&quot;Name&quot;:&quot;Name}]')[0].textContent;

that should parse all the encoded values you need.

Find first element in a sequence that matches a predicate

J.F. Sebastian's answer is most elegant but requires python 2.6 as fortran pointed out.

For Python version < 2.6, here's the best I can come up with:

from itertools import repeat,ifilter,chain
chain(ifilter(predicate,seq),repeat(None)).next()

Alternatively if you needed a list later (list handles the StopIteration), or you needed more than just the first but still not all, you can do it with islice:

from itertools import islice,ifilter
list(islice(ifilter(predicate,seq),1))

UPDATE: Although I am personally using a predefined function called first() that catches a StopIteration and returns None, Here's a possible improvement over the above example: avoid using filter / ifilter:

from itertools import islice,chain
chain((x for x in seq if predicate(x)),repeat(None)).next()

Eclipse: Enable autocomplete / content assist

For auto-completion triggers in Eclipse like IntelliJ, follow these steps,

  1. Go to the Eclipse Windows menu -> Preferences -> Java -> Editor -> Content assist and check your settings here
  2. Enter in Autocomplete activation string for java: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ._@
  3. Apply and Close the Dialog box.

Thanks.

How to create a custom exception type in Java?

You have to define your exception elsewhere as a new class

public class YourCustomException extends Exception{

//Required inherited methods here
}

Then you can throw and catch YourCustomException as much as you'd like.

MySQL: Get column name or alias from query

This is the same as thefreeman but more in pythonic way using list and dictionary comprehension

columns = cursor.description 
result = [{columns[index][0]:column for index, column in enumerate(value)} for value in cursor.fetchall()]

pprint.pprint(result)

How can I easily convert DataReader to List<T>?

I would suggest writing an extension method for this:

public static IEnumerable<T> Select<T>(this IDataReader reader,
                                       Func<IDataReader, T> projection)
{
    while (reader.Read())
    {
        yield return projection(reader);
    }
}

You can then use LINQ's ToList() method to convert that into a List<T> if you want, like this:

using (IDataReader reader = ...)
{
    List<Customer> customers = reader.Select(r => new Customer {
        CustomerId = r["id"] is DBNull ? null : r["id"].ToString(),
        CustomerName = r["name"] is DBNull ? null : r["name"].ToString() 
    }).ToList();
}

I would actually suggest putting a FromDataReader method in Customer (or somewhere else):

public static Customer FromDataReader(IDataReader reader) { ... }

That would leave:

using (IDataReader reader = ...)
{
    List<Customer> customers = reader.Select<Customer>(Customer.FromDataReader)
                                     .ToList();
}

(I don't think type inference would work in this case, but I could be wrong...)

print highest value in dict with key

You could use use max and min with dict.get:

maximum = max(mydict, key=mydict.get)  # Just use 'min' instead of 'max' for minimum.
print(maximum, mydict[maximum])
# D 87

C Program to find day of week given date

As reported also by Wikipedia, in 1990 Michael Keith and Tom Craver published an expression to minimise the number of keystrokes needed to enter a self-contained function for converting a Gregorian date into a numerical day of the week.

The expression does preserve neither y nor d, and returns a zero-based index representing the day, starting with Sunday, i.e. if the day is Monday the expression returns 1.

A code example which uses the expression follows:

int d    = 15   ; //Day     1-31
int m    = 5    ; //Month   1-12`
int y    = 2013 ; //Year    2013` 

int weekday  = (d += m < 3 ? y-- : y - 2, 23*m/9 + d + 4 + y/4- y/100 + y/400)%7;  

The expression uses the comma operator, as discussed in this answer.

Enjoy! ;-)

Convert Month Number to Month Name Function in SQL

SUBSTRING('JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC ', (@intMonth * 4) - 3, 3)

How do you move a file?

Cut file via operating system context menu as you usually do, then instead of doing regular paste, right click to bring context menu, then choose TortoiseSVN -> Paste (make sure you commit from root to include both old and new files in the commit).

Authentication plugin 'caching_sha2_password' cannot be loaded

Almost like answers above but may be in simple queries, I was getting this error in my spring boot application along with hibernate after MySQL upgrade. We created a new user by running the queries below against our DB. I believe this is a temp work around to use sha256_password instead of latest and good authentication caching_sha2_password.

CREATE USER 'username'@'localhost' IDENTIFIED WITH mysql_native_password BY 'pa$$word';

GRANT ALL PRIVILEGES ON * .* TO 'username'@'localhost';

Calling another different view from the controller using ASP.NET MVC 4

Also, you can just set the ViewName:

return View("ViewName");

Full controller example:

public ActionResult SomeAction() {
    if (condition)
    {
        return View("CustomView");
    }else{
        return View();
    }
}

This works on MVC 5.

setting JAVA_HOME & CLASSPATH in CentOS 6

Instructions:

  1. Click on the Terminal icon in the desktop panel to open a terminal window and access the command prompt.
  2. Type the command which java to find the path to the Java executable file.
  3. Type the command su - to become the root user.
  4. Type the command vi /root/.bash_profile to open the system bash_profile file in the Vi text editor. You can replace vi with your preferred text editor.
  5. Type export JAVA_HOME=/usr/local/java/ at the bottom of the file. Replace /usr/local/java with the location found in step two.
  6. Save and close the bash_profile file.
  7. Type the command exit to close the root session.
  8. Log out of the system and log back in.
  9. Type the command echo $JAVA_HOME to ensure that the path was set correctly.

set java_home in centos

Any way to clear python's IDLE window?

It seems it is impossible to do it without any external library.

An alternative way if you are using windows and don't want to open and close the shell everytime you want to clear it is by using windows command prompt.

  • Type python and hit enter to turn windows command prompt to python idle (make sure python is installed).

  • Type quit() and hit enter to turn it back to windows command prompt.

  • Type cls and hit enter to clear the command prompt/ windows shell.

Column/Vertical selection with Keyboard in SublimeText 3

I know notepad++ has a feature that lets you select blocks of text independent of line/column by holding control + alt + drag. So you can select just about any block of text you want.

Listening for variable changes in JavaScript

Using Prototype: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

_x000D_
_x000D_
// Console_x000D_
function print(t) {_x000D_
  var c = document.getElementById('console');_x000D_
  c.innerHTML = c.innerHTML + '<br />' + t;_x000D_
}_x000D_
_x000D_
// Demo_x000D_
var myVar = 123;_x000D_
_x000D_
Object.defineProperty(this, 'varWatch', {_x000D_
  get: function () { return myVar; },_x000D_
  set: function (v) {_x000D_
    myVar = v;_x000D_
    print('Value changed! New value: ' + v);_x000D_
  }_x000D_
});_x000D_
_x000D_
print(varWatch);_x000D_
varWatch = 456;_x000D_
print(varWatch);
_x000D_
<pre id="console">_x000D_
</pre>
_x000D_
_x000D_
_x000D_

Other example

_x000D_
_x000D_
// Console_x000D_
function print(t) {_x000D_
  var c = document.getElementById('console');_x000D_
  c.innerHTML = c.innerHTML + '<br />' + t;_x000D_
}_x000D_
_x000D_
// Demo_x000D_
var varw = (function (context) {_x000D_
  return function (varName, varValue) {_x000D_
    var value = varValue;_x000D_
  _x000D_
    Object.defineProperty(context, varName, {_x000D_
      get: function () { return value; },_x000D_
      set: function (v) {_x000D_
        value = v;_x000D_
        print('Value changed! New value: ' + value);_x000D_
      }_x000D_
    });_x000D_
  };_x000D_
})(window);_x000D_
_x000D_
varw('varWatch'); // Declare_x000D_
print(varWatch);_x000D_
varWatch = 456;_x000D_
print(varWatch);_x000D_
_x000D_
print('---');_x000D_
_x000D_
varw('otherVarWatch', 123); // Declare with initial value_x000D_
print(otherVarWatch);_x000D_
otherVarWatch = 789;_x000D_
print(otherVarWatch);
_x000D_
<pre id="console">_x000D_
</pre>
_x000D_
_x000D_
_x000D_

Capture iOS Simulator video for App Preview

The Apple's Simulator User Guide states in Taking a Screenshot or Recording a Video Using the Command Line paragraph:

You can take a screenshot or record a video of the simulator window using the xcrun command-line utility.


To record a video, use the recordVideo operation in your Terminal:

xcrun simctl io booted recordVideo <filename>.<extension>

Note that the file will be created in the current directory of your Terminal.


If you want to save the video file in your Desktop folder, use the following command:

xcrun simctl io booted recordVideo ~/Desktop/<filename>.<extension>

To stop recording, press Control-C in Terminal.

call javascript function on hyperlink click

The simplest answer of all is...

_x000D_
_x000D_
<a href="javascript:alert('You clicked!')">My link</a>
_x000D_
_x000D_
_x000D_

Or to answer the question of calling a javascript function:

_x000D_
_x000D_
<script type="text/javascript">_x000D_
function myFunction(myMessage) {_x000D_
    alert(myMessage);_x000D_
}_x000D_
</script>_x000D_
_x000D_
<a href="javascript:myFunction('You clicked!')">My link</a>
_x000D_
_x000D_
_x000D_

Concatenating multiple text files into a single file in Bash

all of that is nasty....

ls | grep *.txt | while read file; do cat $file >> ./output.txt; done;

easy stuff.

How to draw checkbox or tick mark in GitHub Markdown table?

Here is what I have that helps you and others about markdown checkbox table. Enjoy!

| Projects | Operating Systems | Programming Languages   | CAM/CAD Programs | Microcontrollers and Processors | 
|---------------------------------- |---------------|---------------|----------------|-----------|
| <ul><li>[ ] Blog </li></ul>       | <ul><li>[ ] CentOS</li></ul>        | <ul><li>[ ] Python </li></ul> | <ul><li>[ ] AutoCAD Electrical </li></ul> | <ul><li>[ ] Arduino </li></ul> |
| <ul><li>[ ] PyGame</li></ul>   | <ul><li>[ ] Fedora </li></ul>       | <ul><li>[ ] C</li></ul> | <ul><li>[ ] 3DsMax </li></ul> |<ul><li>[ ] Raspberry Pi </li></ul> |
| <ul><li>[ ] Server Info Display</li></ul>| <ul><li>[ ] Ubuntu</li></ul> | <ul><li>[ ] C++ </li></ul> | <ul><li>[ ] Adobe AfterEffects </li></ul> |<ul><li>[ ]  </li></ul> |
| <ul><li>[ ] Twitter Subs Bot </li></ul> | <ul><li>[ ] ROS </li></ul>    | <ul><li>[ ] C# </li></ul> | <ul><li>[ ] Adobe Illustrator </li></ul> |<ul><li>[ ]  </li></ul> |

How do you detect where two line segments intersect?

Question C: How do you detect whether or not two line segments intersect?

I have searched for the same topic, and I wasn't happy with the answers. So I have written an article that explains very detailed how to check if two line segments intersect with a lot of images. There is complete (and tested) Java-code.

Here is the article, cropped to the most important parts:

The algorithm, that checks if line segment a intersects with line segment b, looks like this:

Enter image description here

What are bounding boxes? Here are two bounding boxes of two line segments:

enter image description here

If both bounding boxes have an intersection, you move line segment a so that one point is at (0|0). Now you have a line through the origin defined by a. Now move line segment b the same way and check if the new points of line segment b are on different sides of line a. If this is the case, check it the other way around. If this is also the case, the line segments intersect. If not, they don't intersect.

Question A: Where do two line segments intersect?

You know that two line segments a and b intersect. If you don't know that, check it with the tools I gave you in "Question C".

Now you can go through some cases and get the solution with 7th grade math (see code and interactive example).

Question B: How do you detect whether or not two lines intersect?

Let's say your point A = (x1, y1), point B = (x2, y2), C = (x_3, y_3), D = (x_4, y_4). Your first line is defined by AB (with A != B), and your second one by CD (with C != D).

function doLinesIntersect(AB, CD) {
    if (x1 == x2) {
        return !(x3 == x4 && x1 != x3);
    } else if (x3 == x4) {
        return true;
    } else {
        // Both lines are not parallel to the y-axis
        m1 = (y1-y2)/(x1-x2);
        m2 = (y3-y4)/(x3-x4);
        return m1 != m2;
    }
}

Question D: Where do two lines intersect?

Check with Question B if they intersect at all.

The lines a and b are defined by two points for each line. You can basically apply the same logic was used in Question A.

ES6 class variable alternatives

In your example:

class MyClass {
    const MY_CONST = 'string';
    constructor(){
        this.MY_CONST;
    }
}

Because of MY_CONST is primitive https://developer.mozilla.org/en-US/docs/Glossary/Primitive we can just do:

class MyClass {
    static get MY_CONST() {
        return 'string';
    }
    get MY_CONST() {
        return this.constructor.MY_CONST;
    }
    constructor() {
        alert(this.MY_CONST === this.constructor.MY_CONST);
    }
}
alert(MyClass.MY_CONST);
new MyClass

// alert: string ; true

But if MY_CONST is reference type like static get MY_CONST() {return ['string'];} alert output is string, false. In such case delete operator can do the trick:

class MyClass {
    static get MY_CONST() {
        delete MyClass.MY_CONST;
        return MyClass.MY_CONST = 'string';
    }
    get MY_CONST() {
        return this.constructor.MY_CONST;
    }
    constructor() {
        alert(this.MY_CONST === this.constructor.MY_CONST);
    }
}
alert(MyClass.MY_CONST);
new MyClass

// alert: string ; true

And finally for class variable not const:

class MyClass {
    static get MY_CONST() {
        delete MyClass.MY_CONST;
        return MyClass.MY_CONST = 'string';
    }
    static set U_YIN_YANG(value) {
      delete MyClass.MY_CONST;
      MyClass.MY_CONST = value;
    }
    get MY_CONST() {
        return this.constructor.MY_CONST;
    }
    set MY_CONST(value) {
        this.constructor.MY_CONST = value;
    }
    constructor() {
        alert(this.MY_CONST === this.constructor.MY_CONST);
    }
}
alert(MyClass.MY_CONST);
new MyClass
// alert: string, true
MyClass.MY_CONST = ['string, 42']
alert(MyClass.MY_CONST);
new MyClass
// alert: string, 42 ; true

How to keep form values after post

If you are looking to just repopulate the fields with the values that were posted in them, then just echo the post value back into the field, like so:

<input type="text" name="myField1" value="<?php echo isset($_POST['myField1']) ? $_POST['myField1'] : '' ?>" />

How to fix the error "Windows SDK version 8.1" was not found?

I realize this post is a few years old, but I just wanted to extend this to anyone still struggling through this issue.

The company I work for still uses VS2015 so in turn I still use VS2015. I recently started working on a RPC application using C++ and found the need to download the Win32 Templates. Like many others I was having this "SDK 8.1 was not found" issue. i took the following corrective actions with no luck.

  • I found the SDK through Micrsoft at the following link https://developer.microsoft.com/en-us/windows/downloads/sdk-archive/ as referenced above and downloaded it.
  • I located my VS2015 install in Apps & Features and ran the repair.
  • I completely uninstalled my VS2015 and reinstalled it.
  • I attempted to manually point my console app "Executable" and "Include" directories to the C:\Program Files (x86)\Microsoft SDKs\Windows Kits\8.1 and C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools.

None of the attempts above corrected the issue for me...

I then found this article on social MSDN https://social.msdn.microsoft.com/Forums/office/en-US/5287c51b-46d0-4a79-baad-ddde36af4885/visual-studio-cant-find-windows-81-sdk-when-trying-to-build-vs2015?forum=visualstudiogeneral

Finally what resolved the issue for me was:

  • Uninstalling and reinstalling VS2015.
  • Locating my installed "Windows Software Development Kit for Windows 8.1" and running the repair.
  • Checked my "C:\Program Files (x86)\Microsoft SDKs\Windows Kits\8.1" to verify the "DesignTime" folder was in fact there.
  • Opened VS created a Win32 Console application and comiled with no errors or issues

I hope this saves anyone else from almost 3 full days of frustration and loss of productivity.

What does character set and collation mean exactly?

From MySQL docs:

A character set is a set of symbols and encodings. A collation is a set of rules for comparing characters in a character set. Let's make the distinction clear with an example of an imaginary character set.

Suppose that we have an alphabet with four letters: 'A', 'B', 'a', 'b'. We give each letter a number: 'A' = 0, 'B' = 1, 'a' = 2, 'b' = 3. The letter 'A' is a symbol, the number 0 is the encoding for 'A', and the combination of all four letters and their encodings is a character set.

Now, suppose that we want to compare two string values, 'A' and 'B'. The simplest way to do this is to look at the encodings: 0 for 'A' and 1 for 'B'. Because 0 is less than 1, we say 'A' is less than 'B'. Now, what we've just done is apply a collation to our character set. The collation is a set of rules (only one rule in this case): "compare the encodings." We call this simplest of all possible collations a binary collation.

But what if we want to say that the lowercase and uppercase letters are equivalent? Then we would have at least two rules: (1) treat the lowercase letters 'a' and 'b' as equivalent to 'A' and 'B'; (2) then compare the encodings. We call this a case-insensitive collation. It's a little more complex than a binary collation.

In real life, most character sets have many characters: not just 'A' and 'B' but whole alphabets, sometimes multiple alphabets or eastern writing systems with thousands of characters, along with many special symbols and punctuation marks. Also in real life, most collations have many rules: not just case insensitivity but also accent insensitivity (an "accent" is a mark attached to a character as in German 'ö') and multiple-character mappings (such as the rule that 'ö' = 'OE' in one of the two German collations).

How Best to Compare Two Collections in Java and Act on Them?

You can use Java 8 streams, for example

set1.stream().filter(s -> set2.contains(s)).collect(Collectors.toSet());

or Sets class from Guava:

Set<String> intersection = Sets.intersection(set1, set2);
Set<String> difference = Sets.difference(set1, set2);
Set<String> symmetricDifference = Sets.symmetricDifference(set1, set2);
Set<String> union = Sets.union(set1, set2);

Android: Reverse geocoding - getFromLocation

The following code snippet is doing it for me (lat and lng are doubles declared above this bit):

Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);

html button to send email

 <form action="mailto:[email protected]" method="post"               enctype="text/plain">
 Name:<br>
<input type="text" name="name"><br>
 E-mail:<br>
<input type="text" name="mail"><br>
Comment:<br>
<input type="text" name="comment" size="50"><br><br>
<input type="submit" value="Send">
<input type="reset" value="Reset">

Twitter Bootstrap onclick event on buttons-radio

If your html is similar to the example, so the click event is produced over the label, not in the input, so I use the next code: Html example:

<div id="myButtons" class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="radio" name="options" id="option1" autocomplete="off" checked> Radio 1 (preselected)
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option2" autocomplete="off"> Radio 2
  </label>      
</div>

Javascript code for the event:

$('#option1').parent().on("click", function () {
   alert("click fired"); 
});

Is it really impossible to make a div fit its size to its content?

CSS display setting

It is of course possible - JSFiddle proof of concept where you can see all three possible solutions:

  • display: inline-block - this is the one you're not aware of

  • position: absolute

  • float: left/right

Getting Current time to display in Label. VB.net

Try This.....

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load    
    Timer1.Start()
End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    Label12.Text = TimeOfDay.ToString("h:mm:ss tt")
End Sub

build failed with: ld: duplicate symbol _OBJC_CLASS_$_Algebra5FirstViewController

also had this problem by declaring a const * NSString in the header file (incorrectly) instead of the implementation file (correctly)

How can I suppress the newline after a print statement?

Code for Python 3.6.1

print("This first text and " , end="")

print("second text will be on the same line")

print("Unlike this text which will be on a newline")

Output

>>>
This first text and second text will be on the same line
Unlike this text which will be on a newline

Google Chrome display JSON AJAX response as tree and not as a plain text

To see a tree view in recent versions of Chrome:

Navigate to Developer Tools > Network > the given response > Preview

How to do a timer in Angular 5

This may be overkill for what you're looking for, but there is an npm package called marky that you can use to do this. It gives you a couple of extra features beyond just starting and stopping a timer. You just need to install it via npm and then import the dependency anywhere you'd like to use it. Here is a link to the npm package: https://www.npmjs.com/package/marky

An example of use after installing via npm would be as follows:

import * as _M from 'marky';

@Component({
 selector: 'app-test',
 templateUrl: './test.component.html',
 styleUrls: ['./test.component.scss']
})

export class TestComponent implements OnInit {
 Marky = _M;
}

constructor() {}

ngOnInit() {}

startTimer(key: string) {
 this.Marky.mark(key);
}

stopTimer(key: string) {
 this.Marky.stop(key);
}

key is simply a string which you are establishing to identify that particular measurement of time. You can have multiple measures which you can go back and reference your timer stats using the keys you create.

How do I check if an element is really visible with JavaScript?

Interesting question.

This would be my approach.

  1. At first check that element.style.visibility !== 'hidden' && element.style.display !== 'none'
  2. Then test with document.elementFromPoint(element.offsetLeft, element.offsetTop) if the returned element is the element I expect, this is tricky to detect if an element is overlapping another completely.
  3. Finally test if offsetTop and offsetLeft are located in the viewport taking scroll offsets into account.

Hope it helps.

Determine if two rectangles overlap each other?

This is a very fast way to check with C++ if two rectangles overlap:

return std::max(rectA.left, rectB.left) < std::min(rectA.right, rectB.right)
    && std::max(rectA.top, rectB.top) < std::min(rectA.bottom, rectB.bottom);

It works by calculating the left and right borders of the intersecting rectangle, and then comparing them: if the right border is equal to or less than the left border, it means that the intersection is empty and therefore the rectangles do not overlap; otherwise, it tries again with the top and bottom borders.

What is the advantage of this method over the conventional alternative of 4 comparisons? It's about how modern processors are designed. They have something called branch prediction, which works well when the result of a comparison is always the same, but have a huge performance penalty otherwise. However, in the absence of branch instructions, the CPU performs quite well. By calculating the borders of the intersection instead of having two separate checks for each axis, we're saving two branches, one per pair.

It is possible that the four comparisons method outperforms this one, if the first comparison has a high chance of being false. That is very rare, though, because it means that the second rectangle is most often on the left side of the first rectangle, and not on the right side or overlapping it; and most often, you need to check rectangles on both sides of the first one, which normally voids the advantages of branch prediction.

This method can be improved even more, depending on the expected distribution of rectangles:

  • If you expect the checked rectangles to be predominantly to the left or right of each other, then the method above works best. This is probably the case, for example, when you're using the rectangle intersection to check collisions for a game, where the game objects are predominantly distributed horizontally (e.g. a SuperMarioBros-like game).
  • If you expect the checked rectangles to be predominantly to the top or bottom of each other, e.g. in an Icy Tower type of game, then checking top/bottom first and left/right last will probably be faster:
return std::max(rectA.top, rectB.top) < std::min(rectA.bottom, rectB.bottom)
    && std::max(rectA.left, rectB.left) < std::min(rectA.right, rectB.right);
  • If the probability of intersecting is close to the probability of not intersecting, however, it's better to have a completely branchless alternative:
return std::max(rectA.left, rectB.left) < std::min(rectA.right, rectB.right)
     & std::max(rectA.top, rectB.top) < std::min(rectA.bottom, rectB.bottom);

(Note the change of && to a single &)

What are .a and .so files?

.a are static libraries. If you use code stored inside them, it's taken from them and embedded into your own binary. In Visual Studio, these would be .lib files.

.so are dynamic libraries. If you use code stored inside them, it's not taken and embedded into your own binary. Instead it's just referenced, so the binary will depend on them and the code from the so file is added/loaded at runtime. In Visual Studio/Windows these would be .dll files (with small .lib files containing linking information).

How to open a URL in a new Tab using JavaScript or jQuery?

This is as simple as this.

window.open('_link is here_', 'name'); 

Function description:

name is a name of the window. Following names are supported:

  • _blank - URL is loaded into a new tab. This is default.
  • _parent - URL is loaded into the parent frame
  • _self - URL replaces the current page
  • _top - URL replaces any framesets that may be loaded

Change the size of a JTextField inside a JBorderLayout

With a BorderLayout you need to use setPreferredSize instead of setSize

C# how to create a Guid value?

There are two ways

var guid = Guid.NewGuid();

or

var guid = Guid.NewGuid().ToString();

both use the Guid class, the first creates a Guid Object, the second a Guid string.

How to set -source 1.7 in Android Studio and Gradle

Right click on your project > Open Module Setting > Select "Project" in "Project Setting" section

Change the Project SDK to latest(may be API 21) and Project language level to 7+

mkdir's "-p" option

Note that -p is an argument to the mkdir command specifically, not the whole of Unix. Every command can have whatever arguments it needs.

In this case it means "parents", meaning mkdir will create a directory and any parents that don't already exist.

JQuery - Call the jquery button click event based on name property

$('element[name="element_name"]').click(function(){
    //do stuff
});

in your case:

$('input[name="btnName"]').click(function(){
    //do stuff
});

Arduino Tools > Serial Port greyed out

chdmod works for my under debian (proxmox):

# chmod a+rw /dev/ttyACM0

For installing arduino IDE:

# apt-get install arduino arduino-core arduino-mk

Add the user to dialout group:

# gpasswd -a user dialout

Restart Linux.

Try with the File > Examples > 01.Basic > Blink, change the 2 delays to delay(60) and click the upload button for testing on arduino, led must blink faster. ;)

Using C# to check if string contains a string in string array

I would use Linq but it still can be done through:

new[] {"text1", "text2", "etc"}.Contains(ItemToFind);

Add back button to action bar

You'll need to check menuItem.getItemId() against android.R.id.home in the onOptionsItemSelected method

Duplicate of Android Sherlock ActionBar Up button

XML Error: There are multiple root elements

If you're in charge (or have any control over the web service), get them to add a unique root element!

If you can't change that at all, then you can do a bit of regex or string-splitting to parse each and pass each element to your XML Reader.

Alternatively, you could manually add a junk root element, by prefixing an opening tag and suffixing a closing tag.

Create new project on Android, Error: Studio Unknown host 'services.gradle.org'

I was also having the same problem. I tried the following and it's working for me now:
Please try the following steps:

Go to..

File > Settings > Appearance & Behavior > System Settings > HTTP Proxy [Under IDE Settings] Enable following option Auto-detect proxy settings

On Mac it's under:

Android Studio > Preferences > Appearance & Behaviour... etc

you can also use the test connection button and check with google.com to see if it works or not.

Excel: last character/string match in a string

A simple way to do that in VBA is:

YourText = "c:\excel\text.txt"
xString = Mid(YourText, 2 + Len(YourText) - InStr(StrReverse(YourText), "\" ))

Call to undefined function mysql_connect

Check your php.ini, I'm using Apache2.2 + php 5.3. and I had the same problem and after modify the php.ini in order to set the libraries directory of PHP, it worked correctly. The problem is the default extension_dir configuration value.

The default (and WRONG) value for my work enviroment is

; extension_dir="ext"

without any full path and commented with a semicolon.

There are two solution that worked fine for me.

1.- Including this line at php.ini file

extension_dir="X:/[PathToYourPHPDirectory]/ext

Where X: is your drive letter instalation (normally C: or D: )

2.- You can try to simply uncomment, deleting semicolon. Include the next line at php.ini file

extension_dir="ext"

Both ways worked fine for me but choose yours. Don't forget restart Apache before try again.

I hope this help you.

Specifying content of an iframe instead of the src attribute to a page

iframe now supports srcdoc which can be used to specify the HTML content of the page to show in the inline frame.

VSCode Change Default Terminal

If you want to select the type of console, you can write this in the file "keybinding.json" (this file can be found in the following path "File-> Preferences-> Keyboard Shortcuts") `

//with this you can select what type of console you want
{
    "key": "ctrl+shift+t",
    "command": "shellLauncher.launch"
},

//and this will help you quickly change console
{ 
    "key": "ctrl+shift+j", 
    "command": "workbench.action.terminal.focusNext" 
},
{
    "key": "ctrl+shift+k", 
    "command": "workbench.action.terminal.focusPrevious" 
}`

How to start a background process in Python?

You probably want the answer to "How to call an external command in Python".

The simplest approach is to use the os.system function, e.g.:

import os
os.system("some_command &")

Basically, whatever you pass to the system function will be executed the same as if you'd passed it to the shell in a script.

Sourcetree - undo unpushed commits

If you want to delete a commit you can do it as part of an interactive rebase. But do it with caution, so you don't end up messing up your repo.

In Sourcetree:

  1. Right click a commit that's older than the one you want to delete, and choose "Rebase children of xxxx interactively...". The one you click will be your "base" and you can make changes to every commit made after that one.

Screenshot-1

  1. In the new window, select the commit you want gone, and press the "Delete"-button at the bottom, or right click the commit and click "Delete commit".
  2. List item
  3. Click "OK" (or "Cancel" if you want to abort).

Check out this Atlassian blog post for more on interactive rebasing in Sourcetree.

Is it possible to simulate key press events programmatically?

Here's a library that really helps: https://cdn.rawgit.com/ccampbell/mousetrap/2e5c2a8adbe80a89050aaf4e02c45f02f1cc12d4/tests/libs/key-event.js

I don't know from where did it came from, but it is helpful. It adds a .simulate() method to window.KeyEvent, so you use it simply with KeyEvent.simulate(0, 13) for simulating an enter or KeyEvent.simulate(81, 81) for a 'Q'.

I got it at https://github.com/ccampbell/mousetrap/tree/master/tests.

How to disable CSS in Browser for testing purposes

Actually, it's easier than you think. In any browsers press F12 to bring up the debug console. This works for IE, Firefox, and Chrome. Not sure about Opera. Then comment out the CSS in the element windows. That's it.

How to fetch JSON file in Angular 2

You need to make an HTTP call to your games.json to retrieve it. Something like:

this.http.get(./app/resources/games.json).map

Comparing strings by their alphabetical order

Take a look at the String.compareTo method.

s1.compareTo(s2)

From the javadocs:

The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true.

How to get the position of a character in Python?

What happens when the string contains a duplicate character? from my experience with index() I saw that for duplicate you get back the same index.

For example:

s = 'abccde'
for c in s:
    print('%s, %d' % (c, s.index(c)))

would return:

a, 0
b, 1
c, 2
c, 2
d, 4

In that case you can do something like that:

for i, character in enumerate(my_string):
   # i is the position of the character in the string

Make columns of equal width in <table>

Use following property same as table and its fully dynamic:

_x000D_
_x000D_
ul {_x000D_
    width: 100%;_x000D_
    display: table;_x000D_
    table-layout: fixed; /* optional, for equal spacing */_x000D_
    border-collapse: collapse;_x000D_
}_x000D_
li {_x000D_
    display: table-cell;_x000D_
    text-align: center;_x000D_
    border: 1px solid pink;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<ul>_x000D_
  <li>foo<br>foo</li>_x000D_
  <li>barbarbarbarbar</li>_x000D_
  <li>baz klxjgkldjklg </li>_x000D_
  <li>baz</li>_x000D_
  <li>baz lds.jklklds</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

May be its solve your issue.

Regular expression for first and last name

^\p{L}{2,}$

^ asserts position at start of a line.

\p{L} matches any kind of letter from any language

{2,} Quantifier — Matches between 2 and unlimited times, as many times as possible, giving back as needed (greedy)

$ asserts position at the end of a line

So it should be a name in any language containing at least 2 letters(or symbols) without numbers or other characters.

ThreadStart with parameters

You can use the BackgroundWorker RunWorkerAsync method and pass in your value.

How can I measure the similarity between two images?

A ruby solution can be found here

From the readme:

Phashion is a Ruby wrapper around the pHash library, "perceptual hash", which detects duplicate and near duplicate multimedia files

Ruby on Rails: How do I add placeholder text to a f.text_field?

With rails >= 3.0, you can simply use the placeholder option.

f.text_field :attr, placeholder: "placeholder text"

Sorting a list using Lambda/Linq to objects

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Linq.Expressions;

public static class EnumerableHelper
{

    static MethodInfo orderBy = typeof(Enumerable).GetMethods(BindingFlags.Static | BindingFlags.Public).Where(x => x.Name == "OrderBy" && x.GetParameters().Length == 2).First();

    public static IEnumerable<TSource> OrderBy<TSource>(this IEnumerable<TSource> source, string propertyName)
    {
        var pi = typeof(TSource).GetProperty(propertyName, BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance);
        var selectorParam = Expression.Parameter(typeof(TSource), "keySelector");
        var sourceParam = Expression.Parameter(typeof(IEnumerable<TSource>), "source");
        return 
            Expression.Lambda<Func<IEnumerable<TSource>, IOrderedEnumerable<TSource>>>
            (
                Expression.Call
                (
                    orderBy.MakeGenericMethod(typeof(TSource), pi.PropertyType), 
                    sourceParam, 
                    Expression.Lambda
                    (
                        typeof(Func<,>).MakeGenericType(typeof(TSource), pi.PropertyType), 
                        Expression.Property(selectorParam, pi), 
                        selectorParam
                    )
                ), 
                sourceParam
            )
            .Compile()(source);
    }

    public static IEnumerable<TSource> OrderBy<TSource>(this IEnumerable<TSource> source, string propertyName, bool ascending)
    {
        return ascending ? source.OrderBy(propertyName) : source.OrderBy(propertyName).Reverse();
    }

}

Another one, this time for any IQueryable:

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

public static class IQueryableHelper
{

    static MethodInfo orderBy = typeof(Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public).Where(x => x.Name == "OrderBy" && x.GetParameters().Length == 2).First();
    static MethodInfo orderByDescending = typeof(Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public).Where(x => x.Name == "OrderByDescending" && x.GetParameters().Length == 2).First();

    public static IQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, params string[] sortDescriptors)
    {
        return sortDescriptors.Length > 0 ? source.OrderBy(sortDescriptors, 0) : source;
    }

    static IQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, string[] sortDescriptors, int index)
    {
        if (index < sortDescriptors.Length - 1) source = source.OrderBy(sortDescriptors, index + 1);
        string[] splitted = sortDescriptors[index].Split(' ');
        var pi = typeof(TSource).GetProperty(splitted[0], BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.IgnoreCase);
        var selectorParam = Expression.Parameter(typeof(TSource), "keySelector");
        return source.Provider.CreateQuery<TSource>(Expression.Call((splitted.Length > 1 && string.Compare(splitted[1], "desc", StringComparison.Ordinal) == 0 ? orderByDescending : orderBy).MakeGenericMethod(typeof(TSource), pi.PropertyType), source.Expression, Expression.Lambda(typeof(Func<,>).MakeGenericType(typeof(TSource), pi.PropertyType), Expression.Property(selectorParam, pi), selectorParam)));
    }

}

You can pass multiple sort criteria, like this:

var q = dc.Felhasznalos.OrderBy(new string[] { "Email", "FelhasznaloID desc" });

Can you test google analytics on a localhost address?

Following on from Tuong Lu Kim's answer:

Assuming:

ga('create', 'UA-XXXXX-Y', 'auto');

...if analytics.js detects that you're running a server locally (e.g. localhost) it automatically sets the cookieDomain to 'none'....

Excerpt from:

Automatic cookie domain configuration sets the _ga cookie on the highest level domain it can. For example, if your website address is blog.example.co.uk, analytics.js will set the cookie domain to .example.co.uk. In addition, if analytics.js detects that you're running a server locally (e.g. localhost) it automatically sets the cookieDomain to 'none'.

The recommended JavaScript tracking snippet sets the string 'auto' for the cookieDomain field:


Source: https://developers.google.com/analytics/devguides/collection/analyticsjs/cookies-user-id#automatic_cookie_domain_configuration

Can anonymous class implement interface?

No; an anonymous type can't be made to do anything except have a few properties. You will need to create your own type. I didn't read the linked article in depth, but it looks like it uses Reflection.Emit to create new types on the fly; but if you limit discussion to things within C# itself you can't do what you want.

Wireshark vs Firebug vs Fiddler - pros and cons?

Wireshark, Firebug, Fiddler all do similar things - capture network traffic.

  • Wireshark captures any kind of network packet. It can capture packet details below TCP/IP (HTTP is at the top). It does have filters to reduce the noise it captures.

  • Firebug tracks each request the browser page makes and captures the associated headers and the time taken for each stage of the request (DNS, receiving, sending, ...).

  • Fiddler works as an HTTP/HTTPS proxy. It captures every HTTP request the computer makes and records everything associated with it. It does allow things like converting post variables to a table form and editing/replaying requests. It doesn't, by default, capture localhost traffic in IE, see the FAQ for the workaround.

Starting a shell in the Docker Alpine container

Nowadays, Alpine images will boot directly into /bin/sh by default, without having to specify a shell to execute:

$ sudo docker run -it --rm alpine  
/ # echo $0  
/bin/sh  

This is since the alpine image Dockerfiles now contain a CMD command, that specifies the shell to execute when the container starts: CMD ["/bin/sh"].

In older Alpine image versions (pre-2017), the CMD command was not used, since Docker used to create an additional layer for CMD which caused the image size to increase. This is something that the Alpine image developers wanted to avoid. In recent Docker versions (1.10+), CMD no longer occupies a layer, and so it was added to alpine images. Therefore, as long as CMD is not overridden, recent Alpine images will boot into /bin/sh.

For reference, see the following commit to the official Alpine Dockerfiles by Glider Labs:
https://github.com/gliderlabs/docker-alpine/commit/ddc19dd95ceb3584ced58be0b8d7e9169d04c7a3#diff-db3dfdee92c17cf53a96578d4900cb5b

Change color of PNG image via CSS?

The img tag has a background property just like any other. If you have a white PNG with a transparent shape, like a stencil, then you can do this:

<img src= 'stencil.png' style= 'background-color: red'>

If condition inside of map() React

This one I found simple solutions:

row = myArray.map((cell, i) => {

    if (i == myArray.length - 1) {
      return <div> Test Data 1</div>;
    }
    return <div> Test Data 2</div>;
  });

Angular 2: How to call a function after get a response from subscribe http.post

You can do this be using a new Subject too:

Typescript:

let subject = new Subject();

get_categories(...) {
   this.http.post(...).subscribe( 
      (response) => {
         this.total = response.json();
         subject.next();
      }
   ); 

   return subject; // can be subscribed as well 
}

get_categories(...).subscribe(
   (response) => {
     // ...
   }
);

How would I access variables from one class to another?

Can you explain why you want to do this?

You're playing around with instance variables/attributes which won't migrate from one class to another (they're bound not even to ClassA, but to a particular instance of ClassA that you created when you wrote ClassA()). If you want to have changes in one class show up in another, you can use class variables:

class ClassA(object):
   var1 = 1
   var2 = 2
   @classmethod
   def method(cls):
       cls.var1 = cls.var1 + cls.var2
       return cls.var1

In this scenario, ClassB will pick up the values on ClassA from inheritance. You can then access the class variables via ClassA.var1, ClassB.var1 or even from an instance ClassA().var1 (provided that you haven't added an instance method var1 which will be resolved before the class variable in attribute lookup.

I'd have to know a little bit more about your particular use case before I know if this is a course of action that I would actually recommend though...

JavaScript window resize event

Thanks for referencing my blog post at http://mbccs.blogspot.com/2007/11/fixing-window-resize-event-in-ie.html.

While you can just hook up to the standard window resize event, you'll find that in IE, the event is fired once for every X and once for every Y axis movement, resulting in a ton of events being fired which might have a performance impact on your site if rendering is an intensive task.

My method involves a short timeout that gets cancelled on subsequent events so that the event doesn't get bubbled up to your code until the user has finished resizing the window.

surface plots in matplotlib

This is not a general solution but might help many of those who just typed "matplotlib surface plot" in Google and landed here.

Suppose you have data = [(x1,y1,z1),(x2,y2,z2),.....,(xn,yn,zn)], then you can get three 1-d lists using x, y, z = zip(*data). Now you can of course create 3d scatterplot using three 1-d lists.

But, why can't in general this data be used to create surface plot? To understand that consider an empty 3-d plot :

Now, suppose for each possible value of (x, y) on a "discrete" regular grid, you have a z value, then there's no issue & you can in fact get a surface plot:

import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm

x = np.linspace(0, 10, 6)  # [0, 2,..,10] : 6 distinct values
y = np.linspace(0, 20, 5)  # [0, 5,..,20] : 5 distinct values
z = np.linspace(0, 100, 30)  # 6 * 5 = 30 values, 1 for each possible combination of (x,y)

X, Y = np.meshgrid(x, y)
Z = np.reshape(z, X.shape)  # Z.shape must be equal to X.shape = Y.shape

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

ax.plot_surface(X, Y, Z)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()

What's happens when you haven't got z for all possible combinations of (x, y)? Then at the point (at intersection of two black lines on x-y plane on blank plot above), we don't know what is the value of z. It could be anything, we don't know how 'high' or 'low' our surface should be at that point (although it can be approximated using other functions, surface_plot requires that you supply it arguments where X.shape = Y.shape = Z.shape).

How to preserve request url with nginx proxy_pass

I think the proxy_set_header directive could help:

location / {
    proxy_pass http://my_app_upstream;
    proxy_set_header Host $host;
    # ...
}

Display last git commit comment

I just found out a workaround with shell by retrieving the previous command.

Press Ctrl-R to bring up reverse search command:

reverse-i-search

Then start typing git commit -m, this will add this as search command, and this brings the previous git commit with its message:

reverse-i-search`git commit -m`: git commit -m "message"

Enter. That's it!

(tested in Ubuntu shell)

Parse JSON from JQuery.ajax success data

It works fine, Ex :

$.ajax({
    url: "http://localhost:11141/Search/BasicSearchContent?ContentTitle=" + "?????",
    type: 'GET',
    cache: false,
    success: function(result) {
        //  alert(jQuery.dataType);
        if (result) {
            //  var dd = JSON.parse(result);
            alert(result[0].Id)
        }

    },
    error: function() {
        alert("No");
    }
});

Finally, you need to use this statement ...

result[0].Whatever

Git: See my last commit

After you do several commits or clone/pull a repository, you might want to see what commits have been made. Just check these simple solutions to see your commit history (from last/recent commit to the first one).

For the last commit, just fire this command: git log -1. For more interesting things see below -

  1. To see the commit ID (SHA-1 checksum), Author name <mail ID>, Date along with time, and commit message -

    git log
    
  2. To see some more stats, such as the names of all the files changed during that commit and number of insertions/deletions. This comes in very handy while reviewing the code -

    git log --stat
    
  3. To see commit histories in some pretty formats :) (This is followed by some prebuild options)-

    • If you have too many commits to review, this command will show them in a neat single line:

      git log --pretty=oneline
      
    • To see short, medium, full, or even more details of your commit, use following, respectively -

      git log --pretty=short
      git log --pretty=medium
      git log --pretty=full
      git log --pretty=fuller
      
  4. You can even use your own output format using the format option -

    git log --pretty=format:"%an, %ae - %s"
    

    where %an - author name, %ae - author email, %s - subject of commit, etc.

This can help you with your commit histories. For more information, click here.

Python No JSON object could be decoded

It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.

How to assign colors to categorical variables in ggplot2 that have stable mapping?

Based on the very helpful answer by joran I was able to come up with this solution for a stable color scale for a boolean factor (TRUE, FALSE).

boolColors <- as.character(c("TRUE"="#5aae61", "FALSE"="#7b3294"))
boolScale <- scale_colour_manual(name="myboolean", values=boolColors)

ggplot(myDataFrame, aes(date, duration)) + 
  geom_point(aes(colour = myboolean)) +
  boolScale

Since ColorBrewer isn't very helpful with binary color scales, the two needed colors are defined manually.

Here myboolean is the name of the column in myDataFrame holding the TRUE/FALSE factor. date and duration are the column names to be mapped to the x and y axis of the plot in this example.

Add an incremental number in a field in INSERT INTO SELECT query in SQL Server

You can use the row_number() function for this.

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
            row_number() over (order by (select NULL))
    FROM PM_Ingrediants 
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

If you want to start with the maximum already in the table then do:

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
           coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
    FROM PM_Ingrediants cross join
         (select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

Finally, you can just make the sequence column an auto-incrementing identity column. This saves the need to increment it each time:

create table PM_Ingrediants_Arrangement_Temp ( . . .
    sequence int identity(1, 1) -- and might consider making this a primary key too
    . . .
)

phpmailer error "Could not instantiate mail function"

$mail->AddAddress($address, "her name");

should be changed to

$mail->AddAddress($address);

This worked for my case..

How to get hostname from IP (Linux)?

In order to use nslookup, host or gethostbyname() then the target's name will need to be registered with DNS or statically defined in the hosts file on the machine running your program. Yes, you could connect to the target with SSH or some other application and query it directly, but for a generic solution you'll need some sort of DNS entry for it.

System.out.println() shortcut on Intellij IDEA

Open up Settings (By default is Alt + Ctrl + S) and search for Live Templates. In the upper part there's an option that says "By default expand with TAB" (TAB is the default), choose "Custom" and then hit "change" and add the keymap "ctrl+spacebar" to the option "Expand Live Template/Emmet Abbreviation".

Now you can hit ctrl + spacebar and expand the live templates. Now, to change it to "syso" instead of "sout", in the Live Templates option, theres a list of tons of options checked, go to "other" and expand it, there you wil find "sout", just rename it to "syso" and hit aply.

Hope this can help you.

connecting to mysql server on another PC in LAN

Since you have mysql on your local computer, you do not need to bother with the IP address of the machine. Just use localhost:

mysql -u user -p

or

mysql -hlocalhost -u user -p

If you cannot login with this, you must find out what usernames (user@host) exist in the MySQL Server locallly. Here is what you do:

Step 01) Startup mysql so that no passwords are require no passwords and denies TCP/IP connections

service mysql restart --skip-grant-tables --skip-networking

Keep in mind that standard SQL for adding users, granting and revoking privs are disabled.

Step 02) Show users and hosts

select concat(''',user,'''@''',host,'''') userhost,password from mysql.user;

Step 03) Check your password to make sure it works

select user,host from mysql.user where password=password('YourMySQLPassword');

If your password produces no output for this query, you have a bad password.

If your password produces output for this query, look at the users and hosts. If your host value is '%', your should be able to connect from anywhere. If your host is 'localhost', you should be able to connect locally.

Make user you have 'root'@'localhost' defined.

Once you have done what is needed, just restart mysql normally

service mysql restart

If you are able to connect successfully on the macbook, run this query:

SELECT USER(),CURRENT_USER();

USER() reports how you attempted to authenticate in MySQL

CURRENT_USER() reports how you were allowed to authenticate in MySQL

Let us know what happens !!!

UPDATE 2012-02-13 20:47 EDT

Login to the remote server and repeat Step 1-3

See if any user allows remote access (i.e, host in mysql.user is '%'). If you do not, then add 'user'@'%' to mysql.user.

What is the right way to populate a DropDownList from a database?

I hope I am not overstating the obvious, but why not do it directly in the ASP side? Unless you are dynamically altering the SQL based on certain conditions in your program, you should avoid codebehind as much as possible.

You could do the above all in ASP directly without code using the SqlDataSource control and a property in your dropdownlist.

<asp:GridView ID="gvSubjects" runat="server" DataKeyNames="SubjectID" OnRowDataBound="GridView_RowDataBound" OnDataBound="GridView_DataBound">
    <Columns>
        <asp:TemplateField HeaderText="Subjects">
            <ItemTemplate>
                <asp:DropDownList ID="ddlSubjects" runat="server" DataSourceID="sdsSubjects" DataTextField="SubjectName" DataValueField="SubjectID">
                </asp:DropDownList>
                <asp:SqlDataSource ID="sdsSubjects" runat="server"
                    SelectCommand="SELECT SubjectID,SubjectName FROM Students.dbo.Subjects"></asp:SqlDataSource>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

What is the equivalent to getch() & getche() in Linux?

You can use the curses.h library in linux as mentioned in the other answer.

You can install it in Ubuntu by:

sudo apt-get update

sudo apt-get install ncurses-dev

I took the installation part from here.

Scrollable Menu with Bootstrap - Menu expanding its container when it should not

Do everything in the inline of UL tag

<ul class="dropdown-menu scrollable-menu" role="menu" style="height: auto;max-height: 200px; overflow-x: hidden;">
                <li><a href="#">Action</a></li>
                <li><a href="#">Another action</a></li>
                <li><a href="#">Something else here</a></li>
                <li><a href="#">Action</a></li>
                ..
                <li><a href="#">Action</a></li>
                <li><a href="#">Another action</a></li>
            </ul>

How to truncate float values?

If you fancy some mathemagic, this works for +ve numbers:

>>> v = 1.923328437452
>>> v - v % 1e-3
1.923

No 'Access-Control-Allow-Origin' header in Angular 2 app

Simply you can set in php file as

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

jQuery find element by data attribute value

I searched for a the same solution with a variable instead of the String.
I hope i can help someone with my solution :)

var numb = "3";
$(`#myid[data-tab-id=${numb}]`);

Simple VBA selection: Selecting 5 cells to the right of the active cell

This example selects a new Range of Cells defined by the current cell to a cell 5 to the right.

Note that .Offset takes arguments of Offset(row, columns) and can be quite useful.


Sub testForStackOverflow()
    Range(ActiveCell, ActiveCell.Offset(0, 5)).Copy
End Sub

android image button

You just use an ImageButton and make the background whatever you want and set the icon as the src.

<ImageButton
    android:id="@+id/ImageButton01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/album_icon"
    android:background="@drawable/round_button" />

enter image description here

Error: Cannot find module 'webpack'

I solved the same problem by reinstalling, execute these commands

rm -Rf node_modules
rm -f package-lock.json
npm install

rmis always a dangerous command, especially with -f, please notice that before executing it!!!!!

How can I URL encode a string in Excel VBA?

For the sake of bringing this up to date, since Excel 2013 there is now a built-in way of encoding URLs using the worksheet function ENCODEURL.

To use it in your VBA code you just need to call

EncodedUrl = WorksheetFunction.EncodeUrl(InputString)

Documentation

In Powershell what is the idiomatic way of converting a string to an int?

For me $numberAsString -as [int] of @Shay Levy is the best practice, I also use [type]::Parse(...) or [type]::TryParse(...)

But, depending on what you need you can just put a string containing a number on the right of an arithmetic operator with a int on the left the result will be an Int32:

PS > $b = "10"
PS > $a = 0 + $b
PS > $a.gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Int32                                    System.ValueType

You can use Exception (try/parse) to behave in case of Problem

With Spring can I make an optional path variable?

Simplified example of Nicolai Ehmann's comment and wildloop's answer (works with Spring 4.3.3+), basically you can use required = false now:

  @RequestMapping(value = {"/json/{type}", "/json" }, method = RequestMethod.GET)
  public @ResponseBody TestBean testAjax(@PathVariable(required = false) String type) {
    if (type != null) {
      // ...
    }
    return new TestBean();
  }

How to enable explicit_defaults_for_timestamp?

On my system (Windows 8.1), the problem was with the server configuration. The server worked for the first time when I installed it. However, I forgot to check the "run as a service" option and this caused all the problem. I tried all possible solutions available on SO but nothing worked. So, I decided to reinstall MySQL Workbench. On executing the same msi file that I earlier used to install MySQL workbench, I reconfigured the server and allowed to run the server as a service.

C++11 reverse range-based for-loop

If not using C++14, then I find below the simplest solution.

#define METHOD(NAME, ...) auto NAME __VA_ARGS__ -> decltype(m_T.r##NAME) { return m_T.r##NAME; }
template<typename T>
struct Reverse
{
  T& m_T;

  METHOD(begin());
  METHOD(end());
  METHOD(begin(), const);
  METHOD(end(), const);
};
#undef METHOD

template<typename T>
Reverse<T> MakeReverse (T& t) { return Reverse<T>{t}; }

Demo.
It doesn't work for the containers/data-types (like array), which doesn't have begin/rbegin, end/rend functions.

How to get the current time in milliseconds from C in Linux?

C11 timespec_get

It returns up to nanoseconds, rounded to the resolution of the implementation.

It is already implemented in Ubuntu 15.10. API looks the same as the POSIX clock_gettime.

#include <time.h>
struct timespec ts;
timespec_get(&ts, TIME_UTC);
struct timespec {
    time_t   tv_sec;        /* seconds */
    long     tv_nsec;       /* nanoseconds */
};

More details here: https://stackoverflow.com/a/36095407/895245

How to delete a character from a string using Python

Here's what I did to slice out the "M":

s = 'EXAMPLE'
s1 = s[:s.index('M')] + s[s.index('M')+1:]

What does the line "#!/bin/sh" mean in a UNIX shell script?

The first line tells the shell that if you execute the script directly (./run.sh; as opposed to /bin/sh run.sh), it should use that program (/bin/sh in this case) to interpret it.

You can also use it to pass arguments, commonly -e (exit on error), or use other programs (/bin/awk, /usr/bin/perl, etc).

Setting the correct encoding when piping stdout in Python

First, regarding this solution:

# -*- coding: utf-8 -*-
print u"åäö".encode('utf-8')

It's not practical to explicitly print with a given encoding every time. That would be repetitive and error-prone.

A better solution is to change sys.stdout at the start of your program, to encode with a selected encoding. Here is one solution I found on Python: How is sys.stdout.encoding chosen?, in particular a comment by "toka":

import sys
import codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)

What is for Python what 'explode' is for PHP?

Choose one you need:

>>> s = "Rajasekar SP  def"
>>> s.split(' ')
['Rajasekar', 'SP', '', 'def']
>>> s.split()
['Rajasekar', 'SP', 'def']
>>> s.partition(' ')
('Rajasekar', ' ', 'SP  def')

str.split and str.partition

Android EditText Hint

et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {

            et.setHint(temp +" Characters");
        }
    });

Plotting a fast Fourier transform in Python

I've built a function that deals with plotting FFT of real signals. The extra bonus in my function relative to the previous answers is that you get the actual amplitude of the signal.

Also, because of the assumption of a real signal, the FFT is symmetric, so we can plot only the positive side of the x-axis:

import matplotlib.pyplot as plt
import numpy as np
import warnings


def fftPlot(sig, dt=None, plot=True):
    # Here it's assumes analytic signal (real signal...) - so only half of the axis is required

    if dt is None:
        dt = 1
        t = np.arange(0, sig.shape[-1])
        xLabel = 'samples'
    else:
        t = np.arange(0, sig.shape[-1]) * dt
        xLabel = 'freq [Hz]'

    if sig.shape[0] % 2 != 0:
        warnings.warn("signal preferred to be even in size, autoFixing it...")
        t = t[0:-1]
        sig = sig[0:-1]

    sigFFT = np.fft.fft(sig) / t.shape[0]  # Divided by size t for coherent magnitude

    freq = np.fft.fftfreq(t.shape[0], d=dt)

    # Plot analytic signal - right half of frequence axis needed only...
    firstNegInd = np.argmax(freq < 0)
    freqAxisPos = freq[0:firstNegInd]
    sigFFTPos = 2 * sigFFT[0:firstNegInd]  # *2 because of magnitude of analytic signal

    if plot:
        plt.figure()
        plt.plot(freqAxisPos, np.abs(sigFFTPos))
        plt.xlabel(xLabel)
        plt.ylabel('mag')
        plt.title('Analytic FFT plot')
        plt.show()

    return sigFFTPos, freqAxisPos


if __name__ == "__main__":
    dt = 1 / 1000

    # Build a signal within Nyquist - the result will be the positive FFT with actual magnitude
    f0 = 200  # [Hz]
    t = np.arange(0, 1 + dt, dt)
    sig = 1 * np.sin(2 * np.pi * f0 * t) + \
        10 * np.sin(2 * np.pi * f0 / 2 * t) + \
        3 * np.sin(2 * np.pi * f0 / 4 * t) +\
        7.5 * np.sin(2 * np.pi * f0 / 5 * t)

    # Result in frequencies
    fftPlot(sig, dt=dt)
    # Result in samples (if the frequencies axis is unknown)
    fftPlot(sig)

Analytic FFT plot result

Why am I getting "undefined reference to sqrt" error even though I include math.h header?

The math library must be linked in when building the executable. How to do this varies by environment, but in Linux/Unix, just add -lm to the command:

gcc test.c -o test -lm

The math library is named libm.so, and the -l command option assumes a lib prefix and .a or .so suffix.

VBA - If a cell in column A is not blank the column B equals

A simpler way to do this would be:

Sub populateB()

For Each Cel in Range("A1:A100")
    If Cel.value <> "" Then Cel.Offset(0, 1).value = "Your Text"
Next

End Sub

ASP.NET Custom Validator Client side & Server Side validation not firing

Your CustomValidator will only fire when the TextBox isn't empty.

If you need to ensure that it's not empty then you'll need a RequiredFieldValidator too.

Note: If the input control is empty, no validation functions are called and validation succeeds. Use a RequiredFieldValidator control to require the user to enter data in the input control.

EDIT:

If your CustomValidator specifies the ControlToValidate attribute (and your original example does) then your validation functions will only be called when the control isn't empty.

If you don't specify ControlToValidate then your validation functions will be called every time.

This opens up a second possible solution to the problem. Rather than using a separate RequiredFieldValidator, you could omit the ControlToValidate attribute from the CustomValidator and setup your validation functions to do something like this:

Client Side code (Javascript):

function TextBoxDCountyClient(sender, args) {
    var v = document.getElementById('<%=TextBoxDTownCity.ClientID%>').value;
    if (v == '') {
        args.IsValid = false;  // field is empty
    }
    else {
        // do your other validation tests here...
    }
}

Server side code (C#):

protected void TextBoxDTownCity_Validate(
    object source, ServerValidateEventArgs args)
{
    string v = TextBoxDTownCity.Text;
    if (v == string.Empty)
    {
        args.IsValid = false;  // field is empty
    }
    else
    {
        // do your other validation tests here...
    }
}

javascript password generator

Randomly assigns Alpha, Numeric, Caps and Special per character then validates the password. If it doesn't contain each of the above, randomly assigns a new character from the missing element to a random existing character then recursively validates until a password is formed:

function createPassword(length) {
    var alpha = "abcdefghijklmnopqrstuvwxyz";
    var caps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var numeric = "0123456789";
    var special = "!$^&*-=+_?";

    var options = [alpha, caps, numeric, special];

    var password = "";
    var passwordArray = Array(length);

    for (i = 0; i < length; i++) {
        var currentOption = options[Math.floor(Math.random() * options.length)];
        var randomChar = currentOption.charAt(Math.floor(Math.random() * currentOption.length));
        password += randomChar;
        passwordArray.push(randomChar);
    }

    checkPassword();

    function checkPassword() {
        var missingValueArray = [];
        var containsAll = true;

        options.forEach(function (e, i, a) {
            var hasValue = false;
            passwordArray.forEach(function (e1, i1, a1) {
                if (e.indexOf(e1) > -1) {
                    hasValue = true;
                }
            });

            if (!hasValue) {
                missingValueArray = a;
                containsAll = false;
            }
        });

        if (!containsAll) {
            passwordArray[Math.floor(Math.random() * passwordArray.length)] = missingValueArray.charAt(Math.floor(Math.random() * missingValueArray.length));
            password = "";
            passwordArray.forEach(function (e, i, a) {
                password += e;
            });
            checkPassword();
        }
    }

    return password;
}

npm install vs. update - what's the difference?

npm install installs all modules that are listed on package.json file and their dependencies.

npm update updates all packages in the node_modules directory and their dependencies.

npm install express installs only the express module and its dependencies.

npm update express updates express module (starting with [email protected], it doesn't update its dependencies).

So updates are for when you already have the module and wish to get the new version.

Post a json object to mvc controller with jquery and ajax

What am I doing incorrectly?

You have to convert html to javascript object, and then as a second step to json throug JSON.Stringify.

How can I receive a json object in the controller?

View:

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://raw.githubusercontent.com/marioizquierdo/jquery.serializeJSON/master/jquery.serializejson.js"></script>

var obj = $("#form1").serializeJSON({ useIntKeysAsArrayIndex: true });
$.post("http://localhost:52161/Default/PostRawJson/", { json: JSON.stringify(obj) });

<form id="form1" method="post">
<input name="OrderDate" type="text" /><br />
<input name="Item[0][Id]" type="text" /><br />
<input name="Item[1][Id]" type="text" /><br />
<button id="btn" onclick="btnClick()">Button</button>
</form>

Controller:

public void PostRawJson(string json)
{
    var order = System.Web.Helpers.Json.Decode(json);
    var orderDate = order.OrderDate;
    var secondOrderId = order.Item[1].Id;
}

Removing cordova plugins from the project

If the above solution didn't work and you got any unhandled promise rejection then try to follow steps :

  1. Clean the Cordova project

    cordova clean

    1. Remove platform

cordova platform remove android/ios

  1. Then remove plugin

cordova plugin remove

  1. add platforms and run the project It worked for me.

How to update fields in a model without creating a new record in django?

You should do it this way ideally

t = TemperatureData.objects.get(id=1)
t.value = 999
t.save(['value'])

This allow you to specify which column should be saved and rest are left as they currently are in database. (https://code.djangoproject.com/ticket/4102)!

Merge a Branch into Trunk

If your working directory points to the trunk, then you should be able to merge your branch with:

svn merge https://HOST/repository/branches/branch_1

be sure to be to issue this command in the root directory of your trunk

How to list files in a directory in a C program?

Here is a complete program how to recursively list folder's contents:

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

#define NORMAL_COLOR  "\x1B[0m"
#define GREEN  "\x1B[32m"
#define BLUE  "\x1B[34m"



/* let us make a recursive function to print the content of a given folder */

void show_dir_content(char * path)
{
  DIR * d = opendir(path); // open the path
  if(d==NULL) return; // if was not able return
  struct dirent * dir; // for the directory entries
  while ((dir = readdir(d)) != NULL) // if we were able to read somehting from the directory
    {
      if(dir-> d_type != DT_DIR) // if the type is not directory just print it with blue
        printf("%s%s\n",BLUE, dir->d_name);
      else
      if(dir -> d_type == DT_DIR && strcmp(dir->d_name,".")!=0 && strcmp(dir->d_name,"..")!=0 ) // if it is a directory
      {
        printf("%s%s\n",GREEN, dir->d_name); // print its name in green
        char d_path[255]; // here I am using sprintf which is safer than strcat
        sprintf(d_path, "%s/%s", path, dir->d_name);
        show_dir_content(d_path); // recall with the new path
      }
    }
    closedir(d); // finally close the directory
}

int main(int argc, char **argv)
{

  printf("%s\n", NORMAL_COLOR);

    show_dir_content(argv[1]);

  printf("%s\n", NORMAL_COLOR);
  return(0);
}

Insert a new row into DataTable

You can do this, I am using

DataTable 1.10.5

using this code:

var versionNo = $.fn.dataTable.version;
alert(versionNo);

This is how I insert new record on my DataTable using row.add (My table has 10 columns), which can also includes HTML tag elements:

function fncInsertNew() {
            var table = $('#tblRecord').DataTable();

            table.row.add([
                    "Tiger Nixon",
                    "System Architect",
                    "$3,120",
                    "2011/04/25",
                    "Edinburgh",
                    "5421",
                    "Tiger Nixon",
                    "System Architect",
                    "$3,120",
                    "<p>Hello</p>"
            ]).draw();
        }

For multiple inserts at the same time, use rows.add instead:

var table = $('#tblRecord').DataTable();

table.rows.add( [ {
        "Tiger Nixon",
        "System Architect",
        "$3,120",
        "2011/04/25",
        "Edinburgh",
        "5421"
    }, {
        "Garrett Winters",
        "Director",
        "$5,300",
        "2011/07/25",
        "Edinburgh",
        "8422"
    }]).draw();

Extract Number from String in Python

To extract a single number from a string you can use re.search(), which returns the first match (or None):

>>> import re
>>> string = '3158 reviews'
>>> int(re.search(r'\d+', string).group(0))
3158

In Python 3.6+ you can also index into a match object instead of using group():

>>> int(re.search(r'\d+', string)[0])
3158

Text editor to open big (giant, huge, large) text files

Tips and tricks

less

Why are you using editors to just look at a (large) file?

Under *nix or Cygwin, just use less. (There is a famous saying – "less is more, more or less" – because "less" replaced the earlier Unix command "more", with the addition that you could scroll back up.) Searching and navigating under less is very similar to Vim, but there is no swap file and little RAM used.

There is a Win32 port of GNU less. See the "less" section of the answer above.

Perl

Perl is good for quick scripts, and its .. (range flip-flop) operator makes for a nice selection mechanism to limit the crud you have to wade through.

For example:

$ perl -n -e 'print if ( 1000000 .. 2000000)' humongo.txt | less

This will extract everything from line 1 million to line 2 million, and allow you to sift the output manually in less.

Another example:

$ perl -n -e 'print if ( /regex one/ .. /regex two/)' humongo.txt | less

This starts printing when the "regular expression one" finds something, and stops when the "regular expression two" find the end of an interesting block. It may find multiple blocks. Sift the output...

logparser

This is another useful tool you can use. To quote the Wikipedia article:

logparser is a flexible command line utility that was initially written by Gabriele Giuseppini, a Microsoft employee, to automate tests for IIS logging. It was intended for use with the Windows operating system, and was included with the IIS 6.0 Resource Kit Tools. The default behavior of logparser works like a "data processing pipeline", by taking an SQL expression on the command line, and outputting the lines containing matches for the SQL expression.

Microsoft describes Logparser as a powerful, versatile tool that provides universal query access to text-based data such as log files, XML files and CSV files, as well as key data sources on the Windows operating system such as the Event Log, the Registry, the file system, and Active Directory. The results of the input query can be custom-formatted in text based output, or they can be persisted to more specialty targets like SQL, SYSLOG, or a chart.

Example usage:

C:\>logparser.exe -i:textline -o:tsv "select Index, Text from 'c:\path\to\file.log' where line > 1000 and line < 2000"
C:\>logparser.exe -i:textline -o:tsv "select Index, Text from 'c:\path\to\file.log' where line like '%pattern%'"

The relativity of sizes

100 MB isn't too big. 3 GB is getting kind of big. I used to work at a print & mail facility that created about 2% of U.S. first class mail. One of the systems for which I was the tech lead accounted for about 15+% of the pieces of mail. We had some big files to debug here and there.

And more...

Feel free to add more tools and information here. This answer is community wiki for a reason! We all need more advice on dealing with large amounts of data...

How can I change image source on click with jQuery?

It switches back because by default, when you click a link, it follows the link and loads the page. In your case, you don't want that. You can prevent it either by doing e.preventDefault(); (like Neal mentioned) or by returning false :

$(function() {
 $('.menulink').click(function(){
   $("#bg").attr('src',"img/picture1.jpg");
   return false;
 });
});

Interesting question on the differences between prevent default and return false.

In this case, return false will work just fine because the event doesn't need to be propagated.

Python: How to check a string for substrings from a list?

Try this test:

any(substring in string for substring in substring_list)

It will return True if any of the substrings in substring_list is contained in string.

Note that there is a Python analogue of Marc Gravell's answer in the linked question:

from itertools import imap
any(imap(string.__contains__, substring_list)) 

In Python 3, you can use map directly instead:

any(map(string.__contains__, substring_list))

Probably the above version using a generator expression is more clear though.

Java Try Catch Finally blocks without Catch

The Java Language Specification(1) describes how try-catch-finally is executed. Having no catch is equivalent to not having a catch able to catch the given Throwable.

  • If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:
    • If the run-time type of V is assignable to the parameter of any catch clause of the try statement, then …
    • If the run-time type of V is not assignable to the parameter of any catch clause of the try statement, then the finally block is executed. Then there is a choice:
      • If the finally block completes normally, then the try statement completes abruptly because of a throw of the value V.
      • If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and the throw of value V is discarded and forgotten).

(1) Execution of try-catch-finally

How to filter by IP address in Wireshark?

You can also limit the filter to only part of the ip address.

E.G. To filter 123.*.*.* you can use ip.addr == 123.0.0.0/8. Similar effects can be achieved with /16 and /24.

See WireShark man pages (filters) and look for Classless InterDomain Routing (CIDR) notation.

... the number after the slash represents the number of bits used to represent the network.

Using cut command to remove multiple columns

You should be able to continue the sequences directly in your existing -f specification.

To skip both 5 and 7, try:

cut -d, -f-4,6-6,8-

As you're skipping a single sequential column, this can also be written as:

cut -d, -f-4,6,8-

To keep it going, if you wanted to skip 5, 7, and 11, you would use:

cut -d, -f-4,6-6,8-10,12-

To put it into a more-clear perspective, it is easier to visualize when you use starting/ending columns which go on the beginning/end of the sequence list, respectively. For instance, the following will print columns 2 through 20, skipping columns 5 and 11:

cut -d, -f2-4,6-10,12-20

So, this will print "2 through 4", skip 5, "6 through 10", skip 11, and then "12 through 20".

What ports need to be open for TortoiseSVN to authenticate (clear text) and commit?

What's the first part of your Subversion repository URL?

  • If your URL looks like: http://subversion/repos/, then you're probably going over Port 80.
  • If your URL looks like: https://subversion/repos/, then you're probably going over Port 443.
  • If your URL looks like: svn://subversion/, then you're probably going over Port 3690.
  • If your URL looks like: svn+ssh://subversion/repos/, then you're probably going over Port 22.
  • If your URL contains a port number like: http://subversion/repos:8080, then you're using that port.

I can't guarantee the first four since it's possible to reconfigure everything to use different ports, of if you go through a proxy of some sort.

If you're using a VPN, you may have to configure your VPN client to reroute these to their correct ports. A lot of places don't configure their correctly VPNs to do this type of proxying. It's either because they have some sort of anal-retentive IT person who's being overly security conscious, or because they simply don't know any better. Even worse, they'll give you a client where this stuff can't be reconfigured.

The only way around that is to log into a local machine over the VPN, and then do everything from that system.

inject bean reference into a Quartz job in Spring?

Here is what the code looks like with @Component:

Main class that schedules the job:

public class NotificationScheduler {

private SchedulerFactory sf;
private Scheduler scheduler;

@PostConstruct
public void initNotificationScheduler() {
    try {
    sf = new StdSchedulerFactory("spring/quartz.properties");
    scheduler = sf.getScheduler();
    scheduler.start();
            // test out sending a notification at startup, prepare some parameters...
    this.scheduleImmediateNotificationJob(messageParameters, recipients);
        try {
            // wait 20 seconds to show jobs
            logger.info("sleeping...");
            Thread.sleep(40L * 1000L); 
            logger.info("finished sleeping");
           // executing...
        } catch (Exception ignore) {
        }

      } catch (SchedulerException e) {
    e.printStackTrace();
    throw new RuntimeException("NotificationScheduler failed to retrieve a Scheduler instance: ", e);
    }
}


public void scheduleImmediateNotificationJob(){
  try {
    JobKey jobKey = new JobKey("key");
    Date fireTime = DateBuilder.futureDate(delayInSeconds, IntervalUnit.SECOND);
    JobDetail emailJob = JobBuilder.newJob(EMailJob.class)
    .withIdentity(jobKey.toString(), "immediateEmailsGroup")
        .build();

    TriggerKey triggerKey = new TriggerKey("triggerKey");
    SimpleTrigger trigger = (SimpleTrigger) TriggerBuilder.newTrigger() 
        .withIdentity(triggerKey.toString(), "immediateEmailsGroup")
        .startAt(fireTime)
        .build();

    // schedule the job to run
    Date scheduleTime1 = scheduler.scheduleJob(emailJob, trigger);
  } catch (SchedulerException e) {
    logger.error("error scheduling job: " + e.getMessage(), e);
    e.printStackTrace();
      }
}

@PreDestroy
public void cleanup(){
    sf = null;
    try {
        scheduler.shutdown();
    } catch (SchedulerException e) {
        e.printStackTrace();
    }
}

The EmailJob is the same as in my first posting except for the @Component annotation:

@Component
public class EMailJob implements Job { 
  @Autowired
  private JavaMailSenderImpl mailSenderImpl;
... }

And the Spring's configuration file has:

...
<context:property-placeholder location="classpath:spring/*.properties" />
<context:spring-configured/>
<context:component-scan base-package="com.mybasepackage">
  <context:exclude-filter expression="org.springframework.stereotype.Controller"
        type="annotation" />
</context:component-scan>
<bean id="mailSenderImpl" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="${mail.host}"/>
    <property name="port" value="${mail.port}"/>
    ...
</bean>
<bean id="notificationScheduler" class="com.mybasepackage.notifications.NotificationScheduler">
</bean>

Thanks for all the help!

Marina

Does the Java &= operator apply & or &&?

Here's a simple way to test it:

public class OperatorTest {     
    public static void main(String[] args) {
        boolean a = false;
        a &= b();
    }

    private static boolean b() {
        System.out.println("b() was called");
        return true;
    }
}

The output is b() was called, therefore the right-hand operand is evaluated.

So, as already mentioned by others, a &= b is the same as a = a & b.

How do I manually configure a DataSource in Java?

I think the example is wrong - javax.sql.DataSource doesn't have these properties either. Your DataSource needs to be of the type org.apache.derby.jdbc.ClientDataSource, which should have those properties.

How can you test if an object has a specific property?

I've been using the following which returns the property value, as it would be accessed via $thing.$prop, if the "property" would be to exist and not throw a random exception. If the property "doesn't exist" (or has a null value) then $null is returned: this approach functions in/is useful for strict mode, because, well, Gonna Catch 'em All.

I find this approach useful because it allows PS Custom Objects, normal .NET objects, PS HashTables, and .NET collections like Dictionary to be treated as "duck-typed equivalent", which I find is a fairly good fit for PowerShell.

Of course, this does not meet the strict definition of "has a property".. which this question may be explicitly limited to. If accepting the larger definition of "property" assumed here, the method can be trivially modified to return a boolean.

Function Get-PropOrNull {
    param($thing, [string]$prop)
    Try {
        $thing.$prop
    } Catch {
    }
}

Examples:

Get-PropOrNull (Get-Date) "Date"                   # => Monday, February 05, 2018 12:00:00 AM
Get-PropOrNull (Get-Date) "flub"                   # => $null
Get-PropOrNull (@{x="HashTable"}) "x"              # => "HashTable"
Get-PropOrNull ([PSCustomObject]@{x="Custom"}) "x" # => "Custom"
$oldDict = New-Object "System.Collections.HashTable"
$oldDict["x"] = "OldDict"
Get-PropOrNull $d "x"                              # => "OldDict"

And, this behavior might not [always] be desired.. ie. it's not possible to distinguish between x.Count and x["Count"].

How to print a double with two decimals in Android?

Before you use DecimalFormat you need to use the following import or your code will not work:

import java.text.DecimalFormat;

The code for formatting is:

DecimalFormat precision = new DecimalFormat("0.00"); 
// dblVariable is a number variable and not a String in this case
txtTextField.setText(precision.format(dblVariable));

Return single column from a multi-dimensional array

very simple go for this

$str;
foreach ($arrays as $arr) {
$str .= $arr["tag_name"] . ",";
}
$str = trim($str, ',');//removes the final comma 

How do I convert a byte array to Base64 in Java?

Additionally, for our Android friends (API Level 8):

import android.util.Base64

...

Base64.encodeToString(bytes, Base64.DEFAULT);

Tkinter: "Python may not be configured for Tk"

This symptom can also occur when a later version of python (2.7.13, for example) has been installed in /usr/local/bin "alongside of" the release python version, and then a subsequent operating system upgrade (say, Ubuntu 12.04 --> Ubuntu 14.04) fails to remove the updated python there.

To fix that imcompatibility, one must

a) remove the updated version of python in /usr/local/bin;

b) uninstall python-idle2.7; and

c) reinstall python-idle2.7.

Convert string to int if string is a number

Try this: currentLoad = ConvertToLongInteger(oXLSheet2.Cells(4, 6).Value) with this function:

Function ConvertToLongInteger(ByVal stValue As String) As Long
 On Error GoTo ConversionFailureHandler
 ConvertToLongInteger = CLng(stValue)  'TRY to convert to an Integer value
 Exit Function           'If we reach this point, then we succeeded so exit

ConversionFailureHandler:
 'IF we've reached this point, then we did not succeed in conversion
 'If the error is type-mismatch, clear the error and return numeric 0 from the function
 'Otherwise, disable the error handler, and re-run the code to allow the system to 
 'display the error
 If Err.Number = 13 Then 'error # 13 is Type mismatch
      Err.Clear
      ConvertToLongInteger = 0
      Exit Function
 Else
      On Error GoTo 0
      Resume
 End If
End Function

I chose Long (Integer) instead of simply Integer because the min/max size of an Integer in VBA is crummy (min: -32768, max:+32767). It's common to have an integer outside of that range in spreadsheet operations.

The above code can be modified to handle conversion from string to-Integers, to-Currency (using CCur() ), to-Decimal (using CDec() ), to-Double (using CDbl() ), etc. Just replace the conversion function itself (CLng). Change the function return type, and rename all occurrences of the function variable to make everything consistent.

How to change the data type of a column without dropping the column with query?

ALTER tablename MODIFY columnName newColumnType

I'm not sure how it will handle the change from datetime to varchar though, so you may need to rename the column, add a new one with the old name and the correct data type (varchar) and then write an update query to populate the new column from the old.

http://www.1keydata.com/sql/sql-alter-table.html

How to hide code from cells in ipython notebook visualized with nbviewer?

The accepted solution also works in julia Jupyter/IJulia with the following modifications:

display("text/html", """<script>
code_show=true; 
function code_toggle() {
 if (code_show){
 \$("div.input").hide();
 } else {
 \$("div.input").show();
 }
 code_show = !code_show
} 
\$( document ).ready(code_toggle);
</script>
<form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code."></form>""")

note in particular:

  • use the display function
  • escape the $ sign (otherwise seen as a variable)

How to get the full path of running process?

private void Test_Click(object sender, System.EventArgs e){
   string path;
   path = System.IO.Path.GetDirectoryName( 
      System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase );
    Console.WriiteLine( path );  
}

What causes the Broken Pipe Error?

The current state of a socket is determined by 'keep-alive' activity. In your case, this is possible that when you are issuing the send call, the keep-alive activity tells that the socket is active and so the send call will write the required data (40 bytes) in to the buffer and returns without giving any error.

When you are sending a bigger chunk, the send call goes in to blocking state.

The send man page also confirms this:

When the message does not fit into the send buffer of the socket, send() normally blocks, unless the socket has been placed in non-blocking I/O mode. In non-blocking mode it would return EAGAIN in this case

So, while blocking for the free available buffer, if the caller is notified (by keep-alive mechanism) that the other end is no more present, the send call will fail.

Predicting the exact scenario is difficult with the mentioned info, but I believe, this should be the reason for you problem.

Convert Current date to integer

Do you need something like this(without time)?

public static Integer toJulianDate(Date pDate) {
if (pDate == null) {
  return null;
}
Calendar lCal = Calendar.getInstance();
lCal.setTime(pDate);
int lYear = lCal.get(Calendar.YEAR);
int lMonth = lCal.get(Calendar.MONTH) + 1;
int lDay = lCal.get(Calendar.DATE);
int a = (14 - lMonth) / 12;
int y = lYear + 4800 - a;
int m = lMonth + 12 * a - 3;
return lDay + (153 * m + 2) / 5 + 365 * y + y / 4 - y / 100 + y / 400 - 32045;
}

How to load external webpage in WebView

just go into XML file and give id to your webView then in java paste these line:

   public class Main extends Activity {

private WebView mWebview;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.Your_layout_file_name);

    mWebview = (WebView)findViewById(R.id.id_you_gave _to_your_wenview_in_xml);
    mWebview.loadUrl("http://www.google.com");
    }   
}

XPath: select text node

your xpath should work . i have tested your xpath and mine in both MarkLogic and Zorba Xquery/ Xpath implementation.

Both should work.

/node/child::text()[1] - should return Text1
/node/child::text()[2] - should return text2


/node/text()[1] - should return Text1
/node/text()[2] - should return text2

Better way to right align text in HTML Table

A number of years ago (in the IE only days) I was using the <col align="right"> tag, but I just tested it and and it seems to be an IE only feature:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Test</title>
</head>
<body>
    <table width="100%" border="1">
        <col align="left" />
        <col align="left" />
        <col align="right" />
        <tr>
            <th>ISBN</th>
            <th>Title</th>
            <th>Price</th>
        </tr>
        <tr>
            <td>3476896</td>
            <td>My first HTML</td>
            <td>$53</td>
        </tr>
    </table>
</body>
</html>

The snippet is taken from www.w3schools.com. Of course, it should not be used (unless for some reason you really target the IE rendering engine only), but I thought it would be interesting to mention it.

Edit:

Overall, I don't understand the reasoning behing abandoning this tag. It would appear to be very useful (at least for manual HTML publishing).

Simulate low network connectivity for Android

I know it's an old question but...

Some phones nowadays have a setting to utilize 2G only. It's perfect for simulating slow internet on a real device.

enter image description here

"Insufficient Storage Available" even there is lot of free space in device memory

I had this problem even with plenty of internal memory and SD memory. This solution is only for apps that won't update, or have previously been installed on the phone and won't install.

It appears that in some cases there are directories left over from a previous install and the new app cannot remove or overwrite these.

The first thing to do is try uninstalling the app first and try again. In my case this worked for a couple of apps.

For the next step you need root access on your phone:

With a file manager go to /data/app-lib and find the directory (or directories) associated with the app. For example for kindle it is com.amazon.kindle. Delete these. Also go to /data/data and do the same.

Then goto play store and re-install the app. This worked for all apps in my case.

Do not want scientific notation on plot axis

The R graphics package has the function axTicks that returns the tick locations of the ticks that the axis and plot functions would set automatically. The other answers given to this question define the tick locations manually which might not be convenient in some situations.

myTicks = axTicks(1)
axis(1, at = myTicks, labels = formatC(myTicks, format = 'd'))

A minimal example would be

plot(10^(0:10), 0:10, log = 'x', xaxt = 'n')
myTicks = axTicks(1)
axis(1, at = myTicks, labels = formatC(myTicks, format = 'd'))

There is also an log parameter in the axTicks function but in this situation it does not need to be set to get the proper logarithmic axis tick location.

Custom format for time command

Not quite sure what you are asking, have you tried:

time yourscript | tail -n1 >log

Edit: ok, so you know how to get the times out and you just want to change the format. It would help if you described what format you want, but here are some things to try:

time -p script

This changes the output to one time per line in seconds with decimals. You only want the real time, not the other two so to get the number of seconds use:

time -p script | tail -n 3 | head -n 1

How do I install a plugin for vim?

To expand on Karl's reply, Vim looks in a specific set of directories for its runtime files. You can see that set of directories via :set runtimepath?. In order to tell Vim to also look inside ~/.vim/vim-haml you'll want to add

set runtimepath+=$HOME/.vim/vim-haml

to your ~/.vimrc. You'll likely also want the following in your ~/.vimrc to enable all the functionality provided by vim-haml.

filetype plugin indent on
syntax on

You can refer to the 'runtimepath' and :filetype help topics in Vim for more information.

ggplot2 plot without axes, legends, etc

Late to the party, but might be of interest...

I find a combination of labs and guides specification useful in many cases:

You want nothing but a grid and a background:

ggplot(diamonds, mapping = aes(x = clarity)) + 
  geom_bar(aes(fill = cut)) + 
  labs(x = NULL, y = NULL) + 
  guides(x = "none", y = "none")

enter image description here

You want to only suppress the tick-mark label of one or both axes:

ggplot(diamonds, mapping = aes(x = clarity)) + 
  geom_bar(aes(fill = cut)) + 
  guides(x = "none", y = "none")

enter image description here