Programs & Examples On #Audio fingerprinting

An audio fingerprint is a hash code of some digital audio, with the additional properties that it is tolerant of noise and distortion, and can be reproduced without synchronizing with the start of the audio. Audio fingerprints can be used to compare sampled audio with a library of known published audio.

Unable to capture screenshot. Prevented by security policy. Galaxy S6. Android 6.0

You must have either disabled, froze or uninstalled FaceProvider in settings>applications>all
This will only happen if it's frozen, either uninstall it, or enable it.

Where does Android app package gets installed on phone

You will find the application folder at:

/data/data/"your package name"

you can access this folder using the DDMS for your Emulator. you can't access this location on a real device unless you have a rooted device.

How to clear text area with a button in html using javascript?

Change in your html with adding the function on the button click

 <input type="button" value="Clear" onclick="javascript:eraseText();"> 
    <textarea id='output' rows=20 cols=90></textarea>

Try this in your js file:

function eraseText() {
    document.getElementById("output").value = "";
}

Search all tables, all columns for a specific value SQL Server

The below Query works but very slow... copied from vyaskn.tripod.com

Declare @SearchStr nvarchar(100)

SET  @SearchStr='Search String' BEGIN

CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128),
 @SearchStr2 nvarchar(110)  SET  @TableName = ''    SET @SearchStr2 =
 QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL    
BEGIN       
  SET @ColumnName = ''      
  SET @TableName =  (
    SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' +
    QUOTENAME(TABLE_NAME)) FROM INFORMATION_SCHEMA.TABLES 
    WHERE
    TABLE_TYPE = 'BASE TABLE'
    AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
    AND OBJECTPROPERTY(
      OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)),
        'IsMSShipped') = 0)

  WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)      
  BEGIN
    SET @ColumnName = (
      SELECT MIN(QUOTENAME(COLUMN_NAME))
      FROM INFORMATION_SCHEMA.COLUMNS
      WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
        AND TABLE_NAME = PARSENAME(@TableName, 1)
      AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
      AND QUOTENAME(COLUMN_NAME) > @ColumnName)
      IF @ColumnName IS NOT NULL            
      BEGIN
      INSERT INTO #Results
      EXEC
      (
        'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + 
          ', 3630) FROM ' + @TableName + ' (NOLOCK) ' +
        ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
      )             
      END       
    END     
  END

  SELECT ColumnName, ColumnValue FROM #Results END

OWIN Security - How to Implement OAuth2 Refresh Tokens

Just implemented my OWIN Service with Bearer (called access_token in the following) and Refresh Tokens. My insight into this is that you can use different flows. So it depends on the flow you want to use how you set your access_token and refresh_token expiration times.

I will describe two flows A and B in the follwing (I suggest what you want to have is flow B):

A) expiration time of access_token and refresh_token are the same as it is per default 1200 seconds or 20 minutes. This flow needs your client first to send client_id and client_secret with login data to get an access_token, refresh_token and expiration_time. With the refresh_token it is now possible to get a new access_token for 20 minutes (or whatever you set the AccessTokenExpireTimeSpan in the OAuthAuthorizationServerOptions to). For the reason that the expiration time of access_token and refresh_token are the same, your client is responsible to get a new access_token before the expiration time! E.g. your client could send a refresh POST call to your token endpoint with the body (remark: you should use https in production)

grant_type=refresh_token&client_id=xxxxxx&refresh_token=xxxxxxxx-xxxx-xxxx-xxxx-xxxxx

to get a new token after e.g. 19 minutes to prevent the tokens from expiration.

B) in this flow you want to have a short term expiration for your access_token and a long term expiration for your refresh_token. Lets assume for test purpose you set the access_token to expire in 10 seconds (AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(10)) and the refresh_token to 5 Minutes. Now it comes to the interesting part setting the expiration time of refresh_token: You do this in your createAsync function in SimpleRefreshTokenProvider class like this:

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


        //copy properties and set the desired lifetime of refresh token
        var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary)
        {
            IssuedUtc = context.Ticket.Properties.IssuedUtc,
            ExpiresUtc = DateTime.UtcNow.AddMinutes(5) //SET DATETIME to 5 Minutes
            //ExpiresUtc = DateTime.UtcNow.AddMonths(3) 
        };
        /*CREATE A NEW TICKET WITH EXPIRATION TIME OF 5 MINUTES 
         *INCLUDING THE VALUES OF THE CONTEXT TICKET: SO ALL WE 
         *DO HERE IS TO ADD THE PROPERTIES IssuedUtc and 
         *ExpiredUtc to the TICKET*/
        var refreshTokenTicket = new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties);

        //saving the new refreshTokenTicket to a local var of Type ConcurrentDictionary<string,AuthenticationTicket>
        // consider storing only the hash of the handle
        RefreshTokens.TryAdd(guid, refreshTokenTicket);            
        context.SetToken(guid);

Now your client is able to send a POST call with a refresh_token to your token endpoint when the access_token is expired. The body part of the call may look like this: grant_type=refresh_token&client_id=xxxxxx&refresh_token=xxxxxxxx-xxxx-xxxx-xxxx-xx

One important thing is that you may want to use this code not only in your CreateAsync function but also in your Create function. So you should consider to use your own function (e.g. called CreateTokenInternal) for the above code. Here you can find implementations of different flows including refresh_token flow(but without setting the expiration time of the refresh_token)

Here is one sample implementation of IAuthenticationTokenProvider on github (with setting the expiration time of the refresh_token)

I am sorry that I can't help out with further materials than the OAuth Specs and the Microsoft API Documentation. I would post the links here but my reputation doesn't let me post more than 2 links....

I hope this may help some others to spare time when trying to implement OAuth2.0 with refresh_token expiration time different to access_token expiration time. I couldn't find an example implementation on the web (except the one of thinktecture linked above) and it took me some hours of investigation until it worked for me.

New info: In my case I have two different possibilities to receive tokens. One is to receive a valid access_token. There I have to send a POST call with a String body in format application/x-www-form-urlencoded with the following data

client_id=YOURCLIENTID&grant_type=password&username=YOURUSERNAME&password=YOURPASSWORD

Second is if access_token is not valid anymore we can try the refresh_token by sending a POST call with a String body in format application/x-www-form-urlencoded with the following data grant_type=refresh_token&client_id=YOURCLIENTID&refresh_token=YOURREFRESHTOKENGUID

What is the difference between include and require in Ruby?

From Programming Ruby 1.9

We’ll make a couple of points about the include statement before we go on. First, it has nothing to do with files. C programmers use a preprocessor directive called #include to insert the contents of one file into another during compilation. The Ruby include statement simply makes a reference to a module. If that module is in a separate file, you must use require (or its less commonly used cousin, load) to drag that file in before using include. Second, a Ruby include does not simply copy the module’s instance methods into the class. Instead, it makes a reference from the class to the included module. If multiple classes include that module, they’ll all point to the same thing. If you change the definition of a method within a module, even while your program is running, all classes that include that module will exhibit the new behavior.

PKIX path building failed in Java application

Per your pastebin, you need to add the proxy.tkk.com certificate to the truststore.

vertical divider between two columns in bootstrap

To fix the ugly look of a divider being too short when the content of one column is taller, add borders to all columns. Give every other column a negative margin to compensate for position differences.

For example, my three column classes:

.border-right {
    border-right: 1px solid #ddd;
}
.borders {
    border-left: 1px solid #ddd;
    border-right: 1px solid #ddd;
    margin: -1px;
}
.border-left {
    border-left: 1px solid #ddd;
}

And the HTML:

<div class="col-sm-4 border-right">First</div>
<div class="col-sm-4 borders">Second</div>
<div class="col-sm-4 border-left">Third</div>

Make sure you use #ddd if you want the same color as Bootstrap's horizontal dividers.

What's the difference between including files with JSP include directive, JSP include action and using JSP Tag Files?

Possible Duplicate Question

<@include> - The directive tag instructs the JSP compiler to merge contents of the included file into the JSP before creating the generated servlet code. It is the equivalent to cutting and pasting the text from your include page right into your JSP.

  • Only one servlet is executed at run time.
  • Scriptlet variables declared in the parent page can be accessed in the included page (remember, they are the same page).
  • The included page does not need to able to be compiled as a standalone JSP. It can be a code fragment or plain text. The included page will never be compiled as a standalone. The included page can also have any extension, though .jspf has become a conventionally used extension.
  • One drawback on older containers is that changes to the include pages may not take effect until the parent page is updated. Recent versions of Tomcat will check the include pages for updates and force a recompile of the parent if they're updated.
  • A further drawback is that since the code is inlined directly into the service method of the generated servlet, the method can grow very large. If it exceeds 64 KB, your JSP compilation will likely fail.

<jsp:include> - The JSP Action tag on the other hand instructs the container to pause the execution of this page, go run the included page, and merge the output from that page into the output from this page.

  • Each included page is executed as a separate servlet at run time.
  • Pages can conditionally be included at run time. This is often useful for templating frameworks that build pages out of includes. The parent page can determine which page, if any, to include according to some run-time condition.
  • The values of scriptlet variables need to be explicitly passed to the include page.
  • The included page must be able to be run on its own.
  • You are less likely to run into compilation errors due to the maximum method size being exceeded in the generated servlet class.

Depending on your needs, you may either use <@include> or <jsp:include>

How to close a thread from within?

How about sys.exit() from the module sys.

If sys.exit() is executed from within a thread it will close that thread only.

This answer here talks about that: Why does sys.exit() not exit when called inside a thread in Python?

How to output only captured groups with sed?

Sed has up to nine remembered patterns but you need to use escaped parentheses to remember portions of the regular expression.

See here for examples and more detail

How to clone all remote branches in Git?

Here's an answer that uses awk. This method should suffice if used on a new repo.

git branch -r | awk -F/ '{ system("git checkout " $NF) }'

Existing branches will simply be checked out, or declared as already in it, but filters can be added to avoid the conflicts.

It can also be modified so it calls an explicit git checkout -b <branch> -t <remote>/<branch> command.

This answer follows Nikos C.'s idea.


Alternatively we can specify the remote branch instead. This is based on murphytalk's answer.

git branch -r | awk '{ system("git checkout -t " $NF) }'

It throws fatal error messages on conflicts but I see them harmless.


Both commands can be aliased.

Using nobody's answer as reference, we can have the following commands to create the aliases:

git config --global alias.clone-branches '! git branch -r | awk -F/ "{ system(\"git checkout \" \$NF) }"'
git config --global alias.clone-branches '! git branch -r | awk "{ system(\"git checkout -t \" \$NF) }"'

Personally I'd use track-all or track-all-branches.

ModuleNotFoundError: What does it mean __main__ is not a package?

The problem still not resolved after remove the '.', then it start points the error to my folder. As i added this folder first time then i restarted the PyCharm and it automatically resolved the issue

Change background color for selected ListBox item

I've tried various solutions and none worked for me, after some more research I've found a solution that worked for me here

https://gist.github.com/LGM-AdrianHum/c8cb125bc493c1ccac99b4098c7eeb60

   <Style x:Key="_ListBoxItemStyle" TargetType="ListBoxItem">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListBoxItem">
                        <Border Name="_Border"
                                Padding="2"
                                SnapsToDevicePixels="true">
                            <ContentPresenter />
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsSelected" Value="true">
                                <Setter TargetName="_Border" Property="Background" Value="Yellow"/>
                                <Setter Property="Foreground" Value="Red"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

 <ListBox ItemContainerStyle="{DynamicResource _ListBoxItemStyle}"
                 Width="200" Height="250"
                 ScrollViewer.VerticalScrollBarVisibility="Auto"
                 ScrollViewer.HorizontalScrollBarVisibility="Auto">
            <ListBoxItem>Hello</ListBoxItem>
            <ListBoxItem>Hi</ListBoxItem>
        </ListBox>

I posted it here, as this is the first google result for this problem so some others may find it useful.

Python: count repeated elements in the list

Use Counter

>>> from collections import Counter
>>> MyList = ["a", "b", "a", "c", "c", "a", "c"]
>>> c = Counter(MyList)
>>> c
Counter({'a': 3, 'c': 3, 'b': 1})

How to work with progress indicator in flutter?

In flutter, there are a few ways to deal with Asynchronous actions.

A lazy way to do it can be using a modal. Which will block the user input, thus preventing any unwanted actions. This would require very little change to your code. Just modifying your _onLoading to something like this :

void _onLoading() {
  showDialog(
    context: context,
    barrierDismissible: false,
    builder: (BuildContext context) {
      return Dialog(
        child: new Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            new CircularProgressIndicator(),
            new Text("Loading"),
          ],
        ),
      );
    },
  );
  new Future.delayed(new Duration(seconds: 3), () {
    Navigator.pop(context); //pop dialog
    _login();
  });
}

The most ideal way to do it is using FutureBuilder and a stateful widget. Which is what you started. The trick is that, instead of having a boolean loading = false in your state, you can directly use a Future<MyUser> user

And then pass it as argument to FutureBuilder, which will give you some info such as "hasData" or the instance of MyUser when completed.

This would lead to something like this :

@immutable
class MyUser {
  final String name;

  MyUser(this.name);
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Future<MyUser> user;

  void _logIn() {
    setState(() {
      user = new Future.delayed(const Duration(seconds: 3), () {
        return new MyUser("Toto");
      });
    });
  }

  Widget _buildForm(AsyncSnapshot<MyUser> snapshot) {
    var floatBtn = new RaisedButton(
      onPressed:
          snapshot.connectionState == ConnectionState.none ? _logIn : null,
      child: new Icon(Icons.save),
    );
    var action =
        snapshot.connectionState != ConnectionState.none && !snapshot.hasData
            ? new Stack(
                alignment: FractionalOffset.center,
                children: <Widget>[
                  floatBtn,
                  new CircularProgressIndicator(
                    backgroundColor: Colors.red,
                  ),
                ],
              )
            : floatBtn;

    return new ListView(
      padding: const EdgeInsets.all(15.0),
        children: <Widget>[
          new ListTile(
            title: new TextField(),
          ),
          new ListTile(
            title: new TextField(obscureText: true),
          ),
          new Center(child: action)
        ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return new FutureBuilder(
      future: user,
      builder: (context, AsyncSnapshot<MyUser> snapshot) {
        if (snapshot.hasData) {
          return new Scaffold(
            appBar: new AppBar(
              title: new Text("Hello ${snapshot.data.name}"),
            ),
          );
        } else {
          return new Scaffold(
            appBar: new AppBar(
              title: new Text("Connection"),
            ),
            body: _buildForm(snapshot),
          );
        }
      },
    );
  }
}

How to set CATALINA_HOME variable in windows 7?

There is no requirement of setting CATALINA-HOME.

Follow below instruction .

Right click on computer --> properties --> Advanced system setting --> Environment variables.

User variables section --> click on "New" --> variable name : CLASSPATH , variable value : D:\java\lib*.;D:\tomcat8\lib\servlet-api.jar.; --> Click "Ok"

New --> variable name : PATH , variable value : D:\java\bin; --> Click "Ok"

System variables section:-

Click on "New" --> variable name : PATH , variable value : D:\java\jre --> Click "Ok"

I've installed java and tomcat in D drive henceforth the locations above are under my respective paths.

Give location paths where java and tomcat are installed in your PC. Thank You

How to convert a huge list-of-vector to a matrix more efficiently?

It would help to have sample information about your output. Recursively using rbind on bigger and bigger things is not recommended. My first guess at something that would help you:

z <- list(1:3,4:6,7:9)
do.call(rbind,z)

See a related question for more efficiency, if needed.

Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?

Any logic having to do with what is displayed in the view should be delegated to a helper method, as methods in the model are strictly for handling data.

Here is what you could do:

# In the helper...

def link_to_thing(text, thing)
  (thing.url?) ? link_to(text, thing_path(thing)) : link_to(text, thing.url)
end

# In the view...

<%= link_to_thing("text", @thing) %>

How do I shrink my SQL Server Database?

This is an old question but I just happened upon it.

The really short and a correct answer is already given and has the most votes. That is how you shrink a transaction log, and that was probably the OPs problem. And when the transaction log has grown out of control, it often needs to be shrunk back, but care should be taken to prevent future situations of a log growing out of control. This question on dba.se explains that. Basically - Don't let it get that large in the first place through proper recovery model, transaction log maintenance, transaction management, etc.

But the bigger question in my mind when reading this question about shrinking the data file (or even the log file) is why? and what bad things happen when you try? It appears as though shrink operations were done. Now in this case it makes sense in a sense - because MSDE/Express editions are capped at max DB size. But the right answer may be to look at the right version for your needs. And if you stumble upon this question looking to shrink your production database and this isn't the reason why, you should ask yourself the why? question.

I don't want someone searching the web for "how to shrink a database" coming across this and thinking it is a cool or acceptable thing to do.

Shrinking Data Files is a special task that should be reserved for special occasions. Consider that when you shrink a database, you are effectively fragmenting your indexes. Consider that when you shrink a database you are taking away the free space that a database may someday grow right back into - effectively wasting your time and incurring the performance hit of a shrink operation only to see the DB grow again.

I wrote about this concept in several blog posts about shrinking databases. This one called "Don't touch that shrink button" comes to mind first. I talk about these concepts outlined here - but also the concept of "Right-Sizing" your database. It is far better to decide what your database size needs to be, plan for future growth and allocate it to that amount. With Instant File Initialization available in SQL Server 2005 and beyond for data files, the cost of growths is lower - but I still prefer to have a proper initial application - and I'm far less scared of white space in a database than I am of shrinking in general with no thought first. :)

How do I write a bash script to restart a process if it dies?

if ! test -f $PIDFILE || ! psgrep `cat $PIDFILE`; then
    restart_process
    # Write PIDFILE
    echo $! >$PIDFILE
fi

How to deploy correctly when using Composer's develop / production switch?

Why

There is IMHO a good reason why Composer will use the --dev flag by default (on install and update) nowadays. Composer is mostly run in scenario's where this is desired behavior:

The basic Composer workflow is as follows:

  • A new project is started: composer.phar install --dev, json and lock files are commited to VCS.
  • Other developers start working on the project: checkout of VCS and composer.phar install --dev.
  • A developer adds dependancies: composer.phar require <package>, add --dev if you want the package in the require-dev section (and commit).
  • Others go along: (checkout and) composer.phar install --dev.
  • A developer wants newer versions of dependencies: composer.phar update --dev <package> (and commit).
  • Others go along: (checkout and) composer.phar install --dev.
  • Project is deployed: composer.phar install --no-dev

As you can see the --dev flag is used (far) more than the --no-dev flag, especially when the number of developers working on the project grows.

Production deploy

What's the correct way to deploy this without installing the "dev" dependencies?

Well, the composer.json and composer.lock file should be committed to VCS. Don't omit composer.lock because it contains important information on package-versions that should be used.

When performing a production deploy, you can pass the --no-dev flag to Composer:

composer.phar install --no-dev

The composer.lock file might contain information about dev-packages. This doesn't matter. The --no-dev flag will make sure those dev-packages are not installed.

When I say "production deploy", I mean a deploy that's aimed at being used in production. I'm not arguing whether a composer.phar install should be done on a production server, or on a staging server where things can be reviewed. That is not the scope of this answer. I'm merely pointing out how to composer.phar install without installing "dev" dependencies.

Offtopic

The --optimize-autoloader flag might also be desirable on production (it generates a class-map which will speed up autoloading in your application):

composer.phar install --no-dev --optimize-autoloader

Or when automated deployment is done:

composer.phar install --no-ansi --no-dev --no-interaction --no-plugins --no-progress --no-scripts --optimize-autoloader

If your codebase supports it, you could swap out --optimize-autoloader for --classmap-authoritative. More info here

How can I insert vertical blank space into an html document?

Read up some on css, it's fun: http://www.w3.org/Style/Examples/007/units.en.html

<style>
  .bottom-three {
     margin-bottom: 3cm;
  }
</style>


<p class="bottom-three">
   This is the first question?
</p>
<p class="bottom-three">
   This is the second question?
</p>

Travel/Hotel API's?

I've used the TripAdvisor API before and its suited me well. It returns, per destination, a list of top-rated hotels, along with options to retrieve reviews, photos, nearby restaurants and a couple other useful things.

http://www.tripadvisor.com/help/what_type_of_tripadvisor_content_is_available

From the API page (available API content) :

* Hotel, attraction and restaurant ratings and reviews
* Top 10 lists of hotels, attractions and restaurants in a destination
* Traveler photos of a destination
* Travelers' Choice award badges for hotels and destinations

To expand upon @nstehr's answer, you could also use Yahoo Pipes to facilitate a more granular local search. Go to pipes.yahoo.com and do a search for existing hotel pipes and you'll get the idea..

How to embed images in html email

Based on Arthur Halma's answer, I did the following that works correctly with Apple's, Android & iOS mail.

define("EMAIL_DOMAIN", "yourdomain.com");

public function send_email_html($to, $from, $subject, $html) {
  preg_match_all('~<img.*?src=.([\/.a-z0-9:_-]+).*?>~si',$html,$matches);
  $i = 0;
  $paths = array();
  foreach ($matches[1] as $img) {
    $img_old = $img;
    if(strpos($img, "http://") == false) {
      $uri = parse_url($img);
      $paths[$i]['path'] = $_SERVER['DOCUMENT_ROOT'].$uri['path'];
      $content_id = md5($img);
      $html = str_replace($img_old,'cid:'.$content_id,$html);
      $paths[$i++]['cid'] = $content_id;
    }
  }
  $uniqid   = md5(uniqid(time()));
  $boundary = "--==_mimepart_".$uniqid;

  $headers = "From: ".$from."\n".
  'Reply-to: '.$from."\n".
  'Return-Path: '.$from."\n".
  'Message-ID: <'.$uniqid.'@'.EMAIL_DOMAIN.">\n".
  'Date: '.gmdate('D, d M Y H:i:s', time())."\n".
  'Mime-Version: 1.0'."\n".
  'Content-Type: multipart/related;'."\n".
  '  boundary='.$boundary.";\n".
  '  charset=UTF-8'."\n".
  'X-Mailer: PHP/' . phpversion();

  $multipart = '';
  $multipart .= "--$boundary\n";
  $kod = 'UTF-8';
  $multipart .= "Content-Type: text/html; charset=$kod\n";
  $multipart .= "Content-Transfer-Encoding: 7-bit\n\n";
  $multipart .= "$html\n\n";
  foreach ($paths as $path) {
    if (file_exists($path['path']))
      $fp = fopen($path['path'],"r");
      if (!$fp)  {
        return false;
      }
    $imagetype = substr(strrchr($path['path'], '.' ),1);
    $file = fread($fp, filesize($path['path']));
    fclose($fp);
    $message_part = "";
    switch ($imagetype) {
      case 'png':
      case 'PNG':
            $message_part .= "Content-Type: image/png";
            break;
      case 'jpg':
      case 'jpeg':
      case 'JPG':
      case 'JPEG':
            $message_part .= "Content-Type: image/jpeg";
            break;
      case 'gif':
      case 'GIF':
            $message_part .= "Content-Type: image/gif";
            break;
    }
    $message_part .= "; file_name = \"$path\"\n";
    $message_part .= 'Content-ID: <'.$path['cid'].">\n";
    $message_part .= "Content-Transfer-Encoding: base64\n";
    $message_part .= "Content-Disposition: inline; filename = \"".basename($path['path'])."\"\n\n";
    $message_part .= chunk_split(base64_encode($file))."\n";
    $multipart .= "--$boundary\n".$message_part."\n";
  }
  $multipart .= "--$boundary--\n";
  mail($to, $subject, $multipart, $headers);
}

Calculate rolling / moving average in C++

I used a deque... seems to work for me. This example has a vector, but you could skip that aspect and simply add them to deque.

#include <deque>

template <typename T>
double mov_avg(vector<T> vec, int len){
  deque<T> dq = {};
  for(auto i = 0;i < vec.size();i++){
    if(i < len){
      dq.push_back(vec[i]);
    }
    else {
      dq.pop_front();
      dq.push_back(vec[i]);
    }
  }
  double cs = 0;
  for(auto i : dq){
    cs += i;
  }
  return cs / len;
}



//Skip the vector portion, track the input number (or size of deque), and the value.


  double len = 10;
  double val; //Accept as input
  double instance; //Increment each time input accepted.

  deque<double> dq;
  if(instance < len){
      dq.push_back(val);
  }
  else {
      dq.pop_front();
      dq.push_back(val);
    }
  }
  double cs = 0;
  for(auto i : dq){
    cs += i;
  }
  double rolling_avg = cs / len;

//To simplify further -- add values to this, then simply average the deque.

 int MAX_DQ = 3;
 void add_to_dq(deque<double> &dq, double value){
    if(dq.size() < MAX_DQ){
      dq.push_back(value);
    }else {
      dq.pop_front();
      dq.push_back(value);
    }
  }
 

Another sort of hack I use occasionally is using mod to overwrite values in a vector.

  vector<int> test_mod = {0,0,0,0,0};
  int write = 0;
  int LEN = 5;
  
  int instance = 0; //Filler for N -- of Nth Number added.
  int value = 0; //Filler for new number.

  write = instance % LEN;
  test_mod[write] = value;
  //Will write to 0, 1, 2, 3, 4, 0, 1, 2, 3, ...
  //Then average it for MA.

  //To test it...
  int write_idx = 0;
  int len = 5;
  int new_value;
  for(auto i=0;i<100;i++){
      cin >> new_value;
      write_idx = i % len;
      test_mod[write_idx] = new_value;

This last (hack) has no buckets, buffers, loops, nothing. Simply a vector that's overwritten. And it's 100% accurate (for avg / values in vector). Proper order is rarely maintained, as it starts rewriting backwards (at 0), so 5th index would be at 0 in example {5,1,2,3,4}, etc.

Python extract pattern matches

You need to capture from regex. search for the pattern, if found, retrieve the string using group(index). Assuming valid checks are performed:

>>> p = re.compile("name (.*) is valid")
>>> result = p.search(s)
>>> result
<_sre.SRE_Match object at 0x10555e738>
>>> result.group(1)     # group(1) will return the 1st capture (stuff within the brackets).
                        # group(0) will returned the entire matched text.
'my_user_name'

What's the difference between UTF-8 and UTF-8 without BOM?

UTF with a BOM is better if you use UTF-8 in HTML files and if you use Serbian Cyrillic, Serbian Latin, German, Hungarian or some exotic language on the same page.

That is my opinion (30 years of computing and IT industry).

What is the best way to test for an empty string in Go?

This seems to be premature microoptimization. The compiler is free to produce the same code for both cases or at least for these two

if len(s) != 0 { ... }

and

if s != "" { ... }

because the semantics is clearly equal.

How to make the Facebook Like Box responsive?

The answer you're looking for as of June, 2013 can be found here:

https://gist.github.com/dineshcooper/2111366

It's accomplished using jQuery to rewrite the inner HTML of the parent container that holds the facebook widget.

Hope this helps!

Hiding user input on terminal in Linux script

Here's a variation on @SiegeX's excellent *-printing solution for bash with support for backspace added; this allows the user to correct their entry with the backspace key (delete key on a Mac), as is typically supported by password prompts:

#!/usr/bin/env bash

password=''
while IFS= read -r -s -n1 char; do
  [[ -z $char ]] && { printf '\n'; break; } # ENTER pressed; output \n and break.
  if [[ $char == $'\x7f' ]]; then # backspace was pressed
      # Remove last char from output variable.
      [[ -n $password ]] && password=${password%?}
      # Erase '*' to the left.
      printf '\b \b' 
  else
    # Add typed char to output variable.
    password+=$char
    # Print '*' in its stead.
    printf '*'
  fi
done

Note:

  • As for why pressing backspace records character code 0x7f: "In modern systems, the backspace key is often mapped to the delete character (0x7f in ASCII or Unicode)" https://en.wikipedia.org/wiki/Backspace
  • \b \b is needed to give the appearance of deleting the character to the left; just using \b moves the cursor to the left, but leaves the character intact (nondestructive backspace). By printing a space and moving back again, the character appears to have been erased (thanks, The "backspace" escape character '\b' in C, unexpected behavior?).

In a POSIX-only shell (e.g., sh on Debian and Ubuntu, where sh is dash), use the stty -echo approach (which is suboptimal, because it prints nothing), because the read builtin will not support the -s and -n options.

How to change or add theme to Android Studio?

Thought I would add this as an answer, for anyone who accidentally mess up like I did!
It't not really an answer to the original question, but a few other posts refer to this post, so thought I would add it here (cause its slightly relevant to the question). Hope it helps someone!

Today I accidentally set my IDE font size on Android Studio very high (was going to set it to 10, but it accidentally became 110).

Now, the big issue for me was that opening the file menu was not possible (well, could open it, but could not get to the settings choice), so I had to figure out how to do it manually.

I found the Android Studio IDE settings in the Users/%username%/.AndroidStudioPreview/config folder and in there, the ui.inf.xml file, in which I could change the option FONT_SIZE back to a more manageable size.

Following image is android studio with 110 px font size on a 1920x1080 screen: Android studio 110 px font size

MongoDb query condition on comparing 2 fields

In case performance is more important than readability and as long as your condition consists of simple arithmetic operations, you can use aggregation pipeline. First, use $project to calculate the left hand side of the condition (take all fields to left hand side). Then use $match to compare with a constant and filter. This way you avoid javascript execution. Below is my test in python:

import pymongo
from random import randrange

docs = [{'Grade1': randrange(10), 'Grade2': randrange(10)} for __ in range(100000)]

coll = pymongo.MongoClient().test_db.grades
coll.insert_many(docs)

Using aggregate:

%timeit -n1 -r1 list(coll.aggregate([
    {
        '$project': {
            'diff': {'$subtract': ['$Grade1', '$Grade2']},
            'Grade1': 1,
            'Grade2': 1
        }
    },
    {
        '$match': {'diff': {'$gt': 0}}
    }
]))

1 loop, best of 1: 192 ms per loop

Using find and $where:

%timeit -n1 -r1 list(coll.find({'$where': 'this.Grade1 > this.Grade2'}))

1 loop, best of 1: 4.54 s per loop

How might I force a floating DIV to match the height of another floating DIV?

This code will let you have a variable number of rows (with a variable number of DIVs on each row) and it will make all of the DIVs on each row match the height of its tallest neighbour:

If we assumed all the DIVs, that are floating, are inside a container with the id "divContainer", then you could use the following:

$(document).ready(function() {

var currentTallest = 0;
var currentRowStart = 0;
var rowDivs = new Array();

$('div#divContainer div').each(function(index) {

    if(currentRowStart != $(this).position().top) {

        // we just came to a new row.  Set all the heights on the completed row
        for(currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) rowDivs[currentDiv].height(currentTallest);

        // set the variables for the new row
        rowDivs.length = 0; // empty the array
        currentRowStart = $(this).position().top;
        currentTallest = $(this).height();
        rowDivs.push($(this));

    } else {

        // another div on the current row.  Add it to the list and check if it's taller
        rowDivs.push($(this));
        currentTallest = (currentTallest < $(this).height()) ? ($(this).height()) : (currentTallest);

    }
    // do the last row
    for(currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) rowDivs[currentDiv].height(currentTallest);

});
});

Access Google's Traffic Data through a Web Service

I don't think Google will provide this API. And traffic data not only contains the incident data.

Today many online maps show city traffic, but they have not provide the API for the developer. We even don't know where they get the traffic data. Maybe the government has the data.

So I think you could think about it from another direction. For example, there are many social network website out there. Everybody could post the traffic information on the website. We can collection these information to get the traffic status. Or maybe we can create a this type website.

But that type traffic data (talked about above) is not accurate. Even the information provided by human will be wrong.

Luckily I found that my city now provides an Mobile App called "Real-time Bus Information". It could tell the citizen where the bus is now, and when will arrive at the bus station. And I sniff the REST API in this App. The data from REST API give the important data, for example the lat and lon, and also the bus speed. And it's real-time data! So I think we could compute the traffic status from these data (by some programming). Here is some sample data : https://github.com/sp-chenyang/bus/blob/master/sample_data/bjgj_aibang_com_8899_bjgj_php_city_linename_stationno_datatype_type.json

Even the bus data will not enough to compute the accurate real-time traffic status. Incidents, traffic light and other things will affect the traffic status. But I think this is the beginning.

At the end, I think you could try to find whether your city provides these data.

PS: I am always thinking that life will be better for people in the future , but not now.

How to use default Android drawables

As far as i remember, the documentation advises against using the menu icons from android.R.drawable directly and recommends copying them to your drawables folder. The main reason is that those icons and names can be subject to change and may not be available in future releases.

Warning: Because these resources can change between platform versions, you should not reference these icons using the Android platform resource IDs (i.e. menu icons under android.R.drawable). If you want to use any icons or other internal drawable resources, you should store a local copy of those icons or drawables in your application resources, then reference the local copy from your application code. In that way, you can maintain control over the appearance of your icons, even if the system's copy changes.

from: http://developer.android.com/guide/practices/ui_guidelines/icon_design_menu.html

What are the differences between .gitignore and .gitkeep?

.gitkeep is just a placeholder. A dummy file, so Git will not forget about the directory, since Git tracks only files.


If you want an empty directory and make sure it stays 'clean' for Git, create a .gitignore containing the following lines within:

# .gitignore sample
###################

# Ignore all files in this dir...
*

# ... except for this one.
!.gitignore

If you desire to have only one type of files being visible to Git, here is an example how to filter everything out, except .gitignore and all .txt files:

# .gitignore to keep just .txt files
###################################

# Filter everything...
*

# ... except the .gitignore...
!.gitignore

# ... and all text files.
!*.txt

('#' indicates comments.)

Delete data with foreign key in SQL Server table

If you wish the delete to be automatic, you need to change your schema so that the foreign key constraint is ON DELETE CASCADE.

For more information, see the MSDN page on Cascading Referential Integrity Constraints.

ETA (after clarification from the poster): If you can't update the schema, you have to manually DELETE the affected child records first.

How to insert data into elasticsearch

Let me explain clearly.. If you are familiar With rdbms.. Index is database.. And index type is table.. It mean index is collection of index types., like collection of tables as database (DB).

in NOSQL.. Index is database and index type is collections. Group of collection as database..

To execute those queries... U need to install CURL for Windows.

Curl is nothing but a command line rest tool.. If you want a graphical tool.. Try

Sense plugin for chrome...

Hope it helps..

Is it possible to insert multiple rows at a time in an SQLite database?

fearless_fool has a great answer for older versions. I just wanted to add that you need to make sure you have all the columns listed. So if you have 3 columns, you need to make sure select acts on 3 columns.

Example: I have 3 columns but I only want to insert 2 columns worth of data. Assume I don't care about the first column because it's a standard integer id. I could do the following...

INSERT INTO 'tablename'
      SELECT NULL AS 'column1', 'data1' AS 'column2', 'data2' AS 'column3'
UNION SELECT NULL, 'data3', 'data4'
UNION SELECT NULL, 'data5', 'data6'
UNION SELECT NULL, 'data7', 'data8'

Note: Remember the "select ... union" statement will lose the ordering. (From AG1)

Iterate through 2 dimensional array

Consider it as an array of arrays and this will work for sure.

int mat[][] = { {10, 20, 30, 40, 50, 60, 70, 80, 90},
                {15, 25, 35, 45},
                {27, 29, 37, 48},
                {32, 33, 39, 50, 51, 89},
              };


    for(int i=0; i<mat.length; i++) {
        for(int j=0; j<mat[i].length; j++) {
            System.out.println("Values at arr["+i+"]["+j+"] is "+mat[i][j]);
        }
    }

How to set thymeleaf th:field value from other variable

The correct approach is to use preprocessing

For example

th:field="*{__${myVar}__}"

Hiding the R code in Rmarkdown/knit and just showing the results

Might also be interesting for you to know that you can use:

{r echo=FALSE, results='hide',message=FALSE}
a<-as.numeric(rnorm(100))
hist(a, breaks=24)

to exclude all the commands you give, all the results it spits out and all message info being spit out by R (eg. after library(ggplot) or something)

How to show disable HTML select option in by default?

Another SELECT tag solution for those who want to keep first option blank.

_x000D_
_x000D_
<label>Unreal :</label>_x000D_
<select name="unreal">_x000D_
   <option style="display:none"></option>_x000D_
   <option>Money</option>_x000D_
   <option>Country</option>_x000D_
   <option>God</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Eclipse: How do I add the javax.servlet package to a project?

  1. Download the file from http://www.java2s.com/Code/Jar/STUVWXYZ/Downloadjavaxservletjar.htm

  2. Make a folder ("lib") inside the project folder and move that jar file to there.

  3. In Eclipse, right click on project > BuildPath > Configure BuildPath > Libraries > Add External Jar

Thats all

Windows CMD command for accessing usb?

firstly you have to change the drive, which is allocated to your usb.

follow these step to access your pendrive using CMD. 1- type drivename follow by the colon just like k: 2- type dir it will show all the files and directory in your usb 3- now you can access any file or directory of your usb.

"No X11 DISPLAY variable" - what does it mean?

you must enable X11 forwarding in you PuTTy

to do so open PuTTy, go to Connection => SSH => Tunnels and check mark the Enable X11 forwarding

Also sudo to server and export the below variable here IP is your local machine's IP

export DISPLAY=10.75.75.75:0.0

enter image description here

how to find array size in angularjs

Just use the length property of a JavaScript array like so:

$scope.names.length

Also, I don't see a starting <script> tag in your code.

If you want the length inside your view, do it like so:

{{ names.length }}

Map implementation with duplicate keys

commons.apache.org

MultiValueMap class

htaccess "order" Deny, Allow, Deny

Just use order allow,deny instead and remove the deny from all line.

C# Double - ToString() formatting with two decimal places but no rounding

How about adding one extra decimal that is to be rounded and then discarded:

var d = 0.241534545765;
var result1 = d.ToString("0.###%");

var result2 = result1.Remove(result1.Length - 1);

Example of waitpid() in use?

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

int main (){
    int pid;
    int status;

    printf("Parent: %d\n", getpid());

    pid = fork();
    if (pid == 0){
        printf("Child %d\n", getpid());
        sleep(2);
        exit(EXIT_SUCCESS);
    }

//Comment from here to...
    //Parent waits process pid (child)
    waitpid(pid, &status, 0);
    //Option is 0 since I check it later

    if (WIFSIGNALED(status)){
        printf("Error\n");
    }
    else if (WEXITSTATUS(status)){
        printf("Exited Normally\n");
    }
//To Here and see the difference
    printf("Parent: %d\n", getpid());

    return 0;
}

Count immediate child div elements using jQuery

$("#foo > div") 

selects all divs that are immediate descendants of #foo
once you have the set of children you can either use the size function:

$("#foo > div").size()

or you can use

$("#foo > div").length

Both will return you the same result

How do I find Waldo with Mathematica?

I have a quick solution for finding Waldo using OpenCV.

I used the template matching function available in OpenCV to find Waldo.

To do this a template is needed. So I cropped Waldo from the original image and used it as a template.

enter image description here

Next I called the cv2.matchTemplate() function along with the normalized correlation coefficient as the method used. It returned a high probability at a single region as shown in white below (somewhere in the top left region):

enter image description here

The position of the highest probable region was found using cv2.minMaxLoc() function, which I then used to draw the rectangle to highlight Waldo:

enter image description here

Filter element based on .data() key/value

We can make a plugin pretty easily:

$.fn.filterData = function(key, value) {
    return this.filter(function() {
        return $(this).data(key) == value;
    });
};

Usage (checking a radio button):

$('input[name=location_id]').filterData('my-data','data-val').prop('checked',true);

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

I like to do this witch i think is cleaner :

1 - Add the model to namespace:

use App\Employee;

2 - then you can do :

$employees = Employee::get();

or maybe somthing like this:

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

MySQL Results as comma separated list

Now only I came across this situation and found some more interesting features around GROUP_CONCAT. I hope these details will make you feel interesting.

simple GROUP_CONCAT

SELECT GROUP_CONCAT(TaskName) 
FROM Tasks;

Result:

+------------------------------------------------------------------+
| GROUP_CONCAT(TaskName)                                           |
+------------------------------------------------------------------+
| Do garden,Feed cats,Paint roof,Take dog for walk,Relax,Feed cats |
+------------------------------------------------------------------+

GROUP_CONCAT with DISTINCT

SELECT GROUP_CONCAT(TaskName) 
FROM Tasks;

Result:

+------------------------------------------------------------------+
| GROUP_CONCAT(TaskName)                                           |
+------------------------------------------------------------------+
| Do garden,Feed cats,Paint roof,Take dog for walk,Relax,Feed cats |
+------------------------------------------------------------------+

GROUP_CONCAT with DISTINCT and ORDER BY

SELECT GROUP_CONCAT(DISTINCT TaskName ORDER BY TaskName DESC) 
FROM Tasks;

Result:

+--------------------------------------------------------+
| GROUP_CONCAT(DISTINCT TaskName ORDER BY TaskName DESC) |
+--------------------------------------------------------+
| Take dog for walk,Relax,Paint roof,Feed cats,Do garden |
+--------------------------------------------------------+

GROUP_CONCAT with DISTINCT and SEPARATOR

SELECT GROUP_CONCAT(DISTINCT TaskName SEPARATOR ' + ') 
FROM Tasks;

Result:

+----------------------------------------------------------------+
| GROUP_CONCAT(DISTINCT TaskName SEPARATOR ' + ')                |
+----------------------------------------------------------------+
| Do garden + Feed cats + Paint roof + Relax + Take dog for walk |
+----------------------------------------------------------------+

GROUP_CONCAT and Combining Columns

SELECT GROUP_CONCAT(TaskId, ') ', TaskName SEPARATOR ' ') 
FROM Tasks;

Result:

+------------------------------------------------------------------------------------+
| GROUP_CONCAT(TaskId, ') ', TaskName SEPARATOR ' ')                                 |
+------------------------------------------------------------------------------------+
| 1) Do garden 2) Feed cats 3) Paint roof 4) Take dog for walk 5) Relax 6) Feed cats |
+------------------------------------------------------------------------------------+

GROUP_CONCAT and Grouped Results Assume that the following are the results before using GROUP_CONCAT

+------------------------+--------------------------+
| ArtistName             | AlbumName                |
+------------------------+--------------------------+
| Iron Maiden            | Powerslave               |
| AC/DC                  | Powerage                 |
| Jim Reeves             | Singing Down the Lane    |
| Devin Townsend         | Ziltoid the Omniscient   |
| Devin Townsend         | Casualties of Cool       |
| Devin Townsend         | Epicloud                 |
| Iron Maiden            | Somewhere in Time        |
| Iron Maiden            | Piece of Mind            |
| Iron Maiden            | Killers                  |
| Iron Maiden            | No Prayer for the Dying  |
| The Script             | No Sound Without Silence |
| Buddy Rich             | Big Swing Face           |
| Michael Learns to Rock | Blue Night               |
| Michael Learns to Rock | Eternity                 |
| Michael Learns to Rock | Scandinavia              |
| Tom Jones              | Long Lost Suitcase       |
| Tom Jones              | Praise and Blame         |
| Tom Jones              | Along Came Jones         |
| Allan Holdsworth       | All Night Wrong          |
| Allan Holdsworth       | The Sixteen Men of Tain  |
+------------------------+--------------------------+
USE Music;
SELECT ar.ArtistName,
    GROUP_CONCAT(al.AlbumName)
FROM Artists ar
INNER JOIN Albums al
ON ar.ArtistId = al.ArtistId
GROUP BY ArtistName;

Result:

+------------------------+----------------------------------------------------------------------------+
| ArtistName             | GROUP_CONCAT(al.AlbumName)                                                 |
+------------------------+----------------------------------------------------------------------------+
| AC/DC                  | Powerage                                                                   |
| Allan Holdsworth       | All Night Wrong,The Sixteen Men of Tain                                    |
| Buddy Rich             | Big Swing Face                                                             |
| Devin Townsend         | Epicloud,Ziltoid the Omniscient,Casualties of Cool                         |
| Iron Maiden            | Somewhere in Time,Piece of Mind,Powerslave,Killers,No Prayer for the Dying |
| Jim Reeves             | Singing Down the Lane                                                      |
| Michael Learns to Rock | Eternity,Scandinavia,Blue Night                                            |
| The Script             | No Sound Without Silence                                                   |
| Tom Jones              | Long Lost Suitcase,Praise and Blame,Along Came Jones                       |
+------------------------+----------------------------------------------------------------------------+

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0

For users which have flavors in the project and found this thread:

Notice, that if your module dependency has different flavors, you should use one of the strategies:

  1. Module that tightens dependencies should have the same flavors and dimensions as the dependency module
  2. You should explicitly indicate which configuration you target in the module

Like that:

dependencies {
    compile project(path: ':module', configuration:'alphaDebug') 
}

Extract time from date String

I'm assuming your first string is an actual Date object, please correct me if I'm wrong. If so, use the SimpleDateFormat object: http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html. The format string "h:mm" should take care of it.

Paste MS Excel data to SQL Server

I'd think some datbases can import data from CSV (comma separated values) files, wich you can export from exel. Or at least it's quite easy to use a csv parser (find one for your language, don't try to create one yourself - it's harder than it looks) to import it to the database.

I'm not familiar with MS SQL but it wouldn't suprise me if it does support it directly.

In any case I think the requrement must be that the structure in the Exel sheet and the database table is similar.

What is PHPSESSID?

PHPSESSID reveals you are using PHP. If you don't want this you can easily change the name using the session.name in your php.ini file or using the session_name() function.

What online brokers offer APIs?

There are a few. I was looking into MBTrading for a friend. I didn't get too far, as my friend lost interest. Seemed relatively straigt forward with a C# and VB.Net SDK. They had some docs and everything. This was ~6 months ago, so it may be better (or worse) by now.

IIRC, you can create a demo account for free. I don't remember all the details, but it let you connect to their test server and pull quotes and make fake trades and such to get your software fine tuned.

Don't know much about cost for an actual account or anything.

Android activity life cycle - what are all these methods for?

I like this question and the answers to it, but so far there isn't coverage of less frequently used callbacks like onPostCreate() or onPostResume(). Steve Pomeroy has attempted a diagram including these and how they relate to Android's Fragment life cycle, at https://github.com/xxv/android-lifecycle. I revised Steve's large diagram to include only the Activity portion and formatted it for letter size one-page printout. I've posted it as a text PDF at https://github.com/code-read/android-lifecycle/blob/master/AndroidActivityLifecycle1.pdf and below is its image:

Android Activity Lifecycle

Remove spaces from a string in VB.NET

To trim a string down so it does not contain two or more spaces in a row. Every instance of 2 or more space will be trimmed down to 1 space. A simple solution:

While ImageText1.Contains("  ")                     '2 spaces.
    ImageText1 = ImageText1.Replace("  ", " ")      'Replace with 1 space.
End While

Android: disabling highlight on listView click

For me android:focusableInTouchMode="true" is the way to go. android:listSelector="@android:color/transparent" is of no use. Note that I am using a custom listview with a number of objects in each row.

Why can I not switch branches?

You need to commit or destroy any unsaved changes before you switch branch.

Git won't let you switch branch if it means unsaved changes would be removed.

Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id}

The route engine uses the same sequence as you add rules into it. Once it gets the first matched rule, it will stop checking other rules and take this to search for controller and action.

So, you should:

  1. Put your specific rules ahead of your general rules(like default), which means use RouteTable.Routes.MapHttpRoute to map "WithActionApi" first, then "DefaultApi".

  2. Remove the defaults: new { id = System.Web.Http.RouteParameter.Optional } parameter of your "WithActionApi" rule because once id is optional, url like "/api/{part1}/{part2}" will never goes into "DefaultApi".

  3. Add an named action to your "DefaultApi" to tell the route engine which action to enter. Otherwise once you have more than one actions in your controller, the engine won't know which one to use and throws "Multiple actions were found that match the request: ...". Then to make it matches your Get method, use an ActionNameAttribute.

So your route should like this:

// Map this rule first
RouteTable.Routes.MapRoute(
     "WithActionApi",
     "api/{controller}/{action}/{id}"
 );

RouteTable.Routes.MapRoute(
    "DefaultApi",
    "api/{controller}/{id}",
    new { action="DefaultAction", id = System.Web.Http.RouteParameter.Optional }
);

And your controller:

[ActionName("DefaultAction")] //Map Action and you can name your method with any text
public string Get(int id)
{
    return "object of id id";
}        

[HttpGet]
public IEnumerable<string> ByCategoryId(int id)
{
    return new string[] { "byCategory1", "byCategory2" };
}

What steps are needed to stream RTSP from FFmpeg?

An alternative that I used instead of FFServer was Red5 Pro, on Ubuntu, I used this line: ffmpeg -f pulse -i default -f video4linux2 -thread_queue_size 64 -framerate 25 -video_size 640x480 -i /dev/video0 -pix_fmt yuv420p -bsf:v h264_mp4toannexb -profile:v baseline -level:v 3.2 -c:v libx264 -x264-params keyint=120:scenecut=0 -c:a aac -b:a 128k -ar 44100 -f rtsp -muxdelay 0.1 rtsp://localhost:8554/live/paul

Print PDF directly from JavaScript

Based on comments below, it no longer works in modern browsers
This question demonstrates an approach that might be helpful to you: Silent print an embedded PDF

It uses the <embed> tag to embed the PDF in the document:

<embed
    type="application/pdf"
    src="path_to_pdf_document.pdf"
    id="pdfDocument"
    width="100%"
    height="100%" />

Then you call the .print() method on the element in Javascript when the PDF is loaded:

function printDocument(documentId) {
    var doc = document.getElementById(documentId);

    //Wait until PDF is ready to print    
    if (typeof doc.print === 'undefined') {    
        setTimeout(function(){printDocument(documentId);}, 1000);
    } else {
        doc.print();
    }
}

You could place the embed in a hidden iframe and print it from there, giving you a seamless experience.

How to apply a function to two columns of Pandas dataframe

A interesting question! my answer as below:

import pandas as pd

def sublst(row):
    return lst[row['J1']:row['J2']]

df = pd.DataFrame({'ID':['1','2','3'], 'J1': [0,2,3], 'J2':[1,4,5]})
print df
lst = ['a','b','c','d','e','f']

df['J3'] = df.apply(sublst,axis=1)
print df

Output:

  ID  J1  J2
0  1   0   1
1  2   2   4
2  3   3   5
  ID  J1  J2      J3
0  1   0   1     [a]
1  2   2   4  [c, d]
2  3   3   5  [d, e]

I changed the column name to ID,J1,J2,J3 to ensure ID < J1 < J2 < J3, so the column display in right sequence.

One more brief version:

import pandas as pd

df = pd.DataFrame({'ID':['1','2','3'], 'J1': [0,2,3], 'J2':[1,4,5]})
print df
lst = ['a','b','c','d','e','f']

df['J3'] = df.apply(lambda row:lst[row['J1']:row['J2']],axis=1)
print df

PHP: HTML: send HTML select option attribute in POST

You can do this with JQuery

Simply:

   <form name='add'>
   Age: <select id="age" name='age'>
   <option value='1' stud_name='sre'>23</option>
   <option value='2' stud_name='sam'>24</option>
   <option value='5' stud_name='john'>25</option>
   </select>
   <input type='hidden' id="name" name="name" value=""/>
   <input type='submit' name='submit'/>
   </form>

Add this code in Header section:

<script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>

Now JQuery function

<script type="text/javascript" language="javascript">
$(function() {
      $("#age").change(function(){
      var studentNmae= $('option:selected', this).attr('stud_name');
      $('#name').val(studentNmae);
   });
});
</script>

you can use both values as

$name = $_POST['name'];
$value = $_POST['age'];

Eclipse java debugging: source not found

The symptoms perfectly describes the case when the found class doesn't have associated (or assigned) source.

  • You can associate the sources for JDK classes in Preferences > Java > Installed JRE. If JRE (not JDK) is detected as default JRE to be used, then your JDK classes won't have attached sources. Note that, not all of the JDK classes have provided sources, some of them are distributed in binary form only.
  • Classes from project's build path, added manually requires that you manually attach the associated source. The source can reside in a zip or jar file, in the workspace or in the filesystem. Eclipse will scan the zip, so your sources doesn't have to be in the root of the archive file, for example.
  • Classes, from dependencies coming from another plugins (maven, PDE, etc.). In this case, it is up to the plugin how the source will be provided.
    • PDE will require that each plugin have corresponding XXX.source bundle, which contains the source of the plugin. More information can be found here and here.
    • m2eclipse can fetch sources and javadocs for Maven dependencies if they are available. This feature should be enabled m2eclipse preferences (the option was named something like "Download source and javadocs".
    • For other plugins, you'll need to consult their documentation
  • Classes, which are loaded from your project are automatically matched with the sources from the project.

But what if Eclipse still suggest that you attach source, even if I correctly set my classes and their sources:

This almost always means that Eclipse is finding the class from different place than you expect. Inspect your source lookup path to see where it might get the wrong class. Update the path accordingly to your findings.

Eclipse doesn't find anything at all, when breakpoint is hit:

This happens, when you are source lookup path doesn't contain the class, which is currently loaded in the runtime. Even if the class is in the workspace, it can be invisible to the launch configuration, because Eclipse follows the source lookup path strictly and attaches only the dependencies of the project, which is currently debugged.

An exception is the debugging bundles in PDE. In this case, because the runtime is composed from multiple projects, which doesn't have to declare dependencies on one another, Eclipse will automatically find the class in the workspace, even if it is not available in the source lookup path.

I cannot see the variables when I hit a breakpoint or it just opens the source, but doesn't select the breakpoint line:

This means that in the runtime, either the JVM or the classes themselves doesn't have the necessary debug information. Each time classes are compiled, debug information can be attached. To reduce the storage space of the classes, sometimes this information is omitted, which makes debugging such code a pain. Your only chance is to try and recompile with debug enabled.

Eclipse source viewer shows different lines than those that are actually executed:

It sometimes can show that empty space is executed as well. This means that your sources doesn't match your runtime version of the classes. Even if you think that this is not possible, it is, so make sure you setup the correct sources. Or your runtime match your latest changes, depending on what are you trying to do.

creating json object with variables

It's called on Object Literal

I'm not sure what you want your structure to be, but according to what you have above, where you put the values in variables try this.

var formObject =  {"formObject": [
                {"firstName": firstName, "lastName": lastName},
                {"phoneNumber": phone},
                {"address": address},
                ]}

Although this seems to make more sense (Why do you have an array in the above literal?):

var formObject = {
   firstName: firstName
   ...
}

HTML Table width in percentage, table rows separated equally

Use the property table-layout:fixed; on the table to get equally spaced cells. If a column has a width set, then no matter what the content is, it will be the specified width. Columns without a width set will divide whatever room is left over among themselves.

<table style='table-layout:fixed;'>
    <tbody>
        <tr>
            <td>gobble de gook</td>
            <td>mibs</td>
        </tr>
    </tbody>
</table>

Just to throw it out there, you could also use <colgroup><col span='#' style='width:#%;'/></colgroup>, which doesn't require repetition of style per table data or giving the table an id to use in a style sheet. I think setting the widths on the first row is enough though.

Getting a POST variable

Use the

Request.Form[]

for POST variables,

Request.QueryString[]

for GET.

What's the best way to set a single pixel in an HTML5 canvas?

It seems strange, but nonetheless HTML5 supports drawing lines, circles, rectangles and many other basic shapes, it does not have anything suitable for drawing the basic point. The only way to do so is to simulate point with whatever you have.

So basically there are 3 possible solutions:

  • draw point as a line
  • draw point as a polygon
  • draw point as a circle

Each of them has their drawbacks


Line

function point(x, y, canvas){
  canvas.beginPath();
  canvas.moveTo(x, y);
  canvas.lineTo(x+1, y+1);
  canvas.stroke();
}

Keep in mind that we are drawing to South-East direction, and if this is the edge, there can be a problem. But you can also draw in any other direction.


Rectangle

function point(x, y, canvas){
  canvas.strokeRect(x,y,1,1);
}

or in a faster way using fillRect because render engine will just fill one pixel.

function point(x, y, canvas){
  canvas.fillRect(x,y,1,1);
}

Circle


One of the problems with circles is that it is harder for an engine to render them

function point(x, y, canvas){
  canvas.beginPath();
  canvas.arc(x, y, 1, 0, 2 * Math.PI, true);
  canvas.stroke();
}

the same idea as with rectangle you can achieve with fill.

function point(x, y, canvas){
  canvas.beginPath();
  canvas.arc(x, y, 1, 0, 2 * Math.PI, true);
  canvas.fill();
}

Problems with all these solutions:

  • it is hard to keep track of all the points you are going to draw.
  • when you zoom in, it looks ugly.

If you are wondering, "What is the best way to draw a point?", I would go with filled rectangle. You can see my jsperf here with comparison tests.

SVN Error: Commit blocked by pre-commit hook (exit code 1) with output: Error: n/a (6)

If you are getting following exception:

Error: Commit failed (details follow):
Error: Commit blocked by pre-commit hook (exit code 1) with output:
Error: svnlook: Path 'trunk/Development/ProjectName' is not a file

Then first check-in all the the directories and then all the files. It will work.

Getting unique items from a list

You can use Distinct extension method from LINQ

"%%" and "%/%" for the remainder and the quotient

In R, you can assign your own operators using %[characters]%. A trivial example:

'%p%' <- function(x, y){x^2 + y}

2 %p% 3 # result: 7

While I agree with BlueTrin that %% is pretty standard, I have a suspicion %/% may have something to do with the sort of operator definitions I showed above - perhaps it was easier to implement, and makes sense: %/% means do a special sort of division (integer division)

What is the best way to remove a table row with jQuery?

If the row you want to delete might change you can use this. Just pass this function the row # you wish to delete.

function removeMyRow(docRowCount){
   $('table tr').eq(docRowCount).remove();
}

HTML.ActionLink vs Url.Action in ASP.NET Razor

You can easily present Html.ActionLink as a button by using the appropriate CSS style. For example:

@Html.ActionLink("Save", "ActionMethod", "Controller", new { @class = "btn btn-primary" })

How do I make a matrix from a list of vectors in R?

t(sapply(a, '[', 1:max(sapply(a, length))))

where 'a' is a list. Would work for unequal row size

Best C# API to create PDF

My work uses Winnovative's PDF generator (We've used it mainly to convert HTML to PDF, but you can generate it other ways as well)

SELECT with a Replace()

You can reference is that way if you wrap the query, like this:

SELECT P
FROM (SELECT Replace(Postcode, ' ', '') AS P
      FROM Contacts) innertable
WHERE P LIKE 'NW101%'

Be sure to give the wrapped select an alias, even unused (SQL Server doesn't allow it without one IIRC)

python - find index position in list based of partial string

spell_list = ["Tuesday", "Wednesday", "February", "November", "Annual", "Calendar", "Solstice"]

index=spell_list.index("Annual")
print(index)

How to convert comma-separated String to List?

Convert comma separated String to List

List<String> items = Arrays.asList(str.split("\\s*,\\s*"));

The above code splits the string on a delimiter defined as: zero or more whitespace, a literal comma, zero or more whitespace which will place the words into the list and collapse any whitespace between the words and commas.


Please note that this returns simply a wrapper on an array: you CANNOT for example .remove() from the resulting List. For an actual ArrayList you must further use new ArrayList<String>.

How to analyze a JMeter summary report?

Short explanation looks like:

  1. Sample - number of requests sent
  2. Avg - an Arithmetic mean for all responses (sum of all times / count)
  3. Minimal response time (ms)
  4. Maximum response time (ms)
  5. Deviation - see Standard Deviation article
  6. Error rate - percentage of failed tests
  7. Throughput - how many requests per second does your server handle. Larger is better.
  8. KB/Sec - self expalanatory
  9. Avg. Bytes - average response size

If you having troubles with interpreting results you could try BM.Sense results analysis service

Using Python's list index() method on a list of tuples or objects?

I would place this as a comment to Triptych, but I can't comment yet due to lack of rating:

Using the enumerator method to match on sub-indices in a list of tuples. e.g.

li = [(1,2,3,4), (11,22,33,44), (111,222,333,444), ('a','b','c','d'),
        ('aa','bb','cc','dd'), ('aaa','bbb','ccc','ddd')]

# want pos of item having [22,44] in positions 1 and 3:

def getIndexOfTupleWithIndices(li, indices, vals):

    # if index is a tuple of subindices to match against:
    for pos,k in enumerate(li):
        match = True
        for i in indices:
            if k[i] != vals[i]:
                match = False
                break;
        if (match):
            return pos

    # Matches behavior of list.index
    raise ValueError("list.index(x): x not in list")

idx = [1,3]
vals = [22,44]
print getIndexOfTupleWithIndices(li,idx,vals)    # = 1
idx = [0,1]
vals = ['a','b']
print getIndexOfTupleWithIndices(li,idx,vals)    # = 3
idx = [2,1]
vals = ['cc','bb']
print getIndexOfTupleWithIndices(li,idx,vals)    # = 4

How to log cron jobs?

* * * * * myjob.sh >> /var/log/myjob.log 2>&1

will log all output from the cron job to /var/log/myjob.log

You might use mail to send emails. Most systems will send unhandled cron job output by email to root or the corresponding user.

How can I write output from a unit test?

Solved with the following example:

public void CheckConsoleOutput()
{
    Console.WriteLine("Hello, World!");
    Trace.WriteLine("Trace Trace the World");
    Debug.WriteLine("Debug Debug World");
    Assert.IsTrue(true);
}

After running this test, under 'Test Passed', there is the option to view the output, which will bring up the output window.

How to get column values in one comma separated value

You can do this with the following SQL:

SELECT STUFF
(
    (
        SELECT ',' + s.FirstName 
        FROM Employee s
        ORDER BY s.FirstName FOR XML PATH('')
    ),
     1, 1, ''
) AS Employees

java.util.zip.ZipException: error in opening zip file

I was getting exception

java.util.zip.ZipException: invalid entry CRC (expected 0x0 but got 0xdeadface)
    at java.util.zip.ZipInputStream.read(ZipInputStream.java:221)
    at java.util.zip.ZipInputStream.closeEntry(ZipInputStream.java:140)
    at java.util.zip.ZipInputStream.getNextEntry(ZipInputStream.java:118)
...

when unzipping an archive in Java. The archive itself didn't seem corrupted as 7zip (and others) opened it without any problems or complaints about invalid CRC.

I switched to Apache Commons Compress for reading the zip-entries and that resolved the problem.

'Microsoft.ACE.OLEDB.16.0' provider is not registered on the local machine. (System.Data)

As a quick workaround I just saved the workbook as an Excel 97-2003 .xls file. I was able to import with that format with no error.

How to append data to div using JavaScript?

If you want to do it fast and don't want to lose references and listeners use: .insertAdjacentHTML();

"It does not reparse the element it is being used on and thus it does not corrupt the existing elements inside the element. This, and avoiding the extra step of serialization make it much faster than direct innerHTML manipulation."

Supported on all mainline browsers (IE6+, FF8+,All Others and Mobile): http://caniuse.com/#feat=insertadjacenthtml

Example from https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

// <div id="one">one</div>
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');

// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>

Launch an app from within another (iPhone)

The lee answer is absolutely correct for iOS prior to 8.

In iOS 9+ you must whitelist any URL schemes your App wants to query in Info.plist under the LSApplicationQueriesSchemes key (an array of strings):

enter image description here

JavaScript or jQuery browser back button click detector

The 'popstate' event only works when you push something before. So you have to do something like this:

jQuery(document).ready(function($) {

  if (window.history && window.history.pushState) {

    window.history.pushState('forward', null, './#forward');

    $(window).on('popstate', function() {
      alert('Back button was pressed.');
    });

  }
});

For browser backward compatibility I recommend: history.js

How to ping an IP address

This should work:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Pinger {

private static String keyWordTolookFor = "average";

public Pinger() {
    // TODO Auto-generated constructor stub
}


 public static void main(String[] args) {
 //Test the ping method on Windows.
 System.out.println(ping("192.168.0.1")); }


public String ping(String IP) {
    try {
        String line;
        Process p = Runtime.getRuntime().exec("ping -n 1 " + IP);
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while (((line = input.readLine()) != null)) {

            if (line.toLowerCase().indexOf(keyWordTolookFor.toLowerCase()) != -1) {

                String delims = "[ ]+";
                String[] tokens = line.split(delims);
                return tokens[tokens.length - 1];
            } 
        }

        input.close();
    } catch (Exception err) {
        err.printStackTrace();
    }
    return "Offline";
}

}

How to add a jar in External Libraries in android studio

Add your jar file to the folder app/libs. Then right click the jar file and click "add as library".

If there is no libs folder you can create it. Click on the combo box that says "Android", and change it to "Project"

enter image description here

From here, you can right click on "apps" in the directory tree and go to "New" => "Directory"

Delete rows with foreign key in PostgreSQL

It's been a while since this question was asked, hope can help. Because you can not change or alter the db structure, you can do this. according the postgresql docs.

TRUNCATE -- empty a table or set of tables.

TRUNCATE [ TABLE ] [ ONLY ] name [ * ] [, ... ]
    [ RESTART IDENTITY | CONTINUE IDENTITY ] [ CASCADE | RESTRICT ]

Description

TRUNCATE quickly removes all rows from a set of tables. It has the same effect as an unqualified DELETE on each table, but since it does not actually scan the tables it is faster. Furthermore, it reclaims disk space immediately, rather than requiring a subsequent VACUUM operation. This is most useful on large tables.


Truncate the table othertable, and cascade to any tables that reference othertable via foreign-key constraints:

TRUNCATE othertable CASCADE;

The same, and also reset any associated sequence generators:

TRUNCATE bigtable, fattable RESTART IDENTITY;

Truncate and reset any associated sequence generators:

TRUNCATE revinfo RESTART IDENTITY CASCADE ;

maxReceivedMessageSize and maxBufferSize in app.config

The currently accepted answer is incorrect. It is NOT required to set maxBufferSize and maxReceivedMessageSize on the client and the server binding. It depends!

If your request is too large (i.e., method parameters of the service operation are memory intensive) set the properties on the server-side, if the response is too large (i.e., the method return value of the service operation is memory intensive) set the values on the client-side.

For the difference between maxBufferSize and maxReceivedMessageSize see MaxBufferSize property?.

How to compare two columns in Excel and if match, then copy the cell next to it

try this formula in column E:

=IF( AND( ISNUMBER(D2), D2=G2), H2, "")

your error is the number test, ISNUMBER( ISMATCH(D2,G:G,0) )

you do check if ismatch is-a-number, (i.e. isNumber("true") or isNumber("false"), which is not!.

I hope you understand my explanation.

How to check if a directory containing a file exist?

To check if a folder exists or not, you can simply use the exists() method:

// Create a File object representing the folder 'A/B'
def folder = new File( 'A/B' )

// If it doesn't exist
if( !folder.exists() ) {
  // Create all folders up-to and including B
  folder.mkdirs()
}

// Then, write to file.txt inside B
new File( folder, 'file.txt' ).withWriterAppend { w ->
  w << "Some text\n"
}

Which Protocols are used for PING?

The usual command line ping tool uses ICMP Echo, but it's true that other protocols can also be used, and they're useful in debugging different kinds of network problems.

I can remember at least arping (for testing ARP requests) and tcping (which tries to establish a TCP connection and immediately closes it, it can be used to check if traffic reaches a certain port on a host) off the top of my head, but I'm sure there are others aswell.

How to make my layout able to scroll down?

Just wrap all that inside a ScrollView:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
    <!-- Here you put the rest of your current view-->
</ScrollView>

As David Hedlund said, ScrollView can contain just one item... so if you had something like this:

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

You must change it to:

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

Using Apache httpclient for https

This is what worked for me:

    KeyStore keyStore  = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File("client-p12-keystore.p12"));
    try {
        keyStore.load(instream, "password".toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom()
        .loadKeyMaterial(keyStore, "password".toCharArray())
        //.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
        .build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        sslcontext,
        new String[] { "TLSv1" },
        null,
        SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); //TODO
    CloseableHttpClient httpclient = HttpClients.custom()
        .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) //TODO
        .setSSLSocketFactory(sslsf)
        .build();
    try {

        HttpGet httpget = new HttpGet("https://localhost:8443/secure/index");

        System.out.println("executing request" + httpget.getRequestLine());

        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

This code is a modified version of http://hc.apache.org/httpcomponents-client-4.3.x/httpclient/examples/org/apache/http/examples/client/ClientCustomSSL.java

Touch move getting stuck Ignored attempt to cancel a touchmove

The event must be cancelable. Adding an if statement solves this issue.

if (e.cancelable) {
   e.preventDefault();
}

In your code you should put it here:

if (this.isSwipe(swipeThreshold) && e.cancelable) {
   e.preventDefault();
   e.stopPropagation();
   swiping = true;
}

Is there a limit on how much JSON can hold?

There is no fixed limit on how large a JSON data block is or any of the fields.

There are limits to how much JSON the JavaScript implementation of various browsers can handle (e.g. around 40MB in my experience). See this question for example.

Call JavaScript function on DropDownList SelectedIndexChanged Event:

First Method: (Tested)

Code in .aspx.cs:

 protected void Page_Load(object sender, EventArgs e)
    {
        ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
        if (!Page.IsPostBack)
        {
            ddl.Attributes.Add("onchange", "CalcTotalAmt();");
        }
    }

    protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
    {
       //Your Code
    }

JavaScript function: return true from your JS function

   function CalcTotalAmt() 
 {
//Your Code
 }

.aspx code:

<asp:DropDownList ID="ddl" runat="server"  AutoPostBack="true">
        <asp:ListItem Text="a" Value="a"></asp:ListItem>
         <asp:ListItem Text="b" Value="b"></asp:ListItem>
        </asp:DropDownList>

Second Method: (Tested)

Code in .aspx.cs:

protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Params["__EVENTARGUMENT"] != null && Request.Params["__EVENTARGUMENT"].Equals("ddlchange"))
                ddl_SelectedIndexChanged(sender, e);
            if (!Page.IsPostBack)
            {
                ddl.Attributes.Add("onchange", "CalcTotalAmt();");
            }
        }

        protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Your Code
        }

JavaScript function: return true from your JS function

function CalcTotalAmt() {
         //Your Code
     __doPostBack("ctl00$MainContent$ddl","ddlchange");
 }

.aspx code:

<asp:DropDownList ID="ddl" runat="server"  AutoPostBack="true">
        <asp:ListItem Text="a" Value="a"></asp:ListItem>
         <asp:ListItem Text="b" Value="b"></asp:ListItem>
        </asp:DropDownList>

Reading an Excel file in PHP

Read XLSX (Excel 97-2003)
https://github.com/shuchkin/simplexls

if ( $xls = SimpleXLS::parse('book.xls') ) {
    print_r( $xls->rows() );
} else {
    echo SimpleXLS::parseError();
}

Read XLSX (Excel 2003+)
https://github.com/shuchkin/simplexlsx

if ( $xlsx = SimpleXLSX::parse('book.xlsx') ) {
    print_r( $xlsx->rows() );
} else {
    echo SimpleXLSX::parseError();
}

Output

Array (
    [0] => Array
        (
            [0] => ISBN
            [1] => title
            [2] => author
            [3] => publisher
            [4] => ctry
        )
    [1] => Array
        (
            [0] => 618260307
            [1] => The Hobbit
            [2] => J. R. R. Tolkien
            [3] => Houghton Mifflin
            [4] => USA
       )

)

CSV php reader
https://github.com/shuchkin/simplecsv

Is there a way to collapse all code blocks in Eclipse?

I noticed few things:

Ctrl+/ toggles Folding-enabled or -disabled.

It is Ctrl+* that expands. Ctrl+Shift+* collapses just like Ctrl+Shift+/

Getting Gradle dependencies in IntelliJ IDEA using Gradle build

When importing an existing Gradle project (one with a build.gradle) into IntelliJ IDEA, when presented with the following screen, select Import from external model -> Gradle.

Import project from external model

Optionally, select Auto Import on the next screen to automatically import new dependencies.

HTML form action and onsubmit issues

Try

onsubmit="return checkRegistration()"

How do I block or restrict special characters from input fields with jquery?

Yes you can do by using jQuery as:

<script>
$(document).ready(function()
{
    $("#username").blur(function()
    {
        //remove all the class add the messagebox classes and start fading
        $("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
        //check the username exists or not from ajax
        $.post("user_availability.php",{ user_name:$(this).val() } ,function(data)
        {
          if(data=='empty') // if username is empty
          {
            $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
            { 
              //add message and change the class of the box and start fading
              $(this).html('Empty user id is not allowed').addClass('messageboxerror').fadeTo(900,1);
            });
          }
          else if(data=='invalid') // if special characters used in username
          {
            $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
            { 
              //add message and change the class of the box and start fading
              $(this).html('Sorry, only letters (a-z), numbers (0-9), and periods (.) are allowed.').addClass('messageboxerror').fadeTo(900,1);
            });
          }
          else if(data=='no') // if username not avaiable
          {
            $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
            { 
              //add message and change the class of the box and start fading
              $(this).html('User id already exists').addClass('messageboxerror').fadeTo(900,1);
            });     
          }
          else
          {
            $("#msgbox").fadeTo(200,0.1,function()  //start fading the messagebox
            { 
              //add message and change the class of the box and start fading
              $(this).html('User id available to register').addClass('messageboxok').fadeTo(900,1); 
            });
          }

        });

    });
});
</script>
<input type="text" id="username" name="username"/><span id="msgbox" style="display:none"></span>

and script for your user_availability.php will be:

<?php
include'includes/config.php';

//value got from the get method
$user_name = trim($_POST['user_name']);

if($user_name == ''){
    echo "empty";
}elseif(preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $user_name)){
    echo "invalid";
}else{
    $select = mysql_query("SELECT user_id FROM staff");

    $i=0;
    //this varible contains the array of existing users
    while($fetch = mysql_fetch_array($select)){
        $existing_users[$i] = $fetch['user_id'];
        $i++;
    }

    //checking weather user exists or not in $existing_users array
    if (in_array($user_name, $existing_users))
    {
        //user name is not availble
        echo "no";
    } 
    else
    {
        //user name is available
        echo "yes";
    }
}
?>

I tried to add for / and \ but not succeeded.


You can also do it by using javascript & code will be:

<!-- Check special characters in username start -->
<script language="javascript" type="text/javascript">
function check(e) {
    var keynum
    var keychar
    var numcheck
    // For Internet Explorer
    if (window.event) {
        keynum = e.keyCode;
    }
    // For Netscape/Firefox/Opera
    else if (e.which) {
        keynum = e.which;
    }
    keychar = String.fromCharCode(keynum);
    //List of special characters you want to restrict
    if (keychar == "'" || keychar == "`" || keychar =="!" || keychar =="@" || keychar =="#" || keychar =="$" || keychar =="%" || keychar =="^" || keychar =="&" || keychar =="*" || keychar =="(" || keychar ==")" || keychar =="-" || keychar =="_" || keychar =="+" || keychar =="=" || keychar =="/" || keychar =="~" || keychar =="<" || keychar ==">" || keychar =="," || keychar ==";" || keychar ==":" || keychar =="|" || keychar =="?" || keychar =="{" || keychar =="}" || keychar =="[" || keychar =="]" || keychar =="¬" || keychar =="£" || keychar =='"' || keychar =="\\") {
        return false;
    } else {
        return true;
    }
}
</script>
<!-- Check special characters in username end -->

<!-- in your form -->
    User id : <input type="text" id="txtname" name="txtname" onkeypress="return check(event)"/>

How to create a vector of user defined size but with no predefined values?

With the constructor:

// create a vector with 20 integer elements
std::vector<int> arr(20);

for(int x = 0; x < 20; ++x)
   arr[x] = x;

What's the difference between process.cwd() vs __dirname?

Knowing the scope of each can make things easier to remember.

process is node's global object, and .cwd() returns where node is running.

__dirname is module's property, and represents the file path of the module. In node, one module resides in one file.

Similarly, __filename is another module's property, which holds the file name of the module.

How to load a tsv file into a Pandas DataFrame?

Use read_table(filepath). The default separator is tab

Configure active profile in SpringBoot via Maven

I would like to run an automation test in different environments.
So I add this to command maven command:

spring-boot:run -Drun.jvmArguments="-Dspring.profiles.active=productionEnv1"

Here is the link where I found the solution: [1]https://github.com/spring-projects/spring-boot/issues/1095

Instantiate and Present a viewController in Swift

If you want to present it modally, you should have something like bellow:

let vc = self.storyboard!.instantiateViewControllerWithIdentifier("YourViewControllerID")
self.showDetailViewController(vc as! YourViewControllerClassName, sender: self)

Angular and debounce

Not directly accessible like in angular1 but you can easily play with NgFormControl and RxJS observables:

<input type="text" [ngFormControl]="term"/>

this.items = this.term.valueChanges
  .debounceTime(400)
  .distinctUntilChanged()
  .switchMap(term => this.wikipediaService.search(term));

This blog post explains it clearly: http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html

Here it is for an autocomplete but it works all scenarios.

git diff between two different files

If you are using tortoise git you can right-click on a file and git a diff by: Right-clicking on the first file and through the tortoisegit submenu select "Diff later" Then on the second file you can also right-click on this, go to the tortoisegit submenu and then select "Diff with yourfilenamehere.txt"

Get Line Number of certain phrase in file Python

f = open('some_file.txt','r')
line_num = 0
search_phrase = "the dog barked"
for line in f.readlines():
    line_num += 1
    if line.find(search_phrase) >= 0:
        print line_num

EDIT 1.5 years later (after seeing it get another upvote): I'm leaving this as is; but if I was writing today would write something closer to Ash/suzanshakya's solution:

def line_num_for_phrase_in_file(phrase='the dog barked', filename='file.txt')
    with open(filename,'r') as f:
        for (i, line) in enumerate(f):
            if phrase in line:
                return i
    return -1
  • Using with to open files is the pythonic idiom -- it ensures the file will be properly closed when the block using the file ends.
  • Iterating through a file using for line in f is much better than for line in f.readlines(). The former is pythonic (e.g., would work if f is any generic iterable; not necessarily a file object that implements readlines), and more efficient f.readlines() creates an list with the entire file in memory and then iterates through it. * if search_phrase in line is more pythonic than if line.find(search_phrase) >= 0, as it doesn't require line to implement find, reads more easily to see what's intended, and isn't easily screwed up (e.g., if line.find(search_phrase) and if line.find(search_phrase) > 0 both will not work for all cases as find returns the index of the first match or -1).
  • Its simpler/cleaner to wrap an iterated item in enumerate like for i, line in enumerate(f) than to initialize line_num = 0 before the loop and then manually increment in the loop. (Though arguably, this is more difficult to read for people unfamiliar with enumerate.)

See code like pythonista

What does servletcontext.getRealPath("/") mean and when should I use it

My Method:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        String path = request.getRealPath("/WEB-INF/conf.properties");
        Properties p = new Properties();
        p.load(new FileInputStream(path));

        String StringConexion=p.getProperty("StringConexion");
        String User=p.getProperty("User");
        String Password=p.getProperty("Password");
    }
    catch(Exception e){
        String msg = "Excepcion " + e;
    }
}

How do I detect whether a Python variable is a function?

The following is a "repr way" to check it. Also it works with lambda.

def a():pass
type(a) #<class 'function'>
str(type(a))=="<class 'function'>" #True

b = lambda x:x*2
str(type(b))=="<class 'function'>" #True

How do I view / replay a chrome network debugger har file saved with content?

HAR import works seamlessly in Firefox: Open Web Developer -> Network Tab -> HAR -> Import ... (Top-right corner of web developer tool)

HAR Import Option

using CASE in the WHERE clause

SELECT *
FROM logs
WHERE pw='correct'
  AND CASE
          WHEN id<800 THEN success=1
          ELSE 1=1
      END
  AND YEAR(TIMESTAMP)=2011

Print an ArrayList with a for-each loop

import java.util.ArrayList;
import java.util.List;

class ArrLst{

    public static void main(String args[]){

        List l=new ArrayList();
        l.add(10);
        l.add(11);
        l.add(12);
        l.add(13);
        l.add(14);
        l.forEach((a)->System.out.println(a));
    }
}

onchange file input change img src and change image color

Try with this code, you will get the image preview while uploading

<input type='file' id="upload" onChange="readURL(this);"/>
<img id="img" src="#" alt="your image" />

 function readURL(input){
 var ext = input.files[0]['name'].substring(input.files[0]['name'].lastIndexOf('.') + 1).toLowerCase();
if (input.files && input.files[0] && (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg")) 
    var reader = new FileReader();
    reader.onload = function (e) {
        $('#img').attr('src', e.target.result);
    }

    reader.readAsDataURL(input.files[0]);
}else{
     $('#img').attr('src', '/assets/no_preview.png');
}
}

Filter array to have unique values

Filtering an array to contain unique values can be achieved using the JavaScript Set and Array.from method, as shown below:

Array.from(new Set(arrayOfNonUniqueValues));

Set

The Set object lets you store unique values of any type, whether primitive values or object references.

Return value A new Set object.

Array.from()

The Array.from() method creates a new Array instance from an array-like or iterable object.

Return value A new Array instance.

Example Code:

_x000D_
_x000D_
const array = ["X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11"]_x000D_
_x000D_
const uniqueArray = Array.from(new Set(array));_x000D_
_x000D_
console.log("uniqueArray: ", uniqueArray);
_x000D_
_x000D_
_x000D_

What is the difference between a port and a socket?

Firsty, I think we should start with a little understanding of what constitutes getting a packet from A to B.

A common definition for a network is the use of the OSI Model which separates a network out into a number of layers according to purpose. There are a few important ones, which we'll cover here:

  • The data link layer. This layer is responsible for getting packets of data from one network device to another and is just above the layer that actually does the transmitting. It talks about MAC addresses and knows how to find hosts based on their MAC (hardware) address, but nothing more.
  • The network layer is the layer that allows you to transport data across machines and over physical boundaries, such as physical devices. The network layer must essentially support an additional address based mechanism which relates somehow to the physical address; enter the Internet Protocol (IPv4). An IP address can get your packet from A to B over the internet, but knows nothing about how to traverse individual hops. This is handled by the layer above in accordance with routing information.
  • The transport layer. This layer is responsible for defining the way information gets from A to B and any restrictions, checks or errors on that behaviour. For example, TCP adds additional information to a packet such that it is possible to deduce if packets have been lost.

TCP contains, amongst other things, the concept of ports. These are effectively different data endpoints on the same IP address to which an Internet Socket (AF_INET) can bind.

As it happens, so too does UDP, and other transport layer protocols. They don't technically need to feature ports, but these ports do provide a way for multiple applications in the layers above to use the same computer to receive (and indeed make) outgoing connections.

Which brings us to the anatomy of a TCP or UDP connection. Each features a source port and address, and a target port and address. This is so that in any given session, the target application can respond, as well as receive, from the source.

So ports are essentially a specification-mandated way of allowing multiple concurrent connections sharing the same address.

Now, we need to take a look at how you communicate from an application point of view to the outside world. To do this, you need to kindly ask your operating system and since most OSes support the Berkeley Sockets way of doing things, we see we can create sockets involving ports from an application like this:

int fd = socket(AF_INET, SOCK_STREAM, 0); // tcp socket
int fd = socket(AF_INET, SOCK_DGRAM, 0); // udp socket
// later we bind...

Great! So in the sockaddr structures, we'll specify our port and bam! Job done! Well, almost, except:

int fd = socket(AF_UNIX, SOCK_STREAM, 0);

is also possible. Urgh, that's thrown a spanner in the works!

Ok, well actually it hasn't. All we need to do is come up with some appropriate definitions:

  • An internet socket is the combination of an IP address, a protocol and its associated port number on which a service may provide data. So tcp port 80, stackoverflow.com is an internet socket.
  • An unix socket is an IPC endpoint represented in the file system, e.g. /var/run/database.sock.
  • A socket API is a method of requesting an application be able to read and write data to a socket.

Voila! That tidies things up. So in our scheme then,

  • A port is a numeric identifier which, as part of a transport layer protocol, identifies the service number which should respond to the given request.

So really a port is a subset of the requirements for forming an internet socket. Unfortunately, it just so happens that the meaning of the word socket has been applied to several different ideas. So I heartily advise you name your next project socket, just to add to the confusion ;)

WARNING: Can't verify CSRF token authenticity rails

The top voted answers here are correct but will not work if you are performing cross-domain requests because the session will not be available unless you explicitly tell jQuery to pass the session cookie. Here's how to do that:

$.ajax({ 
  url: url,
  type: 'POST',
  beforeSend: function(xhr) {
    xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))
  },
  xhrFields: {
    withCredentials: true
  }
});

Add new row to dataframe, at specific row-index, not appended?

for example you want to add rows of variable 2 to variable 1 of a data named "edges" just do it like this

allEdges <- data.frame(c(edges$V1,edges$V2))

How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?

  • The ownership of the relation is determined by where you place the 'mappedBy' attribute to the annotation. The entity you put 'mappedBy' is the one which is NOT the owner. There's no chance for both sides to be owners. If you don't have a 'delete user' use-case you could simply move the ownership to the Group entity, as currently the User is the owner.
  • On the other hand, you haven't been asking about it, but one thing worth to know. The groups and users are not combined with each other. I mean, after deleting User1 instance from Group1.users, the User1.groups collections is not changed automatically (which is quite surprising for me),
  • All in all, I would suggest you decide who is the owner. Let say the User is the owner. Then when deleting a user the relation user-group will be updated automatically. But when deleting a group you have to take care of deleting the relation yourself like this:

entityManager.remove(group)
for (User user : group.users) {
     user.groups.remove(group);
}
...
// then merge() and flush()

Creating a SearchView that looks like the material design guidelines

Another way you can achieve the desired effect is to use this Material Search View library. It handles search history automatically and it's possible to provide search suggestions to the view as well.

Sample: (It's shown in Portuguese, but it also works in english and italian).

Sample

Setup

Before you can use this lib, you have to implement a class named MsvAuthority inside the br.com.mauker package on your app module, and it should have a public static String variable called CONTENT_AUTHORITY. Give it the value you want and don't forget to add the same name on your manifest file. The lib will use this file to set the Content Provider authority.

Example:

MsvAuthority.java

package br.com.mauker;

public class MsvAuthority {
    public static final String CONTENT_AUTHORITY = "br.com.mauker.materialsearchview.searchhistorydatabase";
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>

    <application ... >
        <provider
        android:name="br.com.mauker.materialsearchview.db.HistoryProvider"
        android:authorities="br.com.mauker.materialsearchview.searchhistorydatabase"
        android:exported="false"
        android:protectionLevel="signature"
        android:syncable="true"/>
    </application>

</manifest>

Usage

To use it, add the dependency:

compile 'br.com.mauker.materialsearchview:materialsearchview:1.2.0'

And then, on your Activity layout file, add the following:

<br.com.mauker.materialsearchview.MaterialSearchView
    android:id="@+id/search_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

After that, you'll just need to get the MaterialSearchView reference by using getViewById(), and open it up or close it using MaterialSearchView#openSearch() and MaterialSearchView#closeSearch().

P.S.: It's possible to open and close the view not only from the Toolbar. You can use the openSearch() method from basically any Button, such as a Floating Action Button.

// Inside onCreate()
MaterialSearchView searchView = (MaterialSearchView) findViewById(R.id.search_view);
Button bt = (Button) findViewById(R.id.button);

bt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            searchView.openSearch();
        }
    });

You can also close the view using the back button, doing the following:

@Override
public void onBackPressed() {
    if (searchView.isOpen()) {
        // Close the search on the back button press.
        searchView.closeSearch();
    } else {
        super.onBackPressed();
    }
}

For more information on how to use the lib, check the github page.

How do I get the old value of a changed cell in Excel VBA?

I have read this old post, and I would like to provide another solution.

The problem with running Application.Undo is that Woksheet_Change runs again. We have the same problem when we restore.

To avoid that, I use a piece of code to avoid the second steps through Worksheet_Change.

Before we begin, we must create a Boolean static variable BlnAlreadyBeenHere, to tell Excel not to run Worksheet_Change again

Here you can see it:

    Private Sub Worksheet_Change(ByVal Target As Range)

    Static blnAlreadyBeenHere As Boolean

    'This piece avoid to execute Worksheet_Change again
    If blnAlreadyBeenHere Then
        blnAlreadyBeenHere = False
        Exit Sub
    End If

    'Now, we will store the old and new value
    Dim vOldValue As Variant
    Dim vNewValue As Variant

    'To store new value
    vNewValue = Target.Value

    'Undo to retrieve old value

    'To avoid new Worksheet_Change execution
    blnAlreadyBeenHere = True

    Application.Undo

    'To store old value
    vOldValue = Target.Value

    'To rewrite new value

    'To avoid new Worksheet_Change execution agein
    blnAlreadyBeenHere = True
    Target.Value = vNewValue

    'Done! I've two vaules stored
    Debug.Print vOldValue, vNewValue

End Sub

The advantage of this method is that it is not necessary to run Worksheet_SelectionChange.

If we want the routine to work from another module, we just have to take the declaration of the variable blnAlreadyBeenHere out of the routine, and declare it with Dim.

Same operation with vOldValue and vNewValue, in the header of a module

Dim blnAlreadyBeenHere As Boolean
Dim vOldValue As Variant
Dim vNewValue As Variant

How can I initialize a String array with length 0 in Java?

Make a function which will not return null instead return an empty array you can go through below code to understand.

    public static String[] getJavaFileNameList(File inputDir) {
    String[] files = inputDir.list(new FilenameFilter() {
        @Override
        public boolean accept(File current, String name) {
            return new File(current, name).isFile() && (name.endsWith("java"));
        }
    });

    return files == null ? new String[0] : files;
}

Execute SQL script to create tables and rows

If you have password for your dB then

mysql -u <username> -p <DBName> < yourfile.sql

Error: Generic Array Creation

The following will give you an array of the type you want while preserving type safety.

PCB[] getAll(Class<PCB[]> arrayType) {  
    PCB[] res = arrayType.cast(java.lang.reflect.Array.newInstance(arrayType.getComponentType(), list.size()));  
    for (int i = 0; i < res.length; i++)  {  
        res[i] = list.get(i);  
    }  
    list.clear();  
    return res;  
}

How this works is explained in depth in my answer to the question that Kirk Woll linked as a duplicate.

Find stored procedure by name

Option 1: In SSMS go to View > Object Explorer Details or press F7. Use the Search box. Finally in the displayed list right click and select Synchronize to find the object in the Object Explorer tree.

Object Explorer Details

Option 2: Install an Add-On like dbForge Search. Right click on the displayed list and select Find in Object Explorer.

enter image description here

raw_input function in Python

raw_input() was renamed to input() in Python 3.

From http://docs.python.org/dev/py3k/whatsnew/3.0.html

CSS selector (id contains part of text)

The only selector I see is a[id$="name"] (all links with id finishing by "name") but it's not as restrictive as it should.

How to check whether Kafka Server is running?

you can use below code to check for brokers available if server is running.

import org.I0Itec.zkclient.ZkClient;
     public static boolean isBrokerRunning(){
        boolean flag = false;
        ZkClient zkClient = new ZkClient(endpoint.getZookeeperConnect(), 10000);//, kafka.utils.ZKStringSerializer$.MODULE$);
        if(zkClient!=null){
            int brokersCount = zkClient.countChildren(ZkUtils.BrokerIdsPath());
            if(brokersCount > 0){
                logger.info("Following Broker(s) {} is/are available on Zookeeper.",zkClient.getChildren(ZkUtils.BrokerIdsPath()));
                flag = true;    
            }
            else{
                logger.error("ERROR:No Broker is available on Zookeeper.");
            }
            zkClient.close();

        }
        return flag;
    }

Why compile Python code?

There's certainly a performance difference when running a compiled script. If you run normal .py scripts, the machine compiles it every time it is run and this takes time. On modern machines this is hardly noticeable but as the script grows it may become more of an issue.

'module' object has no attribute 'DataFrame'

There may be two causes:

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

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

Programmatically Check an Item in Checkboxlist where text is equal to what I want

Example based on ASP.NET CheckBoxList

<asp:CheckBoxList ID="checkBoxList1" runat="server">
    <asp:ListItem>abc</asp:ListItem>
    <asp:ListItem>def</asp:ListItem>
</asp:CheckBoxList>


private void SelectCheckBoxList(string valueToSelect)
{
    ListItem listItem = this.checkBoxList1.Items.FindByText(valueToSelect);

    if(listItem != null) listItem.Selected = true;
}

protected void Page_Load(object sender, EventArgs e)
{
    SelectCheckBoxList("abc");
}

What is the meaning of "POSIX"?

POSIX is a standard for operating systems that was supposed to make it easier to write cross-platform software. It's an especially big deal in the world of Unix.

Pandas - Get first row value of a given column

Note that the answer from @unutbu will be correct until you want to set the value to something new, then it will not work if your dataframe is a view.

In [4]: df = pd.DataFrame({'foo':list('ABC')}, index=[0,2,1])
In [5]: df['bar'] = 100
In [6]: df['bar'].iloc[0] = 99
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas-0.16.0_19_g8d2818e-py2.7-macosx-10.9-x86_64.egg/pandas/core/indexing.py:118: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self._setitem_with_indexer(indexer, value)

Another approach that will consistently work with both setting and getting is:

In [7]: df.loc[df.index[0], 'foo']
Out[7]: 'A'
In [8]: df.loc[df.index[0], 'bar'] = 99
In [9]: df
Out[9]:
  foo  bar
0   A   99
2   B  100
1   C  100

Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

I had many projects of different type in my solution and I could not run the Xunit test project. I unloaded all of them except my Xunit project and then rebuild the solution the tests appeared in visual studio and I could run them.

How do I detect if I am in release or debug mode?

Alternatively, you could differentiate using BuildConfig.BUILD_TYPE;

If you're running debug build BuildConfig.BUILD_TYPE.equals("debug"); returns true. And for release build BuildConfig.BUILD_TYPE.equals("release"); returns true.

Angularjs - display current date

You can also do this with a filter if you don't want to have to attach a date object to the current scope every time you want to print the date:

.filter('currentdate',['$filter',  function($filter) {
    return function() {
        return $filter('date')(new Date(), 'yyyy-MM-dd');
    };
}])

and then in your view:

<div ng-app="myApp">
    <div>{{'' | currentdate}}</div>
</div>

How can I rotate an HTML <div> 90 degrees?

you can use css3 property writing-mode writing-mode: tb-rl

css-tricks

mozilla

What are .NET Assemblies?

MSDN has a good explanation:

Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime with the information it needs to be aware of type implementations. To the runtime, a type does not exist outside the context of an assembly.

jQuery see if any or no checkboxes are selected

Without using 'length' you can do it like this:

if ($('input[type=checkbox]').is(":checked")) {
      //any one is checked
}
else {
//none is checked
}

Unable to set data attribute using jQuery Data() API

Happened the same to me. It turns out that

var data = $("#myObject").data();

gives you a non-writable object. I solved it using:

var data = $.extend({}, $("#myObject").data());

And from then on, data was a standard, writable JS object.

How to convert all tables in database to one collation?

Better option to change also collation of varchar columns inside table also

SELECT CONCAT('ALTER TABLE `', TABLE_NAME,'` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;') AS    mySQL
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA= "myschema"
AND TABLE_TYPE="BASE TABLE"

Additionnaly if you have data with forein key on non utf8 column before launch the bunch script use

SET foreign_key_checks = 0;

It means global SQL will be for mySQL :

SET foreign_key_checks = 0;
ALTER TABLE `table1` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE `table2` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE `tableXXX` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
SET foreign_key_checks = 1;

But take care if according mysql documentation http://dev.mysql.com/doc/refman/5.1/en/charset-column.html,

If you use ALTER TABLE to convert a column from one character set to another, MySQL attempts to map the data values, but if the character sets are incompatible, there may be data loss. "

EDIT: Specially with column type enum, it just crash completly enums set (even if there is no special caracters) https://bugs.mysql.com/bug.php?id=26731

XPath to fetch SQL XML value

Update

My recomendation would be to shred the XML into relations and do searches and joins on the resulted relation, in a set oriented fashion, rather than the procedural fashion of searching specific nodes in the XML. Here is a simple XML query that shreds out the nodes and attributes of interest:

select x.value(N'../../../../@stepId', N'int') as StepID
  , x.value(N'../../@id', N'int') as ComponentID
  , x.value(N'@nom',N'nvarchar(100)') as Nom
  , x.value(N'@valeur', N'nvarchar(100)') as Valeur
from @x.nodes(N'/xml/box/components/component/variables/variable') t(x)

However, if you must use an XPath that retrieves exactly the value of interest:

select x.value(N'@valeur', N'nvarchar(100)') as Valeur
from @x.nodes(N'/xml/box[@stepId=sql:variable("@stepID")]/
    components/component[@id = sql:variable("@componentID")]/
       variables/variable[@nom="Enabled"]') t(x)

If the stepID and component ID are columns, not variables, the you should use sql:column() instead of sql:variable in the XPath filters. See Binding Relational Data Inside XML Data.

And finaly if all you need is to check for existance you can use the exist() XML method:

select @x.exist(
  N'/xml/box[@stepId=sql:variable("@stepID")]/
    components/component[@id = sql:variable("@componentID")]/
      variables/variable[@nom="Enabled" and @valeur="Yes"]') 

Is this the proper way to do boolean test in SQL?

A boolean in SQL is a bit field. This means either 1 or 0. The correct syntax is:

select * from users where active = 1 /* All Active Users */

or

select * from users where active = 0 /* All Inactive Users */

Check for database connection, otherwise display message

Please check this:

$servername='localhost';
$username='root';
$password='';
$databasename='MyDb';

$connection = mysqli_connect($servername,$username,$password);

if (!$connection) {
die("Connection failed: " . $conn->connect_error);
}

/*mysqli_query($connection, "DROP DATABASE if exists MyDb;");

if(!mysqli_query($connection, "CREATE DATABASE MyDb;")){
echo "Error creating database: " . $connection->error;
}

mysqli_query($connection, "use MyDb;");
mysqli_query($connection, "DROP TABLE if exists employee;");

$table="CREATE TABLE employee (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)"; 
$value="INSERT INTO employee (firstname,lastname,email) VALUES ('john', 'steve', '[email protected]')";
if(!mysqli_query($connection, $table)){echo "Error creating table: " . $connection->error;}
if(!mysqli_query($connection, $value)){echo "Error inserting values: " . $connection->error;}*/

Java Compare Two Lists

Using java 8 removeIf

public int getSimilarItems(){
    List<String> one = Arrays.asList("milan", "dingo", "elpha", "hafil", "meat", "iga", "neeta.peeta");
    List<String> two = new ArrayList<>(Arrays.asList("hafil", "iga", "binga", "mike", "dingo")); //Cannot remove directly from array backed collection
    int initial = two.size();

    two.removeIf(one::contains);
    return initial - two.size();
}

How to make Scrollable Table with fixed headers using CSS

I can think of a cheeky way to do it, I don't think this will be the best option but it will work.

Create the header as a separate table then place the other in a div and set a max size, then allow the scroll to come in by using overflow.

_x000D_
_x000D_
table {_x000D_
  width: 500px;_x000D_
}_x000D_
_x000D_
.scroll {_x000D_
  max-height: 60px;_x000D_
  overflow: auto;_x000D_
}
_x000D_
<table border="1">_x000D_
  <tr>_x000D_
  <th>head1</th>_x000D_
  <th>head2</th>_x000D_
  <th>head3</th>_x000D_
  <th>head4</th>_x000D_
  </tr>_x000D_
</table>_x000D_
<div class="scroll">_x000D_
  <table>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>More Text</td><td>More Text</td><td>More Text</td><td>More Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td></tr>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

CSS - display: none; not working

This is because the inline style display:block is overwriting your CSS. You'll need to either remove this inline style or use:

#tfl {
  display: none !important;
}

This overrides inline styles. Note that using !important is generally not recommended unless it's a last resort.

error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj

Last chance (if other ways don't work): define _ALLOW_ITERATOR_DEBUG_LEVEL_MISMATCH macro in all projects. It will disable "#pragma detect_mismatch" feature which is used in CRT headers.

How to programmatically round corners and set random background colors

Copying @cimlman's comment into a top-level answer for more visibility:

PaintDrawable(Color.CYAN).apply {
  setCornerRadius(24f)
}

FYI: ShapeDrawable (and its subtype, PaintDrawable) uses default intrinsic width and height of 0. If the drawable does not show up in your usecase, you might have to set the dimensions manually:

PaintDrawable(Color.CYAN).apply {
  intrinsicWidth = -1
  intrinsicHeight = -1
  setCornerRadius(24f)
}

-1 is a magic constant which indicates that a Drawable has no intrinsic width and height of its own (Source).

C# windows application Event: CLR20r3 on application start

I encountered the same problem when I built an application on a Windows 7 box that had previously been maintained on an XP machine.

The program ran fine when built for Debug, but failed with this error when built for Release. I found the answer on the project's Properties page. Go to the "Build" tab and try changing the Platform Target from "Any CPU" to "x86".

How do I clear/delete the current line in terminal?

CTRL+R and start typing to search for previous commands in history. Will show full lines.
CTRL+R again to cycle.

Spring Resttemplate exception handling

Spring abstracts you from the very very very large list of http status code. That is the idea of the exceptions. Take a look into org.springframework.web.client.RestClientException hierarchy:

You have a bunch of classes to map the most common situations when dealing with http responses. The http codes list is really large, you won't want write code to handle each situation. But for example, take a look into the HttpClientErrorException sub-hierarchy. You have a single exception to map any 4xx kind of error. If you need to go deep, then you can. But with just catching HttpClientErrorException, you can handle any situation where bad data was provided to the service.

The DefaultResponseErrorHandler is really simple and solid. If the response status code is not from the family of 2xx, it just returns true for the hasError method.

How to include file in a bash shell script

Yes, use source or the short form which is just .:

. other_script.sh

correct way of comparing string jquery operator =

No. = sets somevar to have that value. use === to compare value and type which returns a boolean that you need.

Never use or suggest == instead of ===. its a recipe for disaster. e.g 0 == "" is true but "" == '0' is false and many more.

More information also in this great answer

Apply a theme to an activity in Android?

To set it programmatically in Activity.java:

public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setTheme(R.style.MyTheme); // (for Custom theme)
  setTheme(android.R.style.Theme_Holo); // (for Android Built In Theme)

  this.setContentView(R.layout.myactivity);

To set in Application scope in Manifest.xml (all activities):

 <application
    android:theme="@android:style/Theme.Holo"
    android:theme="@style/MyTheme">

To set in Activity scope in Manifest.xml (single activity):

  <activity
    android:theme="@android:style/Theme.Holo"
    android:theme="@style/MyTheme">

To build a custom theme, you will have to declare theme in themes.xml file, and set styles in styles.xml file.

How to check command line parameter in ".bat" file?

Actually, all the other answers have flaws. The most reliable way is:

IF "%~1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)

Detailed Explanation:

Using "%1"=="-b" will flat out crash if passing argument with spaces and quotes. This is the least reliable method.

IF "%1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)

C:\> run.bat "a b"

b""=="-b" was unexpected at this time.

Using [%1]==[-b] is better because it will not crash with spaces and quotes, but it will not match if the argument is surrounded by quotes.

IF [%1]==[-b] (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)

C:\> run.bat "-b"

(does not match, and jumps to UNKNOWN instead of SPECIFIC)

Using "%~1"=="-b" is the most reliable. %~1 will strip off surrounding quotes if they exist. So it works with and without quotes, and also with no args.

IF "%~1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)

C:\> run.bat
C:\> run.bat -b
C:\> run.bat "-b"
C:\> run.bat "a b"

(all of the above tests work correctly)

Multiple Cursors in Sublime Text 2 Windows

Mac Users, let me save you the time:

  • Cmd+a: select the lines you want a cursor
  • Cmd+Shift+l: to create the cursor

Creating random colour in Java?

Copy paste this for bright pastel rainbow colors

int R = (int)(Math.random()*256);
int G = (int)(Math.random()*256);
int B= (int)(Math.random()*256);
Color color = new Color(R, G, B); //random color, but can be bright or dull

//to get rainbow, pastel colors
Random random = new Random();
final float hue = random.nextFloat();
final float saturation = 0.9f;//1.0 for brilliant, 0.0 for dull
final float luminance = 1.0f; //1.0 for brighter, 0.0 for black
color = Color.getHSBColor(hue, saturation, luminance);

how to fire event on file select

<input type="file" @change="onFileChange" class="input upload-input" ref="inputFile"/>

onFileChange(e) {
    //upload file and then delete it from input 
    self.$refs.inputFile.value = ''
}

How to remove square brackets in string using regex?

You probably don't even need string substitution for that. If your original string is JSON, try:

js> a="['abc','xyz']"
['abc','xyz']
js> eval(a).join(",")
abc,xyz

Be careful with eval, of course.

How to decrypt the password generated by wordpress

You will not be able to retrieve a plain text password from wordpress.

Wordpress use a 1 way encryption to store the passwords using a variation of md5. There is no way to reverse this.

See this article for more info http://wordpress.org/support/topic/how-is-the-user-password-encrypted-wp_hash_password

Variables not showing while debugging in Eclipse

Assuming you have your debug view just how you like it and don't want to have to reset it everytime this bug appears, try this. This assumes your "Debug View" has both "Expressions" and "Variables" views open.

Double-Click the Expressions tab (the actual tab with the text, not the 'window bar'). This will maximise it. Repeat to restore it to previous size/location. That should reset everything except Expressions. Repeat for the variables tab and it will reset expressions.

This worked for me on Windows 10 with Eclipse:
Version: 2018-09 (4.9.0)
Build id: 20180917-1800
Java: jdk1.8.0_171

How to hide action bar before activity is created, and then show it again?

best and simple

requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

When to use self over $this?

self (not $self) refers to the type of class, where as $this refers to the current instance of the class. self is for use in static member functions to allow you to access static member variables. $this is used in non-static member functions, and is a reference to the instance of the class on which the member function was called.

Because this is an object, you use it like: $this->member

Because self is not an object, it's basically a type that automatically refers to the current class, you use it like: self::member

How to get value of checked item from CheckedListBox?

I've already posted GetItemValue extension method in this post Get the value for a listbox item by index. This extension method will work for all ListControl classes including CheckedListBox, ListBox and ComboBox.


None of the existing answers are general enough, but there is a general solution for the problem.

In all cases, the underlying Value of an item should be calculated regarding to ValueMember, regardless of the type of data source.

The data source of the CheckedListBox may be a DataTable or it may be a list which contains objects, like a List<T>, so the items of a CheckedListBox control may be DataRowView, Complex Objects, Anonymous types, primary types and other types.

GetItemValue Extension Method

We need a GetItemValue which works similar to GetItemText, but return an object, the underlying value of an item, regardless of the type of object you added as item.

We can create GetItemValue extension method to get item value which works like GetItemText:

using System;
using System.Windows.Forms;
using System.ComponentModel;
public static class ListControlExtensions
{
    public static object GetItemValue(this ListControl list, object item)
    {
        if (item == null)
            throw new ArgumentNullException("item");

        if (string.IsNullOrEmpty(list.ValueMember))
            return item;

        var property = TypeDescriptor.GetProperties(item)[list.ValueMember];
        if (property == null)
            throw new ArgumentException(
                string.Format("item doesn't contain '{0}' property or column.",
                list.ValueMember));
        return property.GetValue(item);
    }
}

Using above method you don't need to worry about settings of ListBox and it will return expected Value for an item. It works with List<T>, Array, ArrayList, DataTable, List of Anonymous Types, list of primary types and all other lists which you can use as data source. Here is an example of usage:

//Gets underlying value at index 2 based on settings
this.checkedListBox.GetItemValue(this.checkedListBox.Items[2]);

Since we created the GetItemValue method as an extension method, when you want to use the method, don't forget to include the namespace in which you put the class.

This method is applicable on ComboBox and CheckedListBox too.

How to resize a custom view programmatically?

try a this one:

...
View view = inflater.inflate(R.layout.active_slide, this);
view.setMinimumWidth(200);

How to sort by dates excel?

For example 8/12/1976. Copy your date column. Highlight the copied column and click Data> Text to Columns> Delimited> Next. In the delimiters column check "Other" and input / and then click Next and Finish. You'll have 3 columns and the first column will be 1/8. Highlight it and click the comma in the Number section and it will give you the month as 8.00, so then reduce it by clicking the comma in Home/Numbers and you'll now have 8 in the first column, 18 in the second column and 1976 in the third column. In the first empty cell to the right use the concatenate function and leave out the year column. If your month is column A, day is column B and year is column C, it will look like this: =concatenate(A2,"/",B2) and hit enter. It will look like 8/18, however, when you click on the cell you'll see the concatenate formula. Highlight the cell(s), then copy and paste special values. Now you can sort by date. It's really quick when you get the hang of it.

What are the rules for JavaScript's automatic semicolon insertion (ASI)?

Regarding semicolon insertion and the var statement, beware forgetting the comma when using var but spanning multiple lines. Somebody found this in my code yesterday:

    var srcRecords = src.records
        srcIds = [];

It ran but the effect was that the srcIds declaration/assignment was global because the local declaration with var on the previous line no longer applied as that statement was considered finished due to automatic semi-colon insertion.

Automatic date update in a cell when another cell's value changes (as calculated by a formula)

You could fill the dependend cell (D2) by a User Defined Function (VBA Macro Function) that takes the value of the C2-Cell as input parameter, returning the current date as ouput.

Having C2 as input parameter for the UDF in D2 tells Excel that it needs to reevaluate D2 everytime C2 changes (that is if auto-calculation of formulas is turned on for the workbook).

EDIT:

Here is some code:

For the UDF:

    Public Function UDF_Date(ByVal data) As Date

        UDF_Date = Now()

    End Function

As Formula in D2:

=UDF_Date(C2)

You will have to give the D2-Cell a Date-Time Format, or it will show a numeric representation of the date-value.

And you can expand the formula over the desired range by draging it if you keep the C2 reference in the D2-formula relative.

Note: This still might not be the ideal solution because every time Excel recalculates the workbook the date in D2 will be reset to the current value. To make D2 only reflect the last time C2 was changed there would have to be some kind of tracking of the past value(s) of C2. This could for example be implemented in the UDF by providing also the address alonside the value of the input parameter, storing the input parameters in a hidden sheet, and comparing them with the previous values everytime the UDF gets called.

Addendum:

Here is a sample implementation of an UDF that tracks the changes of the cell values and returns the date-time when the last changes was detected. When using it, please be aware that:

  • The usage of the UDF is the same as described above.

  • The UDF works only for single cell input ranges.

  • The cell values are tracked by storing the last value of cell and the date-time when the change was detected in the document properties of the workbook. If the formula is used over large datasets the size of the file might increase considerably as for every cell that is tracked by the formula the storage requirements increase (last value of cell + date of last change.) Also, maybe Excel is not capable of handling very large amounts of document properties and the code might brake at a certain point.

  • If the name of a worksheet is changed all the tracking information of the therein contained cells is lost.

  • The code might brake for cell-values for which conversion to string is non-deterministic.

  • The code below is not tested and should be regarded only as proof of concept. Use it at your own risk.

    Public Function UDF_Date(ByVal inData As Range) As Date
    
        Dim wb As Workbook
        Dim dProps As DocumentProperties
        Dim pValue As DocumentProperty
        Dim pDate As DocumentProperty
        Dim sName As String
        Dim sNameDate As String
    
        Dim bDate As Boolean
        Dim bValue As Boolean
        Dim bChanged As Boolean
    
        bDate = True
        bValue = True
    
        bChanged = False
    
    
        Dim sVal As String
        Dim dDate As Date
    
        sName = inData.Address & "_" & inData.Worksheet.Name
        sNameDate = sName & "_dat"
    
        sVal = CStr(inData.Value)
        dDate = Now()
    
        Set wb = inData.Worksheet.Parent
    
        Set dProps = wb.CustomDocumentProperties
    
    On Error Resume Next
    
        Set pValue = dProps.Item(sName)
    
        If Err.Number <> 0 Then
            bValue = False
            Err.Clear
        End If
    
    On Error GoTo 0
    
        If Not bValue Then
            bChanged = True
            Set pValue = dProps.Add(sName, False, msoPropertyTypeString, sVal)
        Else
            bChanged = pValue.Value <> sVal
            If bChanged Then
                pValue.Value = sVal
            End If
        End If
    
    On Error Resume Next
    
        Set pDate = dProps.Item(sNameDate)
    
        If Err.Number <> 0 Then
            bDate = False
            Err.Clear
        End If
    
    On Error GoTo 0
    
        If Not bDate Then
            Set pDate = dProps.Add(sNameDate, False, msoPropertyTypeDate, dDate)
        End If
    
        If bChanged Then
            pDate.Value = dDate
        Else
            dDate = pDate.Value
        End If
    
    
        UDF_Date = dDate
     End Function
    

Make the insertion of the date conditional upon the range.

This has an advantage of not changing the dates unless the content of the cell is changed, and it is in the range C2:C2, even if the sheet is closed and saved, it doesn't recalculate unless the adjacent cell changes.

Adapted from this tip and @Paul S answer

Private Sub Worksheet_Change(ByVal Target As Range)
 Dim R1 As Range
 Dim R2 As Range
 Dim InRange As Boolean
    Set R1 = Range(Target.Address)
    Set R2 = Range("C2:C20")
    Set InterSectRange = Application.Intersect(R1, R2)

  InRange = Not InterSectRange Is Nothing
     Set InterSectRange = Nothing
   If InRange = True Then
     R1.Offset(0, 1).Value = Now()
   End If
     Set R1 = Nothing
     Set R2 = Nothing
 End Sub

To delay JavaScript function call using jQuery

Since you declare sample inside the anonymous function you pass to ready, it is scoped to that function.

You then pass a string to setTimeout which is evaled after 2 seconds. This takes place outside the current scope, so it can't find the function.

Only pass functions to setTimeout, using eval is inefficient and hard to debug.

setTimeout(sample,2000)

VBA - Select columns using numbers?

no need for loops or such.. try this..

dim startColumnas integer

dim endColumn as integer

startColumn = 7

endColumn = 24

Range(Cells(, startColumn), Cells(, endColumn)).ColumnWidth = 3.8 ' <~~ whatever width you want to set..* 

getResourceAsStream returns null

Don't use absolute paths, make them relative to the 'resources' directory in your project. Quick and dirty code that displays the contents of MyTest.txt from the directory 'resources'.

@Test
public void testDefaultResource() {
    // can we see default resources
    BufferedInputStream result = (BufferedInputStream) 
         Config.class.getClassLoader().getResourceAsStream("MyTest.txt");
    byte [] b = new byte[256];
    int val = 0;
    String txt = null;
    do {
        try {
            val = result.read(b);
            if (val > 0) {
                txt += new String(b, 0, val);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } 
    } while (val > -1);
    System.out.println(txt);
}

What exactly is \r in C language?

That is not always true; it only works in Windows.
For interacting with terminal in putty, Linux shell,... it will be used for returning the cursor to the beginning of line. following picture shows the usage of that:

Without '\r':

Data comes without '\r' to the putty terminal, it has just '\n'.
it means that data will be printed just in next line.

enter image description here

With '\r':

Data comes with '\r', i.e. string ends with '\r\n'. So the cursor in putty terminal not only will go to the next line but also at the beginning of line

enter image description here

List(of String) or Array or ArrayList

List(Of String) will handle that, mostly - though you need to either use AddRange to add a collection of items, or Add to add one at a time:

lstOfString.Add(String1)
lstOfString.Add(String2)
lstOfString.Add(String3)
lstOfString.Add(String4)

If you're adding known values, as you show, a good option is to use something like:

Dim inputs() As String = { "some value", _
                              "some value2", _
                              "some value3", _
                              "some value4" }

Dim lstOfString as List(Of String) = new List(Of String)(inputs)

' ...
Dim s3 = lstOfStrings(3)

This will still allow you to add items later as desired, but also get your initial values in quickly.


Edit:

In your code, you need to fix the declaration. Change:

Dim lstWriteBits() As List(Of String) 

To:

Dim lstWriteBits As List(Of String) 

Currently, you're declaring an Array of List(Of String) objects.

Using "-Filter" with a variable

Add double quote

$nameRegex = "chalmw-dm*"

-like "$nameregex" or -like "'$nameregex'"

Add regression line equation and R^2 on graph

Another option would be to create a custom function generating the equation using dplyr and broom libraries:

get_formula <- function(model) {
  
  broom::tidy(model)[, 1:2] %>%
    mutate(sign = ifelse(sign(estimate) == 1, ' + ', ' - ')) %>% #coeff signs
    mutate_if(is.numeric, ~ abs(round(., 2))) %>% #for improving formatting
    mutate(a = ifelse(term == '(Intercept)', paste0('y ~ ', estimate), paste0(sign, estimate, ' * ', term))) %>%
    summarise(formula = paste(a, collapse = '')) %>%
    as.character
  
}

lm(y ~ x, data = df) -> model
get_formula(model)
#"y ~ 6.22 + 3.16 * x"

scales::percent(summary(model)$r.squared, accuracy = 0.01) -> r_squared

Now we need to add the text to the plot:

p + 
  geom_text(x = 20, y = 300,
            label = get_formula(model),
            color = 'red') +
  geom_text(x = 20, y = 285,
            label = r_squared,
            color = 'blue')

plot

Java creating .jar file

In order to create a .jar file, you need to use jar instead of java:

jar cf myJar.jar myClass.class

Additionally, if you want to make it executable, you need to indicate an entry point (i.e., a class with public static void main(String[] args)) for your application. This is usually accomplished by creating a manifest file that contains the Main-Class header (e.g., Main-Class: myClass).

However, as Mark Peters pointed out, with JDK 6, you can use the e option to define the entry point:

jar cfe myJar.jar myClass myClass.class 

Finally, you can execute it:

java -jar myJar.jar

See also

How to delete a whole folder and content?

There is a lot of answers, but I decided to add my own, because it's little different. It's based on OOP ;)

I created class DirectoryCleaner, which help me each time when I need to clean some directory.

public class DirectoryCleaner {
    private final File mFile;

    public DirectoryCleaner(File file) {
        mFile = file;
    }

    public void clean() {
        if (null == mFile || !mFile.exists() || !mFile.isDirectory()) return;
        for (File file : mFile.listFiles()) {
            delete(file);
        }
    }

    private void delete(File file) {
        if (file.isDirectory()) {
            for (File child : file.listFiles()) {
                delete(child);
            }
        }
        file.delete();

    }
}

It can be used to solve this problem in next way:

File dir = new File(Environment.getExternalStorageDirectory(), "your_directory_name");
new DirectoryCleaner(dir).clean();
dir.delete();

Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject

You have to disable the sandbox for Groovy in your job configuration.

Currently this is not possible for multibranch projects where the groovy script comes from the scm. For more information see https://issues.jenkins-ci.org/browse/JENKINS-28178

How do I dynamically set HTML5 data- attributes using react?

Note - if you want to pass a data attribute to a React Component, you need to handle them a little differently than other props.

2 options

Don't use camel case

<Option data-img-src='value' ... />

And then in the component, because of the dashes, you need to refer to the prop in quotes.

// @flow
class Option extends React.Component {

  props: {
    'data-img-src': string
  }

And when you refer to it later, you don't use the dot syntax

  render () {
    return (
      <option data-img-src={this.props['data-img-src']} >...</option>
    )
  }
}

Or use camel case

<Option dataImgSrc='value' ... />

And then in the component, you need to convert.

// @flow
class Option extends React.Component {

  props: {
    dataImgSrc: string
  }

And when you refer to it later, you don't use the dot syntax

  render () {
    return (
      <option data-img-src={this.props.dataImgSrc} >...</option>
    )
  }
}

Mainly just realize data- attributes and aria- attributes are treated specially. You are allowed to use hyphens in the attribute name in those two cases.

Difference between add(), replace(), and addToBackStack()

Example an activity have 2 fragments and we use FragmentManager to replace/add with addToBackstack each fragment to a layout in activity

Use replace

Go Fragment1

Fragment1: onAttach
Fragment1: onCreate
Fragment1: onCreateView
Fragment1: onActivityCreated
Fragment1: onStart
Fragment1: onResume

Go Fragment2

Fragment2: onAttach
Fragment2: onCreate
Fragment1: onPause
Fragment1: onStop
Fragment1: onDestroyView
Fragment2: onCreateView
Fragment2: onActivityCreated
Fragment2: onStart
Fragment2: onResume

Pop Fragment2

Fragment2: onPause
Fragment2: onStop
Fragment2: onDestroyView
Fragment2: onDestroy
Fragment2: onDetach
Fragment1: onCreateView
Fragment1: onStart
Fragment1: onResume

Pop Fragment1

Fragment1: onPause
Fragment1: onStop
Fragment1: onDestroyView
Fragment1: onDestroy
Fragment1: onDetach

Use add

Go Fragment1

Fragment1: onAttach
Fragment1: onCreate
Fragment1: onCreateView
Fragment1: onActivityCreated
Fragment1: onStart
Fragment1: onResume

Go Fragment2

Fragment2: onAttach
Fragment2: onCreate
Fragment2: onCreateView
Fragment2: onActivityCreated
Fragment2: onStart
Fragment2: onResume

Pop Fragment2

Fragment2: onPause
Fragment2: onStop
Fragment2: onDestroyView
Fragment2: onDestroy
Fragment2: onDetach

Pop Fragment1

Fragment1: onPause
Fragment1: onStop
Fragment1: onDestroyView
Fragment1: onDestroy
Fragment1: onDetach

Sample project

'mat-form-field' is not a known element - Angular 5 & Material2

@NgModule({
  declarations: [
    SearchComponent
  ],
  exports: [
    CommonModule,
    MatInputModule,
    MatButtonModule,
    MatCardModule,
    MatFormFieldModule,
    MatDialogModule,
  ]
})
export class MaterialModule { }

Also, do not forget to import the MaterialModule in the imports array of AppModule.

Why use double indirection? or Why use pointers to pointers?

Why double pointers?

The objective is to change what studentA points to, using a function.

#include <stdio.h>
#include <stdlib.h>


typedef struct Person{
    char * name;
} Person; 

/**
 * we need a ponter to a pointer, example: &studentA
 */
void change(Person ** x, Person * y){
    *x = y; // since x is a pointer to a pointer, we access its value: a pointer to a Person struct.
}

void dontChange(Person * x, Person * y){
    x = y;
}

int main()
{

    Person * studentA = (Person *)malloc(sizeof(Person));
    studentA->name = "brian";

    Person * studentB = (Person *)malloc(sizeof(Person));
    studentB->name = "erich";

    /**
     * we could have done the job as simple as this!
     * but we need more work if we want to use a function to do the job!
     */
    // studentA = studentB;

    printf("1. studentA = %s (not changed)\n", studentA->name);

    dontChange(studentA, studentB);
    printf("2. studentA = %s (not changed)\n", studentA->name);

    change(&studentA, studentB);
    printf("3. studentA = %s (changed!)\n", studentA->name);

    return 0;
}

/**
 * OUTPUT:
 * 1. studentA = brian (not changed)
 * 2. studentA = brian (not changed)
 * 3. studentA = erich (changed!)
 */