Programs & Examples On #Session cache

Caches that store session data.

How do I test a website using XAMPP?

Just edit the httpd-vhost-conf scroll to the bottom and on the last example/demo for creating a virtual host, remove the hash-tags for DocumentRoot and ServerName. You may have hash-tags just before the <VirtualHost *.80> and </VirtualHost>

After DocumentRoot, just add the path to your web-docs ... and add your domain-name after ServerNmane

<VirtualHost *:80>
    ##ServerAdmin [email protected]
    DocumentRoot "C:/xampp/htdocs/www"
    ServerName example.com
    ##ErrorLog "logs/dummy-host2.example.com-error.log"
    ##CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

Be sure to create the www folder under htdocs. You do not have to name the folder www but I did just to be simple about it. Be sure to restart Apache and bang! you can now store files in the newly created directory. To test things out just create a simple index.html or index.php file and place in the www folder, then go to your browser and test it out localhost/ ... Note: if your server is serving php files over html then remember to add localhost/index.html if the html file is the one you choose to use for this test.

Something I should add, in order to still have access to the xampp homepage then you will need to create another VirtualHost. To do this just add

<VirtualHost *:80>
    ##ServerAdmin [email protected]
    DocumentRoot "C:/xampp/htdocs"
    ServerName htdocs.example.com
    ##ErrorLog "logs/dummy-host2.example.com-error.log"
    ##CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

underneath the last VirtualHost that you created. Next make the necessary changes to your host file and restart Apache. Now go to your browser and visit htdocs.example.com and your all set.

How to apply a CSS class on hover to dynamically generated submit buttons?

You have two options:

  1. Extend your .paging class definition:

    .paging:hover {
        border:1px solid #999;
        color:#000;
    }
    
  2. Use the DOM hierarchy to apply the CSS style:

    div.paginate input:hover {
        border:1px solid #999;
        color:#000;
    }
    

How can I send an HTTP POST request to a server from Excel using VBA?

I did this before using the MSXML library and then using the XMLHttpRequest object, see here.

Class file has wrong version 52.0, should be 50.0

i faced the same problem "Class file has wrong version 52.0, should be 50.0" when running java through ant... all i did was add fork="true" wherever i used the javac task and it worked...

Show a popup/message box from a Windows batch file

Here is my batch script that I put together based on the good answers here & in other posts

You can set title timeout & even sleep to schedule it for latter & \n for new line

Name it popup.bat & put it in your windows path folder to work globally on your pc

For example popup Line 1\nLine 2 will produce a 2 line popup box (type popup /? for usage)

Here is the code

<!-- : Begin CMD
@echo off
cscript //nologo "%~f0?.wsf" %*
set pop.key=[%errorlevel%]
if %pop.key% == [-1] set pop.key=TimedOut
if %pop.key% == [1]  set pop.key=Ok
if %pop.key% == [2]  set pop.key=Cancel
if %pop.key% == [3]  set pop.key=Abort
if %pop.key% == [4]  set pop.key=Retry
if %pop.key% == [5]  set pop.key=Ignore
if %pop.key% == [6]  set pop.key=Yes
if %pop.key% == [7]  set pop.key=No
if %pop.key% == [10] set pop.key=TryAgain
if %pop.key% == [11] set pop.key=Continue
if %pop.key% == [99] set pop.key=NoWait
exit /b 
-- End CMD -->

<job><script language="VBScript">
'on error resume next
q   =""""
qsq =""" """
Set objArgs = WScript.Arguments
Set objShell= WScript.CreateObject("WScript.Shell")
Popup       =   0
Title       =   "Popup"
Timeout     =   0
Mode        =   0
Message     =   ""
Sleep       =   0
button      =   0
If objArgs.Count = 0 Then 
    Usage()
ElseIf objArgs(0) = "/?" or Lcase(objArgs(0)) = "-h" or Lcase(objArgs(0)) = "--help" Then 
    Usage()
End If
noWait = Not wait() 
For Each arg in objArgs
    If (Mid(arg,1,1) = "/") and (InStr(arg,":") <> 0) Then haveSwitch   =   True
Next
If not haveSwitch Then 
    Message=joinParam("woq")
Else
    For i = 0 To objArgs.Count-1 
        If IsSwitch(objArgs(i)) Then 
            S=split(objArgs(i) , ":" , 2)
                select case Lcase(S(0))
                    case "/m","/message"
                        Message=S(1)
                    case "/tt","/title"
                        Title=S(1)
                    case "/s","/sleep"
                        If IsNumeric(S(1)) Then Sleep=S(1)*1000
                    case "/t","/time"
                        If IsNumeric(S(1)) Then Timeout=S(1)
                    case "/b","/button"
                        select case S(1)
                            case "oc", "1"
                                button=1
                            case "ari","2"
                                button=2
                            case "ync","3"
                                button=3
                            case "yn", "4"
                                button=4
                            case "rc", "5"
                                button=5
                            case "ctc","6"
                                button=6
                            case Else
                                button=0
                        end select
                    case "/i","/icon"
                        select case S(1)
                            case "s","x","stop","16"
                                Mode=16
                            case "?","q","question","32"
                                Mode=32
                            case "!","w","warning","exclamation","48"
                                Mode=48
                            case "i","information","info","64"
                                Mode=64
                            case Else 
                                Mode=0
                        end select
                end select
        End If
    Next
End If
Message = Replace(Message,"/\n", "°"  )
Message = Replace(Message,"\n",vbCrLf)
Message = Replace(Message, "°" , "\n")
If noWait Then button=0

Wscript.Sleep(sleep)
Popup   = objShell.Popup(Message, Timeout, Title, button + Mode + vbSystemModal)
Wscript.Quit Popup

Function IsSwitch(Val)
    IsSwitch        = False
    If Mid(Val,1,1) = "/" Then
        For ii = 3 To 9 
            If Mid(Val,ii,1)    = ":" Then IsSwitch = True
        Next
    End If
End Function

Function joinParam(quotes)
    ReDim ArgArr(objArgs.Count-1)
    For i = 0 To objArgs.Count-1 
        If quotes = "wq" Then 
            ArgArr(i) = q & objArgs(i) & q 
        Else
            ArgArr(i) =     objArgs(i)
        End If
    Next
    joinParam = Join(ArgArr)
End Function

Function wait()
    wait=True
    If objArgs.Named.Exists("NewProcess") Then
        wait=False
        Exit Function
    ElseIf objArgs.Named.Exists("NW") or objArgs.Named.Exists("NoWait") Then
        objShell.Exec q & WScript.FullName & qsq & WScript.ScriptFullName & q & " /NewProcess: " & joinParam("wq") 
        WScript.Quit 99
    End If
End Function

Function Usage()
    Wscript.Echo _
                     vbCrLf&"Usage:" _
                    &vbCrLf&"      popup followed by your message. Example: ""popup First line\nescaped /\n\nSecond line"" " _
                    &vbCrLf&"      To triger a new line use ""\n"" within the msg string [to escape enter ""/"" before ""\n""]" _
                    &vbCrLf&"" _
                    &vbCrLf&"Advanced user" _
                    &vbCrLf&"      If any Switch is used then you must use the /m: switch for the message " _
                    &vbCrLf&"      No space allowed between the switch & the value " _
                    &vbCrLf&"      The switches are NOT case sensitive " _
                    &vbCrLf&"" _
                    &vbCrLf&"      popup [/m:""*""] [/t:*] [/tt:*] [/s:*] [/nw] [/i:*]" _
                    &vbCrLf&"" _
                    &vbCrLf&"      Switch       | value |Description" _
                    &vbCrLf&"      -----------------------------------------------------------------------" _
                    &vbCrLf&"      /m: /message:| ""1 2"" |if the message have spaces you need to quote it " _
                    &vbCrLf&"                   |       |" _
                    &vbCrLf&"      /t: /time:   | nn    |Duration of the popup for n seconds " _
                    &vbCrLf&"                   |       |<Default> untill key pressed" _
                    &vbCrLf&"                   |       |" _
                    &vbCrLf&"      /tt: /title: | ""A B"" |if the title have spaces you need to quote it " _
                    &vbCrLf&"                   |       | <Default> Popup" _
                    &vbCrLf&"                   |       |" _
                    &vbCrLf&"      /s: /sleep:  | nn    |schedule the popup after n seconds " _
                    &vbCrLf&"                   |       |" _
                    &vbCrLf&"      /nw /NoWait  |       |Continue script without the user pressing ok - " _
                    &vbCrLf&"                   |       | botton option will be defaulted to OK button " _
                    &vbCrLf&"                   |       |" _
                    &vbCrLf&"      /i: /icon:   | ?/q   |[question mark]"  _
                    &vbCrLf&"                   | !/w   |[exclamation (warning) mark]"  _
                    &vbCrLf&"                   | i/info|[information mark]"  _
                    &vbCrLf&"                   | x/stop|[stop\error mark]" _
                    &vbCrLf&"                   | n/none|<Default>" _
                    &vbCrLf&"                   |       |" _
                    &vbCrLf&"      /b: /button: | o     |[OK button] <Default>"  _
                    &vbCrLf&"                   | oc    |[OK and Cancel buttons]"  _
                    &vbCrLf&"                   | ari   |[Abort, Retry, and Ignore buttons]"  _
                    &vbCrLf&"                   | ync   |[Yes, No, and Cancel buttons]" _
                    &vbCrLf&"                   | yn    |[Yes and No buttons]" _
                    &vbCrLf&"                   | rc    |[Retry and Cancel buttons]" _
                    &vbCrLf&"                   | ctc   |[Cancel and Try Again and Continue buttons]" _
                    &vbCrLf&"      --->         | --->  |The output will be saved in variable ""pop.key""" _
                    &vbCrLf&"" _
                    &vbCrLf&"Example:" _
                    &vbCrLf&"        popup /tt:""My MessageBox"" /t:5 /m:""Line 1\nLine 2\n/\n\nLine 4""" _
                    &vbCrLf&"" _
                    &vbCrLf&"                     v1.9 By RDR @ 2020"
    Wscript.Quit
End Function

</script></job>

How to get the timezone offset in GMT(Like GMT+7:00) from android device?

This is how Google recommends getting TimezoneOffset.

Calendar calendar = Calendar.getInstance(Locale.getDefault());
int offset = -(calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET)) / (60 * 1000)

https://developer.android.com/reference/java/util/Date#getTimezoneOffset()

How to convert a double to long without casting?

The preferred approach should be:

Double.valueOf(d).longValue()

From the Double (Java Platform SE 7) documentation:

Double.valueOf(d)

Returns a Double instance representing the specified double value. If a new Double instance is not required, this method should generally be used in preference to the constructor Double(double), as this method is likely to yield significantly better space and time performance by caching frequently requested values.

How to loop through all the files in a directory in c # .net?

string[] files = 
    Directory.GetFiles(txtPath.Text, "*ProfileHandler.cs", SearchOption.AllDirectories);

That last parameter effects exactly what you're referring to. Set it to AllDirectories for every file including in subfolders, and set it to TopDirectoryOnly if you only want to search in the directory given and not subfolders.

Refer to MDSN for details: https://msdn.microsoft.com/en-us/library/ms143316(v=vs.110).aspx

How to write a function that takes a positive integer N and returns a list of the first N natural numbers

Do I even need a for loop to create a list?

No, you can (and in general circumstances should) use the built-in function range():

>>> range(1,5)
[1, 2, 3, 4]

i.e.

def naturalNumbers(n):
    return range(1, n + 1)

Python 3's range() is slightly different in that it returns a range object and not a list, so if you're using 3.x wrap it all in list(): list(range(1, n + 1)).

How to multiply values using SQL

Here it is:

select player_name, player_salary, (player_salary * 1.1) as player_newsalary
from player 
order by player_name, player_salary, player_newsalary desc

You don't need to "group by" if there is only one instance of a player in the table.

PySpark: withColumn() with two conditions and three outcomes

The withColumn function in pyspark enables you to make a new variable with conditions, add in the when and otherwise functions and you have a properly working if then else structure. For all of this you would need to import the sparksql functions, as you will see that the following bit of code will not work without the col() function. In the first bit, we declare a new column -'new column', and then give the condition enclosed in when function (i.e. fruit1==fruit2) then give 1 if the condition is true, if untrue the control goes to the otherwise which then takes care of the second condition (fruit1 or fruit2 is Null) with the isNull() function and if true 3 is returned and if false, the otherwise is checked again giving 0 as the answer.

from pyspark.sql import functions as F
df=df.withColumn('new_column', 
    F.when(F.col('fruit1')==F.col('fruit2'), 1)
    .otherwise(F.when((F.col('fruit1').isNull()) | (F.col('fruit2').isNull()), 3))
    .otherwise(0))

library not found for -lPods

Are you opening the workspace (that was generated by CocoaPods) instead of the xcodeproj?

How can I tell if a VARCHAR variable contains a substring?

The standard SQL way is to use like:

where @stringVar like '%thisstring%'

That is in a query statement. You can also do this in TSQL:

if @stringVar like '%thisstring%'

Adding parameter to ng-click function inside ng-repeat doesn't seem to work

Also worth noting, for people who find this in their searches, is this...

<div ng-repeat="button in buttons" class="bb-button" ng-click="goTo(button.path)">
  <div class="bb-button-label">{{ button.label }}</div>
  <div class="bb-button-description">{{ button.description }}</div>
</div>

Note the value of ng-click. The parameter passed to goTo() is a string from a property of the binding object (the button), but it is not wrapped in quotes. Looks like AngularJS handles that for us. I got hung up on that for a few minutes.

How to remove default chrome style for select Input?

Before Applying Property box-shadow : none Before Applying Property box-shadow : none

After Applying Property box-shadow : none After Applying Property box-shadow : none

This is the easiest solution and it worked for me

input {
   box-shadow : none;  
}

String Resource new line /n not possible?

I want to expand on this answer. What they meant is this icon:

Editor window button

It opens a "real editor window" instead of the limited-feature text box in the big overview. In that editor window, special chars, linebreaks etc. are allowed and converted to the correct xml "code" when saved

Can't ping a local VM from the host

I know this is an old post, but I ran into this same issue with my VMs. Log into the VM and go to Control Panel > System and Security > Windows Firewall > Allowed Apps. Then check all of the boxes next to "File and Printer Sharing" to enable file sharing. This should allow you to ping the VM. The screenshot below is from a 2016 Windows Server but the same method will work on older ones.

enter image description here

collapse cell in jupyter notebook

There's also an improved version of Pan Yan suggestion. It adds the button that shows code cells back:

%%html
<style id=hide>div.input{display:none;}</style>
<button type="button" 
onclick="var myStyle = document.getElementById('hide').sheet;myStyle.insertRule('div.input{display:inherit !important;}', 0);">
Show inputs</button>

Or python:

# Run me to hide code cells

from IPython.core.display import display, HTML
display(HTML(r"""<style id=hide>div.input{display:none;}</style><button type="button"onclick="var myStyle = document.getElementById('hide').sheet;myStyle.insertRule('div.input{display:inherit !important;}', 0);">Show inputs</button>"""))

What does "Table does not support optimize, doing recreate + analyze instead" mean?

The better option is create a new table copy the rows to the destination table, drop the actual table and rename the newly created table . This method is good for small tables,

SQL using sp_HelpText to view a stored procedure on a linked server

Little addition in answer if you have different user rather then dbo then do like this.

EXEC  [ServerName].[DatabaseName].dbo.sp_HelpText '[user].[storedProcName]'

Python - abs vs fabs

abs() : Returns the absolute value as per the argument i.e. if argument is int then it returns int, if argument is float it returns float. Also it works on complex variable also i.e. abs(a+bj) also works and returns absolute value i.e.math.sqrt(((a)**2)+((b)**2)

math.fabs() : It only works on the integer or float values. Always returns the absolute float value no matter what is the argument type(except for the complex numbers).

How to solve time out in phpmyadmin?

None of the above answers solved it for me.

I cant even find the 'libraries' folder in my xampp - ubuntu also.

So, I simply restarted using the following commands:

sudo service apache2 restart

and

sudo service mysql restart
  • Just restarted apache and mysql. Logged in phpmyadmin again and it worked as usual.

Thanks me..!!

Proxy setting for R

The problem is with your curl options – the RCurl package doesn't seem to use internet2.dll. You need to specify the port separately, and will probably need to give your user login details as network credentials, e.g.,

opts <- list(
  proxy         = "999.999.999.999", 
  proxyusername = "mydomain\\myusername", 
  proxypassword = "mypassword", 
  proxyport     = 8080
)
getURL("http://stackoverflow.com", .opts = opts)

Remember to escape any backslashes in your password. You may also need to wrap the URL in a call to curlEscape.

Removing body margin in CSS

You've still got a margin on your h1 tag

So you need to remove that like this:

h1 {
 margin-top:0;
}

DateTime "null" value

You can use a nullable DateTime for this.

Nullable<DateTime> myDateTime;

or the same thing written like this:

DateTime? myDateTime;

Setting up FTP on Amazon Cloud Server

maybe worth mentioning in addition to clone45's answer:

Fixing Write Permissions for Chrooted FTP Users in vsftpd

The vsftpd version that comes with Ubuntu 12.04 Precise does not permit chrooted local users to write by default. By default you will have this in /etc/vsftpd.conf:

chroot_local_user=YES
write_enable=YES

In order to allow local users to write, you need to add the following parameter:

allow_writeable_chroot=YES

Note: Issues with write permissions may show up as following FileZilla errors:

Error: GnuTLS error -15: An unexpected TLS packet was received.
Error: Could not connect to server

References:
Fixing Write Permissions for Chrooted FTP Users in vsftpd
VSFTPd stopped working after update

Invalidating JSON Web Tokens

I am going to answer If we need to provide logout from all devices feature when we are using JWT. This approach will use database look-ups for each requests. Because we need a persistence security state even if there is a server crash. In the user table we will have two columns

  1. LastValidTime (default: creation time)
  2. Logged-In (default: true)

Whenever there is a log out request from the user we will update the LastValidTime to current time and Logged-In to false. If there is a log in request we wont change LastValidTime but Logged-In will be set to true.

When we create the JWT we will have the JWT creation time in the payload. When we authorize for a service we will check 3 conditions

  1. Is JWT valid
  2. Is JWT payload creation time is greater than User LastValidTime
  3. Is user Logged-In

Lets see a practical scenario.

User X has two devices A, B. He logged in to our server at 7 pm using device A and device B. (lets say JWT expire time is 12 hrs). A and B both have JWT with createdTime : 7pm

At 9 pm he lost his device B. He immediately log out from the device A. That means Now our database X user entry has LastValidTime as "ThatDate:9:00:xx:xxx" and Logged-In as "false".

At 9:30 the Mr.Thief tries to log in using device B. We will check the database even the Logged-In is false so we wont allow.

At 10 pm Mr.X log in from his device A. Now device A has JWT with created time : 10pm. Now database Logged-In is set to "true"

At 10:30 pm Mr.Thief tries to log in. Even though the Logged-In is true. The LastValidTime is 9 pm in the database but B's JWT has created time as 7pm. So he wont be allowed to access the service. So using device B without having the password he cannot use already created JWT after one device log out.

WampServer: php-win.exe The program can't start because MSVCR110.dll is missing

What solves my problem: I am using 64 bit Windows 7, so I thought I could install 64 bit Wamp. After I Installed the 32-bit version the error does not appear. So something in the developing process at Wamp went wrong...

TypeError: ObjectId('') is not JSON serializable

from bson import json_util
import json

@app.route('/')
def index():
    for _ in "collection_name".find():
        return json.dumps(i, indent=4, default=json_util.default)

This is the sample example for converting BSON into JSON object. You can try this.

How can one tell the version of React running at runtime in the browser?

In index.js file, simply replace App component with "React.version". E.g.

ReactDOM.render(React.version, document.getElementById('root'));

I have checked this with React v16.8.1

Configuring Log4j Loggers Programmatically

You can add/remove Appender programmatically to Log4j:

  ConsoleAppender console = new ConsoleAppender(); //create appender
  //configure the appender
  String PATTERN = "%d [%p|%c|%C{1}] %m%n";
  console.setLayout(new PatternLayout(PATTERN)); 
  console.setThreshold(Level.FATAL);
  console.activateOptions();
  //add appender to any Logger (here is root)
  Logger.getRootLogger().addAppender(console);

  FileAppender fa = new FileAppender();
  fa.setName("FileLogger");
  fa.setFile("mylog.log");
  fa.setLayout(new PatternLayout("%d %-5p [%c{1}] %m%n"));
  fa.setThreshold(Level.DEBUG);
  fa.setAppend(true);
  fa.activateOptions();

  //add appender to any Logger (here is root)
  Logger.getRootLogger().addAppender(fa);
  //repeat with all other desired appenders

I'd suggest you put it into an init() somewhere, where you are sure, that this will be executed before anything else. You can then remove all existing appenders on the root logger with

 Logger.getRootLogger().getLoggerRepository().resetConfiguration();

and start with adding your own. You need log4j in the classpath of course for this to work.

Remark:
You can take any Logger.getLogger(...) you like to add appenders. I just took the root logger because it is at the bottom of all things and will handle everything that is passed through other appenders in other categories (unless configured otherwise by setting the additivity flag).

If you need to know how logging works and how is decided where logs are written read this manual for more infos about that.
In Short:

  Logger fizz = LoggerFactory.getLogger("com.fizz")

will give you a logger for the category "com.fizz".
For the above example this means that everything logged with it will be referred to the console and file appender on the root logger.
If you add an appender to Logger.getLogger("com.fizz").addAppender(newAppender) then logging from fizz will be handled by alle the appenders from the root logger and the newAppender.
You don't create Loggers with the configuration, you just provide handlers for all possible categories in your system.

Converting a String to Object

A String is a type of Object. So any method that accepts Object as parameter will surely accept String also. Please provide more of your code if you still do not find a solution.

Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website

I am on Windows 10, I had the problem with a new fresh installation of Anaconda on python 3.7.4, this post on github solved my problem:

( source: https://github.com/conda/conda/issues/8273)

I cite:

" My workaround: I have copied the following files

libcrypto-1_1-x64.*
libssl-1_1-x64.*

from D:\Anaconda3\Library\bin to D:\Anaconda3\DLLs.

And it works as a charm! "

How do I assign a null value to a variable in PowerShell?

These are automatic variables, like $null, $true, $false etc.

about_Automatic_Variables, see https://technet.microsoft.com/en-us/library/hh847768.aspx?f=255&MSPPError=-2147217396

$NULL
$null is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.

Windows PowerShell treats $null as an object with a value, that is, as an explicit placeholder, so you can use $null to represent an empty value in a series of values.

For example, when $null is included in a collection, it is counted as one of the objects.

C:\PS> $a = ".dir", $null, ".pdf"
C:\PS> $a.count
3

If you pipe the $null variable to the ForEach-Object cmdlet, it generates a value for $null, just as it does for the other objects.

PS C:\ps-test> ".dir", $null, ".pdf" | Foreach {"Hello"}
Hello
Hello
Hello

As a result, you cannot use $null to mean "no parameter value." A parameter value of $null overrides the default parameter value.

However, because Windows PowerShell treats the $null variable as a placeholder, you can use it scripts like the following one, which would not work if $null were ignored.

$calendar = @($null, $null, “Meeting”, $null, $null, “Team Lunch”, $null)
$days = Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"
$currentDay = 0

foreach($day in $calendar)
{
    if($day –ne $null)
    {
        "Appointment on $($days[$currentDay]): $day"
    }

    $currentDay++
}

output:

Appointment on Tuesday: Meeting
Appointment on Friday: Team lunch

"E: Unable to locate package python-pip" on Ubuntu 18.04

To solve the problem of:

E: Unable to locate package python-pip

you should do this. This works with the python2.7 and you not going to get disappointed by it. follow the steps that are mention below. go to get-pip.py and copy all the code from it.
open the terminal using CTRL + ALT +T

vi get-pip.py

paste the copied code here and then exit from the vi editor by pressing

ESC then :wq => press Enter

lastly, now run the code and see the magic

sudo python get-pip.py

It automatically adds the pip command in your Linux.
you can see the output of my machine

How to access the elements of a 2D array?

a[1][1] does work as expected. Do you mean a11 as the first element of the first row? Cause that would be a[0][0].

adb remount permission denied, but able to access super user in shell -- android

In case anyone has the same problem in the future:

$ adb shell
$ su
# mount -o rw,remount /system

Both adb remount and adb root don't work on a production build without altering ro.secure, but you can still remount /system by opening a shell, asking for root permissions and typing the mount command.

Overwriting my local branch with remote branch

git reset --hard

This is to revert all your local changes to the origin head

replace all occurrences in a string

Brighams answer uses literal regexp.

Solution with a Regex object.

var regex = new RegExp('\n', 'g');
text = text.replace(regex, '<br />');

TRY IT HERE : JSFiddle Working Example

Django download a file

You can add "download" attribute inside your tag to download files.

<a  href="/project/download" download> Download Document </a>

https://www.w3schools.com/tags/att_a_download.asp

Converting a year from 4 digit to 2 digit and back again in C#

The answer is quite simple:

DateTime Today = DateTime.Today;
string zeroBased = Today.ToString("yy-MM-dd");

get parent's view from a layout

Check my answer here

The use of Layout Inspector tool can be very convenient when you have a complex view or you are using a third party library where you can't add an id to a view

Run jar file in command prompt

java [any other JVM options you need to give it] -jar foo.jar

Best approach to real time http streaming to HTML5 video client

EDIT 3: As of IOS 10, HLS will support fragmented mp4 files. The answer now, is to create fragmented mp4 assets, with a DASH and HLS manifest. > Pretend flash, iOS9 and below and IE 10 and below don't exist.

Everything below this line is out of date. Keeping it here for posterity.


EDIT 2: As people in the comments are pointing out, things change. Almost all browsers will support AVC/AAC codecs. iOS still requires HLS. But via adaptors like hls.js you can play HLS in MSE. The new answer is HLS+hls.js if you need iOS. or just Fragmented MP4 (i.e. DASH) if you don't

There are many reasons why video and, specifically, live video is very difficult. (Please note that the original question specified that HTML5 video is a requirement, but the asker stated Flash is possible in the comments. So immediately, this question is misleading)

First I will restate: THERE IS NO OFFICIAL SUPPORT FOR LIVE STREAMING OVER HTML5. There are hacks, but your mileage may vary.

EDIT: since I wrote this answer Media Source Extensions have matured, and are now very close to becoming a viable option. They are supported on most major browsers. IOS continues to be a hold out.

Next, you need to understand that Video on demand (VOD) and live video are very different. Yes, they are both video, but the problems are different, hence the formats are different. For example, if the clock in your computer runs 1% faster than it should, you will not notice on a VOD. With live video, you will be trying to play video before it happens. If you want to join a a live video stream in progress, you need the data necessary to initialize the decoder, so it must be repeated in the stream, or sent out of band. With VOD, you can read the beginning of the file them seek to whatever point you wish.

Now let's dig in a bit.

Platforms:

  • iOS
  • PC
  • Mac
  • Android

Codecs:

  • vp8/9
  • h.264
  • thora (vp3)

Common Delivery methods for live video in browsers:

  • DASH (HTTP)
  • HLS (HTTP)
  • flash (RTMP)
  • flash (HDS)

Common Delivery methods for VOD in browsers:

  • DASH (HTTP Streaming)
  • HLS (HTTP Streaming)
  • flash (RTMP)
  • flash (HTTP Streaming)
  • MP4 (HTTP pseudo streaming)
  • I'm not going to talk about MKV and OOG because I do not know them very well.

html5 video tag:

  • MP4
  • webm
  • ogg

Lets look at which browsers support what formats

Safari:

  • HLS (iOS and mac only)
  • h.264
  • MP4

Firefox

  • DASH (via MSE but no h.264)
  • h.264 via Flash only!
  • VP9
  • MP4
  • OGG
  • Webm

IE

  • Flash
  • DASH (via MSE IE 11+ only)
  • h.264
  • MP4

Chrome

  • Flash
  • DASH (via MSE)
  • h.264
  • VP9
  • MP4
  • webm
  • ogg

MP4 cannot be used for live video (NOTE: DASH is a superset of MP4, so don't get confused with that). MP4 is broken into two pieces: moov and mdat. mdat contains the raw audio video data. But it is not indexed, so without the moov, it is useless. The moov contains an index of all data in the mdat. But due to its format, it can not be 'flattened' until the timestamps and size of EVERY frame is known. It may be possible to construct an moov that 'fibs' the frame sizes, but is is very wasteful bandwidth wise.

So if you want to deliver everywhere, we need to find the least common denominator. You will see there is no LCD here without resorting to flash example:

  • iOS only supports h.264 video. and it only supports HLS for live.
  • Firefox does not support h.264 at all, unless you use flash
  • Flash does not work in iOS

The closest thing to an LCD is using HLS to get your iOS users, and flash for everyone else. My personal favorite is to encode HLS, then use flash to play HLS for everyone else. You can play HLS in flash via JW player 6, (or write your own HLS to FLV in AS3 like I did)

Soon, the most common way to do this will be HLS on iOS/Mac and DASH via MSE everywhere else (This is what Netflix will be doing soon). But we are still waiting for everyone to upgrade their browsers. You will also likely need a separate DASH/VP9 for Firefox (I know about open264; it sucks. It can't do video in main or high profile. So it is currently useless).

Angularjs - Pass argument to directive

You can pass arguments to your custom directive as you do with the builtin Angular-directives - by specifying an attribute on the directive-element:

angular.element(document.getElementById('wrapper'))
       .append('<directive-name title="title2"></directive-name>');

What you need to do is define the scope (including the argument(s)/parameter(s)) in the factory function of your directive. In below example the directive takes a title-parameter. You can then use it, for example in the template, using the regular Angular-way: {{title}}

app.directive('directiveName', function(){
   return {
      restrict:'E',
      scope: {
         title: '@'
      },
      template:'<div class="title"><h2>{{title}}</h2></div>'
   };
});

Depending on how/what you want to bind, you have different options:

  • = is two-way binding
  • @ simply reads the value (one-way binding)
  • & is used to bind functions

In some cases you may want use an "external" name which differs from the "internal" name. With external I mean the attribute name on the directive-element and with internal I mean the name of the variable which is used within the directive's scope.

For example if we look at above directive, you might not want to specify another, additional attribute for the title, even though you internally want to work with a title-property. Instead you want to use your directive as follows:

<directive-name="title2"></directive-name>

This can be achieved by specifying a name behind the above mentioned option in the scope definition:

scope: {
    title: '@directiveName'
}

Please also note following things:

  • The HTML5-specification says that custom attributes (this is basically what is all over the place in Angular applications) should be prefixed with data-. Angular supports this by stripping the data--prefix from any attributes. So in above example you could specify the attribute on the element (data-title="title2") and internally everything would be the same.
  • Attributes on elements are always in the form of <div data-my-attribute="..." /> while in code (e.g. properties on scope object) they are in the form of myAttribute. I lost lots of time before I realized this.
  • For another approach to exchanging/sharing data between different Angular components (controllers, directives), you might want to have a look at services or directive controllers.
  • You can find more information on the Angular homepage (directives)

ssh-copy-id no identities found error

You need to use the -i flag:

ssh-copy-id -i my.key.pub 10.10.1.1

From the man page:

If the -i option is given then the identity file (defaults to ~/.ssh/id_rsa.pub) is used, regardless of whether there are any keys in your ssh-agent. Otherwise, if this: ssh-add -L provides any output, it uses that in preference to the identity file

How do you set up use HttpOnly cookies in PHP

A more elegant solution since PHP >=7.0

session_start(['cookie_lifetime' => 43200,'cookie_secure' => true,'cookie_httponly' => true]);

session_start

session_start options

What is the unix command to see how much disk space there is and how much is remaining?

I love doing du -sh * | sort -nr | less to sort by the largest files first

Using iFrames In ASP.NET

You can think of an iframe as an embedded browser window that you can put on an HTML page to show another URL inside it. This URL can be totally distinct from your web site/app.

You can put an iframe in any HTML page, so you could put one inside a contentplaceholder in a webform that has a Masterpage and it will appear with whatever URL you load into it (via Javascript, or C# if you turn your iframe into a server-side control (runat='server') on the final HTML page that your webform produces when requested.

And you can load a URL into your iframe that is a .aspx page.

But - iframes have nothing to do with the ASP.net mechanism. They are HTML elements that can be made to run server-side, but they are essentially 'dumb' and unmanaged/unconnected to the ASP.Net mechanisms - don't confuse a Contentplaceholder with an iframe.

Incidentally, the use of iframes is still contentious - do you really need to use one? Can you afford the negative trade-offs associated with them e.g. lack of navigation history ...?

getMinutes() 0-9 - How to display two digit numbers?

var date = new Date("2012-01-18T16:03");

console.log( (date.getMinutes()<10?'0':'') + date.getMinutes() );

Return value in SQL Server stored procedure

@EmailAddress varchar(200),
@NickName varchar(100),
@Password varchar(150),
@Sex varchar(50),
@Age int,
@EmailUpdates int,
@UserId int OUTPUT
DECLARE @AA INT
SET @AA=(SELECT COUNT(UserId) FROM RegUsers WHERE EmailAddress = @EmailAddress)

IF @AA> 0
    BEGIN
        SET @UserId = 0
    END
ELSE
    BEGIN
        INSERT INTO RegUsers (EmailAddress,NickName,PassWord,Sex,Age,EmailUpdates) VALUES (@EmailAddress,@NickName,@Password,@Sex,@Age,@EmailUpdates)
        SELECT SCOPE_IDENTITY()
    END

END

How can I get the CheckBoxList selected values, what I have doesn't seem to work C#.NET/VisualWebPart

check boxlist selected values with seperator

 string items = string.Empty;
        foreach (ListItem i in CheckBoxList1.Items)
        {
            if (i.Selected == true)
            {
                items += i.Text + ",";
            }
        }
        Response.Write("selected items"+ items);

Amazon S3 upload file and get URL

        System.out.println("Link : " + s3Object.getObjectContent().getHttpRequest().getURI());

with this you can retrieve the link of already uploaded file to S3 bucket.

How to check if a string is numeric?

Simple method:

public boolean isBlank(String value) {
    return (value == null || value.equals("") || value.equals("null") || value.trim().equals(""));
}


public boolean isOnlyNumber(String value) {
    boolean ret = false;
    if (!isBlank(value)) {
        ret = value.matches("^[0-9]+$");
    }
    return ret;
}

how to select first N rows from a table in T-SQL?

SELECT TOP 10 * FROM TABLE_NAME ORDER BY ORDERED_UNIQUE_COLUMN DESC

ORDERED_UNIQUE_COLUMN could be your incrementing primary key or a timestamp

Spring - @Transactional - What happens in background?

When Spring loads your bean definitions, and has been configured to look for @Transactional annotations, it will create these proxy objects around your actual bean. These proxy objects are instances of classes that are auto-generated at runtime. The default behaviour of these proxy objects when a method is invoked is just to invoke the same method on the "target" bean (i.e. your bean).

However, the proxies can also be supplied with interceptors, and when present these interceptors will be invoked by the proxy before it invokes your target bean's method. For target beans annotated with @Transactional, Spring will create a TransactionInterceptor, and pass it to the generated proxy object. So when you call the method from client code, you're calling the method on the proxy object, which first invokes the TransactionInterceptor (which begins a transaction), which in turn invokes the method on your target bean. When the invocation finishes, the TransactionInterceptor commits/rolls back the transaction. It's transparent to the client code.

As for the "external method" thing, if your bean invokes one of its own methods, then it will not be doing so via the proxy. Remember, Spring wraps your bean in the proxy, your bean has no knowledge of it. Only calls from "outside" your bean go through the proxy.

Does that help?

Regular expression for validating names and surnames?

It's a very difficult problem to validate something like a name due to all the corner cases possible.

Corner Cases

Sanitize the inputs and let them enter whatever they want for a name, because deciding what is a valid name and what is not is probably way outside the scope of whatever you're doing; given the range of potential strange - and legal names is nearly infinite.

If they want to call themselves Tricyclopltz^2-Glockenschpiel, that's their problem, not yours.

Login with facebook android sdk app crash API 4

The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):

Mikhail,

The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.

Good luck with your implementation.

Windows batch script to move files

Create a file called MoveFiles.bat with the syntax

move c:\Sourcefoldernam\*.* e:\destinationFolder

then schedule a task to run that MoveFiles.bat every 10 hours.

Checking for an empty field with MySQL

This will work but there is still the possibility of a null record being returned. Though you may be setting the email address to a string of length zero when you insert the record, you may still want to handle the case of a NULL email address getting into the system somehow.

     $aUsers=$this->readToArray('
     SELECT `userID` 
     FROM `users` 
     WHERE `userID` 
     IN(SELECT `userID`
               FROM `users_indvSettings`
               WHERE `indvSettingID`=5 AND `optionID`='.$time.')
     AND `email` != "" AND `email` IS NOT NULL
     ');

Why is JavaFX is not included in OpenJDK 8 on Ubuntu Wily (15.10)?

I use ubuntu 16.04 and because I already had openJDK installed, this command have solved the problem. Don't forget that JavaFX is part of OpenJDK.

sudo apt-get install openjfx

do <something> N times (declarative syntax)

You can also do the same thing with destructuring as follows

[...Array(3)].forEach( _ => console.log('do something'));

or if you need index

[...Array(3)].forEach(( _, index) => console.log('do something'));

What is the difference between require_relative and require in Ruby?

I just saw the RSpec's code has some comment on require_relative being O(1) constant and require being O(N) linear. So probably the difference is that require_relative is the preferred one than require.

"Unable to get the VLookup property of the WorksheetFunction Class" error

I was having the same problem. It seems that passing Me.ComboBox1.Value as an argument for the Vlookup function is causing the issue. What I did was assign this value to a double and then put it into the Vlookup function.

Dim x As Double
x = Me.ComboBox1.Value
Me.TextBox1.Value = Application.WorksheetFunction.VLookup(x, Worksheets("Sheet3").Range("Names"), 2, False) 

Or, for a shorter method, you can just convert the type within the Vlookup function using Cdbl(<Value>).

So it would end up being

Me.TextBox1.Value = Application.WorksheetFunction.VLookup(Cdbl(Me.ComboBox1.Value), Worksheets("Sheet3").Range("Names"), 2, False) 

Strange as it may sound, it works for me.

Hope this helps.

Explain ExtJS 4 event handling

Just wanted to add a couple of pence to the excellent answers above: If you are working on pre Extjs 4.1, and don't have application wide events but need them, I've been using a very simple technique that might help: Create a simple object extending Observable, and define any app wide events you might need in it. You can then fire those events from anywhere in your app, including actual html dom element and listen to them from any component by relaying the required elements from that component.

Ext.define('Lib.MessageBus', {
    extend: 'Ext.util.Observable',

    constructor: function() {
        this.addEvents(
            /*
             * describe the event
             */
                  "eventname"

            );
        this.callParent(arguments);
    }
});

Then you can, from any other component:

 this.relayEvents(MesageBus, ['event1', 'event2'])

And fire them from any component or dom element:

 MessageBus.fireEvent('event1', somearg);

 <input type="button onclick="MessageBus.fireEvent('event2', 'somearg')">

Android ImageView Zoom-in and Zoom-Out

I got the most helpful answer from @Nicolas Tyler but I had issues with how the syntax and logic worked. I also did not want any Alpha space and my Algebra was rusty! After 3 days I have put together my own version of this.

My answer differs from @Nicolas Tyler with the following:

  1. Different variable names which I found made more sense in underlying contextual uses

  2. This Pinch-Zoom image class does NOT show alpha space and will let you zoom in and out and still not let you over/under pan an image and reveal alpha space

  3. Added deep comments to the matrix section to explain what was going on with the math involved

  4. This image class will also let you pass in a resourceId and it will create a bitmap from it

  5. Much simpler algorithms for both scaling and translation and few variables

  6. Changing the image within this will cause it to zoom in/out such that the new image takes up the view container

A great resource refresher on Algebra can be found here: https://youtu.be/IiXB6tYtY4w?t=4m12s That video covers the core of Scalar and Translation matrixes (and will help you make sense of the MTRANS_X and MTRANS_Y stuff). If you have questions ask and I will do my best to answer (but I am NO Algebra expert).

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.ImageView;

public class iImage extends ImageView
{
    static final int NONE_MODE = 0;
    static final int DRAG_MODE = 1;
    static final int ZOOM_MODE = 2;
    int _mode = NONE_MODE;

    Matrix _matrix = new Matrix();
    PointF _previousPoint = new PointF();
    PointF _startPoint = new PointF();
    float _currentScale = 1f;
    float _minScale = 1f;
    float _maxScale = 3f;
    float[] _arrayOf9Floats;
    float _bitmapWidth, _bitmapHeight,_displayWidth, _displayHeight;
    ScaleGestureDetector _scaleDetector;
    Context _context;

    public iImage(Context context)
    {
        super(context);
        super.setClickable(true);
        _context = context;
        _scaleDetector = new ScaleGestureDetector(context, new ScaleListener());
        _arrayOf9Floats = new float[9];
        setScaleType(ScaleType.MATRIX);
        setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return handleTouch(v, event);
            }
        });
    }

    private boolean handleTouch(View v, MotionEvent event)
    {
        _scaleDetector.onTouchEvent(event);
        //Contrary to how this line looks, the matrix is not setting the values from the arrayOf9Floats, but rather taking the
        //matrix values and assigning them into the arrayOf9Floats. I extremely dislike this syntax and I think
        //it should have been written as _arrayOf9Floats = _matrix.getValues() but that's Android for you!!!
        _matrix.getValues(_arrayOf9Floats);

        //Look at https://youtu.be/IiXB6tYtY4w?t=4m12s , it shows scale, rotate, and translate matrices
        //If you look at the translate matrix, you'll see that the 3rd and 6th values are the values which represent x and y translations respectively
        //this corresponds to the 2nd and 5th values in the array and hence why the MTRANS_X and MTRANS_Y have the constants 2 and 5 respectively
        float xTranslate = _arrayOf9Floats[Matrix.MTRANS_X];
        float yTranslate = _arrayOf9Floats[Matrix.MTRANS_Y];
        PointF currentEventPoint = new PointF(event.getX(), event.getY());
        switch (event.getAction())
        {
            //First finger down only
            case MotionEvent.ACTION_DOWN:
                _previousPoint.set(event.getX(), event.getY());
                _startPoint.set(_previousPoint);
                _mode = DRAG_MODE;
                break;
            //Second finger down
            case MotionEvent.ACTION_POINTER_DOWN:
                _previousPoint.set(event.getX(), event.getY());
                _startPoint.set(_previousPoint);
                _mode = ZOOM_MODE;
                break;
            case MotionEvent.ACTION_MOVE:
                if (_mode == ZOOM_MODE || _mode == DRAG_MODE )
                {
                    float deltaX = currentEventPoint.x - _previousPoint.x;
                    float deltaY = currentEventPoint.y - _previousPoint.y;
                    //In matrix terms, going right is + and going left is +
                    //Moving the image right past 0 means it will show alpha space on the left so we dont want that
                    //Keep in mind this is a TOP LEFT pivot point, so we dont want the top left to be past 0 lest we have alpha space
                    if(xTranslate + deltaX > 0)
                    {
                        //get absolute of how much into the negative we would have gone
                        float excessDeltaX = Math.abs(xTranslate + deltaX);
                        //take that excess away from deltaX so X wont got less than 0 after the translation
                        deltaX = deltaX - excessDeltaX;
                    }

                    //Going left we dont want the negative value to be less than the negative width of the sprite, lest we get alpha space on the right
                    //The width is going to be the width of the bitmap * scale and we want the - of it because we are checking for left movement
                    //We also need to account for the width of the DISPLAY CONTAINER (i.e. _displayWidth) so that gets subtracted
                    //i.e. we want the max scroll width value
                    float maxScrollableWidth = _bitmapWidth * _currentScale - _displayWidth;
                    if(xTranslate + deltaX < -maxScrollableWidth)
                    {
                        //this forces the max possible translate to always match the - of maxScrollableWidth
                        deltaX = -maxScrollableWidth - xTranslate;
                    }

                    //repeat for Y
                    if(yTranslate + deltaY > 0)
                    {
                        float excessDeltaY = Math.abs(yTranslate + deltaY);
                        deltaY = deltaY - excessDeltaY;
                    }

                    float maxScrollableHeight = _bitmapHeight * _currentScale - _displayWidth;
                    if(yTranslate + deltaY < -maxScrollableHeight)
                    {
                        //this forces the max possible translate to always match the - of maxScrollableWidth
                        deltaY = -maxScrollableHeight - yTranslate;
                    }

                    _matrix.postTranslate(deltaX, deltaY);
                    _matrix.getValues(_arrayOf9Floats);
                    //System.out.println(_matrix);

                    _previousPoint.set(currentEventPoint.x, currentEventPoint.y);
                }
                break;
            case MotionEvent.ACTION_POINTER_UP:
                _mode = NONE_MODE;
                break;
        }
        setImageMatrix(_matrix);
        invalidate();
        return true;
    }

    @Override
    public void setImageBitmap(Bitmap bm)
    {
        super.setImageBitmap(bm);
        _bitmapWidth = bm.getWidth();
        _bitmapHeight = bm.getHeight();
        invalidate();
    }

    @Override
    public void setImageResource(int resid)
    {
        Bitmap bitmapImage = BitmapFactory.decodeResource(_context.getResources(), resid);
        setImageBitmap(bitmapImage);
    }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener
    {

        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector)
        {
            _mode = ZOOM_MODE;
            return true;
        }

        @Override
        public boolean onScale(ScaleGestureDetector detector)
        {
            float scaleFactor = detector.getScaleFactor();
            float originalScale = _currentScale;
            _currentScale *= scaleFactor;
            //Zoom in too much
            if (_currentScale > _maxScale) {
                _currentScale = _maxScale;
                scaleFactor = _maxScale / originalScale;
            }//Zoom out too much
            else if (_currentScale < _minScale) {
                _currentScale = _minScale;
                scaleFactor = _minScale / originalScale;
            }
           _matrix.postScale(scaleFactor,scaleFactor);

            return true;
        }
    }

    @Override
    protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        _displayWidth = MeasureSpec.getSize(widthMeasureSpec);
        _displayHeight = MeasureSpec.getSize(heightMeasureSpec);
        adjustScale();
    }

    private void adjustScale()
    {
        //Fit to display bounds with NO alpha space
        float scale;
        float scaleX =  _displayWidth / _bitmapWidth;
        float scaleY = _displayHeight / _bitmapHeight;
        scale = Math.max(scaleX, scaleY);
        _matrix.setScale(scale, scale);
        setImageMatrix(_matrix);
        _currentScale = scale;
        _minScale = scale;
    }

    public void setMaxZoom(float maxZoom){_maxScale = maxZoom;}
    public void setMinZoom(float minZoom) {_minScale = minZoom;}
}

Writing List of Strings to Excel CSV File in Python

A sample - write multiple rows with boolean column (using example above by GaretJax and Eran?).

import csv
RESULT = [['IsBerry','FruitName'],
          [False,'apple'],
          [True, 'cherry'],
          [False,'orange'],
          [False,'pineapple'],
          [True, 'strawberry']]
with open("../datasets/dashdb.csv", 'wb') as resultFile:
    wr = csv.writer(resultFile, dialect='excel')
    wr.writerows(RESULT)

Result:

df_data_4 = pd.read_csv('../datasets/dashdb.csv')
df_data_4.head()

Output:

   IsBerry  FruitName
   0    False   apple
   1    True    cherry
   2    False   orange
   3    False   pineapple
   4    True    strawberry

How to check if an object is defined?

If a class type is not defined, you'll get a compiler error if you try to use the class, so in that sense you should have to check.

If you have an instance, and you want to ensure it's not null, simply check for null:

if (value != null)
{
    // it's not null. 
}

Is there a SELECT ... INTO OUTFILE equivalent in SQL Server Management Studio?

In SSMS, "Query" menu item... "Results to"... "Results to File"

Shortcut = CTRL+shift+F

You can set it globally too

"Tools"... "Options"... "Query Results"... "SQL Server".. "Default destination" drop down

Edit: after comment

In SSMS, "Query" menu item... "SQLCMD" mode

This allows you to run "command line" like actions.

A quick test in my SSMS 2008

:OUT c:\foo.txt
SELECT * FROM sys.objects

Edit, Sep 2012

:OUT c:\foo.txt
SET NOCOUNT ON;SELECT * FROM sys.objects

Heroku: How to push different local Git branches to Heroku/master

I think it should be

push = refs/heads/*:refs/heads/*

instead...

Default background color of SVG root element

It is the answer of @Robert Longson, now with code (there was originally no code, it was added later):

_x000D_
_x000D_
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<svg version="1.1" xmlns="http://www.w3.org/2000/svg">_x000D_
 <rect width="100%" height="100%" fill="red"/>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

This answer uses:

How do you get the length of a string?

The easiest way:

$('#selector').val().length

How to Specify "Vary: Accept-Encoding" header in .htaccess

Many hours spent to clarify what was that. Please, read this post to get the advanced .HTACCESS codes and learn what they do.

You can use:

Header append Vary "Accept-Encoding"
#or
Header set Vary "Accept-Encoding"

What's the use of "enum" in Java?

You use an enum instead of a class if the class should have a fixed enumerable number of instances.

Examples:

  • DayOfWeek  = 7 instances ? enum
  • CardSuit    = 4 instances ? enum
  • Singleton  = 1 instance   ? enum

  • Product      = variable number of instances ? class
  • User            = variable number of instances ? class
  • Date            = variable number of instances ? class

how do I set height of container DIV to 100% of window height?

I've been thinking over this and experimenting with height of the elements: html, body and div. Finally I came up with the code:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<title>Height question</title>_x000D_
<style>_x000D_
 html {height: 50%; border: solid red 3px; }_x000D_
 body {height: 70vh; border: solid green 3px; padding: 12pt; }_x000D_
 div {height: 90vh; border: solid blue 3px; padding: 24pt; }_x000D_
 _x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
 <div id="container">_x000D_
  <p>&lt;html&gt; is red</p>_x000D_
  <p>&lt;body&gt; is green</p>_x000D_
  <p>&lt;div&gt; is blue</p>_x000D_
 </div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

With my browser (Firefox 65@mint 64), all three elements are of 1) different height, 2) every one is longer, than the previous (html is 50%, body is 70vh, and div 90vh). I also checked the styles without the height with respect to the html and body tags. Worked fine, too.

About CSS units: w3schools: CSS units

A note about the viewport: " Viewport = the browser window size. If the viewport is 50cm wide, 1vw = 0.5cm."

Select2 doesn't work when embedded in a bootstrap modal

If you have a problem with the iPad keyboard which hide the bootstrap modal while clicking on the select2 input, you can resolve this by adding the following rule after the initialization of the select2 input :

if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {
   var styleEl = document.createElement('style'), styleSheet;
   document.head.appendChild(styleEl);
   styleSheet = styleEl.sheet;
   styleSheet.insertRule(".modal { position:absolute; bottom:auto; }", 0);
   document.body.scrollTop = 0; // Only for Safari
}

Taken from https://github.com/angular-ui/bootstrap/issues/1812#issuecomment-135119475

EDIT: If your options are not shown properly, you need to use the dropdownParent attribute when initializing select2 :

$(".select2").select2({
    dropdownParent: $("#YOURMODALID")
});

Good luck (:

How can I redirect a php page to another php page?

can use this to redirect

echo '<meta http-equiv="refresh" content="1; URL=index.php" />';

the content=1 can be change to different value to increase the delay before redirection

How to set a CMake option() at command line

this works for me:

cmake -D DBUILD_SHARED_LIBS=ON DBUILD_STATIC_LIBS=ON DBUILD_TESTS=ON ..

Adding click event handler to iframe

iframe doesn't have onclick event but we can implement this by using iframe's onload event and javascript like this...

function iframeclick() {
document.getElementById("theiframe").contentWindow.document.body.onclick = function() {
        document.getElementById("theiframe").contentWindow.location.reload();
    }
}


<iframe id="theiframe" src="youriframe.html" style="width: 100px; height: 100px;" onload="iframeclick()"></iframe>

I hope it will helpful to you....

How to create nested directories using Mkdir in Golang?

os.Mkdir is used to create a single directory. To create a folder path, instead try using:

os.MkdirAll(folderPath, os.ModePerm)

Go documentation

func MkdirAll(path string, perm FileMode) error

MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error. The permission bits perm are used for all directories that MkdirAll creates. If path is already a directory, MkdirAll does nothing and returns nil.

Edit:

Updated to correctly use os.ModePerm instead.
For concatenation of file paths, use package path/filepath as described in @Chris' answer.

How do I get the last four characters from a string in C#?

Using Substring is actually quite short and readable:

 var result = mystring.Substring(mystring.Length - Math.Min(4, mystring.Length));
 // result == "d124"

How to get video duration, dimension and size in PHP?

If you have FFMPEG installed on your server (http://www.mysql-apache-php.com/ffmpeg-install.htm), it is possible to get the attributes of your video using the command "-vstats" and parsing the result with some regex - as shown in the example below. Then, you need the PHP funtion filesize() to get the size.

$ffmpeg_path = 'ffmpeg'; //or: /usr/bin/ffmpeg , or /usr/local/bin/ffmpeg - depends on your installation (type which ffmpeg into a console to find the install path)
$vid = 'PATH/TO/VIDEO'; //Replace here!

 if (file_exists($vid)) {

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime_type = finfo_file($finfo, $vid); // check mime type
    finfo_close($finfo);

    if (preg_match('/video\/*/', $mime_type)) {

        $video_attributes = _get_video_attributes($vid, $ffmpeg_path);

        print_r('Codec: ' . $video_attributes['codec'] . '<br/>');

        print_r('Dimension: ' . $video_attributes['width'] . ' x ' . $video_attributes['height'] . ' <br/>');

        print_r('Duration: ' . $video_attributes['hours'] . ':' . $video_attributes['mins'] . ':'
                . $video_attributes['secs'] . '.' . $video_attributes['ms'] . '<br/>');

        print_r('Size:  ' . _human_filesize(filesize($vid)));

    } else {
        print_r('File is not a video.');
    }
} else {
    print_r('File does not exist.');
}

function _get_video_attributes($video, $ffmpeg) {

    $command = $ffmpeg . ' -i ' . $video . ' -vstats 2>&1';
    $output = shell_exec($command);

    $regex_sizes = "/Video: ([^,]*), ([^,]*), ([0-9]{1,4})x([0-9]{1,4})/"; // or : $regex_sizes = "/Video: ([^\r\n]*), ([^,]*), ([0-9]{1,4})x([0-9]{1,4})/"; (code from @1owk3y)
    if (preg_match($regex_sizes, $output, $regs)) {
        $codec = $regs [1] ? $regs [1] : null;
        $width = $regs [3] ? $regs [3] : null;
        $height = $regs [4] ? $regs [4] : null;
    }

    $regex_duration = "/Duration: ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}).([0-9]{1,2})/";
    if (preg_match($regex_duration, $output, $regs)) {
        $hours = $regs [1] ? $regs [1] : null;
        $mins = $regs [2] ? $regs [2] : null;
        $secs = $regs [3] ? $regs [3] : null;
        $ms = $regs [4] ? $regs [4] : null;
    }

    return array('codec' => $codec,
        'width' => $width,
        'height' => $height,
        'hours' => $hours,
        'mins' => $mins,
        'secs' => $secs,
        'ms' => $ms
    );
}

function _human_filesize($bytes, $decimals = 2) {
    $sz = 'BKMGTP';
    $factor = floor((strlen($bytes) - 1) / 3);
    return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}

Xcode - Warning: Implicit declaration of function is invalid in C99

should call the function properly; like- Fibonacci:input

adb uninstall failed

It can be something as simple as typing the package name in the wrong case...

I had the same problem - turned out I was entering the package name in all lower case when the actual package name included upper case characters.

adb uninstall -k <packageName - eg. com.test.app>

( If you're explicitly uninstalling you probably don't want the -k which keeps the app data and cache directories around. )

What is "X-Content-Type-Options=nosniff"?

It prevents the browser from doing MIME-type sniffing. Most browsers are now respecting this header, including Chrome/Chromium, Edge, IE >= 8.0, Firefox >= 50 and Opera >= 13. See :

https://blogs.msdn.com/b/ie/archive/2008/09/02/ie8-security-part-vi-beta-2-update.aspx?Redirected=true

Sending the new X-Content-Type-Options response header with the value nosniff will prevent Internet Explorer from MIME-sniffing a response away from the declared content-type.

EDIT:

Oh and, that's an HTTP header, not a HTML meta tag option.

See also : http://msdn.microsoft.com/en-us/library/ie/gg622941(v=vs.85).aspx

R: "Unary operator error" from multiline ggplot2 command

Try to consolidate the syntax in a single line. this will clear the error

How to change the size of the font of a JLabel to take the maximum size

Not the most pretty code, but the following will pick an appropriate font size for a JLabel called label such that the text inside will fit the interior as much as possible without overflowing the label:

Font labelFont = label.getFont();
String labelText = label.getText();

int stringWidth = label.getFontMetrics(labelFont).stringWidth(labelText);
int componentWidth = label.getWidth();

// Find out how much the font can grow in width.
double widthRatio = (double)componentWidth / (double)stringWidth;

int newFontSize = (int)(labelFont.getSize() * widthRatio);
int componentHeight = label.getHeight();

// Pick a new font size so it will not be larger than the height of label.
int fontSizeToUse = Math.min(newFontSize, componentHeight);

// Set the label's font size to the newly determined size.
label.setFont(new Font(labelFont.getName(), Font.PLAIN, fontSizeToUse));

Basically, the code looks at how much space the text in the JLabel takes up by using the FontMetrics object, and then uses that information to determine the largest font size that can be used without overflowing the text from the JLabel.

The above code can be inserted into perhaps the paint method of the JFrame which holds the JLabel, or some method which will be invoked when the font size needs to be changed.

The following is an screenshot of the above code in action:

alt text
(source: coobird.net)

Why use #ifndef CLASS_H and #define CLASS_H in .h file but not in .cpp?

It doesn't - at least during the compilation phase.

The translation of a c++ program from source code to machine code is performed in three phases:

  1. Preprocessing - The Preprocessor parses all source code for lines beginning with # and executes the directives. In your case, the contents of your file class.h is inserted in place of the line #include "class.h. Since you might be includein your header file in several places, the #ifndef clauses avoid duplicate declaration-errors, since the preprocessor directive is undefined only the first time the header file is included.
  2. Compilation - The Compiler does now translate all preprocessed source code files to binary object files.
  3. Linking - The Linker links (hence the name) together the object files. A reference to your class or one of its methods (which should be declared in class.h and defined in class.cpp) is resolved to the respective offset in one of the object files. I write 'one of your object files' since your class does not need to be defined in a file named class.cpp, it might be in a library which is linked to your project.

In summary, the declarations can be shared through a header file, while the mapping of declarations to definitions is done by the linker.

Using intents to pass data between activities

Try this from your AndroidTabRestaurantDescSearchListView activity

Intent intent  = new Intent(this,RatingDescriptionSearchActivity.class );
intent.putExtras( getIntent().getExtras() );
startActivity( intent );  

And then from RatingDescriptionSearchActivity activity just call

getIntent().getStringExtra("key")

How to make --no-ri --no-rdoc the default for gem install?

On Windows XP the path to the .gemrc file is

c:\Documents and Settings\All Users\Application Data\gemrc 

and this file is not created by default, you should create it yourself.

Why use ICollection and not IEnumerable or List<T> on many-many/one-many relationships?

Usually what you choose will depend on which methods you need access to. In general - IEnumerable<> (MSDN: http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx) for a list of objects that only needs to be iterated through, ICollection<> (MSDN: http://msdn.microsoft.com/en-us/library/92t2ye13.aspx) for a list of objects that needs to be iterated through and modified, List<> for a list of objects that needs to be iterated through, modified, sorted, etc (See here for a full list: http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx).

From a more specific standpoint, lazy loading comes in to play with choosing the type. By default, navigation properties in Entity Framework come with change tracking and are proxies. In order for the dynamic proxy to be created as a navigation property, the virtual type must implement ICollection.

A navigation property that represents the "many" end of a relationship must return a type that implements ICollection, where T is the type of the object at the other end of the relationship. -Requirements for Creating POCO ProxiesMSDN

More information on Defining and Managing RelationshipsMSDN

How do you loop in a Windows batch file?

Conditionally perform a command several times.

  • syntax-FOR-Files

    FOR %%parameter IN (set) DO command 
    
  • syntax-FOR-Files-Rooted at Path

    FOR /R [[drive:]path] %%parameter IN (set) DO command 
    
  • syntax-FOR-Folders

    FOR /D %%parameter IN (folder_set) DO command 
    
  • syntax-FOR-List of numbers

    FOR /L %%parameter IN (start,step,end) DO command 
    
  • syntax-FOR-File contents

    FOR /F ["options"] %%parameter IN (filenameset) DO command 
    

    or

    FOR /F ["options"] %%parameter IN ("Text string to process") DO command
    
  • syntax-FOR-Command Results

    FOR /F ["options"] %%parameter IN ('command to process') DO command
    

It

  • Take a set of data
  • Make a FOR Parameter %%G equal to some part of that data
  • Perform a command (optionally using the parameter as part of the command).
  • --> Repeat for each item of data

If you are using the FOR command at the command line rather than in a batch program, use just one percent sign: %G instead of %%G.

FOR Parameters

  • The first parameter has to be defined using a single character, for example the letter G.

  • FOR %%G IN ...

    In each iteration of a FOR loop, the IN ( ....) clause is evaluated and %%G set to a different value

    If this clause results in a single value then %%G is set equal to that value and the command is performed.

    If the clause results in a multiple values then extra parameters are implicitly defined to hold each. These are automatically assigned in alphabetical order %%H %%I %%J ...(implicit parameter definition)

    If the parameter refers to a file, then enhanced variable reference can be used to extract the filename/path/date/size.

    You can of course pick any letter of the alphabet other than %%G. but it is a good choice because it does not conflict with any of the pathname format letters (a, d, f, n, p, s, t, x) and provides the longest run of non-conflicting letters for use as implicit parameters.

PHP header(Location: ...): Force URL change in address bar

In your form element add data-ajax="false". I had the same problem using jquery mobile.

400 BAD request HTTP error code meaning?

Think about expectations.

As a client app, you expect to know if something goes wrong on the server side. If the server needs to throw an error when blah is missing or the requestedResource value is incorrect than a 400 error would be appropriate.

Variable number of arguments in C++?

It is possible now...using boost any and templates In this case, arguments type can be mixed

#include <boost/any.hpp>
#include <iostream>

#include <vector>
using boost::any_cast;

template <typename T, typename... Types> 
void Alert(T var1,Types... var2) 
{ 

    std::vector<boost::any> a(  {var1,var2...});

    for (int i = 0; i < a.size();i++)
    {

    if (a[i].type() == typeid(int))
    {
        std::cout << "int "  << boost::any_cast<int> (a[i]) << std::endl;
    }
    if (a[i].type() == typeid(double))
    {
        std::cout << "double "  << boost::any_cast<double> (a[i]) << std::endl;
    }
    if (a[i].type() == typeid(const char*))
    {
        std::cout << "char* " << boost::any_cast<const char*> (a[i]) <<std::endl;
    }
    // etc
    }

} 


void main()
{
    Alert("something",0,0,0.3);
}

How do you change video src using jQuery?

What worked for me was issuing the 'play' command after changing the source. Strangely you cannot use 'play()' through a jQuery instance so you just use getElementByID as follows:

HTML

<video id="videoplayer" width="480" height="360"></video>

JAVASCRIPT

$("#videoplayer").html('<source src="'+strSRC+'" type="'+strTYPE+'"></source>' );
document.getElementById("videoplayer").play();

How to call a function after delay in Kotlin?

You have to import the following two libraries:

import java.util.*
import kotlin.concurrent.schedule

and after that use it in this way:

Timer().schedule(10000){
    //do something
}

convert nan value to zero

Where A is your 2D array:

import numpy as np
A[np.isnan(A)] = 0

The function isnan produces a bool array indicating where the NaN values are. A boolean array can by used to index an array of the same shape. Think of it like a mask.

How to decode encrypted wordpress admin password?

just edit wp_user table with your phpmyadmin, and choose MD5 on Function field then input your new password, save it (go button). enter image description here

GitHub authentication failing over https, returning wrong email address

  • Go to Credential Manager => Windows Manager
  • Delete everything related to tfs
  • Now click on Add a generic credential and provide the following values

    (1) Internet or network adress: git:https://tfs.donamain name (2) username: your username (3) password: your password

    this should fix it

How to return only 1 row if multiple duplicate rows and still return rows that are not duplicates?

If this is a SQL question, and I understand what you are asking, (it's not entirely clear), just add distinct to the query

   Select Distinct * From TempTable

Split data frame string column into multiple columns

Since R version 3.4.0 you can use strcapture() from the utils package (included with base R installs), binding the output onto the other column(s).

out <- strcapture(
    "(.*)_and_(.*)",
    as.character(before$type),
    data.frame(type_1 = character(), type_2 = character())
)

cbind(before["attr"], out)
#   attr type_1 type_2
# 1    1    foo    bar
# 2   30    foo  bar_2
# 3    4    foo    bar
# 4    6    foo  bar_2

Getting the current date in SQL Server?

SELECT CAST(GETDATE() AS DATE)

Returns the current date with the time part removed.

DATETIMEs are not "stored in the following format". They are stored in a binary format.

SELECT CAST(GETDATE() AS BINARY(8))

The display format in the question is independent of storage.

Formatting into a particular display format should be done by your application.

IntelliJ Organize Imports

Just move your mouse over the missing view and hit keys on windows ALT + ENTER

How can I convert a .py to .exe for Python?

Python 3.6 is supported by PyInstaller.

Open a cmd window in your Python folder (open a command window and use cd or while holding shift, right click it on Windows Explorer and choose 'Open command window here'). Then just enter

pip install pyinstaller

And that's it.

The simplest way to use it is by entering on your command prompt

pyinstaller file_name.py

For more details on how to use it, take a look at this question.

Pass a javascript variable value into input type hidden value

Hidden Field :

<input type="hidden" name="year" id="year">

Script :

<script type="text/javascript">
     var year = new Date();
     document.getElementById("year").value=(year.getFullYear());
</script>

What is lazy loading in Hibernate?

Lazy Loading? Well, it simply means that child records are not fetched immediately, but automatically as soon as you try to access them.

Check if inputs are empty using jQuery

$(function() {
  var fields = $('#search_form').serializeArray();
  is_blank = true;
  for (var i = 0; i < fields.length; i++) {
    // excluded fields
    if ((fields[i].name != "locale") && (fields[i].name != "utf8")) {
      if (fields[i].value) {
        is_blank = false;
      }
    }
  }
  if (is_blank) {
    $('#filters-button').append(': OFF');
  }
  else {
    $('#filters-button').append(': ON');
  }
});

Check if all fields are empty and append ON or OFF on Filter_button

Prepare for Segue in Swift

Swift 1.2

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
            if (segue.identifier == "ShowDeal") {

                if let viewController: DealLandingViewController = segue.destinationViewController as? DealLandingViewController {
                    viewController.dealEntry = deal
                }

            }
     }

Trigger validation of all fields in Angular Form submit

I like the this approach in handling validation on button click.

  1. There is no need to invoke anything from controller,

  2. it's all handled with a directive.

on github

Converting char[] to byte[]

private static byte[] charArrayToByteArray(char[] c_array) {
        byte[] b_array = new byte[c_array.length];
        for(int i= 0; i < c_array.length; i++) {
            b_array[i] = (byte)(0xFF & (int)c_array[i]);
        }
        return b_array;
}

Find ALL tweets from a user (not just the first 3,200)

The only way to see more is to start saving them before the user's tweet count hits 3200. Services which show more than 3200 tweets have saved them in their own dbs. There's currently no way to get more than that through any Twitter API.

http://www.quora.com/Is-there-a-way-to-get-more-than-3200-tweets-from-a-twitter-user-using-Twitters-API-or-scraping

https://dev.twitter.com/discussions/276

Note from that second link: "…the 3,200 limit is for browsing the timeline only. Tweets can always be requested by their ID using the GET statuses/show/:id method."

Generating Random Passwords

Added some supplemental code to the accepted answer. It improves upon answers just using Random and allows for some password options. I also liked some of the options from the KeePass answer but did not want to include the executable in my solution.

private string RandomPassword(int length, bool includeCharacters, bool includeNumbers, bool includeUppercase, bool includeNonAlphaNumericCharacters, bool includeLookAlikes)
{
    if (length < 8 || length > 128) throw new ArgumentOutOfRangeException("length");
    if (!includeCharacters && !includeNumbers && !includeNonAlphaNumericCharacters) throw new ArgumentException("RandomPassword-Key arguments all false, no values would be returned");

    string pw = "";
    do
    {
        pw += System.Web.Security.Membership.GeneratePassword(128, 25);
        pw = RemoveCharacters(pw, includeCharacters, includeNumbers, includeUppercase, includeNonAlphaNumericCharacters, includeLookAlikes);
    } while (pw.Length < length);

    return pw.Substring(0, length);
}

private string RemoveCharacters(string passwordString, bool includeCharacters, bool includeNumbers, bool includeUppercase, bool includeNonAlphaNumericCharacters, bool includeLookAlikes)
{
    if (!includeCharacters)
    {
        var remove = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
        foreach (string r in remove)
        {
            passwordString = passwordString.Replace(r, string.Empty);
            passwordString = passwordString.Replace(r.ToUpper(), string.Empty);
        }
    }

    if (!includeNumbers)
    {
        var remove = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
        foreach (string r in remove)
            passwordString = passwordString.Replace(r, string.Empty);
    }

    if (!includeUppercase)
        passwordString = passwordString.ToLower();

    if (!includeNonAlphaNumericCharacters)
    {
        var remove = new string[] { "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "_", "+", "=", "{", "}", "[", "]", "|", "\\", ":", ";", "<", ">", "/", "?", "." };
        foreach (string r in remove)
            passwordString = passwordString.Replace(r, string.Empty);
    }

    if (!includeLookAlikes)
    {
        var remove = new string[] { "(", ")", "0", "O", "o", "1", "i", "I", "l", "|", "!", ":", ";" };
        foreach (string r in remove)
            passwordString = passwordString.Replace(r, string.Empty);
    }

    return passwordString;
}

This was the first link when I searched for generating random passwords and the following is out of scope for the current question but might be important to consider.

  • Based upon the assumption that System.Web.Security.Membership.GeneratePassword is cryptographically secure with a minimum of 20% of the characters being Non-Alphanumeric.
  • Not sure if removing characters and appending strings is considered good practice in this case and provides enough entropy.
  • Might want to consider implementing in some way with SecureString for secure password storage in memory.

What to do with branch after merge

After the merge, it's safe to delete the branch:

git branch -d branch1

Additionally, git will warn you (and refuse to delete the branch) if it thinks you didn't fully merge it yet. If you forcefully delete a branch (with git branch -D) which is not completely merged yet, you have to do some tricks to get the unmerged commits back though (see below).

There are some reasons to keep a branch around though. For example, if it's a feature branch, you may want to be able to do bugfixes on that feature still inside that branch.

If you also want to delete the branch on a remote host, you can do:

git push origin :branch1

This will forcefully delete the branch on the remote (this will not affect already checked-out repositiories though and won't prevent anyone with push access to re-push/create it).


git reflog shows the recently checked out revisions. Any branch you've had checked out in the recent repository history will also show up there. Aside from that, git fsck will be the tool of choice at any case of commit-loss in git.

How do I send a cross-domain POST request via JavaScript?

  1. Create an iFrame,
  2. put a form in it with Hidden inputs,
  3. set the form's action to the URL,
  4. Add iframe to document
  5. submit the form

Pseudocode

 var ifr = document.createElement('iframe');
 var frm = document.createElement('form');
 frm.setAttribute("action", "yoururl");
 frm.setAttribute("method", "post");

 // create hidden inputs, add them
 // not shown, but similar (create, setAttribute, appendChild)

 ifr.appendChild(frm);
 document.body.appendChild(ifr);
 frm.submit();

You probably want to style the iframe, to be hidden and absolutely positioned. Not sure cross site posting will be allowed by the browser, but if so, this is how to do it.

Remove an array element and shift the remaining ones

You can use memmove(), but you have to keep track of the array size yourself:

size_t array_size = 5;
int array[5] = {1, 2, 3, 4, 5};

// delete element at index 2
memmove(array + 2, array + 3, (array_size - 2 - 1) * sizeof(int));
array_size--;

In C++, though, it would be better to use a std::vector:

std::vector<int> array;
// initialize array...

// delete element at index 2
array.erase(array.begin() + 2);

How can one run multiple versions of PHP 5.x on a development LAMP server?

With CentOS, you can do it using a combination of fastcgi for one version of PHP, and php-fpm for the other, as described here:

https://web.archive.org/web/20130707085630/http://linuxplayer.org/2011/05/intall-multiple-version-of-php-on-one-server

Based on CentOS 5.6, for Apache only

1. Enable rpmforge and epel yum repository

wget http://packages.sw.be/rpmforge-release/rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm
wget http://download.fedora.redhat.com/pub/epel/5/x86_64/epel-release-5-4.noarch.rpm
sudo rpm -ivh rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm
sudo rpm -ivh epel-release-5-4.noarch.rpm

2. Install php-5.1

CentOS/RHEL 5.x series have php-5.1 in box, simply install it with yum, eg:

sudo yum install php php-mysql php-mbstring php-mcrypt

3. Compile and install php 5.2 and 5.3 from source

For php 5.2 and 5.3, we can find many rpm packages on the Internet. However, they all conflict with the php which comes with CentOS, so, we’d better build and install them from soure, this is not difficult, the point is to install php at different location.

However, when install php as an apache module, we can only use one version of php at the same time. If we need to run different version of php on the same server, at the same time, for example, different virtual host may need different version of php. Fortunately, the cool FastCGI and PHP-FPM can help.

Build and install php-5.2 with fastcgi enabled

1) Install required dev packages

yum install gcc libxml2-devel bzip2-devel zlib-devel \
    curl-devel libmcrypt-devel libjpeg-devel \
    libpng-devel gd-devel mysql-devel

2) Compile and install

wget http://cn.php.net/get/php-5.2.17.tar.bz2/from/this/mirror
tar -xjf php-5.2.17.tar.bz2
cd php-5.2.17
./configure --prefix=/usr/local/php52 \
    --with-config-file-path=/etc/php52 \
    --with-config-file-scan-dir=/etc/php52/php.d \
    --with-libdir=lib64 \
    --with-mysql \
    --with-mysqli \
    --enable-fastcgi \
    --enable-force-cgi-redirect \
    --enable-mbstring \
    --disable-debug \
    --disable-rpath \
    --with-bz2 \
    --with-curl \
    --with-gettext \
    --with-iconv \
    --with-openssl \
    --with-gd \
    --with-mcrypt \
    --with-pcre-regex \
    --with-zlib
make -j4 > /dev/null
sudo make install
sudo mkdir /etc/php52
sudo cp php.ini-recommended /etc/php52/php.ini

3) create a fastcgi wrapper script

create file /usr/local/php52/bin/fcgiwrapper.sh

#!/bin/bash
PHP_FCGI_MAX_REQUESTS=10000
export PHP_FCGI_MAX_REQUESTS
exec /usr/local/php52/bin/php-cgi
chmod a+x /usr/local/php52/bin/fcgiwrapper.sh
Build and install php-5.3 with fpm enabled

wget http://cn.php.net/get/php-5.3.6.tar.bz2/from/this/mirror
tar -xjf php-5.3.6.tar.bz2 
cd php-5.3.6
./configure --prefix=/usr/local/php53 \
    --with-config-file-path=/etc/php53 \
    --with-config-file-scan-dir=/etc/php53/php.d \
    --enable-fpm \
    --with-fpm-user=apache \
    --with-fpm-group=apache \
    --with-libdir=lib64 \
    --with-mysql \
    --with-mysqli \
    --enable-mbstring \
    --disable-debug \
    --disable-rpath \
    --with-bz2 \
    --with-curl \
    --with-gettext \
    --with-iconv \
    --with-openssl \
    --with-gd \
    --with-mcrypt \
    --with-pcre-regex \
    --with-zlib 

make -j4 && sudo make install
sudo mkdir /etc/php53
sudo cp php.ini-production /etc/php53/php.ini

sed -i -e 's#php_fpm_CONF=\${prefix}/etc/php-fpm.conf#php_fpm_CONF=/etc/php53/php-fpm.conf#' \
    sapi/fpm/init.d.php-fpm
sudo cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
sudo chmod a+x /etc/init.d/php-fpm
sudo /sbin/chkconfig --add php-fpm
sudo /sbin/chkconfig php-fpm on

sudo cp sapi/fpm/php-fpm.conf /etc/php53/

Configue php-fpm

Edit /etc/php53/php-fpm.conf, change some settings. This step is mainly to uncomment some settings, you can adjust the value if you like.

pid = run/php-fpm.pid
listen = 127.0.0.1:9000
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20

Then, start fpm

sudo /etc/init.d/php-fpm start

Install and setup mod_fastcgi, mod_fcgid

sudo yum install libtool httpd-devel apr-devel
wget http://www.fastcgi.com/dist/mod_fastcgi-current.tar.gz
tar -xzf mod_fastcgi-current.tar.gz
cd mod_fastcgi-2.4.6
cp Makefile.AP2 Makefile
sudo make top_dir=/usr/lib64/httpd/ install
sudo sh -c "echo 'LoadModule fastcgi_module modules/mod_fastcgi.so' > /etc/httpd/conf.d/mod_fastcgi.conf"
yum install mod_fcgid

Setup and test virtual hosts

1) Add the following line to /etc/hosts

127.0.0.1 web1.example.com web2.example.com web3.example.com

2) Create web document root and drop an index.php under it to show phpinfo switch to user root, run

mkdir /var/www/fcgi-bin
for i in {1..3}; do
    web_root=/var/www/web$i
    mkdir $web_root
    echo "<?php phpinfo(); ?>" > $web_root/index.php
done

Note: The empty /var/www/fcgi-bin directory is required, DO NOT REMOVE IT LATER

3) Create Apache config file(append to httpd.conf)

NameVirtualHost *:80

# module settings
# mod_fcgid
<IfModule mod_fcgid.c>
        idletimeout 3600
        processlifetime 7200
        maxprocesscount 17
        maxrequestsperprocess 16
        ipcconnecttimeout 60 
        ipccommtimeout 90
</IfModule>
# mod_fastcgi with php-fpm
<IfModule mod_fastcgi.c>
        FastCgiExternalServer /var/www/fcgi-bin/php-fpm -host 127.0.0.1:9000
</IfModule>


# virtual hosts...

#################################################################
#1st virtual host, use mod_php, run php-5.1
#################################################################
<VirtualHost *:80>
        ServerName web1.example.com
        DocumentRoot "/var/www/web1"

        <ifmodule mod_php5.c>
                <FilesMatch \.php$>
                        AddHandler php5-script .php
                </FilesMatch>
        </IfModule>

        <Directory "/var/www/web1">
                DirectoryIndex index.php index.html index.htm
                Options -Indexes FollowSymLinks
                Order allow,deny
                Allow from all
        </Directory>

</VirtualHost>
#################################################################
#2nd virtual host, use mod_fcgid, run php-5.2
#################################################################
<VirtualHost *:80>
        ServerName web2.example.com
        DocumentRoot "/var/www/web2"

        <IfModule mod_fcgid.c>
                AddHandler fcgid-script .php
                FCGIWrapper /usr/local/php52/bin/fcgiwrapper.sh
        </IfModule>

        <Directory "/var/www/web2">
                DirectoryIndex index.php index.html index.htm
                Options -Indexes FollowSymLinks +ExecCGI
                Order allow,deny
                Allow from all
        </Directory>

</VirtualHost>
#################################################################
#3rd virtual host, use mod_fastcgi + php-fpm, run php-5.3
#################################################################
<VirtualHost *:80>
        ServerName web3.example.com
        DocumentRoot "/var/www/web3"


        <IfModule mod_fastcgi.c>
                ScriptAlias /fcgi-bin/ /var/www/fcgi-bin/
                AddHandler php5-fastcgi .php
                Action php5-fastcgi /fcgi-bin/php-fpm
        </IfModule>

        <Directory "/var/www/web3">
                DirectoryIndex index.php index.html index.htm
                Options -Indexes FollowSymLinks +ExecCGI
                Order allow,deny
                Allow from all
        </Directory>

</VirtualHost>

4) restart apache. visit the 3 sites respectly to view phpinfo and validate the result. ie:

http://web1.example.com
http://web2.example.com
http://web3.example.com

If all OK, you can use one of the 3 virtual host as template to create new virtual host, with the desired php version.

Using malloc for allocation of multi-dimensional arrays with different row lengths

The other approach would be to allocate one contiguous chunk of memory comprising header block for pointers to rows as well as body block to store actual data in rows. Then just mark up memory by assigning addresses of memory in body to the pointers in header on per-row basis. It would look like follows:

int** 2dAlloc(int rows, int* columns) {    
    int header = rows * sizeof(int*);

    int body = 0;
    for(int i=0; i<rows; body+=columnSizes[i++]) {  
    }
    body*=sizeof(int);

    int** rowptr = (int**)malloc(header + body);

    int* buf  = (int*)(rowptr + rows);
    rowptr[0] = buf;
    int k;
    for(k = 1; k < rows; ++k) {
        rowptr[k] = rowptr[k-1] + columns[k-1];
    }
    return rowptr;
}

int main() {
    // specifying column amount on per-row basis
    int columns[] = {1,2,3};
    int rows = sizeof(columns)/sizeof(int);
    int** matrix = 2dAlloc(rows, &columns);

    // using allocated array
    for(int i = 0; i<rows; ++i) {
        for(int j = 0; j<columns[i]; ++j) {
            cout<<matrix[i][j]<<", ";
        }   
            cout<<endl;
    }

    // now it is time to get rid of allocated 
    // memory in only one call to "free"
    free matrix;
}

The advantage of this approach is elegant freeing of memory and ability to use array-like notation to access elements of the resulting 2D array.

What uses are there for "placement new"?

I have an idea too. C++ does have zero-overhead principle. But exceptions do not follow this principle, so sometimes they are turned off with compiler switch.

Let's look to this example:

#include <new>
#include <cstdio>
#include <cstdlib>

int main() {
    struct A {
        A() {
            printf("A()\n");
        }
        ~A() {
            printf("~A()\n");
        }
        char data[1000000000000000000] = {}; // some very big number
    };

    try {
        A *result = new A();
        printf("new passed: %p\n", result);
        delete result;
    } catch (std::bad_alloc) {
        printf("new failed\n");
    }
}

We allocate a big struct here, and check if allocation is successful, and delete it.

But if we have exceptions turned off, we can't use try block, and unable to handle new[] failure.

So how we can do that? Here is how:

#include <new>
#include <cstdio>
#include <cstdlib>

int main() {
    struct A {
        A() {
            printf("A()\n");
        }
        ~A() {
            printf("~A()\n");
        }
        char data[1000000000000000000] = {}; // some very big number
    };

    void *buf = malloc(sizeof(A));
    if (buf != nullptr) {
        A *result = new(buf) A();
        printf("new passed: %p\n", result);
        result->~A();
        free(result);
    } else {
        printf("new failed\n");
    }
}
  • Use simple malloc
  • Check if it is failed in a C way
  • If it successful, we use placement new
  • Manually call the destructor (we can't just call delete)
  • call free, due we called malloc

UPD @Useless wrote a comment which opened to my view the existence of new(nothrow), which should be used in this case, but not the method I wrote before. Please don't use the code I wrote before. Sorry.

How do you run JavaScript script through the Terminal?

Alternatively, if you're just looking to play around with Javascript a nice in browser option is Codecademy's Javascript Lab.

They also have a Python and Ruby IDE.

How to cast List<Object> to List<MyClass>

List<Object[]> testNovedads = crudService.createNativeQuery(
            "SELECT ID_NOVEDAD_PK, OBSERVACIONES, ID_SOLICITUD_PAGO_FK FROM DBSEGUIMIENTO.SC_NOVEDADES WHERE ID_NOVEDAD_PK < 2000");

Convertir<TestNovedad> convertir = new Convertir<TestNovedad>();
Collection<TestNovedad> novedads = convertir.toList(testNovedads, TestNovedad.class);
for (TestNovedad testNovedad : novedads) {
    System.out.println(testNovedad.toString());
}

public Collection<T> toList(List<Object[]> objects, Class<T> type) {
    Gson gson = new Gson();
    JSONObject jsonObject = new JSONObject();
    Collection<T> collection = new ArrayList<>();
    Field[] fields = TestNovedad.class.getDeclaredFields();
    for (Object[] object : objects) {
        int pos = 0;
        for (Field field : fields) {
            jsonObject.put(field.getName(), object[pos++]);
        }
        collection.add(gson.fromJson(jsonObject.toString(), type));
    }
    return collection;
}

C# - Create SQL Server table programmatically

If you don't like remembering SQL syntax, using Mig# you can simply:

var schema = new DbSchema(ConnectionString, DbPlatform.SqlServer2014);
schema.Alter(db => db.CreateTable("Customer")
     .WithPrimaryKeyColumn("Id", DbType.Int32).AsIdentity()
     .WithNotNullableColumn("First_Name", DbType.String).OfSize(50)
     .WithNotNullableColumn("Last_Name", DbType.String).OfSize(50)
     ...);

If you are not sure if it already exists, call DropIfExists before:

db.Tables["Customers"].DropIfExists();

how to reset <input type = "file">

This is the BEST solution:

input.value = ''

if(!/safari/i.test(navigator.userAgent)){
  input.type = ''
  input.type = 'file'
}

Of all the answers here this is the fastest solution. No input clone, no form reset!

I checked it in all browsers (it even has IE8 support).

In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

Louis' answer is great, but I thought I would try to sum it up succinctly:

The bang operator tells the compiler to temporarily relax the "not null" constraint that it might otherwise demand. It says to the compiler: "As the developer, I know better than you that this variable cannot be null right now".

Youtube - downloading a playlist - youtube-dl

I found the best solution after many attempts for this problem.

youtube-dl --ignore-errors --format bestaudio --extract-audio --audio-format mp3 --audio-quality 160K --output "%(title)s.%(ext)s" --yes-playlist https://www.youtube.com/playlist?list={your-youtube-playlist-id}

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

You cannot session_start(); when your buffer has already been partly sent.

This mean, if your script already sent informations (something you want, or an error report) to the client, session_start() will fail.

Commenting multiple lines in DOS batch file

@jeb

And after using this, the stderr seems to be inaccessible

No, try this:

@echo off 2>Nul 3>Nul 4>Nul

   ben ali  
   mubarak 2>&1
   gadeffi
   ..next ?

   echo hello Tunisia

  pause

But why it works?

sorry, i answer the question in frensh:

( la redirection par 3> est spécial car elle persiste, on va l'utiliser pour capturer le flux des erreurs 2> est on va le transformer en un flux persistant à l'ade de 3> ceci va nous permettre d'avoir une gestion des erreur pour tout notre environement de script..par la suite si on veux recuperer le flux 'stderr' il faut faire une autre redirection du handle 2> au handle 1> qui n'est autre que la console.. )

What does href expression <a href="javascript:;"></a> do?

The best way to always render a link properly is with the css as follows:

a {cursor: pointer !important}

One should avoid to follow un-necessary things like mentioned in the thread.

What do these three dots in React do?

That's property spread notation. It was added in ES2018 (spread for arrays/iterables was earlier, ES2015), but it's been supported in React projects for a long time via transpilation (as "JSX spread attributes" even though you could do it elsewhere, too, not just attributes).

{...this.props} spreads out the "own" enumerable properties in props as discrete properties on the Modal element you're creating. For instance, if this.props contained a: 1 and b: 2, then

<Modal {...this.props} title='Modal heading' animation={false}>

would be the same as

<Modal a={this.props.a} b={this.props.b} title='Modal heading' animation={false}>

But it's dynamic, so whatever "own" properties are in props are included.

Since children is an "own" property in props, spread will include it. So if the component where this appears had child elements, they'll be passed on to Modal. Putting child elements between the opening tag and closing tags is just syntactic sugar — the good kind — for putting a children property in the opening tag. Example:

_x000D_
_x000D_
class Example extends React.Component {_x000D_
  render() {_x000D_
    const { className, children } = this.props;_x000D_
    return (_x000D_
      <div className={className}>_x000D_
      {children}_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
ReactDOM.render(_x000D_
  [_x000D_
    <Example className="first">_x000D_
      <span>Child in first</span>_x000D_
    </Example>,_x000D_
    <Example className="second" children={<span>Child in second</span>} />_x000D_
  ],_x000D_
  document.getElementById("root")_x000D_
);
_x000D_
.first {_x000D_
  color: green;_x000D_
}_x000D_
.second {_x000D_
  color: blue;_x000D_
}
_x000D_
<div id="root"></div>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
_x000D_
_x000D_
_x000D_

Spread notation is handy not only for that use case, but for creating a new object with most (or all) of the properties of an existing object — which comes up a lot when you're updating state, since you can't modify state directly:

this.setState(prevState => {
    return {foo: {...prevState.foo, a: "updated"}};
});

That replaces this.state.foo with a new object with all the same properties as foo except the a property, which becomes "updated":

_x000D_
_x000D_
const obj = {_x000D_
  foo: {_x000D_
    a: 1,_x000D_
    b: 2,_x000D_
    c: 3_x000D_
  }_x000D_
};_x000D_
console.log("original", obj.foo);_x000D_
// Creates a NEW object and assigns it to `obj.foo`_x000D_
obj.foo = {...obj.foo, a: "updated"};_x000D_
console.log("updated", obj.foo);
_x000D_
.as-console-wrapper {_x000D_
  max-height: 100% !important;_x000D_
}
_x000D_
_x000D_
_x000D_

Why is this error, 'Sequence contains no elements', happening?

In the following line.

temp.Response = db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).First();

You are calling First but the collection returned from db.Responses.Where is empty.

Reading DataSet

TL;DR: - grab the datatable from the dataset and read from the rows property.

            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            DataColumn col = new DataColumn("Id", typeof(int));
            dt.Columns.Add(col);
            dt.Rows.Add(new object[] { 1 });
            ds.Tables.Add(dt);

            var row = ds.Tables[0].Rows[0];
            //access the ID column.  
            var id = (int) row.ItemArray[0];

A DataSet is a copy of data accessed from a database, but doesn't even require a database to use at all. It is preferred, though.

Note that if you are creating a new application, consider using an ORM, such as the Entity Framework or NHibernate, since DataSets are no longer preferred; however, they are still supported and as far as I can tell, are not going away any time soon.

If you are reading from standard dataset, then @KMC's answer is what you're looking for. The proper way to do this, though, is to create a Strongly-Typed DataSet and use that so you can take advantage of Intellisense. Assuming you are not using the Entity Framework, proceed.

If you don't already have a dedicated space for your data access layer, such as a project or an App_Data folder, I suggest you create one now. Otherwise, proceed as follows under your data project folder: Add > Add New Item > DataSet. The file created will have an .xsd extension.

You'll then need to create a DataTable. Create a DataTable (click on the file, then right click on the design window - the file has an .xsd extension - and click Add > DataTable). Create some columns (Right click on the datatable you just created > Add > Column). Finally, you'll need a table adapter to access the data. You'll need to setup a connection to your database to access data referenced in the dataset.

After you are done, after successfully referencing the DataSet in your project (using statement), you can access the DataSet with intellisense. This makes it so much easier than untyped datasets.

When possible, use Strongly-Typed DataSets instead of untyped ones. Although it is more work to create, it ends up saving you lots of time later with intellisense. You could do something like:

MyStronglyTypedDataSet trainDataSet = new MyStronglyTypedDataSet();
DataAdapterForThisDataSet dataAdapter = new DataAdapterForThisDataSet();
//code to fill the dataset 
//omitted - you'll have to either use the wizard to create data fill/retrieval
//methods or you'll use your own custom classes to fill the dataset.
if(trainDataSet.NextTrainDepartureTime > CurrentTime){
   trainDataSet.QueueNextTrain = true; //assumes QueueNextTrain is in your Strongly-Typed dataset
}
else
    //do some other work

The above example assumes that your Strongly-Typed DataSet has a column of type DateTime named NextTrainDepartureTime. Hope that helps!

How to compile and run C in sublime text 3?

The latest build of the sublime even allows the direct command instead of double quotes. Try the below code for the build system

{
    "cmd" : ["gcc $file_name -o ${file_base_name} && ./${file_base_name}"],
    "selector" : "source.c",
    "shell": true,
    "working_dir" : "$file_path",
}

Padding zeros to the left in postgreSQL

You can use the rpad and lpad functions to pad numbers to the right or to the left, respectively. Note that this does not work directly on numbers, so you'll have to use ::char or ::text to cast them:

SELECT RPAD(numcol::text, 3, '0'), -- Zero-pads to the right up to the length of 3
       LPAD(numcol::text, 3, '0'), -- Zero-pads to the left up to the length of 3
FROM   my_table

Recursive mkdir() system call on Unix

hmm I thought that mkdir -p does that?

mkdir -p this/is/a/full/path/of/stuff

How to correct "TypeError: 'NoneType' object is not subscriptable" in recursive function?

This simply means that either tree, tree[otu], or tree[otu][0] evaluates to None, and as such is not subscriptable. Most likely tree[otu] or tree[otu][0]. Track it down with some simple debugging like this:

def Ancestors (otu,tree):
    try:
        tree[otu][0][0]
    except TypeError:
        print otu, tre[otu]
        raise
    #etc...

or pdb

Css transition from display none to display block, navigation with subnav

Generally when people are trying to animate display: none what they really want is:

  1. Fade content in, and
  2. Have the item not take up space in the document when hidden

Most popular answers use visibility, which can only achieve the first goal, but luckily it's just as easy to achieve both by using position.

Since position: absolute removes the element from typing document flow spacing, you can toggle between position: absolute and position: static (global default), combined with opacity. See the below example.

_x000D_
_x000D_
.content-page {_x000D_
  position:absolute;_x000D_
  opacity: 0;_x000D_
}_x000D_
_x000D_
.content-page.active {_x000D_
  position: static;_x000D_
  opacity: 1;_x000D_
  transition: opacity 1s linear;_x000D_
}
_x000D_
_x000D_
_x000D_

How to use __doPostBack()

Here's a brief tutorial on how __doPostBack() works.

To be honest, I don't use it much; at least directly. Many server controls, (e.g., Button, LinkButton, ImageButton, parts of the GridView, etc.) use __doPostBack as their post back mechanism.

How do you change the launcher logo of an app in Android Studio?

Go to:

res > drawable > right click > show in folder > add desired logo

Then go to android manifest, edit ICON tag under application tag, use "@drawable/nameOfImage"

Could not connect to Redis at 127.0.0.1:6379: Connection refused with homebrew

I just had this same problem because I had used improper syntax in my config file. I meant to add:

maxmemory-policy allkeys-lru

to my config file, but instead only added:

allkeys-lru

which evidently prevented Redis from parsing the config file, which in turn prevented me from connecting through the cli. Fixing this syntax allowed me to connect to Redis.

Forcing a postback

By using Server.Transfer("YourCurrentPage.aspx"); we can easily acheive this and it is better than Response.Redirect(); coz Server.Transfer() will save you the round trip.

What to use instead of "addPreferencesFromResource" in a PreferenceActivity?

No alternative method is provided in the method's description because the preferred approach (as of API level 11) is to instantiate PreferenceFragment objects to load your preferences from a resource file. See the sample code here: PreferenceActivity

CSS - Overflow: Scroll; - Always show vertical scroll bar?

This will make the scroll bars always display when there is content within windows that must be scrolled to access, it applies to all windows and all apps on the Mac:

Launch System Preferences from the ? Apple menu Click on the “General” settings panel Look for ‘Show scroll bars’ and select the radiobox next to “Always” Close out of System Preferences when finished

AngularJS - Attribute directive input value change

To watch out the runtime changes in value of a custom directive, use $observe method of attrs object, instead of putting $watch inside a custom directive. Here is the documentation for the same ... $observe docs

How to check if a variable is NULL, then set it with a MySQL stored procedure?

@last_run_time is a 9.4. User-Defined Variables and last_run_time datetime one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.

Try: SELECT last_run_time;

UPDATE

Example:

/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$

CREATE PROCEDURE `sp_test`()
BEGIN
    DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
    DECLARE last_run_time DATETIME DEFAULT NULL;
    DECLARE current_run_time DATETIME DEFAULT NOW();

    -- Define the last run time
    SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);

    -- if there is no last run time found then use yesterday as starting point
    IF(last_run_time IS NULL) THEN
        SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
    END IF;

    SELECT last_run_time;

    -- Insert variables in table2
    INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$

DELIMITER ;

How to debug Javascript with IE 8

You can get more information about IE8 Developer Toolbar debugging at Debugging JScript or Debugging Script with the Developer Tools.

I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?

Converting to unix timestamps makes doing date math easier in php:

$startTime = strtotime( '2010-05-01 12:00' );
$endTime = strtotime( '2010-05-10 12:00' );

// Loop between timestamps, 24 hours at a time
for ( $i = $startTime; $i <= $endTime; $i = $i + 86400 ) {
  $thisDate = date( 'Y-m-d', $i ); // 2010-05-01, 2010-05-02, etc
}

When using PHP with a timezone having DST, make sure to add a time that is not 23:00, 00:00 or 1:00 to protect against days skipping or repeating.

How do I make Git ignore file mode (chmod) changes?

If

git config --global core.filemode false

does not work for you, do it manually:

cd into yourLovelyProject folder

cd into .git folder:

cd .git

edit the config file:

nano config

change true to false

[core]
        repositoryformatversion = 0
        filemode = true

->

[core]
        repositoryformatversion = 0
        filemode = false

save, exit, go to upper folder:

cd ..

reinit the git

git init

you are done!

iPhone system font

  1. download required .ttf file

  2. add the .ttf file under copy bundle resource, double check whether the ttf file is added under resource

  3. In info.pllist add the ttf file name as it is.

  4. now open the font book add the .ttf file in the font book, select information icon there you find the postscript name.

  5. now give the postscript name in the place of font name

Why should a Java class implement comparable?

For example when you want to have a sorted collection or map

Java stack overflow error - how to increase the stack size in Eclipse?

When the argument -Xss doesn't do the job try deleting the temporary files from:

c:\Users\{user}\AppData\Local\Temp\.

This did the trick for me.

The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly

This error is also related with a cache issue.

I had the same problem and it was solved just cleaning and building the solution again.

Call web service in excel

Yes You Can!

I worked on a project that did that (see comment). Unfortunately no code samples from that one, but googling revealed these:

How you can integrate data from several Web services using Excel and VBA

STEP BY STEP: Consuming Web Services through VBA (Excel or Word)

VBA: Consume Soap Web Services

AlertDialog styling - how to change style (color) of title, message, etc

Here's my Code to theme the alert dialog box:

<style name="alertDialog" parent="Theme.AppCompat.Dialog.Alert">
    <item name="android:background">@color/light_button_text_color</item>
    <item name="android:textColor">@android:color/black</item>
    <item name="android:textColorPrimary">@android:color/black</item>
    <item name="android:textColorSecondary">@android:color/black</item>
    <item name="android:titleTextColor" tools:targetApi="m">@android:color/black</item>
</style>

Place this code in styles.xml. In your java apply this theme as:

AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.alertDialog);

Output of the code

Display number with leading zeros

The Pythonic way to do this:

str(number).rjust(string_width, fill_char)

This way, the original string is returned unchanged if its length is greater than string_width. Example:

a = [1, 10, 100]
for num in a:
    print str(num).rjust(2, '0')

Results:

01
10
100

How to create dispatch queue in Swift 3

For Swift 3

   DispatchQueue.main.async {
        // Write your code here
    }

onChange and onSelect in DropDownList

To make a robust form, have it load in a useful state and use script to enhance its behaviour. In the following, the select has been replaced by radio buttons (makes life much easier for the user).

The "yes" option is checked by default and the select is enabled. If the user checks either radio button, the select is enabled or disabled accordingly.

<form onclick="this.mySelect1.disabled = this.becomeMember[1].checked;" ... >
  <input type="radio" name="becomeMember" checked>Yes<br>
  <input type="radio" name="becomeMember">No<br>

  <select id="mySelect1">
    <option>Dep1
    <option>Dep2
    <option>Dep3
    <option>Dep4
  </select>
  ...
</form> 

Where does Internet Explorer store saved passwords?

I found the answer. IE stores passwords in two different locations based on the password type:

  • Http-Auth: %APPDATA%\Microsoft\Credentials, in encrypted files
  • Form-based: HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\IntelliForms\Storage2, encrypted with the url

From a very good page on NirSoft.com:

Starting from version 7.0 of Internet Explorer, Microsoft completely changed the way that passwords are saved. In previous versions (4.0 - 6.0), all passwords were saved in a special location in the Registry known as the "Protected Storage". In version 7.0 of Internet Explorer, passwords are saved in different locations, depending on the type of password. Each type of passwords has some limitations in password recovery:

  • AutoComplete Passwords: These passwords are saved in the following location in the Registry: HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\IntelliForms\Storage2 The passwords are encrypted with the URL of the Web sites that asked for the passwords, and thus they can only be recovered if the URLs are stored in the history file. If you clear the history file, IE PassView won't be able to recover the passwords until you visit again the Web sites that asked for the passwords. Alternatively, you can add a list of URLs of Web sites that requires user name/password into the Web sites file (see below).

  • HTTP Authentication Passwords: These passwords are stored in the Credentials file under Documents and Settings\Application Data\Microsoft\Credentials, together with login passwords of LAN computers and other passwords. Due to security limitations, IE PassView can recover these passwords only if you have administrator rights.

In my particular case it answers the question of where; and I decided that I don't want to duplicate that. I'll continue to use CredRead/CredWrite, where the user can manage their passwords from within an established UI system in Windows.

Simple prime number generator in Python

Using generator:

def primes(num):
    if 2 <= num:
        yield 2
    for i in range(3, num + 1, 2):
        if all(i % x != 0 for x in range(3, int(math.sqrt(i) + 1))):
            yield i

Usage:

for i in primes(10):
    print(i)

2, 3, 5, 7

Find child element in AngularJS directive

jQlite (angular's "jQuery" port) doesn't support lookup by classes.

One solution would be to include jQuery in your app.

Another is using QuerySelector or QuerySelectorAll:

link: function(scope, element, attrs) {
   console.log(element[0].querySelector('.list-scrollable'))
}

We use the first item in the element array, which is the HTML element. element.eq(0) would yield the same.

FIDDLE

How can I use modulo operator (%) in JavaScript?

That would be the modulo operator, which produces the remainder of the division of two numbers.

SQL Server: How to check if CLR is enabled?

This is @Jason's answer but with simplified output

SELECT name, CASE WHEN value = 1 THEN 'YES' ELSE 'NO' END AS 'Enabled'
FROM sys.configurations WHERE name = 'clr enabled'

The above returns the following:

| name        | Enabled |
-------------------------
| clr enabled | YES     |

Tested on SQL Server 2017

Get resultset from oracle stored procedure

CREATE OR REPLACE PROCEDURE SP_Invoices(p_nameClient IN CHAR)
AS
BEGIN       
    FOR c_invoice IN 
    (
       SELECT CodeInvoice, NameClient FROM Invoice
       WHERE NameClient = p_nameClient
    )
    LOOP
        dbms_output.put_line('Code Invoice: ' || c_invoice.CodeInvoice);
        dbms_output.put_line('Name Client : ' ||  c_invoice.NameClient );
    END LOOP;
END;

Executing in SQL Developer:

BEGIN
    SP_Invoices('Perico de los palotes');
END;
-- Or:
EXEC SP_Invoices('Perico de los palotes');

Output:

> Code Invoice: 1 
> Name Client : Perico de los palotes
> Code Invoice: 2 
> Name Client : Perico de los palotes

Create GUI using Eclipse (Java)

Yes. Use WindowBuilder Pro (provided by Google). It supports SWT and Swing as well with multiple layouts (Group layout, MiGLayout etc.) It's integrated out of the box with Eclipse Indigo, but you can install plugin on previous versions (3.4/3.5/3.6):

enter image description here

How to iterate object keys using *ngFor

1.Create a custom pipe to get keys.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'keys'
})
export class KeysPipe implements PipeTransform {

  transform(value: any, args?: any): any {
    return Object.keys(value);
  }
}
  1. In angular template file, you can use *ngFor and iterate over your object object
<div class ="test" *ngFor="let key of Obj | keys">
    {{key}}
    {{Obj[key].property}
<div>

add id to dynamically created <div>

If I got you correctly, it is as easy as

cartDiv.id = "someID";

No need for jQuery.

Have a look at the properties of a DOM Element.

For classes it is the same:

cartDiv.className = "classes here";

But note that this will overwrite already existing class names. If you want to add and remove classes dynamically, you either have to use jQuery or write your own function that does some string replacement.

How to get all the values of input array element jquery

You can use .map().

Pass each element in the current matched set through a function, producing a new jQuery object containing the return value.

As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array.

Use

var arr = $('input[name="pname[]"]').map(function () {
    return this.value; // $(this).val()
}).get();

Backup a single table with its data from a database in sql server 2008

Put the table in its own filegroup. You can then use regular SQL Server built in backup to backup the filegroup in which in effect backs up the table.

To backup a filegroup see: https://docs.microsoft.com/en-us/sql/relational-databases/backup-restore/back-up-files-and-filegroups-sql-server

To create a table on a non-default filegroup (its easy) see: Create a table on a filegroup other than the default

C - split string into an array of strings

Since you've already looked into strtok just continue down the same path and split your string using space (' ') as a delimiter, then use something as realloc to increase the size of the array containing the elements to be passed to execvp.

See the below example, but keep in mind that strtok will modify the string passed to it. If you don't want this to happen you are required to make a copy of the original string, using strcpy or similar function.

char    str[]= "ls -l";
char ** res  = NULL;
char *  p    = strtok (str, " ");
int n_spaces = 0, i;


/* split string and append tokens to 'res' */

while (p) {
  res = realloc (res, sizeof (char*) * ++n_spaces);

  if (res == NULL)
    exit (-1); /* memory allocation failed */

  res[n_spaces-1] = p;

  p = strtok (NULL, " ");
}

/* realloc one extra element for the last NULL */

res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = 0;

/* print the result */

for (i = 0; i < (n_spaces+1); ++i)
  printf ("res[%d] = %s\n", i, res[i]);

/* free the memory allocated */

free (res);

res[0] = ls
res[1] = -l
res[2] = (null)

Simple Android RecyclerView example

Minimal Recycler view ready to use Kotlin template for:

  • Vertical layout
  • A single TextView on each row
  • Responds to click events (Single and LongPress)

I know this is an old thread and so are answers here. Adding this answer for future reference:

Add a recycle view in your layout

   <android.support.v7.widget.RecyclerView
            android:id="@+id/wifiList"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
           /> 

Create a layout to display list items (list_item.xml)

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <LinearLayout
        android:padding="5dp"
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_height="wrap_content">

        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/ssid"
            android:text="@string/app_name"
            android:layout_width="match_parent"
            android:textSize="17sp"
            android:layout_height="wrap_content" />

    </LinearLayout>

</android.support.v7.widget.CardView>

Now create a minimal Adapter to hold data, code here is self explanatory

 class WifiAdapter(private val wifiList: ArrayList<ScanResult>) : RecyclerView.Adapter<WifiAdapter.ViewHolder>() {

     // holder class to hold reference
    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        //get view reference
        var ssid: TextView = view.findViewById(R.id.ssid) as TextView
    }

     override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
         // create view holder to hold reference
         return ViewHolder( LayoutInflater.from(parent.context).inflate(R.layout.list_item, parent, false))
     }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        //set values
        holder.ssid.text =  wifiList[position].SSID
    }

    override fun getItemCount(): Int {
        return wifiList.size
    }
      // update your data
     fun updateData(scanResult: ArrayList<ScanResult>) {
         wifiList.clear()
         notifyDataSetChanged()
         wifiList.addAll(scanResult)
         notifyDataSetChanged()

     }
 }

Add this class to handle Single click and long click events on List Items

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {

    public interface ClickListener {
        void onClick(View view, int position);

        void onLongClick(View view, RecyclerView recyclerView, int position);

    }
    private GestureDetector gestureDetector;
    private ClickListener clickListener;

    public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
        this.clickListener = clickListener;
        gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                if (child != null && clickListener != null) {
                    clickListener.onLongClick(child,recyclerView,  recyclerView.getChildPosition(child));
                }
            }
        });
    }


    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
        View child = rv.findChildViewUnder(e.getX(), e.getY());
        if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
            clickListener.onClick(child, rv.getChildPosition(child));
        }
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView rv, MotionEvent e) {

    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }

Lastly Set your adapter to Recycler View and add Touch Listener to start intercepting touch event for single or double tap on list items

    wifiAdapter = WifiAdapter(ArrayList())

    wifiList.apply {
        // vertical layout
        layoutManager = LinearLayoutManager(applicationContext)
        // set adapter
        adapter = wifiAdapter

        // Touch handling
        wifiList.addOnItemTouchListener(RecyclerTouchListener(applicationContext, wifiList, object : RecyclerTouchListener.ClickListener {
            override fun onClick(view: View?, position: Int) {
                Toast.makeText(applicationContext, "RV OnCLickj " + position, Toast.LENGTH_SHORT).show()
            }

            override fun onLongClick(view: View, recyclerView: RecyclerView, position: Int) {
                Toast.makeText(applicationContext, "RV OnLongCLickj " + position, Toast.LENGTH_SHORT).show()
            }
        }
        ))
    }

Bonus ; Update Data

wifiAdapter.updateData(mScanResults as ArrayList<ScanResult>)

Result:

enter image description here

Return sql rows where field contains ONLY non-alphanumeric characters

This will not work correctly, e.g. abcÑxyz will pass thru this as it has a,b,c... you need to work with Collate or check each byte.

What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?

INNER JOIN gets all records that are common between both tables based on the supplied ON clause.

LEFT JOIN gets all records from the LEFT linked and the related record from the right table ,but if you have selected some columns from the RIGHT table, if there is no related records, these columns will contain NULL.

RIGHT JOIN is like the above but gets all records in the RIGHT table.

FULL JOIN gets all records from both tables and puts NULL in the columns where related records do not exist in the opposite table.

How to get memory usage at runtime using C++?

On linux, if you can afford the run time cost (for debugging), you can use valgrind with the massif tool:

http://valgrind.org/docs/manual/ms-manual.html

It is heavy weight, but very useful.

How to create an empty DataFrame with a specified schema?

This is helpful for testing purposes.

Seq.empty[String].toDF()

Changing fonts in ggplot2

A simple answer if you don't want to install anything new

To change all the fonts in your plot plot + theme(text=element_text(family="mono")) Where mono is your chosen font.

List of default font options:

  • mono
  • sans
  • serif
  • Courier
  • Helvetica
  • Times
  • AvantGarde
  • Bookman
  • Helvetica-Narrow
  • NewCenturySchoolbook
  • Palatino
  • URWGothic
  • URWBookman
  • NimbusMon
  • URWHelvetica
  • NimbusSan
  • NimbusSanCond
  • CenturySch
  • URWPalladio
  • URWTimes
  • NimbusRom

R doesn't have great font coverage and, as Mike Wise points out, R uses different names for common fonts.

This page goes through the default fonts in detail.

Running code after Spring Boot starts

I really like the suggestion for usage of the EventListener annotation by @cahen (https://stackoverflow.com/a/44923402/9122660) since it is very clean. Unfortunately I could not get this to work in a Spring + Kotlin setup. What does work for Kotlin is adding the class as a method parameter:

@EventListener 
fun doSomethingAfterStartup(event: ApplicationReadyEvent) {
    System.out.println("hello world, I have just started up");
}

How do you create vectors with specific intervals in R?

Usually, we want to divide our vector into a number of intervals. In this case, you can use a function where (a) is a vector and (b) is the number of intervals. (Let's suppose you want 4 intervals)

a <- 1:10
b <- 4

FunctionIntervalM <- function(a,b) {
  seq(from=min(a), to = max(a), by = (max(a)-min(a))/b)
}

FunctionIntervalM(a,b)
# 1.00  3.25  5.50  7.75 10.00

Therefore you have 4 intervals:

1.00 - 3.25 
3.25 - 5.50
5.50 - 7.75
7.75 - 10.00

You can also use a cut function

  cut(a, 4)

# (0.991,3.25] (0.991,3.25] (0.991,3.25] (3.25,5.5]   (3.25,5.5]   (5.5,7.75]  
# (5.5,7.75]   (7.75,10]    (7.75,10]    (7.75,10]   
#Levels: (0.991,3.25] (3.25,5.5] (5.5,7.75] (7.75,10]

How to convert a private key to an RSA private key?

This may be of some help (do not literally write out the backslashes '\' in the commands, they are meant to indicate that "everything has to be on one line"):

Which Command to Apply When

It seems that all the commands (in grey) take any type of key file (in green) as "in" argument. Which is nice.

Here are the commands again for easier copy-pasting:

openssl rsa                                                -in $FF -out $TF
openssl rsa -aes256                                        -in $FF -out $TF
openssl pkcs8 -topk8 -nocrypt                              -in $FF -out $TF
openssl pkcs8 -topk8 -v2 aes-256-cbc -v2prf hmacWithSHA256 -in $FF -out $TF

and

openssl rsa -check -in $FF
openssl rsa -text  -in $FF

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

I had a similar issue from the console after building a Jar in Intellij. Using the Java configuration to update to a newer version (Windows -> Configure Java -> Update -> Update Now) didn't work and stuck at version 1.8 (Java 8).

To switch to a more recent version locally I had to install the Java 15 JDK from https://www.oracle.com/uk/java/technologies/javase-jdk15-downloads.html and add that to my Java runtime environment settings.

Java Runtime Environment Settings

SQL Logic Operator Precedence: And and Or

  1. Arithmetic operators
  2. Concatenation operator
  3. Comparison conditions
  4. IS [NOT] NULL, LIKE, [NOT] IN
  5. [NOT] BETWEEN
  6. Not equal to
  7. NOT logical condition
  8. AND logical condition
  9. OR logical condition

You can use parentheses to override rules of precedence.

Is it possible to hide the cursor in a webpage using CSS or Javascript?

If you want to hide the cursor in the entire webpage, using body will not work unless it covers the entire visible page, which is not always the case. To make sure the cursor is hidden everywhere in the page, use:

document.documentElement.style.cursor = 'none';

To reenable it:

document.documentElement.style.cursor = 'auto';

The analogue with static CSS notation is in the answer by Pavel Salaquarda (in essence: html * {cursor:none})

How to get the first five character of a String

I use:

var firstFive = stringValue?.Substring(0, stringValue.Length >= 5 ? 5 : customAlias.Length);

or alternative if you want to check for Whitespace too (instead of only Null):

var firstFive = !String.IsNullOrWhiteSpace(stringValue) && stringValue.Length >= 5 ? stringValue.Substring(0, 5) : stringValue

Rerender view on browser resize with React

Wanted to share this pretty cool thing I just found using window.matchMedia

const mq = window.matchMedia('(max-width: 768px)');

  useEffect(() => {
    // initial check to toggle something on or off
    toggle();

    // returns true when window is <= 768px
    mq.addListener(toggle);

    // unmount cleanup handler
    return () => mq.removeListener(toggle);
  }, []);

  // toggle something based on matchMedia event
  const toggle = () => {
    if (mq.matches) {
      // do something here
    } else {
      // do something here
    }
  };

.matches will return true or false if the window is higher or lower than the specified max-width value, this means there is no need to throttle the listener, as the matchMedia only fires one time when the boolean changes.

My code can easily be adjusted to include useState to save the boolean matchMedia returns, and use it to conditionally render a component, fire action etc.

Python Requests - No connection adapters

You need to include the protocol scheme:

'http://192.168.1.61:8080/api/call'

Without the http:// part, requests has no idea how to connect to the remote server.

Note that the protocol scheme must be all lowercase; if your URL starts with HTTP:// for example, it won’t find the http:// connection adapter either.

Syntax behind sorted(key=lambda: ...)

Simple and not time consuming answer with an example relevant to the question asked Follow this example:

 user = [{"name": "Dough", "age": 55}, 
            {"name": "Ben", "age": 44}, 
            {"name": "Citrus", "age": 33},
            {"name": "Abdullah", "age":22},
            ]
    print(sorted(user, key=lambda el: el["name"]))
    print(sorted(user, key= lambda y: y["age"]))

Look at the names in the list, they starts with D, B, C and A. And if you notice the ages, they are 55, 44, 33 and 22. The first print code

print(sorted(user, key=lambda el: el["name"]))

Results to:

[{'name': 'Abdullah', 'age': 22}, 
{'name': 'Ben', 'age': 44}, 
{'name': 'Citrus', 'age': 33}, 
{'name': 'Dough', 'age': 55}]

sorts the name, because by key=lambda el: el["name"] we are sorting the names and the names return in alphabetical order.

The second print code

print(sorted(user, key= lambda y: y["age"]))

Result:

[{'name': 'Abdullah', 'age': 22},
 {'name': 'Citrus', 'age': 33},
 {'name': 'Ben', 'age': 44}, 
 {'name': 'Dough', 'age': 55}]

sorts by age, and hence the list returns by ascending order of age.

Try this code for better understanding.

JavaScript: get code to run every minute

Using setInterval:

setInterval(function() {
    // your code goes here...
}, 60 * 1000); // 60 * 1000 milsec

The function returns an id you can clear your interval with clearInterval:

var timerID = setInterval(function() {
    // your code goes here...
}, 60 * 1000); 

clearInterval(timerID); // The setInterval it cleared and doesn't run anymore.

A "sister" function is setTimeout/clearTimeout look them up.


If you want to run a function on page init and then 60 seconds after, 120 sec after, ...:

function fn60sec() {
    // runs every 60 sec and runs on init.
}
fn60sec();
setInterval(fn60sec, 60*1000);

How to get text from each cell of an HTML table?

Here's a C# example I just cooked up, loosely based on the answer using CSS selectors, hopefully of use to others for seeing how to setup a ReadOnlyCollection of table rows and iterate over it in MS land at least. I'm looking through a collection of table rows to find a row with an OriginatorsRef (just a string) and a TD with an image that contains a title attribute with Overdue by in it:

    public ReadOnlyCollection<IWebElement> GetTableRows()
    {
        this.iwebElement = GetElement();
        return this.iwebElement.FindElements(By.CssSelector("tbody tr"));
    }

And within my main code:

        ...
        ReadOnlyCollection<IWebElement> TableRows;
        TableRows = f.Grid_Fault.GetTableRows();

        foreach (IWebElement row in TableRows)
        {
            if (row.Text.Contains(CustomTestContext.Current.OriginatorsRef) &&
              row.FindElements(By.CssSelector("td img[title*='Overdue by']")).Count > 0)
                return true;
        }

How to insert an object in an ArrayList at a specific position

You must handle ArrayIndexOutOfBounds by yourself when adding to a certain position.

For convenience, you may use this extension function in Kotlin

/**
 * Adds an [element] to index [index] or to the end of the List in case [index] is out of bounds
 */
fun <T> MutableList<T>.insert(index: Int, element: T) {
    if (index <= size) {
        add(index, element)
    } else {
        add(element)
    }
}

How can I determine the character encoding of an excel file?

For Excel 2010 it should be UTF-8. Instruction by MS :
http://msdn.microsoft.com/en-us/library/bb507946:

"The basic document structure of a SpreadsheetML document consists of the Sheets and Sheet elements, which reference the worksheets in the Workbook. A separate XML file is created for each Worksheet. For example, the SpreadsheetML for a workbook that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
<workbook xmlns=http://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
    <sheets>
        <sheet name="MySheet1" sheetId="1" r:id="rId1" /> 
        <sheet name="MySheet2" sheetId="2" r:id="rId2" /> 
    </sheets>
</workbook>

The worksheet XML files contain one or more block level elements such as SheetData. sheetData represents the cell table and contains one or more Row elements. A row contains one or more Cell elements. Each cell contains a CellValue element that represents the value of the cell. For example, the SpreadsheetML for the first worksheet in a workbook, that only has the value 100 in cell A1, is located in the Sheet1.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" ?> 
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <sheetData>
        <row r="1">
            <c r="A1">
                <v>100</v> 
            </c>
        </row>
    </sheetData>
</worksheet>

"

Detection of cell encodings:

https://metacpan.org/pod/Spreadsheet::ParseExcel::Cell

http://forums.asp.net/t/1608228.aspx/1

await vs Task.Wait - Deadlock?

Wait and await - while similar conceptually - are actually completely different.

Wait will synchronously block until the task completes. So the current thread is literally blocked waiting for the task to complete. As a general rule, you should use "async all the way down"; that is, don't block on async code. On my blog, I go into the details of how blocking in asynchronous code causes deadlock.

await will asynchronously wait until the task completes. This means the current method is "paused" (its state is captured) and the method returns an incomplete task to its caller. Later, when the await expression completes, the remainder of the method is scheduled as a continuation.

You also mentioned a "cooperative block", by which I assume you mean a task that you're Waiting on may execute on the waiting thread. There are situations where this can happen, but it's an optimization. There are many situations where it can't happen, like if the task is for another scheduler, or if it's already started or if it's a non-code task (such as in your code example: Wait cannot execute the Delay task inline because there's no code for it).

You may find my async / await intro helpful.

How to decode viewstate

Here is the source code for a ViewState visualizer from Scott Mitchell's article on ViewState (25 pages)

using System;
using System.Collections;
using System.Text;
using System.IO;
using System.Web.UI;


namespace ViewStateArticle.ExtendedPageClasses
{
    /// <summary>
    /// Parses the view state, constructing a viaully-accessible object graph.
    /// </summary>
    public class ViewStateParser
    {
        // private member variables
        private TextWriter tw;
        private string indentString = "   ";

        #region Constructor
        /// <summary>
        /// Creates a new ViewStateParser instance, specifying the TextWriter to emit the output to.
        /// </summary>
        public ViewStateParser(TextWriter writer)
        {
            tw = writer;
        }
        #endregion

        #region Methods
        #region ParseViewStateGraph Methods
        /// <summary>
        /// Emits a readable version of the view state to the TextWriter passed into the object's constructor.
        /// </summary>
        /// <param name="viewState">The view state object to start parsing at.</param>
        public virtual void ParseViewStateGraph(object viewState)
        {
            ParseViewStateGraph(viewState, 0, string.Empty);    
        }

        /// <summary>
        /// Emits a readable version of the view state to the TextWriter passed into the object's constructor.
        /// </summary>
        /// <param name="viewStateAsString">A base-64 encoded representation of the view state to parse.</param>
        public virtual void ParseViewStateGraph(string viewStateAsString)
        {
            // First, deserialize the string into a Triplet
            LosFormatter los = new LosFormatter();
            object viewState = los.Deserialize(viewStateAsString);

            ParseViewStateGraph(viewState, 0, string.Empty);    
        }

        /// <summary>
        /// Recursively parses the view state.
        /// </summary>
        /// <param name="node">The current view state node.</param>
        /// <param name="depth">The "depth" of the view state tree.</param>
        /// <param name="label">A label to display in the emitted output next to the current node.</param>
        protected virtual void ParseViewStateGraph(object node, int depth, string label)
        {
            tw.Write(System.Environment.NewLine);

            if (node == null)
            {
                tw.Write(String.Concat(Indent(depth), label, "NODE IS NULL"));
            } 
            else if (node is Triplet)
            {
                tw.Write(String.Concat(Indent(depth), label, "TRIPLET"));
                ParseViewStateGraph(((Triplet) node).First, depth+1, "First: ");
                ParseViewStateGraph(((Triplet) node).Second, depth+1, "Second: ");
                ParseViewStateGraph(((Triplet) node).Third, depth+1, "Third: ");
            }
            else if (node is Pair)
            {
                tw.Write(String.Concat(Indent(depth), label, "PAIR"));
                ParseViewStateGraph(((Pair) node).First, depth+1, "First: ");
                ParseViewStateGraph(((Pair) node).Second, depth+1, "Second: ");
            }
            else if (node is ArrayList)
            {
                tw.Write(String.Concat(Indent(depth), label, "ARRAYLIST"));

                // display array values
                for (int i = 0; i < ((ArrayList) node).Count; i++)
                    ParseViewStateGraph(((ArrayList) node)[i], depth+1, String.Format("({0}) ", i));
            }
            else if (node.GetType().IsArray)
            {
                tw.Write(String.Concat(Indent(depth), label, "ARRAY "));
                tw.Write(String.Concat("(", node.GetType().ToString(), ")"));
                IEnumerator e = ((Array) node).GetEnumerator();
                int count = 0;
                while (e.MoveNext())
                    ParseViewStateGraph(e.Current, depth+1, String.Format("({0}) ", count++));
            }
            else if (node.GetType().IsPrimitive || node is string)
            {
                tw.Write(String.Concat(Indent(depth), label));
                tw.Write(node.ToString() + " (" + node.GetType().ToString() + ")");
            }
            else
            {
                tw.Write(String.Concat(Indent(depth), label, "OTHER - "));
                tw.Write(node.GetType().ToString());
            }
        }
        #endregion

        /// <summary>
        /// Returns a string containing the <see cref="IndentString"/> property value a specified number of times.
        /// </summary>
        /// <param name="depth">The number of times to repeat the <see cref="IndentString"/> property.</param>
        /// <returns>A string containing the <see cref="IndentString"/> property value a specified number of times.</returns>
        protected virtual string Indent(int depth)
        {
            StringBuilder sb = new StringBuilder(IndentString.Length * depth);
            for (int i = 0; i < depth; i++)
                sb.Append(IndentString);

            return sb.ToString();
        }
        #endregion

        #region Properties
        /// <summary>
        /// Specifies the indentation to use for each level when displaying the object graph.
        /// </summary>
        /// <value>A string value; the default is three blank spaces.</value>
        public string IndentString
        {
            get
            {
                return indentString;
            }
            set
            {
                indentString = value;
            }
        }
        #endregion
    }
}

And here's a simple page to read the viewstate from a textbox and graph it using the above code

private void btnParse_Click(object sender, System.EventArgs e)
        {
            // parse the viewState
            StringWriter writer = new StringWriter();
            ViewStateParser p = new ViewStateParser(writer);

            p.ParseViewStateGraph(txtViewState.Text);
            ltlViewState.Text = writer.ToString();
        }

Retrieve WordPress root directory path?

   Please try this for get the url of root file.

First Way:

 $path = get_home_path();
   print "Path: ".$path; 
// Return "Path: /var/www/htdocs/" or

// "Path: /var/www/htdocs/wordpress/" if it is subfolder

Second Way:

And you can also use 

    "ABSPATH"

this constant is define in wordpress config file.

How to check if a string "StartsWith" another string?

The best performant solution is to stop using library calls and just recognize that you're working with two arrays. A hand-rolled implementation is both short and also faster than every other solution I've seen here.

function startsWith2(str, prefix) {
    if (str.length < prefix.length)
        return false;
    for (var i = prefix.length - 1; (i >= 0) && (str[i] === prefix[i]); --i)
        continue;
    return i < 0;
}

For performance comparisons (success and failure), see http://jsperf.com/startswith2/4. (Make sure you check for later versions that may have trumped mine.)

php codeigniter count rows

This is what is did that solved the same problem. I solved it by creating a function that returns the query result thus:

function getUsers(){
$query = $this->db->get('users');
return $query->result();
}

//The above code can go in the user_model or whatever your model is.

This allows me to use one function for the result and number of returned rows.

Use this code below in your contoller where you need the count as well as the result array().

//This gives you the user count using the count function which returns and integer of the exact rows returned from the query.
$this->data['user_count'] = count($this->user_model->getUsers());

//This gives you the returned result array.
$this->data['users'] = $this->user_model->getUsers();

I hope this helps.

Best way to replace multiple characters in a string?

>>> string="abc&def#ghi"
>>> for ch in ['&','#']:
...   if ch in string:
...      string=string.replace(ch,"\\"+ch)
...
>>> print string
abc\&def\#ghi

Why should the static field be accessed in a static way?

Because ... it (MILLISECONDS) is a static field (hiding in an enumeration, but that's what it is) ... however it is being invoked upon an instance of the given type (but see below as this isn't really true1).

javac will "accept" that, but it should really be MyUnits.MILLISECONDS (or non-prefixed in the applicable scope).

1 Actually, javac "rewrites" the code to the preferred form -- if m happened to be null it would not throw an NPE at run-time -- it is never actually invoked upon the instance).

Happy coding.


I'm not really seeing how the question title fits in with the rest :-) More accurate and specialized titles increase the likely hood the question/answers can benefit other programmers.

Selenium WebDriver and DropDown Boxes

Try the following:

import org.openqa.selenium.support.ui.Select;

Select droplist = new Select(driver.findElement(By.Id("selection")));   
droplist.selectByVisibleText("Germany");

Something like 'contains any' for Java set?

There's a bit rough method to do that. If and only if the A set contains some B's element than the call

A.removeAll(B)

will modify the A set. In this situation removeAll will return true (As stated at removeAll docs). But probably you don't want to modify the A set so you may think to act on a copy, like this way:

new HashSet(A).removeAll(B)

and the returning value will be true if the sets are not distinct, that is they have non-empty intersection.

Also see Apache Commons Collections

Android Studio - local path doesn't exist

like wrote here:

I just ran into this problem, even without transferring from Eclipse, and was frustrated because I kept showing no compile or packageDebug errors. Somehow it all fixes itself if you clean and THEN run packageDebug. Don't worry about the deprecated method statement - it seems to be a generic notice to developers.

Open up a commandline, and in your project's root directory, run:

./gradlew clean packageDebug

Obviously, if either of these steps shows errors, you should fix those...But when they both succeed you should now be able to find the apk when you navigate the local path -- and even better, your program should install/run on the device/emulator!

How to show a dialog to confirm that the user wishes to exit an Android Activity?

@Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
           .setMessage("Are you sure you want to exit?")
           .setCancelable(false)
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   ExampleActivity.super.onBackPressed();
               }
           })
           .setNegativeButton("No", null)
           .show();
}

How to get an MD5 checksum in PowerShell

This site has an example: Using Powershell for MD5 Checksums. It uses the .NET framework to instantiate an instance of the MD5 hash algorithm to calculate the hash.

Here's the code from the article, incorporating Stephen's comment:

param
(
  $file
)

$algo = [System.Security.Cryptography.HashAlgorithm]::Create("MD5")
$stream = New-Object System.IO.FileStream($Path, [System.IO.FileMode]::Open,
    [System.IO.FileAccess]::Read)

$md5StringBuilder = New-Object System.Text.StringBuilder
$algo.ComputeHash($stream) | % { [void] $md5StringBuilder.Append($_.ToString("x2")) }
$md5StringBuilder.ToString()

$stream.Dispose()

JUnit 5: How to assert an exception is thrown?

Actually I think there is a error in the documentation for this particular example. The method that is intended is expectThrows

public static void assertThrows(
public static <T extends Throwable> T expectThrows(