Programs & Examples On #Presentmodalviewcontroller

`presentModalViewController` is a `UIViewController` instance method that presents a modal view controller. This is deprecated as of iOS 6, superseded by `presentViewController`.

iOS: Modal ViewController with transparent background

The solution to this answer using swift would be as follows.

let vc = MyViewController()
vc.view.backgroundColor = UIColor.clear // or whatever color.
vc.modalPresentationStyle = .overCurrentContext
present(vc, animated: true, completion: nil)

presentViewController and displaying navigation bar

try this

     let transition: CATransition = CATransition()
    let timeFunc : CAMediaTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
    transition.duration = 1
    transition.timingFunction = timeFunc
    transition.type = kCATransitionPush
    transition.subtype = kCATransitionFromRight
    self.view.window!.layer.addAnimation(transition, forKey: kCATransition)
    self.presentViewController(vc, animated:true, completion:nil)

How to check if a key exists in Json Object and get its value

JSONObject class has a method named "has". Returns true if this object has a mapping for name. The mapping may be NULL. http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)

Can't install gems on OS X "El Capitan"

Disclaimer: @theTinMan and other Ruby developers often point out not to use sudo when installing gems and point to things like RVM. That's absolutely true when doing Ruby development. Go ahead and use that.

However, many of us just want some binary that happens to be distributed as a gem (e.g. fakes3, cocoapods, xcpretty …). I definitely don't want to bother with managing a separate ruby. Here are your quicker options:

Option 1: Keep using sudo

Using sudo is probably fine if you want these tools to be installed globally.

The problem is that these binaries are installed into /usr/bin, which is off-limits since El Capitan. However, you can install them into /usr/local/bin instead. That's where Homebrew install its stuff, so it probably exists already.

sudo gem install fakes3 -n/usr/local/bin

Gems will be installed into /usr/local/bin and every user on your system can use them if it's in their PATH.

Option 2: Install in your home directory (without sudo)

The following will install gems in ~/.gem and put binaries in ~/bin (which you should then add to your PATH).

gem install fakes3 --user-install -n~/bin

Make it the default

Either way, you can add these parameters to your ~/.gemrc so you don't have to remember them:

gem: -n/usr/local/bin

i.e. echo "gem: -n/usr/local/bin" >> ~/.gemrc

or

gem: --user-install -n~/bin

i.e. echo "gem: --user-install -n~/bin" >> ~/.gemrc

(Tip: You can also throw in --no-document to skip generating Ruby developer documentation.)

Implicit function declarations in C

An implicitly declared function is one that has neither a prototype nor a definition, but is called somewhere in the code. Because of that, the compiler cannot verify that this is the intended usage of the function (whether the count and the type of the arguments match). Resolving the references to it is done after compilation, at link-time (as with all other global symbols), so technically it is not a problem to skip the prototype.

It is assumed that the programmer knows what he is doing and this is the premise under which the formal contract of providing a prototype is omitted.

Nasty bugs can happen if calling the function with arguments of a wrong type or count. The most likely manifestation of this is a corruption of the stack.

Nowadays this feature might seem as an obscure oddity, but in the old days it was a way to reduce the number of header files included, hence faster compilation.

Regular expression to stop at first match

Use of Lazy quantifiers ? with no global flag is the answer.

Eg,

enter image description here

If you had global flag /g then, it would have matched all the lowest length matches as below. enter image description here

Excel: macro to export worksheet as CSV file without leaving my current Excel sheet

For those situations where you need a bit more customisation of the output (separator or decimal symbol), or who have large dataset (over 65k rows), I wrote the following:

Option Explicit

Sub rng2csv(rng As Range, fileName As String, Optional sep As String = ";", Optional decimalSign As String)
'export range data to a CSV file, allowing to chose the separator and decimal symbol
'can export using rng number formatting!
'by Patrick Honorez --- www.idevlop.com
    Dim f As Integer, i As Long, c As Long, r
    Dim ar, rowAr, sOut As String
    Dim replaceDecimal As Boolean, oldDec As String

    Dim a As Application:   Set a = Application

    ar = rng
    f = FreeFile()
    Open fileName For Output As #f

    oldDec = Format(0, ".")     'current client's decimal symbol
    replaceDecimal = (decimalSign <> "") And (decimalSign <> oldDec)

    For Each r In rng.Rows
        rowAr = a.Transpose(a.Transpose(r.Value))
        If replaceDecimal Then
            For c = 1 To UBound(rowAr)
                'use isnumber() to avoid cells with numbers formatted as strings
                If a.IsNumber(rowAr(c)) Then
                    'uncomment the next 3 lines to export numbers using source number formatting
'                    If r.cells(1, c).NumberFormat <> "General" Then
'                        rowAr(c) = Format$(rowAr(c), r.cells(1, c).NumberFormat)
'                    End If
                    rowAr(c) = Replace(rowAr(c), oldDec, decimalSign, 1, 1)
                End If
            Next c
        End If
        sOut = Join(rowAr, sep)
        Print #f, sOut
    Next r
    Close #f

End Sub

Sub export()
    Debug.Print Now, "Start export"
    rng2csv shOutput.Range("a1").CurrentRegion, RemoveExt(ThisWorkbook.FullName) & ".csv", ";", "."
    Debug.Print Now, "Export done"
End Sub

Autocompletion of @author in Intellij

For Intellij IDEA Community 2019.1 you will need to follow these steps :

File -> New -> Edit File Templates.. -> Class -> /* Created by ${USER} on ${DATE} */

How do you merge two Git repositories?

Adjust this shell script for automatic merging two branches.

Android ADB stop application command like "force-stop" for non rooted device

If you want to kill the Sticky Service,the following command NOT WORKING:

adb shell am force-stop <PACKAGE>
adb shell kill <PID>

The following command is WORKING:

adb shell pm disable <PACKAGE>

If you want to restart the app,you must run command below first:

adb shell pm enable <PACKAGE>

How to change value of process.env.PORT in node.js?

For just one run (from the unix shell prompt):

$ PORT=1234 node app.js

More permanently:

$ export PORT=1234
$ node app.js

In Windows:

set PORT=1234

In Windows PowerShell:

$env:PORT = 1234

Why use String.Format?

First, I find

string s = String.Format(
    "Your order {0} will be delivered on {1:yyyy-MM-dd}. Your total cost is {2:C}.",
    orderNumber,
    orderDeliveryDate,
    orderCost
);

far easier to read, write and maintain than

string s = "Your order " +
           orderNumber.ToString() +
           " will be delivered on " +
           orderDeliveryDate.ToString("yyyy-MM-dd") +
           "." +
           "Your total cost is " +
           orderCost.ToString("C") + 
           ".";

Look how much more maintainable the following is

string s = String.Format(
    "Year = {0:yyyy}, Month = {0:MM}, Day = {0:dd}",
    date
);

over the alternative where you'd have to repeat date three times.

Second, the format specifiers that String.Format provides give you great flexibility over the output of the string in a way that is easier to read, write and maintain than just using plain old concatenation. Additionally, it's easier to get culture concerns right with String.Format.

Third, when performance does matter, String.Format will outperform concatenation. Behind the scenes it uses a StringBuilder and avoids the Schlemiel the Painter problem.

Return outside function error in Python

You can only return from inside a function and not from a loop.

It seems like your return should be outside the while loop, and your complete code should be inside a function.

def func():
    N = int(input("enter a positive integer:"))
    counter = 1
    while (N > 0):
        counter = counter * N
        N -= 1
    return counter  # de-indent this 4 spaces to the left.

print func()

And if those codes are not inside a function, then you don't need a return at all. Just print the value of counter outside the while loop.

How do I use the conditional operator (? :) in Ruby?

Easiest way:

param_a = 1
param_b = 2

result = param_a === param_b ? 'Same!' : 'Not same!'

since param_a is not equal to param_b then the result's value will be Not same!

How to select the first row for each group in MySQL?

Yet another way to do it

Select max from group that works in views

SELECT * FROM action a 
WHERE NOT EXISTS (
   SELECT 1 FROM action a2 
   WHERE a2.user_id = a.user_id 
   AND a2.action_date > a.action_date 
   AND a2.action_type = a.action_type
)
AND a.action_type = "CF"

Bootstrap 3 Navbar Collapse

And for those who want to collapse at a width less than the standard 768px (expand at a width less than 768px), this is the css needed:

@media (min-width: 600px) {
.navbar-header {
        float: left;
}
.navbar-toggle {
    display: none;
}
.navbar-collapse {
    border-top: 0 none;
    box-shadow: none;
    width: auto;
}
.navbar-collapse.collapse {
    display: block !important;
    height: auto !important;
    padding-bottom: 0;
    overflow: visible !important;
}
.navbar-nav {
    float: left !important;
    margin: 0;
}
.navbar-nav>li {
    float: left;
}
.navbar-nav>li>a {
    padding-top: 15px;
    padding-bottom: 15px;
}
}

Change visibility of ASP.NET label with JavaScript

If you wait until the page is loaded, and then set the button's display to none, that should work. Then you can make it visible at a later point.

ssh "permissions are too open" error

For me (using the Ubuntu Subsystem for Windows) the error message changed to:

 Permissions 0555 for 'key.pem' are too open

after using chmod 400. It turns out that using root as a default user was the reason.

Change this using the cmd:

 ubuntu config --default-user your_username

What are the differences between Abstract Factory and Factory design patterns?

The main difference between Abstract Factory and Factory Method is that Abstract Factory is implemented by Composition; but Factory Method is implemented by Inheritance.

Yes, you read that correctly: the main difference between these two patterns is the old composition vs inheritance debate.

UML diagrams can be found in the (GoF) book. I want to provide code examples, because I think combining the examples from the top two answers in this thread will give a better demonstration than either answer alone. Additionally, I have used terminology from the book in class and method names.

Abstract Factory

  1. The most important point to grasp here is that the abstract factory is injected into the client. This is why we say that Abstract Factory is implemented by Composition. Often, a dependency injection framework would perform that task; but a framework is not required for DI.
  2. The second critical point is that the concrete factories here are not Factory Method implementations! Example code for Factory Method is shown further below.
  3. And finally, the third point to note is the relationship between the products: in this case the outbound and reply queues. One concrete factory produces Azure queues, the other MSMQ. The GoF refers to this product relationship as a "family" and it's important to be aware that family in this case does not mean class hierarchy.
public class Client {
    private final AbstractFactory_MessageQueue factory;

    public Client(AbstractFactory_MessageQueue factory) {
        // The factory creates message queues either for Azure or MSMQ.
        // The client does not know which technology is used.
        this.factory = factory;
    }

    public void sendMessage() {
        //The client doesn't know whether the OutboundQueue is Azure or MSMQ.
        OutboundQueue out = factory.createProductA();
        out.sendMessage("Hello Abstract Factory!");
    }

    public String receiveMessage() {
        //The client doesn't know whether the ReplyQueue is Azure or MSMQ.
        ReplyQueue in = factory.createProductB();
        return in.receiveMessage();
    }
}

public interface AbstractFactory_MessageQueue {
    OutboundQueue createProductA();
    ReplyQueue createProductB();
}

public class ConcreteFactory_Azure implements AbstractFactory_MessageQueue {
    @Override
    public OutboundQueue createProductA() {
        return new AzureMessageQueue();
    }

    @Override
    public ReplyQueue createProductB() {
        return new AzureResponseMessageQueue();
    }
}

public class ConcreteFactory_Msmq implements AbstractFactory_MessageQueue {
    @Override
    public OutboundQueue createProductA() {
        return new MsmqMessageQueue();
    }

    @Override
    public ReplyQueue createProductB() {
        return new MsmqResponseMessageQueue();
    }
}

Factory Method

  1. The most important point to grasp here is that the ConcreteCreator is the client. In other words, the client is a subclass whose parent defines the factoryMethod(). This is why we say that Factory Method is implemented by Inheritance.
  2. The second critical point is to remember that the Factory Method Pattern is nothing more than a specialization of the Template Method Pattern. The two patterns share an identical structure. They only differ in purpose. Factory Method is creational (it builds something) whereas Template Method is behavioral (it computes something).
  3. And finally, the third point to note is that the Creator (parent) class invokes its own factoryMethod(). If we remove anOperation() from the parent class, leaving only a single method behind, it is no longer the Factory Method pattern. In other words, Factory Method cannot be implemented with less than two methods in the parent class; and one must invoke the other.
public abstract class Creator {
    public void anOperation() {
        Product p = factoryMethod();
        p.whatever();
    }

    protected abstract Product factoryMethod();
}

public class ConcreteCreator extends Creator {
    @Override
    protected Product factoryMethod() {
        return new ConcreteProduct();
    }
}

Misc. & Sundry Factory Patterns

Be aware that although the GoF define two different Factory patterns, these are not the only Factory patterns in existence. They are not even necessarily the most commonly used Factory patterns. A famous third example is Josh Bloch's Static Factory Pattern from Effective Java. The Head First Design Patterns book includes yet another pattern they call Simple Factory.

Don't fall into the trap of assuming every Factory pattern must match one from the GoF.

Google Text-To-Speech API

Allright, so Google has introduces tokens (see the tk parameter in the new url) and the old solution doesn't seem to work. I've found an alternative - which I even think is better-sounding, and has more voices! The command isn't pretty, but it works. Please note that this is for testing purposes only (I use it for a little domotica project) and use the real version from acapella-group if you're planning on using this commercially.

curl $(curl --data 'MyLanguages=sonid10&MySelectedVoice=Sharon&MyTextForTTS=Hello%20World&t=1&SendToVaaS=' 'http://www.acapela-group.com/demo-tts/DemoHTML5Form_V2.php' | grep -o "http.*mp3") > tts_output.mp3

Some of the supported voices are;

  • Sharon
  • Ella (genuine child voice)
  • EmilioEnglish (genuine child voice)
  • Josh (genuine child voice)
  • Karen
  • Kenny (artificial child voice)
  • Laura
  • Micah
  • Nelly (artificial child voice)
  • Rod
  • Ryan
  • Saul
  • Scott (genuine teenager voice)
  • Tracy
  • ValeriaEnglish (genuine child voice)
  • Will
  • WillBadGuy (emotive voice)
  • WillFromAfar (emotive voice)
  • WillHappy (emotive voice)
  • WillLittleCreature (emotive voice)
  • WillOldMan (emotive voice)
  • WillSad (emotive voice)
  • WillUpClose (emotive voice)

It also supports multiple languages and more voices - for that I refer you to their website; http://www.acapela-group.com/

Is it necessary to write HEAD, BODY and HTML tags?

The Google Style Guide for HTML recommends omitting all optional tags.
That includes <html>, <head>, <body>, <p> and <li>.

https://google.github.io/styleguide/htmlcssguide.html#Optional_Tags

For file size optimization and scannability purposes, consider omitting optional tags. The HTML5 specification defines what tags can be omitted.

(This approach may require a grace period to be established as a wider guideline as it’s significantly different from what web developers are typically taught. For consistency and simplicity reasons it’s best served omitting all optional tags, not just a selection.)

<!-- Not recommended -->
<!DOCTYPE html>
<html>
  <head>
    <title>Spending money, spending bytes</title>
  </head>
  <body>
    <p>Sic.</p>
  </body>
</html>

<!-- Recommended -->
<!DOCTYPE html>
<title>Saving money, saving bytes</title>
<p>Qed.

MySQL - UPDATE query based on SELECT Query

I had an issue with duplicate entries in one table itself. Below is the approaches were working for me. It has also been advocated by @sibaz.

Finally I solved it using the below queries:

  1. The select query is saved in a temp table

    IF OBJECT_ID(N'tempdb..#New_format_donor_temp', N'U') IS NOT NULL
        DROP TABLE #New_format_donor_temp;
    
    select *
    into #New_format_donor_temp
    from DONOR_EMPLOYMENTS
    where DONOR_ID IN (
      1, 2
    )
    
    -- Test New_format_donor_temp
    -- SELECT *
    -- FROM #New_format_donor_temp;
    
  2. The temp table is joined in the update query.

    UPDATE de
    SET STATUS_CD=de_new.STATUS_CD, STATUS_REASON_CD=de_new.STATUS_REASON_CD, TYPE_CD=de_new.TYPE_CD
    FROM DONOR_EMPLOYMENTS AS de
      INNER JOIN #New_format_donor_temp AS de_new ON de_new.EMP_NO = de.EMP_NO
    WHERE
      de.DONOR_ID IN (
        3, 4
    )
    

I not very experienced with SQL please advise any better approach you know.

Above queries are for MySql server.

Getting the IP Address of a Remote Socket Endpoint

RemoteEndPoint is a property, its type is System.Net.EndPoint which inherits from System.Net.IPEndPoint.

If you take a look at IPEndPoint's members, you'll see that there's an Address property.

Android: Align button to bottom-right of screen using FrameLayout?

Setting android:layout_gravity="bottom|right" worked for me

How to file split at a line number

file_name=test.log

# set first K lines:
K=1000

# line count (N): 
N=$(wc -l < $file_name)

# length of the bottom file:
L=$(( $N - $K ))

# create the top of file: 
head -n $K $file_name > top_$file_name

# create bottom of file: 
tail -n $L $file_name > bottom_$file_name

Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so

split -l 300000 file_name

will output xaa with 300k lines and xab with 100k lines, for an input with 400k lines.

C# function to return array

You should return the variable withouth the brackets

Return Labels

Selenium 2.53 not working on Firefox 47

New Selenium libraries are now out, according to: https://github.com/SeleniumHQ/selenium/issues/2110

The download page http://www.seleniumhq.org/download/ seems not to be updated just yet, but by adding 1 to the minor version in the link, I could download the C# version: http://selenium-release.storage.googleapis.com/2.53/selenium-dotnet-2.53.1.zip

It works for me with Firefox 47.0.1.

As a side note, I was able build just the webdriver.xpi Firefox extension from the master branch in GitHub, by running ./go //javascript/firefox-driver:webdriver:run – which gave an error message but did build the build/javascript/firefox-driver/webdriver.xpi file, which I could rename (to avoid a name clash) and successfully load with the FirefoxProfile.AddExtension method. That was a reasonable workaround without having to rebuild the entire Selenium library.

How to restart kubernetes nodes?

You can delete the node from the master by issuing:

kubectl delete node hostname.company.net

The NOTReady status probably means that the master can't access the kubelet service. Check if everything is OK on the client.

How to add an extra row to a pandas dataframe

Try this:

df.loc[len(df)]=['8/19/2014','Jun','Fly','98765'] 

Warning: this method works only if there are no "holes" in the index. For example, suppose you have a dataframe with three rows, with indices 0, 1, and 3 (for example, because you deleted row number 2). Then, len(df) = 3, so by the above command does not add a new row - it overrides row number 3.

Adding link a href to an element using css

You don't need CSS for this.

     <img src="abc"/>

now with link:

     <a href="#myLink"><img src="abc"/></a>

Or with jquery, later on, you can use the wrap property, see these questions answer:

how to add a link to an image using jquery?

After submitting a POST form open a new window showing the result

Simplest working solution for flow window (tested at Chrome):

<form action='...' method=post target="result" onsubmit="window.open('','result','width=800,height=400');">
    <input name="..">
    ....
</form>

How can I remove leading and trailing quotes in SQL Server?

I use this:

UPDATE DataImport
SET PRIO = 
        CASE WHEN LEN(PRIO) < 2 
        THEN 
            (CASE PRIO WHEN '""' THEN '' ELSE PRIO END) 
        ELSE REPLACE(PRIO, '"' + SUBSTRING(PRIO, 2, LEN(PRIO) - 2) + '"', 
            SUBSTRING(PRIO, 2, LEN(PRIO) - 2)) 
        END

Create a directory if it does not exist and then create the files in that directory as well

code:

// Create Directory if not exist then Copy a file.


public static void copyFile_Directory(String origin, String destDir, String destination) throws IOException {

    Path FROM = Paths.get(origin);
    Path TO = Paths.get(destination);
    File directory = new File(String.valueOf(destDir));

    if (!directory.exists()) {
        directory.mkdir();
    }
        //overwrite the destination file if it exists, and copy
        // the file attributes, including the rwx permissions
     CopyOption[] options = new CopyOption[]{
                StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.COPY_ATTRIBUTES

        };
        Files.copy(FROM, TO, options);


}

Android Error [Attempt to invoke virtual method 'void android.app.ActionBar' on a null object reference]

Your code is throwing on com.example.tabwithslidingdrawer.MainActivity.onCreate(MainActivity.java:95):

        // enabling action bar app icon and behaving it as toggle button
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

The problem is pretty simple- your Activity is inheriting from the new android.support.v7.app.ActionBarActivity. You should be using a call to getSupportActionBar() instead of getActionBar().

If you look above around line 65 of your code you'll see that you're already doing that:

        actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        // TODO: Remove the redundant calls to getSupportActionBar()
        //       and use variable actionBar instead
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

And then lower down around line 87 it looks like you figured out the same:

        getSupportActionBar().setTitle(
                        Html.fromHtml("<font color=\"black\">" + mTitle + " - "
                                        + menutitles[0] + "</font>"));
        // getActionBar().setTitle(mTitle +menutitles[0]);

Notice how you commented out getActionBar().

Excel "External table is not in the expected format."

I recently saw this error in a context that didn't match any of the previously listed answers. It turned out to be a conflict with AutoVer. Workaround: temporarily disable AutoVer.

How to select bottom most rows?

It would seem that any of the answers which implement an ORDER BY clause in the solution is missing the point, or does not actually understand what TOP returns to you.

TOP returns an unordered query result set which limits the record set to the first N records returned. (From an Oracle perspective, it is akin to adding a where ROWNUM < (N+1).

Any solution which uses an order, may return rows which also are returned by the TOP clause (since that data set was unordered in the first place), depending on what criteria was used in the order by

The usefulness of TOP is that once the dataset reaches a certain size N, it stops fetching rows. You can get a feel for what the data looks like without having to fetch all of it.

To implement BOTTOM accurately, it would need to fetch the entire dataset unordered and then restrict the dataset to the final N records. That will not be particularly effective if you are dealing with huge tables. Nor will it necessarily give you what you think you are asking for. The end of the data set may not necessarily be "the last rows inserted" (and probably won't be for most DML intensive applications).

Similarly, the solutions which implement an ORDER BY are, unfortunately, potentially disastrous when dealing with large data sets. If I have, say, 10 Billion records and want the last 10, it is quite foolish to order 10 Billion records and select the last 10.

The problem here, is that BOTTOM does not have the meaning that we think of when comparing it to TOP.

When records are inserted, deleted, inserted, deleted over and over and over again, some gaps will appear in the storage and later, rows will be slotted in, if possible. But what we often see, when we select TOP, appears to be sorted data, because it may have been inserted early on in the table's existence. If the table does not experience many deletions, it may appear to be ordered. (e.g. creation dates may be as far back in time as the table creation itself). But the reality is, if this is a delete-heavy table, the TOP N rows may not look like that at all.

So -- the bottom line here(pun intended) is that someone who is asking for the BOTTOM N records doesn't actually know what they're asking for. Or, at least, what they're asking for and what BOTTOM actually means are not the same thing.

So -- the solution may meet the actual business need of the requestor...but does not meet the criteria for being the BOTTOM.

Print a list of all installed node.js modules

in any os

npm -g list

and thats it

Change the class from factor to numeric of many columns in a data frame

Here are some dplyr options:

# by column type:
df %>% 
  mutate_if(is.factor, ~as.numeric(as.character(.)))

# by specific columns:
df %>% 
  mutate_at(vars(x, y, z), ~as.numeric(as.character(.))) 

# all columns:
df %>% 
  mutate_all(~as.numeric(as.character(.))) 

Padding characters in printf

There's no way to pad with anything but spaces using printf. You can use sed:

printf "%-50s@%s\n" $PROC_NAME [UP] | sed -e 's/ /-/g' -e 's/@/ /' -e 's/-/ /'

Add left/right horizontal padding to UILabel

If you need a more specific text alignment than what adding spaces to the left of the text provides, you can always add a second blank label of exactly how much of an indent you need.

I've got buttons with text aligned left with an indent of 10px and needed a label below to look in line. It gave the label with text and left alignment and put it at x=10 and then made a small second label of the same background color with a width = 10, and lined it up next to the real label.

Minimal code and looks good. Just makes AutoLayout a little more of a hassle to get everything working.

Sort a two dimensional array based on one column

Check out the ColumnComparator. It is basically the same solution as proposed by Costi, but it also supports sorting on columns in a List and has a few more sort properties.

Option to ignore case with .contains method?

With a null check on the dvdList and your searchString

    if (!StringUtils.isEmpty(searchString)) {
        return Optional.ofNullable(dvdList)
                       .map(Collection::stream)
                       .orElse(Stream.empty())
                       .anyMatch(dvd >searchString.equalsIgnoreCase(dvd.getTitle()));
      }

RecyclerView vs. ListView

Advantages of RecyclerView over listview :

  1. Contains ViewHolder by default.

  2. Easy animations.

  3. Supports horizontal , grid and staggered layouts

Advantages of listView over recyclerView :

  1. Easy to add divider.

  2. Can use inbuilt arrayAdapter for simple plain lists

  3. Supports Header and footer .

  4. Supports OnItemClickListner .

How to set maximum height for table-cell?

Try

   <td style="word-wrap: break-word">Long text here</td>

powershell is missing the terminator: "

Look closely at the two dashes in

unzipRelease –Src '$ReleaseFile' -Dst '$Destination'

This first one is not a normal dash but an en-dash (&ndash; in HTML). Replace that with the dash found before Dst.

Display all views on oracle database

SELECT * 
FROM DBA_OBJECTS  
WHERE OBJECT_TYPE = 'VIEW'

UEFA/FIFA scores API

http://api.football-data.org/index is free and useful. The API is in active development, stable and recently the first versioned release called alpha was put online. Check the blog section to follow updates and changes.

How to convert InputStream to FileInputStream

You need something like:

    URL resource = this.getClass().getResource("/path/to/resource.res");
    File is = null;
    try {
        is = new File(resource.toURI());
    } catch (URISyntaxException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        FileInputStream input = new FileInputStream(is);
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

But it will work only within your IDE, not in runnable JAR. I had same problem explained here.

jQuery return ajax result into outside variable

You are missing a comma after

'data': { 'request': "", 'target': 'arrange_url', 'method': 'method_target' }

Also, if you want return_first to hold the result of your anonymous function, you need to make a function call:

var return_first = function () {
    var tmp = null;
    $.ajax({
        'async': false,
        'type': "POST",
        'global': false,
        'dataType': 'html',
        'url': "ajax.php?first",
        'data': { 'request': "", 'target': 'arrange_url', 'method': 'method_target' },
        'success': function (data) {
            tmp = data;
        }
    });
    return tmp;
}();

Note () at the end.

raw vs. html_safe vs. h to unescape html

The best safe way is: <%= sanitize @x %>

It will avoid XSS!

How to horizontally center an element

Text-align: center

Applying text-align: center the inline contents are centered within the line box. However since the inner div has by default width: 100% you have to set a specific width or use one of the following:

_x000D_
_x000D_
#inner {
  display: inline-block;
}

#outer {
  text-align: center;
}
_x000D_
<div id="outer">
  <div id="inner">Foo foo</div>
</div>
_x000D_
_x000D_
_x000D_


Margin: 0 auto

Using margin: 0 auto is another option and it is more suitable for older browsers compatibility. It works together with display: table.

_x000D_
_x000D_
#inner {
  display: table;
  margin: 0 auto;
}
_x000D_
<div id="outer">
  <div id="inner">Foo foo</div>
</div>
_x000D_
_x000D_
_x000D_


Flexbox

display: flex behaves like a block element and lays out its content according to the flexbox model. It works with justify-content: center.

Please note: Flexbox is compatible with most of the browsers but not all. See display: flex not working on Internet Explorer for a complete and up to date list of browsers compatibility.

_x000D_
_x000D_
#inner {
  display: inline-block;
}

#outer {
  display: flex;
  justify-content: center;
}
_x000D_
<div id="outer">
  <div id="inner">Foo foo</div>
</div>
_x000D_
_x000D_
_x000D_


Transform

transform: translate lets you modify the coordinate space of the CSS visual formatting model. Using it, elements can be translated, rotated, scaled, and skewed. To center horizontally it require position: absolute and left: 50%.

_x000D_
_x000D_
#inner {
  position: absolute;
  left: 50%;
  transform: translate(-50%, 0%);
}
_x000D_
<div id="outer">
  <div id="inner">Foo foo</div>
</div>
_x000D_
_x000D_
_x000D_


<center> (Deprecated)

The tag <center> is the HTML alternative to text-align: center. It works on older browsers and most of the new ones but it is not considered a good practice since this feature is obsolete and has been removed from the Web standards.

_x000D_
_x000D_
#inner {
  display: inline-block;
}
_x000D_
<div id="outer">
  <center>
    <div id="inner">Foo foo</div>
  </center>
</div>
_x000D_
_x000D_
_x000D_

Using VBA code, how to export Excel worksheets as image in Excel 2003?

There's a more direct way to export a range image to a file, without the need to create a temporary chart. It makes use of PowerShell to save the clipboard as a .png file.

Copying the range to the clipboard as an image is straightforward, using the vba CopyPicture command, as shown in some of the other answers.

A PowerShell script to save the clipboard requires only two lines, as noted by thom schumacher in Save Image from clipboard using PowerShell.

VBA can launch a PowerShell script and wait for it to complete, as noted by Asam in Wait for shell command to complete.

Putting these ideas together, we get the following routine. I've tested this only under Windows 10 using the Office 2010 version of Excel. Note that there's an internal constant AidDebugging which can be set to True to provide additional feedback about the execution of the routine.

Option Explicit

' This routine copies the bitmap image of a range of cells to a .png file.
' Input arguments:
'    RangeRef -- the range to be copied. This must be passed as a range object, not as the name
'                or address of the range.
'    Destination -- the name (including path if necessary) of the file to be created, ending in
'                the extension ".png". It will be overwritten without warning if it exists.
'    TempFile -- the name (including path if necessary) of a temporary script file which will be
'                created and destroyed. If this is not supplied, file "RangeToPNG.ps1" will be
'                created in the default folder. If AidDebugging is set to True, then this file
'                will not be deleted, so it can be inspected for debugging.
' If the PowerShell script file cannot be launched, then this routine will display an error message.
' However, if the script can be launched but cannot create the resulting file, this script cannot
' detect that. To diagnose the problem, change AidDebugging from False to True and inspect the
' PowerShell output, which will remain in view until you close its window.

Public Sub RangeToPNG(RangeRef As Range, Destination As String, _
                      Optional TempFile As String = "RangeToPNG.ps1")
Dim WSH As Object
Dim PSCommand As String
Dim WindowStyle As Integer
Dim ErrorCode As Integer
Const WaitOnReturn = True
Const AidDebugging = False ' provide extra feedback about this routine's execution
  ' Create a little PowerShell script to save the clipboard as a .png file
  ' The script is based on a version found on September 13, 2020 at
  '    https://stackoverflow.com/questions/55215482/save-image-from-clipboard-using-powershell
   Open TempFile For Output As #1
   If (AidDebugging) Then ' output some extra feedback
      Print #1, "Set-PSDebug -Trace 1" ' optional -- aids debugging
   End If
   Print #1, "$img = get-clipboard -format image"
   Print #1, "$img.save(""" & Destination & """)"
   If (AidDebugging) Then ' leave the PowerShell execution record on the screen for review
      Print #1, "Read-Host -Prompt ""Press <Enter> to continue"" "
      WindowStyle = 1 ' display window to aid debugging
   Else
      WindowStyle = 0 ' hide window
   End If
   Close #1
  ' Copy the desired range of cells to the clipboard as a bitmap image
   RangeRef.CopyPicture xlScreen, xlBitmap
  ' Execute the PowerShell script
   PSCommand = "POWERSHELL.exe -ExecutionPolicy Bypass -file """ & TempFile & """ "
   Set WSH = VBA.CreateObject("WScript.Shell")
   ErrorCode = WSH.Run(PSCommand, WindowStyle, WaitOnReturn)
   If (ErrorCode <> 0) Then
      MsgBox "The attempt to run a PowerShell script to save a range " & _
             "as a .png file failed -- error code " & ErrorCode
   End If
   If (Not AidDebugging) Then
     ' Delete the script file, unless it might be useful for debugging
      Kill TempFile
   End If
End Sub

' Here's an example which tests the routine above.
Sub Test()
   RangeToPNG Worksheets("Sheet1").Range("A1:F13"), "E:\Temp\ExportTest.png"
End Sub

How to listen state changes in react.js?

In 2020 you can listen state changes with useEffect hook like this

export function MyComponent(props) {
    const [myState, setMystate] = useState('initialState')

    useEffect(() => {
        console.log(myState, '- Has changed')
    },[myState]) // <-- here put the parameter to listen
}

The page cannot be displayed because an internal server error has occurred on server

it seems it works after I commented this line in web.config

<compilation debug="true" targetFramework="4.5.2" />

How do I find out which process is locking a file using .NET?

This works for DLLs locked by other processes. This routine will not find out for example that a text file is locked by a word process.

C#:

using System.Management; 
using System.IO;   

static class Module1 
{ 
static internal ArrayList myProcessArray = new ArrayList(); 
private static Process myProcess; 

public static void Main() 
{ 

    string strFile = "c:\\windows\\system32\\msi.dll"; 
    ArrayList a = getFileProcesses(strFile); 
    foreach (Process p in a) { 
        Debug.Print(p.ProcessName); 
    } 
} 


private static ArrayList getFileProcesses(string strFile) 
{ 
    myProcessArray.Clear(); 
    Process[] processes = Process.GetProcesses; 
    int i = 0; 
    for (i = 0; i <= processes.GetUpperBound(0) - 1; i++) { 
        myProcess = processes(i); 
        if (!myProcess.HasExited) { 
            try { 
                ProcessModuleCollection modules = myProcess.Modules; 
                int j = 0; 
                for (j = 0; j <= modules.Count - 1; j++) { 
                    if ((modules.Item(j).FileName.ToLower.CompareTo(strFile.ToLower) == 0)) { 
                        myProcessArray.Add(myProcess); 
                        break; // TODO: might not be correct. Was : Exit For 
                    } 
                } 
            } 
            catch (Exception exception) { 
            } 
            //MsgBox(("Error : " & exception.Message)) 
        } 
    } 
    return myProcessArray; 
} 
} 

VB.Net:

Imports System.Management
Imports System.IO

Module Module1
Friend myProcessArray As New ArrayList
Private myProcess As Process

Sub Main()

    Dim strFile As String = "c:\windows\system32\msi.dll"
    Dim a As ArrayList = getFileProcesses(strFile)
    For Each p As Process In a
        Debug.Print(p.ProcessName)
    Next
End Sub


Private Function getFileProcesses(ByVal strFile As String) As ArrayList
    myProcessArray.Clear()
    Dim processes As Process() = Process.GetProcesses
    Dim i As Integer
    For i = 0 To processes.GetUpperBound(0) - 1
        myProcess = processes(i)
        If Not myProcess.HasExited Then
            Try
                Dim modules As ProcessModuleCollection = myProcess.Modules
                Dim j As Integer
                For j = 0 To modules.Count - 1
                    If (modules.Item(j).FileName.ToLower.CompareTo(strFile.ToLower) = 0) Then
                        myProcessArray.Add(myProcess)
                        Exit For
                    End If
                Next j
            Catch exception As Exception
                'MsgBox(("Error : " & exception.Message))
            End Try
        End If
    Next i
    Return myProcessArray
End Function
End Module

How can I pad a value with leading zeros?

My contribution:

I'm assuming you want the total string length to include the 'dot'. If not it's still simple to rewrite to add an extra zero if the number is a float.

padZeros = function (num, zeros) {
        return (((num < 0) ? "-" : "") + Array(++zeros - String(Math.abs(num)).length).join("0") + Math.abs(num));
    }

Sorting a list with stream.sorted() in Java

This is a simple example :

List<String> citiesName = Arrays.asList( "Delhi","Mumbai","Chennai","Banglore","Kolkata");
System.out.println("Cities : "+citiesName);
List<String> sortedByName = citiesName.stream()
                .sorted((s1,s2)->s2.compareTo(s1))
                        .collect(Collectors.toList());
System.out.println("Sorted by Name : "+ sortedByName);

It may be possible that your IDE is not getting the jdk 1.8 or upper version to compile the code.

Set the Java version 1.8 for Your_Project > properties > Project Facets > Java version 1.8

MATLAB, Filling in the area between two sets of data, lines in one figure

You can accomplish this using the function FILL to create filled polygons under the sections of your plots. You will want to plot the lines and polygons in the order you want them to be stacked on the screen, starting with the bottom-most one. Here's an example with some sample data:

x = 1:100;             %# X range
y1 = rand(1,100)+1.5;  %# One set of data ranging from 1.5 to 2.5
y2 = rand(1,100)+0.5;  %# Another set of data ranging from 0.5 to 1.5
baseLine = 0.2;        %# Baseline value for filling under the curves
index = 30:70;         %# Indices of points to fill under

plot(x,y1,'b');                              %# Plot the first line
hold on;                                     %# Add to the plot
h1 = fill(x(index([1 1:end end])),...        %# Plot the first filled polygon
          [baseLine y1(index) baseLine],...
          'b','EdgeColor','none');
plot(x,y2,'g');                              %# Plot the second line
h2 = fill(x(index([1 1:end end])),...        %# Plot the second filled polygon
          [baseLine y2(index) baseLine],...
          'g','EdgeColor','none');
plot(x(index),baseLine.*ones(size(index)),'r');  %# Plot the red line

And here's the resulting figure:

enter image description here

You can also change the stacking order of the objects in the figure after you've plotted them by modifying the order of handles in the 'Children' property of the axes object. For example, this code reverses the stacking order, hiding the green polygon behind the blue polygon:

kids = get(gca,'Children');        %# Get the child object handles
set(gca,'Children',flipud(kids));  %# Set them to the reverse order

Finally, if you don't know exactly what order you want to stack your polygons ahead of time (i.e. either one could be the smaller polygon, which you probably want on top), then you could adjust the 'FaceAlpha' property so that one or both polygons will appear partially transparent and show the other beneath it. For example, the following will make the green polygon partially transparent:

set(h2,'FaceAlpha',0.5);

Printing reverse of any String without using any predefined function?

final String s = "123456789";
final char[] word = s.toCharArray();
final int l = s.length() - 2;
final int ll = s.length() - 1;
for (int i = 0; i < l; i++) {
    char x = word[i];
    word[i] = word[ll - i];
    word[ll - i] = x;
}
System.out.println(s);
System.out.println(new String(word));

You can do it either recursively or iteratively (looping).

Iteratively:

static String reverseMe(String s) {
    StringBuilder sb = new StringBuilder();
    for (int i = s.length() - 1; i >= 0; --i)
        sb.append(s.charAt(i));
    return sb.toString();
}

Recursively:

static String reverseMe(String s) {
    if (s.length() == 0)
        return "";
    return s.charAt(s.length() - 1) + reverseMe(s.substring(1));
}

Integer i = new Integer(15);
test(i);
System.out.println(i);
test(i);
System.out.println(i); 
public static void test (Integer i) {
    i = (Integer)i + 10;
}

How to insert multiple rows from array using CodeIgniter framework?

Well, you don't want to execute 1000 query calls, but doing this is fine:

$stmt= array( 'array of statements' );
$query= 'INSERT INTO yourtable (col1,col2,col3) VALUES ';
foreach( $stmt AS $k => $v ) {
  $query.= '(' .$v. ')'; // NOTE: you'll have to change to suit
  if ( $k !== sizeof($stmt)-1 ) $query.= ', ';
}
$r= mysql_query($query);

Depending on your data source, populating the array might be as easy as opening a file and dumping the contents into an array via file().

Why would someone use WHERE 1=1 AND <conditions> in a SQL clause?

Here's a closely related example: using a SQL MERGE statement to update the target tabled using all values from the source table where there is no common attribute on which to join on e.g.

MERGE INTO Circles
   USING 
      (
        SELECT pi
         FROM Constants
      ) AS SourceTable
   ON 1 = 1
WHEN MATCHED THEN 
  UPDATE
     SET circumference = 2 * SourceTable.pi * radius;

How do I disable a jquery-ui draggable?

It took me a little while to figure out how to disable draggable on drop—use ui.draggable to reference the object being dragged from inside the drop function:

$("#drop-target").droppable({
    drop: function(event, ui) {
        ui.draggable.draggable("disable", 1); // *not* ui.draggable("disable", 1);
        …
    }
});

HTH someone

How to return result of a SELECT inside a function in PostgreSQL?

Use RETURN QUERY:

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt   text   -- also visible as OUT parameter inside function
               , cnt   bigint
               , ratio bigint) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt
        , count(*) AS cnt                 -- column alias only visible inside
        , (count(*) * 100) / _max_tokens  -- I added brackets
   FROM  (
      SELECT t.txt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      LIMIT  _max_tokens
      ) t
   GROUP  BY t.txt
   ORDER  BY cnt DESC;                    -- potential ambiguity 
END
$func$  LANGUAGE plpgsql;

Call:

SELECT * FROM word_frequency(123);

Explanation:

  • It is much more practical to explicitly define the return type than simply declaring it as record. This way you don't have to provide a column definition list with every function call. RETURNS TABLE is one way to do that. There are others. Data types of OUT parameters have to match exactly what is returned by the query.

  • Choose names for OUT parameters carefully. They are visible in the function body almost anywhere. Table-qualify columns of the same name to avoid conflicts or unexpected results. I did that for all columns in my example.

    But note the potential naming conflict between the OUT parameter cnt and the column alias of the same name. In this particular case (RETURN QUERY SELECT ...) Postgres uses the column alias over the OUT parameter either way. This can be ambiguous in other contexts, though. There are various ways to avoid any confusion:

    1. Use the ordinal position of the item in the SELECT list: ORDER BY 2 DESC. Example:
    2. Repeat the expression ORDER BY count(*).
    3. (Not applicable here.) Set the configuration parameter plpgsql.variable_conflict or use the special command #variable_conflict error | use_variable | use_column in the function. See:
  • Don't use "text" or "count" as column names. Both are legal to use in Postgres, but "count" is a reserved word in standard SQL and a basic function name and "text" is a basic data type. Can lead to confusing errors. I use txt and cnt in my examples.

  • Added a missing ; and corrected a syntax error in the header. (_max_tokens int), not (int maxTokens) - type after name.

  • While working with integer division, it's better to multiply first and divide later, to minimize the rounding error. Even better: work with numeric (or a floating point type). See below.

Alternative

This is what I think your query should actually look like (calculating a relative share per token):

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt            text
               , abs_cnt        bigint
               , relative_share numeric) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt, t.cnt
        , round((t.cnt * 100) / (sum(t.cnt) OVER ()), 2)  -- AS relative_share
   FROM  (
      SELECT t.txt, count(*) AS cnt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      GROUP  BY t.txt
      ORDER  BY cnt DESC
      LIMIT  _max_tokens
      ) t
   ORDER  BY t.cnt DESC;
END
$func$  LANGUAGE plpgsql;

The expression sum(t.cnt) OVER () is a window function. You could use a CTE instead of the subquery - pretty, but a subquery is typically cheaper in simple cases like this one.

A final explicit RETURN statement is not required (but allowed) when working with OUT parameters or RETURNS TABLE (which makes implicit use of OUT parameters).

round() with two parameters only works for numeric types. count() in the subquery produces a bigint result and a sum() over this bigint produces a numeric result, thus we deal with a numeric number automatically and everything just falls into place.

Asserting successive calls to a mock method

I always have to look this one up time and time again, so here is my answer.


Asserting multiple method calls on different objects of the same class

Suppose we have a heavy duty class (which we want to mock):

In [1]: class HeavyDuty(object):
   ...:     def __init__(self):
   ...:         import time
   ...:         time.sleep(2)  # <- Spends a lot of time here
   ...:     
   ...:     def do_work(self, arg1, arg2):
   ...:         print("Called with %r and %r" % (arg1, arg2))
   ...:  

here is some code that uses two instances of the HeavyDuty class:

In [2]: def heavy_work():
   ...:     hd1 = HeavyDuty()
   ...:     hd1.do_work(13, 17)
   ...:     hd2 = HeavyDuty()
   ...:     hd2.do_work(23, 29)
   ...:    


Now, here is a test case for the heavy_work function:

In [3]: from unittest.mock import patch, call
   ...: def test_heavy_work():
   ...:     expected_calls = [call.do_work(13, 17),call.do_work(23, 29)]
   ...:     
   ...:     with patch('__main__.HeavyDuty') as MockHeavyDuty:
   ...:         heavy_work()
   ...:         MockHeavyDuty.return_value.assert_has_calls(expected_calls)
   ...:  

We are mocking the HeavyDuty class with MockHeavyDuty. To assert method calls coming from every HeavyDuty instance we have to refer to MockHeavyDuty.return_value.assert_has_calls, instead of MockHeavyDuty.assert_has_calls. In addition, in the list of expected_calls we have to specify which method name we are interested in asserting calls for. So our list is made of calls to call.do_work, as opposed to simply call.

Exercising the test case shows us it is successful:

In [4]: print(test_heavy_work())
None


If we modify the heavy_work function, the test fails and produces a helpful error message:

In [5]: def heavy_work():
   ...:     hd1 = HeavyDuty()
   ...:     hd1.do_work(113, 117)  # <- call args are different
   ...:     hd2 = HeavyDuty()
   ...:     hd2.do_work(123, 129)  # <- call args are different
   ...:     

In [6]: print(test_heavy_work())
---------------------------------------------------------------------------
(traceback omitted for clarity)

AssertionError: Calls not found.
Expected: [call.do_work(13, 17), call.do_work(23, 29)]
Actual: [call.do_work(113, 117), call.do_work(123, 129)]


Asserting multiple calls to a function

To contrast with the above, here is an example that shows how to mock multiple calls to a function:

In [7]: def work_function(arg1, arg2):
   ...:     print("Called with args %r and %r" % (arg1, arg2))

In [8]: from unittest.mock import patch, call
   ...: def test_work_function():
   ...:     expected_calls = [call(13, 17), call(23, 29)]    
   ...:     with patch('__main__.work_function') as mock_work_function:
   ...:         work_function(13, 17)
   ...:         work_function(23, 29)
   ...:         mock_work_function.assert_has_calls(expected_calls)
   ...:    

In [9]: print(test_work_function())
None


There are two main differences. The first one is that when mocking a function we setup our expected calls using call, instead of using call.some_method. The second one is that we call assert_has_calls on mock_work_function, instead of on mock_work_function.return_value.

How to get image width and height in OpenCV?

You can use rows and cols:

cout << "Width : " << src.cols << endl;
cout << "Height: " << src.rows << endl;

or size():

cout << "Width : " << src.size().width << endl;
cout << "Height: " << src.size().height << endl;

PHP - Debugging Curl

To just get the info of a CURL request do this:

$response = curl_exec($ch);

$info = curl_getinfo($ch);
var_dump($info);

How to get file_get_contents() to work with HTTPS?

I was stuck with non functional https on IIS. Solved with:

file_get_contents('https.. ) wouldn't load.

  • download https://curl.haxx.se/docs/caextract.html
  • install under ..phpN.N/extras/ssl
  • edit php.ini with:

    curl.cainfo = "C:\Program Files\PHP\v7.3\extras\ssl\cacert.pem" openssl.cafile="C:\Program Files\PHP\v7.3\extras\ssl\cacert.pem"

finally!

Quicker way to get all unique values of a column in VBA?

PowerShell is a very powerful and efficient tool. This is cheating a little, but shelling PowerShell via VBA opens up lots of options

The bulk of the code below is simply to save the current sheet as a csv file. The output is another csv file with just the unique values

Sub AnotherWay()
Dim strPath As String
Dim strPath2 As String

Application.DisplayAlerts = False
strPath = "C:\Temp\test.csv"
strPath2 = "C:\Temp\testout.csv"
ActiveWorkbook.SaveAs strPath, xlCSV
x = Shell("powershell.exe $csv = import-csv -Path """ & strPath & """ -Header A | Select-Object -Unique A | Export-Csv """ & strPath2 & """ -NoTypeInformation", 0)
Application.DisplayAlerts = True

End Sub

Android EditText for password with android:hint

Hint is displayed correctly with

android:inputType="textPassword"

and

android:gravity="center"

if you set also

android:ellipsize="start"

A beginner's guide to SQL database design

It's been a while since I read it (so, I'm not sure how much of it is still relevant), but my recollection is that Joe Celko's SQL for Smarties book provides a lot of info on writing elegant, effective, and efficient queries.

How to add Tomcat Server in eclipse

The Java EE version of Eclipse is not installed, insted a standard SDK version is installed.

You can go to Help > Install New Software then select the Eclipse site from the dropdown (Helios, Kepler depending upon your revision). Then select the option that shows Java EE. Restart Eclipse and you should see the Server list, such as Apache, Oracle, IBM etc.

Create an Array of Arraylists

List[] listArr = new ArrayList[4];

Above line gives warning , but it works (i.e it creates Array of ArrayList)

How to add one day to a date?

I prefer joda for date and time arithmetics because it is much better readable:

Date tomorrow = now().plusDays(1).toDate();

Or

endOfDay(now().plus(days(1))).toDate()
startOfDay(now().plus(days(1))).toDate()

How to run a script at a certain time on Linux?

Cron is good for something that will run periodically, like every Saturday at 4am. There's also anacron, which works around power shutdowns, sleeps, and whatnot. As well as at.

But for a one-off solution, that doesn't require root or anything, you can just use date to compute the seconds-since-epoch of the target time as well as the present time, then use expr to find the difference, and sleep that many seconds.

Rollback one specific migration in Laravel

Rollback one step. Natively.

php artisan migrate:rollback --step=1

Rollback two step. Natively.

php artisan migrate:rollback --step=2

How can I print the contents of a hash in Perl?

Data::Dumper is your friend.

use Data::Dumper;
my %hash = ('abc' => 123, 'def' => [4,5,6]);
print Dumper(\%hash);

will output

$VAR1 = {
          'def' => [
                     4,
                     5,
                     6
                   ],
          'abc' => 123
        };

What do I use on linux to make a python program executable

I do the following:

  1. put #! /usr/bin/env python3 at top of script
  2. chmod u+x file.py
  3. Change .py to .command in file name

This essentially turns the file into a bash executable. When you double-click it, it should run. This works in Unix-based systems.

How to detect duplicate values in PHP array?

Perhaps something like this (untested code but should give you an idea)?

$new = array();

foreach ($array as $value)
{
    if (isset($new[$value]))
        $new[$value]++;
    else
        $new[$value] = 1;
}

Then you'll get a new array with the values as keys and their value is the number of times they existed in the original array.

How to get access to HTTP header information in Spring MVC REST controller?

My solution in Header parameters with example is user="test" is:

@RequestMapping(value = "/restURL")
  public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers){

System.out.println(headers.get("user"));
}

Casting interfaces for deserialization in JSON.NET

Use this JsonKnownTypes, it's very similar way to use, it just add discriminator to json:

[JsonConverter(typeof(JsonKnownTypeConverter<Interface1>))]
[JsonKnownType(typeof(MyClass), "myClass")]
public interface Interface1
{  }
public class MyClass : Interface1
{
    public string Something;
}

Now when you serialize object in json will be add "$type" with "myClass" value and it will be use for deserialize

Json:

{"Something":"something", "$type":"derived"}

CSS to select/style first word

I have to disagree with Dale... The strong element is actually the wrong element to use, implying something about the meaning, use, or emphasis of the content while you are simply intending to provide style to the element.

Ideally you would be able to accomplish this with a pseudo-class and your stylesheet, but as that is not possible you should make your markup semantically correct and use <span class="first-word">.

I am receiving warning in Facebook Application using PHP SDK

You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start(). The headers will be sent automatically when any HTML is output.

Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.

Move the session_start() to the top of your document :

<?php    session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php';    // more PHP code here. 

How can I throw a general exception in Java?

Well, there are lots of exceptions to throw, but here is how you throw an exception:

throw new IllegalArgumentException("INVALID");

Also, yes, you can create your own custom exceptions.

A note about exceptions. When you throw an exception (like above) and you catch the exception: the String that you supply in the exception can be accessed throw the getMessage() method.

try{
    methodThatThrowsException();
}catch(IllegalArgumentException e)
{
  e.getMessage();
}

Python Pandas Counting the Occurrences of a Specific value

Try this:

(df[education]=='9th').sum()

How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption

Errors: "Bad encrypt / decrypt" "gitencrypt_smudge: FAILURE: openssl error decrypting file"

There are various error strings that are thrown from openssl, depending on respective versions, and scenarios. Below is the checklist I use in case of openssl related issues:

  1. Ideally, openssl is able to encrypt/decrypt using same key (+ salt) & enc algo only.
  2. Ensure that openssl versions (used to encrypt/decrypt), are compatible. For eg. the hash used in openssl changed at version 1.1.0 from MD5 to SHA256. This produces a different key from the same password. Fix: add "-md md5" in 1.1.0 to decrypt data from lower versions, and add "-md sha256 in lower versions to decrypt data from 1.1.0

  3. Ensure that there is a single openssl version installed in your machine. In case there are multiple versions installed simultaneously (in my machine, these were installed :- 'LibreSSL 2.6.5' and 'openssl 1.1.1d'), make the sure that only the desired one appears in your PATH variable.

How to remove focus without setting focus to another control?

Using clearFocus() didn't seem to be working for me either as you found (saw in comments to another answer), but what worked for me in the end was adding:

<LinearLayout 
    android:id="@+id/my_layout" 
    android:focusable="true" 
    android:focusableInTouchMode="true" ...>

to my very top level Layout View (a linear layout). To remove focus from all Buttons/EditTexts etc, you can then just do

LinearLayout myLayout = (LinearLayout) activity.findViewById(R.id.my_layout);
myLayout.requestFocus();

Requesting focus did nothing unless I set the view to be focusable.

HTML 5 Geo Location Prompt in Chrome

There's some sort of security restriction in place in Chrome for using geolocation from a file:/// URI, though unfortunately it doesn't seem to record any errors to indicate that. It will work from a local web server. If you have python installed try opening a command prompt in the directory where your test files are and issuing the command:

python -m SimpleHTTPServer

It should start up a web server on port 8000 (might be something else, but it'll tell you in the console what port it's listening on), then browse to http://localhost:8000/mytestpage.html

If you don't have python there are equivalent modules in Ruby, or Visual Web Developer Express comes with a built in local web server.

How to set breakpoints in inline Javascript in Google Chrome?

My situation and what I did to fix it:
I have a javascript file included on an HTML page as follows:
Page Name: test.html

<!DOCTYPE html>
<html>
    <head>
        <script src="scripts/common.js"></script>
        <title>Test debugging JS in Chrome</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <div>
         <script type="text/javascript">
            document.write("something");
         </script>

        </div>
     </body>
</html>

Now entering the Javascript Debugger in Chrome, I click the Scripts Tab, and drop down the list as shown above. I can clearly see scripts/common.js however I could NOT see the current html page test.html in the drop down, therefore I could not debug the embedded javascript:

<script type="text/javascript">
  document.write("something");
</script>

That was perplexing. However, when I removed the obsolete type="text/javascript" from the embedded script:

<script>
  document.write("something");
</script>

..and refreshed / reloaded the page, voila, it appeared in the drop down list, and all was well again.
I hope this is helpful to anyone who is having issues debugging embedded javascript on an html page.

How do I push a local repo to Bitbucket using SourceTree without creating a repo on bitbucket first?

(Linux/WSL at least) From the browser at bitbucket.org, create an empty repo with the same name as your local repo, follow the instructions proposed by bitbucket for importing a local repo (two commands to type).

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app

If you ejected and are curious, this change on the CRA repo is what is causing the error.

To fix it, you need to apply their changes; namely, the last set of files:

  • packages/react-scripts/config/paths.js
  • packages/react-scripts/config/webpack.config.js
  • packages/react-scripts/config/webpackDevServer.config.js
  • packages/react-scripts/package.json
  • packages/react-scripts/scripts/build.js
  • packages/react-scripts/scripts/start.js

Personally, I think you should manually apply the changes because, unless you have been keeping up-to-date with all the changes, you could introduce another bug to your webpack bundle (because of a dependency mismatch or something).

OR, you could do what Geo Angelopoulos suggested. It might take a while but at least your project would be in sync with the CRA repo (and get all their latest enhancements!).

When should I use semicolons in SQL Server?

From a SQLServerCentral.Com article by Ken Powers:

The Semicolon

The semicolon character is a statement terminator. It is a part of the ANSI SQL-92 standard, but was never used within Transact-SQL. Indeed, it was possible to code T-SQL for years without ever encountering a semicolon.

Usage

There are two situations in which you must use the semicolon. The first situation is where you use a Common Table Expression (CTE), and the CTE is not the first statement in the batch. The second is where you issue a Service Broker statement and the Service Broker statement is not the first statement in the batch.

Get Category name from Post ID

echo '<p>'. get_the_category( $id )[0]->name .'</p>';

is what you maybe looking for.

Display string multiple times

Python 2.x:

print '-' * 3

Python 3.x:

print('-' * 3)

How To Create Table with Identity Column

CREATE TABLE [dbo].[History](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [RequestID] [int] NOT NULL,
    [EmployeeID] [varchar](50) NOT NULL,
    [DateStamp] [datetime] NOT NULL,
 CONSTRAINT [PK_History] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON)
) ON [PRIMARY]

Angularjs - Pass argument to directive

You can try like below:

app.directive("directive_name", function(){
return {
    restrict:'E',
    transclude:true,
    template:'<div class="title"><h2>{{title}}</h3></div>',
    scope:{
      accept:"="
    },
    replace:true
  };
})

it sets up a two-way binding between the value of the 'accept' attribute and the parent scope.

And also you can set two way data binding with property: '='

For example, if you want both key and value bound to the local scope you would do:

  scope:{
    key:'=',
    value:'='
  },

For more info, https://docs.angularjs.org/guide/directive

So, if you want to pass an argument from controller to directive, then refer this below fiddle

http://jsfiddle.net/jaimem/y85Ft/7/

Hope it helps..

chrome : how to turn off user agent stylesheet settings?

https://developers.google.com/chrome-developer-tools/docs/settings

  1. Open Chrome dev tools
  2. Click gear icon on bottom right
  3. In General section, check or uncheck "Show user agent styles".

how to find 2d array size in c++

The other answers above have answered your first question. As for your second question, how to detect an error of getting a value that is not set, I am not sure which of the following situation you mean:

  1. Accessing an array element using an invalid index:
    If you use std::vector, you can use vector::at function instead of [] operator to get the value, if the index is invalid, an out_of_range exception will be thrown.

  2. Accessing a valid index, but the element has not been set yet: As far as I know, there is no direct way of it. However, the following common practices can probably solve you problem: (1) Initializes all elements to a value that you are certain that is impossible to have. For example, if you are dealing with positive integers, set all elements to -1, so you know the value is not set yet when you find it being -1. (2). Simply use a bool array of the same size to indicate whether the element of the same index is set or not, this applies when all values are "possible".

SVN (Subversion) Problem "File is scheduled for addition, but is missing" - Using Versions

I'm not sure what you're trying to do: If you added the file via

svn add myfile

you only told svn to put this file into your repository when you do your next commit. There's no change to the repository before you type an

svn commit

If you delete the file before the commit, svn has it in its records (because you added it) but cannot send it to the repository because the file no longer exist.

So either you want to save the file in the repository and then delete it from your working copy: In this case try to get your file back (from the trash?), do the commit and delete the file afterwards via

svn delete myfile
svn commit

If you want to undo the add and just throw the file away, you can to an

svn revert myfile

which tells svn (in this case) to undo the add-Operation.

EDIT

Sorry, I wasn't aware that you're using the "Versions" GUI client for Max OSX. So either try a revert on the containing directory using the GUI or jump into the cold water and fire up your hidden Mac command shell :-) (it's called "Terminal" in the german OSX, no idea how to bring it up in the english version...)

Add a link to an image in a css style sheet

You could do something like

<a href="http://home.com"><img src="images/logo.png" alt="" id="logo"></a>

in HTML

Remove leading and trailing spaces?

Expand your one liner into multiple lines. Then it becomes easy:

f.write(re.split("Tech ID:|Name:|Account #:",line)[-1])

parts = re.split("Tech ID:|Name:|Account #:",line)
wanted_part = parts[-1]
wanted_part_stripped = wanted_part.strip()
f.write(wanted_part_stripped)

How to set aliases in the Git Bash for Windows?

There is two easy way to set the alias.

  1. Using Bash
  2. Updating .gitconfig file

Using Bash

Open bash terminal and type git command. For instance:

$ git config --global alias.a add
$ git config --global alias.aa 'add .'
$ git config --global alias.cm 'commit -m'
$ git config --global alias.s status
---
---

It will eventually add those aliases on .gitconfig file.

Updating .gitconfig file

Open .gitconfig file located at 'C:\Users\username\.gitconfig' in Windows environment. Then add following lines:

[alias]  
a = add  
aa = add . 
cm = commit -m 
gau = add --update 
au = add --update
b = branch
---
---

How to remove a web site from google analytics

After Much Fannying about, deleting this that etc, I found the way to delete a "website" from your list (which is, in fact what the original question was - minus all the flaffing) is

  • Select the Account (Website) that you want to delete
  • In the first column (left hand one)
  • Click Account Settings
  • Down the bottom, it says Delete this account.

That's it… Done.

Remember: for this exercise only Account means Website.

How to return dictionary keys as a list in Python?

Python >= 3.5 alternative: unpack into a list literal [*newdict]

New unpacking generalizations (PEP 448) were introduced with Python 3.5 allowing you to now easily do:

>>> newdict = {1:0, 2:0, 3:0}
>>> [*newdict]
[1, 2, 3]

Unpacking with * works with any object that is iterable and, since dictionaries return their keys when iterated through, you can easily create a list by using it within a list literal.

Adding .keys() i.e [*newdict.keys()] might help in making your intent a bit more explicit though it will cost you a function look-up and invocation. (which, in all honesty, isn't something you should really be worried about).

The *iterable syntax is similar to doing list(iterable) and its behaviour was initially documented in the Calls section of the Python Reference manual. With PEP 448 the restriction on where *iterable could appear was loosened allowing it to also be placed in list, set and tuple literals, the reference manual on Expression lists was also updated to state this.


Though equivalent to list(newdict) with the difference that it's faster (at least for small dictionaries) because no function call is actually performed:

%timeit [*newdict]
1000000 loops, best of 3: 249 ns per loop

%timeit list(newdict)
1000000 loops, best of 3: 508 ns per loop

%timeit [k for k in newdict]
1000000 loops, best of 3: 574 ns per loop

with larger dictionaries the speed is pretty much the same (the overhead of iterating through a large collection trumps the small cost of a function call).


In a similar fashion, you can create tuples and sets of dictionary keys:

>>> *newdict,
(1, 2, 3)
>>> {*newdict}
{1, 2, 3}

beware of the trailing comma in the tuple case!

Website screenshots

It all depends on how you wish to take the screenshot.

You could do this via PHP, using a webservice to get the image for you

grabz.it has a webservice to do just this, here's an article showing a simple example of using the service.

http://www.phpbuilder.com/articles/news-reviews/miscellaneous/capture-screenshots-in-php-with-grabzit-120524022959.html

React - How to pass HTML tags in props?

Adding to the answer: If you intend to parse and you are already in JSX but have an object with nested properties, a very elegant way is to use parentheses in order to force JSX parsing:

const TestPage = () => (
  <Fragment>
    <MyComponent property={
    {
      html: (
        <p>This is a <a href='#'>test</a> text!</p>
      )
    }}>
    </MyComponent>
  </Fragment>
);

How to append elements into a dictionary in Swift?

[String:Any]

For the fellows using [String:Any] instead of Dictionary below is the extension

extension Dictionary where Key == String, Value == Any {
    
    mutating func append(anotherDict:[String:Any]) {
        for (key, value) in anotherDict {
            self.updateValue(value, forKey: key)
        }
    }
}

Generate 'n' unique random numbers within a range

You could add to a set until you reach n:

setOfNumbers = set()
while len(setOfNumbers) < n:
    setOfNumbers.add(random.randint(numLow, numHigh))

Be careful of having a smaller range than will fit in n. It will loop forever, unable to find new numbers to insert up to n

How to create nested directories using Mkdir in Golang?

An utility method like the following can be used to solve this.

import (
  "os"
  "path/filepath"
  "log"
)

func ensureDir(fileName string) {
  dirName := filepath.Dir(fileName)
  if _, serr := os.Stat(dirName); serr != nil {
    merr := os.MkdirAll(dirName, os.ModePerm)
    if merr != nil {
        panic(merr)
    }
  }
}



func main() {
  _, cerr := os.Create("a/b/c/d.txt")
  if cerr != nil {
    log.Fatal("error creating a/b/c", cerr)
  }
  log.Println("created file in a sub-directory.")
}

Is it possible to access to google translate api for free?

Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.

UPD 19.03.2019 Here is a version for browser on GitHub.

How to remove symbols from a string with Python?

I often just open the console and look for the solution in the objects methods. Quite often it's already there:

>>> a = "hello ' s"
>>> dir(a)
[ (....) 'partition', 'replace' (....)]
>>> a.replace("'", " ")
'hello   s'

Short answer: Use string.replace().

Android textview outline text

I found simple way to outline view without inheritance from TextView. I had wrote simple library that use Android's Spannable for outlining text. This solution gives possibility to outline only part of text.

I already had answered on same question (answer)

Class:

class OutlineSpan(
        @ColorInt private val strokeColor: Int,
        @Dimension private val strokeWidth: Float
): ReplacementSpan() {

    override fun getSize(
            paint: Paint,
            text: CharSequence,
            start: Int,
            end: Int,
            fm: Paint.FontMetricsInt?
    ): Int {
        return paint.measureText(text.toString().substring(start until end)).toInt()
    }


    override fun draw(
            canvas: Canvas,
            text: CharSequence,
            start: Int,
            end: Int,
            x: Float,
            top: Int,
            y: Int,
            bottom: Int,
            paint: Paint
    ) {
        val originTextColor = paint.color

        paint.apply {
            color = strokeColor
            style = Paint.Style.STROKE
            this.strokeWidth = [email protected]
        }
        canvas.drawText(text, start, end, x, y.toFloat(), paint)

        paint.apply {
            color = originTextColor
            style = Paint.Style.FILL
        }
        canvas.drawText(text, start, end, x, y.toFloat(), paint)
    }

}

Library: OutlineSpan

How to jump to top of browser page

You could do it without javascript and simply use anchor tags? Then it would be accessible to those js free.

although as you are using modals, I assume you don't care about being js free. ;)

How to decompile to java files intellij idea

Someone had gave good answers. I made another instruction clue step by step. First, open your studio and search. You can find the decompier is Fernflower.

enter image description here

Second, we can find it in the plugins directory.

/Applications/Android Studio.app/Contents/plugins/java-decompiler/lib/java-decompiler.jar

Third, run it, you will get the usage

java -cp "/Applications/Android Studio.app/Contents/plugins/java-decompiler/lib/java-decompiler.jar" org.jetbrains.java.decompiler.main.decompiler.ConsoleDecompiler

Usage: java -jar fernflower.jar [-<option>=<value>]* [<source>]+ <destination>
Example: java -jar fernflower.jar -dgs=true c:\my\source\ c:\my.jar d:\decompiled\

Finally, The studio's nest options for decompiler list as follows according IdeaDecompiler.kt

-hdc=0 -dgs=1 -rsy=1 -rbr=1 -lit=1 -nls=1 -mpm=60 -lac=1

IFernflowerPreferences.HIDE_DEFAULT_CONSTRUCTOR to "0",
        IFernflowerPreferences.DECOMPILE_GENERIC_SIGNATURES to "1",
        IFernflowerPreferences.REMOVE_SYNTHETIC to "1",
        IFernflowerPreferences.REMOVE_BRIDGE to "1",
        IFernflowerPreferences.LITERALS_AS_IS to "1",
        IFernflowerPreferences.NEW_LINE_SEPARATOR to "1",
        **IFernflowerPreferences.BANNER to BANNER,**
        IFernflowerPreferences.MAX_PROCESSING_METHOD to 60,
        **IFernflowerPreferences.INDENT_STRING to indent,**
        **IFernflowerPreferences.IGNORE_INVALID_BYTECODE to "1",**
        IFernflowerPreferences.VERIFY_ANONYMOUS_CLASSES to "1",
         **IFernflowerPreferences.UNIT_TEST_MODE to if (ApplicationManager.getApplication().isUnitTestMode) "1" else "0")**

I cant find the sutialbe option for the asterisk items.

Hope these steps will make the question clear.

Determine number of pages in a PDF file

This should do the trick:

public int getNumberOfPdfPages(string fileName)
{
    using (StreamReader sr = new StreamReader(File.OpenRead(fileName)))
    {
        Regex regex = new Regex(@"/Type\s*/Page[^s]");
        MatchCollection matches = regex.Matches(sr.ReadToEnd());

        return matches.Count;
    }
}

From Rachael's answer and this one too.

How to split a string between letters and digits (or between digits and letters)?

How about:

private List<String> Parse(String str) {
    List<String> output = new ArrayList<String>();
    Matcher match = Pattern.compile("[0-9]+|[a-z]+|[A-Z]+").matcher(str);
    while (match.find()) {
        output.add(match.group());
    }
    return output;
}

Remove Select arrow on IE

In case you want to use the class and pseudo-class:

.simple-control is your css class

:disabled is pseudo class

select.simple-control:disabled{
         /*For FireFox*/
        -webkit-appearance: none;
        /*For Chrome*/
        -moz-appearance: none;
}

/*For IE10+*/
select:disabled.simple-control::-ms-expand {
        display: none;
}

How to return a struct from a function in C++?

You can now (C++14) return a locally-defined (i.e. defined inside the function) as follows:

auto f()
{
    struct S
    {
      int a;
      double b;
    } s;
    s.a = 42;
    s.b = 42.0;
    return s;
}

auto x = f();
a = x.a;
b = x.b;

Put a Delay in Javascript

Use a AJAX function which will call a php page synchronously and then in that page you can put the php usleep() function which will act as a delay.

function delay(t){

var xmlhttp;

if (window.XMLHttpRequest)

{// code for IE7+, Firefox, Chrome, Opera, Safari

xmlhttp=new XMLHttpRequest();

}

else

{// code for IE6, IE5

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}

xmlhttp.open("POST","http://www.hklabs.org/files/delay.php?time="+t,false);

//This will call the page named delay.php and the response will be sent to a division with ID as "response"

xmlhttp.send();

document.getElementById("response").innerHTML=xmlhttp.responseText;

}

http://www.hklabs.org/articles/put-delay-in-javascript

combining two data frames of different lengths

I think I have come up with a quite shorter solution.. Hope it helps someone.

cbind.na<-function(df1, df2){

  #Collect all unique rownames
  total.rownames<-union(x = rownames(x = df1),y = rownames(x=df2))

  #Create a new dataframe with rownames
  df<-data.frame(row.names = total.rownames)

  #Get absent rownames for both of the dataframe
  absent.names.1<-setdiff(x = rownames(df1),y = rownames(df))
  absent.names.2<-setdiff(x = rownames(df2),y = rownames(df))

  #Fill absents with NAs
  df1.fixed<-data.frame(row.names = absent.names.1,matrix(data = NA,nrow = length(absent.names.1),ncol=ncol(df1)))
  colnames(df1.fixed)<-colnames(df1)
  df1<-rbind(df1,df1.fixed)

  df2.fixed<-data.frame(row.names = absent.names.2,matrix(data = NA,nrow = length(absent.names.2),ncol=ncol(df2)))
  colnames(df2.fixed)<-colnames(df2)
  df2<-rbind(df2,df2.fixed)

  #Finally cbind into new dataframe
  df<-cbind(df,df1[rownames(df),],df2[rownames(df),])
  return(df)

}

String formatting: % vs. .format vs. string literal

To answer your first question... .format just seems more sophisticated in many ways. An annoying thing about % is also how it can either take a variable or a tuple. You'd think the following would always work:

"hi there %s" % name

yet, if name happens to be (1, 2, 3), it will throw a TypeError. To guarantee that it always prints, you'd need to do

"hi there %s" % (name,)   # supply the single argument as a single-item tuple

which is just ugly. .format doesn't have those issues. Also in the second example you gave, the .format example is much cleaner looking.

Why would you not use it?

  • not knowing about it (me before reading this)
  • having to be compatible with Python 2.5

To answer your second question, string formatting happens at the same time as any other operation - when the string formatting expression is evaluated. And Python, not being a lazy language, evaluates expressions before calling functions, so in your log.debug example, the expression "some debug info: %s"%some_infowill first evaluate to, e.g. "some debug info: roflcopters are active", then that string will be passed to log.debug().

std::unique_lock<std::mutex> or std::lock_guard<std::mutex>?

As has been mentioned by others, std::unique_lock tracks the locked status of the mutex, so you can defer locking until after construction of the lock, and unlock before destruction of the lock. std::lock_guard does not permit this.

There seems no reason why the std::condition_variable wait functions should not take a lock_guard as well as a unique_lock, because whenever a wait ends (for whatever reason) the mutex is automatically reacquired so that would not cause any semantic violation. However according to the standard, to use a std::lock_guard with a condition variable you have to use a std::condition_variable_any instead of std::condition_variable.

Edit: deleted "Using the pthreads interface std::condition_variable and std::condition_variable_any should be identical". On looking at gcc's implementation:

  • std::condition_variable::wait(std::unique_lock&) just calls pthread_cond_wait() on the underlying pthread condition variable with respect to the mutex held by unique_lock (and so could equally do the same for lock_guard, but doesn't because the standard doesn't provide for that)
  • std::condition_variable_any can work with any lockable object, including one which is not a mutex lock at all (it could therefore even work with an inter-process semaphore)

Check synchronously if file/directory exists in Node.js

From the answers it appears that there is no official API support for this (as in a direct and explicit check). Many of the answers say to use stat, however they are not strict. We can't assume for example that any error thrown by stat means that something doesn't exist.

Lets say we try it with something that doesn't exist:

$ node -e 'require("fs").stat("god",err=>console.log(err))'
{ Error: ENOENT: no such file or directory, stat 'god' errno: -2, code: 'ENOENT', syscall: 'stat', path: 'god' }

Lets try it with something that exists but that we don't have access to:

$ mkdir -p fsm/appendage && sudo chmod 0 fsm
$ node -e 'require("fs").stat("fsm/appendage",err=>console.log(err))'
{ Error: EACCES: permission denied, stat 'access/access' errno: -13, code: 'EACCES', syscall: 'stat', path: 'fsm/appendage' }

At the very least you'll want:

let dir_exists = async path => {
    let stat;
    try {
       stat = await (new Promise(
           (resolve, reject) => require('fs').stat(path,
               (err, result) => err ? reject(err) : resolve(result))
       ));
    }
    catch(e) {
        if(e.code === 'ENOENT') return false;
        throw e;
    }

    if(!stat.isDirectory())
        throw new Error('Not a directory.');

    return true;
};

The question is not clear on if you actually want it to be syncronous or if you only want it to be written as though it is syncronous. This example uses await/async so that it is only written syncronously but runs asyncronously.

This means you have to call it as such at the top level:

(async () => {
    try {
        console.log(await dir_exists('god'));
        console.log(await dir_exists('fsm/appendage'));
    }
    catch(e) {
        console.log(e);
    }
})();

An alternative is using .then and .catch on the promise returned from the async call if you need it further down.

If you want to check if something exists then it's a good practice to also ensure it's the right type of thing such as a directory or file. This is included in the example. If it's not allowed to be a symlink you must use lstat instead of stat as stat will automatically traverse links.

You can replace all of the async to sync code in here and use statSync instead. However expect that once async and await become universally supports the Sync calls will become redundant eventually to be depreciated (otherwise you would have to define them everywhere and up the chain just like with async making it really pointless).

Bootstrap trying to load map file. How to disable it? Do I need to do it?

.map files allow a browser to download a full version of the minified JS. It is really for debugging purposes.

In effect, the .map missing isn't a problem. You only know it is missing, as the browser has had its Developer tools opened, detected a minified file and is just informing you that the JS debugging won't be as good as it could be.

This is why libraries like jQuery have the full, the minified and the map file too.

See this article for a full explanation of .map files:

How to start/stop/restart a thread in Java?

Once a thread stops you cannot restart it. However, there is nothing stopping you from creating and starting a new thread.

Option 1: Create a new thread rather than trying to restart.

Option 2: Instead of letting the thread stop, have it wait and then when it receives notification you can allow it to do work again. This way the thread never stops and will never need to be restarted.

Edit based on comment:

To "kill" the thread you can do something like the following.

yourThread.setIsTerminating(true); // tell the thread to stop
yourThread.join(); // wait for the thread to stop

Transpose a data frame

You'd better not transpose the data.frame while the name column is in it - all numeric values will then be turned into strings!

Here's a solution that keeps numbers as numbers:

# first remember the names
n <- df.aree$name

# transpose all but the first column (name)
df.aree <- as.data.frame(t(df.aree[,-1]))
colnames(df.aree) <- n
df.aree$myfactor <- factor(row.names(df.aree))

str(df.aree) # Check the column types

How to display a gif fullscreen for a webpage background?

This should do what you're looking for.

CSS:

html, body {
    height: 100%;
    margin: 0;
}

.gif-container {
  background: url("image.gif") center;
  background-size: cover;

  height: 100%;
}

HTML:

<div class="gif-container"></div>

Calculate Pandas DataFrame Time Difference Between Two Columns in Hours and Minutes

Pandas timestamp differences returns a datetime.timedelta object. This can easily be converted into hours by using the *as_type* method, like so

import pandas
df = pandas.DataFrame(columns=['to','fr','ans'])
df.to = [pandas.Timestamp('2014-01-24 13:03:12.050000'), pandas.Timestamp('2014-01-27 11:57:18.240000'), pandas.Timestamp('2014-01-23 10:07:47.660000')]
df.fr = [pandas.Timestamp('2014-01-26 23:41:21.870000'), pandas.Timestamp('2014-01-27 15:38:22.540000'), pandas.Timestamp('2014-01-23 18:50:41.420000')]
(df.fr-df.to).astype('timedelta64[h]')

to yield,

0    58
1     3
2     8
dtype: float64

Change value of input placeholder via model?

You can bind with a variable in the controller:

<input type="text" ng-model="inputText" placeholder="{{somePlaceholder}}" />

In the controller:

$scope.somePlaceholder = 'abc';

JavaScript - document.getElementByID with onClick

Perhaps you might want to use "addEventListener"

document.getElementById("test").addEventListener('click',function ()
{
    foo2();
   }  ); 

Hope it's still useful for you

How to check if BigDecimal variable == 0 in java?

You would want to use equals() since they are objects, and utilize the built in ZERO instance:

if (selectPrice.equals(BigDecimal.ZERO))

Note that .equals() takes scale into account, so unless selectPrice is the same scale (0) as .ZERO then this will return false.

To take scale out of the equation as it were:

if (selectPrice.compareTo(BigDecimal.ZERO) == 0)

I should note that for certain mathematical situations, 0.00 != 0, which is why I imagine .equals() takes the scale into account. 0.00 gives precision to the hundredths place, whereas 0 is not that precise. Depending on the situation you may want to stick with .equals().

#define in Java

Simplest Answer is "No Direct method of getting it because there is no pre-compiler" But you can do it by yourself. Use classes and then define variables as final so that it can be assumed as constant throughout the program
Don't forget to use final and variable as public or protected not private otherwise you won't be able to access it from outside that class

Preventing twitter bootstrap carousel from auto sliding on page load

add this to your coursel div :

data-interval="false"

how to pass parameters to query in SQL (Excel)

This post is old enough that this answer will probably be little use to the OP, but I spent forever trying to answer this same question, so I thought I would update it with my findings.

This answer assumes that you already have a working SQL query in place in your Excel document. There are plenty of tutorials to show you how to accomplish this on the web, and plenty that explain how to add a parameterized query to one, except that none seem to work for an existing, OLE DB query.

So, if you, like me, got handed a legacy Excel document with a working query, but the user wants to be able to filter the results based on one of the database fields, and if you, like me, are neither an Excel nor a SQL guru, this might be able to help you out.

Most web responses to this question seem to say that you should add a “?” in your query to get Excel to prompt you for a custom parameter, or place the prompt or the cell reference in [brackets] where the parameter should be. This may work for an ODBC query, but it does not seem to work for an OLE DB, returning “No value given for one or more required parameters” in the former instance, and “Invalid column name ‘xxxx’” or “Unknown object ‘xxxx’” in the latter two. Similarly, using the mythical “Parameters…” or “Edit Query…” buttons is also not an option as they seem to be permanently greyed out in this instance. (For reference, I am using Excel 2010, but with an Excel 97-2003 Workbook (*.xls))

What we can do, however, is add a parameter cell and a button with a simple routine to programmatically update our query text.

First, add a row above your external data table (or wherever) where you can put a parameter prompt next to an empty cell and a button (Developer->Insert->Button (Form Control) – You may need to enable the Developer tab, but you can find out how to do that elsewhere), like so:

[Picture of a cell of prompt (label) text, an empty cell, then a button.]

Next, select a cell in the External Data (blue) area, then open Data->Refresh All (dropdown)->Connection Properties… to look at your query. The code in the next section assumes that you already have a parameter in your query (Connection Properties->Definition->Command Text) in the form “WHERE (DB_TABLE_NAME.Field_Name = ‘Default Query Parameter')” (including the parentheses). Clearly “DB_TABLE_NAME.Field_Name” and “Default Query Parameter” will need to be different in your code, based on the database table name, database value field (column) name, and some default value to search for when the document is opened (if you have auto-refresh set). Make note of the “DB_TABLE_NAME.Field_Name” value as you will need it in the next section, along with the “Connection name” of your query, which can be found at the top of the dialog.

Close the Connection Properties, and hit Alt+F11 to open the VBA editor. If you are not on it already, right click on the name of the sheet containing your button in the “Project” window, and select “View Code”. Paste the following code into the code window (copying is recommended, as the single/double quotes are dicey and necessary).

Sub RefreshQuery()
 Dim queryPreText As String
 Dim queryPostText As String
 Dim valueToFilter As String
 Dim paramPosition As Integer
 valueToFilter = "DB_TABLE_NAME.Field_Name ="

 With ActiveWorkbook.Connections("Connection name").OLEDBConnection
     queryPreText = .CommandText
     paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1
     queryPreText = Left(queryPreText, paramPosition)
     queryPostText = .CommandText
     queryPostText = Right(queryPostText, Len(queryPostText) - paramPosition)
     queryPostText = Right(queryPostText, Len(queryPostText) - InStr(queryPostText, ")") + 1)
     .CommandText = queryPreText & " '" & Range("Cell reference").Value & "'" & queryPostText
 End With
 ActiveWorkbook.Connections("Connection name").Refresh
End Sub

Replace “DB_TABLE_NAME.Field_Name” and "Connection name" (in two locations) with your values (the double quotes and the space and equals sign need to be included).

Replace "Cell reference" with the cell where your parameter will go (the empty cell from the beginning) - mine was the second cell in the first row, so I put “B1” (again, the double quotes are necessary).

Save and close the VBA editor.

Enter your parameter in the appropriate cell.

Right click your button to assign the RefreshQuery sub as the macro, then click your button. The query should update and display the right data!

Notes: Using the entire filter parameter name ("DB_TABLE_NAME.Field_Name =") is only necessary if you have joins or other occurrences of equals signs in your query, otherwise just an equals sign would be sufficient, and the Len() calculation would be superfluous. If your parameter is contained in a field that is also being used to join tables, you will need to change the "paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1" line in the code to "paramPosition = InStr(Right(.CommandText, Len(.CommandText) - InStrRev(.CommandText, "WHERE")), valueToFilter) + Len(valueToFilter) - 1 + InStr(.CommandText, "WHERE")" so that it only looks for the valueToFilter after the "WHERE".

This answer was created with the aid of datapig’s “BaconBits” where I found the base code for the query update.

How add class='active' to html menu with php

You could use this PHP, hope it helps.

<?php if(basename($_SERVER['PHP_SELF'], '.php') == 'home' ) { ?> class="active" <?php } else { ?> <?php }?>

So a list would be like the below.

<ul>
  <li <?php if( basename($_SERVER['PHP_SELF'], '.php') == 'home' ) { ?> class="active" <?php } else { ?> <?php }?>><a href="home"><i class="fa fa-dashboard"></i> <span>Home</span></a></li>
  <li <?php if( basename($_SERVER['PHP_SELF'], '.php') == 'listings' ) { ?> class="active" <?php } else { ?> <?php }?>><a href="other"><i class="fa fa-th-list"></i> <span>Other</span></a></li>
</ul>

List of macOS text editors and code editors

I've tried Komodo out a bit, and I really like it so far. Aptana, an Eclipse variant, is also rather useful for a wide variety of things. There's always good ole' VI, too!

How do I convert a IPython Notebook into a Python file via commandline?

I had this problem and tried to find the solution online. Though I found some solutions, they still have some problems, e.g., the annoying Untitled.txt auto-creation when you start a new notebook from the dashboard.

So eventually I wrote my own solution:

import io
import os
import re
from nbconvert.exporters.script import ScriptExporter
from notebook.utils import to_api_path


def script_post_save(model, os_path, contents_manager, **kwargs):
    """Save a copy of notebook to the corresponding language source script.

    For example, when you save a `foo.ipynb` file, a corresponding `foo.py`
    python script will also be saved in the same directory.

    However, existing config files I found online (including the one written in
    the official documentation), will also create an `Untitile.txt` file when
    you create a new notebook, even if you have not pressed the "save" button.
    This is annoying because we usually will rename the notebook with a more
    meaningful name later, and now we have to rename the generated script file,
    too!

    Therefore we make a change here to filter out the newly created notebooks
    by checking their names. For a notebook which has not been given a name,
    i.e., its name is `Untitled.*`, the corresponding source script will not be
    saved. Note that the behavior also applies even if you manually save an
    "Untitled" notebook. The rationale is that we usually do not want to save
    scripts with the useless "Untitled" names.
    """
    # only process for notebooks
    if model["type"] != "notebook":
        return

    script_exporter = ScriptExporter(parent=contents_manager)
    base, __ = os.path.splitext(os_path)

    # do nothing if the notebook name ends with `Untitled[0-9]*`
    regex = re.compile(r"Untitled[0-9]*$")
    if regex.search(base):
        return

    script, resources = script_exporter.from_filename(os_path)
    script_fname = base + resources.get('output_extension', '.txt')

    log = contents_manager.log
    log.info("Saving script at /%s",
             to_api_path(script_fname, contents_manager.root_dir))

    with io.open(script_fname, "w", encoding="utf-8") as f:
        f.write(script)

c.FileContentsManager.post_save_hook = script_post_save

To use this script, you can add it to ~/.jupyter/jupyter_notebook_config.py :)

Note that you may need to restart the jupyter notebook / lab for it to work.

How to prevent favicon.ico requests?

You can use .htaccess or server directives to deny access to favicon.ico, but the server will send an access denied reply to the browser and this still slows page access.

You can stop the browser requesting favicon.ico when a user returns to your site, by getting it to stay in the browser cache.

First, provide a small favicon.ico image, could be blank, but as small as possible. I made a black and white one under 200 bytes. Then, using .htaccess or server directives, set the file Expires header a month or two in the future. When the same user comes back to your site it will be loaded from the browser cache and no request will go to your site. No more 404's in the server logs too.

If you have control over a complete Apache server or maybe a virtual server you can do this:-

If the server document root is say /var/www/html then add this to /etc/httpd/conf/httpd.conf:-

Alias /favicon.ico "/var/www/html/favicon.ico"
<Directory "/var/www/html">
    <Files favicon.ico>
       ExpiresActive On
       ExpiresDefault "access plus 1 month"
    </Files>
</Directory>

Then a single favicon.ico will work for all the virtual hosted sites since you are aliasing it. It will be drawn from the browser cache for a month after the users visit.

For .htaccess this is reported to work (not checked by me):-

AddType image/x-icon .ico
ExpiresActive On
ExpiresByType image/x-icon "access plus 1 month"

Using a remote repository with non-standard port

SSH doesn't use the : syntax when specifying a port. The easiest way to do this is to edit your ~/.ssh/config file and add:

Host git.host.de
  Port 4019

Then specify just git.host.de without a port number.

How to convert UTC timestamp to device local time in android

Local to UTC

DateTime dateTimeNew = new DateTime(date.getTime(),
DateTimeZone.forID("Asia/Calcutta"));
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String datetimeString = dateTimeNew.toString("yyyy-MM-dd HH:mm:ss");
long milis = 0;
try {
     milis = simpleDateFormat.parse(datetimeString).getTime();
} catch (ParseException e) {
   e.printStackTrace();
}

round value to 2 decimals javascript

Just multiply the number by 100, round, and divide the resulting number by 100.

Decode UTF-8 with Javascript

Perhaps using the textDecoder will be sufficient.

Not supported in IE though.

var decoder = new TextDecoder('utf-8'),
    decodedMessage;

decodedMessage = decoder.decode(message.data);

Handling non-UTF8 text

In this example, we decode the Russian text "??????, ???!", which means "Hello, world." In our TextDecoder() constructor, we specify the Windows-1251 character encoding, which is appropriate for Cyrillic script.

_x000D_
_x000D_
    let win1251decoder = new TextDecoder('windows-1251');
    let bytes = new Uint8Array([207, 240, 232, 226, 229, 242, 44, 32, 236, 232, 240, 33]);
    console.log(win1251decoder.decode(bytes)); // ??????, ???!
_x000D_
_x000D_
_x000D_

The interface for the TextDecoder is described here.

Retrieving a byte array from a string is equally simpel:

_x000D_
_x000D_
const decoder = new TextDecoder();
const encoder = new TextEncoder();

const byteArray = encoder.encode('Größe');
// converted it to a byte array

// now we can decode it back to a string if desired
console.log(decoder.decode(byteArray));
_x000D_
_x000D_
_x000D_

If you have it in a different encoding then you must compensate for that upon encoding. The parameter in the constructor for the TextEncoder is any one of the valid encodings listed here.

Using GCC to produce readable assembly?

Use the -S (note: capital S) switch to GCC, and it will emit the assembly code to a file with a .s extension. For example, the following command:

gcc -O2 -S -c foo.c

How do you check "if not null" with Eloquent?

I see this question is a bit old but I ran across it looking for an answer. Although I did not have success with the answers here I think this might be because I'm on PHP 7.2 and Laravel 5.7. or possible because I was just playing around with some data on the CLI using Laravel Tinker.

I have some things I tried that worked for me and others that did not that I hope will help others out.


I did not have success running:

    MyModel::whereNotNull('deleted_by')->get()->all();             // []
    MyModel::where('deleted_by', '<>', null)->get()->all();        // []
    MyModel::where('deleted_by', '!=', null)->get()->all();        // []
    MyModel::where('deleted_by', '<>', '', 'and')->get()->all();   // []
    MyModel::where('deleted_by', '<>', null, 'and')->get()->all(); // []
    MyModel::where('deleted_by', 'IS NOT', null)->get()->all();    // []

All of the above returned an empty array for me


I did however have success running:

    DB::table('my_models')->whereNotNull('deleted_by')->get()->all(); // [ ... ]

This returned all the results in an array as I expected. Note: you can drop the all() and get back a Illuminate\Database\Eloquent\Collection instead of an array if you prefer.

Trigger Change event when the Input value changed programmatically?

You are using jQuery, right? Separate JavaScript from HTML.

You can use trigger or triggerHandler.

var $myInput = $('#changeProgramatic').on('change', ChangeValue);

var anotherFunction = function() {
  $myInput.val('Another value');
  $myInput.trigger('change');
};

How to use java.String.format in Scala?

You don't need to use numbers to indicate positioning. By default, the position of the argument is simply the order in which it appears in the string.

Here's an example of the proper way to use this:

String result = String.format("The format method is %s!", "great");
// result now equals  "The format method is great!".

You will always use a % followed by some other characters to let the method know how it should display the string. %s is probably the most common, and it just means that the argument should be treated as a string.

I won't list every option, but I'll give a few examples just to give you an idea:

// we can specify the # of decimals we want to show for a floating point:
String result = String.format("10 / 3 = %.2f", 10.0 / 3.0);
// result now equals  "10 / 3 = 3.33"

// we can add commas to long numbers:
result = String.format("Today we processed %,d transactions.", 1000000);
// result now equals  "Today we processed 1,000,000 transactions."

String.format just uses a java.util.Formatter, so for a full description of the options you can see the Formatter javadocs.

And, as BalusC mentions, you will see in the documentation that is possible to change the default argument ordering if you need to. However, probably the only time you'd need / want to do this is if you are using the same argument more than once.

TypeError: 'NoneType' object has no attribute '__getitem__'

move.CompleteMove() does not return a value (perhaps it just prints something). Any method that does not return a value returns None, and you have assigned None to self.values.

Here is an example of this:

>>> def hello(x):
...    print x*2
...
>>> hello('world')
worldworld
>>> y = hello('world')
worldworld
>>> y
>>>

You'll note y doesn't print anything, because its None (the only value that doesn't print anything on the interactive prompt).

Text-decoration: none not working

I have an answer:

<a href="#">
    <div class="widget">  
        <div class="title" style="text-decoration: none;">Underlined. Why?</div>  
    </div>
</a>?

It works.

Where to find 64 bit version of chromedriver.exe for Selenium WebDriver?

Windows 8 64bit runs both 32bit and 64bit applications. You want chromedriver 32bit for the 32bit version of chrome you're using.

The current release of chromedriver (v2.16) has been mentioned as running much smoother since it's older versions (there were a lot of issues before). This post mentions this and some of the slight differences between chromedriver and running the normal firefox driver:

http://seleniumsimplified.com/2015/07/recent-course-source-code-changes-for-webdriver-2-46-0/

What you mentioned about "doesn't call main method" is an odd remark. You may want to elaborate.

Remove all occurrences of a value from a list?

for i in range(a.count(' ')):
    a.remove(' ')

Much simpler I believe.

Decoding UTF-8 strings in Python

You need to properly decode the source text. Most likely the source text is in UTF-8 format, not ASCII.

Because you do not provide any context or code for your question it is not possible to give a direct answer.

I suggest you study how unicode and character encoding is done in Python:

http://docs.python.org/2/howto/unicode.html

Copying Code from Inspect Element in Google Chrome

you dont have to do that in the Google chrome. Use the Internet explorer it offers the option to copy the css associated and after you copy and paste select the style and put that into another file .css to call into that html which you have created. Hope this will solve you problem than anything else:)

Can't build create-react-app project with custom PUBLIC_URL

Actually the way of setting environment variables is different between different Operating System.

Windows (cmd.exe)

set PUBLIC_URL=http://xxxx.com&&npm start

(Note: the lack of whitespace is intentional.)

Linux, macOS (Bash)

 PUBLIC_URL=http://xxxx.com npm start

Recommended: cross-env

{
  "scripts": {
    "serve": "cross-env PUBLIC_URL=http://xxxx.com npm start"
  }
}

ref: create-react-app/README.md#adding-temporary-environment-variables-in-your-shell at master · facebookincubator/create-react-app

Differences between Microsoft .NET 4.0 full Framework and Client Profile

A list of assemblies is available at Assemblies in the .NET Framework Client Profile on MSDN (the list is too long to include here).

If you're more interested in features, .NET Framework Client Profile on MSDN lists the following as being included:

  • common language runtime (CLR)
  • ClickOnce
  • Windows Forms
  • Windows Presentation Foundation (WPF)
  • Windows Communication Foundation (WCF)
  • Entity Framework
  • Windows Workflow Foundation
  • Speech
  • XSLT support
  • LINQ to SQL
  • Runtime design libraries for Entity Framework and WCF Data Services
  • Managed Extensibility Framework (MEF)
  • Dynamic types
  • Parallel-programming features, such as Task Parallel Library (TPL), Parallel LINQ (PLINQ), and Coordination Data Structures (CDS)
  • Debugging client applications

And the following as not being included:

  • ASP.NET
  • Advanced Windows Communication Foundation (WCF) functionality
  • .NET Framework Data Provider for Oracle
  • MSBuild for compiling

How do I redirect in expressjs while passing some context?

I had to find another solution because none of the provided solutions actually met my requirements, for the following reasons:

  • Query strings: You may not want to use query strings because the URLs could be shared by your users, and sometimes the query parameters do not make sense for a different user. For example, an error such as ?error=sessionExpired should never be displayed to another user by accident.

  • req.session: You may not want to use req.session because you need the express-session dependency for this, which includes setting up a session store (such as MongoDB), which you may not need at all, or maybe you are already using a custom session store solution.

  • next(): You may not want to use next() or next("router") because this essentially just renders your new page under the original URL, it's not really a redirect to the new URL, more like a forward/rewrite, which may not be acceptable.

So this is my fourth solution that doesn't suffer from any of the previous issues. Basically it involves using a temporary cookie, for which you will have to first install cookie-parser. Obviously this means it will only work where cookies are enabled, and with a limited amount of data.

Implementation example:

var cookieParser = require("cookie-parser");

app.use(cookieParser());

app.get("/", function(req, res) {
    var context = req.cookies["context"];
    res.clearCookie("context", { httpOnly: true });
    res.render("home.jade", context); // Here context is just a string, you will have to provide a valid context for your template engine
});

app.post("/category", function(req, res) {
    res.cookie("context", "myContext", { httpOnly: true });
    res.redirect("/");
}

What's the best way to calculate the size of a directory in .NET?

The real question is, what do you intend to use the size for?

Your first problem is that there are at least four definitions for "file size":

  • The "end of file" offset, which is the number of bytes you have to skip to go from the beginning to the end of the file.
    In other words, it is the number of bytes logically in the file (from a usage perspective).

  • The "valid data length", which is equal to the offset of the first byte which is not actually stored.
    This is always less than or equal to the "end of file", and is a multiple of the cluster size.
    For example, a 1 GB file can have a valid data length of 1 MB. If you ask Windows to read the first 8 MB, it will read the first 1 MB and pretend the rest of the data was there, returning it as zeros.

  • The "allocated size" of a file. This is always greater than or equal to the "end of file".
    This is the number of clusters that the OS has allocated for the file, multiplied by the cluster size.
    Unlike the case where the "end of file" is greater than the "valid data length", The excess bytes are not considered to be part of the file's data, so the OS will not fill a buffer with zeros if you try to read in the allocated region beyond the end of the file.

  • The "compressed size" of a file, which is only valid for compressed (and sparse?) files.
    It is equal to the size of a cluster, multiplied by the number of clusters on the volume that are actually allocated to this file.
    For non-compressed and non-sparse files, there is no notion of "compressed size"; you would use the "allocated size" instead.

Your second problem is that a "file" like C:\Foo can actually have multiple streams of data.
This name just refers to the default stream. A file might have alternate streams, like C:\Foo:Bar, whose size is not even shown in Explorer!

Your third problem is that a "file" can have multiple names ("hard links").
For example, C:\Windows\notepad.exe and C:\Windows\System32\notepad.exe are two names for the same file. Any name can be used to open any stream of the file.

Your fourth problem is that a "file" (or directory) might in fact not even be a file (or directory):
It might be a soft link (a "symbolic link" or a "reparse point") to some other file (or directory).
That other file might not even be on the same drive. It might even point to something on the network, or it might even be recursive! Should the size be infinity if it's recursive?

Your fifth is that there are "filter" drivers that make certain files or directories look like actual files or directories, even though they aren't. For example, Microsoft's WIM image files (which are compressed) can be "mounted" on a folder using a tool called ImageX, and those do not look like reparse points or links. They look just like directories -- except that the're not actually directories, and the notion of "size" doesn't really make sense for them.

Your sixth problem is that every file requires metadata.
For example, having 10 names for the same file requires more metadata, which requires space. If the file names are short, having 10 names might be as cheap as having 1 name -- and if they're long, then having multiple names can use more disk space for the metadata. (Same story with multiple streams, etc.)
Do you count these, too?

How to debug a stored procedure in Toad?

Basic Steps to Debug a Procedure in Toad

  1. Load your Procedure in Toad Editor.
  2. Put debug point on the line where you want to debug.See the first screenshot.
  3. Right click on the editor Execute->Execute PLSQL(Debugger).See the second screeshot.
  4. A window opens up,you need to select the procedure from the left side and pass parameters for that procedure and then click Execute.See the third screenshot.
  5. Now start your debugging check Debug-->Step Over...Add Watch etc.

Reference:Toad Debugger

Debug

Execute In Debug

parameter

Update data on a page without refreshing

You can read about jQuery Ajax from official jQuery Site: https://api.jquery.com/jQuery.ajax/

If you don't want to use any click event then you can set timer for periodically update.

Below code may be help you just example.

function update() {
  $.get("response.php", function(data) {
    $("#some_div").html(data);
    window.setTimeout(update, 10000);
  });
}

Above function will call after every 10 seconds and get content from response.php and update in #some_div.

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

Following worked on M1

ProductName:    macOS
ProductVersion: 11.2.1
BuildVersion:   20D74

% xcode-select --install

Agree the Terms and Conditions prompt, it will return following message on success.

% xcode-select: note: install requested for command line developer tools

How to obfuscate Python code effectively?

As other answers have stated, there really just isn't a way that's any good. Base64 can be decoded. Bytecode can be decompiled. Python was initially just interpreted, and most interpreted languages try to speed up machine interpretation more than make it difficult for human interpretation.

Python was made to be readable and shareable, not obfuscated. The language decisions about how code has to be formatted were to promote readability across different authors.

Obfuscating python code just doesn't really mesh with the language. Re-evaluate your reasons for obfuscating the code.

How do I deal with certificates using cURL while trying to access an HTTPS url?

It seems your curl points to a non-existing file with CA certs or similar.

For the primary reference on CA certs with curl, see: https://curl.haxx.se/docs/sslcerts.html

Remove or uninstall library previously added : cocoapods

Remove lib from Podfile, then pod install again.

Read input stream twice

If you are using an implementation of InputStream, you can check the result of InputStream#markSupported() that tell you whether or not you can use the method mark() / reset().

If you can mark the stream when you read, then call reset() to go back to begin.

If you can't you'll have to open a stream again.

Another solution would be to convert InputStream to byte array, then iterate over the array as many time as you need. You can find several solutions in this post Convert InputStream to byte array in Java using 3rd party libs or not. Caution, if the read content is too big you might experience some memory troubles.

Finally, if your need is to read image, then use :

BufferedImage image = ImageIO.read(new URL("http://www.example.com/images/toto.jpg"));

Using ImageIO#read(java.net.URL) also allows you to use cache.

How do you check if a selector matches something in jQuery?

no, jquery always returns a jquery object regardless if a selector was matched or not. You need to use .length

if ( $('#someDiv').length ){

}

Oracle SQL : timestamps in where clause

to_timestamp()

You need to use to_timestamp() to convert your string to a proper timestamp value:

to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

to_date()

If your column is of type DATE (which also supports seconds), you need to use to_date()

to_date('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

Example

To get this into a where condition use the following:

select * 
from TableA 
where startdate >= to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
  and startdate <= to_timestamp('12-01-2012 21:25:33', 'dd-mm-yyyy hh24:mi:ss')

Note

You never need to use to_timestamp() on a column that is of type timestamp.

What is the purpose of the single underscore "_" variable in Python?

It's just a variable name, and it's conventional in python to use _ for throwaway variables. It just indicates that the loop variable isn't actually used.

invalid_grant trying to get oAuth token from google

If you're testing this out in postman / insomnia and are just trying to get it working, hint: the server auth code (code parameter) is only good once. Meaning if you stuff up any of the other parameters in the request and get back a 400, you'll need to use a new server auth code or you'll just get another 400.

Checking if form has been submitted - PHP

For general check if there was a POST action use:

if (!empty($_POST))

EDIT: As stated in the comments, this method won't work for in some cases (e.g. with check boxes and button without a name). You really should use:

if ($_SERVER['REQUEST_METHOD'] == 'POST')

How to print table using Javascript?

Here is your code in a jsfiddle example. I have tested it and it looks fine.

http://jsfiddle.net/dimshik/9DbEP/4/

I used a simple table, maybe you are missing some CSS on your new page that was created with JavaScript.

<table border="1" cellpadding="3" id="printTable">
    <tbody><tr>
        <th>First Name</th>
        <th>Last Name</th>      
        <th>Points</th>
    </tr>
    <tr>
        <td>Jill</td>
        <td>Smith</td>      
        <td>50</td>
    </tr>
    <tr>
        <td>Eve</td>
        <td>Jackson</td>        
        <td>94</td>
    </tr>
    <tr>
        <td>John</td>
        <td>Doe</td>        
        <td>80</td>
    </tr>
    <tr>
        <td>Adam</td>
        <td>Johnson</td>        
        <td>67</td>
    </tr>
</tbody></table>

Best way to repeat a character in C#

Using String.Concat and Enumerable.Repeat which will be less expensive than using String.Join

public static Repeat(this String pattern, int count)
{
    return String.Concat(Enumerable.Repeat(pattern, count));
}

EF Core add-migration Build Failed

I had the same problem when running: dotnet ef migrations add InitialCreate so what I did is tried to build the project using: dotnet build command.

It throws an error : Startup.cs(20,27): error CS0103: bla bla for example. which you can trace to find the error in your code.

Then i refactored the code and ran: dotnet build again to check any errors until there is no errors and build is succeded. Then ran: dotnet ef migrations add InitialCreate then the build succeded.

Before and After Suite execution hook in jUnit 4.x

Provided that all your tests may extend a "technical" class and are in the same package, you can do a little trick :

public class AbstractTest {
  private static int nbTests = listClassesIn(<package>).size();
  private static int curTest = 0;

  @BeforeClass
  public static void incCurTest() { curTest++; }

  @AfterClass
  public static void closeTestSuite() {
      if (curTest == nbTests) { /*cleaning*/ }             
  }
}

public class Test1 extends AbstractTest {
   @Test
   public void check() {}
}
public class Test2 extends AbstractTest {
   @Test
   public void check() {}
}

Be aware that this solution has a lot of drawbacks :

  • must execute all tests of the package
  • must subclass a "techincal" class
  • you can not use @BeforeClass and @AfterClass inside subclasses
  • if you execute only one test in the package, cleaning is not done
  • ...

For information: listClassesIn() => How do you find all subclasses of a given class in Java?

Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

For RobotFramework

I solved it! using --no-sandbox

${chrome_options}=  Evaluate  sys.modules['selenium.webdriver'].ChromeOptions()  sys, selenium.webdriver
Call Method    ${chrome_options}    add_argument    test-type
Call Method    ${chrome_options}    add_argument    --disable-extensions
Call Method    ${chrome_options}    add_argument    --headless
Call Method    ${chrome_options}    add_argument    --disable-gpu
Call Method    ${chrome_options}    add_argument    --no-sandbox
Create Webdriver    Chrome    chrome_options=${chrome_options}

Instead of

Open Browser    about:blank    headlesschrome
Open Browser    about:blank    chrome

How to set DOM element as the first child?

Accepted answer refactored into a function:

function prependChild(parentEle, newFirstChildEle) {
    parentEle.insertBefore(newFirstChildEle, parentEle.firstChild)
}

ImportError: No module named PIL

use pil instead of PIL

from pil import Image

How to check syslog in Bash on Linux?

By default it's logged into system log at /var/log/syslog, so it can be read by:

tail -f /var/log/syslog

If the file doesn't exist, check /etc/syslog.conf to see configuration file for syslogd. Note that the configuration file could be different, so check the running process if it's using different file:

# ps wuax | grep syslog
root      /sbin/syslogd -f /etc/syslog-knoppix.conf

Note: In some distributions (such as Knoppix) all logged messages could be sent into different terminal (e.g. /dev/tty12), so to access e.g. tty12 try pressing Control+Alt+F12.

You can also use lsof tool to find out which log file the syslogd process is using, e.g.

sudo lsof -p $(pgrep syslog) | grep log$ 

To send the test message to syslogd in shell, you may try:

echo test | logger

For troubleshooting use a trace tool (strace on Linux, dtruss on Unix), e.g.:

sudo strace -fp $(cat /var/run/syslogd.pid)

PHP Check for NULL

Make sure that the value of the column is really NULL and not an empty string or 0.

Modifying a file inside a jar

You can use Vim:

vim my.jar

Vim is able to edit compressed text files, given you have unzip in your environment.

Declare Variable for a Query String

It's possible, but it requires using dynamic SQL.
I recommend reading The curse and blessings of dynamic SQL before continuing...

DECLARE @theDate varchar(60)
SET @theDate = '''2010-01-01'' AND ''2010-08-31 23:59:59'''

DECLARE @SQL VARCHAR(MAX)  
SET @SQL = 'SELECT AdministratorCode, 
                   SUM(Total) as theTotal, 
                   SUM(WOD.Quantity) as theQty, 
                   AVG(Total) as avgTotal, 
                  (SELECT SUM(tblWOD.Amount)
                     FROM tblWOD
                     JOIN tblWO on tblWOD.OrderID = tblWO.ID
                    WHERE tblWO.Approved = ''1''
                      AND tblWO.AdministratorCode = tblWO.AdministratorCode
                      AND tblWO.OrderDate BETWEEN '+ @theDate +')'

EXEC(@SQL)

Dynamic SQL is just a SQL statement, composed as a string before being executed. So the usual string concatenation occurs. Dynamic SQL is required whenever you want to do something in SQL syntax that isn't allowed, like:

  • a single parameter to represent comma separated list of values for an IN clause
  • a variable to represent both value and SQL syntax (IE: the example you provided)

EXEC sp_executesql allows you to use bind/preparedstatement parameters so you don't have to concern yourself with escaping single quotes/etc for SQL injection attacks.

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

I add the ",-std=c++0x" after "-c -fmessage-length=0",under Project Properties -> C/C++ Build -> Settings -> GCC C++ Compiler -> Miscellaneous. Dont't forget to add the comma "," as the seperator.

How to reset (clear) form through JavaScript?

You could use the following:

$('[element]').trigger('reset')

CSS transition fade on hover

This will do the trick

.gallery-item
{
  opacity:1;
}

.gallery-item:hover
{
  opacity:0;
  transition: opacity .2s ease-out;
  -moz-transition: opacity .2s ease-out;
  -webkit-transition: opacity .2s ease-out;
  -o-transition: opacity .2s ease-out;
}

How can I echo HTML in PHP?

Try it like this (heredoc syntax):

$variable = <<<XYZ
<html>
<body>

</body>
</html>
XYZ;
echo $variable;

Maven plugins can not be found in IntelliJ

If you have red squiggles underneath the project in the Maven plugin, try clicking the "Reimport All Maven Projects" button (looks like a refresh symbol).

Reimport all Maven Projects

How to change the version of the 'default gradle wrapper' in IntelliJ IDEA?

I was facing same issue for changing default gradle version from 5.0 to 4.7, Below are the steps to change default gradle version in intellij enter image description here
1) Change gradle version in gradle/wrapper/gradle-wrapper.properties in this property distributionUrl

2) Hit refresh button in gradle projects menu so that it will start downloading new gradle zip version

Count number of 1's in binary representation

That will be the shortest answer in my SO life: lookup table.

Apparently, I need to explain a bit: "if you have enough memory to play with" means, we've got all the memory we need (nevermind technical possibility). Now, you don't need to store lookup table for more than a byte or two. While it'll technically be O(log(n)) rather than O(1), just reading a number you need is O(log(n)), so if that's a problem, then the answer is, impossible—which is even shorter.

Which of two answers they expect from you on an interview, no one knows.

There's yet another trick: while engineers can take a number and talk about O(log(n)), where n is the number, computer scientists will say that actually we're to measure running time as a function of a length of an input, so what engineers call O(log(n)) is actually O(k), where k is the number of bytes. Still, as I said before, just reading a number is O(k), so there's no way we can do better than that.

How is OAuth 2 different from OAuth 1?

The previous explanations are all overly detailed and complicated IMO. Put simply, OAuth 2 delegates security to the HTTPS protocol. OAuth 1 did not require this and consequentially had alternative methods to deal with various attacks. These methods required the application to engage in certain security protocols which are complicated and can be difficult to implement. Therefore, it is simpler to just rely on the HTTPS for security so that application developers dont need to worry about it.

As to your other questions, the answer depends. Some services dont want to require the use of HTTPS, were developed before OAuth 2, or have some other requirement which may prevent them from using OAuth 2. Furthermore, there has been a lot of debate about the OAuth 2 protocol itself. As you can see, Facebook, Google, and a few others each have slightly varying versions of the protocols implemented. So some people stick with OAuth 1 because it is more uniform across the different platforms. Recently, the OAuth 2 protocol has been finalized but we have yet to see how its adoption will take.

self referential struct definition?

Lets go through basic definition of typedef. typedef use to define an alias to an existing data type either it is user defined or inbuilt.

typedef <data_type> <alias>;

for example

typedef int scores;

scores team1 = 99;

Confusion here is with the self referential structure, due to a member of same data type which is not define earlier. So In standard way you can write your code as :-

//View 1
typedef struct{ bool isParent; struct Cell* child;} Cell;

//View 2
typedef struct{
  bool isParent;
  struct Cell* child;
} Cell;

//Other Available ways, define stucture and create typedef
struct Cell {
  bool isParent;
  struct Cell* child;
};

typedef struct Cell Cell;

But last option increase some extra lines and words with usually we don't want to do (we are so lazy you know ;) ) . So prefer View 2.

Parse String to Date with Different Format in Java

Convert a string date to java.sql.Date

String fromDate = "19/05/2009";
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date dtt = df.parse(fromDate);
java.sql.Date ds = new java.sql.Date(dtt.getTime());
System.out.println(ds);//Mon Jul 05 00:00:00 IST 2010

AngularJS directive does not update on scope variable changes

We can try this

$scope.$apply(function() {
    $scope.step1 = true;
    //scope.list2.length = 0;
});

http://jsfiddle.net/Etb9d/

HTTP POST with URL query parameters -- good idea or not?

The REST camp have some guiding principles that we can use to standardize the way we use HTTP verbs. This is helpful when building RESTful API's as you are doing.

In a nutshell: GET should be Read Only i.e. have no effect on server state. POST is used to create a resource on the server. PUT is used to update or create a resource. DELETE is used to delete a resource.

In other words, if your API action changes the server state, REST advises us to use POST/PUT/DELETE, but not GET.

User agents usually understand that doing multiple POSTs is bad and will warn against it, because the intent of POST is to alter server state (eg. pay for goods at checkout), and you probably don't want to do that twice!

Compare to a GET which you can do an often as you like (idempotent).

Get operating system info

If you want to get all those information, you might want to read this:
http://php.net/manual/en/function.get-browser.php

You can run the sample code and you'll see how it works:

<?php
echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";

$browser = get_browser(null, true);
print_r($browser);
?>

The above example will output something similar to:

Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20040803 Firefox/0.9.3

Array
(
    [browser_name_regex] => ^mozilla/5\.0 (windows; .; windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$
    [browser_name_pattern] => Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9*
    [parent] => Firefox 0.9
    [platform] => WinXP
    [browser] => Firefox
    [version] => 0.9
    [majorver] => 0
    [minorver] => 9
    [cssversion] => 2
    [frames] => 1
    [iframes] => 1
    [tables] => 1
    [cookies] => 1
    [backgroundsounds] =>
    [vbscript] =>
    [javascript] => 1
    [javaapplets] => 1
    [activexcontrols] =>
    [cdf] =>
    [aol] =>
    [beta] => 1
    [win16] =>
    [crawler] =>
    [stripper] =>
    [wap] =>
    [netclr] =>
)

PowerShell Connect to FTP server and get files

The AlexFTPS library used in the question seems to be dead (was not updated since 2011).


With no external libraries

You can try to implement this without any external library. But unfortunately, neither the .NET Framework nor PowerShell have any explicit support for downloading all files in a directory (let only recursive file downloads).

You have to implement that yourself:

  • List the remote directory
  • Iterate the entries, downloading files (and optionally recursing into subdirectories - listing them again, etc.)

Tricky part is to identify files from subdirectories. There's no way to do that in a portable way with the .NET framework (FtpWebRequest or WebClient). The .NET framework unfortunately does not support the MLSD command, which is the only portable way to retrieve directory listing with file attributes in FTP protocol. See also Checking if object on FTP server is file or directory.

Your options are:

  • If you know that the directory does not contain any subdirectories, use the ListDirectory method (NLST FTP command) and simply download all the "names" as files.
  • Do an operation on a file name that is certain to fail for file and succeeds for directories (or vice versa). I.e. you can try to download the "name".
  • You may be lucky and in your specific case, you can tell a file from a directory by a file name (i.e. all your files have an extension, while subdirectories do not)
  • You use a long directory listing (LIST command = ListDirectoryDetails method) and try to parse a server-specific listing. Many FTP servers use *nix-style listing, where you identify a directory by the d at the very beginning of the entry. But many servers use a different format. The following example uses this approach (assuming the *nix format)
function DownloadFtpDirectory($url, $credentials, $localPath)
{
    $listRequest = [Net.WebRequest]::Create($url)
    $listRequest.Method = [System.Net.WebRequestMethods+Ftp]::ListDirectoryDetails
    $listRequest.Credentials = $credentials

    $lines = New-Object System.Collections.ArrayList

    $listResponse = $listRequest.GetResponse()
    $listStream = $listResponse.GetResponseStream()
    $listReader = New-Object System.IO.StreamReader($listStream)
    while (!$listReader.EndOfStream)
    {
        $line = $listReader.ReadLine()
        $lines.Add($line) | Out-Null
    }
    $listReader.Dispose()
    $listStream.Dispose()
    $listResponse.Dispose()

    foreach ($line in $lines)
    {
        $tokens = $line.Split(" ", 9, [StringSplitOptions]::RemoveEmptyEntries)
        $name = $tokens[8]
        $permissions = $tokens[0]

        $localFilePath = Join-Path $localPath $name
        $fileUrl = ($url + $name)

        if ($permissions[0] -eq 'd')
        {
            if (!(Test-Path $localFilePath -PathType container))
            {
                Write-Host "Creating directory $localFilePath"
                New-Item $localFilePath -Type directory | Out-Null
            }

            DownloadFtpDirectory ($fileUrl + "/") $credentials $localFilePath
        }
        else
        {
            Write-Host "Downloading $fileUrl to $localFilePath"

            $downloadRequest = [Net.WebRequest]::Create($fileUrl)
            $downloadRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
            $downloadRequest.Credentials = $credentials

            $downloadResponse = $downloadRequest.GetResponse()
            $sourceStream = $downloadResponse.GetResponseStream()
            $targetStream = [System.IO.File]::Create($localFilePath)
            $buffer = New-Object byte[] 10240
            while (($read = $sourceStream.Read($buffer, 0, $buffer.Length)) -gt 0)
            {
                $targetStream.Write($buffer, 0, $read);
            }
            $targetStream.Dispose()
            $sourceStream.Dispose()
            $downloadResponse.Dispose()
        }
    }
}

Use the function like:

$credentials = New-Object System.Net.NetworkCredential("user", "mypassword") 
$url = "ftp://ftp.example.com/directory/to/download/"
DownloadFtpDirectory $url $credentials "C:\target\directory"

The code is translated from my C# example in C# Download all files and subdirectories through FTP.


Using 3rd party library

If you want to avoid troubles with parsing the server-specific directory listing formats, use a 3rd party library that supports the MLSD command and/or parsing various LIST listing formats. And ideally with a support for downloading all files from a directory or even recursive downloads.

For example with WinSCP .NET assembly you can download whole directory with a single call to Session.GetFiles:

# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"

# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    Protocol = [WinSCP.Protocol]::Ftp
    HostName = "ftp.example.com"
    UserName = "user"
    Password = "mypassword"
}

$session = New-Object WinSCP.Session

try
{
    # Connect
    $session.Open($sessionOptions)

    # Download files
    $session.GetFiles("/directory/to/download/*", "C:\target\directory\*").Check()
}
finally
{
    # Disconnect, clean up
    $session.Dispose()
}    

Internally, WinSCP uses the MLSD command, if supported by the server. If not, it uses the LIST command and supports dozens of different listing formats.

The Session.GetFiles method is recursive by default.

(I'm the author of WinSCP)

Serializing/deserializing with memory stream

Use Method to Serialize and Deserialize Collection object from memory. This works on Collection Data Types. This Method will Serialize collection of any type to a byte stream. Create a Seperate Class SerilizeDeserialize and add following two methods:

public class SerilizeDeserialize
{

    // Serialize collection of any type to a byte stream

    public static byte[] Serialize<T>(T obj)
    {
        using (MemoryStream memStream = new MemoryStream())
        {
            BinaryFormatter binSerializer = new BinaryFormatter();
            binSerializer.Serialize(memStream, obj);
            return memStream.ToArray();
        }
    }

    // DSerialize collection of any type to a byte stream

    public static T Deserialize<T>(byte[] serializedObj)
    {
        T obj = default(T);
        using (MemoryStream memStream = new MemoryStream(serializedObj))
        {
            BinaryFormatter binSerializer = new BinaryFormatter();
            obj = (T)binSerializer.Deserialize(memStream);
        }
        return obj;
    }

}

How To use these method in your Class:

ArrayList arrayListMem = new ArrayList() { "One", "Two", "Three", "Four", "Five", "Six", "Seven" };
Console.WriteLine("Serializing to Memory : arrayListMem");
byte[] stream = SerilizeDeserialize.Serialize(arrayListMem);

ArrayList arrayListMemDes = new ArrayList();

arrayListMemDes = SerilizeDeserialize.Deserialize<ArrayList>(stream);

Console.WriteLine("DSerializing From Memory : arrayListMemDes");
foreach (var item in arrayListMemDes)
{
    Console.WriteLine(item);
}

What is “assert” in JavaScript?

In addition to other options like console.assert or rolling your own, you can use invariant. It has a couple of unique features:

  • It supports formatted error messages (using a %s specifier).
  • In production environments (as determined by the Node.js or Webpack environment), the error message is optional, allowing for (slightly) smaller .js.

fatal: early EOF fatal: index-pack failed

If you're on Windows, you may want to check git clone fails with "index-pack" failed?.

Basically, after running your git.exe daemon ... command, select some text from that console window. Retry pulling/cloning, it might just work now!

See this answer for more info.

Convert array to JSON string in swift

For Swift 3.0 you have to use this:

var postString = ""
    do {
        let data =  try JSONSerialization.data(withJSONObject: self.arrayNParcel, options: .prettyPrinted)
        let string1:String = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String

        postString = "arrayData=\(string1)&user_id=\(userId)&markupSrcReport=\(markup)"
    } catch {
        print(error.localizedDescription)
    }
    request.httpBody = postString.data(using: .utf8)

100% working TESTED

What is the easiest way to parse an INI File in C++?

If you need a cross-platform solution, try Boost's Program Options library.

RandomForestClassfier.fit(): ValueError: could not convert string to float

You have to do some encoding before using fit. As it was told fit() does not accept Strings but you solve this.

There are several classes that can be used :

  • LabelEncoder : turn your string into incremental value
  • OneHotEncoder : use One-of-K algorithm to transform your String into integer

Personally I have post almost the same question on StackOverflow some time ago. I wanted to have a scalable solution but didn't get any answer. I selected OneHotEncoder that binarize all the strings. It is quite effective but if you have a lot different strings the matrix will grow very quickly and memory will be required.

MySQL export into outfile : CSV escaping chars

Probably won't help but you could try creating a CSV table with that content:

DROP TABLE IF EXISTS foo_export;
CREATE TABLE foo_export LIKE foo;
ALTER TABLE foo_export ENGINE=CSV;
INSERT INTO foo_export SELECT id, 
   client,
   project,
   task,
   REPLACE(REPLACE(ifnull(ts.description,''),'\n',' '),'\r',' ') AS description, 
   time,
   date
  FROM ....