Programs & Examples On #Maintainability

Maintainability refers to the nature, methods, theory and art of maximizing the ease with which an asset may be sustained, modified or enhanced throughout the duration of its expected useful life.

React Native: Getting the position of an element

If you use function components and don't want to use a forwardRef to measure your component's absolute layout, you can get a reference to it from the LayoutChangeEvent in the onLayout callback.

This way, you can get the absolute position of the element:

<MyFunctionComp
  onLayout={(event) => {
    event.target.measure(
      (x, y, width, height, pageX, pageX) => {
        doSomethingWithAbsolutePosition({
          x: x + pageX, 
          y: y + pageY,
        });
      },
    );
  }}
/>

Tested with React Native 0.63.3.

JavaScript single line 'if' statement - best syntax, this alternative?

**Old Method:**
if(x){
   add(x);
}
New Method:
x && add(x);

Even assign operation also we can do with round brackets

exp.includes('regexp_replace') && (exp = exp.replace(/,/g, '@&'));

When to use references vs. pointers

Like others already answered: Always use references, unless the variable being NULL/nullptr is really a valid state.

John Carmack's viewpoint on the subject is similar:

NULL pointers are the biggest problem in C/C++, at least in our code. The dual use of a single value as both a flag and an address causes an incredible number of fatal issues. C++ references should be favored over pointers whenever possible; while a reference is “really” just a pointer, it has the implicit contract of being not-NULL. Perform NULL checks when pointers are turned into references, then you can ignore the issue thereafter.

http://www.altdevblogaday.com/2011/12/24/static-code-analysis/

Edit 2012-03-13

User Bret Kuhns rightly remarks:

The C++11 standard has been finalized. I think it's time in this thread to mention that most code should do perfectly fine with a combination of references, shared_ptr, and unique_ptr.

True enough, but the question still remains, even when replacing raw pointers with smart pointers.

For example, both std::unique_ptr and std::shared_ptr can be constructed as "empty" pointers through their default constructor:

... meaning that using them without verifying they are not empty risks a crash, which is exactly what J. Carmack's discussion is all about.

And then, we have the amusing problem of "how do we pass a smart pointer as a function parameter?"

Jon's answer for the question C++ - passing references to boost::shared_ptr, and the following comments show that even then, passing a smart pointer by copy or by reference is not as clear cut as one would like (I favor myself the "by-reference" by default, but I could be wrong).

Get name of property as a string

Okay, here's what I ended up creating (based upon the answer I selected and the question he referenced):

// <summary>
// Get the name of a static or instance property from a property access lambda.
// </summary>
// <typeparam name="T">Type of the property</typeparam>
// <param name="propertyLambda">lambda expression of the form: '() => Class.Property' or '() => object.Property'</param>
// <returns>The name of the property</returns>

public string GetPropertyName<T>(Expression<Func<T>> propertyLambda)
{
    var me = propertyLambda.Body as MemberExpression;

    if (me == null)
    {
        throw new ArgumentException("You must pass a lambda of the form: '() => Class.Property' or '() => object.Property'");
    }

    return me.Member.Name;
 }

Usage:

// Static Property
string name = GetPropertyName(() => SomeClass.SomeProperty);

// Instance Property
string name = GetPropertyName(() => someObject.SomeProperty);

REST API Best practice: How to accept list of parameter values as input

I will side with nategood's answer as it is complete and it seemed to have please your needs. Though, I would like to add a comment on identifying multiple (1 or more) resource that way:

http://our.api.com/Product/101404,7267261

In doing so, you:

Complexify the clients by forcing them to interpret your response as an array, which to me is counter intuitive if I make the following request: http://our.api.com/Product/101404

Create redundant APIs with one API for getting all products and the one above for getting 1 or many. Since you shouldn't show more than 1 page of details to a user for the sake of UX, I believe having more than 1 ID would be useless and purely used for filtering the products.

It might not be that problematic, but you will either have to handle this yourself server side by returning a single entity (by verifying if your response contains one or more) or let clients manage it.

Example

I want to order a book from Amazing. I know exactly which book it is and I see it in the listing when navigating for Horror books:

  1. 10 000 amazing lines, 0 amazing test
  2. The return of the amazing monster
  3. Let's duplicate amazing code
  4. The amazing beginning of the end

After selecting the second book, I am redirected to a page detailing the book part of a list:

--------------------------------------------
Book #1
--------------------------------------------
    Title: The return of the amazing monster
    Summary:
    Pages:
    Publisher:
--------------------------------------------

Or in a page giving me the full details of that book only?

---------------------------------
The return of the amazing monster
---------------------------------
Summary:
Pages:
Publisher:
---------------------------------

My Opinion

I would suggest using the ID in the path variable when unicity is guarantied when getting this resource's details. For example, the APIs below suggest multiple ways to get the details for a specific resource (assuming a product has a unique ID and a spec for that product has a unique name and you can navigate top down):

/products/{id}
/products/{id}/specs/{name}

The moment you need more than 1 resource, I would suggest filtering from a larger collection. For the same example:

/products?ids=

Of course, this is my opinion as it is not imposed.

T-SQL: Looping through an array of known values

What I do in this scenario is create a table variable to hold the Ids.

  Declare @Ids Table (id integer primary Key not null)
  Insert @Ids(id) values (4),(7),(12),(22),(19)

-- (or call another table valued function to generate this table)

Then loop based on the rows in this table

  Declare @Id Integer
  While exists (Select * From @Ids)
    Begin
      Select @Id = Min(id) from @Ids
      exec p_MyInnerProcedure @Id 
      Delete from @Ids Where id = @Id
    End

or...

  Declare @Id Integer = 0 -- assuming all Ids are > 0
  While exists (Select * From @Ids
                where id > @Id)
    Begin
      Select @Id = Min(id) 
      from @Ids Where id > @Id
      exec p_MyInnerProcedure @Id 
    End

Either of above approaches is much faster than a cursor (declared against regular User Table(s)). Table-valued variables have a bad rep because when used improperly, (for very wide tables with large number of rows) they are not performant. But if you are using them only to hold a key value or a 4 byte integer, with a index (as in this case) they are extremely fast.

Java multiline string

You may use scala-code, which is compatible to java, and allows multiline-Strings enclosed with """:

package foobar
object SWrap {
  def bar = """John said: "This is
  a test
  a bloody test,
  my dear." and closed the door.""" 
}

(note the quotes inside the string) and from java:

String s2 = foobar.SWrap.bar ();

Whether this is more comfortable ...?

Another approach, if you often handle long text, which should be placed in your sourcecode, might be a script, which takes the text from an external file, and wrappes it as a multiline-java-String like this:

sed '1s/^/String s = \"/;2,$s/^/\t+ "/;2,$s/$/"/' file > file.java

so that you may cut-and-paste it easily into your source.

What REALLY happens when you don't free after malloc?

You are correct, memory is automatically freed when the process exits. Some people strive not to do extensive cleanup when the process is terminated, since it will all be relinquished to the operating system. However, while your program is running you should free unused memory. If you don't, you may eventually run out or cause excessive paging if your working set gets too big.

How should the ViewModel close the form?

I used attached behaviours to close the window. Bind a "signal" property on your ViewModel to the attached behaviour (I actually use a trigger) When it's set to true, the behaviour closes the window.

http://adammills.wordpress.com/2009/07/01/window-close-from-xaml/

Finding the direction of scrolling in a UIScrollView?

//Vertical detection
    var lastVelocityYSign = 0
            func scrollViewDidScroll(_ scrollView: UIScrollView) {
                let currentVelocityY =  scrollView.panGestureRecognizer.velocity(in: scrollView.superview).y
                let currentVelocityYSign = Int(currentVelocityY).signum()
                if currentVelocityYSign != lastVelocityYSign &&
                    currentVelocityYSign != 0 {
                    lastVelocityYSign = currentVelocityYSign
                }
                if lastVelocityYSign < 0 {
                    print("SCROLLING DOWN")
                } else if lastVelocityYSign > 0 {
                    print("SCOLLING UP")
                }
            }

Answer from Mos6y https://medium.com/@Mos6yCanSwift/swift-ios-determine-scroll-direction-d48a2327a004

Repeat a task with a time delay?

In my case, I had to execute a process if one of these conditions were true: if a previous process was completed or if 5 seconds had already passed. So, I did the following and worked pretty well:

private Runnable mStatusChecker;
private Handler mHandler;

class {
method() {
  mStatusChecker = new Runnable() {
            int times = 0;
            @Override
            public void run() {
                if (times < 5) {
                    if (process1.isRead()) {
                        executeProcess2();
                    } else {
                        times++;
                        mHandler.postDelayed(mStatusChecker, 1000);
                    }
                } else {
                    executeProcess2();
                }
            }
        };

        mHandler = new Handler();
        startRepeatingTask();
}

    void startRepeatingTask() {
       mStatusChecker.run();
    }

    void stopRepeatingTask() {
        mHandler.removeCallbacks(mStatusChecker);
    }


}

If process1 is read, it executes process2. If not, it increments the variable times, and make the Handler be executed after one second. It maintains a loop until process1 is read or times is 5. When times is 5, it means that 5 seconds passed and in each second, the if clause of process1.isRead() is executed.

Best programming based games

I played RoboWar, but the programming game I remember on the Mac was Chipwits. It came out in 1984. Completely graphical, but entertaining. From what I've seen of Lego Mindstorms, the programming style is similar.

Error converting data types when importing from Excel to SQL Server 2008

Going off of what Derloopkat said, which still can fail on conversion (no offense Derloopkat) because Excel is terrible at this:

  1. Paste from excel into Notepad and save as normal (.txt file).
  2. From within excel, open said .txt file.
  3. Select next as it is obviously tab delimited.
  4. Select "none" for text qualifier, then next again.
  5. Select the first row, hold shift, select the last row, and select the text radial button. Click Finish

It will open, check it to make sure it's accurate and then save as an excel file.

What's the best way to get the last element of an array without deleting it?

$lastValue = end(array_values($array))

No modification is made to $array pointers. This avoids the

reset($array)

which might not be desired in certain conditions.

Visual C++ executable and missing MSVCR100d.dll

I got the same error.

I was refering a VS2010 DLL in a VS2012 project.

Just recompiled the DLL on VS2012 and now everything is fine.

How do I install soap extension?

How To for Linux Ubuntu...

sudo apt-get install php7.1-soap 

Check if file php_soap.ao exists on /usr/lib/php/20160303/

ls /usr/lib/php/20160303/ | grep -i soap
soap.so
php_soap.so
sudo vi /etc/php/7.1/cli/php.ini

Change the line :

;extension=php_soap.dll

to

extension=php_soap.so

sudo systemctl restart apache2

CHecking...

php -m | more

WHERE statement after a UNION in SQL?

select column1..... from table1
where column1=''
union
select column1..... from table2
where column1= ''

Data access object (DAO) in Java

I just want to explain it in my own way with a small story that I experienced in one of my projects. First I want to explain Why DAO is important? rather than go to What is DAO? for better understanding.

Why DAO is important?
In my one project of my project, I used Client.class which contains all the basic information of our system users. Where I need client then every time I need to do an ugly query where it is needed. Then I felt that decreases the readability and made a lot of redundant boilerplate code.

Then one of my senior developers introduced a QueryUtils.class where all queries are added using public static access modifier and then I don't need to do query everywhere. Suppose when I needed activated clients then I just call -

QueryUtils.findAllActivatedClients();

In this way, I made some optimizations of my code.

But there was another problem !!!

I felt that the QueryUtils.class was growing very highly. 100+ methods were included in that class which was also very cumbersome to read and use. Because this class contains other queries of another domain models ( For example- products, categories locations, etc ).

Then the superhero Mr. CTO introduced a new solution named DAO which solved the problem finally. I felt DAO is very domain-specific. For example, he created a DAO called ClientDAO.class where all Client.class related queries are found which seems very easy for me to use and maintain. The giant QueryUtils.class was broken down into many other domain-specific DAO for example - ProductsDAO.class, CategoriesDAO.class, etc which made the code more Readable, more Maintainable, more Decoupled.

What is DAO?

It is an object or interface, which made an easy way to access data from the database without writing complex and ugly queries every time in a reusable way.

How to check if object has any properties in JavaScript?

Late answer, but some frameworks handle objects as enumerables. Therefore, bob.js can do it like this:

var objToTest = {};
var propertyCount = bob.collections.extend(objToTest).count();

Dynamically add item to jQuery Select2 control that uses AJAX

$("#my_select").select2('destroy').empty().select2({data: [{id: 1, text: "new_item"}]});

C# using Sendkey function to send a key to another application

If notepad is already started, you should write:

// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);

//...

Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
    IntPtr h = p.MainWindowHandle;
    SetForegroundWindow(h);
    SendKeys.SendWait("k");
}

GetProcessesByName returns an array of processes, so you should get the first one (or find the one you want).

If you want to start notepad and send the key, you should write:

Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");

The only situation in which the code may not work is when notepad is started as Administrator and your application is not.

Is it possible to declare a variable in Gradle usable in Java?

rciovati's answer is entirely correct I just wanted to add one more tidbit that you can also create variables for every build type within the default config portion of your build.gradle. This would look like this:

android {
    defaultConfig {
        buildConfigField "String", "APP_NAME", "\"APP_NAME\""
    }
}

This will allow you to have access to through

BuildConfig.App_NAME

Just wanted to make a note of this scenario as well if you want a common config.

How do I use variables in Oracle SQL Developer?

You can read up elsewhere on substitution variables; they're quite handy in SQL Developer. But I have fits trying to use bind variables in SQL Developer. This is what I do:

SET SERVEROUTPUT ON
declare
  v_testnum number;
  v_teststring varchar2(1000);

begin
   v_testnum := 2;
   DBMS_OUTPUT.put_line('v_testnum is now ' || v_testnum);

   SELECT 36,'hello world'
   INTO v_testnum, v_teststring
   from dual;

   DBMS_OUTPUT.put_line('v_testnum is now ' || v_testnum);
   DBMS_OUTPUT.put_line('v_teststring is ' || v_teststring);
end;

SET SERVEROUTPUT ON makes it so text can be printed to the script output console.

I believe what we're doing here is officially called PL/SQL. We have left the pure SQL land and are using a different engine in Oracle. You see the SELECT above? In PL/SQL you always have to SELECT ... INTO either variable or a refcursor. You can't just SELECT and return a result set in PL/SQL.

Fork() function in C

int a = fork(); 

Creates a duplicate process "clone?", which shares the execution stack. The difference between the parent and the child is the return value of the function.

The child getting 0 returned, and the parent getting the new pid.

Each time the addresses and the values of the stack variables are copied. The execution continues at the point it already got to in the code.

At each fork, only one value is modified - the return value from fork.

Write HTML string in JSON

It is possible to write an HTML string in JSON. You just need to escape your double-quotes.

[
    {
        "id": "services.html",
        "img": "img/SolutionInnerbananer.jpg",
        "html": "<h2class=\"fg-white\">AboutUs</h2><pclass=\"fg-white\">CSMTechnologiesisapioneerinprovidingconsulting,
        developingandsupportingcomplexITsolutions.Touchingmillionsoflivesworldwidebybringingininnovativetechnology,
        CSMforayedintotheuntappedmarketslikee-GovernanceinIndiaandAfricancontinent.</p>"
    }
]

conversion of a varchar data type to a datetime data type resulted in an out-of-range value

i faced this issue where i was using SQL it is different from MYSQL the solution was puting in this format: =date('m-d-y h:m:s'); rather than =date('y-m-d h:m:s');

Alternative for frames in html5 using iframes

HTML 5 does support iframes. There were a few interesting attributes added like "sandbox" and "srcdoc".

http://www.w3schools.com/html5/tag_iframe.asp

or you can use

<object data="framed.html" type="text/html"><p>This is the fallback code!</p></object>

What is the proper way to format a multi-line dict in Python?

Generally, you would not include the comma after the final entry, but Python will correct that for you.

How to write data to a text file without overwriting the current data

Here's a chunk of code that will write values to a log file. If the file doesn't exist, it creates it, otherwise it just appends to the existing file. You need to add "using System.IO;" at the top of your code, if it's not already there.

string strLogText = "Some details you want to log.";

// Create a writer and open the file:
StreamWriter log;

if (!File.Exists("logfile.txt"))
{
  log = new StreamWriter("logfile.txt");
}
else
{
  log = File.AppendText("logfile.txt");
}

// Write to the file:
log.WriteLine(DateTime.Now);
log.WriteLine(strLogText);
log.WriteLine();

// Close the stream:
log.Close();

ggplot2: sorting a plot

I don't know why this question was reopened but here is a tidyverse option.

x %>% 
  arrange(desc(value)) %>%
  mutate(variable=fct_reorder(variable,value)) %>% 
ggplot(aes(variable,value,fill=variable)) + geom_bar(stat="identity") + 
  scale_y_continuous("",label=scales::percent) + coord_flip() 

How do I get the latest version of my code?

If you are using Git GUI, first fetch then merge.

Fetch via Remote menu >> Fetch >> Origin. Merge via Merge menu >> Merge Local.

The following dialog appears.

enter image description here

Select the tracking branch radio button (also by default selected), leave the yellow box empty and press merge and this should update the files.

I had already reverted some local changes before doing these steps since I wanted to discard those anyways so I don't have to eliminate via merge later.

How do I find out if first character of a string is a number?

I just came across this question and thought on contributing with a solution that does not use regex.

In my case I use a helper method:

public boolean notNumber(String input){
    boolean notNumber = false;
    try {
        // must not start with a number
        @SuppressWarnings("unused")
        double checker = Double.valueOf(input.substring(0,1));
    }
    catch (Exception e) {
        notNumber = true;           
    }
    return notNumber;
}

Probably an overkill, but I try to avoid regex whenever I can.

How to add an extra language input to Android?

On android 2.2 you can input multiple language and switch by sliding on the spacebar. Go in the settings under "language and keyboard" and then "Android Keyboard", "Input language".

Hope this helps.

download csv file from web api in angular js

I had to implement this recently. Thought of sharing what I had figured out;

To make it work in Safari, I had to set target: '_self',. Don't worry about filename in Safari. Looks like it's not supported as mentioned here; https://github.com/konklone/json/issues/56 (http://caniuse.com/#search=download)

The below code works fine for me in Mozilla, Chrome & Safari;

  var anchor = angular.element('<a/>');
  anchor.css({display: 'none'});
  angular.element(document.body).append(anchor);
  anchor.attr({
    href: 'data:attachment/csv;charset=utf-8,' + encodeURIComponent(data),
    target: '_self',
    download: 'data.csv'
  })[0].click();
  anchor.remove();

Correct way to set Bearer token with CURL

This is a cURL function that can send or retrieve data. It should work with any PHP app that supports OAuth:

    function jwt_request($token, $post) {

       header('Content-Type: application/json'); // Specify the type of data
       $ch = curl_init('https://APPURL.com/api/json.php'); // Initialise cURL
       $post = json_encode($post); // Encode the data array into a JSON string
       $authorization = "Authorization: Bearer ".$token; // Prepare the authorisation token
       curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization )); // Inject the token into the header
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
       curl_setopt($ch, CURLOPT_POST, 1); // Specify the request method as POST
       curl_setopt($ch, CURLOPT_POSTFIELDS, $post); // Set the posted fields
       curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // This will follow any redirects
       $result = curl_exec($ch); // Execute the cURL statement
       curl_close($ch); // Close the cURL connection
       return json_decode($result); // Return the received data

    }

Use it within one-way or two-way requests:

$token = "080042cad6356ad5dc0a720c18b53b8e53d4c274"; // Get your token from a cookie or database
$post = array('some_trigger'=>'...','some_values'=>'...'); // Array of data with a trigger
$request = jwt_request($token,$post); // Send or retrieve data

Stop jQuery .load response from being cached

/**
 * Use this function as jQuery "load" to disable request caching in IE
 * Example: $('selector').loadWithoutCache('url', function(){ //success function callback... });
 **/
$.fn.loadWithoutCache = function (){
 var elem = $(this);
 var func = arguments[1];
 $.ajax({
     url: arguments[0],
     cache: false,
     dataType: "html",
     success: function(data, textStatus, XMLHttpRequest) {
   elem.html(data);
   if(func != undefined){
    func(data, textStatus, XMLHttpRequest);
   }
     }
 });
 return elem;
}

What is a good Hash Function?

There are two major purposes of hashing functions:

  • to disperse data points uniformly into n bits.
  • to securely identify the input data.

It's impossible to recommend a hash without knowing what you're using it for.

If you're just making a hash table in a program, then you don't need to worry about how reversible or hackable the algorithm is... SHA-1 or AES is completely unnecessary for this, you'd be better off using a variation of FNV. FNV achieves better dispersion (and thus fewer collisions) than a simple prime mod like you mentioned, and it's more adaptable to varying input sizes.

If you're using the hashes to hide and authenticate public information (such as hashing a password, or a document), then you should use one of the major hashing algorithms vetted by public scrutiny. The Hash Function Lounge is a good place to start.

How do I load an org.w3c.dom.Document from XML in a string?

To manipulate XML in Java, I always tend to use the Transformer API:

import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stream.StreamSource;

public static Document loadXMLFrom(String xml) throws TransformerException {
    Source source = new StreamSource(new StringReader(xml));
    DOMResult result = new DOMResult();
    TransformerFactory.newInstance().newTransformer().transform(source , result);
    return (Document) result.getNode();
}   

How to alert using jQuery

Don't do this, but this is how you would do it:

$(".overdue").each(function() { 
    alert("Your book is overdue"); 
});

The reason I say "don't do it" is because nothing is more annoying to users, in my opinion, than repeated pop-ups that cannot be stopped. Instead, just use the length property and let them know that "You have X books overdue".

How can I make a multipart/form-data POST request using Java?

Use this code to upload images or any other files to the server using post in multipart.

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

public class SimplePostRequestTest {

    public static void main(String[] args) throws UnsupportedEncodingException, IOException {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://192.168.0.102/uploadtest/upload_photo");

        try {
            FileBody bin = new FileBody(new File("/home/ubuntu/cd.png"));
            StringBody id = new StringBody("3");
            MultipartEntity reqEntity = new MultipartEntity();
            reqEntity.addPart("upload_image", bin);
            reqEntity.addPart("id", id);
            reqEntity.addPart("image_title", new StringBody("CoolPic"));

            httppost.setEntity(reqEntity);
            System.out.println("Requesting : " + httppost.getRequestLine());
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String responseBody = httpclient.execute(httppost, responseHandler);
            System.out.println("responseBody : " + responseBody);

        } catch (ClientProtocolException e) {

        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    }

}

it requires below files to upload.

libraries are httpclient-4.1.2.jar, httpcore-4.1.2.jar, httpmime-4.1.2.jar, httpclient-cache-4.1.2.jar, commons-codec.jar and commons-logging-1.1.1.jar to be in classpath.

The transaction log for the database is full

Try this:

If possible restart the services MSSQLSERVER and SQLSERVERAGENT.

Fill remaining vertical space with CSS using display:flex

Use the flex-grow property to the main content div and give the dispaly: flex; to its parent;

_x000D_
_x000D_
body {_x000D_
    height: 100%;_x000D_
    position: absolute;_x000D_
    margin: 0;_x000D_
}_x000D_
section {_x000D_
  height: 100%;_x000D_
  display: flex;_x000D_
  flex-direction : column;_x000D_
}_x000D_
header {_x000D_
  background: tomato;_x000D_
}_x000D_
div {_x000D_
  flex: 1; /* or flex-grow: 1  */;_x000D_
  overflow-x: auto;_x000D_
  background: gold;_x000D_
}_x000D_
footer {_x000D_
  background: lightgreen;_x000D_
  min-height: 60px;_x000D_
}
_x000D_
<section>_x000D_
  <header>_x000D_
    header: sized to content_x000D_
    <br>(but is it really?)_x000D_
  </header>_x000D_
  <div>_x000D_
    main content: fills remaining space<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
  </div>_x000D_
  <footer>_x000D_
    footer: fixed height in px_x000D_
  </footer>_x000D_
</section>
_x000D_
_x000D_
_x000D_

Virtual Serial Port for Linux

Complementing the @slonik's answer.

You can test socat to create Virtual Serial Port doing the following procedure (tested on Ubuntu 12.04):

Open a terminal (let's call it Terminal 0) and execute it:

socat -d -d pty,raw,echo=0 pty,raw,echo=0

The code above returns:

2013/11/01 13:47:27 socat[2506] N PTY is /dev/pts/2
2013/11/01 13:47:27 socat[2506] N PTY is /dev/pts/3
2013/11/01 13:47:27 socat[2506] N starting data transfer loop with FDs [3,3] and [5,5]

Open another terminal and write (Terminal 1):

cat < /dev/pts/2

this command's port name can be changed according to the pc. it's depends on the previous output.

2013/11/01 13:47:27 socat[2506] N PTY is /dev/pts/**2**
2013/11/01 13:47:27 socat[2506] N PTY is /dev/pts/**3**
2013/11/01 13:47:27 socat[2506] N starting data transfer loop with FDs 

you should use the number available on highlighted area.

Open another terminal and write (Terminal 2):

echo "Test" > /dev/pts/3

Now back to Terminal 1 and you'll see the string "Test".

How to set min-height for bootstrap container

Two things are happening here.

  1. You are not using the container class properly.
  2. You are trying to override Bootstrap's CSS for the container class

Bootstrap uses a grid system and the .container class is defined in its own CSS. The grid has to exist within a container class DIV. The container DIV is just an indication to Bootstrap that the grid within has that parent. Therefore, you cannot set the height of a container.

What you want to do is the following:

<div class="container-fluid"> <!-- this is to make it responsive to your screen width -->
    <div class="row">
        <div class="col-md-4 myClassName">  <!-- myClassName is defined in my CSS as you defined your container -->
            <img src="#.jpg" height="200px" width="300px">
        </div>
    </div>
</div>

Here you can find more info on the Bootstrap grid system.

That being said, if you absolutely MUST override the Bootstrap CSS then I would try using the "!important" clause to my CSS definition as such...

.container {
   padding-right: 15px;
   padding-left: 15px;
   margin-right: auto;
   margin-left: auto;
   max-width: 900px;
   overflow:hidden;
   min-height:0px !important;
}

But I have always found that the "!important" clause just makes for messy CSS.

Design Patterns web based applications

I have used the struts framework and find it fairly easy to learn. When using the struts framework each page of your site will have the following items.

1) An action which is used is called every time the HTML page is refreshed. The action should populate the data in the form when the page is first loaded and handles interactions between the web UI and the business layer. If you are using the jsp page to modify a mutable java object a copy of the java object should be stored in the form rather than the original so that the original data doesn't get modified unless the user saves the page.

2) The form which is used to transfer data between the action and the jsp page. This object should consist of a set of getter and setters for attributes that need to be accessible to the jsp file. The form also has a method to validate data before it gets persisted.

3) A jsp page which is used to render the final HTML of the page. The jsp page is a hybrid of HTML and special struts tags used to access and manipulate data in the form. Although struts allows users to insert Java code into jsp files you should be very cautious about doing that because it makes your code more difficult to read. Java code inside jsp files is difficult to debug and can not be unit tested. If you find yourself writing more than 4-5 lines of java code inside a jsp file the code should probably be moved to the action.

Java ArrayList clear() function

Your assumptions don't seem to be right. After a clear(), the newly added data start from index 0.

No submodule mapping found in .gitmodule for a path that's not a submodule

Scenario: changing the submodule from directory dirA-xxx to another directory dirB-xxx

  1. move the dirA-xxx to dirB-xxx
  2. modify entry in .gitmodules to use dirB-xxx
  3. modify entry in .git/config to use dirB-xxx
  4. modify .git/modules/dirA-xxx/config to reflect the correct directory
  5. modify dirA-xxx/.git to reflect the correct directory
  6. run git submodule status

    if return error: No submodule mapping found in .gitmodules for path dirA-xxx. This is due to dirA-xxx is not existing, yet it is still tracked by git. Update the git index by: git rm --cached dirA-xxx

    Try with git submodule foreach git pull. I didn't go through the actual study of git submodule structure, so above steps may break something. Nonetheless going through above steps, things look good at the moment. If you have any insight or proper steps to get thing done, do share it here. :)

how to create a login page when username and password is equal in html

<html>
    <head>
        <title>Login page</title>
    </head>
    <body>
        <h1>Simple Login Page</h1>
        <form name="login">
            Username<input type="text" name="userid"/>
            Password<input type="password" name="pswrd"/>
            <input type="button" onclick="check(this.form)" value="Login"/>
            <input type="reset" value="Cancel"/>
        </form>
        <script language="javascript">
            function check(form) { /*function to check userid & password*/
                /*the following code checkes whether the entered userid and password are matching*/
                if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd") {
                    window.open('target.html')/*opens the target page while Id & password matches*/
                }
                else {
                    alert("Error Password or Username")/*displays error message*/
                }
            }
        </script>
    </body>
</html>

How to replace blank (null ) values with 0 for all records?

I just had this same problem, and I ended up finding the simplest solution which works for my needs. In the table properties, I set the default value to 0 for the fields that I don't want to show nulls. Super easy.

How to get the device's IMEI/ESN programmatically in android?

Try this(need to get first IMEI always)

TelephonyManager mTelephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(LoginActivity.this,Manifest.permission.READ_PHONE_STATE)!= PackageManager.PERMISSION_GRANTED) {

         return;
}

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                if (mTelephony.getPhoneCount() == 2) {
                    IME = mTelephony.getImei(0);
                }else{
                    IME = mTelephony.getImei();
                }
            }else{
                if (mTelephony.getPhoneCount() == 2) {
                    IME = mTelephony.getDeviceId(0);
                } else {
                    IME = mTelephony.getDeviceId();
                }
            }
        } else {
            IME = mTelephony.getDeviceId();
        }

How to set the java.library.path from Eclipse

Click Run
Click Debug ...
New Java Application
Click Arguments tab
in the 2nd box (VM Arguments) add the -D entry

-Xdebug -verbose:gc -Xbootclasspath/p:jar/vbjorb.jar;jar/oracle9.jar;classes;jar/mq.jar;jar/xml4j.jar -classpath -DORBInitRef=NameService=iioploc://10.101.2.94:8092/NameService  

etc...

ASP.NET Identity - HttpContext has no extension method for GetOwinContext

Make sure you installed the nuget package Microsoft.AspNet.Identity.Owin. Then add System.Net.Http namespace.

"The following SDK components were not installed: sys-img-x86-addon-google_apis-google-22 and addon-google_apis-google-22"

i have solve my same problem

i update my android studio, and i choose not to import my setting from my previous version than that problem appear.

than i realize that i have 2 AndroidStudio folder on my windows account (.AndroidStudio and .AndroidStudio1.2) and on my new .AndroidStudio1.2 folder there are no other.xml file.

than i copy other.xml file from C:\Users\my windows account name.AndroidStudio\config\options to C:\Users\my windows account name.AndroidStudio1.2\config\options

and that how i solve my problem.

HTTP POST and GET using cURL in Linux

I think Amith Koujalgi is correct but also, in cases where the webservice responses are in JSON then it might be more useful to see the results in a clean JSON format instead of a very long string. Just add | grep }| python -mjson.tool to the end of curl commands here is two examples:

GET approach with JSON result

curl -i -H "Accept: application/json" http://someHostName/someEndpoint | grep }| python -mjson.tool 

POST approach with JSON result

curl -X POST  -H "Accept: Application/json" -H "Content-Type: application/json" http://someHostName/someEndpoint -d '{"id":"IDVALUE","name":"Mike"}' | grep }| python -mjson.tool

enter image description here

How can I revert a single file to a previous version?

Git doesn't think in terms of file versions. A version in git is a snapshot of the entire tree.

Given this, what you really want is a tree that has the latest content of most files, but with the contents of one file the same as it was 5 commits ago. This will take the form of a new commit on top of the old ones, and the latest version of the tree will have what you want.

I don't know if there's a one-liner that will revert a single file to the contents of 5 commits ago, but the lo-fi solution should work: checkout master~5, copy the file somewhere else, checkout master, copy the file back, then commit.

How to access the correct `this` inside a callback?

The question revolves around how this keyword behaves in javascript. this behaves differently as below,

  1. The value of this is usually determined by a function execution context.
  2. In the global scope, this refers to the global object (the window object).
  3. If strict mode is enabled for any function then the value of this will be undefined as in strict mode, global object refers to undefined in place of the window object.
  4. The object that is standing before the dot is what this keyword will be bound to.
  5. We can set the value of this explicitly with call(), bind(), and apply()
  6. When the new keyword is used (a constructor), this is bound to the new object being created.
  7. Arrow Functions don’t bind this — instead, this is bound lexically (i.e. based on the original context)

As most of the answers suggest, we can use Arrow function or bind() Method or Self var. I would quote a point about lambdas (Arrow function) from Google JavaScript Style Guide

Prefer using arrow functions over f.bind(this), and especially over goog.bind(f, this). Avoid writing const self = this. Arrow functions are particularly useful for callbacks, which sometimes pass unexpectedly additional arguments.

Google clearly recommends using lambdas rather than bind or const self = this

So the best solution would be to use lambdas as below,

function MyConstructor(data, transport) {
  this.data = data;
  transport.on('data', () => {
    alert(this.data);
  });
}

References:

  1. https://medium.com/tech-tajawal/javascript-this-4-rules-7354abdb274c
  2. arrow-functions-vs-bind

How do I convert datetime to ISO 8601 in PHP

How to convert from ISO 8601 to unixtimestamp :

strtotime('2012-01-18T11:45:00+01:00');
// Output : 1326883500

How to convert from unixtimestamp to ISO 8601 (timezone server) :

date_format(date_timestamp_set(new DateTime(), 1326883500), 'c');
// Output : 2012-01-18T11:45:00+01:00

How to convert from unixtimestamp to ISO 8601 (GMT) :

date_format(date_create('@'. 1326883500), 'c') . "\n";
// Output : 2012-01-18T10:45:00+00:00

How to convert from unixtimestamp to ISO 8601 (custom timezone) :

date_format(date_timestamp_set(new DateTime(), 1326883500)->setTimezone(new DateTimeZone('America/New_York')), 'c');
// Output : 2012-01-18T05:45:00-05:00

How to check if input file is empty in jQuery

I know I'm late to the party but I thought I'd add what I ended up using for this - which is to simply check if the file upload input does not contain a truthy value with the not operator & JQuery like so:

if (!$('#videoUploadFile').val()) {
  alert('Please Upload File');
}

Note that if this is in a form, you may also want to wrap it with the following handler to prevent the form from submitting:

$(document).on("click", ":submit", function (e) {

  if (!$('#videoUploadFile').val()) {
  e.preventDefault();
  alert('Please Upload File');
  }

}

angular ng-repeat in reverse

You can also use .reverse(). It's a native array function

<div ng-repeat="friend in friends.reverse()">{{friend.name}}</div>

Using two CSS classes on one element

Instead of using multiple CSS classes, to address your underlying problem you can use the :focus pseudo-selector:

input[type="text"] {
   border: 1px solid grey;
   width: 40%;
   height: 30px;
   border-radius: 0;
}
input[type="text"]:focus {
   border: 1px solid #5acdff;
}

Why use static_cast<int>(x) instead of (int)x?

It's about how much type-safety you want to impose.

When you write (bar) foo (which is equivalent to reinterpret_cast<bar> foo if you haven't provided a type conversion operator) you are telling the compiler to ignore type safety, and just do as it's told.

When you write static_cast<bar> foo you are asking the compiler to at least check that the type conversion makes sense and, for integral types, to insert some conversion code.


EDIT 2014-02-26

I wrote this answer more than 5 years ago, and I got it wrong. (See comments.) But it still gets upvotes!

How to design RESTful search/filtering?

If you use the request body in a GET request, you're breaking the REST principle, because your GET request won't be able to be cached, because cache system uses only the URL.

What's worse, your URL can't be bookmarked, because the URL doesn't contain all the information needed to redirect the user to this page.

Use URL or Query parameters instead of request body parameters, e.g.:

/myapp?var1=xxxx&var2=xxxx
/myapp;var1=xxxx/resource;var2=xxxx 

In fact, the HTTP RFC 7231 says that:

A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.

For more information take a look here.

How to get primary key of table?

Shortest possible code seems to be something like

// $dblink contain database login details 
// $tblName the current table name 
$r = mysqli_fetch_assoc(mysqli_query($dblink, "SHOW KEYS FROM $tblName WHERE Key_name = 'PRIMARY'")); 
$iColName = $r['Column_name']; 

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

After trying EVERY solution google came up with on stack overflow, I found what my particular problem was. I had edited my hosts file a long time ago to allow me to access my localhost from my virtualbox.

Removing this entry solved it for me, along with the correct installation of mongoDB from the link given in the above solution, and including the correct promise handling code:

mongoose.connect('mongodb://localhost/testdb').then(() => {
console.log("Connected to Database");
}).catch((err) => {
    console.log("Not Connected to Database ERROR! ", err);
});

Error java.lang.OutOfMemoryError: GC overhead limit exceeded

This message means that for some reason the garbage collector is taking an excessive amount of time (by default 98% of all CPU time of the process) and recovers very little memory in each run (by default 2% of the heap).

This effectively means that your program stops doing any progress and is busy running only the garbage collection at all time.

To prevent your application from soaking up CPU time without getting anything done, the JVM throws this Error so that you have a chance of diagnosing the problem.

The rare cases where I've seen this happen is where some code was creating tons of temporary objects and tons of weakly-referenced objects in an already very memory-constrained environment.

Check out the Java GC tuning guide, which is available for various Java versions and contains sections about this specific problem:

Autoplay audio files on an iPad with HTML5

UPDATE: This is a hack and it's not working anymore on IOS 4.X and above. This one worked on IOS 3.2.X.

It's not true. Apple doesn't want to autoplay video and audio on IPad because of the high amout of traffic you can use on mobile networks. I wouldn't use autoplay for online content. For Offline HTML sites it's a great feature and thats what I've used it for.

Here is a "javascript fake click" solution: http://www.roblaplaca.com/examples/html5AutoPlay/

Copy & Pasted Code from the site:

<script type="text/javascript"> 
        function fakeClick(fn) {
            var $a = $('<a href="#" id="fakeClick"></a>');
                $a.bind("click", function(e) {
                    e.preventDefault();
                    fn();
                });

            $("body").append($a);

            var evt, 
                el = $("#fakeClick").get(0);

            if (document.createEvent) {
                evt = document.createEvent("MouseEvents");
                if (evt.initMouseEvent) {
                    evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
                    el.dispatchEvent(evt);
                }
            }

            $(el).remove();
        }

        $(function() {
            var video = $("#someVideo").get(0);

            fakeClick(function() {
                video.play();
            });
        });

        </script> 

This is not my source. I've found this some time ago and tested the code on an IPad and IPhone with IOS 3.2.X.

How to reset par(mfrow) in R

You can reset the plot by doing this:

dev.off()

Run jar file in command prompt

If you dont have an entry point defined in your manifest invoking java -jar foo.jar will not work.

Use this command if you dont have a manifest or to run a different main class than the one specified in the manifest:

java -cp foo.jar full.package.name.ClassName

See also instructions on how to create a manifest with an entry point: https://docs.oracle.com/javase/tutorial/deployment/jar/appman.html

Dynamically create an array of strings with malloc

Given that your strings are all fixed-length (presumably at compile-time?), you can do the following:

char (*orderedIds)[ID_LEN+1]
    = malloc(variableNumberOfElements * sizeof(*orderedIds));

// Clear-up
free(orderedIds);

A more cumbersome, but more general, solution, is to assign an array of pointers, and psuedo-initialising them to point at elements of a raw backing array:

char *raw = malloc(variableNumberOfElements * (ID_LEN + 1));
char **orderedIds = malloc(sizeof(*orderedIds) * variableNumberOfElements);

// Set each pointer to the start of its corresponding section of the raw buffer.
for (i = 0; i < variableNumberOfElements; i++)
{
    orderedIds[i] = &raw[i * (ID_LEN+1)];
}

...

// Clear-up pointer array
free(orderedIds);
// Clear-up raw array
free(raw);

ASP.NET 5 MVC: unable to connect to web server 'IIS Express'

For those who still experiencing the problem. I had the same issue but the message was showing IIS only not IIS Express. Try to start VS as administrator. That solved the issue for me.

How to start a background process in Python?

Both capture output and run on background with threading

As mentioned on this answer, if you capture the output with stdout= and then try to read(), then the process blocks.

However, there are cases where you need this. For example, I wanted to launch two processes that talk over a port between them, and save their stdout to a log file and stdout.

The threading module allows us to do that.

First, have a look at how to do the output redirection part alone in this question: Python Popen: Write to stdout AND log file simultaneously

Then:

main.py

#!/usr/bin/env python3

import os
import subprocess
import sys
import threading

def output_reader(proc, file):
    while True:
        byte = proc.stdout.read(1)
        if byte:
            sys.stdout.buffer.write(byte)
            sys.stdout.flush()
            file.buffer.write(byte)
        else:
            break

with subprocess.Popen(['./sleep.py', '0'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc1, \
     subprocess.Popen(['./sleep.py', '10'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc2, \
     open('log1.log', 'w') as file1, \
     open('log2.log', 'w') as file2:
    t1 = threading.Thread(target=output_reader, args=(proc1, file1))
    t2 = threading.Thread(target=output_reader, args=(proc2, file2))
    t1.start()
    t2.start()
    t1.join()
    t2.join()

sleep.py

#!/usr/bin/env python3

import sys
import time

for i in range(4):
    print(i + int(sys.argv[1]))
    sys.stdout.flush()
    time.sleep(0.5)

After running:

./main.py

stdout get updated every 0.5 seconds for every two lines to contain:

0
10
1
11
2
12
3
13

and each log file contains the respective log for a given process.

Inspired by: https://eli.thegreenplace.net/2017/interacting-with-a-long-running-child-process-in-python/

Tested on Ubuntu 18.04, Python 3.6.7.

Phone Number Validation MVC

To display a phone number with (###) ###-#### format, you can create a new HtmlHelper.

Usage

@Html.DisplayForPhone(item.Phone)

HtmlHelper Extension

public static class HtmlHelperExtensions
{
    public static HtmlString DisplayForPhone(this HtmlHelper helper, string phone)
    {
        if (phone == null)
        {
            return new HtmlString(string.Empty);
        }
        string formatted = phone;
        if (phone.Length == 10)
        {
            formatted = $"({phone.Substring(0,3)}) {phone.Substring(3,3)}-{phone.Substring(6,4)}";
        }
        else if (phone.Length == 7)
        {
            formatted = $"{phone.Substring(0,3)}-{phone.Substring(3,4)}";
        }
        string s = $"<a href='tel:{phone}'>{formatted}</a>";
        return new HtmlString(s);
    }
}

How to add multiple columns to pandas dataframe in one assignment?

You could instantiate the values from a dictionary if you wanted different values for each column & you don't mind making a dictionary on the line before.

>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame({
  'col_1': [0, 1, 2, 3], 
  'col_2': [4, 5, 6, 7]
})
>>> df
   col_1  col_2
0      0      4
1      1      5
2      2      6
3      3      7
>>> cols = {
  'column_new_1':np.nan,
  'column_new_2':'dogs',
  'column_new_3': 3
}
>>> df[list(cols)] = pd.DataFrame(data={k:[v]*len(df) for k,v in cols.items()})
>>> df
   col_1  col_2  column_new_1 column_new_2  column_new_3
0      0      4           NaN         dogs             3
1      1      5           NaN         dogs             3
2      2      6           NaN         dogs             3
3      3      7           NaN         dogs             3

Not necessarily better than the accepted answer, but it's another approach not yet listed.

twitter bootstrap text-center when in xs mode

Css Part is:

CSS:

@media (max-width: 767px) {

  // Align text to center.
  .text-xs-center {
    text-align: center;
  } 
}

And the HTML part will be ( this text center work only below 767px width )

HTML:

 <div class="col-xs-12 col-sm-6 text-right text-xs-center">
        <p>
            <a href="#"><i class="fa fa-facebook"></i></a> 
            <a href="#"><i class="fa fa-twitter"></i></a> 
            <a href="#"><i class="fa fa-google-plus"></i></a>
        </p>
 </div>

JQuery - File attributes

To get the filenames, use:

var files = document.getElementById('inputElementID').files;

Using jQuery (since you already are) you can adapt this to the following:

$('input[type="file"][multiple]').change(
    function(e){
        var files = this.files;
        for (i=0;i<files.length;i++){
            console.log(files[i].fileName + ' (' + files[i].fileSize + ').');
        }
        return false;
    });

JS Fiddle demo.

Graphviz: How to go from .dot to a graph?

dot -Tps input.dot > output.eps
dot -Tpng input.dot > output.png

PostScript output seems always there. I am not sure if dot has PNG output by default. This may depend on how you have built it.

Java serialization - java.io.InvalidClassException local class incompatible

This worked for me:

If you wrote your Serialized class object into a file, then made some changes to file and compiled it, and then you try to read an object, then this will happen.

So, write the necessary objects to file again if a class is modified and recompiled.

PS: This is NOT a solution; was meant to be a workaround.

How to Inspect Element using Safari Browser

in menu bar click on Edit->preference->advance at bottom click the check box true that is for Show develop menu in menu bar now a develop menu is display at menu bar where you can see all develop option and inspect.

SQL Server Jobs with SSIS packages - Failed to decrypt protected XML node "DTS:Password" with error 0x8009000B

Little late to the game but i found a way to fix this for me that i had not seen anywhere else. Select your connection from Connection Managers. On the right you should see properties. Check to see if there are any expressions there if not add one. In your package explorer add a variable called connection to sql or whatever. Set the variable as a string and set the value as your connection string and include the User Id and password. Back to the connection manager properties and expression. From the drop down select ConnectionString and set the second box as the name of your variable. It should look like this

enter image description here

I could not for the life of me find another solution but this worked!

Sort rows in data.table in decreasing order on string key `order(-x,v)` gives error on data.table 1.9.4 or earlier

Update

data.table v1.9.6+ now supports OP's original attempt and the following answer is no longer necessary.


You can use DT[order(-rank(x), y)].

   x y v
1: c 1 7
2: c 3 8
3: c 6 9
4: b 1 1
5: b 3 2
6: b 6 3
7: a 1 4
8: a 3 5
9: a 6 6

Handling a timeout error in python sockets

Here is a solution I use in one of my project.

network_utils.telnet

import socket
from timeit import default_timer as timer

def telnet(hostname, port=23, timeout=1):
    start = timer()
    connection = socket.socket()
    connection.settimeout(timeout)
    try:
        connection.connect((hostname, port))
        end = timer()
        delta = end - start
    except (socket.timeout, socket.gaierror) as error:
        logger.debug('telnet error: ', error)
        delta = None
    finally:
        connection.close()

    return {
        hostname: delta
    }

Tests

def test_telnet_is_null_when_host_unreachable(self):
    hostname = 'unreachable'

    response = network_utils.telnet(hostname)

    self.assertDictEqual(response, {'unreachable': None})

def test_telnet_give_time_when_reachable(self):
    hostname = '127.0.0.1'

    response = network_utils.telnet(hostname, port=22)

    self.assertGreater(response[hostname], 0)

How to create a session using JavaScript?

You can try jstorage javascript plugin, it is an elegant way to maintain sessions check this http://www.jstorage.info/

include the jStorage.js script into your html

<script src="jStorage.js"></script>

Then in your javascript place the sessiontoken into the a key like this

$.jStorage.set("YOUR_KEY",session_id);

Where "YOUR_KEY" is the key using which you can access you session_id , like this:

var id = $.jStorage.get("YOUR_KEY");

javac option to compile all java files under a given directory recursively

javac command does not follow a recursive compilation process, so you have either specify each directory when running command, or provide a text file with directories you want to include:

javac -classpath "${CLASSPATH}" @java_sources.txt

How to pass a querystring or route parameter to AWS Lambda from Amazon API Gateway

My goal was to pass a query string similar to:

 protodb?sql=select * from protodb.prototab

to a Node.js 12 Lambda function via a URL from the API gateway. I tried a number of the ideas from the other answers but really wanted to do something in the most API gateway UI native way possible, so I came up with this that worked for me (as of the UI for API Gateway as of December 2020):

On the API Gateway console for a given API, under resources, select the get method. Then select its Integration Request and fill out the data for the lambda function at the top of the page.

Scroll to the bottom and open up the mapping templates section. Choose Request Body Passthrough when there are no templates defined (recommended).

Click on Add mapping templates and create one with the content-type of application/json and hit the check mark button.

For that mapping template, choose the Method Request passthrough on the drop down list for generate template which will fill the textbox under it with AWS' general way to pass everything.

Hit the save button.

Now when I tested it, I could not get the parameter to come through as event.sql under node JS in the Lambda function. It turns out that when the API gateway sends the URL sql query parameter to the Lambda function, it comes through for Node.js as:

 var insql = event.params.querystring.sql;

So the trick that took some time for me was to use JSON.stringify to show the full event stack and then work my way down through the sections to be able to pull out the sql parameter from the query string.

So basically you can use the default passthrough functionality in the API gateway with the trick being how the parameters are passed when you are in the Lambda function.

How To Get Selected Value From UIPickerView

       NSInteger SelectedRow;
                   SelectedRow = [yourPickerView selectedRowInComponent:0];
                   selectedPickerString = [YourPickerArray objectAtIndex:SelectedRow];
                   self.YourTextField.text= selectedPickerString;

    // if  you want to move pickerview to selected row then 
 for (int i = 0; I<YourPickerArray.count; i++) {
  if ([[YourPickerArray objectAtIndex:i] isEqualToString:self.YourTextField.text]) { 
[yourPickerView selectRow:i inComponent:0 animated:NO];
 }
}

History or log of commands executed in Git

I found out that in my version of git bash "2.24.0.windows.2" in my "home" folder under windows users, there will be a file called ".bash-history" with no file extension in that folder. It's only created after you exit from bash.

Here's my workflow:

  1. before exiting bash type "history >> history.txt" [ENTER]
  2. exit the bash prompt
  3. hold Win+R to open the Run command box
  4. enter shell:profile
  5. open "history.txt" to confirm that my text was added
  6. On a new line press [F5] to enter a timestamp
  7. save and close the history textfile
  8. Delete the ".bash-history" file so the next session will create a new history

If you really want points I guess you could make a batch file to do all this but this is good enough for me. Hope it helps someone.

How do I REALLY reset the Visual Studio window layout?

If you want to reset your development environment of your visual studio, then you can use Import and Export setting wizard. see this for all steps:

http://www.authorcode.com/forums/topic/how-to-reset-development-environment-settings-of-your-visual-studio/

Cannot get OpenCV to compile because of undefined references?

If you do the following, you will be able to use opencv build from OpenCV_INSTALL_PATH.

cmake_minimum_required(VERSION 2.8)

SET(OpenCV_INSTALL_PATH /home/user/opencv/opencv-2.4.13/release/)

SET(OpenCV_INCLUDE_DIRS "${OpenCV_INSTALL_PATH}/include/opencv;${OpenCV_INSTALL_PATH}/include")

SET(OpenCV_LIB_DIR "${OpenCV_INSTALL_PATH}/lib")

LINK_DIRECTORIES(${OpenCV_LIB_DIR})

set(OpenCV_LIBS opencv_core opencv_imgproc opencv_calib3d opencv_video opencv_features2d opencv_ml opencv_highgui opencv_objdetect opencv_contrib opencv_legacy opencv_gpu)

# find_package( OpenCV )

project(edge.cpp)

add_executable(edge edge.cpp)

Show tables, describe tables equivalent in redshift

In the following post, I documented queries to retrieve TABLE and COLUMN comments from Redshift. https://sqlsylvia.wordpress.com/2017/04/29/redshift-comment-views-documenting-data/

Enjoy!

Table Comments

    SELECT n.nspname AS schema_name
     , pg_get_userbyid(c.relowner) AS table_owner
     , c.relname AS table_name
     , CASE WHEN c.relkind = 'v' THEN 'view' ELSE 'table' END 
       AS table_type
     , d.description AS table_description
     FROM pg_class As c
     LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
     LEFT JOIN pg_tablespace t ON t.oid = c.reltablespace
     LEFT JOIN pg_description As d 
          ON (d.objoid = c.oid AND d.objsubid = 0)
     WHERE c.relkind IN('r', 'v') AND d.description > ''
     ORDER BY n.nspname, c.relname ;

Column Comments

    SELECT n.nspname AS schema_name
     , pg_get_userbyid(c.relowner) AS table_owner
     , c.relname AS table_name
     , a.attname AS column_name
     , d.description AS column_description
    FROM pg_class AS c
    INNER JOIN pg_attribute As a ON c.oid = a.attrelid
    INNER JOIN pg_namespace n ON n.oid = c.relnamespace
    LEFT JOIN pg_tablespace t ON t.oid = c.reltablespace
    LEFT JOIN pg_description As d 
     ON (d.objoid = c.oid AND d.objsubid = a.attnum)
    WHERE c.relkind IN('r', 'v')
     AND a.attname NOT         
     IN ('cmax', 'oid', 'cmin', 'deletexid', 'ctid', 'tableoid','xmax', 'xmin', 'insertxid')
    ORDER BY n.nspname, c.relname, a.attname;

How to make a cross-module variable?

You can already do this with module-level variables. Modules are the same no matter what module they're being imported from. So you can make the variable a module-level variable in whatever module it makes sense to put it in, and access it or assign to it from other modules. It would be better to call a function to set the variable's value, or to make it a property of some singleton object. That way if you end up needing to run some code when the variable's changed, you can do so without breaking your module's external interface.

It's not usually a great way to do things — using globals seldom is — but I think this is the cleanest way to do it.

Duplicate symbols for architecture x86_64 under Xcode

  • Go to Targets
  • Select Build Settings
  • Search for "No Common Blocks", select it to NO.

It worked for me

Android Get Current timestamp?

From developers blog:

System.currentTimeMillis() is the standard "wall" clock (time and date) expressing milliseconds since the epoch. The wall clock can be set by the user or the phone network (see setCurrentTimeMillis(long)), so the time may jump backwards or forwards unpredictably. This clock should only be used when correspondence with real-world dates and times is important, such as in a calendar or alarm clock application. Interval or elapsed time measurements should use a different clock. If you are using System.currentTimeMillis(), consider listening to the ACTION_TIME_TICK, ACTION_TIME_CHANGED and ACTION_TIMEZONE_CHANGED Intent broadcasts to find out when the time changes.

how to change php version in htaccess in server

Try this to switch to php4:

AddHandler application/x-httpd-php4 .php

Upd. Looks like I didn't understand your question correctly. This will not help if you have only php 4 on your server.

Android - SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length

Make clear you have pass a value in your MainAcitivity for the following methods onCreateOptionsMenu and onCreate

In some cases, the developer deletes the "return super.onCreateOptionsMenu(menu)" statement and changed to "return true".

INSERT INTO TABLE from comma separated varchar-list

Something like this should work:

INSERT INTO #IMEIS (imei) VALUES ('val1'), ('val2'), ...

UPDATE:

Apparently this syntax is only available starting on SQL Server 2008.

IntelliJ does not show 'Class' when we right click and select 'New'

If you open your module settings (F4) you can nominate which paths contain 'source'. Intellij will then mark these directories in blue and allow you to add classes etc.

In a similar fashion you can highlight test directories for unit tests.

Swift addsubview and remove it

Thanks for help. This is the solution: I created the subview and i add a gesture to remove it

@IBAction func infoView(sender: UIButton) {
    var testView: UIView = UIView(frame: CGRectMake(0, 0, 320, 568))
    testView.backgroundColor = UIColor.blueColor()
    testView.alpha = 0.5
    testView.tag = 100
    testView.userInteractionEnabled = true
    self.view.addSubview(testView)

    let aSelector : Selector = "removeSubview"
    let tapGesture = UITapGestureRecognizer(target:self, action: aSelector)
    testView.addGestureRecognizer(tapGesture)
}

func removeSubview(){
    println("Start remove sibview")
    if let viewWithTag = self.view.viewWithTag(100) {
        viewWithTag.removeFromSuperview()
    }else{
        println("No!")
    }
}

Update:

Swift 3+

@IBAction func infoView(sender: UIButton) {
    let testView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 568))
    testView.backgroundColor = .blue
    testView.alpha = 0.5
    testView.tag = 100
    testView.isUserInteractionEnabled = true
    self.view.addSubview(testView)

    let aSelector : Selector = #selector(GasMapViewController.removeSubview)
    let tapGesture = UITapGestureRecognizer(target:self, action: aSelector)
    testView.addGestureRecognizer(tapGesture)
}

func removeSubview(){
    print("Start remove sibview")
    if let viewWithTag = self.view.viewWithTag(100) {
        viewWithTag.removeFromSuperview()
    }else{
        print("No!")
    }
}

Can't find the 'libpq-fe.h header when trying to install pg gem

The right answer for Mac users with Postgres.app is to build against the libpq provided with that package. For example, with the 9.4 release (current as of this writing), all you need is:

export CONFIGURE_ARGS="with-pg-include=/Applications/Postgres.app/Contents/Versions/9.4/include"
gem install pg

This will keep your pg gem in sync with exactly the version of PostgreSQL you have installed. Installing something from Homebrew is a waste in this case.

Capturing Groups From a Grep RegEx

Not possible in just grep I believe

for sed:

name=`echo $f | sed -E 's/([0-9]+_([a-z]+)_[0-9a-z]*)|.*/\2/'`

I'll take a stab at the bonus though:

echo "$name.jpg"

ansible: lineinfile for several lines?

You can try using blockinfile instead.

You can do something like

- blockinfile: |
    dest=/etc/network/interfaces backup=yes
    content="iface eth0 inet static
        address 192.168.0.1
        netmask 255.255.255.0"

What is difference between INNER join and OUTER join

INNER JOIN: Returns all rows when there is at least one match in BOTH tables

LEFT JOIN: Return all rows from the left table, and the matched rows from the right table

RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table

FULL JOIN: Return all rows when there is a match in ONE of the tables

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();
}

Error to run Android Studio

 sudo apt-get install default-jdk

That's all in ubuntu 11

Download files in laravel using Response::download

File downloads are super simple in Laravel 5.

As @Ashwani mentioned Laravel 5 allows file downloads with response()->download() to return file for download. We no longer need to mess with any headers. To return a file we simply:

return response()->download(public_path('file_path/from_public_dir.pdf'));

from within the controller.


Reusable Download Route/Controller

Now let's make a reusable file download route and controller so we can server up any file in our public/files directory.

Create the controller:

php artisan make:controller --plain DownloadsController

Create the route in app/Http/routes.php:

Route::get('/download/{file}', 'DownloadsController@download');

Make download method in app/Http/Controllers/DownloadsController:

class DownloadsController extends Controller
{
  public function download($file_name) {
    $file_path = public_path('files/'.$file_name);
    return response()->download($file_path);
  }
}

Now simply drops some files in the public/files directory and you can server them up by linking to /download/filename.ext:

<a href="/download/filename.ext">File Name</a> // update to your own "filename.ext"

If you pulled in Laravel Collective's Html package you can use the Html facade:

{!! Html::link('download/filename.ext', 'File Name') !!}

Add timer to a Windows Forms application

Something like this in your form main. Double click the form in the visual editor to create the form load event.

 Timer Clock=new Timer();
 Clock.Interval=2700000; // not sure if this length of time will work 
 Clock.Start();
 Clock.Tick+=new EventHandler(Timer_Tick);

Then add an event handler to do something when the timer fires.

  public void Timer_Tick(object sender,EventArgs eArgs)
  {
    if(sender==Clock)
    {
      // do something here      
    }
  }

php return 500 error but no error log

You need to enable the PHP error log.

This is due to some random glitch in the web server when you have a php error, it throws a 500 internal error (i have the same issue).

If you look in the PHP error log, you should find your solution.

see here in the doc of how to enable it in the php.ini

how to check if object already exists in a list

It depends on the needs of the specific situation. For example, the dictionary approach would be quite good assuming:

  1. The list is relatively stable (not a lot of inserts/deletions, which dictionaries are not optimized for)
  2. The list is quite large (otherwise the overhead of the dictionary is pointless).

If the above are not true for your situation, just use the method Any():

Item wonderIfItsPresent = ...
bool containsItem = myList.Any(item => item.UniqueProperty == wonderIfItsPresent.UniqueProperty);

This will enumerate through the list until it finds a match, or until it reaches the end.

How to sort a Ruby Hash by number value?

That's not the behavior I'm seeing:

irb(main):001:0> metrics = {"sitea.com" => 745, "siteb.com" => 9, "sitec.com" =>
 10 }
=> {"siteb.com"=>9, "sitec.com"=>10, "sitea.com"=>745}
irb(main):002:0> metrics.sort {|a1,a2| a2[1]<=>a1[1]}
=> [["sitea.com", 745], ["sitec.com", 10], ["siteb.com", 9]]

Is it possible that somewhere along the line your numbers are being converted to strings? Is there more code you're not posting?

How to print a string multiple times?

for i in range(3):
    print "Your text here"

Or

for i in range(3):
    print("Your text here")

How do I create a custom Error in JavaScript?

Update your code to assign your prototype to the Error.prototype and the instanceof and your asserts work.

function NotImplementedError(message = "") {
    this.name = "NotImplementedError";
    this.message = message;
}
NotImplementedError.prototype = Error.prototype;

However, I would just throw your own object and just check the name property.

throw {name : "NotImplementedError", message : "too lazy to implement"}; 

Edit based on comments

After looking at the comments and trying to remember why I would assign prototype to Error.prototype instead of new Error() like Nicholas Zakas did in his article, I created a jsFiddle with the code below:

_x000D_
_x000D_
function NotImplementedError(message = "") {
  this.name = "NotImplementedError";
  this.message = message;
}
NotImplementedError.prototype = Error.prototype;

function NotImplementedError2(message = "") {
  this.message = message;
}
NotImplementedError2.prototype = new Error();

try {
  var e = new NotImplementedError("NotImplementedError message");
  throw e;
} catch (ex1) {
  console.log(ex1.stack);
  console.log("ex1 instanceof NotImplementedError = " + (ex1 instanceof NotImplementedError));
  console.log("ex1 instanceof Error = " + (ex1 instanceof Error));
  console.log("ex1.name = " + ex1.name);
  console.log("ex1.message = " + ex1.message);
}

try {
  var e = new NotImplementedError2("NotImplementedError2 message");
  throw e;
} catch (ex1) {
  console.log(ex1.stack);
  console.log("ex1 instanceof NotImplementedError2 = " + (ex1 instanceof NotImplementedError2));
  console.log("ex1 instanceof Error = " + (ex1 instanceof Error));
  console.log("ex1.name = " + ex1.name);
  console.log("ex1.message = " + ex1.message);
}
_x000D_
_x000D_
_x000D_

The console output was this.

undefined
ex1 instanceof NotImplementedError = true
ex1 instanceof Error = true
ex1.name = NotImplementedError
ex1.message = NotImplementedError message
Error
    at window.onload (http://fiddle.jshell.net/MwMEJ/show/:29:34)
ex1 instanceof NotImplementedError2 = true
ex1 instanceof Error = true
ex1.name = Error
ex1.message = NotImplementedError2 message

This confirmes the "problem" I ran into was the stack property of the error was the line number where new Error() was created, and not where the throw e occurred. However, that may be better that having the side effect of a NotImplementedError.prototype.name = "NotImplementedError" line affecting the Error object.

Also, notice with NotImplementedError2, when I don't set the .name explicitly, it is equal to "Error". However, as mentioned in the comments, because that version sets prototype to new Error(), I could set NotImplementedError2.prototype.name = "NotImplementedError2" and be OK.

Why is my CSS bundling not working with a bin deployed MVC4 app?

One of my css files had an '_' character in the file name which caused issues.

Renamed your_style.css to yourstyle.css

SVN- How to commit multiple files in a single shot

You can use an svn changelist to keep track of a set of files that you want to commit together.

The linked page goes into lots of details, but here's an executive summary example:

$ svn changelist my-changelist mydir/dir1/file1.c mydir/dir2/myfile1.h
$ svn changelist my-changelist mydir/dir3/myfile3.c etc.
... (add all the files you want to commit together at your own rate)
$ svn commit -m"log msg" --changelist my-changelist

Finding diff between current and last version

Difference between last but one commit and last commit (plus current state, if any):

git diff HEAD~

or even (easier to type)

git diff @~

where @ is the synonim for HEAD of current branch and ~ means "give me the parent of mentioned revision".

How to group dataframe rows into list in pandas groupby

If performance is important go down to numpy level:

import numpy as np

df = pd.DataFrame({'a': np.random.randint(0, 60, 600), 'b': [1, 2, 5, 5, 4, 6]*100})

def f(df):
         keys, values = df.sort_values('a').values.T
         ukeys, index = np.unique(keys, True)
         arrays = np.split(values, index[1:])
         df2 = pd.DataFrame({'a':ukeys, 'b':[list(a) for a in arrays]})
         return df2

Tests:

In [301]: %timeit f(df)
1000 loops, best of 3: 1.64 ms per loop

In [302]: %timeit df.groupby('a')['b'].apply(list)
100 loops, best of 3: 5.26 ms per loop

Pandas groupby: How to get a union of strings

You can use the apply method to apply an arbitrary function to the grouped data. So if you want a set, apply set. If you want a list, apply list.

>>> d
   A       B
0  1    This
1  2      is
2  3       a
3  4  random
4  1  string
5  2       !
>>> d.groupby('A')['B'].apply(list)
A
1    [This, string]
2           [is, !]
3               [a]
4          [random]
dtype: object

If you want something else, just write a function that does what you want and then apply that.

ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

I ran this on MacOS /Applications/Python\ 3.6/Install\ Certificates.command

How to send a POST request in Go?

I know this is old but this answer came up in search results. For the next guy - the proposed and accepted answer works, however the code initially submitted in the question is lower-level than it needs to be. Nobody got time for that.

//one-line post request/response...
response, err := http.PostForm(APIURL, url.Values{
    "ln": {c.ln},
    "ip": {c.ip},
    "ua": {c.ua}})

//okay, moving on...
if err != nil {
  //handle postform error
}

defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)

if err != nil {
  //handle read response error
}

fmt.Printf("%s\n", string(body))

https://golang.org/pkg/net/http/#pkg-overview

How to connect to Mysql Server inside VirtualBox Vagrant?

Make sure MySQL binds to 0.0.0.0 and not 127.0.0.1 or it will not be accessible from outside the machine

You can ensure this by editing your my.conf file and looking for the bind-address item--you want it to look like bind-address = 0.0.0.0. Then save this and restart mysql:

sudo service mysql restart

If you are doing this on a production server, you want to be aware of the security implications, discussed here: https://serverfault.com/questions/257513/how-bad-is-setting-mysqls-bind-address-to-0-0-0-0

What is a bus error?

I was getting a bus error when the root directory was at 100%.

Warning: Permanently added the RSA host key for IP address

E.g. ip 192.30.253.112 in warning:

$ git clone [email protected]:EXAMPLE.git
Cloning into 'EXAMPLE'...
Warning: Permanently added the RSA host key for IP address '192.30.253.112' to the list of known hosts.
remote: Enumerating objects: 135, done.
remote: Total 135 (delta 0), reused 0 (delta 0), pack-reused 135
Receiving objects: 100% (135/135), 9.49 MiB | 2.46 MiB/s, done.
Resolving deltas: 100% (40/40), done.

It's the ip if you nslookup github url:

$ nslookup github.com
Server:         127.0.0.53
Address:        127.0.0.53#53

Non-authoritative answer:
Name:   github.com
Address: 192.30.253.112
Name:   github.com
Address: 192.30.253.113

$ 

How to plot all the columns of a data frame in R

There is very simple way to plot all columns from a data frame using separate panels or the same panel:

plot.ts(data)

Which yields (where X1 - X4 are column names):

enter image description here

Have look at ?plot.ts for all the options.

If you wan't more control over your plotting function and not use a loop, you could also do something like:

par(mfcol = c(ncol(data), 1))
Map(function(x,y) plot(x, main =y), data, names(data))

How do you get a directory listing sorted by creation date in python?

from pathlib import Path
import os

sorted(Path('./').iterdir(), key=lambda t: t.stat().st_mtime)

or

sorted(Path('./').iterdir(), key=os.path.getmtime)

or

sorted(os.scandir('./'), key=lambda t: t.stat().st_mtime)

where m time is modified time.

Access restriction: The type 'Application' is not API (restriction on required library rt.jar)

If you're having this same issue using Spring Tool Suite:

The Spring Tool Suite's underlying IDE is, in fact, Eclipse. I've gotten this error just now trying to use some com.sun.net classes. To remove these errors and prevent them from popping up in the Eclipse Luna SR1 (4.4.2) platform of STS:

  • Navigate to Project > Properties
  • Expand the Java Compiler heading
  • Click on Errors/Warnings
  • Expand deprecated and restricted API
  • Next to "Forbidden reference (access rules)" select "ignore"
  • Next to "Discouraged reference (access rules)" select "ignore"

You're good to go.

Spark: subtract two DataFrames

According to the api docs, doing:

dataFrame1.except(dataFrame2)

will return a new DataFrame containing rows in dataFrame1 but not in dataframe2.

How to get xdebug var_dump to show full object/array

Or you can use an alternative:

https://github.com/kint-php/kint

It works with zero set up and has much more features than Xdebug's var_dump anyway. To bypass the nested limit on the fly with Kint, just use

 +d( $variable ); // append `+` to the dump call

Display two fields side by side in a Bootstrap Form

@KyleMit answer is one way to solve this, however we may chose to avoid the undivided input fields acheived by input-group class. A better way to do this is by using form-group and row classes on a parent div and use input elements with grid-system classes provided by bootstrap.

<div class="form-group row">
    <input class="form-control col-md-6" type="text">
    <input class="form-control col-md-6" type="text">
</div>

How to populate a sub-document in mongoose after creating it?

In order to populate referenced subdocuments, you need to explicitly define the document collection to which the ID references to (like created_by: { type: Schema.Types.ObjectId, ref: 'User' }).

Given this reference is defined and your schema is otherwise well defined as well, you can now just call populate as usual (e.g. populate('comments.created_by'))

Proof of concept code:

// Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserSchema = new Schema({
  name: String
});

var CommentSchema = new Schema({
  text: String,
  created_by: { type: Schema.Types.ObjectId, ref: 'User' }
});

var ItemSchema = new Schema({
   comments: [CommentSchema]
});

// Connect to DB and instantiate models    
var db = mongoose.connect('enter your database here');
var User = db.model('User', UserSchema);
var Comment = db.model('Comment', CommentSchema);
var Item = db.model('Item', ItemSchema);

// Find and populate
Item.find({}).populate('comments.created_by').exec(function(err, items) {
    console.log(items[0].comments[0].created_by.name);
});

Finally note that populate works only for queries so you need to first pass your item into a query and then call it:

item.save(function(err, item) {
    Item.findOne(item).populate('comments.created_by').exec(function (err, item) {
        res.json({
            status: 'success',
            message: "You have commented on this item",
            comment: item.comments.id(comment._id)
        });
    });
});

jquery get height of iframe content when loaded

The less complicated answer is to use .contents() to get at the iframe. Interestingly, though, it returns a different value from what I get using the code in my original answer, due to the padding on the body, I believe.

$('iframe').contents().height() + 'is the height'

This is how I've done it for cross-domain communication, so I'm afraid it's maybe unnecessarily complicated. First, I would put jQuery inside the iFrame's document; this will consume more memory, but it shouldn't increase load time as the script only needs to be loaded once.

Use the iFrame's jQuery to measure the height of your iframe's body as early as possible (onDOMReady) and then set the URL hash to that height. And in the parent document, add an onload event to the iFrame tag that will look at the location of the iframe and extract the value you need. Because onDOMReady will always occur before the document's load event, you can be fairly certain the value will get communicated correctly without a race condition complicating things.

In other words:

...in Help.php:

var getDocumentHeight = function() {
    if (location.hash === '') { // EDIT: this should prevent the retriggering of onDOMReady
        location.hash = $('body').height(); 
        // at this point the document address will be something like help.php#1552
    }
};
$(getDocumentHeight);

...and in the parent document:

var getIFrameHeight = function() {
    var iFrame = $('iframe')[0]; // this will return the DOM element
    var strHash = iFrame.contentDocument.location.hash;
    alert(strHash); // will return something like '#1552'
};
$('iframe').bind('load', getIFrameHeight );

How to create Select List for Country and States/province in MVC

Best way to make drop down list:

grid.Column("PriceType",canSort:true,header: "PriceType",format: @<span>
    <span id="[email protected]">@item.PriceTypeDescription</span>
    @Html.DropDownList("PriceType"+(int)item.ShoppingCartID,new SelectList(MvcApplication1.Services.ExigoApiContext.CreateODataContext().PriceTypes.Select(s => new { s.PriceTypeID, s.PriceTypeDescription }).AsEnumerable(),"PriceTypeID", "PriceTypeDescription",Convert.ToInt32(item.PriceTypeId)), new { @class = "PriceType",@style="width:120px;display:none",@selectedvalue="selected"})
        </span>),

How to declare a local variable in Razor?

If you're looking for a int variable, one that increments as the code loops, you can use something like this:

@{
  int counter = 1;

  foreach (var item in Model.Stuff) {
    ... some code ...
    counter = counter + 1;
  }
} 

Adding local .aar files to Gradle build using "flatDirs" is not working

Update : As @amram99 mentioned, the issue has been fixed as of the release of Android Studio v1.3.

Tested and verified with below specifications

  • Android Studio v1.3
  • gradle plugin v1.2.3
  • Gradle v2.4

What works now

  • Now you can import a local aar file via the File>New>New Module>Import .JAR/.AAR Package option in Android Studio v1.3

  • However the below answer holds true and effective irrespective of the Android Studio changes as this is based of gradle scripting.


Old Answer : In a recent update the people at android broke the inclusion of local aar files via the Android Studio's add new module menu option. Check the Issue listed here. Irrespective of anything that goes in and out of IDE's feature list , the below method works when it comes to working with local aar files.(Tested it today):

Put the aar file in the libs directory (create it if needed), then, add the following code in your build.gradle :

dependencies {
   compile(name:'nameOfYourAARFileWithoutExtension', ext:'aar')
 }
repositories{
      flatDir{
              dirs 'libs'
       }
 }

java.util.zip.ZipException: duplicate entry during packageAllDebugClassesForMultiDex

I also have the issue because of i have compile 'com.android.support:appcompat-v7:24.0.0-alpha1' but i added recyclerview liberary compile 'com.android.support:recyclerview-v7:24.0.2'..i changed the version as same as compat like (24.0.2 intead of 24.0.0).

i got the answer..may be it will help for someone.

How to configure nginx to enable kinda 'file browser' mode?

You need create /home/yozloy/html/test folder. Or you can use alias like below show:

location /test {
    alias /home/yozloy/html/;
    autoindex on;
}

AttributeError: can't set attribute in python

items[node.ind] = items[node.ind]._replace(v=node.v)

(Note: Don't be discouraged to use this solution because of the leading underscore in the function _replace. Specifically for namedtuple some functions have leading underscore which is not for indicating they are meant to be "private")

What is AndroidX?

AndroidX - Android Extension Library

From AndroidX documentation

We are rolling out a new package structure to make it clearer which packages are bundled with the Android operating system, and which are packaged with your app's APK. Going forward, the android.* package hierarchy will be reserved for Android packages that ship with the operating system. Other packages will be issued in the new androidx.* package hierarchy as part of the AndroidX library.

Need of AndroidX

AndroidX is a redesigned library to make package names more clear. So from now on android hierarchy will be for only android default classes, which comes with android operating system and other library/dependencies will be part of androidx (makes more sense). So from now on all the new development will be updated in androidx.

com.android.support.** : androidx.
com.android.support:appcompat-v7 : androidx.appcompat:appcompat com.android.support:recyclerview-v7 : androidx.recyclerview:recyclerview com.android.support:design : com.google.android.material:material

Complete Artifact mappings for AndroidX packages

AndroidX uses Semantic-version

Previously, support library used the SDK version but AndroidX uses the Semantic-version. It’s going to re-version from 28.0.0 ? 1.0.0.

How to migrate current project

In Android Studio 3.2 (September 2018), there is a direct option to migrate existing project to AndroidX. This refactor all packages automatically.

Before you migrate, it is strongly recommended to backup your project.

Existing project

  • Android Studio > Refactor Menu > Migrate to AndroidX...
  • It will analyze and will open Refractor window in bottom. Accept changes to be done.

image

New project

Put these flags in your gradle.properties

android.enableJetifier=true
android.useAndroidX=true

Check @Library mappings for equal AndroidX package.

Check @Official page of Migrate to AndroidX

What is Jetifier?

Bugs of migrating

  • If you build app, and find some errors after migrating, then you need to fix those minor errors. You will not get stuck there, because that can be easily fixed.
  • 3rd party libraries are not converted to AndroidX in directory, but they get converted at run time by Jetifier, so don't worry about compile time errors, your app will run perfectly.

Support 28.0.0 is last release?

From Android Support Revision 28.0.0

This will be the last feature release under the android.support packaging, and developers are encouraged to migrate to AndroidX 1.0.0

So go with AndroidX, because Android will update only androidx package from now.

Further Reading

https://developer.android.com/topic/libraries/support-library/androidx-overview

https://android-developers.googleblog.com/2018/05/hello-world-androidx.html

Troubleshooting misplaced .git directory (nothing to commit)

Here is another twist on it. My .gitignore file seemed to have been modified / corrupted so that a file I was ignoring

e.g.

/Project/Folder/StyleCop.cache

got changed to this (Note now 2 separate lines)

/Project/Folder
StyleCop.cache

so git was ignoring any files I added to the project and below.

Very weird, no idea how the .gitignore file was changed, but took me a while to spot. Once fixed, the hundreds of css and js files I added went in.

How to get child process from parent process

For the case when the process tree of interest has more than 2 levels (e.g. Chromium spawns 4-level deep process tree), pgrep isn't of much use. As others have mentioned above, procfs files contain all the information about processes and one just needs to read them. I built a CLI tool called Procpath which does exactly this. It reads all /proc/N/stat files, represents the contents as a JSON tree and expose it to JSONPath queries.

To get all descendant process' comma-separated PIDs of a non-root process (for the root it's ..stat.pid) it's:

$ procpath query -d, "..children[?(@.stat.pid == 24243)]..pid"
24243,24259,24284,24289,24260,24262,24333,24337,24439,24570,24592,24606,...

Synchronous Requests in Node.js

The short answer is: don't. (...) You really can't. And that's a good thing

I'd like to set the record straight regarding this:

NodeJS does support Synchronous Requests. It wasn't designed to support them out of the box, but there are a few workarounds if you are keen enough, here is an example:

var request = require('sync-request'),
    res1, res2, ucomp, vcomp;

try {
    res1 = request('GET', base + u_ext);
    res2 = request('GET', base + v_ext);
    ucomp = res1.split('\n')[1].split(', ')[1];
    vcomp = res2.split('\n')[1].split(', ')[1];
    doSomething(ucomp, vcomp);

} catch (e) {}

When you pop the hood open on the 'sync-request' library you can see that this runs a synchronous child process in the background. And as is explained in the sync-request README it should be used very judiciously. This approach locks the main thread, and that is bad for performance.

However, in some cases there is little or no advantage to be gained by writing an asynchronous solution (compared to the certain harm you are doing by writing code that is harder to read).

This is the default assumption held by many of the HTTP request libraries in other languages (Python, Java, C# etc), and that philosophy can also be carried to JavaScript. A language is a tool for solving problems after all, and sometimes you may not want to use callbacks if the benefits outweigh the disadvantages.

For JavaScript purists this may rankle of heresy, but I'm a pragmatist so I can clearly see that the simplicity of using synchronous requests helps if you find yourself in some of the following scenarios:

  1. Test Automation (tests are usually synchronous by nature).

  2. Quick API mash-ups (ie hackathon, proof of concept works etc).

  3. Simple examples to help beginners (before and after).

Be warned that the code above should not be used for production. If you are going to run a proper API then use callbacks, use promises, use async/await, or whatever, but avoid synchronous code unless you want to incur a significant cost for wasted CPU time on your server.

Conversion failed when converting from a character string to uniqueidentifier - Two GUIDs

The problem was that the ID column wasn't getting any value. I saw on @Martin Smith SQL Fiddle that he declared the ID column with DEFAULT newid and I didn't..

Pass array to where in Codeigniter Active Record

$this->db->where_in('id', ['20','15','22','42','86']);

Reference: where_in

How remove border around image in css?

What class do you have on the image tag?

Try this

<img src="/images/myimage.jpg" style="border:none;" alt="my image" />

What is attr_accessor in Ruby?

Defines a named attribute for this module, where the name is symbol.id2name, creating an instance variable (@name) and a corresponding access method to read it. Also creates a method called name= to set the attribute.

module Mod
  attr_accessor(:one, :two)
end
Mod.instance_methods.sort   #=> [:one, :one=, :two, :two=]

Angular.js: set element height on page load

Combining matty-j suggestion with the snippet of the question, I ended up with this code focusing on resizing the grid after the data was loaded.

The HTML:

<div ng-grid="gridOptions" class="gridStyle"></div>

The directive:

angular.module('myApp.directives', [])
    .directive('resize', function ($window) {
        return function (scope, element) {

            var w = angular.element($window);
            scope.getWindowDimensions = function () {
                return { 'h': w.height(), 'w': w.width() };
            };
            scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {

                // resize Grid to optimize height
                $('.gridStyle').height(newValue.h - 250);
            }, true);

            w.bind('resize', function () {
                scope.$apply();
            });
        }
    });

The controller:

angular.module('myApp').controller('Admin/SurveyCtrl', function ($scope, $routeParams, $location, $window, $timeout, Survey) {

    // Retrieve data from the server
    $scope.surveys = Survey.query(function(data) {

        // Trigger resize event informing elements to resize according to the height of the window.
        $timeout(function () {
            angular.element($window).resize();
        }, 0)
    });

    // Configure ng-grid.
    $scope.gridOptions = {
        data: 'surveys',
        ...
    };
}

CSS How to set div height 100% minus nPx

If you don't want to use absolute positioning and all that jazz, here's a fix I like to use:

your html:

<body>    
   <div id="header"></div>
   <div id="wrapper"></div>
</body>

your css:

body {
     height:100%;
     padding-top:60px;
}
#header {
     margin-top:60px;
     height:60px;
}
#wrapper {
     height:100%;
}

How to printf "unsigned long" in C?

Out of all the combinations you tried, %ld and %lu are the only ones which are valid printf format specifiers at all. %lu (long unsigned decimal), %lx or %lX (long hex with lowercase or uppercase letters), and %lo (long octal) are the only valid format specifiers for a variable of type unsigned long (of course you can add field width, precision, etc modifiers between the % and the l).

How to create a Calendar table for 100 years in Sql

This will create you the result in lightning fast.

select top 100000  identity (int ,1,1) as Sequence into Tally from sysobjects , sys.all_columns


select dateadd(dd,sequence,-1) Dates into CalenderTable from tally


delete from CalenderTable where dates < -- mention the mindate you need
delete from CalenderTable where dates >  -- mention the max date you need

Step 1 : Create a sequence table

Step 2 : Use the sequence table to generate the desired dates

Step 3 : Delete unwanted dates

jquery ajax function not working

For the sake of documentation. I spent two days working out an ajax problem and this afternoon when I started testing, my PHP ajax handler wasn't getting called....

Extraordinarily frustrating.

The solution to my problem (which might help others) is the priority of the add_action.

add_action ('wp_ajax_(my handler), array('class_name', 'static_function'), 1);

recalling that the default priority = 10

I was getting a return code of zero and none of my code was being called.

...noting that this wasn't a WordPress problem, I probably misspoke on this question. My apologies.

XML Serialize generic list of serializable objects

I think Dreas' approach is ok. An alternative to this however is to have some static helper methods and implement IXmlSerializable on each of your methods e.g an XmlWriter extension method and the XmlReader one to read it back.

public static void SaveXmlSerialiableElement<T>(this XmlWriter writer, String elementName, T element) where T : IXmlSerializable
{
   writer.WriteStartElement(elementName);
   writer.WriteAttributeString("TYPE", element.GetType().AssemblyQualifiedName);
   element.WriteXml(writer);
   writer.WriteEndElement();
}

public static T ReadXmlSerializableElement<T>(this XmlReader reader, String elementName) where T : IXmlSerializable
{
   reader.ReadToElement(elementName);

   Type elementType = Type.GetType(reader.GetAttribute("TYPE"));
   T element = (T)Activator.CreateInstance(elementType);
   element.ReadXml(reader);
   return element;
}

If you do go down the route of using the XmlSerializer class directly, create serialization assemblies before hand if possible, as you can take a large performance hit in constructing new XmlSerializers regularly.

For a collection you need something like this:

public static void SaveXmlSerialiazbleCollection<T>(this XmlWriter writer, String collectionName, String elementName, IEnumerable<T> items) where T : IXmlSerializable
{
   writer.WriteStartElement(collectionName);
   foreach (T item in items)
   {
      writer.WriteStartElement(elementName);
      writer.WriteAttributeString("TYPE", item.GetType().AssemblyQualifiedName);
      item.WriteXml(writer);
      writer.WriteEndElement();
   }
   writer.WriteEndElement();
}

Linking a UNC / Network drive on an html page

To link to a UNC path from an HTML document, use file:///// (yes, that's five slashes).

file://///server/path/to/file.txt

Note that this is most useful in IE and Outlook/Word. It won't work in Chrome or Firefox, intentionally - the link will fail silently. Some words from the Mozilla team:

For security purposes, Mozilla applications block links to local files (and directories) from remote files.

And less directly, from Google:

Firefox and Chrome doesn't open "file://" links from pages that originated from outside the local machine. This is a design decision made by those browsers to improve security.

The Mozilla article includes a set of client settings you can use to override this behavior in Firefox, and there are extensions for both browsers to override this restriction.

Converting String to Cstring in C++

.c_str() returns a const char*. If you need a mutable version, you will need to produce a copy yourself.

Determining image file size + dimensions via Javascript?

Check the uploaded image size using Javascript

<script type="text/javascript">
    function check(){
      var imgpath=document.getElementById('imgfile');
      if (!imgpath.value==""){
        var img=imgpath.files[0].size;
        var imgsize=img/1024; 
        alert(imgsize);
      }
    }
</script>

Html code

<form method="post" enctype="multipart/form-data" onsubmit="return check();">
<input type="file" name="imgfile" id="imgfile"><br><input type="submit">
</form>

How to hide a mobile browser's address bar?

create host file = manifest.json

html tag head

<link rel="manifest" href="/manifest.json">

file

manifest.json

{
"name": "news",
"short_name": "news",
"description": "des news application day",
"categories": [
"news",
"business"
],
"theme_color": "#ffffff",
"background_color": "#ffffff",
"display": "standalone",
"orientation": "natural",
"lang": "fa",
"dir": "rtl",
"start_url": "/?application=true",
"gcm_sender_id": "482941778795",
"DO_NOT_CHANGE_GCM_SENDER_ID": "Do not change the GCM Sender ID",
"icons": [
{
"src": "https://s100.divarcdn.com/static/thewall-assets/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "https://s100.divarcdn.com/static/thewall-assets/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"related_applications": [
{
"platform": "play",
"url": "https://play.google.com/store/apps/details?id=ir.divar"
}
],
"prefer_related_applications": true
}

PowerShell Connect to FTP server and get files

For retrieving files /folder from FTP via powerShell I wrote some functions, you can get even hidden stuff from FTP.

Example for getting all files which are not hidden in a specific folder:

Get-FtpChildItem -ftpFolderPath "ftp://myHost.com/root/leaf/" -userName "User" -password "pw" -hidden $false -File

Example for getting all folders(also hidden) in a specific folder:

Get-FtpChildItem -ftpFolderPath"ftp://myHost.com/root/leaf/" -userName "User" -password "pw" -Directory

You can just copy the functions from the following module without needing and 3rd library installing: https://github.com/AstralisSomnium/PowerShell-No-Library-Just-Functions/blob/master/FTPModule.ps1

How to execute a raw update sql with dynamic binding in rails

ActiveRecord::Base.connection has a quote method that takes a string value (and optionally the column object). So you can say this:

ActiveRecord::Base.connection.execute(<<-EOQ)
  UPDATE  foo
  SET     bar = #{ActiveRecord::Base.connection.quote(baz)}
EOQ

Note if you're in a Rails migration or an ActiveRecord object you can shorten that to:

connection.execute(<<-EOQ)
  UPDATE  foo
  SET     bar = #{connection.quote(baz)}
EOQ

UPDATE: As @kolen points out, you should use exec_update instead. This will handle the quoting for you and also avoid leaking memory. The signature works a bit differently though:

connection.exec_update(<<-EOQ, "SQL", [[nil, baz]])
  UPDATE  foo
  SET     bar = $1
EOQ

Here the last param is a array of tuples representing bind parameters. In each tuple, the first entry is the column type and the second is the value. You can give nil for the column type and Rails will usually do the right thing though.

There are also exec_query, exec_insert, and exec_delete, depending on what you need.

Preventing SQL injection in Node.js

The library has a section in the readme about escaping. It's Javascript-native, so I do not suggest switching to node-mysql-native. The documentation states these guidelines for escaping:

Edit: node-mysql-native is also a pure-Javascript solution.

  • Numbers are left untouched
  • Booleans are converted to true / false strings
  • Date objects are converted to YYYY-mm-dd HH:ii:ss strings
  • Buffers are converted to hex strings, e.g. X'0fa5'
  • Strings are safely escaped
  • Arrays are turned into list, e.g. ['a', 'b'] turns into 'a', 'b'
  • Nested arrays are turned into grouped lists (for bulk inserts), e.g. [['a', 'b'], ['c', 'd']] turns into ('a', 'b'), ('c', 'd')
  • Objects are turned into key = 'val' pairs. Nested objects are cast to strings.
  • undefined / null are converted to NULL
  • NaN / Infinity are left as-is. MySQL does not support these, and trying to insert them as values will trigger MySQL errors until they implement support.

This allows for you to do things like so:

var userId = 5;
var query = connection.query('SELECT * FROM users WHERE id = ?', [userId], function(err, results) {
  //query.sql returns SELECT * FROM users WHERE id = '5'
});

As well as this:

var post  = {id: 1, title: 'Hello MySQL'};
var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
  //query.sql returns INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
});

Aside from those functions, you can also use the escape functions:

connection.escape(query);
mysql.escape(query);

To escape query identifiers:

mysql.escapeId(identifier);

And as a response to your comment on prepared statements:

From a usability perspective, the module is great, but it has not yet implemented something akin to PHP's Prepared Statements.

The prepared statements are on the todo list for this connector, but this module at least allows you to specify custom formats that can be very similar to prepared statements. Here's an example from the readme:

connection.config.queryFormat = function (query, values) {
  if (!values) return query;
  return query.replace(/\:(\w+)/g, function (txt, key) {
    if (values.hasOwnProperty(key)) {
      return this.escape(values[key]);
    }
    return txt;
  }.bind(this));
};

This changes the query format of the connection so you can use queries like this:

connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" });
//equivalent to
connection.query("UPDATE posts SET title = " + mysql.escape("Hello MySQL");

Is It Possible to NSLog C Structs (Like CGRect or CGPoint)?

You can try this:

NSLog(@"%@", NSStringFromCGPoint(cgPoint));

There are a number of functions provided by UIKit that convert the various CG structs into NSStrings. The reason it doesn't work is because %@ signifies an object. A CGPoint is a C struct (and so are CGRects and CGSizes).

Installing NumPy via Anaconda in Windows

The above answers seem to resolve the issue. If it doesn't, then you may also try to update conda using the following command.

conda update conda

And then try to install numpy using

conda install numpy

How can I convert a .jar to an .exe?

Launch4j works on both Windows and Linux/Mac. But if you're running Linux/Mac, there is a way to embed your jar into a shell script that performs the autolaunch for you, so you have only one runnable file:

exestub.sh:

#!/bin/sh
MYSELF=`which "$0" 2>/dev/null`
[ $? -gt  0 -a -f "$0" ] && MYSELF="./$0"
JAVA_OPT=""
PROG_OPT=""
# Parse options to determine which ones are for Java and which ones are for the Program
while [ $# -gt 0 ] ; do
    case $1 in
        -Xm*) JAVA_OPT="$JAVA_OPT $1" ;;
        -D*)  JAVA_OPT="$JAVA_OPT $1" ;;
        *)    PROG_OPT="$PROG_OPT $1" ;;
    esac
    shift
done
exec java $JAVA_OPT -jar $MYSELF $PROG_OPT

Then you create your runnable file from your jar:

$ cat exestub.sh myrunnablejar.jar > myrunnable
$ chmod +x myrunnable

It works the same way launch4j works: because a jar has a zip format, which header is located at the end of the file. You can have any header you want (either binary executable or, like here, shell script) and run java -jar <myexe>, as <myexe> is a valid zip/jar file.

Allowed characters in filename

OK, so looking at Comparison of file systems if you only care about the main players file systems:

so any byte except NUL, \, /, :, *, ", <, >, | and you can't have files/folders call . or .. and no control characters (of course).

Mailto links do nothing in Chrome but work in Firefox?

This is because chrome handles the mailto in different way. You can go to chrome://settings/handlers and make sure that which is the default handler. In your case it will be none (i.e. not listed). Now go to gmail.com. You should see something like this when you click on the button beside the bookmark button.

Set mailto in chrome

If you wish to open all email links through gmail then set "Use Gmail". Now when you click on mailto button, chrome will automatically opens in gmail.

How to discard all changes made to a branch?

If you don't want any changes in design and definitely want it to just match a remote's branch, you can also just delete the branch and recreate it:

# Switch to some branch other than design
$ git br -D design
$ git co -b design origin/design            # Will set up design to track origin's design branch

Solving sslv3 alert handshake failure when trying to use a client certificate

Not a definite answer but too much to fit in comments:

I hypothesize they gave you a cert that either has a wrong issuer (although their server could use a more specific alert code for that) or a wrong subject. We know the cert matches your privatekey -- because both curl and openssl client paired them without complaining about a mismatch; but we don't actually know it matches their desired CA(s) -- because your curl uses openssl and openssl SSL client does NOT enforce that a configured client cert matches certreq.CAs.

Do openssl x509 <clientcert.pem -noout -subject -issuer and the same on the cert from the test P12 that works. Do openssl s_client (or check the one you did) and look under Acceptable client certificate CA names; the name there or one of them should match (exactly!) the issuer(s) of your certs. If not, that's most likely your problem and you need to check with them you submitted your CSR to the correct place and in the correct way. Perhaps they have different regimes in different regions, or business lines, or test vs prod, or active vs pending, etc.

If the issuer of your cert does match desiredCAs, compare its subject to the working (test-P12) one: are they in similar format? are there any components in the working one not present in yours? If they allow it, try generating and submitting a new CSR with a subject name exactly the same as the test-P12 one, or as close as you can get, and see if that produces a cert that works better. (You don't have to generate a new key to do this, but if you choose to, keep track of which certs match which keys so you don't get them mixed up.) If that doesn't help look at the certificate extensions with openssl x509 <cert -noout -text for any difference(s) that might reasonably be related to subject authorization, like KeyUsage, ExtendedKeyUsage, maybe Policy, maybe Constraints, maybe even something nonstandard.

If all else fails, ask the server operator(s) what their logs say about the problem, or if you have access look at the logs yourself.

Binding ComboBox SelectedItem using MVVM

<!-- xaml code-->
    <Grid>
        <ComboBox Name="cmbData"    SelectedItem="{Binding SelectedstudentInfo, Mode=OneWayToSource}" HorizontalAlignment="Left" Margin="225,150,0,0" VerticalAlignment="Top" Width="120" DisplayMemberPath="name" SelectedValuePath="id" SelectedIndex="0" />
        <Button VerticalAlignment="Center" Margin="0,0,150,0" Height="40" Width="70" Click="Button_Click">OK</Button>
    </Grid>



        //student Class
        public class Student
        {
            public  int Id { set; get; }
            public string name { set; get; }
        }

        //set 2 properties in MainWindow.xaml.cs Class
        public ObservableCollection<Student> studentInfo { set; get; }
        public Student SelectedstudentInfo { set; get; }

        //MainWindow.xaml.cs Constructor
        public MainWindow()
        {
            InitializeComponent();
            bindCombo();
            this.DataContext = this;
            cmbData.ItemsSource = studentInfo;

        }

        //method to bind cobobox or you can fetch data from database in MainWindow.xaml.cs
        public void bindCombo()
        {
            ObservableCollection<Student> studentList = new ObservableCollection<Student>();
            studentList.Add(new Student { Id=0 ,name="==Select=="});
            studentList.Add(new Student { Id = 1, name = "zoyeb" });
            studentList.Add(new Student { Id = 2, name = "siddiq" });
            studentList.Add(new Student { Id = 3, name = "James" });

              studentInfo=studentList;

        }

        //button click to get selected student MainWindow.xaml.cs
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Student student = SelectedstudentInfo;
            if(student.Id ==0)
            {
                MessageBox.Show("select name from dropdown");
            }
            else
            {
                MessageBox.Show("Name :"+student.name + "Id :"+student.Id);
            }
        }

Get list of all tables in Oracle?

For better viewing with sqlplus

If you're using sqlplus you may want to first set up a few parameters for nicer viewing if your columns are getting mangled (these variables should not persist after you exit your sqlplus session ):

set colsep '|'
set linesize 167
set pagesize 30
set pagesize 1000

Show All Tables

You can then use something like this to see all table names:

SELECT table_name, owner, tablespace_name FROM all_tables;

Show Tables You Own

As @Justin Cave mentions, you can use this to show only tables that you own:

SELECT table_name FROM user_tables;

Don't Forget about Views

Keep in mind that some "tables" may actually be "views" so you can also try running something like:

SELECT view_name FROM all_views;

The Results

This should yield something that looks fairly acceptable like:

result

Could pandas use column as index?

Yes, with set_index you can make Locality your row index.

data.set_index('Locality', inplace=True)

If inplace=True is not provided, set_index returns the modified dataframe as a result.

Example:

> import pandas as pd
> df = pd.DataFrame([['ABBOTSFORD', 427000, 448000],
                     ['ABERFELDIE', 534000, 600000]],
                    columns=['Locality', 2005, 2006])

> df
     Locality    2005    2006
0  ABBOTSFORD  427000  448000
1  ABERFELDIE  534000  600000

> df.set_index('Locality', inplace=True)
> df
              2005    2006
Locality                  
ABBOTSFORD  427000  448000
ABERFELDIE  534000  600000

> df.loc['ABBOTSFORD']
2005    427000
2006    448000
Name: ABBOTSFORD, dtype: int64

> df.loc['ABBOTSFORD'][2005]
427000

> df.loc['ABBOTSFORD'].values
array([427000, 448000])

> df.loc['ABBOTSFORD'].tolist()
[427000, 448000]

Enable CORS in fetch api

Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors at your server side.

You can fetch request using mode: 'cors'. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.

So in both condition you need to configure cors in your server or you need to use custom proxy server.

how to set cursor style to pointer for links without hrefs

in your css file add this....

a:hover {
 cursor:pointer;
}

if you don't have a css file, add this to the HEAD of your HTML page

<style type="text/css">
 a:hover {
  cursor:pointer;
 }
</style>

also you can use the href="" attribute by returning false at the end of your javascript.

<a href="" onclick="doSomething(); return false;">a link</a>

this is good for many reasons. SEO or if people don't have javascript, the href="" will work. e.g.

<a href="nojavascriptpage.html" onclick="doSomething(); return false;">a link</a>

@see http://www.alistapart.com/articles/behavioralseparation

Edit: Worth noting @BalusC's answer where he mentions :hover is not necessary for the OP's use case. Although other style can be add with the :hover selector.

How the int.TryParse actually works

Check this simple program to understand int.TryParse

 class Program
 {
    static void Main()
    {
        string str = "7788";
        int num1;
        bool n = int.TryParse(str, out num1);
        Console.WriteLine(num1);
        Console.ReadLine();
    }
}

Output is : 7788

ReactJS: Warning: setState(...): Cannot update during an existing state transition

From react docs Passing arguments to event handlers

<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>

How to declare string constants in JavaScript?

So many ways to skin this cat. You can do this in a closure. This code will give you a read-only , namespaced way to have constants. Just declare them in the Public area.

//Namespaced Constants
var MyAppName;
//MyAppName Namespace
(function (MyAppName) {
    //MyAppName.Constants Namespace
    (function (Constants) {
        //Private
        function createConstant(name, val) {
            Object.defineProperty(MyAppName.Constants, name, {
                value: val,
                writable: false
            });
        }

        //Public
        Constants.FOO = createConstant("FOO", 1);
        Constants.FOO2 = createConstant("FOO2", 1);

        MyAppName.Constants = Constants;
    })(MyAppName.Constants || (MyAppName.Constants = {}));
})(MyAppName || (MyAppName = {}));

Usage:

console.log(MyAppName.Constants.FOO);       //prints 1
MyAppName.Constants.FOO = 2;
console.log(MyAppName.Constants.FOO);       //does not change - still prints 1

Is it possible to get the current spark context settings in PySpark?

Suppose I want to increase the driver memory in runtime using Spark Session:

s2 = SparkSession.builder.config("spark.driver.memory", "29g").getOrCreate()

Now I want to view the updated settings:

s2.conf.get("spark.driver.memory")

To get all the settings, you can make use of spark.sparkContext._conf.getAll()

UPDATED SETTINGS

Hope this helps

Change Color of Fonts in DIV (CSS)

Your first CSS selector—social.h2—is looking for the "social" element in the "h2", class, e.g.:

<social class="h2">

Class selectors are proceeded with a dot (.). Also, use a space () to indicate that one element is inside of another. To find an <h2> descendant of an element in the social class, try something like:

.social h2 {
  color: pink;
  font-size: 14px;
}

To get a better understanding of CSS selectors and how they are used to reference your HTML, I suggest going through the interactive HTML and CSS tutorials from CodeAcademy. I hope that this helps point you in the right direction.

Does file_get_contents() have a timeout setting?

The default timeout is defined by default_socket_timeout ini-setting, which is 60 seconds. You can also change it on the fly:

ini_set('default_socket_timeout', 900); // 900 Seconds = 15 Minutes

Another way to set a timeout, would be to use stream_context_create to set the timeout as HTTP context options of the HTTP stream wrapper in use:

$ctx = stream_context_create(array('http'=>
    array(
        'timeout' => 1200,  //1200 Seconds is 20 Minutes
    )
));

echo file_get_contents('http://example.com/', false, $ctx);

Access to file download dialog in Firefox

I didnt unserstood your objective, Do you wanted your test to automatically download file when test is getting executed, if yes, then You need to use custom Firefox profile in your test execution.

In the custom profile, for first time execute test manually and if download dialog comes, the set it Save it to Disk, also check Always perform this action checkbox which will ensure that file automatically get downloaded next time you run your test.

Excluding directory when creating a .tar.gz file

tar -pczf <target_file.tar.gz> --exclude /path/to/exclude --exclude /another/path/to/exclude/* /path/to/include/ /another/path/to/include/*

Tested in Ubuntu 19.10.

  1. The = after exclude is optional. You can use = instead of space after keyword exclude if you like.
  2. Parameter exclude must be placed before the source.
  3. The difference between use folder name (like the 1st) or the * (like the 2nd) is: the 2nd one will include an empty folder in package but the 1st will not.

Formatting struct timespec

I wanted to ask the same question. Here is my current solution to obtain a string like this: 2013-02-07 09:24:40.749355372 I am not sure if there is a more straight forward solution than this, but at least the string format is freely configurable with this approach.

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

#define NANO 1000000000L

// buf needs to store 30 characters
int timespec2str(char *buf, uint len, struct timespec *ts) {
    int ret;
    struct tm t;

    tzset();
    if (localtime_r(&(ts->tv_sec), &t) == NULL)
        return 1;

    ret = strftime(buf, len, "%F %T", &t);
    if (ret == 0)
        return 2;
    len -= ret - 1;

    ret = snprintf(&buf[strlen(buf)], len, ".%09ld", ts->tv_nsec);
    if (ret >= len)
        return 3;

    return 0;
}

int main(int argc, char **argv) {
    clockid_t clk_id = CLOCK_REALTIME;
    const uint TIME_FMT = strlen("2012-12-31 12:59:59.123456789") + 1;
    char timestr[TIME_FMT];

    struct timespec ts, res;
    clock_getres(clk_id, &res);
    clock_gettime(clk_id, &ts);

    if (timespec2str(timestr, sizeof(timestr), &ts) != 0) {
        printf("timespec2str failed!\n");
        return EXIT_FAILURE;
    } else {
        unsigned long resol = res.tv_sec * NANO + res.tv_nsec;
        printf("CLOCK_REALTIME: res=%ld ns, time=%s\n", resol, timestr);
        return EXIT_SUCCESS;
    }
}

output:

gcc mwe.c -lrt 
$ ./a.out 
CLOCK_REALTIME: res=1 ns, time=2013-02-07 13:41:17.994326501

Padding or margin value in pixels as integer using jQuery

You can just grab them as with any CSS attribute:

alert($("#mybox").css("padding-right"));
alert($("#mybox").css("margin-bottom"));

You can set them with a second attribute in the css method:

$("#mybox").css("padding-right", "20px");

EDIT: If you need just the pixel value, use parseInt(val, 10):

parseInt($("#mybox").css("padding-right", "20px"), 10);

CodeIgniter PHP Model Access "Unable to locate the model you have specified"

Changing the name of model name starting with Uppercase works. Example : Login_model.php instead of login_model.php

What does the DOCKER_HOST variable do?

It points to the docker host! I followed these steps:

$ boot2docker start

Waiting for VM and Docker daemon to start...
..............................
Started.

To connect the Docker client to the Docker daemon, please set:
    export DOCKER_HOST=tcp://192.168.59.103:2375

$ export DOCKER_HOST=tcp://192.168.59.103:2375

$ docker run ubuntu:14.04 /bin/echo 'Hello world'
Unable to find image 'ubuntu:14.04' locally
Pulling repository ubuntu
9cbaf023786c: Download complete 
511136ea3c5a: Download complete 
97fd97495e49: Download complete 
2dcbbf65536c: Download complete 
6a459d727ebb: Download complete 
8f321fc43180: Download complete 
03db2b23cf03: Download complete 
Hello world

See:
http://docs.docker.com/userguide/dockerizing/

How to format numbers?

Use the Number function toFixed and this function to add the commas.

function addCommas(nStr)
{
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}
n = 10000;
r = n.toFixed(2); //10000.00

addCommas(r); // 10,000.00

http://www.mredkj.com/javascript/numberFormat.html

How to get the parent dir location

I think use this is better:

os.path.realpath(__file__).rsplit('/', X)[0]


In [1]: __file__ = "/aParent/templates/blog1/page.html"

In [2]: os.path.realpath(__file__).rsplit('/', 3)[0]
Out[3]: '/aParent'

In [4]: __file__ = "/aParent/templates/blog1/page.html"

In [5]: os.path.realpath(__file__).rsplit('/', 1)[0]
Out[6]: '/aParent/templates/blog1'

In [7]: os.path.realpath(__file__).rsplit('/', 2)[0]
Out[8]: '/aParent/templates'

In [9]: os.path.realpath(__file__).rsplit('/', 3)[0]
Out[10]: '/aParent'

QUERY syntax using cell reference

none of the above answers worked for me. This one did:

=QUERY(Copy!A1:AP, "select AP, E, F, AO where AP="&E1&" ",1)

Sorting A ListView By Column

My solution is a class to sort listView items when you click on column header.

You can specify the type of each column.

listView.ListViewItemSorter = new ListViewColumnSorter();
listView.ListViewItemSorter.ColumnsTypeComparer.Add(0, DateTime);
listView.ListViewItemSorter.ColumnsTypeComparer.Add(1, int);

That's it !

The C# class :

using System.Collections;
using System.Collections.Generic;
using EDV;

namespace System.Windows.Forms
{
    /// <summary>
    /// Cette classe est une implémentation de l'interface 'IComparer' pour le tri des items de ListView. Adapté de http://support.microsoft.com/kb/319401.
    /// </summary>
    /// <remarks>Intégré par EDVariables.</remarks>
    public class ListViewColumnSorter : IComparer
    {
        /// <summary>
        /// Spécifie la colonne à trier
        /// </summary>
        private int ColumnToSort;
        /// <summary>
        /// Spécifie l'ordre de tri (en d'autres termes 'Croissant').
        /// </summary>
        private SortOrder OrderOfSort;
        /// <summary>
        /// Objet de comparaison ne respectant pas les majuscules et minuscules
        /// </summary>
        private CaseInsensitiveComparer ObjectCompare;

        /// <summary>
        /// Constructeur de classe.  Initialise la colonne sur '0' et aucun tri
        /// </summary>
        public ListViewColumnSorter()
            : this(0, SortOrder.None) { }

        /// <summary>
        /// Constructeur de classe.  Initializes various elements
        /// <param name="columnToSort">Spécifie la colonne à trier</param>
        /// <param name="orderOfSort">Spécifie l'ordre de tri</param>
        /// </summary>
        public ListViewColumnSorter(int columnToSort, SortOrder orderOfSort)
        {
            // Initialise la colonne
            ColumnToSort = columnToSort;

            // Initialise l'ordre de tri
            OrderOfSort = orderOfSort;

            // Initialise l'objet CaseInsensitiveComparer
            ObjectCompare = new CaseInsensitiveComparer();

            // Dictionnaire de comparateurs
            ColumnsComparer = new Dictionary<int, IComparer>();
            ColumnsTypeComparer = new Dictionary<int, Type>();

        }

        /// <summary>
        /// Cette méthode est héritée de l'interface IComparer.  Il compare les deux objets passés en effectuant une comparaison 
        ///qui ne tient pas compte des majuscules et des minuscules.
        /// <br/>Si le comparateur n'existe pas dans ColumnsComparer, CaseInsensitiveComparer est utilisé.
        /// </summary>
        /// <param name="x">Premier objet à comparer</param>
        /// <param name="x">Deuxième objet à comparer</param>
        /// <returns>Le résultat de la comparaison. "0" si équivalent, négatif si 'x' est inférieur à 'y' 
        ///et positif si 'x' est supérieur à 'y'</returns>
        public int Compare(object x, object y)
        {
            int compareResult;
            ListViewItem listviewX, listviewY;

            // Envoit les objets à comparer aux objets ListViewItem
            listviewX = (ListViewItem)x;
            listviewY = (ListViewItem)y;

            if (listviewX.SubItems.Count < ColumnToSort + 1 || listviewY.SubItems.Count < ColumnToSort + 1)
                return 0;

            IComparer objectComparer = null;
            Type comparableType = null;
            if (ColumnsComparer == null || !ColumnsComparer.TryGetValue(ColumnToSort, out objectComparer))
                if (ColumnsTypeComparer == null || !ColumnsTypeComparer.TryGetValue(ColumnToSort, out comparableType))
                    objectComparer = ObjectCompare;

            // Compare les deux éléments
            if (comparableType != null) {
                //Conversion du type
                object valueX = listviewX.SubItems[ColumnToSort].Text;
                object valueY = listviewY.SubItems[ColumnToSort].Text;
                if (!edvTools.TryParse(ref valueX, comparableType) || !edvTools.TryParse(ref valueY, comparableType))
                    return 0;
                compareResult = (valueX as IComparable).CompareTo(valueY);
            }
            else
                compareResult = objectComparer.Compare(listviewX.SubItems[ColumnToSort].Text, listviewY.SubItems[ColumnToSort].Text);

            // Calcule la valeur correcte d'après la comparaison d'objets
            if (OrderOfSort == SortOrder.Ascending) {
                // Le tri croissant est sélectionné, renvoie des résultats normaux de comparaison
                return compareResult;
            }
            else if (OrderOfSort == SortOrder.Descending) {
                // Le tri décroissant est sélectionné, renvoie des résultats négatifs de comparaison
                return (-compareResult);
            }
            else {
                // Renvoie '0' pour indiquer qu'ils sont égaux
                return 0;
            }
        }

        /// <summary>
        /// Obtient ou définit le numéro de la colonne à laquelle appliquer l'opération de tri (par défaut sur '0').
        /// </summary>
        public int SortColumn
        {
            set
            {
                ColumnToSort = value;
            }
            get
            {
                return ColumnToSort;
            }
        }

        /// <summary>
        /// Obtient ou définit l'ordre de tri à appliquer (par exemple, 'croissant' ou 'décroissant').
        /// </summary>
        public SortOrder Order
        {
            set
            {
                OrderOfSort = value;
            }
            get
            {
                return OrderOfSort;
            }
        }

        /// <summary>
        /// Dictionnaire de comparateurs par colonne.
        /// <br/>Pendant le tri, si le comparateur n'existe pas dans ColumnsComparer, CaseInsensitiveComparer est utilisé.
        /// </summary>
        public Dictionary<int, IComparer> ColumnsComparer { get; set; }

        /// <summary>
        /// Dictionnaire de comparateurs par colonne.
        /// <br/>Pendant le tri, si le comparateur n'existe pas dans ColumnsTypeComparer, CaseInsensitiveComparer est utilisé.
        /// </summary>
        public Dictionary<int, Type> ColumnsTypeComparer { get; set; }
    }
}

Initializing a ListView :

    <var>Visual.WIN.ctrlListView.OnShown</var>  : 
    eventSender.Columns.Clear();
    eventSender.SmallImageList = edvWinForm.ImageList16;
    eventSender.ListViewItemSorter = new ListViewColumnSorter();
    var col = eventSender.Columns.Add("Répertoire");
    col.Width = 160;
    col.ImageKey = "Domain";
    col = eventSender.Columns.Add("Fichier");
    col.Width = 180;
    col.ImageKey = "File";
    col = eventSender.Columns.Add("Date");
    col.Width = 120;
    col.ImageKey = "DateTime";
    eventSender.ListViewItemSorter.ColumnsTypeComparer.Add(col.Index, DateTime);
    col = eventSender.Columns.Add("Position");
    col.TextAlign = HorizontalAlignment.Right;
    col.Width = 80;
    col.ImageKey = "Num";
    eventSender.ListViewItemSorter.ColumnsTypeComparer.Add(col.Index, Int32);

Fill a ListView :

<var>Visual.WIN.cmdSearch.OnClick</var>  : 
//non récursif et sans fonction
    ..ctrlListView:Items.Clear();
    ..ctrlListView:Sorting = SortOrder.None;
    var group = ..ctrlListView:Groups.Add(DateTime.Now.ToString()
                , Path.Combine(..cboDir:Text, ..ctrlPattern1:Text) + " contenant " + ..ctrlSearch1:Text);
    var perf =  Environment.TickCount;

    var files = new DirectoryInfo(..cboDir:Text).GetFiles(..ctrlPattern1:Text)
    var search = ..ctrlSearch1:Text;
    var ignoreCase = ..Search.IgnoreCase;
    //var result = new StringBuilder();
    var dirLength : int = ..cboDir:Text.Length;
    var position : int;
    var added : int = 0;
    for(var i : int = 0; i &lt; files.Length; i++){
        var file = files[i];
        if(search == ""
        || (position = File.ReadAllText(file.FullName).IndexOf(String(search)
                            , StringComparison(ignoreCase ? StringComparison.InvariantCultureIgnoreCase : StringComparison.InvariantCulture))) &gt; =0) {

        //  result.AppendLine(file.FullName.Substring(dirLength) + "\tPos : " + pkvFile.Value);
            var item = ..ctrlListView:Items.Add(file.FullName.Substring(dirLength));
            item.SubItems.Add(file.Name);
            item.SubItems.Add(File.GetLastWriteTime(file.FullName).ToString());
            item.SubItems.Add(position.ToString("# ### ##0"));
            item.Group = group;
            ++added;
        }
    }
    group.Header += " : " + added + "/" + files.Length + " fichier(s)"
                + "  en " + (Environment.TickCount - perf).ToString("# ##0 msec");

On ListView column click :

<var>Visual.WIN.ctrlListView.OnColumnClick</var>  : 
// Déterminer si la colonne sélectionnée est déjà la colonne triée.
var sorter = eventSender.ListViewItemSorter;
if ( eventArgs.Column == sorter .SortColumn )
{
    // Inverser le sens de tri en cours pour cette colonne.
    if (sorter.Order == SortOrder.Ascending)
    {
        sorter.Order = SortOrder.Descending;
    }
    else
    {
        sorter.Order = SortOrder.Ascending;
    }
}
else
{
    // Définir le numéro de colonne à trier ; par défaut sur croissant.
    sorter.SortColumn = eventArgs.Column;
    sorter.Order = SortOrder.Ascending;
}

// Procéder au tri avec les nouvelles options.
eventSender.Sort();

Function edvTools.TryParse used above

class edvTools {
    /// <summary>
    /// Tente la conversion d'une valeur suivant un type EDVType
    /// </summary>
    /// <param name="pValue">Référence de la valeur à convertir</param>
    /// <param name="pType">Type EDV en sortie</param>
    /// <returns></returns>
    public static bool TryParse(ref object pValue, System.Type pType)
    {
        int lIParsed;
        double lDParsed;
        string lsValue;
        if (pValue == null) return false;
        if (pType.Equals(typeof(bool))) {
            bool lBParsed;
            if (pValue is bool) return true;
            if (double.TryParse(pValue.ToString(), out lDParsed)) {
                pValue = lDParsed != 0D;
                return true;
            }
            if (bool.TryParse(pValue.ToString(), out lBParsed)) {
                pValue = lBParsed;
                return true;
            }
            else
                return false;
        }
        if (pType.Equals(typeof(Double))) {
            if (pValue is Double) return true;
            if (double.TryParse(pValue.ToString(), out lDParsed)
                || double.TryParse(pValue.ToString().Replace(NumberDecimalSeparatorNOT, NumberDecimalSeparator), out lDParsed)) {
                pValue = lDParsed;
                return true;
            }
            else
                return false;
        }
        if (pType.Equals(typeof(int))) {
            if (pValue is int) return true;
            if (Int32.TryParse(pValue.ToString(), out lIParsed)) {
                pValue = lIParsed;
                return true;
            }
            else if (double.TryParse(pValue.ToString(), out lDParsed)) {
                pValue = (int)lDParsed;
                return true;
            }
            else
                return false;
        }
        if (pType.Equals(typeof(Byte))) {
            if (pValue is byte) return true;
            byte lByte;
            if (Byte.TryParse(pValue.ToString(), out lByte)) {
                pValue = lByte;
                return true;
            }
            else if (double.TryParse(pValue.ToString(), out lDParsed)) {
                pValue = (byte)lDParsed;
                return true;
            }
            else
                return false;
        }
        if (pType.Equals(typeof(long))) {
            long lLParsed;
            if (pValue is long) return true;
            if (long.TryParse(pValue.ToString(), out lLParsed)) {
                pValue = lLParsed;
                return true;
            }
            else if (double.TryParse(pValue.ToString(), out lDParsed)) {
                pValue = (long)lDParsed;
                return true;
            }
            else
                return false;
        }
        if (pType.Equals(typeof(Single))) {
            if (pValue is float) return true;
            Single lSParsed;
            if (Single.TryParse(pValue.ToString(), out lSParsed)
                || Single.TryParse(pValue.ToString().Replace(NumberDecimalSeparatorNOT, NumberDecimalSeparator), out lSParsed)) {
                pValue = lSParsed;
                return true;
            }
            else
                return false;
        }
        if (pType.Equals(typeof(DateTime))) {
            if (pValue is DateTime) return true;
            DateTime lDTParsed;
            if (DateTime.TryParse(pValue.ToString(), out lDTParsed)) {
                pValue = lDTParsed;
                return true;
            }
            else if (pValue.ToString().Contains("UTC")) //Date venant de JScript
            {
                if (_MonthsUTC == null) InitMonthsUTC();
                string[] lDateParts = pValue.ToString().Split(' ');
                lDTParsed = new DateTime(int.Parse(lDateParts[5]), _MonthsUTC[lDateParts[1]], int.Parse(lDateParts[2]));
                lDateParts = lDateParts[3].ToString().Split(':');
                pValue = lDTParsed.AddSeconds(int.Parse(lDateParts[0]) * 3600 + int.Parse(lDateParts[1]) * 60 + int.Parse(lDateParts[2]));
                return true;
            }
            else
                return false;

        }
        if (pType.Equals(typeof(Array))) {
            if (pValue is System.Collections.ICollection || pValue is System.Collections.ArrayList)
                return true;
            return pValue is System.Data.DataTable
                || pValue is string && (pValue as string).StartsWith("<");
        }
        if (pType.Equals(typeof(DataTable))) {
            return pValue is System.Data.DataTable
                || pValue is string && (pValue as string).StartsWith("<");

        }
        if (pType.Equals(typeof(System.Drawing.Bitmap))) {
            return pValue is System.Drawing.Image || pValue is byte[];

        }
        if (pType.Equals(typeof(System.Drawing.Image))) {
            return pValue is System.Drawing.Image || pValue is byte[];

        }
        if (pType.Equals(typeof(System.Drawing.Color))) {
            if (pValue is System.Drawing.Color) return true;
            if (pValue is System.Drawing.KnownColor) {
                pValue = System.Drawing.Color.FromKnownColor((System.Drawing.KnownColor)pValue);
                return true;
            }

            int lARGB;
            if (!int.TryParse(lsValue = pValue.ToString(), out lARGB)) {
                if (lsValue.StartsWith("Color [A=", StringComparison.InvariantCulture)) {
                    foreach (string lsARGB in lsValue.Substring("Color [".Length, lsValue.Length - "Color []".Length).Split(','))
                        switch (lsARGB.TrimStart().Substring(0, 1)) {
                            case "A":
                                lARGB = int.Parse(lsARGB.Substring(2)) * 0x1000000;
                                break;
                            case "R":
                                lARGB += int.Parse(lsARGB.TrimStart().Substring(2)) * 0x10000;
                                break;
                            case "G":
                                lARGB += int.Parse(lsARGB.TrimStart().Substring(2)) * 0x100;
                                break;
                            case "B":
                                lARGB += int.Parse(lsARGB.TrimStart().Substring(2));
                                break;
                            default:
                                break;
                        }
                    pValue = System.Drawing.Color.FromArgb(lARGB);
                    return true;
                }
                if (lsValue.StartsWith("Color [", StringComparison.InvariantCulture)) {
                    pValue = System.Drawing.Color.FromName(lsValue.Substring("Color [".Length, lsValue.Length - "Color []".Length));
                    return true;
                }
                return false;
            }
            pValue = System.Drawing.Color.FromArgb(lARGB);
            return true;
        }
        if (pType.IsEnum) {
            try {
                if (pValue == null) return false;
                if (pValue is int || pValue is byte || pValue is ulong || pValue is long || pValue is double)
                    pValue = Enum.ToObject(pType, pValue);
                else
                    pValue = Enum.Parse(pType, pValue.ToString());
            }
            catch {
                return false;
            }
        }
        return true;
    }
}

How to animate button in android?

I can't comment on @omega's comment because I don't have enough reputation but the answer to that question should be something like:

shake.xml

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="100"          <!-- how long the animation lasts -->
    android:fromDegrees="-5"        <!-- how far to swing left -->
    android:pivotX="50%"            <!-- pivot from horizontal center -->
    android:pivotY="50%"            <!-- pivot from vertical center -->
    android:repeatCount="10"        <!-- how many times to swing back and forth -->
    android:repeatMode="reverse"    <!-- to make the animation go the other way -->
    android:toDegrees="5" />        <!-- how far to swing right -->

Class.java

Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
view.startAnimation(shake);

This is just one way of doing what you want, there may be better methods out there.

How to find the users list in oracle 11g db?

You can think of a mysql database as a schema/user in Oracle. If you have the privileges, you can query the DBA_USERS view to see the list of schema.

How do you use $sce.trustAsHtml(string) to replicate ng-bind-html-unsafe in Angular 1.2+

Simply creating a filter will do the trick. (Answered for Angular 1.6)

.filter('trustHtml', [
        '$sce',
        function($sce) {
            return function(value) {
                return $sce.trustAs('html', value);
            }
        }
    ]);

And use this as follow in the html.

<h2 ng-bind-html="someScopeValue | trustHtml"></h2>

Returning the product of a list

One option is to use numba and the @jit or @njit decorator. I also made one or two little tweaks to your code (at least in Python 3, "list" is a keyword that shouldn't be used for a variable name):

@njit
def njit_product(lst):
    p = lst[0]  # first element
    for i in lst[1:]:  # loop over remaining elements
        p *= i
    return p

For timing purposes, you need to run once to compile the function first using numba. In general, the function will be compiled the first time it is called, and then called from memory after that (faster).

njit_product([1, 2])  # execute once to compile

Now when you execute your code, it will run with the compiled version of the function. I timed them using a Jupyter notebook and the %timeit magic function:

product(b)  # yours
# 32.7 µs ± 510 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

njit_product(b)
# 92.9 µs ± 392 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Note that on my machine, running Python 3.5, the native Python for loop was actually the fastest. There may be a trick here when it comes to measuring numba-decorated performance with Jupyter notebooks and the %timeit magic function. I am not sure that the timings above are correct, so I recommend trying it out on your system and seeing if numba gives you a performance boost.

What are the most useful Intellij IDEA keyboard shortcuts?

Help\Productivity Guide

It tells you what are the shortcuts you use/don't use and displays usage statistics. It will guide you to the unknown features.

Batch command to move files to a new directory

this will also work, if you like

 xcopy  C:\Test\Log "c:\Test\Backup-%date:~4,2%-%date:~7,2%-%date:~10,4%_%time:~0,2%%time:~3,2%" /s /i
 del C:\Test\Log

java.sql.SQLException: Incorrect string value: '\xF0\x9F\x91\xBD\xF0\x9F...'

Weirdly, I found that REMOVING &characterEncoding=UTF-8 from the JDBC url did the trick for me with similar issues.

Based on my properties,

jdbc_url=jdbc:mysql://localhost:3306/dbName?useUnicode=true

I think this supports what @Esailija has said above, i.e. my MySQL, which is indeed 5.5, is figuring out its own favorite flavor of UTF-8 encoding.

(Note, I'm also specifying the InputStream I'm reading from as UTF-8 in the java code, which probably doesn't hurt)...

What is stdClass in PHP?

Actually I tried creating empty stdClass and compared the speed to empty class.

class emp{}

then proceeded creating 1000 stdClasses and emps... empty classes were done in around 1100 microseconds while stdClasses took over 1700 microseconds. So I guess its better to create your own dummy class for storing data if you want to use objects for that so badly (arrays are a lot faster for both writing and reading).

What is the python keyword "with" used for?

In python the with keyword is used when working with unmanaged resources (like file streams). It is similar to the using statement in VB.NET and C#. It allows you to ensure that a resource is "cleaned up" when the code that uses it finishes running, even if exceptions are thrown. It provides 'syntactic sugar' for try/finally blocks.

From Python Docs:

The with statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.

The with statement is a control-flow structure whose basic structure is:

with expression [as variable]:
    with-block

The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has __enter__() and __exit__() methods).

Update fixed VB callout per Scott Wisniewski's comment. I was indeed confusing with with using.

Spring can you autowire inside an abstract class?

What if you need any database operation in SuperGirl you would inject it again into SuperGirl.

I think the main idea is using the same object reference in different classes. So what about this:

//There is no annotation about Spring in the abstract part.
abstract class SuperMan {


    private final DatabaseService databaseService;

    public SuperMan(DatabaseService databaseService) {
     this.databaseService = databaseService;
    }

    abstract void Fly();

    protected void doSuperPowerAction(Thing thing) {

        //busy code

        databaseService.save(thing);

    }
}

@Component
public class SuperGirl extends SuperMan {

private final DatabaseService databaseService;

@Autowired
public SuperGirl (DatabaseService databaseService) {
     super(databaseService);
     this.databaseService = databaseService;
    }

@Override
public void Fly() {
    //busy code
}

public doSomethingSuperGirlDoes() {

    //busy code

    doSuperPowerAction(thing)

}

In my opinion, inject once run everywhere :)

jQuery set checkbox checked

Dude try below code :

$("div.row-form input[type='checkbox']").attr('checked','checked')

OR

$("div.row-form #estado_cat").attr("checked","checked");

OR

$("div.row-form #estado_cat").attr("checked",true);

What are some reasons for jquery .focus() not working?

Try something like this when you are applying focus that way if the element is hidden, it won't throw an error:

$("#elementid").filter(':visible').focus();

It may make more sense to make the element visible, though that will require code specific to your layout.

Read response headers from API response - Angular 5 + TypeScript

You can get headers using below code

let main_headers = {}
this.http.post(url,
  {email: this.username, password: this.password},
  {'headers' : new HttpHeaders ({'Content-Type' : 'application/json'}), 'responseType': 'text', observe:'response'})
  .subscribe(response => {
    const keys = response.headers.keys();
    let headers = keys.map(key => {
      `${key}: ${response.headers.get(key)}`
        main_headers[key] = response.headers.get(key)
       }
      );
  });

later we can get the required header form the json object.

header_list['X-Token']

How can you dynamically create variables via a while loop?

vars()['meta_anio_2012'] = 'translate'

get Context in non-Activity class

If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows:

class YourNonActivityClass{

// variable to hold context
private Context context;

//save the context recievied via constructor in a local variable

public YourNonActivityClass(Context context){
    this.context=context;
}

}

You can create instance of this class from the activity as follows:

new YourNonActivityClass(this);

Function names in C++: Capitalize or not?

There isn't a 'correct way'. They're all syntactically correct, though there are some conventions. You could follow the Google style guide, although there are others out there.

From said guide:

Regular functions have mixed case; accessors and mutators match the name of the variable: MyExcitingFunction(), MyExcitingMethod(), my_exciting_member_variable(), set_my_exciting_member_variable().

Using local makefile for CLion instead of CMake

I am not very familiar with CMake and could not use Mondkin's solution directly.

Here is what I came up with in my CMakeLists.txt using the latest version of CLion (1.2.4) and MinGW on Windows (I guess you will just need to replace all: g++ mytest.cpp -o bin/mytest by make if you are not using the same setup):

cmake_minimum_required(VERSION 3.3)
project(mytest)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

add_custom_target(mytest ALL COMMAND mingw32-make WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})

And the custom Makefile is like this (it is located at the root of my project and generates the executable in a bin directory):

all:
    g++ mytest.cpp -o bin/mytest

I am able to build the executable and errors in the log window are clickable.

Hints in the IDE are quite limited through, which is a big limitation compared to pure CMake projects...

How to get the nvidia driver version from the command line?

Windows version:

cd \Program Files\NVIDIA Corporation\NVSMI

nvidia-smi

Draw a curve with css

You could use an asymmetrical border to make curves with CSS.

border-radius: 50%/100px 100px 0 0;

VIEW DEMO

_x000D_
_x000D_
.box {_x000D_
  width: 500px; _x000D_
  height: 100px;  _x000D_
  border: solid 5px #000;_x000D_
  border-color: #000 transparent transparent transparent;_x000D_
  border-radius: 50%/100px 100px 0 0;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
_x000D_
_x000D_

What USB driver should we use for the Nexus 5?

I had similar problems as people here with Nexus 5 on Windows 7. No .inf file edits were needed, my computer was stuck on an old version of the Google USB drivers (7.0.0.1). Windows 7 refused to install the newer version even if I tried to manually select the directory or .inf file. Had to manually delete specific cached .inf files in WINDOWS\inf folder, follow directions here: http://code.google.com/p/android/issues/detail?id=62365#c7

Also be sure USB debugging is turned on in developer options. There's a trick to expose the developer options, click 7 times on the build number at the bottom of the "About Phone" information!

How do I update Anaconda?

Open "command or conda prompt" and run:

conda update conda
conda update anaconda

It's a good idea to run both command twice (one after the other) to be sure that all the basic files are updated.

This should put you back on the latest 'releases', which contains packages that are selected by the people at Continuum to work well together.

If you want the last version of each package run (this can lead to an unstable environment):

conda update --all 

Hope this helps.

Sources:

How to mock private method for testing using PowerMock?

With no argument:

ourObject = PowerMockito.spy(new OurClass());
when(ourObject , "ourPrivateMethodName").thenReturn("mocked result");

With String argument:

ourObject = PowerMockito.spy(new OurClass());
when(ourObject, method(OurClass.class, "ourPrivateMethodName", String.class))
                .withArguments(anyString()).thenReturn("mocked result");