Programs & Examples On #Custom component

custom component is a generic term for a manually developed UI component for a component based UI framework. When using JSF, please don't confuse this with "composite component", where the component is definied by XHTML using cc:xxx tags instead of by a Java class extending UIComponent.

automating telnet session using bash scripts

Telnet is often used when you learn HTTP protocol. I used to use that script as a part of my web-scraper:

echo "open www.example.com 80" 
sleep 2 
echo "GET /index.html HTTP/1.1" 
echo "Host: www.example.com" 
echo 
echo 
sleep 2

let's say the name of the script is get-page.sh then:

get-page.sh | telnet

will give you a html document.

Hope it will be helpful to someone ;)

Can I add a custom attribute to an HTML tag?

Yes, you can do it!

Having the next HTML tag:

<tag key="value"/>

We can access their attributes with JavaScript:

element.getAttribute('key'); // Getter
element.setAttribute('key', 'value'); // Setter

Element.setAttribute() put the attribute in the HTML tag if not exist. So, you dont need to declare it in the HTML code if you are going to set it with JavaScript.

key: could be any name you desire for the attribute, while is not already used for the current tag. value: it's always a string containing what you need.

appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'

My problem was that I had other libraries that my project referenced and those libraries had another version of appcompat referenced. This is what I did to resolve the issue:

(You should back up your project before doing this)

1) I deleted all the appcompat layout folders (ex: /res/layout-v11).

2) Solved the problems that arose from that, usually an error in menu.xml

3) Back to main project and add appcompat library, clean, and everything works!

How to add an ORDER BY clause using CodeIgniter's Active Record methods?

Using this code to multiple order by in single query.

$this->db->from($this->table_name);
$this->db->order_by("column1 asc,column2 desc");
$query = $this->db->get(); 
return $query->result();

How do you delete all text above a certain line

:1,.d deletes lines 1 to current.
:1,.-1d deletes lines 1 to above current.

(Personally I'd use dgg or kdgg like the other answers, but TMTOWTDI.)

How do I cast a string to integer and have 0 in case of error in the cast with PostgreSQL?

If the data is supposed to be integers, and you only need those values as integers, why don't you go the whole mile and convert the column into an integer column?

Then you could do this conversion of illegal values into zeroes just once, at the point of the system where the data is inserted into the table.

With the above conversion you are forcing Postgres to convert those values again and again for each single row in each query for that table - this can seriously degrade performance if you do a lot of queries against this column in this table.

Run PHP function on html button click

Use ajax, a simple example,

HTML

<button id="button">Get Data</button>

Javascript

var button = document.getElementById("button");

button.addEventListener("click" ajaxFunction, false);

var ajaxFunction = function () {
    // ajax code here
}

Alternatively look into jquery ajax http://api.jquery.com/jQuery.ajax/

Java 8 Streams FlatMap method example

Am I the only one who finds unwinding lists boring? ;-)

Let's try with objects. Real world example by the way.

Given: Object representing repetitive task. About important task fields: reminders are starting to ring at start and repeat every repeatPeriod repeatUnit(e.g. 5 HOURS) and there will be repeatCount reminders in total(including starting one).

Goal: achieve a list of task copies, one for each task reminder invocation.

List<Task> tasks =
            Arrays.asList(
                    new Task(
                            false,//completed sign
                            "My important task",//task name (text)
                            LocalDateTime.now().plus(2, ChronoUnit.DAYS),//first reminder(start)
                            true,//is task repetitive?
                            1,//reminder interval
                            ChronoUnit.DAYS,//interval unit
                            5//total number of reminders
                    )
            );

tasks.stream().flatMap(
        x -> LongStream.iterate(
                x.getStart().toEpochSecond(ZoneOffset.UTC),
                p -> (p + x.getRepeatPeriod()*x.getRepeatUnit().getDuration().getSeconds())
        ).limit(x.getRepeatCount()).boxed()
        .map( y -> new Task(x,LocalDateTime.ofEpochSecond(y,0,ZoneOffset.UTC)))
).forEach(System.out::println);

Output:

Task{completed=false, text='My important task', start=2014-10-01T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-02T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-03T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-04T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-05T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}

P.S.: I would appreciate if someone suggested a simpler solution, I'm not a pro after all.

UPDATE: @RBz asked for detailed explanation so here it is. Basically flatMap puts all elements from streams inside another stream into output stream. A lot of streams here :). So, for each Task in initial stream lambda expression x -> LongStream.iterate... creates a stream of long values that represent task start moments. This stream is limited to x.getRepeatCount() instances. It's values start from x.getStart().toEpochSecond(ZoneOffset.UTC) and each next value is calculated using lambda p -> (p + x.getRepeatPeriod()*x.getRepeatUnit().getDuration().getSeconds(). boxed() returns the stream with each long value as a Long wrapper instance. Then each Long in that stream is mapped to new Task instance that is not repetitive anymore and contains exact execution time. This sample contains only one Task in input list. But imagine that you have a thousand. You will have then a stream of 1000 streams of Task objects. And what flatMap does here is putting all Tasks from all streams onto the same output stream. That's all as I understand it. Thank you for your question!

Create a table without a header in Markdown

$ cat foo.md
Key 1 | Value 1
Key 2 | Value 2
$ kramdown foo.md
<table>
  <tbody>
    <tr>
      <td>Key 1</td>
      <td>Value 1</td>
    </tr>
    <tr>
      <td>Key 2</td>
      <td>Value 2</td>
    </tr>
  </tbody>
</table>

Add new item in existing array in c#.net

Why not try out using the Stringbuilder class. It has methods such as .insert and .append. You can read more about it here: http://msdn.microsoft.com/en-us/library/2839d5h5(v=vs.71).aspx

cc1plus: error: unrecognized command line option "-std=c++11" with g++

I also got same error, compiling with -D flag fixed it, Try this:

g++ -Dstd=c++11

Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6

All answers here are using gradle but if someone like me ends up here and needs answer for maven:

    <build>
        <sourceDirectory>src/main/kotlin</sourceDirectory>
        <testSourceDirectory>src/test/kotlin</testSourceDirectory>

        <plugins>
            <plugin>
                <groupId>org.jetbrains.kotlin</groupId>
                <artifactId>kotlin-maven-plugin</artifactId>
                <version>${kotlin.version}</version>
                <executions>
                    <execution>
                        <id>compile</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>test-compile</id>
                        <phase>test-compile</phase>
                        <goals>
                            <goal>test-compile</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <jvmTarget>11</jvmTarget>
                </configuration>
            </plugin>
        </plugins>
    </build>

The change from jetbrains archetype for kotlin-jvm is the <configuration></configuration> specifying the jvmTarget. In my case 11

What does "connection reset by peer" mean?

This means that a TCP RST was received and the connection is now closed. This occurs when a packet is sent from your end of the connection but the other end does not recognize the connection; it will send back a packet with the RST bit set in order to forcibly close the connection.

This can happen if the other side crashes and then comes back up or if it calls close() on the socket while there is data from you in transit, and is an indication to you that some of the data that you previously sent may not have been received.

It is up to you whether that is an error; if the information you were sending was only for the benefit of the remote client then it may not matter that any final data may have been lost. However you should close the socket and free up any other resources associated with the connection.

Progress during large file copy (Copy-Item & Write-Progress?)

i found none of the examples above met my needs, i wanted to copy a directory with sub directories, the problem is my source directory had too many files so i quickly hit the BITS file limit (i had > 1500 file) also the total directory size was quite large.

i found a function using robocopy that was a good starting point at https://keithga.wordpress.com/2014/06/23/copy-itemwithprogress/, however i found it wasn't quite robust enough, it didn't handle trailing slashes, spaces gracefully and did not stop the copy when the script was halted.

Here is my refined version:

function Copy-ItemWithProgress
{
    <#
    .SYNOPSIS
    RoboCopy with PowerShell progress.

    .DESCRIPTION
    Performs file copy with RoboCopy. Output from RoboCopy is captured,
    parsed, and returned as Powershell native status and progress.

    .PARAMETER Source
    Directory to copy files from, this should not contain trailing slashes

    .PARAMETER Destination
    DIrectory to copy files to, this should not contain trailing slahes

    .PARAMETER FilesToCopy
    A wildcard expresion of which files to copy, defaults to *.*

    .PARAMETER RobocopyArgs
    List of arguments passed directly to Robocopy.
    Must not conflict with defaults: /ndl /TEE /Bytes /NC /nfl /Log

    .PARAMETER ProgressID
    When specified (>=0) will use this identifier for the progress bar

    .PARAMETER ParentProgressID
    When specified (>= 0) will use this identifier as the parent ID for progress bars
    so that they appear nested which allows for usage in more complex scripts.

    .OUTPUTS
    Returns an object with the status of final copy.
    REMINDER: Any error level below 8 can be considered a success by RoboCopy.

    .EXAMPLE
    C:\PS> .\Copy-ItemWithProgress c:\Src d:\Dest

    Copy the contents of the c:\Src directory to a directory d:\Dest
    Without the /e or /mir switch, only files from the root of c:\src are copied.

    .EXAMPLE
    C:\PS> .\Copy-ItemWithProgress '"c:\Src Files"' d:\Dest /mir /xf *.log -Verbose

    Copy the contents of the 'c:\Name with Space' directory to a directory d:\Dest
    /mir and /XF parameters are passed to robocopy, and script is run verbose

    .LINK
    https://keithga.wordpress.com/2014/06/23/copy-itemwithprogress

    .NOTES
    By Keith S. Garner ([email protected]) - 6/23/2014
    With inspiration by Trevor Sullivan @pcgeek86
    Tweaked by Justin Marshall - 02/20/2020

    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [string]$Source,
        [Parameter(Mandatory=$true)]
        [string]$Destination,
        [Parameter(Mandatory=$false)]
        [string]$FilesToCopy="*.*",
        [Parameter(Mandatory = $true,ValueFromRemainingArguments=$true)] 
        [string[]] $RobocopyArgs,
        [int]$ParentProgressID=-1,
        [int]$ProgressID=-1
    )

    #handle spaces and trailing slashes
    $SourceDir = '"{0}"' -f ($Source -replace "\\+$","")
    $TargetDir = '"{0}"' -f ($Destination -replace "\\+$","")


    $ScanLog  = [IO.Path]::GetTempFileName()
    $RoboLog  = [IO.Path]::GetTempFileName()
    $ScanArgs = @($SourceDir,$TargetDir,$FilesToCopy) + $RobocopyArgs + "/ndl /TEE /bytes /Log:$ScanLog /nfl /L".Split(" ")
    $RoboArgs = @($SourceDir,$TargetDir,$FilesToCopy) + $RobocopyArgs + "/ndl /TEE /bytes /Log:$RoboLog /NC".Split(" ")

    # Launch Robocopy Processes
    write-verbose ("Robocopy Scan:`n" + ($ScanArgs -join " "))
    write-verbose ("Robocopy Full:`n" + ($RoboArgs -join " "))
    $ScanRun = start-process robocopy -PassThru -WindowStyle Hidden -ArgumentList $ScanArgs
    try
    {
        $RoboRun = start-process robocopy -PassThru -WindowStyle Hidden -ArgumentList $RoboArgs
        try
        {
            # Parse Robocopy "Scan" pass
            $ScanRun.WaitForExit()
            $LogData = get-content $ScanLog
            if ($ScanRun.ExitCode -ge 8)
            {
                $LogData|out-string|Write-Error
                throw "Robocopy $($ScanRun.ExitCode)"
            }
            $FileSize = [regex]::Match($LogData[-4],".+:\s+(\d+)\s+(\d+)").Groups[2].Value
            write-verbose ("Robocopy Bytes: $FileSize `n" +($LogData -join "`n"))
            #determine progress parameters
            $ProgressParms=@{}
            if ($ParentProgressID -ge 0) {
                $ProgressParms['ParentID']=$ParentProgressID
            }
            if ($ProgressID -ge 0) {
                $ProgressParms['ID']=$ProgressID
            } else {
                $ProgressParms['ID']=$RoboRun.Id
            }
            # Monitor Full RoboCopy
            while (!$RoboRun.HasExited)
            {
                $LogData = get-content $RoboLog
                $Files = $LogData -match "^\s*(\d+)\s+(\S+)"
                if ($null -ne $Files )
                {
                    $copied = ($Files[0..($Files.Length-2)] | ForEach-Object {$_.Split("`t")[-2]} | Measure-Object -sum).Sum
                    if ($LogData[-1] -match "(100|\d?\d\.\d)\%")
                    {
                        write-progress Copy -ParentID $ProgressParms['ID'] -percentComplete $LogData[-1].Trim("% `t") $LogData[-1]
                        $Copied += $Files[-1].Split("`t")[-2] /100 * ($LogData[-1].Trim("% `t"))
                    }
                    else
                    {
                        write-progress Copy -ParentID $ProgressParms['ID'] -Complete
                    }
                    write-progress ROBOCOPY  -PercentComplete ($Copied/$FileSize*100) $Files[-1].Split("`t")[-1] @ProgressParms
                }
            }
        } finally {
            if (!$RoboRun.HasExited) {Write-Warning "Terminating copy process with ID $($RoboRun.Id)..."; $RoboRun.Kill() ; }
            $RoboRun.WaitForExit()
            # Parse full RoboCopy pass results, and cleanup
            (get-content $RoboLog)[-11..-2] | out-string | Write-Verbose
            remove-item $RoboLog
            write-output ([PSCustomObject]@{ ExitCode = $RoboRun.ExitCode })

        }
    } finally {
        if (!$ScanRun.HasExited) {Write-Warning "Terminating scan process with ID $($ScanRun.Id)..."; $ScanRun.Kill() }
        $ScanRun.WaitForExit()

        remove-item $ScanLog
    }
}

Can someone give an example of cosine similarity, in a very simple, graphical way?

For simplicity I am reducing the vector a and b:

Let :
    a : [1, 1, 0]
    b : [1, 0, 1]

Then cosine similarity (Theta):

 (Theta) = (1*1 + 1*0 + 0*1)/sqrt((1^2 + 1^2))* sqrt((1^2 + 1^2)) = 1/2 = 0.5

then inverse of cos 0.5 is 60 degrees.

Return background color of selected cell

Maybe you can use this properties:

ActiveCell.Interior.ColorIndex - one of 56 preset colors

and

ActiveCell.Interior.Color - RGB color, used like that:

ActiveCell.Interior.Color = RGB(255,255,255)

Count how many rows have the same value

SELECT SUM(IF(your_column=3,1,0)) FROM your_table WHERE your_where_contion='something';

e.g. for you query:-

SELECT SUM(IF(num=1,1,0)) FROM your_table_name;

Python 3.1.1 string to hex

base64.b16encode and base64.b16decode convert bytes to and from hex and work across all Python versions. The codecs approach also works, but is less straightforward in Python 3.

How to find which views are using a certain table in SQL Server (2008)?

I find this works better:

SELECT type, *
FROM sys.objects
WHERE OBJECT_DEFINITION(object_id) LIKE '%' + @ObjectName + '%'
AND type IN ('V')
ORDER BY name

Filtering VIEW_DEFINTION inside INFORMATION_SCHEMA.VIEWS is giving me quite a few false positives.

How can I set the maximum length of 6 and minimum length of 6 in a textbox?

Addition to Alex' answer:

JavaScript

$(function() {
    $('input[type="submit"]').prop('disabled', true);
    $('#check').on('input', function(e) {
        if(this.value.length === 6) {
            $('input[type="submit"]').prop('disabled', false);
        } else {
            $('input[type="submit"]').prop('disabled', true);
        }
    });
});

HTML

<input type="text" maxlength="6" id="check" data-minlength="6" /><br />
<input type="submit" value="send" />

JsFiddle

But: You should always remember to validate the user input on the server side again. The user could modify the local HTML or disable JavaScript.

pip install failing with: OSError: [Errno 13] Permission denied on directory

You are trying to install a package on the system-wide path without having the permission to do so.

  1. In general, you can use sudo to temporarily obtain superuser permissions at your responsibility in order to install the package on the system-wide path:

     sudo pip install -r requirements.txt
    

    Find more about sudo here.

    Actually, this is a bad idea and there's no good use case for it, see @wim's comment.

  2. If you don't want to make system-wide changes, you can install the package on your per-user path using the --user flag.

    All it takes is:

     pip install --user runloop requirements.txt
    
  3. Finally, for even finer grained control, you can also use a virtualenv, which might be the superior solution for a development environment, especially if you are working on multiple projects and want to keep track of each one's dependencies.

    After activating your virtualenv with

    $ my-virtualenv/bin/activate

    the following command will install the package inside the virtualenv (and not on the system-wide path):

    pip install -r requirements.txt

Change Title of Javascript Alert

As others have said, you can't do that either using alert()or confirm().

You can, however, create an external HTML document containing your error message and an OK button, set its <title> element to whatever you want, then display it in a modal dialog box using showModalDialog().

What are the advantages and disadvantages of recursion?

We should use recursion in following scenarios:

  • when we don't know the finite number of iteration for example our fuction exit condition is based on dynamic programming (memoization)
  • when we need to perform operations on reverse order of the elements. Meaning we want to process last element first and then n-1, n-2 and so on till first element

Recursion will save multiple traversals. And it will be useful, if we can divide the stack allocation like:

int N = 10;
int output = process(N) + process(N/2);
public void process(int n) {
    if (n==N/2 + 1 || n==1) {
       return 1;
    }

    return process(n-1) + process(n-2);
}

In this case only half stacks will be allocated at any given time.

Reading HTML content from a UIWebView

In Swift v3:

let doc = webView.stringByEvaluatingJavaScript(from: "document.documentElement.outerHTML")

Environment variables in Jenkins

What ultimately worked for me was the following steps:

  1. Configure the Environment Injector Plugin: https://wiki.jenkins-ci.org/display/JENKINS/EnvInject+Plugin
  2. Goto to the /job//configure screen
  3. In Build Environment section check "Inject environment variables to the build process"
  4. In "Properties Content" specified: TZ=America/New_York

Blur the edges of an image or background image with CSS

<html>
<head>
<meta charset="utf-8">
<title>test</title>

<style>
#grad1 {
  height: 400px;
  width: 600px;
  background-image: url(t1.jpg);/* Select Image Hare */
}


#gradup {
  height: 100%;
  width: 100%;
  background: radial-gradient(transparent 20%, white 70%); /* Set radial-gradient to faded edges */

}
</style>

</head>

<body>
<h1>Fade Image Edge With Radial Gradient</h1>

<div id="grad1"><div id="gradup"></div></div>

</body>
</html>

How to JSON serialize sets?

If you need just quick dump and don't want to implement custom encoder. You can use the following:

json_string = json.dumps(data, iterable_as_array=True)

This will convert all sets (and other iterables) into arrays. Just beware that those fields will stay arrays when you parse the json back. If you want to preserve the types, you need to write custom encoder.

How is the java memory pool divided?

Heap memory

The heap memory is the runtime data area from which the Java VM allocates memory for all class instances and arrays. The heap may be of a fixed or variable size. The garbage collector is an automatic memory management system that reclaims heap memory for objects.

  • Eden Space: The pool from which memory is initially allocated for most objects.

  • Survivor Space: The pool containing objects that have survived the garbage collection of the Eden space.

  • Tenured Generation or Old Gen: The pool containing objects that have existed for some time in the survivor space.

Non-heap memory

Non-heap memory includes a method area shared among all threads and memory required for the internal processing or optimization for the Java VM. It stores per-class structures such as a runtime constant pool, field and method data, and the code for methods and constructors. The method area is logically part of the heap but, depending on the implementation, a Java VM may not garbage collect or compact it. Like the heap memory, the method area may be of a fixed or variable size. The memory for the method area does not need to be contiguous.

  • Permanent Generation: The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas.

  • Code Cache: The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code.

Here's some documentation on how to use Jconsole.

Why are Python lambdas useful?

I use it quite often, mainly as a null object or to partially bind parameters to a function.

Here are examples:

to implement null object pattern:

{
    DATA_PACKET: self.handle_data_packets
    NET_PACKET: self.handle_hardware_packets
}.get(packet_type, lambda x : None)(payload)

for parameter binding:

let say that I have the following API

def dump_hex(file, var)
    # some code
    pass

class X(object):
    #...
    def packet_received(data):
        # some kind of preprocessing
        self.callback(data)
    #...

Then, when I wan't to quickly dump the recieved data to a file I do that:

dump_file = file('hex_dump.txt','w')
X.callback = lambda (x): dump_hex(dump_file, x)
...
dump_file.close()

How to undo local changes to a specific file

You don't want git revert. That undoes a previous commit. You want git checkout to get git's version of the file from master.

git checkout -- filename.txt

In general, when you want to perform a git operation on a single file, use -- filename.



2020 Update

Git introduced a new command git restore in version 2.23.0. Therefore, if you have git version 2.23.0+, you can simply git restore filename.txt - which does the same thing as git checkout -- filename.txt. The docs for this command do note that it is currently experimental.

How to make a link open multiple pages when clicked

HTML:

<a href="#" class="yourlink">Click Here</a>

JS:

$('a.yourlink').click(function(e) {
    e.preventDefault();
    window.open('http://yoururl1.com');
    window.open('http://yoururl2.com');
});

window.open also can take additional parameters. See them here: http://www.javascript-coder.com/window-popup/javascript-window-open.phtml

You should also know that window.open is sometimes blocked by popup blockers and/or ad-filters.

Addition from Paul below: This approach also places a dependency on JavaScript being enabled. Not typically a good idea, but sometimes necessary.

MySQL Error 1153 - Got a packet bigger than 'max_allowed_packet' bytes

In etc/my.cnf try changing the max_allowed _packet and net_buffer_length to

max_allowed_packet=100000000
net_buffer_length=1000000 

if this is not working then try changing to

max_allowed_packet=100M
net_buffer_length=100K 

Disable and later enable all table indexes in Oracle

If you're on Oracle 11g, you may also want to check out dbms_index_utl.

Install specific version using laravel installer

Via composer installing specific version 7.*

composer create-project --prefer-dist laravel/laravel:^7.0 project_name

To install specific version 6.* and below use the following command:

composer create-project --prefer-dist laravel/laravel project_name "6.*"

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

If you have a rooted device you can use kill command

Connect to your device with adb:

adb shell

Once the session is established, you have to escalade privileges:

su

Then

ps

will list running processes. Note down the PID of the process you want to terminate. Then get rid of it

kill PID

Django -- Template tag in {% if %} block

{% for source in sources %}
  <tr>
    <td>{{ source }}</td>
    <td>
      {% ifequal title source %}
        Just now!
      {% endifequal %}
    </td>
  </tr>
{% endfor %}

                or


{% for source in sources %}
      <tr>
        <td>{{ source }}</td>
        <td>
          {% if title == source %}
            Just now!
          {% endif %}
        </td>
      </tr>
    {% endfor %}

See Django Doc

How to get HTTP response code for a URL in Java?

This has worked for me :

            import org.apache.http.client.HttpClient;
            import org.apache.http.client.methods.HttpGet;  
            import org.apache.http.impl.client.DefaultHttpClient;
            import org.apache.http.HttpResponse;
            import java.io.BufferedReader;
            import java.io.InputStreamReader;



            public static void main(String[] args) throws Exception {   
                        HttpClient client = new DefaultHttpClient();
                        //args[0] ="http://hostname:port/xyz/zbc";
                        HttpGet request1 = new HttpGet(args[0]);
                        HttpResponse response1 = client.execute(request1);
                        int code = response1.getStatusLine().getStatusCode();

                         try(BufferedReader br = new BufferedReader(new InputStreamReader((response1.getEntity().getContent())));){
                            // Read in all of the post results into a String.
                            String output = "";
                            Boolean keepGoing = true;
                            while (keepGoing) {
                                String currentLine = br.readLine();          
                                if (currentLine == null) {
                                    keepGoing = false;
                                } else {
                                    output += currentLine;
                                }
                            }
                            System.out.println("Response-->"+output);   
                         }

                         catch(Exception e){
                              System.out.println("Exception"+e);  

                          }


                   }

How can I save application settings in a Windows Forms application?

A simple way is to use a configuration data object, save it as an XML file with the name of the application in the local Folder and on startup read it back.

Here is an example to store the position and size of a form.

The configuration dataobject is strongly typed and easy to use:

[Serializable()]
public class CConfigDO
{
    private System.Drawing.Point m_oStartPos;
    private System.Drawing.Size m_oStartSize;

    public System.Drawing.Point StartPos
    {
        get { return m_oStartPos; }
        set { m_oStartPos = value; }
    }

    public System.Drawing.Size StartSize
    {
        get { return m_oStartSize; }
        set { m_oStartSize = value; }
    }
}

A manager class for saving and loading:

public class CConfigMng
{
    private string m_sConfigFileName = System.IO.Path.GetFileNameWithoutExtension(System.Windows.Forms.Application.ExecutablePath) + ".xml";
    private CConfigDO m_oConfig = new CConfigDO();

    public CConfigDO Config
    {
        get { return m_oConfig; }
        set { m_oConfig = value; }
    }

    // Load configuration file
    public void LoadConfig()
    {
        if (System.IO.File.Exists(m_sConfigFileName))
        {
            System.IO.StreamReader srReader = System.IO.File.OpenText(m_sConfigFileName);
            Type tType = m_oConfig.GetType();
            System.Xml.Serialization.XmlSerializer xsSerializer = new System.Xml.Serialization.XmlSerializer(tType);
            object oData = xsSerializer.Deserialize(srReader);
            m_oConfig = (CConfigDO)oData;
            srReader.Close();
        }
    }

    // Save configuration file
    public void SaveConfig()
    {
        System.IO.StreamWriter swWriter = System.IO.File.CreateText(m_sConfigFileName);
        Type tType = m_oConfig.GetType();
        if (tType.IsSerializable)
        {
            System.Xml.Serialization.XmlSerializer xsSerializer = new System.Xml.Serialization.XmlSerializer(tType);
            xsSerializer.Serialize(swWriter, m_oConfig);
            swWriter.Close();
        }
    }
}

Now you can create an instance and use in your form's load and close events:

    private CConfigMng oConfigMng = new CConfigMng();

    private void Form1_Load(object sender, EventArgs e)
    {
        // Load configuration
        oConfigMng.LoadConfig();
        if (oConfigMng.Config.StartPos.X != 0 || oConfigMng.Config.StartPos.Y != 0)
        {
            Location = oConfigMng.Config.StartPos;
            Size = oConfigMng.Config.StartSize;
        }
    }

    private void Form1_FormClosed(object sender, FormClosedEventArgs e)
    {
        // Save configuration
        oConfigMng.Config.StartPos = Location;
        oConfigMng.Config.StartSize = Size;
        oConfigMng.SaveConfig();
    }

And the produced XML file is also readable:

<?xml version="1.0" encoding="utf-8"?>
<CConfigDO xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <StartPos>
    <X>70</X>
    <Y>278</Y>
  </StartPos>
  <StartSize>
    <Width>253</Width>
    <Height>229</Height>
  </StartSize>
</CConfigDO>

Length of array in function argument

First, a better usage to compute number of elements when the actual array declaration is in scope is:

sizeof array / sizeof array[0]

This way you don't repeat the type name, which of course could change in the declaration and make you end up with an incorrect length computation. This is a typical case of don't repeat yourself.

Second, as a minor point, please note that sizeof is not a function, so the expression above doesn't need any parenthesis around the argument to sizeof.

Third, C doesn't have references so your usage of & in a declaration won't work.

I agree that the proper C solution is to pass the length (using the size_t type) as a separate argument, and use sizeof at the place the call is being made if the argument is a "real" array.

Note that often you work with memory returned by e.g. malloc(), and in those cases you never have a "true" array to compute the size off of, so designing the function to use an element count is more flexible.

Drop-down box dependent on the option selected in another drop-down box

In this jsfiddle you'll find a solution I deviced. The idea is to have a selector pair in html and use (plain) javascript to filter the options in the dependent selector, based on the selected option of the first. For example:

<select id="continents">
 <option value = 0>All</option>   
 <option value = 1>Asia</option>
 <option value = 2>Europe</option>
 <option value = 3>Africa</option>
</select> 
<select id="selectcountries"></select>

Uses (in the jsFiddle)

 MAIN.createRelatedSelector
     ( document.querySelector('#continents')           // from select element
      ,document.querySelector('#selectcountries')      // to select element
      ,{                                               // values object 
        Asia: ['China','Japan','North Korea',
               'South Korea','India','Malaysia',
               'Uzbekistan'],
        Europe: ['France','Belgium','Spain','Netherlands','Sweden','Germany'],
        Africa: ['Mali','Namibia','Botswana','Zimbabwe','Burkina Faso','Burundi']
      }
      ,function(a,b){return a>b ? 1 : a<b ? -1 : 0;}   // sort method
 );

[Edit 2021] or use data-attributes, something like:

_x000D_
_x000D_
document.addEventListener("change", checkSelect);

function checkSelect(evt) {
  const origin = evt.target;

  if (origin.dataset.dependentSelector) {
    const selectedOptFrom = origin.querySelector("option:checked")
      .dataset.dependentOpt || "n/a";
    const addRemove = optData => (optData || "") === selectedOptFrom 
      ? "add" : "remove";
    document.querySelectorAll(`${origin.dataset.dependentSelector} option`)
      .forEach( opt => 
        opt.classList[addRemove(opt.dataset.fromDependent)]("display") );
  }
}
_x000D_
[data-from-dependent] {
  display: none;
}

[data-from-dependent].display {
  display: initial;
}
_x000D_
<select id="source" name="source" data-dependent-selector="#status">
  <option>MANUAL</option>
  <option data-dependent-opt="ONLINE">ONLINE</option>
  <option data-dependent-opt="UNKNOWN">UNKNOWN</option>
</select>

<select id="status" name="status">
  <option>OPEN</option>
  <option>DELIVERED</option>
  <option data-from-dependent="ONLINE">SHIPPED</option>
  <option data-from-dependent="UNKNOWN">SHOULD SELECT</option>
  <option data-from-dependent="UNKNOWN">MAYBE IN TRANSIT</option>
</select>
_x000D_
_x000D_
_x000D_

Day Name from Date in JS

One more option is to use the inbuilt function Intl.DateTimeFormat, e.g.:

_x000D_
_x000D_
function getDayName(dateString) {
    const [date, options] = [new Date(dateString), {weekday: 'long'}];
    return new Intl.DateTimeFormat('en-Us', options).format(date);
}
_x000D_
<label for="inp">Enter a date string in the format "MM/DD/YYYY" or "YYYY-MM-DD" and press "OK":</label><br>
<input type="text" id="inp" value="01/31/2021">
<button onclick="alert(getDayName(document.getElementById('inp').value))">OK</button>
_x000D_
_x000D_
_x000D_

CURL to access a page that requires a login from a different page

The web site likely uses cookies to store your session information. When you run

curl --user user:pass https://xyz.com/a  #works ok
curl https://xyz.com/b #doesn't work

curl is run twice, in two separate sessions. Thus when the second command runs, the cookies set by the 1st command are not available; it's just as if you logged in to page a in one browser session, and tried to access page b in a different one.

What you need to do is save the cookies created by the first command:

curl --user user:pass --cookie-jar ./somefile https://xyz.com/a

and then read them back in when running the second:

curl --cookie ./somefile https://xyz.com/b

Alternatively you can try downloading both files in the same command, which I think will use the same cookies.

Repository Pattern Step by Step Explanation

As a summary, I would describe the wider impact of the repository pattern. It allows all of your code to use objects without having to know how the objects are persisted. All of the knowledge of persistence, including mapping from tables to objects, is safely contained in the repository.

Very often, you will find SQL queries scattered in the codebase and when you come to add a column to a table you have to search code files to try and find usages of a table. The impact of the change is far-reaching.

With the repository pattern, you would only need to change one object and one repository. The impact is very small.

Perhaps it would help to think about why you would use the repository pattern. Here are some reasons:

  • You have a single place to make changes to your data access

  • You have a single place responsible for a set of tables (usually)

  • It is easy to replace a repository with a fake implementation for testing - so you don't need to have a database available to your unit tests

There are other benefits too, for example, if you were using MySQL and wanted to switch to SQL Server - but I have never actually seen this in practice!

How do I create an iCal-type .ics file that can be downloaded by other users?

There is also this tool you can use. It supports multi-events .ics file creation. It also supports timezone as well.

http://apps.marudot.com/ical/

Android Studio : How to uninstall APK (or execute adb command) automatically before Run or Debug?

This command with --user 0 do the job:

adb uninstall --user 0 <package_name>

How do I get sed to read from standard input?

To make sed catch from stdin , instead of from a file, you should use -e.

Like this:

curl -k -u admin:admin https://$HOSTNAME:9070/api/tm/3.8/status/$HOSTNAME/statistics/traffic_ips/trafc_ip/ | sed -e 's/["{}]//g' |sed -e 's/[]]//g' |sed -e 's/[\[]//g' |awk  'BEGIN{FS=":"} {print $4}'

How to reset sequence in postgres and fill id column with new data?

Even the auto-increment column is not PK ( in this example it is called seq - aka sequence ) you could achieve that with a trigger :

DROP TABLE IF EXISTS devops_guide CASCADE;

SELECT 'create the "devops_guide" table'
;
   CREATE TABLE devops_guide (
      guid           UUID NOT NULL DEFAULT gen_random_uuid()
    , level          integer NULL
    , seq            integer NOT NULL DEFAULT 1
    , name           varchar (200) NOT NULL DEFAULT 'name ...'
    , description    text NULL
    , CONSTRAINT pk_devops_guide_guid PRIMARY KEY (guid)
    ) WITH (
      OIDS=FALSE
    );

-- START trg_devops_guide_set_all_seq
CREATE OR REPLACE FUNCTION fnc_devops_guide_set_all_seq()
    RETURNS TRIGGER
    AS $$
       BEGIN
         UPDATE devops_guide SET seq=col_serial FROM
         (SELECT guid, row_number() OVER ( ORDER BY seq) AS col_serial FROM devops_guide ORDER BY seq) AS tmp_devops_guide
         WHERE devops_guide.guid=tmp_devops_guide.guid;

         RETURN NEW;
       END;
    $$ LANGUAGE plpgsql;

 CREATE TRIGGER trg_devops_guide_set_all_seq
  AFTER UPDATE OR DELETE ON devops_guide
  FOR EACH ROW
  WHEN (pg_trigger_depth() < 1)
  EXECUTE PROCEDURE fnc_devops_guide_set_all_seq();

Remove portion of a string after a certain character

If you're using PHP 5.3+ take a look at the $before_needle flag of strstr()

$s = 'Posted On April 6th By Some Dude';
echo strstr($s, 'By', true);

How to create an empty array in Swift?

As per Swift 5

    // An array of 'Int' elements
    let oddNumbers = [1, 3, 5, 7, 9, 11, 13, 15]

    // An array of 'String' elements
    let streets = ["Albemarle", "Brandywine", "Chesapeake"]

    // Shortened forms are preferred
    var emptyDoubles: [Double] = []

    // The full type name is also allowed
    var emptyFloats: Array<Float> = Array()

Counting the number of occurences of characters in a string

I think what you are looking for is this:

public class Ques2 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String input = br.readLine().toLowerCase();
    StringBuilder result = new StringBuilder();
    char currentCharacter;
    int count;

    for (int i = 0; i < input.length(); i++) {
        currentCharacter = input.charAt(i);
        count = 1;
        while (i < input.length() - 1 && input.charAt(i + 1) == currentCharacter) {
            count++;
            i++;
        }
        result.append(currentCharacter);
        result.append(count);
    }

    System.out.println("" + result);
}

}

jQuery AJAX cross domain

JSONP is a good option, but there is an easier way. You can simply set the Access-Control-Allow-Origin header on your server. Setting it to * will accept cross-domain AJAX requests from any domain. (https://developer.mozilla.org/en/http_access_control)

The method to do this will vary from language to language, of course. Here it is in Rails:

class HelloController < ApplicationController
  def say_hello
    headers['Access-Control-Allow-Origin'] = "*"
    render text: "hello!"
  end
end

In this example, the say_hello action will accept AJAX requests from any domain and return a response of "hello!".

Here is an example of the headers it might return:

HTTP/1.1 200 OK 
Access-Control-Allow-Origin: *
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Type: text/html; charset=utf-8
X-Ua-Compatible: IE=Edge
Etag: "c4ca4238a0b923820dcc509a6f75849b"
X-Runtime: 0.913606
Content-Length: 6
Server: WEBrick/1.3.1 (Ruby/1.9.2/2011-07-09)
Date: Thu, 01 Mar 2012 20:44:28 GMT
Connection: Keep-Alive

Easy as it is, it does have some browser limitations. See http://caniuse.com/#feat=cors.

jQuery post() with serialize and extra data

You can use serializeArray [docs] and add the additional data:

var data = $('#myForm').serializeArray();
data.push({name: 'wordlist', value: wordlist});

$.post("page.php", data);

spacing between form fields

In your CSS file:

input { margin-bottom: 10px; }

Emulating a do-while loop in Bash

We can emulate a do-while loop in Bash with while [[condition]]; do true; done like this:

while [[ current_time <= $cutoff ]]
    check_if_file_present
    #do other stuff
do true; done

For an example. Here is my implementation on getting ssh connection in bash script:

#!/bin/bash
while [[ $STATUS != 0 ]]
    ssh-add -l &>/dev/null; STATUS="$?"
    if [[ $STATUS == 127 ]]; then echo "ssh not instaled" && exit 0;
    elif [[ $STATUS == 2 ]]; then echo "running ssh-agent.." && eval `ssh-agent` > /dev/null;
    elif [[ $STATUS == 1 ]]; then echo "get session identity.." && expect $HOME/agent &> /dev/null;
    else ssh-add -l && git submodule update --init --recursive --remote --merge && return 0; fi
do true; done

It will give the output in sequence as below:

Step #0 - "gcloud": intalling expect..
Step #0 - "gcloud": running ssh-agent..
Step #0 - "gcloud": get session identity..
Step #0 - "gcloud": 4096 SHA256:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX /builder/home/.ssh/id_rsa (RSA)
Step #0 - "gcloud": Submodule '.google/cloud/compute/home/chetabahana/.docker/compose' ([email protected]:chetabahana/compose) registered for path '.google/cloud/compute/home/chetabahana/.docker/compose'
Step #0 - "gcloud": Cloning into '/workspace/.io/.google/cloud/compute/home/chetabahana/.docker/compose'...
Step #0 - "gcloud": Warning: Permanently added the RSA host key for IP address 'XXX.XX.XXX.XXX' to the list of known hosts.
Step #0 - "gcloud": Submodule path '.google/cloud/compute/home/chetabahana/.docker/compose': checked out '24a28a7a306a671bbc430aa27b83c09cc5f1c62d'
Finished Step #0 - "gcloud"

Mongoose query where value is not null

Hello guys I am stucked with this. I've a Document Profile who has a reference to User,and I've tried to list the profiles where user ref is not null (because I already filtered by rol during the population), but after googleing a few hours I cannot figure out how to get this. I have this query:

const profiles = await Profile.find({ user: {$exists: true,  $ne: null }})
                            .select("-gallery")
                            .sort( {_id: -1} )
                            .skip( skip )
                            .limit(10)
                            .select(exclude)
                            .populate({
                                path: 'user',
                                match: { role: {$eq: customer}},
                                select: '-password -verified -_id -__v'
                              })

                            .exec();

And I get this result, how can I remove from the results the user:null colletions? . I meant, I dont want to get the profile when user is null (the role does not match).
{
    "code": 200,
    "profiles": [
        {
            "description": null,
            "province": "West Midlands",
            "country": "UK",
            "postal_code": "83000",
            "user": null
        },
        {
            "description": null,

            "province": "Madrid",
            "country": "Spain",
            "postal_code": "43000",
            "user": {
                "role": "customer",
                "name": "pedrita",
                "email": "[email protected]",
                "created_at": "2020-06-05T11:05:36.450Z"
            }
        }
    ],
    "page": 1
}

Thanks in advance.

How can I merge the columns from two tables into one output?

Specifying the columns on your query should do the trick:

select a.col1, b.col2, a.col3, b.col4, a.category_id 
from items_a a, items_b b 
where a.category_id = b.category_id

should do the trick with regards to picking the columns you want.

To get around the fact that some data is only in items_a and some data is only in items_b, you would be able to do:

select 
  coalesce(a.col1, b.col1) as col1, 
  coalesce(a.col2, b.col2) as col2,
  coalesce(a.col3, b.col3) as col3,
  a.category_id
from items_a a, items_b b
where a.category_id = b.category_id

The coalesce function will return the first non-null value, so for each row if col1 is non null, it'll use that, otherwise it'll get the value from col2, etc.

How to properly import a selfsigned certificate into Java keystore that is available to all Java applications by default?

The simple command 'keytool' also works on Windows and/or with Cygwin.

IF you're using Cygwin here is the modified command that I used from the bottom of "S.Botha's" answer :

  1. make sure you identify the JRE inside the JDK that you will be using
  2. Start your prompt/cygwin as admin
  3. go inside the bin directory of that JDK e.g. cd /cygdrive/c/Program\ Files/Java/jdk1.8.0_121/jre/bin
  4. Execute the keytool command from inside it, where you provide the path to your new Cert at the end, like so:

    ./keytool.exe -import -trustcacerts -keystore ../lib/security/cacerts  -storepass changeit -noprompt -alias myownaliasformysystem -file "D:\Stuff\saved-certs\ca.cert"
    

Notice, because if this is under Cygwin you're giving a path to a non-Cygwin program, so the path is DOS-like and in quotes.

How to get text box value in JavaScript

+1 Gumbo: ‘id’ is the easiest way to access page elements. IE (pre version 8) will return things with a matching ‘name’ if it can't find anything with the given ID, but this is a bug.

i am getting only "software".

id-vs-name won't affect this; I suspect what's happened is that (contrary to the example code) you've forgotten to quote your ‘value’ attribute:

<input type="text" name="txtJob" value=software engineer>

Flutter: Run method on Widget build complete

Flutter 1.2 - dart 2.2

According with the official guidelines and sources if you want to be certain that also the last frame of your layout was drawned you can write for example:

import 'package:flutter/scheduler.dart';

void initState() {
   super.initState();
   if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) {
        SchedulerBinding.instance.addPostFrameCallback((_) => yourFunction(context));
   }
}

How do I change the background color of a plot made with ggplot2

To avoid deprecated opts and theme_rect use:

myplot + theme(panel.background = element_rect(fill='green', colour='red'))

To define your own custom theme, based on theme_gray but with some of your changes and a few added extras including control of gridline colour/size (more options available to play with at ggplot2.org):

theme_jack <- function (base_size = 12, base_family = "") {
    theme_gray(base_size = base_size, base_family = base_family) %+replace% 
        theme(
            axis.text = element_text(colour = "white"),
            axis.title.x = element_text(colour = "pink", size=rel(3)),
            axis.title.y = element_text(colour = "blue", angle=45),
            panel.background = element_rect(fill="green"),
            panel.grid.minor.y = element_line(size=3),
            panel.grid.major = element_line(colour = "orange"),
            plot.background = element_rect(fill="red")
    )   
}

To make your custom theme the default when ggplot is called in future, without masking:

theme_set(theme_jack())

If you want to change an element of the currently set theme:

theme_update(plot.background = element_rect(fill="pink"), axis.title.x = element_text(colour = "red"))

To store the current default theme as an object:

theme_pink <- theme_get()

Note that theme_pink is a list whereas theme_jack was a function. So to return the theme to theme_jack use theme_set(theme_jack()) whereas to return to theme_pink use theme_set(theme_pink).

You can replace theme_gray by theme_bw in the definition of theme_jack if you prefer. For your custom theme to resemble theme_bw but with all gridlines (x, y, major and minor) turned off:

theme_nogrid <- function (base_size = 12, base_family = "") {
    theme_bw(base_size = base_size, base_family = base_family) %+replace% 
        theme(
            panel.grid = element_blank()
    )   
}

Finally a more radical theme useful when plotting choropleths or other maps in ggplot, based on discussion here but updated to avoid deprecation. The aim here is to remove the gray background, and any other features that might distract from the map.

theme_map <- function (base_size = 12, base_family = "") {
    theme_gray(base_size = base_size, base_family = base_family) %+replace% 
        theme(
            axis.line=element_blank(),
            axis.text.x=element_blank(),
            axis.text.y=element_blank(),
            axis.ticks=element_blank(),
            axis.ticks.length=unit(0.3, "lines"),
            axis.ticks.margin=unit(0.5, "lines"),
            axis.title.x=element_blank(),
            axis.title.y=element_blank(),
            legend.background=element_rect(fill="white", colour=NA),
            legend.key=element_rect(colour="white"),
            legend.key.size=unit(1.2, "lines"),
            legend.position="right",
            legend.text=element_text(size=rel(0.8)),
            legend.title=element_text(size=rel(0.8), face="bold", hjust=0),
            panel.background=element_blank(),
            panel.border=element_blank(),
            panel.grid.major=element_blank(),
            panel.grid.minor=element_blank(),
            panel.margin=unit(0, "lines"),
            plot.background=element_blank(),
            plot.margin=unit(c(1, 1, 0.5, 0.5), "lines"),
            plot.title=element_text(size=rel(1.2)),
            strip.background=element_rect(fill="grey90", colour="grey50"),
            strip.text.x=element_text(size=rel(0.8)),
            strip.text.y=element_text(size=rel(0.8), angle=-90) 
        )   
}

How to pass an array to a function in VBA?

This seems unnecessary, but VBA is a strange place. If you declare an array variable, then set it using Array() then pass the variable into your function, VBA will be happy.

Sub test()
    Dim fString As String
    Dim arr() As Variant
    arr = Array("foo", "bar")
    fString = processArr(arr)
End Sub

Also your function processArr() could be written as:

Function processArr(arr() As Variant) As String
    processArr = Replace(Join(arr()), " ", "")
End Function

If you are into the whole brevity thing.

rebase in progress. Cannot commit. How to proceed or stop (abort)?

I got into this state recently. After resolving conflicts during a rebase, I committed my changes, rather than running git rebase --continue. This yields the same messages you saw when you ran your git status and git rebase --continue commands. I resolved the issue by running git rebase --abort, and then re-running the rebase. One could likely also skip the rebase, but I wasn't sure what state that would leave me in.

$ git rebase --continue
Applying: <commit message>
No changes - did you forget to use 'git add'?
If there is nothing left to stage, chances are that something else
already introduced the same changes; you might want to skip this patch.

When you have resolved this problem, run "git rebase --continue".
If you prefer to skip this patch, run "git rebase --skip" instead.
To check out the original branch and stop rebasing, run "git rebase --abort".

$ git status
rebase in progress; onto 4df0775
You are currently rebasing branch '<local-branch-name>' on '4df0775'.
  (all conflicts fixed: run "git rebase --continue")

nothing to commit, working directory clean

Does the target directory for a git clone have to match the repo name?

Yes, it is possible:

git clone https://github.com/pitosalas/st3_packages Packages 

You can specify the local root directory when using git clone.

<directory> 

The name of a new directory to clone into.
The "humanish" part of the source repository is used if no directory is explicitly given (repo for /path/to/repo.git and foo for host.xz:foo/.git).
Cloning into an existing directory is only allowed if the directory is empty.


As Chris comments, you can then rename that top directory.
Git only cares about the .git within said top folder, which you can get with various commands:

git rev-parse --show-toplevel git rev-parse --git-dir 

Tar archiving that takes input from a list of files

Yes:

tar -cvf allfiles.tar -T mylist.txt

What are the best practices for SQLite on Android?

after struggling with this for a couple of hours, I've found that you can only use one db helper object per db execution. For example,

for(int x = 0; x < someMaxValue; x++)
{
    db = new DBAdapter(this);
    try
    {

        db.addRow
        (
                NamesStringArray[i].toString(), 
                StartTimeStringArray[i].toString(),
                EndTimeStringArray[i].toString()
        );

    }
    catch (Exception e)
    {
        Log.e("Add Error", e.toString());
        e.printStackTrace();
    }
    db.close();
}

as apposed to:

db = new DBAdapter(this);
for(int x = 0; x < someMaxValue; x++)
{

    try
    {
        // ask the database manager to add a row given the two strings
        db.addRow
        (
                NamesStringArray[i].toString(), 
                StartTimeStringArray[i].toString(),
                EndTimeStringArray[i].toString()
        );

    }
    catch (Exception e)
    {
        Log.e("Add Error", e.toString());
        e.printStackTrace();
    }

}
db.close();

creating a new DBAdapter each time the loop iterates was the only way I could get my strings into a database through my helper class.

Setting the selected attribute on a select list using jQuery

Code:

var select = function(dropdown, selectedValue) {
    var options = $(dropdown).find("option");
    var matches = $.grep(options,
        function(n) { return $(n).text() == selectedValue; });
    $(matches).attr("selected", "selected");
};

Example:

select("#dropdown", "B");

$_SERVER['HTTP_REFERER'] missing

From the documentation:

The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.

http://php.net/manual/en/reserved.variables.server.php

How to output loop.counter in python jinja template?

Inside of a for-loop block, you can access some special variables including loop.index --but no loop.counter. From the official docs:

Variable    Description
loop.index  The current iteration of the loop. (1 indexed)
loop.index0 The current iteration of the loop. (0 indexed)
loop.revindex   The number of iterations from the end of the loop (1 indexed)
loop.revindex0  The number of iterations from the end of the loop (0 indexed)
loop.first  True if first iteration.
loop.last   True if last iteration.
loop.length The number of items in the sequence.
loop.cycle  A helper function to cycle between a list of sequences. See the explanation below.
loop.depth  Indicates how deep in a recursive loop the rendering currently is. Starts at level 1
loop.depth0 Indicates how deep in a recursive loop the rendering currently is. Starts at level 0
loop.previtem   The item from the previous iteration of the loop. Undefined during the first iteration.
loop.nextitem   The item from the following iteration of the loop. Undefined during the last iteration.
loop.changed(*val)  True if previously called with a different value (or not called at all).

c# write text on bitmap

Very old question, but just had to build this for an app today and found the settings shown in other answers do not result in a clean image (possibly as new options were added in later .Net versions).

Assuming you want the text in the centre of the bitmap, you can do this:

// Load the original image
Bitmap bmp = new Bitmap("filename.bmp");

// Create a rectangle for the entire bitmap
RectangleF rectf = new RectangleF(0, 0, bmp.Width, bmp.Height);

// Create graphic object that will draw onto the bitmap
Graphics g = Graphics.FromImage(bmp);

// ------------------------------------------
// Ensure the best possible quality rendering
// ------------------------------------------
// The smoothing mode specifies whether lines, curves, and the edges of filled areas use smoothing (also called antialiasing). 
// One exception is that path gradient brushes do not obey the smoothing mode. 
// Areas filled using a PathGradientBrush are rendered the same way (aliased) regardless of the SmoothingMode property.
g.SmoothingMode = SmoothingMode.AntiAlias;

// The interpolation mode determines how intermediate values between two endpoints are calculated.
g.InterpolationMode = InterpolationMode.HighQualityBicubic;

// Use this property to specify either higher quality, slower rendering, or lower quality, faster rendering of the contents of this Graphics object.
g.PixelOffsetMode = PixelOffsetMode.HighQuality;

// This one is important
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;

// Create string formatting options (used for alignment)
StringFormat format = new StringFormat()
{
    Alignment = StringAlignment.Center,
    LineAlignment = StringAlignment.Center
};

// Draw the text onto the image
g.DrawString("yourText", new Font("Tahoma",8), Brushes.Black, rectf, format);

// Flush all graphics changes to the bitmap
g.Flush();

// Now save or use the bitmap
image.Image = bmp;

References

SQL Server database backup restore on lower version

No, is not possible to downgrade a database. 10.50.1600 is the SQL Server 2008 R2 version. There is absolutely no way you can restore or attach this database to the SQL Server 2008 instance you are trying to restore on (10.00.1600 is SQL Server 2008). Your only options are:

  • upgrade this instance to SQL Server 2008 R2 or
  • restore the backup you have on a SQL Server 2008 R2 instance, export all the data and import it on a SQL Server 2008 database.

Python xticks in subplots

See the (quite) recent answer on the matplotlib repository, in which the following solution is suggested:

  • If you want to set the xticklabels:

    ax.set_xticks([1,4,5]) 
    ax.set_xticklabels([1,4,5], fontsize=12)
    
  • If you want to only increase the fontsize of the xticklabels, using the default values and locations (which is something I personally often need and find very handy):

    ax.tick_params(axis="x", labelsize=12) 
    
  • To do it all at once:

    plt.setp(ax.get_xticklabels(), fontsize=12, fontweight="bold", 
             horizontalalignment="left")`
    

converting a javascript string to a html object

Had the same issue. I used a dirty trick like so:

var s = '<div id="myDiv"></div>';
var temp = document.createElement('div');
temp.innerHTML = s;
var htmlObject = temp.firstChild;

Now, you can add styles the way you like:

htmlObject.style.marginTop = something;

How print out the contents of a HashMap<String, String> in ascending order based on its values?

You aren't going to be able to do this from the HashMap class alone.

I would take the Map<String, String> codes, construct a reverse map of TreeMap<String, String> reversedMap where you map the values of the codes Map to the keys (this would require your original Map to have a one-to-one mapping from key-to-value). Since the TreeMap provides Iterators which returns entries in ascending key order, this will give you the value/key combination of the first map in the order (sorted by values) you desire.

Map<String, String> reversedMap = new TreeMap<String, String>(codes);

//then you just access the reversedMap however you like...
for (Map.Entry entry : reversedMap.entrySet()) {
    System.out.println(entry.getKey() + ", " + entry.getValue());
}

There are several collections libraries (commons-collections, Google Collections, etc) which have similar bidirectional Map implementations.

How do I get the position selected in a RecyclerView?

Set your onClickListeners on onBindViewHolder() and you can access the position from there. If you set them in your ViewHolder you won't know what position was clicked unless you also pass the position into the ViewHolder

EDIT

As pskink pointed out ViewHolder has a getPosition() so the way you were originally doing it was correct.

When the view is clicked you can use getPosition() in your ViewHolder and it returns the position

Update

getPosition() is now deprecated and replaced with getAdapterPosition()

Update 2020

getAdapterPosition() is now deprecated and replaced with getAbsoluteAdapterPosition() or getBindingAdapterPosition()

Kotlin code:

override fun onBindViewHolder(holder: MyHolder, position: Int) {
        // - get element from your dataset at this position
        val item = myDataset.get(holder.absoluteAdapterPosition)
    }

jquery if div id has children

Another option, just for the heck of it would be:

if ( $('#myFav > *').length > 0 ) {
     // do something
}

May actually be the fastest since it strictly uses the Sizzle engine and not necessarily any jQuery, as it were. Could be wrong though. Nevertheless, it works.

Passing variables, creating instances, self, The mechanics and usage of classes: need explanation

The whole point of a class is that you create an instance, and that instance encapsulates a set of data. So it's wrong to say that your variables are global within the scope of the class: say rather that an instance holds attributes, and that instance can refer to its own attributes in any of its code (via self.whatever). Similarly, any other code given an instance can use that instance to access the instance's attributes - ie instance.whatever.

How to add,set and get Header in request of HttpClient?

On apache page: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html

You have something like this:

URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("www.google.com").setPath("/search")
    .setParameter("q", "httpclient")
    .setParameter("btnG", "Google Search")
    .setParameter("aq", "f")
    .setParameter("oq", "");
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());

Markdown and image alignment

Many Markdown "extra" processors support attributes. So you can include a class name like so (PHP Markdown Extra):

![Flowers](/flowers.jpeg){.callout}

or, alternatively (Maruku, Kramdown, Python Markdown):

![Flowers](/flowers.jpeg){: .callout}

Then, of course, you can use a stylesheet the proper way:

.callout {
    float: right;
}

If yours supports this syntax, it gives you the best of both worlds: no embedded markup, and a stylesheet abstract enough to not need to be modified by your content editor.

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

UPDATE: 2019-12-30

It seem that this tool is no longer working! [Request for update!]

UPDATE 2019-01-06: You can bypass X-Frame-Options in an <iframe> using my X-Frame-Bypass Web Component. It extends the IFrame element by using multiple CORS proxies and it was tested in the latest Firefox and Chrome.

You can use it as follows:

  1. (Optional) Include the Custom Elements with Built-in Extends polyfill for Safari:

    <script src="https://unpkg.com/@ungap/custom-elements-builtin"></script>
    
  2. Include the X-Frame-Bypass JS module:

    <script type="module" src="x-frame-bypass.js"></script>
    
  3. Insert the X-Frame-Bypass Custom Element:

    <iframe is="x-frame-bypass" src="https://example.org/"></iframe>
    

What is the difference between Cloud, Grid and Cluster?

my two cents worth ~

Cloud refers to an (imaginary/easily scalable) unlimited space and processing power. The term shields the underlying technologies and highlights solely its unlimited storage-space and power.

Grid is a group of physically close-by machines setup. Term usually imply the processing power (ie:MFLOPS/GFLOPS), referred by engineers

Cluster is a set of logically connected machines/device (like a clusters of harddisk, cluster of database). Term highlights how devices are able to connect together and operate as a unit, referred by engineers

SQL Server - copy stored procedures from one db to another

  • Right click on database
  • Tasks
  • Generate Scripts
  • Select the objects you wish to script
  • Script to File
  • Run generated scripts against target database

Use HTML5 to resize an image before upload

if any interested I've made a typescript version:

interface IResizeImageOptions {
  maxSize: number;
  file: File;
}
const resizeImage = (settings: IResizeImageOptions) => {
  const file = settings.file;
  const maxSize = settings.maxSize;
  const reader = new FileReader();
  const image = new Image();
  const canvas = document.createElement('canvas');
  const dataURItoBlob = (dataURI: string) => {
    const bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
        atob(dataURI.split(',')[1]) :
        unescape(dataURI.split(',')[1]);
    const mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
    const max = bytes.length;
    const ia = new Uint8Array(max);
    for (var i = 0; i < max; i++) ia[i] = bytes.charCodeAt(i);
    return new Blob([ia], {type:mime});
  };
  const resize = () => {
    let width = image.width;
    let height = image.height;

    if (width > height) {
        if (width > maxSize) {
            height *= maxSize / width;
            width = maxSize;
        }
    } else {
        if (height > maxSize) {
            width *= maxSize / height;
            height = maxSize;
        }
    }

    canvas.width = width;
    canvas.height = height;
    canvas.getContext('2d').drawImage(image, 0, 0, width, height);
    let dataUrl = canvas.toDataURL('image/jpeg');
    return dataURItoBlob(dataUrl);
  };

  return new Promise((ok, no) => {
      if (!file.type.match(/image.*/)) {
        no(new Error("Not an image"));
        return;
      }

      reader.onload = (readerEvent: any) => {
        image.onload = () => ok(resize());
        image.src = readerEvent.target.result;
      };
      reader.readAsDataURL(file);
  })    
};

and here's the javascript result:

var resizeImage = function (settings) {
    var file = settings.file;
    var maxSize = settings.maxSize;
    var reader = new FileReader();
    var image = new Image();
    var canvas = document.createElement('canvas');
    var dataURItoBlob = function (dataURI) {
        var bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
            atob(dataURI.split(',')[1]) :
            unescape(dataURI.split(',')[1]);
        var mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
        var max = bytes.length;
        var ia = new Uint8Array(max);
        for (var i = 0; i < max; i++)
            ia[i] = bytes.charCodeAt(i);
        return new Blob([ia], { type: mime });
    };
    var resize = function () {
        var width = image.width;
        var height = image.height;
        if (width > height) {
            if (width > maxSize) {
                height *= maxSize / width;
                width = maxSize;
            }
        } else {
            if (height > maxSize) {
                width *= maxSize / height;
                height = maxSize;
            }
        }
        canvas.width = width;
        canvas.height = height;
        canvas.getContext('2d').drawImage(image, 0, 0, width, height);
        var dataUrl = canvas.toDataURL('image/jpeg');
        return dataURItoBlob(dataUrl);
    };
    return new Promise(function (ok, no) {
        if (!file.type.match(/image.*/)) {
            no(new Error("Not an image"));
            return;
        }
        reader.onload = function (readerEvent) {
            image.onload = function () { return ok(resize()); };
            image.src = readerEvent.target.result;
        };
        reader.readAsDataURL(file);
    });
};

usage is like:

resizeImage({
    file: $image.files[0],
    maxSize: 500
}).then(function (resizedImage) {
    console.log("upload resized image")
}).catch(function (err) {
    console.error(err);
});

or (async/await):

const config = {
    file: $image.files[0],
    maxSize: 500
};
const resizedImage = await resizeImage(config)
console.log("upload resized image")

Max value of Xmx and Xms in Eclipse?

I have tried the following config for eclipse.ini:

org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
1024M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
1024m
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Xms128m
-Xmx2048m

Now eclipse performance is about 2 times faster then before.

You can also find a good help ref here: http://help.eclipse.org/indigo/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/misc/runtime-options.html

error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj

I had a mismatch between projects: one with multi-byte character set, the other with Unicode. Correcting these to agree on Unicode corrected the problem.

TypeError: 'float' object is not callable

The problem is with -3.7(prof[x]), which looks like a function call (note the parens). Just use a * like this -3.7*prof[x].

How to validate phone number in laravel 5.2?

Validator::extend('phone', function($attribute, $value, $parameters, $validator) {
        return preg_match('%^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$%i', $value) && strlen($value) >= 10;
    });

Validator::replacer('phone', function($message, $attribute, $rule, $parameters) {
        return str_replace(':attribute',$attribute, ':attribute is invalid phone number');
    });

Usage

Insert this code in the app/Providers/AppServiceProvider.php to be booted up with your application.

This rule validates the telephone number against the given pattern above that i found after
long search it matches the most common mobile or telephone numbers in a lot of countries
This will allow you to use the phone validation rule anywhere in your application, so your form validation could be:

 'phone' => 'required|numeric|phone' 

curl Failed to connect to localhost port 80

Since you have a ::1 localhost line in your hosts file, it would seem that curl is attempting to use IPv6 to contact your local web server.

Since the web server is not listening on IPv6, the connection fails.

You could try to use the --ipv4 option to curl, which should force an IPv4 connection when both are available.

How do I lowercase a string in Python?

How to convert string to lowercase in Python?

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

E.g. Kilometers --> kilometers

The canonical Pythonic way of doing this is

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

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

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

Here's why:

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

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

Unicode Python 3

Python 3 handles plain string literals as unicode:

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

Python 2, plain string literals are bytes

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

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

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

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

Use Unicode literals, not str literals

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

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

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

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

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

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

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

Best Practice, use Unicode

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

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

Can encode back when necessary

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

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

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

Package structure for a Java project?

You could follow maven's standard project layout. You don't have to actually use maven, but it would make the transition easier in the future (if necessary). Plus, other developers will be used to seeing that layout, since many open source projects are layed out this way,

xsd:boolean element type accept "true" but not "True". How can I make it accept it?

xs:boolean is predefined with regard to what kind of input it accepts. If you need something different, you have to define your own enumeration:

 <xs:simpleType name="my:boolean">
    <xs:restriction base="xs:string">
      <xs:enumeration value="True"/>
      <xs:enumeration value="False"/>
    </xs:restriction>
  </xs:simpleType>

Is it possible to style a mouseover on an image map using CSS?

With pseudo elements.

HTML:

<div class="image-map-container">
    <img src="https://upload.wikimedia.org/wikipedia/commons/8/83/FibonacciBlocks.png" alt="" usemap="#image-map" />
    <div class="map-selector"></div>
</div>

<map name="image-map" id="image-map">
    <area alt="" title="" href="#" shape="rect" coords="54,36,66,49" />
    <area alt="" title="" href="#" shape="rect" coords="72,38,83,48" />
    <area alt="" title="" href="#" shape="rect" coords="56,4,80,28" />
    <area alt="" title="" href="#" shape="rect" coords="7,7,45,46" />
    <area alt="" title="" href="#" shape="rect" coords="10,59,76,125" />
    <area alt="" title="" href="#" shape="rect" coords="93,9,199,122" />
</map>

some CSS:

.image-map-container {
    position: relative;
    display:inline-block;
}
.image-map-container img {
    display:block;
}
.image-map-container .map-selector {
    left:0;top:0;right:0;bottom:0;
    color:#546E7A00;
    transition-duration: .3s;
    transition-timing-function: ease-out;
    transition-property: top, left, right, bottom, color;
}
.image-map-container .map-selector.hover {
    color:#546E7A80;
}

.map-selector:after {
    content: '';
    position: absolute;
    top: inherit;right: inherit;bottom: inherit;left: inherit;
    background: currentColor;
    transition-duration: .3s;
    transition-timing-function: ease-out;
    transition-property: top, left, right, bottom, background;
    pointer-events: none;
}

JS:

$('#image-map area').hover(
    function () { 
        var coords = $(this).attr('coords').split(','),
            width = $('.image-map-container').width(),
            height = $('.image-map-container').height();
        $('.image-map-container .map-selector').addClass('hover').css({
            'left': coords[0]+'px',
            'top': coords[1] + 'px',
            'right': width - coords[2],
            'bottom': height - coords[3]
        })
    },
    function () { 
        $('.image-map-container .map-selector').removeClass('hover').attr('style','');
    }
)

https://jsfiddle.net/79ebt32x/1/

Get next / previous element using JavaScript?

all these solutions look like an overkill. Why use my solution?

previousElementSibling supported from IE9

document.addEventListener needs a polyfill

previousSibling might return a text

Please note i have chosen to return the first/last element in case boundaries are broken. In a RL usage, i would prefer it to return a null.

_x000D_
_x000D_
var el = document.getElementById("child1"),_x000D_
    children = el.parentNode.children,_x000D_
    len = children.length,_x000D_
    ind = [].indexOf.call(children, el),_x000D_
    nextEl = children[ind === len ? len : ind + 1],_x000D_
    prevEl = children[ind === 0 ? 0 : ind - 1];_x000D_
    _x000D_
    document.write(nextEl.id);_x000D_
    document.write("<br/>");_x000D_
    document.write(prevEl.id);
_x000D_
<div id="parent">_x000D_
  <div id="child1"></div>_x000D_
  <div id="child2"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Failed to load resource under Chrome

There is a temporary work around in Reenable (temporary) showModalDialog support in Chrome (for Windows) 37+.

Basically, create a new string in the registry at

HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\EnableDeprecatedWebPlatformFeatures

Under the EnableDeprecatedWebPlatformFeatures key, create a string value with the name 1 and a value of ShowModalDialog_EffectiveUntil20150430. To verify that the policy is enabled, visit chrome://policy URL.

Export data from R to Excel

I have been trying out the different packages including the function:

install.packages ("prettyR") 

library (prettyR)

delimit.table (Corrvar,"Name the csv.csv") ## Corrvar is a name of an object from an output I had on scaled variables to run a regression.

However I tried this same code for an output from another analysis (occupancy models model selection output) and it did not work. And after many attempts and exploration I:

  • copied the output from R (Ctrl+c)
  • in Excel sheet I pasted it (Ctrl+V)
  • Select the first column where the data is
  • In the "Data" vignette, click on "Text to column"

  • Select Delimited option, click next

  • Tick space box in "Separator", click next

  • Click Finalize (End)

Your output now should be in a form you can manipulate easy in excel. So perhaps not the fanciest option but it does the trick if you just want to explore your data in another way.

PS. If the labels in excel are not the exact one it is because Im translating the lables from my spanish excel.

Timeout on a function call

I have a different proposal which is a pure function (with the same API as the threading suggestion) and seems to work fine (based on suggestions on this thread)

def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
    import signal

    class TimeoutError(Exception):
        pass

    def handler(signum, frame):
        raise TimeoutError()

    # set the timeout handler
    signal.signal(signal.SIGALRM, handler) 
    signal.alarm(timeout_duration)
    try:
        result = func(*args, **kwargs)
    except TimeoutError as exc:
        result = default
    finally:
        signal.alarm(0)

    return result

Can't get Gulp to run: cannot find module 'gulp-util'

Linux Ubuntu 18:04 user here. I tried all the solutions on this board to date. Even though I read above in the accepted answer that "From later versions, there is no need to manually install gulp-util.", it was the thing that worked for me. (...maybe bc I'm on Ubuntu? I don't know. )

To recap, I kept getting the "cannot find module 'gulp-util'" error when just checking to see if gulp was installed by running:

gulp --version

...again, the 'gulp-util' error kept appearing...

So, I followed the npm install [package name] advice listed above, but ended up getting several other packages that needed to be installed as well. And one had a issue of already existing, and i wasn't sure how to replace it. ...I will put all the packages/install commands that I had to use here, just as reference in case someone else experiences this problem:

sudo npm install -g gulp-util

(then I got an error for 'pretty-hrtime' so I added that, and then the others as Error: Cannot find module ___ kept popping up after each gulp --version check. ...so I just kept installing each one.)

sudo npm install -g pretty-hrtime
sudo npm install -g chalk
sudo npm install -g semver --force

(without --force, on my system I got an error: "EEXIST: file already exists, symlink". --force is not recommended, but idk any other way. )

sudo npm install -g archy
sudo npm install -g liftoff
sudo npm install -g tildify
sudo npm install -g interpret
sudo npm install -g v8flags
sudo npm install -g minimist

And now gulp --version is finally showing: CLI version 3.9.1 Local version 3.9.1

gnuplot : plotting data from multiple input files in a single graph

replot

This is another way to get multiple plots at once:

plot file1.data
replot file2.data

printf not printing on console

You could try writing to stderr, rather than stdout.

fprintf(stderr, "Hello, please enter your age\n");

You should also have a look at this relevant thread.

What is the difference between 'git pull' and 'git fetch'?

git fetch pulls down the code from the remote server to your tracking branches in your local repository. If your remote is named origin (the default) then these branches will be within origin/, for example origin/master, origin/mybranch-123, etc. These are not your current branches, they are local copies of those branches from the server.

git pull does a git fetch but then also merges the code from the tracking branch into your current local version of that branch. If you're not ready for that changes yet, just git fetch first.

Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

This excellent answer explains very well what is happening and provides a solution. I would like to add another solution that might be suitable in similar cases: using the query method:

result = result.query("(var > 0.25) or (var < -0.25)")

See also http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-query.

(Some tests with a dataframe I'm currently working with suggest that this method is a bit slower than using the bitwise operators on series of booleans: 2 ms vs. 870 µs)

A piece of warning: At least one situation where this is not straightforward is when column names happen to be python expressions. I had columns named WT_38hph_IP_2, WT_38hph_input_2 and log2(WT_38hph_IP_2/WT_38hph_input_2) and wanted to perform the following query: "(log2(WT_38hph_IP_2/WT_38hph_input_2) > 1) and (WT_38hph_IP_2 > 20)"

I obtained the following exception cascade:

  • KeyError: 'log2'
  • UndefinedVariableError: name 'log2' is not defined
  • ValueError: "log2" is not a supported function

I guess this happened because the query parser was trying to make something from the first two columns instead of identifying the expression with the name of the third column.

A possible workaround is proposed here.

Inconsistent accessibility: property type is less accessible

make your class public access modifier,

just add public keyword infront of your class name

 namespace Test
{
  public  class Delivery
    {
        private string name;
        private string address;
        private DateTime arrivalTime;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public string Address
        {
            get { return address; }
            set { address = value; }
        }

        public DateTime ArrivlaTime
        {
            get { return arrivalTime; }
            set { arrivalTime = value; }
        }

        public string ToString()
        {
            { return name + address + arrivalTime.ToString(); }
        }
    }
}

Compression/Decompression string with C#

according to this snippet i use this code and it's working fine:

using System;
using System.IO;
using System.IO.Compression;
using System.Text;

namespace CompressString
{
    internal static class StringCompressor
    {
        /// <summary>
        /// Compresses the string.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <returns></returns>
        public static string CompressString(string text)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(text);
            var memoryStream = new MemoryStream();
            using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Compress, true))
            {
                gZipStream.Write(buffer, 0, buffer.Length);
            }

            memoryStream.Position = 0;

            var compressedData = new byte[memoryStream.Length];
            memoryStream.Read(compressedData, 0, compressedData.Length);

            var gZipBuffer = new byte[compressedData.Length + 4];
            Buffer.BlockCopy(compressedData, 0, gZipBuffer, 4, compressedData.Length);
            Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gZipBuffer, 0, 4);
            return Convert.ToBase64String(gZipBuffer);
        }

        /// <summary>
        /// Decompresses the string.
        /// </summary>
        /// <param name="compressedText">The compressed text.</param>
        /// <returns></returns>
        public static string DecompressString(string compressedText)
        {
            byte[] gZipBuffer = Convert.FromBase64String(compressedText);
            using (var memoryStream = new MemoryStream())
            {
                int dataLength = BitConverter.ToInt32(gZipBuffer, 0);
                memoryStream.Write(gZipBuffer, 4, gZipBuffer.Length - 4);

                var buffer = new byte[dataLength];

                memoryStream.Position = 0;
                using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
                {
                    gZipStream.Read(buffer, 0, buffer.Length);
                }

                return Encoding.UTF8.GetString(buffer);
            }
        }
    }
}

How to perform a fade animation on Activity transition?

you can also add animation in your activity, in onCreate method like below becasue overridePendingTransition is not working with some mobile, or it depends on device settings...

View view = findViewById(android.R.id.content);
Animation mLoadAnimation = AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.fade_in);
mLoadAnimation.setDuration(2000);
view.startAnimation(mLoadAnimation);

Creating a simple login form

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
      <title>Login Page</title>
      <style>
         /* Basics */
         html, body {
         width: 100%;
         height: 100%;
         font-family: "Helvetica Neue", Helvetica, sans-serif;
         color: #444;
         -webkit-font-smoothing: antialiased;
         background: #f0f0f0;
         }
         #container {
         position: fixed;
         width: 340px;
         height: 280px;
         top: 50%;
         left: 50%;
         margin-top: -140px;
         margin-left: -170px;
         background: #fff;
         border-radius: 3px;
         border: 1px solid #ccc;
         box-shadow: 0 1px 2px rgba(0, 0, 0, .1);
         }
         form {
         margin: 0 auto;
         margin-top: 20px;
         }
         label {
         color: #555;
         display: inline-block;
         margin-left: 18px;
         padding-top: 10px;
         font-size: 14px;
         }
         p a {
         font-size: 11px;
         color: #aaa;
         float: right;
         margin-top: -13px;
         margin-right: 20px;
         -webkit-transition: all .4s ease;
         -moz-transition: all .4s ease;
         transition: all .4s ease;
         }
         p a:hover {
         color: #555;
         }
         input {
         font-family: "Helvetica Neue", Helvetica, sans-serif;
         font-size: 12px;
         outline: none;
         }
         input[type=text],
         input[type=password] ,input[type=time]{
         color: #777;
         padding-left: 10px;
         margin: 10px;
         margin-top: 12px;
         margin-left: 18px;
         width: 290px;
         height: 35px;
         border: 1px solid #c7d0d2;
         border-radius: 2px;
         box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #f5f7f8;
         -webkit-transition: all .4s ease;
         -moz-transition: all .4s ease;
         transition: all .4s ease;
         }
         input[type=text]:hover,
         input[type=password]:hover,input[type=time]:hover {
         border: 1px solid #b6bfc0;
         box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .7), 0 0 0 5px #f5f7f8;
         }
         input[type=text]:focus,
         input[type=password]:focus,input[type=time]:focus {
         border: 1px solid #a8c9e4;
         box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #e6f2f9;
         }
         #lower {
         background: #ecf2f5;
         width: 100%;
         height: 69px;
         margin-top: 20px;
         box-shadow: inset 0 1px 1px #fff;
         border-top: 1px solid #ccc;
         border-bottom-right-radius: 3px;
         border-bottom-left-radius: 3px;
         }
         input[type=checkbox] {
         margin-left: 20px;
         margin-top: 30px;
         }
         .check {
         margin-left: 3px;
         font-size: 11px;
         color: #444;
         text-shadow: 0 1px 0 #fff;
         }
         input[type=submit] {
         float: right;
         margin-right: 20px;
         margin-top: 20px;
         width: 80px;
         height: 30px;
         font-size: 14px;
         font-weight: bold;
         color: #fff;
         background-color: #acd6ef; /*IE fallback*/
         background-image: -webkit-gradient(linear, left top, left bottom, from(#acd6ef), to(#6ec2e8));
         background-image: -moz-linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
         background-image: linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
         border-radius: 30px;
         border: 1px solid #66add6;
         box-shadow: 0 1px 2px rgba(0, 0, 0, .3), inset 0 1px 0 rgba(255, 255, 255, .5);
         cursor: pointer;
         }
         input[type=submit]:hover {
         background-image: -webkit-gradient(linear, left top, left bottom, from(#b6e2ff), to(#6ec2e8));
         background-image: -moz-linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
         background-image: linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
         }
         input[type=submit]:active {
         background-image: -webkit-gradient(linear, left top, left bottom, from(#6ec2e8), to(#b6e2ff));
         background-image: -moz-linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
         background-image: linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
         }
      </style>
   </head>
   <body>
      <!-- Begin Page Content -->
      <div id="container">
         <form action="login_process.php" method="post">
            <label for="loginmsg" style="color:hsla(0,100%,50%,0.5); font-family:"Helvetica Neue",Helvetica,sans-serif;"><?php  echo @$_GET['msg'];?></label>
            <label for="username">Username:</label>
            <input type="text" id="username" name="username">
            <label for="password">Password:</label>
            <input type="password" id="password" name="password">
            <div id="lower">
               <input type="checkbox"><label class="check" for="checkbox">Keep me logged in</label>
               <input type="submit" value="Login">
            </div>
            <!--/ lower-->
         </form>
      </div>
      <!--/ container-->
      <!-- End Page Content -->
   </body>
</html>

Stop Visual Studio from mixing line endings in files

see http://editorconfig.org and https://docs.microsoft.com/en-us/visualstudio/ide/create-portable-custom-editor-options?view=vs-2017

  1. If it does not exist, add a new file called .editorconfig for your project

  2. manipulate editor config to use your preferred behaviour.

I prefer spaces over tabs, and CRLF for all code files.
Here's my .editorconfig

# http://editorconfig.org
root = true

[*]
indent_style = space
indent_size = 4
end_of_line = crlf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false

[*.tmpl.html]
indent_size = 4

[*.scss]
indent_size = 2 

Find which commit is currently checked out in Git

You can just do:

git rev-parse HEAD

To explain a bit further: git rev-parse is git's basic command for interpreting any of the exotic ways that you can specify the name of a commit and HEAD is a reference to your current commit or branch. (In a git bisect session, it points directly to a commit ("detached HEAD") rather than a branch.)

Alternatively (and easier to remember) would be to just do:

git show

... which defaults to showing the commit that HEAD points to. For a more concise version, you can do:

$ git show --oneline -s
c0235b7 Autorotate uploaded images based on EXIF orientation

How to block users from closing a window in Javascript?

If your sending out an internal survey that requires 100% participation from your company's employees, then a better route would be to just have the form keep track of the responders ID/Username/email etc. Every few days or so just send a nice little email reminder to those in your organization to complete the survey...you could probably even automate this.

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

The previously accepted answer has been deprecated as of Python 3.0. Instead of using inspect.getargspec you should now opt for the Signature class which superseded it.

Creating a Signature for the function is easy via the signature function:

from inspect import signature

def someMethod(self, arg1, kwarg1=None):
    pass

sig = signature(someMethod)

Now, you can either view its parameters quickly by string it:

str(sig)  # returns: '(self, arg1, kwarg1=None)'

or you can also get a mapping of attribute names to parameter objects via sig.parameters.

params = sig.parameters 
print(params['kwarg1']) # prints: kwarg1=20

Additionally, you can call len on sig.parameters to also see the number of arguments this function requires:

print(len(params))  # 3

Each entry in the params mapping is actually a Parameter object that has further attributes making your life easier. For example, grabbing a parameter and viewing its default value is now easily performed with:

kwarg1 = params['kwarg1']
kwarg1.default # returns: None

similarly for the rest of the objects contained in parameters.


As for Python 2.x users, while inspect.getargspec isn't deprecated, the language will soon be :-). The Signature class isn't available in the 2.x series and won't be. So you still need to work with inspect.getargspec.

As for transitioning between Python 2 and 3, if you have code that relies on the interface of getargspec in Python 2 and switching to signature in 3 is too difficult, you do have the valuable option of using inspect.getfullargspec. It offers a similar interface to getargspec (a single callable argument) in order to grab the arguments of a function while also handling some additional cases that getargspec doesn't:

from inspect import getfullargspec

def someMethod(self, arg1, kwarg1=None):
    pass

args = getfullargspec(someMethod)

As with getargspec, getfullargspec returns a NamedTuple which contains the arguments.

print(args)
FullArgSpec(args=['self', 'arg1', 'kwarg1'], varargs=None, varkw=None, defaults=(None,), kwonlyargs=[], kwonlydefaults=None, annotations={})

Is it possible to make input fields read-only through CSS?

With CSS only? This is sort of possible on text inputs by using user-select:none:

.print {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;          
}

JSFiddle example.

It's well worth noting that this will not work in browsers which do not support CSS3 or support the user-select property. The readonly property should be ideally given to the input markup you wish to be made readonly, but this does work as a hacky CSS alternative.

With JavaScript:

document.getElementById("myReadonlyInput").setAttribute("readonly", "true");

Edit: The CSS method no longer works in Chrome (29). The -webkit-user-select property now appears to be ignored on input elements.

How to comment a block in Eclipse?

I have Eclipse IDE for Java Developers Version: Juno Service Release 2 and it is -

Every line prepended with //

ctrl + / for both comment and uncomment .

Close iOS Keyboard by touching anywhere using Swift

Swift 3:

Extension with Selector as parameter to be able to do additional stuff in the dismiss function and cancelsTouchesInView to prevent distortion with touches on other elements of the view.

extension UIViewController {
    func hideKeyboardOnTap(_ selector: Selector) {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: selector)
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }
}

Usage:

override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardOnTap(#selector(self.dismissKeyboard))
}

func dismissKeyboard() {
    view.endEditing(true)
    // do aditional stuff
}

HTML if image is not found

simple way to handle this, just add an background image.

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

You're out of memory. Try adding -Xmx256m to your java command line. The 256m is the amount of memory to give to the JVM (256 megabytes). It usually defaults to 64m.

How to show DatePickerDialog on Button click?

enter image description here

I. In your build.gradle add latest appcompat library, at the time 24.2.1

dependencies {  
    compile 'com.android.support:appcompat-v7:X.X.X' 
    // where X.X.X version
}

II. Make your activity extend android.support.v7.app.AppCompatActivity and implement the DatePickerDialog.OnDateSetListener interface.

public class MainActivity extends AppCompatActivity  
    implements DatePickerDialog.OnDateSetListener {

III. Create your DatePickerDialog setting a context, the implementation of the listener and the start year, month and day of the date picker.

DatePickerDialog datePickerDialog = new DatePickerDialog(  
    context, MainActivity.this, startYear, starthMonth, startDay);

IV. Show your dialog on the click event listener of your button

((Button) findViewById(R.id.myButton))
    .setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        datePickerDialog.show();
    }
});

I need to learn Web Services in Java. What are the different types in it?

  1. SOAP Web Services are standard-based and supported by almost every software platform: They rely heavily in XML and have support for transactions, security, asynchronous messages and many other issues. It’s a pretty big and complicated standard, but covers almost every messaging situation. On the other side, RESTful services relies of HTTP protocol and verbs (GET, POST, PUT, DELETE) to interchange messages in any format, preferable JSON and XML. It’s a pretty simple and elegant architectural approach.
  2. As in every topic in the Java World, there are several libraries to build/consume Web Services. In the SOAP Side you have the JAX-WS standard and Apache Axis, and in REST you can use Restlets or Spring REST Facilities among other libraries.

With question 3, this article states that RESTful Services are appropiate in this scenarios:

  • If you have limited bandwidth
  • If your operations are stateless: No information is preserved from one invocation to the next one, and each request is treated independently.
  • If your clients require caching.

While SOAP is the way to go when:

  • If you require asynchronous processing
  • If you need formal contract/Interfaces
  • In your service operations are stateful: For example, you store information/data on a request and use that stored data on the next one.

CSS: Set Div height to 100% - Pixels

Alternatively, you can just use position:absolute:

#content
{
    position:absolute;
    top: 111px;
    bottom: 0px;
}

However, IE6 doesn't like top and bottom declarations. But web developers don't like IE6.

SQL Server: Get data for only the past year

declare @iMonth int
declare @sYear varchar(4)
declare @sMonth varchar(2)
set @iMonth = 0
while @iMonth > -12
begin
    set @sYear = year(DATEADD(month,@iMonth,GETDATE()))
    set @sMonth = right('0'+cast(month(DATEADD(month,@iMonth,GETDATE())) as varchar(2)),2)
    select @sYear + @sMonth
    set @iMonth = @iMonth - 1
end

How to save username and password with Mercurial?

While it may or may not work in your situation, I have found it useful to generate a public / private key using Putty's Pageant.

If you are also working with bitbucket (.org) it should give you the ability to provide a public key to your user account and then commands that reach out to the repository will be secured automatically.

If Pageant doesn't start up for you upon a reboot, you can add a shortcut to Pageant to your Windows "Start menu" and the shortcut may need to have a 'properties' populated with the location of your private (.ppk) file.

With this in place Mercurial and your local repositories will need to be set up to push/pull using the SSH format.

Here are some detailed instructions on Atlassian's site for Windows OR Mac/Linux.

You don't have to take my word for it and there are no doubt other ways to do it. Perhaps these steps described here are more for you:

  1. Start PuttyGen from Start -> PuTTY-> PuttyGen
  2. Generate a new key and save it as a .ppk file without a passphrase
  3. Use Putty to login to the server you want to connect to
  4. Append the Public Key text from PuttyGen to the text of ~/.ssh/authorized_keys
  5. Create a shortcut to your .ppk file from Start -> Putty to Start -> Startup
  6. Select the .ppk shortcut from the Startup menu (this will happen automatically at every startup)
  7. See the Pageant icon in the system tray? Right-click it and select “New session”
  8. Enter username@hostname in the “Host name” field
  9. You will now log in automatically.

Most Pythonic way to provide global configuration variables in config.py?

I like this solution for small applications:

class App:
  __conf = {
    "username": "",
    "password": "",
    "MYSQL_PORT": 3306,
    "MYSQL_DATABASE": 'mydb',
    "MYSQL_DATABASE_TABLES": ['tb_users', 'tb_groups']
  }
  __setters = ["username", "password"]

  @staticmethod
  def config(name):
    return App.__conf[name]

  @staticmethod
  def set(name, value):
    if name in App.__setters:
      App.__conf[name] = value
    else:
      raise NameError("Name not accepted in set() method")

And then usage is:

if __name__ == "__main__":
   # from config import App
   App.config("MYSQL_PORT")     # return 3306
   App.set("username", "hi")    # set new username value
   App.config("username")       # return "hi"
   App.set("MYSQL_PORT", "abc") # this raises NameError

.. you should like it because:

  • uses class variables (no object to pass around/ no singleton required),
  • uses encapsulated built-in types and looks like (is) a method call on App,
  • has control over individual config immutability, mutable globals are the worst kind of globals.
  • promotes conventional and well named access / readability in your source code
  • is a simple class but enforces structured access, an alternative is to use @property, but that requires more variable handling code per item and is object-based.
  • requires minimal changes to add new config items and set its mutability.

--Edit--: For large applications, storing values in a YAML (i.e. properties) file and reading that in as immutable data is a better approach (i.e. blubb/ohaal's answer). For small applications, this solution above is simpler.

Servlet for serving static content

Use org.mortbay.jetty.handler.ContextHandler. You don't need additional components like StaticServlet.

At the jetty home,

$ cd contexts

$ cp javadoc.xml static.xml

$ vi static.xml

...

<Configure class="org.mortbay.jetty.handler.ContextHandler">
<Set name="contextPath">/static</Set>
<Set name="resourceBase"><SystemProperty name="jetty.home" default="."/>/static/</Set>
<Set name="handler">
  <New class="org.mortbay.jetty.handler.ResourceHandler">
    <Set name="cacheControl">max-age=3600,public</Set>
  </New>
 </Set>
</Configure>

Set the value of contextPath with your URL prefix, and set the value of resourceBase as the file path of the static content.

It worked for me.

Bulk create model objects in django

worked for me to use manual transaction handling for the loop(postgres 9.1):

from django.db import transaction
with transaction.commit_on_success():
    for item in items:
        MyModel.objects.create(name=item.name)

in fact it's not the same, as 'native' database bulk insert, but it allows you to avoid/descrease transport/orms operations/sql query analyse costs

What does %>% mean in R

matrix multiplication, see the following example:

> A <- matrix (c(1,3,4, 5,8,9, 1,3,3), 3,3)
> A
     [,1] [,2] [,3]
[1,]    1    5    1
[2,]    3    8    3
[3,]    4    9    3
> 
> B <- matrix (c(2,4,5, 8,9,2, 3,4,5), 3,3)
> 
> B
     [,1] [,2] [,3]
[1,]    2    8    3
[2,]    4    9    4
[3,]    5    2    5
> 
> 
> A %*% B
     [,1] [,2] [,3]
[1,]   27   55   28
[2,]   53  102   56
[3,]   59  119   63

> B %*% A
     [,1] [,2] [,3]
[1,]   38  101   35
[2,]   47  128   43
[3,]   31   86   26

Also see:

http://en.wikipedia.org/wiki/Matrix_multiplication

If this does not follow the size of matrix rule you will get the error:

> A <- matrix(c(1,2,3,4,5,6), 3,2)
    > A
     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6

> B <- matrix (c(3,1,3,4,4,4,4,4,3), 3,3)

> B
         [,1] [,2] [,3]
    [1,]    3    4    4
    [2,]    1    4    4
    [3,]    3    4    3
    > A%*%B
    Error in A %*% B : non-conformable arguments

How to import and use image in a Vue single file component?

I came across this issue recently, and i'm using Typescript. If you're using Typescript like I am, then you need to import assets like so:

<img src="@/assets/images/logo.png" alt="">

Get Client Machine Name in PHP

PHP Manual says:

gethostname (PHP >= 5.3.0) gethostname — Gets the host name

Look:

<?php
echo gethostname(); // may output e.g,: sandie
// Or, an option that also works before PHP 5.3
echo php_uname('n'); // may output e.g,: sandie
?>

http://php.net/manual/en/function.gethostname.php

Enjoy

What exactly is an instance in Java?

Computer c= new Computer()

Here an object is created from the Computer class. A reference named c allows the programmer to access the object.

How can I extract embedded fonts from a PDF as valid font files?

This is a followup to the font-forge section of @Kurt Pfeifle's answer, specific to Red Hat (and possibly other Linux distros).

  1. After opening the PDF and selecting the font you want, you will want to select "File -> Generate Fonts..." option.
  2. If there are errors in the file, you can choose to ignore them or save the file and edit them. Most of the errors can be fixed automatically if you click "Fix" enough times.
  3. Click "Element -> Font Info...", and "Fontname", "Family Name" and "Name for Humans" are all set to values you like. If not, modify them and save the file somewhere. These names will determine how your font appears on the system.
  4. Select your file name and click "Save..."

Once you have your TTF file, you can install it on your system by

  1. Copying it to folder /usr/share/fonts (as root)
  2. Running fc-cache -f /usr/share/fonts/ (as root)

Validate select box

For starters, you can "disable" the option from being selected accidentally by users:

<option value="" disabled="disabled">Choose an option</option>

Then, inside your JavaScript event (doesn't matter whether it is jQuery or JavaScript), for your form to validate whether it is set, do:

select = document.getElementById('select'); // or in jQuery use: select = this;
if (select.value) {
  // value is set to a valid option, so submit form
  return true;
}
return false;

Or something to that effect.

how to get GET and POST variables with JQuery?

Or you can use this one http://plugins.jquery.com/project/parseQuery, it's smaller than most (minified 449 bytes), returns an object representing name-value pairs.

How to place a file on classpath in Eclipse?

Copy the file into your src folder. Go to the Project Explorer in Eclipse, Right-click on your project, and click on "Refresh". The file should appear on the Project Explorer pane as well.

Get AVG ignoring Null or Zero values

NULL is already ignored so you can use NULLIF to turn 0 to NULL. Also you don't need DISTINCT and your WHERE on ActualTime is not sargable.

SELECT AVG(cast(NULLIF(a.SecurityW, 0) AS BIGINT)) AS Average1,
       AVG(cast(NULLIF(a.TransferW, 0) AS BIGINT)) AS Average2,
       AVG(cast(NULLIF(a.StaffW, 0) AS BIGINT))    AS Average3
FROM   Table1 a
WHERE  a.ActualTime >= '20130401'
       AND a.ActualTime < '20130501' 

PS I have no idea what Table2 b is in the original query for as there is no join condition for it so have omitted it from my answer.

Select Tag Helper in ASP.NET Core MVC

You can use below code for multiple select:

<select asp-for="EmployeeId"  multiple="multiple" asp-items="@ViewBag.Employees">
    <option>Please select</option>
</select>

You can also use:

<select id="EmployeeId" name="EmployeeId"  multiple="multiple" asp-items="@ViewBag.Employees">
    <option>Please select</option>
</select>

Merging cells in Excel using Apache POI

The best answer

sheet.addMergedRegion(new CellRangeAddress(start-col,end-col,start-cell,end-cell));

Bash script - variable content as a command to run

line=$((${RANDOM} % $(wc -l < /etc/passwd)))
sed -n "${line}p" /etc/passwd

just with your file instead.

In this example I used the file /etc/password, using the special variable ${RANDOM} (about which I learned here), and the sed expression you had, only difference is that I am using double quotes instead of single to allow the variable expansion.

Scheduling recurring task in Android

Timer

As mentioned on the javadocs you are better off using a ScheduledThreadPoolExecutor.

ScheduledThreadPoolExecutor

Use this class when your use case requires multiple worker threads and the sleep interval is small. How small ? Well, I'd say about 15 minutes. The AlarmManager starts schedule intervals at this time and it seems to suggest that for smaller sleep intervals this class can be used. I do not have data to back the last statement. It is a hunch.

Service

Your service can be closed any time by the VM. Do not use services for recurring tasks. A recurring task can start a service, which is another matter entirely.

BroadcastReciever with AlarmManager

For longer sleep intervals (>15 minutes), this is the way to go. AlarmManager already has constants ( AlarmManager.INTERVAL_DAY ) suggesting that it can trigger tasks several days after it has initially been scheduled. It can also wake up the CPU to run your code.

You should use one of those solutions based on your timing and worker thread needs.

Easiest way to copy a table from one database to another?

With MySQL Workbench you can use Data Export to dump just the table to a local SQL file (Data Only, Structure Only or Structure and Data) and then Data Import to load it into the other DB.

You can have multiple connections (different hosts, databases, users) open at the same time.

Difference between variable declaration syntaxes in Javascript (including global variables)?

<title>Index.html</title>
<script>
    var varDeclaration = true;
    noVarDeclaration = true;
    window.hungOnWindow = true;
    document.hungOnDocument = true;
</script>
<script src="external.js"></script>

/* external.js */

console.info(varDeclaration == true); // could be .log, alert etc
// returns false in IE8

console.info(noVarDeclaration == true); // could be .log, alert etc
// returns false in IE8

console.info(window.hungOnWindow == true); // could be .log, alert etc
// returns true in IE8

console.info(document.hungOnDocument == true); // could be .log, alert etc
// returns ??? in IE8 (untested!)  *I personally find this more clugy than hanging off window obj

Is there a global object that all vars are hung off of by default? eg: 'globals.noVar declaration'

How to change font in ipython notebook

In your notebook (simple approach). Add new cell with following code

%%html
<style type='text/css'>
.CodeMirror{
    font-size: 12px;
}

div.output_area pre {
    font-size: 12px;
}
</style>

Single selection in RecyclerView

This simple one worked for me

private RadioButton lastCheckedRB = null;
...
@Override
public void onBindViewHolder(final CoachListViewHolder holder, final int position) {
  holder.priceRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        RadioButton checked_rb = (RadioButton) group.findViewById(checkedId);
        if (lastCheckedRB != null && lastCheckedRB != checked_rb) {
            lastCheckedRB.setChecked(false);
        }
        //store the clicked radiobutton
        lastCheckedRB = checked_rb;
    }
});

How to refresh datagrid in WPF

How about

mydatagrid.UpdateLayout();

A process crashed in windows .. Crash dump location

I have observed on Windows 2008 the Windows Error Reporting crash dumps get staged in the folder:

C:\Users\All Users\Microsoft\Windows\WER\ReportQueue

Which, starting with Windows Vista, is an alias for:

C:\ProgramData\Microsoft\Windows\WER\ReportQueue

Eliminating NAs from a ggplot

From my point of view this error "Error: Aesthetics must either be length one, or the same length as the data" refers to the argument aes(x,y) I tried the na.omit() and worked just fine to me.

How to return history of validation loss in Keras

Actually, you can also do it with the iteration method. Because sometimes we might need to use the iteration method instead of the built-in epochs method to visualize the training results after each iteration.

history = [] #Creating a empty list for holding the loss later
for iteration in range(1, 3):
    print()
    print('-' * 50)
    print('Iteration', iteration)
    result = model.fit(X, y, batch_size=128, nb_epoch=1) #Obtaining the loss after each training
    history.append(result.history['loss']) #Now append the loss after the training to the list.
    start_index = random.randint(0, len(text) - maxlen - 1)
print(history)

This way allows you to get the loss you want while maintaining your iteration method.

Site does not exist error for a2ensite

Worked after I added .conf to the configuration file

What is the <leader> in a .vimrc file?

The <Leader> key is mapped to \ by default. So if you have a map of <Leader>t, you can execute it by default with \+t. For more detail or re-assigning it using the mapleader variable, see

:help leader

To define a mapping which uses the "mapleader" variable, the special string
"<Leader>" can be used.  It is replaced with the string value of "mapleader".
If "mapleader" is not set or empty, a backslash is used instead.  
Example:
    :map <Leader>A  oanother line <Esc>
Works like:
    :map \A  oanother line <Esc>
But after:
    :let mapleader = ","
It works like:
    :map ,A  oanother line <Esc>

Note that the value of "mapleader" is used at the moment the mapping is
defined.  Changing "mapleader" after that has no effect for already defined
mappings.


hadoop copy a local file system folder to HDFS

If you copy a folder from local then it will copy folder with all its sub folders to HDFS.

For copying a folder from local to hdfs, you can use

hadoop fs -put localpath

or

hadoop fs -copyFromLocal localpath

or

hadoop fs -put localpath hdfspath

or

hadoop fs -copyFromLocal localpath hdfspath

Note:

If you are not specified hdfs path then folder copy will be copy to hdfs with the same name of that folder.

To copy from hdfs to local

 hadoop fs -get hdfspath localpath

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at

  1. session_start() must be at the top of your source, no html or other output befor!
  2. your can only send session_start() one time
  3. by this way if(session_status()!=PHP_SESSION_ACTIVE) session_start()

How to pass object from one component to another in Angular 2?

Use the output annotation

@Directive({
  selector: 'interval-dir',
})
class IntervalDir {
  @Output() everySecond = new EventEmitter();
  @Output('everyFiveSeconds') five5Secs = new EventEmitter();
  constructor() {
    setInterval(() => this.everySecond.emit("event"), 1000);
    setInterval(() => this.five5Secs.emit("event"), 5000);
  }
}
@Component({
  selector: 'app',
  template: `
    <interval-dir (everySecond)="everySecond()" (everyFiveSeconds)="everyFiveSeconds()">
    </interval-dir>
  `,
  directives: [IntervalDir]
})
class App {
  everySecond() { console.log('second'); }
  everyFiveSeconds() { console.log('five seconds'); }
}
bootstrap(App);

Refresh Page and Keep Scroll Position

This might be useful for refreshing also. But if you want to keep track of position on the page before you click on a same position.. The following code will help.

Also added a data-confirm for prompting the user if they really want to do that..

Note: I'm using jQuery and js-cookie.js to store cookie info.

$(document).ready(function() {
    // make all links with data-confirm prompt the user first.
    $('[data-confirm]').on("click", function (e) {
        e.preventDefault();
        var msg = $(this).data("confirm");
        if(confirm(msg)==true) {
            var url = this.href;
            if(url.length>0) window.location = url;
            return true;
        }
        return false;
    });

    // on certain links save the scroll postion.
    $('.saveScrollPostion').on("click", function (e) {
        e.preventDefault();
        var currentYOffset = window.pageYOffset;  // save current page postion.
        Cookies.set('jumpToScrollPostion', currentYOffset);
        if(!$(this).attr("data-confirm")) {  // if there is no data-confirm on this link then trigger the click. else we have issues.
            var url = this.href;
            window.location = url;
            //$(this).trigger('click');  // continue with click event.
        }
    });

    // check if we should jump to postion.
    if(Cookies.get('jumpToScrollPostion') !== "undefined") {
        var jumpTo = Cookies.get('jumpToScrollPostion');
        window.scrollTo(0, jumpTo);
        Cookies.remove('jumpToScrollPostion');  // and delete cookie so we don't jump again.
    }
});

A example of using it like this.

<a href='gotopage.html' class='saveScrollPostion' data-confirm='Are you sure?'>Goto what the heck</a>

php function mail() isn't working

I think you are not configured properly,

if you are using XAMPP then you can easily send mail from localhost.

for example you can configure C:\xampp\php\php.ini and c:\xampp\sendmail\sendmail.ini for gmail to send mail.

in C:\xampp\php\php.ini find extension=php_openssl.dll and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.

in php.ini file find [mail function] and change

SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

(use the above send mail path only and it will work)

Now Open C:\xampp\sendmail\sendmail.ini. Replace all the existing code in sendmail.ini with following code

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]

Now you have done!! create php file with mail function and send mail from localhost.

Update

First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()).

You can set the following settings in your PHP.ini:

ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");

How do I create/edit a Manifest file?

In Visual Studio 2019 WinForm Projects, it is available under

Project Properties -> Application -> View Windows Settings (button)

enter image description here

How to shift a block of code left/right by one space in VSCode?

UPDATE

While these methods work, newer versions of VS Code uses the Ctrl+] shortcut to indent a block of code once, and Ctrl+[ to remove indentation.

This method detects the indentation in a file and indents accordingly.You can change the size of indentation by clicking on the Select Indentation setting in the bottom right of VS Code (looks something like "Spaces: 2"), selecting "Indent using Spaces" from the drop-down menu and then selecting by how many spaces you would like to indent.

How can I access iframe elements with Javascript?

Using jQuery you can use contents(). For example:

var inside = $('#one').contents();

Should I put #! (shebang) in Python scripts, and what form should it take?

The shebang line in any script determines the script's ability to be executed like a standalone executable without typing python beforehand in the terminal or when double clicking it in a file manager (when configured properly). It isn't necessary but generally put there so when someone sees the file opened in an editor, they immediately know what they're looking at. However, which shebang line you use IS important.

Correct usage for Python 3 scripts is:

#!/usr/bin/env python3

This defaults to version 3.latest. For Python 2.7.latest use python2 in place of python3.

The following should NOT be used (except for the rare case that you are writing code which is compatible with both Python 2.x and 3.x):

#!/usr/bin/env python

The reason for these recommendations, given in PEP 394, is that python can refer either to python2 or python3 on different systems. It currently refers to python2 on most distributions, but that is likely to change at some point.

Also, DO NOT Use:

#!/usr/local/bin/python

"python may be installed at /usr/bin/python or /bin/python in those cases, the above #! will fail."

--"#!/usr/bin/env python" vs "#!/usr/local/bin/python"

Trying to read cell 1,1 in spreadsheet using Google Script API

You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of

function email() {

// Opens SS by its ID

var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");

// Get the name of this SS

var name = ss.getName();  // Not necessary 

// Read cell 1,1 * Line below does't work *

// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet 
var range = sheet.getRange(1,1); 
var data = range.getValue();

}

The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.

Calculating number of full months between two dates in SQL

This is for ORACLE only and not for SQL-Server:

months_between(to_date ('2009/05/15', 'yyyy/mm/dd'), 
               to_date ('2009/04/16', 'yyyy/mm/dd'))

And for full month:

round(months_between(to_date ('2009/05/15', 'yyyy/mm/dd'), 
                     to_date ('2009/04/16', 'yyyy/mm/dd')))

Can be used in Oracle 8i and above.

Select something that has more/less than x character

If you are using SQL Server, Use the LEN (Length) function:

SELECT EmployeeName FROM EmployeeTable WHERE LEN(EmployeeName) > 4

MSDN for it states:

Returns the number of characters of the specified string expression,
excluding trailing blanks.

Here's the link to the MSDN

For oracle/plsql you can use Length(), mysql also uses Length.

Here is the Oracle documentation:

http://www.techonthenet.com/oracle/functions/length.php

And here is the mySQL Documentation of Length(string):

http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_length

For PostgreSQL, you can use length(string) or char_length(string). Here is the PostgreSQL documentation:

http://www.postgresql.org/docs/current/static/functions-string.html#FUNCTIONS-STRING-SQL

What are the undocumented features and limitations of the Windows FINDSTR command?

findstr sometimes hangs unexpectedly when searching large files.

I haven't confirmed the exact conditions or boundary sizes. I suspect any file larger 2GB may be at risk.

I have had mixed experiences with this, so it is more than just file size. This looks like it may be a variation on FINDSTR hangs on XP and Windows 7 if redirected input does not end with LF, but as demonstrated this particular problem manifests when input is not redirected.

The following command line session (Windows 7) demonstrates how findstr can hang when searching a 3GB file.

C:\Data\Temp\2014-04>echo 1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890> T100B.txt

C:\Data\Temp\2014-04>for /L %i in (1,1,10) do @type T100B.txt >> T1KB.txt

C:\Data\Temp\2014-04>for /L %i in (1,1,1000) do @type T1KB.txt >> T1MB.txt

C:\Data\Temp\2014-04>for /L %i in (1,1,1000) do @type T1MB.txt >> T1GB.txt

C:\Data\Temp\2014-04>echo find this line>> T1GB.txt

C:\Data\Temp\2014-04>copy T1GB.txt + T1GB.txt + T1GB.txt T3GB.txt
T1GB.txt
T1GB.txt
T1GB.txt
        1 file(s) copied.

C:\Data\Temp\2014-04>dir
 Volume in drive C has no label.
 Volume Serial Number is D2B2-FFDF

 Directory of C:\Data\Temp\2014-04

2014/04/08  04:28 PM    <DIR>          .
2014/04/08  04:28 PM    <DIR>          ..
2014/04/08  04:22 PM               102 T100B.txt
2014/04/08  04:28 PM     1 020 000 016 T1GB.txt
2014/04/08  04:23 PM             1 020 T1KB.txt
2014/04/08  04:23 PM         1 020 000 T1MB.txt
2014/04/08  04:29 PM     3 060 000 049 T3GB.txt
               5 File(s)  4 081 021 187 bytes
               2 Dir(s)  51 881 050 112 bytes free
C:\Data\Temp\2014-04>rem Findstr on the 1GB file does not hang

C:\Data\Temp\2014-04>findstr "this" T1GB.txt
find this line

C:\Data\Temp\2014-04>rem On the 3GB file, findstr hangs and must be aborted... even though it clearly reaches end of file

C:\Data\Temp\2014-04>findstr "this" T3GB.txt
find this line
find this line
find this line
^C
C:\Data\Temp\2014-04>

Note, I've verified in a hex editor that all lines are terminated with CRLF. The only anomaly is that the file is terminated with 0x1A due to the way copy works. Note however, that this anomaly doesn't cause a problem on "small" files.

With additional testing I have confirmed the following:

  • Using copy with the /b option for binary files prevents the addition of the 0x1A character, and findstr doesn't hang on the 3GB file.
  • Terminating the 3GB file with a different character also causes a findstr to hang.
  • The 0x1A character doesn't cause any problems on a "small" file. (Similarly for other terminating characters.)
  • Adding CRLF after 0x1A resolves the problem. (LF by itself would probably suffice.)
  • Using type to pipe the file into findstr works without hanging. (This might be due to a side effect of either type or | that inserts an additional End Of Line.)
  • Use redirected input < also causes findstr to hang. But this is expected; as explained in dbenham's post: "redirected input must end in LF".

How to add one column into existing SQL Table

The syntax you need is

ALTER TABLE Products ADD LastUpdate  varchar(200) NULL

This is a metadata only operation

What is a stack trace, and how can I use it to debug my application errors?

To understand the name: A stack trace is a a list of Exceptions( or you can say a list of "Cause by"), from the most surface Exception(e.g. Service Layer Exception) to the deepest one (e.g. Database Exception). Just like the reason we call it 'stack' is because stack is First in Last out (FILO), the deepest exception was happened in the very beginning, then a chain of exception was generated a series of consequences, the surface Exception was the last one happened in time, but we see it in the first place.

Key 1:A tricky and important thing here need to be understand is : the deepest cause may not be the "root cause", because if you write some "bad code", it may cause some exception underneath which is deeper than its layer. For example, a bad sql query may cause SQLServerException connection reset in the bottem instead of syndax error, which may just in the middle of the stack.

-> Locate the root cause in the middle is your job. enter image description here

Key 2:Another tricky but important thing is inside each "Cause by" block, the first line was the deepest layer and happen first place for this block. For instance,

Exception in thread "main" java.lang.NullPointerException
        at com.example.myproject.Book.getTitle(Book.java:16)
           at com.example.myproject.Author.getBookTitles(Author.java:25)
               at com.example.myproject.Bootstrap.main(Bootstrap.java:14)

Book.java:16 was called by Auther.java:25 which was called by Bootstrap.java:14, Book.java:16 was the root cause. Here attach a diagram sort the trace stack in chronological order. enter image description here

Fit image into ImageView, keep aspect ratio and then resize ImageView to image dimensions?

I am using a very simple solution. Here my code:

imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.getLayoutParams().height = imageView.getLayoutParams().width;
imageView.setMinimumHeight(imageView.getLayoutParams().width);

My pictures are added dynamically in a gridview. When you make these settings to the imageview, the picture can be automatically displayed in 1:1 ratio.

What is the best way to redirect a page using React Router?

Actually it depends on your use case.

1) You want to protect your route from unauthorized users

If that is the case you can use the component called <Redirect /> and can implement the following logic:

import React from 'react'
import  { Redirect } from 'react-router-dom'

const ProtectedComponent = () => {
  if (authFails)
    return <Redirect to='/login'  />
  }
  return <div> My Protected Component </div>
}

Keep in mind that if you want <Redirect /> to work the way you expect, you should place it inside of your component's render method so that it should eventually be considered as a DOM element, otherwise it won't work.

2) You want to redirect after a certain action (let's say after creating an item)

In that case you can use history:

myFunction() {
  addSomeStuff(data).then(() => {
      this.props.history.push('/path')
    }).catch((error) => {
      console.log(error)
    })

or

myFunction() {
  addSomeStuff()
  this.props.history.push('/path')
}

In order to have access to history, you can wrap your component with an HOC called withRouter. When you wrap your component with it, it passes match location and history props. For more detail please have a look at the official documentation for withRouter.

If your component is a child of a <Route /> component, i.e. if it is something like <Route path='/path' component={myComponent} />, you don't have to wrap your component with withRouter, because <Route /> passes match, location, and history to its child.

3) Redirect after clicking some element

There are two options here. You can use history.push() by passing it to an onClick event:

<div onClick={this.props.history.push('/path')}> some stuff </div>

or you can use a <Link /> component:

 <Link to='/path' > some stuff </Link>

I think the rule of thumb with this case is to try to use <Link /> first, I suppose especially because of performance.

TypeError: argument of type 'NoneType' is not iterable

The python error says that wordInput is not an iterable -> it is of NoneType.

If you print wordInput before the offending line, you will see that wordInput is None.

Since wordInput is None, that means that the argument passed to the function is also None. In this case word. You assign the result of pickEasy to word.

The problem is that your pickEasy function does not return anything. In Python, a method that didn't return anything returns a NoneType.

I think you wanted to return a word, so this will suffice:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
        wordCount.append("_")
    return word

How to overcome the CORS issue in ReactJS

You can set up a express proxy server using http-proxy-middleware to bypass CORS:

const express = require('express');
const proxy = require('http-proxy-middleware');
const path = require('path');
const port = process.env.PORT || 8080;
const app = express();

app.use(express.static(__dirname));
app.use('/proxy', proxy({
    pathRewrite: {
       '^/proxy/': '/'
    },
    target: 'https://server.com',
    secure: false
}));

app.get('*', (req, res) => {
   res.sendFile(path.resolve(__dirname, 'index.html'));
});

app.listen(port);
console.log('Server started');

From your react app all requests should be sent to /proxy endpoint and they will be redirected to the intended server.

const URL = `/proxy/${PATH}`;
return axios.get(URL);

Why is the parent div height zero when it has floated children

Content that is floating does not influence the height of its container. The element contains no content that isn't floating (so nothing stops the height of the container being 0, as if it were empty).

Setting overflow: hidden on the container will avoid that by establishing a new block formatting context. See methods for containing floats for other techniques and containing floats for an explanation about why CSS was designed this way.

How to enable Ad Hoc Distributed Queries

The following command may help you..

EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE
GO

Don't understand why UnboundLocalError occurs (closure)

try this

counter = 0

def increment():
  global counter
  counter += 1

increment()

Remove array element based on object property

In ES6, just one line.

const arr = arr.filter(item => item.key !== "some value");

:)

Remote JMX connection

http://blogs.oracle.com/jmxetc/entry/troubleshooting_connection_problems_in_jconsole

If you are trying to access a server which is behind a NAT - you will most probably have to start your server with the option

-Djava.rmi.server.hostname=<public/NAT address>

so that the RMI stubs sent to the client contain the server's public address allowing it to be reached by the clients from the outside.

C# : "A first chance exception of type 'System.InvalidOperationException'"

The problem here is that your timer starts a thread and when it runs the callback function, the callback function ( updatelistview) is accessing controls on UI thread so this can not be done becuase of this

Change route params without reloading in Angular 2

Using location.go(url) is the way to go, but instead of hardcoding the url , consider generating it using router.createUrlTree().

Given that you want to do the following router call: this.router.navigate([{param: 1}], {relativeTo: this.activatedRoute}) but without reloading the component, it can be rewritten as:

const url = this.router.createUrlTree([], {relativeTo: this.activatedRoute, queryParams: {param: 1}}).toString()

 this.location.go(url);

How to get rid of `deprecated conversion from string constant to ‘char*’` warnings in GCC?

just use -w option for g++

example:

g++ -w -o simple.o simple.cpp -lpthread

Remember this doesn't avoid deprecation rather it prevents showing warning message on the terminal.

Now if you really want to avoid deprecation use const keyword like this:

const char* s="constant string";  

set environment variable in python script

Compact solution (provided you don't need other environment variables):

call('sqsub -np {} /homedir/anotherdir/executable'.format(var1).split(),
      env=dict(LD_LIBRARY_PATH=my_path))

Using the env command line tool:

call('env LD_LIBRARY_PATH=my_path sqsub -np {} /homedir/anotherdir/executable'.format(var1).split())

Use SELECT inside an UPDATE query

I wrote about some of the limitations of correlated subqueries in Access/JET SQL a while back, and noted the syntax for joining multiple tables for SQL UPDATEs. Based on that info and some quick testing, I don't believe there's any way to do what you want with Access/JET in a single SQL UPDATE statement. If you could, the statement would read something like this:

UPDATE FUNCTIONS A
INNER JOIN (
  SELECT AA.Func_ID, Min(BB.Tax_Code) AS MinOfTax_Code
  FROM TAX BB, FUNCTIONS AA
  WHERE AA.Func_Pure<=BB.Tax_ToPrice AND AA.Func_Year= BB.Tax_Year
  GROUP BY AA.Func_ID
) B 
ON B.Func_ID = A.Func_ID
SET A.Func_TaxRef = B.MinOfTax_Code

Alternatively, Access/JET will sometimes let you get away with saving a subquery as a separate query and then joining it in the UPDATE statement in a more traditional way. So, for instance, if we saved the SELECT subquery above as a separate query named FUNCTIONS_TAX, then the UPDATE statement would be:

UPDATE FUNCTIONS
INNER JOIN FUNCTIONS_TAX
ON FUNCTIONS.Func_ID = FUNCTIONS_TAX.Func_ID
SET FUNCTIONS.Func_TaxRef = FUNCTIONS_TAX.MinOfTax_Code

However, this still doesn't work.

I believe the only way you will make this work is to move the selection and aggregation of the minimum Tax_Code value out-of-band. You could do this with a VBA function, or more easily using the Access DLookup function. Save the GROUP BY subquery above to a separate query named FUNCTIONS_TAX and rewrite the UPDATE statement as:

UPDATE FUNCTIONS
SET Func_TaxRef = DLookup(
  "MinOfTax_Code", 
  "FUNCTIONS_TAX", 
  "Func_ID = '" & Func_ID & "'"
)

Note that the DLookup function prevents this query from being used outside of Access, for instance via JET OLEDB. Also, the performance of this approach can be pretty terrible depending on how many rows you're targeting, as the subquery is being executed for each FUNCTIONS row (because, of course, it is no longer correlated, which is the whole point in order for it to work).

Good luck!

WCF error - There was no endpoint listening at

I had the same issue. For me I noticed that the https is using another Certificate which was invalid in terms of expiration date. Not sure why it happened. I changed the Https port number and a new self signed cert. WCFtestClinet could connect to the server via HTTPS!

How to install pandas from pip on windows cmd?

In my opinion, the issue is because the environment variable is not set up to recognize pip as a valid command.

In general, the pip in Python is at this location:

C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts > pip

So all we need to do is go to Computer Name> Right Click > Advanced System Settings > Select Env Variable then under system variables > reach to Path> Edit path and add the Path by separating this path by putting a semicolon after the last path already was in the Env Variable.

Now run Python shell, and this should work.

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

<?php

    /**
     * Comparison of two PHP objects                         ==     ===
     * Checks for
     * 1. References                                         yes    yes
     * 2. Instances with matching attributes and its values  yes    no
     * 3. Instances with different attributes                yes    no
     **/

    // There is no need to worry about comparing visibility of property or
    // method, because it will be the same whenever an object instance is
    // created, however visibility of an object can be modified during run
    // time using ReflectionClass()
    // http://php.net/manual/en/reflectionproperty.setaccessible.php
    //
    class Foo
    {
        public $foobar = 1;

        public function createNewProperty($name, $value)
        {
            $this->{$name} = $value;
        }
    }

    class Bar
    {
    }
    // 1. Object handles or references
    // Is an object a reference to itself or a clone or totally a different object?
    //
    //   ==  true   Name of two objects are same, for example, Foo() and Foo()
    //   ==  false  Name of two objects are different, for example, Foo() and Bar()
    //   === true   ID of two objects are same, for example, 1 and 1
    //   === false  ID of two objects are different, for example, 1 and 2

    echo "1. Object handles or references (both == and    ===) <br />";

    $bar = new Foo();    // New object Foo() created
    $bar2 = new Foo();   // New object Foo() created
    $baz = clone $bar;   // Object Foo() cloned
    $qux = $bar;         // Object Foo() referenced
    $norf = new Bar();   // New object Bar() created
    echo "bar";
    var_dump($bar);
    echo "baz";
    var_dump($baz);
    echo "qux";
    var_dump($qux);
    echo "bar2";
    var_dump($bar2);
    echo "norf";
    var_dump($norf);

    // Clone: == true and === false
    echo '$bar == $bar2';
    var_dump($bar == $bar2); // true

    echo '$bar === $bar2';
    var_dump($bar === $bar2); // false

    echo '$bar == $baz';
    var_dump($bar == $baz); // true

    echo '$bar === $baz';
    var_dump($bar === $baz); // false

    // Object reference: == true and === true
    echo '$bar == $qux';
    var_dump($bar == $qux); // true

    echo '$bar === $qux';
    var_dump($bar === $qux); // true

    // Two different objects: == false and === false
    echo '$bar == $norf';
    var_dump($bar == $norf); // false

    echo '$bar === $norf';
    var_dump($bar === $norf); // false

    // 2. Instances with matching attributes and its values (only ==).
    //    What happens when objects (even in cloned object) have same
    //    attributes but varying values?

    // $foobar value is different
    echo "2. Instances with matching attributes  and its values (only ==) <br />";

    $baz->foobar = 2;
    echo '$foobar' . " value is different <br />";
    echo '$bar->foobar = ' . $bar->foobar . "<br />";
    echo '$baz->foobar = ' . $baz->foobar . "<br />";
    echo '$bar == $baz';
    var_dump($bar == $baz); // false

    // $foobar's value is the same again
    $baz->foobar = 1;
    echo '$foobar' . " value is the same again <br />";
    echo '$bar->foobar is ' . $bar->foobar . "<br />";
    echo '$baz->foobar is ' . $baz->foobar . "<br />";
    echo '$bar == $baz';
    var_dump($bar == $baz); // true

    // Changing values of properties in $qux object will change the property
    // value of $bar and evaluates true always, because $qux = &$bar.
    $qux->foobar = 2;
    echo '$foobar value of both $qux and $bar is 2, because $qux = &$bar' . "<br />";
    echo '$qux->foobar is ' . $qux->foobar . "<br />";
    echo '$bar->foobar is ' . $bar->foobar . "<br />";
    echo '$bar == $qux';
    var_dump($bar == $qux); // true

    // 3. Instances with different attributes (only ==)
    //    What happens when objects have different attributes even though
    //    one of the attributes has same value?
    echo "3. Instances with different attributes (only ==) <br />";

    // Dynamically create a property with the name in $name and value
    // in $value for baz object
    $name = 'newproperty';
    $value = null;
    $baz->createNewProperty($name, $value);
    echo '$baz->newproperty is ' . $baz->{$name};
    var_dump($baz);

    $baz->foobar = 2;
    echo '$foobar' . " value is same again <br />";
    echo '$bar->foobar is ' . $bar->foobar . "<br />";
    echo '$baz->foobar is ' . $baz->foobar . "<br />";
    echo '$bar == $baz';
    var_dump($bar == $baz); // false
    var_dump($bar);
    var_dump($baz);
?>

How do I revert back to an OpenWrt router configuration?

If you enabled it as a DHCP client then your router should get an IP address from a DHCP server. If you connect your router on a net with a DHCP server you should reach your router's administrator page on the IP address assigned by the DHCP.

Invalid Host Header when ngrok tries to connect to React dev server

Option 1

If you do not need to use Authentication you can add configs to ngrok commands

ngrok http 9000 --host-header=rewrite

or

ngrok http 9000 --host-header="localhost:9000"

But in this case Authentication will not work on your website because ngrok rewriting headers and session is not valid for your ngrok domain

Option 2

If you are using webpack you can add the following configuration

devServer: {
    disableHostCheck: true
}

In that case Authentication header will be valid for your ngrok domain

Evenly space multiple views within a container view

Very easy way to solve this in InterfaceBuilder:

Set the centered label (label2) to "Horizontal Center in Container" and "Vertical Center in Container"

Select the centered label and the top label (label1 + label2) and add TWO constraints for Vertical Spacing. One with Greater Than or Equal the min spacing. One with Less Than or Equal the max spacing.

The same for the centered label and the bottom label (label2 + label3).

Additionally you could also add two constraints to label1 - Top Space To SuperView and two constraints to label2 - Bottom Space To SuperView.

The result will be that all 4 spacings will change their sizes equally.

Using RegEx in SQL Server

You do not need to interact with managed code, as you can use LIKE:

CREATE TABLE #Sample(Field varchar(50), Result varchar(50))
GO
INSERT INTO #Sample (Field, Result) VALUES ('ABC123 ', 'Do not match')
INSERT INTO #Sample (Field, Result) VALUES ('ABC123.', 'Do not match')
INSERT INTO #Sample (Field, Result) VALUES ('ABC123&', 'Match')
SELECT * FROM #Sample WHERE Field LIKE '%[^a-z0-9 .]%'
GO
DROP TABLE #Sample

As your expression ends with + you can go with '%[^a-z0-9 .][^a-z0-9 .]%'

EDIT:
To make it clear: SQL Server doesn't support regular expressions without managed code. Depending on the situation, the LIKE operator can be an option, but it lacks the flexibility that regular expressions provides.

String Comparison in Java

Java lexicographically order:

  1. Numbers -before-
  2. Uppercase -before-
  3. Lowercase

Odd as this seems, it is true...
I have had to write comparator chains to be able to change the default behavior.
Play around with the following snippet with better examples of input strings to verify the order (you will need JSE 8):

import java.util.ArrayList;

public class HelloLambda {

public static void main(String[] args) {
    ArrayList<String> names = new ArrayList<>();
    names.add("Kambiz");
    names.add("kambiz");
    names.add("k1ambiz");
    names.add("1Bmbiza");
    names.add("Samantha");
    names.add("Jakey");
    names.add("Lesley");
    names.add("Hayley");
    names.add("Benjamin");
    names.add("Anthony");

    names.stream().
        filter(e -> e.contains("a")).
        sorted().
        forEach(System.out::println);
}
}

Result

1Bmbiza
Benjamin
Hayley
Jakey
Kambiz
Samantha
k1ambiz
kambiz

Please note this is answer is Locale specific.
Please note that I am filtering for a name containing the lowercase letter a.

Just disable scroll not hide it?

I'm the OP

With the help of answer from fcalderan I was able to form a solution. I leave my solution here as it brings clarity to how to use it, and adds a very crucial detail, width: 100%;

I add this class

body.noscroll
{
    position: fixed; 
    overflow-y: scroll;
    width: 100%;
}

this worked for me and I was using Fancyapp.

Async/Await Class Constructor

@slebetmen's accepted answer explains well why this doesn't work. In addition to the two patterns presented in that answer, another option is to only access your async properties through a custom async getter. The constructor() can then trigger the async creation of the properties, but the getter then checks to see if the property is available before it uses or returns it.

This approach is particularly useful when you want to initialize a global object once on startup, and you want to do it inside a module. Instead of initializing in your index.js and passing the instance in the places that need it, simply require your module wherever the global object is needed.

Usage

const instance = new MyClass();
const prop = await instance.getMyProperty();

Implementation

class MyClass {
  constructor() {
    this.myProperty = null;
    this.myPropertyPromise = this.downloadAsyncStuff();
  }
  async downloadAsyncStuff() {
    // await yourAsyncCall();
    this.myProperty = 'async property'; // this would instead by your async call
    return this.myProperty;
  }
  getMyProperty() {
    if (this.myProperty) {
      return this.myProperty;
    } else {
      return this.myPropertyPromise;
    }
  }
}

Inserting values to SQLite table in Android

I recommend to create a method just for inserting and than use ContentValues. For further info https://www.tutorialspoint.com/android/android_sqlite_database.htm

public boolean insertToTable(String DESCRIPTION, String AMOUNT, String TRNS){

    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues contentValues = new ContentValues();
    contentValues.put("this is",DESCRIPTION);
    contentValues.put("5000",AMOUNT);
    contentValues.put("TRAN",TRNS);
    db.insert("Your table name",null,contentValues);

    return true;
}

How to sum array of numbers in Ruby?

Try this:

array.inject(0){|sum,x| sum + x }

See Ruby's Enumerable Documentation

(note: the 0 base case is needed so that 0 will be returned on an empty array instead of nil)

How are cookies passed in the HTTP protocol?

Cookies are passed as HTTP headers, both in the request (client -> server), and in the response (server -> client).

What is the color code for transparency in CSS?

Simply choose your background color of your item and specify the opacity separatly:

div { background-color:#000; opacity:0.8; }

How to get the HTML for a DOM element in javascript

var x = $('#container').get(0).outerHTML;

How can I use NSError in my iPhone App?

I'll try summarize the great answer by Alex and the jlmendezbonini's point, adding a modification that will make everything ARC compatible (so far it's not since ARC will complain since you should return id, which means "any object", but BOOL is not an object type).

- (BOOL) endWorldHunger:(id)largeAmountsOfMonies error:(NSError**)error {
    // begin feeding the world's children...
    // it's all going well until....
    if (ohNoImOutOfMonies) {
        // sad, we can't solve world hunger, but we can let people know what went wrong!
        // init dictionary to be used to populate error object
        NSMutableDictionary* details = [NSMutableDictionary dictionary];
        [details setValue:@"ran out of money" forKey:NSLocalizedDescriptionKey];
        // populate the error object with the details
        if (error != NULL) {
             // populate the error object with the details
             *error = [NSError errorWithDomain:@"world" code:200 userInfo:details];
        }
        // we couldn't feed the world's children...return nil..sniffle...sniffle
        return NO;
    }
    // wohoo! We fed the world's children. The world is now in lots of debt. But who cares? 
    return YES;
}

Now instead of checking for the return value of our method call, we check whether error is still nil. If it's not we have a problem.

// initialize NSError object
NSError* error = nil;
// try to feed the world
BOOL success = [self endWorldHunger:smallAmountsOfMonies error:&error];
if (!success) {
   // inspect error
   NSLog(@"%@", [error localizedDescription]);
}
// otherwise the world has been fed. Wow, your code must rock.

How to iterate through range of Dates in Java?

private static void iterateBetweenDates(Date startDate, Date endDate) {
    Calendar startCalender = Calendar.getInstance();
    startCalender.setTime(startDate);
    Calendar endCalendar = Calendar.getInstance();
    endCalendar.setTime(endDate);

    for(; startCalender.compareTo(endCalendar)<=0;
          startCalender.add(Calendar.DATE, 1)) {
        // write your main logic here
    }

}

What is the way of declaring an array in JavaScript?

The preferred way is to always use the literal syntax with square brackets; its behaviour is predictable for any number of items, unlike Array's. What's more, Array is not a keyword, and although it is not a realistic situation, someone could easily overwrite it:

function Array() { return []; }

alert(Array(1, 2, 3)); // An empty alert box

However, the larger issue is that of consistency. Someone refactoring code could come across this function:

function fetchValue(n) {
    var arr = new Array(1, 2, 3);

    return arr[n];
}

As it turns out, only fetchValue(0) is ever needed, so the programmer drops the other elements and breaks the code, because it now returns undefined:

var arr = new Array(1);

Find the max of two or more columns with pandas

@DSM's answer is perfectly fine in almost any normal scenario. But if you're the type of programmer who wants to go a little deeper than the surface level, you might be interested to know that it is a little faster to call numpy functions on the underlying .to_numpy() (or .values for <0.24) array instead of directly calling the (cythonized) functions defined on the DataFrame/Series objects.

For example, you can use ndarray.max() along the first axis.

# Data borrowed from @DSM's post.
df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
df
   A  B
0  1 -2
1  2  8
2  3  1

df['C'] = df[['A', 'B']].values.max(1)
# Or, assuming "A" and "B" are the only columns, 
# df['C'] = df.values.max(1) 
df

   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3 

If your data has NaNs, you will need numpy.nanmax:

df['C'] = np.nanmax(df.values, axis=1)
df

   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3 

You can also use numpy.maximum.reduce. numpy.maximum is a ufunc (Universal Function), and every ufunc has a reduce:

df['C'] = np.maximum.reduce(df['A', 'B']].values, axis=1)
# df['C'] = np.maximum.reduce(df[['A', 'B']], axis=1)
# df['C'] = np.maximum.reduce(df, axis=1)
df

   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3

enter image description here

np.maximum.reduce and np.max appear to be more or less the same (for most normal sized DataFrames)—and happen to be a shade faster than DataFrame.max. I imagine this difference roughly remains constant, and is due to internal overhead (indexing alignment, handling NaNs, etc).

The graph was generated using perfplot. Benchmarking code, for reference:

import pandas as pd
import perfplot

np.random.seed(0)
df_ = pd.DataFrame(np.random.randn(5, 1000))

perfplot.show(
    setup=lambda n: pd.concat([df_] * n, ignore_index=True),
    kernels=[
        lambda df: df.assign(new=df.max(axis=1)),
        lambda df: df.assign(new=df.values.max(1)),
        lambda df: df.assign(new=np.nanmax(df.values, axis=1)),
        lambda df: df.assign(new=np.maximum.reduce(df.values, axis=1)),
    ],
    labels=['df.max', 'np.max', 'np.maximum.reduce', 'np.nanmax'],
    n_range=[2**k for k in range(0, 15)],
    xlabel='N (* len(df))',
    logx=True,
    logy=True)

Calling UserForm_Initialize() in a Module

From a module:

UserFormName.UserForm_Initialize

Just make sure that in your userform, you update the sub like so:

Public Sub UserForm_Initialize() so it can be called from outside the form.

Alternately, if the Userform hasn't been loaded:

UserFormName.Show will end up calling UserForm_Initialize because it loads the form.

PHP cURL not working - WAMP on Windows 7 64 bit

Works for me:

  • Go to this link
  • Download *php_curl-5.4.3-VC9-x64.zip* under "Fixed curl extensions:"
  • Replace the php_curl.dll file in the ext folder.

This worked for me.

Docker remove <none> TAG images

try this to see list docker images ID with tag <none>

docker images -a | awk '/^<none>/ {print $3}'

and then you can delete all image with tag <none>. this worked for me.

docker rmi $(docker images -a | awk '/^<none>/ {print $3}')

npm install Error: rollbackFailedOptional

I've already had the proxies set as described above and it was working until today. Then it turned out that now I need "http://" in front of my proxy address: "http://{proxyURL}:{proxyPort}". Then it finally worked.

Unable to Install Any Package in Visual Studio 2015

I was able to resolve this issue by reinstalling Nuget Package Manager via Tools -> Extensions and Updates

Python: Get the first character of the first string in a list?

Try mylist[0][0]. This should return the first character.