Programs & Examples On #Relationships

CakePHP select default value in SELECT input

If you are using cakephp version 3.0 and above, then you can add default value in select input using empty attribute as given in below example.

echo $this->Form->input('category_id', ['options'=>$categories,'empty'=>'Choose']);

What is the difference between char s[] and char *s?

Just to add: you also get different values for their sizes.

printf("sizeof s[] = %zu\n", sizeof(s));  //6
printf("sizeof *s  = %zu\n", sizeof(s));  //4 or 8

As mentioned above, for an array '\0' will be allocated as the final element.

Resizable table columns with jQuery

So I started writing my own, just bare bones functionality for now, will be working on it next week... http://jsfiddle.net/ydTCZ/

How to create a new text file using Python

Looks like you forgot the mode parameter when calling open, try w:

file = open("copy.txt", "w") 
file.write("Your text goes here") 
file.close() 

The default value is r and will fail if the file does not exist

'r' open for reading (default)
'w' open for writing, truncating the file first

Other interesting options are

'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists

See Doc for Python2.7 or Python3.6

-- EDIT --

As stated by chepner in the comment below, it is better practice to do it with a withstatement (it guarantees that the file will be closed)

with open("copy.txt", "w") as file:
    file.write("Your text goes here")

Redis - Connect to Remote Server

I've been stuck with the same issue, and the preceding answer did not help me (albeit well written).

The solution is here : check your /etc/redis/redis.conf, and make sure to change the default

bind 127.0.0.1

to

bind 0.0.0.0

Then restart your service (service redis-server restart)

You can then now check that redis is listening on non-local interface with

redis-cli -h 192.168.x.x ping

(replace 192.168.x.x with your IP adress)

Important note : as several users stated, it is not safe to set this on a server which is exposed to the Internet. You should be certain that you redis is protected with any means that fits your needs.

Pytorch tensor to numpy array

There are 4 dimensions of the tensor you want to convert.

[:, ::-1, :, :] 

: means that the first dimension should be copied as it is and converted, same goes for the third and fourth dimension.

::-1 means that for the second axes it reverses the the axes

Simple jQuery, PHP and JSONP example?

First of all you can't make a POST request using JSONP.

What basically is happening is that dynamically a script tag is inserted to load your data. Therefore only GET requests are possible.

Furthermore your data has to be wrapped in a callback function which is called after the request is finished to load the data in a variable.

This whole process is automated by jQuery for you. Just using $.getJSON on an external domain doesn't always work though. I can tell out of personal experience.

The best thing to do is adding &callback=? to you url.

At the server side you've got to make sure that your data is wrapped in this callback function.

ie.

echo $_GET['callback'] . '(' . $data . ')';

EDIT:

Don't have enough rep yet to comment on Liam's answer so therefore the solution over here.

Replace Liam's line

 echo "{'fullname' : 'Jeff Hansen'}";

with

 echo $_GET['callback'] . '(' . "{'fullname' : 'Jeff Hansen'}" . ')';

How do I get the name of the rows from the index of a data frame?

if you want to get the index values, you can simply do:

dataframe.index

this will output a pandas.core.index

How do I configure different environments in Angular.js?

If you're using Brunch, the plugin Constangular helps you to manage variables for different environments.

Getting the HTTP Referrer in ASP.NET

I'm using .Net Core 2 mvc, this one work for me ( to get the previews page) :

HttpContext.Request.Headers["Referer"];

Refused to execute script, strict MIME type checking is enabled?

This result is the first that pops-up in google, and is more broad than what's happening here. The following will apply to an express server:

I was trying to access resources from a nested folder.

Inside index.html i had

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

The static route was mounted at :

app.use(express.static(__dirname));

But the script.js is located in the nested folder as in: js/myStaticApp/script.js refused to execute script, meme type checking is enabled. I just changed the static route to:

app.use(express.static(path.join(__dirname, "js")));

Now it works :)

How do I properly clean up Excel interop objects?

My answer is late and its only purpose is to support the solution proposed by Govert, Porkbutts, and Dave Cousineau with a complete example. Automating Excel or other COM objects from the COM-agnostic .NET world is a “tough nut,” as we say in German, and you can easily go nuts. I rely on the following steps:

  1. For each interaction with Excel, get one and only one local instance ExcelApp of the Application interface and create a scope within which ExcelApp lives. This is necessary, because the CLR won’t free the resources of Excel before any reference to Excel goes out of scope. A new Excel process is started in the background.

  2. Implement functions that do the tasks by using ExcelApp to generate via Collection properties new objects like Workbook(s), Worksheet(s), and Cell(s). In these functions don’t care for the voodoo one-dot-good, two-dot-bad rule, don’t try to get a reference for each implicitly created object and don’t Marshall.ReleaseComObject anything. That is the job of the Garbage Collection.

  3. Within the scope of ExcelApp, call these functions and pass the reference ExcelApp.

  4. While your Excel instance is loaded, don’t allow any user actions that would bypass the Quit function that unloads this instance again.

  5. When you are done with Excel, call the separate Quit function within the scope made for Excel handling. This should be the last statement within this scope.

Before you run my app, open the task manager and watch in the Processes tab the entries in background processes. When you start the program, a new Excel process entry appears in the list and stays there until the thread wakes up again after 5 seconds. After that the Quit function will be called, stopping the Excel process that gracefully vanishes from the list of background processes.

using System;
using System.Threading;
using Excel = Microsoft.Office.Interop.Excel;

namespace GCTestOnOffice
{
  class Program
  {
    //Don't: private  static Excel.Application ExcelApp = new Excel.Application();

    private static void DoSomething(Excel.Application ExcelApp)
    {
        Excel.Workbook Wb = ExcelApp.Workbooks.Open(@"D:\Aktuell\SampleWorkbook.xlsx");
        Excel.Worksheet NewWs = Wb.Worksheets.Add();

        for (int i = 1; i < 10; i++)
        {
            NewWs.Cells[i, 1] = i;
        }
        Wb.Save();
    }

    public static void Quit(Excel.Application ExcelApp)
    {
        if (ExcelApp != null)
        {
            ExcelApp.Quit(); //Don't forget!!!!!
            ExcelApp = null;
        }
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }

    static void Main(string[] args)
    {
      {
        Excel.Application ExcelApp = new Excel.Application();
        Thread.Sleep(5000);
        DoSomething(ExcelApp);
        Quit(ExcelApp);
        //ExcelApp goes out of scope, the CLR can and will(!) release Excel
      }

      Console.WriteLine("Input a digit: ");
      int k = Console.Read(); 
    }
  }
}

If I changed the Main function to

static void Main(string[] args)
{
  Excel.Application ExcelApp = new Excel.Application();
  DoSomething(ExcelApp);

  Console.WriteLine("Input a digit: ");
  int k = Console.Read(); 
  Quit(ExcelApp);
}

the user could instead of inputting a number, hit the Close button of the console and my Excel instance lived happily ever after. So, in cases where your Excel instance remains stubbornly loaded, your cleanup feature might not be wrong, but is bypassed by unforeseen user actions.

If the Program class would have a member for the Excel instance, the CLR would not unload the Excel instance before the app terminates. That's why I prefer local references that go out of scope when they are no longer needed.

moment.js, how to get day of week number

Define "doesn't work".

_x000D_
_x000D_
const date = moment("2015-07-02"); // Thursday Feb 2015_x000D_
const dow = date.day();_x000D_
console.log(dow);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

This prints "4", as expected.

How can I make an image transparent on Android?

If you are in an XML file, use the following to make your imageview transparent!

 android:background="@null" 

Does Python have a package/module management system?

It's called setuptools. You run it with the "easy_install" command.

You can find the directory at http://pypi.python.org/

How to return a 200 HTTP Status Code from ASP.NET MVC 3 controller

In your controller you'd return an HttpStatusCodeResult like this...

[HttpPost]
public ActionResult SomeMethod(...your method parameters go here...)
{
   // todo: put your processing code here

   //If not using MVC5
   return new HttpStatusCodeResult(200);

   //If using MVC5
   return new HttpStatusCodeResult(HttpStatusCode.OK);  // OK = 200
}

Possible cases for Javascript error: "Expected identifier, string or number"

IE7 has problems with arrays of objects

columns: [
{
  field: "id",
  header: "ID"
},
{
  field: "name",
  header: "Name" , /* this comma was the problem*/ 
},
...

What is the python keyword "with" used for?

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

From Python Docs:

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

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

with expression [as variable]:
    with-block

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

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

format a Date column in a Data Frame

try this package, works wonders, and was made for date/time...

library(lubridate)
Portfolio$Date2 <- mdy(Portfolio.all$Date2)

Empty ArrayList equals null

arrayList == null if there are no instance of the class ArrayList assigned to the variable arrayList (note the upercase for classes and the lowercase for variables).

If, at anytime, you do arrayList = new ArrayList() then arrayList != null because is pointing to an instance of the class ArrayList

If you want to know if the list is empty, do

if(arrayList != null && !arrayList.isEmpty()) {
 //has items here. The fact that has items does not mean that the items are != null. 
 //You have to check the nullity for every item

}
else {
// either there is no instance of ArrayList in arrayList or the list is empty.
}

If you don't want null items in your list, I'd suggest you to extend the ArrayList class with your own, for example:

public class NotNullArrayList extends ArrayList{

@Override
public boolean add(Object o) 
   { if(o==null) throw new IllegalArgumentException("Cannot add null items to the list");
      else return super.add(o);
    }
}

Or maybe you can extend it to have a method inside your own class that re-defines the concept of "empty List".

public class NullIsEmptyArrayList extends ArrayList{

@Override
public boolean isEmpty() 
   if(super.isEmpty()) return true;
   else{
   //Iterate through the items to see if all of them are null. 
   //You can use any of the algorithms in the other responses. Return true if all are null, false otherwise. 
   //You can short-circuit to return false when you find the first item not null, so it will improve performance.
  }
}

The last two approaches are more Object-Oriented, more elegant and reusable solutions.

Updated with Jeff suggestion IAE instead of NPE.

Create a date time with month and day only, no year

How about creating a timer with the next date?

In your timer callback you create the timer for the following year? DateTime has always a year value. What you want to express is a recurring time specification. This is another type which you would need to create. DateTime is always represents a specific date and time but not a recurring date.

iOS app 'The application could not be verified' only on one device

Just had the same problem and I found out that the issue is with expired certificate. My app was distributed (AdHoc) through firebase and few days ago app was working just fine. Today I've realized that I can't install it because 'The application could not be verified'.

Finally I realized that certificate that I was using for app signing has expired 2 days ago. You need to upload it again and you'll be able to install it.

Set output of a command as a variable (with pipes)

In a batch file I usually create a file in the temp directory and append output from a program, then I call it with a variable-name to set that variable. Like this:

:: Create a set_var.cmd file containing: set %1=
set /p="set %%1="<nul>"%temp%\set_var.cmd"

:: Append output from a command
ipconfig | find "IPv4" >> "%temp%\set_var.cmd"
call "%temp%\set_var.cmd" IPAddress
echo %IPAddress%

No module named 'openpyxl' - Python 3.4 - Ubuntu

I had the same problem solved using instead of pip install :

sudo apt-get install python-openpyxl
sudo apt-get install python3-openpyxl

The sudo command also works better for other packages.

Angular 2 - View not updating after model changes

It might be that the code in your service somehow breaks out of Angular's zone. This breaks change detection. This should work:

import {Component, OnInit, NgZone} from 'angular2/core';

export class RecentDetectionComponent implements OnInit {

    recentDetections: Array<RecentDetection>;

    constructor(private zone:NgZone, // <== added
        private recentDetectionService: RecentDetectionService) {
        this.recentDetections = new Array<RecentDetection>();
    }

    getRecentDetections(): void {
        this.recentDetectionService.getJsonFromApi()
            .subscribe(recent => { 
                 this.zone.run(() => { // <== added
                     this.recentDetections = recent;
                     console.log(this.recentDetections[0].macAddress) 
                 });
        });
    }

    ngOnInit() {
        this.getRecentDetections();
        let timer = Observable.timer(2000, 5000);
        timer.subscribe(() => this.getRecentDetections());
    }
}

For other ways to invoke change detection see Triggering change detection manually in Angular

Alternative ways to invoke change detection are

ChangeDetectorRef.detectChanges()

to immediately run change detection for the current component and its children

ChangeDetectorRef.markForCheck()

to include the current component the next time Angular runs change detection

ApplicationRef.tick()

to run change detection for the whole application

Message "Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout"

For those who are looking for an explanation about jest --runInBand, you can go to the documentation.

Running Puppeteer in CI environments

GitHub - smooth-code/jest-puppeteer: Run your tests using Jest & Puppeteer

"This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded"

I got same error message. I was giving

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe "C:\MyService\MyService.exe"

Instead of

C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe "C:\MyService\MyService.exe"

How to turn IDENTITY_INSERT on and off using SQL Server 2008?

It looks necessary to put a SET IDENTITY_INSERT Database.dbo.Baskets ON; before every SQL INSERT sending batch.

You can send several INSERT ... VALUES ... commands started with one SET IDENTITY_INSERT ... ON; string at the beginning. Just don't put any batch separator between.

I don't know why the SET IDENTITY_INSERT ... ON stops working after the sending block (for ex.: .ExecuteNonQuery() in C#). I had to put SET IDENTITY_INSERT ... ON; again at the beginning of next SQL command string.

Reading input files by line using read command in shell scripting skips last line

Below code with Redirected "while-read" loop works fine for me

while read LINE
do
      let count++
      echo "$count $LINE"

done < $FILENAME

echo -e "\nTotal $count Lines read"

How to set a single, main title above all the subplots with Pyplot?

If your subplots also have titles, you may need to adjust the main title size:

plt.suptitle("Main Title", size=16)

80-characters / right margin line in Sublime Text 3

For this to work, your font also needs to be set to monospace.
If you think about it, lines can't otherwise line up perfectly perfectly.

This answer is detailed at sublime text forum:
http://www.sublimetext.com/forum/viewtopic.php?f=3&p=42052
This answer has links for choosing an appropriate font for your OS,
and gives an answer to an edge case of fonts not lining up.

Another website that lists great monospaced free fonts for programmers. http://hivelogic.com/articles/top-10-programming-fonts

On stackoverflow, see:

Michael Ruth's answer here: How to make ruler always be shown in Sublime text 2?

MattDMo's answer here: What is the default font of Sublime Text?

I have rulers set at the following:
30
50 (git commit message titles should be limited to 50 characters)
72 (git commit message details should be limited to 72 characters)
80 (Windows Command Console Window maxes out at 80 character width)

Other viewing environments that benefit from shorter lines: github: there is no word wrap when viewing a file online
So, I try to keep .js .md and other files at 70-80 characters.
Windows Console: 80 characters.

Why does Date.parse give incorrect results?

Use moment.js to parse dates:

var caseOne = moment("Jul 8, 2005", "MMM D, YYYY", true).toDate();
var caseTwo = moment("2005-07-08", "YYYY-MM-DD", true).toDate();

The 3rd argument determines strict parsing (available as of 2.3.0). Without it moment.js may also give incorrect results.

get unique machine id

There are two ways possible to this that I know:

  1. Get the Processor id of the system:

    public string getCPUId()
    {
        string cpuInfo = string.Empty;
        ManagementClass mc = new ManagementClass("win32_processor");
        ManagementObjectCollection moc = mc.GetInstances();
    
        foreach (ManagementObject mo in moc)
        {
            if (cpuInfo == "")
            {
                //Get only the first CPU's ID
                cpuInfo = mo.Properties["processorID"].Value.ToString();
                break;
            }
        }
        return cpuInfo;
    }
    
  2. Get UUID of the system:

    public string getUUID()
    {
            Process process = new Process();
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            startInfo.FileName = "CMD.exe";
            startInfo.Arguments = "/C wmic csproduct get UUID";
            process.StartInfo = startInfo;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.Start();
            process.WaitForExit();
            string output = process.StandardOutput.ReadToEnd();
            return output;
    }
    

Programmatically set image to UIImageView with Xcode 6.1/Swift

In Swift 4, if the image is returned as nil.

Click on image, on the right hand side (Utilities) -> Check Target Membership

How to check if String is null

An object can't be null - the value of an expression can be null. It's worth making the difference clear in your mind. The value of s isn't an object - it's a reference, which is either null or refers to an object.

And yes, you should just use

if (s == null)

Note that this will still use the overloaded == operator defined in string, but that will do the right thing.

Open an image using URI in Android's default gallery image viewer

A much cleaner, safer answer to this problem (you really shouldn't hard code Strings):

public void openInGallery(String imageId) {
  Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI.buildUpon().appendPath(imageId).build();
  Intent intent = new Intent(Intent.ACTION_VIEW, uri);
  startActivity(intent);
}

All you have to do is append the image id to the end of the path for the EXTERNAL_CONTENT_URI. Then launch an Intent with the View action, and the Uri.

The image id comes from querying the content resolver.

What is the final version of the ADT Bundle?

You can also get an updated version of the Eclipse's ADT plugin (based on an unreleased 24.2.0 version) that I managed to patch and compile at https://github.com/khaledev/ADT.

How to add onload event to a div element

Avoid using any interval based methods and use MutationObserver targeting a parent div of dynamically loaded div for better efficiency.

Here's the simple snippet:

HTML:

<div class="parent-static-div">
  <div class="dynamic-loaded-div">
    this div is loaded after DOM ready event
  </div>
</div>

JS:

var observer = new MutationObserver(function (mutationList, obsrvr) {
  var div_to_check = document.querySelector(".dynamic-loaded-div"); //get div by class
  // var div_to_check = document.getElementById('div-id'); //get div by id

  console.log("checking for div...");
  if (div_to_check) {
    console.log("div is loaded now"); // DO YOUR STUFF!
    obsrvr.disconnect(); // stop observing
    return;
  }
});

var parentElement = document.querySelector("parent-static-div"); // use parent div which is already present in DOM to maximise efficiency
// var parentElement = document // if not sure about parent div then just use whole 'document'

// start observing for dynamic div
observer.observe(parentElement, {
  // for properties details: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserverInit
  childList: true,
  subtree: true,
});

Stream file using ASP.NET MVC FileContentResult in a browser with a name?

public FileContentResult GetImage(int productId) { 
     Product prod = repository.Products.FirstOrDefault(p => p.ProductID == productId); 
     if (prod != null) { 
         return File(prod.ImageData, prod.ImageMimeType); 
      } else { 
         return null; 
     } 
}

Unknown SSL protocol error in connection

I get the same problem. With the last version of git and no proxy.

I fixed it:

  • sign in the GitHub
  • enter the interface: "Personal settings", then click "SSH Keys" please confirm whether you have put the 'id_rsa.pub' that generated by the command
  • 'ssh-keygen -t rsa ' on windows into github --> GIT BASH
  • 'Add SSH key' and put the 'id_rsa.pub' into it.

More info: create the key

copy the key

Casting int to bool in C/C++

There some kind of old school 'Marxismic' way to the cast int -> bool without C4800 warnings of Microsoft's cl compiler - is to use negation of negation.

int  i  = 0;
bool bi = !!i;

int  j  = 1;
bool bj = !!j;

How to write a SQL DELETE statement with a SELECT statement in the WHERE clause?

Did something like that once:

CREATE TABLE exclusions(excl VARCHAR(250));
INSERT INTO exclusions(excl)
VALUES
       ('%timeline%'),
       ('%Placeholders%'),
       ('%Stages%'),
       ('%master_stage_1205x465%'),
       ('%Accessories%'),
       ('%chosen-sprite.png'),
('%WebResource.axd');
GO
CREATE VIEW ToBeDeleted AS 
SELECT * FROM chunks
       WHERE chunks.file_id IN
       (
       SELECT DISTINCT
             lf.file_id
       FROM LargeFiles lf
       WHERE lf.file_id NOT IN
             (
             SELECT DISTINCT
                    lf.file_id
             FROM LargeFiles lf
                LEFT JOIN exclusions e ON(lf.URL LIKE e.excl)
                WHERE e.excl IS NULL
             )
       );
GO
CHECKPOINT
GO
SET NOCOUNT ON;
DECLARE @r INT;
SET @r = 1;
WHILE @r>0

BEGIN
    DELETE TOP (10000) FROM ToBeDeleted;
    SET @r = @@ROWCOUNT  
END
GO

dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib

I spent a lot of time trying all of the above, and nothing seemed to solve. Then I resorted the reinstalling ruby, and 2 minutes later the problem entirely vanished.

I hope this saves something else some time.

Plot data in descending order as appears in data frame

You want reorder(). Here is an example with dummy data

set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))

require("ggplot2")

p1 <- ggplot(df, aes(x = Category, y = Count)) +
         geom_bar(stat = "identity")

p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
         geom_bar(stat = "identity")

require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))

Giving:

enter image description here

Use reorder(Category, Count) to have Category ordered from low-high.

Using if elif fi in shell scripts

Josh Lee's answer works, but you can use the "&&" operator for better readability like this:

echo "You have provided the following arguments $arg1 $arg2 $arg3"
if [ "$arg1" = "$arg2" ] && [ "$arg1" != "$arg3" ]
then 
    echo "Two of the provided args are equal."
    exit 3
elif [ $arg1 = $arg2 ] && [ $arg1 = $arg3 ]
then
    echo "All of the specified args are equal"
    exit 0
else
    echo "All of the specified args are different"
    exit 4 
fi

Generics in C#, using type of a variable as parameter

The point about generics is to give compile-time type safety - which means that types need to be known at compile-time.

You can call generic methods with types only known at execution time, but you have to use reflection:

// For non-public methods, you'll need to specify binding flags too
MethodInfo method = GetType().GetMethod("DoesEntityExist")
                             .MakeGenericMethod(new Type[] { t });
method.Invoke(this, new object[] { entityGuid, transaction });

Ick.

Can you make your calling method generic instead, and pass in your type parameter as the type argument, pushing the decision one level higher up the stack?

If you could give us more information about what you're doing, that would help. Sometimes you may need to use reflection as above, but if you pick the right point to do it, you can make sure you only need to do it once, and let everything below that point use the type parameter in a normal way.

Use Toast inside Fragment

You can get the current activity with getActivity()

Toast.makeText(getActivity(),"Toast your message" ,Toast.LENGTH_SHORT).show();

How long to brute force a salted SHA-512 hash? (salt provided)

There isn't a single answer to this question as there are too many variables, but SHA2 is not yet really cracked (see: Lifetimes of cryptographic hash functions) so it is still a good algorithm to use to store passwords in. The use of salt is good because it prevents attack from dictionary attacks or rainbow tables. Importance of a salt is that it should be unique for each password. You can use a format like [128-bit salt][512-bit password hash] when storing the hashed passwords.

The only viable way to attack is to actually calculate hashes for different possibilities of password and eventually find the right one by matching the hashes.

To give an idea about how many hashes can be done in a second, I think Bitcoin is a decent example. Bitcoin uses SHA256 and to cut it short, the more hashes you generate, the more bitcoins you get (which you can trade for real money) and as such people are motivated to use GPUs for this purpose. You can see in the hardware overview that an average graphic card that costs only $150 can calculate more than 200 million hashes/s. The longer and more complex your password is, the longer time it will take. Calculating at 200M/s, to try all possibilities for an 8 character alphanumberic (capital, lower, numbers) will take around 300 hours. The real time will most likely less if the password is something eligible or a common english word.

As such with anything security you need to look at in context. What is the attacker's motivation? What is the kind of application? Having a hash with random salt for each gives pretty good protection against cases where something like thousands of passwords are compromised.

One thing you can do is also add additional brute force protection by slowing down the hashing procedure. As you only hash passwords once, and the attacker has to do it many times, this works in your favor. The typical way to do is to take a value, hash it, take the output, hash it again and so forth for a fixed amount of iterations. You can try something like 1,000 or 10,000 iterations for example. This will make it that many times times slower for the attacker to find each password.

How to use log4net in Asp.net core 2.0

I am porting a .Net Framework console app to .Net Core and found a similar issue with log files not getting created under certain circumstances.

When using "CreateRepository" there appears to be a difference between .net framework and .net standard.

Under .Net Framework this worked to create a unique Log instance with it's own filename using the same property from log4net.config

GlobalContext.Properties["LogName"] = LogName;
var loggerRepository = LogManager.CreateRepository(LogName);
XmlConfigurator.Configure(loggerRepository);

Under .Net Standard this didn't work and if you turn on tracing you see it can't find the configuration file ".config". It wasn't loading the previous known configuration. Once I added the configuration to the configurator it still didn't log, while not complaining about it either.

To get it working under .Net Standard with similar behavior as before, this is what I did.

var loggerRepository = LogManager.CreateRepository(LogName);
XmlConfigurator.Configure(loggerRepository,new FileInfo("log4net.config"));
var hierarchy = (Hierarchy) loggerRepository;
var appender = (RollingFileAppender)hierarchy.Root.GetAppender("RollingLogFileAppender");
appender.File = Path.Combine(Directory.GetCurrentDirectory(), "logs", $"{LogName}.log");

I didn't want to create a configuration file for every repo, so this works. Perhaps there is a better way to get the .Net Framework behavior as before and if there is please let me know below.

Check date between two other dates spring data jpa

I did use following solution to this:

findAllByStartDateLessThanEqualAndEndDateGreaterThanEqual(OffsetDateTime endDate, OffsetDateTime startDate);

How to execute an .SQL script file using c#

I couldn't find any exact and valid way to do this. So after a whole day, I came with this mixed code achieved from different sources and trying to get the job done.

But it is still generating an exception ExecuteNonQuery: CommandText property has not been Initialized even though it successfully runs the script file - in my case, it successfully creates the database and inserts data on the first startup.

public partial class Form1 : MetroForm
{
    SqlConnection cn;
    SqlCommand cm;
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        if (!CheckDatabaseExist())
        {
            GenerateDatabase();
        }
    }

    private bool CheckDatabaseExist()
    {
        SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=SalmanTradersDB;Integrated Security=true");
        try
        {
            con.Open();
            return true;
        }
        catch
        {
            return false;
        }
    }

    private void GenerateDatabase()
    {

        try
        {
            cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True");
            StringBuilder sb = new StringBuilder();
            sb.Append(string.Format("drop databse {0}", "SalmanTradersDB"));
            cm = new SqlCommand(sb.ToString() , cn);
            cn.Open();
            cm.ExecuteNonQuery();
            cn.Close();
        }
        catch
        {

        }
        try
        {
            //Application.StartupPath is the location where the application is Installed
            //Here File Path Can Be Provided Via OpenFileDialog
            if (File.Exists(Application.StartupPath + "\\script.sql"))
            {
                string script = null;
                script = File.ReadAllText(Application.StartupPath + "\\script.sql");
                string[] ScriptSplitter = script.Split(new string[] { "GO" }, StringSplitOptions.None);
                using (cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"))
                {
                    cn.Open();
                    foreach (string str in ScriptSplitter)
                    {
                        using (cm = cn.CreateCommand())
                        {
                            cm.CommandText = str;
                            cm.ExecuteNonQuery();
                        }
                    }
                }
            }
        }
        catch
        {

        }

    }

}

Web colors in an Android color xml resource file

I change all code to lower case for mono android

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    <color name="white">#FFFFFF</color>
    <color name="ivory">#FFFFF0</color>
    <color name="lightyellow">#FFFFE0</color>
    <color name="yellow">#FFFF00</color>
    <color name="snow">#FFFAFA</color>
    <color name="floralwhite">#FFFAF0</color>
    <color name="lemonchiffon">#FFFACD</color>
    <color name="cornsilk">#FFF8DC</color>
    <color name="seashell">#FFF5EE</color>
    <color name="lavenderblush">#FFF0F5</color>
    <color name="papayawhip">#FFEFD5</color>
    <color name="blanchedalmond">#FFEBCD</color>
    <color name="mistyrose">#FFE4E1</color>
    <color name="bisque">#FFE4C4</color>
    <color name="moccasin">#FFE4B5</color>
    <color name="navajowhite">#FFDEAD</color>
    <color name="peachpuff">#FFDAB9</color>
    <color name="gold">#FFD700</color>
    <color name="pink">#FFC0CB</color>
    <color name="lightpink">#FFB6C1</color>
    <color name="orange">#FFA500</color>
    <color name="lightsalmon">#FFA07A</color>
    <color name="darkorange">#FF8C00</color>
    <color name="coral">#FF7F50</color>
    <color name="hotpink">#FF69B4</color>
    <color name="tomato">#FF6347</color>
    <color name="orangered">#FF4500</color>
    <color name="deeppink">#FF1493</color>
    <color name="fuchsia">#FF00FF</color>
    <color name="magenta">#FF00FF</color>
    <color name="red">#FF0000</color>
    <color name="oldlace">#FDF5E6</color>
    <color name="lightgoldenrodyellow">#FAFAD2</color>
    <color name="linen">#FAF0E6</color>
    <color name="antiquewhite">#FAEBD7</color>
    <color name="salmon">#FA8072</color>
    <color name="ghostwhite">#F8F8FF</color>
    <color name="mintcream">#F5FFFA</color>
    <color name="whitesmoke">#F5F5F5</color>
    <color name="beige">#F5F5DC</color>
    <color name="wheat">#F5DEB3</color>
    <color name="sandybrown">#F4A460</color>
    <color name="azure">#F0FFFF</color>
    <color name="honeydew">#F0FFF0</color>
    <color name="aliceblue">#F0F8FF</color>
    <color name="khaki">#F0E68C</color>
    <color name="lightcoral">#F08080</color>
    <color name="palegoldenrod">#EEE8AA</color>
    <color name="violet">#EE82EE</color>
    <color name="darksalmon">#E9967A</color>
    <color name="lavender">#E6E6FA</color>
    <color name="lightcyan">#E0FFFF</color>
    <color name="burlywood">#DEB887</color>
    <color name="plum">#DDA0DD</color>
    <color name="gainsboro">#DCDCDC</color>
    <color name="crimson">#DC143C</color>
    <color name="palevioletred">#DB7093</color>
    <color name="goldenrod">#DAA520</color>
    <color name="orchid">#DA70D6</color>
    <color name="thistle">#D8BFD8</color>
    <color name="lightgrey">#D3D3D3</color>
    <color name="tan">#D2B48C</color>
    <color name="chocolate">#D2691E</color>
    <color name="peru">#CD853F</color>
    <color name="indianred">#CD5C5C</color>
    <color name="mediumvioletred">#C71585</color>
    <color name="silver">#C0C0C0</color>
    <color name="darkkhaki">#BDB76B</color>
    <color name="rosybrown">#BC8F8F</color>
    <color name="mediumorchid">#BA55D3</color>
    <color name="darkgoldenrod">#B8860B</color>
    <color name="firebrick">#B22222</color>
    <color name="powderblue">#B0E0E6</color>
    <color name="lightsteelblue">#B0C4DE</color>
    <color name="paleturquoise">#AFEEEE</color>
    <color name="greenyellow">#ADFF2F</color>
    <color name="lightblue">#ADD8E6</color>
    <color name="darkgray">#A9A9A9</color>
    <color name="brown">#A52A2A</color>
    <color name="sienna">#A0522D</color>
    <color name="yellowgreen">#9ACD32</color>
    <color name="darkorchid">#9932CC</color>
    <color name="palegreen">#98FB98</color>
    <color name="darkviolet">#9400D3</color>
    <color name="mediumpurple">#9370DB</color>
    <color name="lightgreen">#90EE90</color>
    <color name="darkseagreen">#8FBC8F</color>
    <color name="saddlebrown">#8B4513</color>
    <color name="darkmagenta">#8B008B</color>
    <color name="darkred">#8B0000</color>
    <color name="blueviolet">#8A2BE2</color>
    <color name="lightskyblue">#87CEFA</color>
    <color name="skyblue">#87CEEB</color>
    <color name="gray">#808080</color>
    <color name="olive">#808000</color>
    <color name="purple">#800080</color>
    <color name="maroon">#800000</color>
    <color name="aquamarine">#7FFFD4</color>
    <color name="chartreuse">#7FFF00</color>
    <color name="lawngreen">#7CFC00</color>
    <color name="mediumslateblue">#7B68EE</color>
    <color name="lightslategray">#778899</color>
    <color name="slategray">#708090</color>
    <color name="olivedrab">#6B8E23</color>
    <color name="slateblue">#6A5ACD</color>
    <color name="dimgray">#696969</color>
    <color name="mediumaquamarine">#66CDAA</color>
    <color name="cornflowerblue">#6495ED</color>
    <color name="cadetblue">#5F9EA0</color>
    <color name="darkolivegreen">#556B2F</color>
    <color name="indigo">#4B0082</color>
    <color name="mediumturquoise">#48D1CC</color>
    <color name="darkslateblue">#483D8B</color>
    <color name="steelblue">#4682B4</color>
    <color name="royalblue">#4169E1</color>
    <color name="turquoise">#40E0D0</color>
    <color name="mediumseagreen">#3CB371</color>
    <color name="limegreen">#32CD32</color>
    <color name="darkslategray">#2F4F4F</color>
    <color name="seagreen">#2E8B57</color>
    <color name="forestgreen">#228B22</color>
    <color name="lightseagreen">#20B2AA</color>
    <color name="dodgerblue">#1E90FF</color>
    <color name="midnightblue">#191970</color>
    <color name="aqua">#00FFFF</color>
    <color name="cyan">#00FFFF</color>
    <color name="springgreen">#00FF7F</color>
    <color name="lime">#00FF00</color>
    <color name="mediumspringgreen">#00FA9A</color>
    <color name="darkturquoise">#00CED1</color>
    <color name="deepskyblue">#00BFFF</color>
    <color name="darkcyan">#008B8B</color>
    <color name="teal">#008080</color>
    <color name="green">#008000</color>
    <color name="darkgreen">#006400</color>
    <color name="blue">#0000FF</color>
    <color name="mediumblue">#0000CD</color>
    <color name="darkblue">#00008B</color>
    <color name="navy">#000080</color>
    <color name="black">#000000</color>
    </resources>

What is a regex to match ONLY an empty string?

Try looking here: https://docs.python.org/2/library/re.html

I ran into the same problem you had though. I could only build a regex that would match only the empty string and also "\n". Try trimming/replacing the newline characters in the string with another character first.

I was using http://pythex.org/ and trying weird regexes like these:

()

(?:)

^$

^(?:^\n){0}$

and so on.

How to run multiple Python versions on Windows

I thought this answer might be helpful to others having multiple versions of python and wants to use pipenv to create virtual environment.

  1. navigate to the project directory, and run py -[python version] pip install pipenv, example: py -3.6 pip install pipenv
  2. run pipenv --python [version] to create the virtual environment in the version of the python you desire. example: pipenv --python 3.6
  3. run pipenv shell to activate your virtual environment.

How can I get the current user's username in Bash?

The current user's username can be gotten in pure Bash with the ${parameter@operator} parameter expansion (introduced in Bash 4.4):

$ : \\u
$ printf '%s\n' "${_@P}"

The : built-in (synonym of true) is used instead of a temporary variable by setting the last argument, which is stored in $_. We then expand it (\u) as if it were a prompt string with the P operator.

This is better than using $USER, as $USER is just a regular environmental variable; it can be modified, unset, etc. Even if it isn't intentionally tampered with, a common case where it's still incorrect is when the user is switched without starting a login shell (su's default).

Extracting specific columns in numpy array

Assuming you want to get columns 1 and 9 with that code snippet, it should be:

extractedData = data[:,[1,9]]

VSCode: How to Split Editor Vertically

In 1.20

ALT+SHIFT+0 PC (Windows, Linux)

?+?+0 Mac

Pre-1.20

ALT+SHIFT+1 PC (Windows, Linux)

?+?+1 Mac

Changes editor split layout from horizontal to vertical

In 1.25 you can split editor into Grid layout. Check View=>Editor Layout

It is nicely presented in Release notes v1.25: VS Code grid editor layout

Converting String to Int using try/except in Python

You can do :

try : 
   string_integer = int(string)
except ValueError  :
   print("This string doesn't contain an integer")

Redis command to get all available keys?

If you are using Laravel Framework then you can simply use this:

$allKeyList = Redis::KEYS("*");

print_r($allKeyList);

In Core PHP:

$redis = new Redis();

$redis->connect('hostname', 6379);

$allKeyList = $redis->keys('*');

print_r($allKeyList);

postgresql return 0 if returned value is null

I can think of 2 ways to achieve this:

  • IFNULL():

    The IFNULL() function returns a specified value if the expression is NULL.If the expression is NOT NULL, this function returns the expression.

Syntax:

IFNULL(expression, alt_value)

Example of IFNULL() with your query:

SELECT AVG( price )
FROM(
      SELECT *, cume_dist() OVER ( ORDER BY price DESC ) FROM web_price_scan
      WHERE listing_Type = 'AARM'
        AND u_kbalikepartnumbers_id = 1000307
        AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
        AND IFNULL( price, 0 ) > ( SELECT AVG( IFNULL( price, 0 ) )* 0.50
                                     FROM ( SELECT *, cume_dist() OVER ( ORDER BY price DESC )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) g
                                    WHERE cume_dist < 0.50
                                  )
        AND IFNULL( price, 0 ) < ( SELECT AVG( IFNULL( price, 0 ) ) *2
                                     FROM( SELECT *, cume_dist() OVER ( ORDER BY price desc )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) d
                                     WHERE cume_dist < 0.50)
     )s
HAVING COUNT(*) > 5
  • COALESCE()

    The COALESCE() function returns the first non-null value in a list.

Syntax:

COALESCE(val1, val2, ...., val_n)

Example of COALESCE() with your query:

SELECT AVG( price )
FROM(
      SELECT *, cume_dist() OVER ( ORDER BY price DESC ) FROM web_price_scan
      WHERE listing_Type = 'AARM'
        AND u_kbalikepartnumbers_id = 1000307
        AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
        AND COALESCE( price, 0 ) > ( SELECT AVG( COALESCE( price, 0 ) )* 0.50
                                     FROM ( SELECT *, cume_dist() OVER ( ORDER BY price DESC )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) g
                                    WHERE cume_dist < 0.50
                                  )
        AND COALESCE( price, 0 ) < ( SELECT AVG( COALESCE( price, 0 ) ) *2
                                     FROM( SELECT *, cume_dist() OVER ( ORDER BY price desc )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) d
                                     WHERE cume_dist < 0.50)
     )s
HAVING COUNT(*) > 5

Checking if a key exists in a JavaScript object?

Optional Chaining operator can also be used for this

 ?.

sorce: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined

What's the fastest way of checking if a point is inside a polygon in python

Your test is good, but it measures only some specific situation: we have one polygon with many vertices, and long array of points to check them within polygon.

Moreover, I suppose that you're measuring not matplotlib-inside-polygon-method vs ray-method, but matplotlib-somehow-optimized-iteration vs simple-list-iteration

Let's make N independent comparisons (N pairs of point and polygon)?

# ... your code...
lenpoly = 100
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in np.linspace(0,2*np.pi,lenpoly)[:-1]]

M = 10000
start_time = time()
# Ray tracing
for i in range(M):
    x,y = np.random.random(), np.random.random()
    inside1 = ray_tracing_method(x,y, polygon)
print "Ray Tracing Elapsed time: " + str(time()-start_time)

# Matplotlib mplPath
start_time = time()
for i in range(M):
    x,y = np.random.random(), np.random.random()
    inside2 = path.contains_points([[x,y]])
print "Matplotlib contains_points Elapsed time: " + str(time()-start_time)

Result:

Ray Tracing Elapsed time: 0.548588991165
Matplotlib contains_points Elapsed time: 0.103765010834

Matplotlib is still much better, but not 100 times better. Now let's try much simpler polygon...

lenpoly = 5
# ... same code

result:

Ray Tracing Elapsed time: 0.0727779865265
Matplotlib contains_points Elapsed time: 0.105288982391

error: Your local changes to the following files would be overwritten by checkout

Your error appears when you have modified a file and the branch that you are switching to has changes for this file too (from latest merge point).

Your options, as I see it, are - commit, and then amend this commit with extra changes (you can modify commits in git, as long as they're not pushed); or - use stash:

git stash save your-file-name
git checkout master
# do whatever you had to do with master
git checkout staging
git stash pop

git stash save will create stash that contains your changes, but it isn't associated with any commit or even branch. git stash pop will apply latest stash entry to your current branch, restoring saved changes and removing it from stash.

Identifier is undefined

Are you missing a function declaration?

void ac_search(uint num_patterns, uint pattern_length, const char *patterns, 
               uint num_records, uint record_length, const char *records, int *matches, Node* trie);

Add it just before your implementation of ac_benchmark_search.

Karma: Running a single test file from command line

This option is no longer supported in recent versions of karma:

see https://github.com/karma-runner/karma/issues/1731#issuecomment-174227054

The files array can be redefined using the CLI as such:

karma start --files=Array("test/Spec/services/myServiceSpec.js")

or escaped:

karma start --files=Array\(\"test/Spec/services/myServiceSpec.js\"\)

References

Negative regex for Perl string pattern match

What's wrong with using two regexs (or three)? This makes your intentions more clear and may even improve your performance:

if ($string =~ /^(Clinton|Reagan)/i && $string !~ /Bush/i) { ... }

if (($string =~ /^Clinton/i || $string =~ /^Reagan/i)
        && $string !~ /Bush/i) {
    print "$string\n"
}

Why does the order in which libraries are linked sometimes cause errors in GCC?

(See the history on this answer to get the more elaborate text, but I now think it's easier for the reader to see real command lines).


Common files shared by all below commands

$ cat a.cpp
extern int a;
int main() {
  return a;
}

$ cat b.cpp
extern int b;
int a = b;

$ cat d.cpp
int b;

Linking to static libraries

$ g++ -c b.cpp -o b.o
$ ar cr libb.a b.o
$ g++ -c d.cpp -o d.o
$ ar cr libd.a d.o

$ g++ -L. -ld -lb a.cpp # wrong order
$ g++ -L. -lb -ld a.cpp # wrong order
$ g++ a.cpp -L. -ld -lb # wrong order
$ g++ a.cpp -L. -lb -ld # right order

The linker searches from left to right, and notes unresolved symbols as it goes. If a library resolves the symbol, it takes the object files of that library to resolve the symbol (b.o out of libb.a in this case).

Dependencies of static libraries against each other work the same - the library that needs symbols must be first, then the library that resolves the symbol.

If a static library depends on another library, but the other library again depends on the former library, there is a cycle. You can resolve this by enclosing the cyclically dependent libraries by -( and -), such as -( -la -lb -) (you may need to escape the parens, such as -\( and -\)). The linker then searches those enclosed lib multiple times to ensure cycling dependencies are resolved. Alternatively, you can specify the libraries multiple times, so each is before one another: -la -lb -la.

Linking to dynamic libraries

$ export LD_LIBRARY_PATH=. # not needed if libs go to /usr/lib etc
$ g++ -fpic -shared d.cpp -o libd.so
$ g++ -fpic -shared b.cpp -L. -ld -o libb.so # specifies its dependency!

$ g++ -L. -lb a.cpp # wrong order (works on some distributions)
$ g++ -Wl,--as-needed -L. -lb a.cpp # wrong order
$ g++ -Wl,--as-needed a.cpp -L. -lb # right order

It's the same here - the libraries must follow the object files of the program. The difference here compared with static libraries is that you need not care about the dependencies of the libraries against each other, because dynamic libraries sort out their dependencies themselves.

Some recent distributions apparently default to using the --as-needed linker flag, which enforces that the program's object files come before the dynamic libraries. If that flag is passed, the linker will not link to libraries that are not actually needed by the executable (and it detects this from left to right). My recent archlinux distribution doesn't use this flag by default, so it didn't give an error for not following the correct order.

It is not correct to omit the dependency of b.so against d.so when creating the former. You will be required to specify the library when linking a then, but a doesn't really need the integer b itself, so it should not be made to care about b's own dependencies.

Here is an example of the implications if you miss specifying the dependencies for libb.so

$ export LD_LIBRARY_PATH=. # not needed if libs go to /usr/lib etc
$ g++ -fpic -shared d.cpp -o libd.so
$ g++ -fpic -shared b.cpp -o libb.so # wrong (but links)

$ g++ -L. -lb a.cpp # wrong, as above
$ g++ -Wl,--as-needed -L. -lb a.cpp # wrong, as above
$ g++ a.cpp -L. -lb # wrong, missing libd.so
$ g++ a.cpp -L. -ld -lb # wrong order (works on some distributions)
$ g++ -Wl,--as-needed a.cpp -L. -ld -lb # wrong order (like static libs)
$ g++ -Wl,--as-needed a.cpp -L. -lb -ld # "right"

If you now look into what dependencies the binary has, you note the binary itself depends also on libd, not just libb as it should. The binary will need to be relinked if libb later depends on another library, if you do it this way. And if someone else loads libb using dlopen at runtime (think of loading plugins dynamically), the call will fail as well. So the "right" really should be a wrong as well.

show all tags in git log

Note about tag of tag (tagging a tag), which is at the origin of your issue, as Charles Bailey correctly pointed out in the comment:

Make sure you study this thread, as overriding a signed tag is not as easy:

  • if you already pushed a tag, the git tag man page seriously advised against a simple git tag -f B to replace a tag name "A"
  • don't try to recreate a signed tag with git tag -f (see the thread extract below)

    (it is about a corner case, but quite instructive about tags in general, and it comes from another SO contributor Jakub Narebski):

Please note that the name of tag (heavyweight tag, i.e. tag object) is stored in two places:

  • in the tag object itself as a contents of 'tag' header (you can see it in output of "git show <tag>" and also in output of "git cat-file -p <tag>", where <tag> is heavyweight tag, e.g. v1.6.3 in git.git repository),
  • and also is default name of tag reference (reference in "refs/tags/*" namespace) pointing to a tag object.
    Note that the tag reference (appropriate reference in the "refs/tags/*" namespace) is purely local matter; what one repository has in 'refs/tags/v0.1.3', other can have in 'refs/tags/sub/v0.1.3' for example.

So when you create signed tag 'A', you have the following situation (assuming that it points at some commit)

  35805ce   <--- 5b7b4ead  <=== refs/tags/A
  (commit)       tag A
                 (tag)

Please also note that "git tag -f A A" (notice the absence of options forcing it to be an annotated tag) is a noop - it doesn't change the situation.

If you do "git tag -f -s A A": note that you force owerwriting a tag (so git assumes that you know what you are doing), and that one of -s / -a / -m options is used to force annotated tag (creation of tag object), you will get the following situation

  35805ce   <--- 5b7b4ea  <--- ada8ddc  <=== refs/tags/A
  (commit)       tag A         tag A
                 (tag)         (tag)

Note also that "git show A" would show the whole chain down to the non-tag object...

Decreasing for loops in Python impossible?

For python3 where -1 indicate the value that to be decremented in each step for n in range(6,0,-1): print(n)

How to get detailed list of connections to database in sql server 2005?

sp_who2 will actually provide a list of connections for the database server, not a database. To view connections for a single database (YourDatabaseName in this example), you can use

DECLARE @AllConnections TABLE(
    SPID INT,
    Status VARCHAR(MAX),
    LOGIN VARCHAR(MAX),
    HostName VARCHAR(MAX),
    BlkBy VARCHAR(MAX),
    DBName VARCHAR(MAX),
    Command VARCHAR(MAX),
    CPUTime INT,
    DiskIO INT,
    LastBatch VARCHAR(MAX),
    ProgramName VARCHAR(MAX),
    SPID_1 INT,
    REQUESTID INT
)

INSERT INTO @AllConnections EXEC sp_who2

SELECT * FROM @AllConnections WHERE DBName = 'YourDatabaseName'

(Adapted from SQL Server: Filter output of sp_who2.)

What is the shortest function for reading a cookie by name in JavaScript?

To have all cookies accessible by name in a Map:

const cookies = "a=b ; c = d ;e=";
const map = cookies.split(";").map((s) => s.split("=").map((s) => s.trim())).reduce((m, [k, v]) => (m.set(k, v), m), new Map());
console.log(map); //Map(3) {'a' => 'b', 'c' => 'd', 'e' => ''}
map.get("a"); //returns "b"
map.get("c"); //returns "d"
map.get("e"); //returns ""

Can you write virtual functions / methods in Java?

In Java, all public (non-private) variables & functions are Virtual by default. Moreover variables & functions using keyword final are not virtual.

Can you issue pull requests from the command line on GitHub?

I personally like to view the diff in GitHub prior to opening the PR. Additionally, I prefer writing the PR description on GitHub.

For those reasons, I made an alias (or technically a function without arguments), that opens the diff in GitHub between your current branch and master. If you add this to your .zshrc or .bashrc, you will be able to simply type open-pr and see your changes in GitHub. FYI, you will need to have your changes pushed.

function open-pr() {
  # Get the root of the github project, based on where you are configured to push to.  Ex: https://github.com/tensorflow/tensorflow
  base_uri=$(git remote -v | grep push | tr '\t' ' ' | cut -d ' ' -f 2 | rev | cut -d '.' -f 2- | rev)

  # Get your current branch name
  branch=$(git branch --show-current)

  # Create PR url and open in the default web browser
  url="${base_uri}/compare/${branch}/?expand=1"
  open $url
}

How to use jQuery in chrome extension?

Apart from the solutions already mentioned, you can also download jquery.min.js locally and then use it -

For downloading -

wget "https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"

manifest.json -

"content_scripts": [
   {
    "js": ["/path/to/jquery.min.js", ...]
   }
],

in html -

<script src="/path/to/jquery.min.js"></script>

Reference - https://developer.chrome.com/extensions/contentSecurityPolicy

convert HTML ( having Javascript ) to PDF using JavaScript

We are also looking for some way to convert html files with complex javascript to pdf. The javasript in our files contains document.write and DOM manipulation.

We have tried using a combination of HtmlUnit to parse the files and Flying Saucer to render to pdf but the results are not satisfactory enough. It works, but in our case the pdf is not close enough to what the user wants.

If you want to try this out, here is a code snippet to convert a local html file to pdf.

URL url = new File("test.html").toURI().toURL();
WebClient webClient = new WebClient(); 
HtmlPage page = webClient.getPage(url);

OutputStream os = null;
try{
   os = new FileOutputStream("test.pdf");

   ITextRenderer renderer = new ITextRenderer();
   renderer.setDocument(page,url.toString());
   renderer.layout();
   renderer.createPDF(os);
} finally{
   if(os != null) os.close();
}

Can I have multiple :before pseudo-elements for the same element?

I've resolved this using:

.element:before {
    font-family: "Font Awesome 5 Free" , "CircularStd";
    content: "\f017" " Date";
}

Using the font family "font awesome 5 free" for the icon, and after, We have to specify the font that we are using again because if we doesn't do this, navigator will use the default font (times new roman or something like this).

Good Free Alternative To MS Access

NuBuilder (www.nubuilder.net) might be right.

NuBuilder is a GPLv3-licensed PHP web application that requires MySQL as backend database. Users and programmers both use the web interface.

They promote it as a free, web based MS Access alternative. I'm creating my second NuBuilder application these days. The NuBuilder seems to be very actively developed, and I found it stable and well documented (provided you can stand video tutorials.)

Best way to get identity of inserted row?

  • @@IDENTITY returns the last identity value generated for any table in the current session, across all scopes. You need to be careful here, since it's across scopes. You could get a value from a trigger, instead of your current statement.

  • SCOPE_IDENTITY() returns the last identity value generated for any table in the current session and the current scope. Generally what you want to use.

  • IDENT_CURRENT('tableName') returns the last identity value generated for a specific table in any session and any scope. This lets you specify which table you want the value from, in case the two above aren't quite what you need (very rare). Also, as @Guy Starbuck mentioned, "You could use this if you want to get the current IDENTITY value for a table that you have not inserted a record into."

  • The OUTPUT clause of the INSERT statement will let you access every row that was inserted via that statement. Since it's scoped to the specific statement, it's more straightforward than the other functions above. However, it's a little more verbose (you'll need to insert into a table variable/temp table and then query that) and it gives results even in an error scenario where the statement is rolled back. That said, if your query uses a parallel execution plan, this is the only guaranteed method for getting the identity (short of turning off parallelism). However, it is executed before triggers and cannot be used to return trigger-generated values.

@Media min-width & max-width

The correct value for the content attribute should include initial-scale instead:

_x000D_
_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
                                                   ^^^^^^^^^^^^^^^
_x000D_
_x000D_
_x000D_

Distinct by property of class with LINQ

Another extension method for Linq-to-Objects, without using GroupBy:

    /// <summary>
    /// Returns the set of items, made distinct by the selected value.
    /// </summary>
    /// <typeparam name="TSource">The type of the source.</typeparam>
    /// <typeparam name="TResult">The type of the result.</typeparam>
    /// <param name="source">The source collection.</param>
    /// <param name="selector">A function that selects a value to determine unique results.</param>
    /// <returns>IEnumerable&lt;TSource&gt;.</returns>
    public static IEnumerable<TSource> Distinct<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)
    {
        HashSet<TResult> set = new HashSet<TResult>();

        foreach(var item in source)
        {
            var selectedValue = selector(item);

            if (set.Add(selectedValue))
                yield return item;
        }
    }

Configure apache to listen on port other than 80

If you need apache Listen port other than 80, you should add next file under ubuntu

"/etc/apache2/ports.conf"

the list of Listen ports

Listen 80
Listen 81
Listen 82

After you have to go on your Virtual hosts conf file and define next

<VirtualHost *:80>
  #...v host 1
</VirtualHost>


<VirtualHost *:81>
  #...host 2
</VirtualHost>


<VirtualHost *:82>
  #...host 3
</VirtualHost>

E: Unable to locate package mongodb-org

Try without '-org':

sudo apt-get install -y mongodb

Worked for me!

How to send a simple string between two programs using pipes?

dup2( STDIN_FILENO, newfd )

And read:

char reading[ 1025 ];
int fdin = 0, r_control;
if( dup2( STDIN_FILENO, fdin ) < 0 ){
    perror( "dup2(  )" );
    exit( errno );
}
memset( reading, '\0', 1025 );
while( ( r_control = read( fdin, reading, 1024 ) ) > 0 ){
    printf( "<%s>", reading );
    memset( reading, '\0', 1025 );
}
if( r_control < 0 )
    perror( "read(  )" );    
close( fdin );    

But, I think that fcntl can be a better solution

echo "salut" | code

How to test an SQL Update statement before running it?

I know this is a repeat of other answers, but it has some emotional support to take the extra step for testing update :D

For testing update, hash # is your friend.

If you have an update statement like:

UPDATE 
wp_history
SET history_by="admin"
WHERE
history_ip LIKE '123%'

You hash UPDATE and SET out for testing, then hash them back in:

SELECT * FROM
#UPDATE
wp_history
#SET history_by="admin"
WHERE
history_ip LIKE '123%'

It works for simple statements.

An additional practically mandatory solution is, to get a copy (backup duplicate), whenever using update on a production table. Phpmyadmin > operations > copy: table_yearmonthday. It just takes a few seconds for tables <=100M.

selenium - chromedriver executable needs to be in PATH

An answer from 2020. The following code solves this. A lot of people new to selenium seem to have to get past this step. Install the chromedriver and put it inside a folder on your desktop. Also make sure to put the selenium python project in the same folder as where the chrome driver is located.

Change USER_NAME and FOLDER in accordance to your computer.

For Windows

driver = webdriver.Chrome(r"C:\Users\USER_NAME\Desktop\FOLDER\chromedriver")

For Linux/Mac

driver = webdriver.Chrome("/home/USER_NAME/FOLDER/chromedriver")

Combining multiple condition in single case statement in Sql Server

You can put the condition after the WHEN clause, like so:

SELECT
  CASE
    WHEN PAT_ENT.SCR_DT is not null and PAT_ENTRY.ELIGIBILITY is null THEN 'Favor'
    WHEN PAT_ENT.SCR_DT is not null and PAT_ENTRY.EL = 'No' THEN 'Error'
    WHEN PAT_ENTRY.EL = 'Yes' and ISNULL(DS.DES, 'OFF') = 'OFF' THEN 'Active'
    WHEN DS.DES = 'N' THEN 'Early Term'
    WHEN DS.DES = 'Y' THEN 'Complete'
  END
FROM
  ....

Of course, the argument could be made that complex rules like this belong in your business logic layer, not in a stored procedure in the database...

Implementing multiple interfaces with Java - is there a way to delegate?

There is one way to implement multiple interface.

Just extend one interface from another or create interface that extends predefined interface Ex:

public interface PlnRow_CallBack extends OnDateSetListener {
    public void Plan_Removed();
    public BaseDB getDB();
}

now we have interface that extends another interface to use in out class just use this new interface who implements two or more interfaces

public class Calculator extends FragmentActivity implements PlnRow_CallBack {

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

    }

    @Override
    public void Plan_Removed() {

    }

    @Override
    public BaseDB getDB() {

    }
}

hope this helps

C# if/then directives for debug vs release

Slightly modified (bastardized?) version of the answer by Tod Thomson as a static function rather than a separate class (I wanted to be able to call it in a WebForm viewbinding from a viewutils class I already had included).

public static bool isDebugging() {
    bool debugging = false;

    WellAreWe(ref debugging);

    return debugging;
}

[Conditional("DEBUG")]
private static void WellAreWe(ref bool debugging)
{
    debugging = true;
}

Remove elements from collection while iterating

In Java 8, there is another approach. Collection#removeIf

eg:

List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);

list.removeIf(i -> i > 2);

How can I select item with class within a DIV?

try this instead $(".video-divs.focused"). This works if you are looking for video-divs that are focused.

what are the .map files used for in Bootstrap 3.x?

Map files (source maps) are there to de-reference minified code (css and javascript).

And they are mainly used to help developers debugging a production environment, because developers usually use minified files for production which makes it impossible to debug. Map files help them de-referencing the code to see how the original file looked like.

Using '<%# Eval("item") %>'; Handling Null Value and showing 0 against

I'm using this for string values:

<%#(String.IsNullOrEmpty(Eval("Data").ToString()) ? "0" : Eval("Data"))%>

You can also use following for nullable values:

<%#(Eval("Data") == null ? "0" : Eval("Data"))%>

Also if you're using .net 4.5 and above I suggest you use strongly typed data binding:

<asp:Repeater runat="server" DataSourceID="odsUsers" ItemType="Entity.User">
    <ItemTemplate>
        <%# Item.Title %>
    </ItemTemplate>
</asp:Repeater>

Page scroll when soft keyboard popped up

check out this.

<activity android:name=".Calculator"
    android:windowSoftInputMode="stateHidden|adjustResize" 
    android:theme="@android:style/Theme.Black.NoTitleBar">
</activity>

Can I use jQuery with Node.js?

You can use Electron, it allows hybrid browserjs and nodejs.

Before, I tried to use canvas2d in nodejs, but finally I gave up. It's not supported by nodejs default, and too hard to install it (many many ... dependeces). Until I use Electron, I can easily use all my previous browserjs code, even WebGL, and pass the result value(eg. result base64 image data) to nodejs code.

Convert Pandas column containing NaNs to dtype `int`

I had the problem a few weeks ago with a few discrete features which were formatted as 'object'. This solution seemed to work.

for col in discrete:
df[col] = pd.to_numeric(df[col], errors='coerce').astype(pd.Int64Dtype())

Ansible Ignore errors in tasks and fail at end of the playbook if any tasks had errors

You can wrap all tasks which can fail in block, and use ignore_errors: yes with that block.

tasks:
  - name: ls
    command: ls -la
  - name: pwd
    command: pwd

  - block:
    - name: ls non-existing txt file
      command: ls -la no_file.txt
    - name: ls non-existing pic
      command: ls -la no_pic.jpg
    ignore_errors: yes 

Read more about error handling in blocks here.

Jenkins Slave port number for firewall

I have a similar scenario, and had no problem connecting after setting the JNLP port as you describe, and adding a single firewall rule allowing a connection on the server using that port. Granted it is a randomly selected client port going to a known server port (a host:ANY -> server:1 rule is needed).

From my reading of the source code, I don't see a way to set the local port to use when making the request from the slave. It's unfortunate, it would be a nice feature to have.

Alternatives:

Use a simple proxy on your client that listens on port N and then does forward all data to the actual Jenkins server on the remote host using a constant local port. Connect your slave to this local proxy instead of the real Jenkins server.

Create a custom Jenkins slave build that allows an option to specify the local port to use.

Remember also if you are using HTTPS via a self-signed certificate, you must alter the configuration jenkins-slave.xml file on the slave to specify the -noCertificateCheck option on the command line.

Are one-line 'if'/'for'-statements good Python style?

Older versions of Python would only allow a single simple statement after for ...: if ...: or similar block introductory statements.

I see that one can have multiple simple statements on the same line as any of these. However, there are various combinations that don't work. For example we can:

for i in range(3): print "Here's i:"; print i

... but, on the other hand, we can't:

for i in range(3): if i % 2: print "That's odd!"

We can:

x=10
while x > 0: print x; x-=1

... but we can't:

x=10; while x > 0: print x; x-=1

... and so on.

In any event all of these are considered to be extremely NON-pythonic. If you write code like this then experience Pythonistas will probably take a dim view of your skills.

It's marginally acceptable to combine multiple statements on a line in some cases. For example:

x=0; y=1

... or even:

if some_condition(): break

... for simple break continue and even return statements or assigments.

In particular if one needs to use a series of elif one might use something like:

if     keystroke == 'q':   break
elif   keystroke == 'c':   action='continue'
elif   keystroke == 'd':   action='delete'
# ...
else:                      action='ask again'

... then you might not irk your colleagues too much. (However, chains of elif like that scream to be refactored into a dispatch table ... a dictionary that might look more like:

dispatch = {
    'q': foo.break,
    'c': foo.continue,
    'd': foo.delete
    }


# ...
while True:
    key = SomeGetKey()
    dispatch.get(key, foo.try_again)()

How to inject Javascript in WebBrowser control?

i use this:

webBrowser.Document.InvokeScript("execScript", new object[] { "alert(123)", "JavaScript" })

Get current category ID of the active page

The oldest but fastest way you can use is:

$cat_id = get_query_var('cat');

How to sort a dataframe by multiple column(s)

Alternatively, using the package Deducer

library(Deducer)
dd<- sortData(dd,c("z","b"),increasing= c(FALSE,TRUE))

Utilizing multi core for tar+gzip/bzip compression/decompression

You can use pigz instead of gzip, which does gzip compression on multiple cores. Instead of using the -z option, you would pipe it through pigz:

tar cf - paths-to-archive | pigz > archive.tar.gz

By default, pigz uses the number of available cores, or eight if it could not query that. You can ask for more with -p n, e.g. -p 32. pigz has the same options as gzip, so you can request better compression with -9. E.g.

tar cf - paths-to-archive | pigz -9 -p 32 > archive.tar.gz

Function to calculate R2 (R-squared) in R

It is not something obvious, but the caret package has a function postResample() that will calculate "A vector of performance estimates" according to the documentation. The "performance estimates" are

  • RMSE
  • Rsquared
  • mean absolute error (MAE)

and have to be accessed from the vector like this

library(caret)
vect1 <- c(1, 2, 3)
vect2 <- c(3, 2, 2)
res <- caret::postResample(vect1, vect2)
rsq <- res[2]

However, this is using the correlation squared approximation for r-squared as mentioned in another answer. I'm not sure why Max Kuhn didn't just use the conventional 1-SSE/SST.

caret also has an R2() method, although it's hard to find in the documentation.

The way to implement the normal coefficient of determination equation is:

preds <- c(1, 2, 3)
actual <- c(2, 2, 4)
rss <- sum((preds - actual) ^ 2)
tss <- sum((actual - mean(actual)) ^ 2)
rsq <- 1 - rss/tss

Not too bad to code by hand of course, but why isn't there a function for it in a language primarily made for statistics? I'm thinking I must be missing the implementation of R^2 somewhere, or no one cares enough about it to implement it. Most of the implementations, like this one, seem to be for generalized linear models.

Zoom to fit: PDF Embedded in HTML

Bit of a late response but I noticed that this information can be hard to find and haven't found the answer on SO, so here it is.

Try a differnt parameter #view=FitH to force it to fit in the horzontal space and also you need to start the querystring off with a # rather than an & making it:

filename.pdf#view=FitH

What I've noticed it is that this will work if adobe reader is embedded in the browser but chrome will use it's own version of the reader and won't respond in the same way. In my own case, the chrome browser zoomed to fit width by default, so no problem , but Internet Explorer needed the above parameters to ensure the link always opened the pdf page with the correct view setting.

For a full list of available parameters see this doc

EDIT: (lazy mode on)

enter image description here enter image description here enter image description here enter image description here enter image description here

How to use private Github repo as npm dependency

If someone is looking for another option for Git Lab and the options above do not work, then we have another option. For a local installation of Git Lab server, we have found that the approach, below, allows us to include the package dependency. We generated and use an access token to do so.

$ npm install --save-dev https://git.yourdomain.com/userOrGroup/gitLabProjectName/repository/archive.tar.gz?private_token=InsertYourAccessTokenHere

Of course, if one is using an access key this way, it should have a limited set of permissions.

Good luck!

Break promise chain and call a function based on the step in the chain where it is broken (rejected)

Attach error handlers as separate chain elements directly to the execution of the steps:

        // Handle errors for step(1)
step(1).then(null, function() { stepError(1); return $q.reject(); })
.then(function() {
                 // Attach error handler for step(2),
                 // but only if step(2) is actually executed
  return step(2).then(null, function() { stepError(2); return $q.reject(); });
})
.then(function() {
                 // Attach error handler for step(3),
                 // but only if step(3) is actually executed
  return step(3).then(null, function() { stepError(3); return $q.reject(); });
});

or using catch():

       // Handle errors for step(1)
step(1).catch(function() { stepError(1); return $q.reject(); })
.then(function() {
                 // Attach error handler for step(2),
                 // but only if step(2) is actually executed
  return step(2).catch(function() { stepError(2); return $q.reject(); });
})
.then(function() {
                 // Attach error handler for step(3),
                 // but only if step(3) is actually executed
  return step(3).catch(function() { stepError(3); return $q.reject(); });
});

Note: This is basically the same pattern as pluma suggests in his answer but using the OP's naming.

Firebase FCM force onTokenRefresh() to be called

This answer does not destroy instance id, instead it is able to get current one. It also store refreshed one in Shared preferences.

Strings.xml

<string name="pref_firebase_instance_id_key">pref_firebase_instance_id</string>
<string name="pref_firebase_instance_id_default_key">default</string>

Utility.java (any class where you want to set/get preferences)

public static void setFirebaseInstanceId(Context context, String InstanceId) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor;
    editor = sharedPreferences.edit();
    editor.putString(context.getString(R.string.pref_firebase_instance_id_key),InstanceId);
    editor.apply();
}

public static String getFirebaseInstanceId(Context context) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    String key = context.getString(R.string.pref_firebase_instance_id_key);
    String default_value = context.getString(R.string.pref_firebase_instance_id_default_key);
    return sharedPreferences.getString(key, default_value);
}

MyFirebaseInstanceIdService.java (extends FirebaseInstanceIdService)

@Override
public void onCreate()
{
    String CurrentToken = FirebaseInstanceId.getInstance().getToken();

    //Log.d(this.getClass().getSimpleName(),"Inside Instance on onCreate");
    String savedToken = Utility.getFirebaseInstanceId(getApplicationContext());
    String defaultToken = getApplication().getString(R.string.pref_firebase_instance_id_default_key);

    if(CurrentToken != null && !savedToken.equalsIgnoreCase(defaultToken))
    //currentToken is null when app is first installed and token is not available
    //also skip if token is already saved in preferences...
    {
        Utility.setFirebaseInstanceId(getApplicationContext(),CurrentToken);
    }
    super.onCreate();
}

@Override
public void onTokenRefresh() {
     .... prev code
      Utility.setFirebaseInstanceId(getApplicationContext(),refreshedToken);
     ....

}

Android 2.0 and above onCreate of service is not invoked when started automatically (source). Instead onStartCommand is overridden and used. But in actual FirebaseInstanceIdService it is declared as final and can't be overridden. However, when we start service using startService(), if service is already running, its original instance is used (which is good). Our onCreate() (defined above) also got invoked!.

Use this in begining of MainActivity or at whichever point you think you need instance id.

MyFirebaseInstanceIdService myFirebaseInstanceIdService = new MyFirebaseInstanceIdService();
Intent intent= new Intent(getApplicationContext(),myFirebaseInstanceIdService.getClass());
//Log.d(this.getClass().getSimpleName(),"Starting MyFirebaseInstanceIdService");
startService(intent); //invoke onCreate

And Finally,

Utility.getFirebaseInstanceId(getApplicationContext())

Note, you can futher enhance this by trying to move startservice() code to getFirebaseInstanceId method.

Plot multiple columns on the same graph in R

The easiest is to convert your data to a "tall" format.

s <- 
"A       B        C       G       Xax
0.451   0.333   0.034   0.173   0.22        
0.491   0.270   0.033   0.207   0.34    
0.389   0.249   0.084   0.271   0.54    
0.425   0.819   0.077   0.281   0.34
0.457   0.429   0.053   0.386   0.53    
0.436   0.524   0.049   0.249   0.12    
0.423   0.270   0.093   0.279   0.61    
0.463   0.315   0.019   0.204   0.23
"
d <- read.delim(textConnection(s), sep="")

library(ggplot2)
library(reshape2)
d <- melt(d, id.vars="Xax")

# Everything on the same plot
ggplot(d, aes(Xax,value, col=variable)) + 
  geom_point() + 
  stat_smooth() 

# Separate plots
ggplot(d, aes(Xax,value)) + 
  geom_point() + 
  stat_smooth() +
  facet_wrap(~variable)

Filter by process/PID in Wireshark

You can check for port numbers with these command examples on wireshark:-

tcp.port==80

tcp.port==14220

JUnit Testing Exceptions

@Test(expected = Exception.class)  

Tells Junit that exception is the expected result so test will be passed (marked as green) when exception is thrown.

For

@Test

Junit will consider test as failed if exception is thrown, provided it's an unchecked exception. If the exception is checked it won't compile and you will need to use other methods. This link might help.

Adding external library in Android studio

To reference an external lib project without copy, just do this: - Insert this 2 lines on setting.gradle:

  include ':your-lib-name'
  project(':your-lib-name').projectDir = new File('/path-to-your-lib/your-lib-name)

Insert this line on on dependencies part of build.gradle file:

compile project(':your-lib-name')

Sync project

importing go files in same folder

Any number of files in a directory are a single package; symbols declared in one file are available to the others without any imports or qualifiers. All of the files do need the same package foo declaration at the top (or you'll get an error from go build).

You do need GOPATH set to the directory where your pkg, src, and bin directories reside. This is just a matter of preference, but it's common to have a single workspace for all your apps (sometimes $HOME), not one per app.

Normally a Github path would be github.com/username/reponame (not just github.com/xxxx). So if you want to have main and another package, you may end up doing something under workspace/src like

github.com/
  username/
    reponame/
      main.go   // package main, importing "github.com/username/reponame/b"
      b/
        b.go    // package b

Note you always import with the full github.com/... path: relative imports aren't allowed in a workspace. If you get tired of typing paths, use goimports. If you were getting by with go run, it's time to switch to go build: run deals poorly with multiple-file mains and I didn't bother to test but heard (from Dave Cheney here) go run doesn't rebuild dirty dependencies.

Sounds like you've at least tried to set GOPATH to the right thing, so if you're still stuck, maybe include exactly how you set the environment variable (the command, etc.) and what command you ran and what error happened. Here are instructions on how to set it (and make the setting persistent) under Linux/UNIX and here is the Go team's advice on workspace setup. Maybe neither helps, but take a look and at least point to which part confuses you if you're confused.

How to get JavaScript caller function line number? How to get JavaScript caller source URL?

Answers are simple. No and No (No).

By the time javascript is running the concept of source files/urls from which the come is gone.

There is also no way to determine a line number because again by the time of execution the notion of code "lines" is no longer meaningful in Javascript.

Specific implementations may provide API hooks to allow priviledged code access to such details for the purpose of debugging but these APIs are not exposed to ordinary standard Javascript code.

best way to preserve numpy arrays on disk

I've compared performance (space and time) for a number of ways to store numpy arrays. Few of them support multiple arrays per file, but perhaps it's useful anyway.

benchmark for numpy array storage

Npy and binary files are both really fast and small for dense data. If the data is sparse or very structured, you might want to use npz with compression, which'll save a lot of space but cost some load time.

If portability is an issue, binary is better than npy. If human readability is important, then you'll have to sacrifice a lot of performance, but it can be achieved fairly well using csv (which is also very portable of course).

More details and the code are available at the github repo.

How to populate HTML dropdown list with values from database

<select name="owner">
<?php 
$sql = mysql_query("SELECT username FROM users");
while ($row = mysql_fetch_array($sql)){
echo "<option value=\"owner1\">" . $row['username'] . "</option>";
}
?>
</select>

await is only valid in async function

"await is only valid in async function"

But why? 'await' explicitly turns an async call into a synchronous call, and therefore the caller cannot be async (or asyncable) - at least, not because of the call being made at 'await'.

Regex to remove letters, symbols except numbers

Use /[^0-9.,]+/ if you want floats.

Currency formatting in Python

New in 2.7

>>> '{:20,.2f}'.format(18446744073709551616.0)
'18,446,744,073,709,551,616.00'

http://docs.python.org/dev/whatsnew/2.7.html#pep-0378

Laravel Eloquent Join vs Inner Join?

I'm sure there are other ways to accomplish this, but one solution would be to use join through the Query Builder.

If you have tables set up something like this:

users
    id
    ...

friends
    id
    user_id
    friend_id
    ...

votes, comments and status_updates (3 tables)
    id
    user_id
    ....

In your User model:

class User extends Eloquent {
    public function friends()
    {
        return $this->hasMany('Friend');
    }
}

In your Friend model:

class Friend extends Eloquent {
    public function user()
    {
        return $this->belongsTo('User');
    }
}

Then, to gather all the votes for the friends of the user with the id of 1, you could run this query:

$user = User::find(1);
$friends_votes = $user->friends()
    ->with('user') // bring along details of the friend
    ->join('votes', 'votes.user_id', '=', 'friends.friend_id')
    ->get(['votes.*']); // exclude extra details from friends table

Run the same join for the comments and status_updates tables. If you would like votes, comments, and status_updates to be in one chronological list, you can merge the resulting three collections into one and then sort the merged collection.


Edit

To get votes, comments, and status updates in one query, you could build up each query and then union the results. Unfortunately, this doesn't seem to work if we use the Eloquent hasMany relationship (see comments for this question for a discussion of that problem) so we have to modify to queries to use where instead:

$friends_votes = 
    DB::table('friends')->where('friends.user_id','1')
    ->join('votes', 'votes.user_id', '=', 'friends.friend_id');

$friends_comments = 
    DB::table('friends')->where('friends.user_id','1')
    ->join('comments', 'comments.user_id', '=', 'friends.friend_id');

$friends_status_updates = 
    DB::table('status_updates')->where('status_updates.user_id','1')
    ->join('friends', 'status_updates.user_id', '=', 'friends.friend_id');

$friends_events = 
    $friends_votes
    ->union($friends_comments)
    ->union($friends_status_updates)
    ->get();

At this point, though, our query is getting a bit hairy, so a polymorphic relationship with and an extra table (like DefiniteIntegral suggests below) might be a better idea.

Flask Value error view function did not return a response

The following does not return a response:

You must return anything like return afunction() or return 'a string'.

This can solve the issue

Automatically capture output of last command into a variable using Bash?

Disclamers:

  • This answer is late half a year :D
  • I'm a heavy tmux user
  • You have to run your shell in tmux for this to work

When running an interactive shell in tmux, you can easily access the data currently displayed on a terminal. Let's take a look at some interesting commands:

  • tmux capture-pane: this one copies the displayed data to one of the tmux's internal buffers. It can copy the history that's currently not visible, but we're not interested in that now
  • tmux list-buffers: this displays the info about the captured buffers. The newest one will have the number 0.
  • tmux show-buffer -b (buffer num): this prints the contents of the given buffer on a terminal
  • tmux paste-buffer -b (buffer num): this pastes the contents of the given buffer as input

Yeah, this gives us a lot of possibilities now :) As for me, I set up a simple alias: alias L="tmux capture-pane; tmux showb -b 0 | tail -n 3 | head -n 1" and now every time I need to access the last line i simply use $(L) to get it.

This is independent of the output stream the program uses (be it stdin or stderr), the printing method (ncurses, etc.) and the program's exit code - the data just needs to be displayed.

Finding the id of a parent div using Jquery

You could use event delegation on the parent div. Or use the closest method to find the parent of the button.

The easiest of the two is probably the closest.

var id = $("button").closest("div").prop("id");

Is there an easy way to convert jquery code to javascript?

This will get you 90% of the way there ; )

window.$ = document.querySelectorAll.bind(document)

For Ajax, the Fetch API is now supported on the current version of every major browser. For $.ready(), DOMContentLoaded has near universal support. You Might Not Need jQuery gives equivalent native methods for other common jQuery functions.

Zepto offers similar functionality but weighs in at 10K zipped. There are custom Ajax builds for jQuery and Zepto as well as some micro frameworks, but jQuery/Zepto have solid support and 10KB is only ~1 second on a 56K modem.

Dictionary text file

There's also WordNet. Its data files format are well-documented.
I used it for building an embeddable dictionary library for iOS developers (www.lexicontext.com) and also in one of my apps.

Setting Curl's Timeout in PHP

Your code sets the timeout to 1000 seconds. For milliseconds, use CURLOPT_TIMEOUT_MS.

How would I create a UIAlertView in Swift?

try This. Put Bellow Code In Button.

let alert = UIAlertController(title: "Your_Title_Text", message: "Your_MSG", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Your_Text", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated:true, completion: nil)

What is stability in sorting algorithms and why is it important?

I know there are many answers for this, but to me, this answer, by Robert Harvey, summarized it much more clearly:

A stable sort is one which preserves the original order of the input set, where the [unstable] algorithm does not distinguish between two or more items.

Source

How to pass integer from one Activity to another?

It's simple. On the sender side, use Intent.putExtra:

Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("intVariableName", intValue);
startActivity(myIntent);

On the receiver side, use Intent.getIntExtra:

 Intent mIntent = getIntent();
 int intValue = mIntent.getIntExtra("intVariableName", 0);

What is a void pointer in C++?

A void* does not mean anything. It is a pointer, but the type that it points to is not known.

It's not that it can return "anything". A function that returns a void* generally is doing one of the following:

  • It is dealing in unformatted memory. This is what operator new and malloc return: a pointer to a block of memory of a certain size. Since the memory does not have a type (because it does not have a properly constructed object in it yet), it is typeless. IE: void.
  • It is an opaque handle; it references a created object without naming a specific type. Code that does this is generally poorly formed, since this is better done by forward declaring a struct/class and simply not providing a public definition for it. Because then, at least it has a real type.
  • It returns a pointer to storage that contains an object of a known type. However, that API is used to deal with objects of a wide variety of types, so the exact type that a particular call returns cannot be known at compile time. Therefore, there will be some documentation explaining when it stores which kinds of objects, and therefore which type you can safely cast it to.

This construct is nothing like dynamic or object in C#. Those tools actually know what the original type is; void* does not. This makes it far more dangerous than any of those, because it is very easy to get it wrong, and there's no way to ask if a particular usage is the right one.

And on a personal note, if you see code that uses void*'s "often", you should rethink what code you're looking at. void* usage, especially in C++, should be rare, used primary for dealing in raw memory.

How to build jars from IntelliJ properly?

Here's how to build a jar with IntelliJ 10 http://blogs.jetbrains.com/idea/2010/08/quickly-create-jar-artifact/

File -> Project Structure -> Project Settings -> Artifacts -> Click green plus sign -> Jar -> From modules with dependencies...

The above sets the "skeleton" to where the jar will be saved to. To actually build and save it do the following:

Extract to the target Jar

OK

Build | Build Artifact | Build

Try Extracting the .jar file from

ProjectName | out | artifacts | ProjectName_jar | ProjectName.jar

Subtract two variables in Bash

You just need a little extra whitespace around the minus sign, and backticks:

COUNT=`expr $FIRSTV - $SECONDV`

Be aware of the exit status:

The exit status is 0 if EXPRESSION is neither null nor 0, 1 if EXPRESSION is null or 0.

Keep this in mind when using the expression in a bash script in combination with set -e which will exit immediately if a command exits with a non-zero status.

Regarding C++ Include another class

What is the basic problem in your code?

Your code needs to be separated out in to interfaces(.h) and Implementations(.cpp).
The compiler needs to see the composition of a type when you write something like

ClassTwo obj;

This is because the compiler needs to reserve enough memory for object of type ClassTwo to do so it needs to see the definition of ClassTwo. The most common way to do this in C++ is to split your code in to header files and source files.
The class definitions go in the header file while the implementation of the class goes in to source files. This way one can easily include header files in to other source files which need to see the definition of class who's object they create.

Why can't I simply put all code in cpp files and include them in other files?

You cannot simple put all the code in source file and then include that source file in other files.C++ standard mandates that you can declare a entity as many times as you need but you can define it only once(One Definition Rule(ODR)). Including the source file would violate the ODR because a copy of the entity is created in every translation unit where the file is included.

How to solve this particular problem?

Your code should be organized as follows:

//File1.h

Define ClassOne 

//File2.h

#include <iostream>
#include <string>


class ClassTwo
{
private:
   string myType;
public:
   void setType(string);
   std::string getType();
}; 

//File1.cpp

#include"File1.h"

Implementation of ClassOne 

//File2.cpp

#include"File2.h"

void ClassTwo::setType(std::string sType)
{
    myType = sType;
}

void ClassTwo::getType(float fVal)
{
    return myType;
} 

//main.cpp

#include <iostream>
#include <string>
#include "file1.h"
#include "file2.h"
using namespace std;

int main()
{

    ClassOne cone;
    ClassTwo ctwo;

    //some codes
}

Is there any alternative means rather than including header files?

If your code only needs to create pointers and not actual objects you might as well use Forward Declarations but note that using forward declarations adds some restrictions on how that type can be used because compiler sees that type as an Incomplete type.

How to format a Java string with leading zero?

You can use this:

org.apache.commons.lang.StringUtils.leftPad("Apple", 8, "0")

How to Select Min and Max date values in Linq Query

dim mydate = from cv in mydata.t1s
  select cv.date1 asc

datetime mindata = mydate[0];

Calling remove in foreach loop in Java

for (String name : new ArrayList<String>(names)) {
    // Do something
    names.remove(nameToRemove);
}

You clone the list names and iterate through the clone while you remove from the original list. A bit cleaner than the top answer.

commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated

<ui:composition>  
  <h:form id="form1">
    <p:dialog id="dialog1">
      <p:commandButton value="Save" action="#{bean.method1}" /> <!--Working-->
    </p:dialog>
  </h:form>

  <h:form id="form2">
    <p:dialog id="dialog2">
      <p:commandButton value="Save" action="#{bean.method2}" /> <!--Not Working-->
    </p:dialog>
  </h:form>
</ui:composition>

To solve;

<ui:composition>  
  <h:form id="form1">
    <p:dialog id="dialog1">
      <p:commandButton value="Save" action="#{bean.method1}" />   <!-- Working  -->
    </p:dialog>

    <p:dialog id="dialog2">
      <p:commandButton value="Save" action="#{bean.method2}" />   <!--Working  -->
    </p:dialog>
  </h:form>
  <h:form id="form2">
    <!-- ..........  -->
  </h:form>
</ui:composition>

bash script read all the files in directory

To write it with a while loop you can do:

ls -f /var | while read -r file; do cmd $file; done

The primary disadvantage of this is that cmd is run in a subshell, which causes some difficulty if you are trying to set variables. The main advantages are that the shell does not need to load all of the filenames into memory, and there is no globbing. When you have a lot of files in the directory, those advantages are important (that's why I use -f on ls; in a large directory ls itself can take several tens of seconds to run and -f speeds that up appreciably. In such cases 'for file in /var/*' will likely fail with a glob error.)

Is it possible to make a Tree View with Angular?

You can use angular-recursion-injector for that: https://github.com/knyga/angular-recursion-injector

Allows you to do unlimited depth nesting with conditioning. Does recompilation only if needed and compiles only right elements. No magic in code.

<div class="node">
  <span>{{name}}</span>

  <node--recursion recursion-if="subNode" ng-model="subNode"></node--recursion>
</div>

One of the things that allows it to work faster and simpler then the other solutions is "--recursion" suffix.

Disable Tensorflow debugging information

To add some flexibility here, you can achieve more fine-grained control over the level of logging by writing a function that filters out messages however you like:

logging.getLogger('tensorflow').addFilter(my_filter_func)

where my_filter_func accepts a LogRecord object as input [LogRecord docs] and returns zero if you want the message thrown out; nonzero otherwise.

Here's an example filter that only keeps every nth info message (Python 3 due to the use of nonlocal here):

def keep_every_nth_info(n):
    i = -1
    def filter_record(record):
        nonlocal i
        i += 1
        return int(record.levelname != 'INFO' or i % n == 0)
    return filter_record

# Example usage for TensorFlow:
logging.getLogger('tensorflow').addFilter(keep_every_nth_info(5))

All of the above has assumed that TensorFlow has set up its logging state already. You can ensure this without side effects by calling tf.logging.get_verbosity() before adding a filter.

How can I detect when an Android application is running in the emulator?

if (Build.BRAND.equalsIgnoreCase("generic")) {
    // Is the emulator
}

All BUILD references are build.prop values, so you have to consider that if you are going to put this into release code, you may have some users with root that have modified theirs for whatever reason. There are virtually no modifications that require using generic as the brand unless specifically trying to emulate the emulator.

Fingerprint is the build compile and kernel compile signature. There are builds that use generic, usually directly sourced from Google.

On a device that has been modified, the IMEI has a possibility of being zeroed out as well, so that is unreliable unless you are blocking modified devices altogether.

Goldfish is the base android build that all other devices are extended from. EVERY Android device has an init.goldfish.rc unless hacked and removed for unknown reasons.

css selector to match an element without attribute x

Just wanted to add to this, you can have the :not selector in oldIE using selectivizr: http://selectivizr.com/

How to get a responsive button in bootstrap 3

For anyone who may be interested, another approach is using @media queries to scale the buttons on different viewport widths..

Demo: http://bootply.com/93706

Finding duplicate values in a SQL table

In case you work with Microsoft Access, this way works:

CREATE TABLE users (id int, name varchar(10), email varchar(50));

INSERT INTO users VALUES (1, 'John', '[email protected]');
INSERT INTO users VALUES (2, 'Sam', '[email protected]');
INSERT INTO users VALUES (3, 'Tom', '[email protected]');
INSERT INTO users VALUES (4, 'Bob', '[email protected]');
INSERT INTO users VALUES (5, 'Tom', '[email protected]');

SELECT name, email, COUNT(*) AS CountOf
FROM users
GROUP BY name, email
HAVING COUNT(*)>1;

DELETE *
FROM users
WHERE id IN (
    SELECT u1.id 
    FROM users u1, users u2 
    WHERE u1.name = u2.name AND u1.email = u2.email AND u1.id > u2.id
);

Thanks to Tancrede Chazallet for the delete code.

Letsencrypt add domain to existing certificate

You need to specify all of the names, including those already registered.

I used the following command originally to register some certificates:

/opt/certbot/certbot-auto certonly --webroot --agree-tos -w /srv/www/letsencrypt/ \
--email [email protected] \
--expand -d example.com,www.example.com

... and just now I successfully used the following command to expand my registration to include a new subdomain as a SAN:

/opt/certbot/certbot-auto certonly --webroot --agree-tos -w /srv/www/letsencrypt/ \
--expand -d example.com,www.example.com,click.example.com

From the documentation:

--expand "If an existing cert covers some subset of the requested names, always expand and replace it with the additional names."

Don't forget to restart the server to load the new certificates if you are running nginx.

WCF Error - Could not find default endpoint element that references contract 'UserService.UserService'

In case if you are using WPF application using PRISM framework then configuration should exist in your start up project (i.e. in the project where your bootstrapper resides.)

In short just remove it from the class library and put into a start up project.

How to implement endless list with RecyclerView?

Try below:

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.LayoutManager;

/**
 * Abstract Endless ScrollListener
 * 
 */
public abstract class EndlessScrollListener extends
        RecyclerView.OnScrollListener {
    // The minimum amount of items to have below your current scroll position
    // before loading more.
    private int visibleThreshold = 10;
    // The current offset index of data you have loaded
    private int currentPage = 1;
    // True if we are still waiting for the last set of data to load.
    private boolean loading = true;
    // The total number of items in the data set after the last load
    private int previousTotal = 0;
    private int firstVisibleItem;
    private int visibleItemCount;
    private int totalItemCount;
    private LayoutManager layoutManager;

    public EndlessScrollListener(LayoutManager layoutManager) {
        validateLayoutManager(layoutManager);
        this.layoutManager = layoutManager;
    }

    public EndlessScrollListener(int visibleThreshold,
            LayoutManager layoutManager, int startPage) {
        validateLayoutManager(layoutManager);
        this.visibleThreshold = visibleThreshold;
        this.layoutManager = layoutManager;
        this.currentPage = startPage;
    }

    private void validateLayoutManager(LayoutManager layoutManager)
            throws IllegalArgumentException {
        if (null == layoutManager
                || !(layoutManager instanceof GridLayoutManager)
                || !(layoutManager instanceof LinearLayoutManager)) {
            throw new IllegalArgumentException(
                    "LayoutManager must be of type GridLayoutManager or LinearLayoutManager.");
        }
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        visibleItemCount = recyclerView.getChildCount();
        totalItemCount = layoutManager.getItemCount();
        if (layoutManager instanceof GridLayoutManager) {
            firstVisibleItem = ((GridLayoutManager) layoutManager)
                    .findFirstVisibleItemPosition();
        } else if (layoutManager instanceof LinearLayoutManager) {
            firstVisibleItem = ((LinearLayoutManager) layoutManager)
                    .findFirstVisibleItemPosition();
        }
        if (loading) {
            if (totalItemCount > previousTotal) {
                loading = false;
                previousTotal = totalItemCount;
            }
        }
        if (!loading
                && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
            // End has been reached do something
            currentPage++;
            onLoadMore(currentPage);
            loading = true;
        }
    }

    // Defines the process for actually loading more data based on page
    public abstract void onLoadMore(int page);

}

What is the best way to parse html in C#?

Depending on your needs you might go for the more feature-rich libraries. I tried most/all of the solutions suggested, but what stood out head & shoulders was Html Agility Pack. It is a very forgiving and flexible parser.

how to do bitwise exclusive or of two strings in python?

I've found that the ''.join(chr(ord(a)^ord(b)) for a,b in zip(s,m)) method is pretty slow. Instead, I've been doing this:

fmt = '%dB' % len(source)
s = struct.unpack(fmt, source)
m = struct.unpack(fmt, xor_data)
final = struct.pack(fmt, *(a ^ b for a, b in izip(s, m)))

How can I print message in Makefile?

It's not clear what you want, or whether you want this trick to work with different targets, or whether you've defined these targets elsewhere, or what version of Make you're using, but what the heck, I'll go out on a limb:

ifeq (yes, ${TEST})
CXXFLAGS := ${CXXFLAGS} -DDESKTOP_TEST
test:
$(info ************  TEST VERSION ************)
else
release:
$(info ************ RELEASE VERSIOIN **********)
endif

Math.random() versus Random.nextInt(int)

another important point is that Random.nextInt(n) is repeatable since you can create two Random object with the same seed. This is not possible with Math.random().

Best way to log POST data in Apache?

Use Apache's mod_dumpio. Be careful for obvious reasons.

Note that mod_dumpio stops logging binary payloads at the first null character. For example a multipart/form-data upload of a gzip'd file will probably only show the first few bytes with mod_dumpio.

Also note that Apache might not mention this module in httpd.conf even when it's present in the /modules folder. Just manually adding LoadModule will work fine.

Java - How to access an ArrayList of another class?

Put them in an arrayList in your first class like:

import java.util.ArrayList;
    public class numbers {

    private int number1 = 50;
    private int number2 = 100;

    public ArrayList<int> getNumberList() {
        ArrayList<int> numbersList= new ArrayList<int>();
        numbersList.add(number1);
        numberList.add(number2);
        ....
        return numberList;
    }
}

Then, in your test class you can call numbers.getNumberList() to get your arrayList. In addition, you might want to create methods like addToList / removeFromList in your numbers class so you can handle it the way you need it.

You can also access a variable declared in one class from another simply like

numbers.numberList;

if you have it declared there as public.

But it isn't such a good practice in my opinion, since you probably need to modify this list in your code later. Note that you have to add your class to the import list.

If you can tell me what your app requirements are, i'll be able tell you more precise what i think it's best to do.

Combine two columns of text in pandas dataframe

The method cat() of the .str accessor works really well for this:

>>> import pandas as pd
>>> df = pd.DataFrame([["2014", "q1"], 
...                    ["2015", "q3"]],
...                   columns=('Year', 'Quarter'))
>>> print(df)
   Year Quarter
0  2014      q1
1  2015      q3
>>> df['Period'] = df.Year.str.cat(df.Quarter)
>>> print(df)
   Year Quarter  Period
0  2014      q1  2014q1
1  2015      q3  2015q3

cat() even allows you to add a separator so, for example, suppose you only have integers for year and period, you can do this:

>>> import pandas as pd
>>> df = pd.DataFrame([[2014, 1],
...                    [2015, 3]],
...                   columns=('Year', 'Quarter'))
>>> print(df)
   Year Quarter
0  2014       1
1  2015       3
>>> df['Period'] = df.Year.astype(str).str.cat(df.Quarter.astype(str), sep='q')
>>> print(df)
   Year Quarter  Period
0  2014       1  2014q1
1  2015       3  2015q3

Joining multiple columns is just a matter of passing either a list of series or a dataframe containing all but the first column as a parameter to str.cat() invoked on the first column (Series):

>>> df = pd.DataFrame(
...     [['USA', 'Nevada', 'Las Vegas'],
...      ['Brazil', 'Pernambuco', 'Recife']],
...     columns=['Country', 'State', 'City'],
... )
>>> df['AllTogether'] = df['Country'].str.cat(df[['State', 'City']], sep=' - ')
>>> print(df)
  Country       State       City                   AllTogether
0     USA      Nevada  Las Vegas      USA - Nevada - Las Vegas
1  Brazil  Pernambuco     Recife  Brazil - Pernambuco - Recife

Do note that if your pandas dataframe/series has null values, you need to include the parameter na_rep to replace the NaN values with a string, otherwise the combined column will default to NaN.

Convert PDF to image with high resolution

I have found it both faster and more stable when batch-processing large PDFs into PNGs and JPGs to use the underlying gs (aka Ghostscript) command that convert uses.

You can see the command in the output of convert -verbose and there are a few more tweaks possible there (YMMV) that are difficult / impossible to access directly via convert.

However, it would be harder to do your trimming and sharpening using gs, so, as I said, YMMV!

write newline into a file

Solution:

in WINDOWS you should write "\r\n" for a new line.

Error Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35

I have a files only website. Added MVC 5 to webforms application (targeting net45). I had to modify the packages.config

package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net45"

to

package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net45" developmentDependency="true"

in order for it to startup on local box in debug mode (previously had the top described error). Running VS 2017 on Windows 7...opened through File > Open > Web Site > File (chose root directory outside of IIS).

mysql update query with sub query

You can check your eav_attributes table to find the relevant attribute IDs for each image role, such as; eav_attributes

Then you can use those to set whichever role to any other role for all products like so;

UPDATE catalog_product_entity_varchar AS `v` INNER JOIN (SELECT `value`,`entity_id` FROM `catalog_product_entity_varchar` WHERE `attribute_id`=86) AS `j` ON `j`.`entity_id`=`v`.entity_id SET `v`.`value`=j.`value` WHERE `v`.attribute_id = 85 AND `v`.`entity_id`=`j`.`entity_id`

The above will set all your 'base' roles to the 'small' image of the same product.

Warning: DOMDocument::loadHTML(): htmlParseEntityRef: expecting ';' in Entity,

Another possibile solution is

$sContent = htmlspecialchars($sHTML);
$oDom = new DOMDocument();
$oDom->loadHTML($sContent);
echo html_entity_decode($oDom->saveHTML());

DataAnnotations validation (Regular Expression) in asp.net mvc 4 - razor view

UPDATE 9 July 2012 - Looks like this is fixed in RTM.

  1. We already imply ^ and $ so you don't need to add them. (It doesn't appear to be a problem to include them, but you don't need them)
  2. This appears to be a bug in ASP.NET MVC 4/Preview/Beta. I've opened a bug

View source shows the following:

data-val-regex-pattern="([a-zA-Z0-9 .&amp;&#39;-]+)"                  <-- MVC 3
data-val-regex-pattern="([a-zA-Z0-9&#32;.&amp;amp;&amp;#39;-]+)"      <-- MVC 4/Beta

It looks like we're double encoding.

Start / Stop a Windows Service from a non-Administrator user account

subinacl.exe command-line tool is probably the only viable and very easy to use from anything in this post. You cant use a GPO with non-system services and the other option is just way way way too complicated.

How to read the output from git diff?

The default output format (which originally comes from a program known as diff if you want to look for more info) is known as a “unified diff”. It contains essentially 4 different types of lines:

  • context lines, which start with a single space,
  • insertion lines that show a line that has been inserted, which start with a +,
  • deletion lines, which start with a -, and
  • metadata lines which describe higher level things like which file this is talking about, what options were used to generate the diff, whether the file changed its permissions, etc.

I advise that you practice reading diffs between two versions of a file where you know exactly what you changed. Like that you'll recognize just what is going on when you see it.

How to drop column with constraint?

The following worked for me against a SQL Azure backend (using SQL Server Management Studio), so YMMV, but, if it works for you, it's waaaaay simpler than the other solutions.

ALTER TABLE MyTable
    DROP CONSTRAINT FK_MyColumn
    CONSTRAINT DK_MyColumn
    -- etc...
    COLUMN MyColumn
GO

Accessing the logged-in user in a template

You can access user data directly in the twig template without requesting anything in the controller. The user is accessible like that : app.user.

Now, you can access every property of the user. For example, you can access the username like that : app.user.username.

Warning, if the user is not logged, the app.user is null.

If you want to check if the user is logged, you can use the is_granted twig function. For example, if you want to check if the user has ROLE_ADMIN, you just have to do is_granted("ROLE_ADMIN").

So, in every of your pages you can do :

{% if is_granted("ROLE") %}
    Hi {{ app.user.username }}
{% endif %}

Regular expression to extract URL from an HTML link

You can use this.

<a[^>]+href=["'](.*?)["']

"Could not find a version that satisfies the requirement opencv-python"

A way to do this is to install Anaconda on your computer.

Then you should be able to do:

pip install opencv-python

or

conda install opencv

Difference between app.use and app.get in express.js

app.use is the "lower level" method from Connect, the middleware framework that Express depends on.

Here's my guideline:

  • Use app.get if you want to expose a GET method.
  • Use app.use if you want to add some middleware (a handler for the HTTP request before it arrives to the routes you've set up in Express), or if you'd like to make your routes modular (for example, expose a set of routes from an npm module that other web applications could use).

Is the 'as' keyword required in Oracle to define an alias?

Both are correct. Oracle allows the use of both.

Get day of week in SQL Server 2005/2008

SELECT  CASE DATEPART(WEEKDAY,GETDATE())  
    WHEN 1 THEN 'SUNDAY' 
    WHEN 2 THEN 'MONDAY' 
    WHEN 3 THEN 'TUESDAY' 
    WHEN 4 THEN 'WEDNESDAY' 
    WHEN 5 THEN 'THURSDAY' 
    WHEN 6 THEN 'FRIDAY' 
    WHEN 7 THEN 'SATURDAY' 
END

ValueError: object too deep for desired array while using convolution

You could try using scipy.ndimage.convolve it allows convolution of multidimensional images. here is the docs

Pick any kind of file via an Intent in Android

If you want to know this, it exists an open source library called aFileDialog that it is an small and easy to use which provides a file picker.

The difference with another file chooser's libraries for Android is that aFileDialog gives you the option to open the file chooser as a Dialog and as an Activity.

It also lets you to select folders, create files, filter files using regular expressions and show confirmation dialogs.

How to avoid Number Format Exception in java?

To Determine if a string is Int or Float and to represent in longer format.

Integer

 String  cost=Long.MAX_VALUE+"";
  if (isNumeric (cost))    // returns false for non numeric
  {  
      BigInteger bi  = new BigInteger(cost);

  }

public static boolean isNumeric(String str) 
{ 
  NumberFormat formatter = NumberFormat.getInstance(); 
  ParsePosition pos = new ParsePosition(0); 
  formatter.parse(str, pos); 
  return str.length() == pos.getIndex(); 
} 

How to get current moment in ISO 8601 format with date, hour, and minute?

Use SimpleDateFormat to format any Date object you want:

TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); // Quoted "Z" to indicate UTC, no timezone offset
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());

Using a new Date() as shown above will format the current time.

How to create Gmail filter searching for text only at start of subject line?

The only option I have found to do this is find some exact wording and put that under the "Has the words" option. Its not the best option, but it works.

C++ float array initialization

You only initialize the first N positions to the values in braces and all others are initialized to 0. In this case, N is the number of arguments you passed to the initialization list, i.e.,

float arr1[10] = { };       // all elements are 0
float arr2[10] = { 0 };     // all elements are 0
float arr3[10] = { 1 };     // first element is 1, all others are 0
float arr4[10] = { 1, 2 };  // first element is 1, second is 2, all others are 0

What value could I insert into a bit type column?

Your issue is in PHPMyAdmin itself. Some versions do not display the value of bit columns, even though you did set it correctly.

psql: could not connect to server: No such file or directory (Mac OS X)

None of the above worked for me. I had to reinstall Postgres the following way :

  • Uninstall postgresql with brew : brew uninstall postgresql
  • brew doctor (fix whatever is here)
  • brew cleanup
  • Remove all Postgres folders :

    • rm -r /usr/local/var/postgres
    • rm -r /Users/<username>/Library/Application\ Support/Postgres
  • Reinstall postgresql with brew : brew install postgresql

  • Start server : brew services start postgresql
  • You should now have to create your databases... (createdb)

/** and /* in Java Comments

First one is for Javadoc you define on the top of classes, interfaces, methods etc. You can use Javadoc as the name suggest to document your code on what the class does or what method does etc and generate report on it.

Second one is code block comment. Say for example you have some code block which you do not want compiler to interpret then you use code block comment.

another one is // this you use on statement level to specify what the proceeding lines of codes are supposed to do.

There are some other also like //TODO, this will mark that you want to do something later on that place

//FIXME you can use when you have some temporary solution but you want to visit later and make it better.

Hope this helps

What is the difference between "expose" and "publish" in Docker?

See the official documentation reference: https://docs.docker.com/engine/reference/builder/#expose

The EXPOSE allow you to define private (container) and public (host) ports to expose at image build time for when the container is running if you run the container with -P.

$ docker help run
...
  -P, --publish-all                    Publish all exposed ports to random ports
...

The public port and protocol are optional, if not a public port is specified, a random port will be selected on host by docker to expose the specified container port on Dockerfile.

A good pratice is do not specify public port, because it limits only one container per host ( a second container will throw a port already in use ).

You can use -p in docker run to control what public port the exposed container ports will be connectable.

Anyway, If you do not use EXPOSE (with -P on docker run) nor -p, no ports will be exposed.

If you always use -p at docker run you do not need EXPOSE but if you use EXPOSE your docker run command may be more simple, EXPOSE can be useful if you don't care what port will be expose on host, or if you are sure of only one container will be loaded.

Ansible: Set variable to file content

lookup only works on localhost. If you want to retrieve variables from a variables file you made remotely use include_vars: {{ varfile }} . Contents of {{ varfile }} should be a dictionary of the form {"key":"value"}, you will find ansible gives you trouble if you include a space after the colon.

How can I show a hidden div when a select option is selected?

Being more generic, passing values from calling element (which is easier to maintain).

  • Specify the start condition in the text field (display:none)
  • Pass the required option value to show/hide on ("Other")
  • Pass the target and field to show/hide ("TitleOther")

_x000D_
_x000D_
function showHideEle(selectSrc, targetEleId, triggerValue) { _x000D_
 if(selectSrc.value==triggerValue) {_x000D_
  document.getElementById(targetEleId).style.display = "inline-block";_x000D_
 } else {_x000D_
  document.getElementById(targetEleId).style.display = "none";_x000D_
 }_x000D_
} 
_x000D_
<select id="Title"_x000D_
   onchange="showHideEle(this, 'TitleOther', 'Other')">_x000D_
      <option value="">-- Choose</option>_x000D_
      <option value="Mr">Mr</option>_x000D_
      <option value="Mrs">Mrs</option>_x000D_
      <option value="Miss">Miss</option>_x000D_
      <option value="Other">Other --&gt;</option>      _x000D_
</select>_x000D_
<input id="TitleOther" type="text" title="Title other" placeholder="Other title" _x000D_
    style="display:none;"/>
_x000D_
_x000D_
_x000D_

Accessing Google Spreadsheets with C# using Google Data API

(Jun-Nov 2016) The question and its answers are now out-of-date as: 1) GData APIs are the previous generation of Google APIs. While not all GData APIs have been deprecated, all the latest Google APIs do not use the Google Data Protocol; and 2) there is a new Google Sheets API v4 (also not GData).

Moving forward from here, you need to get the Google APIs Client Library for .NET and use the latest Sheets API, which is much more powerful and flexible than any previous API. Here's a C# code sample to help get you started. Also check the .NET reference docs for the Sheets API and the .NET Google APIs Client Library developers guide.

If you're not allergic to Python (if you are, just pretend it's pseudocode ;) ), I made several videos with slightly longer, more "real-world" examples of using the API you can learn from and migrate to C# if desired:

Is it possible to set the equivalent of a src attribute of an img tag in CSS?

Alternative way

.myClass {
background: url('/img/loading_big.gif');
}
<div class="myClass"></div>

Spring Data JPA findOne() change to Optional how to use this?

Optional api provides methods for getting the values. You can check isPresent() for the presence of the value and then make a call to get() or you can make a call to get() chained with orElse() and provide a default value.

The last thing you can try doing is using @Query() over a custom method.

Django model "doesn't declare an explicit app_label"

TL;DR: Adding a blank __init__.py fixed the issue for me.

I got this error in PyCharm and realised that my settings file was not being imported at all. There was no obvious error telling me this, but when I put some nonsense code into the settings.py, it didn't cause an error.

I had settings.py inside a local_settings folder. However, I'd fogotten to include a __init__.py in the same folder to allow it to be imported. Once I'd added this, the error went away.

How to get last inserted row ID from WordPress database?

Putting the call to mysql_insert_id() inside a transaction, should do it:

mysql_query('BEGIN');
// Whatever code that does the insert here.
$id = mysql_insert_id();
mysql_query('COMMIT');
// Stuff with $id.

Binding multiple events to a listener (without JQuery)?

I have a simpler solution for you:

window.onload = window.onresize = (event) => {
    //Your Code Here
}

I've tested this an it works great, on the plus side it's compact and uncomplicated like the other examples here.

download csv file from web api in angular js

I think the best way to download any file generated by REST call is to use window.location example :

_x000D_
_x000D_
    $http({_x000D_
        url: url,_x000D_
        method: 'GET'_x000D_
    })_x000D_
    .then(function scb(response) {_x000D_
        var dataResponse = response.data;_x000D_
        //if response.data for example is : localhost/export/data.csv_x000D_
        _x000D_
        //the following will download the file without changing the current page location_x000D_
        window.location = 'http://'+ response.data_x000D_
    }, function(response) {_x000D_
      showWarningNotification($filter('translate')("global.errorGetDataServer"));_x000D_
    });
_x000D_
_x000D_
_x000D_

Tomcat request timeout

If you are trying to prevent a request from running too long, then setting a timeout in Tomcat will not help you. As Chris says, you can set the global timeout value for Tomcat. But, from The Apache Tomcat Connector - Generic HowTo Timeouts, see the Reply Timeout section:

JK can also use a timeout on request replies. This timeout does not measure the full processing time of the response. Instead it controls, how much time between consecutive response packets is allowed.

In most cases, this is what one actually wants. Consider for example long running downloads. You would not be able to set an effective global reply timeout, because downloads could last for many minutes. Most applications though have limited processing time before starting to return the response. For those applications you could set an explicit reply timeout. Applications that do not harmonise with reply timeouts are batch type applications, data warehouse and reporting applications which are expected to observe long processing times.

If JK aborts waiting for a response, because a reply timeout fired, there is no way to stop processing on the backend. Although you free processing resources in your web server, the request will continue to run on the backend - without any way to send back a result once the reply timeout fired.

So Tomcat will detect that the servlet has not responded within the timeout and will send back a response to the user, but will not stop the thread running. I don't think you can achieve what you want to do.

Pass Method as Parameter using C#

You should use a Func<string, int> delegate, that represents a function taking a string argument and returning an int value:

public bool RunTheMethod(Func<string, int> myMethod)
{
    // Do stuff
    myMethod.Invoke("My String");
    // Do stuff
    return true;
}

Then invoke it this way:

public bool Test()
{
    return RunTheMethod(Method1);
}

How to find the last day of the month from date?

I am using strtotime with cal_days_in_month as following:

$date_at_last_of_month=date('Y-m-d', strtotime('2020-4-1
+'.(cal_days_in_month(CAL_GREGORIAN,4,2020)-1).' day'));

Detecting attribute change of value of an attribute I made

You can use MutationObserver to track attribute changes including data-* changes. For example:

_x000D_
_x000D_
var foo = document.getElementById('foo');_x000D_
_x000D_
var observer = new MutationObserver(function(mutations) {_x000D_
  console.log('data-select-content-val changed');_x000D_
});_x000D_
observer.observe(foo, { _x000D_
  attributes: true, _x000D_
  attributeFilter: ['data-select-content-val'] });_x000D_
_x000D_
foo.dataset.selectContentVal = 1;
_x000D_
 <div id='foo'></div>_x000D_
 
_x000D_
_x000D_
_x000D_

ASP.NET set hiddenfield a value in Javascript

  • First you need to create the Hidden Field properly

    <asp:HiddenField ID="hdntxtbxTaksit" runat="server"></asp:HiddenField>

  • Then you need to set value to the hidden field

    If you aren't using Jquery you should use it:

    document.getElementById("<%= hdntxtbxTaksit.ClientID %>").value = "test";

    If you are using Jquery, this is how it should be:

    $("#<%= hdntxtbxTaksit.ClientID %>").val("test");

Retrieving Android API version programmatically

I generally prefer to add these codes in a function to get the Android version:

int whichAndroidVersion;

whichAndroidVersion= Build.VERSION.SDK_INT;
textView.setText("" + whichAndroidVersion); //If you don't use "" then app crashes.

For example, that code above will set the text into my textView as "29" now.

How do I format date and time on ssrs report?

If the date and time is in its own cell (aka textbox), then you should look at applying the format to the entire textbox. This will create cleaner exports to other formats; in particular, the value will export as a datetime value to Excel instead of a string.

Use the properties pane or dialog to set the format for the textbox to "MM/dd/yyyy hh:mm tt"

I would only use Ian's answer if the datetime is being concatenated with another string.

How to convert int to float in python?

To convert an integer to a float in Python you can use the following:

float_version = float(int_version)

The reason you are getting 0 is that Python 2 returns an integer if the mathematical operation (here a division) is between two integers. So while the division of 144 by 314 is 0.45~~~, Python converts this to integer and returns just the 0 by eliminating all numbers after the decimal point.

Alternatively you can convert one of the numbers in any operation to a float since an operation between a float and an integer would return a float. In your case you could write float(144)/314 or 144/float(314). Another, less generic code, is to say 144.0/314. Here 144.0 is a float so it’s the same thing.

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

It could be that the gradle-2.1 distribution specified by the wrapper was not downloaded properly. This was the root cause of the same problem in my environment.

Look into this directory:

ls -l ~/.gradle/wrapper/dists/

In there you should find a gradle-2.1 folder. Delete it like so:

rm -rf ~/.gradle/wrapper/dists/gradle-2.1-bin/

Restart IntelliJ, after that it will restart the download from the beginning and hopefully work.

Thanks, Ioannis

The view or its master was not found or no view engine supports the searched locations

Be careful if your model type is String because the second parameter of View(string, string) is masterName, not model. You may need to call the overload with object(model) as the second paramater:

Not correct :

protected ActionResult ShowMessageResult(string msg)
{
    return View("Message",msg);
}

Correct :

protected ActionResult ShowMessageResult(string msg)
{
    return View("Message",(object)msg);
}

OR (provided by bradlis7):

protected ActionResult ShowMessageResult(string msg)
{
    return View("Message",model:msg);
}

Get the Id of current table row with Jquery

$('input[type=button]' ).click(function() {
   var bid = jQuery(this).attr('id'); // button ID 
   var trid = $(this).parents('tr:first').attr('id'); // table row ID 
 });

How to set opacity to the background color of a div?

You can use CSS3 RGBA in this way:

rgba(255, 0, 0, 0.7);

0.7 means 70% opacity.

Convert object to JSON in Android

Might be better choice:

@Override
public String toString() {
    return new GsonBuilder().create().toJson(this, Producto.class);
}