Programs & Examples On #Startmenu

Make WPF Application Fullscreen (Cover startmenu)

You're probably missing the WindowState="Maximized", try the following:

<Window x:Class="HTA.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    WindowStyle="None" ResizeMode="NoResize"  
    WindowStartupLocation="CenterScreen" WindowState="Maximized">

Configure active profile in SpringBoot via Maven

The Maven profile and the Spring profile are two completely different things. Your pom.xml defines spring.profiles.active variable which is available in the build process, but not at runtime. That is why only the default profile is activated.

How to bind Maven profile with Spring?

You need to pass the build variable to your application so that it is available when it is started.

  1. Define a placeholder in your application.properties:

    [email protected]@
    

    The @spring.profiles.active@ variable must match the declared property from the Maven profile.

  2. Enable resource filtering in you pom.xml:

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        …
    </build>
    

    When the build is executed, all files in the src/main/resources directory will be processed by Maven and the placeholder in your application.properties will be replaced with the variable you defined in your Maven profile.

For more details you can go to my post where I described this use case.

how to make a div to wrap two float divs inside?

This should do it:

<div id="wrap">
  <div id="nav"></div>
  <div id="content"></div>
  <div style="clear:both"></div>
</div>

How to get all options in a drop-down list by Selenium WebDriver using C#?

You can use selenium.Support to use the SelectElement class, this class have a property "Options" that is what you are looking for, I created an extension method to convert your web element to a select element

public static SelectElement AsDropDown(this IWebElement webElement)
{
    return new SelectElement(webElement);
}

then you could use it like this

var elem = driver.FindElement(By.XPath("//select[@name='time_zone']"));
var options = elem.AsDropDown().Options

How to set default Checked in checkbox ReactJS?

 <div className="form-group">
          <div className="checkbox">
            <label><input type="checkbox" value="" onChange={this.handleInputChange.bind(this)}  />Flagged</label>
            <br />
            <label><input type="checkbox" value=""  />Un Flagged</label>
          </div>
        </div

handleInputChange(event){

console.log("event",event.target.checked)   }

the Above handle give you the value of true or false upon checked or unChecked

What's the difference between <b> and <strong>, <i> and <em>?

As the others have stated, the difference is that <b> and <i> hardcode font styles, whereas <strong> and <em> dictate semantic meaning, with the font style (or speaking browser intonation, or what-have-you) to be determined at the time the text is rendered (or spoken).

You can think of this as a difference between a “physical” font style and a “logical” style, if you will. At some later time, you may wish to change the way <strong> and <em> text are displayed, say, by altering properties in a style sheet to add color and size changes, or even to use different font faces entirely. If you've used “logical” markup instead of hardcoded “physical” markup, then you can simply change the display properties in one place each in your style sheet, and then all of the pages that reference that style sheet get changed automatically, without ever having to edit them.

Pretty slick, huh?

This is also the rationale behind defining sub-styles (referenced using the style= property in text tags) for paragraphs, table cells, header text, captions, etc., and using <div> tags. You can define physical representation for your logical styles in the style sheet, and the changes are automatically reflected in the web pages that reference that style sheet. Want a different representation for source code? Redefine the font, size, weight, spacing, etc. for your "code" style.

If you use XHTML, you can even define your own semantic tags, and your style sheet would do the conversions to physical font styles and layouts for you.

src absolute path problem

<img src="file://C:/wamp/www/site/img/mypicture.jpg"/>

Adding Counter in shell script

Here's how you might implement a counter:

counter=0
while true; do
  if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
       echo "Files Present" | mailx -s "File Present"  -r [email protected] [email protected]
       exit 0
  elif [[ "$counter" -gt 20 ]]; then
       echo "Counter: $counter times reached; Exiting loop!"
       exit 1
  else
       counter=$((counter+1))
       echo "Counter: $counter time(s); Sleeping for another half an hour" | mailx -s "Time to Sleep Now"  -r [email protected] [email protected]
       sleep 1800
  fi
done

Some Explanations:

  • counter=$((counter+1)) - this is how you can increment a counter. The $ for counter is optional inside the double parentheses in this case.
  • elif [[ "$counter" -gt 20 ]]; then - this checks whether $counter is not greater than 20. If so, it outputs the appropriate message and breaks out of your while loop.

How to parse json string in Android?

Below is the link which guide in parsing JSON string in android.

http://www.ibm.com/developerworks/xml/library/x-andbene1/?S_TACT=105AGY82&S_CMP=MAVE

Also according to your json string code snippet must be something like this:-

JSONObject mainObject = new JSONObject(yourstring);

JSONObject universityObject = mainObject.getJSONObject("university");
JSONString name = universityObject.getString("name");  
JSONString url = universityObject.getString("url");

Following is the API reference for JSOnObject: https://developer.android.com/reference/org/json/JSONObject.html#getString(java.lang.String)

Same for other object.

Programmatically change the src of an img tag

You can use both jquery and javascript method: if you have two images for example:

<img class="image1" src="image1.jpg" alt="image">
<img class="image2" src="image2.jpg" alt="image">

1)Jquery Method->

$(".image2").attr("src","image1.jpg");

2)Javascript Method->

var image = document.getElementsByClassName("image2");
image.src = "image1.jpg"

For this type of issue jquery is the simple one to use.

iPhone UILabel text soft shadow

While it's impossible to set a blur radius directly on UILabel, you definitely could change it by manipulating CALayer.

Just set:

//Required properties
customLabel.layer.shadowRadius = 5.0 //set shadow radius to your desired value.
customLabel.layer.shadowOpacity = 1.0 //Choose an opacity. Make sure it's visible (default is 0.0)

//Other options
customLabel.layer.shadowOffset = CGSize(width: 10, height: 10)
customLabel.layer.shadowColor = UIColor.black.cgColor
customLabel.layer.masksToBounds = false

What I hope will help someone and other answers failed to clarify is that it will not work if you also set UILabel Shadow Color property directly on Interface Builder while trying to setup .layer.shadowRadius.

So if setting label.layer.shadowRadius didn't work, please verify Shadow Color for this UILabel on Interface Builder. It should be set to default. And then, please, if you want a shadow color other than black, set this color also through .layer property.

enter image description here

How can I completely remove TFS Bindings

In visual studio 2015,

  1. Unbind the solution and project by File->Source Control->Advanced->Change Source Control
  2. Remove the cache in C:\Users\<user>\AppData\Local\Microsoft\Team Foundation\6.0

How can I get the height of an element using css only

You could use the CSS calc parameter to calculate the height dynamically like so:

_x000D_
_x000D_
.dynamic-height {_x000D_
   color: #000;_x000D_
   font-size: 12px;_x000D_
   margin-top: calc(100% - 10px);_x000D_
   text-align: left;_x000D_
}
_x000D_
<div class='dynamic-height'>_x000D_
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Changing .gitconfig location on Windows

I wanted to do the same thing. The best I could find was @MicTech's solution. However, as pointed out by @MotoWilliams this does not survive any updates made by Git to the .gitconfig file which replaces the link with a new file containing only the new settings.

I solved this by writing the following PowerShell script and running it in my profile startup script. Each time it is run it copies any settings that have been added to the user's .gitconfig to the global one and then replaces all the text in the .gitconfig file with and [include] header that imports the global file.

I keep the global .gitconfig file in a repo along with a lot of other global scripts and tools. All I have to do is remember to check in any changes that the script appends to my global file.

This seems to work pretty transparently for me. Hope it helps!

Sept 9th: Updated to detect when new entries added to the config file are duplicates and ignore them. This is useful for tools like SourceTree which will write new updates if they cannot find existing ones and do not follow includes.

function git-config-update
{
  $localPath = "$env:USERPROFILE\.gitconfig".replace('\', "\\")
  $globalPath = "C:\src\github\Global\Git\gitconfig".replace('\', "\\")

  $redirectAutoText = "# Generated file. Do not edit!`n[include]`n  path = $globalPath`n`n"
  $localText = get-content $localPath

  $diffs = (compare-object -ref $redirectAutoText.split("`n") -diff ($localText) | 
    measure-object).count

  if ($diffs -eq 0)
  {
    write-output ".gitconfig unchanged."
    return
  }

  $skipLines = 0
  $diffs = (compare-object -ref ($redirectAutoText.split("`n") | 
     select -f 3) -diff ($localText | select -f 3) | measure-object).count
  if ($diffs -eq 0)
  {
    $skipLines = 4
    write-warning "New settings appended to $localPath...`n "
  }
  else
  {
    write-warning "New settings found in $localPath...`n "
  }
  $localLines = (get-content $localPath | select -Skip $skipLines) -join "`n"
  $newSettings = $localLines.Split(@("["), [StringSplitOptions]::RemoveEmptyEntries) | 
    where { ![String]::IsNullOrWhiteSpace($_) } | %{ "[$_".TrimEnd() }

  $globalLines = (get-content  $globalPath) -join "`n"
  $globalSettings =  $globalLines.Split(@("["), [StringSplitOptions]::RemoveEmptyEntries)| 
    where { ![String]::IsNullOrWhiteSpace($_) } | %{ "[$_".TrimEnd() }

  $appendSettings = ($newSettings | %{ $_.Trim() } | 
    where { !($globalSettings -contains $_.Trim()) })
  if ([string]::IsNullOrWhitespace($appendSettings))
  {
    write-output "No new settings found."
  }
  else
  {
    echo $appendSettings
    add-content $globalPath ("`n# Additional settings added from $env:COMPUTERNAME on " + (Get-Date -displayhint date) + "`n" + $appendSettings)
  }
  set-content $localPath $redirectAutoText -force
}

denied: requested access to the resource is denied : docker

I got the same issue while taking the docker beginner Course. I solved the issue by doing adocker login before the docker push call.

How to make the first option of <select> selected with jQuery

$('select#id').val($('#id option')[index].value)

Replace the id with particular select tag id and index with particular element you want to select.

i.e.

<select class="input-field" multiple="multiple" id="ddlState" name="ddlState">
                                        <option value="AB">AB</option>
                                        <option value="AK">AK</option>
                                        <option value="AL">AL</option>
</select>

So here for first element selection I will use following code :

$('select#ddlState').val($('#ddlState option')[0].value)

Mocking a function to raise an Exception to test an except block

Your mock is raising the exception just fine, but the error.resp.status value is missing. Rather than use return_value, just tell Mock that status is an attribute:

barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')

Additional keyword arguments to Mock() are set as attributes on the resulting object.

I put your foo and bar definitions in a my_tests module, added in the HttpError class so I could use it too, and your test then can be ran to success:

>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
...     barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
...     result = my_test.foo()
... 
404 - 
>>> result is None
True

You can even see the print '404 - %s' % error.message line run, but I think you wanted to use error.content there instead; that's the attribute HttpError() sets from the second argument, at any rate.

Select unique values with 'select' function in 'dplyr' library

In dplyr 0.3 this can be easily achieved using the distinct() method.

Here is an example:

distinct_df = df %>% distinct(field1)

You can get a vector of the distinct values with:

distinct_vector = distinct_df$field1

You can also select a subset of columns at the same time as you perform the distinct() call, which can be cleaner to look at if you examine the data frame using head/tail/glimpse.:

distinct_df = df %>% distinct(field1) %>% select(field1) distinct_vector = distinct_df$field1

Replace non-ASCII characters with a single space

As a native and efficient approach, you don't need to use ord or any loop over the characters. Just encode with ascii and ignore the errors.

The following will just remove the non-ascii characters:

new_string = old_string.encode('ascii',errors='ignore')

Now if you want to replace the deleted characters just do the following:

final_string = new_string + b' ' * (len(old_string) - len(new_string))

Why is the time complexity of both DFS and BFS O( V + E )

Very simplified without much formality: every edge is considered exactly twice, and every node is processed exactly once, so the complexity has to be a constant multiple of the number of edges as well as the number of vertices.

Fastest method to replace all instances of a character in a string

Use the replace() method of the String object.

As mentioned in the selected answer, the /g flag should be used in the regex, in order to replace all instances of the substring in the string.

Twitter API returns error 215, Bad Authentication Data

I was facing the same problem all the time the only solution I figurae out is typing CONSUMER_KEY and CONSUMER_SECRET directly to new TwitterOAuth class defination .

$connection = new TwitterOAuth(  "MY_CK" , "MY_CS"  );

Don't use variable or statics on this and see if the issue sloved .

Set Background color programmatically

If you just want to use some of the predefined Android colors, you can use Color.COLOR (where COLOR is BLACK, WHITE, RED, etc.):

myView.setBackgroundColor(Color.GREEN);

Otherwise you can do as others have suggested with

myView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.myCustomGreen));

I don't recommend using a hex color directly. You should keep all of your custom colors in colors.xml.

What is tempuri.org?

Note that namespaces that are in the format of a valid Web URL don't necessarily need to be dereferenced i.e. you don't need to serve actual content at that URL. All that matters is that the namespace is globally unique.

Invalid character in identifier

This error occurs mainly when copy-pasting the code. Try editing/replacing minus(-), bracket({) symbols.

How to style readonly attribute with CSS?

capitalize the first letter of Only

_x000D_
_x000D_
input[readOnly] {_x000D_
      background: red !important;_x000D_
    }
_x000D_
<input type="text" name="country" value="China" readonly="readonly" />
_x000D_
_x000D_
_x000D_

jquery - Check for file extension before uploading

Here is a simple code for javascript validation, and after it validates it will clean the input file.

<input type="file" id="image" accept="image/*" onChange="validate(this.value)"/>

function validate(file) {
    var ext = file.split(".");
    ext = ext[ext.length-1].toLowerCase();      
    var arrayExtensions = ["jpg" , "jpeg", "png", "bmp", "gif"];

    if (arrayExtensions.lastIndexOf(ext) == -1) {
        alert("Wrong extension type.");
        $("#image").val("");
    }
}

Check if Cell value exists in Column, and then get the value of the NEXT Cell

How about this?

=IF(ISERROR(MATCH(A1,B:B, 0)), "No Match", INDIRECT(ADDRESS(MATCH(A1,B:B, 0), 3)))

The "3" at the end means for column C.

Angular and Typescript: Can't find names - Error: cannot find name

I was getting this on Angular 2 rc1. Turns out some names changed with typings v1 vs the old 0.x. The browser.d.ts files became index.d.ts.

After running typings install locate your startup file (where you bootstrap) and add:

/// <reference path="../typings/index.d.ts" /> (or without the ../ if your startup file is in the same folder as the typings folder)

Adding index.d.ts to the files list in tsconfig.json did not work for some reason.

Also, the es6-shim package was not needed.

Formatting MM/DD/YYYY dates in textbox in VBA

While I agree with what's mentioned in the answers below, suggesting that this is a very bad design for a Userform unless copious amounts of error checks are included...

to accomplish what you need to do, with minimal changes to your code, there are two approaches.

  1. Use KeyUp() event instead of Change event for the textbox. Here is an example:

    Private Sub TextBox2_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    
        Dim TextStr As String
        TextStr = TextBox2.Text
    
        If KeyCode <> 8 Then ' i.e. not a backspace
    
            If (Len(TextStr) = 2 Or Len(TextStr) = 5) Then
                TextStr = TextStr & "/"
            End If
    
        End If
        TextBox2.Text = TextStr
    End Sub
    
  2. Alternately, if you need to use the Change() event, use the following code. This alters the behavior so the user keeps entering the numbers, as

    12072003
    

while the result as he's typing appears as

    12/07/2003

But the '/' character appears only once the first character of the DD i.e. 0 of 07 is entered. Not ideal, but will still handle backspaces.

    Private Sub TextBox1_Change()
        Dim TextStr As String

        TextStr = TextBox1.Text

        If (Len(TextStr) = 3 And Mid(TextStr, 3, 1) <> "/") Then
            TextStr = Left(TextStr, 2) & "/" & Right(TextStr, 1)
        ElseIf (Len(TextStr) = 6 And Mid(TextStr, 6, 1) <> "/") Then
            TextStr = Left(TextStr, 5) & "/" & Right(TextStr, 1)
        End If

        TextBox1.Text = TextStr
    End Sub

jQuery: Check if special characters exists in string

var specialChars = "<>@!#$%^&*()_+[]{}?:;|'\"\\,./~`-="
var check = function(string){
    for(i = 0; i < specialChars.length;i++){
        if(string.indexOf(specialChars[i]) > -1){
            return true
        }
    }
    return false;
}

if(check($('#Search').val()) == false){
    // Code that needs to execute when none of the above is in the string
}else{
    alert('Your search string contains illegal characters.');
}

jquery UI dialog: how to initialize without a title bar?

This worked for me:

$("#dialog").dialog({
    create: function (event, ui) {
        $(".ui-widget-header").hide();
    },

Why should Java 8's Optional not be used in arguments

There are almost no good reasons for not using Optional as parameters. The arguments against this rely on arguments from authority (see Brian Goetz - his argument is we can't enforce non null optionals) or that the Optional arguments may be null (essentially the same argument). Of course, any reference in Java can be null, we need to encourage rules being enforced by the compiler, not programmers memory (which is problematic and does not scale).

Functional programming languages encourage Optional parameters. One of the best ways of using this is to have multiple optional parameters and using liftM2 to use a function assuming the parameters are not empty and returning an optional (see http://www.functionaljava.org/javadoc/4.4/functionaljava/fj/data/Option.html#liftM2-fj.F-). Java 8 has unfortunately implemented a very limited library supporting optional.

As Java programmers we should only be using null to interact with legacy libraries.

How to loop through a collection that supports IEnumerable?

Maybe you forgot the await before returning your collection

Why can't I see the "Report Data" window when creating reports?

First of all select report file with rdlc extension and then go to View > Report Data

Rollback one specific migration in Laravel

1.) Inside the database, head to the migrations table and delete the entry of the migration related to the table you want to drop.

Migration table image example

2.) Next, delete the table related to the migration you just deleted from instruction 1.

Delete table image example

3.) Finally, do the changes you want to the migration file of the table you deleted from instruction no. 2 then run php artisan migrate to migrate the table again.

"You have mail" message in terminal, os X

Probably it is some message from your system.

Type in terminal:

man mail

, and see how can you get this message from your system.

Git - push current branch shortcut

The simplest way: run git push -u origin feature/123-sandbox-tests once. That pushes the branch the way you're used to doing it and also sets the upstream tracking info in your local config. After that, you can just git push to push tracked branches to their upstream remote(s).

You can also do this in the config yourself by setting branch.<branch name>.merge to the remote branch name (in your case the same as the local name) and optionally, branch.<branch name>.remote to the name of the remote you want to push to (defaults to origin). If you look in your config, there's most likely already one of these set for master, so you can follow that example.

Finally, make sure you consider the push.default setting. It defaults to "matching", which can have undesired and unexpected results. Most people I know find "upstream" more intuitive, which pushes only the current branch.

Details on each of these settings can be found in the git-config man page.

On second thought, on re-reading your question, I think you know all this. I think what you're actually looking for doesn't exist. How about a bash function something like (untested):

function pushCurrent {
  git config push.default upstream
  git push
  git config push.default matching
}

R Apply() function on specific dataframe columns

lapply is probably a better choice than apply here, as apply first coerces your data.frame to an array which means all the columns must have the same type. Depending on your context, this could have unintended consequences.

The pattern is:

df[cols] <- lapply(df[cols], FUN)

The 'cols' vector can be variable names or indices. I prefer to use names whenever possible (it's robust to column reordering). So in your case this might be:

wifi[4:9] <- lapply(wifi[4:9], A)

An example of using column names:

wifi <- data.frame(A=1:4, B=runif(4), C=5:8)
wifi[c("B", "C")] <- lapply(wifi[c("B", "C")], function(x) -1 * x)

How to assign more memory to docker container

That 2GB limit you see is the total memory of the VM in which docker runs.

If you are using docker-for-windows or docker-for-mac you can easily increase it from the Whale icon in the task bar, then go to Preferences -> Advanced:

Docker Preferences

But if you are using VirtualBox behind, open VirtualBox, Select and configure the docker-machine assigned memory.

See this for Mac:

https://docs.docker.com/docker-for-mac/#memory

MEMORY By default, Docker for Mac is set to use 2 GB runtime memory, allocated from the total available memory on your Mac. You can increase the RAM on the app to get faster performance by setting this number higher (for example to 3) or lower (to 1) if you want Docker for Mac to use less memory.

For Windows:

https://docs.docker.com/docker-for-windows/#advanced

Memory - Change the amount of memory the Docker for Windows Linux VM uses

How to convert ActiveRecord results into an array of hashes

For current ActiveRecord (4.2.4+) there is a method to_hash on the Result object that returns an array of hashes. You can then map over it and convert to symbolized hashes:

# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
      {"id" => 2, "title" => "title_2", "body" => "body_2"},
      ...
     ]

result.to_hash.map(&:symbolize_keys)
# => [{:id => 1, :title => "title_1", :body => "body_1"},
      {:id => 2, :title => "title_2", :body => "body_2"},
      ...
     ]

See the ActiveRecord::Result docs for more info.

Referring to a table in LaTeX

You must place the label after a caption in order to for label to store the table's number, not the chapter's number.

\begin{table}
\begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |}
  -- cut --
\end{tabular}
\caption{My table}
\label{table:kysymys}
\end{table}

Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...

Connecting to MySQL from Android with JDBC

this code runs permanently!!! created by diko(Turkey)

public void mysql() {

    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();

    }

    thrd1 = new Thread(new Runnable() {
        public void run() {
            while (!Thread.interrupted()) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e1) {

                }
                if (con == null) {
                    try {
                        con = DriverManager.getConnection("jdbc:mysql://192.168.1.45:3306/deneme", "ali", "12345");

                    } catch (SQLException e) {
                        e.printStackTrace();
                        con = null;
                    }

                    if ((thrd2 != null) && (!thrd2.isAlive()))
                        thrd2.start();

                }
            }

        }
    });
    if ((thrd1 != null) && (!thrd1.isAlive())) thrd1.start();

    thrd2 = new Thread(new Runnable() {
        public void run() {
            while (!Thread.interrupted()) {

                if (con != null) {
                    try {
                     //   con = DriverManager.getConnection("jdbc:mysql://192.168.1.45:3306/deneme", "ali", "12345");
                        Statement st = con.createStatement();
                        String ali = "'fff'";
                        st.execute("INSERT INTO deneme (name) VALUES(" + ali + ")");
                      //  ResultSet rs = st.executeQuery("select * from deneme");
                      //  ResultSetMetaData rsmd = rs.getMetaData();
                      //  String result = new String();


                      //  while (rs.next()) {
                      //      result += rsmd.getColumnName(1) + ": " + rs.getInt(1) + "\n";
                     //       result += rsmd.getColumnName(2) + ": " + rs.getString(2) + "\n";


                     //   }

                    } catch (SQLException e) {
                        e.printStackTrace();
                        con = null;
                    }

                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    });


}

What's the fastest way to do a bulk insert into Postgres?

The external file is the best and typical bulk-data

The term "bulk data" is related to "a lot of data", so it is natural to use original raw data, with no need to transform it into SQL. Typical raw data files for "bulk insert" are CSV and JSON formats.

Bulk insert with some transformation

In ETL applications and ingestion processes, we need to change the data before inserting it. Temporary table consumes (a lot of) disk space, and it is not the faster way to do it. The PostgreSQL foreign-data wrapper (FDW) is the best choice.

CSV example. Suppose the tablename (x, y, z) on SQL and a CSV file like

fieldname1,fieldname2,fieldname3
etc,etc,etc
... million lines ...

You can use the classic SQL COPY to load (as is original data) into tmp_tablename, them insert filtered data into tablename... But, to avoid disk consumption, the best is to ingested directly by

INSERT INTO tablename (x, y, z)
  SELECT f1(fieldname1), f2(fieldname2), f3(fieldname3) -- the transforms 
  FROM tmp_tablename_fdw
  -- WHERE condictions
;

You need to prepare database for FDW, and instead static tmp_tablename_fdw you can use a function that generates it:

CREATE EXTENSION file_fdw;
CREATE SERVER import FOREIGN DATA WRAPPER file_fdw;
CREATE FOREIGN TABLE tmp_tablename_fdw(
  ...
) SERVER import OPTIONS ( filename '/tmp/pg_io/file.csv', format 'csv');

JSON example. A set of two files, myRawData1.json and Ranger_Policies2.json can be ingested by:

INSERT INTO tablename (fname, metadata, content)
 SELECT fname, meta, j  -- do any data transformation here
 FROM jsonb_read_files('myRawData%.json')
 -- WHERE any_condiction_here
;

where the function jsonb_read_files() reads all files of a folder, defined by a mask:

CREATE or replace FUNCTION jsonb_read_files(
  p_flike text, p_fpath text DEFAULT '/tmp/pg_io/'
) RETURNS TABLE (fid int,  fname text, fmeta jsonb, j jsonb) AS $f$
  WITH t AS (
     SELECT (row_number() OVER ())::int id, 
           f as fname,
           p_fpath ||'/'|| f as f
     FROM pg_ls_dir(p_fpath) t(f)
     WHERE    f like p_flike
  ) SELECT id,  fname,
         to_jsonb( pg_stat_file(f) ) || jsonb_build_object('fpath',p_fpath),
         pg_read_file(f)::jsonb
    FROM t
$f$  LANGUAGE SQL IMMUTABLE;

Lack of gzip streaming

The most frequent method for "file ingestion" (mainlly in Big Data) is preserving original file on gzip format and transfering it with streaming algorithm, anything that can runs fast and without disc consumption in unix pipes:

 gunzip remote_or_local_file.csv.gz | convert_to_sql | psql 

So ideal (future) is a server option for format .csv.gz.

Linq on DataTable: select specific column into datatable, not whole table

LINQ is very effective and easy to use on Lists rather than DataTable. I can see the above answers have a loop(for, foreach), which I will not prefer.

So the best thing to select a perticular column from a DataTable is just use a DataView to filter the column and use it as you want.

Find it here how to do this.

DataView dtView = new DataView(dtYourDataTable);
DataTable dtTableWithOneColumn= dtView .ToTable(true, "ColumnA");

Now the DataTable dtTableWithOneColumn contains only one column(ColumnA).

Switching a DIV background image with jQuery

Here is how I do it:

CSS

#button{
   background-image: url("initial_image.png");
}

#button.toggled{
  background-image:url("toggled_image.png");
}

JS

$('#button').click(function(){
  $('#my_content').toggle();
  $(this).toggleClass('toggled');
});

Replace given value in vector

Why the fuss?

replace(haystack, haystack %in% needles, replacements)

Demo:

haystack <- c("q", "w", "e", "r", "t", "y")
needles <- c("q", "w")
replacements <- c("a", "z")

replace(haystack, haystack %in% needles, replacements)
#> [1] "a" "z" "e" "r" "t" "y"

Regular expression for checking if capital letters are found consecutively in a string?

Aside from tchrists excellent post concerning unicode, I think you don't need the complex solution with a negative lookahead... Your definition requires an Uppercase-letter followed by at least one group of (a lowercase letter optionally followed by an Uppercase-letter)

^
[A-Z]    // Start with an uppercase Letter
(        // A Group of:
  [a-z]  // mandatory lowercase letter
  [A-Z]? // an optional Uppercase Letter at the end
         // or in between lowercase letters
)+       // This group at least one time
$

Just a bit more compact and easier to read I think...

Extracting text OpenCV

@dhanushka's approach showed the most promise but I wanted to play around in Python so went ahead and translated it for fun:

import cv2
import numpy as np
from cv2 import boundingRect, countNonZero, cvtColor, drawContours, findContours, getStructuringElement, imread, morphologyEx, pyrDown, rectangle, threshold

large = imread(image_path)
# downsample and use it for processing
rgb = pyrDown(large)
# apply grayscale
small = cvtColor(rgb, cv2.COLOR_BGR2GRAY)
# morphological gradient
morph_kernel = getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
grad = morphologyEx(small, cv2.MORPH_GRADIENT, morph_kernel)
# binarize
_, bw = threshold(src=grad, thresh=0, maxval=255, type=cv2.THRESH_BINARY+cv2.THRESH_OTSU)
morph_kernel = getStructuringElement(cv2.MORPH_RECT, (9, 1))
# connect horizontally oriented regions
connected = morphologyEx(bw, cv2.MORPH_CLOSE, morph_kernel)
mask = np.zeros(bw.shape, np.uint8)
# find contours
im2, contours, hierarchy = findContours(connected, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
# filter contours
for idx in range(0, len(hierarchy[0])):
    rect = x, y, rect_width, rect_height = boundingRect(contours[idx])
    # fill the contour
    mask = drawContours(mask, contours, idx, (255, 255, 2555), cv2.FILLED)
    # ratio of non-zero pixels in the filled region
    r = float(countNonZero(mask)) / (rect_width * rect_height)
    if r > 0.45 and rect_height > 8 and rect_width > 8:
        rgb = rectangle(rgb, (x, y+rect_height), (x+rect_width, y), (0,255,0),3)

Now to display the image:

from PIL import Image
Image.fromarray(rgb).show()

Not the most Pythonic of scripts but I tried to resemble the original C++ code as closely as possible for readers to follow.

It works almost as well as the original. I'll be happy to read suggestions how it could be improved/fixed to resemble the original results fully.

enter image description here

enter image description here

enter image description here

String escape into XML

George, it's simple. Always use the XML APIs to handle XML. They do all the escaping and unescaping for you.

Never create XML by appending strings.

How to get the xml node value in string

The problem in your code is xml.LoadXml(filePath);

LoadXml method take parameter as xml data not the xml file path

Try this code

   string xmlFile = File.ReadAllText(@"D:\Work_Time_Calculator\10-07-2013.xml");
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(xmlFile);
                XmlNodeList nodeList = xmldoc.GetElementsByTagName("Short_Fall");
                string Short_Fall=string.Empty;
                foreach (XmlNode node in nodeList)
                {
                    Short_Fall = node.InnerText;
                }

Edit

Seeing the last edit of your question i found the solution,

Just replace the below 2 lines

XmlNode node = xml.SelectSingleNode("/Data[@*]/Short_Fall");
string id = node["Short_Fall"].InnerText; // Exception occurs here ("Object reference not set to an instance of an object.")

with

string id = xml.SelectSingleNode("Data/Short_Fall").InnerText;

It should solve your problem or you can use the solution i provided earlier.

Best method to download image from url in Android

I'm still learning Android, so I cannot provide a rich context or reason for my suggestion, but this is what I am using to retrive files from both https and local urls. I am using this in my onActivity result (for both taking pictures and selecting from gallery), as well in an AsyncTask to retrieve the https urls.

InputStream input = new URL("your_url_string").openStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);

React Router Pass Param to Component

I used this to access the ID in my component:

<Route path="/details/:id" component={DetailsPage}/>

And in the detail component:

export default class DetailsPage extends Component {
  render() {
    return(
      <div>
        <h2>{this.props.match.params.id}</h2>
      </div>
    )
  }
}

This will render any ID inside an h2, hope that helps someone.

Write single CSV file using spark-csv

you can use rdd.coalesce(1, true).saveAsTextFile(path)

it will store data as singile file in path/part-00000

How to Debug Variables in Smarty like in PHP var_dump()

just use {debug} in your .tpl and look at your sourcecode

How to get max value of a column using Entity Framework?

Try this int maxAge = context.Persons.Max(p => p.Age);

And make sure you have using System.Linq; at the top of your file

Ubuntu, how do you remove all Python 3 but not 2

Removing Python 3 was the worst thing I did since I recently moved to the world of Linux. It removed Firefox, my launcher and, as I read while trying to fix my problem, it may also remove your desktop and terminal! Finally fixed after a long daytime nightmare. Just don't remove Python 3. Keep it there!

If that happens to you, here is the fix:

https://askubuntu.com/q/384033/402539

https://askubuntu.com/q/810854/402539

How to properly add cross-site request forgery (CSRF) token using PHP

CSRF protection

TYPES OF CSRF USAGE

IN FORM

<form>
   @csrf
</form>

or

<input type="hidden" name="token" value="{{ form_token() }}" />

META TAG

<meta name="csrf-token" content="{{ csrf_token() }}">

AJAX

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

SESSION

use Illuminate\Http\Request;

Route::get('/token', function (Request $request) {
    $token = $request->session()->token();

    $token = csrf_token();

    // ...
});

MIDDLEWARE

 App\Providers\RouteServiceProvider

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'stripe/*',
        'http://example.com/foo/bar',
        'http://example.com/foo/*',
    ];
}

Display SQL query results in php

You need to do a while loop to get the result from the SQL query, like this:

require_once('db.php');  
$sql="SELECT * FROM  modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )    
FROM modul1open) ORDER BY idM1O LIMIT 1";

$result = mysql_query($sql);

while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

    // If you want to display all results from the query at once:
    print_r($row);

    // If you want to display the results one by one
    echo $row['column1'];
    echo $row['column2']; // etc..

}

Also I would strongly recommend not using mysql_* since it's deprecated. Instead use the mysqli or PDO extension. You can read more about that here.

Android: how to hide ActionBar on certain activities

To hide the ActionBar add this code into java file.

    ActionBar actionBar = getSupportActionBar();
    actionBar.hide();

/usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

In my case LD_LIBRARY_PATH had /usr/lib64 first before /usr/local/lib64. (I was builing llvm 3.9).
The new gcc compiler that I installed to compile llvm 3.9 had libraries using newer GLIBCXX libraries under /usr/local/lib64 So I fixed LD_LIBRARY_PATH for the linker to see /usr/local/lib64 first.
That solved this problem.

check / uncheck checkbox using jquery?

For jQuery 1.6+ :

.attr() is deprecated for properties; use the new .prop() function instead as:

$('#myCheckbox').prop('checked', true); // Checks it
$('#myCheckbox').prop('checked', false); // Unchecks it

For jQuery < 1.6:

To check/uncheck a checkbox, use the attribute checked and alter that. With jQuery you can do:

$('#myCheckbox').attr('checked', true); // Checks it
$('#myCheckbox').attr('checked', false); // Unchecks it

Cause you know, in HTML, it would look something like:

<input type="checkbox" id="myCheckbox" checked="checked" /> <!-- Checked -->
<input type="checkbox" id="myCheckbox" /> <!-- Unchecked -->

However, you cannot trust the .attr() method to get the value of the checkbox (if you need to). You will have to rely in the .prop() method.

jQuery: If this HREF contains

You could just outright select the elements of interest.

$('a[href*="?"]').each(function() {
    alert('Contains question mark');
});

http://jsfiddle.net/mattball/TzUN3/

Note that you were using the attribute-ends-with selector, the above code uses the attribute-contains selector, which is what it sounds like you're actually aiming for.

How to use OAuth2RestTemplate?

I have different approach if you want access token and make call to other resource system with access token in header

Spring Security comes with automatic security: oauth2 properties access from application.yml file for every request and every request has SESSIONID which it reads and pull user info via Principal, so you need to make sure inject Principal in OAuthUser and get accessToken and make call to resource server

This is your application.yml, change according to your auth server:

security:
  oauth2:
    client:
      clientId: 233668646673605
      clientSecret: 33b17e044ee6a4fa383f46ec6e28ea1d
      accessTokenUri: https://graph.facebook.com/oauth/access_token
      userAuthorizationUri: https://www.facebook.com/dialog/oauth
      tokenName: oauth_token
      authenticationScheme: query
      clientAuthenticationScheme: form
    resource:
      userInfoUri: https://graph.facebook.com/me

@Component
public class OAuthUser implements Serializable {

private static final long serialVersionUID = 1L;

private String authority;

@JsonIgnore
private String clientId;

@JsonIgnore
private String grantType;
private boolean isAuthenticated;
private Map<String, Object> userDetail = new LinkedHashMap<String, Object>();

@JsonIgnore
private String sessionId;

@JsonIgnore
private String tokenType;

@JsonIgnore
private String accessToken;

@JsonIgnore
private Principal principal;

public void setOAuthUser(Principal principal) {
    this.principal = principal;
    init();
}

public Principal getPrincipal() {
    return principal;
}

private void init() {
    if (principal != null) {
        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) principal;
        if (oAuth2Authentication != null) {
            for (GrantedAuthority ga : oAuth2Authentication.getAuthorities()) {
                setAuthority(ga.getAuthority());
            }
            setClientId(oAuth2Authentication.getOAuth2Request().getClientId());
            setGrantType(oAuth2Authentication.getOAuth2Request().getGrantType());
            setAuthenticated(oAuth2Authentication.getUserAuthentication().isAuthenticated());

            OAuth2AuthenticationDetails oAuth2AuthenticationDetails = (OAuth2AuthenticationDetails) oAuth2Authentication
                    .getDetails();
            if (oAuth2AuthenticationDetails != null) {
                setSessionId(oAuth2AuthenticationDetails.getSessionId());
                setTokenType(oAuth2AuthenticationDetails.getTokenType());

            // This is what you will be looking for 
                setAccessToken(oAuth2AuthenticationDetails.getTokenValue());
            }

    // This detail is more related to Logged-in User
            UsernamePasswordAuthenticationToken userAuthenticationToken = (UsernamePasswordAuthenticationToken) oAuth2Authentication.getUserAuthentication();
            if (userAuthenticationToken != null) {
                LinkedHashMap<String, Object> detailMap = (LinkedHashMap<String, Object>) userAuthenticationToken.getDetails();
                if (detailMap != null) {
                    for (Map.Entry<String, Object> mapEntry : detailMap.entrySet()) {
                        //System.out.println("#### detail Key = " + mapEntry.getKey());
                        //System.out.println("#### detail Value = " + mapEntry.getValue());
                        getUserDetail().put(mapEntry.getKey(), mapEntry.getValue());
                    }

                }

            }

        }

    }
}


public String getAuthority() {
    return authority;
}

public void setAuthority(String authority) {
    this.authority = authority;
}

public String getClientId() {
    return clientId;
}

public void setClientId(String clientId) {
    this.clientId = clientId;
}

public String getGrantType() {
    return grantType;
}

public void setGrantType(String grantType) {
    this.grantType = grantType;
}

public boolean isAuthenticated() {
    return isAuthenticated;
}

public void setAuthenticated(boolean isAuthenticated) {
    this.isAuthenticated = isAuthenticated;
}

public Map<String, Object> getUserDetail() {
    return userDetail;
}

public void setUserDetail(Map<String, Object> userDetail) {
    this.userDetail = userDetail;
}

public String getSessionId() {
    return sessionId;
}

public void setSessionId(String sessionId) {
    this.sessionId = sessionId;
}

public String getTokenType() {
    return tokenType;
}

public void setTokenType(String tokenType) {
    this.tokenType = tokenType;
}

public String getAccessToken() {
    return accessToken;
}

public void setAccessToken(String accessToken) {
    this.accessToken = accessToken;
}

@Override
public String toString() {
    return "OAuthUser [clientId=" + clientId + ", grantType=" + grantType + ", isAuthenticated=" + isAuthenticated
            + ", userDetail=" + userDetail + ", sessionId=" + sessionId + ", tokenType="
            + tokenType + ", accessToken= " + accessToken + " ]";
}

@RestController
public class YourController {

@Autowired
OAuthUser oAuthUser;

// In case if you want to see Profile of user then you this 
@RequestMapping(value = "/profile", produces = MediaType.APPLICATION_JSON_VALUE)
public OAuthUser user(Principal principal) {
    oAuthUser.setOAuthUser(principal);

    // System.out.println("#### Inside user() - oAuthUser.toString() = " + oAuthUser.toString());

    return oAuthUser;
}


@RequestMapping(value = "/createOrder",
        method = RequestMethod.POST,
        headers = {"Content-type=application/json"},
        consumes = MediaType.APPLICATION_JSON_VALUE,
        produces = MediaType.APPLICATION_JSON_VALUE)
public FinalOrderDetail createOrder(@RequestBody CreateOrder createOrder) {

    return postCreateOrder_restTemplate(createOrder, oAuthUser).getBody();
}


private ResponseEntity<String> postCreateOrder_restTemplate(CreateOrder createOrder, OAuthUser oAuthUser) {

String url_POST = "your post url goes here";

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("Authorization", String.format("%s %s", oAuthUser.getTokenType(), oAuthUser.getAccessToken()));
    headers.add("Content-Type", "application/json");

    RestTemplate restTemplate = new RestTemplate();
    //restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

    HttpEntity<String> request = new HttpEntity<String>(createOrder, headers);

    ResponseEntity<String> result = restTemplate.exchange(url_POST, HttpMethod.POST, request, String.class);
    System.out.println("#### post response = " + result);

    return result;
}


}

Junit test case for database insert method with DAO and web service

The design of your classes will make it hard to test them. Using hardcoded connection strings or instantiating collaborators in your methods with new can be considered as test-antipatterns. Have a look at the DependencyInjection pattern. Frameworks like Spring might be of help here.

To have your DAO tested you need to have control over your database connection in your unit tests. So the first thing you would want to do is extract it out of your DAO into a class that you can either mock or point to a specific test database, which you can setup and inspect before and after your tests run.

A technical solution for testing db/DAO code might be dbunit. You can define your test data in a schema-less XML and let dbunit populate it in your test database. But you still have to wire everything up yourself. With Spring however you could use something like spring-test-dbunit which gives you lots of leverage and additional tooling.

As you call yourself a total beginner I suspect this is all very daunting. You should ask yourself if you really need to test your database code. If not you should at least refactor your code, so you can easily mock out all database access. For mocking in general, have a look at Mockito.

LINQ select in C# dictionary

var res = exitDictionary
            .Select(p => p.Value).Cast<Dictionary<string, object>>()
            .SelectMany(d => d)
            .Where(p => p.Key == "fieldname1")
            .Select(p => p.Value).Cast<List<Dictionary<string,string>>>()
            .SelectMany(l => l)
            .SelectMany(d=> d)
            .Where(p => p.Key == "valueTitle")
            .Select(p => p.Value)
            .ToList();

This also works, and easy to understand.

'str' object does not support item assignment in Python

As aix mentioned - strings in Python are immutable (you cannot change them inplace).

What you are trying to do can be done in many ways:

# Copy the string

foo = 'Hello'
bar = foo

# Create a new string by joining all characters of the old string

new_string = ''.join(c for c in oldstring)

# Slice and copy
new_string = oldstring[:]

Set a variable if undefined in JavaScript

Ran into this scenario today as well where I didn't want zero to be overwritten for several values. We have a file with some common utility methods for scenarios like this. Here's what I added to handle the scenario and be flexible.

function getIfNotSet(value, newValue, overwriteNull, overwriteZero) {
    if (typeof (value) === 'undefined') {
        return newValue;
    } else if (value === null && overwriteNull === true) {
        return newValue;
    } else if (value === 0 && overwriteZero === true) {
        return newValue;
    } else {
        return value;
    }
}

It can then be called with the last two parameters being optional if I want to only set for undefined values or also overwrite null or 0 values. Here's an example of a call to it that will set the ID to -1 if the ID is undefined or null, but wont overwrite a 0 value.

data.ID = Util.getIfNotSet(data.ID, -1, true);

Install specific version using laravel installer

use

laravel new blog --version

Example laravel new blog --5.1

You can also use the composer method

composer create-project laravel/laravel app "5.1.*"

here, app is the name of your project

please see the documentation for laravel 5.1 here

UPDATE:

The above commands are no longer supports so please use

composer create-project laravel/laravel="5.1.*" appName

Convert Xml to Table SQL Server

This is the answer, hope it helps someone :)

First there are two variations on how the xml can be written:

1

<row>
    <IdInvernadero>8</IdInvernadero>
    <IdProducto>3</IdProducto>
    <IdCaracteristica1>8</IdCaracteristica1>
    <IdCaracteristica2>8</IdCaracteristica2>
    <Cantidad>25</Cantidad>
    <Folio>4568457</Folio>
</row>
<row>
    <IdInvernadero>3</IdInvernadero>
    <IdProducto>3</IdProducto>
    <IdCaracteristica1>1</IdCaracteristica1>
    <IdCaracteristica2>2</IdCaracteristica2>
    <Cantidad>72</Cantidad>
    <Folio>4568457</Folio>
</row>

Answer:

SELECT  
       Tbl.Col.value('IdInvernadero[1]', 'smallint'),  
       Tbl.Col.value('IdProducto[1]', 'smallint'),  
       Tbl.Col.value('IdCaracteristica1[1]', 'smallint'),
       Tbl.Col.value('IdCaracteristica2[1]', 'smallint'),
       Tbl.Col.value('Cantidad[1]', 'int'),
       Tbl.Col.value('Folio[1]', 'varchar(7)')
FROM   @xml.nodes('//row') Tbl(Col)  

2.

<row IdInvernadero="8" IdProducto="3" IdCaracteristica1="8" IdCaracteristica2="8" Cantidad ="25" Folio="4568457" />                         
<row IdInvernadero="3" IdProducto="3" IdCaracteristica1="1" IdCaracteristica2="2" Cantidad ="72" Folio="4568457" />

Answer:

SELECT  
       Tbl.Col.value('@IdInvernadero', 'smallint'),  
       Tbl.Col.value('@IdProducto', 'smallint'),  
       Tbl.Col.value('@IdCaracteristica1', 'smallint'),
       Tbl.Col.value('@IdCaracteristica2', 'smallint'),
       Tbl.Col.value('@Cantidad', 'int'),
       Tbl.Col.value('@Folio', 'varchar(7)')

FROM   @xml.nodes('//row') Tbl(Col)

Taken from:

  1. http://kennyshu.blogspot.com/2007/12/convert-xml-file-to-table-in-sql-2005.html

  2. http://msdn.microsoft.com/en-us/library/ms345117(SQL.90).aspx

cat, grep and cut - translated to python

You need to have better understanding of the python language and its standard library to translate the expression

cat "$filename": Reads the file cat "$filename" and dumps the content to stdout

|: pipe redirects the stdout from previous command and feeds it to the stdin of the next command

grep "something": Searches the regular expressionsomething plain text data file (if specified) or in the stdin and returns the matching lines.

cut -d'"' -f2: Splits the string with the specific delimiter and indexes/splices particular fields from the resultant list

Python Equivalent

cat "$filename"  | with open("$filename",'r') as fin:        | Read the file Sequentially
                 |     for line in fin:                      |   
-----------------------------------------------------------------------------------
grep 'something' | import re                                 | The python version returns
                 | line = re.findall(r'something', line)[0]  | a list of matches. We are only
                 |                                           | interested in the zero group
-----------------------------------------------------------------------------------
cut -d'"' -f2    | line = line.split('"')[1]                 | Splits the string and selects
                 |                                           | the second field (which is
                 |                                           | index 1 in python)

Combining

import re
with open("filename") as origin_file:
    for line in origin_file:
        line = re.findall(r'something', line)
        if line:
           line = line[0].split('"')[1]
        print line

Android: how to handle button click

To make things easier asp Question 2 stated, you can make use of lambda method like this to save variable memory and to avoid navigating up and down in your view class

//method 1
findViewById(R.id.buttonSend).setOnClickListener(v -> {
          // handle click
});

but if you wish to apply click event to your button at once in a method.

you can make use of Question 3 by @D. Tran answer. But do not forget to implement your view class with View.OnClickListener.

In other to use Question #3 properly

How can I print using JQuery

Try like

$('.printMe').click(function(){
     window.print();
});

or if you want to print selected area try like

$('.printMe').click(function(){
     $("#outprint").print();
});

Python 2.7.10 error "from urllib.request import urlopen" no module named request

You are right the urllib and urllib2 packages have been split into urllib.request , urllib.parse and urllib.error packages in Python 3.x. The latter packages do not exist in Python 2.x

From documentation -

The urllib module has been split into parts and renamed in Python 3 to urllib.request, urllib.parse, and urllib.error.

From urllib2 documentation -

The urllib2 module has been split across several modules in Python 3 named urllib.request and urllib.error.

So I am pretty sure the code you downloaded has been written for Python 3.x , since they are using a library that is only present in Python 3.x .

There is a urllib package in python, but it does not have the request subpackage. Also, lets assume you do lots of work and somehow make request subpackage available in Python 2.x .

There is a very very high probability that you will run into more issues, there is lots of incompatibility between Python 2.x and Python 3.x , in the end you would most probably end up rewriting atleast half the code from github (and most probably reading and understanding the complete code from there).

Even then there may be other bugs arising from the fact that some of the implementation details changed between Python 2.x to Python 3.x (As an example - list comprehension got its own namespace in Python 3.x)

You are better off trying to download and use Python 3 , than trying to make code written for Python 3.x compatible with Python 2.x

How can I specify my .keystore file with Spring Boot and Tomcat?

For external keystores, prefix with "file:"

server.ssl.key-store=file:config/keystore 

Submit button not working in Bootstrap form

The .btn classes are designed for , or elements (though some browsers may apply a slightly different rendering).

If you’re using .btn classes on elements that are used to trigger functionality ex. collapsing content, these links should be given a role="button" to adequately communicate their meaning to assistive technologies such as screen readers. I hope this help.

#1142 - SELECT command denied to user ''@'localhost' for table 'pma_table_uiprefs'

Try this before anything else - 'clear your cache'. I had the same issue. I was instructed to clear my cache. It worked.

How to append text to an existing file in Java?

Create a function anywhere in your project and simply call that function where ever you need it.

Guys you got to remember that you guys are calling active threads that you are not calling asynchronously and since it would likely be a good 5 to 10 pages to get it done right. Why not spend more time on your project and forget about writing anything already written. Properly

    //Adding a static modifier would make this accessible anywhere in your app

    public Logger getLogger()
    {
       return java.util.logging.Logger.getLogger("MyLogFileName");
    }
    //call the method anywhere and append what you want to log 
    //Logger class will take care of putting timestamps for you
    //plus the are ansychronously done so more of the 
    //processing power will go into your application

    //from inside a function body in the same class ...{...

    getLogger().log(Level.INFO,"the text you want to append");

    ...}...
    /*********log file resides in server root log files********/

three lines of code two really since the third actually appends text. :P

Multiple commands on a single line in a Windows batch file

Can be achieved also with scriptrunner

ScriptRunner.exe -appvscript demoA.cmd arg1 arg2 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror -appvscript demoB.ps1 arg3 arg4 -appvscriptrunnerparameters -wait -timeout=30 

Which also have some features as rollback , timeout and waiting.

Send HTTP POST message in ASP.NET Core using HttpClient PostAsJsonAsync

I would add to the accepted answer that you would also want to add the Accept header to the httpClient:

httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

jQuery click events not working in iOS

There is an issue with iOS not registering click/touch events bound to elements added after DOM loads.

While PPK has this advice: http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html

I've found this the easy fix, simply add this to the css:

cursor: pointer;

How to print a query string with parameter values when using Hibernate

Hibernate shows query and their parameter values in different lines.

If you are using application.properties in spring boot and you can use below highlighted parameter in application.properties.

  1. org.hibernate.SQL will show queries

    logging.level.org.hibernate.SQL=DEBUG

  2. org.hibernate.type will show all parameter values, which will map with select , insert and update queries. logging.level.org.hibernate.type=TRACE

    • org.hibernate.type.EnumType will show enum type parameter value

      logging.level.org.hibernate.type.EnumType=TRACE

      example ::

      2018-06-14 11:06:28,217 TRACE [main] [EnumType.java : 321] Binding [active] to parameter: [1]
      
    • sql.BasicBinder will show integer, varchar, boolean type parameter value

      logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

      example ::

      • 2018-06-14 11:28:29,750 TRACE [http-nio-9891-exec-2] [BasicBinder.java : 65] binding parameter [1] as [BOOLEAN] - [true]
      • 2018-06-14 11:28:29,751 TRACE [http-nio-9891-exec-2] [BasicBinder.java : 65] binding parameter [2] as [INTEGER] - [1]
      • 2018-06-14 11:28:29,752 TRACE [http-nio-9891-exec-2] [BasicBinder.java : 65] binding parameter [3] as [VARCHAR] - [public]

I can't understand why this JAXB IllegalAnnotationException is thrown

One of the following may cause the exception:

  1. Add an empty public constructor to your Fields class, JAXB uses reflection to load your classes, that's why the exception is thrown.
  2. Add separate getter and setter for your list.

How to run .NET Core console app from the command line

If it's a framework-dependent application (the default), you run it by dotnet yourapp.dll.

If it's a self-contained application, you run it using yourapp.exe on Windows and ./yourapp on Unix.

For more information about the differences between the two app types, see the .NET Core Application Deployment article on .Net Docs.

Matplotlib 2 Subplots, 1 Colorbar

This topic is well covered but I still would like to propose another approach in a slightly different philosophy.

It is a bit more complex to set-up but it allow (in my opinion) a bit more flexibility. For example, one can play with the respective ratios of each subplots / colorbar:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec

# Define number of rows and columns you want in your figure
nrow = 2
ncol = 3

# Make a new figure
fig = plt.figure(constrained_layout=True)

# Design your figure properties
widths = [3,4,5,1]
gs = GridSpec(nrow, ncol + 1, figure=fig, width_ratios=widths)

# Fill your figure with desired plots
axes = []
for i in range(nrow):
    for j in range(ncol):
        axes.append(fig.add_subplot(gs[i, j]))
        im = axes[-1].pcolormesh(np.random.random((10,10)))

# Shared colorbar    
axes.append(fig.add_subplot(gs[:, ncol]))
fig.colorbar(im, cax=axes[-1])

plt.show()

enter image description here

In SQL, how can you "group by" in ranges?

select cast(score/10 as varchar) + '-' + cast(score/10+9 as varchar), 
       count(*)
from scores
group by score/10

What's the most efficient way to test two integer ranges for overlap?

You have the most efficient representation already - it's the bare minimum that needs to be checked unless you know for sure that x1 < x2 etc, then use the solutions others have provided.

You should probably note that some compilers will actually optimise this for you - by returning as soon as any of those 4 expressions return true. If one returns true, so will the end result - so the other checks can just be skipped.

How can I apply a function to every row/column of a matrix in MATLAB?

Many built-in operations like sum and prod are already able to operate across rows or columns, so you may be able to refactor the function you are applying to take advantage of this.

If that's not a viable option, one way to do it is to collect the rows or columns into cells using mat2cell or num2cell, then use cellfun to operate on the resulting cell array.

As an example, let's say you want to sum the columns of a matrix M. You can do this simply using sum:

M = magic(10);           %# A 10-by-10 matrix
columnSums = sum(M, 1);  %# A 1-by-10 vector of sums for each column

And here is how you would do this using the more complicated num2cell/cellfun option:

M = magic(10);                  %# A 10-by-10 matrix
C = num2cell(M, 1);             %# Collect the columns into cells
columnSums = cellfun(@sum, C);  %# A 1-by-10 vector of sums for each cell

How do I print a datetime in the local timezone?

Think your should look around: datetime.astimezone()

http://docs.python.org/library/datetime.html#datetime.datetime.astimezone

Also see pytz module - it's quite easy to use -- as example:

eastern = timezone('US/Eastern')

http://pytz.sourceforge.net/

Example:

from datetime import datetime
import pytz
from tzlocal import get_localzone # $ pip install tzlocal

utc_dt = datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=pytz.utc)
print(utc_dt.astimezone(get_localzone())) # print local time
# -> 2009-07-10 14:44:59.193982-04:00

how to change namespace of entire project?

In asp.net is more to do, to get completely running under another namespace.

  • Copy your source folder and rename it to your new project name.
  • Open it and Replace all by Ctrl + H and be sure to include all Replace everything
  • Press F2 on your Projectname and rename it to your new project name
  • go to your project properties and adjust it, coz everything has gone and you need to make a new Debug Profile Profile to Create
  • All dependencies have now an exclamation mark - restart visual studio
  • Clean your solution and Run it and it should work :)

How to insert a text at the beginning of a file?

There is a very easy way:

echo "your header" > headerFile.txt
cat yourFile >> headerFile.txt

Get a list of dates between two dates using a function

Declare @date1 date = '2016-01-01'
              ,@date2 date = '2016-03-31'
              ,@date_index date
Declare @calender table (D date)
SET @date_index = @date1
WHILE @date_index<=@date2
BEGIN
INSERT INTO @calender
SELECT @date_index

SET @date_index = dateadd(day,1,@date_index)

IF @date_index>@date2
Break
ELSE
Continue
END

API vs. Webservice

Check this http://en.wikipedia.org/wiki/Web_service

As the link mentioned then Web API is a development in Web services that most likely relates to Web 2.0, whereas SOAP based services are replaced by REST based communications. Note that REST services do not require XML, SOAP, or WSDL service-API definitions so this is major different to traditional web service.

How to get index using LINQ?

I will make my contribution here... why? just because :p Its a different implementation, based on the Any LINQ extension, and a delegate. Here it is:

public static class Extensions
{
    public static int IndexOf<T>(
            this IEnumerable<T> list, 
            Predicate<T> condition) {               
        int i = -1;
        return list.Any(x => { i++; return condition(x); }) ? i : -1;
    }
}

void Main()
{
    TestGetsFirstItem();
    TestGetsLastItem();
    TestGetsMinusOneOnNotFound();
    TestGetsMiddleItem();   
    TestGetsMinusOneOnEmptyList();
}

void TestGetsFirstItem()
{
    // Arrange
    var list = new string[] { "a", "b", "c", "d" };

    // Act
    int index = list.IndexOf(item => item.Equals("a"));

    // Assert
    if(index != 0)
    {
        throw new Exception("Index should be 0 but is: " + index);
    }

    "Test Successful".Dump();
}

void TestGetsLastItem()
{
    // Arrange
    var list = new string[] { "a", "b", "c", "d" };

    // Act
    int index = list.IndexOf(item => item.Equals("d"));

    // Assert
    if(index != 3)
    {
        throw new Exception("Index should be 3 but is: " + index);
    }

    "Test Successful".Dump();
}

void TestGetsMinusOneOnNotFound()
{
    // Arrange
    var list = new string[] { "a", "b", "c", "d" };

    // Act
    int index = list.IndexOf(item => item.Equals("e"));

    // Assert
    if(index != -1)
    {
        throw new Exception("Index should be -1 but is: " + index);
    }

    "Test Successful".Dump();
}

void TestGetsMinusOneOnEmptyList()
{
    // Arrange
    var list = new string[] {  };

    // Act
    int index = list.IndexOf(item => item.Equals("e"));

    // Assert
    if(index != -1)
    {
        throw new Exception("Index should be -1 but is: " + index);
    }

    "Test Successful".Dump();
}

void TestGetsMiddleItem()
{
    // Arrange
    var list = new string[] { "a", "b", "c", "d", "e" };

    // Act
    int index = list.IndexOf(item => item.Equals("c"));

    // Assert
    if(index != 2)
    {
        throw new Exception("Index should be 2 but is: " + index);
    }

    "Test Successful".Dump();
}        

Removing NA observations with dplyr::filter()

If someone is here in 2020, after making all the pipes, if u pipe %>% na.exclude will take away all the NAs in the pipe!

How to find the nearest parent of a Git branch?

The solutions based on git show-branch -a plus some filters have one downside: git may consider a branch name of a short lived branch.

If you have a few possible parents which you care about, you can ask yourself this similar question (and probably the one the OP wanted to know about):

From a specific subset of all branches, which is the nearest parent of a git branch?

To simplify, I'll consider "a git branch" to refer to HEAD (i.e., the current branch).

Let's imagine that we have the following branches:

HEAD
important/a
important/b
spam/a
spam/b

The solutions based on git show-branch -a + filters, may give that the nearest parent of HEAD is spam/a, but we don't care about that.

If we want to know which of important/a and important/b is the closest parent of HEAD, we could run the following:

for b in $(git branch -a -l "important/*"); do
    d1=$(git rev-list --first-parent ^${b} HEAD |wc -l);
    d2=$(git rev-list --first-parent ^HEAD ${b} |wc -l);
    echo "${b} ${d1} ${d2}";
done \
|sort -n -k2 -k3 \
|head -n1 \
|awk '{print $1}';

What it does:

1.) $(git branch -a -l "important/*"): Print a list of all branches with some pattern ("important/*").

2.) d=$(git rev-list --first-parent ^${b} HEAD |wc -l);: For each of those branches ($b), calculate the distance ($d1) in number of commits, from HEAD to the nearest commit in $b (similar to when you calculate the distance from a point to a line). You may want to consider the distance differently here: you may not want to use --first-parent, or may want distance from tip to the tip of the branches ("${b}"...HEAD), ...

2.2) d2=$(git rev-list --first-parent ^HEAD ${b} |wc -l);: For each of those branches ($b), calculate the distance ($d2) in number of commits from the tip of the branch to the nearest commit in HEAD. We will use this distance to choose between two branches whose distance $d1 was equal.

3.) echo "${b} ${d1} ${d2}";: Print the name of each of the branches, followed by the distances to be able to sort them later (first $d1, and then $d2).

4.) |sort -n -k2 -k3: Sort the previous result, so we get a sorted (by distance) list of all of the branches, followed by their distances (both).

5.) |head -n1: The first result of the previous step will be the branch that has a smaller distance, i.e., the closest parent branch. So just discard all other branches.

6.) |awk '{print $1}';: We only care about the branch name, and not about the distance, so extract the first field, which was the parent's name. Here it is! :)

Is the 'as' keyword required in Oracle to define an alias?

AS without double quotations is good.

SELECT employee_id,department_id AS department
FROM employees
order by department

--ok--

SELECT employee_id,department_id AS "department"
FROM employees
order by department

--error on oracle--

so better to use AS without double quotation if you use ORDER BY clause

Credit card payment gateway in PHP?

The best solution we found was to team up with one of those intermediaries. Otherwise you will have to deal with a bunch of other requirements like PCI compliance. We use Verifone's IPCharge and it works quite well.

How do files get into the External Dependencies in Visual Studio C++?

The External Dependencies folder is populated by IntelliSense: the contents of the folder do not affect the build at all (you can in fact disable the folder in the UI).

You need to actually include the header (using a #include directive) to use it. Depending on what that header is, you may also need to add its containing folder to the "Additional Include Directories" property and you may need to add additional libraries and library folders to the linker options; you can set all of these in the project properties (right click the project, select Properties). You should compare the properties with those of the project that does build to determine what you need to add.

Spring Rest POST Json RequestBody Content type not supported

Be aware also if you have declared getters and setters for attributes of the parameter which are not sent in the POST (event if they are not declared in the constructor), for example:

@RestController
public class TestController {

    @RequestMapping(value = "/test", method = RequestMethod.POST)
    public String test(@RequestBody BeanTest beanTest) {
        return "Hello " + beanTest.getName();
    }


    public static class BeanTest {

        private Long id;
        private String name;

        public BeanTest() {
        }

        public BeanTest(Long id) {
            this.id = id;
        }

        public Long getId() {
            return id;
        }

        public void setId(Long id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}

A post request with the next structure: {"id":"1"} would not work, you must delete name get and set.

change the date format in laravel view page

Method One:

Using the strtotime() to time is the best format to change the date to the given format.

strtotime() - Parse about any English textual datetime description into a Unix timestamp

The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.

Example:

<?php
$timestamp = strtotime( "February 26, 2007" );  
print date('Y-m-d', $timestamp );
?>

Output:

2007-02-26

Method Two:

date_format() - Return a new DateTime object, and then format the date:

<?php
$date=date_create("2013-03-15");
echo date_format($date,"Y/m/d H:i:s");
?>

Output:

 2013/03/15 00:00:00 

What does the keyword "transient" mean in Java?

Google is your friend - first hit - also you might first have a look at what serialization is.

It marks a member variable not to be serialized when it is persisted to streams of bytes. When an object is transferred through the network, the object needs to be 'serialized'. Serialization converts the object state to serial bytes. Those bytes are sent over the network and the object is recreated from those bytes. Member variables marked by the java transient keyword are not transferred, they are lost intentionally.

Example from there, slightly modified (thanks @pgras):

public class Foo implements Serializable
 {
   private String saveMe;
   private transient String dontSaveMe;
   private transient String password;
   //...
 }

What is an MvcHtmlString and when should I use it?

You would use an MvcHtmlString if you want to pass raw HTML to an MVC helper method and you don't want the helper method to encode the HTML.

Iterating through struct fieldnames in MATLAB

You can use the for each toolbox from http://www.mathworks.com/matlabcentral/fileexchange/48729-for-each.

>> signal
signal = 
sin: {{1x1x25 cell}  {1x1x25 cell}}
cos: {{1x1x25 cell}  {1x1x25 cell}}

>> each(fieldnames(signal))
ans = 
CellIterator with properties:

NumberOfIterations: 2.0000e+000

Usage:

for bridge = each(fieldnames(signal))
   signal.(bridge) = rand(10);
end

I like it very much. Credit of course go to Jeremy Hughes who developed the toolbox.

Find stored procedure by name

When I have a Store Procedure name, and do not know which database it belongs to, I use the following -

Use [master]
GO

DECLARE @dbname VARCHAR(50)   
DECLARE @statement NVARCHAR(max)

DECLARE db_cursor CURSOR 
LOCAL FAST_FORWARD
FOR  
--Status 48 (mirrored db)
SELECT name FROM MASTER.dbo.sysdatabases WHERE STATUS NOT LIKE 48 AND name NOT IN ('master','model','msdb','tempdb','distribution')  

OPEN db_cursor  
FETCH NEXT FROM db_cursor INTO @dbname  
WHILE @@FETCH_STATUS = 0  
BEGIN  

SELECT @statement = 'SELECT * FROM ['+@dbname+'].INFORMATION_SCHEMA.ROUTINES  WHERE [ROUTINE_NAME] LIKE ''%name_of_proc%'''+';'
print @statement

EXEC sp_executesql @statement

FETCH NEXT FROM db_cursor INTO @dbname  
END  
CLOSE db_cursor  
DEALLOCATE db_cursor

window.location.href doesn't redirect

In my case it is working as expected for all browsers after setting time interval.

setTimeout(function(){document.location.href = "myNextPage.html;"},100);

How to add new column to MYSQL table?

You should look into normalizing your database to avoid creating columns at runtime.

Make 3 tables:

  1. assessment
  2. question
  3. assessment_question (columns assessmentId, questionId)

Put questions and assessments in their respective tables and link them together through assessment_question using foreign keys.

Form inside a form, is that alright?

No. HTML explicitly forbids nested forms.

From the HTML 5 draft:

Content model: Flow content, but with no form element descendants.

From the HTML 4.01 Recommendation:

<!ELEMENT FORM - - (%block;|SCRIPT)+ -(FORM) -- interactive form -->

(Note the -(FORM) section).

Compiling an application for use in highly radioactive environments

You may also be interested in the rich literature on the subject of algorithmic fault tolerance. This includes the old assignment: Write a sort that correctly sorts its input when a constant number of comparisons will fail (or, the slightly more evil version, when the asymptotic number of failed comparisons scales as log(n) for n comparisons).

A place to start reading is Huang and Abraham's 1984 paper "Algorithm-Based Fault Tolerance for Matrix Operations". Their idea is vaguely similar to homomorphic encrypted computation (but it is not really the same, since they are attempting error detection/correction at the operation level).

A more recent descendant of that paper is Bosilca, Delmas, Dongarra, and Langou's "Algorithm-based fault tolerance applied to high performance computing".

What is the worst programming language you ever worked with?

Objective-C.

The annotations are confusing, using brackets to call methods still does not compute in my brain, and what is worse is that all of the library functions from C are called using the standard operators in C, -> and ., and it seems like the only company that is driving this language is Apple.

I admit I have only used the language when programming for the iPhone (and looking into programming for OS X), but it feels as if C++ were merely forked, adding in annotations and forcing the implementation and the header files to be separate would make much more sense.

Java for loop multiple variables

Your for loop is wrong. Try :

for(int a = 0, b = 1; a<cards.length()-1; b=a+1, a++){

Also, System instead of system and == instead of ===.

But I'm not sure what you're trying to do.

Java Web Service client basic authentication

This worked for me:

 BindingProvider bp = (BindingProvider) port;
 Map<String, Object> map = bp.getRequestContext();
 map.put(BindingProvider.USERNAME_PROPERTY, "aspbbo");
 map.put(BindingProvider.PASSWORD_PROPERTY, "9FFFN6P");

What is the difference between the float and integer data type when the size is the same?

  • float stores floating-point values, that is, values that have potential decimal places
  • int only stores integral values, that is, whole numbers

So while both are 32 bits wide, their use (and representation) is quite different. You cannot store 3.141 in an integer, but you can in a float.

Dissecting them both a little further:

In an integer, all bits are used to store the number value. This is (in Java and many computers too) done in the so-called two's complement. This basically means that you can represent the values of −231 to 231 − 1.

In a float, those 32 bits are divided between three distinct parts: The sign bit, the exponent and the mantissa. They are laid out as follows:

S EEEEEEEE MMMMMMMMMMMMMMMMMMMMMMM

There is a single bit that determines whether the number is negative or non-negative (zero is neither positive nor negative, but has the sign bit set to zero). Then there are eight bits of an exponent and 23 bits of mantissa. To get a useful number from that, (roughly) the following calculation is performed:

M × 2E

(There is more to it, but this should suffice for the purpose of this discussion)

The mantissa is in essence not much more than a 24-bit integer number. This gets multiplied by 2 to the power of the exponent part, which, roughly, is a number between −128 and 127.

Therefore you can accurately represent all numbers that would fit in a 24-bit integer but the numeric range is also much greater as larger exponents allow for larger values. For example, the maximum value for a float is around 3.4 × 1038 whereas int only allows values up to 2.1 × 109.

But that also means, since 32 bits only have 4.2 × 109 different states (which are all used to represent the values int can store), that at the larger end of float's numeric range the numbers are spaced wider apart (since there cannot be more unique float numbers than there are unique int numbers). You cannot represent some numbers exactly, then. For example, the number 2 × 1012 has a representation in float of 1,999,999,991,808. That might be close to 2,000,000,000,000 but it's not exact. Likewise, adding 1 to that number does not change it because 1 is too small to make a difference in the larger scales float is using there.

Similarly, you can also represent very small numbers (between 0 and 1) in a float but regardless of whether the numbers are very large or very small, float only has a precision of around 6 or 7 decimal digits. If you have large numbers those digits are at the start of the number (e.g. 4.51534 × 1035, which is nothing more than 451534 follows by 30 zeroes – and float cannot tell anything useful about whether those 30 digits are actually zeroes or something else), for very small numbers (e.g. 3.14159 × 10−27) they are at the far end of the number, way beyond the starting digits of 0.0000...

Check folder size in Bash

if you just want to see the folder size and not the sub-folders, you can use:

du -hs /path/to/directory

Update:

You should know that du shows the used disk space; and not the file size.

You can use --apparent-size if u want to see sum of actual file sizes.

--apparent-size
      print  apparent  sizes,  rather  than  disk  usage; although the apparent size is usually smaller, it may be larger due to holes in ('sparse')
      files, internal fragmentation, indirect blocks, and the like

And of course theres no need for -h (Human readable) option inside a script.

Instead You can use -b for easier comparison inside script.

But You should Note that -b applies --apparent-size by itself. And it might not be what you need.

-b, --bytes
      equivalent to '--apparent-size --block-size=1'

so I think, you should use --block-size or -B

#!/bin/bash
SIZE=$(du -B 1 /path/to/directory | cut -f 1 -d "   ")    
# 2GB = 2147483648 bytes
# 10GB = 10737418240 bytes
if [[ $SIZE -gt 2147483648 && $SIZE -lt 10737418240 ]]; then
    echo 'Condition returned True'
fi

How do you synchronise projects to GitHub with Android Studio?

First time I have added a video link for solving your problem but I learned it was a bad idea. This time I'll explain it briefly.

Android studio is compatible with github but you need adjust something:

  1. Setup Android Studio
  2. Setup the Github plugins in the Android Studio settings

    • Android Studio settings >> Plugins page enter image description here
  3. Download the git version control system from this link and setup https://git-scm.com/

  4. After the installation, open Android Studio settings page and select the git.exe
    • settings >> version control >> git
    • Usually the path to git.exe is program files >> git >> bin >> git.exe
  5. Go to Settings >> Version control >> Github you will see login and password for your Github account. Apply the settings.
  6. For updating the project, go in Android Studio top line click VCS >> enable version control integration >> git
  7. One more time VCS >> import into version control >> share project on Github and enter your master password.

Now you can use VCS update buttons for updating your project to Github

Count items in a folder with PowerShell

Only Files

Get-ChildItem D:\ -Recurse -File | Measure-Object | %{$_.Count}

Only Folders

Get-ChildItem D:\ -Recurse -Directory | Measure-Object | %{$_.Count}

Both

Get-ChildItem D:\ -Recurse | Measure-Object | %{$_.Count}

How to do left join in Doctrine?

If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user, picked from your example), then the syntax is quite simple:

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin('a.user', 'u')
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

Since you are applying a condition on the joined result here, using a LEFT JOIN or simply JOIN is the same.

If no association is available, then the query looks like following

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin(
            'User\Entity\User',
            'u',
            \Doctrine\ORM\Query\Expr\Join::WITH,
            'a.user = u.id'
        )
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

This will produce a resultset that looks like following:

array(
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    // ...
)

Example to use shared_ptr?

Using a vector of shared_ptr removes the possibility of leaking memory because you forgot to walk the vector and call delete on each element. Let's walk through a slightly modified version of the example line-by-line.

typedef boost::shared_ptr<gate> gate_ptr;

Create an alias for the shared pointer type. This avoids the ugliness in the C++ language that results from typing std::vector<boost::shared_ptr<gate> > and forgetting the space between the closing greater-than signs.

    std::vector<gate_ptr> vec;

Creates an empty vector of boost::shared_ptr<gate> objects.

    gate_ptr ptr(new ANDgate);

Allocate a new ANDgate instance and store it into a shared_ptr. The reason for doing this separately is to prevent a problem that can occur if an operation throws. This isn't possible in this example. The Boost shared_ptr "Best Practices" explain why it is a best practice to allocate into a free-standing object instead of a temporary.

    vec.push_back(ptr);

This creates a new shared pointer in the vector and copies ptr into it. The reference counting in the guts of shared_ptr ensures that the allocated object inside of ptr is safely transferred into the vector.

What is not explained is that the destructor for shared_ptr<gate> ensures that the allocated memory is deleted. This is where the memory leak is avoided. The destructor for std::vector<T> ensures that the destructor for T is called for every element stored in the vector. However, the destructor for a pointer (e.g., gate*) does not delete the memory that you had allocated. That is what you are trying to avoid by using shared_ptr or ptr_vector.

Change the color of a checked menu item in a navigation drawer

Well you can achieve this using Color State Resource. If you notice inside your NavigationView you're using

app:itemIconTint="@color/black"
app:itemTextColor="@color/primary_text"

Here instead of using @color/black or @color/primary_test, use a Color State List Resource. For that, first create a new xml (e.g drawer_item.xml) inside color directory (which should be inside res directory.) If you don't have a directory named color already, create one.

Now inside drawer_item.xml do something like this

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="checked state color" android:state_checked="true" />
    <item android:color="your default color" />
</selector>

Final step would be to change your NavigationView

<android.support.design.widget.NavigationView
    android:id="@+id/activity_main_navigationview"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:headerLayout="@layout/drawer_header"
    app:itemIconTint="@color/drawer_item"  // notice here
    app:itemTextColor="@color/drawer_item" // and here
    app:itemBackground="@android:color/transparent"// and here for setting the background color to tranparent
    app:menu="@menu/menu_drawer">

Like this you can use separate Color State List Resources for IconTint, ItemTextColor, ItemBackground.

Now when you set an item as checked (either in xml or programmatically), the particular item will have different color than the unchecked ones.

How do I draw a set of vertical lines in gnuplot?

To elaborate on previous answers about the "every x units" part, here is what I came up with:

# Draw 5 vertical lines
n = 5

# ... evenly spaced between x0 and x1
x0 = 1.0
x1 = 2.0
dx = (x1-x0)/(n-1.0)

# ... each line going from y0 to y1
y0 = 0
y1 = 10

do for [i = 0:n-1] {
    x = x0 + i*dx
    set arrow from x,y0 to x,y1 nohead linecolor "blue" # add other styling options if needed
}

2D cross-platform game engine for Android and iOS?

I currently use Corona for business applications with great success. As far as games go, I'm under the impression that it doesn't provide the performance that some of the other cross-platform development engines do. It is worth noting that Carlos (founder of Ansca Mobile/Corona SDK) has started another company on a competing engine; Lanica Platino Engine for Appcelerator Titanium. While I haven't worked with this personally, it does look promising. Keep in mind, however, that it comes with a $999/yr price tag.

All that said, I have been researching Moai for a little while now (since I am already familiar with Lua syntax) and it does seem promising. The fact that it can compile for multiple platforms, not limited to mobile environments, is appealing.

Multimedia Fusion 2 is also a worth contender, considering the complexity of games produced and the performance realized from them. Vincere Totus Astrum (http://gamesare.com) comes to mind.

How do I disable TextBox using JavaScript?

Form elements can be accessed via the form's DOM element by name, not by "id" value. Give your form elements names if you want to access them like that, or else access them directly by "id" value:

document.getElementById("color").disabled = true;

edit — oh also, as pointed out by others, it's just "text", not "TextBox", for the "type" attribute.

You might want to invest a little time in reading some front-end development tutorials.

How to fix symbol lookup error: undefined symbol errors in a cluster environment

After two dozens of comments to understand the situation, it was found that the libhdf5.so.7 was actually a symlink (with several levels of indirection) to a file that was not shared between the queued processes and the interactive processes. This means even though the symlink itself lies on a shared filesystem, the contents of the file do not and as a result the process was seeing different versions of the library.

For future reference: other than checking LD_LIBRARY_PATH, it's always a good idea to check a library with nm -D to see if the symbols actually exist. In this case it was found that they do exist in interactive mode but not when run in the queue. A quick md5sum revealed that the files were actually different.

How to get duration, as int milli's and float seconds from <chrono>?

Is this what you're looking for?

#include <chrono>
#include <iostream>

int main()
{
    typedef std::chrono::high_resolution_clock Time;
    typedef std::chrono::milliseconds ms;
    typedef std::chrono::duration<float> fsec;
    auto t0 = Time::now();
    auto t1 = Time::now();
    fsec fs = t1 - t0;
    ms d = std::chrono::duration_cast<ms>(fs);
    std::cout << fs.count() << "s\n";
    std::cout << d.count() << "ms\n";
}

which for me prints out:

6.5e-08s
0ms

Search for all files in project containing the text 'querystring' in Eclipse

Yes, you can do this quite easily. Click on your project in the project explorer or Navigator, go to the Search menu at the top, click File..., input your search string, and make sure that 'Selected Resources' or 'Enclosing Projects' is selected, then hit search. The alternative way to open the window is with Ctrl-H. This may depend on your keyboard accelerator configuration.

More details: http://www.ehow.com/how_4742705_file-eclipse.html and http://www.avajava.com/tutorials/lessons/how-do-i-do-a-find-and-replace-in-multiple-files-in-eclipse.html

alt text
(source: avajava.com)

Java Singleton and Synchronization

Yes, it is necessary. There are several methods you can use to achieve thread safety with lazy initialization:

Draconian synchronization:

private static YourObject instance;

public static synchronized YourObject getInstance() {
    if (instance == null) {
        instance = new YourObject();
    }
    return instance;
}

This solution requires that every thread be synchronized when in reality only the first few need to be.

Double check synchronization:

private static final Object lock = new Object();
private static volatile YourObject instance;

public static YourObject getInstance() {
    YourObject r = instance;
    if (r == null) {
        synchronized (lock) {    // While we were waiting for the lock, another 
            r = instance;        // thread may have instantiated the object.
            if (r == null) {  
                r = new YourObject();
                instance = r;
            }
        }
    }
    return r;
}

This solution ensures that only the first few threads that try to acquire your singleton have to go through the process of acquiring the lock.

Initialization on Demand:

private static class InstanceHolder {
    private static final YourObject instance = new YourObject();
}

public static YourObject getInstance() {
    return InstanceHolder.instance;
}

This solution takes advantage of the Java memory model's guarantees about class initialization to ensure thread safety. Each class can only be loaded once, and it will only be loaded when it is needed. That means that the first time getInstance is called, InstanceHolder will be loaded and instance will be created, and since this is controlled by ClassLoaders, no additional synchronization is necessary.

MySQL InnoDB not releasing disk space after deleting data rows from table

Year back i also faced same problem on mysql5.7 version and ibdata1 occupied 150 Gb. so i added undo tablespaces

Take Mysqldump backup
Stop mysql service
Remove all data from data dir
Add below undo tablespace parameter in current my.cnf

 #undo tablespace
  innodb_undo_directory =  /var/lib/mysql/
  innodb_rollback_segments = 128 
  innodb_undo_tablespaces = 3
  innodb_undo_logs = 128  
  innodb_max_undo_log_size=1G
  innodb_undo_log_truncate = ON

Start mysql service
store mysqldump backup

Problem resolved !!

Is there a method that tells my program to quit?

In Python 3 there is an exit() function:

elif choice == "q":
    exit()

How do I use the Simple HTTP client in Android?

You can use like this:

public static String executeHttpPost1(String url,
            HashMap<String, String> postParameters) throws UnsupportedEncodingException {
        // TODO Auto-generated method stub

        HttpClient client = getNewHttpClient();

        try{
        request = new HttpPost(url);

        }
        catch(Exception e){
            e.printStackTrace();
        }


        if(postParameters!=null && postParameters.isEmpty()==false){

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(postParameters.size());
            String k, v;
            Iterator<String> itKeys = postParameters.keySet().iterator();
            while (itKeys.hasNext()) 
            {
                k = itKeys.next();
                v = postParameters.get(k);
                nameValuePairs.add(new BasicNameValuePair(k, v));
            }     

            UrlEncodedFormEntity urlEntity  = new  UrlEncodedFormEntity(nameValuePairs);
            request.setEntity(urlEntity);

        }
        try {


            Response = client.execute(request,localContext);
            HttpEntity entity = Response.getEntity();
            int statusCode = Response.getStatusLine().getStatusCode();
            Log.i(TAG, ""+statusCode);


            Log.i(TAG, "------------------------------------------------");





                try{
                    InputStream in = (InputStream) entity.getContent(); 
                    //Header contentEncoding = Response.getFirstHeader("Content-Encoding");
                    /*if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                        in = new GZIPInputStream(in);
                    }*/
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder str = new StringBuilder();
                    String line = null;
                    while((line = reader.readLine()) != null){
                        str.append(line + "\n");
                    }
                    in.close();
                    response = str.toString();
                    Log.i(TAG, "response"+response);
                }
                catch(IllegalStateException exc){

                    exc.printStackTrace();
                }


        } catch(Exception e){

            Log.e("log_tag", "Error in http connection "+response);         

        }
        finally {

        }

        return response;
    }

Laravel, sync() - how to sync an array and also pass additional pivot fields?

Simply just append your fields and their values to the elements:

$user->roles()->sync([
   1 => ['F1' => 'F1 Updated']
]);

EditText request focus

It has worked for me as follows.

ed1.requestFocus();

            return; //Faça um return para retornar o foco

How to place the cursor (auto focus) in text box when a page gets loaded without javascript support?

An expansion for those who did a bit of fiddling around like I did.

The following work (from W3):

<input type="text" autofocus />
<input type="text" autofocus="" />
<input type="text" autofocus="autofocus" />
<input type="text" autofocus="AuToFoCuS" />

It is important to note that this does not work in CSS though. I.e. you can't use:

.first-input {
    autofocus:"autofocus"
}

At least it didn't work for me...

Reading file input from a multipart/form-data POST

The guy who solved this posted it as LGPL and you're not allowed to modify it. I didn't even click on it when I saw that. Here's my version. This needs to be tested. There are probably bugs. Please post any updates. No warranty. You can modify this all you want, call it your own, print it out on a piece of paper and use it for kennel scrap, ... don't care.

using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;
using System.Web;

namespace DigitalBoundaryGroup
{
    class HttpNameValueCollection
    {
        public class File
        {
            private string _fileName;
            public string FileName { get { return _fileName ?? (_fileName = ""); } set { _fileName = value; } }

            private string _fileData;
            public string FileData { get { return _fileData ?? (_fileName = ""); } set { _fileData = value; } }

            private string _contentType;
            public string ContentType { get { return _contentType ?? (_contentType = ""); } set { _contentType = value; } }
        }

        private NameValueCollection _post;
        private Dictionary<string, File> _files;
        private readonly HttpListenerContext _ctx;

        public NameValueCollection Post { get { return _post ?? (_post = new NameValueCollection()); } set { _post = value; } }
        public NameValueCollection Get { get { return _ctx.Request.QueryString; } }
        public Dictionary<string, File> Files { get { return _files ?? (_files = new Dictionary<string, File>()); } set { _files = value; } }

        private void PopulatePostMultiPart(string post_string)
        {
            var boundary_index = _ctx.Request.ContentType.IndexOf("boundary=") + 9;
            var boundary = _ctx.Request.ContentType.Substring(boundary_index, _ctx.Request.ContentType.Length - boundary_index);

            var upper_bound = post_string.Length - 4;

            if (post_string.Substring(2, boundary.Length) != boundary)
                throw (new InvalidDataException());

            var current_string = new StringBuilder();

            for (var x = 4 + boundary.Length; x < upper_bound; ++x)
            {
                if (post_string.Substring(x, boundary.Length) == boundary)
                {
                    x += boundary.Length + 1;

                    var post_variable_string = current_string.Remove(current_string.Length - 4, 4).ToString();

                    var end_of_header = post_variable_string.IndexOf("\r\n\r\n");

                    if (end_of_header == -1) throw (new InvalidDataException());

                    var filename_index = post_variable_string.IndexOf("filename=\"", 0, end_of_header);
                    var filename_starts = filename_index + 10;
                    var content_type_starts = post_variable_string.IndexOf("Content-Type: ", 0, end_of_header) + 14;
                    var name_starts = post_variable_string.IndexOf("name=\"") + 6;
                    var data_starts = end_of_header + 4;

                    if (filename_index != -1)
                    {
                        var filename = post_variable_string.Substring(filename_starts, post_variable_string.IndexOf("\"", filename_starts) - filename_starts);
                        var content_type = post_variable_string.Substring(content_type_starts, post_variable_string.IndexOf("\r\n", content_type_starts) - content_type_starts);
                        var file_data = post_variable_string.Substring(data_starts, post_variable_string.Length - data_starts);
                        var name = post_variable_string.Substring(name_starts, post_variable_string.IndexOf("\"", name_starts) - name_starts);
                        Files.Add(name, new File() { FileName = filename, ContentType = content_type, FileData = file_data });
                    }
                    else
                    {
                        var name = post_variable_string.Substring(name_starts, post_variable_string.IndexOf("\"", name_starts) - name_starts);
                        var value = post_variable_string.Substring(data_starts, post_variable_string.Length - data_starts);
                        Post.Add(name, value);
                    }

                    current_string.Clear();
                    continue;
                }

                current_string.Append(post_string[x]);
            }
        }

        private void PopulatePost()
        {
            if (_ctx.Request.HttpMethod != "POST" || _ctx.Request.ContentType == null) return;

            var post_string = new StreamReader(_ctx.Request.InputStream, _ctx.Request.ContentEncoding).ReadToEnd();

            if (_ctx.Request.ContentType.StartsWith("multipart/form-data"))
                PopulatePostMultiPart(post_string);
            else
                Post = HttpUtility.ParseQueryString(post_string);

        }

        public HttpNameValueCollection(ref HttpListenerContext ctx)
        {
            _ctx = ctx;
            PopulatePost();
        }


    }
}

Android Percentage Layout Height

android:layout_weight=".YOURVALUE" is best way to implement in percentage

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

    <TextView
        android:id="@+id/logTextBox"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight=".20"
        android:maxLines="500"
        android:scrollbars="vertical"
        android:singleLine="false"
        android:text="@string/logText" >
    </TextView>

</LinearLayout>

What's the most useful and complete Java cheat sheet?

This Quick Reference looks pretty good if you're looking for a language reference. It's especially geared towards the user interface portion of the API.

For the complete API, however, I always use the Javadoc. I reference it constantly.

JavaScript: client-side vs. server-side validation

I will suggest to implement both client and server validation it keeps project more secure......if i have to choose one i will go with server side validation.

You can find some relevant information here https://web.archive.org/web/20131210085944/http://www.webexpertlabs.com/server-side-form-validation-using-regular-expression/

Python requests - print entire http request (raw)?

requests supports so called event hooks (as of 2.23 there's actually only response hook). The hook can be used on a request to print full request-response pair's data, including effective URL, headers and bodies, like:

import textwrap
import requests

def print_roundtrip(response, *args, **kwargs):
    format_headers = lambda d: '\n'.join(f'{k}: {v}' for k, v in d.items())
    print(textwrap.dedent('''
        ---------------- request ----------------
        {req.method} {req.url}
        {reqhdrs}

        {req.body}
        ---------------- response ----------------
        {res.status_code} {res.reason} {res.url}
        {reshdrs}

        {res.text}
    ''').format(
        req=response.request, 
        res=response, 
        reqhdrs=format_headers(response.request.headers), 
        reshdrs=format_headers(response.headers), 
    ))

requests.get('https://httpbin.org/', hooks={'response': print_roundtrip})

Running it prints:

---------------- request ----------------
GET https://httpbin.org/
User-Agent: python-requests/2.23.0
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive

None
---------------- response ----------------
200 OK https://httpbin.org/
Date: Thu, 14 May 2020 17:16:13 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 9593
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

<!DOCTYPE html>
<html lang="en">
...
</html>

You may want to change res.text to res.content if the response is binary.

Custom thread pool in Java 8 parallel stream

If you don't mind using a third-party library, with cyclops-react you can mix sequential and parallel Streams within the same pipeline and provide custom ForkJoinPools. For example

 ReactiveSeq.range(1, 1_000_000)
            .foldParallel(new ForkJoinPool(10),
                          s->s.filter(i->true)
                              .peek(i->System.out.println("Thread " + Thread.currentThread().getId()))
                              .max(Comparator.naturalOrder()));

Or if we wished to continue processing within a sequential Stream

 ReactiveSeq.range(1, 1_000_000)
            .parallel(new ForkJoinPool(10),
                      s->s.filter(i->true)
                          .peek(i->System.out.println("Thread " + Thread.currentThread().getId())))
            .map(this::processSequentially)
            .forEach(System.out::println);

[Disclosure I am the lead developer of cyclops-react]

Completely removing phpMyAdmin

If your system is using dpkg and apt (debian, ubuntu, etc), try running the following commands in that order (be careful with the sudo rm commands):

sudo apt-get -f install
sudo dpkg -P phpmyadmin  
sudo rm -vf /etc/apache2/conf.d/phpmyadmin.conf
sudo rm -vfR /usr/share/phpmyadmin
sudo service apache2 restart

Share Text on Facebook from Android App via ACTION_SEND

It appears that it's a bug in the Facebook app that was reported in April 2011 and has still yet to be fixed by the Android Facebook developers.

The only work around for the moment is to use their SDK.

How to disable submit button once it has been clicked?

 
    A better trick, so you don't lose the value of the button is

    function showwait() {
    document.getElementById('WAIT').style['display']='inline';
    document.getElementById('BUTTONS').style['display']='none';
    }
 

wrap code to show in a div

id=WAIT style="display:none"> text to display (end div)

wrap code to hide in a div

id=BUTTONS style="display:inline"> ... buttons or whatever to hide with
onclick="showwait();" (end div)

gradlew command not found?

First thing is you need to run the gradle task that you mentioned for this wrapper. Ex : gradle wrapper After running this command, check your directory for gradlew and gradlew.bat files. gradlew is the shell script file & can be used in linux/Mac OS. gradlew.bat is the batch file for windows OS. Then run,

./gradlew build (linux/mac). It will work.

Python element-wise tuple operations like sum

In case someone need to average a list of tuples:

import operator 
from functools import reduce
tuple(reduce(lambda x, y: tuple(map(operator.add, x, y)),list_of_tuples))

'Conda' is not recognized as internal or external command

Go To anaconda prompt(type "anaconda" in search box in your laptop). type following commands

where conda

add that location to your environment path variables. Close the cmd and open it again

How to programmatically clear application data

If you have just a couple of shared preferences to clear, then this solution is much nicer.

@Override
protected void setUp() throws Exception {
    super.setUp();
    Instrumentation instrumentation = getInstrumentation();
    SharedPreferences preferences = instrumentation.getTargetContext().getSharedPreferences(...), Context.MODE_PRIVATE);
    preferences.edit().clear().commit();
    solo = new Solo(instrumentation, getActivity());
}

How long will my session last?

In general you can say session.gc_maxlifetime specifies the maximum lifetime since the last change of your session data (not the last time session_start was called!). But PHP’s session handling is a little bit more complicated.

Because the session data is removed by a garbage collector that is only called by session_start with a probability of session.gc_probability devided by session.gc_divisor. The default values are 1 and 100, so the garbage collector is only started in only 1% of all session_start calls. That means even if the the session is already timed out in theory (the session data had been changed more than session.gc_maxlifetime seconds ago), the session data can be used longer than that.

Because of that fact I recommend you to implement your own session timeout mechanism. See my answer to How do I expire a PHP session after 30 minutes? for more details.

How to check if array is empty or does not exist?

You want to do the check for undefined first. If you do it the other way round, it will generate an error if the array is undefined.

if (array === undefined || array.length == 0) {
    // array empty or does not exist
}

Update

This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null values, other types of objects with a length property, etc. It is also not very idiomatic JavaScript.

The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length property.

if (!Array.isArray(array) || !array.length) {
  // array does not exist, is not an array, or is empty
  // ? do not attempt to process array
}

To break it down:

  1. Array.isArray(), unsurprisingly, checks whether its argument is an array. This weeds out values like null, undefined and anything else that is not an array.
    Note that this will also eliminate array-like objects, such as the arguments object and DOM NodeList objects. Depending on your situation, this might not be the behavior you're after.

  2. The array.length condition checks whether the variable's length property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0 or array.length !== 0 are not required here.

The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.

In those cases, I tend to go for the following, more idiomatic JavaScript:

if (!array || !array.length) {
    // array or array.length are falsy
    // ? do not attempt to process array
}

Or, more frequently, its inverse:

if (array && array.length) {
    // array and array.length are truthy
    // ? probably OK to process array
}

With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:

if (!array?.length) {
    // array or array.length are falsy
    // ? do not attempt to process array
}

Or the opposite:

if (array?.length) {
    // array and array.length are truthy
    // ? probably OK to process array
}

How to check if current thread is not main thread

The best way is the clearest, most robust way: *

Thread.currentThread().equals( Looper.getMainLooper().getThread() )

Or, if the runtime platform is API level 23 (Marshmallow 6.0) or higher:

Looper.getMainLooper().isCurrentThread()

See the Looper API. Note that calling Looper.getMainLooper() involves synchronization (see the source). You might want to avoid the overhead by storing the return value and reusing it.

   * credit greg7gkb and 2cupsOfTech

Key Presses in Python

PyAutoGui also lets you press a button multiple times:

pyautogui.press('tab', presses=5)   # press TAB five times in a row

pyautogui.press('A', presses=1000)   # press A a thousand times in a row

Difference between webdriver.Dispose(), .Close() and .Quit()

close() is a webdriver command which closes the browser window which is currently in focus. Despite the familiar name for this method, WebDriver does not implement the AutoCloseable interface.

During the automation process, if there are more than one browser window opened, then the close() command will close only the current browser window which is having focus at that time. The remaining browser windows will not be closed. The following code can be used to close the current browser window:

quit() is a webdriver command which calls the driver.dispose method, which in turn closes all the browser windows and terminates the WebDriver session. If we do not use quit() at the end of program, the WebDriver session will not be closed properly and the files will not be cleared off memory. This may result in memory leak errors.

If the Automation process opens only a single browser window, the close() and quit() commands work in the same way. Both will differ in their functionality when there are more than one browser window opened during Automation.

For Above Ref : click here

Dispose Command Dispose() should call Quit(), and it appears it does. However, it also has the same problem in that any subsequent actions are blocked until PhantomJS is manually closed.

Ref Link

Mapping over values in a python dictionary

These toolz are great for this kind of simple yet repetitive logic.

http://toolz.readthedocs.org/en/latest/api.html#toolz.dicttoolz.valmap

Gets you right where you want to be.

import toolz
def f(x):
  return x+1

toolz.valmap(f, my_list)

jquery ui Dialog: cannot call methods on dialog prior to initialization

So you use this:

var theDialog = $("#divDialog").dialog(opt);
theDialog.dialog("open");

and if you open a MVC Partial View in Dialog, you can create in index a hidden button and JQUERY click event:

$("#YourButton").click(function()
{
   theDialog.dialog("open");
   OR
   theDialog.dialog("close");
});

then inside partial view html you call button trigger click like:

$("#YouButton").trigger("click")

see ya.

How to kill a child process by the parent process?

Send a SIGTERM or a SIGKILL to it:

http://en.wikipedia.org/wiki/SIGKILL

http://en.wikipedia.org/wiki/SIGTERM

SIGTERM is polite and lets the process clean up before it goes, whereas, SIGKILL is for when it won't listen >:)

Example from the shell (man page: http://unixhelp.ed.ac.uk/CGI/man-cgi?kill )

kill -9 pid

In C, you can do the same thing using the kill syscall:

kill(pid, SIGKILL);

See the following man page: http://linux.die.net/man/2/kill

1064 error in CREATE TABLE ... TYPE=MYISAM

Try the below query

CREATE TABLE card_types (
  card_type_id int(11) NOT NULL auto_increment,
  name varchar(50) NOT NULL default '',
  PRIMARY KEY  (card_type_id),
) ENGINE = MyISAM ;

Spring: How to inject a value to static field?

Spring uses dependency injection to populate the specific value when it finds the @Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.

    @RestController 
//or if you want to declare some specific use of the properties file then use
//@Configuration
//@PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {

    @Value("${name}")//not necessary
    private String name;//not necessary

    private static String NAME_STATIC;

    @Value("${name}")
    public void setNameStatic(String name){
        PropertyController.NAME_STATIC = name;
    }
}

Visual studio code terminal, how to run a command with administrator rights?

Step 1: Restart VS Code as an adminstrator

(click the windows key, search for "Visual Studio Code", right click, and you'll see the administrator option)

Step 2: In your VS code powershell terminal run Set-ExecutionPolicy Unrestricted

Mixing a PHP variable with a string literal

echo "{$test}y";

You can use braces to remove ambiguity when interpolating variables directly in strings.

Also, this doesn't work with single quotes. So:

echo '{$test}y';

will output

{$test}y

Requery a subform from another form?

I had a similar kind of issue, but with some differences...

In my case, my main form has a Control (vendor) which value I used to update a Query in my DB, using the following code:

Sub Set_Qry_PedidosRealizadosImportados_frm(Vd As Long)
Dim temp_qry As DAO.QueryDef

'Procedimento para ajustar o codigo do cliente na Qry_Pedidos realizados e importados
'Procedure to adjust the code of the client on Qry_Pedidos realizados e importados
Set temp_qry = CurrentDb.QueryDefs("Qry_Pedidos realizados e importados")
temp_qry.SQL = "SELECT DISTINCT " & _
            "[Qry_Pedidos distintos].[Codigo], " & _
            "[Qry_Pedidos distintos].[Razao social], " & _
            "COUNT([Qry_Pedidos distintos].[Pedido Avante]) As [Pedidos realizados], " & _
            "SUM(IIf(NZ([Qry_Pedidos distintos].[Pedido Flexx], 0) > 1, 1, 0)) As [Pedidos Importados] " & _
            "FROM [Qry_Pedidos distintos] " & _
            "WHERE [Qry_Pedidos distintos].Vd = " & Vd & _
            " Group BY " & _
            "[Qry_Pedidos distintos].[Razao social], " & _
            "[Qry_Pedidos distintos].[Codigo];"
End Sub

Since the beginning my subform record source was the query named "Qry_Pedidos realizados e importados".

But the only way I could update the subform data inside the main form context was to refresh the data source of the subform to it self, like posted bellow:

Private Sub cmb_vendedor_v1_Exit(Cancel As Integer)
'Codigo para atualizar o comando SQL da query
'Code to update the SQL statement of the query 
    Call Set_Qry_Pedidosrealizadosimportados_frm(Me.cmb_vendedor_v1.Value)

'Codigo para forçar o Access a aceitar o novo comando SQL
'Code to force de Access to accept the new sql statement
    Me!Frm_Pedidos_realizados_importados.Form.RecordSource = "Qry_Pedidos realizados e importados"
End Sub

No refresh, recalc, requery, etc, was necessary after all...

Is there an online application that automatically draws tree structures for phrases/sentences?

There are lots of options out there. Many of which are available as downloadable software as well as public websites. I do not think many of them expect to be used as API's unless they explicitly state that.

The one that I found effective was Enju which did not have the character limit that the Marc's Carnagie Mellon link had. Marc also mentioned a VISL scanner in comments, but that requires java in the browser, which is a non-starter for me.

Note that recently, Google has offered a new NLP Machine Learning API that providers amoung other features, a automatic sentence parser. I will likely not update this answer again, especially since the question is closed, but I suspect that the other big ML cloud stacks will soon support the same.

create array from mysql query php

You could also make life easier using a wrapper, e.g. with ADODb:

$myarray=$db->GetCol("SELECT type FROM cars ".
    "WHERE owner=? and selling=0", 
    array($_SESSION['username']));

A good wrapper will do all your escaping for you too, making things easier to read.

Left/Right float button inside div

You can use justify-content: space-between in .test like so:

_x000D_
_x000D_
.test {_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
  width: 20rem;_x000D_
  border: .1rem red solid;_x000D_
}
_x000D_
<div class="test">_x000D_
  <button>test</button>_x000D_
  <button>test</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_


For those who want to use Bootstrap 4 can use justify-content-between:

_x000D_
_x000D_
div {_x000D_
  width: 20rem;_x000D_
  border: .1rem red solid;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="d-flex justify-content-between">_x000D_
  <button>test</button>_x000D_
  <button>test</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jQuery scrollTop not working in Chrome but working in Firefox

It works in both browsers if you use scrollTop() with 'document':

$(document).scrollTop();

...instead of 'html' or 'body'. Other way it won't work at the same time in both browsers.

JNZ & CMP Assembly Instructions

JNZ is short for "Jump if not zero (ZF = 0)", and NOT "Jump if the ZF is set".

If it's any easier to remember, consider that JNZ and JNE (jump if not equal) are equivalent. Therefore, when you're doing cmp al, 47 and the content of AL is equal to 47, the ZF is set, ergo the jump (if Not Equal - JNE) should not be taken.

Share link on Google+

Yes, you can.

https://plus.google.com/share?url=YOUR_URL_HERE

Edit: It works only with eff.org.

Edit: As of March 2012 it works on all sites.

Documentation for this sharing method is available on the Google Developers site.

How to add to an existing hash in Ruby

x = {:ca => "Canada", :us => "United States"}
x[:de] = "Germany"
p x

How to round up a number to nearest 10?

I was actually searching for a function that could round to the nearest variable, and this page kept coming up in my searches. So when I finally ended up writing the function myself, I thought I would post it here for others to find.

The function will round to the nearest variable:

function roundToTheNearestAnything($value, $roundTo)
{
    $mod = $value%$roundTo;
    return $value+($mod<($roundTo/2)?-$mod:$roundTo-$mod);
}

This code:

echo roundToTheNearestAnything(1234, 10).'<br>';
echo roundToTheNearestAnything(1234, 5).'<br>';
echo roundToTheNearestAnything(1234, 15).'<br>';
echo roundToTheNearestAnything(1234, 167).'<br>';

Will output:

1230
1235
1230
1169

Adding click event for a button created dynamically using jQuery

Question 1: Use .delegate on the div to bind a click handler to the button.

Question 2: Use $(this).val() or this.value (the latter would be faster) inside of the click handler. this will refer to the button.

$("#pg_menu_content").on('click', '#btn_a', function () {
  alert($(this).val());
});

$div = $('<div data-role="fieldcontain"/>');
$("<input type='button' value='Dynamic Button' id='btn_a' />").appendTo($div.clone()).appendTo('#pg_menu_content');

How to check if X server is running?

xprop -root &> /dev/null 

...is my tried & true command to test for an "X-able" situation. And, it's pretty much guaranteed to be on any system running X, of course, the command fails if not found anyways, so even if it doesnt exist, you can pretty much assume there is no X either. (thats why I use &> instead of >)

What is the difference between using constructor vs getInitialState in React / React Native?

Constructor The constructor is a method that's automatically called during the creation of an object from a class. ... Simply put, the constructor aids in constructing things. In React, the constructor is no different. It can be used to bind event handlers to the component and/or initializing the local state of the component.Jan 23, 2019

getInitialState In ES6 classes, you can define the initial state by assigning this.state in the constructor:

Look at this example

var Counter = createReactClass({
  getInitialState: function() {
    return {count: this.props.initialCount};
  },
  // ...
});

With createReactClass(), you have to provide a separate getInitialState method that returns the initial state:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

May be its irrelevant answer but its working in my case...don't know what was wrong on my server...I just enable error log on Ubuntu 16.04 server.

//For PHP
error_reporting(E_ALL);
ini_set('display_errors', 1);

How do I get java logging output to appear on a single line?

I've figured out a way that works. You can subclass SimpleFormatter and override the format method

    public String format(LogRecord record) {
        return new java.util.Date() + " " + record.getLevel() + " " + record.getMessage() + "\r\n";
    }

A bit surprised at this API I would have thought that more functionality/flexibility would have been provided out of the box

Bitbucket git credentials if signed up with Google

Update as at September, 2019:

This whole process is now way easier than it used to be. It doesn't matter if your auth style is regular or Google-dependent, it works regardless. Follow these four easy steps:

  • Visit this link and enter your email.
  • Check your mail for the reactivation email and click the big blue button therein.
  • Change your password!

I hope this helps. Merry coding!

How to open a folder in Windows Explorer from VBA?

You can use the following code to open a file location from vba.

Dim Foldername As String
Foldername = "\\server\Instructions\"

Shell "C:\WINDOWS\explorer.exe """ & Foldername & "", vbNormalFocus

You can use this code for both windows shares and local drives.

VbNormalFocus can be swapper for VbMaximizedFocus if you want a maximized view.

DataGridView - how to set column width?

Use:

yourdataView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);

Restore a postgres backup file using the command line?

try this:

psql -U <username> -d <dbname> -f <filename>.sql

Restore DB psql from .sql file

Javascript how to split newline

It should be

yadayada.val.split(/\n/)

you're passing in a literal string to the split command, not a regex.

Class has no objects member

If you use python 3

python3 -m pip install pylint-django

If python < 3

python -m pip install pylint-django==0.11.1

NOTE: Version 2.0, requires pylint >= 2.0 which doesn’t support Python 2 anymore! (https://pypi.org/project/pylint-django/)

How to time Java program execution speed

Using System.currentTimeMillis() is the proper way of doing this. But, if you use command line, and you want to time the whole program approximately and quickly, think about:

time java App

which allows you not to modify the code and time your App.

Adding Only Untracked Files

If you have thousands of untracked files (ugh, don't ask) then git add -i will not work when adding *. You will get an error stating Argument list too long.

If you then also are on Windows (don't ask #2 :-) and need to use PowerShell for adding all untracked files, you can use this command:

git ls-files -o --exclude-standard | select | foreach { git add $_ }

How to check encoding of a CSV file

If you use Python, just use a print() function to check the encoding of a csv file. For example:

with open('file_name.csv') as f:
    print(f)

The output is something like this:

<_io.TextIOWrapper name='file_name.csv' mode='r' encoding='utf8'>

How to concatenate strings of a string field in a PostgreSQL 'group by' query?

I'm using Jetbrains Rider and it was a hassle copying the results from above examples to re-execute because it seemed to wrap it all in JSON. This joins them into a single statement that was easier to run

select string_agg('drop table if exists "' || tablename || '" cascade', ';') 
from pg_tables where schemaname != $$pg_catalog$$ and tableName like $$rm_%$$

Print multiple arguments in Python

print("Total score for %s is %s  " % (name, score))

%s can be replace by %d or %f

How can I shuffle the lines of a text file on the Unix command line or in a shell script?

Another awk variant:

#!/usr/bin/awk -f
# usage:
# awk -f randomize_lines.awk lines.txt
# usage after "chmod +x randomize_lines.awk":
# randomize_lines.awk lines.txt

BEGIN {
  FS = "\n";
  srand();
}

{
  lines[ rand()] = $0;
}

END {
  for( k in lines ){
    print lines[k];
  }
}

How to get annotations of a member variable?

Everybody describes issue with getting annotations, but the problem is in definition of your annotation. You should to add to your annotation definition a @Retention(RetentionPolicy.RUNTIME):

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAnnotation{
    int id();
}

Is it possible to save HTML page as PDF using JavaScript or jquery?

In short: no. The first problem is access to the filesystem, which in most browsers is set to no by default due to security reasons. Modern browsers sometimes support minimalistic storage in the form of a database, or you can ask the user to enable file access.

If you have access to the filesystem then saving as HTML is not that hard (see the file object in the JS documentation) - but PDF is not so easy. PDF is a quite advanced file-format that really is ill suited for Javascript. It requires you to write information in datatypes not directly supported by Javascript, such as words and quads. You also need to pre-define a dictionary lookup system that must be saved to the file. Im sure someone could make it work, but the effort and time involved would be better spent learning C++ or Delphi.

HTML export however should be possible if the user gives you non restricted access

Android: Color To Int conversion

R.color.black or some color are obviously integers. It needs a RGB value. You can give your own like #FF123454 which represents various primary colors

Iterate over the lines of a string

I'm not sure what you mean by "then again by the parser". After the splitting has been done, there's no further traversal of the string, only a traversal of the list of split strings. This will probably actually be the fastest way to accomplish this, so long as the size of your string isn't absolutely huge. The fact that python uses immutable strings means that you must always create a new string, so this has to be done at some point anyway.

If your string is very large, the disadvantage is in memory usage: you'll have the original string and a list of split strings in memory at the same time, doubling the memory required. An iterator approach can save you this, building a string as needed, though it still pays the "splitting" penalty. However, if your string is that large, you generally want to avoid even the unsplit string being in memory. It would be better just to read the string from a file, which already allows you to iterate through it as lines.

However if you do have a huge string in memory already, one approach would be to use StringIO, which presents a file-like interface to a string, including allowing iterating by line (internally using .find to find the next newline). You then get:

import StringIO
s = StringIO.StringIO(myString)
for line in s:
    do_something_with(line)

Function to Calculate a CRC16 Checksum

There are several different varieties of CRC-16. See wiki page.

Every of those will return different results from the same input.

So you must carefully select correct one for your program.

How do I get an object's unqualified (short) class name?

$shortClassName = join('',array_slice(explode('\\', $longClassName), -1));

Excel SUMIF between dates

One more solution when you want to use data from any sell ( in the key C3)

=SUMIF(Sheet6!M:M;CONCATENATE("<";TEXT(C3;"dd.mm.yyyy"));Sheet6!L:L)

Javascript (+) sign concatenates instead of giving sum of variables

using braces surrounding the numbers will treat as addition instead of concat.

divID = "question-" + (i+1)

What is the significance of url-pattern in web.xml and how to configure servlet?

Servlet-mapping has two child tags, url-pattern and servlet-name. url-pattern specifies the type of urls for which, the servlet given in servlet-name should be called. Be aware that, the container will use case-sensitive for string comparisons for servlet matching.

First specification of url-pattern a web.xml file for the server context on the servlet container at server .com matches the pattern in <url-pattern>/status/*</url-pattern> as follows:

http://server.com/server/status/synopsis               = Matches
http://server.com/server/status/complete?date=today    = Matches
http://server.com/server/status                        = Matches
http://server.com/server/server1/status                = Does not match

Second specification of url-pattern A context located at the path /examples on the Agent at example.com matches the pattern in <url-pattern>*.map</url-pattern> as follows:

 http://server.com/server/US/Oregon/Portland.map    = Matches
 http://server.com/server/US/server/Seattle.map     = Matches
 http://server.com/server/Paris.France.map          = Matches
 http://server.com/server/US/Oregon/Portland.MAP    = Does not match, the extension is uppercase
 http://example.com/examples/interface/description/mail.mapi  =Does not match, the extension is mapi rather than map`

Third specification of url-mapping,A mapping that contains the pattern <url-pattern>/</url-pattern> matches a request if no other pattern matches. This is the default mapping. The servlet mapped to this pattern is called the default servlet.

The default mapping is often directed to the first page of an application. Explicitly providing a default mapping also ensures that malformed URL requests into the application return are handled by the application rather than returning an error.

The servlet-mapping element below maps the server servlet instance to the default mapping.

<servlet-mapping>
  <servlet-name>server</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>

For the context that contains this element, any request that is not handled by another mapping is forwarded to the server servlet.

And Most importantly we should Know about Rule for URL path mapping

  1. The container will try to find an exact match of the path of the request to the path of the servlet. A successful match selects the servlet.
  2. The container will recursively try to match the longest path-prefix. This is done by stepping down the path tree a directory at a time, using the ’/’ character as a path separator. The longest match determines the servlet selected.
  3. If the last segment in the URL path contains an extension (e.g. .jsp), the servlet container will try to match a servlet that handles requests for the extension. An extension is defined as the part of the last segment after the last ’.’ character.
  4. If neither of the previous three rules result in a servlet match, the container will attempt to serve content appropriate for the resource requested. If a “default” servlet is defined for the application, it will be used.

Reference URL Pattern

How to enable remote access of mysql in centos?

Bind-address XXX.XX.XX.XXX in /etc/my.cnf

comment line:

skip-networking

or

skip-external-locking

after edit hit service mysqld restart

login into mysql and hit this query:

GRANT ALL PRIVILEGES ON dbname.* TO 'username'@'%' IDENTIFIED BY 'password';

FLUSH PRIVILEGES;
quit;

add firewall rule:

iptables -I INPUT -i eth0 -p tcp --destination-port 3306 -j ACCEPT

AngularJS: Basic example to use authentication in Single Page Application

_x000D_
_x000D_
var _login = function (loginData) {_x000D_
 _x000D_
        var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password;_x000D_
 _x000D_
        var deferred = $q.defer();_x000D_
 _x000D_
        $http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response) {_x000D_
 _x000D_
            localStorageService.set('authorizationData', { token: response.access_token, userName: loginData.userName });_x000D_
 _x000D_
            _authentication.isAuth = true;_x000D_
            _authentication.userName = loginData.userName;_x000D_
 _x000D_
            deferred.resolve(response);_x000D_
 _x000D_
        }).error(function (err, status) {_x000D_
            _logOut();_x000D_
            deferred.reject(err);_x000D_
        });_x000D_
 _x000D_
        return deferred.promise;_x000D_
 _x000D_
    };_x000D_
 
_x000D_
_x000D_
_x000D_

Open link in new tab or window

It shouldn't be your call to decide whether the link should open in a new tab or a new window, since ultimately this choice should be done by the settings of the user's browser. Some people like tabs; some like new windows.

Using _blank will tell the browser to use a new tab/window, depending on the user's browser configuration and how they click on the link (e.g. middle click, Ctrl+click, or normal click).

AWS - Disconnected : No supported authentication methods available (server sent :publickey)

For me this error appeared immediatey after I changed the user's home directory by

sudo usermod -d var/www/html username

It can also happen because of lack of proper permission to authorized_key file in ~/.ssh. Make sure the permission of this file is 0600 and permission of ~/.ssh is 700.

What uses are there for "placement new"?

I have an idea too. C++ does have zero-overhead principle. But exceptions do not follow this principle, so sometimes they are turned off with compiler switch.

Let's look to this example:

#include <new>
#include <cstdio>
#include <cstdlib>

int main() {
    struct A {
        A() {
            printf("A()\n");
        }
        ~A() {
            printf("~A()\n");
        }
        char data[1000000000000000000] = {}; // some very big number
    };

    try {
        A *result = new A();
        printf("new passed: %p\n", result);
        delete result;
    } catch (std::bad_alloc) {
        printf("new failed\n");
    }
}

We allocate a big struct here, and check if allocation is successful, and delete it.

But if we have exceptions turned off, we can't use try block, and unable to handle new[] failure.

So how we can do that? Here is how:

#include <new>
#include <cstdio>
#include <cstdlib>

int main() {
    struct A {
        A() {
            printf("A()\n");
        }
        ~A() {
            printf("~A()\n");
        }
        char data[1000000000000000000] = {}; // some very big number
    };

    void *buf = malloc(sizeof(A));
    if (buf != nullptr) {
        A *result = new(buf) A();
        printf("new passed: %p\n", result);
        result->~A();
        free(result);
    } else {
        printf("new failed\n");
    }
}
  • Use simple malloc
  • Check if it is failed in a C way
  • If it successful, we use placement new
  • Manually call the destructor (we can't just call delete)
  • call free, due we called malloc

UPD @Useless wrote a comment which opened to my view the existence of new(nothrow), which should be used in this case, but not the method I wrote before. Please don't use the code I wrote before. Sorry.

What's the difference between primitive and reference types?

Primitives vs. References

First :-

Primitive types are the basic types of data: byte, short, int, long, float, double, boolean, char. Primitive variables store primitive values. Reference types are any instantiable class as well as arrays: String, Scanner, Random, Die, int[], String[], etc. Reference variables store addresses to locations in memory for where the data is stored.

Second:-

Primitive types store values but Reference type store handles to objects in heap space. Remember, reference variables are not pointers like you might have seen in C and C++, they are just handles to objects, so that you can access them and make some change on object's state.

Read more: http://javarevisited.blogspot.com/2015/09/difference-between-primitive-and-reference-variable-java.html#ixzz3xVBhi2cr

Spring MVC UTF-8 Encoding

right-click to your controller.java then properties and check if your text file is encoded with utf-8, if not this is your mistake.

how do I query sql for a latest record date for each user

From my experience the fastest way is to take each row for which there is no newer row in the table.

Another advantage is that the syntax used is very simple, and that the meaning of the query is rather easy to grasp (take all rows such that no newer row exists for the username being considered).

NOT EXISTS

SELECT username, value
FROM t
WHERE NOT EXISTS (
  SELECT *
  FROM t AS witness
  WHERE witness.username = t.username AND witness.date > t.date
);

ROW_NUMBER

SELECT username, value
FROM (
  SELECT username, value, row_number() OVER (PARTITION BY username ORDER BY date DESC) AS rn
  FROM t
) t2
WHERE rn = 1

INNER JOIN

SELECT t.username, t.value
FROM t
INNER JOIN (
  SELECT username, MAX(date) AS date
  FROM t
  GROUP BY username
) tm ON t.username = tm.username AND t.date = tm.date;

LEFT OUTER JOIN

SELECT username, value
FROM t
LEFT OUTER JOIN t AS w ON t.username = w.username AND t.date < w.date
WHERE w.username IS NULL

Batch files - number of command line arguments

The last answer was two years ago now, but I needed a version for more than nine command line arguments. May be another one also does...

@echo off
setlocal

set argc_=1
set arg0_=%0
set argv_=

:_LOOP
set arg_=%1
if defined arg_ (
  set arg%argc_%_=%1
  set argv_=%argv_% %1
  set /a argc_+=1
  shift
  goto _LOOP
)
::dont count arg0
set /a argc_-=1
echo %argc_% arg(s)

for /L %%i in (0,1,%argc_%) do (
  call :_SHOW_ARG arg%%i_ %%arg%%i_%%
)

echo converted to local args
call :_LIST_ARGS %argv_%
exit /b


:_LIST_ARGS
setlocal
set argc_=0
echo arg0=%0

:_LOOP_LIST_ARGS
set arg_=%1
if not defined arg_ exit /b
set /a argc_+=1
call :_SHOW_ARG arg%argc_% %1
shift
goto _LOOP_LIST_ARGS


:_SHOW_ARG
echo %1=%2
exit /b

The solution is the first 19 lines and converts all arguments to variables in a c-like style. All other stuff just probes the result and shows conversion to local args. You can reference arguments by index in any function.