Programs & Examples On #Bnf

BNF stands for Backus-Naur Form, or Backus Normal Form. It is a form of notation for context-free grammars and is often used for (but is not restricted to) the description of the syntax of programming languages. In addition to programming languages, it is also used to describe communication protocols and document formats.

ProgressDialog spinning circle

Just change from ProgressDialog to ProgressBar in a layout:

res/layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
        //Your content here
     </LinearLayout>

        <ProgressBar
            android:id="@+id/progressBar"
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:visibility="gone"
            android:indeterminateDrawable="@drawable/progress" >
        </ProgressBar>
</RelativeLayout>

src/yourPackage/YourActivity.java

public class YourActivity extends Activity{

private ProgressBar bar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout);
    bar = (ProgressBar) this.findViewById(R.id.progressBar);
    new ProgressTask().execute();
}
private class ProgressTask extends AsyncTask <Void,Void,Void>{
    @Override
    protected void onPreExecute(){
        bar.setVisibility(View.VISIBLE);
    }

    @Override
    protected Void doInBackground(Void... arg0) {   
           //my stuff is here
    }

    @Override
    protected void onPostExecute(Void result) {
          bar.setVisibility(View.GONE);
    }
}
}

drawable/progress.xml This is a custom ProgressBar that i use to change the default colors.

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

<!-- 
    Duration = 1 means that one rotation will be done in 1 second. leave it.
    If you want to speed up the rotation, increase duration value. 
    in example 1080 shows three times faster revolution. 
    make the value multiply of 360, or the ring animates clunky 
-->
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:duration="1"
    android:toDegrees="360" >

    <shape
        android:innerRadiusRatio="3"
        android:shape="ring"
        android:thicknessRatio="8"
        android:useLevel="false" >
        <size
            android:height="48dip"
            android:width="48dip" />

        <gradient
            android:centerColor="@color/color_preloader_center"
            android:centerY="0.50"
            android:endColor="@color/color_preloader_end"
            android:startColor="@color/color_preloader_start"
            android:type="sweep"
            android:useLevel="false" />
    </shape>

</rotate>

How to convert image into byte array and byte array to base64 String in android?

here is another solution...

System.IO.Stream st = new System.IO.StreamReader (picturePath).BaseStream;
byte[] buffer = new byte[4096];

System.IO.MemoryStream m = new System.IO.MemoryStream ();
while (st.Read (buffer,0,buffer.Length) > 0) {
    m.Write (buffer, 0, buffer.Length);
}  
imgView.Tag = m.ToArray ();
st.Close ();
m.Close ();

hope it helps!

Add a pipe separator after items in an unordered list unless that item is the last on a line

I came across a solution today that does not appear to be here already and which seems to work quite well so far. The accepted answer does not work as-is on IE10 but this one does. http://codepen.io/vithun/pen/yDsjf/ credit to the author of course!

_x000D_
_x000D_
.pipe-separated-list-container {_x000D_
  overflow-x: hidden;_x000D_
}_x000D_
.pipe-separated-list-container ul {_x000D_
  list-style-type: none;_x000D_
  position: relative;_x000D_
  left: -1px;_x000D_
  padding: 0;_x000D_
}_x000D_
.pipe-separated-list-container ul li {_x000D_
  display: inline-block;_x000D_
  line-height: 1;_x000D_
  padding: 0 1em;_x000D_
  margin-bottom: 1em;_x000D_
  border-left: 1px solid;_x000D_
}
_x000D_
<div class="pipe-separated-list-container">_x000D_
  <ul>_x000D_
    <li>One</li>_x000D_
    <li>Two</li>_x000D_
    <li>Three</li>_x000D_
    <li>Four</li>_x000D_
    <li>Five</li>_x000D_
    <li>Six</li>_x000D_
    <li>Seven</li>_x000D_
    <li>Eight</li>_x000D_
    <li>Nine</li>_x000D_
    <li>Ten</li>_x000D_
    <li>Eleven</li>_x000D_
    <li>Twelve</li>_x000D_
    <li>Thirteen</li>_x000D_
    <li>Fourteen</li>_x000D_
    <li>Fifteen</li>_x000D_
    <li>Sixteen</li>_x000D_
    <li>Seventeen</li>_x000D_
    <li>Eighteen</li>_x000D_
    <li>Nineteen</li>_x000D_
    <li>Twenty</li>_x000D_
    <li>Twenty One</li>_x000D_
    <li>Twenty Two</li>_x000D_
    <li>Twenty Three</li>_x000D_
    <li>Twenty Four</li>_x000D_
    <li>Twenty Five</li>_x000D_
    <li>Twenty Six</li>_x000D_
    <li>Twenty Seven</li>_x000D_
    <li>Twenty Eight</li>_x000D_
    <li>Twenty Nine</li>_x000D_
    <li>Thirty</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

what does this mean ? image/png;base64?

That data:image/png;base64 URL is cool, I’ve never run into it before. The long encrypted link is the actual image, i.e. no image call to the server. See RFC 2397 for details.

Side note: I have had trouble getting larger base64 images to render on IE8. I believe IE8 has a 32K limit that can be problematic for larger files. See this other StackOverflow thread for details.

What is parsing in terms that a new programmer would understand?

Parsing is about READING data in one format, so that you can use it to your needs.

I think you need to teach them to think like this. So, this is the simplest way I can think of to explain parsing for someone new to this concept.

Generally, we try to parse data one line at a time because generally it is easier for humans to think this way, dividing and conquering, and also easier to code.

We call field to every minimum undivisible data. Name is field, Age is another field, and Surname is another field. For example.

In a line, we can have various fields. In order to distinguish them, we can delimit fields by separators or by the maximum length assign to each field.

For example: By separating fields by comma

Paul,20,Jones

Or by space (Name can have 20 letters max, age up to 3 digits, Jones up to 20 letters)

Paul                020Jones               

Any of the before set of fields is called a record.

To separate between a delimited field record we need to delimit record. A dot will be enough (though you know you can apply CR/LF).

A list could be:

Michael,39,Jordan.Shaquille,40,O'neal.Lebron,24,James.

or with CR/LF

Michael,39,Jordan
Shaquille,40,O'neal
Lebron,24,James

You can say them to list 10 nba (or nlf) players they like. Then, they should type them according to a format. Then make a program to parse it and display each record. One group, can make list in a comma-separated format and a program to parse a list in a fixed size format, and viceversa.

lexers vs parsers

Yes, they are very different in theory, and in implementation.

Lexers are used to recognize "words" that make up language elements, because the structure of such words is generally simple. Regular expressions are extremely good at handling this simpler structure, and there are very high-performance regular-expression matching engines used to implement lexers.

Parsers are used to recognize "structure" of a language phrases. Such structure is generally far beyond what "regular expressions" can recognize, so one needs "context sensitive" parsers to extract such structure. Context-sensitive parsers are hard to build, so the engineering compromise is to use "context-free" grammars and add hacks to the parsers ("symbol tables", etc.) to handle the context-sensitive part.

Neither lexing nor parsing technology is likely to go away soon.

They may be unified by deciding to use "parsing" technology to recognize "words", as is currently explored by so-called scannerless GLR parsers. That has a runtime cost, as you are applying more general machinery to what is often a problem that doesn't need it, and usually you pay for that in overhead. Where you have lots of free cycles, that overhead may not matter. If you process a lot of text, then the overhead does matter and classical regular expression parsers will continue to be used.

Remove duplicated rows

You can also use dplyr's distinct() function! It tends to be more efficient than alternative options, especially if you have loads of observations.

distinct_data <- dplyr::distinct(yourdata)

How do I disable a Button in Flutter?

You can also use the AbsorbPointer, and you can use it in the following way:

AbsorbPointer(
      absorbing: true, // by default is true
      child: RaisedButton(
        onPressed: (){
          print('pending to implement onPressed function');
        },
        child: Text("Button Click!!!"),
      ),
    ),

If you want to know more about this widget, you can check the following link Flutter Docs

Fatal error: Call to undefined function pg_connect()

  1. Add 'PHPIniDir "C:/php"' into the httpd.conf file.(provided you have your PHP saved in C:, or else give the location where PHP is saved.)
  2. Uncomment following 'extension=php_pgsql.dll' in php.ini file
  3. Uncomment ';extension_dir = "ext"' in php.ini directory

Two Decimal places using c#

Probably a variant of the other examples, but I use this method to also make sure a dot is shown before the decimal places and not a comma:

someValue.ToString("0.00", CultureInfo.InvariantCulture)

download and install visual studio 2008

https://www.microsoft.com/en-us/download/details.aspx?id=14258

which leads to:

Microsoft® Visual Studio Team System 2008 Database Edition GDR R2

Hope this is helpfull

Setting the classpath in java using Eclipse IDE

Try this:

Project -> Properties -> Java Build Path -> Add Class Folder.

If it doesnt work, please be specific in what way your compilation fails, specifically post the error messages Eclipse returns, and i will know what to do about it.

ListView inside ScrollView is not scrolling on Android

list.setOnTouchListener(new OnTouchListener() {
    // Setting on Touch Listener for handling the touch inside ScrollView
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        // Disallow the touch request for parent scroll on touch of child view
        v.getParent().requestDisallowInterceptTouchEvent(true);
        return false;
    }
});

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

I had the same problem and none of these solutions worked and I don't know why, they worked for me in the past for similar problems.

Anyway to solve the problem I've just manually rebuild the package using node-pre-gyp

cd node_modules/bcrypt
node-pre-gyp rebuild

And everything worked as expected.

Hope this helps

Suppress console output in PowerShell

Try redirecting the output to Out-Null. Like so,

$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose | out-null

How to change the remote a branch is tracking?

After trying the above and searching, searching, etc. I realized none of my changes were on the server that were on my local branch and Visual Studio in Team Explorer did not indicate this branch tracked a remote branch. The remote branch was there, so it should have worked. I ended up deleting the remote branch on github and 're' Push my local branch that had my changes that were not being tracked for an unknown reason.

By deleting the remote branch and 're' Push my local branch that was not being tracked, the local branch was re-created on git hub. I tried to this at the command prompt (using Windows) I could not get my local branch to track the remote branch until I did this. Everything is back to normal.

Converting integer to binary in python

eumiro's answer is better, however I'm just posting this for variety:

>>> "%08d" % int(bin(6)[2:])
00000110

How to get a view table query (code) in SQL Server 2008 Management Studio

Use sp_helptext before the view_name. Example:

sp_helptext Example_1

Hence you will get the query:

CREATE VIEW dbo.Example_1
AS
SELECT       a, b, c
FROM         dbo.table_name JOIN blah blah blah
WHERE        blah blah blah

sp_helptext will give stored procedures.

Calculate percentage saved between two numbers?

100% - discounted price / full price

How do I turn a C# object into a JSON string in .NET?

Use the below code for converting XML to JSON.

var json = new JavaScriptSerializer().Serialize(obj);

Eclipse: stop code from running (java)

The easiest way to do this is to click on the Terminate button(red square) in the console:

enter image description here

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

Here is my full solution for Full Screen and Exit Full Screen both (many thanks to help from tower's answer above):

$(document).ready(function(){
$.is_fs = false;
$.requestFullScreen = function(calr)
{
    var element = document.body;

    // Supports most browsers and their versions.
    var requestMethod = element.requestFullScreen || element.webkitRequestFullScreen || element.mozRequestFullScreen || element.msRequestFullScreen;

    if (requestMethod) { // Native full screen.
        requestMethod.call(element);
    } else if (typeof window.ActiveXObject !== "undefined") { // Older IE.
        var wscript = new ActiveXObject("WScript.Shell");
        if (wscript !== null) {
            wscript.SendKeys("{F11}");
        }
    }

    $.is_fs = true;    
    $(calr).val('Exit Full Screen');
}

$.cancel_fs = function(calr)
{
    var element = document; //and NOT document.body!!
    var requestMethod = element.exitFullScreen || element.mozCancelFullScreen || element.webkitExitFullScreen || element.mozExitFullScreen || element.msExitFullScreen || element.webkitCancelFullScreen;

    if (requestMethod) { // Native full screen.
    requestMethod.call(element);
    } else if (typeof window.ActiveXObject !== "undefined") { // Older IE.
        var wscript = new ActiveXObject("WScript.Shell");
        if (wscript !== null) {
            wscript.SendKeys("{F11}");
        }
    }    

    $(calr).val('Full Screen');    
    $.is_fs = false;
}

$.toggleFS = function(calr)
{    
    $.is_fs == true? $.cancel_fs(calr):$.requestFullScreen(calr);
}

});

// CALLING:

<input type="button" value="Full Screen" onclick="$.toggleFS(this);" />

Combining two sorted lists in Python

is there a smarter way to do this in Python

This hasn't been mentioned, so I'll go ahead - there is a merge stdlib function in the heapq module of python 2.6+. If all you're looking to do is getting things done, this might be a better idea. Of course, if you want to implement your own, the merge of merge-sort is the way to go.

>>> list1 = [1, 5, 8, 10, 50]
>>> list2 = [3, 4, 29, 41, 45, 49]
>>> from heapq import merge
>>> list(merge(list1, list2))
[1, 3, 4, 5, 8, 10, 29, 41, 45, 49, 50]

Here's the documentation.

Return in Scala

Don't write if statements without a corresponding else. Once you add the else to your fragment you'll see that your true and false are in fact the last expressions of the function.

def balanceMain(elem: List[Char]): Boolean =
  {
    if (elem.isEmpty)
      if (count == 0)
        true
      else
        false
    else
      if (elem.head == '(')
        balanceMain(elem.tail, open, count + 1)
      else....

Which is the best library for XML parsing in java

You don't need an external library for parsing XML in Java. Java has come with built-in implementations for SAX and DOM for ages.

C# Error "The type initializer for ... threw an exception

I had this problem and like Anderson Imes said it had to do with app settings. My problem was the scope of one of my settings was set to "User" when it should have been "Application".

How to reload .bashrc settings without logging out and back in again?

To complement and contrast the two most popular answers, . ~/.bashrc and exec bash:

Both solutions effectively reload ~/.bashrc, but there are differences:

  • . ~/.bashrc or source ~/.bashrc will preserve your current shell:

    • Except for the modifications that reloading ~/.bashrc into the current shell (sourcing) makes, the current shell and its state are preserved, which includes environment variables, shell variables, shell options, shell functions, and command history.
  • exec bash, or, more robustly, exec "$BASH"[1], will replace your current shell with a new instance, and therefore only preserve your current shell's environment variables (including ones you've defined ad-hoc).

    • In other words: Any ad-hoc changes to the current shell in terms of shell variables, shell functions, shell options, command history are lost.

Depending on your needs, one or the other approach may be preferred.


[1] exec bash could in theory execute a different bash executable than the one that started the current shell, if it happens to exist in a directory listed earlier in the $PATH. Since special variable $BASH always contains the full path of the executable that started the current shell, exec "$BASH" is guaranteed to use the same executable.
A note re "..." around $BASH: double-quoting ensures that the variable value is used as-is, without interpretation by Bash; if the value has no embedded spaces or other shell metacharacters (which is not likely in this case), you don't strictly need double quotes, but using them is a good habit to form.

How to increase maximum execution time in php

You can try to set_time_limit(n). However, if your PHP setup is running in safe mode, you can only change it from the php.ini file.

How can I print a quotation mark in C?

you should use escape character like this:

printf("\"");

How to find row number of a value in R code

If you want to know the row and column of a value in a matrix or data.frame, consider using the arr.ind=TRUE argument to which:

> which(mydata_2 == 1578, arr.ind=TRUE)
  row col
7   7   3

So 1578 is in column 3 (which you already know) and row 7.

How to change the scrollbar color using css

Your css will only work in IE browser. And the css suggessted by hayk.mart will olny work in webkit browsers. And by using different css hacks you can't style your browsers scroll bars with a same result.

So, it is better to use a jQuery/Javascript plugin to achieve a cross browser solution with a same result.

Solution:

By Using jScrollPane a jQuery plugin, you can achieve a cross browser solution

See This Demo

Open an html page in default browser with VBA?

If you want a more robust solution with ShellExecute that will open ANY file, folder or URL using the default OS associated program to do so, here is a function taken from http://access.mvps.org/access/api/api0018.htm:

'************ Code Start **********
' This code was originally written by Dev Ashish.
' It is not to be altered or distributed,
' except as part of an application.
' You are free to use it in any application,
' provided the copyright notice is left unchanged.
'
' Code Courtesy of
' Dev Ashish
'
Private Declare Function apiShellExecute Lib "shell32.dll" _
    Alias "ShellExecuteA" _
    (ByVal hwnd As Long, _
    ByVal lpOperation As String, _
    ByVal lpFile As String, _
    ByVal lpParameters As String, _
    ByVal lpDirectory As String, _
    ByVal nShowCmd As Long) _
    As Long

'***App Window Constants***
Public Const WIN_NORMAL = 1         'Open Normal
Public Const WIN_MAX = 3            'Open Maximized
Public Const WIN_MIN = 2            'Open Minimized

'***Error Codes***
Private Const ERROR_SUCCESS = 32&
Private Const ERROR_NO_ASSOC = 31&
Private Const ERROR_OUT_OF_MEM = 0&
Private Const ERROR_FILE_NOT_FOUND = 2&
Private Const ERROR_PATH_NOT_FOUND = 3&
Private Const ERROR_BAD_FORMAT = 11&

'***************Usage Examples***********************
'Open a folder:     ?fHandleFile("C:\TEMP\",WIN_NORMAL)
'Call Email app:    ?fHandleFile("mailto:[email protected]",WIN_NORMAL)
'Open URL:          ?fHandleFile("http://home.att.net/~dashish", WIN_NORMAL)
'Handle Unknown extensions (call Open With Dialog):
'                   ?fHandleFile("C:\TEMP\TestThis",Win_Normal)
'Start Access instance:
'                   ?fHandleFile("I:\mdbs\CodeNStuff.mdb", Win_NORMAL)
'****************************************************

Function fHandleFile(stFile As String, lShowHow As Long)
Dim lRet As Long, varTaskID As Variant
Dim stRet As String
    'First try ShellExecute
    lRet = apiShellExecute(hWndAccessApp, vbNullString, _
            stFile, vbNullString, vbNullString, lShowHow)

    If lRet > ERROR_SUCCESS Then
        stRet = vbNullString
        lRet = -1
    Else
        Select Case lRet
            Case ERROR_NO_ASSOC:
                'Try the OpenWith dialog
                varTaskID = Shell("rundll32.exe shell32.dll,OpenAs_RunDLL " _
                        & stFile, WIN_NORMAL)
                lRet = (varTaskID <> 0)
            Case ERROR_OUT_OF_MEM:
                stRet = "Error: Out of Memory/Resources. Couldn't Execute!"
            Case ERROR_FILE_NOT_FOUND:
                stRet = "Error: File not found.  Couldn't Execute!"
            Case ERROR_PATH_NOT_FOUND:
                stRet = "Error: Path not found. Couldn't Execute!"
            Case ERROR_BAD_FORMAT:
                stRet = "Error:  Bad File Format. Couldn't Execute!"
            Case Else:
        End Select
    End If
    fHandleFile = lRet & _
                IIf(stRet = "", vbNullString, ", " & stRet)
End Function
'************ Code End **********

Just put this into a separate module and call fHandleFile() with the right parameters.

Python: call a function from string name

You can use a dictionary too.

def install():
    print "In install"

methods = {'install': install}

method_name = 'install' # set by the command line options
if method_name in methods:
    methods[method_name]() # + argument list of course
else:
    raise Exception("Method %s not implemented" % method_name)

DataAdapter.Fill(Dataset)

leDbConnection connection = 
new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Inventar.accdb");
DataSet1 DS = new DataSet1();
connection.Open();

OleDbDataAdapter DBAdapter = new OleDbDataAdapter(
@"SELECT tbl_Computer.*,  tbl_Besitzer.*
  FROM tbl_Computer 
  INNER JOIN tbl_Besitzer ON tbl_Computer.FK_Benutzer = tbl_Besitzer.ID 
  WHERE (((tbl_Besitzer.Vorname)='ma'));", 
connection);

Haskell: Converting Int to String

An example based on Chuck's answer:

myIntToStr :: Int -> String
myIntToStr x
    | x < 3     = show x ++ " is less than three"
    | otherwise = "normal"

Note that without the show the third line will not compile.

How to get Top 5 records in SqLite?

An equivalent statement would be

select * from [TableName] limit 5

http://www.w3schools.com/sql/sql_top.asp

log4j vs logback

Should you? Yes.

Why? Log4J has essentially been deprecated by Logback.

Is it urgent? Maybe not.

Is it painless? Probably, but it may depend on your logging statements.

Note that if you really want to take full advantage of LogBack (or SLF4J), then you really need to write proper logging statements. This will yield advantages like faster code because of the lazy evaluation, and less lines of code because you can avoid guards.

Finally, I highly recommend SLF4J. (Why recreate the wheel with your own facade?)

Execute Python script via crontab

Put your script in a file foo.py starting with

#!/usr/bin/python

Then give execute permission to that script using

chmod a+x foo.py

and use the full path of your foo.py file in your crontab.

See documentation of execve(2) which is handling the shebang.

What is the canonical way to trim a string in Ruby without creating a new string?

My way:

> (@title = " abc ").strip!
 => "abc" 
> @title
 => "abc" 

How to establish a connection pool in JDBC?

Vibur DBCP is another library for that purpose. Several examples showing how to configure it for use with Hibernate, Spring+Hibernate, or programatically, can be found on its website: http://www.vibur.org/

Also, see the disclaimer here.

How to set the JSTL variable value in javascript?

one more approach to use.

first, define the following somewhere on the page:

<div id="valueHolderId">${someValue}</div>

then in JS, just do something similar to

var someValue = $('#valueHolderId').html();

it works great for the cases when all scripts are inside .js files and obviously there is no jstl available

The CSRF token is invalid. Please try to resubmit the form

You need to remember that CSRF token is stored in the session, so this problem can also occur due to invalid session handling. If you're working on the localhost, check e.g. if session cookie domain is set correctly (in PHP it should be empty when on localhost).

Detect whether current Windows version is 32 bit or 64 bit

Another way created by eGerman that uses PE numbers of compiled executables (does not rely on registry records or environment variables):

@echo off &setlocal


call :getPETarget "%SystemRoot%\explorer.exe"


if "%=ExitCode%" EQU "00008664" (
    echo x64
) else (
    if "%=ExitCode%" EQU "0000014C" (
        echo x32
    ) else (
        echo undefined
    )
)


goto :eof


:getPETarget FilePath
:: ~~~~~~~~~~~~~~~~~~~~~~
:: Errorlevel
::   0 Success
::   1 File Not Found
::   2 Wrong Magic Number
::   3 Out Of Scope
::   4 No PE File
:: ~~~~~~~~~~~~~~~~~~~~~~
:: =ExitCode
::   CPU identifier

setlocal DisableDelayedExpansion
set "File=%~1"
set Cmp="%temp%\%random%.%random%.1KB"
set Dmp="%temp%\%random%.%random%.dmp"

REM write 1024 times 'A' into a temporary file
if exist "%File%" (
  >%Cmp% (
    for /l %%i in (1 1 32) do <nul set /p "=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
  )
  setlocal EnableDelayedExpansion
) else (endlocal &cmd /c exit 0 &exit /b 1)

REM generate a HEX dump of the executable file (first 1024 Bytes)
set "X=1"
>!Dmp! (
  for /f "skip=1 tokens=1,2 delims=: " %%i in ('fc /b "!File!" !Cmp!^|findstr /vbi "FC:"') do (
    set /a "Y=0x%%i"
    for /l %%k in (!X! 1 !Y!) do echo 41
    set /a "X=Y+2"
    echo %%j
  )
)
del !Cmp!

REM read certain values out of the HEX dump
set "err="
<!Dmp! (
  set /p "A="
  set /p "B="
  REM magic number has to be "MZ"
  if "!A!!B!" neq "4D5A" (set "err=2") else (
    REM skip next 58 bytes
    for /l %%i in (3 1 60) do set /p "="
    REM bytes 61-64 contain the offset to the PE header in little endian order
    set /p "C="
    set /p "D="
    set /p "E="
    set /p "F="
    REM check if the beginning of the PE header is part of the HEX dump
    if 0x!F!!E!!D!!C! lss 1 (set "err=3") else (
      if 0x!F!!E!!D!!C! gtr 1018 (set "err=3") else (
        REM skip the offset to the PE header
        for /l %%i in (65 1 0x!F!!E!!D!!C!) do set /p "="
        REM next 4 bytes have to contain the signature of the PE header
        set /p "G="
        set /p "H="
        set /p "I="
        set /p "J="
        REM next 2 bytes contain the CPU identifier in little endian order
        set /p "K="
        set /p "L="
      )
    )
  )
)
del !Dmp!
if defined err (endlocal &endlocal &cmd /c exit 0 &exit /b %err%)

REM was the signature ("PE\0\0") of the PE header found
if "%G%%H%%I%%J%"=="50450000" (
  REM calculate the decimal value of the CPU identifier
  set /a "CPUID=0x%L%%K%"
) else (endlocal &endlocal &cmd /c exit 0 &exit /b 4)
endlocal &endlocal &cmd /c exit %CPUID% &exit /b 0

Use SQL Server Management Studio to connect remotely to an SQL Server Express instance hosted on an Azure Virtual Machine

I too struggled with something similar. My guess is your actual problem is connecting to a SQL Express instance running on a different machine. The steps to do this can be summarized as follows:

  1. Ensure SQL Express is configured for SQL Authentication as well as Windows Authentication (the default). You do this via SQL Server Management Studio (SSMS) Server Properties/Security
  2. In SSMS create a new login called "sqlUser", say, with a suitable password, "sql", say. Ensure this new login is set for SQL Authentication, not Windows Authentication. SSMS Server Security/Logins/Properties/General. Also ensure "Enforce password policy" is unchecked
  3. Under Properties/Server Roles ensure this new user has the "sysadmin" role
  4. In SQL Server Configuration Manager SSCM (search for SQLServerManagerxx.msc file in Windows\SysWOW64 if you can't find SSCM) under SQL Server Network Configuration/Protocols for SQLExpress make sure TCP/IP is enabled. You can disable Named Pipes if you want
  5. Right-click protocol TCP/IP and on the IPAddresses tab, ensure every one of the IP addresses is set to Enabled Yes, and TCP Port 1433 (this is the default port for SQL Server)
  6. In Windows Firewall (WF.msc) create two new Inbound Rules - one for SQL Server and another for SQL Browser Service. For SQL Server you need to open TCP Port 1433 (if you are using the default port for SQL Server) and very importantly for the SQL Browser Service you need to open UDP Port 1434. Name these two rules suitably in your firewall
  7. Stop and restart the SQL Server Service using either SSCM or the Services.msc snap-in
  8. In the Services.msc snap-in make sure SQL Browser Service Startup Type is Automatic and then start this service

At this point you should be able to connect remotely, using SQL Authentication, user "sqlUser" password "sql" to the SQL Express instance configured as above. A final tip and easy way to check this out is to create an empty text file with the .UDL extension, say "Test.UDL" on your desktop. Double-clicking to edit this file invokes the Microsoft Data Link Properties dialog with which you can quickly test your remote SQL connection

How to convert array values to lowercase in PHP?

Hi, try this solution. Simple use php array map

function myfunction($value)
{
 return strtolower($value);
}

$new_array = ["Value1","Value2","Value3" ];
print_r(array_map("myfunction",$new_array ));

Output Array ( [0] => value1 [1] => value2 [2] => value3 )

SQL Select between dates

One more way to select between dates in SQLite is to use the powerful strftime function:

SELECT * FROM test WHERE strftime('%Y-%m-%d', date) BETWEEN "11-01-2011" AND "11-08-2011"

These are equivalent according to https://sqlite.org/lang_datefunc.html:

date(...)

strftime('%Y-%m-%d', ...)

but if you want more choice, you have it.

How to load an ImageView by URL in Android?

Anyway people ask my comment to post it as answer. i am posting.

URL newurl = new URL(photo_url_str); 
mIcon_val = BitmapFactory.decodeStream(newurl.openConnection().getInputStream());
profile_photo.setImageBitmap(mIcon_val);

Can I use jQuery to check whether at least one checkbox is checked?

$("#frmTest").submit(function(){
    var checked = $("#frmText input:checked").length > 0;
    if (!checked){
        alert("Please check at least one checkbox");
        return false;
    }
});

How to locate the git config file in Mac

You don't need to find the file.

Only write this instruction on terminal:

git config --global --edit

Array.push() if does not exist?

In case you need something simple without wanting to extend the Array prototype:

// Example array
var array = [{id: 1}, {id: 2}, {id: 3}];

function pushIfNew(obj) {
  for (var i = 0; i < array.length; i++) {
    if (array[i].id === obj.id) { // modify whatever property you need
      return;
    }
  }
  array.push(obj);
}

Rails 2.3.4 Persisting Model on Validation Failure

In your controller, render the new action from your create action if validation fails, with an instance variable, @car populated from the user input (i.e., the params hash). Then, in your view, add a logic check (either an if block around the form or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car is set.

Create a date from day month and year with T-SQL

Or using just a single dateadd function:

DECLARE @day int, @month int, @year int
SELECT @day = 4, @month = 3, @year = 2011

SELECT dateadd(mm, (@year - 1900) * 12 + @month - 1 , @day - 1)

How to convert an ArrayList containing Integers to primitive int array?

If you're using Eclipse Collections, you can use the collectInt() method to switch from an object container to a primitive int container.

List<Integer> integers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
MutableIntList intList =
  ListAdapter.adapt(integers).collectInt(i -> i);
Assert.assertArrayEquals(new int[]{1, 2, 3, 4, 5}, intList.toArray());

If you can convert your ArrayList to a FastList, you can get rid of the adapter.

Assert.assertArrayEquals(
  new int[]{1, 2, 3, 4, 5},
  Lists.mutable.with(1, 2, 3, 4, 5)
    .collectInt(i -> i).toArray());

Note: I am a committer for Eclipse collections.

How to round up a number to nearest 10?

to nearest 10 , should be as below

$number = ceil($input * 0.1)/0.1 ;

What do numbers using 0x notation mean?

It's a hexadecimal number.

0x6400 translates to 4*16^2 + 6*16^3 = 25600

System.Data.SqlClient.SqlException: Invalid object name 'dbo.Projects'

If you use two databases you can add another DataClasses.dbml and map the second database into it.
It works.

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

java.text.ParseException: Unparseable date

  • Your formatting pattern fails to match the input string, as noted by other Answers.
  • Your input format is terrible.
  • You are using troublesome old date-time classes that were supplanted years ago by the java.time classes.

ISO 8601

Instead a format such as yours, use ISO 8601 standard formats for exchanging date-time values as text.

The java.time classes use the standard ISO 8601 formats by default when parsing/generating strings.

Proper time zone name

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

Your IST could mean Iceland Standard Time, India Standard Time, Ireland Standard Time, or others. The java.time classes are left to merely guessing, as there is no logical solution to this ambiguity.

java.time

The modern approach uses the java.time classes.

Define a formatting pattern to match your input strings.

String input = "Sat Jun 01 12:53:10 IST 2013";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss z uuuu" , Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );

zdt.toString(): 2013-06-01T12:53:10Z[Atlantic/Reykjavik]

If your input was not intended for Iceland, you should pre-parse the string to adjust to a proper time zone name. For example, if you are certain the input was intended for India, change IST to Asia/Kolkata.

String input = "Sat Jun 01 12:53:10 IST 2013".replace( "IST" , "Asia/Kolkata" );
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss z uuuu" , Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );

zdt.toString(): 2013-06-01T12:53:10+05:30[Asia/Kolkata]


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How can I add an element after another element?

try

.insertAfter()

here

$(content).insertAfter('#bla');

Best way to do a PHP switch with multiple values per case?

No version 2 doesn't actually work but if you want this kind of approach you can do the following (probably not the speediest, but arguably more intuitive):

switch (true) {
case ($var === 'something' || $var === 'something else'):
// do some stuff
break;
}

python selenium click on button

For python, use the

from selenium.webdriver import ActionChains

and

ActionChains(browser).click(element).perform()

What does it mean to have an index to scalar variable error? python

exponent is a 1D array. This means that exponent[0] is a scalar, and exponent[0][i] is trying to access it as if it were an array.

Did you mean to say:

L = identity(len(l))
for i in xrange(len(l)):
    L[i][i] = exponent[i]

or even

L = diag(exponent)

?

mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

Simply put, you need to rewrite all of your database connections and queries.

You are using mysql_* functions which are now deprecated and will be removed from PHP in the future. So you need to start using MySQLi or PDO instead, just as the error notice warned you.

A basic example of using PDO (without error handling):

<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$result = $db->exec("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");
$insertId = $db->lastInsertId();
?>

A basic example of using MySQLi (without error handling):

$db = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
$result = $db->query("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");

Here's a handy little PDO tutorial to get you started. There are plenty of others, and ones about the PDO alternative, MySQLi.

How can I keep a container running on Kubernetes?

Use Kubernetes Deployment and services.

Warning: Permanently added the RSA host key for IP address

From: https://github.blog/changelog/2019-04-09-webhooks-ip-changes/

April 9, 2019

Webhooks IP changes

The IP addresses we use to send webhooks from are broadening to encompass a larger range.

We are adding IP’s within 140.82.112.0/20 to the current pool from 192.30.252.0/22.

Learn more about GitHub’s IP addresses

PHP - regex to allow letters and numbers only

  • Missing end anchor $
  • Missing multiplier
  • Missing end delimiter

So it should fail anyway, but if it may work, it matches against just one digit at the beginning of the string.

/^[a-z0-9]+$/i

Mysql: Select rows from a table that are not in another

SELECT *
FROM Table1 AS a
WHERE NOT EXISTS (
  SELECT *
  FROM Table2 AS b 
  WHERE a.FirstName=b.FirstName AND a.LastName=b.Last_Name
)

EXISTS will help you...

time.sleep -- sleeps thread or process?

The thread will block, but the process is still alive.

In a single threaded application, this means everything is blocked while you sleep. In a multithreaded application, only the thread you explicitly 'sleep' will block and the other threads still run within the process.

Minimum Hardware requirements for Android development

I did the following experiment at home:

let's compare how 2 computers compile the same android application in eclipse. Here are the competitors:

"the monster" - pentinum i7 - 16 gig RAM - solid state hard drive

"peabody" - pentinum i3 - 4 gig RAM

The results: when I compiled the same application in eclipse, the monster and peabody took exactly the same amount of time to bring up the emulator to the point where you have to slide the button to run the app: 1 minute 12 seconds.

After that point, the monster executed the app 30-40 seconds faster than peabody.

The monster costs about $500 more than the peabody. So the question is, is it really worth it? In my opinion, No. I can wait the extra 30-40 seconds

Javascript: How to generate formatted easy-to-read JSON straight from an object?

JSON.stringify takes more optional arguments.

Try:

 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab

From:

How can I beautify JSON programmatically?

Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre> tag to get newlines to show.

How do I correctly upgrade angular 2 (npm) to the latest version?

Official npm page suggest a structured method to update angular version for both global and local scenarios.

1.First of all, you need to uninstall the current angular from your system.

npm uninstall -g angular-cli
npm uninstall --save-dev angular-cli
npm uninstall -g @angular/cli

2.Clean up the cache

npm cache clean

EDIT

As pointed out by @candidj

npm cache clean is renamed as npm cache verify from npm 5 onwards

3.Install angular globally

npm install -g @angular/cli@latest

4.Local project setup if you have one

rm -rf node_modules
npm install --save-dev @angular/cli@latest
npm install

Please check the same down on the link below:

https://www.npmjs.com/package/@angular/cli#updating-angular-cli

This will solve the problem.

How can I set a custom date time format in Oracle SQL Developer?

I stumbled on this post while trying to change the display format for dates in sql-developer. Just wanted to add to this what I found out:

  • To Change the default display format, I would use the steps provided by ousoo i.e Tools > Preferences > ...
  • But a lot of times, I just want to retain the DEFAULT_FORMAT while modifying the format only during a bunch of related queries. That's when I would change the format of the session with the following:

    alter SESSION set NLS_DATE_FORMAT = 'my_required_date_format'

Eg:

   alter SESSION set NLS_DATE_FORMAT = 'DD-MM-YYYY HH24:MI:SS' 

Print to standard printer from Python?

To print to any printer on the network you can send a PJL/PCL print job directly to a network printer on port 9100.

Please have a look at the below link that should give a good start:

http://frank.zinepal.com/printing-directly-to-a-network-printer

Also, If there is a way to call Windows cmd you can use FTP put to print your page on 9100. Below link should give you details, I have used this method for HP printers but I believe it will work for other printers.

http://h20000.www2.hp.com/bizsupport/TechSupport/Document.jsp?objectID=bpj06165

Importing Excel into a DataTable Quickly

In case anyone else is using EPPlus. This implementation is pretty naive, but there are comments that draw attention to such. If you were to layer one more method GetWorkbookAsDataSet() on top it would do what the OP is asking for.

    /// <summary>
    /// Assumption: Worksheet is in table format with no weird padding or blank column headers.
    /// 
    /// Assertion: Duplicate column names will be aliased by appending a sequence number (eg. Column, Column1, Column2)
    /// </summary>
    /// <param name="worksheet"></param>
    /// <returns></returns>
    public static DataTable GetWorksheetAsDataTable(ExcelWorksheet worksheet)
    {
        var dt = new DataTable(worksheet.Name);
        dt.Columns.AddRange(GetDataColumns(worksheet).ToArray());
        var headerOffset = 1; //have to skip header row
        var width = dt.Columns.Count;
        var depth = GetTableDepth(worksheet, headerOffset);
        for (var i = 1; i <= depth; i++)
        {
            var row = dt.NewRow();
            for (var j = 1; j <= width; j++)
            {
                var currentValue = worksheet.Cells[i + headerOffset, j].Value;

                //have to decrement b/c excel is 1 based and datatable is 0 based.
                row[j - 1] = currentValue == null ? null : currentValue.ToString();
            }

            dt.Rows.Add(row);
        }

        return dt;
    }

    /// <summary>
    /// Assumption: There are no null or empty cells in the first column
    /// </summary>
    /// <param name="worksheet"></param>
    /// <returns></returns>
    private static int GetTableDepth(ExcelWorksheet worksheet, int headerOffset)
    {
        var i = 1;
        var j = 1;
        var cellValue = worksheet.Cells[i + headerOffset, j].Value;
        while (cellValue != null)
        {
            i++;
            cellValue = worksheet.Cells[i + headerOffset, j].Value;
        }

        return i - 1; //subtract one because we're going from rownumber (1 based) to depth (0 based)
    }

    private static IEnumerable<DataColumn> GetDataColumns(ExcelWorksheet worksheet)
    {
        return GatherColumnNames(worksheet).Select(x => new DataColumn(x));
    }

    private static IEnumerable<string> GatherColumnNames(ExcelWorksheet worksheet)
    {
        var columns = new List<string>();

        var i = 1;
        var j = 1;
        var columnName = worksheet.Cells[i, j].Value;
        while (columnName != null)
        {
            columns.Add(GetUniqueColumnName(columns, columnName.ToString()));
            j++;
            columnName = worksheet.Cells[i, j].Value;
        }

        return columns;
    }

    private static string GetUniqueColumnName(IEnumerable<string> columnNames, string columnName)
    {
        var colName = columnName;
        var i = 1;
        while (columnNames.Contains(colName))
        {
            colName = columnName + i.ToString();
            i++;
        }

        return colName;
    }

Is it a good idea to index datetime field in mysql?

MySQL recommends using indexes for a variety of reasons including elimination of rows between conditions: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html

This makes your datetime column an excellent candidate for an index if you are going to be using it in conditions frequently in queries. If your only condition is BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY) and you have no other index in the condition, MySQL will have to do a full table scan on every query. I'm not sure how many rows are generated in 30 days, but as long as it's less than about 1/3 of the total rows it will be more efficient to use an index on the column.

Your question about creating an efficient database is very broad. I'd say to just make sure that it's normalized and all appropriate columns are indexed (i.e. ones used in joins and where clauses).

Child element click event trigger the parent click event

Without jQuery : DEMO

 <div id="parentDiv" onclick="alert('parentDiv');">
   <div id="childDiv" onclick="alert('childDiv');event.cancelBubble=true;">
     AAA
   </div>   
</div>

Copy all files with a certain extension from all subdirectories

--parents is copying the directory structure, so you should get rid of that.

The way you've written this, the find executes, and the output is put onto the command line such that cp can't distinguish between the spaces separating the filenames, and the spaces within the filename. It's better to do something like

$ find . -name \*.xls -exec cp {} newDir \;

in which cp is executed for each filename that find finds, and passed the filename correctly. Here's more info on this technique.

Instead of all the above, you could use zsh and simply type

$ cp **/*.xls target_directory

zsh can expand wildcards to include subdirectories and makes this sort of thing very easy.

How to set Google Chrome in WebDriver

public void setUp() throws Exception {

 System.setProperty("webdriver.chrome.driver","Absolute path of Chrome driver");

 driver =new ChromeDriver();
 baseUrl = "URL/";

    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
  }

How to pass a value from one jsp to another jsp page?

Use sessions

On your search.jsp

Put your scard in sessions using session.setAttribute("scard","scard")

//the 1st variable is the string name that you will retrieve in ur next page,and the 2nd variable is the its value,i.e the scard value.

And in your next page you retrieve it using session.getAttribute("scard")

UPDATE

<input type="text" value="<%=session.getAttribute("scard")%>"/>

How to include js and CSS in JSP with spring MVC

If you using java-based annotation you can do this:

 @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("/static/");
    }

Where static folder

src  
¦
+---main
    +---java
    +---resources
    +---webapp
        +---static
            +---css
            +---....


Java Array, Finding Duplicates

Initialize k = j+1. You won't compare elements to themselves and you'll also not duplicate comparisons. For example, j = 0, k = 1 and k = 0, j = 1 compare the same set of elements. This would remove the k = 0, j = 1 comparison.

Difference between partition key, composite key and clustering key in Cassandra?

In cassandra , the difference between primary key,partition key,composite key, clustering key always makes some confusion.. So I am going to explain below and co relate to each others. We use CQL (Cassandra Query Language) for Cassandra database access. Note:- Answer is as per updated version of Cassandra. Primary Key :-

In cassandra there are 2 different way to use primary Key .

CREATE TABLE Cass (
    id int PRIMARY KEY,
    name text 
);

Create Table Cass (
   id int,
   name text,
   PRIMARY KEY(id) 
);

In CQL, the order in which columns are defined for the PRIMARY KEY matters. The first column of the key is called the partition key having property that all the rows sharing the same partition key (even across table in fact) are stored on the same physical node. Also, insertion/update/deletion on rows sharing the same partition key for a given table are performed atomically and in isolation. Note that it is possible to have a composite partition key, i.e. a partition key formed of multiple columns, using an extra set of parentheses to define which columns forms the partition key.

Partitioning and Clustering The PRIMARY KEY definition is made up of two parts: the Partition Key and the Clustering Columns. The first part maps to the storage engine row key, while the second is used to group columns in a row.

CREATE TABLE device_check (
  device_id   int,
  checked_at  timestamp,
  is_power    boolean,
  is_locked   boolean,
  PRIMARY KEY (device_id, checked_at)
);

Here device_id is partition key and checked_at is cluster_key.

We can have multiple cluster key as well as partition key too which depends on declaration.

How to test android apps in a real device with Android Studio?

  • First we have to enable the USB debugging mode. for that go to Settings -> Developer Options ->USB debugging in your phone checked it and allow it.
  • After it open android studio, click on SDK manager , check mark the Google USB Driver and hit install package.
  • After Installing Google USB Driver, close SDK Manager window, Connect your phone or tablet through USB cable to your laptop or PC.
  • Now click on My Computer (Windows 7) (or) This PC(Windows 8.1).Select Manage.
  • Select Device Manager –> Portable Devices –> Your Device Name
  • Right Click on Your Device Name and Select Browse My Computer For Driver Software.
  • Point it to C:\Users\YourUserName\AppData\Local\Android\sdk\extras\google\usb_driver. Hit Next and Finish.
  • Now Hit Run Button after selecting Your Project in Project Explorer in Android studio. Choose your device and press OK.

Have a fixed position div that needs to scroll if content overflows

Leaving an answer for anyone looking to do something similar but in a horizontal direction, like I wanted to.

Tweaking @strider820's answer like below will do the magic:

.fixed-content {        //comments showing what I replaced.
    left:0;             //top: 0;
    right:0;            //bottom:0;
    position:fixed;
    overflow-y:hidden;  //overflow-y:scroll;
    overflow-x:auto;    //overflow-x:hidden;
}

That's it. Also check this comment where @train explained using overflow:auto over overflow:scroll.

How to initailize byte array of 100 bytes in java with all 0's

byte [] arr = new byte[100] 

Each element has 0 by default.

You could find primitive default values here:

Data Type   Default Value
byte        0
short       0
int         0
long        0L
float       0.0f
double      0.0d
char        '\u0000'
boolean     false

How to check if keras tensorflow backend is GPU or CPU version?

Also you can check using Keras backend function:

from keras import backend as K
K.tensorflow_backend._get_available_gpus()

I test this on Keras (2.1.1)

How can I make a UITextField move up when the keyboard is present - on starting to edit?

If the text field should be at the bottom of the screen, then the most magical solution is the following override on your viewcontroller:

override var inputAccessoryView: UIView? {
    return <yourTextField>
}

SQL Inner join more than two tables

select * from Employee inner join [Order] 
On Employee.Employee_id=[Order].Employee_id
inner join Book 
On Book.Book_id=[Order].Book_id
inner join Book_Author
On Book_Author.Book_id=Book.Book_id
inner join Author
On Book_Author.Author_id=Author.Author_id;

Determine if variable is defined in Python

try:
    a # does a exist in the current namespace
except NameError:
    a = 10 # nope

OpenJDK availability for Windows OS

Only OpenJDK 7. OpenJDK6 is basically the same code base as SUN's version, that's why it redirects you to the official Oracle site.

How to return part of string before a certain character?

And note that first argument of subString is 0 based while second is one based.

Example:

String str= "0123456";
String sbstr= str.substring(0,5);

Output will be sbstr= 01234 and not sbstr = 012345

Automatically scroll down chat div

after append in JQuery,just add this line

<script>
    $("#messages").animate({ scrollTop: 20000000 }, "slow");
</script>

No line-break after a hyphen

Try using the non-breaking hyphen &#8209;. I've replaced the dash with that character in your jsfiddle, shrunk the frame down as small as it can go, and the line doesn't split there any more.

Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired

It should work if you try all of these steps:

  1. Ensure that your session is well configured, the easiest way is to make it file and make sure storage folder has chmod 755 permission then in your .env you set it like below, file session driver is the easiest way to set.

    SESSION_DRIVER=file
    SESSION_DOMAIN=
    SESSION_SECURE_COOKIE=false
    
  2. Ensure Cache folder is cleared and writable, you can do this by running below artisan command.

    php artisan cache:clear
    
  3. Ensure folder permissions are well set, they should be configured like below:

    sudo chmod -R 755 storage
    sudo chmod -R 755 vendor
    sudo chmod -R 644 bootstrap/cache
    
  4. Ensure your form has @csrf token included.

Hope this will solve your problem.

SQL Server: Error converting data type nvarchar to numeric

I was running into this error while converting from nvarchar to float.
What I had to do was to use the LEFT function on the nvarchar field.

Example: Left(Field,4)

Basically, the query will look like:

Select convert(float,left(Field,4)) from TABLE

Just ridiculous that SQL would complicate it to this extent, while with C# it's a breeze!
Hope it helps someone out there.

Disabling Minimize & Maximize On WinForm?

you can simply disable maximize inside form constructor.

 public Form1(){
     InitializeComponent();
     MaximizeBox = false;
 }

to minimize when closing.

private void Form1_FormClosing(Object sender, FormClosingEventArgs e) {
    e.Cancel = true;
    WindowState = FormWindowState.Minimized;
}

How do you use subprocess.check_output() in Python?

The right answer (using Python 2.7 and later, since check_output() was introduced then) is:

py2output = subprocess.check_output(['python','py2.py','-i', 'test.txt'])

To demonstrate, here are my two programs:

py2.py:

import sys
print sys.argv

py3.py:

import subprocess
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'])
print('py2 said:', py2output)

Running it:

$ python3 py3.py
py2 said: b"['py2.py', '-i', 'test.txt']\n"

Here's what's wrong with each of your versions:

py2output = subprocess.check_output([str('python py2.py '),'-i', 'test.txt'])

First, str('python py2.py') is exactly the same thing as 'python py2.py'—you're taking a str, and calling str to convert it to an str. This makes the code harder to read, longer, and even slower, without adding any benefit.

More seriously, python py2.py can't be a single argument, unless you're actually trying to run a program named, say, /usr/bin/python\ py2.py. Which you're not; you're trying to run, say, /usr/bin/python with first argument py2.py. So, you need to make them separate elements in the list.

Your second version fixes that, but you're missing the ' before test.txt'. This should give you a SyntaxError, probably saying EOL while scanning string literal.

Meanwhile, I'm not sure how you found documentation but couldn't find any examples with arguments. The very first example is:

>>> subprocess.check_output(["echo", "Hello World!"])
b'Hello World!\n'

That calls the "echo" command with an additional argument, "Hello World!".

Also:

-i is a positional argument for argparse, test.txt is what the -i is

I'm pretty sure -i is not a positional argument, but an optional argument. Otherwise, the second half of the sentence makes no sense.

Print commit message of a given commit in git

This will give you a very compact list of all messages for any specified time.

git log --since=1/11/2011 --until=28/11/2011 --no-merges --format=%B > CHANGELOG.TXT

Detecting Enter keypress on VB.NET

I had the same problem and I could not make this answer work on Framework 2.0 so I dug deeper.

You would have to first handle the PreviewKeyDown on the textbox so when ENTER came along you would set IsInputKey so that it could be handled by or forwarded to the keyDown event on the textbox. Like this:

Private Sub txtFiltro_PreviewKeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles txtFiltro.PreviewKeyDown
    Select Case e.KeyCode
        Case Keys.Enter
            e.IsInputKey = True
    End Select
 End Sub

and then you would handle the event keydown on the textbox. One of the answer was on the right track but missed setting the e.IsInputKey.

Private Sub txtFiltro_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtFiltro.KeyDown
    If e.KeyCode = Keys.Enter Then
        e.handled = True
        Textbox1.Focus()
    End If
End Sub

How can I get the count of line in a file in an efficient way?

BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
int lines = 0;
while (reader.readLine() != null) lines++;
reader.close();

Update: To answer the performance-question raised here, I made a measurement. First thing: 20.000 lines are too few, to get the program running for a noticeable time. I created a text-file with 5 million lines. This solution (started with java without parameters like -server or -XX-options) needed around 11 seconds on my box. The same with wc -l (UNIX command-line-tool to count lines), 11 seconds. The solution reading every single character and looking for '\n' needed 104 seconds, 9-10 times as much.

How to tell whether a point is to the right or left side of a line

Try this code which makes use of a cross product:

public bool isLeft(Point a, Point b, Point c){
     return ((b.X - a.X)*(c.Y - a.Y) - (b.Y - a.Y)*(c.X - a.X)) > 0;
}

Where a = line point 1; b = line point 2; c = point to check against.

If the formula is equal to 0, the points are colinear.

If the line is horizontal, then this returns true if the point is above the line.

How to generate an openSSL key using a passphrase from the command line?

If you don't use a passphrase, then the private key is not encrypted with any symmetric cipher - it is output completely unprotected.

You can generate a keypair, supplying the password on the command-line using an invocation like (in this case, the password is foobar):

openssl genrsa -aes128 -passout pass:foobar 3072

However, note that this passphrase could be grabbed by any other process running on the machine at the time, since command-line arguments are generally visible to all processes.

A better alternative is to write the passphrase into a temporary file that is protected with file permissions, and specify that:

openssl genrsa -aes128 -passout file:passphrase.txt 3072

Or supply the passphrase on standard input:

openssl genrsa -aes128 -passout stdin 3072

You can also used a named pipe with the file: option, or a file descriptor.


To then obtain the matching public key, you need to use openssl rsa, supplying the same passphrase with the -passin parameter as was used to encrypt the private key:

openssl rsa -passin file:passphrase.txt -pubout

(This expects the encrypted private key on standard input - you can instead read it from a file using -in <file>).


Example of creating a 3072-bit private and public key pair in files, with the private key pair encrypted with password foobar:

openssl genrsa -aes128 -passout pass:foobar -out privkey.pem 3072
openssl rsa -in privkey.pem -passin pass:foobar -pubout -out privkey.pub

Intellij IDEA Java classes not auto compiling on save

The only thing that worked for me in my maven project that was affected by this is to add a "test-compile" goal to the run configuration of my unit tests. Incredibly clumsy solution, but it works.

enter image description here

Counting the number of True Booleans in a Python List

True is equal to 1.

>>> sum([True, True, False, False, False, True])
3

Difference between / and /* in servlet mapping url pattern

I think Candy's answer is mostly correct. There is one small part I think otherwise.

To map host:port/context/hello.jsp

  1. No exact URL servlets installed, next.
  2. Found wildcard paths servlets, return.

I believe that why "/*" does not match host:port/context/hello because it treats "/hello" as a path instead of a file (since it does not have an extension).

Unknown URL content://downloads/my_downloads

I have encountered the exception java.lang.IllegalArgumentException: Unknown URI: content://downloads/public_downloads/7505 in getting the doucument from the downloads. This solution worked for me.

else if (isDownloadsDocument(uri)) {
            String fileName = getFilePath(context, uri);
            if (fileName != null) {
                return Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName;
            }

            String id = DocumentsContract.getDocumentId(uri);
            if (id.startsWith("raw:")) {
                id = id.replaceFirst("raw:", "");
                File file = new File(id);
                if (file.exists())
                    return id;
            }

            final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
            return getDataColumn(context, contentUri, null, null);
        }

This the method used to get the filepath

   public static String getFilePath(Context context, Uri uri) {

    Cursor cursor = null;
    final String[] projection = {
            MediaStore.MediaColumns.DISPLAY_NAME
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, null, null,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME);
            return cursor.getString(index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}

How to change target build on Android project?

The file default.properties is by default read only, changing that worked for me.

Converting string to numeric

I suspect you are having a problem with factors. For example,

> x = factor(4:8)
> x
[1] 4 5 6 7 8
Levels: 4 5 6 7 8
> as.numeric(x)
[1] 1 2 3 4 5
> as.numeric(as.character(x))
[1] 4 5 6 7 8

Some comments:

  • You mention that your vector contains the characters "Down" and "NoData". What do expect/want as.numeric to do with these values?
  • In read.csv, try using the argument stringsAsFactors=FALSE
  • Are you sure it's sep="/t and not sep="\t"
  • Use the command head(pitchman) to check the first fews rows of your data
  • Also, it's very tricky to guess what your problem is when you don't provide data. A minimal working example is always preferable. For example, I can't run the command pichman <- read.csv(file="picman.txt", header=TRUE, sep="/t") since I don't have access to the data set.

MySQL Calculate Percentage

try this

   SELECT group_name, employees, surveys, COUNT( surveys ) AS test1, 
        concat(round(( surveys/employees * 100 ),2),'%') AS percentage
    FROM a_test
    GROUP BY employees

DEMO HERE

jQuery Find and List all LI elements within a UL within a specific DIV

html

<ul class="answerList" id="oneAnswer">
    <li class="answer" value="false">info1</li>
    <li class="answer" value="false">info2</li>
    <li class="answer" value="false">info3</li>
</ul>   

Get index,text,value js

    $('#oneAnswer li').each(function (i) {

        var index = $(this).index();
        var text = $(this).text();
        var value = $(this).attr('value');
        alert('Index is: ' + index + ' and text is ' + text + ' and Value ' + value);
    });

How to print the data in byte array as characters?

Well if you're happy printing it in decimal, you could just make it positive by masking:

int positive = bytes[i] & 0xff;

If you're printing out a hash though, it would be more conventional to use hex. There are plenty of other questions on Stack Overflow addressing converting binary data to a hex string in Java.

typeof !== "undefined" vs. != null

_x000D_
_x000D_
function greet(name, greeting) {_x000D_
  name = (typeof name !== 'undefined') ?  name : 'Student';_x000D_
  greeting = (typeof greeting !== 'undefined') ?  greeting : 'Welcome';_x000D_
_x000D_
  console.log(greeting,name);_x000D_
}_x000D_
_x000D_
greet(); // Welcome Student!_x000D_
greet('James'); // Welcome James!_x000D_
greet('Richard', 'Howdy'); // Howdy Richard!_x000D_
_x000D_
//ES6 provides new ways of introducing default function parameters this way:_x000D_
_x000D_
function greet2(name = 'Student', greeting = 'Welcome') {_x000D_
//  return '${greeting} ${name}!';_x000D_
console.log(greeting,name);_x000D_
}_x000D_
_x000D_
greet2(); // Welcome Student!_x000D_
greet2('James'); // Welcome James!_x000D_
greet2('Richard', 'Howdy'); // Howdy Richard!
_x000D_
_x000D_
_x000D_

Google Maps API v3 marker with label

I can't guarantee it's the simplest, but I like MarkerWithLabel. As shown in the basic example, CSS styles define the label's appearance and options in the JavaScript define the content and placement.

 .labels {
   color: red;
   background-color: white;
   font-family: "Lucida Grande", "Arial", sans-serif;
   font-size: 10px;
   font-weight: bold;
   text-align: center;
   width: 60px;     
   border: 2px solid black;
   white-space: nowrap;
 }

JavaScript:

 var marker = new MarkerWithLabel({
   position: homeLatLng,
   draggable: true,
   map: map,
   labelContent: "$425K",
   labelAnchor: new google.maps.Point(22, 0),
   labelClass: "labels", // the CSS class for the label
   labelStyle: {opacity: 0.75}
 });

The only part that may be confusing is the labelAnchor. By default, the label's top left corner will line up to the marker pushpin's endpoint. Setting the labelAnchor's x-value to half the width defined in the CSS width property will center the label. You can make the label float above the marker pushpin with an anchor point like new google.maps.Point(22, 50).

In case access to the links above are blocked, I copied and pasted the packed source of MarkerWithLabel into this JSFiddle demo. I hope JSFiddle is allowed in China :|

Can I set an unlimited length for maxJsonLength in web.config?

I suggest setting it to Int32.MaxValue.

JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;

How to make Sonar ignore some classes for codeCoverage metric?

I think you 're looking for the solution described in this answer Exclude methods from code coverage with Cobertura Keep in mind that if you're using Sonar 3.2 you have specify that your coverage tool is cobertura and not jacoco ( default ), which doesn't support this kind of feature yet

Configure Log4Net in web application

You need to call the Configurefunction of the XmlConfigurator

log4net.Config.XmlConfigurator.Configure();

Either call before your first loggin call or in your Global.asax like this:

protected void Application_Start(Object sender, EventArgs e) {
   log4net.Config.XmlConfigurator.Configure();
}

Getting the count of unique values in a column in bash

Perl

This code computes the occurrences of all columns, and prints a sorted report for each of them:

# columnvalues.pl
while (<>) {
    @Fields = split /\s+/;
    for $i ( 0 .. $#Fields ) {
        $result[$i]{$Fields[$i]}++
    };
}
for $j ( 0 .. $#result ) {
    print "column $j:\n";
    @values = keys %{$result[$j]};
    @sorted = sort { $result[$j]{$b} <=> $result[$j]{$a}  ||  $a cmp $b } @values;
    for $k ( @sorted ) {
        print " $k $result[$j]{$k}\n"
    }
}

Save the text as columnvalues.pl
Run it as: perl columnvalues.pl files*

Explanation

In the top-level while loop:
* Loop over each line of the combined input files
* Split the line into the @Fields array
* For every column, increment the result array-of-hashes data structure

In the top-level for loop:
* Loop over the result array
* Print the column number
* Get the values used in that column
* Sort the values by the number of occurrences
* Secondary sort based on the value (for example b vs g vs m vs z)
* Iterate through the result hash, using the sorted list
* Print the value and number of each occurrence

Results based on the sample input files provided by @Dennis

column 0:
 a 3
 z 3
 t 1
 v 1
 w 1
column 1:
 d 3
 r 2
 b 1
 g 1
 m 1
 z 1
column 2:
 c 4
 a 3
 e 2

.csv input

If your input files are .csv, change /\s+/ to /,/

Obfuscation

In an ugly contest, Perl is particularly well equipped.
This one-liner does the same:

perl -lane 'for $i (0..$#F){$g[$i]{$F[$i]}++};END{for $j (0..$#g){print "$j:";for $k (sort{$g[$j]{$b}<=>$g[$j]{$a}||$a cmp $b} keys %{$g[$j]}){print " $k $g[$j]{$k}"}}}' files*

Spring Boot - Loading Initial Data

I solved similar problem this way:

@Component
public class DataLoader {

    @Autowired
    private UserRepository userRepository;

    //method invoked during the startup
    @PostConstruct
    public void loadData() {
        userRepository.save(new User("user"));
    }

    //method invoked during the shutdown
    @PreDestroy
    public void removeData() {
        userRepository.deleteAll();
    }
}

Maintaining the final state at end of a CSS3 animation

Use animation-fill-mode: forwards;

animation-fill-mode: forwards;

The element will retain the style values that is set by the last keyframe (depends on animation-direction and animation-iteration-count).

Note: The @keyframes rule is not supported in Internet Explorer 9 and earlier versions.

Working example

_x000D_
_x000D_
div {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: red;_x000D_
  position :relative;_x000D_
  -webkit-animation: mymove 3ss forwards; /* Safari 4.0 - 8.0 */_x000D_
  animation: bubble 3s forwards;_x000D_
  /* animation-name: bubble; _x000D_
  animation-duration: 3s;_x000D_
  animation-fill-mode: forwards; */_x000D_
}_x000D_
_x000D_
/* Safari */_x000D_
@-webkit-keyframes bubble  {_x000D_
  0%   { transform:scale(0.5); opacity:0.0; left:0}_x000D_
    50%  { transform:scale(1.2); opacity:0.5; left:100px}_x000D_
    100% { transform:scale(1.0); opacity:1.0; left:200px}_x000D_
}_x000D_
_x000D_
/* Standard syntax */_x000D_
@keyframes bubble  {_x000D_
   0%   { transform:scale(0.5); opacity:0.0; left:0}_x000D_
    50%  { transform:scale(1.2); opacity:0.5; left:100px}_x000D_
    100% { transform:scale(1.0); opacity:1.0; left:200px}_x000D_
}
_x000D_
<h1>The keyframes </h1>_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

How to directly execute SQL query in C#?

To execute your command directly from within C#, you would use the SqlCommand class.

Quick sample code using paramaterized SQL (to avoid injection attacks) might look like this:

string queryString = "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday  FROM  [dbo].[TPatientRaw] WHERE tPatSName = @tPatSName";
string connectionString = "Server=.\PDATA_SQLEXPRESS;Database=;User Id=sa;Password=2BeChanged!;";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand(queryString, connection);
    command.Parameters.AddWithValue("@tPatSName", "Your-Parm-Value");
    connection.Open();
    SqlDataReader reader = command.ExecuteReader();
    try
    {
        while (reader.Read())
        {
            Console.WriteLine(String.Format("{0}, {1}",
            reader["tPatCulIntPatIDPk"], reader["tPatSFirstname"]));// etc
        }
    }
    finally
    {
        // Always call Close when done reading.
        reader.Close();
    }
}

Remove a git commit which has not been pushed

This is what I do:

First checkout your branch (for my case master branch):

git checkout master

Then reset to remote HEAD^ (it'll remove all your local changes), force clean and pull:

git reset HEAD^ --hard && git clean -df && git pull

Rebuild or regenerate 'ic_launcher.png' from images in Android Studio

In Android studio 0.8 and after Right click on app folder then New > Image Asset

Browse for best resolution image you have in "Image file" field

hit Next The rest will be generated

input file appears to be a text format dump. Please use psql

If you have a full DB dump:

PGPASSWORD="your_pass" psql -h "your_host" -U "your_user" -d "your_database" -f backup.sql

If you have schemas kept separately, however, that won't work. Then you'll need to disable triggers for data insertion, akin to pg_restore --disable-triggers. You can then use this:

cat database_data_only.gzip | gunzip | PGPASSWORD="your_pass" psql -h "your_host" -U root "your_database" -c 'SET session_replication_role = replica;' -f /dev/stdin

On a side note, it is a very unfortunate downside of postgres, I think. The default way of creating a dump in pg_dump is incompatible with pg_restore. With some additional keys, however, it is. WTF?

Remove element of a regular array

This is a way to delete an array element, as of .Net 3.5, without copying to another array - using the same array instance with Array.Resize<T>:

public static void RemoveAt<T>(ref T[] arr, int index)
{
    for (int a = index; a < arr.Length - 1; a++)
    {
        // moving elements downwards, to fill the gap at [index]
        arr[a] = arr[a + 1];
    }
    // finally, let's decrement Array's size by one
    Array.Resize(ref arr, arr.Length - 1);
}

In Python, how do you convert a `datetime` object to seconds?

from the python docs:

timedelta.total_seconds()

Return the total number of seconds contained in the duration. Equivalent to

(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6

computed with true division enabled.

Note that for very large time intervals (greater than 270 years on most platforms) this method will lose microsecond accuracy.

This functionality is new in version 2.7.

Android Text over image

That is how I did it and it worked exactly as you asked for inside a RelativeLayout:

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relativelayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ImageView
        android:id="@+id/myImageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/myImageSouce" />

    <TextView
        android:id="@+id/myImageViewText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/myImageView"
        android:layout_alignTop="@id/myImageView"
        android:layout_alignRight="@id/myImageView"
        android:layout_alignBottom="@id/myImageView"
        android:layout_margin="1dp"
        android:gravity="center"
        android:text="Hello"
        android:textColor="#000000" />

</RelativeLayout>

Change package name for Android in React Native

I've renamed the project' subfolder from: "android/app/src/main/java/MY/APP/OLD_ID/" to: "android/app/src/main/java/MY/APP/NEW_ID/"

Then manually switched the old and new package ids:

In: android/app/src/main/java/MY/APP/NEW_ID/MainActivity.java:

package MY.APP.NEW_ID;

In android/app/src/main/java/MY/APP/NEW_ID/MainApplication.java:

package MY.APP.NEW_ID;

In android/app/src/main/AndroidManifest.xml:

package="MY.APP.NEW_ID"

And in android/app/build.gradle:

applicationId "MY.APP.NEW_ID"

In android/app/BUCK:

android_build_config(
  package="MY.APP.NEW_ID"
)
android_resource(
  package="MY.APP.NEW_ID"
)

Gradle' cleaning in the end (in /android folder):

./gradlew clean

Google Chrome redirecting localhost to https

I never figured out the root of the problem however I was able to fix this problem. I deleted the Google Chrome app cache folder which solved the problem.

C:\Users[users]\AppData\Local\Google\Chrome

How do I change the title of the "back" button on a Navigation Bar

It seems that the navigation controller looks for

previousViewController.navigationItem.title

If nothing there it looks for

previousViewController.title

ng-repeat :filter by single field

You can filter by an object with a property matching the objects you have to filter on it:

app.controller('FooCtrl', function($scope) {
   $scope.products = [
       { id: 1, name: 'test', color: 'red' },
       { id: 2, name: 'bob', color: 'blue' }
       /*... etc... */
   ];
});
<div ng-repeat="product in products | filter: { color: 'red' }"> 

This can of course be passed in by variable, as Mark Rajcok suggested.

Python - Move and overwrite files and folders

Since none of the above worked for me, so I wrote my own recursive function. Call Function copyTree(dir1, dir2) to merge directories. Run on multi-platforms Linux and Windows.

def forceMergeFlatDir(srcDir, dstDir):
    if not os.path.exists(dstDir):
        os.makedirs(dstDir)
    for item in os.listdir(srcDir):
        srcFile = os.path.join(srcDir, item)
        dstFile = os.path.join(dstDir, item)
        forceCopyFile(srcFile, dstFile)

def forceCopyFile (sfile, dfile):
    if os.path.isfile(sfile):
        shutil.copy2(sfile, dfile)

def isAFlatDir(sDir):
    for item in os.listdir(sDir):
        sItem = os.path.join(sDir, item)
        if os.path.isdir(sItem):
            return False
    return True


def copyTree(src, dst):
    for item in os.listdir(src):
        s = os.path.join(src, item)
        d = os.path.join(dst, item)
        if os.path.isfile(s):
            if not os.path.exists(dst):
                os.makedirs(dst)
            forceCopyFile(s,d)
        if os.path.isdir(s):
            isRecursive = not isAFlatDir(s)
            if isRecursive:
                copyTree(s, d)
            else:
                forceMergeFlatDir(s, d)

What are WSDL, SOAP and REST?

Some clear explanations (for SOAP and WSDL) can be found here as well.

Difference between a SOAP message and a WSDL?

What is the iPad user agent?

(almost 10 years later...)

From iOS 13 the iPad's user agent has changed to Mac OS, for example:

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Safari/605.1.15

How can I write variables inside the tasks file in ansible

Variable definitions are meant to be used in tasks. But if you want to include them in tasks probably use the register directive. Like this:

- name: Define variable in task.
  shell: echo "http://www.my.url.com"
  register: url

- name: Download apache
  shell: wget {{ item }}
  with_items: url.stdout

You can also look at roles as a way of separating tasks depending on the different roles roles. This way you can have separate variables for each of one of your roles. For example you may have a url variable for apache1 and a separate url variable for the role apache2.

Storyboard - refer to ViewController in AppDelegate

If you use XCode 5 you should do it in a different way.

  • Select your UIViewController in UIStoryboard
  • Go to the Identity Inspector on the right top pane
  • Check the Use Storyboard ID checkbox
  • Write a unique id to the Storyboard ID field

Then write your code.

// Override point for customization after application launch.

if (<your implementation>) {
    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" 
                                                             bundle: nil];
    YourViewController *yourController = (YourViewController *)[mainStoryboard 
      instantiateViewControllerWithIdentifier:@"YourViewControllerID"];
    self.window.rootViewController = yourController;
}

return YES;

Read file from line 2 or skip header row

f = open(fname,'r')
lines = f.readlines()[1:]
f.close()

How to convert integer into date object python?

import datetime

timestamp = datetime.datetime.fromtimestamp(1500000000)

print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))

This will give the output:

2017-07-14 08:10:00

adding text to an existing text element in javascript via DOM

Instead of appending element you can just do.

 document.getElementById("p").textContent += " this has just been added";

_x000D_
_x000D_
document.getElementById("p").textContent += " this has just been added";
_x000D_
<p id ="p">This is some text</p>
_x000D_
_x000D_
_x000D_

How to change the default charset of a MySQL table?

The ALTER TABLE MySQL command should do the trick. The following command will change the default character set of your table and the character set of all its columns to UTF8.

ALTER TABLE etape_prospection CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;

This command will convert all text-like columns in the table to the new character set. Character sets use different amounts of data per character, so MySQL will convert the type of some columns to ensure there's enough room to fit the same number of characters as the old column type.

I recommend you read the ALTER TABLE MySQL documentation before modifying any live data.

How to get all subsets of a set? (powerset)

With empty set, which is part of all the subsets, you could use:

def subsets(iterable):
    for n in range(len(iterable) + 1):
        yield from combinations(iterable, n)

How to use regex in String.contains() method in Java

You can simply use matches method of String class.

boolean result = someString.matches("stores.*store.*product.*");

Remove element by id

You can directly remove that element by using remove() method of DOM.

here's an example:

let subsWrapper = document.getElementById("element_id");
subsWrapper.remove();
//OR directly.
document.getElementById("element_id").remove();

How to configure XAMPP to send mail from localhost?

You have to configure SMTP on your server. You can use G Suite SMTP by Google for free:

<?php

$mail = new PHPMailer(true);

// Send mail using Gmail
if($send_using_gmail){
    $mail->IsSMTP(); // telling the class to use SMTP
    $mail->SMTPAuth = true; // enable SMTP authentication
    $mail->SMTPSecure = "ssl"; // sets the prefix to the servier
    $mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
    $mail->Port = 465; // set the SMTP port for the GMAIL server
    $mail->Username = "[email protected]"; // GMAIL username
    $mail->Password = "your-gmail-password"; // GMAIL password
}

// Typical mail data
$mail->AddAddress($email, $name);
$mail->SetFrom($email_from, $name_from);
$mail->Subject = "My Subject";
$mail->Body = "Mail contents";

try{
    $mail->Send();
    echo "Success!";
} catch(Exception $e){
    // Something went bad
    echo "Fail :(";
}

?>

Read more about PHPMailer here.

How do I remove the blue styling of telephone numbers on iPhone/iOS?

If you don't intend to have any telephone numbers on your page, then <meta name="format-detection" content="telephone=no"> will work just fine. But rhetorically speaking, what if you intend to use a mix of phone and non-phone numbers?

Assuming you're just hard-coding numbers into your HTML, the "insert stuff in the middle of your digits" hacks will work. But they are of little to no use for dynamic pages, such as using PHP to output numerical data from a query.

As an example, I was generating a list of city populations. Some of the populations were large enough to cause Mobile Safari to turn them into phone number links. Fortunately, all I had to do was use PHP number_format() around the array output to insert "thousands" commas:

<?php echo number_format($row["population"]) ?>

This formatting was enough to convince Mobile Safari that there was a somewhat more specific purpose for the number, so it didn't default my larger numbers into telephone links anymore. The same would hold true for the suggestion by @davidcondrey of using <a href="tel:18001234567">1-800-123-4567</a> to specify a purpose to the number.

Bottom line is that Safari Mobile apparently does pay attention to semantics. Given that HTML5 is built around semantic markup, and search engines are relying on semantic markup, I intend to use it as much as I can.

jQuery won't parse my JSON from AJAX query

In a ColdFusion environment, one thing that will cause an error, even with well-formed JSON, is having Enable Request Debugging Output turned on in the ColdFusion Administrator (under Debugging & Logging > Debug Output Settings). Debugging information will be returned with the JSON data and will thus make it invalid.

How can I generate Javadoc comments in Eclipse?

JAutoDoc:

an Eclipse Plugin for automatically adding Javadoc and file headers to your source code. It optionally generates initial comments from element name by using Velocity templates for Javadoc and file headers...

Get Multiple Values in SQL Server Cursor

Do not use @@fetch_status - this will return status from the last cursor in the current connection. Use the example below:

declare @sqCur cursor;
declare @data varchar(1000);
declare @i int = 0, @lastNum int, @rowNum int;
set @sqCur = cursor local static read_only for 
    select
         row_number() over (order by(select null)) as RowNum
        ,Data -- you fields
    from YourIntTable
open @cur
begin try
    fetch last from @cur into @lastNum, @data
    fetch absolute 1 from @cur into @rowNum, @data --start from the beginning and get first value 
    while @i < @lastNum
    begin
        set @i += 1

        --Do your job here
        print @data

        fetch next from @cur into @rowNum, @data
    end
end try
begin catch
    close @cur      --|
    deallocate @cur --|-remove this 3 lines if you do not throw
    ;throw          --|
end catch
close @cur
deallocate @cur

Get the Last Inserted Id Using Laravel Eloquent

You can do this:

$result=app('db')->insert("INSERT INTO table...");

$lastInsertId=app('db')->getPdo()->lastInsertId();

Uncaught TypeError: Object #<Object> has no method 'movingBoxes'

I had the same problem. I changed the order of the scripts in the head part, and it worked for me. Every script the plugin needs - needs to stay close.

For example:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cloud.github.com/downloads/malsup/cycle/jquery.cycle.all.latest.js"></script>
<script type="text/javascript"> 
$(document).ready(function() {
    $('#slider').cycle({
            fx: 'fade' 
        });
    });
</script>

How can I tell jackson to ignore a property for which I don't have control over the source code?

Using Java Class

new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

Using Annotation

@JsonIgnoreProperties(ignoreUnknown=true)

In a Bash script, how can I exit the entire script if a certain condition occurs?

I have the same question but cannot ask it because it would be a duplicate.

The accepted answer, using exit, does not work when the script is a bit more complicated. If you use a background process to check for the condition, exit only exits that process, as it runs in a sub-shell. To kill the script, you have to explicitly kill it (at least that is the only way I know).

Here is a little script on how to do it:

#!/bin/bash

boom() {
    while true; do sleep 1.2; echo boom; done
}

f() {
    echo Hello
    N=0
    while
        ((N++ <10))
    do
        sleep 1
        echo $N
        #        ((N > 5)) && exit 4 # does not work
        ((N > 5)) && { kill -9 $$; exit 5; } # works 
    done
}

boom &
f &

while true; do sleep 0.5; echo beep; done

This is a better answer but still incomplete a I really don't know how to get rid of the boom part.

No server in windows>preferences

In Eclipse Kepler,

  1. go to Help, select ‘Install New Software’
  2. Choose “Kepler- http://download.eclipse.org/releases/kepler” site or add it in if it’s missing.
  3. Expand “Web, XML, and Java EE Development” section Check JST Server Adapters and JST Server Adapters Extensions and install it

After Eclipse restart, go to Window / Preferences / Server / Runtime Environments

How do I "shake" an Android device within the Android emulator to bring up the dev menu to debug my React Native app

Use command + m(cmd + M) on MAC. Also make sure that you are accessing your application while you try to access the Debug Menui.e. your app must be running otherwise Cmd + M will just return the usual ordinary phone menu.

browser.msie error after update to jQuery 1.9.1

Update! Complete answer overhaul for new plugin!

The following plugin has been tested in all major browsers. It makes traditional use of userAgent string to re-equip jQuery.browser only if you're using jQuery version 1.9 or Greater!

It has the traditional jQuery.browser.msie type properties as well as a few new ones, including a .mobile property to help decide if user is on a mobile device.

Note: This is not a suitable replacement for feature testing. If you expect to support a specific feature on a specific device, it's still best to use traditional feature testing

_x000D_
_x000D_
/** jQuery.browser_x000D_
 * @author J.D. McKinstry (2014)_x000D_
 * @description Made to replicate older jQuery.browser command in jQuery versions 1.9+_x000D_
 * @see http://jsfiddle.net/SpYk3/wsqfbe4s/_x000D_
 *_x000D_
 * @extends jQuery_x000D_
 * @namespace jQuery.browser_x000D_
 * @example jQuery.browser.browser == 'browserNameInLowerCase'_x000D_
 * @example jQuery.browser.version_x000D_
 * @example jQuery.browser.mobile @returns BOOLEAN_x000D_
 * @example jQuery.browser['browserNameInLowerCase']_x000D_
 * @example jQuery.browser.chrome @returns BOOLEAN_x000D_
 * @example jQuery.browser.safari @returns BOOLEAN_x000D_
 * @example jQuery.browser.opera @returns BOOLEAN_x000D_
 * @example jQuery.browser.msie @returns BOOLEAN_x000D_
 * @example jQuery.browser.mozilla @returns BOOLEAN_x000D_
 * @example jQuery.browser.webkit @returns BOOLEAN_x000D_
 * @example jQuery.browser.ua @returns navigator.userAgent String_x000D_
 */_x000D_
;;(function($){var a=$.fn.jquery.split("."),b;for(b in a)a[b]=parseInt(a[b]);if(!$.browser&&(1<a[0]||9<=a[1])){a={browser:void 0,version:void 0,mobile:!1};navigator&&navigator.userAgent&&(a.ua=navigator.userAgent,a.webkit=/WebKit/i.test(a.ua),a.browserArray="MSIE Chrome Opera Kindle Silk BlackBerry PlayBook Android Safari Mozilla Nokia".split(" "),/Sony[^ ]*/i.test(a.ua)?a.mobile="Sony":/RIM Tablet/i.test(a.ua)?a.mobile="RIM Tablet":/BlackBerry/i.test(a.ua)?a.mobile="BlackBerry":/iPhone/i.test(a.ua)?_x000D_
a.mobile="iPhone":/iPad/i.test(a.ua)?a.mobile="iPad":/iPod/i.test(a.ua)?a.mobile="iPod":/Opera Mini/i.test(a.ua)?a.mobile="Opera Mini":/IEMobile/i.test(a.ua)?a.mobile="IEMobile":/BB[0-9]{1,}; Touch/i.test(a.ua)?a.mobile="BlackBerry":/Nokia/i.test(a.ua)?a.mobile="Nokia":/Android/i.test(a.ua)&&(a.mobile="Android"),/MSIE|Trident/i.test(a.ua)?(a.browser="MSIE",a.version=/MSIE/i.test(navigator.userAgent)&&0<parseFloat(a.ua.split("MSIE")[1].match(/[0-9\.]{1,}/)[0])?parseFloat(a.ua.split("MSIE")[1].match(/[0-9\.]{1,}/)[0]):_x000D_
"Edge",/Trident/i.test(a.ua)&&/rv:([0-9]{1,}[\.0-9]{0,})/.test(a.ua)&&(a.version=parseFloat(a.ua.match(/rv:([0-9]{1,}[\.0-9]{0,})/)[1].match(/[0-9\.]{1,}/)[0]))):/Chrome/.test(a.ua)?(a.browser="Chrome",a.version=parseFloat(a.ua.split("Chrome/")[1].split("Safari")[0].match(/[0-9\.]{1,}/)[0])):/Opera/.test(a.ua)?(a.browser="Opera",a.version=parseFloat(a.ua.split("Version/")[1].match(/[0-9\.]{1,}/)[0])):/Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI/i.test(a.ua)?(a.mobile="Kindle",_x000D_
/Silk/i.test(a.ua)?(a.browser="Silk",a.version=parseFloat(a.ua.split("Silk/")[1].split("Safari")[0].match(/[0-9\.]{1,}/)[0])):/Kindle/i.test(a.ua)&&/Version/i.test(a.ua)&&(a.browser="Kindle",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].match(/[0-9\.]{1,}/)[0]))):/BlackBerry/.test(a.ua)?(a.browser="BlackBerry",a.version=parseFloat(a.ua.split("/")[1].match(/[0-9\.]{1,}/)[0])):/PlayBook/.test(a.ua)?(a.browser="PlayBook",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].match(/[0-9\.]{1,}/)[0])):_x000D_
/BB[0-9]{1,}; Touch/.test(a.ua)?(a.browser="Blackberry",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].match(/[0-9\.]{1,}/)[0])):/Android/.test(a.ua)?(a.browser="Android",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].match(/[0-9\.]{1,}/)[0])):/Safari/.test(a.ua)?(a.browser="Safari",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].match(/[0-9\.]{1,}/)[0])):/Firefox/.test(a.ua)?(a.browser="Mozilla",a.version=parseFloat(a.ua.split("Firefox/")[1].match(/[0-9\.]{1,}/)[0])):_x000D_
/Nokia/.test(a.ua)&&(a.browser="Nokia",a.version=parseFloat(a.ua.split("Browser")[1].match(/[0-9\.]{1,}/)[0])));if(a.browser)for(var c in a.browserArray)a[a.browserArray[c].toLowerCase()]=a.browser==a.browserArray[c];$.extend(!0,$.browser={},a)}})(jQuery);_x000D_
/* - - - - - - - - - - - - - - - - - - - */_x000D_
_x000D_
var b = $.browser;_x000D_
console.log($.browser);    //    see console, working example of jQuery Plugin_x000D_
console.log($.browser.chrome);_x000D_
_x000D_
for (var x in b) {_x000D_
    if (x != 'init')_x000D_
        $('<tr />').append(_x000D_
            $('<th />', { text: x }),_x000D_
            $('<td />', { text: b[x] })_x000D_
        ).appendTo($('table'));_x000D_
}
_x000D_
table { border-collapse: collapse; }_x000D_
th, td { border: 1px solid; padding: .25em .5em; vertical-align: top; }_x000D_
th { text-align: right; }_x000D_
_x000D_
textarea { height: 500px; width: 100%; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<table></table>
_x000D_
_x000D_
_x000D_

Adding System.Web.Script reference in class library

You need to add a reference to System.Web.Extensions.dll in project for System.Web.Script.Serialization error.

Set value of hidden input with jquery

You should use val instead of value.

<script type="text/javascript" language="javascript">
$(document).ready(function () { 
    $('input[name="testing"]').val('Work!');
});
</script>

When are static variables initialized?

The order of initialization is:

  1. Static initialization blocks
  2. Instance initialization blocks
  3. Constructors

The details of the process are explained in the JVM specification document.

How can I map True/False to 1/0 in a Pandas DataFrame?

I had to map FAKE/REAL to 0/1 but couldn't find proper answer.

Please find below how to map column name 'type' which has values FAKE/REAL to 0/1
(Note: similar can be applied to any column name and values)

df.loc[df['type'] == 'FAKE', 'type'] = 0
df.loc[df['type'] == 'REAL', 'type'] = 1

413 Request Entity Too Large - File Upload Issue

I got the upload working with above changes. But when I made the changes I started getting 404 response in file upload which lead me to do further debugging and figured out its a permission issue by checking nginx error.log

Solution:

Check the current user and group ownership on /var/lib/nginx.

$ ls -ld /var/lib/nginx

drwx------. 3 nginx nginx 17 Oct 5 19:31 /var/lib/nginx

This tells that a possibly non-existent user and group named nginx owns this folder. This is preventing file uploading.

In my case, the username mentioned in "/etc/nginx/nginx.conf" was

user vagrant; 

Change the folder ownership to the user defined in nginx.conf in this case vagrant.

$ sudo chown -Rf vagrant:vagrant /var/lib/nginx

Verify that it actually changed.

$ ls -ld /var/lib/nginx
drwx------. 3 vagrant vagrant 17 Oct  5 19:31 /var/lib/nginx

Reload nginx and php-fpm for safer sade.

$ sudo service nginx reload
$ sudo service php-fpm reload

The permission denied error should now go away. Check the error.log (based on nginx.conf error_log location).

$ sudo nano /path/to/nginx/error.log

Retrieving Android API version programmatically

Very easy:

   String manufacturer = Build.MANUFACTURER;
   String model = Build.MODEL;
   int version = Build.VERSION.SDK_INT;
   String versionRelease = Build.VERSION.RELEASE;

Log.e("MyActivity", "manufacturer " + manufacturer
            + " \n model " + model
            + " \n version " + version
            + " \n versionRelease " + versionRelease
    );

Output:

E/MyActivity:   manufacturer ManufacturerX
                model SM-T310 
                version 19 
                versionRelease 4.4.2

S3 - Access-Control-Allow-Origin Header

Below is the configuration and it's fine to work for me. I hope it will help to resolve your issue on AWS S3.

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <ExposeHeader>ETag</ExposeHeader>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

CSS: borders between table columns only

I may be simplifying the issue, but does td {border-right: 1px solid red;} work for your table setup?

MongoDB: How to update multiple documents with a single command?

In the MongoDB Client, type:

db.Collection.updateMany({}, $set: {field1: 'field1', field2: 'field2'})

New in version 3.2

Params::

{}:  select all records updated

Keyword argument multi not taken

Untrack files from git temporarily

To remove all Untrack files. Try this terminal command

 git clean -fdx

Why does Java have transient fields?

A field which is declare with transient modifier it will not take part in serialized process. When an object is serialized(saved in any state), the values of its transient fields are ignored in the serial representation, while the field other than transient fields will take part in serialization process. That is the main purpose of the transient keyword.

Highest Salary in each department

with ctesal as (
 select DepartmentId , Name , Salary, ROW_Number() OVER (partition by DepartmentId 
 order by Salary desc) as RowNum
 from dbo.Employee
 )
 select DepartmentId , Name , Salary , RowNum from ctesal where RowNum  =2;

This is applicable to SQL server. ROW_Number is a inbuilt function in SQL server .It gives count starting from 1 based on partition by and order by clause. At the end, We can write where condition based on our requirements.

How to get JSON from URL in JavaScript?

You can use jQuery .getJSON() function:

$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback', function(data) {
    // JSON result in `data` variable
});

If you don't want to use jQuery you should look at this answer for pure JS solution: https://stackoverflow.com/a/2499647/1361042

Simplest way to form a union of two lists

Using LINQ's Union

Enumerable.Union(ListA,ListB);

or

ListA.Union(ListB);

How do I remove all non alphanumeric characters from a string except dash?

I´ve made a different solution, by eliminating the Control characters, which was my original problem.

It is better than putting in a list all the "special but good" chars

char[] arr = str.Where(c => !char.IsControl(c)).ToArray();    
str = new string(arr);

it´s simpler, so I think it´s better !

Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"?

Windows 10 Professional

PHP 7.3.1

I ran these commands to fix the problem on my desktop

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php composer-setup.php

What is sharding and why is it important?

Sharding does more than just horizontal partitioning. According to the wikipedia article,

Horizontal partitioning splits one or more tables by row, usually within a single instance of a schema and a database server. It may offer an advantage by reducing index size (and thus search effort) provided that there is some obvious, robust, implicit way to identify in which partition a particular row will be found, without first needing to search the index, e.g., the classic example of the 'CustomersEast' and 'CustomersWest' tables, where their zip code already indicates where they will be found.

Sharding goes beyond this: it partitions the problematic table(s) in the same way, but it does this across potentially multiple instances of the schema. The obvious advantage would be that search load for the large partitioned table can now be split across multiple servers (logical or physical), not just multiple indexes on the same logical server.

Also,

Splitting shards across multiple isolated instances requires more than simple horizontal partitioning. The hoped-for gains in efficiency would be lost, if querying the database required both instances to be queried, just to retrieve a simple dimension table. Beyond partitioning, sharding thus splits large partitionable tables across the servers, while smaller tables are replicated as complete units

How to use <DllImport> in VB.NET?

I saw in getwindowtext (user32) on pinvoke.net that you can place a MarshalAs statement to state that the StringBuffer is equivalent to LPSTR.

<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Ansi)> _
Public Function GetWindowText(hwnd As IntPtr, <MarshalAs(UnManagedType.LPStr)>lpString As System.Text.StringBuilder, cch As Integer) As Integer
End Function

How to pass macro definition from "make" command line arguments (-D) to C source code?

Call make command this way:

make CFLAGS=-Dvar=42

And be sure to use $(CFLAGS) in your compile command in the Makefile. As @jørgensen mentioned , putting the variable assignment after the make command will override the CFLAGS value already defined the Makefile.

Alternatively you could set -Dvar=42 in another variable than CFLAGS and then reuse this variable in CFLAGS to avoid completely overriding CFLAGS.

How to start jenkins on different port rather than 8080 using command prompt in Windows?

In CentOS/RedHat (assuming you installed the jenkins package)

vim /etc/sysconfig/jenkins

....
# Port Jenkins is listening on.
# Set to -1 to disable
#
JENKINS_PORT="8080"

change it to any port you want.

How to solve time out in phpmyadmin?

To increase the phpMyAdmin Session Timeout, open config.inc.php in the root phpMyAdmin directory and add this setting (anywhere).

$cfg['LoginCookieValidity'] = <your_new_timeout>;

Where is some number larger than 1800.

Note:

Always keep on mind that a short cookie lifetime is all well and good for the development server. So do not do this on your production server.

Reference

What does iterator->second mean?

The type of the elements of an std::map (which is also the type of an expression obtained by dereferencing an iterator of that map) whose key is K and value is V is std::pair<const K, V> - the key is const to prevent you from interfering with the internal sorting of map values.

std::pair<> has two members named first and second (see here), with quite an intuitive meaning. Thus, given an iterator i to a certain map, the expression:

i->first

Which is equivalent to:

(*i).first

Refers to the first (const) element of the pair object pointed to by the iterator - i.e. it refers to a key in the map. Instead, the expression:

i->second

Which is equivalent to:

(*i).second

Refers to the second element of the pair - i.e. to the corresponding value in the map.

Logging POST data from $request_body

I had a similar problem. GET requests worked and their (empty) request bodies got written to the the log file. POST requests failed with a 404. Experimenting a bit, I found that all POST requests were failing. I found a forum posting asking about POST requests and the solution there worked for me. That solution? Add a proxy_header line right before the proxy_pass line, exactly like the one in the example below.

server {
    listen       192.168.0.1:45080;
    server_name  foo.example.org;

    access_log  /path/to/log/nginx/post_bodies.log post_bodies;
    location / {
      ### add the following proxy_header line to get POSTs to work
      proxy_set_header Host $http_host;
      proxy_pass   http://10.1.2.3;
    }
}

(This is with nginx 1.2.1 for what it is worth.)

How to add title to subplots in Matplotlib?

If you want to make it shorter, you could write :

import matplolib.pyplot as plt
for i in range(4):
    plt.subplot(2,2,i+1).set_title('Subplot n°{}' .format(i+1))
plt.show()

It makes it maybe less clear but you don't need more lines or variables

Increase bootstrap dropdown menu width

Usually the desire is to match the menu width to the width of the dropdown parent. This can be achieved easily like so:

.dropdown-menu {
  width:100%;
}

Remove rows not .isin('X')

You can use numpy.logical_not to invert the boolean array returned by isin:

In [63]: s = pd.Series(np.arange(10.0))

In [64]: x = range(4, 8)

In [65]: mask = np.logical_not(s.isin(x))

In [66]: s[mask]
Out[66]: 
0    0
1    1
2    2
3    3
8    8
9    9

As given in the comment by Wes McKinney you can also use

s[~s.isin(x)]

Check if process returns 0 with batch file

This is not exactly the answer to the question, but I end up here every time I want to find out how to get my batch file to exit with and error code when a process returns an nonzero code.

So here is the answer to that:

if %ERRORLEVEL% NEQ 0 exit %ERRORLEVEL%

Concatenating string and integer in python

in python 3.6 and newer, you can format it just like this:

new_string = f'{s} {i}'
print(new_string)

or just:

print(f'{s} {i}')

using c# .net libraries to check for IMAP messages from gmail servers

I'd recommend looking at MailKit as it is probably the most robust mail library out there and it's Open Source (MIT).

One of the awesome things about MailKit is that all network APIs are cancelable (something I haven't seen available in any other IMAP library).

It's also the only library that I know of that supports threading of messages.

using System;
using System.Net;
using System.Threading;

using MailKit.Net.Imap;
using MailKit.Search;
using MailKit;
using MimeKit;

namespace TestClient {
    class Program
    {
        public static void Main (string[] args)
        {
            using (var client = new ImapClient ()) {
                using (var cancel = new CancellationTokenSource ()) {
                    client.Connect ("imap.gmail.com", 993, true, cancel.Token);

                    // If you want to disable an authentication mechanism,
                    // you can do so by removing the mechanism like this:
                    client.AuthenticationMechanisms.Remove ("XOAUTH");

                    client.Authenticate ("joey", "password", cancel.Token);

                    // The Inbox folder is always available...
                    var inbox = client.Inbox;
                    inbox.Open (FolderAccess.ReadOnly, cancel.Token);

                    Console.WriteLine ("Total messages: {0}", inbox.Count);
                    Console.WriteLine ("Recent messages: {0}", inbox.Recent);

                    // download each message based on the message index
                    for (int i = 0; i < inbox.Count; i++) {
                        var message = inbox.GetMessage (i, cancel.Token);
                        Console.WriteLine ("Subject: {0}", message.Subject);
                    }

                    // let's try searching for some messages...
                    var query = SearchQuery.DeliveredAfter (DateTime.Parse ("2013-01-12"))
                        .And (SearchQuery.SubjectContains ("MailKit"))
                        .And (SearchQuery.Seen);

                    foreach (var uid in inbox.Search (query, cancel.Token)) {
                        var message = inbox.GetMessage (uid, cancel.Token);
                        Console.WriteLine ("[match] {0}: {1}", uid, message.Subject);
                    }

                    client.Disconnect (true, cancel.Token);
                }
            }
        }
    }
}

Find records with a date field in the last 24 hours

SELECT * FROM news WHERE date > DATEADD(d,-1,GETDATE())

Why does javascript replace only first instance when using replace?

Unlike the C#/.NET class library (and most other sensible languages), when you pass a String in as the string-to-match argument to the string.replace method, it doesn't do a string replace. It converts the string to a RegExp and does a regex substitution. As Gumbo explains, a regex substitution requires the g?lobal flag, which is not on by default, to replace all matches in one go.

If you want a real string-based replace — for example because the match-string is dynamic and might contain characters that have a special meaning in regexen — the JavaScript idiom for that is:

var id= 'c_'+date.split('/').join('');

Return generated pdf using spring MVC

You were on the right track with response.getOutputStream(), but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:

@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
    // convert JSON to Employee 
    Employee emp = convertSomehow(json);

    // generate the file
    PdfUtil.showHelp(emp);

    // retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
    byte[] contents = (...);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);
    // Here you have to set the actual filename of your pdf
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
    return response;
}

Notes:

  • use meaningful names for your methods: naming a method that writes a PDF document showHelp is not a good idea
  • reading a file into a byte[]: example here
  • I'd suggest adding a random string to the temporary PDF file name inside showHelp() to avoid overwriting the file if two users send a request at the same time

How to $http Synchronous call with AngularJS

What about wrapping your call in a Promise.all() method i.e.

Promise.all([$http.get(url).then(function(result){....}, function(error){....}])

According to MDN

Promise.all waits for all fulfillments (or the first rejection)

how to rotate text left 90 degree and cell size is adjusted according to text in html

Daniel Imms answer is excellent in regards to applying your CSS rotation to an inner element. However, it is possible to accomplish the end goal in a way that does not require JavaScript and works with longer strings of text.

Typically the whole reason to have vertical text in the first table column is to fit a long line of text in a short horizontal space and to go alongside tall rows of content (as in your example) or multiple rows of content (which I'll use in this example).

enter image description here

By using the ".rotate" class on the parent TD tag, we can not only rotate the inner DIV, but we can also set a few CSS properties on the parent TD tag that will force all of the text to stay on one line and keep the width to 1.5em. Then we can use some negative margins on the inner DIV to make sure that it centers nicely.

_x000D_
_x000D_
td {_x000D_
    border: 1px black solid;_x000D_
    padding: 5px;_x000D_
}_x000D_
.rotate {_x000D_
  text-align: center;_x000D_
  white-space: nowrap;_x000D_
  vertical-align: middle;_x000D_
  width: 1.5em;_x000D_
}_x000D_
.rotate div {_x000D_
     -moz-transform: rotate(-90.0deg);  /* FF3.5+ */_x000D_
       -o-transform: rotate(-90.0deg);  /* Opera 10.5 */_x000D_
  -webkit-transform: rotate(-90.0deg);  /* Saf3.1+, Chrome */_x000D_
             filter:  progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083);  /* IE6,IE7 */_x000D_
         -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)"; /* IE8 */_x000D_
         margin-left: -10em;_x000D_
         margin-right: -10em;_x000D_
}
_x000D_
<table cellpadding="0" cellspacing="0" align="center">_x000D_
    <tr>_x000D_
        <td class='rotate' rowspan="4"><div>10 kilograms</div></td>_x000D_
        <td>B</td>_x000D_
        <td>C</td>_x000D_
        <td>D</td>_x000D_
        <td>E</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>G</td>_x000D_
        <td>H</td>_x000D_
        <td>I</td>_x000D_
        <td>J</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>L</td>_x000D_
        <td>M</td>_x000D_
        <td>N</td>_x000D_
        <td>O</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Q</td>_x000D_
        <td>R</td>_x000D_
        <td>S</td>_x000D_
        <td>T</td>_x000D_
    </tr>_x000D_
    _x000D_
    <tr>_x000D_
        <td class='rotate' rowspan="4"><div>20 kilograms</div></td>_x000D_
        <td>B</td>_x000D_
        <td>C</td>_x000D_
        <td>D</td>_x000D_
        <td>E</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>G</td>_x000D_
        <td>H</td>_x000D_
        <td>I</td>_x000D_
        <td>J</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>L</td>_x000D_
        <td>M</td>_x000D_
        <td>N</td>_x000D_
        <td>O</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Q</td>_x000D_
        <td>R</td>_x000D_
        <td>S</td>_x000D_
        <td>T</td>_x000D_
    </tr>_x000D_
    _x000D_
    <tr>_x000D_
        <td class='rotate' rowspan="4"><div>30 kilograms</div></td>_x000D_
        <td>B</td>_x000D_
        <td>C</td>_x000D_
        <td>D</td>_x000D_
        <td>E</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>G</td>_x000D_
        <td>H</td>_x000D_
        <td>I</td>_x000D_
        <td>J</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>L</td>_x000D_
        <td>M</td>_x000D_
        <td>N</td>_x000D_
        <td>O</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Q</td>_x000D_
        <td>R</td>_x000D_
        <td>S</td>_x000D_
        <td>T</td>_x000D_
    </tr>_x000D_
    _x000D_
</table>
_x000D_
_x000D_
_x000D_

One thing to keep in mind with this solution is that it does not work well if the height of the row (or spanned rows) is shorter than the vertical text in the first column. It works best if you're spanning multiple rows or you have a lot of content creating tall rows.

Have fun playing around with this on jsFiddle.

Oracle query to fetch column names

The below query worked for me in Oracle database.

select COLUMN_NAME from ALL_TAB_COLUMNS where TABLE_NAME='MyTableName';

Can two applications listen to the same port?

Just to share what @jnewton mentioned. I started an nginx and an embedded tomcat process on my mac. I can see both process runninng at 8080.

LT<XXXX>-MAC:~ b0<XXX>$ sudo netstat -anp tcp | grep LISTEN
tcp46      0      0  *.8080                 *.*                    LISTEN     
tcp4       0      0  *.8080                 *.*                    LISTEN   

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

The provided solution here is correct. However, the same error can also occur from a user error, where your endpoint request method is NOT matching the method your using when making the request.

For example, the server endpoint is defined with "RequestMethod.PUT" while you are requesting the method as POST.

Undefined function mysql_connect()

The question is tagged with ubuntu, but the solution of un-commenting the extension=mysqli.dll is specific to windows. I am confused here?!, anyways, first thing run <? php phpinfo ?> and search for mysql* under Configuration heading. If you don't see such a thing implies you have not installed or enabled php-mysql. So first install php-mysql

sudo apt get install php-mysql

This command will install php-mysql depending on the php you have already installed, so no worries about the version!!.

Then comes the unix specific solution, in the php.ini file un-comment the line

extension=msql.so

verify that msql.so is present in /usr/lib/php/<timestamp_folder>, ELSE

extension=path/to/msql.so

Then finally restart the apache and mysql services, and you should now see the mysql section under Configrations heading in phpinfo page

array of string with unknown size

Can you use a List strings and then when you are done use strings.ToArray() to get the array of strings to work with?

How do I create test and train samples from one dataframe with pandas?

How about this? df is my dataframe

total_size=len(df)

train_size=math.floor(0.66*total_size) (2/3 part of my dataset)

#training dataset
train=df.head(train_size)
#test dataset
test=df.tail(len(df) -train_size)

text-align:center won't work with form <label> tag (?)

This is because label is an inline element, and is therefore only as big as the text it contains.

The possible is to display your label as a block element like this:

#formItem label {
    display: block;
    text-align: center;
    line-height: 150%;
    font-size: .85em;
}

However, if you want to use the label on the same line with other elements, you either need to set display: inline-block; and give it an explicit width (which doesn't work on most browsers), or you need to wrap it inside a div and do the alignment in the div.

How to put an image next to each other

You don't need the div's.

HTML:

<div class="nav3" style="height:705px;">
    <a href="http://www.facebook.com/" class="icons"><img src="images/facebook.png"></a>
    <a href="https://twitter.com" class="icons"><img src="images/twitter.png"></a>
</div>

CSS:

.nav3 {
    background-color: #E9E8C7;
    height: auto;
    width: 150px;
    float: left;
    padding-left: 20px;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 12px;
    color: #333333;
    padding-top: 20px;
    padding-right: 20px;
}

.icons{
    display:inline-block;
    width: 64px; 
    height: 64px; 
   }

 a.icons:hover {
     background: #C93;
 }

See this fiddle

How to send email to multiple address using System.Net.Mail

MailMessage msg = new MailMessage();
msg.Body = ....;
msg.To.Add(...);
msg.To.Add(...);

SmtpClient smtp = new SmtpClient();
smtp.Send(msg);

To is a MailAddressCollection, so you can add how many addresses you need.

If you need a display name, try this:

MailAddress to = new MailAddress(
    String.Format("{0} <{1}>",display_name, address));

What are the "standard unambiguous date" formats for string-to-date conversion in R?

As a complement to @JoshuaUlrich answer, here is the definition of function as.Date.character:

as.Date.character
function (x, format = "", ...) 
{
    charToDate <- function(x) {
        xx <- x[1L]
        if (is.na(xx)) {
            j <- 1L
            while (is.na(xx) && (j <- j + 1L) <= length(x)) xx <- x[j]
            if (is.na(xx)) 
                f <- "%Y-%m-%d"
        }
        if (is.na(xx) || !is.na(strptime(xx, f <- "%Y-%m-%d", 
            tz = "GMT")) || !is.na(strptime(xx, f <- "%Y/%m/%d", 
            tz = "GMT"))) 
            return(strptime(x, f))
        stop("character string is not in a standard unambiguous format")
    }
    res <- if (missing(format)) 
        charToDate(x)
    else strptime(x, format, tz = "GMT")
    as.Date(res)
}
<bytecode: 0x265b0ec>
<environment: namespace:base>

So basically if both strptime(x, format="%Y-%m-%d") and strptime(x, format="%Y/%m/%d") throws an NA it is considered ambiguous and if not unambiguous.

Spring: How to inject a value to static field?

Spring uses dependency injection to populate the specific value when it finds the @Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.

    @RestController 
//or if you want to declare some specific use of the properties file then use
//@Configuration
//@PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {

    @Value("${name}")//not necessary
    private String name;//not necessary

    private static String NAME_STATIC;

    @Value("${name}")
    public void setNameStatic(String name){
        PropertyController.NAME_STATIC = name;
    }
}

Cannot execute RUN mkdir in a Dockerfile

When creating subdirectories hanging off from a non-existing parent directory(s) you must pass the -p flag to mkdir ... Please update your Dockerfile with

RUN mkdir -p ... 

I tested this and it's correct.

Can I safely delete contents of Xcode Derived data folder?

I got this error because Int was int in one file. So stupid.

How to delete duplicate lines in a file without sorting it in Unix?

An alternative way using Vim(Vi compatible):

Delete duplicate, consecutive lines from a file:

vim -esu NONE +'g/\v^(.*)\n\1$/d' +wq

Delete duplicate, nonconsecutive and nonempty lines from a file:

vim -esu NONE +'g/\v^(.+)$\_.{-}^\1$/d' +wq