Programs & Examples On #Derived types

How to delete specific rows and columns from a matrix in a smarter way?

> S = matrix(c(1,2,3,4,5,2,1,2,3,4,3,2,1,2,3,4,3,2,1,2,5,4,3,2,1),ncol = 5,byrow = TRUE);S
[,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    2    1    2    3    4
[3,]    3    2    1    2    3
[4,]    4    3    2    1    2
[5,]    5    4    3    2    1
> S<-S[,-2]
> S
[,1] [,2] [,3] [,4]
[1,]    1    3    4    5
[2,]    2    2    3    4
[3,]    3    1    2    3
[4,]    4    2    1    2
[5,]    5    3    2    1

Just use the command S <- S[,-2] to remove the second column. Similarly to delete a row, for example, to delete the second row use S <- S[-2,].

IIS7 Cache-Control

there is a easy way: 1. using website's web.config 2. in "staticContent" section remove specific fileExtension and add mimeMap 3. add "clientCache"

<configuration>
  <system.webServer>
    <urlCompression doStaticCompression="true" doDynamicCompression="true" />
    <staticContent>
      <remove fileExtension=".ipa" />
      <remove fileExtension=".apk" />
      <mimeMap fileExtension=".ipa" mimeType="application/iphone" />
      <mimeMap fileExtension=".apk" mimeType="application/vnd.android.package-archive" />
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="777.00:00:00" />
    </staticContent>
  </system.webServer>
</configuration>

How do I print out the value of this boolean? (Java)

There are several problems.

One is of style; always capitalize class names. This is a universally observed Java convention. Failing to do so confuses other programmers.

Secondly, the line

System.out.println(boolean isLeapYear);

is a syntax error. Delete it.

Thirdly.

You never call the function from your main routine. That is why you never see any reply to the input.

Connect Java to a MySQL database

you need to have mysql connector jar in your classpath.

in Java JDBC API makes everything with databases. using JDBC we can write Java applications to
1. Send queries or update SQL to DB(any relational Database) 2. Retrieve and process the results from DB

with below three steps we can able to retrieve data from any Database

Connection con = DriverManager.getConnection(
                     "jdbc:myDriver:DatabaseName",
                     dBuserName,
                     dBuserPassword);

Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table");

while (rs.next()) {
    int x = rs.getInt("a");
    String s = rs.getString("b");
    float f = rs.getFloat("c");
}

Get value of multiselect box using jQuery or pure JS

the val function called from the select will return an array if its a multiple. $('select#my_multiselect').val() will return an array of the values for the selected options - you dont need to loop through and get them yourself.

Session state can only be used when enableSessionState is set to true either in a configuration

Following answer from below given path worked fine.

I found a solution that worked perfectly! Add the following to web.config:

<system.webServer>
<modules>
<!-- UrlRewriter code here -->
<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule" preCondition="" />
</modules>
</system.webServer>

Hope this helps someone else!

Internal Error 500 Apache, but nothing in the logs?

Why are the 500 Internal Server Errors not being logged into your apache error logs?

The errors that cause your 500 Internal Server Error are coming from a PHP module. By default, PHP does NOT log these errors. Reason being you want web requests go as fast as physically possible and it's a security hazard to log errors to screen where attackers can observe them.

These instructions to enable Internal Server Error Logging are for Ubuntu 12.10 with PHP 5.3.10 and Apache/2.2.22.

Make sure PHP logging is turned on:

  1. Locate your php.ini file:

    el@apollo:~$ locate php.ini
    /etc/php5/apache2/php.ini
    
  2. Edit that file as root:

    sudo vi /etc/php5/apache2/php.ini
    
  3. Find this line in php.ini:

    display_errors = Off
    
  4. Change the above line to this:

    display_errors = On
    
  5. Lower down in the file you'll see this:

    ;display_startup_errors
    ;   Default Value: Off
    ;   Development Value: On
    ;   Production Value: Off
    
    ;error_reporting
    ;   Default Value: E_ALL & ~E_NOTICE
    ;   Development Value: E_ALL | E_STRICT
    ;   Production Value: E_ALL & ~E_DEPRECATED
    
  6. The semicolons are comments, that means the lines don't take effect. Change those lines so they look like this:

    display_startup_errors = On
    ;   Default Value: Off
    ;   Development Value: On
    ;   Production Value: Off
    
    error_reporting = E_ALL
    ;   Default Value: E_ALL & ~E_NOTICE
    ;   Development Value: E_ALL | E_STRICT
    ;   Production Value: E_ALL & ~E_DEPRECATED
    

    What this communicates to PHP is that we want to log all these errors. Warning, there will be a large performance hit, so you don't want this enabled on production because logging takes work and work takes time, time costs money.

  7. Restarting PHP and Apache should apply the change.

  8. Do what you did to cause the 500 Internal Server error again, and check the log:

    tail -f /var/log/apache2/error.log
    
  9. You should see the 500 error at the end, something like this:

    [Wed Dec 11 01:00:40 2013] [error] [client 192.168.11.11] PHP Fatal error:  
    Call to undefined function Foobar\\byob\\penguin\\alert() in /yourproject/
    your_src/symfony/Controller/MessedUpController.php on line 249, referer: 
    https://nuclearreactor.com/abouttoblowup
    

How do I remove the horizontal scrollbar in a div?

To hide the horizontal scrollbar, we can just select the scrollbar of the required div and set it to display: none;

One thing to note is that this will only work for WebKit-based browsers (like Chrome) as there is no such option available for Mozilla.

In order to select the scrollbar, use ::-webkit-scrollbar

So the final code will be like this:

div::-webkit-scrollbar {
  display: none;
}

Clone only one branch

--single-branch” switch is your answer, but it only works if you have git version 1.8.X onwards, first check

#git --version 

If you already have git version 1.8.X installed then simply use "-b branch and --single branch" to clone a single branch

#git clone -b branch --single-branch git://github/repository.git

By default in Ubuntu 12.04/12.10/13.10 and Debian 7 the default git installation is for version 1.7.x only, where --single-branch is an unknown switch. In that case you need to install newer git first from a non-default ppa as below.

sudo add-apt-repository ppa:pdoes/ppa
sudo apt-get update
sudo apt-get install git
git --version

Once 1.8.X is installed now simply do:

git clone -b branch --single-branch git://github/repository.git

Git will now only download a single branch from the server.

Java: method to get position of a match in a String?

I have some big code but working nicely....

   class strDemo
   { 
       public static void main(String args[])
       {
       String s1=new String("The Ghost of The Arabean Sea");
           String s2=new String ("The");
           String s6=new String ("ehT");
           StringBuffer s3;
           StringBuffer s4=new StringBuffer(s1);
           StringBuffer s5=new StringBuffer(s2);
           char c1[]=new char[30];
           char c2[]=new char[5];
           char c3[]=new char[5];
           s1.getChars(0,28,c1,0);
           s2.getChars(0,3,c2,0);
           s6.getChars(0,3,c3,0); s3=s4.reverse();      
           int pf=0,pl=0;
           char c5[]=new char[30];
           s3.getChars(0,28,c5,0);
           for(int i=0;i<(s1.length()-s2.length());i++)
           {
               int j=0;
               if(pf<=1)
               {
                  while (c1[i+j]==c2[j] && j<=s2.length())
                  {           
                    j++;
                    System.out.println(s2.length()+" "+j);
                    if(j>=s2.length())
                    {
                       System.out.println("first match of(The) :->"+i);

                     }
                     pf=pf+1;         
                  }   
             }                
       }       
         for(int i=0;i<(s3.length()-s6.length()+1);i++)
        {
            int j=0;
            if(pl<=1)
            {
             while (c5[i+j]==c3[j] && j<=s6.length())
             {
                 j++;
                 System.out.println(s6.length()+" "+j);
                 if(j>=s6.length())
                 {
                         System.out.println((s3.length()-i-3));
                         pl=pl+1;

                 }   
                }                 
              }  
           }  
         }
       }

Building a fat jar using maven

An alternative is to use the maven shade plugin to build an uber-jar.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version> Your Version Here </version>
    <configuration>
            <!-- put your configurations here -->
    </configuration>
    <executions>
            <execution>
                    <phase>package</phase>
                    <goals>
                            <goal>shade</goal>
                    </goals>
            </execution>
    </executions>
</plugin>

appending list but error 'NoneType' object has no attribute 'append'

You are not supposed to assign it to any variable, when you append something in the list, it updates automatically. use only:-

last_list.append(p.last)

if you assign this to a variable "last_list" again, it will no more be a list (will become a none type variable since you haven't declared the type for that) and append will become invalid in the next run.

QByteArray to QString

You can use QTextCodec to convert the bytearray to a string:

QString DataAsString = QTextCodec::codecForMib(1015)->toUnicode(Data);

(1015 is UTF-16, 1014 UTF-16LE, 1013 UTF-16BE, 106 UTF-8)

From your example we can see that the string "test" is encoded as "t\0 e\0 s\0 t\0 \0 \0" in your encoding, i.e. every ascii character is followed by a \0-byte, or resp. every ascii character is encoded as 2 bytes. The only unicode encoding in which ascii letters are encoded in this way, are UTF-16 or UCS-2 (which is a restricted version of UTF-16), so in your case the 1015 mib is needed (assuming your local endianess is the same as the input endianess).

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

Your DemoApplication class is in the com.ag.digital.demo.boot package and your LoginBean class is in the com.ag.digital.demo.bean package. By default components (classes annotated with @Component) are found if they are in the same package or a sub-package of your main application class DemoApplication. This means that LoginBean isn't being found so dependency injection fails.

There are a couple of ways to solve your problem:

  1. Move LoginBean into com.ag.digital.demo.boot or a sub-package.
  2. Configure the packages that are scanned for components using the scanBasePackages attribute of @SpringBootApplication that should be on DemoApplication.

A few of other things that aren't causing a problem, but are not quite right with the code you've posted:

  • @Service is a specialisation of @Component so you don't need both on LoginBean
  • Similarly, @RestController is a specialisation of @Component so you don't need both on DemoRestController
  • DemoRestController is an unusual place for @EnableAutoConfiguration. That annotation is typically found on your main application class (DemoApplication) either directly or via @SpringBootApplication which is a combination of @ComponentScan, @Configuration, and @EnableAutoConfiguration.

What is the opposite of :hover (on mouse leave)?

Just add a transition and the name of the animation on the class inicial, in your case, ul li a, just add a "transition" property and that is all you need

_x000D_
_x000D_
ul li {_x000D_
    display: inline;_x000D_
    margin-left: 20px;_x000D_
}_x000D_
_x000D_
ul li a {_x000D_
    color: #999;_x000D_
    transition: 1s;_x000D_
    -webkit-animation: item-hover-off 1s;_x000D_
    -moz-animation: item-hover-off 1s;_x000D_
    animation: item-hover-off 1s;_x000D_
}_x000D_
_x000D_
ul li a:hover {_x000D_
    color: black;_x000D_
    cursor: pointer;_x000D_
    -webkit-animation: item-hover 1s;_x000D_
    -moz-animation: item-hover 1s;_x000D_
    animation: item-hover 1s;_x000D_
}_x000D_
_x000D_
@keyframes item-hover {_x000D_
    from {_x000D_
      color: #999;_x000D_
      }_x000D_
    to {_x000D_
      color: black;_x000D_
      }_x000D_
}_x000D_
    _x000D_
@-moz-keyframes item-hover {_x000D_
    from {_x000D_
        color: #999;_x000D_
      }_x000D_
    to {_x000D_
        color: black;_x000D_
      }_x000D_
}_x000D_
    _x000D_
@-webkit-keyframes item-hover {_x000D_
    from {_x000D_
        color: #999;_x000D_
      }_x000D_
    to {_x000D_
        color: black;_x000D_
      }_x000D_
}_x000D_
_x000D_
@keyframes item-hover-off {_x000D_
    from {_x000D_
      color: black;_x000D_
      }_x000D_
    to {_x000D_
      color: #999;_x000D_
      }_x000D_
}_x000D_
    _x000D_
@-moz-keyframes item-hover-off {_x000D_
    from {_x000D_
        color: black;_x000D_
      }_x000D_
    to {_x000D_
        color: #999;_x000D_
      }_x000D_
}_x000D_
    _x000D_
@-webkit-keyframes item-hover-off {_x000D_
    from {_x000D_
        color: black;_x000D_
      }_x000D_
    to {_x000D_
        color: #999;_x000D_
      }_x000D_
}
_x000D_
<ul>_x000D_
    <li><a>Home</a></li>_x000D_
    <li><a>About</a></li>_x000D_
    <li><a>Contacts</a></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Android how to convert int to String?

Use this String.valueOf(value);

How do I force Kubernetes to re-pull an image?

The Image pull policy will always actually help to pull the image every single time a new pod is created (this can be in any case like scaling the replicas, or pod dies and new pod is created)

But if you want to update the image of the current running pod, deployment is the best way. It leaves you flawless update without any problem (mainly when you have a persistent volume attached to the pod) :)

JavaScript - Replace all commas in a string

The third parameter of String.prototype.replace() function was never defined as a standard, so most browsers simply do not implement it.

The best way is to use regular expression with g (global) flag.

_x000D_
_x000D_
var myStr = 'this,is,a,test';_x000D_
var newStr = myStr.replace(/,/g, '-');_x000D_
_x000D_
console.log( newStr );  // "this-is-a-test"
_x000D_
_x000D_
_x000D_

Still have issues?

It is important to note, that regular expressions use special characters that need to be escaped. As an example, if you need to escape a dot (.) character, you should use /\./ literal, as in the regex syntax a dot matches any single character (except line terminators).

_x000D_
_x000D_
var myStr = 'this.is.a.test';_x000D_
var newStr = myStr.replace(/\./g, '-');_x000D_
_x000D_
console.log( newStr );  // "this-is-a-test"
_x000D_
_x000D_
_x000D_

If you need to pass a variable as a replacement string, instead of using regex literal you may create RegExp object and pass a string as the first argument of the constructor. The normal string escape rules (preceding special characters with \ when included in a string) will be necessary.

_x000D_
_x000D_
var myStr = 'this.is.a.test';_x000D_
var reStr = '\\.';_x000D_
var newStr = myStr.replace(new RegExp(reStr, 'g'), '-');_x000D_
_x000D_
console.log( newStr );  // "this-is-a-test"
_x000D_
_x000D_
_x000D_

Callback functions in C++

There is also the C way of doing callbacks: function pointers

//Define a type for the callback signature,
//it is not necessary, but makes life easier

//Function pointer called CallbackType that takes a float
//and returns an int
typedef int (*CallbackType)(float);  


void DoWork(CallbackType callback)
{
  float variable = 0.0f;

  //Do calculations

  //Call the callback with the variable, and retrieve the
  //result
  int result = callback(variable);

  //Do something with the result
}

int SomeCallback(float variable)
{
  int result;

  //Interpret variable

  return result;
}

int main(int argc, char ** argv)
{
  //Pass in SomeCallback to the DoWork
  DoWork(&SomeCallback);
}

Now if you want to pass in class methods as callbacks, the declarations to those function pointers have more complex declarations, example:

//Declaration:
typedef int (ClassName::*CallbackType)(float);

//This method performs work using an object instance
void DoWorkObject(CallbackType callback)
{
  //Class instance to invoke it through
  ClassName objectInstance;

  //Invocation
  int result = (objectInstance.*callback)(1.0f);
}

//This method performs work using an object pointer
void DoWorkPointer(CallbackType callback)
{
  //Class pointer to invoke it through
  ClassName * pointerInstance;

  //Invocation
  int result = (pointerInstance->*callback)(1.0f);
}

int main(int argc, char ** argv)
{
  //Pass in SomeCallback to the DoWork
  DoWorkObject(&ClassName::Method);
  DoWorkPointer(&ClassName::Method);
}

Is there a minlength validation attribute in HTML5?

If desired to make this behavior, always show a small prefix on the input field or the user can't erase a prefix:

   // prefix="prefix_text"
   // If the user changes the prefix, restore the input with the prefix:
   if(document.getElementById('myInput').value.substring(0,prefix.length).localeCompare(prefix))
       document.getElementById('myInput').value = prefix;

java: How can I do dynamic casting of a variable from one type to another?

Don't do this. Just have a properly parameterized constructor instead. The set and types of the connection parameters are fixed anyway, so there is no point in doing this all dynamically.

Border around tr element doesn't show?

Add this to the stylesheet:

table {
  border-collapse: collapse;
}

JSFiddle.

The reason why it behaves this way is actually described pretty well in the specification:

There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.

... and later, for collapse setting:

In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.

How do you store Java objects in HttpSession?

Add it to the session, not to the request.

HttpSession session = request.getSession();
session.setAttribute("object", object);

Also, don't use scriptlets in the JSP. Use EL instead; to access object all you need is ${object}.

A primary feature of JSP technology version 2.0 is its support for an expression language (EL). An expression language makes it possible to easily access application data stored in JavaBeans components. For example, the JSP expression language allows a page author to access a bean using simple syntax such as ${name} for a simple variable or ${name.foo.bar} for a nested property.

How to programmatically set style attribute in a view

At runtime, you know what style you want your button to have. So beforehand, in xml in the layout folder, you can have all ready to go buttons with the styles you need. So in the layout folder, you might have a file named: button_style_1.xml. The contents of that file might look like:

<?xml version="1.0" encoding="utf-8"?>
<Button
    android:id="@+id/styleOneButton"
    style="@style/FirstStyle" />

If you are working with fragments, then in onCreateView you inflate that button, like:

Button firstStyleBtn = (Button) inflater.inflate(R.layout.button_style_1, container, false);

where container is the ViewGroup container associated with the onCreateView method you override when creating your fragment.

Need two more such buttons? You create them like this:

Button secondFirstStyleBtn = (Button) inflater.inflate(R.layout.button_style_1, container, false);
Button thirdFirstStyleBtn = (Button) inflater.inflate(R.layout.button_style_1, container, false);

You can customize those buttons:

secondFirstStyleBtn.setText("My Second");
thirdFirstStyleBtn.setText("My Third");

Then you add your customized, stylized buttons to the layout container you also inflated in the onCreateView method:

_stylizedButtonsContainer = (LinearLayout) rootView.findViewById(R.id.stylizedButtonsContainer);

_stylizedButtonsContainer.addView(firstStyleBtn);
_stylizedButtonsContainer.addView(secondFirstStyleBtn);
_stylizedButtonsContainer.addView(thirdFirstStyleBtn);

And that's how you can dynamically work with stylized buttons.

Modify request parameter with servlet filter

You can use Regular Expression for Sanitization. Inside filter before calling chain.doFilter(request, response) method, call this code. Here is Sample Code:

for (Enumeration en = request.getParameterNames(); en.hasMoreElements(); ) {
String name = (String)en.nextElement();
String values[] = request.getParameterValues(name);
int n = values.length;
    for(int i=0; i < n; i++) {
     values[i] = values[i].replaceAll("[^\\dA-Za-z ]","").replaceAll("\\s+","+").trim();   
    }
}

Wampserver icon not going green fully, mysql services not starting up?

For me, adding innodb_force_recovery=3 to my.ini solved the issue

Another option is removing ibdata files and all ib_logfile from the data directory , as explained in MySQL docs here. However this will cause any innoDB tables not to work(because the some information stored in ibdata1)

Inline CSS styles in React: how to implement a:hover?

The simple way is using ternary operator

var Link = React.createClass({
  getInitialState: function(){
    return {hover: false}
  },
  toggleHover: function(){
    this.setState({hover: !this.state.hover})
  },
  render: function() {
    var linkStyle;
    if (this.state.hover) {
      linkStyle = {backgroundColor: 'red'}
    } else {
      linkStyle = {backgroundColor: 'blue'}
    }
    return(
      <div>
        <a style={this.state.hover ? {"backgroundColor": 'red'}: {"backgroundColor": 'blue'}} onMouseEnter={this.toggleHover} onMouseLeave={this.toggleHover}>Link</a>
      </div>
    )
  }

Get Hard disk serial Number

I have used the following method in a project and it's working successfully.

private string identifier(string wmiClass, string wmiProperty)
//Return a hardware identifier
{
    string result = "";
    System.Management.ManagementClass mc = new System.Management.ManagementClass(wmiClass);
    System.Management.ManagementObjectCollection moc = mc.GetInstances();
    foreach (System.Management.ManagementObject mo in moc)
    {
        //Only get the first one
        if (result == "")
        {
            try
            {
                result = mo[wmiProperty].ToString();
                break;
            }
            catch
            {
            }
        }
    }
    return result;
}

you can call the above method as mentioned below,

string modelNo = identifier("Win32_DiskDrive", "Model");
string manufatureID = identifier("Win32_DiskDrive", "Manufacturer");
string signature = identifier("Win32_DiskDrive", "Signature");
string totalHeads = identifier("Win32_DiskDrive", "TotalHeads");

If you need a unique identifier, use a combination of these IDs.

How to call a JavaScript function within an HTML body

Try to use createChild() method of DOM or insertRow() and insertCell() method of table object in script tag.

How do I format date in jQuery datetimepicker?

You can use the format option, as described in the documentation

$("#timePicker").datetimepicker({
  format: 'Y-m-d H:i'
});

How to change date format from DD/MM/YYYY or MM/DD/YYYY to YYYY-MM-DD?

String dt = Date.Now.ToString("yyyy-MM-dd");

Now you got this for dt, 2010-09-09

How to properly create composite primary keys - MYSQL

the syntax is CONSTRAINT constraint_name PRIMARY KEY(col1,col2,col3) for example ::

CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)

the above example will work if you are writting it while you are creating the table for example ::

CREATE TABLE person (
   P_Id int ,
   ............,
   ............,
   CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
);

to add this constraint to an existing table you need to follow the following syntax

ALTER TABLE table_name ADD CONSTRAINT constraint_name PRIMARY KEY (P_Id,LastName)

What does "var" mean in C#?

Did you ever hated to write such variable initializers?

XmlSerializer xmlSerializer = new XmlSerialzer(typeof(int))

So, starting with C# 3.0, you can replace it with

var xmlSerializer = new XmlSerialzer(typeof(int))

One notice: Type is resolved during compilation, so no problems with performance. But Compiler should be able to detect type during build step, so code like var xmlSerializer; won't compile at all.

data.frame rows to a list

I was working on this today for a data.frame (really a data.table) with millions of observations and 35 columns. My goal was to return a list of data.frames (data.tables) each with a single row. That is, I wanted to split each row into a separate data.frame and store these in a list.

Here are two methods I came up with that were roughly 3 times faster than split(dat, seq_len(nrow(dat))) for that data set. Below, I benchmark the three methods on a 7500 row, 5 column data set (iris repeated 50 times).

library(data.table)
library(microbenchmark)

microbenchmark(
split={dat1 <- split(dat, seq_len(nrow(dat)))},
setDF={dat2 <- lapply(seq_len(nrow(dat)),
                  function(i) setDF(lapply(dat, "[", i)))},
attrDT={dat3 <- lapply(seq_len(nrow(dat)),
           function(i) {
             tmp <- lapply(dat, "[", i)
             attr(tmp, "class") <- c("data.table", "data.frame")
             setDF(tmp)
           })},
datList = {datL <- lapply(seq_len(nrow(dat)),
                          function(i) lapply(dat, "[", i))},
times=20
) 

This returns

Unit: milliseconds
       expr      min       lq     mean   median        uq       max neval
      split 861.8126 889.1849 973.5294 943.2288 1041.7206 1250.6150    20
      setDF 459.0577 466.3432 511.2656 482.1943  500.6958  750.6635    20
     attrDT 399.1999 409.6316 461.6454 422.5436  490.5620  717.6355    20
    datList 192.1175 201.9896 241.4726 208.4535  246.4299  411.2097    20

While the differences are not as large as in my previous test, the straight setDF method is significantly faster at all levels of the distribution of runs with max(setDF) < min(split) and the attr method is typically more than twice as fast.

A fourth method is the extreme champion, which is a simple nested lapply, returning a nested list. This method exemplifies the cost of constructing a data.frame from a list. Moreover, all methods I tried with the data.frame function were roughly an order of magnitude slower than the data.table techniques.

data

dat <- vector("list", 50)
for(i in 1:50) dat[[i]] <- iris
dat <- setDF(rbindlist(dat))

Checking version of angular-cli that's installed?

You can use npm list -global to list all the component versions currently installed on your system.
For viewing specific lists at different levels use --depth.

e.g:

npm list -global --depth 0

How can I test a PDF document if it is PDF/A compliant?

The 3-Heights™ PDF Validator Online Tool provides good feedback for different PDF/A conformance levels and versions.

  • PDF/A1-a
  • PDF/A2-a
  • PDF/A2-b
  • PDF/A1-b
  • PDF/A2-u

C++ Error 'nullptr was not declared in this scope' in Eclipse IDE

Finally found out what to do. Added the -std=c++0x compiler argument under Project Properties -> C/C++ Build -> Settings -> GCC C++ Compiler -> Miscellaneous. It works now!

But how to add this flag by default for all C++ projects? Anybody?

How to dynamically add elements to String array?

You cant add add items in string array more than its size, i'll suggest you to use ArrayList you can add items dynamically at run time in arrayList if you feel any problem you can freely ask

Python - How to cut a string in Python?

string = 'http://www.domain.com/?s=some&two=20'
cut_string = string.split('&')
new_string = cut_string[0]
print(new_string)

Replace Multiple String Elements in C#

string input = "it's worth a lot of money, if you can find a buyer.";
for (dynamic i = 0, repl = new string[,] { { "'", "''" }, { "money", "$" }, { "find", "locate" } }; i < repl.Length / 2; i++) {
    input = input.Replace(repl[i, 0], repl[i, 1]);
}

Keep SSH session alive

I wanted a one-time solution:

ssh -o ServerAliveInterval=60 [email protected]

Stored it in an alias:

alias sshprod='ssh -v -o ServerAliveInterval=60 [email protected]'

Now can connect like this:

me@MyMachine:~$ sshprod

Using "&times" word in html changes to ×

Use the &#215 code instead of &times Because JSF don't understand the &times; code.

Use: &#215 with ;

This link provides some additional information about the topic.

Is there a job scheduler library for node.js?

node-crontab allows you to edit system cron jobs from node.js. Using this library will allow you to run programs even after your main process termintates. Disclaimer: I'm the developer.

How can I create a progress bar in Excel VBA?

I liked the Status Bar from this page:

https://wellsr.com/vba/2017/excel/vba-application-statusbar-to-mark-progress/

I updated it so it could be used as a called procedure. No credit to me.


showStatus Current, Total, "  Process Running: "

Private Sub showStatus(Current As Integer, lastrow As Integer, Topic As String)
Dim NumberOfBars As Integer
Dim pctDone As Integer

NumberOfBars = 50
'Application.StatusBar = "[" & Space(NumberOfBars) & "]"


' Display and update Status Bar
    CurrentStatus = Int((Current / lastrow) * NumberOfBars)
    pctDone = Round(CurrentStatus / NumberOfBars * 100, 0)
    Application.StatusBar = Topic & " [" & String(CurrentStatus, "|") & _
                            Space(NumberOfBars - CurrentStatus) & "]" & _
                            " " & pctDone & "% Complete"

' Clear the Status Bar when you're done
'    If Current = Total Then Application.StatusBar = ""

End Sub

enter image description here

Running a script inside a docker container using shell script

I was searching an answer for this same question and found ENTRYPOINT in Dockerfile solution for me.

Dockerfile

...
ENTRYPOINT /my-script.sh ; /my-script2.sh ; /bin/bash

Now the scripts are executed when I start the container and I get the bash prompt after the scripts has been executed.

getting the table row values with jquery

Give something like this a try:

$(document).ready(function(){
    $("#thisTable tr").click(function(){
        $(this).find("td").each(function(){
            alert($(this).html());
        });
    });
});?

Here is a fiddle of the code in action: http://jsfiddle.net/YhZsW/

Rails - Could not find a JavaScript runtime?

I had this issue on a Windows machine and installing node.js was the solution that finally worked for me. This came after trying multiple other routes including trying to get 'therubyracer' working. Though the github for node.js suggests that installation on windows is still unstable, the website at http://nodejs.org/ had a Windows installer which worked perfectly.

Routing with multiple Get methods in ASP.NET Web API

First, add new route with action on top:

  config.Routes.MapHttpRoute(
           name: "ActionApi",
           routeTemplate: "api/{controller}/{action}/{id}",
           defaults: new { id = RouteParameter.Optional }
       );

  config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

Then use ActionName attribute to map:

[HttpGet]
public List<Customer> Get()
{
    //gets all customer
}

[ActionName("CurrentMonth")]
public List<Customer> GetCustomerByCurrentMonth()
{
    //gets some customer on some logic
}

[ActionName("customerById")]
public Customer GetCustomerById(string id)
{
    //gets a single customer using id
}

[ActionName("customerByUsername")]
public Customer GetCustomerByUsername(string username)
{
    //gets a single customer using username
}

Loop through Map in Groovy?

When using the for loop, the value of s is a Map.Entry element, meaning that you can get the key from s.key and the value from s.value

How to filter an array of objects based on values in an inner array with jq?

Here is another solution which uses any/2

map(select(any(.Names[]; contains("data"))|not)|.Id)[]

with the sample data and the -r option it produces

cb94e7a42732b598ad18a8f27454a886c1aa8bbba6167646d8f064cd86191e2b
a4b7e6f5752d8dcb906a5901f7ab82e403b9dff4eaaeebea767a04bac4aada19

How to square all the values in a vector in R?

This is another simple way:

sq_data <- data**2

How to convert an Image to base64 string in java?

The problem is that you are returning the toString() of the call to Base64.encodeBase64(bytes) which returns a byte array. So what you get in the end is the default string representation of a byte array, which corresponds to the output you get.

Instead, you should do:

encodedfile = new String(Base64.encodeBase64(bytes), "UTF-8");

How to set aliases in the Git Bash for Windows?

Follow below steps:

  1. Open the file .bashrc which is found in location C:\Users\USERNAME\.bashrc

    If file .bashrc not exist then create it using below steps:

    1. Open Command Prompt and goto C:\Users\USERNAME\.
    2. Type command notepad ~/.bashrc
      It generates the .bashrc file.
  2. Add below sample commands of WP CLI, Git, Grunt & PHPCS etc.


# ----------------------
# Git Command Aliases
# ----------------------
alias ga='git add'
alias gaa='git add .'
alias gaaa='git add --all'

# ----------------------
# WP CLI
# ----------------------
alias wpthl='wp theme list'
alias wppll='wp plugin list'

Now you can use the commands:

  • ga instead of git add .
  • wpthl instead of wp theme list

Eg. I have used wpthl for the WP CLI command wp theme list.

Yum@M MINGW64 /c/xampp/htdocs/dev.test
$ wpthl
+------------------------+----------+-----------+----------+
| name                   | status   | update    | version  |
+------------------------+----------+-----------+----------+
| twentyeleven           | inactive | none      | 2.8      |
| twentyfifteen          | inactive | none      | 2.0      |
| twentyfourteen         | inactive | none      | 2.2      |
| twentyseventeen        | inactive | available | 1.6      |
| twentysixteen          | inactive | none      | 1.5      |
| twentyten              | inactive | none      | 2.5      |
| twentythirteen         | inactive | none      | 2.4      |
| twentytwelve           | inactive | none      | 2.5      |

For more details read the article Keyboard shortcut/aliases for the WP CLI, Git, Grunt & PHPCS commands for windows

Password encryption at client side

For a similar situation I used this PKCS #5: Password-Based Cryptography Standard from RSA laboratories. You can avoid storing password, by substituting it with something that can be generated only from the password (in one sentence). There are some JavaScript implementations.

Equivalent of jQuery .hide() to set visibility: hidden

An even simpler way to do this is to use jQuery's toggleClass() method

CSS

.newClass{visibility: hidden}

HTML

<a href="#" class=trigger>Trigger Element </a>
<div class="hidden_element">Some Content</div>

JS

$(document).ready(function(){
    $(".trigger").click(function(){
        $(".hidden_element").toggleClass("newClass");
    });
});

Change Git repository directory location.

While the question involves Git for Windows, this seems to be the top result even when searching for Visual Studio Tools For Git (extension in VS 2012, native support in VS 2013).

Using the solutions above as a guide I determined that Visual Studio Git Tools makes moving repos (or even entire directory structure for all repos) locally very easy.

1) Close Visual Studio. 2) Move the Repo folder(s) to new location. 3) Open Visual Studio. Open Team Explorer. Switch to "Connect" view (plug icon at top). 3a) If Repos still show old path, click Refresh to force an update. 4) Repos that were moved locally should no longer be showing in "Local Git Repositories". 5) Click Add (not new or clone) and select the repo folder to add.

In step 5 you really are just providing a search path and the search automatically includes all subfolders. If you have multiple repos organized under a single root (independent repos just having the same parent folder) then selecting the parent will include all repos found below that.

Example: E:\Repos\RepoA E:\Repos\RepoB E:\Repos\RepoC

In Visual Studio Team Explorer [Add] > "E:\Repos\" > [Add] will return all three to the Local Repositories.

JavaScript: Difference between .forEach() and .map()

forEach() :

return value : undefined

originalArray : not modified after the method call

newArray is not created after the end of method call.

map() :

return value : new Array populated with the results of calling a provided function on every element in the calling array

originalArray : not modified after the method call

newArray is created after the end of method call.

Since map builds a new array, using it when you aren't using the
returned array is an anti-pattern; use forEach or for-of instead.

Import SQL file by command line in Windows 7

Try like this:

I think you need to use the full path at the command line, something like this, perhaps:

C:\xampp\mysql\bin\mysql -u {username} -p {databasename} < file_name.sql

Refer this link also:

http://www.ryantetek.com/2011/09/importing-large-sql-files-through-command-line-when-using-phpmyadminxampp/

How to delete all data from solr and hbase

I've used this request to delete all my records but sometimes it's necessary to commit this.

For that, add &commit=true to your request :

http://host:port/solr/core/update?stream.body=<delete><query>*:*</query></delete>&commit=true

Close Current Tab

You can only close windows/tabs that you create yourself. That is, you cannot programmatically close a window/tab that the user creates.

For example, if you create a window with window.open() you can close it with window.close().

How to replace multiple patterns at once with sed?

Here is an awk based on oogas sed

echo 'abbc' | awk '{gsub(/ab/,"xy");gsub(/bc/,"ab");gsub(/xy/,"bc")}1'
bcab

Scanner vs. StringTokenizer vs. String.Split

They're essentially horses for courses.

  • Scanner is designed for cases where you need to parse a string, pulling out data of different types. It's very flexible, but arguably doesn't give you the simplest API for simply getting an array of strings delimited by a particular expression.
  • String.split() and Pattern.split() give you an easy syntax for doing the latter, but that's essentially all that they do. If you want to parse the resulting strings, or change the delimiter halfway through depending on a particular token, they won't help you with that.
  • StringTokenizer is even more restrictive than String.split(), and also a bit fiddlier to use. It is essentially designed for pulling out tokens delimited by fixed substrings. Because of this restriction, it's about twice as fast as String.split(). (See my comparison of String.split() and StringTokenizer.) It also predates the regular expressions API, of which String.split() is a part.

You'll note from my timings that String.split() can still tokenize thousands of strings in a few milliseconds on a typical machine. In addition, it has the advantage over StringTokenizer that it gives you the output as a string array, which is usually what you want. Using an Enumeration, as provided by StringTokenizer, is too "syntactically fussy" most of the time. From this point of view, StringTokenizer is a bit of a waste of space nowadays, and you may as well just use String.split().

How line ending conversions work with git core.autocrlf between different operating systems

The best explanation of how core.autocrlf works is found on the gitattributes man page, in the text attribute section.

This is how core.autocrlf appears to work currently (or at least since v1.7.2 from what I am aware):

  • core.autocrlf = true
  1. Text files checked-out from the repository that have only LF characters are normalized to CRLF in your working tree; files that contain CRLF in the repository will not be touched
  2. Text files that have only LF characters in the repository, are normalized from CRLF to LF when committed back to the repository. Files that contain CRLF in the repository will be committed untouched.
  • core.autocrlf = input
  1. Text files checked-out from the repository will keep original EOL characters in your working tree.
  2. Text files in your working tree with CRLF characters are normalized to LF when committed back to the repository.
  • core.autocrlf = false
  1. core.eol dictates EOL characters in the text files of your working tree.
  2. core.eol = native by default, which means Windows EOLs are CRLF and *nix EOLs are LF in working trees.
  3. Repository gitattributes settings determines EOL character normalization for commits to the repository (default is normalization to LF characters).

I've only just recently researched this issue and I also find the situation to be very convoluted. The core.eol setting definitely helped clarify how EOL characters are handled by git.

Altering a column: null to not null

I had the same problem, but the field used to default to null, and now I want to default it to 0. That required adding one more line after mdb's solution:

ALTER TABLE [Table] ADD CONSTRAINT [Constraint] DEFAULT 0 FOR [Column];

How to achieve ripple animation using support library?

sometimes will b usable this line on any layout or components.

 android:background="?attr/selectableItemBackground"

Like as.

 <RelativeLayout
                android:id="@+id/relative_ticket_checkin"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="?attr/selectableItemBackground">

Java: Get first item from a collection

You can do a casting. For example, if exists one method with this definition, and you know that this method is returning a List:

Collection<String> getStrings();

And after invoke it, you need the first element, you can do it like this:

List<String> listString = (List) getStrings();
String firstElement = (listString.isEmpty() ? null : listString.get(0));

How to download a file from my server using SSH (using PuTTY on Windows)

There's no way to initiate a file transfer back to/from local Windows from a SSH session opened in PuTTY window.

Though PuTTY supports connection-sharing.

While you still need to run a compatible file transfer client (pscp or psftp), no new login is required, it automatically (if enabled) makes use of an existing PuTTY session.

To enable the sharing see:
Sharing an SSH connection between PuTTY tools.


Even without connection-sharing, you can still use the psftp or pscp from Windows command line.

See How to use PSCP to copy file from Unix machine to Windows machine ...?

Note that the scp is OpenSSH program. It's primarily *nix program, but you can run it via Windows Subsystem for Linux or get a Windows build from Win32-OpenSSH (it is already built-in in the latest versions of Windows 10).


If you really want to download the files to a local desktop, you have to specify a target path as %USERPROFILE%\Desktop (what typically resolves to a path like C:\Users\username\Desktop).


Alternative way is to use WinSCP, a GUI SFTP/SCP client. While you browse the remote site, you can anytime open SSH terminal to the same site using Open in PuTTY command.
See Opening Session in PuTTY.

With an additional setup, you can even make PuTTY automatically navigate to the same directory you are browsing with WinSCP.
See Opening PuTTY in the same directory.

(I'm the author of WinSCP)

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

Your strings are JSON formatted, so you will need to parse it into a object. For that you can use JSON.NET.

Here is an example on how to parse a JSON string into a dynamic object:

string source = "{\r\n   \"id\": \"100000280905615\", \r\n \"name\": \"Jerard Jones\",  \r\n   \"first_name\": \"Jerard\", \r\n   \"last_name\": \"Jones\", \r\n   \"link\": \"https://www.facebook.com/Jerard.Jones\", \r\n   \"username\": \"Jerard.Jones\", \r\n   \"gender\": \"female\", \r\n   \"locale\": \"en_US\"\r\n}";
dynamic data = JObject.Parse(source);
Console.WriteLine(data.id);
Console.WriteLine(data.first_name);
Console.WriteLine(data.last_name);
Console.WriteLine(data.gender);
Console.WriteLine(data.locale);

Happy coding!

How to use MySQLdb with Python and Django in OSX 10.6?

pip install mysql-python

raised an error:

EnvironmentError: mysql_config not found

sudo apt-get install python-mysqldb

fixed the problem.

How to do an Integer.parseInt() for a decimal number?

suppose we take a integer in string.

String s="100"; int i=Integer.parseInt(s); or int i=Integer.valueOf(s);

but in your question the number you are trying to do the change is the whole number

String s="10.00";

double d=Double.parseDouble(s);

int i=(int)d;

This way you get the answer of the value which you are trying to get it.

Correct way to initialize empty slice

The two alternative you gave are semantically identical, but using make([]int, 0) will result in an internal call to runtime.makeslice (Go 1.14).

You also have the option to leave it with a nil value:

var myslice []int

As written in the Golang.org blog:

a nil slice is functionally equivalent to a zero-length slice, even though it points to nothing. It has length zero and can be appended to, with allocation.

A nil slice will however json.Marshal() into "null" whereas an empty slice will marshal into "[]", as pointed out by @farwayer.

None of the above options will cause any allocation, as pointed out by @ArmanOrdookhani.

Calling virtual functions inside constructors

Calling a polymorphic function from a constructor is a recipe for disaster in most OO languages. Different languages will perform differently when this situation is encountered.

The basic problem is that in all languages the Base type(s) must be constructed previous to the Derived type. Now, the problem is what does it mean to call a polymorphic method from the constructor. What do you expect it to behave like? There are two approaches: call the method at the Base level (C++ style) or call the polymorphic method on an unconstructed object at the bottom of the hierarchy (Java way).

In C++ the Base class will build its version of the virtual method table prior to entering its own construction. At this point a call to the virtual method will end up calling the Base version of the method or producing a pure virtual method called in case it has no implementation at that level of the hierarchy. After the Base has been fully constructed, the compiler will start building the Derived class, and it will override the method pointers to point to the implementations in the next level of the hierarchy.

class Base {
public:
   Base() { f(); }
   virtual void f() { std::cout << "Base" << std::endl; } 
};
class Derived : public Base
{
public:
   Derived() : Base() {}
   virtual void f() { std::cout << "Derived" << std::endl; }
};
int main() {
   Derived d;
}
// outputs: "Base" as the vtable still points to Base::f() when Base::Base() is run

In Java, the compiler will build the virtual table equivalent at the very first step of construction, prior to entering the Base constructor or Derived constructor. The implications are different (and to my likings more dangerous). If the base class constructor calls a method that is overriden in the derived class the call will actually be handled at the derived level calling a method on an unconstructed object, yielding unexpected results. All attributes of the derived class that are initialized inside the constructor block are yet uninitialized, including 'final' attributes. Elements that have a default value defined at the class level will have that value.

public class Base {
   public Base() { polymorphic(); }
   public void polymorphic() { 
      System.out.println( "Base" );
   }
}
public class Derived extends Base
{
   final int x;
   public Derived( int value ) {
      x = value;
      polymorphic();
   }
   public void polymorphic() {
      System.out.println( "Derived: " + x ); 
   }
   public static void main( String args[] ) {
      Derived d = new Derived( 5 );
   }
}
// outputs: Derived 0
//          Derived 5
// ... so much for final attributes never changing :P

As you see, calling a polymorphic (virtual in C++ terminology) methods is a common source of errors. In C++, at least you have the guarantee that it will never call a method on a yet unconstructed object...

Linq Select Group By

This will give you sequence of anonymous objects, containing date string and two properties with average price:

var query = from p in PriceLogList
            group p by p.LogDateTime.ToString("MMM yyyy") into g
            select new { 
               LogDate = g.Key,
               AvgGoldPrice = (int)g.Average(x => x.GoldPrice), 
               AvgSilverPrice = (int)g.Average(x => x.SilverPrice)
            };

If you need to get list of PriceLog objects:

var query = from p in PriceLogList
            group p by p.LogDateTime.ToString("MMM yyyy") into g
            select new PriceLog { 
               LogDateTime = DateTime.Parse(g.Key),
               GoldPrice = (int)g.Average(x => x.GoldPrice), 
               SilverPrice = (int)g.Average(x => x.SilverPrice)
            };

How to detect browser using angularjs?

Not sure why you specify that it has to be within Angular. It's easily accomplished through JavaScript. Look at the navigator object.

Just open up your console and inspect navigator. It seems what you're specifically looking for is .userAgent or .appVersion.

I don't have IE9 installed, but you could try this following code

//Detect if IE 9
if(navigator.appVersion.indexOf("MSIE 9.")!=-1)

Bitbucket git credentials if signed up with Google

you don't have a bitbucket password because you log with google, but you can "reset" the password here https://bitbucket.org/account/password/reset/

you will receive an email to setup a new password and that's it.

How to delete Certain Characters in a excel 2010 cell

Replace [ with nothing, then ] with nothing.

How to sort by Date with DataTables jquery plugin?

Click on the "show details" link under Date (dd/mm/YYY), then you can copy and paste that plugin code provided there


Update: I think you can just switch the order of the array, like so:

jQuery.fn.dataTableExt.oSort['us_date-asc']  = function(a,b) {
    var usDatea = a.split('/');
    var usDateb = b.split('/');

    var x = (usDatea[2] + usDatea[0] + usDatea[1]) * 1;
    var y = (usDateb[2] + usDateb[0] + usDateb[1]) * 1;

    return ((x < y) ? -1 : ((x > y) ?  1 : 0));
};

jQuery.fn.dataTableExt.oSort['us_date-desc'] = function(a,b) {
    var usDatea = a.split('/');
    var usDateb = b.split('/');

    var x = (usDatea[2] + usDatea[0] + usDatea[1]) * 1;
    var y = (usDateb[2] + usDateb[0] + usDateb[1]) * 1;

    return ((x < y) ? 1 : ((x > y) ?  -1 : 0));
};

All I did was switch the __date_[1] (day) and __date_[0] (month), and replaced uk with us so you won't get confused. I think that should take care of it for you.


Update #2: You should be able to just use the date object for comparison. Try this:

jQuery.fn.dataTableExt.oSort['us_date-asc']  = function(a,b) {
 var x = new Date(a),
     y = new Date(b);
 return ((x < y) ? -1 : ((x > y) ?  1 : 0));
};

jQuery.fn.dataTableExt.oSort['us_date-desc'] = function(a,b) {
 var x = new Date(a),
     y = new Date(b);
 return ((x < y) ? 1 : ((x > y) ?  -1 : 0));
};

Shared-memory objects in multiprocessing

I run into the same problem and wrote a little shared-memory utility class to work around it.

I'm using multiprocessing.RawArray (lockfree), and also the access to the arrays is not synchronized at all (lockfree), be careful not to shoot your own feet.

With the solution I get speedups by a factor of approx 3 on a quad-core i7.

Here's the code: Feel free to use and improve it, and please report back any bugs.

'''
Created on 14.05.2013

@author: martin
'''

import multiprocessing
import ctypes
import numpy as np

class SharedNumpyMemManagerError(Exception):
    pass

'''
Singleton Pattern
'''
class SharedNumpyMemManager:    

    _initSize = 1024

    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(SharedNumpyMemManager, cls).__new__(
                                cls, *args, **kwargs)
        return cls._instance        

    def __init__(self):
        self.lock = multiprocessing.Lock()
        self.cur = 0
        self.cnt = 0
        self.shared_arrays = [None] * SharedNumpyMemManager._initSize

    def __createArray(self, dimensions, ctype=ctypes.c_double):

        self.lock.acquire()

        # double size if necessary
        if (self.cnt >= len(self.shared_arrays)):
            self.shared_arrays = self.shared_arrays + [None] * len(self.shared_arrays)

        # next handle
        self.__getNextFreeHdl()        

        # create array in shared memory segment
        shared_array_base = multiprocessing.RawArray(ctype, np.prod(dimensions))

        # convert to numpy array vie ctypeslib
        self.shared_arrays[self.cur] = np.ctypeslib.as_array(shared_array_base)

        # do a reshape for correct dimensions            
        # Returns a masked array containing the same data, but with a new shape.
        # The result is a view on the original array
        self.shared_arrays[self.cur] = self.shared_arrays[self.cnt].reshape(dimensions)

        # update cnt
        self.cnt += 1

        self.lock.release()

        # return handle to the shared memory numpy array
        return self.cur

    def __getNextFreeHdl(self):
        orgCur = self.cur
        while self.shared_arrays[self.cur] is not None:
            self.cur = (self.cur + 1) % len(self.shared_arrays)
            if orgCur == self.cur:
                raise SharedNumpyMemManagerError('Max Number of Shared Numpy Arrays Exceeded!')

    def __freeArray(self, hdl):
        self.lock.acquire()
        # set reference to None
        if self.shared_arrays[hdl] is not None: # consider multiple calls to free
            self.shared_arrays[hdl] = None
            self.cnt -= 1
        self.lock.release()

    def __getArray(self, i):
        return self.shared_arrays[i]

    @staticmethod
    def getInstance():
        if not SharedNumpyMemManager._instance:
            SharedNumpyMemManager._instance = SharedNumpyMemManager()
        return SharedNumpyMemManager._instance

    @staticmethod
    def createArray(*args, **kwargs):
        return SharedNumpyMemManager.getInstance().__createArray(*args, **kwargs)

    @staticmethod
    def getArray(*args, **kwargs):
        return SharedNumpyMemManager.getInstance().__getArray(*args, **kwargs)

    @staticmethod    
    def freeArray(*args, **kwargs):
        return SharedNumpyMemManager.getInstance().__freeArray(*args, **kwargs)

# Init Singleton on module load
SharedNumpyMemManager.getInstance()

if __name__ == '__main__':

    import timeit

    N_PROC = 8
    INNER_LOOP = 10000
    N = 1000

    def propagate(t):
        i, shm_hdl, evidence = t
        a = SharedNumpyMemManager.getArray(shm_hdl)
        for j in range(INNER_LOOP):
            a[i] = i

    class Parallel_Dummy_PF:

        def __init__(self, N):
            self.N = N
            self.arrayHdl = SharedNumpyMemManager.createArray(self.N, ctype=ctypes.c_double)            
            self.pool = multiprocessing.Pool(processes=N_PROC)

        def update_par(self, evidence):
            self.pool.map(propagate, zip(range(self.N), [self.arrayHdl] * self.N, [evidence] * self.N))

        def update_seq(self, evidence):
            for i in range(self.N):
                propagate((i, self.arrayHdl, evidence))

        def getArray(self):
            return SharedNumpyMemManager.getArray(self.arrayHdl)

    def parallelExec():
        pf = Parallel_Dummy_PF(N)
        print(pf.getArray())
        pf.update_par(5)
        print(pf.getArray())

    def sequentialExec():
        pf = Parallel_Dummy_PF(N)
        print(pf.getArray())
        pf.update_seq(5)
        print(pf.getArray())

    t1 = timeit.Timer("sequentialExec()", "from __main__ import sequentialExec")
    t2 = timeit.Timer("parallelExec()", "from __main__ import parallelExec")

    print("Sequential: ", t1.timeit(number=1))    
    print("Parallel: ", t2.timeit(number=1))

Hide password with "•••••••" in a textField

In XCode 6.3.1, if you use a NSTextField you will not see the checkbox for secure.

Instead of using NSTextField use NSSecureTextField

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSSecureTextField_Class/index.html

I'm guessing this is a Swift/Objective-C change since there is now a class for secure text fields. In the above link it says Available in OS X v10.0 and later. If you know more about when/why/what versions of Swift/Objective-C, XCode, or OS X this

Logical Operators, || or OR?

They are used for different purposes and in fact have different operator precedences. The && and || operators are intended for Boolean conditions, whereas and and or are intended for control flow.

For example, the following is a Boolean condition:

if ($foo == $bar && $baz != $quxx) {

This differs from control flow:

doSomething() or die();

Autocomplete syntax for HTML or PHP in Notepad++. Not auto-close, autocompelete

In Notepad++ v. 6.4.1 is this possibility in:Settings->Preferences->Auto-Completion and there check Enable auto-completion on each input.

For auto-complete in code press Ctrl + Enter.

AWS - Disconnected : No supported authentication methods available (server sent :publickey)

There is another cause that would impact a previously working system. I re-created my instances (using AWS OpsWorks) to use Amazon Linux instead of Ubuntu, and received this error after doing so. Switching to use "ec2-user" as the username instead of "ubuntu" resolved the issue for me.

How does the keyword "use" work in PHP and can I import classes with it?

The issue is most likely you will need to use an auto loader that will take the name of the class (break by '\' in this case) and map it to a directory structure.

You can check out this article on the autoloading functionality of PHP. There are many implementations of this type of functionality in frameworks already.

I've actually implemented one before. Here's a link.

Wrapping long text without white space inside of a div

You can't wrap that text as it's unbroken without any spaces. You need a JavaScript or server side solution which splits the string after a few characters.

EDIT

You need to add this property in CSS.

word-wrap: break-word;

How to find which columns contain any NaN value in Pandas dataframe

You can use df.isnull().sum(). It shows all columns and the total NaNs of each feature.

How can I generate a 6 digit unique number?

Here's another one:

substr(number_format(time() * rand(),0,'',''),0,6);

How different is Objective-C from C++?

As others have said, Objective-C is much more dynamic in terms of how it thinks of objects vs. C++'s fairly static realm.

Objective-C, being in the Smalltalk lineage of object-oriented languages, has a concept of objects that is very similar to that of Java, Python, and other "standard", non-C++ object-oriented languages. Lots of dynamic dispatch, no operator overloading, send messages around.

C++ is its own weird animal; it mostly skipped the Smalltalk portion of the family tree. In some ways, it has a good module system with support for inheritance that happens to be able to be used for object-oriented programming. Things are much more static (overridable methods are not the default, for example).

How to convert a PIL Image into a numpy array?

I am using Pillow 4.1.1 (the successor of PIL) in Python 3.5. The conversion between Pillow and numpy is straightforward.

from PIL import Image
import numpy as np
im = Image.open('1.jpg')
im2arr = np.array(im) # im2arr.shape: height x width x channel
arr2im = Image.fromarray(im2arr)

One thing that needs noticing is that Pillow-style im is column-major while numpy-style im2arr is row-major. However, the function Image.fromarray already takes this into consideration. That is, arr2im.size == im.size and arr2im.mode == im.mode in the above example.

We should take care of the HxWxC data format when processing the transformed numpy arrays, e.g. do the transform im2arr = np.rollaxis(im2arr, 2, 0) or im2arr = np.transpose(im2arr, (2, 0, 1)) into CxHxW format.

decompiling DEX into Java sourcecode

You might try JADX (https://bitbucket.org/mstrobel/procyon/wiki/Java%20Decompiler), this is a perfect tool for DEX decompilation.

And yes, it is also available online on (my :0)) new site: http://www.javadecompilers.com/apk/

What is the best way to add options to a select from a JavaScript object with jQuery?

I have made something like this, loading a dropdown item via Ajax. The response above is also acceptable, but it is always good to have as little DOM modification as as possible for better performance.

So rather than add each item inside a loop it is better to collect items within a loop and append it once it's completed.

$(data).each(function(){
    ... Collect items
})

Append it,

$('#select_id').append(items); 

or even better

$('#select_id').html(items);

Difference between SET autocommit=1 and START TRANSACTION in mysql (Have I missed something?)

If you want to use rollback, then use start transaction and otherwise forget all those things,

By default, MySQL automatically commits the changes to the database.

To force MySQL not to commit these changes automatically, execute following:

SET autocommit = 0;
//OR    
SET autocommit = OFF

To enable the autocommit mode explicitly:

SET autocommit = 1;
//OR    
SET autocommit = ON;

Get list of databases from SQL Server

SELECT [name] 
FROM master.dbo.sysdatabases 
WHERE dbid > 4 and [name] <> 'ReportServer' and [name] <> 'ReportServerTempDB'

This will work for both condition, Whether reporting is enabled or not

How can I wrap text in a label using WPF?

Often you cannot replace a Label with a TextBlock as you want to the use the Target property (which sets focus to the targeted control when using the keyboard e.g. ALT+C in the sample code below), as that's all a Label really offers over a TextBlock.

However, a Label uses a TextBlock to render text (if a string is placed in the Content property, which it typically is); therefore, you can add a style for TextBlock inside the Label like so:

<Label              
    Content="_Content Text:"
    Target="{Binding ElementName=MyTargetControl}">
    <Label.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="TextWrapping" Value="Wrap" />
        </Style>
    </Label.Resources>
 </Label>
 <CheckBox x:Name = "MyTargetControl" />

This way you get to keep the functionality of a Label whilst also being able to wrap the text.

Can I execute a function after setState is finished updating?

Making setState return a Promise

In addition to passing a callback to setState() method, you can wrap it around an async function and use the then() method -- which in some cases might produce a cleaner code:

(async () => new Promise(resolve => this.setState({dummy: true}), resolve)()
    .then(() => { console.log('state:', this.state) });

And here you can take this one more step ahead and make a reusable setState function that in my opinion is better than the above version:

const promiseState = async state =>
    new Promise(resolve => this.setState(state, resolve));

promiseState({...})
    .then(() => promiseState({...})
    .then(() => {
        ...  // other code
        return promiseState({...});
    })
    .then(() => {...});

This works fine in React 16.4, but I haven't tested it in earlier versions of React yet.

Also worth mentioning that keeping your callback code in componentDidUpdate method is a better practice in most -- probably all, cases.

Fatal error: Call to undefined function mysql_connect()

This Code Can Help You

<?php 

$servername = "localhost";
$username = "root";
$password = "";


$con = new mysqli($servername, $username, $password);

?>

But Change The "servername","username" and "password"

How to center a subview of UIView

I would use:

child.center = CGPointMake(parent.bounds.height / 2, parent.bounds.width / 2)

This is simple, short, and sweet. If you use @Hejazi's answer above and parent.center is set to anything other than (0,0) your subview will not be centered!

SQL Server - copy stored procedures from one db to another

use

select * from sys.procedures

to show all your procedures;

sp_helptext @objname = 'Procedure_name'

to get the code

and your creativity to build something to loop through them all and generate the export code :)

How to print out more than 20 items (documents) in MongoDB's shell?

I suggest you to have a ~/.mongorc.js file so you do not have to set the default size everytime.

 # execute in your terminal
 touch ~/.mongorc.js
 echo 'DBQuery.shellBatchSize = 100;' > ~/.mongorc.js
 # add one more line to always prettyprint the ouput
 echo 'DBQuery.prototype._prettyShell = true; ' >> ~/.mongorc.js

To know more about what else you can do, I suggest you to look at this article: http://mo.github.io/2017/01/22/mongo-db-tips-and-tricks.html

Better way to sort array in descending order

Yes, you can pass predicate to sort. That would be your reverse implementation.

android.app.Application cannot be cast to android.app.Activity

In my case, when I'm in an activity that extends from AppCompatActivity, it did not work(Activity) getApplicationContext (), I just putthis in its place.

How to send parameters with jquery $.get()

Try this:

$.ajax({
    type: 'get',
    url: 'manageproducts.do',
    data: 'option=1',
    success: function(data) {

        availableProductNames = data.split(",");

        alert(availableProductNames);

    }
});

Also You have a few errors in your sample code, not sure if that was causing the error or it was just a typo upon entering the question.

How to set the color of "placeholder" text?

Try this

_x000D_
_x000D_
input::-webkit-input-placeholder { /* WebKit browsers */_x000D_
    color:    #f51;_x000D_
}_x000D_
input:-moz-placeholder { /* Mozilla Firefox 4 to 18 */_x000D_
    color:    #f51;_x000D_
}_x000D_
input::-moz-placeholder { /* Mozilla Firefox 19+ */_x000D_
    color:    #f51;_x000D_
}_x000D_
input:-ms-input-placeholder { /* Internet Explorer 10+ */_x000D_
    color:    #f51;_x000D_
}
_x000D_
<input type="text" placeholder="Value" />
_x000D_
_x000D_
_x000D_

What is a "thread" (really)?

A thread is a set of (CPU)instructions which can be executed.

But in order to better understand the thread we have to have some knowledge about how the CPU and RAM works.

A computer follows instructions and manipulates data. RAM is the place where those instructions and data on which the CPU will operate on, are saved. Within the CPU some memory cells called registers exist. Those registers contain numbers on which the CPU performs simple mathematical operations. An example can be the following: “Add the number in register #3 to the number in register #1.”.

The collection of all operations a CPU can do is called instruction set. Each operation in the instruction set is assigned a number, so computer code is essentially a sequence of numbers representing CPU operations. These operations are stored as numbers in the RAM.

The CPU works in a never-ending loop, always fetching and executing an instruction from memory. At the core of this cycle is the PC register, or Program Counter. It's a special register that stores the memory address of the next instruction to be executed.

The CPU will:  

  1. Fetch the instruction at the memory address given by the PC,
  2. Increment the PC by 1,
  3. Execute the instruction,
  4. Go back to step 1.

The CPU can be instructed to write a new value to the PC, causing the execution to branch, or "jump" to somewhere else in the memory. And this branching can be conditional. For instance, a CPU instruction could say: "set PC to address #200 if register #1 equals zero". This allows computers to execute stuff like this:

if  x = 0
    compute_this()
else
    compute_that()

Resources taken from Computer Science Distilled were used.

How to execute an .SQL script file using c#

This works for me:

public void updatedatabase()
{

    SqlConnection conn = new SqlConnection("Data Source=" + txtserver.Text.Trim() + ";Initial Catalog=" + txtdatabase.Text.Trim() + ";User ID=" + txtuserid.Text.Trim() + ";Password=" + txtpwd.Text.Trim() + "");
    try
    {

        conn.Open();

        string script = File.ReadAllText(Server.MapPath("~/Script/DatingDemo.sql"));

        // split script on GO command
        IEnumerable<string> commandStrings = Regex.Split(script, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
        foreach (string commandString in commandStrings)
        {
            if (commandString.Trim() != "")
            {
                new SqlCommand(commandString, conn).ExecuteNonQuery();
            }
        }
        lblmsg.Text = "Database updated successfully.";

    }
    catch (SqlException er)
    {
        lblmsg.Text = er.Message;
        lblmsg.ForeColor = Color.Red;
    }
    finally
    {
        conn.Close();
    }
}

MSVCP140.dll missing

That's probably the C++ runtime library. Since it's a DLL it is not included in your program executable. Your friend can download those libraries from Microsoft.

How can I get the active screen dimensions?

in C# winforms I have got start point (for case when we have several monitor/diplay and one form is calling another one) with help of the following method:

private Point get_start_point()
    {
        return
            new Point(Screen.GetBounds(parent_class_with_form.ActiveForm).X,
                      Screen.GetBounds(parent_class_with_form.ActiveForm).Y
                      );
    }

How to check if an element is off-screen

  • Get the distance from the top of the given element
  • Add the height of the same given element. This will tell you the total number from the top of the screen to the end of the given element.
  • Then all you have to do is subtract that from total document height

    jQuery(function () {
        var documentHeight = jQuery(document).height();
        var element = jQuery('#you-element');
        var distanceFromBottom = documentHeight - (element.position().top + element.outerHeight(true));
        alert(distanceFromBottom)
    });
    

What is "not assignable to parameter of type never" error in typescript?

I was having same error In ReactJS statless function while using ReactJs Hook useState. I wanted to set state of an object array , so if I use the following way

const [items , setItems] = useState([]);

and update the state like this:

 const item = { id : new Date().getTime() , text : 'New Text' };
 setItems([ item , ...items ]);

I was getting error:

Argument of type '{ id: number; text: any }' is not assignable to parameter of type 'never'

but if do it like this,

const [items , setItems] = useState([{}]);

Error is gone but there is an item at 0 index which don't have any data(don't want that).

so the solution I found is:

const [items , setItems] = useState([] as any);

How do I find the index of a character in a string in Ruby?

str="abcdef"

str.index('c') #=> 2 #String matching approach
str=~/c/ #=> 2 #Regexp approach 
$~ #=> #<MatchData "c">

Hope it helps. :)

C# : 'is' keyword and checking for Not

The way you have it is fine but you could create a set of extension methods to make "a more elegant way to check for the 'NOT' instance."

public static bool Is<T>(this object myObject)
{
    return (myObject is T);
}

public static bool IsNot<T>(this object myObject)
{
    return !(myObject is T);
}

Then you could write:

if (child.IsNot<IContainer>())
{
    // child is not an IContainer
}

EditText, clear focus on touch outside

You've probably found the answer to this problem already but I've been looking on how to solve this and still can't really find exactly what I was looking for so I figured I'd post it here.

What I did was the following (this is very generalized, purpose is to give you an idea of how to proceed, copying and pasting all the code will not work O:D ):

First have the EditText and any other views you want in your program wrapped by a single view. In my case I used a LinearLayout to wrap everything.

<LinearLayout 
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/mainLinearLayout">
 <EditText
  android:id="@+id/editText"/>
 <ImageView
  android:id="@+id/imageView"/>
 <TextView
  android:id="@+id/textView"/>
 </LinearLayout>

Then in your code you have to set a Touch Listener to your main LinearLayout.

final EditText searchEditText = (EditText) findViewById(R.id.editText);
mainLinearLayout.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            if(searchEditText.isFocused()){
                if(event.getY() >= 72){
                    //Will only enter this if the EditText already has focus
                    //And if a touch event happens outside of the EditText
                    //Which in my case is at the top of my layout
                    //and 72 pixels long
                    searchEditText.clearFocus();
                    InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            Toast.makeText(getBaseContext(), "Clicked", Toast.LENGTH_SHORT).show();
            return false;
        }
    });

I hope this helps some people. Or at least helps them start solving their problem.

jQuery - checkbox enable/disable

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#InventoryMasterError').click(function(event) { //on click_x000D_
    if (this.checked) { // check select status_x000D_
      $('.checkerror').each(function() { //loop through each checkbox_x000D_
        $('#selecctall').attr('disabled', 'disabled');_x000D_
      });_x000D_
    } else {_x000D_
      $('.checkerror').each(function() { //loop through each checkbox_x000D_
        $('#selecctall').removeAttr('disabled', 'disabled');_x000D_
      });_x000D_
    }_x000D_
  });_x000D_
_x000D_
});_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#selecctall').click(function(event) { //on click_x000D_
    if (this.checked) { // check select status_x000D_
      $('.checkbox1').each(function() { //loop through each checkbox_x000D_
        $('#InventoryMasterError').attr('disabled', 'disabled');_x000D_
      });_x000D_
_x000D_
    } else {_x000D_
      $('.checkbox1').each(function() { //loop through each checkbox_x000D_
        $('#InventoryMasterError').removeAttr('disabled', 'disabled');_x000D_
      });_x000D_
    }_x000D_
  });_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="checkbox" id="selecctall" name="selecctall" value="All" />_x000D_
<input type="checkbox" name="data[InventoryMaster][error]" label="" value="error" id="InventoryMasterError" />_x000D_
<input type="checkbox" name="checkid[]" class="checkbox1" value="1" id="InventoryMasterId" />_x000D_
<input type="checkbox" name="checkid[]" class="checkbox1" value="2" id="InventoryMasterId" />
_x000D_
_x000D_
_x000D_

Remove an element from a Bash array

Here's a one-line solution with mapfile:

$ mapfile -d $'\0' -t arr < <(printf '%s\0' "${arr[@]}" | grep -Pzv "<regexp>")

Example:

$ arr=("Adam" "Bob" "Claire"$'\n'"Smith" "David" "Eve" "Fred")

$ echo "Size: ${#arr[*]} Contents: ${arr[*]}"

Size: 6 Contents: Adam Bob Claire
Smith David Eve Fred

$ mapfile -d $'\0' -t arr < <(printf '%s\0' "${arr[@]}" | grep -Pzv "^Claire\nSmith$")

$ echo "Size: ${#arr[*]} Contents: ${arr[*]}"

Size: 5 Contents: Adam Bob David Eve Fred

This method allows for great flexibility by modifying/exchanging the grep command and doesn't leave any empty strings in the array.

How do I find a default constraint using INFORMATION_SCHEMA?

WHILE EXISTS( 
    SELECT * FROM  sys.all_columns 
    INNER JOIN sys.tables ST  ON all_columns.object_id = ST.object_id
    INNER JOIN sys.schemas ON ST.schema_id = schemas.schema_id
    INNER JOIN sys.default_constraints ON all_columns.default_object_id = default_constraints.object_id
    WHERE 
    schemas.name = 'dbo'
    AND ST.name = 'MyTable'
)
BEGIN 
DECLARE @SQL NVARCHAR(MAX) = N'';

SET @SQL = (  SELECT TOP 1
     'ALTER TABLE ['+  schemas.name + '].[' + ST.name + '] DROP CONSTRAINT ' + default_constraints.name + ';'
   FROM 
      sys.all_columns

         INNER JOIN
      sys.tables ST
         ON all_columns.object_id = ST.object_id

         INNER JOIN 
      sys.schemas
         ON ST.schema_id = schemas.schema_id

         INNER JOIN
      sys.default_constraints
         ON all_columns.default_object_id = default_constraints.object_id

   WHERE 
         schemas.name = 'dbo'
      AND ST.name = 'MyTable'
      )
   PRINT @SQL
   EXECUTE sp_executesql @SQL 

   --End if Error 
   IF @@ERROR <> 0 
   BREAK
END 

MySQL: Selecting multiple fields into multiple variables in a stored procedure

==========Advise==========

@martin clayton Answer is correct, But this is an advise only.

Please avoid the use of ambiguous variable in the stored procedure.

Example :

SELECT Id, dateCreated
INTO id, datecreated
FROM products
WHERE pName = iName

The above example will cause an error (null value error)

Example give below is correct. I hope this make sense.

Example :

SELECT Id, dateCreated
INTO val_id, val_datecreated
FROM products
WHERE pName = iName

You can also make them unambiguous by referencing the table, like:

[ Credit : maganap ]

SELECT p.Id, p.dateCreated INTO id, datecreated FROM products p 
WHERE pName = iName

Where is svn.exe in my machine?

Recent versions of the TortoiseSVN package can install a discrete svn.exe in addition to the one linked into the GUI binary. It is located in the same bin directory where the main program is installed. (If you have already installed TortoiseSVN, then rerun the installer, select Modify, and select command line tools for installation.)

Highcharts - redraw() vs. new Highcharts.chart

@RobinL as mentioned in previous comments, you can use chart.series[n].setData(). First you need to make sure you’ve assigned a chart instance to the chart variable, that way it adopts all the properties and methods you need to access and manipulate the chart.

I’ve also used the second parameter of setData() and had it false, to prevent automatic rendering of the chart. This was because I have multiple data series, so I’ll rather update each of them, with render=false, and then running chart.redraw(). This multiplied performance (I’m having 10,000-100,000 data points and refreshing the data set every 50 milliseconds).

Android: long click on a button -> perform actions

I've done it before, I just used:

down.setOnLongClickListener(new OnLongClickListener() { 
        @Override
        public boolean onLongClick(View v) {
            // TODO Auto-generated method stub
            return true;
        }
    });

Per documentation:

public void setOnLongClickListener (View.OnLongClickListener l)

Since: API Level 1 Register a callback to be invoked when this view is clicked and held. If this view is not long clickable, it becomes long clickable.

Notice that it requires to return a boolean, this should work.

Is it possible to specify condition in Count()?

Note with PrestoDB SQL (from Facebook), there is a shortcut:

https://prestodb.io/docs/current/functions/aggregate.html

count_if(x) ? bigint

Returns the number of TRUE input values. This function is equivalent to count(CASE WHEN x THEN 1 END)

check if a key exists in a bucket in s3 using boto3

Assuming you just want to check if a key exists (instead of quietly over-writing it), do this check first:

import boto3

def key_exists(mykey, mybucket):
  s3_client = boto3.client('s3')
  response = s3_client.list_objects_v2(Bucket=mybucket, Prefix=mykey)
  if response:
      for obj in response['Contents']:
          if mykey == obj['Key']:
              return True
  return False

if key_exists('someprefix/myfile-abc123', 'my-bucket-name'):
    print("key exists")
else:
    print("safe to put new bucket object")
    # try:
    #     resp = s3_client.put_object(Body="Your string or file-like object",
    #                                 Bucket=mybucket,Key=mykey)
    # ...check resp success and ClientError exception for errors...

How to encrypt a large file in openssl using public key

Solution for safe and high secured encode anyone file in OpenSSL and command-line:

You should have ready some X.509 certificate for encrypt files in PEM format.

Encrypt file:

openssl smime -encrypt -binary -aes-256-cbc -in plainfile.zip -out encrypted.zip.enc -outform DER yourSslCertificate.pem

What is what:

  • smime - ssl command for S/MIME utility (smime(1))
  • -encrypt - chosen method for file process
  • -binary - use safe file process. Normally the input message is converted to "canonical" format as required by the S/MIME specification, this switch disable it. It is necessary for all binary files (like a images, sounds, ZIP archives).
  • -aes-256-cbc - chosen cipher AES in 256 bit for encryption (strong). If not specified 40 bit RC2 is used (very weak). (Supported ciphers)
  • -in plainfile.zip - input file name
  • -out encrypted.zip.enc - output file name
  • -outform DER - encode output file as binary. If is not specified, file is encoded by base64 and file size will be increased by 30%.
  • yourSslCertificate.pem - file name of your certificate's. That should be in PEM format.

That command can very effectively a strongly encrypt big files regardless of its format.
Known issue: Something wrong happens when you try encrypt huge file (>600MB). No error thrown, but encrypted file will be corrupted. Always verify each file! (or use PGP - that has bigger support for files encryption with public key)

Decrypt file:

openssl smime -decrypt -binary -in encrypted.zip.enc -inform DER -out decrypted.zip -inkey private.key -passin pass:your_password

What is what:

  • -inform DER - same as -outform above
  • -inkey private.key - file name of your private key. That should be in PEM format and can be encrypted by password.
  • -passin pass:your_password - your password for private key encrypt. (passphrase arguments)

Highlight Bash/shell code in Markdown files

If I need only to highlight the first word as a command, I often use properties:

```properties
npm run build
```  

I obtain something like:

npm run build

Postgresql GROUP_CONCAT equivalent?

Hope below Oracle query will work.

Select First_column,LISTAGG(second_column,',') 
    WITHIN GROUP (ORDER BY second_column) as Sec_column, 
    LISTAGG(third_column,',') 
    WITHIN GROUP (ORDER BY second_column) as thrd_column 
FROM tablename 
GROUP BY first_column

Strings in C, how to get subString

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

int main ()
{
        char someString[]="abcdedgh";
        char otherString[]="00000";
        memcpy (otherString, someString, 5);
        printf ("someString: %s\notherString: %s\n", someString, otherString);
        return 0;
}

You will not need stdio.h if you don't use the printf statement and putting constants in all but the smallest programs is bad form and should be avoided.

Access a function variable outside the function without using "global"

You could do something along these lines (which worked in both Python v2.7.17 and v3.8.1 when I tested it/them):

def hi():
    # other code...
    hi.bye = 42  # Create function attribute.
    sigh = 10

hi()
print(hi.bye)  # -> 42

Functions are objects in Python and can have arbitrary attributes assigned to them.

If you're going to be doing this kind of thing often, you could implement something more generic by creating a function decorator that adds a this argument to each call to the decorated function.

This additional argument will give functions a way to reference themselves without needing to explicitly embed (hardcode) their name into the rest of the definition and is similar to the instance argument that class methods automatically receive as their first argument which is usually named self — I picked something different to avoid confusion, but like the self argument, it can be named whatever you wish.

Here's an example of that approach:

def add_this_arg(func):
    def wrapped(*args, **kwargs):
        return func(wrapped, *args, **kwargs)
    return wrapped

@add_this_arg
def hi(this, that):
    # other code...
    this.bye = 2 * that  # Create function attribute.
    sigh = 10

hi(21)
print(hi.bye)  # -> 42

Note

This doesn't work for class methods. Just use the self argument already passed being passed to instead of the method name. You can reference class-level attributes through type(self). See Function's attributes when in a class.

console.log(result) returns [object Object]. How do I get result.name?

Use console.log(JSON.stringify(result)) to get the JSON in a string format.

EDIT: If your intention is to get the id and other properties from the result object and you want to see it console to know if its there then you can check with hasOwnProperty and access the property if it does exist:

var obj = {id : "007", name : "James Bond"};
console.log(obj);                    // Object { id: "007", name: "James Bond" }
console.log(JSON.stringify(obj));    //{"id":"007","name":"James Bond"}
if (obj.hasOwnProperty("id")){
    console.log(obj.id);             //007
}

How to get Real IP from Visitor?

This works for Windows and Linux! It doesn't matter if it's localhost or online..

    function getIP() {
    $ip = $_SERVER['SERVER_ADDR'];

    if (PHP_OS == 'WINNT'){
        $ip = getHostByName(getHostName());
    }

    if (PHP_OS == 'Linux'){
        $command="/sbin/ifconfig";
        exec($command, $output);
        // var_dump($output);
        $pattern = '/inet addr:?([^ ]+)/';

        $ip = array();
        foreach ($output as $key => $subject) {
            $result = preg_match_all($pattern, $subject, $subpattern);
            if ($result == 1) {
                if ($subpattern[1][0] != "127.0.0.1")
                $ip = $subpattern[1][0];
            }
        //var_dump($subpattern);
        }
    }
    return $ip;
}

Converts scss to css

You can use sass /sassFile.scss /cssFile.css

Attention: Before using sass command you must install ruby and then install sass.

For installing sass, after ruby installation type gem install sass in your Terminal

Hint: sass compile SCSS files

Overwriting txt file in java

SOLVED

My biggest "D'oh" moment! I've been compiling it on Eclipse rather than cmd which was where I was executing it. So my newly compiled classes went to the bin folder and the compiled class file via command prompt remained the same in my src folder. I recompiled with my new code and it works like a charm.

File fold = new File("../playlist/" + existingPlaylist.getText() + ".txt");
fold.delete();

File fnew = new File("../playlist/" + existingPlaylist.getText() + ".txt");

String source = textArea.getText();
System.out.println(source);

try {
    FileWriter f2 = new FileWriter(fnew, false);
    f2.write(source);
    f2.close();

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

Check if a user has scrolled to the bottom

My solution in plain js:

_x000D_
_x000D_
let el=document.getElementById('el');_x000D_
el.addEventListener('scroll', function(e) {_x000D_
    if (this.scrollHeight - this.scrollTop - this.clientHeight<=0) {_x000D_
        alert('Bottom');_x000D_
    }_x000D_
});
_x000D_
#el{_x000D_
  width:400px;_x000D_
  height:100px;_x000D_
  overflow-y:scroll;_x000D_
}
_x000D_
<div id="el">_x000D_
<div>content</div>_x000D_
<div>content</div>_x000D_
<div>content</div>_x000D_
<div>content</div>_x000D_
<div>content</div>_x000D_
<div>content</div>_x000D_
<div>content</div>_x000D_
<div>content</div>_x000D_
<div>content</div>_x000D_
<div>content</div>_x000D_
<div>content</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

Using Javascript

I created a working demo that shows how to use the Google Maps API Directions Service in Javascript through a

  • DirectionsService object to send and receive direction requests
  • DirectionsRenderer object to render the returned route on the map

_x000D_
_x000D_
function initMap() {_x000D_
  var pointA = new google.maps.LatLng(51.7519, -1.2578),_x000D_
    pointB = new google.maps.LatLng(50.8429, -0.1313),_x000D_
    myOptions = {_x000D_
      zoom: 7,_x000D_
      center: pointA_x000D_
    },_x000D_
    map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),_x000D_
    // Instantiate a directions service._x000D_
    directionsService = new google.maps.DirectionsService,_x000D_
    directionsDisplay = new google.maps.DirectionsRenderer({_x000D_
      map: map_x000D_
    }),_x000D_
    markerA = new google.maps.Marker({_x000D_
      position: pointA,_x000D_
      title: "point A",_x000D_
      label: "A",_x000D_
      map: map_x000D_
    }),_x000D_
    markerB = new google.maps.Marker({_x000D_
      position: pointB,_x000D_
      title: "point B",_x000D_
      label: "B",_x000D_
      map: map_x000D_
    });_x000D_
_x000D_
  // get route from A to B_x000D_
  calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB);_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
function calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB) {_x000D_
  directionsService.route({_x000D_
    origin: pointA,_x000D_
    destination: pointB,_x000D_
    travelMode: google.maps.TravelMode.DRIVING_x000D_
  }, function(response, status) {_x000D_
    if (status == google.maps.DirectionsStatus.OK) {_x000D_
      directionsDisplay.setDirections(response);_x000D_
    } else {_x000D_
      window.alert('Directions request failed due to ' + status);_x000D_
    }_x000D_
  });_x000D_
}_x000D_
_x000D_
initMap();
_x000D_
    html,_x000D_
    body {_x000D_
      height: 100%;_x000D_
      margin: 0;_x000D_
      padding: 0;_x000D_
    }_x000D_
    #map-canvas {_x000D_
      height: 100%;_x000D_
      width: 100%;_x000D_
    }
_x000D_
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>_x000D_
_x000D_
<div id="map-canvas"></div>
_x000D_
_x000D_
_x000D_

Also on Jsfiddle: http://jsfiddle.net/user2314737/u9no8te4/

Using Google Maps Web Services

You can use the Web Services using an API_KEY issuing a request like this:

https://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&key=API_KEY

An API_KEY can be obtained in the Google Developer Console with a quota of 2,500 free requests/day.

A request can return JSON or XML results that can be used to draw a path on a map.

Official documentation for Web Services using the Google Maps Directions API are here

How to get the html of a div on another page with jQuery ajax?

Unfortunately an ajax request gets the entire file, but you can filter the content once it's retrieved:

$.ajax({
   url:href,
   type:'GET',
   success: function(data) {
       var content = $('<div>').append(data).find('#content');
       $('#content').html( content );
   }
});

Note the use of a dummy element as find() only works with descendants, and won't find root elements.

or let jQuery filter it for you:

$('#content').load(href + ' #IDofDivToFind');

I'm assuming this isn't a cross domain request, as that won't work, only pages on the same domain.

CSS performance relative to translateZ(0)

If you want implications, in some scenarios Google Chrome performance is horrible with hardware acceleration enabled. Oddly enough, changing the "trick" to -webkit-transform: rotateZ(360deg); worked just fine.

I don't believe we ever figured out why.

Microsoft.Office.Core Reference Missing

If someone not have reference in .NET . COM (tab) or not have office installed on machine where visual was installed can do :

  1. Download and install: Microsoft Office Developer Tools
  2. Add references from:

    C:\Program Files (x86)\Microsoft Visual Studio 11.0\Visual Studio Tools for Office\PIA\Office15
    

How do you find out which version of GTK+ is installed on Ubuntu?

You can also just open synaptic and search for libgtk, it will show you exactly which lib is installed.

Order of items in classes: Fields, Properties, Constructors, Methods

The closest you're likely to find is "Design Guidelines, Managed code and the .NET Framework" (http://blogs.msdn.com/brada/articles/361363.aspx) by Brad Abrams

Many standards are outlined here. The relevant section is 2.8 I think.

What is the difference between iterator and iterable and how to use them?

Implementing Iterable interface allows an object to be the target of the "foreach" statement.

class SomeClass implements Iterable<String> {}

class Main 
{
  public void method()
  {
     SomeClass someClass = new SomeClass();
     .....

    for(String s : someClass) {
     //do something
    }
  }
}

Iterator is an interface, which has implementation for iterate over elements. Iterable is an interface which provides Iterator.

What exactly is node.js used for?

Node.js is an open source command line tool built for the server side JavaScript code.

Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications.

Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

The basic philosophy of node.js is:

Non-blocking I/O - every I/O call must take a callback, whether it is to retrieve information from disk, network or another process. Built-in support for the most important protocols (HTTP, DNS, TLS) Low-level. Do not remove functionality present at the POSIX layer. For example, support half-closed TCP connections. Stream everything; never force the buffering of data.

Credit - Simple Overview About Node.js

Reading file using relative path in python project

Relative paths are relative to current working directory. If you do not your want your path to be, it must be absolute.

But there is an often used trick to build an absolute path from current script: use its __file__ special attribute:

from pathlib import Path

path = Path(__file__).parent / "../data/test.csv"
with path.open() as f:
    test = list(csv.reader(f))

This requires python 3.4+ (for the pathlib module).

If you still need to support older versions, you can get the same result with:

import csv
import os.path

my_path = os.path.abspath(os.path.dirname(__file__))
path = os.path.join(my_path, "../data/test.csv")
with open(path) as f:
    test = list(csv.reader(f))

[2020 edit: python3.4+ should now be the norm, so I moved the pathlib version inspired by jpyams' comment first]

Instantiating a generic class in Java

Here's a rather contrived way to do it without explicitly using an constructor argument. You need to extend a parameterized abstract class.

public class Test {   
    public static void main(String [] args) throws Exception {
        Generic g = new Generic();
        g.initParameter();
    }
}

import java.lang.reflect.ParameterizedType;
public abstract class GenericAbstract<T extends Foo> {
    protected T parameter;

    @SuppressWarnings("unchecked")
    void initParameter() throws Exception, ClassNotFoundException, 
        InstantiationException {
        // Get the class name of this instance's type.
        ParameterizedType pt
            = (ParameterizedType) getClass().getGenericSuperclass();
        // You may need this split or not, use logging to check
        String parameterClassName
            = pt.getActualTypeArguments()[0].toString().split("\\s")[1];
        // Instantiate the Parameter and initialize it.
        parameter = (T) Class.forName(parameterClassName).newInstance();
    }
}

public class Generic extends GenericAbstract<Foo> {
}

public class Foo {
    public Foo() {
        System.out.println("Foo constructor...");
    }
}

Delete specific line number(s) from a text file using sed?

You can delete a particular single line with its line number by

sed -i '33d' file

This will delete the line on 33 line number and save the updated file.

how to define variable in jquery

You can also use text() to set or get the text content of selected elements

var text1 = $("#idName").text();

How to display a Windows Form in full screen on top of the taskbar?

FormBorderStyle = FormBorderStyle.Sizable;
TopMost = false;
WindowState = FormWindowState.Normal;

THIS CODE MAKE YOUR WINDOWS FULL SCREEN THIS WILL ALSO COVER WHOLE SCREEN

Find nearest value in numpy array

Here's an extension to find the nearest vector in an array of vectors.

import numpy as np

def find_nearest_vector(array, value):
  idx = np.array([np.linalg.norm(x+y) for (x,y) in array-value]).argmin()
  return array[idx]

A = np.random.random((10,2))*100
""" A = array([[ 34.19762933,  43.14534123],
   [ 48.79558706,  47.79243283],
   [ 38.42774411,  84.87155478],
   [ 63.64371943,  50.7722317 ],
   [ 73.56362857,  27.87895698],
   [ 96.67790593,  77.76150486],
   [ 68.86202147,  21.38735169],
   [  5.21796467,  59.17051276],
   [ 82.92389467,  99.90387851],
   [  6.76626539,  30.50661753]])"""
pt = [6, 30]  
print find_nearest_vector(A,pt)
# array([  6.76626539,  30.50661753])

Convert floats to ints in Pandas?

To modify the float output do this:

df= pd.DataFrame(range(5), columns=['a'])
df.a = df.a.astype(float)
df

Out[33]:

          a
0 0.0000000
1 1.0000000
2 2.0000000
3 3.0000000
4 4.0000000

pd.options.display.float_format = '{:,.0f}'.format
df

Out[35]:

   a
0  0
1  1
2  2
3  3
4  4

Let JSON object accept bytes or let urlopen output strings

For anyone else trying to solve this using the requests library:

import json
import requests

r = requests.get('http://localhost/index.json')
r.raise_for_status()
# works for Python2 and Python3
json.loads(r.content.decode('utf-8'))

Difference between DTO, VO, POJO, JavaBeans?

Basically,

DTO: "Data transfer objects " can travel between seperate layers in software architecture.

VO: "Value objects " hold a object such as Integer,Money etc.

POJO: Plain Old Java Object which is not a special object.

Java Beans: requires a Java Class to be serializable, have a no-arg constructor and a getter and setter for each field

Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...

$time_ago = ' ';
$time = time() - $time; // to get the time since that moment
$tokens = array (
31536000 => 'year',2592000 => 'month',604800 => 'week',86400 => 'day',3600 => 'hour',
60  => 'minute',1 => 'second');
foreach ($tokens as $unit => $text) {
if ($time < $unit)continue;
$numberOfUnits = floor($time / $unit);
$time_ago = ' '.$time_ago. $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'').'  ';
$time = $time % $unit;}echo $time_ago;

Cannot read property 'length' of null (javascript)

if (capital.touched && capital != undefined && capital.length < 1 ) { 
//capital does exists
}

Ajax Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource

Place below line at the top of the file which you are calling through AJAX.

header("Access-Control-Allow-Origin: *");

Does it matter what extension is used for SQLite database files?

Emacs expects one of db, sqlite, sqlite2 or sqlite3 in the default configuration for sql-sqlite mode.

Pass parameter from a batch file to a PowerShell script

The answer from @Emiliano is excellent. You can also pass named parameters like so:

powershell.exe -Command 'G:\Karan\PowerShell_Scripts\START_DEV.ps1' -NamedParam1 "SomeDataA" -NamedParam2 "SomeData2"

Note the parameters are outside the command call, and you'll use:

[parameter(Mandatory=$false)]
  [string]$NamedParam1,
[parameter(Mandatory=$false)]
  [string]$NamedParam2

How do I return multiple values from a function?

I prefer:

def g(x):
  y0 = x + 1
  y1 = x * 3
  y2 = y0 ** y3
  return {'y0':y0, 'y1':y1 ,'y2':y2 }

It seems everything else is just extra code to do the same thing.

Writing outputs to log file and console

I wanted to display logs on stdout and log file along with the timestamp. None of the above answers worked for me. I made use of process substitution and exec command and came up with the following code. Sample logs:

2017-06-21 11:16:41+05:30 Fetching information about files in the directory...

Add following lines at the top of your script:

LOG_FILE=script.log
exec > >(while read -r line; do printf '%s %s\n' "$(date --rfc-3339=seconds)" "$line" | tee -a $LOG_FILE; done)
exec 2> >(while read -r line; do printf '%s %s\n' "$(date --rfc-3339=seconds)" "$line" | tee -a $LOG_FILE; done >&2)

Hope this helps somebody!

Slick Carousel Uncaught TypeError: $(...).slick is not a function

I'm not 100% sure, but I believe the error was caused by some client-side JavaScript that was turning exports into an object. Some code in the Slick plugin (see below) calls the require function if exports is not undefined.

Here's the portion of code I had to change in slick.js. You can see I am just commenting out the if statements, and, instead, I'm just calling factory(jQuery).

;(function(factory) {
console.log('slick in factory', define, 'exports', exports, 'factory', factory);
'use strict';
// if (typeof define === 'function' && define.amd) {
//     define(['jquery'], factory);
// } else if (typeof exports !== 'undefined') {
//     module.exports = factory(require('jquery'));
// } else {
//     factory(jQuery);
// }
factory(jQuery);
}

Is bool a native C type?

No, there is no bool in ISO C90.

Here's a list of keywords in standard C (not C99):

  • auto
  • break
  • case
  • char
  • const
  • continue
  • default
  • do
  • double
  • else
  • enum
  • extern
  • float
  • for
  • goto
  • if
  • int
  • long
  • register
  • return
  • short
  • signed
  • static
  • struct
  • switch
  • typedef
  • union
  • unsigned
  • void
  • volatile
  • while

Here's an article discussing some other differences with C as used in the kernel and the standard: http://www.ibm.com/developerworks/linux/library/l-gcc-hacks/index.html

Store List to session

public class ProductList
{
   public string product{get;set;}
   public List<ProductList> objList{get;set;}
}

ProductList obj=new ProductList();
obj.objList=new List<ProductList>();
obj.objList.add(new ProductList{product="Football"});

now assign obj to session

Session["Product"]=obj;

for retrieval of session.

ProductList objLst = (ProductList)Session["Product"];

SCCM 2012 application install "Failed" in client Software Center

The execmgr.log will show the commandline and ccmcache folder used for installation. Typically, required apps don't show on appenforce.log and some clients will have outdated appenforce or no ppenforce.log files. execmgr.log also shows required hidden uninstall actions as well.

You may want to save the blog link. I still reference it from time to time.

Calling filter returns <filter object at ... >

It's an iterator returned by the filter function.

If you want a list, just do

list(filter(f, range(2, 25)))

Nonetheless, you can just iterate over this object with a for loop.

for e in filter(f, range(2, 25)):
    do_stuff(e)

Explain __dict__ attribute

Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes. Quoting from the documentation for __dict__

A dictionary or other mapping object used to store an object's (writable) attributes.

Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:

def func():
    pass

func.temp = 1

print(func.__dict__)

class TempClass:
    a = 1
    def temp_function(self):
        pass

print(TempClass.__dict__)

will output

{'temp': 1}
{'__module__': '__main__', 
 'a': 1, 
 'temp_function': <function TempClass.temp_function at 0x10a3a2950>, 
 '__dict__': <attribute '__dict__' of 'TempClass' objects>, 
 '__weakref__': <attribute '__weakref__' of 'TempClass' objects>, 
 '__doc__': None}

REST API using POST instead of GET

I use POST body for anything non-trivial and line-of-business apps for these reasons:

  1. Security - If we use GET with query strings and https, the query strings can be saved in server logs and forwarded as referral links. Both of these are now visible by server/network admins and the next domain the user went to after leaving your app. So if we send a query containing confidential PII data such as a customer's name this may not be desired.
  2. URL maximum length - Not a big issue, but some browsers have a limit on the length. So if we have several items in our URL like query, paging, fields to return, etc....
  3. POST is not cached by default. Some say caching is desired; however, how often is that exact same set of search criteria for that exact object for that exact customer going to occur before the cache times out anyway?

BTW, I also put the fields to return in my POST body as I may not wish to expose my field names. Security is like an onion; it has many layers and makes us cry!

How to display with n decimal places in Matlab

i use like tim say sprintf('%0.6f', x), it's a string then i change it to number by using command str2double(x).

Shrink a YouTube video to responsive width

Okay, looks like big solutions.

Why not to add width: 100%; directly in your iframe. ;)

So your code would looks something like <iframe style="width: 100%;" ...></iframe>

Try this it'll work as it worked in my case.

Enjoy! :)

rails generate model

The error shows you either didn't create the rails project yet or you're not in the rails project directory.

Suppose if you're working on myapp project. You've to move to that project directory on your command line and then generate the model. Here are some steps you can refer.

Example: Assuming you didn't create the Rails app yet:

$> rails new myapp
$> cd myapp

Now generate the model from your commandline.

$> rails generate model your_model_name 

Namespace not recognized (even though it is there)

Restarting Visual Studio 2019 - that did it.

Confirm deletion using Bootstrap 3 modal box

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

https://getbootstrap.com/docs/4.0/components/modal/

Python 2.7: %d, %s, and float()

See String Formatting Operations:

%d is the format code for an integer. %f is the format code for a float.

%s prints the str() of an object (What you see when you print(object)).

%r prints the repr() of an object (What you see when you print(repr(object)).

For a float %s, %r and %f all display the same value, but that isn't the case for all objects. The other fields of a format specifier work differently as well:

>>> print('%10.2s' % 1.123) # print as string, truncate to 2 characters in a 10-place field.
        1.
>>> print('%10.2f' % 1.123) # print as float, round to 2 decimal places in a 10-place field.
      1.12

Switching to landscape mode in Android Emulator

I'm using Android Studio and none of the suggestions worked. I can turn the emulator but it stays in portrait. I didn't want to add a command in the manifest forcing landscape. The fix for me was:

  1. turn the emulator to landscape mode using ctrlF11 (the image will still be in portrait though)

  2. Open up the camera in the os, it opens up in landscape mode, the only app that does this

  3. without doing anything else, debug my app from Android Studio and now it shows up in landscape

How to restore the menu bar in Visual Studio Code

You have two options.

Option 1

Make the menu bar temporarily visible.

  • press Alt key and you will be able to see the menu bar

Option 2

Make the menu bar permanently visible.

Steps:

  1. Press F1
  2. Type user settings
  3. Press Enter
  4. Click on the { } (top right corner of the window) to open settings.json file see the screenshot
  5. Then in the settings.json file, change the value to the default "window.menuBarVisibility": "default" you can see a sample here (or remove this line from JSON file. If you remove any value from the settings.json file then it will use the default settings for those entries. So if you want to make everything to default settings then remove all entries in the settings.json file).

How to prevent Right Click option using jquery

The following code will disable mouse right click from full page.

$(document).ready(function () {
   $("body").on("contextmenu",function(e){
     return false;
   });
});

The full tutorial and working demo can be found from here - Disable mouse right click using jQuery

Returning anonymous type in C#

Three options:

Option1:

public class TheRepresentativeType {
    public ... SomeVariable {get;set;}
    public ... AnotherVariable {get;set;}
}

public IEnumerable<TheRepresentativeType> TheMethod(SomeParameter)
{
   using (MyDC TheDC = new MyDC())
   {
     var TheQueryFromDB = (....
                           select new TheRepresentativeType{ SomeVariable = ....,
                                        AnotherVariable = ....}
                           ).ToList();

     return TheQueryFromDB;
   } 
}

Option 2:

public IEnumerable TheMethod(SomeParameter)
{
   using (MyDC TheDC = new MyDC())
   {
     var TheQueryFromDB = (....
                           select new TheRepresentativeType{ SomeVariable = ....,
                                        AnotherVariable = ....}
                           ).ToList();
     return TheQueryFromDB;
   } 
}

you can iterate it as object

Option 3:

public IEnumerable<dynamic> TheMethod(SomeParameter)
{
   using (MyDC TheDC = new MyDC())
   {
     var TheQueryFromDB = (....
                           select new TheRepresentativeType{ SomeVariable = ....,
                                        AnotherVariable = ....}
                           ).ToList();

     return TheQueryFromDB; //You may need to call .Cast<dynamic>(), but I'm not sure
   } 
}

and you will be able to iterate it as a dynamic object and access their properties directly

Excel VBA If cell.Value =... then

You can determine if as certain word is found in a cell by using

If InStr(cell.Value, "Word1") > 0 Then

If Word1 is found in the string the InStr() function will return the location of the first character of Word1 in the string.

Javascript require() function giving ReferenceError: require is not defined

require is part of the Asynchronous Module Definition (AMD) API.

A browser implementation can be found via require.js and native support can be found in node.js.

The documentation for the library you are using should tell you what you need to use it, I suspect that it is intended to run under Node.js and not in browsers.

const vs constexpr on variables

constexpr indicates a value that's constant and known during compilation.
const indicates a value that's only constant; it's not compulsory to know during compilation.

int sz;
constexpr auto arraySize1 = sz;    // error! sz's value unknown at compilation
std::array<int, sz> data1;         // error! same problem

constexpr auto arraySize2 = 10;    // fine, 10 is a compile-time constant
std::array<int, arraySize2> data2; // fine, arraySize2 is constexpr

Note that const doesn’t offer the same guarantee as constexpr, because const objects need not be initialized with values known during compilation.

int sz;
const auto arraySize = sz;       // fine, arraySize is const copy of sz
std::array<int, arraySize> data; // error! arraySize's value unknown at compilation

All constexpr objects are const, but not all const objects are constexpr.

If you want compilers to guarantee that a variable has a value that can be used in contexts requiring compile-time constants, the tool to reach for is constexpr, not const.

Setting up and using Meld as your git difftool and mergetool

For Windows. Run these commands in Git Bash:

git config --global diff.tool meld
git config --global difftool.meld.path "C:\Program Files (x86)\Meld\Meld.exe"
git config --global difftool.prompt false

git config --global merge.tool meld
git config --global mergetool.meld.path "C:\Program Files (x86)\Meld\Meld.exe"
git config --global mergetool.prompt false

(Update the file path for Meld.exe if yours is different.)

For Linux. Run these commands in Git Bash:

git config --global diff.tool meld
git config --global difftool.meld.path "/usr/bin/meld"
git config --global difftool.prompt false

git config --global merge.tool meld
git config --global mergetool.meld.path "/usr/bin/meld"
git config --global mergetool.prompt false

You can verify Meld's path using this command:

which meld

Calculate days between two Dates in Java 8

If the goal is just to get the difference in days and since the above answers mention about delegate methods would like to point out that once can also simply use -

public long daysInBetween(java.time.LocalDate startDate, java.time.LocalDate endDate) {
  // Check for null values here

  return endDate.toEpochDay() - startDate.toEpochDay();
}

HTML radio buttons allowing multiple selections

They all need to have the same name attribute.

The radio buttons are grouped by the name attribute. Here's an example:

<fieldset>
    <legend>Please select one of the following</legend>
    <input type="radio" name="action" id="track" value="track" /><label for="track">Track Submission</label><br />
    <input type="radio" name="action" id="event" value="event"  /><label for="event">Events and Artist booking</label><br />
    <input type="radio" name="action" id="message" value="message" /><label for="message">Message us</label><br />
</fieldset>

How to go from one page to another page using javascript?

hope this would help:

window.location.href = '/url_after_domain';

Ignore fields from Java object dynamically while sending as JSON from Spring MVC

To acheive dynamic filtering follow the link - https://iamvickyav.medium.com/spring-boot-dynamically-ignore-fields-while-converting-java-object-to-json-e8d642088f55

  1. Add the @JsonFilter("Filter name") annotation to the model class.

  2. Inside the controller function add the code:-

    SimpleBeanPropertyFilter simpleBeanPropertyFilter =
            SimpleBeanPropertyFilter.serializeAllExcept("id", "dob"); 
    
    FilterProvider filterProvider = new SimpleFilterProvider()
            .addFilter("Filter name", simpleBeanPropertyFilter);
    
    List<User> userList = userService.getAllUsers();
    MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(userList);
    mappingJacksonValue.setFilters(filterProvider);
    
    return mappingJacksonValue;
    
  3. make sure the return type is MappingJacksonValue.

Adding open/closed icon to Twitter Bootstrap collapsibles (accordions)

For Bootstrup 3.2 + FontAwesome

$(document).ready(function(){    
    $('#accordProfile').on('shown.bs.collapse', function () {
       $(".fa-chevron-down").removeClass("fa-chevron-down").addClass("fa-chevron-up");
    });

    $('#accordProfile').on('hidden.bs.collapse', function () {
       $(".fa-chevron-up").removeClass("fa-chevron-up").addClass("fa-chevron-down");
    });
});

Sometimes you have to write so. If so

$('.collapsed span').removeClass('fa-minus').addClass('fa-plus');

Automatically generated (class="collapsed"), when you press the hide menu.

ps when you need to create a tree menu

Post form data using HttpWebRequest

Try this:

var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");

var postData = "thing1=hello";
    postData += "&thing2=world";
var data = Encoding.ASCII.GetBytes(postData);

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;

using (var stream = request.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}

var response = (HttpWebResponse)request.GetResponse();

var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

What is Common Gateway Interface (CGI)?

CGI is an interface specification between a web server (HTTP server) and an executable program of some type that is to handle a particular request.

It describes how certain properties of that request should be communicated to the environment of that program and how the program should communicate the response back to the server and how the server should 'complete' the response to form a valid reply to the original HTTP request.

For a while CGI was an IETF Internet Draft and as such had an expiry date. It expired with no update so there was no CGI 'standard'. It is now an informational RFC, but as such documents common practice and isn't a standard itself. rfc3875.txt, rfc3875.html

Programs implementing a CGI interface can be written in any language runnable on the target machine. They must be able to access environment variables and usually standard input and they generate their output on standard output.

Compiled languages such as C were commonly used as were scripting languages such as perl, often using libraries to make accessing the CGI environment easier.

One of the big disadvantages of CGI is that a new program is spawned for each request so maintaining state between requests could be a major performance issue. The state might be handled in cookies or encoded in a URL, but if it gets to large it must be stored elsewhere and keyed from encoded url information or a cookie. Each CGI invocation would then have to reload the stored state from a store somewhere.

For this reason, and for a greatly simple interface to requests and sessions, better integrated environments between web servers and applications are much more popular. Environments like a modern php implementation with apache integrate the target language much better with web server and provide access to request and sessions objects that are needed to efficiently serve http requests. They offer a much easier and richer way to write 'programs' to handle HTTP requests.

Whether you wrote a CGI script rather depends on interpretation. It certainly did the job of one but it is much more usual to run php as a module where the interface between the script and the server isn't strictly a CGI interface.

Regex match one of two words

There are different regex engines but I think most of them will work with this:

apple|banana

Replace all whitespace characters

Not /gi but /g

var fname = "My Family File.jpg"
fname = fname.replace(/ /g,"_");
console.log(fname);

gives

"My_Family_File.jpg"

Querying Windows Active Directory server using ldapsearch from command line

The short answer is "yes". A sample ldapsearch command to query an Active Directory server is:

ldapsearch \
    -x -h ldapserver.mydomain.com \
    -D "[email protected]" \
    -W \
    -b "cn=users,dc=mydomain,dc=com" \
    -s sub "(cn=*)" cn mail sn

This would connect to an AD server at hostname ldapserver.mydomain.com as user [email protected], prompt for the password on the command line and show name and email details for users in the cn=users,dc=mydomain,dc=com subtree.

See Managing LDAP from the Command Line on Linux for more samples. See LDAP Query Basics for Microsoft Exchange documentation for samples using LDAP queries with Active Directory.

how to convert date to a format `mm/dd/yyyy`

As your data already in varchar, you have to convert it into date first:

select convert(varchar(10), cast(ts as date), 101) from <your table>

What is the purpose for using OPTION(MAXDOP 1) in SQL Server?

There are a couple of parallization bugs in SQL server with abnormal input. OPTION(MAXDOP 1) will sidestep them.

EDIT: Old. My testing was done largely on SQL 2005. Most of these seem to not exist anymore, but every once in awhile we question the assumption when SQL 2014 does something dumb and we go back to the old way and it works. We never managed to demonstrate that it wasn't just a bad plan generation on more recent cases though since SQL server can be relied on to get the old way right in newer versions. Since all cases were IO bound queries MAXDOP 1 doesn't hurt.

Counter increment in Bash loop not working

COUNTER=$((COUNTER+1)) 

is quite a clumsy construct in modern programming.

(( COUNTER++ ))

looks more "modern". You can also use

let COUNTER++

if you think that improves readability. Sometimes, Bash gives too many ways of doing things - Perl philosophy I suppose - when perhaps the Python "there is only one right way to do it" might be more appropriate. That's a debatable statement if ever there was one! Anyway, I would suggest the aim (in this case) is not just to increment a variable but (general rule) to also write code that someone else can understand and support. Conformity goes a long way to achieving that.

HTH

Getting "java.nio.file.AccessDeniedException" when trying to write to a folder

I was getting the same error when trying to copy a file. Closing a channel associated with the target file solved the problem.

Path destFile = Paths.get("dest file");
SeekableByteChannel destFileChannel = Files.newByteChannel(destFile);
//...
destFileChannel.close();  //removing this will throw java.nio.file.AccessDeniedException:
Files.copy(Paths.get("source file"), destFile);

Run batch file as a Windows service

On Windows 2019 Server, you can run a Minecraft java server with these commands:

sc create minecraft-server DisplayName= "minecraft-server" binpath= "cmd.exe /C C:\Users\Administrator\Desktop\rungui1151.lnk" type= own start= auto

The .lnk file is a standard windows shortcut to a batch file.

--- .bat file begins ---

java -Xmx40960M -Xms40960M -d64 -jar minecraft_server.1.15.1.jar

--- .bat file ends ---

All this because:

service does not know how to start in a folder,

cmd.exe does not know how to start in a folder

Starting the service will produce "timely manner" error, but the log file reveals the server is running.

If you need to shut down the server, just go into task manager and find the server java in background processes and end it, or terminate the server from in the game using the /stop command, or for other programs/servers, use the methods relevant to the server.

How can I easily add storage to a VirtualBox machine with XP installed?

Adding a second drive is probably easiest. That would only take a few minutes, and it wouldn't require any configuration, really.

Alternatively, you could create the second, bigger drive, then run a disk imaging utility to copy all data on disk1 to disk2. That certainly shouldn't take a few hours, but it would take longer than just living with two drives.

jQuery equivalent to Prototype array.last()

For arrays, you could simply retrieve the last element position with array.length - 1:

var a = [1,2,3,4];

var lastEl = a[a.length-1]; // 4

In jQuery you have the :last selector, but this won't help you on plain arrays.

Initialising mock objects - MockIto

A little example for JUnit 5 Jupiter, the "RunWith" was removed you now need to use the Extensions using the "@ExtendWith" Annotation.

@ExtendWith(MockitoExtension.class)
class FooTest {

  @InjectMocks
  ClassUnderTest test = new ClassUnderTest();

  @Spy
  SomeInject bla = new SomeInject();
}

how to set image from url for imageView

Try this :

ImageView imageview = (ImageView)findViewById(R.id.your_imageview_id);
Bitmap bmp = BitmapFactory.decodeFile(new java.net.URL(your_url).openStream());  
imageview.setImageBitmap(bmp);

You can also try this : Android-Universal-Image-Loader for efficiently loading your image from URL

getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)

Starting from Android Support Library 23,
a new getColor() method has been added to ContextCompat.

Its description from the official JavaDoc:

Returns a color associated with a particular resource ID

Starting in M, the returned color will be styled for the specified Context's theme.


So, just call:

ContextCompat.getColor(context, R.color.your_color);

You can check the ContextCompat.getColor() source code on GitHub.

What is the difference between ( for... in ) and ( for... of ) statements?

There are some already defined data types which allows us to iterate over them easily e.g Array, Map, String Objects

Normal for in iterates over the iterator and in response provides us with the keys that are in the order of insertion as shown in below example.

  const numbers = [1,2,3,4,5];
   for(let number in number) {
     console.log(number);
   }

   // result: 0, 1, 2, 3, 4

Now if we try same with for of, then in response it provides us with the values not the keys. e.g

  const numbers = [1,2,3,4,5];
   for(let numbers of numbers) {
    console.log(number);
  }

  // result: 1, 2, 3, 4, 5

So looking at both of the iterators we can easily differentiate the difference between both of them.

Note:- For of only works with the Symbol.iterator

So if we try to iterate over normal object, then it will give us an error e.g-

const Room = {
   area: 1000,
   height: 7,
   floor: 2
 }

for(let prop in Room) {
 console.log(prop);
 } 

// Result area, height, floor

for(let prop of Room) {
  console.log(prop);
 } 

Room is not iterable

Now for iterating over we need to define an ES6 Symbol.iterator e.g

  const Room= {
    area: 1000, height: 7, floor: 2,
   [Symbol.iterator]: function* (){
    yield this.area;
    yield this.height;
    yield this.floors;
  }
}


for(let prop of Room) {
  console.log(prop);
 } 

//Result 1000, 7, 2

This is the difference between For in and For of. Hope that it might clear the difference.