Programs & Examples On #Configurationelement

I'm getting the "missing a using directive or assembly reference" and no clue what's going wrong

Your using statements appear to be correct.

Are you, perhaps, missing the assembly reference to System.configuration.dll?

Right click the "References" folder in your project and click on "Add Reference..."

Eclipse will not start and I haven't changed anything

Read my answer if recently you have been using a VPN connection.

Today I had the same exact issue and learned how to fix it without removing any plugins. So I thought maybe I would share my own experience.

My issue definitely had something to do with Spring Framework

I was using a VPN connection over my internet connection. Once I disconnected my VPN, everything instantly turned right.

How to implement a ConfigurationSection with a ConfigurationElementCollection

Try inheriting from ConfigurationSection. This blog post by Phil Haack has an example.

Confirmed, per the documentation for IConfigurationSectionHandler:

In .NET Framework version 2.0 and above, you must instead derive from the ConfigurationSection class to implement the related configuration section handler.

Android Studio doesn't recognize my device

Change the connection method Build-In CD ROM it works for me

How to change date format using jQuery?

I dont think you need to use jQuery at all, just simple JavaScript...

Save the date as a string:

dte = fecha.value;//2014-01-06

Split the string to get the day, month & year values...

dteSplit = dte.split("-");
yr = dteSplit[0][2] + dteSplit[0][3]; //special yr format, take last 2 digits
month = dteSplit[1];
day = dteSplit[2];

Rejoin into final date string:

finalDate = month+"-"+day+"-"+year

Remove Fragment Page from ViewPager in Android

For future readers!

Now you can use ViewPager2 for dynamically adding, removing fragment from the viewpager.

Quoting form API reference

ViewPager2 replaces ViewPager, addressing most of its predecessor’s pain-points, including right-to-left layout support, vertical orientation, modifiable Fragment collections, etc.

Take look at MutableCollectionFragmentActivity.kt in googlesample/android-viewpager2 for an example of adding, removing fragments dynamically from the viewpager.


For your information:

Articles:

API reference

Release notes

Samples Repo: https://github.com/googlesamples/android-viewpager2

web-api POST body object always null

I just ran into this and was frustrating. My setup: The header was set to Content-Type: application/JSON and was passing the info from the body with JSON format, and was reading [FromBody] on the controller.

Everything was set up fine and I expect it to work, but the problem was with the JSON sent over. Since it was a complex structure, one of my classes which was defined 'Abstract' was not getting initialized and hence the values weren't assigned to the model properly. I removed the abstract keyword and it just worked..!!!

One tip, the way I could figure this out was to send data in parts to my controller and check when it becomes null... since it was a complex model I was appending one model at a time to my request params. Hope it helps someone who runs into this stupid issue.

How to Compare two strings using a if in a stored procedure in sql server 2008?

declare @temp as varchar
  set @temp='Measure'
  if(@temp = 'Measure')
Select Measure from Measuretable
else
Select OtherMeasure from Measuretable

What does %~d0 mean in a Windows batch file?

%~d0 gives you the drive letter of argument 0 (the script name), %~p0 the path.

Working with select using AngularJS's ng-options

I hope the following will work for you.

<select class="form-control"
        ng-model="selectedOption"
        ng-options="option.name + ' (' + (option.price | currency:'USD$') + ')' for option in options">
</select>

Is there a way to get a collection of all the Models in your Rails app?

Here's a solution that has been vetted with a complex Rails app (the one powering Square)

def all_models
  # must eager load all the classes...
  Dir.glob("#{RAILS_ROOT}/app/models/**/*.rb") do |model_path|
    begin
      require model_path
    rescue
      # ignore
    end
  end
  # simply return them
  ActiveRecord::Base.send(:subclasses)
end

It takes the best parts of the answers in this thread and combines them in the simplest and most thorough solution. This handle cases where your models are in subdirectories, use set_table_name etc.

How can I output leading zeros in Ruby?

Use String#next as the counter.

>> n = "000"
>> 3.times { puts "file_#{n.next!}" }
file_001
file_002
file_003

next is relatively 'clever', meaning you can even go for

>> n = "file_000"
>> 3.times { puts n.next! }
file_001
file_002
file_003

how to declare global variable in SQL Server..?

You can get a similar result by creating scalar-valued functions that return the variable values. Of course, function calls can be expensive if you use them in queries that return a large number of results, but if you're limiting the result-set you should be fine. Here I'm using a database created just to hold these semi-static values, but you can create them on a per-database basis, too. As you can see, there are no input variables, just a well-named function that returns a static value: if you change that value in the function, it will instantly change anywhere it's used (the next time it's called).

USE [globalDatabase]
GO

CREATE FUNCTION dbo.global_GetStandardFonts ()
RETURNS NVARCHAR(255)
AS
BEGIN
    RETURN 'font-family:"Calibri Light","sans-serif";'
END
GO

--  Usage: 
SELECT '<html><head><style>body{' + globalDatabase.dbo.global_GetStandardFonts() + '}</style></head><body>...'

--  Result: <html><head><style>body{font-family:"Calibri Light","sans-serif";}</style></head><body>...

Sleep for milliseconds

From C++14 using std and also its numeric literals:

#include <chrono>
#include <thread>

using namespace std::chrono;

std::this_thread::sleep_for(123ms);

Write / add data in JSON file using Node.js

Please try the following program. You might be expecting this output.

var fs = require('fs');

var data = {}
data.table = []
for (i=0; i <26 ; i++){
   var obj = {
       id: i,
       square: i * i
   }
   data.table.push(obj)
}
fs.writeFile ("input.json", JSON.stringify(data), function(err) {
    if (err) throw err;
    console.log('complete');
    }
);

Save this program in a javascript file, say, square.js.

Then run the program from command prompt using the command node square.js

What it does is, simply overwriting the existing file with new set of data, every time you execute the command.

Happy Coding.

Removing double quotes from a string in Java

Use replace method of string like the following way:

String x="\"abcd";
String z=x.replace("\"", "");
System.out.println(z);

Output:

abcd

Can't import database through phpmyadmin file size too large

For Upload large size data in using phpmyadmin Do following steps.

  1. Open php.ini file from C:\wamp\bin\apache\Apache2.4.4\bin Update following lines
    max_execution_time = 259200
    max_input_time = 259200
    memory_limit = 1000M
    upload_max_filesize = 750M
    post_max_size = 750M
    than after restart wamp server or restart all services Now Upload data using import function in phymyadmin. Apply second step if till not upload data.
  2. open config.default.php file in c:\wamp\apps\phpmyadmin4.0.4\libraries (Open this file accoring to phpmyadmin version)
    Find $cfg['ExecTimeLimit'] = 300;Replace to $cfg['ExecTimeLimit'] = 0;
    Now you can upload data.

You can also upload large size database using MySQL Console as below.

  1. Click on WampServer Icon -> MySQL -> MySQL Consol
  2. Enter your database password like root in popup
  3. Select database name for insert data by writing command USE DATABASENAME
  4. Then load source sql file as SOURCE C:\FOLDER\database.sql
  5. Press enter for insert data.

Note: You can't load a compressed database file e.g. database.sql.zip or database.sql.gz, you have to extract it first. Otherwise the console will just crash.

Set CFLAGS and CXXFLAGS options using CMake

You must change the cmake C/CXX default FLAGS .

According to CMAKE_BUILD_TYPE={DEBUG/MINSIZEREL/RELWITHDEBINFO/RELEASE} put in the main CMakeLists.txt one of :

For C

set(CMAKE_C_FLAGS_DEBUG "put your flags")
set(CMAKE_C_FLAGS_MINSIZEREL "put your flags")
set(CMAKE_C_FLAGS_RELWITHDEBINFO "put your flags")
set(CMAKE_C_FLAGS_RELEASE "put your flags")

For C++

set(CMAKE_CXX_FLAGS_DEBUG "put your flags")
set(CMAKE_CXX_FLAGS_MINSIZEREL "put your flags")
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "put your flags")
set(CMAKE_CXX_FLAGS_RELEASE "put your flags")

This will override the values defined in CMakeCache.txt

Skip a submodule during a Maven build

there is now (from 1.1.1 version) a 'skip' flag in pit.

So you can do things like :

    <profile>
        <id>pit</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.pitest</groupId>
                    <artifactId>pitest-maven</artifactId>
                    <configuration>
                        <skip>true</skip>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>

in your module, and pit will skip

[INFO] --- pitest-maven:1.1.3:mutationCoverage (default-cli) @ module-selenium --- [INFO] Skipping project

Handling a timeout error in python sockets

I had enough success just catchig socket.timeout and socket.error; although socket.error can be raised for lots of reasons. Be careful.

import socket
import logging

hostname='google.com'
port=443

try:
    sock = socket.create_connection((hostname, port), timeout=3)

except socket.timeout as err:
    logging.error(err)

except socket.error as err:
    logging.error(err)

jQuery ui datepicker with Angularjs

onSelect doesn't work well in ng-repeat, so I made another version using event bind

html

<tr ng-repeat="product in products">
<td>
    <input type="text" ng-model="product.startDate" class="form-control date-picker" data-date-format="yyyy-mm-dd" datepicker/>
</td>
</tr>

script

angular.module('app', []).directive('datepicker', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModelCtrl) {
            element.datepicker();
            element.bind('blur keyup change', function(){
                var model = attrs.ngModel;
                if (model.indexOf(".") > -1) scope[model.replace(/\.[^.]*/, "")][model.replace(/[^.]*\./, "")] = element.val();
                else scope[model] = element.val();
            });
        }
    };
});

How to get the value from the GET parameters?

Simple way

function getParams(url){
        var regex = /[?&]([^=#]+)=([^&#]*)/g,
            params = {},
            match;
        while(match = regex.exec(url)) {
            params[match[1]] = match[2];
        }
        return params;
    }

then call it like getParams(url)

File to import not found or unreadable: compass

I'm seeing this issue using Rails 4.0.2 and compass-rails 1.1.3

I got past this error by moving gem 'compass-rails' outside of the :assets group in my Gemfile

It looks something like this:

# stuff
gem 'compass-rails', '~> 1.1.3'
group :assets do
  # more stuff
end

jQuery .scrollTop(); + animation

Try this code:

$('.Classname').click(function(){
    $("html, body").animate({ scrollTop: 0 }, 600);
    return false;
});

How to select between brackets (or quotes or ...) in Vim?

To select between the single quotes I usually do a vi' ("select inner single quotes").

Inside a parenthesis block, I use vib ("select inner block")

Inside a curly braces block you can use viB ("capital B")

To make the selections "inclusive" (select also the quotes, parenthesis or braces) you can use a instead of i.

You can read more about the Text object selections on the manual, or :help text-objects within vim.

How to load image files with webpack file-loader

This is my working example of our simple Vue component.

<template functional>
    <div v-html="require('!!html-loader!./../svg/logo.svg')"></div>
</template>

R data formats: RData, Rda, Rds etc

In addition to @KenM's answer, another important distinction is that, when loading in a saved object, you can assign the contents of an Rds file. Not so for Rda

> x <- 1:5
> save(x, file="x.Rda")
> saveRDS(x, file="x.Rds")
> rm(x)

## ASSIGN USING readRDS
> new_x1 <- readRDS("x.Rds")
> new_x1
[1] 1 2 3 4 5

## 'ASSIGN' USING load -- note the result
> new_x2 <- load("x.Rda")
loading in to  <environment: R_GlobalEnv> 
> new_x2
[1] "x"
# NOTE: `load()` simply returns the name of the objects loaded. Not the values. 
> x
[1] 1 2 3 4 5

How to style child components from parent component's CSS file?

Update - Newest Way

Don't do it, if you can avoid it. As Devon Sans points out in the comments: This feature will most likely be deprecated.

#Update - Newer Way From Angular 4.3.0, all piercing css combinators were deprecated. Angular team introduced a new combinator ::ng-deep (still it is experimental and not the full and final way) as shown below,

DEMO : https://plnkr.co/edit/RBJIszu14o4svHLQt563?p=preview

styles: [
    `
     :host { color: red; }
     
     :host ::ng-deep parent {
       color:blue;
     }
     :host ::ng-deep child{
       color:orange;
     }
     :host ::ng-deep child.class1 {
       color:yellow;
     }
     :host ::ng-deep child.class2{
       color:pink;
     }
    `
],



template: `
      Angular2                                //red
      <parent>                                //blue
          <child></child>                     //orange
          <child class="class1"></child>      //yellow
          <child class="class2"></child>      //pink
      </parent>      
    `

# Old way

You can use encapsulation mode and/or piercing CSS combinators >>>, /deep/ and ::shadow

working example : http://plnkr.co/edit/1RBDGQ?p=preview

styles: [
    `
     :host { color: red; }
     :host >>> parent {
       color:blue;
     }
     :host >>> child{
       color:orange;
     }
     :host >>> child.class1 {
       color:yellow;
     }
     :host >>> child.class2{
       color:pink;
     }
    `
    ],

template: `
  Angular2                                //red
  <parent>                                //blue
      <child></child>                     //orange
      <child class="class1"></child>      //yellow
      <child class="class2"></child>      //pink
  </parent>      
`

Why I get 'list' object has no attribute 'items'?

result_list = [int(v) for k,v in qs[0].items()]

qs is a list, qs[0] is the dict which you want!

How can I include css files using node, express, and ejs?

1.Create a new folder named 'public' if none exists.

2.Create a new folder named 'css' under the newly created 'public' folder

3.create your css file under the public/css path

4.On your html link css i.e <link rel="stylesheet" type="text/css" href="/css/style.css">

// note the href uses a slash(/) before and you do not need to include the 'public'

5.On your app.js include : app.use(express.static('public'));

Boom.It works!!

Cannot access wamp server on local network

If you are using wamp stack, it will be fixed by open port in Firewall (Control Pannel). It work for my case (detail how to open port 80: https://tips.alocentral.com/open-tcp-port-80-in-windows-firewall/)

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

I got the same problem in a SpringBoot project and, in my case, the cause was that the ouput folder '/target/test-classes' was empty.

Fixed it manually in the .classpath file, looking for the classpathentry with the attribute "test" and changing the content of the output attribute:

From this:

<classpathentry kind="src" output="<project folder>/target/test-classes" path="src/test/java">
    <attributes>
        <attribute name="test" value="true"/>
        <attribute name="optional" value="true"/>
        <attribute name="maven.pomderived" value="true"/>
    </attributes>
</classpathentry>

to this:

<classpathentry kind="src" output="target/test-classes" path="src/test/java">
    <attributes>
        <attribute name="test" value="true"/>
        <attribute name="optional" value="true"/>
        <attribute name="maven.pomderived" value="true"/>
    </attributes>
</classpathentry>

How can I create persistent cookies in ASP.NET?

Here's how you can do that.

Writing the persistent cookie.

//create a cookie
HttpCookie myCookie = new HttpCookie("myCookie");

//Add key-values in the cookie
myCookie.Values.Add("userid", objUser.id.ToString());

//set cookie expiry date-time. Made it to last for next 12 hours.
myCookie.Expires = DateTime.Now.AddHours(12);

//Most important, write the cookie to client.
Response.Cookies.Add(myCookie);

Reading the persistent cookie.

//Assuming user comes back after several hours. several < 12.
//Read the cookie from Request.
HttpCookie myCookie = Request.Cookies["myCookie"];
if (myCookie == null)
{
    //No cookie found or cookie expired.
    //Handle the situation here, Redirect the user or simply return;
}

//ok - cookie is found.
//Gracefully check if the cookie has the key-value as expected.
if (!string.IsNullOrEmpty(myCookie.Values["userid"]))
{
    string userId = myCookie.Values["userid"].ToString();
    //Yes userId is found. Mission accomplished.
}

Display Last Saved Date on worksheet

You can also simple add the following into the Header or Footer of the Worksheet

Last Saved: &[Date] &[Time]

how to get the child node in div using javascript

var tds = document.getElementById("ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a").getElementsByTagName("td");
time = tds[0].firstChild.value;
address = tds[3].firstChild.value;

Ignoring NaNs with str.contains

There's a flag for that:

In [11]: df = pd.DataFrame([["foo1"], ["foo2"], ["bar"], [np.nan]], columns=['a'])

In [12]: df.a.str.contains("foo")
Out[12]:
0     True
1     True
2    False
3      NaN
Name: a, dtype: object

In [13]: df.a.str.contains("foo", na=False)
Out[13]:
0     True
1     True
2    False
3    False
Name: a, dtype: bool

See the str.replace docs:

na : default NaN, fill value for missing values.


So you can do the following:

In [21]: df.loc[df.a.str.contains("foo", na=False)]
Out[21]:
      a
0  foo1
1  foo2

Find file in directory from command line

When I was in the UNIX world (using tcsh (sigh...)), I used to have all sorts of "find" aliases/scripts setup for searching for files. I think the default "find" syntax is a little clunky, so I used to have aliases/scripts to pipe "find . -print" into grep, which allows you to use regular expressions for searching:

# finds all .java files starting in current directory
find . -print | grep '\.java'

#finds all .java files whose name contains "Message"
find . -print | grep '.*Message.*\.java'

Of course, the above examples can be done with plain-old find, but if you have a more specific search, grep can help quite a bit. This works pretty well, unless "find . -print" has too many directories to recurse through... then it gets pretty slow. (for example, you wouldn't want to do this starting in root "/")

Send data from activity to fragment in Android

I would like to add for the beginners that the difference between the 2 most upvoted answers here is given by the different use of a fragment.

If you use the fragment within the java class where you have the data you want to pass, you can apply the first answer to pass data:

Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);

If however you use for example the default code given by Android Studio for tabbed fragments, this code will not work.

It will not work even if you replace the default PlaceholderFragment with your FragmentClasses, and even if you correct the FragmentPagerAdapter to the new situation adding a switch for getItem() and another switch for getPageTitle() (as shown here)

Warning: the clip mentioned above has code errors, which I explain later here, but is useful to see how you go from default code to editable code for tabbed fragments)! The rest of my answer makes much more sense if you consider the java classes and xml files from that clip (representative for a first use of tabbed fragments by a beginner scenario).

The main reason the most upvoted answer from this page will not work is that in that default code for tabbed fragments, the fragments are used in another java class: FragmentPagerAdapter!

So, in order to send the data, you are tempted to create a bundle in the MotherActivity and pass it in the FragmentPagerAdapter, using answer no.2.

Only that is wrong again. (Probably you could do it like that, but it is just a complication which is not really needed).

The correct/easier way to do it, I think, is to pass the data directly to the fragment in question, using answer no.2. Yes, there will be tight coupling between the Activity and the Fragment, BUT, for tabbed fragments, that is kind of expected. I would even advice you to create the tabbed fragments inside the MotherActivity java class (as subclasses, as they will never be used outside the MotherActivity) - it is easy, just add inside the MotherActivity java class as many Fragments as you need like this:

 public static class Tab1 extends Fragment {

    public Tab1() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.your_layout_name_for_fragment_1, container, false);
        return rootView;
    }
}.

So, to pass data from the MotherActivity to such a Fragment you will need to create private Strings/Bundles above the onCreate of your Mother activity - which you can fill with the data you want to pass to the fragments, and pass them on via a method created after the onCreate (here called getMyData()).

public class MotherActivity extends Activity {

    private String out;
    private Bundle results;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mother_activity);

       // for example get a value from the previous activity
        Intent intent = getIntent();
        out = intent.getExtras().getString("Key");

    }

    public Bundle getMyData() {
        Bundle hm = new Bundle();
        hm.putString("val1",out);
        return hm;
    }
}

And then in the fragment class, you use getMyData:

public static class Tab1 extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        public Tab1() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.your_layout_name_for_fragment_1, container, false);
            TextView output = (TextView)rootView.findViewById(R.id.your_id_for_a_text_view_within_the_layout);

            MotherActivity activity = (MotherActivity)getActivity();

            Bundle results = activity.getMyData();
            String value1 = results.getString("val1");

            output.setText(value1);
            return rootView;
        }
    }

If you have database queries I advice you to do them in the MotherActivity (and pass their results as Strings/Integers attached to keys inside a bundle as shown above), as inside the tabbed fragments, your syntax will become more complex (this becomes getActivity() for example, and getIntent becomes getActivity().getIntent), but you have also the option to do as you wish.

My advice for beginners is to focus on small steps. First, get your intent to open a very simple tabbed activity, without passing ANY data. Does it work? Does it open the tabs you expect? If not, why?

Start from that, and by applying solutions such as those presented in this clip, see what is missing. For that particular clip, the mainactivity.xml is never shown. That will surely confuse you. But if you pay attention, you will see that for example the context (tools:context) is wrong in the xml fragment files. Each fragment XML needs to point to the correct fragment class (or subclass using the separator $).

You will also see that in the main activity java class you need to add tabLayout.setupWithViewPager(mViewPager) - right after the line TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); without this line, your view is actually not linked to the XML files of the fragments, but it shows ONLY the xml file of the main activity.

In addition to the line in the main activity java class, in the main activity XML file you need to change the tabs to fit your situation (e.g. add or remove TabItems). If you do not have tabs in the main activity XML, then possibly you did not choose the correct activity type when you created it in the first place (new activity - tabbed activity).

Please note that in the last 3 paragraphs I talk about the video! So when I say main activity XML, it is the main activity XML in the video, which in your situation is the MotherActivity XML file.

loading json data from local file into React JS

If you want to load the file, as part of your app functionality, then the best approach would be to include and reference to that file.

Another approach is to ask for the file, and load it during runtime. This can be done with the FileAPI. There is also another StackOverflow answer about using it: How to open a local disk file with Javascript?

I will include a slightly modified version for using it in React:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: null
    };
    this.handleFileSelect = this.handleFileSelect.bind(this);
  }

  displayData(content) {
    this.setState({data: content});
  }

  handleFileSelect(evt) {
    let files = evt.target.files;
    if (!files.length) {
      alert('No file select');
      return;
    }
    let file = files[0];
    let that = this;
    let reader = new FileReader();
    reader.onload = function(e) {
      that.displayData(e.target.result);
    };
    reader.readAsText(file);
  }

  render() {
    const data = this.state.data;
    return (
      <div>
        <input type="file" onChange={this.handleFileSelect}/>
        { data && <p> {data} </p> }
      </div>
    );
  }
}

Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone

If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".

enter image description here

Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".

Is it possible to read from a InputStream with a timeout?

If your InputStream is backed by a Socket, you can set a Socket timeout (in milliseconds) using setSoTimeout. If the read() call doesn't unblock within the timeout specified, it will throw a SocketTimeoutException.

Just make sure that you call setSoTimeout on the Socket before making the read() call.

How to Execute SQL Server Stored Procedure in SQL Developer?

You don't need EXEC clause. Simply use

proc_name paramValue1, paramValue2

(and you need commas as Misnomer mentioned)

ObservableCollection Doesn't support AddRange method, so I get notified for each item added, besides what about INotifyCollectionChanging?

Yes, adding your own Custom Observable Collection would be fair enough. Don't forget to raise appropriate events regardless whether it is used by UI for the moment or not ;) You will have to raise property change notification for "Item[]" property (required by WPF side and bound controls) as well as NotifyCollectionChangedEventArgs with a set of items added (your range). I've did such things (as well as sorting support and some other stuff) and had no problems with both Presentation and Code Behind layers.

nginx error:"location" directive is not allowed here in /etc/nginx/nginx.conf:76

Since your server already includes the sites-enabled folder ( notice the include /etc/nginx/sites-enabled/* line ), then you better use that.

  1. Create a file inside /etc/nginx/sites-available and call it whatever you want, I'll call it django since it's a djanog server

    sudo touch /etc/nginx/sites-available/django
    
  2. Then create a symlink that points to it

    sudo ln -s /etc/nginx/sites-available/django /etc/nginx/sites-enabled
    
  3. Then edit that file with whatever file editor you use, vim or nano or whatever and create the server inside it

    server {
        # hostname or ip or multiple separated by spaces
        server_name localhost example.com 192.168.1.1; #change to your setting
        location / {
            root /home/techcee/scrapbook/local/lib/python2.7/site-packages/django/__init__.pyc/;
        }
    }
    
  4. Restart or reload nginx settings

    sudo service nginx reload
    

Note I believe that your configuration like this probably won't work yet because you need to pass it to a fastcgi server or something, but at least this is how you could create a valid server

To add server using sp_addlinkedserver

Add the linked server first with

exec sp_addlinkedserver
@server = 'SNRJDI\SLAMANAGEMENT',
@srvproduct=N'',
@provider=N'SQLNCLI'

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

What database does Google use?

As others have mentioned, Google uses a homegrown solution called BigTable and they've released a few papers describing it out into the real world.

The Apache folks have an implementation of the ideas presented in these papers called HBase. HBase is part of the larger Hadoop project which according to their site "is a software platform that lets one easily write and run applications that process vast amounts of data." Some of the benchmarks are quite impressive. Their site is at http://hadoop.apache.org.

Include .so library in apk in android studio

To include native libraries you need:

  1. create "jar" file with special structure containing ".so" files;
  2. include that file in dependencies list.

To create jar file, use the following snippet:

task nativeLibsToJar(type: Zip, description: 'create a jar archive of the native libs') {
    destinationDir file("$buildDir/native-libs")
    baseName 'native-libs'
    extension 'jar'
    from fileTree(dir: 'libs', include: '**/*.so')
    into 'lib/'
}

tasks.withType(Compile) {
    compileTask -> compileTask.dependsOn(nativeLibsToJar)
}

To include resulting file, paste the following line into "dependencies" section in "build.gradle" file:

compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')

Regular expression to extract URL from an HTML link

Yes, there are tons of them on regexlib. That only proves that RE's should not be used to do that. Use SGMLParser or BeautifulSoup or write a parser - but don't use RE's. The ones that seems to work are extremely compliated and still don't cover all cases.

How do I escape a percentage sign in T-SQL?

You can use the ESCAPE keyword with LIKE. Simply prepend the desired character (e.g. '!') to each of the existing % signs in the string and then add ESCAPE '!' (or your character of choice) to the end of the query.

For example:

SELECT *
FROM prices
WHERE discount LIKE '%80!% off%'
ESCAPE '!'

This will make the database treat 80% as an actual part of the string to search for and not 80(wildcard).

MSDN Docs for LIKE

Can't bind to 'ngModel' since it isn't a known property of 'input'

Recently I found that mistake happened not only in case when you forgot to import FormsModule in your module. In my case problem was in this code:

<input type="text" class="form-control" id="firstName"
                   formControlName="firstName" placeholder="Enter First Name"
                   value={{user.firstName}} [(ngModel)]="user.firstName">

I fix it with change formControlName -> name

<input type="text" class="form-control" id="firstName"
                   name="firstName" placeholder="Enter First Name"
                   value={{user.firstName}} [(ngModel)]="user.firstName">

Get data from php array - AJAX - jQuery

When you do echo $array;, PHP will simply echo 'Array' since it can't convert an array to a string. So The 'A' that you are actually getting is the first letter of Array, which is correct.

You might actually need

echo json_encode($array);

This should get you what you want.

EDIT : And obviously, you'd need to change your JS to work with JSON instead of just text (as pointed out by @genesis)

Change HTML email body font type and size in VBA

Set texts with different sizes and styles, and size and style for texts from cells ( with Range)

Sub EmailManuellAbsenden()

Dim ghApp As Object
Dim ghOldBody As String
Dim ghNewBody As String

Set ghApp = CreateObject("Outlook.Application")
With ghApp.CreateItem(0)
.To = Range("B2")
.CC = Range("B3")
.Subject = Range("B4")
.GetInspector.Display
 ghOldBody = .htmlBody

 ghNewBody = "<font style=""font-family: Calibri; font-size: 11pt;""/font>" & _
 "<font style=""font-family: Arial; font-size: 14pt;"">Arial Text 14</font>" & _
 Range("B5") & "<br>" & _
 Range("B6") & "<br>" & _
 "<font style=""font-family: Chiller; font-size: 21pt;"">Ciller 21</font>" &
 Range("B5")
 .htmlBody = ghNewBody & ghOldBody

 End With

End Sub
'Fill B2 to B6 with some letters for testing
'"<font style=""font-family: Calibri; font-size: 15pt;""/font>" = works for all Range Objekts

Check synchronously if file/directory exists in Node.js

Looking at the source, there's a synchronous version of path.exists - path.existsSync. Looks like it got missed in the docs.

Update:

path.exists and path.existsSync are now deprecated. Please use fs.exists and fs.existsSync.

Update 2016:

fs.exists and fs.existsSync have also been deprecated. Use fs.stat() or fs.access() instead.

Update 2019:

use fs.existsSync. It's not deprecated. https://nodejs.org/api/fs.html#fs_fs_existssync_path

Groovy - Convert object to JSON string

I couldn't get the other answers to work within the evaluate console in Intellij so...

groovy.json.JsonOutput.toJson(myObject)

This works quite well, but unfortunately

groovy.json.JsonOutput.prettyString(myObject)

didn't work for me.

To get it pretty printed I had to do this...

groovy.json.JsonOutput.prettyPrint(groovy.json.JsonOutput.toJson(myObject))

How to fully clean bin and obj folders within Visual Studio?

This is how I do with a batch file to delete all BIN and OBJ folders recursively.

  • Create an empty file and name it DeleteBinObjFolders.bat
  • Copy-paste code the below code into the DeleteBinObjFolders.bat
  • Move the DeleteBinObjFolders.bat file in the same folder with your solution (*.sln) file.
@echo off
@echo Deleting all BIN and OBJ folders...
for /d /r . %%d in (bin,obj) do @if exist "%%d" rd /s/q "%%d"
@echo BIN and OBJ folders successfully deleted :) Close the window.
pause > nul

Turn a number into star rating display using jQuery and CSS

Here's my take using JSX and font awesome, limited on only .5 accuracy, though:

       <span>
          {Array(Math.floor(rating)).fill(<i className="fa fa-star"></i>)}
          {(rating) - Math.floor(rating)==0 ? ('') : (<i className="fa fa-star-half"></i>)}
       </span>

First row is for whole star and second row is for half star (if any)

CSS background image in :after element

As AlienWebGuy said, you can use background-image. I'd suggest you use background, but it will need three more properties after the URL:

background: url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") 0 0 no-repeat;

Explanation: the two zeros are x and y positioning for the image; if you want to adjust where the background image displays, play around with these (you can use both positive and negative values, e.g: 1px or -1px).

No-repeat says you don't want the image to repeat across the entire background. This can also be repeat-x and repeat-y.

Convert UTF-8 encoded NSData to NSString

You could call this method

+(id)stringWithUTF8String:(const char *)bytes.

Chrome hangs after certain amount of data transfered - waiting for available socket

Explanation:

This problem occurs because Chrome allows up to 6 open connections by default. So if you're streaming multiple media files simultaneously from 6 <video> or <audio> tags, the 7th connection (for example, an image) will just hang, until one of the sockets opens up. Usually, an open connection will close after 5 minutes of inactivity, and that's why you're seeing your .pngs finally loading at that point.

Solution 1:

You can avoid this by minimizing the number of media tags that keep an open connection. And if you need to have more than 6, make sure that you load them last, or that they don't have attributes like preload="auto".

Solution 2:

If you're trying to use multiple sound effects for a web game, you could use the Web Audio API. Or to simplify things, just use a library like SoundJS, which is a great tool for playing a large amount of sound effects / music tracks simultaneously.

Solution 3: Force-open Sockets (Not recommended)

If you must, you can force-open the sockets in your browser (In Chrome only):

  1. Go to the address bar and type chrome://net-internals.
  2. Select Sockets from the menu.
  3. Click on the Flush socket pools button.

This solution is not recommended because you shouldn't expect your visitors to follow these instructions to be able to view your site.

d3.select("#element") not working when code above the html element

Please try this approach. It worked for me.

<head> 
<script  type="text/javascript" src='./d3.v4.min.js'></script>
</head> 

<body>
    <div id="jschart41448" style="color:red">
        Hi red
    </div>

    <div id="jschart41449" style="color:blueviolet">
        Hi blueviolet
    </div>

 <script type="text/javascript"   >
            d3.select("#jschart41448").style('color', 'green' , null);
            d3.select("#jschart41449").style('color', 'yellow', null);
</script>
</body>

How to draw a path on a map using kml file?

Mathias Lin code working beautifully. However, you might want to consider changing this part inside drawPath method:

 if (lngLat.length >= 2 && gp1.getLatitudeE6() > 0 && gp1.getLongitudeE6() > 0
                    && gp2.getLatitudeE6() > 0 && gp2.getLongitudeE6() > 0) {

GeoPoint can be less than zero as well, I switch mine to:

     if (lngLat.length >= 2 && gp1.getLatitudeE6() != 0 && gp1.getLongitudeE6() != 0
                    && gp2.getLatitudeE6() != 0 && gp2.getLongitudeE6() != 0) {

Thank you :D

How do I debug a stand-alone VBScript script?

Export this folder to a backup file and try remove this folder and all the content.

HKEY_CURRENT_USER\Software\Microsoft\Script Debugger

How to cherry pick a range of commits and merge into another branch?

git cherry-pick FIRST^..LAST works only for simple scenarios.

To achieve a decent "merge it into the integration branch" while having the usal comfort with things like auto-skipping of already integrated picks, transplanting diamond-merges, interactive control ...) better use a rebase. One answer here pointed to that, however the protocol included a dicey git branch -f and a juggling with a temp branch. Here a straight robust method:

git rebase -i FIRST LAST~0 --onto integration
git rebase @ integration

The -i allows for interactive control. The ~0 ensures a detached rebase (not moving the / another branch) in case LAST is a branch name. It can be omitted otherwise. The second rebase command just moves the integration branch ref in safe manner forward to the intermediate detached head - it doesn't introduce new commits. To rebase a complex structure with merge diamonds etc. consider --rebase-merges or --rebase-merges=rebase-cousins in the first rebase.

Using pg_dump to only get insert statements from one table within database

if version < 8.4.0

pg_dump -D -t <table> <database>

Add -a before the -t if you only want the INSERTs, without the CREATE TABLE etc to set up the table in the first place.

version >= 8.4.0

pg_dump --column-inserts --data-only --table=<table> <database>

How do I get Maven to use the correct repositories?

I think what you have missed here is this:

https://maven.apache.org/settings.html#Servers

The repositories for download and deployment are defined by the repositories and distributionManagement elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml.

This is the prefered way of using custom repos. So probably what is happening is that the url of this repo is in settings.xml of the build server.

Once you get hold of the url and credentials, you can put them in your machine here: ~/.m2/settings.xml like this:

<settings ...> 

        .
        .
        .
        <servers>
            <server>
              <id>internal-repository-group</id>
              <username>YOUR-USERNAME-HERE</username>
              <password>YOUR-PASSWORD-HERE</password>
            </server>
        </servers>
</settings>

EDIT:

You then need to refer this repository into project POM. The id internal-repository-group can be used in every project. You can setup multiple repos and credentials setting using different IDs in settings xml.

The advantage of this approach is that project can be shared without worrying about the credentials and don't have to mention the credentials in every project.

Following is a sample pom of a project using "internal-repository-group"

<repositories>
    <repository>
        <id>internal-repository-group</id>
        <name>repo-name</name>
        <url>http://project.com/yourrepourl/</url>
        <layout>default</layout>
        <releases>
            <enabled>true</enabled>
            <updatePolicy>never</updatePolicy>
        </releases>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>never</updatePolicy>
        </snapshots>
    </repository>
</repositories>

What's the "Content-Length" field in HTTP header?

The Content-Length header is a number denoting an the exact byte length of the HTTP body. The HTTP body starts immediately after the first empty line that is found after the start-line and headers.

Generally the Content-Length header is used for HTTP 1.1 so that the receiving party knows when the current response* has finished, so the connection can be reused for another request.

* ...or request, in the case of request methods that have a body, such as POST, PUT or PATCH

Alternatively, Content-Length header can be omitted and a chunked Transfer-Encoding header can be used.

If both Content-Length and Transfer-Encoding headers are missing, then at the end of the response the connection must be closed.

The following resource is a guide that I found very useful when learning about HTTP:

HTTP Made Really Easy.

Error: Specified cast is not valid. (SqlManagerUI)

Sometimes it happens because of the version change like store 2012 db on 2008, so how to check it?

RESTORE VERIFYONLY FROM DISK = N'd:\yourbackup.bak'

if it gives error like:

Msg 3241, Level 16, State 13, Line 2 The media family on device 'd:\alibaba.bak' is incorrectly formed. SQL Server cannot process this media family. Msg 3013, Level 16, State 1, Line 2 VERIFY DATABASE is terminating abnormally.

Check it further:

RESTORE HEADERONLY FROM DISK = N'd:\yourbackup.bak'

BackupName is "* INCOMPLETE *", Position is "1", other fields are "NULL".

Means either your backup is corrupt or taken from newer version.

Removing a non empty directory programmatically in C or C++

Many unix-like systems (Linux, the BSDs, and OS X, at the very least) have the fts functions for directory traversal.

To recursively delete a directory, perform a depth-first traversal (without following symlinks) and remove every visited file:

int recursive_delete(const char *dir)
{
    int ret = 0;
    FTS *ftsp = NULL;
    FTSENT *curr;

    // Cast needed (in C) because fts_open() takes a "char * const *", instead
    // of a "const char * const *", which is only allowed in C++. fts_open()
    // does not modify the argument.
    char *files[] = { (char *) dir, NULL };

    // FTS_NOCHDIR  - Avoid changing cwd, which could cause unexpected behavior
    //                in multithreaded programs
    // FTS_PHYSICAL - Don't follow symlinks. Prevents deletion of files outside
    //                of the specified directory
    // FTS_XDEV     - Don't cross filesystem boundaries
    ftsp = fts_open(files, FTS_NOCHDIR | FTS_PHYSICAL | FTS_XDEV, NULL);
    if (!ftsp) {
        fprintf(stderr, "%s: fts_open failed: %s\n", dir, strerror(errno));
        ret = -1;
        goto finish;
    }

    while ((curr = fts_read(ftsp))) {
        switch (curr->fts_info) {
        case FTS_NS:
        case FTS_DNR:
        case FTS_ERR:
            fprintf(stderr, "%s: fts_read error: %s\n",
                    curr->fts_accpath, strerror(curr->fts_errno));
            break;

        case FTS_DC:
        case FTS_DOT:
        case FTS_NSOK:
            // Not reached unless FTS_LOGICAL, FTS_SEEDOT, or FTS_NOSTAT were
            // passed to fts_open()
            break;

        case FTS_D:
            // Do nothing. Need depth-first search, so directories are deleted
            // in FTS_DP
            break;

        case FTS_DP:
        case FTS_F:
        case FTS_SL:
        case FTS_SLNONE:
        case FTS_DEFAULT:
            if (remove(curr->fts_accpath) < 0) {
                fprintf(stderr, "%s: Failed to remove: %s\n",
                        curr->fts_path, strerror(curr->fts_errno));
                ret = -1;
            }
            break;
        }
    }

finish:
    if (ftsp) {
        fts_close(ftsp);
    }

    return ret;
}

How to download a file with Node.js (without using third-party libraries)?

You can create an HTTP GET request and pipe its response into a writable file stream:

const http = require('http'); // or 'https' for https:// URLs
const fs = require('fs');

const file = fs.createWriteStream("file.jpg");
const request = http.get("http://i3.ytimg.com/vi/J---aiyznGQ/mqdefault.jpg", function(response) {
  response.pipe(file);
});

If you want to support gathering information on the command line--like specifying a target file or directory, or URL--check out something like Commander.

Linux command for extracting war file?

Using unzip

unzip -c whatever.war META-INF/MANIFEST.MF  

It will print the output in terminal.

And for extracting all the files,

 unzip whatever.war

Using jar

jar xvf test.war

Note! The jar command will extract war contents to current directory. Not to a subdirectory (like Tomcat does).

How do I uninstall nodejs installed from pkg (Mac OS X)?

In order to delete the 'native' node.js installation, I have used the method suggested in previous answers sudo npm uninstall npm -g, with additional sudo rm -rf /usr/local/lib/node /usr/local/lib/node_modules /var/db/receipts/org.nodejs.*.

BUT, I had to also delete the following two directories:

sudo rm -rf /usr/local/include/node /Users/$USER/.npm

Only after that I could install node.js with Homebrew.

Escaping single quote in PHP when inserting into MySQL

I had the same problem and I solved it like this:

$text = str_replace("'", "\'", $YourContent);

There is probably a better way to do this, but it worked for me and it should work for you too.

Error "can't use subversion command line client : svn" when opening android project checked out from svn

Android Studio cannot find the svn command because it's not on PATH, and it doesn't know where svn is installed.

One way to fix is to edit the PATH environment variable: add the directory that contains svn.exe. You will need to restart Android Studio to make it re-read the PATH variable.

Another way is to set the absolute path of svn.exe in the Use command client box in the settings screen that you included in your post.

UPDATE

According to this other post, TortoiseSVN doesn't include the command line tools by default. But you can re-run the installer and enable it. That will add svn.exe to PATH, and Android Studio will correctly pick it up.

Remove last commit from remote git repository

If nobody has pulled it, you can probably do something like

git push remote +branch^1:remotebranch

which will forcibly update the remote branch to the last but one commit of your branch.

How do I compare version numbers in Python?

Posting my full function based on Kindall's solution. I was able to support any alphanumeric characters mixed in with the numbers by padding each version section with leading zeros.

While certainly not as pretty as his one-liner function, it seems to work well with alpha-numeric version numbers. (Just be sure to set the zfill(#) value appropriately if you have long strings in your versioning system.)

def versiontuple(v):
   filled = []
   for point in v.split("."):
      filled.append(point.zfill(8))
   return tuple(filled)

.

>>> versiontuple("10a.4.5.23-alpha") > versiontuple("2a.4.5.23-alpha")
True


>>> "10a.4.5.23-alpha" > "2a.4.5.23-alpha"
False

How to overcome "'aclocal-1.15' is missing on your system" warning?

You can install the version you need easily:

First get source:

$ wget https://ftp.gnu.org/gnu/automake/automake-1.15.tar.gz

Unpack it:

$ tar -xzvf automake-1.15.tar.gz

Build and install:

$ cd automake-1.15
$ ./configure  --prefix=/opt/aclocal-1.15
$ make
$ sudo mkdir -p /opt
$ sudo make install

Use it:

$ export PATH=/opt/aclocal-1.15/bin:$PATH
$ aclocal --version

aclocal (GNU automake) 1.15

Now when aclocal is called, you get the right version.

Rendering HTML elements to <canvas>

Take a look on MDN

It will render html element using creating SVG images.

For Example: There is <em>I</em> like <span style="color:white; text-shadow:0 0 2px blue;">cheese</span> HTML element. And I want to add it into <canvas id="canvas" style="border:2px solid black;" width="200" height="200"></canvas> Canvas Element.

Here is Javascript Code to add HTML element to canvas.

_x000D_
_x000D_
var canvas = document.getElementById('canvas');_x000D_
var ctx = canvas.getContext('2d');_x000D_
_x000D_
var data = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +_x000D_
  '<foreignObject width="100%" height="100%">' +_x000D_
  '<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:40px">' +_x000D_
  '<em>I</em> like <span style="color:white; text-shadow:0 0 2px blue;">cheese</span>' +_x000D_
  '</div>' +_x000D_
  '</foreignObject>' +_x000D_
  '</svg>';_x000D_
_x000D_
var DOMURL = window.URL || window.webkitURL || window;_x000D_
_x000D_
var img = new Image();_x000D_
var svg = new Blob([data], {_x000D_
  type: 'image/svg+xml;charset=utf-8'_x000D_
});_x000D_
var url = DOMURL.createObjectURL(svg);_x000D_
_x000D_
img.onload = function() {_x000D_
  ctx.drawImage(img, 0, 0);_x000D_
  DOMURL.revokeObjectURL(url);_x000D_
}_x000D_
_x000D_
img.src = url;
_x000D_
<canvas id="canvas" style="border:2px solid black;" width="200" height="200"></canvas>
_x000D_
_x000D_
_x000D_

Retrieve a single file from a repository

Following on from Jakub's answer. git archive produces a tar or zip archive, so you need to pipe the output through tar to get the file content:

git archive --remote=git://git.foo.com/project.git HEAD:path/to/directory filename | tar -x

Will save a copy of 'filename' from the HEAD of the remote repository in the current directory.

The :path/to/directory part is optional. If excluded, the fetched file will be saved to <current working dir>/path/to/directory/filename

In addition, if you want to enable use of git archive --remote on Git repositories hosted by git-daemon, you need to enable the daemon.uploadarch config option. See https://kernel.org/pub/software/scm/git/docs/git-daemon.html

Conditional logic in AngularJS template

You could use the ngSwitch directive:

  <div ng-switch on="selection" >
    <div ng-switch-when="settings">Settings Div</div>
    <span ng-switch-when="home">Home Span</span>
    <span ng-switch-default>default</span>
  </div>

If you don't want the DOM to be loaded with empty divs, you need to create your custom directive using $http to load the (sub)templates and $compile to inject it in the DOM when a certain condition has reached.

This is just an (untested) example. It can and should be optimized:

HTML:

<conditional-template ng-model="element" template-url1="path/to/partial1" template-url2="path/to/partial2"></div>

Directive:

app.directive('conditionalTemplate', function($http, $compile) {
   return {
      restrict: 'E',
      require: '^ngModel',
      link: function(sope, element, attrs, ctrl) {
        // get template with $http
        // check model via ctrl.$viewValue
        // compile with $compile
        // replace element with element.replaceWith()
      }
   };
});

How do I configure Maven for offline development?

In preparation before working offline just run mvn dependency:go-offline

How to group time by hour or by 10 minutes

Should be something like

select timeslot, count(*)  
from 
    (
    select datepart('hh', date) timeslot
    FROM [FRIIB].[dbo].[ArchiveAnalog]  
    ) 
group by timeslot

(Not 100% sure about the syntax - I'm more an Oracle kind of guy)

In Oracle:

SELECT timeslot, COUNT(*) 
FROM
(  
    SELECT to_char(l_time, 'YYYY-MM-DD hh24') timeslot 
    FROM
    (
        SELECT l_time FROM mytab  
    )  
) GROUP BY timeslot 

What is the perfect counterpart in Python for "while not EOF"

You can imitate the C idiom in Python.

To read a buffer up to max_size number of bytes, you can do this:

with open(filename, 'rb') as f:
    while True:
        buf = f.read(max_size)
        if not buf:
            break
        process(buf)

Or, a text file line by line:

# warning -- not idiomatic Python! See below...
with open(filename, 'rb') as f:
    while True:
        line = f.readline()
        if not line:
            break
        process(line)

You need to use while True / break construct since there is no eof test in Python other than the lack of bytes returned from a read.

In C, you might have:

while ((ch != '\n') && (ch != EOF)) {
   // read the next ch and add to a buffer
   // ..
}

However, you cannot have this in Python:

 while (line = f.readline()):
     # syntax error

because assignments are not allowed in expressions in Python (although recent versions of Python can mimic this using assignment expressions, see below).

It is certainly more idiomatic in Python to do this:

# THIS IS IDIOMATIC Python. Do this:
with open('somefile') as f:
    for line in f:
        process(line)

Update: Since Python 3.8 you may also use assignment expressions:

 while line := f.readline():
     process(line)

What is the best open XML parser for C++?

I like the Gnome xml parser. It's open source (MIT License, so you can use it in commercial products), fast and has DOM and SAX based interfaces.

http://xmlsoft.org/

PHP write file from input to txt

If you use file_put_contents you don't need to do a fopen -> fwrite -> fclose, the file_put_contents does all that for you. You should also check if the webserver has write rights in the directory where you are trying to write your "data.txt" file.

Depending on your PHP version (if it's old) you might not have the file_get/put_contents functions. Check your webserver log to see if any error appeared when you executed the script.

how to initialize a char array?

char * msg = new char[65546]();

It's known as value-initialisation, and was introduced in C++03. If you happen to find yourself trapped in a previous decade, then you'll need to use std::fill() (or memset() if you want to pretend it's C).

Note that this won't work for any value other than zero. I think C++0x will offer a way to do that, but I'm a bit behind the times so I can't comment on that.

UPDATE: it seems my ruminations on the past and future of the language aren't entirely accurate; see the comments for corrections.

calling java methods in javascript code

When it is on server side, use web services - maybe RESTful with JSON.

  • create a web service (for example with Tomcat)
  • call its URL from JavaScript (for example with JQuery or dojo)

When Java code is in applet you can use JavaScript bridge. The bridge between the Java and JavaScript programming languages, known informally as LiveConnect, is implemented in Java plugin. Formerly Mozilla-specific LiveConnect functionality, such as the ability to call static Java methods, instantiate new Java objects and reference third-party packages from JavaScript, is now available in all browsers.

Below is example from documentation. Look at methodReturningString.

Java code:

public class MethodInvocation extends Applet {
    public void noArgMethod() { ... }
    public void someMethod(String arg) { ... }
    public void someMethod(int arg) { ... }
    public int  methodReturningInt() { return 5; }
    public String methodReturningString() { return "Hello"; }
    public OtherClass methodReturningObject() { return new OtherClass(); }
}

public class OtherClass {
    public void anotherMethod();
}

Web page and JavaScript code:

<applet id="app"
        archive="examples.jar"
        code="MethodInvocation" ...>
</applet>
<script language="javascript">
    app.noArgMethod();
    app.someMethod("Hello");
    app.someMethod(5);
    var five = app.methodReturningInt();
    var hello = app.methodReturningString();
    app.methodReturningObject().anotherMethod();
</script>

How to change the default charset of a MySQL table?

You can change the default with an alter table set default charset but that won't change the charset of the existing columns. To change that you need to use a alter table modify column.

Changing the charset of a column only means that it will be able to store a wider range of characters. Your application talks to the db using the mysql client so you may need to change the client encoding as well.

Squash the first two commits in Git?

I've reworked VonC's script to do everything automatically and not ask me for anything. You give it two commit SHA1s and it will squash everything between them into one commit named "squashed history":

#!/bin/sh
# Go back to the last commit that we want
# to form the initial commit (detach HEAD)
git checkout $2

# reset the branch pointer to the initial commit (= $1),
# but leaving the index and working tree intact.
git reset --soft $1

# amend the initial tree using the tree from $2
git commit --amend -m "squashed history"

# remember the new commit sha1
TARGET=`git rev-list HEAD --max-count=1`

# go back to the original branch (assume master for this example)
git checkout master

# Replay all the commits after $2 onto the new initial commit
git rebase --onto $TARGET $2

UIView's frame, bounds, center, origin, when to use what?

Marco's answer above is correct, but just to expand on the question of "under what context"...

frame - this is the property you most often use for normal iPhone applications. most controls will be laid out relative to the "containing" control so the frame.origin will directly correspond to where the control needs to display, and frame.size will determine how big to make the control.

center - this is the property you will likely focus on for sprite based games and animations where movement or scaling may occur. By default animation and rotation will be based on the center of the UIView. It rarely makes sense to try and manage such objects by the frame property.

bounds - this property is not a positioning property, but defines the drawable area of the UIView "relative" to the frame. By default this property is usually (0, 0, width, height). Changing this property will allow you to draw outside of the frame or restrict drawing to a smaller area within the frame. A good discussion of this can be found at the link below. It is uncommon for this property to be manipulated unless there is specific need to adjust the drawing region. The only exception is that most programs will use the [[UIScreen mainScreen] bounds] on startup to determine the visible area for the application and setup their initial UIView's frame accordingly.

Why is there an frame rectangle and an bounds rectangle in an UIView?

Hopefully this helps clarify the circumstances where each property might get used.

How to use a class object in C++ as a function parameter

holy errors The reason for the code below is to show how to not void main every function and not to type return; for functions...... instead push everything into the sediment for which is the print function prototype... if you need to use useful functions ... you will have to below..... (p.s. this below is for people overwhelmed by these object and T templates which allow different variable declaration types(such as float and char) to use the same passed by value in a user defined function)

char arr[ ] = "This is a test";

string str(arr);


//  You can also assign directly to a string.
str = "This is another string";

can anyone tell me why c++ made arrays into pass by value one at a time and the only way to eliminate spaces and punctuation is the use of string tokens. I couldn't get around the problem when i was trying to delete spaces for a palindrome...

#include <iostream>
#include <iomanip>
using namespace std;
int getgrades(float[]);
int getaverage(float[], float);
int calculateletters(float[], float, float, float[]);
int printResults(float[], float, float, float[]);


int main()
{

int i;
float  maxSize=3, size;
float  lettergrades[5], numericgrades[100], average;

size=getgrades(numericgrades);
average = getaverage(numericgrades, size);
printResults(numericgrades, size, average, lettergrades);
return 0;
}

int getgrades(float a[])
{ 


int i, max=3;

for (i = 0; i <max; i++)
{
    //ask use for input
    cout << "\nPlease Enter grade " << i+1 << " : ";
    cin >> a[i];
    //makes sure that user enters a vlue between 0 and 100

   if(a[i] < 0 || a[i] >100)
    {
        cout << "Wrong input. Please
 enter a value between 0 and 100 only." << endl;
        cout << "\nPlease Reenter grade " << i+1 << " : ";
        cin >> a[i];

        return i;
    }
}
}

int getaverage(float a[], float n) 
{ 
int i;
float sum = 0;
 if (n == 0)
return 0;
for (i = 0; i < n; i++)
sum += a[i];
return sum / n;
}                               


int printResults(float a[], float n, float average, float letters[]) 
{
int i;
cout << "Index Number | input  |
array values address in memory " << endl;

for (i = 0; i < 3; i++)
{
cout <<"     "<< i<<" \t\t"<<setprecision(3)<<
a[i]<<"\t\t" << &a[i] << endl;
}
cout<<"The average of your grades is: "<<setprecision(3)<<average<<endl;

}

Choosing a jQuery datagrid plugin?

You should look here: https://stackoverflow.com/questions/159025/jquery-grid-recommendations

Update

The link above takes to a question that was closed and then deleted. Here are the original suggestions that were on the most voted answer:

Insert HTML with React Variable Statements (JSX)

To avoid linter errors, I use it like this:

  render() {
    const props = {
      dangerouslySetInnerHTML: { __html: '<br/>' },
    };
    return (
        <div {...props}></div>
    );
  }

How do I fix a merge conflict due to removal of a file in a branch?

The conflict message:

CONFLICT (delete/modify): res/layout/dialog_item.xml deleted in dialog and modified in HEAD

means that res/layout/dialog_item.xml was deleted in the 'dialog' branch you are merging, but was modified in HEAD (in the branch you are merging to).

So you have to decide whether

  • remove file using "git rm res/layout/dialog_item.xml"

or

  • accept version from HEAD (perhaps after editing it) with "git add res/layout/dialog_item.xml"

Then you finalize merge with "git commit".

Note that git will warn you that you are creating a merge commit, in the (rare) case where it is something you don't want. Probably remains from the days where said case was less rare.

How can I convert a string with dot and comma into a float in Python

What about this?

 my_string = "123,456.908"
 commas_removed = my_string.replace(',', '') # remove comma separation
 my_float = float(commas_removed) # turn from string to float.

In short:

my_float = float(my_string.replace(',', ''))

Two-way SSL clarification

In two way ssl the client asks for servers digital certificate and server ask for the same from the client. It is more secured as it is both ways, although its bit slow. Generally we dont follow it as the server doesnt care about the identity of the client, but a client needs to make sure about the integrity of server it is connecting to.

javascript date to string

Relying on JQuery Datepicker, but it could be done easily:

var mydate = new Date();
$.datepicker.formatDate('yy-mm-dd', mydate);

Dynamically adding properties to an ExpandoObject

i think this add new property in desired type without having to set a primitive value, like when property defined in class definition

var x = new ExpandoObject();
x.NewProp = default(string)

Doctrine query builder using inner join with conditions

I'm going to answer my own question.

  1. innerJoin should use the keyword "WITH" instead of "ON" (Doctrine's documentation [13.2.6. Helper methods] is inaccurate; [13.2.5. The Expr class] is correct)
  2. no need to link foreign keys in join condition as they're already specified in the entity mapping.

Therefore, the following works for me

$qb->select('c')
    ->innerJoin('c.phones', 'p', 'WITH', 'p.phone = :phone')
    ->where('c.username = :username');

or

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::WITH, $qb->expr()->eq('p.phone', ':phone'))
    ->where('c.username = :username');

simple way to display data in a .txt file on a webpage?

I find that if I try things that others say do not work, it's how I learn the most.

<p>&nbsp;</p>
<p>README.txt</p>
<p>&nbsp;</p>
<div id="list">
  <p><iframe src="README.txt" frameborder="0" height="400"
      width="95%"></iframe></p>
</div>

This worked for me. I used the yellow background-color that I set in the stylesheet.

#list  p {
    font: arial;
    font-size: 14px;
    background-color: yellow ;
}

Is it possible to use a div as content for Twitter's Popover

In addition to other replies. If you allow html in options you can pass jQuery object to content, and it will be appended to popover's content with all events and bindings. Here is the logic from source code:

  • if you pass a function it will be called to unwrap content data
  • if html is not allowed content data will be applied as text
  • if html allowed and content data is string it will be applied as html
  • otherwise content data will be appended to popover's content container
$("#popover-button").popover({
    content: $("#popover-content"),
    html: true,
    title: "Popover title"
});

Switch/toggle div (jQuery)

I used this way to do that for multiple blocks without conjuring new JavaScript code:

<a href="#" data-toggle="thatblock">Show/Hide Content</a>

<div id="thatblock" style="display: none">
  Here is some description that will appear when we click on the button
</div>

Then a JavaScript portion for all such cases:

$(function() {
  $('*[data-toggle]').click(function() {
    $('#'+$(this).attr('data-toggle')).toggle();
    return false;
  });
});

FFmpeg: How to split video efficiently?

Here's a useful script, it helps you split automatically: A script for splitting videos using ffmpeg

#!/bin/bash
 
# Written by Alexis Bezverkhyy <[email protected]> in 2011
# This is free and unencumbered software released into the public domain.
# For more information, please refer to <http://unlicense.org/>
 
function usage {
        echo "Usage : ffsplit.sh input.file chunk-duration [output-filename-format]"
        echo -e "\t - input file may be any kind of file reconginzed by ffmpeg"
        echo -e "\t - chunk duration must be in seconds"
        echo -e "\t - output filename format must be printf-like, for example myvideo-part-%04d.avi"
        echo -e "\t - if no output filename format is given, it will be computed\
 automatically from input filename"
}
 
IN_FILE="$1"
OUT_FILE_FORMAT="$3"
typeset -i CHUNK_LEN
CHUNK_LEN="$2"
 
DURATION_HMS=$(ffmpeg -i "$IN_FILE" 2>&1 | grep Duration | cut -f 4 -d ' ')
DURATION_H=$(echo "$DURATION_HMS" | cut -d ':' -f 1)
DURATION_M=$(echo "$DURATION_HMS" | cut -d ':' -f 2)
DURATION_S=$(echo "$DURATION_HMS" | cut -d ':' -f 3 | cut -d '.' -f 1)
let "DURATION = ( DURATION_H * 60 + DURATION_M ) * 60 + DURATION_S"
 
if [ "$DURATION" = '0' ] ; then
        echo "Invalid input video"
        usage
        exit 1
fi
 
if [ "$CHUNK_LEN" = "0" ] ; then
        echo "Invalid chunk size"
        usage
        exit 2
fi
 
if [ -z "$OUT_FILE_FORMAT" ] ; then
        FILE_EXT=$(echo "$IN_FILE" | sed 's/^.*\.\([a-zA-Z0-9]\+\)$/\1/')
        FILE_NAME=$(echo "$IN_FILE" | sed 's/^\(.*\)\.[a-zA-Z0-9]\+$/\1/')
        OUT_FILE_FORMAT="${FILE_NAME}-%03d.${FILE_EXT}"
        echo "Using default output file format : $OUT_FILE_FORMAT"
fi
 
N='1'
OFFSET='0'
let 'N_FILES = DURATION / CHUNK_LEN + 1'
 
while [ "$OFFSET" -lt "$DURATION" ] ; do
        OUT_FILE=$(printf "$OUT_FILE_FORMAT" "$N")
        echo "writing $OUT_FILE ($N/$N_FILES)..."
        ffmpeg -i "$IN_FILE" -vcodec copy -acodec copy -ss "$OFFSET" -t "$CHUNK_LEN" "$OUT_FILE"
        let "N = N + 1"
        let "OFFSET = OFFSET + CHUNK_LEN"
done

PHP: Read Specific Line From File

If you use PHP on Linux, you may try the following to read text for example between 74th and 159th lines:

$text = shell_exec("sed -n '74,159p' path/to/file.log");

This solution is good if your file is large.

How can I hide a TD tag using inline JavaScript or CSS?

If you have more than this in javascript consider some javascript library, e.g. jquery which takes away a little speed, but gives you more readable code.

Your question's code via jquery:

$("td").hide();

Of course there are other javascript libraries out there, as this comparison on wikipedia shows.

How can I run Android emulator for Intel x86 Atom without hardware acceleration on Windows 8 for API 21 and 19?

use bluestacks as a emulator for best performance. blusestack working fast without hardware based emulation

To connect bluestack to android studio.

  • Close Android Studio.
  • Go to adb.exe location.(Bydefault its C:\Users\Tarun\AppData\Local\Android\sdk\platform-tools)
  • Run adb connect localhost:5555 from this location.
  • Start Android Studio and you will get Blue Stack as emulator when you run your app.

How to configure Fiddler to listen to localhost?

And I just found out that on vista 'localhost.' will not work. In this case use '127.0.0.1.' (loopback address with a dot appended to it).

Add column with constant value to pandas dataframe

Super simple in-place assignment: df['new'] = 0

For in-place modification, perform direct assignment. This assignment is broadcasted by pandas for each row.

df = pd.DataFrame('x', index=range(4), columns=list('ABC'))
df

   A  B  C
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x

df['new'] = 'y'
# Same as,
# df.loc[:, 'new'] = 'y'
df

   A  B  C new
0  x  x  x   y
1  x  x  x   y
2  x  x  x   y
3  x  x  x   y

Note for object columns

If you want to add an column of empty lists, here is my advice:

  • Consider not doing this. object columns are bad news in terms of performance. Rethink how your data is structured.
  • Consider storing your data in a sparse data structure. More information: sparse data structures
  • If you must store a column of lists, ensure not to copy the same reference multiple times.

    # Wrong
    df['new'] = [[]] * len(df)
    # Right
    df['new'] = [[] for _ in range(len(df))]
    

Generating a copy: df.assign(new=0)

If you need a copy instead, use DataFrame.assign:

df.assign(new='y')

   A  B  C new
0  x  x  x   y
1  x  x  x   y
2  x  x  x   y
3  x  x  x   y

And, if you need to assign multiple such columns with the same value, this is as simple as,

c = ['new1', 'new2', ...]
df.assign(**dict.fromkeys(c, 'y'))

   A  B  C new1 new2
0  x  x  x    y    y
1  x  x  x    y    y
2  x  x  x    y    y
3  x  x  x    y    y

Multiple column assignment

Finally, if you need to assign multiple columns with different values, you can use assign with a dictionary.

c = {'new1': 'w', 'new2': 'y', 'new3': 'z'}
df.assign(**c)

   A  B  C new1 new2 new3
0  x  x  x    w    y    z
1  x  x  x    w    y    z
2  x  x  x    w    y    z
3  x  x  x    w    y    z

Using setImageDrawable dynamically to set image in an ImageView

btnImg.SetImageDrawable(GetDrawable(Resource.Drawable.button_round_green));

API 23 Android 6.0

How to get Current Directory?

The question is not clear whether the current working directory is wanted or the path of the directory containing the executable.

Most answers seem to answer the latter.

But for the former, and for the second part of the question of creating the file, the C++17 standard now incorporates the filesystem library which simplifies this a lot:

#include <filesystem>
#include <iostream>

std::filesystem::path cwd = std::filesystem::current_path() / "filename.txt";
std::ofstream file(cwd.string());
file.close();

This fetches the current working directory, adds the filename to the path and creates an empty file. Note that the path object takes care of os dependent path handling, so cwd.string() returns an os dependent path string. Neato.

Get bottom and right position of an element

I think

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<div>Testing</div>
<div id="result" style="margin:1em 4em; background:rgb(200,200,255); height:500px"></div>
<div style="background:rgb(200,255,200); height:3000px; width:5000px;"></div>

<script>
(function(){
    var link=$("#result");

    var top = link.offset().top; // position from $(document).offset().top
    var bottom = top + link.height(); // position from $(document).offset().top

    var left = link.offset().left; // position from $(document).offset().left
    var right = left + link.width(); // position from $(document).offset().left

    var bottomFromBottom = $(document).height() - bottom;
    // distance from document's bottom
    var rightFromRight = $(document).width() - right;
    // distance from document's right

    var str="";
    str+="top: "+top+"<br>";
    str+="bottom: "+bottom+"<br>";
    str+="left: "+left+"<br>";
    str+="right: "+right+"<br>";
    str+="bottomFromBottom: "+bottomFromBottom+"<br>";
    str+="rightFromRight: "+rightFromRight+"<br>";
    link.html(str);
})();
</script>

The result are

top: 44
bottom: 544
left: 72
right: 1277
bottomFromBottom: 3068
rightFromRight: 3731

in chrome browser of mine.

When the document is scrollable, $(window).height() returns height of browser viewport, not the width of document of which some parts are hiden in scroll. See http://api.jquery.com/height/ .

Full Page <iframe>

For full-screen frame redirects and similar things I have two methods. Both work fine on mobile and desktop.

Note this are complete cross-browser working, valid HTML files. Just change title and src for your needs.

1. this is my favorite:

<!DOCTYPE html>
<meta charset=utf-8>
<title> Title-1 </title>
<meta name=viewport content="width=device-width">
<style>
 html, body, iframe { height:100%; width:100%; margin:0; border:0; display:block }
</style>
<iframe src=src1></iframe>

<!-- More verbose CSS for better understanding:
  html   { height:100% }
  body   { height:100%; margin:0 }
  iframe { height:100%; width:100%; border:0; display:block }
-->

or 2. something like that, slightly shorter:

<!DOCTYPE html>
<meta charset=utf-8>
<title> Title-2 </title>
<meta name=viewport content="width=device-width">
<iframe src=src2 style="position:absolute; top:0; left:0; width:100%; height:100%; border:0">
</iframe>


Note:
The above examples avoid using height:100vh because old browsers don't know it (maybe moot these days) and height:100vh is not always equal to height:100% on mobile browsers (probably not applicable here). Otherwise, vh simplifies things a little bit, so

3. this is an example using vh (not my favorite, less compatible with little advantage)

<!DOCTYPE html>
<meta charset=utf-8>
<title> Title-3 </title>
<meta name=viewport content="width=device-width">
<style>
 body { margin:0 }
 iframe { display:block; width:100%; height:100vh; border:0 }
</style>
<iframe src=src3></iframe>

Server is already running in Rails

Remove the file: C:/Sites/folder/Pids/Server.pids

Explanation In UNIX land at least we usually track the process id (pid) in a file like server.pid. I think this is doing the same thing here. That file was probably left over from a crash.

SQL Server 2012 can't start because of a login failure

Short answer:
install Remote Server Administration tools on your SQL Server (it's an optional feature of Windows Server), reboot, then run SQL Server configuration manager, access the service settings for each of the services whose logon account starts with "NT Service...", clear out the password fields and restart the service. Under the covers, SQL Server Config manager will assign these virtual accounts the Log On as a Service right, and you'll be on your way.

tl;dr;

There is a catch-22 between default settings for a windows domain and default install of SQL Server 2012.

As mentioned above, default Windows domain setup will indeed prevent you from defining the "log on as a service" right via Group Policy Edit at the local machine (via GUI at least; if you install Powershell ActiveDirectory module (via Remote Server Administration tools download) you can do it by scripting.

And, by default, SQL Server 2012 setup runs services in "virtual accounts" (NT Service\ prefix, e.g, NT Service\MSSQLServer. These are like local machine accounts, not domain accounts, but you still can't assign them log on as service rights if your server is joined to a domain. SQL Server setup attempts to assign the right at install, and the SQL Server Config Management tool likewise attempts to assign the right when you change logon account.

And the beautiful catch-22 is this: SQL Server tools depend on (some component of) RSAT to assign the logon as service right. If you don't happen to have RSAT installed on your member server, SQL Server Config Manager fails silently trying to apply the setting (despite all the gaudy pre-installation verification it runs) and you end up with services that won't start.

The one hint of this requirement that I was able to find in the blizzard of SQL Server and Virtual Account doc was this: https://msdn.microsoft.com/en-us/library/ms143504.aspx#New_Accounts, search for RSAT.

dropping infinite values from dataframes in pandas?

The above solution will modify the infs that are not in the target columns. To remedy that,

lst = [np.inf, -np.inf]
to_replace = {v: lst for v in ['col1', 'col2']}
df.replace(to_replace, np.nan)

Class constants in python

Since Horse is a subclass of Animal, you can just change

print(Animal.SIZES[1])

with

print(self.SIZES[1])

Still, you need to remember that SIZES[1] means "big", so probably you could improve your code by doing something like:

class Animal:
    SIZE_HUGE="Huge"
    SIZE_BIG="Big"
    SIZE_MEDIUM="Medium"
    SIZE_SMALL="Small"

class Horse(Animal):
    def printSize(self):
        print(self.SIZE_BIG)

Alternatively, you could create intermediate classes: HugeAnimal, BigAnimal, and so on. That would be especially helpful if each animal class will contain different logic.

Getting the computer name in Java

I agree with peterh's answer, so for those of you who like to copy and paste instead of 60 more seconds of Googling:

private String getComputerName()
{
    Map<String, String> env = System.getenv();
    if (env.containsKey("COMPUTERNAME"))
        return env.get("COMPUTERNAME");
    else if (env.containsKey("HOSTNAME"))
        return env.get("HOSTNAME");
    else
        return "Unknown Computer";
}

I have tested this in Windows 7 and it works. If peterh was right the else if should take care of Mac and Linux. Maybe someone can test this? You could also implement Brian Roach's answer inside the else if you wanted extra robustness.

How to select following sibling/xml tag using xpath

For completeness - adding to accepted answer above - in case you are interested in any sibling regardless of the element type you can use variation:

following-sibling::*

List All Google Map Marker Images

var pinIcon = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00D900",
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(12, 18)
);

Use stored procedure to insert some data into a table

If you have the table definition to have an IDENTITY column e.g. IDENTITY(1,1) then don't include MyId in your INSERT INTO statement. The point of IDENTITY is it gives it the next unused value as the primary key value.

insert into MYDB.dbo.MainTable (MyFirstName, MyLastName, MyAddress, MyPort)
values(@myFirstName, @myLastName, @myAddress, @myPort)

There is then no need to pass the @MyId parameter into your stored procedure either. So change it to:

CREATE PROCEDURE [dbo].[sp_Test]
@myFirstName nvarchar(50)
,@myLastName nvarchar(50)
,@myAddress nvarchar(MAX)
,@myPort int

AS 

If you want to know what the ID of the newly inserted record is add

SELECT @@IDENTITY

to the end of your procedure. e.g. http://msdn.microsoft.com/en-us/library/ms187342.aspx

You will then be able to pick this up in which ever way you are calling it be it SQL or .NET.

P.s. a better way to show you table definision would have been to script the table and paste the text into your stackoverflow browser window because your screen shot is missing the column properties part where IDENTITY is set via the GUI. To do that right click the table 'Script Table as' --> 'CREATE to' --> Clipboard. You can also do File or New Query Editor Window (all self explanitory) experient and see what you get.

Image inside div has extra space below the image

All you have to do is assign this property:

img {
    display: block;
}

The images by default have this property:

img {
    display: inline;
}

Definition of a Balanced Tree

  1. The height of a node in a tree is the length of the longest path from that node downward to a leaf, counting both the start and end vertices of the path.
  2. A node in a tree is height-balanced if the heights of its subtrees differ by no more than 1.
  3. A tree is height-balanced if all of its nodes are height-balanced.

SQL Greater than, Equal to AND Less Than

declare @starttime datetime = '2012-03-07 22:58:00'

SELECT BookingId, StartTime
FROM Booking
WHERE ABS( DATEDIFF( minute, StartTime, @starttime ) ) <= 60

Clear image on picturebox

For the Sake of Understanding:

Depending on how you're approaching your objective(s), keep in mind that the developer is responsible to Dispose everything that is no longer being used or necessary.

This means: Everything you've created along with your pictureBox (i.e: Graphics, List; etc) shall be disposed whenever it is no longer necessary.

For Instance: Let's say you have a Image File Loaded into your PictureBox, and you wish to somehow Delete that file. If you don't unload the Image File from PictureBox correctly; you won't be able to delete the file, as this will likely throw an Exception saying that the file is being used.

Therefore you'd be required to do something like:

pic_PhotoDisplay.Image.Dispose();
pic_PhotoDisplay.Image = null;
pic_PhotoDisplay.ImageLocation = null;
// Required if you've drawn something in the PictureBox. Just Don't forget to Dispose Graphic.
pic_PhotoDisplay.Update();

// Depending on your approach; Dispose the Graphics with Something Like:
gfx = null;
gfx.Clear();
gfx.Dispose();

Hope this helps you out.

How to enable CORS on Firefox?

I was stucked with this problem for a long time (CORS does not work in FF, but works in Chrome and others). No advice could help. Finally, i found that my local dev subdomain (like sub.example.dev) was not explicitly mentioned in /etc/hosts, thus FF just is not able to find it and shows confusing error message 'Aborted...' in dev tools panel.

Putting the exact subdomain into my local /etc/hosts fixed the problem. /etc/hosts is just a plain-text file in unix systems, so you can open it under the root user and put your subdomain in front of '127.0.0.1' ip address.

Converting NumPy array into Python List structure?

tolist() works fine even if encountered a nested array, say a pandas DataFrame;

my_list = [0,1,2,3,4,5,4,3,2,1,0]
my_dt = pd.DataFrame(my_list)
new_list = [i[0] for i in my_dt.values.tolist()]

print(type(my_list),type(my_dt),type(new_list))

Recommended way to save uploaded files in a servlet application

I post my final way of doing it based on the accepted answer:

@SuppressWarnings("serial")
@WebServlet("/")
@MultipartConfig
public final class DataCollectionServlet extends Controller {

    private static final String UPLOAD_LOCATION_PROPERTY_KEY="upload.location";
    private String uploadsDirName;

    @Override
    public void init() throws ServletException {
        super.init();
        uploadsDirName = property(UPLOAD_LOCATION_PROPERTY_KEY);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // ...
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Collection<Part> parts = req.getParts();
        for (Part part : parts) {
            File save = new File(uploadsDirName, getFilename(part) + "_"
                + System.currentTimeMillis());
            final String absolutePath = save.getAbsolutePath();
            log.debug(absolutePath);
            part.write(absolutePath);
            sc.getRequestDispatcher(DATA_COLLECTION_JSP).forward(req, resp);
        }
    }

    // helpers
    private static String getFilename(Part part) {
        // courtesy of BalusC : http://stackoverflow.com/a/2424824/281545
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String filename = cd.substring(cd.indexOf('=') + 1).trim()
                        .replace("\"", "");
                return filename.substring(filename.lastIndexOf('/') + 1)
                        .substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
            }
        }
        return null;
    }
}

where :

@SuppressWarnings("serial")
class Controller extends HttpServlet {

    static final String DATA_COLLECTION_JSP="/WEB-INF/jsp/data_collection.jsp";
    static ServletContext sc;
    Logger log;
    // private
    // "/WEB-INF/app.properties" also works...
    private static final String PROPERTIES_PATH = "WEB-INF/app.properties";
    private Properties properties;

    @Override
    public void init() throws ServletException {
        super.init();
        // synchronize !
        if (sc == null) sc = getServletContext();
        log = LoggerFactory.getLogger(this.getClass());
        try {
            loadProperties();
        } catch (IOException e) {
            throw new RuntimeException("Can't load properties file", e);
        }
    }

    private void loadProperties() throws IOException {
        try(InputStream is= sc.getResourceAsStream(PROPERTIES_PATH)) {
                if (is == null)
                    throw new RuntimeException("Can't locate properties file");
                properties = new Properties();
                properties.load(is);
        }
    }

    String property(final String key) {
        return properties.getProperty(key);
    }
}

and the /WEB-INF/app.properties :

upload.location=C:/_/

HTH and if you find a bug let me know

Java String split removed empty values

From the documentation of String.split(String regex):

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

So you will have to use the two argument version String.split(String regex, int limit) with a negative value:

String[] split = data.split("\\|",-1);

Doc:

If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

This will not leave out any empty elements, including the trailing ones.

Disable activity slide-in animation when launching new activity?

The FLAG_ACTIVITY_NO_ANIMATION flag works fine for disabling the animation when starting activities.

To disable the similar animation that is triggered when calling finish() on an Activity, i.e the animation slides from right to left instead, you can call overridePendingTransition(0, 0) after calling finish() and the next animation will be excluded.

This also works on the in-animation if you call overridePendingTransition(0, 0) after calling startActivity(...).

Bootstrap throws Uncaught Error: Bootstrap's JavaScript requires jQuery

If your code looks good, verify that jQuery successfully loaded to your server. In my case, the jQuery files were published to the server by my IDE, but the web server only had a 0 KB file stub. With no content, the server failed to serve the file to the browser.

After re-publishing the file and verifying that the server actually received the whole file, then my web page stopped giving me the error.

How to use border with Bootstrap

As of Bootstrap 3, you can use Panel classes:

<div class="panel panel-default">Surrounded by border</div>

In Bootstrap 4, you can use Border classes:

<div class="border border-secondary">Surrounded by border</div>

What is a Memory Heap?

Presumably you mean heap from a memory allocation point of view, not from a data structure point of view (the term has multiple meanings).

A very simple explanation is that the heap is the portion of memory where dynamically allocated memory resides (i.e. memory allocated via malloc). Memory allocated from the heap will remain allocated until one of the following occurs:

  1. The memory is free'd
  2. The program terminates

If all references to allocated memory are lost (e.g. you don't store a pointer to it anymore), you have what is called a memory leak. This is where the memory has still been allocated, but you have no easy way of accessing it anymore. Leaked memory cannot be reclaimed for future memory allocations, but when the program ends the memory will be free'd up by the operating system.

Contrast this with stack memory which is where local variables (those defined within a method) live. Memory allocated on the stack generally only lives until the function returns (there are some exceptions to this, e.g. static local variables).

You can find more information about the heap in this article.

How to get some values from a JSON string in C#?

Create a class like this:

public class Data
{
    public string Id {get; set;}
    public string Name {get; set;}
    public string First_Name {get; set;}
    public string Last_Name {get; set;}
    public string Username {get; set;}
    public string Gender {get; set;}
    public string Locale {get; set;}
}

(I'm not 100% sure, but if that doesn't work you'll need use [DataContract] and [DataMember] for DataContractJsonSerializer.)

Then create JSonSerializer:

private static readonly XmlObjectSerializer Serializer = new DataContractJsonSerializer(typeof(Data));

and deserialize object:

// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(contents);
using(var stream = new MemoryStream(byteArray))
{
    (Data)Serializer.ReadObject(stream);
}

Increase JVM max heap size for Eclipse

--launcher.XXMaxPermSize

256m

Try to bump that value up!

regex match any single character (one character only)

Match any single character

  • Use the dot . character as a wildcard to match any single character.

Example regex: a.c

abc   // match
a c   // match
azc   // match
ac    // no match
abbc  // no match

Match any specific character in a set

  • Use square brackets [] to match any characters in a set.
  • Use \w to match any single alphanumeric character: 0-9, a-z, A-Z, and _ (underscore).
  • Use \d to match any single digit.
  • Use \s to match any single whitespace character.

Example 1 regex: a[bcd]c

abc   // match
acc   // match
adc   // match
ac    // no match
abbc  // no match

Example 2 regex: a[0-7]c

a0c   // match
a3c   // match
a7c   // match
a8c   // no match
ac    // no match
a55c  // no match

Match any character except ...

Use the hat in square brackets [^] to match any single character except for any of the characters that come after the hat ^.

Example regex: a[^abc]c

aac   // no match
abc   // no match
acc   // no match
a c   // match
azc   // match
ac    // no match
azzc  // no match

(Don't confuse the ^ here in [^] with its other usage as the start of line character: ^ = line start, $ = line end.)

Match any character optionally

Use the optional character ? after any character to specify zero or one occurrence of that character. Thus, you would use .? to match any single character optionally.

Example regex: a.?c

abc   // match
a c   // match
azc   // match
ac    // match
abbc  // no match

See also

How can I add to a List's first position?

You do that by inserting into position 0:

List myList = new List();
myList.Insert(0, "test");

How to set value to variable using 'execute' in t-sql?

You can try like below

DECLARE @sqlCommand NVARCHAR(4000)
DECLARE @ID INT
DECLARE @Name NVARCHAR(100)
SET @ID = 4
SET @sqlCommand = 'SELECT @Name = [Name]
FROM [AdventureWorks2014].[HumanResources].[Department]
WHERE DepartmentID = @ID'
EXEC sp_executesql @sqlCommand, N'@ID INT, @Name NVARCHAR(100) OUTPUT',
@ID = @ID, @Name = @Name OUTPUT
SELECT @Name ReturnedName

Source : blog.sqlauthority.com

How do I concatenate two strings in Java?

In java concatenate symbol is "+". If you are trying to concatenate two or three strings while using jdbc then use this:

String u = t1.getString();
String v = t2.getString();
String w = t3.getString();
String X = u + "" + v + "" + w;
st.setString(1, X);

Here "" is used for space only.

How do I create a basic UIButton programmatically?

UIButton *saveLibrary=[UIButton buttonWithType:UIButtonTypeCustom];

[saveLibrary setTitle:@"Library" forState:UIControlStateNormal];

[saveLibrary setBackgroundColor:[UIColor redColor]];

[saveLibrary addTarget:self 
action:@selector(saveOnGalleryButtonIsPressed) forControlEvents:UIControlEventTouchUpInside];

[saveLibrary setImage:[UIImage imageWithContentsOfFile:[[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"/library225.png"]]forState:UIControlStateNormal];

saveLibrary.frame=CGRectMake(323, 15, 75, 75);  

[self.view addSubview:saveLibrary];

Pretty-Print JSON Data to a File using Python

You could redirect a file to python and open using the tool and to read it use more.

The sample code will be,

cat filename.json | python -m json.tool | more

Gmail Error :The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required

If your are using gmail.

  • 1-logon to your account

    2- browse this link

    3- Allow less secure apps: ON

Enjoy....

GridView sorting: SortDirection always Ascending

This is another way of solving the issue:

protected void grdHeader_OnSorting(object sender, GridViewSortEventArgs e)
{
    List<V_ReportPeriodStatusEntity> items = GetPeriodStatusesForScreenSelection();
    items.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e);
    grdHeader.DataSource = items;
    grdHeader.DataBind();
}

private string ConvertSortDirectionToSql(GridViewSortEventArgs e)
{
    ViewState[e.SortExpression] = ViewState[e.SortExpression] ?? "ASC";
    ViewState[e.SortExpression] = (ViewState[e.SortExpression].ToString() == "ASC") ? "DESC" : "ASC";
    return ViewState[e.SortExpression].ToString();
}

Call of overloaded function is ambiguous

Cast the value so the compiler knows which function to call:

p.setval(static_cast<const char *>( 0 ));

Note, that you have a segmentation fault in your code after you get it to compile (depending on which function you really wanted to call).

Declare a Range relative to the Active Cell with VBA

Like this:

Dim rng as Range
Set rng = ActiveCell.Resize(numRows, numCols)

then read the contents of that range to an array:

Dim arr As Variant
arr = rng.Value
'arr is now a two-dimensional array of size (numRows, numCols)

or, select the range (I don't think that's what you really want, but you ask for this in the question).

rng.Select

How to run a class from Jar which is not the Main-Class in its Manifest file

First of all jar creates a jar, and does not run it. Try java -jar instead.

Second, why do you pass the class twice, as FQCN (com.mycomp.myproj.dir2.MainClass2) and as file (com/mycomp/myproj/dir2/MainClass2.class)?

Edit:

It seems as if java -jar requires a main class to be specified. You could try java -cp your.jar com.mycomp.myproj.dir2.MainClass2 ... instead. -cp sets the jar on the classpath and enables java to look up the main class there.

jQuery if statement, syntax

To add to what the others are saying, A and B can be function calls as well that return boolean values. If A returns false then B would never be called.

if (A() && B()) {
    // if A() returns false then B() is never called...
}

How to read file with space separated values in pandas

you can use regex as the delimiter:

pd.read_csv("whitespace.csv", header=None, delimiter=r"\s+")

Paramiko's SSHClient with SFTP

If you have a SSHClient, you can also use open_sftp():

import paramiko


# lets say you have SSH client...
client = paramiko.SSHClient()

sftp = client.open_sftp()

# then you can use upload & download as shown above
...

HashMap to return default value for non-found keys?

Can't you just create a static method that does exactly this?

private static <K, V> V getOrDefault(Map<K,V> map, K key, V defaultValue) {
    return map.containsKey(key) ? map.get(key) : defaultValue;
}

Is there a way to make numbers in an ordered list bold?

You also could put <span style="font-weight:normal"> around a,b,c and then bold the ul in the CSS.

Example

ul {
    font-weight: bold;
}

<ul><li><span style="font-weight:normal">a</span></li></ul>

Assigning multiple styles on an HTML element

The way you have used the HTML syntax is problematic.

This is how the syntax should be

style="property1:value1;property2:value2"

In your case, this will be the way to do

<h2 style="text-align :center; font-family :tahoma" >TITLE</h2>

A further example would be as follows

<div class ="row">
    <button type="button" style= "margin-top : 20px; border-radius: 15px" 
    class="btn btn-primary">View Full Profile</button>
</div>

javascript setTimeout() not working

Use:

setTimeout(startTimer,startInterval); 

You're calling startTimer() and feed it's result (which is undefined) as an argument to setTimeout().

User Control - Custom Properties

It is very simple, just add a property:

public string Value {
  get { return textBox1.Text; }
  set { textBox1.Text = value; }
}

Using the Text property is a bit trickier, the UserControl class intentionally hides it. You'll need to override the attributes to put it back in working order:

[Browsable(true), EditorBrowsable(EditorBrowsableState.Always), Bindable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override string Text {
  get { return textBox1.Text; }
  set { textBox1.Text = value; }
}

How to get first item from a java.util.Set?

I just had the same problem and found your question here ...

This was my solution:

Set<Integer> mySetOfIntegers = new HashSet<Integer>();
/* ... there's at least one integer in the set ... */

Integer iFirstItemInSet = new ArrayList<Integer>(mySetOfIntegers).get(0);

How to tell if string starts with a number with Python?

Surprising that after such a long time there is still the best answer missing.

The downside of the other answers is using [0] to select the first character, but as noted, this breaks on the empty string.

Using the following circumvents this problem, and, in my opinion, gives the prettiest and most readable syntax of the options we have. It also does not import/bother with regex either):

>>> string = '1abc'
>>> string[:1].isdigit()
True

>>> string = ''
>>> string[:1].isdigit()
False

SET NOCOUNT ON usage

SET NOCOUNT ON;

This line of code is used in SQL for not returning the number rows affected in the execution of the query. If we don't require the number of rows affected, we can use this as this would help in saving memory usage and increase the speeed of execution of the query.

With Twitter Bootstrap, how can I customize the h1 text color of one page and leave the other pages to be default?

In addition to @Connor Leech's answer.

If you want to create a new custom typography type of your own, define the following in your css file.

.text-foo {
  .text-emphasis-variant(#FFFFFF);
}

The mixin text-emphasis-variant is defined in Bootstrap's mixins.less file.

How do I upload a file with metadata using a REST web service?

I realize this is a very old question, but hopefully this will help someone else out as I came upon this post looking for the same thing. I had a similar issue, just that my metadata was a Guid and int. The solution is the same though. You can just make the needed metadata part of the URL.

POST accepting method in your "Controller" class:

public Task<HttpResponseMessage> PostFile(string name, float latitude, float longitude)
{
    //See http://stackoverflow.com/a/10327789/431906 for how to accept a file
    return null;
}

Then in whatever you're registering routes, WebApiConfig.Register(HttpConfiguration config) for me in this case.

config.Routes.MapHttpRoute(
    name: "FooController",
    routeTemplate: "api/{controller}/{name}/{latitude}/{longitude}",
    defaults: new { }
);

SQL Server Operating system error 5: "5(Access is denied.)"

I used Entity framework in my application and had this problem,I seted any permission in folders and windows services and not work, after that I start my application as administrator (right click in exe file and select "run as admin") and that works fine.

How can my iphone app detect its own version number?

Building on Brad Larson's answer, if you have major and minor version info stored in the info plist (as I did on a particular project), this worked well for me:

- (NSString *)appNameAndVersionNumberDisplayString {
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *appDisplayName = [infoDictionary objectForKey:@"CFBundleDisplayName"];
    NSString *majorVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSString *minorVersion = [infoDictionary objectForKey:@"CFBundleVersion"];

    return [NSString stringWithFormat:@"%@, Version %@ (%@)", 
                appDisplayName, majorVersion, minorVersion];
}

Now revving a minor version manually can be a pain, and so using a source repository revision number trick is ideal. If you've not tied that in (as I hadn't), the above snippet can be useful. It also pulls out the app's display name.

Downloading jQuery UI CSS from Google's CDN

I would think so. Why not? Wouldn't be much of a CDN w/o offering the CSS to support the script files

This link suggests that they are:

We find it particularly exciting that the jQuery UI CSS themes are now hosted on Google's Ajax Libraries CDN.

How can I verify if one list is a subset of another?

If you are asking if one list is "contained" in another list then:

>>>if listA in listB: return True

If you are asking if each element in listA has an equal number of matching elements in listB try:

all(True if listA.count(item) <= listB.count(item) else False for item in listA)

Set value for particular cell in pandas DataFrame with iloc

To modify the value in a cell at the intersection of row "r" (in column "A") and column "C"

  1. retrieve the index of the row "r" in column "A"

        i = df[ df['A']=='r' ].index.values[0]
    
  2. modify the value in the desired column "C"

        df.loc[i,"C"]="newValue"
    

Note: before, be sure to reset the index of rows ...to have a nice index list!

        df=df.reset_index(drop=True)

List Highest Correlation Pairs from a Large Correlation Matrix in Pandas?

I was trying some of the solutions here but then I actually came up with my own one. I hope this might be useful for the next one so I share it here:

def sort_correlation_matrix(correlation_matrix):
    cor = correlation_matrix.abs()
    top_col = cor[cor.columns[0]][1:]
    top_col = top_col.sort_values(ascending=False)
    ordered_columns = [cor.columns[0]] + top_col.index.tolist()
    return correlation_matrix[ordered_columns].reindex(ordered_columns)

Tomcat 7.0.43 "INFO: Error parsing HTTP request header"

If you don't want to upgrade your tomcat, Add this line in your catalina.properties

tomcat.util.http.parser.HttpParser.requestTargetAllow=|{}

It works for me http://www.zhoulujun.cn/zhoulujun/html/java/tomcat/2018_0508_8109.html

How to update specific key's value in an associative array in PHP?

This a single solution, in where your_field is a field that will set and new_value is a new value field, that can a function or a single value

foreach ($array as $key => $item) {
   $item["your_field"] = "new_value";
   $array[$key] = $item;
}

In your case new_value will be a date() function

How can we programmatically detect which iOS version is device running on?

[[[UIDevice currentDevice] systemVersion] floatValue]

Preprocessing in scikit learn - single sample - Depreciation warning

.values.reshape(-1,1) will be accepted without alerts/warnings

.reshape(-1,1) will be accepted, but with deprecation war

What is href="#" and why is it used?

Putting the "#" symbol as the href for something means that it points not to a different URL, but rather to another id or name tag on the same page. For example:

<a href="#bottomOfPage">Click to go to the bottom of the page</a>
blah blah
blah blah
...
<a id="bottomOfPage"></a>

However, if there is no id or name then it goes "no where."

Here's another similar question asked HTML Anchors with 'name' or 'id'?

Why is synchronized block better than synchronized method?

One classic difference between Synchronized block and Synchronized method is that Synchronized method locks the entire object. Synchronized block just locks the code within the block.

Synchronized method: Basically these 2 sync methods disable multithreading. So one thread completes the method1() and the another thread waits for the Thread1 completion.

class SyncExerciseWithSyncMethod {

public synchronized void method1() {
    try {
        System.out.println("In Method 1");
        Thread.sleep(5000);
    } catch (Exception e) {
        System.out.println("Catch of method 1");
    } finally {
        System.out.println("Finally of method 1");
    }

}

public synchronized void method2() {
    try {
        for (int i = 1; i < 10; i++) {
            System.out.println("Method 2 " + i);
            Thread.sleep(1000);
        }
    } catch (Exception e) {
        System.out.println("Catch of method 2");
    } finally {
        System.out.println("Finally of method 2");
    }
}

}

Output

In Method 1

Finally of method 1

Method 2 1

Method 2 2

Method 2 3

Method 2 4

Method 2 5

Method 2 6

Method 2 7

Method 2 8

Method 2 9

Finally of method 2


Synchronized block: Enables multiple threads to access the same object at same time [Enables multi-threading].

class SyncExerciseWithSyncBlock {

public Object lock1 = new Object();
public Object lock2 = new Object();

public void method1() {
    synchronized (lock1) {
        try {
            System.out.println("In Method 1");
            Thread.sleep(5000);
        } catch (Exception e) {
            System.out.println("Catch of method 1");
        } finally {
            System.out.println("Finally of method 1");
        }
    }

}

public void method2() {

    synchronized (lock2) {
        try {
            for (int i = 1; i < 10; i++) {
                System.out.println("Method 2 " + i);
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            System.out.println("Catch of method 2");
        } finally {
            System.out.println("Finally of method 2");
        }
    }
}

}

Output

In Method 1

Method 2 1

Method 2 2

Method 2 3

Method 2 4

Method 2 5

Finally of method 1

Method 2 6

Method 2 7

Method 2 8

Method 2 9

Finally of method 2

How do I find the PublicKeyToken for a particular dll?

I use Windows Explorer, navigate to C:\Windows\assembly , find the one I need. From the Properties you can copy the PublicKeyToken.

This doesn't rely on Visual Studio or any other utilities being installed.

How to set width of mat-table column in angular?

Here's an alternative way of tackling the problem:

Instead of trying to "fix it in post" why don't you truncate the description before the table needs to try and fit it into its columns? I did it like this:

<ng-container matColumnDef="description">
   <th mat-header-cell *matHeaderCellDef> {{ 'Parts.description' | translate }} </th>
            <td mat-cell *matCellDef="let element">
                {{(element.description.length > 80) ? ((element.description).slice(0, 80) + '...') : element.description}}
   </td>
</ng-container>

So I first check if the array is bigger than a certain length, if Yes then truncate and add '...' otherwise pass the value as is. This enables us to still benefit from the auto-spacing the table does :)

enter image description here

How to get current CPU and RAM usage in Python?

To get a line-by-line memory and time analysis of your program, I suggest using memory_profiler and line_profiler.

Installation:

# Time profiler
$ pip install line_profiler
# Memory profiler
$ pip install memory_profiler
# Install the dependency for a faster analysis
$ pip install psutil

The common part is, you specify which function you want to analyse by using the respective decorators.

Example: I have several functions in my Python file main.py that I want to analyse. One of them is linearRegressionfit(). I need to use the decorator @profile that helps me profile the code with respect to both: Time & Memory.

Make the following changes to the function definition

@profile
def linearRegressionfit(Xt,Yt,Xts,Yts):
    lr=LinearRegression()
    model=lr.fit(Xt,Yt)
    predict=lr.predict(Xts)
    # More Code

For Time Profiling,

Run:

$ kernprof -l -v main.py

Output

Total time: 0.181071 s
File: main.py
Function: linearRegressionfit at line 35

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
    35                                           @profile
    36                                           def linearRegressionfit(Xt,Yt,Xts,Yts):
    37         1         52.0     52.0      0.1      lr=LinearRegression()
    38         1      28942.0  28942.0     75.2      model=lr.fit(Xt,Yt)
    39         1       1347.0   1347.0      3.5      predict=lr.predict(Xts)
    40                                           
    41         1       4924.0   4924.0     12.8      print("train Accuracy",lr.score(Xt,Yt))
    42         1       3242.0   3242.0      8.4      print("test Accuracy",lr.score(Xts,Yts))

For Memory Profiling,

Run:

$ python -m memory_profiler main.py

Output

Filename: main.py

Line #    Mem usage    Increment   Line Contents
================================================
    35  125.992 MiB  125.992 MiB   @profile
    36                             def linearRegressionfit(Xt,Yt,Xts,Yts):
    37  125.992 MiB    0.000 MiB       lr=LinearRegression()
    38  130.547 MiB    4.555 MiB       model=lr.fit(Xt,Yt)
    39  130.547 MiB    0.000 MiB       predict=lr.predict(Xts)
    40                             
    41  130.547 MiB    0.000 MiB       print("train Accuracy",lr.score(Xt,Yt))
    42  130.547 MiB    0.000 MiB       print("test Accuracy",lr.score(Xts,Yts))

Also, the memory profiler results can also be plotted using matplotlib using

$ mprof run main.py
$ mprof plot

enter image description here Note: Tested on

line_profiler version == 3.0.2

memory_profiler version == 0.57.0

psutil version == 5.7.0


EDIT: The results from the profilers can be parsed using the TAMPPA package. Using it, we can get line-by-line desired plots as plot

Convert a tensor to numpy array in Tensorflow?

TensorFlow 2.x

Eager Execution is enabled by default, so just call .numpy() on the Tensor object.

import tensorflow as tf

a = tf.constant([[1, 2], [3, 4]])                 
b = tf.add(a, 1)

a.numpy()
# array([[1, 2],
#        [3, 4]], dtype=int32)

b.numpy()
# array([[2, 3],
#        [4, 5]], dtype=int32)

tf.multiply(a, b).numpy()
# array([[ 2,  6],
#        [12, 20]], dtype=int32)

See NumPy Compatibility for more. It is worth noting (from the docs),

Numpy array may share memory with the Tensor object. Any changes to one may be reflected in the other.

Bold emphasis mine. A copy may or may not be returned, and this is an implementation detail based on whether the data is in CPU or GPU (in the latter case, a copy has to be made from GPU to host memory).

But why am I getting AttributeError: 'Tensor' object has no attribute 'numpy'?.
A lot of folks have commented about this issue, there are a couple of possible reasons:

  • TF 2.0 is not correctly installed (in which case, try re-installing), or
  • TF 2.0 is installed, but eager execution is disabled for some reason. In such cases, call tf.compat.v1.enable_eager_execution() to enable it, or see below.

If Eager Execution is disabled, you can build a graph and then run it through tf.compat.v1.Session:

a = tf.constant([[1, 2], [3, 4]])                 
b = tf.add(a, 1)
out = tf.multiply(a, b)

out.eval(session=tf.compat.v1.Session())    
# array([[ 2,  6],
#        [12, 20]], dtype=int32)

See also TF 2.0 Symbols Map for a mapping of the old API to the new one.

Bootstrap - dropdown menu not working?

This is a Rails specific answer, but I had this same problem with Bootstrap dropdown menus in my Rails app. What fixed it was adding this to app/assets/javascripts/application.js:

//= require bootstrap

Hope that helps someone.

Disable back button in react navigation

i think it is simple just add headerLeft : null , i am using react-native cli, so this is the example :

static navigationOptions = {
    headerLeft : null
};

Oracle query to fetch column names

The below query worked for me in Oracle database.

select COLUMN_NAME from ALL_TAB_COLUMNS where TABLE_NAME='MyTableName';

How do you style a TextInput in react native for password input

I am using 0.56RC secureTextEntry={true} Along with password={true} then only its working as mentioned by @NicholasByDesign

How can I strip first X characters from string using sed?

Rather than removing n characters from the start, perhaps you could just extract the digits directly. Like so...

$ echo "pid: 1234" | grep -Po "\d+"

This may be a more robust solution, and seems more intuitive.

How do you get the string length in a batch file?

@ECHO OFF

SET string=
SET /A stringLength=0

:CheckNextLetter
REM Subtract the first letter and count up until the string="".
IF "%string%" NEQ "" (
    SET string=%string:~1%
    SET /A stringLength=%stringLength%+1
    GOTO :CheckNextLetter
) ELSE (
    GOTO :TheEnd
)

:TheEnd
    ECHO There is %stringLength% character^(s^) in the string.
PAUSE

This works for me. Hope this is useful for someone else. No need to adjust for any length. I just remove the first letter and compare against "" until the string equals "".

Twitter Bootstrap 3: How to center a block

It's new in the Bootstrap 3.0.1 release, so make sure you have the latest (10/29)...

Demo: http://bootply.com/91632

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="row">_x000D_
    <div class="center-block" style="width:200px;background-color:#ccc;">...</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Clicking HTML 5 Video element to play, pause video, breaks play button

How about this one

<video class="play-video" muted onclick="this.paused?this.play():this.pause();">
   <source src="" type="video/mp4">
</video>

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)

if you get Software Update server issue: enter image description here

use with sudo:

sudo xcode-select --install

Set default heap size in Windows

Setup JAVA_OPTS as a system variable with the following content:

JAVA_OPTS="-Xms256m -Xmx512m"

After that in a command prompt run the following commands:

SET JAVA_OPTS="-Xms256m -Xmx512m"

This can be explained as follows:

  • allocate at minimum 256MBs of heap
  • allocate at maximum 512MBs of heap

These values should be changed according to application requirements.

EDIT:

You can also try adding it through the Environment Properties menu which can be found at:

  1. From the Desktop, right-click My Computer and click Properties.
  2. Click Advanced System Settings link in the left column.
  3. In the System Properties window click the Environment Variables button.
  4. Click New to add a new variable name and value.
  5. For variable name enter JAVA_OPTS for variable value enter -Xms256m -Xmx512m
  6. Click ok and close the System Properties Tab.
  7. Restart any java applications.

EDIT 2:

JAVA_OPTS is a system variable that stores various settings/configurations for your local Java Virtual Machine. By having JAVA_OPTS set as a system variable all applications running on top of the JVM will take their settings from this parameter.

To setup a system variable you have to complete the steps listed above from 1 to 4.

What is the best alternative IDE to Visual Studio

The other great thing about SharpDevelop is the ability to translate solutions between the two big managed .NET languages VB.NET and C#. I believe it doesn't work for "websites" but it does for web application projects.

Using number_format method in Laravel

If you are using Eloquent the best solution is:

public function getFormattedPriceAttribute()
{
    return number_format($this->attributes['price'], 2);
}

So now you must append formattedPrice in your model and you can use both, price (at its original state) and formattedPrice.

laravel select where and where condition

$userRecord = Model::where([['email','=',$email],['password','=', $password]])->first();

or

$userRecord = self::where([['email','=',$email],['password','=', $password]])->first();

I` think this condition is better then 2 where. Its where condition array in array of where conditions;

pip: no module named _internal

Refer to this issue list

sudo easy_install pip

works for me under Mac OS

For python3, may try sudo easy_install-3.x pip depends on the python 3.x version. Or python3 -m pip install --user --upgrade pip

What is `related_name` used for in Django?

The related_name argument is also useful if you have more complex related class names. For example, if you have a foreign key relationship:

class UserMapDataFrame(models.Model):
    user = models.ForeignKey(User) 

In order to access UserMapDataFrame objects from the related User, the default call would be User.usermapdataframe_set.all(), which it is quite difficult to read.

Using the related_name allows you to specify a simpler or more legible name to get the reverse relation. In this case, if you specify user = models.ForeignKey(User, related_name='map_data'), the call would then be User.map_data.all().

Find location of a removable SD card

Here is the method I use to find a removable SD card. It's complex, and probably overkill for some situations, but it works on a wide variety of Android versions and device manufacturers that I've tested over the last few years. I don't know of any devices since API level 15 on which it doesn't find the SD card, if there is one mounted. It won't return false positives in most cases, especially if you give it the name of a known file to look for.

Please let me know if you run into any cases where it doesn't work.

import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.regex.Pattern;

public class SDCard {
    private static final String TAG = "SDCard";

    /** In some scenarios we can expect to find a specified file or folder on SD cards designed
     * to work with this app. If so, set KNOWNFILE to that filename. It will make our job easier.
     * Set it to null otherwise. */
    private static final String KNOWNFILE = null;

    /** Common paths for microSD card. **/
    private static String[] commonPaths = {
            // Some of these taken from
            // https://stackoverflow.com/questions/13976982/removable-storage-external-sdcard-path-by-manufacturers
            // These are roughly in order such that the earlier ones, if they exist, are more sure
            // to be removable storage than the later ones.
            "/mnt/Removable/MicroSD",
            "/storage/removable/sdcard1", // !< Sony Xperia Z1
            "/Removable/MicroSD", // Asus ZenPad C
            "/removable/microsd",
            "/external_sd", // Samsung
            "/_ExternalSD", // some LGs
            "/storage/extSdCard", // later Samsung
            "/storage/extsdcard", // Main filesystem is case-sensitive; FAT isn't.
            "/mnt/extsd", // some Chinese tablets, e.g. Zeki
            "/storage/sdcard1", // If this exists it's more likely than sdcard0 to be removable.
            "/mnt/extSdCard",
            "/mnt/sdcard/external_sd",
            "/mnt/external_sd",
            "/storage/external_SD",
            "/storage/ext_sd", // HTC One Max
            "/mnt/sdcard/_ExternalSD",
            "/mnt/sdcard-ext",

            "/sdcard2", // HTC One M8s
            "/sdcard1", // Sony Xperia Z
            "/mnt/media_rw/sdcard1",   // 4.4.2 on CyanogenMod S3
            "/mnt/sdcard", // This can be built-in storage (non-removable).
            "/sdcard",
            "/storage/sdcard0",
            "/emmc",
            "/mnt/emmc",
            "/sdcard/sd",
            "/mnt/sdcard/bpemmctest",
            "/mnt/external1",
            "/data/sdext4",
            "/data/sdext3",
            "/data/sdext2",
            "/data/sdext",
            "/storage/microsd" //ASUS ZenFone 2

            // If we ever decide to support USB OTG storage, the following paths could be helpful:
            // An LG Nexus 5 apparently uses usb://1002/UsbStorage/ as a URI to access an SD
            // card over OTG cable. Other models, like Galaxy S5, use /storage/UsbDriveA
            //        "/mnt/usb_storage",
            //        "/mnt/UsbDriveA",
            //        "/mnt/UsbDriveB",
    };

    /** Find path to removable SD card. */
    public static File findSdCardPath(Context context) {
        String[] mountFields;
        BufferedReader bufferedReader = null;
        String lineRead = null;

        /** Possible SD card paths */
        LinkedHashSet<File> candidatePaths = new LinkedHashSet<>();

        /** Build a list of candidate paths, roughly in order of preference. That way if
         * we can't definitively detect removable storage, we at least can pick a more likely
         * candidate. */

        // Could do: use getExternalStorageState(File path), with and without an argument, when
        // available. With an argument is available since API level 21.
        // This may not be necessary, since we also check whether a directory exists and has contents,
        // which would fail if the external storage state is neither MOUNTED nor MOUNTED_READ_ONLY.

        // I moved hard-coded paths toward the end, but we need to make sure we put the ones in
        // backwards order that are returned by the OS. And make sure the iterators respect
        // the order!
        // This is because when multiple "external" storage paths are returned, it's always (in
        // experience, but not guaranteed by documentation) with internal/emulated storage
        // first, removable storage second.

        // Add value of environment variables as candidates, if set:
        // EXTERNAL_STORAGE, SECONDARY_STORAGE, EXTERNAL_SDCARD_STORAGE
        // But note they are *not* necessarily *removable* storage! Especially EXTERNAL_STORAGE.
        // And they are not documented (API) features. Typically useful only for old versions of Android.

        String val = System.getenv("SECONDARY_STORAGE");
        if (!TextUtils.isEmpty(val)) addPath(val, null, candidatePaths);
        val = System.getenv("EXTERNAL_SDCARD_STORAGE");
        if (!TextUtils.isEmpty(val)) addPath(val, null, candidatePaths);

        // Get listing of mounted devices with their properties.
        ArrayList<File> mountedPaths = new ArrayList<>();
        try {
            // Note: Despite restricting some access to /proc (http://stackoverflow.com/a/38728738/423105),
            // Android 7.0 does *not* block access to /proc/mounts, according to our test on George's Alcatel A30 GSM.
            bufferedReader = new BufferedReader(new FileReader("/proc/mounts"));

            // Iterate over each line of the mounts listing.
            while ((lineRead = bufferedReader.readLine()) != null) {
                Log.d(TAG, "\nMounts line: " + lineRead);
                mountFields = lineRead.split(" ");

                // columns: device, mountpoint, fs type, options... Example:
                // /dev/block/vold/179:97 /storage/sdcard1 vfat rw,dirsync,nosuid,nodev,noexec,relatime,uid=1000,gid=1015,fmask=0002,dmask=0002,allow_utime=0020,codepage=cp437,iocharset=iso8859-1,shortname=mixed,utf8,errors=remount-ro 0 0
                String device = mountFields[0], path = mountFields[1], fsType = mountFields[2];

                // The device, path, and fs type must conform to expected patterns.
                if (!(devicePattern.matcher(device).matches() &&
                        pathPattern.matcher(path).matches() &&
                        fsTypePattern.matcher(fsType).matches()) ||
                        // mtdblock is internal, I'm told.
                        device.contains("mtdblock") ||
                        // Check for disqualifying patterns in the path.
                        pathAntiPattern.matcher(path).matches()) {
                    // If this mounts line fails our tests, skip it.
                    continue;
                }

                // TODO maybe: check options to make sure it's mounted RW?
                // The answer at http://stackoverflow.com/a/13648873/423105 does.
                // But it hasn't seemed to be necessary so far in my testing.

                // This line met the criteria so far, so add it to candidate list.
                addPath(path, null, mountedPaths);
            }
        } catch (IOException ignored) {
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException ignored) {
                }
            }
        }

        // Append the paths from mount table to candidate list, in reverse order.
        if (!mountedPaths.isEmpty()) {
            // See https://stackoverflow.com/a/5374346/423105 on why the following is necessary.
            // Basically, .toArray() needs its parameter to know what type of array to return.
            File[] mountedPathsArray = mountedPaths.toArray(new File[mountedPaths.size()]);
            addAncestors(candidatePaths, mountedPathsArray);
        }

        // Add hard-coded known common paths to candidate list:
        addStrings(candidatePaths, commonPaths);

        // If the above doesn't work we could try the following other options, but in my experience they
        // haven't added anything helpful yet.

        // getExternalFilesDir() and getExternalStorageDirectory() typically something app-specific like
        //   /storage/sdcard1/Android/data/com.mybackuparchives.android/files
        // so we want the great-great-grandparent folder.

        // This may be non-removable.
        Log.d(TAG, "Environment.getExternalStorageDirectory():");
        addPath(null, ancestor(Environment.getExternalStorageDirectory()), candidatePaths);

        // Context.getExternalFilesDirs() is only available from API level 19. You can use
        // ContextCompat.getExternalFilesDirs() on earlier APIs, but it only returns one dir anyway.
        Log.d(TAG, "context.getExternalFilesDir(null):");
        addPath(null, ancestor(context.getExternalFilesDir(null)), candidatePaths);

        // "Returns absolute paths to application-specific directories on all external storage
        // devices where the application can place persistent files it owns."
        // We might be able to use these to deduce a higher-level folder that isn't app-specific.
        // Also, we apparently have to call getExternalFilesDir[s](), at least in KITKAT+, in order to ensure that the
        // "external files" directory exists and is available.
        Log.d(TAG, "ContextCompat.getExternalFilesDirs(context, null):");
        addAncestors(candidatePaths, ContextCompat.getExternalFilesDirs(context, null));
        // Very similar results:
        Log.d(TAG, "ContextCompat.getExternalCacheDirs(context):");
        addAncestors(candidatePaths, ContextCompat.getExternalCacheDirs(context));

        // TODO maybe: use getExternalStorageState(File path), with and without an argument, when
        // available. With an argument is available since API level 21.
        // This may not be necessary, since we also check whether a directory exists,
        // which would fail if the external storage state is neither MOUNTED nor MOUNTED_READ_ONLY.

        // A "public" external storage directory. But in my experience it doesn't add anything helpful.
        // Note that you can't pass null, or you'll get an NPE.
        final File publicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
        // Take the parent, because we tend to get a path like /pathTo/sdCard/Music.
        addPath(null, publicDirectory.getParentFile(), candidatePaths);
        // EXTERNAL_STORAGE: may not be removable.
        val = System.getenv("EXTERNAL_STORAGE");
        if (!TextUtils.isEmpty(val)) addPath(val, null, candidatePaths);

        if (candidatePaths.isEmpty()) {
            Log.w(TAG, "No removable microSD card found.");
            return null;
        } else {
            Log.i(TAG, "\nFound potential removable storage locations: " + candidatePaths);
        }

        // Accept or eliminate candidate paths if we can determine whether they're removable storage.
        // In Lollipop and later, we can check isExternalStorageRemovable() status on each candidate.
        if (Build.VERSION.SDK_INT >= 21) {
            Iterator<File> itf = candidatePaths.iterator();
            while (itf.hasNext()) {
                File dir = itf.next();
                // handle illegalArgumentException if the path is not a valid storage device.
                try {
                    if (Environment.isExternalStorageRemovable(dir)
                        // && containsKnownFile(dir)
                            ) {
                        Log.i(TAG, dir.getPath() + " is removable external storage");
                        return dir;
                    } else if (Environment.isExternalStorageEmulated(dir)) {
                        Log.d(TAG, "Removing emulated external storage dir " + dir);
                        itf.remove();
                    }
                } catch (IllegalArgumentException e) {
                    Log.d(TAG, "isRemovable(" + dir.getPath() + "): not a valid storage device.", e);
                }
            }
        }

        // Continue trying to accept or eliminate candidate paths based on whether they're removable storage.
        // On pre-Lollipop, we only have singular externalStorage. Check whether it's removable.
        if (Build.VERSION.SDK_INT >= 9) {
            File externalStorage = Environment.getExternalStorageDirectory();
            Log.d(TAG, String.format(Locale.ROOT, "findSDCardPath: getExternalStorageDirectory = %s", externalStorage.getPath()));
            if (Environment.isExternalStorageRemovable()) {
                // Make sure this is a candidate.
                // TODO: Does this contains() work? Should we be canonicalizing paths before comparing?
                if (candidatePaths.contains(externalStorage)
                    // && containsKnownFile(externalStorage)
                        ) {
                    Log.d(TAG, "Using externalStorage dir " + externalStorage);
                    return externalStorage;
                }
            } else if (Build.VERSION.SDK_INT >= 11 && Environment.isExternalStorageEmulated()) {
                Log.d(TAG, "Removing emulated external storage dir " + externalStorage);
                candidatePaths.remove(externalStorage);
            }
        }

        // If any directory contains our special test file, consider that the microSD card.
        if (KNOWNFILE != null) {
            for (File dir : candidatePaths) {
                Log.d(TAG, String.format(Locale.ROOT, "findSdCardPath: Looking for known file in candidate path, %s", dir));
                if (containsKnownFile(dir)) return dir;
            }
        }

        // If we don't find the known file, still try taking the first candidate.
        if (!candidatePaths.isEmpty()) {
            Log.d(TAG, "No definitive path to SD card; taking the first realistic candidate.");
            return candidatePaths.iterator().next();
        }

        // If no reasonable path was found, give up.
        return null;
    }

    /** Add each path to the collection. */
    private static void addStrings(LinkedHashSet<File> candidatePaths, String[] newPaths) {
        for (String path : newPaths) {
            addPath(path, null, candidatePaths);
        }
    }

    /** Add ancestor of each File to the collection. */
    private static void addAncestors(LinkedHashSet<File> candidatePaths, File[] files) {
        for (int i = files.length - 1; i >= 0; i--) {
            addPath(null, ancestor(files[i]), candidatePaths);
        }
    }

    /**
     * Add a new candidate directory path to our list, if it's not obviously wrong.
     * Supply path as either String or File object.
     * @param strNew path of directory to add (or null)
     * @param fileNew directory to add (or null)
     */
    private static void addPath(String strNew, File fileNew, Collection<File> paths) {
        // If one of the arguments is null, fill it in from the other.
        if (strNew == null) {
            if (fileNew == null) return;
            strNew = fileNew.getPath();
        } else if (fileNew == null) {
            fileNew = new File(strNew);
        }

        if (!paths.contains(fileNew) &&
                // Check for paths known not to be removable SD card.
                // The antipattern check can be redundant, depending on where this is called from.
                !pathAntiPattern.matcher(strNew).matches()) {

            // Eliminate candidate if not a directory or not fully accessible.
            if (fileNew.exists() && fileNew.isDirectory() && fileNew.canExecute()) {
                Log.d(TAG, "  Adding candidate path " + strNew);
                paths.add(fileNew);
            } else {
                Log.d(TAG, String.format(Locale.ROOT, "  Invalid path %s: exists: %b isDir: %b canExec: %b canRead: %b",
                        strNew, fileNew.exists(), fileNew.isDirectory(), fileNew.canExecute(), fileNew.canRead()));
            }
        }
    }

    private static final String ANDROID_DIR = File.separator + "Android";

    private static File ancestor(File dir) {
        // getExternalFilesDir() and getExternalStorageDirectory() typically something app-specific like
        //   /storage/sdcard1/Android/data/com.mybackuparchives.android/files
        // so we want the great-great-grandparent folder.
        if (dir == null) {
            return null;
        } else {
            String path = dir.getAbsolutePath();
            int i = path.indexOf(ANDROID_DIR);
            if (i == -1) {
                return dir;
            } else {
                return new File(path.substring(0, i));
            }
        }
    }

    /** Returns true iff dir contains the special test file.
     * Assumes that dir exists and is a directory. (Is this a necessary assumption?) */
    private static boolean containsKnownFile(File dir) {
        if (KNOWNFILE == null) return false;

        File knownFile = new File(dir, KNOWNFILE);
        return knownFile.exists();
    }

    private static Pattern
            /** Pattern that SD card device should match */
            devicePattern = Pattern.compile("/dev/(block/.*vold.*|fuse)|/mnt/.*"),
    /** Pattern that SD card mount path should match */
    pathPattern = Pattern.compile("/(mnt|storage|external_sd|extsd|_ExternalSD|Removable|.*MicroSD).*",
            Pattern.CASE_INSENSITIVE),
    /** Pattern that the mount path should not match.
     * 'emulated' indicates an internal storage location, so skip it.
     * 'asec' is an encrypted package file, decrypted and mounted as a directory. */
    pathAntiPattern = Pattern.compile(".*(/secure|/asec|/emulated).*"),
    /** These are expected fs types, including vfat. tmpfs is not OK.
     * fuse can be removable SD card (as on Moto E or Asus ZenPad), or can be internal (Huawei G610). */
    fsTypePattern = Pattern.compile(".*(fat|msdos|ntfs|ext[34]|fuse|sdcard|esdfs).*");
}

P.S.

  • Don't forget <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> in the manifest. And at API level 23 and higher, make sure to use checkSelfPermission / requestPermissions.
  • Set KNOWNFILE="myappfile" if there's a file or folder you expect to find on the SD card. That makes detection more accurate.
  • Obviously you'll want to cache the value of findSdCardPath(), rather than recomputing it every time you need it.
  • There's a bunch of logging (Log.d()) in the above code. It helps diagnose any cases where the right path isn't found. Comment it out if you don't want logging.

Execute raw SQL using Doctrine 2

In your model create the raw SQL statement (example below is an example of a date interval I had to use but substitute your own. If you are doing a SELECT add ->fetchall() to the execute() call.

   $sql = "DELETE FROM tmp 
            WHERE lastedit + INTERVAL '5 minute' < NOW() ";

    $stmt = $this->getServiceLocator()
                 ->get('Doctrine\ORM\EntityManager')
                 ->getConnection()
                 ->prepare($sql);

    $stmt->execute();

Waiting for Target Device to Come Online

Did not read all the answers. Anyway Accepted one didn't work for me. What did was upgrading the android studio to last stable version and then created a new virtual device. I guess my nexus 5p virtual device got out of sync with the android studio environment.

Howto? Parameters and LIKE statement SQL

you have to do:

LIKE '%' + @param + '%'

How to specify a port to run a create-react-app based project?

You could use cross-env to set the port, and it will work on Windows, Linux and Mac.

yarn add -D cross-env

then in package.json the start link could be like this:

"start": "cross-env PORT=3006 react-scripts start",

How can I stop .gitignore from appearing in the list of untracked files?

After you add the .gitignore file and commit it, it will no longer show up in the "untracked files" list.

git add .gitignore
git commit -m "add .gitignore file"
git status

Batch - Echo or Variable Not Working

Dont use spaces:

SET @var="GREG"
::instead of SET @var = "GREG"
ECHO %@var%
PAUSE

Case objects vs Enumerations in Scala

UPDATE: The code below has a bug, described here. The test program below works, but if you were to use DayOfWeek.Mon (for example) before DayOfWeek itself, it would fail because DayOfWeek has not been initialized (use of an inner object does not cause an outer object to be initialized). You can still use this code if you do something like val enums = Seq( DayOfWeek ) in your main class, forcing initialization of your enums, or you can use chaotic3quilibrium's modifications. Looking forward to a macro-based enum!


If you want

  • warnings about non-exhaustive pattern matches
  • an Int ID assigned to each enum value, which you can optionally control
  • an immutable List of the enum values, in the order they were defined
  • an immutable Map from name to enum value
  • an immutable Map from id to enum value
  • places to stick methods/data for all or particular enum values, or for the enum as a whole
  • ordered enum values (so you can test, for example, whether day < Wednesday)
  • the ability to extend one enum to create others

then the following may be of interest. Feedback welcome.

In this implementation there are abstract Enum and EnumVal base classes, which you extend. We'll see those classes in a minute, but first, here's how you would define an enum:

object DayOfWeek extends Enum {
  sealed abstract class Val extends EnumVal
  case object Mon extends Val; Mon()
  case object Tue extends Val; Tue()
  case object Wed extends Val; Wed()
  case object Thu extends Val; Thu()
  case object Fri extends Val; Fri()
  case object Sat extends Val; Sat()
  case object Sun extends Val; Sun()
}

Note that you have to use each enum value (call its apply method) to bring it to life. [I wish inner objects weren't lazy unless I specifically ask for them to be. I think.]

We could of course add methods/data to DayOfWeek, Val, or the individual case objects if we so desired.

And here's how you would use such an enum:

object DayOfWeekTest extends App {

  // To get a map from Int id to enum:
  println( DayOfWeek.valuesById )

  // To get a map from String name to enum:
  println( DayOfWeek.valuesByName )

  // To iterate through a list of the enum values in definition order,
  // which can be made different from ID order, and get their IDs and names:
  DayOfWeek.values foreach { v => println( v.id + " = " + v ) }

  // To sort by ID or name:
  println( DayOfWeek.values.sorted mkString ", " )
  println( DayOfWeek.values.sortBy(_.toString) mkString ", " )

  // To look up enum values by name:
  println( DayOfWeek("Tue") ) // Some[DayOfWeek.Val]
  println( DayOfWeek("Xyz") ) // None

  // To look up enum values by id:
  println( DayOfWeek(3) )         // Some[DayOfWeek.Val]
  println( DayOfWeek(9) )         // None

  import DayOfWeek._

  // To compare enums as ordinals:
  println( Tue < Fri )

  // Warnings about non-exhaustive pattern matches:
  def aufDeutsch( day: DayOfWeek.Val ) = day match {
    case Mon => "Montag"
    case Tue => "Dienstag"
    case Wed => "Mittwoch"
    case Thu => "Donnerstag"
    case Fri => "Freitag"
 // Commenting these out causes compiler warning: "match is not exhaustive!"
 // case Sat => "Samstag"
 // case Sun => "Sonntag"
  }

}

Here's what you get when you compile it:

DayOfWeekTest.scala:31: warning: match is not exhaustive!
missing combination            Sat
missing combination            Sun

  def aufDeutsch( day: DayOfWeek.Val ) = day match {
                                         ^
one warning found

You can replace "day match" with "( day: @unchecked ) match" where you don't want such warnings, or simply include a catch-all case at the end.

When you run the above program, you get this output:

Map(0 -> Mon, 5 -> Sat, 1 -> Tue, 6 -> Sun, 2 -> Wed, 3 -> Thu, 4 -> Fri)
Map(Thu -> Thu, Sat -> Sat, Tue -> Tue, Sun -> Sun, Mon -> Mon, Wed -> Wed, Fri -> Fri)
0 = Mon
1 = Tue
2 = Wed
3 = Thu
4 = Fri
5 = Sat
6 = Sun
Mon, Tue, Wed, Thu, Fri, Sat, Sun
Fri, Mon, Sat, Sun, Thu, Tue, Wed
Some(Tue)
None
Some(Thu)
None
true

Note that since the List and Maps are immutable, you can easily remove elements to create subsets, without breaking the enum itself.

Here is the Enum class itself (and EnumVal within it):

abstract class Enum {

  type Val <: EnumVal

  protected var nextId: Int = 0

  private var values_       =       List[Val]()
  private var valuesById_   = Map[Int   ,Val]()
  private var valuesByName_ = Map[String,Val]()

  def values       = values_
  def valuesById   = valuesById_
  def valuesByName = valuesByName_

  def apply( id  : Int    ) = valuesById  .get(id  )  // Some|None
  def apply( name: String ) = valuesByName.get(name)  // Some|None

  // Base class for enum values; it registers the value with the Enum.
  protected abstract class EnumVal extends Ordered[Val] {
    val theVal = this.asInstanceOf[Val]  // only extend EnumVal to Val
    val id = nextId
    def bumpId { nextId += 1 }
    def compare( that:Val ) = this.id - that.id
    def apply() {
      if ( valuesById_.get(id) != None )
        throw new Exception( "cannot init " + this + " enum value twice" )
      bumpId
      values_ ++= List(theVal)
      valuesById_   += ( id       -> theVal )
      valuesByName_ += ( toString -> theVal )
    }
  }

}

And here is a more advanced use of it which controls the IDs and adds data/methods to the Val abstraction and to the enum itself:

object DayOfWeek extends Enum {

  sealed abstract class Val( val isWeekday:Boolean = true ) extends EnumVal {
    def isWeekend = !isWeekday
    val abbrev = toString take 3
  }
  case object    Monday extends Val;    Monday()
  case object   Tuesday extends Val;   Tuesday()
  case object Wednesday extends Val; Wednesday()
  case object  Thursday extends Val;  Thursday()
  case object    Friday extends Val;    Friday()
  nextId = -2
  case object  Saturday extends Val(false); Saturday()
  case object    Sunday extends Val(false);   Sunday()

  val (weekDays,weekendDays) = values partition (_.isWeekday)
}

How to get an Android WakeLock to work?

Try using the ACQUIRE_CAUSES_WAKEUP flag when you create the wake lock. The ON_AFTER_RELEASE flag just resets the activity timer to keep the screen on a bit longer.

http://developer.android.com/reference/android/os/PowerManager.html#ACQUIRE_CAUSES_WAKEUP

UPDATE and REPLACE part of a string

CREATE TABLE tbl_PersonalDetail
(ID INT IDENTITY ,[Date] nvarchar(20), Name nvarchar(20), GenderID int);

INSERT INTO Tbl_PersonalDetail VALUES(N'18-4-2015', N'Monay', 2),
                                     (N'31-3-2015', N'Monay', 2),
                                     (N'28-12-2015', N'Monay', 2),
                                     (N'19-4-2015', N'Monay', 2)

DECLARE @Date Nvarchar(200)

SET @Date = (SELECT [Date] FROM Tbl_PersonalDetail WHERE ID = 2)

Update Tbl_PersonalDetail SET [Date] = (REPLACE(@Date , '-','/')) WHERE ID = 2 

Handling key-press events (F1-F12) using JavaScript and jQuery, cross-browser

Without other external class you can create your personal hack code simply using

event.keyCode

Another help for all, I think is this test page for intercept the keyCode (simply copy and past in new file.html for testing your event).

 <html>
 <head>
 <title>Untitled</title>
 <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
 <style type="text/css">
 td,th{border:2px solid #aaa;}
 </style>
 <script type="text/javascript">
 var t_cel,tc_ln;
 if(document.addEventListener){ //code for Moz
   document.addEventListener("keydown",keyCapt,false); 
   document.addEventListener("keyup",keyCapt,false);
   document.addEventListener("keypress",keyCapt,false);
 }else{
   document.attachEvent("onkeydown",keyCapt); //code for IE
   document.attachEvent("onkeyup",keyCapt); 
   document.attachEvent("onkeypress",keyCapt); 
 }
 function keyCapt(e){
   if(typeof window.event!="undefined"){
    e=window.event;//code for IE
   }
   if(e.type=="keydown"){
    t_cel[0].innerHTML=e.keyCode;
    t_cel[3].innerHTML=e.charCode;
   }else if(e.type=="keyup"){
    t_cel[1].innerHTML=e.keyCode;
    t_cel[4].innerHTML=e.charCode;
   }else if(e.type=="keypress"){
    t_cel[2].innerHTML=e.keyCode;
    t_cel[5].innerHTML=e.charCode;
   }
 }
 window.onload=function(){
   t_cel=document.getElementById("tblOne").getElementsByTagName("td");
   tc_ln=t_cel.length;
 }
 </script>
 </head>
 <body>
 <table id="tblOne">
 <tr>
 <th style="border:none;"></th><th>onkeydown</th><th>onkeyup</th><th>onkeypress</td>
 </tr>
 <tr>
 <th>keyCode</th><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>
 </tr>
 <tr>
 <th>charCode</th><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>
 </tr>
 </table>
 <button onclick="for(i=0;i<tc_ln;i++){t_cel[i].innerHTML='&nbsp;'};">CLEAR</button>
 </body>
 </html>

Here is a working demo so you can try it right here:

_x000D_
_x000D_
var t_cel, tc_ln;_x000D_
if (document.addEventListener) { //code for Moz_x000D_
  document.addEventListener("keydown", keyCapt, false);_x000D_
  document.addEventListener("keyup", keyCapt, false);_x000D_
  document.addEventListener("keypress", keyCapt, false);_x000D_
} else {_x000D_
  document.attachEvent("onkeydown", keyCapt); //code for IE_x000D_
  document.attachEvent("onkeyup", keyCapt);_x000D_
  document.attachEvent("onkeypress", keyCapt);_x000D_
}_x000D_
_x000D_
function keyCapt(e) {_x000D_
  if (typeof window.event != "undefined") {_x000D_
    e = window.event; //code for IE_x000D_
  }_x000D_
  if (e.type == "keydown") {_x000D_
    t_cel[0].innerHTML = e.keyCode;_x000D_
    t_cel[3].innerHTML = e.charCode;_x000D_
  } else if (e.type == "keyup") {_x000D_
    t_cel[1].innerHTML = e.keyCode;_x000D_
    t_cel[4].innerHTML = e.charCode;_x000D_
  } else if (e.type == "keypress") {_x000D_
    t_cel[2].innerHTML = e.keyCode;_x000D_
    t_cel[5].innerHTML = e.charCode;_x000D_
  }_x000D_
}_x000D_
window.onload = function() {_x000D_
  t_cel = document.getElementById("tblOne").getElementsByTagName("td");_x000D_
  tc_ln = t_cel.length;_x000D_
}
_x000D_
td,_x000D_
th {_x000D_
  border: 2px solid #aaa;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <title>Untitled</title>_x000D_
  <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <table id="tblOne">_x000D_
    <tr>_x000D_
      <th style="border:none;"></th>_x000D_
      <th>onkeydown</th>_x000D_
      <th>onkeyup</th>_x000D_
      <th>onkeypress</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <th>keyCode</th>_x000D_
      <td>&nbsp;</td>_x000D_
      <td>&nbsp;</td>_x000D_
      <td>&nbsp;</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <th>charCode</th>_x000D_
      <td>&nbsp;</td>_x000D_
      <td>&nbsp;</td>_x000D_
      <td>&nbsp;</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
  <button onclick="for(i=0;i<tc_ln;i++){t_cel[i].innerHTML='&nbsp;'};">CLEAR</button>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to count the number of letters in a string without the spaces?

I found this is working perfectly

str = "count a character occurance"
str = str.replace(' ', '')
print (str)
print (len(str))

Given an array of numbers, return array of products of all other numbers (no division)

// This is the recursive solution in Java // Called as following from main product(a,1,0);

public static double product(double[] a, double fwdprod, int index){
    double revprod = 1;
    if (index < a.length){
        revprod = product2(a, fwdprod*a[index], index+1);
        double cur = a[index];
        a[index] = fwdprod * revprod;
        revprod *= cur;
    }
    return revprod;
}