Programs & Examples On #String utils

Extract digits from string - StringUtils Java

Use this code numberOnly will contain your desired output.

   String str="sdfvsdf68fsdfsf8999fsdf09";
   String numberOnly= str.replaceAll("[^0-9]", "");

StringUtils.isBlank() vs String.isEmpty()

The bottom line is :

isEmpty take " " as a character but isBlank not. Rest both are same.

How do you test your Request.QueryString[] variables?

Use int.TryParse instead to get rid of the try-catch block:

if (!int.TryParse(Request.QueryString["id"], out id))
{
  // error case
}

How to shift a column in Pandas DataFrame

If you don't want to lose the columns you shift past the end of your dataframe, simply append the required number first:

    offset = 5
    DF = DF.append([np.nan for x in range(offset)])
    DF = DF.shift(periods=offset)
    DF = DF.reset_index() #Only works if sequential index

CMD: How do I recursively remove the "Hidden"-Attribute of files and directories

For example folder named new under E: drive

type the command:

e:\cd new

e:\new\attrib *.* -s -h /s /d

and all the files and folders are un-hidden

CSS media query to target only iOS devices

I don't know about targeting iOS as a whole, but to target iOS Safari specifically:

@supports (-webkit-touch-callout: none) {
   /* CSS specific to iOS devices */ 
}

@supports not (-webkit-touch-callout: none) {
   /* CSS for other than iOS devices */ 
}

Apparently as of iOS 13 -webkit-overflow-scrolling no longer responds to @supports, but -webkit-touch-callout still does. Of course that could change in the future...

Adding Multiple Values in ArrayList at a single index

import java.util.*;
public class HelloWorld{

 public static void main(String []args){
  List<String> threadSafeList = new ArrayList<String>();
    threadSafeList.add("A");
    threadSafeList.add("D");
    threadSafeList.add("F");

Set<String> threadSafeList1 = new TreeSet<String>();
    threadSafeList1.add("B");
    threadSafeList1.add("C");
    threadSafeList1.add("E");
    threadSafeList1.addAll(threadSafeList);


 List mainList = new ArrayList();   
 mainList.addAll(Arrays.asList(threadSafeList1));
 Iterator<String> mainList1 = mainList.iterator();
 while(mainList1.hasNext()){
 System.out.printf("total : %s %n", mainList1.next());
 }
}
}

How do I compile a Visual Studio project from the command-line?

I know of two ways to do it.

Method 1
The first method (which I prefer) is to use msbuild:

msbuild project.sln /Flags...

Method 2
You can also run:

vcexpress project.sln /build /Flags...

The vcexpress option returns immediately and does not print any output. I suppose that might be what you want for a script.

Note that DevEnv is not distributed with Visual Studio Express 2008 (I spent a lot of time trying to figure that out when I first had a similar issue).

So, the end result might be:

os.system("msbuild project.sln /p:Configuration=Debug")

You'll also want to make sure your environment variables are correct, as msbuild and vcexpress are not by default on the system path. Either start the Visual Studio build environment and run your script from there, or modify the paths in Python (with os.putenv).

Calculate distance between two points in google maps V3

In my case it was best to calculate this in SQL Server, since i wanted to take current location and then search for all zip codes within a certain distance from current location. I also had a DB which contained a list of zip codes and their lat longs. Cheers

--will return the radius for a given number
create function getRad(@variable float)--function to return rad
returns float
as
begin
declare @retval float 
select @retval=(@variable * PI()/180)
--print @retval
return @retval
end
go

--calc distance
--drop function dbo.getDistance
create function getDistance(@cLat float,@cLong float, @tLat float, @tLong float)
returns float
as
begin
declare @emr float
declare @dLat float
declare @dLong float
declare @a float
declare @distance float
declare @c float

set @emr = 6371--earth mean 
set @dLat = dbo.getRad(@tLat - @cLat);
set @dLong = dbo.getRad(@tLong - @cLong);
set @a = sin(@dLat/2)*sin(@dLat/2)+cos(dbo.getRad(@cLat))*cos(dbo.getRad(@tLat))*sin(@dLong/2)*sin(@dLong/2);
set @c = 2*atn2(sqrt(@a),sqrt(1-@a))
set @distance = @emr*@c;
set @distance = @distance * 0.621371 -- i needed it in miles
--print @distance
return @distance;
end 
go


--get all zipcodes within 2 miles, the hardcoded #'s would be passed in by C#
select *
from cityzips a where dbo.getDistance(29.76,-95.38,a.lat,a.long) <3
order by zipcode

Using partial views in ASP.net MVC 4

You're passing the same model to the partial view as is being passed to the main view, and they are different types. The model is a DbSet of Notes, where you need to pass in a single Note.

You can do this by adding a parameter, which I'm guessing as it's the create form would be a new Note

@Html.Partial("_CreateNote", new QuickNotes.Models.Note())

Partial Dependency (Databases)

Partial dependence is solved for arriving to a relation in 2NF but 2NF is a "stepping stone" (C. Date) for solving any transitive dependency and arriving to a relation in 3NF (which is the operational target). However, the most interested thing on partial dependence is that it is a particular case of the own transitive dependency. This was demostrated by P. A. Berstein in 1976: IF {(x•y)?z but y?z} THEN {(x•y)?y & y?z}. The 3NF synthesizer algorithm of Berstein does not need doing distintions among these two type of relational defects.

Make Iframe to fit 100% of container's remaining height

You can do this with html/css like this:

<body>
    <div style="width:100%; height:30px; background-color:#cccccc;">Banner</div>
    <iframe src="http: //www.google.com.tw" style="position:fixed;top:30px;bottom:0px;width:100%;"></iframe>
</body>

Compare two columns using pandas

I think the closest to the OP's intuition is an inline if statement:

df['que'] = (df['one'] if ((df['one'] >= df['two']) and (df['one'] <= df['three'])) 

Necessary to add link tag for favicon.ico?

We can add for all devices with platform specific size

<link rel="apple-touch-icon" sizes="57x57" href="fav_icons/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="fav_icons/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="fav_icons/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="fav_icons/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="fav_icons/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="fav_icons/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="fav_icons/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="fav_icons/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="fav_icons/apple-icon-180x180.png">

<link rel="icon" type="image/png" sizes="192x192"  href="fav_icons/android-icon-192x192.pn">
<link rel="icon" type="image/png" sizes="32x32" href="fav_icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="fav_icons/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="fav_icons/favicon-16x16.png">

How can I refresh or reload the JFrame?

Try this code. I also faced the same problem, but some how I solved it.

public class KitchenUserInterface {

    private JFrame frame;
    private JPanel main_panel, northpanel , southpanel;
    private JLabel label;
    private JButton nextOrder;
    private JList list;

    private static KitchenUserInterface kitchenRunner ;

    public void setList(String[] order){
        kitchenRunner.frame.dispose();
        kitchenRunner.frame.setVisible(false);
        kitchenRunner= new KitchenUserInterface(order);

    }

    public KitchenUserInterface getInstance() {
        if(kitchenRunner == null) {
            synchronized(KitchenUserInterface.class) {
                if(kitchenRunner == null) {
                    kitchenRunner = new KitchenUserInterface();
                }
            }
        }


        return this.kitchenRunner;
    }

    private KitchenUserInterface() {


        frame = new JFrame("Lullaby's Kitchen");
        main_panel = new JPanel();
        main_panel.setLayout(new BorderLayout());
        frame.setContentPane(main_panel);



        northpanel = new JPanel();
        northpanel.setLayout(new FlowLayout());


        label = new JLabel("Kitchen");

        northpanel.add(label);


        main_panel.add(northpanel , BorderLayout.NORTH);


        frame.setSize(500 , 500 );
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private KitchenUserInterface (String[] order){
        this();
        list = new JList<String>(order);
        main_panel.add(list , BorderLayout.CENTER);

        southpanel = new JPanel();
         southpanel.setLayout(new FlowLayout());

         nextOrder = new JButton("Next Order Set");
         nextOrder.addActionListener(new OrderUpListener(list));
         southpanel.add(nextOrder);
         main_panel.add(southpanel, BorderLayout.SOUTH);



    }

    public static void main(String[] args) {
        KitchenUserInterface dat = kitchenRunner.getInstance();
        try{

        Thread.sleep(1500);
        System.out.println("Ready");
        dat.setList(OrderArray.getInstance().getOrders());
        }
        catch(Exception event) {
            System.out.println("Error sleep");
            System.out.println(event);
        }


        }

}

How to call a stored procedure from Java and JPA

May be it's not the same for Sql Srver but for people using oracle and eclipslink it's working for me

ex: a procedure that have one IN param (type CHAR) and two OUT params (NUMBER & VARCHAR)

in the persistence.xml declare the persistence-unit :

<persistence-unit name="presistanceNameOfProc" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>jdbc/DataSourceName</jta-data-source>
    <mapping-file>META-INF/eclipselink-orm.xml</mapping-file>
    <properties>
        <property name="eclipselink.logging.level" value="FINEST"/>
        <property name="eclipselink.logging.logger" value="DefaultLogger"/>
        <property name="eclipselink.weaving" value="static"/>
        <property name="eclipselink.ddl.table-creation-suffix" value="JPA_STORED_PROC" />
    </properties>
</persistence-unit>

and declare the structure of the proc in the eclipselink-orm.xml

<?xml version="1.0" encoding="UTF-8"?><entity-mappings version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence/orm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd">
<named-stored-procedure-query name="PERSIST_PROC_NAME" procedure-name="name_of_proc" returns-result-set="false">
    <parameter direction="IN" name="in_param_char" query-parameter="in_param_char" type="Character"/>
    <parameter direction="OUT" name="out_param_int" query-parameter="out_param_int" type="Integer"/>
    <parameter direction="OUT" name="out_param_varchar" query-parameter="out_param_varchar" type="String"/>
</named-stored-procedure-query>

in the code you just have to call your proc like this :

try {
        final Query query = this.entityManager
                .createNamedQuery("PERSIST_PROC_NAME");
        query.setParameter("in_param_char", 'V'); 
        resultQuery = (Object[]) query.getSingleResult();

    } catch (final Exception ex) {
        LOGGER.log(ex);
        throw new TechnicalException(ex);
    }

to get the two output params :

Integer myInt = (Integer) resultQuery[0];
String myStr =  (String) resultQuery[1];

Right way to convert data.frame to a numeric matrix, when df also contains strings?

I had the same problem and I solved it like this, by taking the original data frame without row names and adding them later

SFIo <- as.matrix(apply(SFI[,-1],2,as.numeric))
row.names(SFIo) <- SFI[,1]

How to put spacing between floating divs?

A litte late answer.

If you want to use a grid like this, you should have a look at Bootstrap, It's relatively easy to install, and it gives you exactly what you are looking for, all wrapped in nice and simple html/css + it works easily for making websites responsive.

How do I print a double value without scientific notation using Java?

I needed to convert some double to currency values and found that most of the solutions were OK, but not for me.

The DecimalFormat was eventually the way for me, so here is what I've done:

   public String foo(double value) //Got here 6.743240136E7 or something..
    {
        DecimalFormat formatter;

        if(value - (int)value > 0.0)
            formatter = new DecimalFormat("0.00"); // Here you can also deal with rounding if you wish..
        else
            formatter = new DecimalFormat("0");

        return formatter.format(value);
    }

As you can see, if the number is natural I get - say - 20000000 instead of 2E7 (etc.) - without any decimal point.

And if it's decimal, I get only two decimal digits.

How to apply two CSS classes to a single element

_x000D_
_x000D_
.color_x000D_
{background-color:#21B286;}_x000D_
.box_x000D_
{_x000D_
  width:"100%";_x000D_
  height:"100px";_x000D_
  font-size: 16px;_x000D_
  text-align:center;_x000D_
  line-height:1.19em;_x000D_
}_x000D_
.box.color_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size:16px;_x000D_
color:#000000;_x000D_
text-align:center;_x000D_
}
_x000D_
<div class="box color">orderlist</div>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
.color_x000D_
{background-color:#21B286;}_x000D_
.box_x000D_
{_x000D_
  width:"100%";_x000D_
  height:"100px";_x000D_
  font-size: 16px;_x000D_
  text-align:center;_x000D_
  line-height:1.19em;_x000D_
}_x000D_
.box.color_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size:16px;_x000D_
color:#000000;_x000D_
text-align:center;_x000D_
}
_x000D_
<div class="box color">orderlist</div>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
.color_x000D_
{background-color:#21B286;}_x000D_
.box_x000D_
{_x000D_
  width:"100%";_x000D_
  height:"100px";_x000D_
  font-size: 16px;_x000D_
  text-align:center;_x000D_
  line-height:1.19em;_x000D_
}_x000D_
.box.color_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size:16px;_x000D_
color:#000000;_x000D_
text-align:center;_x000D_
}
_x000D_
<div class="box color">orderlist</div>
_x000D_
_x000D_
_x000D_

Send mail via Gmail with PowerShell V2's Send-MailMessage

I am really new to PowerShell, and I was searching about gmailing from PowerShell. I took what you folks did in previous answers, and modified it a bit and have come up with a script which will check for attachments before adding them, and also to take an array of recipients.

## Send-Gmail.ps1 - Send a gmail message
## By Rodney Fisk - [email protected]
## 2 / 13 / 2011

# Get command line arguments to fill in the fields
# Must be the first statement in the script
param(
    [Parameter(Mandatory = $true,
               Position = 0,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('From')] # This is the name of the parameter e.g. -From [email protected]
    [String]$EmailFrom, # This is the value [Don't forget the comma at the end!]

    [Parameter(Mandatory = $true,
               Position = 1,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('To')]
    [String[]]$Arry_EmailTo,

    [Parameter(Mandatory = $true,
               Position = 2,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('Subj')]
    [String]$EmailSubj,

    [Parameter(Mandatory = $true,
               Position = 3,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('Body')]
    [String]$EmailBody,

    [Parameter(Mandatory = $false,
               Position = 4,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('Attachment')]
    [String[]]$Arry_EmailAttachments
)

# From Christian @ stackoverflow.com
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SMTPClient($SmtpServer, 587)
$SMTPClient.EnableSSL = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("GMAIL_USERNAME", "GMAIL_PASSWORD");

# From Core @ stackoverflow.com
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = $EmailFrom
foreach ($recipient in $Arry_EmailTo)
{
    $emailMessage.To.Add($recipient)
}
$emailMessage.Subject = $EmailSubj
$emailMessage.Body = $EmailBody
# Do we have any attachments?
# If yes, then add them, if not, do nothing
if ($Arry_EmailAttachments.Count -ne $NULL)
{
    $emailMessage.Attachments.Add()
}
$SMTPClient.Send($emailMessage)

Of course, change the GMAIL_USERNAME and GMAIL_PASSWORD values to your particular user and password.

How can I obfuscate (protect) JavaScript?

I'm under the impression that some enterprises (e.g.: JackBe) put encrypted JavaScript code inside *.gif files, rather than JS files, as an additional measure of obfuscation.

#1142 - SELECT command denied to user ''@'localhost' for table 'pma_table_uiprefs'

Another option is to disable this functionality. If we allow access on the server only for reading Disable pmadb

  1. add config for server
$cfg['Servers'][$i]['userconfig'] =false;
$cfg['Servers'][$i]['pmadb'] = false;
$cfg['Servers'][$i]['bookmarktable'] = false;
$cfg['Servers'][$i]['relation'] = false;
$cfg['Servers'][$i]['table_info'] = false;
$cfg['Servers'][$i]['table_coords'] = false;
$cfg['Servers'][$i]['pdf_pages'] = false;
$cfg['Servers'][$i]['column_info'] = false;
$cfg['Servers'][$i]['history'] = false;
$cfg['Servers'][$i]['table_uiprefs'] = false;
$cfg['Servers'][$i]['tracking'] = false;
$cfg['Servers'][$i]['designer_coords'] = false;
$cfg['Servers'][$i]['userconfig'] = false;
$cfg['Servers'][$i]['recent'] = false;
  1. and refresh session (private tab browser or other)

Laravel Update Query

Try doing it like this.

User::where('email', $userEmail)
       ->update([
           'member_type' => $plan
        ]);

What is the difference between VFAT and FAT32 file systems?

Copied from http://technet.microsoft.com/en-us/library/cc750354.aspx

What's FAT?

FAT may sound like a strange name for a file system, but it's actually an acronym for File Allocation Table. Introduced in 1981, FAT is ancient in computer terms. Because of its age, most operating systems, including Microsoft Windows NT®, Windows 98, the Macintosh OS, and some versions of UNIX, offer support for FAT.

The FAT file system limits filenames to the 8.3 naming convention, meaning that a filename can have no more than eight characters before the period and no more than three after. Filenames in a FAT file system must also begin with a letter or number, and they can't contain spaces. Filenames aren't case sensitive.

What About VFAT?

Perhaps you've also heard of a file system called VFAT. VFAT is an extension of the FAT file system and was introduced with Windows 95. VFAT maintains backward compatibility with FAT but relaxes the rules. For example, VFAT filenames can contain up to 255 characters, spaces, and multiple periods. Although VFAT preserves the case of filenames, it's not considered case sensitive.

When you create a long filename (longer than 8.3) with VFAT, the file system actually creates two different filenames. One is the actual long filename. This name is visible to Windows 95, Windows 98, and Windows NT (4.0 and later). The second filename is called an MS-DOS® alias. An MS-DOS alias is an abbreviated form of the long filename. The file system creates the MS-DOS alias by taking the first six characters of the long filename (not counting spaces), followed by the tilde [~] and a numeric trailer. For example, the filename Brien's Document.txt would have an alias of BRIEN'~1.txt.

An interesting side effect results from the way VFAT stores its long filenames. When you create a long filename with VFAT, it uses one directory entry for the MS-DOS alias and another entry for every 13 characters of the long filename. In theory, a single long filename could occupy up to 21 directory entries. The root directory has a limit of 512 files, but if you were to use the maximum length long filenames in the root directory, you could cut this limit to a mere 24 files. Therefore, you should use long filenames very sparingly in the root directory. Other directories aren't affected by this limit.

You may be wondering why we're discussing VFAT. The reason is it's becoming more common than FAT, but aside from the differences I mentioned above, VFAT has the same limitations. When you tell Windows NT to format a partition as FAT, it actually formats the partition as VFAT. The only time you'll have a true FAT partition under Windows NT 4.0 is when you use another operating system, such as MS-DOS, to format the partition.

FAT32

FAT32 is actually an extension of FAT and VFAT, first introduced with Windows 95 OEM Service Release 2 (OSR2). FAT32 greatly enhances the VFAT file system but it does have its drawbacks.

The greatest advantage to FAT32 is that it dramatically increases the amount of free hard disk space. To illustrate this point, consider that a FAT partition (also known as a FAT16 partition) allows only a certain number of clusters per partition. Therefore, as your partition size increases, the cluster size must also increase. For example, a 512-MB FAT partition has a cluster size of 8K, while a 2-GB partition has a cluster size of 32K.

This may not sound like a big deal until you consider that the FAT file system only works in single cluster increments. For example, on a 2-GB partition, a 1-byte file will occupy the entire cluster, thereby consuming 32K, or roughly 32,000 times the amount of space that the file should consume. This rule applies to every file on your hard disk, so you can see how much space can be wasted.

Converting a partition to FAT32 reduces the cluster size (and overcomes the 2-GB partition size limit). For partitions 8 GB and smaller, the cluster size is reduced to a mere 4K. As you can imagine, it's not uncommon to gain back hundreds of megabytes by converting a partition to FAT32, especially if the partition contains a lot of small files.

Note: This section of the quote/ article (1999) is out of date. Updated info quote below.

As I mentioned, FAT32 does have limitations. Unfortunately, it isn't compatible with any operating system other than Windows 98 and the OSR2 version of Windows 95. However, Windows 2000 will be able to read FAT32 partitions.

The other disadvantage is that your disk utilities and antivirus software must be FAT32-aware. Otherwise, they could interpret the new file structure as an error and try to correct it, thus destroying data in the process.

Finally, I should mention that converting to FAT32 is a one-way process. Once you've converted to FAT32, you can't convert the partition back to FAT16. Therefore, before converting to FAT32, you need to consider whether the computer will ever be used in a dual-boot environment. I should also point out that although other operating systems such as Windows NT can't directly read a FAT32 partition, they can read it across the network. Therefore, it's no problem to share information stored on a FAT32 partition with other computers on a network that run older operating systems.

Updated mentioned in comment by Doktor-J (assimilated to update out of date answer in case comment is ever lost):

I'd just like to point out that most modern operating systems (WinXP/Vista/7/8, MacOS X, most if not all Linux variants) can read FAT32, contrary to what the second-to-last paragraph suggests.

The original article was written in 1999, and being posted on a Microsoft website, probably wasn't concerned with non-Microsoft operating systems anyways.

The operating systems "excluded" by that paragraph are probably the original Windows 95, Windows NT 4.0, Windows 3.1, DOS, etc.

How to obtain the number of CPUs/cores in Linux from the command line?

Here's the way I use for counting the number of physical cores that are online on Linux:

lscpu --online --parse=Core,Socket | grep --invert-match '^#' | sort --unique | wc --lines

or in short:

lscpu -b -p=Core,Socket | grep -v '^#' | sort -u | wc -l

Example (1 socket):

> lscpu
...
CPU(s):                28
Thread(s) per core:    2
Core(s) per socket:    14
Socket(s):             1
....
> lscpu -b -p=Core,Socket | grep -v '^#' | sort -u | wc -l
14

Example (2 sockets):

> lscpu
...
CPU(s):                56
Thread(s) per core:    2
Core(s) per socket:    14
Socket(s):             2
...
> lscpu -b -p=Core,Socket | grep -v '^#' | sort -u | wc -l
28

Example (4 sockets):

> lscpu
...
CPU(s):                64
Thread(s) per core:    2
Core(s) per socket:    8
Socket(s):             4
...
> lscpu -b -p=Core,Socket | grep -v '^#' | sort -u | wc -l
32

Print newline in PHP in single quotes

in case you have a variable :

$your_var = 'declare your var';
echo 'i want to show my var here'.$your_var.'<br>';

How do I terminate a thread in C++11?

  1. You could call std::terminate() from any thread and the thread you're referring to will forcefully end.

  2. You could arrange for ~thread() to be executed on the object of the target thread, without a intervening join() nor detach() on that object. This will have the same effect as option 1.

  3. You could design an exception which has a destructor which throws an exception. And then arrange for the target thread to throw this exception when it is to be forcefully terminated. The tricky part on this one is getting the target thread to throw this exception.

Options 1 and 2 don't leak intra-process resources, but they terminate every thread.

Option 3 will probably leak resources, but is partially cooperative in that the target thread has to agree to throw the exception.

There is no portable way in C++11 (that I'm aware of) to non-cooperatively kill a single thread in a multi-thread program (i.e. without killing all threads). There was no motivation to design such a feature.

A std::thread may have this member function:

native_handle_type native_handle();

You might be able to use this to call an OS-dependent function to do what you want. For example on Apple's OS's, this function exists and native_handle_type is a pthread_t. If you are successful, you are likely to leak resources.

How do I check if an object's type is a particular subclass in C++?

I don't know if I understand your problem correctly, so let me restate it in my own words...

Problem: Given classes B and D, determine if D is a subclass of B (or vice-versa?)

Solution: Use some template magic! Okay, seriously you need to take a look at LOKI, an excellent template meta-programming library produced by the fabled C++ author Andrei Alexandrescu.

More specifically, download LOKI and include header TypeManip.h from it in your source code then use the SuperSubclass class template as follows:

if(SuperSubClass<B,D>::value)
{
...
}

According to documentation, SuperSubClass<B,D>::value will be true if B is a public base of D, or if B and D are aliases of the same type.

i.e. either D is a subclass of B or D is the same as B.

I hope this helps.

edit:

Please note the evaluation of SuperSubClass<B,D>::value happens at compile time unlike some methods which use dynamic_cast, hence there is no penalty for using this system at runtime.

Deserialize json object into dynamic object using Json.net

If you just deserialize to dynamic you will get a JObject back. You can get what you want by using an ExpandoObject.

var converter = new ExpandoObjectConverter();    
dynamic message = JsonConvert.DeserializeObject<ExpandoObject>(jsonString, converter);

Checking for an empty field with MySQL

check this code for the problem:

$sql = "SELECT * FROM tablename WHERE condition";

$res = mysql_query($sql);

while ($row = mysql_fetch_assoc($res)) {

    foreach($row as $key => $field) {  

        echo "<br>";

        if(empty($row[$key])){

            echo $key." : empty field :"."<br>"; 

        }else{

        echo $key." =" . $field."<br>";     

        }
    }
}

Unknown version of Tomcat was specified in Eclipse

This happened to me because Tomcat was still in the process of downloading (Download and Install). The message disappeared after a few minutes.

The eclipse window should really have some type of progress indicator showing download status.

Interface vs Base class

Also keep in mind not to get swept away in OO (see blog) and always model objects based on behavior required, if you were designing an app where the only behavior you required was a generic name and species for an animal then you would only need one class Animal with a property for the name, instead of millions of classes for every possible animal in the world.

How can I count the occurrences of a string within a file?

I'm taking some guesses here, because I don't quite understand what you're asking.

I think that what you want is a count of the number of lines on which the pattern 'echo' appears in the given file.

I've pasted your sample text into a file called 6741967.

First, grep finds the matches:

james@Brindle:tmp$grep echo 6741967 
    echo "Preparing to add a new user..."
echo "1. Add user"
echo "2. Exit"
echo "Enter your choice: "

Second, use wc -l to count the lines

james@Brindle:tmp$grep echo 6741967  | wc -l
       4

await is only valid in async function

Yes, await / async was a great concept, but the implementation is completely broken.

For whatever reason, the await keyword has been implemented such that it can only be used within an async method. This is in fact a bug, though you will not see it referred to as such anywhere but right here. The fix for this bug would be to implement the await keyword such that it can only be used TO CALL an async function, regardless of whether the calling function is itself synchronous or asynchronous.

Due to this bug, if you use await to call a real asynchronous function somewhere in your code, then ALL of your functions must be marked as async and ALL of your function calls must use await.

This essentially means that you must add the overhead of promises to all of the functions in your entire application, most of which are not and never will be asynchronous.

If you actually think about it, using await in a function should require the function containing the await keyword TO NOT BE ASYNC - this is because the await keyword is going to pause processing in the function where the await keyword is found. If processing in that function is paused, then it is definitely NOT asynchronous.

So, to the developers of javascript and ECMAScript - please fix the await/async implementation as follows...

  • await can only be used to CALL async functions.
  • await can appear in any kind of function, synchronous or asynchronous.
  • Change the error message from "await is only valid in async function" to "await can only be used to call async functions".

Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51

you need just run this below commands:

$ rm -rf node_modules
$ rm -rf yarn.lock
$ yarn install

and finally

$ ./node_modules/.bin/electron-rebuild

don't forget to yarn add electron-rebuild if it doesn't exist in your dependencies.

Angularjs simple file download causes router to redirect

If you need a directive more advanced, I recomend the solution that I implemnted, correctly tested on Internet Explorer 11, Chrome and FireFox.

I hope it, will be helpfull.

HTML :

<a href="#" class="btn btn-default" file-name="'fileName.extension'"  ng-click="getFile()" file-download="myBlobObject"><i class="fa fa-file-excel-o"></i></a>

DIRECTIVE :

directive('fileDownload',function(){
    return{
        restrict:'A',
        scope:{
            fileDownload:'=',
            fileName:'=',
        },

        link:function(scope,elem,atrs){


            scope.$watch('fileDownload',function(newValue, oldValue){

                if(newValue!=undefined && newValue!=null){
                    console.debug('Downloading a new file'); 
                    var isFirefox = typeof InstallTrigger !== 'undefined';
                    var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
                    var isIE = /*@cc_on!@*/false || !!document.documentMode;
                    var isEdge = !isIE && !!window.StyleMedia;
                    var isChrome = !!window.chrome && !!window.chrome.webstore;
                    var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
                    var isBlink = (isChrome || isOpera) && !!window.CSS;

                    if(isFirefox || isIE || isChrome){
                        if(isChrome){
                            console.log('Manage Google Chrome download');
                            var url = window.URL || window.webkitURL;
                            var fileURL = url.createObjectURL(scope.fileDownload);
                            var downloadLink = angular.element('<a></a>');//create a new  <a> tag element
                            downloadLink.attr('href',fileURL);
                            downloadLink.attr('download',scope.fileName);
                            downloadLink.attr('target','_self');
                            downloadLink[0].click();//call click function
                            url.revokeObjectURL(fileURL);//revoke the object from URL
                        }
                        if(isIE){
                            console.log('Manage IE download>10');
                            window.navigator.msSaveOrOpenBlob(scope.fileDownload,scope.fileName); 
                        }
                        if(isFirefox){
                            console.log('Manage Mozilla Firefox download');
                            var url = window.URL || window.webkitURL;
                            var fileURL = url.createObjectURL(scope.fileDownload);
                            var a=elem[0];//recover the <a> tag from directive
                            a.href=fileURL;
                            a.download=scope.fileName;
                            a.target='_self';
                            a.click();//we call click function
                        }


                    }else{
                        alert('SORRY YOUR BROWSER IS NOT COMPATIBLE');
                    }
                }
            });

        }
    }
})

IN CONTROLLER:

$scope.myBlobObject=undefined;
$scope.getFile=function(){
        console.log('download started, you can show a wating animation');
        serviceAsPromise.getStream({param1:'data1',param1:'data2', ...})
        .then(function(data){//is important that the data was returned as Aray Buffer
                console.log('Stream download complete, stop animation!');
                $scope.myBlobObject=new Blob([data],{ type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
        },function(fail){
                console.log('Download Error, stop animation and show error message');
                                    $scope.myBlobObject=[];
                                });
                            }; 

IN SERVICE:

function getStream(params){
                 console.log("RUNNING");
                 var deferred = $q.defer();

                 $http({
                     url:'../downloadURL/',
                     method:"PUT",//you can use also GET or POST
                     data:params,
                     headers:{'Content-type': 'application/json'},
                     responseType : 'arraybuffer',//THIS IS IMPORTANT
                    })
                    .success(function (data) {
                        console.debug("SUCCESS");
                        deferred.resolve(data);
                    }).error(function (data) {
                         console.error("ERROR");
                         deferred.reject(data);
                    });

                 return deferred.promise;
                };

BACKEND(on SPRING):

@RequestMapping(value = "/downloadURL/", method = RequestMethod.PUT)
public void downloadExcel(HttpServletResponse response,
        @RequestBody Map<String,String> spParams
        ) throws IOException {
        OutputStream outStream=null;
outStream = response.getOutputStream();//is important manage the exceptions here
ObjectThatWritesOnOutputStream myWriter= new ObjectThatWritesOnOutputStream();// note that this object doesn exist on JAVA,
ObjectThatWritesOnOutputStream.write(outStream);//you can configure more things here
outStream.flush();
return;
}

Turn a number into star rating display using jQuery and CSS

using jquery without prototype, update the js code to

$( ".stars" ).each(function() { 
    // Get the value
    var val = $(this).data("rating");
    // Make sure that the value is in 0 - 5 range, multiply to get width
    var size = Math.max(0, (Math.min(5, val))) * 16;
    // Create stars holder
    var $span = $('<span />').width(size);
    // Replace the numerical value with stars
    $(this).html($span);
});

I also added a data attribute by the name of data-rating in the span.

<span class="stars" data-rating="4" ></span>

How do I delete everything in Redis?

After you start the Redis-server using:service redis-server start --port 8000 or redis-server.

Use redis-cli -p 8000 to connect to the server as a client in a different terminal.

You can use either

  1. FLUSHDB - Delete all the keys of the currently selected DB. This command never fails. The time-complexity for this operation is O(N), N being the number of keys in the database.
  2. FLUSHALL - Delete all the keys of all the existing databases, not just the currently selected one. This command never fails. The time-complexity for this operation is O(N), N being the number of keys in all existing databases.

Check the documentation for ASYNC option for both.

If you are using Redis through its python interface, use these two functions for the same functionality:

def flushall(self):
    "Delete all keys in all databases on the current host"
    return self.execute_command('FLUSHALL')

and

def flushdb(self):
    "Delete all keys in the current database"
    return self.execute_command('FLUSHDB')

Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies

I had a project with the same problem , I solved it with change dotnet core version from 2.2 to 2.0, If your problem has remained , Try this solution

Plugin is too old, please update to a more recent version, or set ANDROID_DAILY_OVERRIDE environment variable to

Check the latest version of Gradle Plugin Here:

Download

You should change this in dependencies of app settings

buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:[PLACE VERSION CODE HERE]'

}

}

How to log a method's execution time exactly in milliseconds?

For Swift 4, add as a Delegate to your class:

public protocol TimingDelegate: class {
    var _TICK: Date?{ get set }
}

extension TimingDelegate {
    var TICK: Date {
        _TICK = Date()
        return(_TICK)!
     }

    func TOCK(message: String)  {

        if (_TICK == nil){
            print("Call 'TICK' first!")
        }

        if (message == ""){
            print("\(Date().timeIntervalSince(_TICK!))")
        }
        else{
            print("\(message): \(Date().timeIntervalSince(_TICK!))")
        }
    }
}

Add to our class:

class MyViewcontroller: UIViewController, TimingDelegate

Then add to your class:

var _TICK: Date?

When you want to time something, start with:

TICK

And end with:

TOCK("Timing the XXX routine")

Exiting out of a FOR loop in a batch file?

You could simply use echo on and you will see that goto :eof or even exit /b doesn't work as expected.

The code inside of the loop isn't executed anymore, but the loop is expanded for all numbers to the end.
That's why it's so slow.

The only way to exit a FOR /L loop seems to be the variant of exit like the exsample of Wimmel, but this isn't very fast nor useful to access any results from the loop.

This shows 10 expansions, but none of them will be executed

echo on
for /l %%n in (1,1,10) do (
  goto :eof
  echo %%n
)

How do I install the yaml package for Python?

pip install pyyaml

If you don't have pip, run easy_install pip to install pip, which is the go-to package installer - Why use pip over easy_install?. If you prefer to stick with easy_install, then easy_install pyyaml

Eslint: How to disable "unexpected console statement" in Node.js?

The following works with ESLint in VSCode if you want to disable the rule for just one line.

To disable the next line:

// eslint-disable-next-line no-console
console.log('hello world');

To disable the current line:

console.log('hello world'); // eslint-disable-line no-console

Re-run Spring Boot Configuration Annotation Processor to update generated metadata

You can enable annotation processors in IntelliJ via the following:

  1. Click on File
  2. Click on Settings
  3. In the little search box in the upper-left hand corner, search for "Annotation Processors"
  4. Check "Enable annotation processing"
  5. Click OK

Check if a Python list item contains a string inside another string

def find_dog(new_ls):
    splt = new_ls.split()
    if 'dog' in splt:
        print("True")
    else:
        print('False')


find_dog("Is there a dog here?")

ASP.NET Custom Validator Client side & Server Side validation not firing

Use this:

<asp:CustomValidator runat="server" id="vld" ValidateEmptyText="true"/>

To validate an empty field.

You don't need to add 2 validators !

The type or namespace cannot be found (are you missing a using directive or an assembly reference?)

If you have Login in a seperate folder within your project make sure that where you are using it you do:

using FootballLeagueSystem.[Whatever folder you are using]

Setting and getting localStorage with jQuery

The localStorage can only store string content and you are trying to store a jQuery object since html(htmlString) returns a jQuery object.

You need to set the string content instead of an object. And use the setItem method to add data and getItem to get data.

window.localStorage.setItem('content', 'Test');
$('#test').html(window.localStorage.getItem('content'));

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

This works for me on a similar issue where I failed to delete the user due to the reference. Thank you

@ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST,CascadeType.REFRESH})

Display open transactions in MySQL

Although there won't be any remaining transaction in the case, as @Johan said, you can see the current transaction list in InnoDB with the query below if you want.

SELECT * FROM information_schema.innodb_trx\G

From the document:

The INNODB_TRX table contains information about every transaction (excluding read-only transactions) currently executing inside InnoDB, including whether the transaction is waiting for a lock, when the transaction started, and the SQL statement the transaction is executing, if any.

Check if file is already open

org.apache.commons.io.FileUtils.touch(yourFile) doesn't check if your file is open or not. Instead, it changes the timestamp of the file to the current time.

I used IOException and it works just fine:

try 
{
  String filePath = "C:\sheet.xlsx";
  FileWriter fw = new FileWriter(filePath );                
}
catch (IOException e)
{
    System.out.println("File is open");
}

How can I list all foreign keys referencing a given table in SQL Server?

Mysql server has information_schema.REFERENTIAL_CONSTRAINTS table FYI, you can filter it by table name or referenced table name.

Make XAMPP / Apache serve file outside of htdocs folder

You can set Apache to serve pages from anywhere with any restrictions but it's normally distributed in a more secure form.

Editing your apache files (http.conf is one of the more common names) will allow you to set any folder so it appears in your webroot.

EDIT:

alias myapp c:\myapp\

I've edited my answer to include the format for creating an alias in the http.conf file which is sort of like a shortcut in windows or a symlink under un*x where Apache 'pretends' a folder is in the webroot. This is probably going to be more useful to you in the long term.

git clone from another directory

cd /d c:\
git clone C:\folder1 folder2

From the documentation for git clone:

For local repositories, also supported by git natively, the following syntaxes may be used:

/path/to/repo.git/

file:///path/to/repo.git/

These two syntaxes are mostly equivalent, except the former implies --local option.

Disabling and enabling a html input button

You can do this fairly easily with just straight JavaScript, no libraries required.

Enable a button

document.getElementById("Button").disabled=false;

Disable a button

 document.getElementById("Button").disabled=true;

No external libraries necessary.

Java Set retain order?

Only SortedSet can do the ordering of the Set

Convert a hexadecimal string to an integer efficiently in C?

For AVR Microcontrollers I wrote the following function, including relevant comments to make it easy to understand:

/**
 * hex2int
 * take a hex string and convert it to a 32bit number (max 8 hex digits)
 */
uint32_t hex2int(char *hex) {
    uint32_t val = 0;
    while (*hex) {
        // get current character then increment
        char byte = *hex++; 
        // transform hex character to the 4bit equivalent number, using the ascii table indexes
        if (byte >= '0' && byte <= '9') byte = byte - '0';
        else if (byte >= 'a' && byte <='f') byte = byte - 'a' + 10;
        else if (byte >= 'A' && byte <='F') byte = byte - 'A' + 10;    
        // shift 4 to make space for new digit, and add the 4 bits of the new digit 
        val = (val << 4) | (byte & 0xF);
    }
    return val;
}

Example:

char *z ="82ABC1EF";
uint32_t x = hex2int(z);
printf("Number is [%X]\n", x);

Will output: enter image description here

Scrolling to element using webdriver?

It's not a direct answer on question (its not about Actions), but it also allow you to scroll easily to required element:

element = driver.find_element_by_id('some_id')
element.location_once_scrolled_into_view

This actually intend to return you coordinates (x, y) of element on page, but also scroll down right to target element

Flask Python Buttons

The appropriate way for doing this:

@app.route('/')
def index():
    if form.validate_on_submit():
        if 'download' in request.form:
            pass # do something
        elif 'watch' in request.form:
            pass # do something else

Put watch and download buttons into your template:

<input type="submit" name="download" value="Download">
<input type="submit" name="watch" value="Watch">

Python: URLError: <urlopen error [Errno 10060]

The error code 10060 means it cannot connect to the remote peer. It might be because of the network problem or mostly your setting issues, such as proxy setting.

You could try to connect the same host with other tools(such as ncat) and/or with another PC within your same local network to find out where the problem is occuring.

For proxy issue, there are some material here:

Using an HTTP PROXY - Python

Why can't I get Python's urlopen() method to work on Windows?

Hope it helps!

google console error `OR-IEH-01`

i found that my google payment account was not activated. i activated it and the error was solved. link for vitrification: google account verification

How do I use DateTime.TryParse with a Nullable<DateTime>?

Here is a slightly concised edition of what Jason suggested:

DateTime? d; DateTime dt;
d = DateTime.TryParse(DateTime.Now.ToString(), out dt)? dt : (DateTime?)null;

Is there a no-duplicate List implementation out there?

You should seriously consider dhiller's answer:

  1. Instead of worrying about adding your objects to a duplicate-less List, add them to a Set (any implementation), which will by nature filter out the duplicates.
  2. When you need to call the method that requires a List, wrap it in a new ArrayList(set) (or a new LinkedList(set), whatever).

I think that the solution you posted with the NoDuplicatesList has some issues, mostly with the contains() method, plus your class does not handle checking for duplicates in the Collection passed to your addAll() method.

What is the Sign Off feature in Git for?

Sign-off is a requirement for getting patches into the Linux kernel and a few other projects, but most projects don't actually use it.

It was introduced in the wake of the SCO lawsuit, (and other accusations of copyright infringement from SCO, most of which they never actually took to court), as a Developers Certificate of Origin. It is used to say that you certify that you have created the patch in question, or that you certify that to the best of your knowledge, it was created under an appropriate open-source license, or that it has been provided to you by someone else under those terms. This can help establish a chain of people who take responsibility for the copyright status of the code in question, to help ensure that copyrighted code not released under an appropriate free software (open source) license is not included in the kernel.

Jenkins - How to access BUILD_NUMBER environment variable

For Groovy script in the Jenkinsfile using the $BUILD_NUMBER it works.

deleting folder from java

I found this piece of code more understadable and working:

public static boolean deleteDir(File dir) {
    if (dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }

    return dir.delete(); // The directory is empty now and can be deleted.
}

How to set initial value and auto increment in MySQL?

Use this:

ALTER TABLE users AUTO_INCREMENT=1001;

or if you haven't already added an id column, also add it

ALTER TABLE users ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    ADD INDEX (id);

Mockito. Verify method arguments

  • You don't need the eq matcher if you don't use other matchers.
  • You are not using the correct syntax - your method call should be outside the .verify(mock). You are now initiating verification on the result of the method call, without verifying anything (not making a method call). Hence all tests are passing.

You code should look like:

Mockito.verify(mock).mymethod(obj);
Mockito.verify(mock).mymethod(null);
Mockito.verify(mock).mymethod("something_else");

Simple if else onclick then do?

The preferred modern method is to use addEventListener either by adding the event listener direct to the element or to a parent of the elements (delegated).

An example, using delegated events, might be

_x000D_
_x000D_
var box = document.getElementById('box');_x000D_
_x000D_
document.getElementById('buttons').addEventListener('click', function(evt) {_x000D_
  var target = evt.target;_x000D_
  if (target.id === 'yes') {_x000D_
    box.style.backgroundColor = 'red';_x000D_
  } else if (target.id === 'no') {_x000D_
    box.style.backgroundColor = 'green';_x000D_
  } else {_x000D_
    box.style.backgroundColor = 'purple';_x000D_
  }_x000D_
}, false);
_x000D_
#box {_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  background-color: red;_x000D_
}_x000D_
#buttons {_x000D_
  margin-top: 50px;_x000D_
}
_x000D_
<div id='box'></div>_x000D_
<div id='buttons'>_x000D_
  <button id='yes'>yes</button>_x000D_
  <button id='no'>no</button>_x000D_
  <p>Click one of the buttons above.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to position two elements side by side using CSS

You can float the elements (the map wrapper, and the paragraph), or use inline-block on both of them.

Easier way to debug a Windows service

How about Debugger.Break() in the first line?

Simplest way to detect a mobile device in PHP

I was wondering, until now, why someone had not posted a slightly alteration of the accepted answer to the use of implode() in order to have a better readability of the code. So here it goes:

<?php
$uaFull = strtolower($_SERVER['HTTP_USER_AGENT']);
$uaStart = substr($uaFull, 0, 4);

$uaPhone = [
    '(android|bb\d+|meego).+mobile',
    'avantgo',
    'bada\/',
    'blackberry',
    'blazer',
    'compal',
    'elaine',
    'fennec',
    'hiptop',
    'iemobile',
    'ip(hone|od)',
    'iris',
    'kindle',
    'lge ',
    'maemo',
    'midp',
    'mmp',
    'mobile.+firefox',
    'netfront',
    'opera m(ob|in)i',
    'palm( os)?',
    'phone',
    'p(ixi|re)\/',
    'plucker',
    'pocket',
    'psp',
    'series(4|6)0',
    'symbian',
    'treo',
    'up\.(browser|link)',
    'vodafone',
    'wap',
    'windows ce',
    'xda',
    'xiino'
];

$uaMobile = [
    '1207', 
    '6310', 
    '6590', 
    '3gso', 
    '4thp', 
    '50[1-6]i', 
    '770s', 
    '802s', 
    'a wa', 
    'abac|ac(er|oo|s\-)', 
    'ai(ko|rn)', 
    'al(av|ca|co)', 
    'amoi', 
    'an(ex|ny|yw)', 
    'aptu', 
    'ar(ch|go)', 
    'as(te|us)', 
    'attw', 
    'au(di|\-m|r |s )', 
    'avan', 
    'be(ck|ll|nq)', 
    'bi(lb|rd)', 
    'bl(ac|az)', 
    'br(e|v)w', 
    'bumb', 
    'bw\-(n|u)', 
    'c55\/', 
    'capi', 
    'ccwa', 
    'cdm\-', 
    'cell', 
    'chtm', 
    'cldc', 
    'cmd\-', 
    'co(mp|nd)', 
    'craw', 
    'da(it|ll|ng)', 
    'dbte', 
    'dc\-s', 
    'devi', 
    'dica', 
    'dmob', 
    'do(c|p)o', 
    'ds(12|\-d)', 
    'el(49|ai)', 
    'em(l2|ul)', 
    'er(ic|k0)', 
    'esl8', 
    'ez([4-7]0|os|wa|ze)', 
    'fetc', 
    'fly(\-|_)', 
    'g1 u', 
    'g560', 
    'gene', 
    'gf\-5', 
    'g\-mo', 
    'go(\.w|od)', 
    'gr(ad|un)', 
    'haie', 
    'hcit', 
    'hd\-(m|p|t)', 
    'hei\-', 
    'hi(pt|ta)', 
    'hp( i|ip)', 
    'hs\-c', 
    'ht(c(\-| |_|a|g|p|s|t)|tp)', 
    'hu(aw|tc)', 
    'i\-(20|go|ma)', 
    'i230', 
    'iac( |\-|\/)', 
    'ibro', 
    'idea', 
    'ig01', 
    'ikom', 
    'im1k', 
    'inno', 
    'ipaq', 
    'iris', 
    'ja(t|v)a', 
    'jbro', 
    'jemu', 
    'jigs', 
    'kddi', 
    'keji', 
    'kgt( |\/)', 
    'klon', 
    'kpt ', 
    'kwc\-', 
    'kyo(c|k)', 
    'le(no|xi)', 
    'lg( g|\/(k|l|u)|50|54|\-[a-w])', 
    'libw', 
    'lynx', 
    'm1\-w', 
    'm3ga', 
    'm50\/', 
    'ma(te|ui|xo)', 
    'mc(01|21|ca)', 
    'm\-cr', 
    'me(rc|ri)', 
    'mi(o8|oa|ts)', 
    'mmef', 
    'mo(01|02|bi|de|do|t(\-| |o|v)|zz)', 
    'mt(50|p1|v )', 
    'mwbp', 
    'mywa', 
    'n10[0-2]', 
    'n20[2-3]', 
    'n30(0|2)', 
    'n50(0|2|5)', 
    'n7(0(0|1)|10)', 
    'ne((c|m)\-|on|tf|wf|wg|wt)', 
    'nok(6|i)', 
    'nzph', 
    'o2im', 
    'op(ti|wv)', 
    'oran', 
    'owg1', 
    'p800', 
    'pan(a|d|t)', 
    'pdxg', 
    'pg(13|\-([1-8]|c))', 
    'phil', 
    'pire', 
    'pl(ay|uc)', 
    'pn\-2', 
    'po(ck|rt|se)', 
    'prox', 
    'psio', 
    'pt\-g', 
    'qa\-a', 
    'qc(07|12|21|32|60|\-[2-7]|i\-)', 
    'qtek', 
    'r380', 
    'r600', 
    'raks', 
    'rim9', 
    'ro(ve|zo)', 
    's55\/', 
    'sa(ge|ma|mm|ms|ny|va)', 
    'sc(01|h\-|oo|p\-)', 
    'sdk\/', 
    'se(c(\-|0|1)|47|mc|nd|ri)', 
    'sgh\-', 
    'shar', 
    'sie(\-|m)', 
    'sk\-0', 
    'sl(45|id)', 
    'sm(al|ar|b3|it|t5)', 
    'so(ft|ny)', 
    'sp(01|h\-|v\-|v )', 
    'sy(01|mb)', 
    't2(18|50)', 
    't6(00|10|18)', 
    'ta(gt|lk)', 
    'tcl\-', 
    'tdg\-', 
    'tel(i|m)', 
    'tim\-', 
    't\-mo', 
    'to(pl|sh)', 
    'ts(70|m\-|m3|m5)', 
    'tx\-9', 
    'up(\.b|g1|si)', 
    'utst', 
    'v400', 
    'v750', 
    'veri', 
    'vi(rg|te)', 
    'vk(40|5[0-3]|\-v)', 
    'vm40', 
    'voda', 
    'vulc', 
    'vx(52|53|60|61|70|80|81|83|85|98)', 
    'w3c(\-| )', 
    'webc', 
    'whit', 
    'wi(g |nc|nw)', 
    'wmlb', 
    'wonu', 
    'x700', 
    'yas\-', 
    'your', 
    'zeto', 
    'zte\-'
];

$isPhone = preg_match('/' . implode($uaPhone, '|') . '/i', $uaFull);
$isMobile = preg_match('/' . implode($uaMobile, '|') . '/i', $uaStart);

if($isPhone || $isMobile) {
    // do something with that device
} else {
    // process normally
}

How to export data to CSV in PowerShell?

what you are searching for is the Export-Csv file.csv

try using Get-Help Export-Csv to see whats possible

also Out-File -FilePath "file.csv" will work

Count number of rows per group and add result to original data frame

You can do this:

> ddply(df,.(name,type),transform,count = NROW(piece))
   name  type num count
1 black chair   4     2
2 black chair   5     2
3 black  sofa  12     1
4   red plate   3     1
5   red  sofa   4     1

or perhaps more intuitively,

> ddply(df,.(name,type),transform,count = length(num))
   name  type num count
1 black chair   4     2
2 black chair   5     2
3 black  sofa  12     1
4   red plate   3     1
5   red  sofa   4     1

AngularJS passing data to $http.get request

Here's a complete example of an HTTP GET request with parameters using angular.js in ASP.NET MVC:

CONTROLLER:

public class AngularController : Controller
{
    public JsonResult GetFullName(string name, string surname)
    {
        System.Diagnostics.Debugger.Break();
        return Json(new { fullName = String.Format("{0} {1}",name,surname) }, JsonRequestBehavior.AllowGet);
    }
}

VIEW:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script type="text/javascript">
    var myApp = angular.module("app", []);

    myApp.controller('controller', function ($scope, $http) {

        $scope.GetFullName = function (employee) {

            //The url is as follows - ControllerName/ActionName?name=nameValue&surname=surnameValue

            $http.get("/Angular/GetFullName?name=" + $scope.name + "&surname=" + $scope.surname).
            success(function (data, status, headers, config) {
                alert('Your full name is - ' + data.fullName);
            }).
            error(function (data, status, headers, config) {
                alert("An error occurred during the AJAX request");
            });

        }
    });

</script>

<div ng-app="app" ng-controller="controller">

    <input type="text" ng-model="name" />
    <input type="text" ng-model="surname" />
    <input type="button" ng-click="GetFullName()" value="Get Full Name" />
</div>

Handling 'Sequence has no elements' Exception

The value is null, you have to check why... (in addition to the implementation of the solutions proposed here)

Check the hardware Connections.

How to make the window full screen with Javascript (stretching all over the screen)

Simple example from: http://www.longtailvideo.com/blog/26517/using-the-browsers-new-html5-fullscreen-capabilities/

<script type="text/javascript">
  function goFullscreen(id) {
    // Get the element that we want to take into fullscreen mode
    var element = document.getElementById(id);

    // These function will not exist in the browsers that don't support fullscreen mode yet, 
    // so we'll have to check to see if they're available before calling them.

    if (element.mozRequestFullScreen) {
      // This is how to go into fullscren mode in Firefox
      // Note the "moz" prefix, which is short for Mozilla.
      element.mozRequestFullScreen();
    } else if (element.webkitRequestFullScreen) {
      // This is how to go into fullscreen mode in Chrome and Safari
      // Both of those browsers are based on the Webkit project, hence the same prefix.
      element.webkitRequestFullScreen();
   }
   // Hooray, now we're in fullscreen mode!
  }
</script>

<img class="video_player" src="image.jpg" id="player"></img>
<button onclick="goFullscreen('player'); return false">Click Me To Go Fullscreen! (For real)</button>

How can I change Mac OS's default Java VM returned from /usr/libexec/java_home

I tested "jenv" and other things like setting "JAVA_HOME" without success. Now i and endet up with following solution

function setJava {
    export JAVA_HOME="$(/usr/libexec/java_home -v $1)"
    launchctl setenv JAVA_HOME $JAVA_HOME
    sudo ln -nsf "$(dirname ${JAVA_HOME})/MacOS" /Library/Java/MacOS 
    java -version
}

(added to ~/.bashrc or ~/.bash.profile or ~/.zshrc)

And calling like that:

setJava 1.8

java_home will handle the wrong input. so you can't do something wrong. Maven and other stuff will pick up the right version now.

How can I generate a list of consecutive numbers?

You can use itertools.count() to generate unbounded sequences. (itertools is in the Python standard library). Docs here:
https://docs.python.org/3/library/itertools.html#itertools.count

delete all from table

This should be faster:

DELETE * FROM table_name;

because RDBMS don't have to look where is what.

You should be fine with truncate though:

truncate table table_name

How to get a list of images on docker registry v2

Here is a nice little one liner (uses JQ) to print out a list of Repos and associated tags.

If you dont have jq installed you can use: brew install jq

# This is my URL but you can use any
REPO_URL=10.230.47.94:443

curl -k -s -X GET https://$REPO_URL/v2/_catalog \
 | jq '.repositories[]' \
 | sort \
 | xargs -I _ curl -s -k -X GET https://$REPO_URL/v2/_/tags/list

TERM environment variable not set

You've answered the question with this statement:

Cron calls this .sh every 2 minutes

Cron does not run in a terminal, so why would you expect one to be set?

The most common reason for getting this error message is because the script attempts to source the user's .profile which does not check that it's running in a terminal before doing something tty related. Workarounds include using a shebang line like:

#!/bin/bash -p

Which causes the sourcing of system-level profile scripts which (one hopes) does not attempt to do anything too silly and will have guards around code that depends on being run from a terminal.

If this is the entirety of the script, then the TERM error is coming from something other than the plain content of the script.

Beginner Python Practice?

Try Project Euler:

Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.

The problem is:

Add all the natural numbers below 1000 that are multiples of 3 or 5.

This question will probably introduce you to Python for-loops and the range() builtin function in the least. It might lead you to discover list comprehensions, or generator expressions and the sum() builtin function.

How can I backup a remote SQL Server database to a local drive?

Create a local shared folder, with "everyone" read/write privileges

Connect to the target database, start the backup and point to the share like below

\mymachine\shared_folder\mybackup.bak

(Tried on Windows domain environment)

Batch file to copy files from one folder to another folder

To bypass the 'specify a file name or directory name on the target (F = file, D = directory)?' prompt with xcopy, you can do the following...

echo f | xcopy /f /y srcfile destfile

or for those of us just copying large substructures/folders:

use /i which specifies destination must be a directory if copying more than one file

Transfer data from one HTML file to another

HI im going to leave this here cz i cant comment due to restrictions but i found AlexFitiskin's answer perfect, but a small correction was needed

document.getElementById('here').innerHTML = data.name; 

This needed to be changed to

document.getElementById('here').innerHTML = data.n;

I know that after five years the owner of the post will not find it of any importance but this is for people who might come across in the future .

Find size and free space of the filesystem containing a given file

import os

def get_mount_point(pathname):
    "Get the mount point of the filesystem containing pathname"
    pathname= os.path.normcase(os.path.realpath(pathname))
    parent_device= path_device= os.stat(pathname).st_dev
    while parent_device == path_device:
        mount_point= pathname
        pathname= os.path.dirname(pathname)
        if pathname == mount_point: break
        parent_device= os.stat(pathname).st_dev
    return mount_point

def get_mounted_device(pathname):
    "Get the device mounted at pathname"
    # uses "/proc/mounts"
    pathname= os.path.normcase(pathname) # might be unnecessary here
    try:
        with open("/proc/mounts", "r") as ifp:
            for line in ifp:
                fields= line.rstrip('\n').split()
                # note that line above assumes that
                # no mount points contain whitespace
                if fields[1] == pathname:
                    return fields[0]
    except EnvironmentError:
        pass
    return None # explicit

def get_fs_freespace(pathname):
    "Get the free space of the filesystem containing pathname"
    stat= os.statvfs(pathname)
    # use f_bfree for superuser, or f_bavail if filesystem
    # has reserved space for superuser
    return stat.f_bfree*stat.f_bsize

Some sample pathnames on my computer:

path 'trash':
  mp /home /dev/sda4
  free 6413754368
path 'smov':
  mp /mnt/S /dev/sde
  free 86761562112
path '/usr/local/lib':
  mp / rootfs
  free 2184364032
path '/proc/self/cmdline':
  mp /proc proc
  free 0

PS

if on Python =3.3, there's shutil.disk_usage(path) which returns a named tuple of (total, used, free) expressed in bytes.

How can I correctly format currency using jquery?

Use jquery.inputmask 3.x. See demos here

Include files:

<script src="/assets/jquery.inputmask.js" type="text/javascript"></script>
<script src="/assets/jquery.inputmask.extensions.js" type="text/javascript"></script>
<script src="/assets/jquery.inputmask.numeric.extensions.js" type="text/javascript"></script>

And code as

$(selector).inputmask('decimal',
  { 'alias': 'numeric',
    'groupSeparator': '.',
    'autoGroup': true,
    'digits': 2,
    'radixPoint': ",",
    'digitsOptional': false,
    'allowMinus': false,
    'prefix': '$ ',
    'placeholder': '0'
  }
);

Highlights:

  • easy to use
  • optional parts anywere in the mask
  • possibility to define aliases which hide complexity
  • date / datetime masks
  • numeric masks
  • lots of callbacks
  • non-greedy masks
  • many features can be enabled/disabled/configured by options
  • supports readonly/disabled/dir="rtl" attributes
  • support data-inputmask attribute(s)
  • multi-mask support
  • regex-mask support
  • dynamic-mask support
  • preprocessing-mask support
  • value formatting / validating without input element

How to render a PDF file in Android

There is no anyway to preview pdf document in Android webview.If you want to preview base64 pdf. It requires to third-party library.

build.Gradle

compile 'com.github.barteksc:android-pdf-viewer:2.7.0'

dialog_pdf_viewer

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/dialog_pdf_viewer_close"
        style="@style/ExitButtonImageViewStyle"
        android:src="@drawable/popup_exit" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="@color/white"
        android:orientation="vertical">

        <com.github.barteksc.pdfviewer.PDFView
            android:id="@+id/pdfView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>

    <View style="@style/HorizontalLine" />

    <com.pozitron.commons.customviews.ButtonFont
        android:id="@+id/dialog_pdf_viewer_button"
        style="@style/ButtonPrimary2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="15dp"
        android:text="@string/agreed" />

</LinearLayout>

DailogPDFViewer.java

public class DialogPdfViewer extends Dialog {
    PDFView pdfView;
    byte[] decodedString;

    public interface OnDialogPdfViewerListener {
        void onAgreeClick(DialogPdfViewer dialogFullEula);

        void onCloseClick(DialogPdfViewer dialogFullEula);
    }

    public DialogPdfViewer(Context context, String base64, final DialogPdfViewer.OnDialogPdfViewerListener onDialogPdfViewerListener) {
        super(context);

        setContentView(R.layout.dialog_pdf_viewer);
        findViewById(R.id.dialog_pdf_viewer_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onDialogPdfViewerListener.onCloseClick(DialogPdfViewer.this);
            }
        });

        findViewById(R.id.dialog_pdf_viewer_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onDialogPdfViewerListener.onAgreeClick(DialogPdfViewer.this);
            }
        });

        decodedString = Base64.decode(base64.toString(), Base64.DEFAULT);

        pdfView = ((PDFView) findViewById(R.id.pdfView));
        pdfView.fromBytes(decodedString).load();

        setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    onDialogPdfViewerListener.onCloseClick(DialogPdfViewer.this);
                }
                return true;
            }
        });

    }
}

Spring Boot - How to log all requests and responses with exceptions in single place?

If you are seeing only part of your request payload, you need to call the setMaxPayloadLength function as it defaults to showing only 50 characters in your request body. Also, setting setIncludeHeaders to false is a good idea if you don't want to log your auth headers!

@Bean
public CommonsRequestLoggingFilter requestLoggingFilter() {
    CommonsRequestLoggingFilter loggingFilter = new CommonsRequestLoggingFilter();
    loggingFilter.setIncludeClientInfo(false);
    loggingFilter.setIncludeQueryString(false);
    loggingFilter.setIncludePayload(true);
    loggingFilter.setIncludeHeaders(false);
    loggingFilter.setMaxPayloadLength(500);
    return loggingFilter;
}

How do you stop MySQL on a Mac OS install?

This worked for me on macOS 10.13.6 with 8.0.12 MySQL

/usr/local/mysql/support-files/mysql.server start

/usr/local/mysql/support-files/mysql.server restart

/usr/local/mysql/support-files/mysql.server stop

Java: set timeout on a certain block of code?

I faced a similar kind of issue where my task was to push a message to SQS within a particular timeout. I used the trivial logic of executing it via another thread and waiting on its future object by specifying the timeout. This would give me a TIMEOUT exception in case of timeouts.

final Future<ISendMessageResult> future = 
timeoutHelperThreadPool.getExecutor().submit(() -> {
  return getQueueStore().sendMessage(request).get();
});
try {
  sendMessageResult = future.get(200, TimeUnit.MILLISECONDS);
  logger.info("SQS_PUSH_SUCCESSFUL");
  return true;

} catch (final TimeoutException e) {
  logger.error("SQS_PUSH_TIMEOUT_EXCEPTION");
}

But there are cases where you can't stop the code being executed by another thread and you get true negatives in that case.

For example - In my case, my request reached SQS and while the message was being pushed, my code logic encountered the specified timeout. Now in reality my message was pushed into the Queue but my main thread assumed it to be failed because of the TIMEOUT exception. This is a type of problem which can be avoided rather than being solved. Like in my case I avoided it by providing a timeout which would suffice in nearly all of the cases.

If the code you want to interrupt is within you application and is not something like an API call then you can simply use

future.cancel(true)

However do remember that java docs says that it does guarantee that the execution will be blocked.

"Attempts to cancel execution of this task. This attempt will fail if the task has already completed, has already been cancelled,or could not be cancelled for some other reason. If successful,and this task has not started when cancel is called,this task should never run. If the task has already started,then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted inan attempt to stop the task."

How to use private Github repo as npm dependency

I wasn't able to make the accepted answer work in a Docker container.

What worked for me was to set the Personal Access Token from github in a file .nextrc

ARG GITHUB_READ_TOKEN
RUN echo -e "machine github.com\n  login $GITHUB_READ_TOKEN" > ~/.netrc 
RUN npm install --only=production --force \
  && npm cache clean --force
RUN rm ~/.netrc

in package.json

"my-lib": "github:username/repo",

How to Delete a topic in apache kafka

Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable to true) on all brokers first.

Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable is by default true.

Follow this step by step process for manual deletion of topics

  1. Stop Kafka server
  2. Delete the topic directory, on each broker (as defined in the logs.dirs and log.dir properties) with rm -rf command
  3. Connect to Zookeeper instance: zookeeper-shell.sh host:port
  4. From within the Zookeeper instance:
    1. List the topics using: ls /brokers/topics
    2. Remove the topic folder from ZooKeeper using: rmr /brokers/topics/yourtopic
    3. Exit the Zookeeper instance (Ctrl+C)
  5. Restart Kafka server
  6. Confirm if it was deleted or not by using this command kafka-topics.sh --list --zookeeper host:port

Is it possible in Java to catch two exceptions in the same catch block?

Java 7 and later

Multiple-exception catches are supported, starting in Java 7.

The syntax is:

try {
     // stuff
} catch (Exception1 | Exception2 ex) {
     // Handle both exceptions
}

The static type of ex is the most specialized common supertype of the exceptions listed. There is a nice feature where if you rethrow ex in the catch, the compiler knows that only one of the listed exceptions can be thrown.


Java 6 and earlier

Prior to Java 7, there are ways to handle this problem, but they tend to be inelegant, and to have limitations.

Approach #1

try {
     // stuff
} catch (Exception1 ex) {
     handleException(ex);
} catch (Exception2 ex) {
     handleException(ex);
}

public void handleException(SuperException ex) {
     // handle exception here
}

This gets messy if the exception handler needs to access local variables declared before the try. And if the handler method needs to rethrow the exception (and it is checked) then you run into serious problems with the signature. Specifically, handleException has to be declared as throwing SuperException ... which potentially means you have to change the signature of the enclosing method, and so on.

Approach #2

try {
     // stuff
} catch (SuperException ex) {
     if (ex instanceof Exception1 || ex instanceof Exception2) {
         // handle exception
     } else {
         throw ex;
     }
}

Once again, we have a potential problem with signatures.

Approach #3

try {
     // stuff
} catch (SuperException ex) {
     if (ex instanceof Exception1 || ex instanceof Exception2) {
         // handle exception
     }
}

If you leave out the else part (e.g. because there are no other subtypes of SuperException at the moment) the code becomes more fragile. If the exception hierarchy is reorganized, this handler without an else may end up silently eating exceptions!

Save PHP array to MySQL?

you can insert serialized object ( array ) to mysql , example serialize($object) and you can unserize object example unserialize($object)

How to work with complex numbers in C?

To extract the real part of a complex-valued expression z, use the notation as __real__ z. Similarly, use __imag__ attribute on the z to extract the imaginary part.

For example;

__complex__ float z;
float r;
float i;
r = __real__ z;
i = __imag__ z;

r is the real part of the complex number "z" i is the imaginary part of the complex number "z"

regular expression for finding 'href' value of a <a> link

Thanks everyone (specially @plalx)

I find it quite overkill enforce the validity of the href attribute with such a complex and cryptic pattern while a simple expression such as
<a\s+(?:[^>]*?\s+)?href="([^"]*)"
would suffice to capture all URLs. If you want to make sure they contain at least a query string, you could just use
<a\s+(?:[^>]*?\s+)?href="([^"]+\?[^"]+)"


My final regex string:


First use one of this:
st = @"((www\.|https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+ \w\d:#@%/;$()~_?\+-=\\\.&]*)";
st = @"<a href[^>]*>(.*?)</a>";
st = @"((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)";
st = @"((?:(?:https?|ftp|gopher|telnet|file|notes|ms-help):(?://|\\\\)(?:www\.)?|www\.)[\w\d:#@%/;$()~_?\+,\-=\\.&]+)";
st = @"(?:(?:https?|ftp|gopher|telnet|file|notes|ms-help):(?://|\\\\)(?:www\.)?|www\.)";
st = @"(((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+)|(www\.)[\w\d:#@%/;$()~_?\+-=\\\.&]*)";
st = @"href=[""'](?<url>(http|https)://[^/]*?\.(com|org|net|gov))(/.*)?[""']";
st = @"(<a.*?>.*?</a>)";
st = @"(?:hrefs*=)(?:[s""']*)(?!#|mailto|location.|javascript|.*css|.*this.)(?.*?)(?:[s>""'])";
st = @"http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?";
st = @"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?";
st = @"(http|https)://([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?";
st = @"((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?)";
st = @"http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?";
st = @"http(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?$";
st = @"(?<Protocol>\w+):\/\/(?<Domain>[\w.]+\/?)\S*";

my choice is

@"(?<Protocol>\w+):\/\/(?<Domain>[\w.]+\/?)\S*"

Second Use this:

st = "(.*)?(.*)=(.*)";


Problem Solved. Thanks every one :)

How I can check whether a page is loaded completely or not in web driver?

Below is some code from my BasePageObject class for waits:

public void waitForPageLoadAndTitleContains(int timeout, String pageTitle) {
    WebDriverWait wait = new WebDriverWait(driver, timeout, 1000);
    wait.until(ExpectedConditions.titleContains(pageTitle));
}

public void waitForElementPresence(By locator, int seconds) {
    WebDriverWait wait = new WebDriverWait(driver, seconds);
    wait.until(ExpectedConditions.presenceOfElementLocated(locator));
}

public void jsWaitForPageToLoad(int timeOutInSeconds) {
    JavascriptExecutor js = (JavascriptExecutor) driver;
    String jsCommand = "return document.readyState";

    // Validate readyState before doing any waits
    if (js.executeScript(jsCommand).toString().equals("complete")) {
        return;
    }

    for (int i = 0; i < timeOutInSeconds; i++) {
        TimeManager.waitInSeconds(3);
        if (js.executeScript(jsCommand).toString().equals("complete")) {
            break;
        }
    }
}

   /**
     * Looks for a visible OR invisible element via the provided locator for up
     * to maxWaitTime. Returns as soon as the element is found.
     *
     * @param byLocator
     * @param maxWaitTime - In seconds
     * @return
     *
     */
    public WebElement findElementThatIsPresent(final By byLocator, int maxWaitTime) {
        if (driver == null) {
            nullDriverNullPointerExeption();
        }
        FluentWait<WebDriver> wait = new FluentWait<>(driver).withTimeout(maxWaitTime, java.util.concurrent.TimeUnit.SECONDS)
                .pollingEvery(200, java.util.concurrent.TimeUnit.MILLISECONDS);

        try {
            return wait.until((WebDriver webDriver) -> {
                List<WebElement> elems = driver.findElements(byLocator);
                if (elems.size() > 0) {
                    return elems.get(0);
                } else {
                    return null;
                }
            });
        } catch (Exception e) {
            return null;
        }
    }

Supporting methods:

     /**
     * Gets locator.
     *
     * @param fieldName
     * @return
     */
    public By getBy(String fieldName) {
        try {
            return new Annotations(this.getClass().getDeclaredField(fieldName)).buildBy();
        } catch (NoSuchFieldException e) {
            return null;
        }
    }

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

You can use a very good online tool for it. Here is the link dreampuf.github.io Just replace the code inside editer with your code.

Android ImageView Fixing Image Size

I had the same issue and this helped me.

<ImageView
    android:id="@+id/image"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:scaleType="fitXY"
    />

np.mean() vs np.average() in Python NumPy?

np.average takes an optional weight parameter. If it is not supplied they are equivalent. Take a look at the source code: Mean, Average

np.mean:

try:
    mean = a.mean
except AttributeError:
    return _wrapit(a, 'mean', axis, dtype, out)
return mean(axis, dtype, out)

np.average:

...
if weights is None :
    avg = a.mean(axis)
    scl = avg.dtype.type(a.size/avg.size)
else:
    #code that does weighted mean here

if returned: #returned is another optional argument
    scl = np.multiply(avg, 0) + scl
    return avg, scl
else:
    return avg
...

"break;" out of "if" statement?

break interacts solely with the closest enclosing loop or switch, whether it be a for, while or do .. while type. It is frequently referred to as a goto in disguise, as all loops in C can in fact be transformed into a set of conditional gotos:

for (A; B; C) D;
// translates to
A;
goto test;
loop: D;
iter: C;
test: if (B) goto loop;
end:

while (B) D;          // Simply doesn't have A or C
do { D; } while (B);  // Omits initial goto test
continue;             // goto iter;
break;                // goto end;

The difference is, continue and break interact with virtual labels automatically placed by the compiler. This is similar to what return does as you know it will always jump ahead in the program flow. Switches are slightly more complicated, generating arrays of labels and computed gotos, but the way break works with them is similar.

The programming error the notice refers to is misunderstanding break as interacting with an enclosing block rather than an enclosing loop. Consider:

for (A; B; C) {
   D;
   if (E) {
       F;
       if (G) break;   // Incorrectly assumed to break if(E), breaks for()
       H;
   }
   I;
}
J;

Someone thought, given such a piece of code, that G would cause a jump to I, but it jumps to J. The intended function would use if (!G) H; instead.

Python name 'os' is not defined

The problem is that you forgot to import os. Add this line of code:

import os

And everything should be fine. Hope this helps!

Define global variable with webpack

You can use define window.myvar = {}. When you want to use it, you can use like window.myvar = 1

Calculate mean and standard deviation from a vector of samples in C++ using Boost

My answer is similar as Josh Greifer but generalised to sample covariance. Sample variance is just sample covariance but with the two inputs identical. This includes Bessel's correlation.

    template <class Iter> typename Iter::value_type cov(const Iter &x, const Iter &y)
    {
        double sum_x = std::accumulate(std::begin(x), std::end(x), 0.0);
        double sum_y = std::accumulate(std::begin(y), std::end(y), 0.0);

        double mx =  sum_x / x.size();
        double my =  sum_y / y.size();

        double accum = 0.0;

        for (auto i = 0; i < x.size(); i++)
        {
            accum += (x.at(i) - mx) * (y.at(i) - my);
        }

        return accum / (x.size() - 1);
    }

Capturing a single image from my webcam in Java or Python

On windows it is easy to interact with your webcam with pygame:

from VideoCapture import Device
cam = Device()
cam.saveSnapshot('image.jpg')

I haven't tried using pygame on linux (all my linux boxen are servers without X), but this link might be helpful http://www.jperla.com/blog/post/capturing-frames-from-a-webcam-on-linux

Setting Short Value Java

Generally you can just cast the variable to become a short.

You can also get problems like this that can be confusing. This is because the + operator promotes them to an int

enter image description here

Casting the elements won't help:

enter image description here

You need to cast the expression:

enter image description here

How can I push a specific commit to a remote, and not previous commits?

To push up through a given commit, you can write:

git push <remotename> <commit SHA>:<remotebranchname>

provided <remotebranchname> already exists on the remote. (If it doesn't, you can use git push <remotename> <commit SHA>:refs/heads/<remotebranchname> to autocreate it.)

If you want to push a commit without pushing previous commits, you should first use git rebase -i to re-order the commits.

How can I change CSS display none or block property using jQuery?

In my case I was doing show / hide elements of a form according to whether an input element was empty or not, so that when hiding the elements the element following the hidden ones was repositioned occupying its space it was necessary to do a float: left of the element of such an element. Even using a plugin as dependsOn it was necessary to use float.

Python != operation vs "is not"

>>> () is ()
True
>>> 1 is 1
True
>>> (1,) == (1,)
True
>>> (1,) is (1,)
False
>>> a = (1,)
>>> b = a
>>> a is b
True

Some objects are singletons, and thus is with them is equivalent to ==. Most are not.

Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2

About Android Studio Gradle plugin version and Required Gradle version, you can see more detailed answer here: What is real Android Studio Gradle Version?

For each version of this Gradle plugin, it requires a minimum Gradle version as listed on below table

(Reference page:gradle-plugin#updating-gradle).

enter image description here

When you update Android Studio, you may receive a prompt to also update Gradle to the latest available version.

For example, Android Gradle Plugin version 3.1.0+ requires a minimal gradle version 4.4.

You can be configured via Android Studio File -> Project Structure -> Project. See below:

enter image description here

Or you can manually modify the file gradle/wrapper/gradle-wrapper.properties. For example:

distributionUrl = https\://services.gradle.org/distributions/gradle-4.6-all.zip

Paste MS Excel data to SQL Server

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

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

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

Moving from position A to position B slowly with animation

Use jquery animate and give it a long duration say 2000

$("#Friends").animate({ 
        top: "-=30px",
      }, duration );

The -= means that the animation will be relative to the current top position.

Note that the Friends element must have position set to relative in the css:

#Friends{position:relative;}

How do I rename the android package name?

What I did was the following :

I simply created the package with the desired name , in the src folder , next to the current package with current name.

I dragged all contents of current package to new package , intellij popped a dialog box asking me if I want to refactor inside package references and project references to new package , I clicked 'yes' and TA-DAAA , worked like a charm.

Insert using LEFT JOIN and INNER JOIN

you can't use VALUES clause when inserting data using another SELECT query. see INSERT SYNTAX

INSERT INTO user
(
 id, name, username, email, opted_in
)
(
    SELECT id, name, username, email, opted_in
    FROM user
         LEFT JOIN user_permission AS userPerm
            ON user.id = userPerm.user_id
);

Get installed applications in a system

it's worth noting that the Win32_Product WMI class represents products as they are installed by Windows Installer. not every application use windows installer

however "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" represents applications for 32 bit. For 64 bit you also need to traverse "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall" and since not every software has a 64 bit version the total applications installed are a union of keys on both locations that have "UninstallString" Value with them.

but the best options remains the same .traverse registry keys is a better approach since every application have an entry in registry[including the ones in Windows Installer].however the registry method is insecure as if anyone removes the corresponding key then you will not know the Application entry.On the contrary Altering the HKEY_Classes_ROOT\Installers is more tricky as it is linked with licensing issues such as Microsoft office or other products. for more robust solution you can always combine registry alternative with the WMI.

What is the best java image processing library/approach?

RoboRealm vision software list mentions JHLabs and NeatVision among lots of other non-Java based libraries.

How do I open port 22 in OS X 10.6.7

There are 3 solutions available for these.

1) Enable remote login using below command - sudo systemsetup -setremotelogin on

2) In Mac, go to System Preference -> Sharing -> enable Remote Login that's it. 100% working solution

3) Final and most important solution is - Check your private area network connection . Sometime remote login isn't allow inside the local area network.

Kindly try to connect your machine using personal network like mobile network, Hotspot etc.

rotate image with css

Perform rotation using transform: rotate(xdeg) and also apply overflow: hidden to the parent component to avoid overlapping effect

.div-parent {
   overflow: hidden
}

.div-child {
   transform: rotate(270deg);
}

Change directory in PowerShell

You can simply type Q: and that should solve your problem.

Python pandas Filtering out nan from a data selection of a column of strings

Simplest of all solutions:

filtered_df = df[df['name'].notnull()]

Thus, it filters out only rows that doesn't have NaN values in 'name' column.

For multiple columns:

filtered_df = df[df[['name', 'country', 'region']].notnull().all(1)]

Copying text to the clipboard using Java

For JavaFx based applications.

        //returns System Clipboard
        final Clipboard clipboard = Clipboard.getSystemClipboard();
        // ClipboardContent provides flexibility to store data in different formats
        final ClipboardContent content = new ClipboardContent();
        content.putString("Some text");
        content.putHtml("<b>Some</b> text");
        //this will be replaced by previous putString
        content.putString("Some different text");
        //set the content to clipboard
        clipboard.setContent(content);
       // validate before retrieving it
        if(clipboard.hasContent(DataFormat.HTML)){
            System.out.println(clipboard.getHtml());
        }
        if(clipboard.hasString()){
            System.out.println(clipboard.getString());
        }

ClipboardContent can save multiple data in several data formats like(html,url,plain text,image).

For more information see official documentation

PHP shell_exec() vs exec()

Here are the differences. Note the newlines at the end.

> shell_exec('date')
string(29) "Wed Mar  6 14:18:08 PST 2013\n"
> exec('date')
string(28) "Wed Mar  6 14:18:12 PST 2013"

> shell_exec('whoami')
string(9) "mark\n"
> exec('whoami')
string(8) "mark"

> shell_exec('ifconfig')
string(1244) "eth0      Link encap:Ethernet  HWaddr 10:bf:44:44:22:33  \n          inet addr:192.168.0.90  Bcast:192.168.0.255  Mask:255.255.255.0\n          inet6 addr: fe80::12bf:ffff:eeee:2222/64 Scope:Link\n          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1\n          RX packets:16264200 errors:0 dropped:1 overruns:0 frame:0\n          TX packets:7205647 errors:0 dropped:0 overruns:0 carrier:0\n          collisions:0 txqueuelen:1000 \n          RX bytes:13151177627 (13.1 GB)  TX bytes:2779457335 (2.7 GB)\n"...
> exec('ifconfig')
string(0) ""

Note that use of the backtick operator is identical to shell_exec().

Update: I really should explain that last one. Looking at this answer years later even I don't know why that came out blank! Daniel explains it above -- it's because exec only returns the last line, and ifconfig's last line happens to be blank.

How do I lowercase a string in Python?

How to convert string to lowercase in Python?

Is there any way to convert an entire user inputted string from uppercase, or even part uppercase to lowercase?

E.g. Kilometers --> kilometers

The canonical Pythonic way of doing this is

>>> 'Kilometers'.lower()
'kilometers'

However, if the purpose is to do case insensitive matching, you should use case-folding:

>>> 'Kilometers'.casefold()
'kilometers'

Here's why:

>>> "Maße".casefold()
'masse'
>>> "Maße".lower()
'maße'
>>> "MASSE" == "Maße"
False
>>> "MASSE".lower() == "Maße".lower()
False
>>> "MASSE".casefold() == "Maße".casefold()
True

This is a str method in Python 3, but in Python 2, you'll want to look at the PyICU or py2casefold - several answers address this here.

Unicode Python 3

Python 3 handles plain string literals as unicode:

>>> string = '????????'
>>> string
'????????'
>>> string.lower()
'????????'

Python 2, plain string literals are bytes

In Python 2, the below, pasted into a shell, encodes the literal as a string of bytes, using utf-8.

And lower doesn't map any changes that bytes would be aware of, so we get the same string.

>>> string = '????????'
>>> string
'\xd0\x9a\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> string.lower()
'\xd0\x9a\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> print string.lower()
????????

In scripts, Python will object to non-ascii (as of Python 2.5, and warning in Python 2.4) bytes being in a string with no encoding given, since the intended coding would be ambiguous. For more on that, see the Unicode how-to in the docs and PEP 263

Use Unicode literals, not str literals

So we need a unicode string to handle this conversion, accomplished easily with a unicode string literal, which disambiguates with a u prefix (and note the u prefix also works in Python 3):

>>> unicode_literal = u'????????'
>>> print(unicode_literal.lower())
????????

Note that the bytes are completely different from the str bytes - the escape character is '\u' followed by the 2-byte width, or 16 bit representation of these unicode letters:

>>> unicode_literal
u'\u041a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
>>> unicode_literal.lower()
u'\u043a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'

Now if we only have it in the form of a str, we need to convert it to unicode. Python's Unicode type is a universal encoding format that has many advantages relative to most other encodings. We can either use the unicode constructor or str.decode method with the codec to convert the str to unicode:

>>> unicode_from_string = unicode(string, 'utf-8') # "encoding" unicode from string
>>> print(unicode_from_string.lower())
????????
>>> string_to_unicode = string.decode('utf-8') 
>>> print(string_to_unicode.lower())
????????
>>> unicode_from_string == string_to_unicode == unicode_literal
True

Both methods convert to the unicode type - and same as the unicode_literal.

Best Practice, use Unicode

It is recommended that you always work with text in Unicode.

Software should only work with Unicode strings internally, converting to a particular encoding on output.

Can encode back when necessary

However, to get the lowercase back in type str, encode the python string to utf-8 again:

>>> print string
????????
>>> string
'\xd0\x9a\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> string.decode('utf-8')
u'\u041a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
>>> string.decode('utf-8').lower()
u'\u043a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
>>> string.decode('utf-8').lower().encode('utf-8')
'\xd0\xba\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> print string.decode('utf-8').lower().encode('utf-8')
????????

So in Python 2, Unicode can encode into Python strings, and Python strings can decode into the Unicode type.

How do I find and replace all occurrences (in all files) in Visual Studio Code?

To replace a string in a single file (currently opened): CTRL + H

For replacing at workspace level use: CTRL + SHIFT + H

What could cause java.lang.reflect.InvocationTargetException?

That InvocationTargetException is probably wrapping up your ArrayIndexOutOfBoundsException. There is no telling upfront when using reflection what that method can throw -- so rather than using a throws Exception approach, all the exceptions are being caught and wrapped up in InvocationTargetException.

Convert canvas to PDF

You can achieve this by utilizing the jsPDF library and the toDataURL function.

I made a little demonstration:

_x000D_
_x000D_
var canvas = document.getElementById('myCanvas');_x000D_
var context = canvas.getContext('2d');_x000D_
_x000D_
// draw a blue cloud_x000D_
context.beginPath();_x000D_
context.moveTo(170, 80);_x000D_
context.bezierCurveTo(130, 100, 130, 150, 230, 150);_x000D_
context.bezierCurveTo(250, 180, 320, 180, 340, 150);_x000D_
context.bezierCurveTo(420, 150, 420, 120, 390, 100);_x000D_
context.bezierCurveTo(430, 40, 370, 30, 340, 50);_x000D_
context.bezierCurveTo(320, 5, 250, 20, 250, 50);_x000D_
context.bezierCurveTo(200, 5, 150, 20, 170, 80);_x000D_
context.closePath();_x000D_
context.lineWidth = 5;_x000D_
context.fillStyle = '#8ED6FF';_x000D_
context.fill();_x000D_
context.strokeStyle = '#0000ff';_x000D_
context.stroke();_x000D_
_x000D_
download.addEventListener("click", function() {_x000D_
  // only jpeg is supported by jsPDF_x000D_
  var imgData = canvas.toDataURL("image/jpeg", 1.0);_x000D_
  var pdf = new jsPDF();_x000D_
_x000D_
  pdf.addImage(imgData, 'JPEG', 0, 0);_x000D_
  pdf.save("download.pdf");_x000D_
}, false);
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>_x000D_
_x000D_
_x000D_
<canvas id="myCanvas" width="578" height="200"></canvas>_x000D_
<button id="download">download</button>
_x000D_
_x000D_
_x000D_

Loop over array dimension in plpgsql

Since PostgreSQL 9.1 there is the convenient FOREACH:

DO
$do$
DECLARE
   m   varchar[];
   arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
   FOREACH m SLICE 1 IN ARRAY arr
   LOOP
      RAISE NOTICE 'another_func(%,%)',m[1], m[2];
   END LOOP;
END
$do$

Solution for older versions:

DO
$do$
DECLARE
   arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
   FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
   LOOP
      RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
   END LOOP;
END
$do$

Also, there is no difference between varchar[] and varchar[][] for the PostgreSQL type system. I explain in more detail here.

The DO statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql is the default (so you can omit the declaration).

validate a dropdownlist in asp.net mvc

There is an overload with 3 arguments. Html.DropdownList(name, selectList, optionLabel) Update: there was a typo in the below code snippet.

@Html.DropDownList("Cat", new SelectList(ViewBag.Categories,"ID", "CategoryName"), "-Select Category-")

For the validator use

@Html.ValidationMessage("Cat")

HTML5 Video autoplay on iPhone

I had a similar problem and I tried multiple solution. I solved it implementing 2 considerations.

  1. Using dangerouslySetInnerHtml to embed the <video> code. For example:
<div dangerouslySetInnerHTML={{ __html: `
    <video class="video-js" playsinline autoplay loop muted>
        <source src="../video_path.mp4" type="video/mp4"/>
    </video>`}}
/>
  1. Resizing the video weight. I noticed my iPhone does not autoplay videos over 3 megabytes. So I used an online compressor tool (https://www.mp4compress.com/) to go from 4mb to less than 500kb

Also, thanks to @boltcoder for his guide: Autoplay muted HTML5 video using React on mobile (Safari / iOS 10+)

Build fat static library (device + simulator) using Xcode and SDK 4+

ALTERNATIVES:

Easy copy/paste of latest version (but install instructions may change - see below!)

Karl's library takes much more effort to setup, but much nicer long-term solution (it converts your library into a Framework).

Use this, then tweak it to add support for Archive builds - c.f. @Frederik's comment below on the changes he's using to make this work nicely with Archive mode.


RECENT CHANGES: 1. Added support for iOS 10.x (while maintaining support for older platforms)

  1. Info on how to use this script with a project-embedded-in-another-project (although I highly recommend NOT doing that, ever - Apple has a couple of show-stopper bugs in Xcode if you embed projects inside each other, from Xcode 3.x through to Xcode 4.6.x)

  2. Bonus script to let you auto-include Bundles (i.e. include PNG files, PLIST files etc from your library!) - see below (scroll to bottom)

  3. now supports iPhone5 (using Apple's workaround to the bugs in lipo). NOTE: the install instructions have changed (I can probably simplify this by changing the script in future, but don't want to risk it now)

  4. "copy headers" section now respects the build setting for the location of the public headers (courtesy of Frederik Wallner)

  5. Added explicit setting of SYMROOT (maybe need OBJROOT to be set too?), thanks to Doug Dickinson


SCRIPT (this is what you have to copy/paste)

For usage / install instructions, see below

##########################################
#
# c.f. https://stackoverflow.com/questions/3520977/build-fat-static-library-device-simulator-using-xcode-and-sdk-4
#
# Version 2.82
#
# Latest Change:
# - MORE tweaks to get the iOS 10+ and 9- working
# - Support iOS 10+
# - Corrected typo for iOS 1-10+ (thanks @stuikomma)
# 
# Purpose:
#   Automatically create a Universal static library for iPhone + iPad + iPhone Simulator from within XCode
#
# Author: Adam Martin - http://twitter.com/redglassesapps
# Based on: original script from Eonil (main changes: Eonil's script WILL NOT WORK in Xcode GUI - it WILL CRASH YOUR COMPUTER)
#

set -e
set -o pipefail

#################[ Tests: helps workaround any future bugs in Xcode ]########
#
DEBUG_THIS_SCRIPT="false"

if [ $DEBUG_THIS_SCRIPT = "true" ]
then
echo "########### TESTS #############"
echo "Use the following variables when debugging this script; note that they may change on recursions"
echo "BUILD_DIR = $BUILD_DIR"
echo "BUILD_ROOT = $BUILD_ROOT"
echo "CONFIGURATION_BUILD_DIR = $CONFIGURATION_BUILD_DIR"
echo "BUILT_PRODUCTS_DIR = $BUILT_PRODUCTS_DIR"
echo "CONFIGURATION_TEMP_DIR = $CONFIGURATION_TEMP_DIR"
echo "TARGET_BUILD_DIR = $TARGET_BUILD_DIR"
fi

#####################[ part 1 ]##################
# First, work out the BASESDK version number (NB: Apple ought to report this, but they hide it)
#    (incidental: searching for substrings in sh is a nightmare! Sob)

SDK_VERSION=$(echo ${SDK_NAME} | grep -o '\d\{1,2\}\.\d\{1,2\}$')

# Next, work out if we're in SIM or DEVICE

if [ ${PLATFORM_NAME} = "iphonesimulator" ]
then
OTHER_SDK_TO_BUILD=iphoneos${SDK_VERSION}
else
OTHER_SDK_TO_BUILD=iphonesimulator${SDK_VERSION}
fi

echo "XCode has selected SDK: ${PLATFORM_NAME} with version: ${SDK_VERSION} (although back-targetting: ${IPHONEOS_DEPLOYMENT_TARGET})"
echo "...therefore, OTHER_SDK_TO_BUILD = ${OTHER_SDK_TO_BUILD}"
#
#####################[ end of part 1 ]##################

#####################[ part 2 ]##################
#
# IF this is the original invocation, invoke WHATEVER other builds are required
#
# Xcode is already building ONE target...
#
# ...but this is a LIBRARY, so Apple is wrong to set it to build just one.
# ...we need to build ALL targets
# ...we MUST NOT re-build the target that is ALREADY being built: Xcode WILL CRASH YOUR COMPUTER if you try this (infinite recursion!)
#
#
# So: build ONLY the missing platforms/configurations.

if [ "true" == ${ALREADYINVOKED:-false} ]
then
echo "RECURSION: I am NOT the root invocation, so I'm NOT going to recurse"
else
# CRITICAL:
# Prevent infinite recursion (Xcode sucks)
export ALREADYINVOKED="true"

echo "RECURSION: I am the root ... recursing all missing build targets NOW..."
echo "RECURSION: ...about to invoke: xcodebuild -configuration \"${CONFIGURATION}\" -project \"${PROJECT_NAME}.xcodeproj\" -target \"${TARGET_NAME}\" -sdk \"${OTHER_SDK_TO_BUILD}\" ${ACTION} RUN_CLANG_STATIC_ANALYZER=NO" BUILD_DIR=\"${BUILD_DIR}\" BUILD_ROOT=\"${BUILD_ROOT}\" SYMROOT=\"${SYMROOT}\"

xcodebuild -configuration "${CONFIGURATION}" -project "${PROJECT_NAME}.xcodeproj" -target "${TARGET_NAME}" -sdk "${OTHER_SDK_TO_BUILD}" ${ACTION} RUN_CLANG_STATIC_ANALYZER=NO BUILD_DIR="${BUILD_DIR}" BUILD_ROOT="${BUILD_ROOT}" SYMROOT="${SYMROOT}"

ACTION="build"

#Merge all platform binaries as a fat binary for each configurations.

# Calculate where the (multiple) built files are coming from:
CURRENTCONFIG_DEVICE_DIR=${SYMROOT}/${CONFIGURATION}-iphoneos
CURRENTCONFIG_SIMULATOR_DIR=${SYMROOT}/${CONFIGURATION}-iphonesimulator

echo "Taking device build from: ${CURRENTCONFIG_DEVICE_DIR}"
echo "Taking simulator build from: ${CURRENTCONFIG_SIMULATOR_DIR}"

CREATING_UNIVERSAL_DIR=${SYMROOT}/${CONFIGURATION}-universal
echo "...I will output a universal build to: ${CREATING_UNIVERSAL_DIR}"

# ... remove the products of previous runs of this script
#      NB: this directory is ONLY created by this script - it should be safe to delete!

rm -rf "${CREATING_UNIVERSAL_DIR}"
mkdir "${CREATING_UNIVERSAL_DIR}"

#
echo "lipo: for current configuration (${CONFIGURATION}) creating output file: ${CREATING_UNIVERSAL_DIR}/${EXECUTABLE_NAME}"
xcrun -sdk iphoneos lipo -create -output "${CREATING_UNIVERSAL_DIR}/${EXECUTABLE_NAME}" "${CURRENTCONFIG_DEVICE_DIR}/${EXECUTABLE_NAME}" "${CURRENTCONFIG_SIMULATOR_DIR}/${EXECUTABLE_NAME}"

#########
#
# Added: StackOverflow suggestion to also copy "include" files
#    (untested, but should work OK)
#
echo "Fetching headers from ${PUBLIC_HEADERS_FOLDER_PATH}"
echo "  (if you embed your library project in another project, you will need to add"
echo "   a "User Search Headers" build setting of: (NB INCLUDE THE DOUBLE QUOTES BELOW!)"
echo '        "$(TARGET_BUILD_DIR)/usr/local/include/"'
if [ -d "${CURRENTCONFIG_DEVICE_DIR}${PUBLIC_HEADERS_FOLDER_PATH}" ]
then
mkdir -p "${CREATING_UNIVERSAL_DIR}${PUBLIC_HEADERS_FOLDER_PATH}"
# * needs to be outside the double quotes?
cp -r "${CURRENTCONFIG_DEVICE_DIR}${PUBLIC_HEADERS_FOLDER_PATH}"* "${CREATING_UNIVERSAL_DIR}${PUBLIC_HEADERS_FOLDER_PATH}"
fi
fi

INSTALL INSTRUCTIONS

  1. Create a static lib project
  2. Select the Target
  3. In "Build Settings" tab, set "Build Active Architecture Only" to "NO" (for all items)
  4. In "Build Phases" tab, select "Add ... New Build Phase ... New Run Script Build Phase"
  5. Copy/paste the script (above) into the box

...BONUS OPTIONAL usage:

  1. OPTIONAL: if you have headers in your library, add them to the "Copy Headers" phase
  2. OPTIONAL: ...and drag/drop them from the "Project" section to the "Public" section
  3. OPTIONAL: ...and they will AUTOMATICALLY be exported every time you build the app, into a sub-directory of the "debug-universal" directory (they will be in usr/local/include)
  4. OPTIONAL: NOTE: if you also try to drag/drop your project into another Xcode project, this exposes a bug in Xcode 4, where it cannot create an .IPA file if you have Public Headers in your drag/dropped project. The workaround: dont' embed xcode projects (too many bugs in Apple's code!)

If you can't find the output file, here's a workaround:

  1. Add the following code to the very end of the script (courtesy of Frederik Wallner): open "${CREATING_UNIVERSAL_DIR}"

  2. Apple deletes all output after 200 lines. Select your Target, and in the Run Script Phase, you MUST untick: "Show environment variables in build log"

  3. if you're using a custom "build output" directory for XCode4, then XCode puts all your "unexpected" files in the wrong place.

    1. Build the project
    2. Click on the last icon on the right, in the top left area of Xcode4.
    3. Select the top item (this is your "most recent build". Apple should auto-select it, but they didn't think of that)
    4. in the main window, scroll to bottom. The very last line should read: lipo: for current configuration (Debug) creating output file: /Users/blah/Library/Developer/Xcode/DerivedData/AppName-ashwnbutvodmoleijzlncudsekyf/Build/Products/Debug-universal/libTargetName.a

    ...that is the location of your Universal Build.


How to include "non sourcecode" files in your project (PNG, PLIST, XML, etc)

  1. Do everything above, check it works
  2. Create a new Run Script phase that comes AFTER THE FIRST ONE (copy/paste the code below)
  3. Create a new Target in Xcode, of type "bundle"
  4. In your MAIN PROJECT, in "Build Phases", add the new bundle as something it "depends on" (top section, hit the plus button, scroll to bottom, find the ".bundle" file in your Products)
  5. In your NEW BUNDLE TARGET, in "Build Phases", add a "Copy Bundle Resources" section, and drag/drop all the PNG files etc into it

Script to auto-copy the built bundle(s) into same folder as your FAT static library:

echo "RunScript2:"
echo "Autocopying any bundles into the 'universal' output folder created by RunScript1"
CREATING_UNIVERSAL_DIR=${SYMROOT}/${CONFIGURATION}-universal
cp -r "${BUILT_PRODUCTS_DIR}/"*.bundle "${CREATING_UNIVERSAL_DIR}"

How to call javascript from a href?

The proper way to invoke javascript code when clicking a link would be to add an onclick handler:

<a href="#" onclick="myFunction()">LinkText</a>

Although an even "more proper" way would be to get it out of the html all together and add the handler with another javascript when the dom is loaded.

What is the garbage collector in Java?

As objects are dynamically allocated by the new operator, you can ask how these objects are destroyed and how busy memory is freed. In other languages such as C++, you need to free manually allocated objects dynamically by the delete operator. Java has a different approach; it automatically handles deallocation. The technique is known as Garbage Collection.

It works like this: when there are no references to an object, it is assumed that this object is no longer needed and you can retrieve the memory occupied by the object. It is not necessary to explicitly destroy objects as in C++. Garbage collection occurs sporadically during program execution; It does not simply happen because there are one or more objects that are no longer used. In addition, several Java runtime implementations have different approaches to garbage collection, but most programmers do not have to worry about this when writing programs.

The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

- What is @objc inference? What is going on?

In Swift 3, the compiler infers @objc in a number of places so you wouldn't have to. In other words, it makes sure to add @objc for you!

In Swift 4, the compiler no longer does this (as much). You now must add @objc explicitly.

By default, if you have a pre-Swift 4 project, you will get warnings about this. In a Swift 4 project, you will get build errors. This is controlled via the SWIFT_SWIFT3_OBJC_INFERENCE build setting. In a pre-Swift 4 project this is set to On. I would recommend to set this to Default (or Off), which is now the default option on a new project.

It will take some time to convert everything, but since it's the default for Swift 4, it's worth doing it.

- How do I stop the compiler warnings/errors?

There are two ways to go about converting your code so the compiler doesn't complain.

One is to use @objc on each function or variable that needs to be exposed to the Objective-C runtime:

@objc func foo() {

}

The other is to use @objcMembers by a Class declaration. This makes sure to automatically add @objc to ALL the functions and variables in the class. This is the easy way, but it has a cost, for example, it can increase the size of your application by exposing functions that did not need to be exposed.

@objcMembers class Test {

}

- What is @objc and why is it necessary?

If you introduce new methods or variables to a Swift class, marking them as @objc exposes them to the Objective-C runtime. This is necessary when you have Objective-C code that uses your Swift class, or, if you are using Objective-C-type features like Selectors. For example, the target-action pattern: button.addTarget(self, action:#selector(didPressButton), for:.touchUpInside)

- Why would I not mark everything @objc?

There are negatives that come with marking something as @objc:

  • Increased application binary size
  • No function overloading

Please keep in mind that this is a very high-level summary and that it is more complicated than I wrote. I would recommend reading the actual proposal for more information.

Sources:

How do I diff the same file between two different commits on the same branch?

You can also compare two different files in two different revisions, like this:

git diff <revision_1>:<file_1> <revision_2>:<file_2>

What's the difference between Docker Compose vs. Dockerfile

docker-compose exists to keep you having to write a ton of commands you would have to with docker-cli.

docker-compose also makes it easy to startup multiple containers at the same time and automatically connect them together with some form of networking.

The purpose of docker-compose is to function as docker cli but to issue multiple commands much more quickly.

To make use of docker-compose, you need to encode the commands you were running before into a docker-compose.yml file.

You are not just going to copy paste them into the yaml file, there is a special syntax.

Once created, you have to feed it to the docker-compose cli and it will be up to the cli to parse the file and create all the different containers with the correct configuration we specify.

So you will have separate containers, let's say, one is redis-server and the second one is node-app, and you want that created using the Dockerfile in your current directory.

Additionally, after making that container, you would map some port from the container to the local machine to access everything running inside of it.

So for your docker-compose.yml file, you would want to start the first line like so:

version: '3'

That tells Docker the version of docker-compose you want to use. After that, you have to add:

version: '3'
services: 
  redis-server: 
    image: 'redis'
  node-app:
    build: .

Please notice the indentation, very important. Also, notice for one service I am grabbing an image, but for another service I am telling docker-compose to look inside the current directory to build the image that will be used for the second container.

Then you want to specify all the different ports that you want open on this container.

version: '3'
services: 
  redis-server: 
    image: 'redis'
  node-app:
    build: .
    ports:
      -

Please notice the dash, a dash in a yaml file is how we specify an array. In this example, I am mapping 8081 on my local machine to 8081 on the container like so:

version: '3'
services: 
  redis-server: 
    image: 'redis'
  node-app:
    build: .
    ports:
      - "8081:8081"

So the first port is your local machine, and the other is the port on the container, you could also distinguish between the two to avoid confusion like so:

version: '3'
services:
  redis-server:
    image: 'redis'
  node-app:
    build: .
    ports:
      - "4001:8081"

By developing your docker-compose.yml file like this, it will create these containers on essentially the same network and they will have free access to communicate with each other any way they please and exchange as much information as they want.

When the two containers are created using docker-compose, we do not need any port declarations.

Now in my example, we need to do some code configuration in the Nodejs app that looks something like this:

const express = require('express');
const redis = require('redis');

const app = express();
const client = redis.createClient({
  host: 'redis-server'
});

I use this example above to make you aware that there may be some specific configuration you would have to do in addition to the docker-compose.yml file that may be specific to your project.

Now, if you ever find yourself working with a Nodejs app and redis, you want to ensure you are aware of the default port Nodejs uses, so I will add this:

const express = require('express');
const redis = require('redis');

const app = express();
const client = redis.createClient({
  host: 'redis-server',
  port: 6379
});

So Docker is going to see that the Node app is looking for redis-server and redirect that connection over to this running container.

The whole time, the Dockerfile only contains this:

FROM node:alpine

WORKDIR '/app'

COPY /package.json ./
RUN npm install
COPY . .

CMD ["npm", "start"]

So, whereas before you would have to run docker run myimage to create an instance of all the containers or services inside the file, you can instead run docker-compose up and you don't have to specify an image because Docker will look in the current working directory and look for a docker-compose.yml file inside.

Before docker-compose.yml, we had to deal with two separate commands of docker build . and docker run myimage, but in the docker-compose world, if you want to rebuild your images, you write docker-compose up --build. That tells Docker to start up the containers again but rebuild it to get the latest changes.

So docker-compose makes it easier for working with multiple containers. The next time you need to start this group of containers in the background, you can do docker-compose up -d; and to stop them, you can do docker-compose down.

Android camera android.hardware.Camera deprecated

 if ( getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {

          CameraManager cameraManager=(CameraManager) getActivity().getSystemService(Context.CAMERA_SERVICE);


           try {
               String cameraId = cameraManager.getCameraIdList()[0];
               cameraManager.setTorchMode(cameraId,true);
           } catch (CameraAccessException e) {
               e.printStackTrace();
           }


 }

How to fire an event when v-model changes?

Vue2: if you only want to detect change on input blur (e.g. after press enter or click somewhere else) do (more info here)

<input @change="foo" v-model... >

If you wanna detect single character changes (during user typing) use

<input @keydown="foo" v-model... >

You can also use @keyup and @input events. If you wanna to pass additional parameters use in template e.g. @keyDown="foo($event, param1, param2)". Comparision below (editable version here)

_x000D_
_x000D_
new Vue({_x000D_
  el: "#app",_x000D_
  data: { _x000D_
    keyDown: { key:null, val: null,  model: null, modelCopy: null },_x000D_
    keyUp: { key:null, val: null,  model: null, modelCopy: null },_x000D_
    change: { val: null,  model: null, modelCopy: null },_x000D_
    input: { val: null,  model: null, modelCopy: null },_x000D_
    _x000D_
    _x000D_
  },_x000D_
  methods: {_x000D_
  _x000D_
    keyDownFun: function(event){                   // type of event: KeyboardEvent   _x000D_
      console.log(event);  _x000D_
      this.keyDown.key = event.key;                // or event.keyCode_x000D_
      this.keyDown.val = event.target.value;       // html current input value_x000D_
      this.keyDown.modelCopy = this.keyDown.model; // copy of model value at the moment on event handling_x000D_
    },_x000D_
    _x000D_
    keyUpFun: function(event){                     // type of event: KeyboardEvent_x000D_
      console.log(event);  _x000D_
      this.keyUp.key = event.key;                  // or event.keyCode_x000D_
      this.keyUp.val = event.target.value;         // html current input value_x000D_
      this.keyUp.modelCopy = this.keyUp.model;     // copy of model value at the moment on event handling_x000D_
    },_x000D_
    _x000D_
    changeFun: function(event) {                   // type of event: Event_x000D_
      console.log(event);_x000D_
      this.change.val = event.target.value;        // html current input value_x000D_
      this.change.modelCopy = this.change.model;   // copy of model value at the moment on event handling_x000D_
    },_x000D_
    _x000D_
    inputFun: function(event) {                    // type of event: Event_x000D_
      console.log(event);_x000D_
      this.input.val = event.target.value;         // html current input value_x000D_
      this.input.modelCopy = this.input.model;     // copy of model value at the moment on event handling_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
div {_x000D_
  margin-top: 20px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
_x000D_
Type in fields below (to see events details open browser console)_x000D_
_x000D_
<div id="app">_x000D_
  <div><input type="text" @keyDown="keyDownFun" v-model="keyDown.model"><br> @keyDown (note: model is different than value and modelCopy)<br> key:{{keyDown.key}}<br> value: {{ keyDown.val }}<br> modelCopy: {{keyDown.modelCopy}}<br> model: {{keyDown.model}}</div>_x000D_
  _x000D_
  <div><input type="text" @keyUp="keyUpFun" v-model="keyUp.model"><br> @keyUp (note: model change value before event occure) <br> key:{{keyUp.key}}<br> value: {{ keyUp.val }}<br> modelCopy: {{keyUp.modelCopy}}<br> model: {{keyUp.model}}</div>_x000D_
  _x000D_
  <div><input type="text" @change="changeFun" v-model="change.model"><br> @change (occures on enter key or focus change (tab, outside mouse click) etc.)<br> value: {{ change.val }}<br> modelCopy: {{change.modelCopy}}<br> model: {{change.model}}</div>_x000D_
  _x000D_
  <div><input type="text" @input="inputFun" v-model="input.model"><br> @input<br> value: {{ input.val }}<br> modelCopy: {{input.modelCopy}}<br> model: {{input.model}}</div>_x000D_
     _x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get file creation date/time in Bash/Debian?

Creation date/time is normally not stored. So no, you can't.

class method generates "TypeError: ... got multiple values for keyword argument ..."

Thanks for the instructive posts. I'd just like to keep a note that if you're getting "TypeError: foodo() got multiple values for keyword argument 'thing'", it may also be that you're mistakenly passing the 'self' as a parameter when calling the function (probably because you copied the line from the class declaration - it's a common error when one's in a hurry).

Android Studio build fails with "Task '' not found in root project 'MyProject'."

Apparently this issue caused by Android Studio on the various situation but the reason is build error When importing an existing project into android studio.

In my case, I've imported my exist project where I was supposed to install few build tools then finally build configuration was done with error. In this case, just do the following things

  1. Close the current project
  2. File>New>Import Project (Don't use the open recent project)

    Note: I'm sure this kind of error is not on source code when this happened on Import project.

Basic Python client socket example

It looks like your client is trying to connect to a non-existent server. In a shell window, run:

$ nc -l 5000

before running your Python code. It will act as a server listening on port 5000 for you to connect to. Then you can play with typing into your Python window and seeing it appear in the other terminal and vice versa.

How can I declare optional function parameters in JavaScript?

Update

With ES6, this is possible in exactly the manner you have described; a detailed description can be found in the documentation.

Old answer

Default parameters in JavaScript can be implemented in mainly two ways:

function myfunc(a, b)
{
    // use this if you specifically want to know if b was passed
    if (b === undefined) {
        // b was not passed
    }
    // use this if you know that a truthy value comparison will be enough
    if (b) {
        // b was passed and has truthy value
    } else {
        // b was not passed or has falsy value
    }
    // use this to set b to a default value (using truthy comparison)
    b = b || "default value";
}

The expression b || "default value" evaluates the value AND existence of b and returns the value of "default value" if b either doesn't exist or is falsy.

Alternative declaration:

function myfunc(a)
{
    var b;

    // use this to determine whether b was passed or not
    if (arguments.length == 1) {
        // b was not passed
    } else {
        b = arguments[1]; // take second argument
    }
}

The special "array" arguments is available inside the function; it contains all the arguments, starting from index 0 to N - 1 (where N is the number of arguments passed).

This is typically used to support an unknown number of optional parameters (of the same type); however, stating the expected arguments is preferred!

Further considerations

Although undefined is not writable since ES5, some browsers are known to not enforce this. There are two alternatives you could use if you're worried about this:

b === void 0;
typeof b === 'undefined'; // also works for undeclared variables

Full width layout with twitter bootstrap

*{
   margin:0
   padding:0
}

make sure your container's width:%100

How to print exact sql query in zend framework ?

This one's from Zend Framework documentation (ie. UPDATE):

echo $update->getSqlString();

(Bonus) I use this one in my own model files:

echo $this->tableGateway->getSql()->getSqlstringForSqlObject($select);

Have a nice day :)

javascript node.js next()

It's basically like a callback that express.js use after a certain part of the code is executed and done, you can use it to make sure that part of code is done and what you wanna do next thing, but always be mindful you only can do one res.send in your each REST block...

So you can do something like this as a simple next() example:

app.get("/", (req, res, next) => {
  console.log("req:", req, "res:", res);
  res.send(["data": "whatever"]);
  next();
},(req, res) =>
  console.log("it's all done!");
);

It's also very useful when you'd like to have a middleware in your app...

To load the middleware function, call app.use(), specifying the middleware function. For example, the following code loads the myLogger middleware function before the route to the root path (/).

var express = require('express');
var app = express();

var myLogger = function (req, res, next) {
  console.log('LOGGED');
  next();
}

app.use(myLogger);

app.get('/', function (req, res) {
  res.send('Hello World!');
})

app.listen(3000);

How to draw a filled triangle in android canvas?

You probably need to do something like :

Paint red = new Paint();

red.setColor(android.graphics.Color.RED);
red.setStyle(Paint.Style.FILL);

And use this color for your path, instead of your ARGB. Make sure the last point of your path ends on the first one, it makes sense also.

Tell me if it works please !

How to round up a number in Javascript?

I've been using @AndrewMarshall answer for a long time, but found some edge cases. The following tests doesn't pass:

equals(roundUp(9.69545, 4), 9.6955);
equals(roundUp(37.760000000000005, 4), 37.76);
equals(roundUp(5.83333333, 4), 5.8333);

Here is what I now use to have round up behave correctly:

// Closure
(function() {
  /**
   * Decimal adjustment of a number.
   *
   * @param {String}  type  The type of adjustment.
   * @param {Number}  value The number.
   * @param {Integer} exp   The exponent (the 10 logarithm of the adjustment base).
   * @returns {Number} The adjusted value.
   */
  function decimalAdjust(type, value, exp) {
    // If the exp is undefined or zero...
    if (typeof exp === 'undefined' || +exp === 0) {
      return Math[type](value);
    }
    value = +value;
    exp = +exp;
    // If the value is not a number or the exp is not an integer...
    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
      return NaN;
    }
    // If the value is negative...
    if (value < 0) {
      return -decimalAdjust(type, -value, exp);
    }
    // Shift
    value = value.toString().split('e');
    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
    // Shift back
    value = value.toString().split('e');
    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
  }

  // Decimal round
  if (!Math.round10) {
    Math.round10 = function(value, exp) {
      return decimalAdjust('round', value, exp);
    };
  }
  // Decimal floor
  if (!Math.floor10) {
    Math.floor10 = function(value, exp) {
      return decimalAdjust('floor', value, exp);
    };
  }
  // Decimal ceil
  if (!Math.ceil10) {
    Math.ceil10 = function(value, exp) {
      return decimalAdjust('ceil', value, exp);
    };
  }
})();

// Round
Math.round10(55.55, -1);   // 55.6
Math.round10(55.549, -1);  // 55.5
Math.round10(55, 1);       // 60
Math.round10(54.9, 1);     // 50
Math.round10(-55.55, -1);  // -55.5
Math.round10(-55.551, -1); // -55.6
Math.round10(-55, 1);      // -50
Math.round10(-55.1, 1);    // -60
Math.round10(1.005, -2);   // 1.01 -- compare this with Math.round(1.005*100)/100 above
Math.round10(-1.005, -2);  // -1.01
// Floor
Math.floor10(55.59, -1);   // 55.5
Math.floor10(59, 1);       // 50
Math.floor10(-55.51, -1);  // -55.6
Math.floor10(-51, 1);      // -60
// Ceil
Math.ceil10(55.51, -1);    // 55.6
Math.ceil10(51, 1);        // 60
Math.ceil10(-55.59, -1);   // -55.5
Math.ceil10(-59, 1);       // -50

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round

Typing Greek letters etc. in Python plots

You need to make the strings raw and use latex:

fig.gca().set_ylabel(r'$\lambda$')

As of matplotlib 2.0 the default font supports most western alphabets and can simple do

ax.set_xlabel('?')

with unicode.

angular 2 ngIf and CSS transition/animation

In my case I declared the animation on the wrong component by mistake.

app.component.html

  <app-order-details *ngIf="orderDetails" [@fadeInOut] [orderDetails]="orderDetails">
  </app-order-details>

The animation needs to be declared on the component where the element is used in (appComponent.ts). I was declaring the animation on OrderDetailsComponent.ts instead.

Hopefully it will help someone making the same mistake

Convert Bitmap to File

Hope it will help u:

//create a file to write bitmap data
File f = new File(context.getCacheDir(), filename);
f.createNewFile();

//Convert bitmap to byte array
Bitmap bitmap = your bitmap;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();

//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();

Ifelse statement in R with multiple conditions

Very simple use of any

df <- <your structure>

df$Den <- apply(df,1,function(i) {ifelse(any(is.na(i)) | any(i != 1), 0, 1)})

Cannot create Maven Project in eclipse

Same problem here, solved.

I will explain the problem and the solution, to help others.

My software is:

Windows 7
Eclipse 4.4.1 (Luna SR1)
m2e 1.5.0.20140606-0033
    (from eclipse repository: http://download.eclipse.org/releases/luna)

And I'm accessing internet through a proxy.

My problem was the same:

  • Just installed m2e, went to menu: File > New > Other > Maven > Maven project > Next > Next.
  • Selected "Catalog: All catalogs" and "Filter: maven-archetype-quickstart", then clicked on the search result, then on button Next.
  • Then entered "Group Id: test_gr" and "Artifact Id: test_art", then clicked on Finish button.
  • Got the "Could not resolve archetype..." error.

After a lot of try-and-error, and reading a lot of pages, I've finally found a solution to fix it. Some important points of the solution:

  • It uses the default (embedded) Maven installation (3.2.1/1.5.0.20140605-2032) that comes with m2e.
  • So no aditional (external) Maven installation is required.
  • No special m2e config is required.

The solution is:

  • Open eclipse.
  • Restore m2e original preferences (if you changed any of them): Click on menu: Window > Preferences > Maven > Restore defaults. Do the same for all tree items under "Maven" item: Archetypes, Discovery, Errors/Warnings, Instalation, Lifecycle Mappings, Templates, User Interface, User Settings. Click on "OK" button.
  • Copy (for example to a notepad window) the path of the user settings file. To see the path, click again on menu: Window > Preferences > Maven > User Settings, and the path is at the "User settings" textbox. You will have to write the path manually, since it is not posible to copy-and-paste. After coping the path to the notepad, don't close the Preferences window.
  • At the Preferences window that is already open, click on the "open file" link. Close the Preferences window, and you will see the "settings.xml" file already openned in a Eclipse editor.
  • The editor will have 2 tabs at the bottom: "Design" and "Source". Click on "Source" tab. You will see all the source code (xml).
  • Delete all the source code: Click on the code, press control+a, press "del".
  • Copy the following code to the editor (and customize the uppercased values):
<settings>
  <proxies>
   <proxy>
      <active>true</active>
      <protocol>http</protocol>
      <host>YOUR.PROXY.IP.OR.NAME</host>
      <port>YOUR PROXY PORT</port>
      <username>YOUR PROXY USERNAME (OR EMPTY IF NOT REQUIRED)</username>
      <password>YOUR PROXY PASSWORD (OR EMPTY IF NOT REQUIRED)</password>
      <nonProxyHosts>YOUR PROXY EXCLUSION HOST LIST (OR EMPTY)</nonProxyHosts>
    </proxy>
  </proxies>
</settings>
  • Save the file: control+s.
  • Exit Eclipse: Menu File > Exit.
  • Open in a Windows Explorer the path you copied (without the filename, just the path of directories).
  • You will probaly see the xml file ("settings.xml") and a directoy ("repository"). Remove the directoy ("repository"): Right click > Delete > Yes.
  • Start Eclipse.
  • Now you will be able to create a maven project: File > New > Other > Maven > Maven project > Next > Next, select "Catalog: All catalogs" and "Filter: maven-archetype-quickstart", click on the search result, then on button Next, enter "Group Id: test_gr" and "Artifact Id: test_art", click on Finish button.

Finally, I would like to give a suggestion to m2e developers, to make config easier. After installing m2e from the internet (from a repository), m2e should check if Eclipse is using a proxy (Preferences > General > Network Connections). If Eclipse is using a proxy, the m2e should show a dialog to the user:

m2e has detected that Eclipse is using a proxy to access to the internet.
Would you like me to create a User settings file (settings.xml) for the embedded 
Maven software?

[ Yes ] [ No ]

If the user clicks on Yes, then m2e should create automatically the "settings.xml" file by copying proxy values from Eclipse preferences.

Pointer vs. Reference

My rule of thumb is:

Use pointers if you want to do pointer arithmetic with them (e.g. incrementing the pointer address to step through an array) or if you ever have to pass a NULL-pointer.

Use references otherwise.

Apply .gitignore on an existing repository already tracking large number of files

Here is one way to “untrack” any files that are would otherwise be ignored under the current set of exclude patterns:

(GIT_INDEX_FILE=some-non-existent-file \
git ls-files --exclude-standard --others --directory --ignored -z) |
xargs -0 git rm --cached -r --ignore-unmatch --

This leaves the files in your working directory but removes them from the index.

The trick used here is to provide a non-existent index file to git ls-files so that it thinks there are no tracked files. The shell code above asks for all the files that would be ignored if the index were empty and then removes them from the actual index with git rm.

After the files have been “untracked”, use git status to verify that nothing important was removed (if so adjust your exclude patterns and use git reset -- path to restore the removed index entry). Then make a new commit that leaves out the “crud”.

The “crud” will still be in any old commits. You can use git filter-branch to produce clean versions of the old commits if you really need a clean history (n.b. using git filter-branch will “rewrite history”, so it should not be undertaken lightly if you have any collaborators that have pulled any of your historical commits after the “crud” was first introduced).

JavaScript string and number conversion

Simplest is when you want to make a integer a string do

var a,b, c;
a = 1;
b = a.toString(); // This will give you string

Now, from the variable b which is of type string we can get the integer

c = b *1; //This will give you integer value of number :-)

If you want to check above is a number. If you are not sure if b contains integer then you can use

if(isNaN(c*1)) {
  //NOt a number
}
else //number

How to detect Windows 64-bit platform with .NET?

All fine, but this should also work from env:

PROCESSOR_ARCHITECTURE=x86

..

PROCESSOR_ARCHITECTURE=AMD64

Too easy, maybe ;-)

Java Timer vs ExecutorService?

Here's some more good practices around Timer use:

http://tech.puredanger.com/2008/09/22/timer-rules/

In general, I'd use Timer for quick and dirty stuff and Executor for more robust usage.

Detect whether there is an Internet connection available on Android

Probably I have found myself:

ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
return connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting();

How can I get the Google cache age of any URL or web page?

its too simple, you can just type "cache:" before the URL of the page. for example if you want to check the last webcache of this page simply type on URL bar cache:http://stackoverflow.com/questions/4560400/how-can-i-get-the-google-cache-age-of-any-url-or-web-page

this will show you the last webcache of the page.see here:

enter image description here

But remember, the caching of a webpage will only show if the page is already indexed on search engine(Google). for this you need to check the meta robot tag of that page.

Hashing a string with Sha256

Encoding.Unicode is Microsoft's misleading name for UTF-16 (a double-wide encoding, used in the Windows world for historical reasons but not used by anyone else). http://msdn.microsoft.com/en-us/library/system.text.encoding.unicode.aspx

If you inspect your bytes array, you'll see that every second byte is 0x00 (because of the double-wide encoding).

You should be using Encoding.UTF8.GetBytes instead.

But also, you will see different results depending on whether or not you consider the terminating '\0' byte to be part of the data you're hashing. Hashing the two bytes "Hi" will give a different result from hashing the three bytes "Hi". You'll have to decide which you want to do. (Presumably you want to do whichever one your friend's PHP code is doing.)

For ASCII text, Encoding.UTF8 will definitely be suitable. If you're aiming for perfect compatibility with your friend's code, even on non-ASCII inputs, you'd better try a few test cases with non-ASCII characters such as é and ? and see whether your results still match up. If not, you'll have to figure out what encoding your friend is really using; it might be one of the 8-bit "code pages" that used to be popular before the invention of Unicode. (Again, I think Windows is the main reason that anyone still needs to worry about "code pages".)

what is right way to do API call in react js?

This discussion has been for a while and @Alexander T.'s answer provided a good guide to follow for newer of React like me. And I'm gonna share some additional know-hows about calling the same API multiple times to refresh the component, I think it's probably a common problem that newbie may face at the beginning.

componentWillReceiveProps(nextProps), from official documentation :

If you need to update the state in response to prop changes (for example, to reset it), you may compare this.props and nextProps and perform state transitions using this.setState() in this method.

We could conclude that here is the place we handle props from the parent component, have API calls, and update state.

Base on @Alexander T.'s example:

export default class UserList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {person: []};
  }

  componentDidMount() {
   //For our first load. 
   this.UserList(this.props.group); //maybe something like "groupOne"
  }

  componentWillReceiveProps(nextProps) {
    // Assuming parameter comes from url.
    // let group = window.location.toString().split("/")[*indexParameterLocated*];
    // this.UserList(group);

    // Assuming parameter comes from props that from parent component.
    let group = nextProps.group; // Maybe something like "groupTwo" 
    this.UserList(group);
  }

  UserList(group) {
    $.getJSON('https://randomuser.me/api/' + group)
      .then(({ results }) => this.setState({ person: results }));
  }

  render() {
    return (...)
  }
}

Update

componentWillReceiveProps() would be deprecated.

Here are only some methods (all of them in Doc) in the life cycle which I think would be related to deploying API in general case: enter image description here

By referring the diagram above:

  • Deploy API in componentDidMount()

    The proper scenario to have API call here is that the content (from the response of API) of this component will be static, componentDidMount() only fire once while the component is mounting, even new props are passed from parent component or have actions to lead re-rendering.
    The component do check difference to re-render but not re-mount.
    Quote from doc:

If you need to load data from a remote endpoint, this is a good place to instantiate the network request.


  • Deploy API in static getDerivedStateFromProps(nextProps, prevState)

We should notice that there are two kinds of component updating, setState() in current component would not lead this method to trigger, but re-rendering or new props from parent component do. We could found out that this method also fires while mounting.

This is a proper place to deploy API if we want to use the current component like a template, and the new parameters for API are props coming from parent component.
We receive a different response from API and return a new state here to change the content of this component.

For example:
We have a dropdown list for different Cars in the parent component, this component needs to show the details of the selected one.


  • Deploy API in componentDidUpdate(prevProps, prevState)

Differ from static getDerivedStateFromProps(), this method is invoked immediately after every rendering except the initial rendering. We could have API calling and render difference in one component.

Extend the previous example:
The component to show Car's details may contain a list of series of this car, if we want to check the 2013 production one, we may click or select or ... the list item to lead a first setState() to reflect this behavior (such as highlighting the list item) in this component, and in the following componentDidUpdate() we send our request with new parameters (state). After getting the response, we setState() again for rendering the different content of the Car details. To prevent the following componentDidUpdate() from causing the infinity loop, we need to compare the state by utilizing prevState at the beginning of this method to decide if we send the API and render the new content.

This method really could be utilized just like static getDerivedStateFromProps() with props, but need to handle the changes of props by utilizing prevProps. And we need to cooperate with componentDidMount() to handle the initial API call.

Quote from doc:

... This is also a good place to do network requests as long as you compare the current props to previous props ...

How to find the first and second maximum number?

OK I found it.

=LARGE($E$4:$E$9;A12)

=large(array, k)

Array Required. The array or range of data for which you want to determine the k-th largest value.

K Required. The position (from the largest) in the array or cell range of data to return.

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

If you are using Spring as Back-End server and especially using Spring Security then i found a solution by putting http.cors(); in the configure method. The method looks like that:

protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests() // authorize
                .anyRequest().authenticated() // all requests are authenticated
                .and()
                .httpBasic();

        http.cors();
}

How to open port in Linux

The following configs works on Cent OS 6 or earlier

As stated above first have to disable selinux.

Step 1 nano /etc/sysconfig/selinux

Make sure the file has this configurations

SELINUX=disabled

SELINUXTYPE=targeted

Then restart the system

Step 2

iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT

Step 3

sudo service iptables save

For Cent OS 7

step 1

firewall-cmd --zone=public --permanent --add-port=8080/tcp

Step 2

firewall-cmd --reload

How do I express "if value is not empty" in the VBA language?

Why not just use the built-in Format() function?

Dim vTest As Variant
vTest = Empty ' or vTest = null or vTest = ""

If Format(vTest) = vbNullString Then
    doSomethingWhenEmpty() 
Else
   doSomethingElse() 
End If

Format() will catch empty variants as well as null ones and transforms them in strings. I use it for things like null/empty validations and to check if an item has been selected in a combobox.

How to use mongoose findOne

Found the problem, need to use function(err,obj) instead:

Auth.findOne({nick: 'noname'}, function(err,obj) { console.log(obj); });

How do I merge my local uncommitted changes into another Git branch?

If it were about committed changes, you should have a look at git-rebase, but as pointed out in comment by VonC, as you're talking about local changes, git-stash would certainly be the good way to do this.

jquery toggle slide from left to right and back

Sliding from the right:

$('#example').animate({width:'toggle'},350);

Sliding to the left:

$('#example').toggle({ direction: "left" }, 1000);

Read specific columns from a csv file with csv module?

SAMPLE.CSV
a, 1, +
b, 2, -
c, 3, *
d, 4, /
column_names = ["Letter", "Number", "Symbol"]
df = pd.read_csv("sample.csv", names=column_names)
print(df)
OUTPUT
  Letter  Number Symbol
0      a       1      +
1      b       2      -
2      c       3      *
3      d       4      /

letters = df.Letter.to_list()
print(letters)
OUTPUT
['a', 'b', 'c', 'd']

How to get value by key from JObject?

You can also get the value of an item in the jObject like this:

JToken value;
if (json.TryGetValue(key, out value))
{
   DoSomething(value);
}

Applying a single font to an entire website with CSS

in Bootstrap, web inspector says the Headings are set to 'inherit'

all i needed to set my page to the new font was

div, p {font-family: Algerian}

that's in .scss

The Import android.support.v7 cannot be resolved

In my case, the auto-generated project appcompat_v7 was closed. So just open up that project in Package Explorer.

Hope this help.

Can I access a form in the controller?

This answer is a little late, but I stumbled upon a solution that makes everything a LOT easier.

You can actually assign the form name directly to your controller if you're using the controllerAs syntax and then reference it from your "this" variable. Here's how I did it in my code:

I configured the controller via ui-router (but you can do it however you want, even in the HTML directly with something like <div ng-controller="someController as myCtrl">) This is what it might look like in a ui-router configuration:

views: {
            "": {
                templateUrl: "someTemplate.html",
                controller: "someController",
                controllerAs: "myCtrl"
            }
       }

and then in the HTML, you just set the form name as the "controllerAs"."name" like so:

<ng-form name="myCtrl.someForm">
    <!-- example form code here -->
    <input name="firstName" ng-model="myCtrl.user.firstName" required>
</ng-form>

now inside your controller you can very simply do this:

angular
.module("something")
.controller("someController",
    [
       "$scope",
        function ($scope) {
            var vm = this;
            if(vm.someForm.$valid){
              // do something
            }
    }]);

How can I add a space in between two outputs?

+"\n" + can be added in print command to display the code block after it in next line

E.g. System.out.println ("a" + "\n" + "b") outputs a in first line and b in second line.

document.getElementByID is not a function

It worked like this for me:

document.getElementById("theElementID").setAttribute("src", source);
document.getElementById("task-text").innerHTML = "";

Change the

getElementById("theElementID")

for your element locator (name, css, xpath...)

Listen to port via a Java socket

What do you actually want to achieve? What your code does is it tries to connect to a server located at 192.168.1.104:4000. Is this the address of a server that sends the messages (because this looks like a client-side code)? If I run fake server locally:

$ nc -l 4000

...and change socket address to localhost:4000, it will work and try to read something from nc-created server.

What you probably want is to create a ServerSocket and listen on it:

ServerSocket serverSocket = new ServerSocket(4000);
Socket socket = serverSocket.accept();

The second line will block until some other piece of software connects to your machine on port 4000. Then you can read from the returned socket. Look at this tutorial, this is actually a very broad topic (threading, protocols...)

What are App Domains in Facebook Apps?

it stands for your website where your app is running on. like you have made an app www.xyz.pqr then you will type this www.xyz.pqr in App domain the site where your app is running on should be secure and valid

How can I conditionally import an ES6 module?

2020 Update

You can now call the import keyword as a function (i.e. import()) to load a module at runtime.

Example:

const mymodule = await import(modulename);

or:

import(modulename)
    .then(mymodule => /* ... */);

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Dynamic_Imports

Root user/sudo equivalent in Cygwin?

Being unhappy with the available solution, I adopted nu774's script to add security and make it easier to setup and use. The project is available on Github

To use it, just download cygwin-sudo.py and run it via python3 cygwin-sudo.py **yourcommand**.

You can set up an alias for convenience:

alias sudo="python3 /path-to-cygwin-sudo/cygwin-sudo.py"

Control flow in T-SQL SP using IF..ELSE IF - are there other ways?

Also you can try to formulate your answer in the form of a SELECT CASE Statement. You can then later create simple if then's that use your results if needed as you have narrowed down the possibilities.

SELECT @Result =   
CASE @inputParam   
WHEN 1 THEN 1   
WHEN 2 THEN 2   
WHEN 3 THEN 1   
ELSE 4   
END  

IF @Result = 1   
BEGIN  
...  
END  

IF @Result = 2   
BEGIN   
....  
END  

IF @Result = 4   
BEGIN   
//Error handling code   
END   

How to run a Maven project from Eclipse?

(Alt + Shift + X) , then M to Run Maven Build. You will need to specify the Maven goals you want on Run -> Run Configurations

Convert DataTable to CSV stream

Update 1

I have modified it to use StreamWriter instead, add an option to check if you need column headers in your output.

public static bool DataTableToCSV(DataTable dtSource, StreamWriter writer, bool includeHeader)
{
    if (dtSource == null || writer == null) return false;

    if (includeHeader)
    {
        string[] columnNames = dtSource.Columns.Cast<DataColumn>().Select(column => "\"" + column.ColumnName.Replace("\"", "\"\"") + "\"").ToArray<string>();
        writer.WriteLine(String.Join(",", columnNames));
        writer.Flush();
    }

    foreach (DataRow row in dtSource.Rows)
    {
        string[] fields = row.ItemArray.Select(field => "\"" + field.ToString().Replace("\"", "\"\"") + "\"").ToArray<string>();
        writer.WriteLine(String.Join(",", fields));
        writer.Flush();
    }

    return true;
}

As you can see, you can choose the output by initial StreamWriter, if you use StreamWriter(Stream BaseStream), you can write csv into MemeryStream, FileStream, etc.

Origin

I have an easy datatable to csv function, it serves me well:

    public static void DataTableToCsv(DataTable dt, string csvFile)
    {
        StringBuilder sb = new StringBuilder();

        var columnNames = dt.Columns.Cast<DataColumn>().Select(column => "\"" + column.ColumnName.Replace("\"", "\"\"") + "\"").ToArray();
        sb.AppendLine(string.Join(",", columnNames));

        foreach (DataRow row in dt.Rows)
        {
            var fields = row.ItemArray.Select(field => "\"" + field.ToString().Replace("\"", "\"\"") + "\"").ToArray();
            sb.AppendLine(string.Join(",", fields));
        }

        File.WriteAllText(csvFile, sb.ToString(), Encoding.Default);
    }

IFRAMEs and the Safari on the iPad, how can the user scroll the content?

Based on this article, I have put together the following snippet that provides some very basic functionality:

<div id = "container"></div>
<script>
function setPDFHeight(){ 
        $("#pdfObject")[0].height = $("#pdfObject")[0].offsetHeight;   
}   
$('#container').append('<div align="center" style="width: 100%; height:100%; overflow: auto !important; -webkit-overflow-scrolling: touch !important;">\
      <object id="pdfObject" width="100%" height="1000000000000" align="center" data="content/lessons/12/t.pdf" type="application/pdf" onload="setPDFHeight()">You have no plugin installed</object></div>');  
</script>

Obviously it is far from perfect (given that it practically expands your page height to infinity), but it's the only viable workaround I've found so far.

How to get the latest tag name in current branch in Git?

If you want to find the last tag that was applied on a specific branch you can try the following:

git describe --tag $(git rev-parse --verify refs/remotes/origin/"branch_name")

Automatically open default email client and pre-populate content

Try this: It will open the default mail directly.

<a href="mailto:[email protected]"><img src="ICON2.png"></a>

Java and unlimited decimal places?

I believe that you are looking for the java.lang.BigDecimal class.

CONVERT Image url to Base64

Here's the Typescript version of Abubakar Ahmad's answer

function imageTo64(
  url: string, 
  callback: (path64: string | ArrayBuffer) => void
): void {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', url);
  xhr.responseType = 'blob';
  xhr.send();

  xhr.onload = (): void => {
    const reader = new FileReader();
    reader.readAsDataURL(xhr.response);
    reader.onloadend = (): void => callback(reader.result);
  }
}

How do I generate a constructor from class fields using Visual Studio (and/or ReSharper)?

You could write a macro to do this -- you would use Visual Studio's parser to retrieve information about the class's members.

I wrote a similar macro. (I'll share the code below). The macro I wrote is for copying forward all of the constructors in a base class when you inherit from it (useful for classes like Exception that have lots of overloads on the ctor).

Here's my macro (again, it doesn't solve your problem, but you can probably modify to do what you want)


Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE100
Imports System.Diagnostics

Public Module ConstructorEditor
    Public Sub StubConstructors()
        'adds stubs for all of the constructors in the current class's base class
        Dim selection As TextSelection = DTE.ActiveDocument.Selection
        Dim classInfo As CodeClass2 = GetClassElement()

        If classInfo Is Nothing Then
            System.Windows.Forms.MessageBox.Show("No class was found surrounding the cursor.  Make sure that this file compiles and try again.", "Error")
            Return
        End If

        If classInfo.Bases.Count = 0 Then
            System.Windows.Forms.MessageBox.Show("No parent class was found for this class.  Make sure that this file, and any file containing parent classes compiles and try again")
            Return
        End If

        'setting up an undo context -- one ctrl+z undoes everything
        Dim closeUndoContext As Boolean = False
        If DTE.UndoContext.IsOpen = False Then
            closeUndoContext = True
            DTE.UndoContext.Open("StubConstructorsContext", False)
        End If

        Try
            Dim parentInfo As CodeClass2 = classInfo.Bases.Item(1)
            Dim childConstructors As System.Collections.Generic.List(Of CodeFunction2) = GetConstructors(classInfo)
            Dim parentConstructors As System.Collections.Generic.List(Of CodeFunction2) = GetConstructors(parentInfo)
            For Each constructor As CodeFunction2 In parentConstructors
                If Not MatchingSignatureExists(constructor, childConstructors) Then
                    ' we only want to create ctor stubs for ctors that are missing
                    ' note: a dictionary could be more efficient, but I doubt most classes will have more than 4 or 5 ctors...
                    StubConstructor(classInfo, constructor)
                End If
            Next
        Finally
            If closeUndoContext Then
                DTE.UndoContext.Close()
            End If
        End Try
    End Sub
    Private Function GetConstructors(ByVal classInfo As CodeClass2) As System.Collections.Generic.List(Of CodeFunction2)
        ' return a list of all of the constructors in the specified class
        Dim result As System.Collections.Generic.List(Of CodeFunction2) = New System.Collections.Generic.List(Of CodeFunction2)
        Dim func As CodeFunction2
        For Each member As CodeElement2 In classInfo.Members
            ' members collection has all class members.  filter out just the function members, and then of the functions, grab just the ctors
            func = TryCast(member, CodeFunction2)
            If func Is Nothing Then Continue For
            If func.FunctionKind = vsCMFunction.vsCMFunctionConstructor Then
                result.Add(func)
            End If
        Next
        Return result
    End Function
    Private Function MatchingSignatureExists(ByVal searchFunction As CodeFunction2, ByVal functions As System.Collections.Generic.List(Of CodeFunction2)) As Boolean
        ' given a function (searchFunction), searches a list of functions where the function signatures (not necessarily the names) match
        ' return null if no match is found, otherwise returns first match
        For Each func As CodeFunction In functions
            If func.Parameters.Count <> searchFunction.Parameters.Count Then Continue For
            Dim searchParam As CodeParameter2
            Dim funcParam As CodeParameter2
            Dim match As Boolean = True

            For count As Integer = 1 To searchFunction.Parameters.Count
                searchParam = searchFunction.Parameters.Item(count)
                funcParam = func.Parameters.Item(count)
                If searchParam.Type.AsFullName <> funcParam.Type.AsFullName Then
                    match = False
                    Exit For
                End If
            Next

            If match Then
                Return True
            End If
        Next
        ' no match found
        Return False
    End Function

    Private Sub StubConstructor(ByVal classInfo As CodeClass2, ByVal parentConstructor As CodeFunction2)
        ' adds a constructor to the current class, based upon the parentConstructor that is passed in

        ' highly inefficient hack to position the ctor where I want it (after the last ctor in the class, if there is another ctor
        ' note that passing zero as the position (put the ctor first) caused some problems when we were adding ctors to classes that already had ctors
        Dim position As Object
        Dim ctors As System.Collections.Generic.List(Of CodeFunction2) = GetConstructors(classInfo)

        If ctors.Count = 0 Then
            position = 0
        Else
            position = ctors.Item(ctors.Count - 1)
        End If

        ' if there are no other ctors, put this one at the top
        Dim ctor As CodeFunction2 = classInfo.AddFunction(classInfo.Name, vsCMFunction.vsCMFunctionConstructor, vsCMTypeRef.vsCMTypeRefVoid, position, parentConstructor.Access)

        Dim baseCall As String = ":base("
        Dim separator As String = ""
        For Each parameter As CodeParameter2 In parentConstructor.Parameters
            ctor.AddParameter(parameter.Name, parameter.Type, -1)
            baseCall += separator + parameter.Name
            separator = ", "
        Next
        baseCall += ")"

        ' and 1 sad hack -- appears to be no way to programmatically add the :base() calls without using direct string manipulation
        Dim startPoint As TextPoint = ctor.GetStartPoint()
        Dim endOfSignature As EditPoint = startPoint.CreateEditPoint()
        endOfSignature.EndOfLine()
        endOfSignature.Insert(baseCall)
        startPoint.CreateEditPoint().SmartFormat(endOfSignature)
    End Sub

    Private Function GetClassElement() As CodeClass2
        'returns a CodeClass2 element representing the class that the cursor is within, or null if there is no class
        Try
            Dim selection As TextSelection = DTE.ActiveDocument.Selection
            Dim fileCodeModel As FileCodeModel2 = DTE.ActiveDocument.ProjectItem.FileCodeModel
            Dim element As CodeElement2 = fileCodeModel.CodeElementFromPoint(selection.TopPoint, vsCMElement.vsCMElementClass)
            Return element
        Catch
            Return Nothing
        End Try
    End Function

End Module

PHP upload image

<?php
include("config.php");

if(isset($_POST['but_upload'])){
 
  $name = $_FILES['file']['name'];
  $target_dir = "upload/";
  $target_file = $target_dir . basename($_FILES["file"]["name"]);

  // Select file type
  $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

  // Valid file extensions
  $extensions_arr = array("jpg","jpeg","png","gif");

  // Check extension
  if( in_array($imageFileType,$extensions_arr) ){
 
     // Insert record
     $query = "insert into images(name) values('".$name."')";
     mysqli_query($con,$query);
  
     // Upload file
     move_uploaded_file($_FILES['file']['tmp_name'],$target_dir.$name);

  }
 
}
?>
<form method="post" action="" enctype='multipart/form-data'>
  <input type='file' name='file' />
  <input type='submit' value='Save name' name='but_upload'>
</form>

Select the name or path of the image which you have stored in the database table and use it in the image source. Read More

 <?php
    $sql = "select name from images where id=1";
    $result = mysqli_query($con,$sql);
    while($row = mysqli_fetch_array($result)){
          $image = $row['name'];
          $image_src = "upload/".$image; 
          <img src='<?php echo $image_src;  ?>' > echo '<br>';
    }
    ?>

source code: https://www.phpcodingstuff.com/blog/how-to-insert-image-in-php.html

Git removing upstream from local repository

git remote manpage is pretty straightforward:

Use

Older (backwards-compatible) syntax:
$ git remote rm upstream
Newer syntax for newer git versions: (* see below)
$ git remote remove upstream

Then do:    
$ git remote add upstream https://github.com/Foo/repos.git

or just update the URL directly:

$ git remote set-url upstream https://github.com/Foo/repos.git

or if you are comfortable with it, just update the .git/config directly - you can probably figure out what you need to change (left as exercise for the reader).

...
[remote "upstream"]
    fetch = +refs/heads/*:refs/remotes/upstream/*
    url = https://github.com/foo/repos.git
...

===

* Regarding 'git remote rm' vs 'git remote remove' - this changed around git 1.7.10.3 / 1.7.12 2 - see

https://code.google.com/p/git-core/source/detail?spec=svne17dba8fe15028425acd6a4ebebf1b8e9377d3c6&r=e17dba8fe15028425acd6a4ebebf1b8e9377d3c6

Log message

remote: prefer subcommand name 'remove' to 'rm'

All remote subcommands are spelled out words except 'rm'. 'rm', being a
popular UNIX command name, may mislead users that there are also 'ls' or
'mv'. Use 'remove' to fit with the rest of subcommands.

'rm' is still supported and used in the test suite. It's just not
widely advertised.

LINQ equivalent of foreach for IEnumerable<T>

This "functional approach" abstraction leaks big time. Nothing on the language level prevents side effects. As long as you can make it call your lambda/delegate for every element in the container - you will get the "ForEach" behavior.

Here for example one way of merging srcDictionary into destDictionary (if key already exists - overwrites)

this is a hack, and should not be used in any production code.

var b = srcDictionary.Select(
                             x=>
                                {
                                  destDictionary[x.Key] = x.Value;
                                  return true;
                                }
                             ).Count();

Browser detection

Try the below code

HttpRequest req = System.Web.HttpContext.Current.Request
string browserName = req.Browser.Browser;

Using RegEx in SQL Server

You will have to build a CLR procedure that provides regex functionality, as this article illustrates.

Their example function uses VB.NET:

Imports System
Imports System.Data.Sql
Imports Microsoft.SqlServer.Server
Imports System.Data.SqlTypes
Imports System.Runtime.InteropServices
Imports System.Text.RegularExpressions
Imports System.Collections 'the IEnumerable interface is here  


Namespace SimpleTalk.Phil.Factor
    Public Class RegularExpressionFunctions
        'RegExIsMatch function
        <SqlFunction(IsDeterministic:=True, IsPrecise:=True)> _
        Public Shared Function RegExIsMatch( _
                                            ByVal pattern As SqlString, _
                                            ByVal input As SqlString, _
                                            ByVal Options As SqlInt32) As SqlBoolean
            If (input.IsNull OrElse pattern.IsNull) Then
                Return SqlBoolean.False
            End If
            Dim RegExOption As New System.Text.RegularExpressions.RegExOptions
            RegExOption = Options
            Return RegEx.IsMatch(input.Value, pattern.Value, RegExOption)
        End Function
    End Class      ' 
End Namespace

...and is installed in SQL Server using the following SQL (replacing '%'-delimted variables by their actual equivalents:

sp_configure 'clr enabled', 1
RECONFIGURE WITH OVERRIDE

IF EXISTS ( SELECT   1
            FROM     sys.objects
            WHERE    object_id = OBJECT_ID(N'dbo.RegExIsMatch') ) 
   DROP FUNCTION dbo.RegExIsMatch
go

IF EXISTS ( SELECT   1
            FROM     sys.assemblies asms
            WHERE    asms.name = N'RegExFunction ' ) 
   DROP ASSEMBLY [RegExFunction]

CREATE ASSEMBLY RegExFunction 
           FROM '%FILE%'
GO

CREATE FUNCTION RegExIsMatch
   (
    @Pattern NVARCHAR(4000),
    @Input NVARCHAR(MAX),
    @Options int
   )
RETURNS BIT
AS EXTERNAL NAME 
   RegExFunction.[SimpleTalk.Phil.Factor.RegularExpressionFunctions].RegExIsMatch
GO

--a few tests
---Is this card a valid credit card?
SELECT dbo.RegExIsMatch ('^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$','4241825283987487',1)
--is there a number in this string
SELECT dbo.RegExIsMatch( '\d','there is 1 thing I hate',1)
--Verifies number Returns 1
DECLARE @pattern VARCHAR(255)
SELECT @pattern ='[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]'
SELECT  dbo.RegExIsMatch (@pattern, '1298-673-4192',1),
        dbo.RegExIsMatch (@pattern,'A08Z-931-468A',1),
        dbo.RegExIsMatch (@pattern,'[A90-123-129X',1),
        dbo.RegExIsMatch (@pattern,'12345-KKA-1230',1),
        dbo.RegExIsMatch (@pattern,'0919-2893-1256',1)

Java - Convert int to Byte Array of 4 Bytes?

You can convert yourInt to bytes by using a ByteBuffer like this:

return ByteBuffer.allocate(4).putInt(yourInt).array();

Beware that you might have to think about the byte order when doing so.

How to remove undefined and null values from an object using lodash?

You can simply chain _.omit() with _.isUndefined and _.isNull compositions, and get the result with lazy evaluation.

Demo

var result = _(my_object).omit(_.isUndefined).omit(_.isNull).value();

Update March 14, 2016:

As mentioned by dylants in the comment section, you should use the _.omitBy() function since it uses a predicate instead of a property. You should use this for lodash version 4.0.0 and above.

DEMO

var result = _(my_object).omitBy(_.isUndefined).omitBy(_.isNull).value();

Update June 1, 2016:

As commented by Max Truxa, lodash already provided an alternative _.isNil, which checks for both null and undefined:

var result = _.omitBy(my_object, _.isNil);

How to define hash tables in Bash?

A coworker just mentioned this thread. I've independently implemented hash tables within bash, and it's not dependent on version 4. From a blog post of mine in March 2010 (before some of the answers here...) entitled Hash tables in bash:

I previously used cksum to hash but have since translated Java's string hashCode to native bash/zsh.

# Here's the hashing function
ht() {
  local h=0 i
  for (( i=0; i < ${#1}; i++ )); do
    let "h=( (h<<5) - h ) + $(printf %d \'${1:$i:1})"
    let "h |= h"
  done
  printf "$h"
}

# Example:

myhash[`ht foo bar`]="a value"
myhash[`ht baz baf`]="b value"

echo ${myhash[`ht baz baf`]} # "b value"
echo ${myhash[@]} # "a value b value" though perhaps reversed
echo ${#myhash[@]} # "2" - there are two values (note, zsh doesn't count right)

It's not bidirectional, and the built-in way is a lot better, but neither should really be used anyway. Bash is for quick one-offs, and such things should quite rarely involve complexity that might require hashes, except perhaps in your ~/.bashrc and friends.