Programs & Examples On #37 signals

37signals is the company behind Basecamp, Campfire, and Highrise.

Delete item from state array in react

const [people, setPeople] = useState(data);

const handleRemove = (id) => {
   const newPeople = people.filter((person) => { person.id !== id;
     setPeople( newPeople );
     
   });
 };

<button onClick={() => handleRemove(id)}>Remove</button>

Read file data without saving it in Flask

I was trying to do the exact same thing, open a text file (a CSV for Pandas actually). Don't want to make a copy of it, just want to open it. The form-WTF has a nice file browser, but then it opens the file and makes a temporary file, which it presents as a memory stream. With a little work under the hood,

form = UploadForm() 
 if form.validate_on_submit(): 
      filename = secure_filename(form.fileContents.data.filename)  
      filestream =  form.fileContents.data 
      filestream.seek(0)
      ef = pd.read_csv( filestream  )
      sr = pd.DataFrame(ef)  
      return render_template('dataframe.html',tables=[sr.to_html(justify='center, classes='table table-bordered table-hover')],titles = [filename], form=form) 

How do I implement a progress bar in C#?

If you can't know the progress you should not fake it by abusing a progress bar, instead just display some sort of busy icon like en.wikipedia.org/wiki/Throbber#Spinning_wheel Show it when starting the task and hide it when it's finished. That would make for a more "honest" GUI.

Is a GUID unique 100% of the time?

Yes, a GUID should always be unique. It is based on both hardware and time, plus a few extra bits to make sure it's unique. I'm sure it's theoretically possible to end up with two identical ones, but extremely unlikely in a real-world scenario.

Here's a great article by Raymond Chen on Guids:

https://blogs.msdn.com/oldnewthing/archive/2008/06/27/8659071.aspx ? ? ?

WPF TabItem Header Styling

While searching for a way to round tabs, I found Carlo's answer and it did help but I needed a bit more. Here is what I put together, based on his work. This was done with MS Visual Studio 2015.

The Code:

<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MealNinja"
        mc:Ignorable="d"
        Title="Rounded Tabs Example" Height="550" Width="700" WindowStartupLocation="CenterScreen" FontFamily="DokChampa" FontSize="13.333" ResizeMode="CanMinimize" BorderThickness="0">
    <Window.Effect>
        <DropShadowEffect Opacity="0.5"/>
    </Window.Effect>
    <Grid Background="#FF423C3C">
        <TabControl x:Name="tabControl" TabStripPlacement="Left" Margin="6,10,10,10" BorderThickness="3">
            <TabControl.Resources>
                <Style TargetType="{x:Type TabItem}">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type TabItem}">
                                <Grid>
                                    <Border Name="Border" Background="#FF6E6C67" Margin="2,2,-8,0" BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="10">
                                        <ContentPresenter x:Name="ContentSite" ContentSource="Header" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="2,2,12,2" RecognizesAccessKey="True"/>
                                    </Border>
                                    <Rectangle Height="100" Width="10" Margin="0,0,-10,0" Stroke="Black" VerticalAlignment="Bottom" HorizontalAlignment="Right" StrokeThickness="0" Fill="#FFD4D0C8"/>
                                </Grid>
                                <ControlTemplate.Triggers>
                                    <Trigger Property="IsSelected" Value="True">
                                        <Setter Property="FontWeight" Value="Bold" />
                                        <Setter TargetName="ContentSite" Property="Width" Value="30" />
                                        <Setter TargetName="Border" Property="Background" Value="#FFD4D0C8" />
                                    </Trigger>
                                    <Trigger Property="IsEnabled" Value="False">
                                        <Setter TargetName="Border" Property="Background" Value="#FF6E6C67" />
                                    </Trigger>
                                    <Trigger Property="IsMouseOver" Value="true">
                                        <Setter Property="FontWeight" Value="Bold" />
                                    </Trigger>
                                </ControlTemplate.Triggers>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="HeaderTemplate">
                        <Setter.Value>
                            <DataTemplate>
                                <ContentPresenter Content="{TemplateBinding Content}">
                                    <ContentPresenter.LayoutTransform>
                                        <RotateTransform Angle="270" />
                                    </ContentPresenter.LayoutTransform>
                                </ContentPresenter>
                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="Background" Value="#FF6E6C67" />
                    <Setter Property="Height" Value="90" />
                    <Setter Property="Margin" Value="0" />
                    <Setter Property="Padding" Value="0" />
                    <Setter Property="FontFamily" Value="DokChampa" />
                    <Setter Property="FontSize" Value="16" />
                    <Setter Property="VerticalAlignment" Value="Top" />
                    <Setter Property="HorizontalAlignment" Value="Right" />
                    <Setter Property="UseLayoutRounding" Value="False" />
                </Style>
                <Style x:Key="tabGrids">
                    <Setter Property="Grid.Background" Value="#FFE5E5E5" />
                    <Setter Property="Grid.Margin" Value="6,10,10,10" />
                </Style>
            </TabControl.Resources>
            <TabItem Header="Planner">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Section 2">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Section III">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Section 04">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Tools">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
        </TabControl>
    </Grid>
</Window>

Screenshot:

enter image description here

jQuery get input value after keypress

You have to interrupt the execution thread to allow the input to update.

  $(document).ready(function(event) {
       $("#dSuggest").keypress(function() {
           //Interrupt the execution thread to allow input to update
               setTimeout(function() {
                   var dInput = $('input:text[name=dSuggest]').val();
                   console.log(dInput);
                   $(".dDimension:contains('" + dInput + "')").css("display","block");
               }, 0);
       });
  });

Is it worth using Python's re.compile?

Regular Expressions are compiled before being used when using the second version. If you are going to executing it many times it is definatly better to compile it first. If not compiling every time you match for one off's is fine.

Read specific columns with pandas or other python module

According to the latest pandas documentation you can read a csv file selecting only the columns which you want to read.

import pandas as pd

df = pd.read_csv('some_data.csv', usecols = ['col1','col2'], low_memory = True)

Here we use usecols which reads only selected columns in a dataframe.

We are using low_memory so that we Internally process the file in chunks.

How to unstash only certain files?

git checkout stash@{N} <File(s)/Folder(s) path> 

Eg. To restore only ./test.c file and ./include folder from last stashed,

git checkout stash@{0} ./test.c ./include

How to extract the n-th elements from a list of tuples?

Using islice and chain.from_iterable:

>>> from itertools import chain, islice
>>> elements = [(1,1,1),(2,3,7),(3,5,10)]
>>> list(chain.from_iterable(islice(item, 1, 2) for item in elements))
[1, 3, 5]

This can be useful when you need more than one element:

>>> elements = [(0, 1, 2, 3, 4, 5), 
                (10, 11, 12, 13, 14, 15), 
                (20, 21, 22, 23, 24, 25)]
>>> list(chain.from_iterable(islice(tuple_, 2, 5) for tuple_ in elements))
[2, 3, 4, 12, 13, 14, 22, 23, 24]

Understanding the basics of Git and GitHub

  1. What is the difference between Git and GitHub?

    Linus Torvalds would kill you for this. Git is the name of the version manager program he wrote. GitHub is a website on which there are source code repositories manageable by Git. Thus, GitHub is completely unrelated to the original Git tool.

  2. Is git saving every repository locally (in the user's machine) and in GitHub?

    If you commit changes, it stores locally. Then, if you push the commits, it also sotres them remotely.

  3. Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?

    You can, but I'm sure you don't want to manually set up a git server for yourself. Benefits of GitHub? Well, easy to use, lot of people know it so others may find your code and follow/fork it to make improvements as well.

  4. How does Git compare to a backup system such as Time Machine?

    Git is specifically designed and optimized for source code.

  5. Is this a manual process, in other words if you don't commit you wont have a new version of the changes made?

    Exactly.

  6. If are not collaborating and you are already using a backup system why would you use Git?

    See #4.

How to select a single column with Entity Framework?

Using LINQ your query should look something like this:

public User GetUser(int userID){

return
(
 from p in "MyTable" //(Your Entity Model)
 where p.UserID == userID
 select p.Name
).SingleOrDefault();

}

Of course to do this you need to have an ADO.Net Entity Model in your solution.

position fixed is not working

Another cause could be a parent container that contains the CSS animation property. That's what it was for me.

What is the difference between "word-break: break-all" versus "word-wrap: break-word" in CSS

At least in Firefox (as of v24) and Chrome (as of v30), when applied to content in a table element:

word-wrap:break-word

will not actually cause long words to wrap, which can result in the table exceeding the bounds of its container;

word-break:break-all

will result in words wrapping, and the table fitting within its container.

enter image description here

jsfiddle demo.

How to define dimens.xml for every different screen size in android?

Use Scalable DP

Although making a different layout for different screen sizes is theoretically a good idea, it can get very difficult to accommodate for all screen dimensions, and pixel densities. Having over 20+ different dimens.xml files as suggested in the above answers, is not easy to manage at all.

How To Use:

To use sdp:

  1. Include implementation 'com.intuit.sdp:sdp-android:1.0.5' in your build.gradle,
  2. Replace any dp value such as 50dp with a @dimen/50_sdp like so:

    <TextView
     android:layout_width="@dimen/_50sdp"
     android:layout_height="@dimen/_50sdp"
     android:text="Hello World!" />
    

How It Works:

sdp scales with the screen size because it is essentially a huge list of different dimens.xml for every possible dp value.

enter image description here

See It In Action:

Here it is on three devices with widely differing screen dimensions, and densities:

enter image description here

Note that the sdp size unit calculation includes some approximation due to some performance and usability constraints.

How to determine if Javascript array contains an object with an attribute that equals a given value?

I would rather go with regex.

If your code is as follows,

vendors = [
    {
      Name: 'Magenic',
      ID: 'ABC'
     },
    {
      Name: 'Microsoft',
      ID: 'DEF'
    }
];

I would recommend

/"Name":"Magenic"/.test(JSON.stringify(vendors))

How to crop an image using PIL?

An easier way to do this is using crop from ImageOps. You can feed the number of pixels you want to crop from each side.

from PIL import ImageOps

border = (0, 30, 0, 30) # left, up, right, bottom
ImageOps.crop(img, border)

Unicode, UTF, ASCII, ANSI format differences

Going down your list:

  • "Unicode" isn't an encoding, although unfortunately, a lot of documentation imprecisely uses it to refer to whichever Unicode encoding that particular system uses by default. On Windows and Java, this often means UTF-16; in many other places, it means UTF-8. Properly, Unicode refers to the abstract character set itself, not to any particular encoding.
  • UTF-16: 2 bytes per "code unit". This is the native format of strings in .NET, and generally in Windows and Java. Values outside the Basic Multilingual Plane (BMP) are encoded as surrogate pairs. These used to be relatively rarely used, but now many consumer applications will need to be aware of non-BMP characters in order to support emojis.
  • UTF-8: Variable length encoding, 1-4 bytes per code point. ASCII values are encoded as ASCII using 1 byte.
  • UTF-7: Usually used for mail encoding. Chances are if you think you need it and you're not doing mail, you're wrong. (That's just my experience of people posting in newsgroups etc - outside mail, it's really not widely used at all.)
  • UTF-32: Fixed width encoding using 4 bytes per code point. This isn't very efficient, but makes life easier outside the BMP. I have a .NET Utf32String class as part of my MiscUtil library, should you ever want it. (It's not been very thoroughly tested, mind you.)
  • ASCII: Single byte encoding only using the bottom 7 bits. (Unicode code points 0-127.) No accents etc.
  • ANSI: There's no one fixed ANSI encoding - there are lots of them. Usually when people say "ANSI" they mean "the default locale/codepage for my system" which is obtained via Encoding.Default, and is often Windows-1252 but can be other locales.

There's more on my Unicode page and tips for debugging Unicode problems.

The other big resource of code is unicode.org which contains more information than you'll ever be able to work your way through - possibly the most useful bit is the code charts.

System.Drawing.Image to stream C#

Use a memory stream

using(MemoryStream ms = new MemoryStream())
{
    image.Save(ms, ...);
    return ms.ToArray();
}

String replacement in batch file

I was able to use Joey's Answer to create a function:

Use it as:

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

SET "MYTEXT=jump over the chair"
echo !MYTEXT!
call:ReplaceText "!MYTEXT!" chair table RESULT
echo !RESULT!

GOTO:EOF

And these Functions to the bottom of your Batch File.

:FUNCTIONS
@REM FUNCTIONS AREA
GOTO:EOF
EXIT /B

:ReplaceText
::Replace Text In String
::USE:
:: CALL:ReplaceText "!OrginalText!" OldWordToReplace NewWordToUse  Result
::Example
::SET "MYTEXT=jump over the chair"
::  echo !MYTEXT!
::  call:ReplaceText "!MYTEXT!" chair table RESULT
::  echo !RESULT!
::
:: Remember to use the "! on the input text, but NOT on the Output text.
:: The Following is Wrong: "!MYTEXT!" !chair! !table! !RESULT!
:: ^^Because it has a ! around the chair table and RESULT
:: Remember to add quotes "" around the MYTEXT Variable when calling.
:: If you don't add quotes, it won't treat it as a single string
::
set "OrginalText=%~1"
set "OldWord=%~2"
set "NewWord=%~3"
call set OrginalText=%%OrginalText:!OldWord!=!NewWord!%%
SET %4=!OrginalText!
GOTO:EOF

And remember you MUST add "SETLOCAL ENABLEDELAYEDEXPANSION" to the top of your batch file or else none of this will work properly.

SETLOCAL ENABLEDELAYEDEXPANSION
@REM # Remember to add this to the top of your batch file.

Difference between "process.stdout.write" and "console.log" in node.js?

I know this is a very old question but I didn't see anybody talking about the main difference between process.stdout.write and console.log and I just want to mention it.

As Mauvis Leford and TK-421 pointed out, the console.log adds a line-break character at the end of the line (\n) but that's not all what it does.

The code has not changed since at least 0.10.X version and now we have a a 5.X version.

Here is the code:

Console.prototype.log = function() {
  this._stdout.write(util.format.apply(this, arguments) + '\n');
};

As you can see, there is a part that says .apply(this, arguments) and that makes a big difference on functionality. It is easier to explain that with examples:

process.stdout.write has a very basic functionality, you can just write something in there, like this:

process.stdout.write("Hello World\n"); 

If you don't put the break line at the end you will get a weird character after your string, something like this:

process.stdout.write("Hello World"); //Hello World% 

(I think that means something like "the end of the program", so you will see it only if you process.stdout.write was used at the end of your file and you didn't add the break line)

On the other hand, console.log can do more.

  1. You can use it in the same way

    console.log("Hello World"); //You don't need the break line here because it was already formated and also that weird character did disappear

  2. You can write more than one string

    console.log("Hello", "World");

  3. You can make associations

    console.log("Hello %s", "World") //Useful when "World" is inside a variable

An that's it, that added functionality is given thanks to the util.format.apply part (I could talk a lot about what exactly this does but you get my point, you can read more here).

I hope somebody find this information useful.

How to use shared memory with Linux in C

Here's a mmap example:

#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

/*
 * pvtmMmapAlloc - creates a memory mapped file area.  
 * The return value is a page-aligned memory value, or NULL if there is a failure.
 * Here's the list of arguments:
 * @mmapFileName - the name of the memory mapped file
 * @size - the size of the memory mapped file (should be a multiple of the system page for best performance)
 * @create - determines whether or not the area should be created.
 */
void* pvtmMmapAlloc (char * mmapFileName, size_t size, char create)  
{      
  void * retv = NULL;                                                                                              
  if (create)                                                                                         
  {                                                                                                   
    mode_t origMask = umask(0);                                                                       
    int mmapFd = open(mmapFileName, O_CREAT|O_RDWR, 00666);                                           
    umask(origMask);                                                                                  
    if (mmapFd < 0)                                                                                   
    {                                                                                                 
      perror("open mmapFd failed");                                                                   
      return NULL;                                                                                    
    }                                                                                                 
    if ((ftruncate(mmapFd, size) == 0))               
    {                                                                                                 
      int result = lseek(mmapFd, size - 1, SEEK_SET);               
      if (result == -1)                                                                               
      {                                                                                               
        perror("lseek mmapFd failed");                                                                
        close(mmapFd);                                                                                
        return NULL;                                                                                  
      }                                                                                               

      /* Something needs to be written at the end of the file to                                      
       * have the file actually have the new size.                                                    
       * Just writing an empty string at the current file position will do.                           
       * Note:                                                                                        
       *  - The current position in the file is at the end of the stretched                           
       *    file due to the call to lseek().  
              *  - The current position in the file is at the end of the stretched                    
       *    file due to the call to lseek().                                                          
       *  - An empty string is actually a single '\0' character, so a zero-byte                       
       *    will be written at the last byte of the file.                                             
       */                                                                                             
      result = write(mmapFd, "", 1);                                                                  
      if (result != 1)                                                                                
      {                                                                                               
        perror("write mmapFd failed");                                                                
        close(mmapFd);                                                                                
        return NULL;                                                                                  
      }                                                                                               
      retv  =  mmap(NULL, size,   
                  PROT_READ | PROT_WRITE, MAP_SHARED, mmapFd, 0);                                     

      if (retv == MAP_FAILED || retv == NULL)                                                         
      {                                                                                               
        perror("mmap");                                                                               
        close(mmapFd);                                                                                
        return NULL;                                                                                  
      }                                                                                               
    }                                                                                                 
  }                                                                                                   
  else                                                                                                
  {                                                                                                   
    int mmapFd = open(mmapFileName, O_RDWR, 00666);                                                   
    if (mmapFd < 0)                                                                                   
    {                                                                                                 
      return NULL;                                                                                    
    }                                                                                                 
    int result = lseek(mmapFd, 0, SEEK_END);                                                          
    if (result == -1)                                                                                 
    {                                                                                                 
      perror("lseek mmapFd failed");                  
      close(mmapFd);                                                                                  
      return NULL;                                                                                    
    }                                                                                                 
    if (result == 0)                                                                                  
    {                                                                                                 
      perror("The file has 0 bytes");                           
      close(mmapFd);                                                                                  
      return NULL;                                                                                    
    }                                                                                              
    retv  =  mmap(NULL, size,     
                PROT_READ | PROT_WRITE, MAP_SHARED, mmapFd, 0);                                       

    if (retv == MAP_FAILED || retv == NULL)                                                           
    {                                                                                                 
      perror("mmap");                                                                                 
      close(mmapFd);                                                                                  
      return NULL;                                                                                    
    }                                                                                                 

    close(mmapFd);                                                                                    

  }                                                                                                   
  return retv;                                                                                        
}                                                                                                     

linux shell script: split string, put them in an array then loop through them

You can probably skip the step of explicitly creating an array...

One trick that I like to use is to set the inter-field separator (IFS) to the delimiter character. This is especially handy for iterating through the space or return delimited results from the stdout of any of a number of unix commands.

Below is an example using semicolons (as you had mentioned in your question):

export IFS=";"
sentence="one;two;three"
for word in $sentence; do
  echo "$word"
done

Note: in regular Bourne-shell scripting setting and exporting the IFS would occur on two separate lines (IFS='x'; export IFS;).

Regex matching in a Bash if statement

In case someone wanted an example using variables...

#!/bin/bash

# Only continue for 'develop' or 'release/*' branches
BRANCH_REGEX="^(develop$|release//*)"

if [[ $BRANCH =~ $BRANCH_REGEX ]];
then
    echo "BRANCH '$BRANCH' matches BRANCH_REGEX '$BRANCH_REGEX'"
else
    echo "BRANCH '$BRANCH' DOES NOT MATCH BRANCH_REGEX '$BRANCH_REGEX'"
fi

doGet and doPost in Servlets

If you do <form action="identification" > for your html form, data will be passed using 'Get' by default and hence you can catch this using doGet function in your java servlet code. This way data will be passed under the HTML header and hence will be visible in the URL when submitted. On the other hand if you want to pass data in HTML body, then USE Post: <form action="identification" method="post"> and catch this data in doPost function. This was, data will be passed under the html body and not the html header, and you will not see the data in the URL after submitting the form.

Examples from my html:

<body>  
<form action="StartProcessUrl" method="post">
.....
.....

Examples from my java servlet code:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        PrintWriter out = response.getWriter();
         String surname = request.getParameter("txtSurname");
         String firstname = request.getParameter("txtForename");
         String rqNo = request.getParameter("txtRQ6");
         String nhsNo = request.getParameter("txtNHSNo");

         String attachment1 = request.getParameter("base64textarea1");
         String attachment2 = request.getParameter("base64textarea2");

.........
.........

How to post pictures to instagram using API

For anyone who is searching for a solution about posting to Instagram using AWS lambda and puppeteer (chrome-aws-lambda). Noted that this solution allow you to post 1 photo for each post only. If you are not using lambda, just replace chrome-aws-lambda with puppeteer.

For the first launch of lambda, it is normal that will not work because instagram detects “Suspicious login attempt”. Just goto instagram page using your PC and approve it, everything should be fine.

Here's my code, feel free to optimize it:

// instagram.js
const chromium = require('chrome-aws-lambda');

const username = process.env.IG_USERNAME;
const password = process.env.IG_PASSWORD;

module.exports.post = async function(fileToUpload, caption){
    const browser = await chromium.puppeteer.launch({
        args: [...chromium.args, '--window-size=520,700'],
        defaultViewport: chromium.defaultViewport,
        executablePath: await chromium.executablePath,
        headless: false,
        ignoreHTTPSErrors: true,
    });
    const page = await browser.newPage();
    await page.setUserAgent('Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) FxiOS/7.5b3349 Mobile/14F89 Safari/603.2.4');
    await page.goto('https://www.instagram.com/', {waitUntil: 'networkidle2'});
    
    const [buttonLogIn] = await page.$x("//button[contains(., 'Log In')]");
    if (buttonLogIn) {
        await buttonLogIn.click();
    }

    await page.waitFor('input[name="username"]');
    await page.type('input[name="username"]', username)
    await page.type('input[name="password"]', password)
    await page.click('form button[type="submit"]');

    await page.waitFor(3000);
    const [buttonSaveInfo] = await page.$x("//button[contains(., 'Not Now')]");
    if (buttonSaveInfo) {
        await buttonSaveInfo.click();
    }

    await page.waitFor(3000);
    const [buttonNotificationNotNow] = await page.$x("//button[contains(., 'Not Now')]");
    const [buttonNotificationCancel] = await page.$x("//button[contains(., 'Cancel')]");
    if (buttonNotificationNotNow) {
        await buttonNotificationNotNow.click();
    } else if (buttonNotificationCancel) {
        await buttonNotificationCancel.click(); 
    }

    await page.waitFor('form[enctype="multipart/form-data"]');
    const inputUploadHandle = await page.$('form[enctype="multipart/form-data"] input[type=file]');

    await page.waitFor(5000);
    const [buttonPopUpNotNow] = await page.$x("//button[contains(., 'Not Now')]");
    const [buttonPopUpCancel] = await page.$x("//button[contains(., 'Cancel')]");
    if (buttonPopUpNotNow) {
        await buttonPopUpNotNow.click();
    } else if (buttonPopUpCancel) {
        await buttonPopUpCancel.click(); 
    }

    await page.click('[data-testid="new-post-button"]')
    await inputUploadHandle.uploadFile(fileToUpload);

    await page.waitFor(3000);
    const [buttonNext] = await page.$x("//button[contains(., 'Next')]");
    await buttonNext.click();

    await page.waitFor(3000);
    await page.type('textarea', caption);

    const [buttonShare] = await page.$x("//button[contains(., 'Share')]");
    await buttonShare.click();
    await page.waitFor(3000);

    return true;
};
// handler.js

await instagram.post('/tmp/image.png', '#text');

it must be local file path, if it is url, download it to /tmp folder first.

How to add row in JTable?

The TableModel behind the JTable handles all of the data behind the table. In order to add and remove rows from a table, you need to use a DefaultTableModel

To create the table with this model:

JTable table = new JTable(new DefaultTableModel(new Object[]{"Column1", "Column2"}));

To add a row:

DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(new Object[]{"Column 1", "Column 2", "Column 3"});

You can also remove rows with this method.

Full details on the DefaultTableModel can be found here

How do I delay a function call for 5 seconds?

You can use plain javascript, this will call your_func once, after 5 seconds:

setTimeout(function() { your_func(); }, 5000);

If your function has no parameters and no explicit receiver you can call directly setTimeout(func, 5000)

There is also a plugin I've used once. It has oneTime and everyTime methods.

jQuery - hashchange event

There is a hashchange plug-in which wraps up the functionality and cross browser issues available here.

java.util.regex - importance of Pattern.compile()?

When you compile the Pattern Java does some computation to make finding matches in Strings faster. (Builds an in-memory representation of the regex)

If you are going to reuse the Pattern multiple times you would see a vast performance increase over creating a new Pattern every time.

In the case of only using the Pattern once, the compiling step just seems like an extra line of code, but, in fact, it can be very helpful in the general case.

Convert seconds into days, hours, minutes and seconds

This is a function i used in the past for substracting a date from another one related with your question, my principe was to get how many days, hours minutes and seconds has left until a product has expired :

$expirationDate = strtotime("2015-01-12 20:08:23");
$toDay = strtotime(date('Y-m-d H:i:s'));
$difference = abs($toDay - $expirationDate);
$days = floor($difference / 86400);
$hours = floor(($difference - $days * 86400) / 3600);
$minutes = floor(($difference - $days * 86400 - $hours * 3600) / 60);
$seconds = floor($difference - $days * 86400 - $hours * 3600 - $minutes * 60);

echo "{$days} days {$hours} hours {$minutes} minutes {$seconds} seconds";

Extract time from date String

If you have date in integers, you could use like here:

Date date = new Date();
date.setYear(2010);
date.setMonth(07);
date.setDate(14)
date.setHours(9);
date.setMinutes(0);
date.setSeconds(0);
String time = new SimpleDateFormat("HH:mm:ss").format(date);

Class has been compiled by a more recent version of the Java Environment

Your JDK version: Java 8
Your JRE version: Java 9

Here your JRE version is different than the JDK version that's the case. Here you can compile all the java classes using JDK version 1.8. If you want to compile only one java class just change the *.java into <yourclassname>.java

javac -source 1.8 -target 1.8  *.java

source: The version that your source code requires to compile.
target: The oldest JRE version you want to support.

Python conversion between coordinates

Using numpy, you can define the following:

import numpy as np

def cart2pol(x, y):
    rho = np.sqrt(x**2 + y**2)
    phi = np.arctan2(y, x)
    return(rho, phi)

def pol2cart(rho, phi):
    x = rho * np.cos(phi)
    y = rho * np.sin(phi)
    return(x, y)

Regex pattern including all special characters

Here is my regular expression, that I used for removing all the special characters from any string :

String regex = ("[ \\\\s@  [\\\"]\\\\[\\\\]\\\\\\\0-9|^{#%'*/<()>}:`;,!& .?_$+-]+")

Oracle listener not running and won't start

I encountered the same problem and reason being: Mine is a personal windows PC. And i have modified the computer name and the same did not reflect in listener.ora. Updating ORACLE_HOME\network\ADMIN\listener.ora with updated host name fixed the issue.

How can I get the baseurl of site?

The popular GetLeftPart solution is not supported in the PCL version of Uri, unfortunately. GetComponents is, however, so if you need portability, this should do the trick:

uri.GetComponents(
    UriComponents.SchemeAndServer | UriComponents.UserInfo, UriFormat.Unescaped);

How can I execute PHP code from the command line?

On the command line:

php -i | grep sourceguardian

If it's there, then you'll get some text. If not, you won't get a thing.

C# Test if user has write access to a folder

That's a perfectly valid way to check for folder access in C#. The only place it might fall down is if you need to call this in a tight loop where the overhead of an exception may be an issue.

There have been other similar questions asked previously.

What is the difference between varchar and varchar2 in Oracle?

Currently VARCHAR behaves exactly the same as VARCHAR2. However, the type VARCHAR should not be used as it is reserved for future usage.

Taken from: Difference Between CHAR, VARCHAR, VARCHAR2

Changing CSS for last <li>

I've done this with pure CSS (probably because I come from the future - 3 years later than everyone else :P )

Supposing we have a list:

<ul id="nav">
  <li><span>Category 1</span></li>
  <li><span>Category 2</span></li>
  <li><span>Category 3</span></li>
</ul>

Then we can easily make the text of the last item red with:

ul#nav li:last-child span {
   color: Red;
}

What does an exclamation mark before a cell reference mean?

If you use that forumla in the name manager you are creating a dynamic range which uses "this sheet" in place of a specific sheet.

As Jerry says, Sheet1!A1 refers to cell A1 on Sheet1. If you create a named range and omit the Sheet1 part you will reference cell A1 on the currently active sheet. (omitting the sheet reference and using it in a cell formula will error).

edit: my bad, I was using $A$1 which will lock it to the A1 cell as above, thanks pnuts :p

python: urllib2 how to send cookie with urlopen request

You might want to take a look at the excellent HTTP Python library called Requests. It makes every task involving HTTP a bit easier than urllib2. From Cookies section of quickstart guide:

To send your own cookies to the server, you can use the cookies parameter:

>>> cookies = dict(cookies_are='working')

>>> r = requests.get('http://httpbin.org/cookies', cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'

Find out time it took for a python script to complete execution

Do you execute the script from the command line on Linux or UNIX? In that case, you could just use

time ./script.py

Java error: Only a type can be imported. XYZ resolves to a package

I had this same issue when running from Eclipse. To fix the issue I went into the Configure Build Path and removed the src folder from the build path. Then closed and reopened the project. Then I added the src folder to the build path. The src folder contained the java class I was trying to access.

pass JSON to HTTP POST Request

I feel

var x = request.post({
       uri: config.uri,
       json: reqData
    });

Defining like this will be the effective way of writing your code. And application/json should be automatically added. There is no need to specifically declare it.

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;

R Markdown - changing font size and font type in html output

I had the same issue and solved by making sure that 1. when you make the style.css file, make sure you didn't just rename a text file as "style.css", make sure it's really the .css format (e.g, use visual studio code); 2. put that style.css file in the same folder with your .rmd file. Hopefully this works for you.

Enable/disable buttons with Angular

Set a property for the current lesson: currentLesson. It will hold, obviously, the 'number' of the choosen lesson. On each button click, set the currentLesson value to 'number'/ order of the button, i.e. for the first button, it will be '1', for the second '2' and so on. Each button now can be disabled with [disabled] attribute, if it the currentLesson is not the same as it's order.

HTML

  <button  (click)="currentLesson = '1'"
         [disabled]="currentLesson !== '1'" class="primair">
           Start lesson</button>
  <button (click)="currentLesson = '2'"
         [disabled]="currentLesson !== '2'" class="primair">
           Start lesson</button>
 .....//so on

Typescript

currentLesson:string;

  classes = [
{
  name: 'string',
  level: 'string',
  code: 'number',
  currentLesson: '1'
}]

constructor(){
  this.currentLesson=this.classes[0].currentLesson
}

DEMO

Putting everything in a loop:

HTML

<div *ngFor="let class of classes; let i = index">
   <button [disabled]="currentLesson !== i + 1" class="primair">
           Start lesson {{i +  1}}</button>
</div>

Typescript

currentLesson:string;

classes = [
{
  name: 'Lesson1',
  level: 1,
  code: 1,
},{
  name: 'Lesson2',
  level: 1,
  code: 2,
},
{
  name: 'Lesson3',
  level: 2,
  code: 3,
}]

DEMO

Installing tensorflow with anaconda in windows

Open anaconda prompt

make sure your pip version is updated

and you have python 3.4 3.5 or 3.6

Just run the command

pip install --upgrade tensorflow

you can take help from the documentation and video

Goodluck

How do I combine a background-image and CSS3 gradient on the same element?

I wanted to make span button with background image, background gradient combination.

http://enjoycss.com/ helped to do my work task. Only I have to remove some auto generated additional CSS. But it's really nice site build your scratch work.

#nav a.link-style span {
    background: url("../images/order-now-mobile.png"), -webkit-linear-gradient(0deg, rgba(190,20,27,1) 0, rgba(224,97,102,1) 51%, rgba(226,0,0,1) 100%);
    background: url("../images/order-now-mobile.png"), -moz-linear-gradient(90deg, rgba(190,20,27,1) 0, rgba(224,97,102,1) 51%, rgba(226,0,0,1) 100%);
    background: url("../images/order-now-mobile.png"), linear-gradient(90deg, rgba(170,31,0,1) 0, rgba(214,18,26,1) 51%, rgba(170,31,0,1) 100%);
    background-repeat: no-repeat;
    background-position: 50% 50%;
    border-radius: 8px;
    border: 3px solid #b30a11;
}

How to close the current fragment by using Button like the back button?

if you need in 2020

    Objects.requireNonNull(getActivity()).onBackPressed();

adding directory to sys.path /PYTHONPATH

Temporarily changing dirs works well for importing:

cwd = os.getcwd()
os.chdir(<module_path>)
import <module>
os.chdir(cwd)

python tuple to dict

Here are couple ways of doing it:

>>> t = ((1, 'a'), (2, 'b'))

>>> # using reversed function
>>> dict(reversed(i) for i in t)
{'a': 1, 'b': 2}

>>> # using slice operator
>>> dict(i[::-1] for i in t)
{'a': 1, 'b': 2}

How to install SignTool.exe for Windows 10

Best solution end of 2020:

Just download Windows 10 SDK from Microsoft here:
https://go.microsoft.com/fwlink/?LinkID=698771

In setup, choose only Windows App Certification App (it's only 120 MB)

enter image description here

You can find signtool.exe here:
%PROGRAMFILES(X86)%\Windows Kits\10\bin\x64

Cheers!

How to ensure a <select> form field is submitted when it is disabled?

I`ve been looking for a solution for this, and since i didnt find a solution in this thread i did my own.

// With jQuery
$('#selectbox').focus(function(e) {
    $(this).blur();
});

Simple, you just blur the field when you focus on it, something like disabling it, but you actually send its data.

How to get index using LINQ?

An IEnumerable is not an ordered set.
Although most IEnumerables are ordered, some (such as Dictionary or HashSet) are not.

Therefore, LINQ does not have an IndexOf method.

However, you can write one yourself:

///<summary>Finds the index of the first item matching an expression in an enumerable.</summary>
///<param name="items">The enumerable to search.</param>
///<param name="predicate">The expression to test the items against.</param>
///<returns>The index of the first matching item, or -1 if no items match.</returns>
public static int FindIndex<T>(this IEnumerable<T> items, Func<T, bool> predicate) {
    if (items == null) throw new ArgumentNullException("items");
    if (predicate == null) throw new ArgumentNullException("predicate");

    int retVal = 0;
    foreach (var item in items) {
        if (predicate(item)) return retVal;
        retVal++;
    }
    return -1;
}
///<summary>Finds the index of the first occurrence of an item in an enumerable.</summary>
///<param name="items">The enumerable to search.</param>
///<param name="item">The item to find.</param>
///<returns>The index of the first matching item, or -1 if the item was not found.</returns>
public static int IndexOf<T>(this IEnumerable<T> items, T item) { return items.FindIndex(i => EqualityComparer<T>.Default.Equals(item, i)); }

How can I use xargs to copy files that have spaces and quotes in their names?

If you are using Bash, you can convert stdout to an array of lines by mapfile:

find . | grep "FooBar" | (mapfile -t; cp "${MAPFILE[@]}" ~/foobar)

The benefits are:

  • It's built-in, so it's faster.
  • Execute the command with all file names in one time, so it's faster.
  • You can append other arguments to the file names. For cp, you can also:

    find . -name '*FooBar*' -exec cp -t ~/foobar -- {} +
    

    however, some commands don't have such feature.

The disadvantages:

  • Maybe not scale well if there are too many file names. (The limit? I don't know, but I had tested with 10 MB list file which includes 10000+ file names with no problem, under Debian)

Well... who knows if Bash is available on OS X?

How to delete Certain Characters in a excel 2010 cell

Replace [ with nothing, then ] with nothing.

How to open/run .jar file (double-click not working)?

You may have several JDKs installed in your PC. Some older JDK installers also copy some java files such as java.exe, javaw.exe into C:\Windows\System32 folder.

I had a similar issue, and searched the internet for a solution and none of the suggestions didn’t open by double clicking the .jar file.

In my case the reason is I have multiple JDK & JRE versions installed on my computer. Since I am a software developer working with several different versions for different clients I need to use multiple JDKs in my PC (Windows 10 Pro). So I do not want to change the system variables (i.e. JAVA_HOME, JRE_HOME or PATH), instead I use command prompt to run java in user process whenever I wanted to use a different version.

When installing JDK it registers the .jar file association with latest version we installed in the PC. If you right click on the .jar icon and select properties, it will show that file opens with “Java(TM) Platform SE Binary”. If we look at the registry key: HKEY_CLASSES_ROOT\jarfile\shell\open\command, it will point to latest JDK version.

It is not a good idea (sometimes annoying) to change the registry key every time I want to run an app build from a different version.

So in my situation it is impossible to just double click the .jar file to execute it. But instead I found a work around solution myself.

Scenario:

Multiple JDKs (1.7, 1.8, 9.0, 10.0, 11.0, and 12.0)are installed in the PC, so the latest installed was 12.0.

Problem

Want to double click an executable .jar developed using JDK 1.8 and didn’t work

This is my work around solution:

  1. Create a shortcut for the .jar file that you want to open.

  2. Right click the shortcut icon and select properties -> Shortcut tab

  3. Change the text in the target (for example "D:\Dev\JavaApp1.8.jar") To

    "C:\Program Files\Java\jdk1.8.0\bin\javaw.exe" -jar "D:\Dev\JavaApp1.8.jar"

  4. Then click ok Double click the shortcut.

It should now open the app.

Bootstrap button drop-down inside responsive table not visible because of scroll

This worked for me in Bootstrap 4 since it has different breakpoints than v3:

@media (min-width: 992px) {
    .table-responsive {
        overflow: inherit;
    }
}

How to convert a timezone aware string to datetime in Python without dateutil?

There are two issues with the code in the original question: there should not be a : in the timezone and the format string for "timezone as an offset" is lower case %z not upper %Z.

This works for me in Python v3.6

>>> from datetime import datetime
>>> t = datetime.strptime("2012-11-01T04:16:13-0400", "%Y-%m-%dT%H:%M:%S%z")
>>> print(t)
2012-11-01 04:16:13-04:00

Print commit message of a given commit in git

It's not "plumbing", but it'll do exactly what you want:

$ git log --format=%B -n 1 <commit>

If you absolutely need a "plumbing" command (not sure why that's a requirement), you can use rev-list:

$ git rev-list --format=%B --max-count=1 <commit>

Although rev-list will also print out the commit sha (on the first line) in addition to the commit message.

Getting time elapsed in Objective-C

Use the timeIntervalSinceDate method

NSTimeInterval secondsElapsed = [secondDate timeIntervalSinceDate:firstDate];

NSTimeInterval is just a double, define in NSDate like this:

typedef double NSTimeInterval;

How to create nested directories using Mkdir in Golang?

This is one alternative for achieving the same but it avoids race condition caused by having two distinct "check ..and.. create" operations.

package main

import (
    "fmt"
    "os"
)

func main()  {
    if err := ensureDir("/test-dir"); err != nil {
        fmt.Println("Directory creation failed with error: " + err.Error())
        os.Exit(1)
    }
    // Proceed forward
}

func ensureDir(dirName string) error {

    err := os.MkdirAll(dirName, os.ModeDir)

    if err == nil || os.IsExist(err) {
        return nil
    } else {
        return err
    }
}

How to get the width of a react element

A simple and up to date solution is to use the React React useRef hook that stores a reference to the component/element, combined with a useEffect hook, which fires at component renders.

import React, {useState, useEffect, useRef} from 'react';

export default App = () => {
  const [width, setWidth] = useState(0);
  const elementRef = useRef(null);

  useEffect(() => {
    setWidth(elementRef.current.getBoundingClientRect().width);
  }, []); //empty dependency array so it only runs once at render

  return (
    <div ref={elementRef}>
      {width}
    </div>
  )
}

What is the PostgreSQL equivalent for ISNULL()

How do I emulate the ISNULL() functionality ?

SELECT (Field IS NULL) FROM ...

How to stretch div height to fill parent div - CSS

http://jsfiddle.net/QWDxr/1/

Use the "min-height" property
Be wary of paddings, margins and borders :)

html, body {
    margin: 0;
    padding: 0;
    border: 0;
}
#B, #C, #D {
    position: absolute;
}
#A{
    top: 0;
    width: 100%;
    height: 35px;
    background-color: #99CC00;
}
#B {
    top: 35px;
    width: 200px;
    bottom: 35px;
    background-color: #999999;
    z-index:100;
}
#B2 {
    min-height: 100%;
    height: 100%;
    margin-top: -35px;
    bottom: 0;
    background-color: red;
    width: 200px;
    overflow: scroll;
}
#B1 {
    height: 35px;
    width: 35px;
    margin-left: 200px;
    background-color: #CC0066;
}
#C {
    top: 35px;
    left: 200px;
    right: 0;
    bottom: 35px;
    background-color: #CCCCCC;
}
#D {
    bottom: 0;
    width: 100%;
    height: 35px;
    background-color: #3399FF;
}

cmd line rename file with date and time

problem in %time:~0,2% can't set to 24 hrs format, ended with space(1-9), instead of 0(1-9)

go around with:

set HR=%time:~0,2%

set HR=%Hr: =0% (replace space with 0 if any <has a space in between : =0>)

then replace %time:~0,2% with %HR%

good luck

Cannot truncate table because it is being referenced by a FOREIGN KEY constraint?

You cannot truncate a table if you don't drop the constraints. A disable also doesn't work. you need to Drop everything. i've made a script that drop all constrainsts and then recreate then.

Be sure to wrap it in a transaction ;)

SET NOCOUNT ON
GO

DECLARE @table TABLE(
RowId INT PRIMARY KEY IDENTITY(1, 1),
ForeignKeyConstraintName NVARCHAR(200),
ForeignKeyConstraintTableSchema NVARCHAR(200),
ForeignKeyConstraintTableName NVARCHAR(200),
ForeignKeyConstraintColumnName NVARCHAR(200),
PrimaryKeyConstraintName NVARCHAR(200),
PrimaryKeyConstraintTableSchema NVARCHAR(200),
PrimaryKeyConstraintTableName NVARCHAR(200),
PrimaryKeyConstraintColumnName NVARCHAR(200)
)

INSERT INTO @table(ForeignKeyConstraintName, ForeignKeyConstraintTableSchema, ForeignKeyConstraintTableName, ForeignKeyConstraintColumnName)
SELECT
U.CONSTRAINT_NAME,
U.TABLE_SCHEMA,
U.TABLE_NAME,
U.COLUMN_NAME
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE U
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C
ON U.CONSTRAINT_NAME = C.CONSTRAINT_NAME
WHERE
C.CONSTRAINT_TYPE = 'FOREIGN KEY'

UPDATE @table SET
PrimaryKeyConstraintName = UNIQUE_CONSTRAINT_NAME
FROM
@table T
INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS R
ON T.ForeignKeyConstraintName = R.CONSTRAINT_NAME

UPDATE @table SET
PrimaryKeyConstraintTableSchema = TABLE_SCHEMA,
PrimaryKeyConstraintTableName = TABLE_NAME
FROM @table T
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C
ON T.PrimaryKeyConstraintName = C.CONSTRAINT_NAME

UPDATE @table SET
PrimaryKeyConstraintColumnName = COLUMN_NAME
FROM @table T
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE U
ON T.PrimaryKeyConstraintName = U.CONSTRAINT_NAME

--DROP CONSTRAINT:

DECLARE @dynSQL varchar(MAX);

DECLARE cur CURSOR FOR
SELECT
'
ALTER TABLE [' + ForeignKeyConstraintTableSchema + '].[' + ForeignKeyConstraintTableName + ']
DROP CONSTRAINT ' + ForeignKeyConstraintName + '
'
FROM
@table

OPEN cur

FETCH cur into @dynSQL
WHILE @@FETCH_STATUS = 0 
BEGIN
    exec(@dynSQL)
    print @dynSQL

    FETCH cur into @dynSQL
END
CLOSE cur
DEALLOCATE cur
---------------------



   --HERE GOES YOUR TRUNCATES!!!!!
   --HERE GOES YOUR TRUNCATES!!!!!
   --HERE GOES YOUR TRUNCATES!!!!!

    truncate table your_table

   --HERE GOES YOUR TRUNCATES!!!!!
   --HERE GOES YOUR TRUNCATES!!!!!
   --HERE GOES YOUR TRUNCATES!!!!!

---------------------
--ADD CONSTRAINT:

DECLARE cur2 CURSOR FOR
SELECT
'
ALTER TABLE [' + ForeignKeyConstraintTableSchema + '].[' + ForeignKeyConstraintTableName + ']
ADD CONSTRAINT ' + ForeignKeyConstraintName + ' FOREIGN KEY(' + ForeignKeyConstraintColumnName + ') REFERENCES [' + PrimaryKeyConstraintTableSchema + '].[' + PrimaryKeyConstraintTableName + '](' + PrimaryKeyConstraintColumnName + ')
'
FROM
@table

OPEN cur2

FETCH cur2 into @dynSQL
WHILE @@FETCH_STATUS = 0 
BEGIN
    exec(@dynSQL)

    print @dynSQL

    FETCH cur2 into @dynSQL
END
CLOSE cur2
DEALLOCATE cur2

Git push/clone to new server

You can push a branch to a remote server, say github. You would first have to do the initial project setup, then clone your project and:

git push <remote repo> <your branch>

Java collections convert a string to a list of characters

List<String> result = Arrays.asList("abc".split(""));

Using Regular Expressions to Extract a Value in Java

Simple Solution

// Regexplanation:
// ^       beginning of line
// \\D+    1+ non-digit characters
// (\\d+)  1+ digit characters in a capture group
// .*      0+ any character
String regexStr = "^\\D+(\\d+).*";

// Compile the regex String into a Pattern
Pattern p = Pattern.compile(regexStr);

// Create a matcher with the input String
Matcher m = p.matcher(inputStr);

// If we find a match
if (m.find()) {
    // Get the String from the first capture group
    String someDigits = m.group(1);
    // ...do something with someDigits
}

Solution in a Util Class

public class MyUtil {
    private static Pattern pattern = Pattern.compile("^\\D+(\\d+).*");
    private static Matcher matcher = pattern.matcher("");

    // Assumptions: inputStr is a non-null String
    public static String extractFirstNumber(String inputStr){
        // Reset the matcher with a new input String
        matcher.reset(inputStr);

        // Check if there's a match
        if(matcher.find()){
            // Return the number (in the first capture group)
            return matcher.group(1);
        }else{
            // Return some default value, if there is no match
            return null;
        }
    }
}

...

// Use the util function and print out the result
String firstNum = MyUtil.extractFirstNumber("Testing4234Things");
System.out.println(firstNum);

Error With Port 8080 already in use

on Mac, how I usually solve it

  1. open terminal and cd to downloaded-apache-files-folder/bin (i.e to the folder where shutdown.sh file is located)
  2. enter "sh shutdown.sh" as a terminal command
  3. restart Tomcat/Eclipse..tada!

Hope this helps OP or someone else reading

How can I deploy an iPhone application from Xcode to a real iPhone device?

Nothing I've seen anywhere indicates you can ad-hoc deploy to a real iPhone without a (paid for) certificate.

Batch Renaming of Files in a Directory

directoryName = "Photographs"
filePath = os.path.abspath(directoryName)
filePathWithSlash = filePath + "\\"

for counter, filename in enumerate(os.listdir(directoryName)):

    filenameWithPath = os.path.join(filePathWithSlash, filename)

    os.rename(filenameWithPath, filenameWithPath.replace(filename,"DSC_" + \
          str(counter).zfill(4) + ".jpg" ))

# e.g. filename = "photo1.jpg", directory = "c:\users\Photographs"        
# The string.replace call swaps in the new filename into 
# the current filename within the filenameWitPath string. Which    
# is then used by os.rename to rename the file in place, using the  
# current (unmodified) filenameWithPath.

# os.listdir delivers the filename(s) from the directory
# however in attempting to "rename" the file using os 
# a specific location of the file to be renamed is required.

# this code is from Windows 

Certificate is trusted by PC but not by Android

I had the same problem. Another way to generate the correct .crt file is like this:

Sometimes you get a .PEM file with an entire certificate chain inside. The file may look like this....

-----BEGIN RSA PRIVATE KEY-----
blablablabase64private...
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
blablablabase64CRT1...
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
blablablabase64CRT2...
-----END CERTIFICATE-----
...

If you remove the entire private key section, you will have a valid chained .crt

What does 'x packages are looking for funding' mean when running `npm install`?

npm decided to add a new command: npm fund that will provide more visibility to npm users on what dependencies are actively looking for ways to fund their work.

npm install will also show a single message at the end in order to let user aware that dependencies are looking for funding, it looks like this:

$ npm install
packages are looking for funding.
run `npm fund` for details.

Running npm fund <package> will open the url listed for that given package right in your browser.

For more details look here

When should you use 'friend' in C++?

edit: Reading the faq a bit longer I like the idea of the << >> operator overloading and adding as a friend of those classes, however I am not sure how this doesn't break encapsulation

How would it break encapsulation?

You break encapsulation when you allow unrestricted access to a data member. Consider the following classes:

class c1 {
public:
  int x;
};

class c2 {
public:
  int foo();
private:
  int x;
};

class c3 {
  friend int foo();
private:
  int x;
};

c1 is obviously not encapsulated. Anyone can read and modify x in it. We have no way to enforce any kind of access control.

c2 is obviously encapsulated. There is no public access to x. All you can do is call the foo function, which performs some meaningful operation on the class.

c3? Is that less encapsulated? Does it allow unrestricted access to x? Does it allow unknown functions access?

No. It allows precisely one function to access the private members of the class. Just like c2 did. And just like c2, the one function which has access is not "some random, unknown function", but "the function listed in the class definition". Just like c2, we can see, just by looking at the class definitions, a complete list of who has access.

So how exactly is this less encapsulated? The same amount of code has access to the private members of the class. And everyone who has access is listed in the class definition.

friend does not break encapsulation. It makes some Java people programmers feel uncomfortable, because when they say "OOP", they actually mean "Java". When they say "Encapsulation", they don't mean "private members must be protected from arbitrary accesses", but "a Java class where the only functions able to access private members, are class members", even though this is complete nonsense for several reasons.

First, as already shown, it is too restricting. There's no reason why friend methods shouldn't be allowed to do the same.

Second, it is not restrictive enough. Consider a fourth class:

class c4 {
public:
  int getx();
  void setx(int x);
private:
  int x;
};

This, according to aforesaid Java mentality, is perfectly encapsulated. And yet, it allows absolutely anyone to read and modify x. How does that even make sense? (hint: It doesn't)

Bottom line: Encapsulation is about being able to control which functions can access private members. It is not about precisely where the definitions of these functions are located.

How do I sort an observable collection?

You can use this simple method:

public static void Sort<TSource, TKey>(this Collection<TSource> source, Func<TSource, TKey> keySelector)
{
    List<TSource> sortedList = source.OrderBy(keySelector).ToList();
    source.Clear();
    foreach (var sortedItem in sortedList)
        source.Add(sortedItem);
}

You can sort like this:

_collection.Sort(i => i.Key);

Find row number of matching value

For your first method change ws.Range("A") to ws.Range("A:A") which will search the entirety of column a, like so:

Sub Find_Bingo()

        Dim wb As Workbook
        Dim ws As Worksheet
        Dim FoundCell As Range
        Set wb = ActiveWorkbook
        Set ws = ActiveSheet

            Const WHAT_TO_FIND As String = "Bingo"

            Set FoundCell = ws.Range("A:A").Find(What:=WHAT_TO_FIND)
            If Not FoundCell Is Nothing Then
                MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row)
            Else
                MsgBox (WHAT_TO_FIND & " not found")
            End If
End Sub

For your second method, you are using Bingo as a variable instead of a string literal. This is a good example of why I add Option Explicit to the top of all of my code modules, as when you try to run the code it will direct you to this "variable" which is undefined and not intended to be a variable at all.

Additionally, when you are using With...End With you need a period . before you reference Cells, so Cells should be .Cells. This mimics the normal qualifying behavior (i.e. Sheet1.Cells.Find..)

Change Bingo to "Bingo" and change Cells to .Cells

With Sheet1
        Set FoundCell = .Cells.Find(What:="Bingo", After:=.Cells(1, 1), _
        LookIn:=xlValues, lookat:=xlPart, SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
    End With

If Not FoundCell Is Nothing Then
        MsgBox ("""Bingo"" found in row " & FoundCell.Row)
Else
        MsgBox ("Bingo not found")
End If

Update

In my

With Sheet1
    .....
End With

The Sheet1 refers to a worksheet's code name, not the name of the worksheet itself. For example, say I open a new blank Excel workbook. The default worksheet is just Sheet1. I can refer to that in code either with the code name of Sheet1 or I can refer to it with the index of Sheets("Sheet1"). The advantage to using a codename is that it does not change if you change the name of the worksheet.

Continuing this example, let's say I renamed Sheet1 to Data. Using Sheet1 would continue to work, as the code name doesn't change, but now using Sheets("Sheet1") would return an error and that syntax must be updated to the new name of the sheet, so it would need to be Sheets("Data").

In the VB Editor you would see something like this:

code object explorer example

Notice how, even though I changed the name to Data, there is still a Sheet1 to the left. That is what I mean by codename.

The Data worksheet can be referenced in two ways:

Debug.Print Sheet1.Name
Debug.Print Sheets("Data").Name

Both should return Data

More discussion on worksheet code names can be found here.

How to see JavaDoc in IntelliJ IDEA?

For me, it wasn't just getting the javadoc window to open, but also getting the complete javadoc to present. You may still get a sparse javadoc that is based solely on the method signature if you are importing libraries from a Maven repository and do not tell Idea to include the javadocs in the download. Be sure to tick the "JavaDocs" option in the "Download Library From Maven Repository" dialog, which can be found under Project Structure -> Projtect Settings -> Libraries.

jquery save json data object in cookie

Try this one: https://github.com/tantau-horia/jquery-SuperCookie

Quick Usage:

create - create cookie

check - check existance

verify - verify cookie value if JSON

check_index - verify if index exists in JSON

read_values - read cookie value as string

read_JSON - read cookie value as JSON object

read_value - read value of index stored in JSON object

replace_value - replace value from a specified index stored in JSON object

remove_value - remove value and index stored in JSON object

Just use:

$.super_cookie().create("name_of_the_cookie",name_field_1:"value1",name_field_2:"value2"});
$.super_cookie().read_json("name_of_the_cookie");

How to configure the web.config to allow requests of any length

I had to add [AllowAnonymous] to the ActionResult functions in my login page because the user was not authenticated yet.

create a trusted self-signed SSL cert for localhost (for use with Express/Node)

Mkcert from @FiloSottile makes this process infinitely simpler:

  1. Install mkcert, there are instructions for macOS/Windows/Linux
  2. mkcert -install to create a local CA
  3. mkcert localhost 127.0.0.1 ::1 to create a trusted cert for localhost in the current directory
  4. You're using node (which doesn't use the system root store), so you need to specify the CA explicitly in an environment variable, e.g: export NODE_EXTRA_CA_CERTS="$(mkcert -CAROOT)/rootCA.pem"
  5. Finally run your express server using the setup described in various other answers (e.g. below)
  6. boom. localhost's swimming in green.

Basic node setup:

const https = require('https');
const fs = require('fs');
const express = require('express');

const app = express();    
const server = https.createServer({
    key: fs.readFileSync('/XXX/localhost+2-key.pem'), // where's me key?
    cert: fs.readFileSync('/XXX/localhost+2.pem'), // where's me cert?
    requestCert: false,
    rejectUnauthorized: false,
}, app).listen(10443); // get creative

What is the (best) way to manage permissions for Docker shared volumes?

This is arguably not the best way for most circumstances, but it's not been mentioned yet so perhaps it will help someone.

  1. Bind mount host volume

    Host folder FOOBAR is mounted in container /volume/FOOBAR

  2. Modify your container's startup script to find GID of the volume you're interested in

    $ TARGET_GID=$(stat -c "%g" /volume/FOOBAR)

  3. Ensure your user belongs to a group with this GID (you may have to create a new group). For this example I'll pretend my software runs as the nobody user when inside the container, so I want to ensure nobody belongs to a group with a group id equal to TARGET_GID

  EXISTS=$(cat /etc/group | grep $TARGET_GID | wc -l)

  # Create new group using target GID and add nobody user
  if [ $EXISTS == "0" ]; then
    groupadd -g $TARGET_GID tempgroup
    usermod -a -G tempgroup nobody
  else
    # GID exists, find group name and add
    GROUP=$(getent group $TARGET_GID | cut -d: -f1)
    usermod -a -G $GROUP nobody
  fi

I like this because I can easily modify group permissions on my host volumes and know that those updated permissions apply inside the docker container. This happens without any permission or ownership modifications to my host folders/files, which makes me happy.

I don't like this because it assumes there's no danger in adding yourself to an arbitrary groups inside the container that happen to be using a GID you want. It cannot be used with a USER clause in a Dockerfile (unless that user has root privileges I suppose). Also, it screams hack job ;-)

If you want to be hardcore you can obviously extend this in many ways - e.g. search for all groups on any subfiles, multiple volumes, etc.

scrollTop jquery, scrolling to div with id?

instead of

$('html, body').animate({scrollTop:xxx}, 'slow');

use

$('html, body').animate({scrollTop:$('#div_id').position().top}, 'slow');

this will return the absolute top position of whatever element you select as #div_id

PHP cURL custom headers

$subscription_key  ='';
    $host = '';    
    $request_headers = array(
                    "X-Mashape-Key:" . $subscription_key,
                    "X-Mashape-Host:" . $host
                );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);

    $season_data = curl_exec($ch);

    if (curl_errno($ch)) {
        print "Error: " . curl_error($ch);
        exit();
    }

    // Show me the result
    curl_close($ch);
    $json= json_decode($season_data, true);

Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++

OCV goes out of its way to make sure you can't do this without knowing the element type, but if you want an easily codable but not-very-efficient way to read it type-agnostically, you can use something like

double val=mean(someMat(Rect(x,y,1,1)))[channel];

To do it well, you do have to know the type though. The at<> method is the safe way, but direct access to the data pointer is generally faster if you do it correctly.

Change the row color in DataGridView based on the quantity of a cell value

Using the CellFormating event and the e argument:

If CInt(e.Value) < 5 Then e.CellStyle.ForeColor = Color.Red

SQL exclude a column using SELECT * [except columnA] FROM tableA?

If you're using mysql-workbench, you can right click on the table explorer and click on "Send to SQL editor->Select all statement".

It sends a statement like "Select col1, col2,... from tablename".

Then remove those that you don't need.

Why is enum class preferred over plain enum?

The basic advantage of using enum class over normal enums is that you may have same enum variables for 2 different enums and still can resolve them(which has been mentioned as type safe by OP)

For eg:

enum class Color1 { red, green, blue };    //this will compile
enum class Color2 { red, green, blue };

enum Color1 { red, green, blue };    //this will not compile 
enum Color2 { red, green, blue };

As for the basic enums, compiler will not be able to distinguish whether red is refering to the type Color1 or Color2 as in hte below statement.

enum Color1 { red, green, blue };   
enum Color2 { red, green, blue };
int x = red;    //Compile time error(which red are you refering to??)

How to open new browser window on button click event?

It can be done all on the client-side using the OnClientClick[MSDN] event handler and window.open[MDN]:

<asp:Button 
     runat="server" 
     OnClientClick="window.open('http://www.stackoverflow.com'); return false;">
     Open a new window!
</asp:Button>

Changing case in Vim

Visual select the text, then U for uppercase or u for lowercase. To swap all casing in a visual selection, press ~ (tilde).

Without using a visual selection, gU<motion> will make the characters in motion uppercase, or use gu<motion> for lowercase.

For more of these, see Section 3 in Vim's change.txt help file.

Create a tar.xz in one command

Try this: tar -cf file.tar file-to-compress ; xz -z file.tar

Note:

  1. tar.gz and tar.xz are not the same; xz provides better compression.
  2. Don't use pipe | because this runs commands simultaneously. Using ; or & executes commands one after another.

Check if textbox has empty value

if ( $("#txt").val().length == 0 )
{
  // do something
}

I had to add in the == to get it to work for me, otherwise it ignored the condition even with empty text input. May help someone.

How to add values in a variable in Unix shell scripting?

Here's a simple example to add two variables:

var1=4
var2=3
let var3=$var1+$var2
echo $var3

Regular Expression for any number greater than 0?

I think the best solution is to add the + sign between the two brackets of regex expression:

^[1-9]+[0-9]*$

Symfony - generate url with parameter in controller

make sure your controller extends Symfony\Bundle\FrameworkBundle\Controller\Controller;

you should also check app/console debug:router in terminal to see what name symfony has named the route

in my case it used a minus instead of an underscore

i.e blog-show

$uri = $this->generateUrl('blog-show', ['slug' => 'my-blog-post']);

Specify multiple attribute selectors in CSS

Simple input[name=Sex][value=M] would do pretty nice. And it's actually well-described in the standard doc:

Multiple attribute selectors can be used to refer to several attributes of an element, or even several times to the same attribute.

Here, the selector matches all SPAN elements whose "hello" attribute has exactly the value "Cleveland" and whose "goodbye" attribute has exactly the value "Columbus":

span[hello="Cleveland"][goodbye="Columbus"] { color: blue; }

As a side note, using quotation marks around an attribute value is required only if this value is not a valid identifier.

JSFiddle Demo

Oracle - How to generate script from sql developer

step 1. select * from <tablename>;

step 2. just right click on your output(t.e data) then go to last option export it will give u some extension then click on your required extension then apply u will get new file including data.

How do I run pip on python for windows?

First go to the pip documentation if not install before: http://pip.readthedocs.org/en/stable/installing/

and follow the install pip which is first download get-pip.py from https://bootstrap.pypa.io/get-pip.py

Then run the following (which may require administrator access): python get-pip.py

Is there a way to view two blocks of code from the same file simultaneously in Sublime Text?

In the nav go View => Layout => Columns:2 (alt+shift+2) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py)

It appears you can also reopen the file using the command File -> New View into File which will open the current file in a new tab

Display MessageBox in ASP

<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
    alert("Hello!");
}
</script>

</body>
</html>

Copy Paste this in an HTML file and run in any browser , this should show an alert using javascript.

Remove all the elements that occur in one list from another

Try this:

l1=[1,2,6,8]
l2=[2,3,5,8]
r=[]
for x in l1:
    if x in l2:
        continue
    r=r+[x]
print(r)

Creating a class object in c++

I can use the same in c++ like this [...] Where constructor is compulsory. From this tutorial I got that we can create object like this [...] Which do not require an constructor.

This is wrong. A constructor must exist in order to create an object. The constructor could be defined implicitly by the compiler under some conditions if you do not provide any, but eventually the constructor must be there if you want an object to be instantiated. In fact, the lifetime of an object is defined to begin when the constructor routine returns.

From Paragraph 3.8/1 of the C++11 Standard:

[...] The lifetime of an object of type T begins when:

— storage with the proper alignment and size for type T is obtained, and

— if the object has non-trivial initialization, its initialization is complete.

Therefore, a constructor must be present.

1) What is the difference between both the way of creating class objects.

When you instantiate object with automatic storage duration, like this (where X is some class):

X x;

You are creating an object which will be automatically destroyed when it goes out of scope. On the other hand, when you do:

X* x = new X();

You are creating an object dynamically and you are binding its address to a pointer. This way, the object you created will not be destroyed when your x pointer goes out of scope.

In Modern C++, this is regarded as a dubious programming practice: although pointers are important because they allow realizing reference semantics, raw pointers are bad because they could result in memory leaks (objects outliving all of their pointers and never getting destroyed) or in dangling pointers (pointers outliving the object they point to, potentially causing Undefined Behavior when dereferenced).

In fact, when creating an object with new, you always have to remember destroying it with delete:

delete x;

If you need reference semantics and are forced to use pointers, in C++11 you should consider using smart pointers instead:

std::shared_ptr<X> x = std::make_shared<X>();

Smart pointers take care of memory management issues, which is what gives you headache with raw pointers. Smart pointers are, in fact, almost the same as Java or C# object references. The "almost" is necessary because the programmer must take care of not introducing cyclic dependencies through owning smart pointers.

2) If i am creating object like Example example; how to use that in an singleton class.

You could do something like this (simplified code):

struct Example
{
    static Example& instance()
    {
        static Example example;
        return example;
    }

 private:

    Example() { }
    Example(Example const&) = delete;
    Example(Example&&) = delete;
    Example& operator = (Example const&) = delete;
    Example& operator = (Example&&) = delete;

};

How does one sum only those rows in excel not filtered out?

You need to use the SUBTOTAL function. The SUBTOTAL function ignores rows that have been excluded by a filter.

The formula would look like this:

=SUBTOTAL(9,B1:B20)

The function number 9, tells it to use the SUM function on the data range B1:B20.

If you are 'filtering' by hiding rows, the function number should be updated to 109.

=SUBTOTAL(109,B1:B20)

The function number 109 is for the SUM function as well, but hidden rows are ignored.

Unable to open debugger port in IntelliJ

For me, the problem was that catalina.sh didnt have execute permissions. The "Unable to open debugger port in intellij" message appeared in Intellij, but it sort of masked the 'could not execute catalina.sh' error that appeared in the logs immediately prior.

What's the valid way to include an image with no src?

I found that simply setting the src to an empty string and adding a rule to your CSS to hide the broken image icon works just fine.

[src=''] {
    visibility: hidden;
}

Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android

  1. If you have android studio installed within your system, then copy the templates folder from C:\Program Files\Android\Android Studio\plugins\android\lib\templates
  2. Paste it in the folder C:\Users\<user-name>\AppData\Local\Android\sdk\tools
  3. Run the command: ionic build android

All necessary jar files will be downloaded and apk file for the application will be generated.

Note: Set environment variables to C:\Users\<user-name>\AppData\Local\Android\sdk\tools. Also set user-name to your current username.

How can I combine two HashMap objects containing the same types?

You can use putAll function for Map as explained in the code below

HashMap<String, Integer> map1 = new HashMap<String, Integer>();
map1.put("a", 1);
map1.put("b", 2);
map1.put("c", 3);
HashMap<String, Integer> map2 = new HashMap<String, Integer>();
map1.put("aa", 11);
map1.put("bb", 12);
HashMap<String, Integer> map3 = new HashMap<String, Integer>();
map3.putAll(map1);
map3.putAll(map2);
map3.keySet().stream().forEach(System.out::println);
map3.values().stream().forEach(System.out::println);

generate random double numbers in c++

This should be performant, thread-safe and flexible enough for many uses:

#include <random>
#include <iostream>

template<typename Numeric, typename Generator = std::mt19937>
Numeric random(Numeric from, Numeric to)
{
    thread_local static Generator gen(std::random_device{}());

    using dist_type = typename std::conditional
    <
        std::is_integral<Numeric>::value
        , std::uniform_int_distribution<Numeric>
        , std::uniform_real_distribution<Numeric>
    >::type;

    thread_local static dist_type dist;

    return dist(gen, typename dist_type::param_type{from, to});
}

int main(int, char*[])
{
    for(auto i = 0U; i < 20; ++i)
        std::cout << random<double>(0.0, 0.3) << '\n';
}

JUnit assertEquals(double expected, double actual, double epsilon)

Epsilon is your "fuzz factor," since doubles may not be exactly equal. Epsilon lets you describe how close they have to be.

If you were expecting 3.14159 but would take anywhere from 3.14059 to 3.14259 (that is, within 0.001), then you should write something like

double myPi = 22.0d / 7.0d; //Don't use this in real life!
assertEquals(3.14159, myPi, 0.001);

(By the way, 22/7 comes out to 3.1428+, and would fail the assertion. This is a good thing.)

How do I compare a value to a backslash?

If message.value[] is string:

if message.value[0] in ('/', '\'):
    do_stuff()

If it not str

Show values from a MySQL database table inside a HTML table on a webpage

Try this: (Completely Dynamic...)

<?php
$host    = "localhost";
$user    = "username_here";
$pass    = "password_here";
$db_name = "database_name_here";

//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);

//test if connection failed
if(mysqli_connect_errno()){
    die("connection failed: "
        . mysqli_connect_error()
        . " (" . mysqli_connect_errno()
        . ")");
}

//get results from database
$result = mysqli_query($connection,"SELECT * FROM products");
$all_property = array();  //declare an array for saving property

//showing property
echo '<table class="data-table">
        <tr class="data-heading">';  //initialize table tag
while ($property = mysqli_fetch_field($result)) {
    echo '<td>' . $property->name . '</td>';  //get field name for header
    array_push($all_property, $property->name);  //save those to array
}
echo '</tr>'; //end tr tag

//showing all data
while ($row = mysqli_fetch_array($result)) {
    echo "<tr>";
    foreach ($all_property as $item) {
        echo '<td>' . $row[$item] . '</td>'; //get items using property value
    }
    echo '</tr>';
}
echo "</table>";
?>

How to pass a form input value into a JavaScript function

Use onclick="foo(document.getElementById('formValueId').value)"

Ellipsis for overflow text in dropdown boxes

I used this approach in a recent project and I was pretty happy with the result:

.select-wrapper {
    position: relative;
    &::after {
        position: absolute;
        top: 0;
        right: 0;
        width: 100px;
        height: 100%;
        content: "";
        background: linear-gradient(to right, transparent, white);
        pointer-events: none;
    }
}

Basically, wrap the select in a div and insert a pseudo element to overlay the end of the text to create the appearance that the text fades out.

enter image description here

Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

Along with the embed, I also had to install the Google Cast extension in my browser.

<iframe width="1280" height="720" src="https://www.youtube.com/embed/4u856utdR94" frameborder="0" allowfullscreen></iframe>

Uninstall Node.JS using Linux command line?

Sorry the answer of George Bailey does work very fine when you want absolutely remove the node from your machine.

This answer is referred from : @tedeh https://github.com/nodesource/distributions/issues/486

If you wanna install a new version of node you have to use the code below

sudo rm -rf /var/cache/yum
sudo yum remove -y nodejs
sudo rm /etc/yum.repos.d/nodesource*
sudo yum clean all

And add new nodejs version to "yum" an new version of node

#using this command for Node version 8
curl --silent --location https://rpm.nodesource.com/setup_8.x | sudo bash -

#using this command for Node version 10
curl --silent --location https://rpm.nodesource.com/setup_10.x | sudo bash -

Install nodejs

sudo yum -y install nodejs

I hope it gonna help you guy!!!

Codesign error: Provisioning profile cannot be found after deleting expired profile

I was having issues because I updated my AdHoc provisioning profile with some new devices for use on TestFlight. Assumedly this is happening because Xcode has an old reference to your provisioning profile in either the codesigning build settings for the project or the targets. The way I fixed mine was to:

  1. Go to both target build settings and project build settings, Under code signing change all the provisioning profiles to something else.
  2. Go to devices/provisioning profiles in the Organizer delete the offending profiles, then click the refresh button in the bottom right.
  3. Go back to to the target and project build settings and set your provisioning profiles to the appropriate (hopefully) newly refreshed provisioning profiles.

Difference between Divide and Conquer Algo and Dynamic Programming

Dynamic Programming and Divide-and-Conquer Similarities

As I see it for now I can say that dynamic programming is an extension of divide and conquer paradigm.

I would not treat them as something completely different. Because they both work by recursively breaking down a problem into two or more sub-problems of the same or related type, until these become simple enough to be solved directly. The solutions to the sub-problems are then combined to give a solution to the original problem.

So why do we still have different paradigm names then and why I called dynamic programming an extension. It is because dynamic programming approach may be applied to the problem only if the problem has certain restrictions or prerequisites. And after that dynamic programming extends divide and conquer approach with memoization or tabulation technique.

Let’s go step by step…

Dynamic Programming Prerequisites/Restrictions

As we’ve just discovered there are two key attributes that divide and conquer problem must have in order for dynamic programming to be applicable:

  • Optimal substructure — optimal solution can be constructed from optimal solutions of its subproblems

  • Overlapping sub-problems — problem can be broken down into subproblems which are reused several times or a recursive algorithm for the problem solves the same subproblem over and over rather than always generating new subproblems

Once these two conditions are met we can say that this divide and conquer problem may be solved using dynamic programming approach.

Dynamic Programming Extension for Divide and Conquer

Dynamic programming approach extends divide and conquer approach with two techniques (memoization and tabulation) that both have a purpose of storing and re-using sub-problems solutions that may drastically improve performance. For example naive recursive implementation of Fibonacci function has time complexity of O(2^n) where DP solution doing the same with only O(n) time.

Memoization (top-down cache filling) refers to the technique of caching and reusing previously computed results. The memoized fib function would thus look like this:

memFib(n) {
    if (mem[n] is undefined)
        if (n < 2) result = n
        else result = memFib(n-2) + memFib(n-1)
        
        mem[n] = result
    return mem[n]
}

Tabulation (bottom-up cache filling) is similar but focuses on filling the entries of the cache. Computing the values in the cache is easiest done iteratively. The tabulation version of fib would look like this:

tabFib(n) {
    mem[0] = 0
    mem[1] = 1
    for i = 2...n
        mem[i] = mem[i-2] + mem[i-1]
    return mem[n]
}

You may read more about memoization and tabulation comparison here.

The main idea you should grasp here is that because our divide and conquer problem has overlapping sub-problems the caching of sub-problem solutions becomes possible and thus memoization/tabulation step up onto the scene.

So What the Difference Between DP and DC After All

Since we’re now familiar with DP prerequisites and its methodologies we’re ready to put all that was mentioned above into one picture.

Dynamic Programming vs Divide-and-Conquer

If you want to see code examples you may take a look at more detailed explanation here where you'll find two algorithm examples: Binary Search and Minimum Edit Distance (Levenshtein Distance) that are illustrating the difference between DP and DC.

Where are static methods and static variables stored in Java?

When we create a static variable or method it is stored in the special area on heap: PermGen(Permanent Generation), where it lays down with all the data applying to classes(non-instance data). Starting from Java 8 the PermGen became - Metaspace. The difference is that Metaspace is auto-growing space, while PermGen has a fixed Max size, and this space is shared among all of the instances. Plus the Metaspace is a part of a Native Memory and not JVM Memory.

You can look into this for more details.

Should import statements always be at the top of a module?

Putting the import statement inside of a function can prevent circular dependencies. For example, if you have 2 modules, X.py and Y.py, and they both need to import each other, this will cause a circular dependency when you import one of the modules causing an infinite loop. If you move the import statement in one of the modules then it won't try to import the other module till the function is called, and that module will already be imported, so no infinite loop. Read here for more - effbot.org/zone/import-confusion.htm

Using jQuery to compare two arrays of Javascript objects

I was also looking for this today and found: http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256BFB0077DFFD

Don't know if that's a good solution though they do mention some performance considerations taken into account.

I like the idea of a jQuery helper method. @David I'd rather see your compare method to work like:

jQuery.compare(a, b)

I doesn't make sense to me to be doing:

$(a).compare(b)

where a and b are arrays. Normally when you $(something) you'd be passing a selector string to work with DOM elements.

Also regarding sorting and 'caching' the sorted arrays:

  • I don't think sorting once at the start of the method instead of every time through the loop is 'caching'. The sort will still happen every time you call compare(b). That's just semantics, but...
  • for (var i = 0; t[i]; i++) { ...this loop finishes early if your t array contains a false value in it somewhere, so $([1, 2, 3, 4]).compare([1, false, 2, 3]) returns true!
  • More importantly the array sort() method sorts the array in place, so doing var b = t.sort() ...doesn't create a sorted copy of the original array, it sorts the original array and also assigns a reference to it in b. I don't think the compare method should have side-effects.

It seems what we need to do is to copy the arrays before working on them. The best answer I could find for how to do that in a jQuery way was by none other than John Resig here on SO! What is the most efficient way to deep clone an object in JavaScript? (see comments on his answer for the array version of the object cloning recipe)

In which case I think the code for it would be:

jQuery.extend({
    compare: function (arrayA, arrayB) {
        if (arrayA.length != arrayB.length) { return false; }
        // sort modifies original array
        // (which are passed by reference to our method!)
        // so clone the arrays before sorting
        var a = jQuery.extend(true, [], arrayA);
        var b = jQuery.extend(true, [], arrayB);
        a.sort(); 
        b.sort();
        for (var i = 0, l = a.length; i < l; i++) {
            if (a[i] !== b[i]) { 
                return false;
            }
        }
        return true;
    }
});

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

jQuery.compare(a, b);
// false

jQuery.compare(b, c);
// true

// c is still unsorted [3, 4, 2]

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

In my case, I was fetching data from database, changing some column values and updating it in database but for updating I was using the same save query which was violating primary key constraints i.e duplicate values for primary key, so I had written a separate query for updating the columns and it solved my problem..!

Stop embedded youtube iframe?

Here is a codepen, it worked for me.

I was searching for the simplest solution for embedding the YT video within an iframe, and I feel this is it.

What I needed was to have the video appear in a modal window and stop playing when it was closed

Here is the code : (from: https://codepen.io/anon/pen/GBjqQr)

    <div><a href="#" class="play-video">Play Video</a></div>
    <div><a href="#" class="stop-video">Stop Video</a></div>
    <div><a href="#" class="pause-video">Pause Video</a></div>

    <iframe class="youtube-video" width="560" height="315" src="https://www.youtube.com/embed/glEiPXAYE-U?enablejsapi=1&version=3&playerapiid=ytplayer" frameborder="0" allowfullscreen></iframe>

$('a.play-video').click(function(){
    $('.youtube-video')[0].contentWindow.postMessage('{"event":"command","func":"' + 'playVideo' + '","args":""}', '*');
});

$('a.stop-video').click(function(){
    $('.youtube-video')[0].contentWindow.postMessage('{"event":"command","func":"' + 'stopVideo' + '","args":""}', '*');
});

$('a.pause-video').click(function(){
    $('.youtube-video')[0].contentWindow.postMessage('{"event":"command","func":"' + 'pauseVideo' + '","args":""}', '*');
});

Additionally, if you want it to autoplay in a DOM-object that is not yet visible, such as a modal window, if I used the same button to play the video that I was using to show the modal it would not work so I used THIS:

https://www.youtube.com/embed/EzAGZCPSOfg?autoplay=1&enablejsapi=1&version=3&playerapiid=ytplayer

Note: The ?autoplay=1& where it's placed and the use of the '&' before the next property to allow the pause to continue to work.

__FILE__, __LINE__, and __FUNCTION__ usage in C++

C++20 std::source_location

C++ has finally added a non-macro option, and it will likely dominate at some point in the future when C++20 becomes widespread:

The documentation says:

constexpr const char* function_name() const noexcept;

6 Returns: If this object represents a position in the body of a function, returns an implementation-defined NTBS that should correspond to the function name. Otherwise, returns an empty string.

where NTBS means "Null Terminated Byte String".

I'll give it a try when support arrives to GCC, GCC 9.1.0 with g++-9 -std=c++2a still doesn't support it.

https://en.cppreference.com/w/cpp/utility/source_location claims usage will be like:

#include <iostream>
#include <string_view>
#include <source_location>

void log(std::string_view message,
         const std::source_location& location std::source_location::current()
) {
    std::cout << "info:"
              << location.file_name() << ":"
              << location.line() << ":"
              << location.function_name() << " "
              << message << '\n';
}

int main() {
    log("Hello world!");
}

Possible output:

info:main.cpp:16:main Hello world!

__PRETTY_FUNCTION__ vs __FUNCTION__ vs __func__ vs std::source_location::function_name

Answered at: What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?

2D Euclidean vector rotations

Sounds easier to do with the standard classes:

std::complex<double> vecA(0,1);
std::complex<double> i(0,1); // 90 degrees
std::complex<double> r45(sqrt(2.0),sqrt(2.0));
vecA *= i;
vecA *= r45;

Vector rotation is a subset of complex multiplication. To rotate over an angle alpha, you multiply by std::complex<double> { cos(alpha), sin(alpha) }

CASE WHEN statement for ORDER BY clause

declare @OrderByCmd  nvarchar(2000)
declare @OrderByName nvarchar(100)
declare @OrderByCity nvarchar(100)
set @OrderByName='Name'    
set @OrderByCity='city'
set @OrderByCmd= 'select * from customer Order By '+@OrderByName+','+@OrderByCity+''
EXECUTE sp_executesql @OrderByCmd 

How do I execute a stored procedure in a SQL Agent job?

You just need to add this line to the window there:

exec (your stored proc name) (and possibly add parameters)

What is your stored proc called, and what parameters does it expect?

C++ Redefinition Header Files (winsock2.h)

#include guards are the standard way of doing this. #pragma once is not, meaning that not all compilers support it.

For loop in Objective-C

The traditional for loop in Objective-C is inherited from standard C and takes the following form:

for (/* Instantiate local variables*/ ; /* Condition to keep looping. */ ; /* End of loop expressions */)
{
    // Do something.
}

For example, to print the numbers from 1 to 10, you could use the for loop:

for (int i = 1; i <= 10; i++)
{
    NSLog(@"%d", i);
}

On the other hand, the for in loop was introduced in Objective-C 2.0, and is used to loop through objects in a collection, such as an NSArray instance. For example, to loop through a collection of NSString objects in an NSArray and print them all out, you could use the following format.

for (NSString* currentString in myArrayOfStrings)
{
    NSLog(@"%@", currentString);
}

This is logically equivilant to the following traditional for loop:

for (int i = 0; i < [myArrayOfStrings count]; i++)
{
    NSLog(@"%@", [myArrayOfStrings objectAtIndex:i]);
}

The advantage of using the for in loop is firstly that it's a lot cleaner code to look at. Secondly, the Objective-C compiler can optimize the for in loop so as the code runs faster than doing the same thing with a traditional for loop.

Hope this helps.

How to connect to remote Redis server?

There are two ways to connect remote redis server using redis-cli:

1. Using host & port individually as options in command

redis-cli -h host -p port

If your instance is password protected

redis-cli -h host -p port -a password

e.g. if my-web.cache.amazonaws.com is the host url and 6379 is the port

Then this will be the command:

redis-cli -h my-web.cache.amazonaws.com -p 6379

if 92.101.91.8 is the host IP address and 6379 is the port:

redis-cli -h 92.101.91.8 -p 6379

command if the instance is protected with password pass123:

redis-cli -h my-web.cache.amazonaws.com -p 6379 -a pass123

2. Using single uri option in command

redis-cli -u redis://password@host:port

command in a single uri form with username & password

redis-cli -u redis://username:password@host:port

e.g. for the same above host - port configuration command would be

redis-cli -u redis://[email protected]:6379

command if username is also provided user123

redis-cli -u redis://user123:[email protected]:6379

This detailed answer was for those who wants to check all options. For more information check documentation: Redis command line usage

Python dictionary: are keys() and values() always the same order?

For what it's worth, some heavy used production code I have written is based on this assumption and I never had a problem with it. I know that doesn't make it true though :-)

If you don't want to take the risk I would use iteritems() if you can.

for key, value in myDictionary.iteritems():
    print key, value

Passing an integer by reference in Python

In Python, everything is passed by value, but if you want to modify some state, you can change the value of an integer inside a list or object that's passed to a method.

What is the difference between a port and a socket?

A socket is a special type of file handle which is used by a process to request network services from the operating system. A socket address is the triple: {protocol, local-address, local-process} where the local process is identified by a port number.

In the TCP/IP suite, for example:

{tcp, 193.44.234.3, 12345}

A conversation is the communication link between two processes thus depicting an association between two. An association is the 5-tuple that completely specifies the two processes that comprise a connection: {protocol, local-address, local-process, foreign-address, foreign-process}

In the TCP/IP suite, for example:

{tcp, 193.44.234.3, 1500, 193.44.234.5, 21}

could be a valid association.

A half-association is either: {protocol, local-address, local-process}

or

{protocol, foreign-address, foreign-process}

which specify each half of a connection.

The half-association is also called a socket or a transport address. That is, a socket is an end point for communication that can be named and addressed in a network. The socket interface is one of several application programming interfaces (APIs) to the communication protocols. Designed to be a generic communication programming interface, it was first introduced by the 4.2BSD UNIX system. Although it has not been standardized, it has become a de facto industry standard.

How do I retrieve an HTML element's actual width and height?

You only need to calculate it for IE7 and older (and only if your content doesn't have fixed size). I suggest using HTML conditional comments to limit hack to old IEs that don't support CSS2. For all other browsers use this:

<style type="text/css">
    html,body {display:table; height:100%;width:100%;margin:0;padding:0;}
    body {display:table-cell; vertical-align:middle;}
    div {display:table; margin:0 auto; background:red;}
</style>
<body><div>test<br>test</div></body>

This is the perfect solution. It centers <div> of any size, and shrink-wraps it to size of its content.

AngularJS UI Router - change url without reloading state

Calling

$state.go($state.current, {myParam: newValue}, {notify: false});

will still reload the controller, meaning you will lose state data.

To avoid it, simply declare the parameter as dynamic:

$stateProvider.state({
    name: 'myState',
    url: '/my_state?myParam',
    params: {
        myParam: {
          dynamic: true,    // <----------
        }
    },
    ...
});

Then you don't even need the notify, just calling

$state.go($state.current, {myParam: newValue})

suffices. Neato!

From the documentation:

When dynamic is true, changes to the parameter value will not cause the state to be entered/exited. The resolves will not be re-fetched, nor will views be reloaded.

This can be useful to build UI where the component updates itself when the param values change.

JPA: unidirectional many-to-one and cascading delete

I have seen in unidirectional @ManytoOne, delete don't work as expected. When parent is deleted, ideally child should also be deleted, but only parent is deleted and child is NOT deleted and is left as orphan

Technology used are Spring Boot/Spring Data JPA/Hibernate

Sprint Boot : 2.1.2.RELEASE

Spring Data JPA/Hibernate is used to delete row .eg

parentRepository.delete(parent)

ParentRepository extends standard CRUD repository as shown below ParentRepository extends CrudRepository<T, ID>

Following are my entity class

@Entity(name = “child”)
public class Child  {

    @Id
    @GeneratedValue
    private long id;

    @ManyToOne( fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = “parent_id", nullable = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    private Parent parent;
}

@Entity(name = “parent”)
public class Parent {

    @Id
    @GeneratedValue
    private long id;

    @Column(nullable = false, length = 50)
    private String firstName;


}

Best way to add Gradle support to IntelliJ Project

To add to other answers. For me it was helpful to delete .mvn directory and then add build.gradle. New versions of IntelliJ will then automatically notice that you use Gradle.

<code> vs <pre> vs <samp> for inline and block code snippets

For normal inlined <code> use:

<code>...</code>

and for each and every place where blocked <code> is needed use

<code style="display:block; white-space:pre-wrap">...</code>

Alternatively, define a <codenza> tag for break lining block <code> (no classes)

<script>
</script>
<style>
  codenza, code {}     /*  noop mnemonic aide that codenza mimes code tag  */
  codenza {display:block;white-space:pre-wrap}
</style>`

Testing: (NB: the following is a scURIple utilizing a data: URI protocol/scheme, therefore the %0A nl format codes are essential in preserving such when cut and pasted into the URL bar for testing - so view-source: (ctrl-U) looks good preceed every line below with %0A)

data:text/html;charset=utf-8,<html >
<script>document.write(window.navigator.userAgent)</script>
<script></script>
<style>
  codenza, code {}     /*  noop mnemonic aide that codenza mimes code tag  */
  codenza {display:block;white-space:pre-wrap}
</style>
<p>First using the usual &lt;code> tag
<code>
  %0A     function x(arghhh){ 
  %0A          return "a very long line of text that will extend the code beyond the boundaries of the margins, guaranteed for the most part, well maybe without you as a warrantee (except in abnormally conditioned perverse environs in which case a warranty is useless)"
  %0A     }
</code>
and then 
<p>with the tag blocked using pre-wrapped lines
<code style=display:block;white-space:pre-wrap> 
  %0A     function x(arghhh){ 
  %0A          return "a very long line of text that will extend the code beyond the boundaries of the margins, guaranteed for the most part, well maybe without you as a warrantee (except in abnormally conditioned perverse environs in which case a warranty is useless)"
  %0A     }
</code>
<br>using an ersatz tag
<codenza>
  %0A     function x(arghhh){ 
  %0A          return "a very long line of text that will extend the code beyond the boundaries of the margins, guaranteed for the most part, well maybe without you as a warrantee (except in abnormally conditioned perverse environs in which case a warranty is useless)"
 %0A     }
</codenza>
</html>

What does __FILE__ mean in Ruby?

It is a reference to the current file name. In the file foo.rb, __FILE__ would be interpreted as "foo.rb".

Edit: Ruby 1.9.2 and 1.9.3 appear to behave a little differently from what Luke Bayes said in his comment. With these files:

# test.rb
puts __FILE__
require './dir2/test.rb'
# dir2/test.rb
puts __FILE__

Running ruby test.rb will output

test.rb
/full/path/to/dir2/test.rb

Position absolute and overflow hidden

What about position: relative for the outer div? In the example that hides the inner one. It also won't move it in its layout since you don't specify a top or left.

Remove accents/diacritics in a string in JavaScript

With ES2015/ES6 String.prototype.normalize(),

const str = "Crème Brulée"
str.normalize("NFD").replace(/[\u0300-\u036f]/g, "")
> "Creme Brulee"

Two things are happening here:

  1. normalize()ing to NFD Unicode normal form decomposes combined graphemes into the combination of simple ones. The è of Crème ends up expressed as e + `.
  2. Using a regex character class to match the U+0300 ? U+036F range, it is now trivial to globally get rid of the diacritics, which the Unicode standard conveniently groups as the Combining Diacritical Marks Unicode block.

See comment for performance testing.

Alternatively, if you just want sorting

Intl.Collator has sufficient support ~95% right now, a polyfill is also available here but I haven't tested it.

const c = new Intl.Collator();
["creme brulee", "crème brulée", "crame brulai", "crome brouillé",
"creme brulay", "creme brulfé", "creme bruléa"].sort(c.compare)
["crame brulai", "creme brulay", "creme bruléa", "creme brulee",
"crème brulée", "creme brulfé", "crome brouillé"]


["creme brulee", "crème brulée", "crame brulai", "crome brouillé"].sort((a,b) => a>b)
["crame brulai", "creme brulee", "crome brouillé", "crème brulée"]

Reading the selected value from asp:RadioButtonList using jQuery

The simple way to retrieve checked value of RadioButtonList1 is:

$('#RadioButtonList1 input:checked').val()

Edit by Tim:

where RadioButtonList1 must be the ClientID of the RadioButtonList

var rblSelectedValue = $("#<%= RadioButtonList1.ClientID %> input:checked"); 

How can I resize an image using Java?

If, having imagemagick installed on your maschine is an option, I recommend im4java. It is a very thin abstraction layer upon the command line interface, but does its job very well.

Convert DateTime to TimeSpan

In case you are using WPF and Xceed's TimePicker (which seems to be using DateTime?) as a timespan picker -as I do right now- you can get the total milliseconds (or a TimeSpan) out of it like so:

var milliseconds = DateTimeToTimeSpan(timePicker.Value).TotalMilliseconds;

    TimeSpan DateTimeToTimeSpan(DateTime? ts)
    {
        if (!ts.HasValue) return TimeSpan.Zero;
        else return new TimeSpan(0, ts.Value.Hour, ts.Value.Minute, ts.Value.Second, ts.Value.Millisecond);
    }

XAML :

<Xceed:TimePicker x:Name="timePicker" Format="Custom" FormatString="H'h 'm'm 's's'" />

If not, I guess you could just adjust my DateTimeToTimeSpan() so that it also takes 'days' into account or do sth like dateTime.Substract(DateTime.MinValue).TotalMilliseconds.

In-place edits with sed on OS X

The -i flag probably doesn't work for you, because you followed an example for GNU sed while macOS uses BSD sed and they have a slightly different syntax.

All the other answers tell you how to correct the syntax to work with BSD sed. The alternative is to install GNU sed on your macOS with:

brew install gsed

and then use it instead of the sed version shipped with macOS (note the g prefix), e.g:

gsed -i 's/oldword/newword/' file1.txt

If you want GNU sed commands to be always portable to your macOS, you could prepend "gnubin" directory to your path, by adding something like this to your .bashrc/.zshrc file (run brew info gsed to see what exactly you need to do):

export PATH="/usr/local/opt/gnu-sed/libexec/gnubin:$PATH"

and from then on the GNU sed becomes your default sed and you can simply run:

sed -i 's/oldword/newword/' file1.txt

git revert back to certain commit

git reset --hard 4a155e5 Will move the HEAD back to where you want to be. There may be other references ahead of that time that you would need to remove if you don't want anything to point to the history you just deleted.

Why does Lua have no "continue" statement?

The way that the language manages lexical scope creates issues with including both goto and continue. For example,

local a=0
repeat 
    if f() then
        a=1 --change outer a
    end
    local a=f() -- inner a
until a==0 -- test inner a

The declaration of local a inside the loop body masks the outer variable named a, and the scope of that local extends across the condition of the until statement so the condition is testing the innermost a.

If continue existed, it would have to be restricted semantically to be only valid after all of the variables used in the condition have come into scope. This is a difficult condition to document to the user and enforce in the compiler. Various proposals around this issue have been discussed, including the simple answer of disallowing continue with the repeat ... until style of loop. So far, none have had a sufficiently compelling use case to get them included in the language.

The work around is generally to invert the condition that would cause a continue to be executed, and collect the rest of the loop body under that condition. So, the following loop

-- not valid Lua 5.1 (or 5.2)
for k,v in pairs(t) do
  if isstring(k) then continue end
  -- do something to t[k] when k is not a string
end

could be written

-- valid Lua 5.1 (or 5.2)
for k,v in pairs(t) do
  if not isstring(k) then 
    -- do something to t[k] when k is not a string
  end
end

It is clear enough, and usually not a burden unless you have a series of elaborate culls that control the loop operation.

How to implement a material design circular progress bar in android

I've backported the three Material Design progress drawables to Android 4.0, which can be used as a drop-in replacement for regular ProgressBar, with exactly the same appearance.

These drawables also backported the tinting APIs (and RTL support), and uses ?colorControlActivated as the default tint. A MaterialProgressBar widget which extends ProgressBar has also been introduced for convenience.

DreaminginCodeZH/MaterialProgressBar

This project has also been adopted by afollestad/material-dialogs for progress dialog.

On Android 4.4.4:

Android 4.4.4

On Android 5.1.1:

Android 5.1.1

ImportError: DLL load failed: The specified module could not be found

For Windows 10 x64 and Python:

Open a Visual Studio x64 command prompt, and use dumpbin:

dumpbin /dependents [Python Module DLL or PYD file]

If you do not have Visual Studio installed, it is possible to download dumpbin elsewhere, or use another utility such as Dependency Walker.

Note that all other answers (to date) are simply random stabs in the dark, whereas this method is closer to a sniper rifle with night vision.

Case study 1

  1. I switched on Address Sanitizer for a Python module that I wrote using C++ using MSVC and CMake.

  2. It was giving this error: ImportError: DLL load failed: The specified module could not be found

  3. Opened a Visual Studio x64 command prompt.

  4. Under Windows, a .pyd file is a .dll file in disguise, so we want to run dumpbin on this file.

  5. cd MyLibrary\build\lib.win-amd64-3.7\Debug

  6. dumpbin /dependents MyLibrary.cp37-win_amd64.pyd which prints this:

    Microsoft (R) COFF/PE Dumper Version 14.27.29112.0
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    
    Dump of file MyLibrary.cp37-win_amd64.pyd
    
    File Type: DLL
    
      Image has the following dependencies:
    
        clang_rt.asan_dbg_dynamic-x86_64.dll
        gtestd.dll
        tbb_debug.dll
        python37.dll
        KERNEL32.dll
        MSVCP140D.dll
        VCOMP140D.DLL
        VCRUNTIME140D.dll
        VCRUNTIME140_1D.dll
        ucrtbased.dll
    
      Summary
    
         1000 .00cfg
        D6000 .data
         7000 .idata
        46000 .pdata
       341000 .rdata
        23000 .reloc
         1000 .rsrc
       856000 .text
    
  7. Searched for clang_rt.asan_dbg_dynamic-x86_64.dll, copied it into the same directory, problem solved.

  8. Alternatively, could update the environment variable PATH to point to the directory with the missing .dll.

Please feel free to add your own case studies here! I've made it a community wiki answer.

How does the stack work in assembly language?

What is Stack? A stack is a type of data structure -- a means of storing information in a computer. When a new object is entered in a stack, it is placed on top of all the previously entered objects. In other words, the stack data structure is just like a stack of cards, papers, credit card mailings, or any other real-world objects you can think of. When removing an object from a stack, the one on top gets removed first. This method is referred to as LIFO (last in, first out).

The term "stack" can also be short for a network protocol stack. In networking, connections between computers are made through a series of smaller connections. These connections, or layers, act like the stack data structure, in that they are built and disposed of in the same way.

Convert dateTime to ISO format yyyy-mm-dd hh:mm:ss in C#

The DateTime::ToString() method has a string formatter that can be used to output datetime in any required format. See DateTime.ToString Method (String) for more information.

How to check that a string is parseable to a double?

Something like below should suffice :-

String decimalPattern = "([0-9]*)\\.([0-9]*)";  
String number="20.00";  
boolean match = Pattern.matches(decimalPattern, number);
System.out.println(match); //if true then decimal else not  

How to resolve git's "not something we can merge" error

I suggest checking if you are able to switch to the branch that you are trying to merge with.

I got this error even though the branch I wanted to merge with was in local repository and there were no spelling errors.

I ignored my local changes so that I could switch to the branch (Stash or commit can also be preferred). After this I switched back to the initial branch, and the merge was successful.

Add new item in existing array in c#.net

It's better to keeps Array immutable and fixed size.

you can simulate Add by Extension Method and IEnumerable.Concat()

public static class ArrayExtensions
    {
        public static string[] Add(this string[] array, string item)
        {
            return array.Concat(new[] {item}).ToArray();
        }
    }

How to sort an array of objects in Java?

[Employee(name=John, age=25, salary=3000.0, mobile=9922001), 
Employee(name=Ace, age=22, salary=2000.0, mobile=5924001), 
Employee(name=Keith, age=35, salary=4000.0, mobile=3924401)]


public void whenComparing_thenSortedByName() {
Comparator<Employee> employeeNameComparator
  = Comparator.comparing(Employee::getName);

Arrays.sort(employees, employeeNameComparator);

assertTrue(Arrays.equals(employees, sortedEmployeesByName));

}

result

[Employee(name=Ace, age=22, salary=2000.0, mobile=5924001), 
Employee(name=John, age=25, salary=3000.0, mobile=9922001), 
Employee(name=Keith, age=35, salary=4000.0, mobile=3924401)]

Why is sed not recognizing \t as a tab?

TAB=$(printf '\t')
sed "s/${TAB}//g" input_file

It works for me on Red Hat, which will remove tabs from the input file.

Return from lambda forEach() in java

You can also throw an exception:

Note:

For the sake of readability each step of stream should be listed in new line.

players.stream()
       .filter(player -> player.getName().contains(name))
       .findFirst()
       .orElseThrow(MyCustomRuntimeException::new);

if your logic is loosely "exception driven" such as there is one place in your code that catches all exceptions and decides what to do next. Only use exception driven development when you can avoid littering your code base with multiples try-catch and throwing these exceptions are for very special cases that you expect them and can be handled properly.)

Setting environment variables on OS X

There are two type of shells at play here.

  • Non-login: .bashrc is reloaded every time you start a new copy of Bash
  • Login: The .profile is loaded only when you either login, or explicitly tell Bash to load it and use it as a login shell.

It's important to understand here that with Bash, file .bashrc is only read by a shell that's both interactive and non-login, and you will find that people often load .bashrc in .bash_profile to overcome this limitation.

Now that you have the basic understanding, let’s move on to how I would advice you to set it up.

  • .profile: create it non-existing. Put your PATH setup in there.
  • .bashrc: create if non-existing. Put all your aliases and custom methods in there.
  • .bash_profile: create if non-existing. Put the following in there.

.bash_file:

#!/bin/bash
source ~/.profile # Get the PATH settings
source ~/.bashrc  # Get Aliases and Functions
#

How to check if type is Boolean

One more decision with es2015 arrow function

const isBoolean = val => typeof val === 'boolean';

Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

This is due a conflict of versions, to solve it, just force an update of your support-annotations version, adding this line on your module: app gradle

implementation ('com.android.support:support-annotations:27.1.1')

Hope this solves your issue ;)

Edit

Almost forgot, you can declare a single extra property (https://docs.gradle.org/current/userguide/writing_build_scripts.html#sec:extra_properties) for the version, go to your project (or your top) gradle file, and declare your support, or just for this example, annotation version var

ext.annotation_version = "27.1.1"

Then in your module gradle replace it with:

implementation ("com.android.support:support-annotations:$annotation_version")

This is very similar to the @emadabel solution, which is a good alternative for doing it, but without the block, or the rootproject prefix.

How to select first and last TD in a row?

You could use the :first-child and :last-child pseudo-selectors:

tr td:first-child,
tr td:last-child {
    /* styles */
}

This should work in all major browsers, but IE7 has some problems when elements are added dynamically (and it won't work in IE6).

How can I delay a method call for 1 second?

Best way to do is :

[self performSelector:@selector(YourFunctionName) 
           withObject:(can be Self or Object from other Classes) 
           afterDelay:(Time Of Delay)];

you can also pass nil as withObject parameter.

example :

[self performSelector:@selector(subscribe) withObject:self afterDelay:3.0 ];

How to make grep only match if the entire line matches?

I intend to add some extra explanation regarding the attempts of OP and other answers as well.

You can use John Kugelmans' solution like this too:

grep -x "ABB\.log" a.tmp

quoting the string and escaping the dot (.) makes it to not need the -F flag any more.

You need to escape the . (dot) (because it matches any character (not only .) if not escaped) or use the -F flag with grep. -F flag makes it a fixed string (not a regex).

If you don't quote the string, you may need double backslash to escape the dot (.):

grep -x ABB\\.log a.tmp


Test:

$ echo "ABBElog"|grep -x  ABB.log
ABBElog #matched !!!
$ echo "ABBElog"|grep -x  "ABB\.log"
#returns empty string, no match


Note:

  1. -x forces to match the whole line.
  2. Answers using a non escaped . without -F flag are wrong.
  3. You can avoid -x switch by wrapping your pattern string with ^ and $. In this case make sure you don't use -F, instead escape the ., because -F will prevent the regex interpretation of ^ and $.


EDIT: (Adding extra explanation in regards of @hakre ):

If you want to match a string starting with -, then you should use -- with grep. Whatever follows -- will be taken as an input (not option).

Example:

echo -f |grep -- "-f"     # where grep "-f" will show error
echo -f |grep -F -- "-f"  # whre grep -F "-f" will show error
grep "pat" -- "-file"     # grep "pat" "-file" won't work. -file is the filename

Run a Java Application as a Service on Linux

Im having Netty java application and I want to run it as a service with systemd. Unfortunately application stops no matter of what Type I'm using. At the end I've wrapped java start in screen. Here are the config files:

service

[Unit]
Description=Netty service
After=network.target
[Service]
User=user
Type=forking
WorkingDirectory=/home/user/app
ExecStart=/home/user/app/start.sh
TimeoutStopSec=10
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target

start

#!/bin/sh
/usr/bin/screen -L -dmS netty_app java -cp app.jar classPath

from that point you can use systemctl [start|stop|status] service.

Using IS NULL or IS NOT NULL on join conditions - Theory question

Example with tables A and B:

 A (parent)       B (child)    
============    =============
 id | name        pid | name 
------------    -------------
  1 | Alex         1  | Kate
  2 | Bill         1  | Lia
  3 | Cath         3  | Mary
  4 | Dale       NULL | Pan
  5 | Evan  

If you want to find parents and their kids, you do an INNER JOIN:

SELECT id,  parent.name AS parent
     , pid, child.name  AS child

FROM
        parent  INNER JOIN  child
  ON   parent.id     =    child.pid

Result is that every match of a parent's id from the left table and a child's pid from the second table will show as a row in the result:

+----+--------+------+-------+
| id | parent | pid  | child | 
+----+--------+------+-------+
|  1 | Alex   |   1  | Kate  |
|  1 | Alex   |   1  | Lia   |
|  3 | Cath   |   3  | Mary  |
+----+--------+------+-------+

Now, the above does not show parents without kids (because their ids do not have a match in child's ids, so what do you do? You do an outer join instead. There are three types of outer joins, the left, the right and the full outer join. We need the left one as we want the "extra" rows from the left table (parent):

SELECT id,  parent.name AS parent
     , pid, child.name  AS child

FROM
        parent  LEFT JOIN  child
  ON   parent.id    =    child.pid

Result is that besides previous matches, all parents that do not have a match (read: do not have a kid) are shown too:

+----+--------+------+-------+
| id | parent | pid  | child | 
+----+--------+------+-------+
|  1 | Alex   |   1  | Kate  |
|  1 | Alex   |   1  | Lia   |
|  3 | Cath   |   3  | Mary  |
|  2 | Bill   | NULL | NULL  |
|  4 | Dale   | NULL | NULL  |
|  5 | Evan   | NULL | NULL  |
+----+--------+------+-------+

Where did all those NULL come from? Well, MySQL (or any other RDBMS you may use) will not know what to put there as these parents have no match (kid), so there is no pid nor child.name to match with those parents. So, it puts this special non-value called NULL.

My point is that these NULLs are created (in the result set) during the LEFT OUTER JOIN.


So, if we want to show only the parents that do NOT have a kid, we can add a WHERE child.pid IS NULL to the LEFT JOIN above. The WHERE clause is evaluated (checked) after the JOIN is done. So, it's clear from the above result that only the last three rows where the pid is NULL will be shown:

SELECT id,  parent.name AS parent
     , pid, child.name  AS child

FROM
        parent  LEFT JOIN  child
  ON   parent.id    =    child.pid

WHERE child.pid IS NULL

Result:

+----+--------+------+-------+
| id | parent | pid  | child | 
+----+--------+------+-------+
|  2 | Bill   | NULL | NULL  |
|  4 | Dale   | NULL | NULL  |
|  5 | Evan   | NULL | NULL  |
+----+--------+------+-------+

Now, what happens if we move that IS NULL check from the WHERE to the joining ON clause?

SELECT id,  parent.name AS parent
     , pid, child.name  AS child

FROM
        parent  LEFT JOIN  child
  ON   parent.id    =    child.pid
  AND  child.pid IS NULL

In this case the database tries to find rows from the two tables that match these conditions. That is, rows where parent.id = child.pid AND child.pid IN NULL. But it can find no such match because no child.pid can be equal to something (1, 2, 3, 4 or 5) and be NULL at the same time!

So, the condition:

ON   parent.id    =    child.pid
AND  child.pid IS NULL

is equivalent to:

ON   1 = 0

which is always False.

So, why does it return ALL rows from the left table? Because it's a LEFT JOIN! And left joins return rows that match (none in this case) and also rows from the left table that do not match the check (all in this case):

+----+--------+------+-------+
| id | parent | pid  | child | 
+----+--------+------+-------+
|  1 | Alex   | NULL | NULL  |
|  2 | Bill   | NULL | NULL  |
|  3 | Cath   | NULL | NULL  |
|  4 | Dale   | NULL | NULL  |
|  5 | Evan   | NULL | NULL  |
+----+--------+------+-------+

I hope the above explanation is clear.



Sidenote (not directly related to your question): Why on earth doesn't Pan show up in none of our JOINs? Because his pid is NULL and NULL in the (not common) logic of SQL is not equal to anything so it can't match with any of the parent ids (which are 1,2,3,4 and 5). Even if there was a NULL there, it still wouldn't match because NULL does not equal anything, not even NULL itself (it's a very strange logic, indeed!). That's why we use the special check IS NULL and not a = NULL check.

So, will Pan show up if we do a RIGHT JOIN ? Yes, it will! Because a RIGHT JOIN will show all results that match (the first INNER JOIN we did) plus all rows from the RIGHT table that don't match (which in our case is one, the (NULL, 'Pan') row.

SELECT id,  parent.name AS parent
     , pid, child.name  AS child

FROM
        parent  RIGHT JOIN  child
  ON   parent.id     =    child.pid

Result:

+------+--------+------+-------+
| id   | parent | pid  | child | 
+---------------+------+-------+
|   1  | Alex   |   1  | Kate  |
|   1  | Alex   |   1  | Lia   |
|   3  | Cath   |   3  | Mary  |
| NULL | NULL   | NULL | Pan   |
+------+--------+------+-------+

Unfortunately, MySQL does not have FULL JOIN. You can try it in other RDBMSs, and it will show:

+------+--------+------+-------+
|  id  | parent | pid  | child | 
+------+--------+------+-------+
|   1  | Alex   |   1  | Kate  |
|   1  | Alex   |   1  | Lia   |
|   3  | Cath   |   3  | Mary  |
|   2  | Bill   | NULL | NULL  |
|   4  | Dale   | NULL | NULL  |
|   5  | Evan   | NULL | NULL  |
| NULL | NULL   | NULL | Pan   |
+------+--------+------+-------+

Removing the first 3 characters from a string

Use the substring method of the String class :

String removeCurrency=amount.getText().toString().substring(3);

What is ROWS UNBOUNDED PRECEDING used for in Teradata?

It's the "frame" or "range" clause of window functions, which are part of the SQL standard and implemented in many databases, including Teradata.

A simple example would be to calculate the average amount in a frame of three days. I'm using PostgreSQL syntax for the example, but it will be the same for Teradata:

WITH data (t, a) AS (
  VALUES(1, 1),
        (2, 5),
        (3, 3),
        (4, 5),
        (5, 4),
        (6, 11)
)
SELECT t, a, avg(a) OVER (ORDER BY t ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
FROM data
ORDER BY t

... which yields:

t  a  avg
----------
1  1  3.00
2  5  3.00
3  3  4.33
4  5  4.00
5  4  6.67
6 11  7.50

As you can see, each average is calculated "over" an ordered frame consisting of the range between the previous row (1 preceding) and the subsequent row (1 following).

When you write ROWS UNBOUNDED PRECEDING, then the frame's lower bound is simply infinite. This is useful when calculating sums (i.e. "running totals"), for instance:

WITH data (t, a) AS (
  VALUES(1, 1),
        (2, 5),
        (3, 3),
        (4, 5),
        (5, 4),
        (6, 11)
)
SELECT t, a, sum(a) OVER (ORDER BY t ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM data
ORDER BY t

yielding...

t  a  sum
---------
1  1    1
2  5    6
3  3    9
4  5   14
5  4   18
6 11   29

Here's another very good explanations of SQL window functions.

SQLAlchemy: print the actual query

Given that what you want makes sense only when debugging, you could start SQLAlchemy with echo=True, to log all SQL queries. For example:

engine = create_engine(
    "mysql://scott:tiger@hostname/dbname",
    encoding="latin1",
    echo=True,
)

This can also be modified for just a single request:

echo=False – if True, the Engine will log all statements as well as a repr() of their parameter lists to the engines logger, which defaults to sys.stdout. The echo attribute of Engine can be modified at any time to turn logging on and off. If set to the string "debug", result rows will be printed to the standard output as well. This flag ultimately controls a Python logger; see Configuring Logging for information on how to configure logging directly.

Source: SQLAlchemy Engine Configuration

If used with Flask, you can simply set

app.config["SQLALCHEMY_ECHO"] = True

to get the same behaviour.

DataTables: Uncaught TypeError: Cannot read property 'defaults' of undefined

The problem is that dataTable is not defined at the point you are calling this method.

Ensure that you are loading the .js files in the correct order:

<script src="/Scripts/jquery.dataTables.js"></script>
<script src="/Scripts/dataTables.bootstrap.js"></script>

Importing data from a JSON file into R

First install the RJSONIO and RCurl package:

_x000D_
_x000D_
install.packages("RJSONIO")_x000D_
install.packages("(RCurl")
_x000D_
_x000D_
_x000D_

Try below code using RJSONIO in console

_x000D_
_x000D_
library(RJSONIO)_x000D_
library(RCurl)_x000D_
json_file = getURL("https://raw.githubusercontent.com/isrini/SI_IS607/master/books.json")_x000D_
json_file2 = RJSONIO::fromJSON(json_file)_x000D_
head(json_file2)
_x000D_
_x000D_
_x000D_

Bootstrap: Open Another Modal in Modal

try this

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
  <title></title>_x000D_
  <meta charset="utf-8">_x000D_
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>_x000D_
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#test1">Open Modal 1 </button>_x000D_
_x000D_
_x000D_
_x000D_
<div id="test1" class="modal fade" role="dialog" style="z-index: 1400;">_x000D_
  <div class="modal-dialog">_x000D_
    <!-- Modal content-->_x000D_
    <div class="modal-content">_x000D_
      _x000D_
      <div class="modal-body">_x000D_
       <button type="button" class="btn btn-info btn-lg" data-toggle="modal"      data-target="#test2">Open Modal 2</button>_x000D_
       _x000D_
      </div>      _x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<div id="test2" class="modal fade" role="dialog" style="z-index: 1600;">_x000D_
  <div class="modal-dialog">_x000D_
    <!-- Modal content-->_x000D_
    <div class="modal-content">_x000D_
      _x000D_
      <div class="modal-body">_x000D_
       _x000D_
        content_x000D_
       _x000D_
      </div>      _x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
  _x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Concatenate in jQuery Selector

There is nothing wrong with syntax of

$('#part' + number).html(text);

jQuery accepts a String (usually a CSS Selector) or a DOM Node as parameter to create a jQuery Object.

In your case you should pass a String to $() that is

$(<a string>)

Make sure you have access to the variables number and text.

To test do:

function(){
    alert(number + ":" + text);//or use console.log(number + ":" + text)
    $('#part' + number).html(text);
}); 

If you see you dont have access, pass them as parameters to the function, you have to include the uual parameters for $.get and pass the custom parameters after them.

How to do case insensitive search in Vim

You can issue the command

:set ignorecase

and after that your searches will be case-insensitive.

Rename computer and join to domain in one step with PowerShell

I was able to accomplish both tasks with one reboot using the following method and it worked with the following JoinDomainOrWorkGroup flags. This was a new build and using Windows 2008 R2 Enterprise. I verified that it does create the computer account as well in AD with the new name.

1 (0x1) Default. Joins a computer to a domain. If this value is not specified, the join is a computer to a workgroup

32 (0x20) Allows a join to a new domain, even if the computer is already joined to a domain

$comp=gwmi win32_computersystem
$cred=get-credential
$newname="*newcomputername*"
$domain="*domainname*"
$OU="OU=Servers, DC=domain, DC=Domain, DC=com"
$comp.JoinDomainOrWorkGroup($domain ,($cred.getnetworkcredential()).password, $cred.username, $OU, 33)
$comp.rename($newname,$cred.getnetworkcredential()).password,$cred.username)

How can I programmatically get the MAC address of an iphone

A lot of these questions only address the Mac address. If you also require the IP address I just wrote this, may need some work but seems to work well on my machine...

- (NSString *)getLocalIPAddress
{
    NSArray *ipAddresses = [[NSHost currentHost] addresses];
    NSArray *sortedIPAddresses = [ipAddresses sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    numberFormatter.allowsFloats = NO;

    for (NSString *potentialIPAddress in sortedIPAddresses)
    {
        if ([potentialIPAddress isEqualToString:@"127.0.0.1"]) {
            continue;
        }

        NSArray *ipParts = [potentialIPAddress componentsSeparatedByString:@"."];

        BOOL isMatch = YES;

        for (NSString *ipPart in ipParts) {
            if (![numberFormatter numberFromString:ipPart]) {
                isMatch = NO;
                break;
            }
        }
        if (isMatch) {
            return potentialIPAddress;
        }
    }

    // No IP found
    return @"?.?.?.?";
}

How to embed an autoplaying YouTube video in an iframe?

<iframe width="560" height="315" 
        src="https://www.youtube.com/embed/9IILMHo4RCQ?rel=0&amp;controls=0&amp;showinfo=0&amp;autoplay=1" 
        frameborder="0" allowfullscreen></iframe>

What is the difference between vmalloc and kmalloc?

What are the advantages of having a contiguous block of memory? Specifically, why would I need to have a contiguous physical block of memory in a system call? Is there any reason I couldn't just use vmalloc?

From Google's "I'm Feeling Lucky" on vmalloc:

kmalloc is the preferred way, as long as you don't need very big areas. The trouble is, if you want to do DMA from/to some hardware device, you'll need to use kmalloc, and you'll probably need bigger chunk. The solution is to allocate memory as soon as possible, before memory gets fragmented.

Convert list of dictionaries to a pandas DataFrame

Supposing d is your list of dicts, simply:

df = pd.DataFrame(d)

Note: this does not work with nested data.

Xml serialization - Hide null values

Additionally to what Chris Taylor wrote: if you have something serialized as an attribute, you can have a property on your class named {PropertyName}Specified to control if it should be serialized. In code:

public class MyClass
{
    [XmlAttribute]
    public int MyValue;

    [XmlIgnore]
    public bool MyValueSpecified;
}

How to list all properties of a PowerShell object

The most succinct way to do this is:

Get-WmiObject -Class win32_computersystem -Property *

How can I find the number of arguments of a Python function?

Good news for folks who want to do this in a portable way between Python 2 and Python 3.6+: use inspect.getfullargspec() method. It works in both Python 2.x and 3.6+

As Jim Fasarakis Hilliard and others have pointed out, it used to be like this:
1. In Python 2.x: use inspect.getargspec()
2. In Python 3.x: use signature, as getargspec() and getfullargspec() were deprecated.

However, starting Python 3.6 (by popular demand?), things have changed towards better:

From the Python 3 documentation page:

inspect.getfullargspec(func)

Changed in version 3.6: This method was previously documented as deprecated in favour of signature() in Python 3.5, but that decision has been reversed in order to restore a clearly supported standard interface for single-source Python 2/3 code migrating away from the legacy getargspec() API.

SQL WITH clause example

This has been fully answered here.

See Oracle's docs on SELECT to see how subquery factoring works, and Mark's example:

WITH employee AS (SELECT * FROM Employees)
SELECT * FROM employee WHERE ID < 20
UNION ALL
SELECT * FROM employee WHERE Sex = 'M'

Convert JSON string to array of JSON objects in Javascript

Using jQuery:

var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
var jsonObj = $.parseJSON('[' + str + ']');

jsonObj is your JSON object.

Xcode "Device Locked" When iPhone is unlocked

Recently I have met the Xcode shows "development cannot be enabled while your device is locked, Please unlock your device and reattach. (0xE80000E2).

If your iOS device is already unlocked and connected to mac and still get the error from Xcode 8.1 after upgrading to iOS 10.1.1, then the mac is not trusted by the device.

To fix it, first disconnect device to mac and then go to iOS settings app, and open general->reset->Reset Location & Privacy.

Then connect device to mac and when prompted, set select trust the mac.

Then wait the processing symbol files within your device and mac. After it finished, you can run the project to your device. It will be working.

Global variables in Javascript across multiple files

OK, guys, here's my little test too. I had a similar problem, so I decided to test out 3 situations:

  1. One HTML file, one external JS file... does it work at all - can functions communicate via a global var?
  2. Two HTML files, one external JS file, one browser, two tabs: will they interfere via the global var?
  3. One HTML file, open by 2 browsers, will it work and will they interfere?

All the results were as expected.

  1. It works. Functions f1() and f2() communicate via global var (var is in the external JS file, not in HTML file).
  2. They do not interfere. Apparently distinct copies of JS file have been made for each browser tab, each HTML page.
  3. All works independently, as expected.

Instead of browsing tutorials, I found it easier to try it out, so I did. My conclusion: whenever you include an external JS file in your HTML page, the contents of the external JS gets "copy/pasted" into your HTML page before the page is rendered. Or into your PHP page if you will. Please correct me if I'm wrong here. Thanx.

My example files follow:

EXTERNAL JS:

var global = 0;

function f1()
{
    alert('fired: f1');
    global = 1;
    alert('global changed to 1');
}

function f2()
{
    alert('fired f2');
    alert('value of global: '+global);
}

HTML 1:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>

HTML 2

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index2.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>

In angular $http service, How can I catch the "status" of error?

Your arguments are incorrect, error doesn't return an object containing status and message, it passed them as separate parameters in the order described below.

Taken from the angular docs:

  • data – {string|Object} – The response body transformed with the transform functions.
  • status – {number} – HTTP status code of the response.
  • headers – {function([headerName])} – Header getter function.
  • config – {Object} – The configuration object that was used to generate the request.
  • statusText – {string} – HTTP status text of the response.

So you'd need to change your code to:

$http.get(dataUrl)
    .success(function (data){
        $scope.data.products = data;
    })
    .error(function (error, status){
        $scope.data.error = { message: error, status: status};
        console.log($scope.data.error.status); 
  }); 

Obviously, you don't have to create an object representing the error, you could just create separate scope properties but the same principle applies.

How to install all required PHP extensions for Laravel?

Laravel Server Requirements mention that BCMath, Ctype, JSON, Mbstring, OpenSSL, PDO, Tokenizer, and XML extensions are required. Most of the extensions are installed and enabled by default.

You can run the following command in Ubuntu to make sure the extensions are installed.

sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip

PHP version specific installation (if PHP 7.4 installed)

sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring

You may need other PHP extensions for your composer packages. Find from links below.

PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)

PHP extensions for Ubuntu 18.04 LTS (Bionic)

PHP extensions for Ubuntu 16.04 LTS (Xenial)

How do you import a large MS SQL .sql file?

You can use this tool as well. It is really useful.

BigSqlRunner

How to detect if a stored procedure already exists

The cleanest way is to test for it's existence, drop it if it exists, and then recreate it. You can't embed a "create proc" statement inside an IF statement. This should do nicely:

IF OBJECT_ID('MySproc', 'P') IS NOT NULL
DROP PROC MySproc
GO

CREATE PROC MySproc
AS
BEGIN
    ...
END

MySQL INNER JOIN Alias

You'll need to join twice:

SELECT home.*, away.*, g.network, g.date_start 
FROM game AS g
INNER JOIN team AS home
  ON home.importid = g.home
INNER JOIN team AS away
  ON away.importid = g.away
ORDER BY g.date_start DESC 
LIMIT 7

Adding click event for a button created dynamically using jQuery

Just create a button element with jQuery, and add the event handler when you create it :

var div = $('<div />', {'data-role' : 'fieldcontain'}),
    btn = $('<input />', {
              type  : 'button',
              value : 'Dynamic Button',
              id    : 'btn_a',
              on    : {
                 click: function() {
                     alert ( this.value );
                 }
              }
          });

div.append(btn).appendTo( $('#pg_menu_content').empty() );

FIDDLE

Floating point vs integer calculations on modern hardware

Unless you're writing code that will be called millions of times per second (such as, e.g., drawing a line to the screen in a graphics application), integer vs. floating-point arithmetic is rarely the bottleneck.

The usual first step to the efficiency questions is to profile your code to see where the run-time is really spent. The linux command for this is gprof.

Edit:

Though I suppose you can always implement the line drawing algorithm using integers and floating-point numbers, call it a large number of times and see if it makes a difference:

http://en.wikipedia.org/wiki/Bresenham's_algorithm

How to serve static files in Flask

You can also, and this is my favorite, set a folder as static path so that the files inside are reachable for everyone.

app = Flask(__name__, static_url_path='/static')

With that set you can use the standard HTML:

<link rel="stylesheet" type="text/css" href="/static/style.css">

SQL Server: How to use UNION with two queries that BOTH have a WHERE clause?

Create views on two first "selects" and "union" them.

Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response

this problem occurs when we make custom header for request.This request that uses the HTTP OPTIONS and includes several headers.

The required header for this request is Access-Control-Request-Headers , which should be part of response header and should allow request from all the origin. Sometimes it needs Content-Type as well in header of response. So your response header should be like that -

response.header("Access-Control-Allow-Origin", "*"); // allow request from all origin
response.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
response.header("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Authorization");