Programs & Examples On #Qwebpage

The QWebPage class, part of the Qt framework, provides an object to view and edit web documents.

Local variable referenced before assignment?

As the Python interpreter reads the definition of a function (or, I think, even a block of indented code), all variables that are assigned to inside the function are added to the locals for that function. If a local does not have a definition before an assignment, the Python interpreter does not know what to do, so it throws this error.

The solution here is to add

global feed

to your function (usually near the top) to indicate to the interpreter that the feed variable is not local to this function.

Using partial views in ASP.net MVC 4

Change the code where you load the partial view to:

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

This is because the partial view is expecting a Note but is getting passed the model of the parent view which is the IEnumerable

How can I simulate an anchor click via jquery?

Do you need to fake an anchor click? From the thickbox site:

ThickBox can be invoked from a link element, input element (typically a button), and the area element (image maps).

If that is acceptable it should be as easy as putting the thickbox class on the input itself:

<input id="thickboxButton" type="button" class="thickbox" value="Click me">

If not, I would recommend using Firebug and placing a breakpoint in the onclick method of the anchor element to see if it's only triggered on the first click.

Edit:

Okay, I had to try it for myself and for me pretty much exactly your code worked in both Chrome and Firefox:

<html>
<head>
<link rel="stylesheet" href="thickbox.css" type="text/css" media="screen" />
</head>
<body>
<script src="jquery-latest.pack.js" type="text/javascript"></script>
<script src="thickbox.js" type="text/javascript"></script>
<input onclick="$('#thickboxId').click();" type="button" value="Click me">
<a id="thickboxId" href="myScript.php" class="thickbox" title="">Link</a>
</body>
</html>

The window pop ups no matter if I click the input or the anchor element. If the above code works for you, I suggest your error lies elsewhere and that you try to isolate the problem.

Another possibly is that we are using different versions of jquery/thickbox. I am using what I got from the thickbox page - jquery 1.3.2 and thickbox 3.1.

Non-recursive depth first search algorithm

If you have pointers to parent nodes, you can do it without additional memory.

def dfs(root):
    node = root
    while True:
        visit(node)
        if node.first_child:
            node = node.first_child      # walk down
        else:
            while not node.next_sibling:
                if node is root:
                    return
                node = node.parent       # walk up ...
            node = node.next_sibling     # ... and right

Note that if the child nodes are stored as an array rather than through sibling pointers, the next sibling can be found as:

def next_sibling(node):
    try:
        i =    node.parent.child_nodes.index(node)
        return node.parent.child_nodes[i+1]
    except (IndexError, AttributeError):
        return None

How to sleep for five seconds in a batch file/cmd

One hack is to (mis)use the ping command:

ping 127.0.0.1 -n 6 > nul

Explanation:

  • ping is a system utility that sends ping requests. ping is available on all versions of Windows.
  • 127.0.0.1 is the IP address of localhost. This IP address is guaranteed to always resolve, be reachable, and immediately respond to pings.
  • -n 6 specifies that there are to be 6 pings. There is a 1s delay between each ping, so for a 5s delay you need to send 6 pings.
  • > nul suppress the output of ping, by redirecting it to nul.

How do I escape the wildcard/asterisk character in bash?

It may be worth getting into the habit of using printf rather then echo on the command line.

In this example it doesn't give much benefit but it can be more useful with more complex output.

FOO="BAR * BAR"
printf %s "$FOO"

How to return a file (FileContentResult) in ASP.NET WebAPI

If you want to return IHttpActionResult you can do it like this:

[HttpGet]
public IHttpActionResult Test()
{
    var stream = new MemoryStream();

    var result = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new ByteArrayContent(stream.GetBuffer())
    };
    result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = "test.pdf"
    };
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

    var response = ResponseMessage(result);

    return response;
}

How does one use glide to download an image into a bitmap?

If you want to assign dynamic bitmap image to bitmap variables

Example for kotlin

backgroundImage = Glide.with(applicationContext).asBitmap().load(PresignedUrl().getUrl(items!![position].img)).into(100, 100).get();

The above answers did not work for me

.asBitmap should be before the .load("http://....")

Example to use shared_ptr?

Using a vector of shared_ptr removes the possibility of leaking memory because you forgot to walk the vector and call delete on each element. Let's walk through a slightly modified version of the example line-by-line.

typedef boost::shared_ptr<gate> gate_ptr;

Create an alias for the shared pointer type. This avoids the ugliness in the C++ language that results from typing std::vector<boost::shared_ptr<gate> > and forgetting the space between the closing greater-than signs.

    std::vector<gate_ptr> vec;

Creates an empty vector of boost::shared_ptr<gate> objects.

    gate_ptr ptr(new ANDgate);

Allocate a new ANDgate instance and store it into a shared_ptr. The reason for doing this separately is to prevent a problem that can occur if an operation throws. This isn't possible in this example. The Boost shared_ptr "Best Practices" explain why it is a best practice to allocate into a free-standing object instead of a temporary.

    vec.push_back(ptr);

This creates a new shared pointer in the vector and copies ptr into it. The reference counting in the guts of shared_ptr ensures that the allocated object inside of ptr is safely transferred into the vector.

What is not explained is that the destructor for shared_ptr<gate> ensures that the allocated memory is deleted. This is where the memory leak is avoided. The destructor for std::vector<T> ensures that the destructor for T is called for every element stored in the vector. However, the destructor for a pointer (e.g., gate*) does not delete the memory that you had allocated. That is what you are trying to avoid by using shared_ptr or ptr_vector.

AccessDenied for ListObjects for S3 bucket when permissions are s3:*

I had this issue my requirement i wanted to allow user to write to specific path

{
            "Sid": "raspiiotallowspecificBucket",
            "Effect": "Allow",
            "Action": [
                "s3:GetObject",
                "s3:PutObject",
                "s3:ListBucket"
            ],
            "Resource": [
                "arn:aws:s3:::<bucketname>/scripts",
                "arn:aws:s3:::<bucketname>/scripts/*"
            ]
        },

and problem was solved with this change

{
            "Sid": "raspiiotallowspecificBucket",
            "Effect": "Allow",
            "Action": [
                "s3:GetObject",
                "s3:PutObject",
                "s3:ListBucket"
            ],
            "Resource": [
                "arn:aws:s3:::<bucketname>",
                "arn:aws:s3:::<bucketname>/*"
            ]
        },

Android: show soft keyboard automatically when focus is on an EditText

Well, this is a pretty old post, still there is something to add.
These are 2 simple methods that help me to keep keyboard under control and they work just perfect:

Show keyboard

public void showKeyboard() {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    View v = getCurrentFocus();
    if (v != null)
        imm.showSoftInput(v, 0);
}

Hide keyboard

public void hideKeyboard() {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    View v = getCurrentFocus();
    if (v != null)
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}

How to get first and last day of previous month (with timestamp) in SQL Server

Here's a fairly straight forward and dynamic way. For last month's last day, subtract the current numeric day from today's date. For first day of last month, use the same code, just repeat subtracting the numeric day from the prior result and add 1.

declare @PriorEOM as datetime
declare @PriorFOM as datetime

Set @PriorEOM = dateadd(day,-day(getdate()),getdate())

Set @PriorFOM = dateadd(day,-day(@PriorEOM) + 1,@PriorEOM)

Print @PriorEOM
Print @PriorFOM

A network-related or instance-specific error occurred while establishing a connection to SQL Server

Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.

  1. Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .

  2. if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .

  3. if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .

  4. after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).

  5. if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.

  6. If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.

  7. If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.

  8. If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property. enter image description here

    1. Restart your sql server instance after making any changes in property as some changes will require restart.

if you further face any difficulty then you need to provide more information about your web site and sql server .

Failing to run jar file from command line: “no main manifest attribute”

Try to run

java -cp ScrumTimeCaptureMaintenence.jar Main

What is the purpose of using WHERE 1=1 in SQL statements?

As you said:

if you are adding conditions dynamically you don't have to worry about stripping the initial AND that's the only reason could be, you are right.

Email Address Validation in Android on EditText

Use this method for validating your email format. Pass email as string , it returns true if format is correct otherwise false.

/**
 * validate your email address format. [email protected]
 */
public boolean emailValidator(String email) 
{
    Pattern pattern;
    Matcher matcher;
    final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    pattern = Pattern.compile(EMAIL_PATTERN);
    matcher = pattern.matcher(email);
    return matcher.matches();
}

Enabling CORS in Cloud Functions for Firebase

There are two sample functions provided by the Firebase team that demonstrate the use of CORS:

The second sample uses a different way of working with cors than you're currently using.

Consider importing like this, as shown in the samples:

const cors = require('cors')({origin: true});

And the general form of your function will be like this:

exports.fn = functions.https.onRequest((req, res) => {
    cors(req, res, () => {
        // your function body here - use the provided req and res from cors
    })
});

Is it acceptable and safe to run pip install under sudo?

Is it acceptable & safe to run pip install under sudo?

It's not safe and it's being frowned upon – see What are the risks of running 'sudo pip'? To install Python package in your home directory you don't need root privileges. See description of --user option to pip.

jQuery check if attr = value

jQuery's attr method returns the value of the attribute:

The .attr() method gets the attribute value for only the first element in the matched set. To get the value for each element individually, use a looping construct such as jQuery's .each() or .map() method.

All you need is:

$('html').attr('lang') == 'fr-FR'

However, you might want to do a case-insensitive match:

$('html').attr('lang').toLowerCase() === 'fr-fr'

jQuery's val method returns the value of a form element.

The .val() method is primarily used to get the values of form elements such as input, select and textarea. In the case of <select multiple="multiple"> elements, the .val() method returns an array containing each selected option; if no option is selected, it returns null.

How to use pull to refresh in Swift?

For the pull to refresh i am using

DGElasticPullToRefresh

https://github.com/gontovnik/DGElasticPullToRefresh

Installation

pod 'DGElasticPullToRefresh'

import DGElasticPullToRefresh

and put this function into your swift file and call this funtion from your

override func viewWillAppear(_ animated: Bool)

     func Refresher() {
      let loadingView = DGElasticPullToRefreshLoadingViewCircle()
      loadingView.tintColor = UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1.0)
      self.table.dg_addPullToRefreshWithActionHandler({ [weak self] () -> Void in

          //Completion block you can perfrom your code here.

           print("Stack Overflow")

           self?.table.dg_stopLoading()
           }, loadingView: loadingView)
      self.table.dg_setPullToRefreshFillColor(UIColor(red: 255.0/255.0, green: 57.0/255.0, blue: 66.0/255.0, alpha: 1))
      self.table.dg_setPullToRefreshBackgroundColor(self.table.backgroundColor!)
 }

And dont forget to remove reference while view will get dissapear

to remove pull to refresh put this code in to your

override func viewDidDisappear(_ animated: Bool)

override func viewDidDisappear(_ animated: Bool) {
      table.dg_removePullToRefresh()

 }

And it will looks like

enter image description here

Happy coding :)

Setting a windows batch file variable to the day of the week

few more ways:

1.Robocopy not available in XP but can be downloaded form with win 2003 resource tool kit .Also might depend on localization:

@echo off
setlocal 
for /f "skip=8 tokens=2,3,4,5,6,7,8 delims=: " %%D in ('robocopy /l * \ \ /ns /nc /ndl /nfl /np /njh /XF * /XD *') do (
 set "dow=%%D"
 set "month=%%E"
 set "day=%%F"
 set "HH=%%G"
 set "MM=%%H"
 set "SS=%%I"
 set "year=%%J"
)

echo Day of the week: %dow%
endlocal

2.MAKECAB - works on every windows machine (but creates a small temp file).Function provided by carlos:

@Echo Off


Call :GetDate.Init
Rem :GetDate.Init should be called one time in the code before call to :Getdate
Call :GetDate
Echo weekday:%weekday%

Goto :EOF

:GetDate.Init
Set /A "jan=1,feb=2,mar=3,apr=4,may=5,jun=6,jul=7,aug=8,sep=9,oct=10,nov=11,dec=12"
Set /A "mon=1,tue=2,wed=3,thu=4,fri=5,sat=6,sun=7"
(
Echo .Set InfHeader=""
Echo .Set InfSectionOrder=""
Echo .Set InfFooter="%%2"
Echo .Set InfFooter1=""
Echo .Set InfFooter2=""
Echo .Set InfFooter3=""
Echo .Set InfFooter4=""
Echo .Set Cabinet="OFF"
Echo .Set Compress="OFF"
Echo .Set DoNotCopyFiles="ON"
Echo .Set RptFileName="NUL"
) >"%Temp%\~foo.ddf"
Goto :Eof

:GetDate
Set "tf=%Temp%\~%random%"
Makecab /D InfFileName="%tf%" /F "%Temp%\~foo.ddf" >NUL
For /F "usebackq tokens=1-7 delims=: " %%a In ("%tf%") Do (
Set /A "year=%%g,month=%%b,day=1%%c-100,weekday=%%a"
Set /A "hour=1%%d-100,minute=1%%e-100,second=1%%f-100")
Del "%tf%" >NUL 2>&1
Goto :Eof

3.W32TM - uses command switches introduced in Vista so will not work on windows 2003/XP:

@echo off
setlocal
call :w32dow day_ow
echo %day_ow%
pause
exit /b 0
endlocal
:w32dow [RrnVar]
setlocal

rem :: prints the day of the week
rem :: works on Vista and above


rem :: getting ansi date ( days passed from 1st jan 1601 ) , timer server hour and current hour
FOR /F "tokens=4,5 delims=:( " %%D in ('w32tm /stripchart /computer:localhost  /samples:1  /period:1 /dataonly /packetinfo^|find "Transmit Timestamp:" ') do (
 set "ANSI_DATE=%%D"
 set  "TIMESERVER_HOURS=%%E"
)

set  "LOCAL_HOURS=%TIME:~0,2%"
if "%TIMESERVER_HOURS:~0,1%0" EQU "00" set TIMESERVER_HOURS=%TIMESERVER_HOURS:~1,1%
if "%LOCAL_HOURS:~0,1%0" EQU "00" set LOCAL_HOURS=%LOCAL_HOURS:~1,1%
set /a OFFSET=TIMESERVER_HOURS-LOCAL_HOURS

rem :: day of the week will be the modulus of 7 of local ansi date +1
rem :: we need need +1 because Monday will be calculated as 0
rem ::  1st jan 1601 was Monday

rem :: if abs(offset)>12 we are in different days with the time server

IF %OFFSET%0 GTR 120 set /a DOW=(ANSI_DATE+1)%%7+1
IF %OFFSET%0 LSS -120 set /a DOW=(ANSI_DATE-1)%%7+1
IF %OFFSET%0 LEQ 120 IF %OFFSET%0 GEQ -120 set /a DOW=ANSI_DATE%%7+1


rem echo Day of the week: %DOW% 
endlocal & if "%~1" neq "" (set "%~1=%DOW%") else echo %DOW%

4..bat/jscript hybrid (must be saved as .bat):

 @if (@x)==(@y) @end /***** jscript comment ******
 @echo off
 for /f  %%d in ('cscript //E:JScript //nologo "%~f0"') do echo %%d
 exit /b 0
 *****  end comment *********/
 WScript.Echo((new Date).getDay());

5..bat/vbscript hybrid (must be saved as .bat)

 :sub echo(str) :end sub
echo off
'>nul 2>&1|| copy /Y %windir%\System32\doskey.exe '.exe >nul

'& echo/ 
'& for /f %%w in ('cscript /nologo /E:vbscript %~dpfn0') do echo day of the week %%w
'& echo/
'& del /q "'.exe" >nul 2>&1
'& exit /b

WScript.Echo Weekday(Date)
WScript.Quit

6.powershell can be downloaded from microsoft.Available by default in everything form win7 and above:

@echo off
setlocal
for /f %%d in ('"powershell (Get-Date).DayOfWeek.Value__"') do set dow=%%d

echo day of the week : %dow%
endlocal

7.WMIC already used as an answer but just want to have a full reference.And with cleared <CR>:

@echo off
setlocal
for /f "delims=" %%a in ('wmic path win32_localtime get dayofweek /format:list ') do for /f "delims=" %%d in ("%%a") do set %%d

echo day of the week : %dayofweek%
endlocal

9.Selfcompiled jscript.net (must be saved as .bat):

@if (@X)==(@Y) @end /****** silent line that start jscript comment ******

@echo off
::::::::::::::::::::::::::::::::::::
:::       compile the script    ::::
::::::::::::::::::::::::::::::::::::
setlocal
if exist "%~n0.exe" goto :skip_compilation

set "frm=%SystemRoot%\Microsoft.NET\Framework\"
:: searching the latest installed .net framework
for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
    if exist "%%v\jsc.exe" (
        rem :: the javascript.net compiler
        set "jsc=%%~dpsnfxv\jsc.exe"
        goto :break_loop
    )
)
echo jsc.exe not found && exit /b 0
:break_loop


call %jsc% /nologo /out:"%~n0.exe" "%~dpsfnx0"
::::::::::::::::::::::::::::::::::::
:::       end of compilation    ::::
::::::::::::::::::::::::::::::::::::
:skip_compilation

"%~n0.exe"

exit /b 0


****** end of jscript comment ******/
import System;
import System.IO;

var dt=DateTime.Now;
 Console.WriteLine(dt.DayOfWeek);

R: rJava package install failing

The problem was rJava wont install in RStudio (Version 1.0.136). The following worked for me (macOS Sierra version 10.12.6) (found here):

Step-1: Download and install javaforosx.dmg from here

Step-2: Next, run the command from inside RStudio:

install.packages("rJava", type = 'source')

Should you use .htm or .html file extension? What is the difference, and which file is correct?

Here is some food for thought.

If you had been using all .htm files on your website and now, for example, you have changed the editor that you are using, and your new editor is outputting all your files with the .html extension. When you re-publish your site to the server, it would seem to me that you could really hurt your SEO position/ranking as many of the links out there in the web, including Google, that were looking for the .htm and not the new .html for that same page. This assumes that you are still using the same page names from your old editor which would make sense.

Anyway... My point is, be careful not to loose that link juice you have build up. So I guess in this example, there is a reason to stick with .htm... But other then that as mentioned by everyone else they seem to be the same.

Please correct if I'm wrong.

The reason I mention all this is because this is what I was in the process of doing when it occurred to me I may be damaging the site SEO with the new editor.

The original editor was MS Front Page, which always outputted .htm, dead now, and the new editor "90 Second Web Builder 9" which outputs all .html files... Luckily, they must have thought about this and they included a way to change the output extension back to .htm

Anyway, that's my 2 cents... hope it helps someone..

Putty: Getting Server refused our key Error

I have solved this problem,puttygen is a third-party software, ssh key which generated by it didn't be used directly, so you must make some changes. For example, it look like this

---- BEGIN SSH2 PUBLIC KEY ----
Comment: "rsa-key-20170502"
AAAAB3NzaC1yc2EAAAABJQAAAQEAr4Ffd3LD1pa7KVSBDU+lq0M7vNvLp6TewkP7
*******C4eq1cdJACBPyjqUCoz00r+LqkGA6sIFGooeVuUXTOxbYULuNQ==
---- END SSH2 PUBLIC KEY ---- 

I omit some of the alphabets in the middle, replaced by *, if not, StackOverflow told me that the code format is wrong, do not let me post?

this is my ssh key generated by puttygen, you must change to this

ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAQEAr4Ffd3LD1pa7KVSBDU+lq0M7vNvLp6TewkP7wfvKGWWR7wxA8GEXJsM01FQw5hYWbNF0CDI7nCMXDUEDOzO1xKtNoaidlLA0qGl67bHaF5t+0mE+dZBGqK7jG9L8/KU/b66/tuZnqFqBjLkT+lS8MDo1okJOScuLSilk9oT5ZiqxsD24sdEcUE62S8Qwu7roVEAWU3hHNpnMK+1szlPBCVpbjcQTdiv1MjsOHJXY2PWx6DAIBii+/N+IdGzoFdhq+Yo/RGWdr1Zw/LSwqKDq1SmrpToW9uWVdAxeC4eq1cdJACBPyjqUCoz00r+LqkGA6sIFGooeVuUXTOxbYULuNQ== yourname@hostname

In my case, I have deleted some comments, such as

---- BEGIN SSH2 PUBLIC KEY ----
Comment: "rsa-key-20170502"
---- END SSH2 PUBLIC KEY ----

and add ssh-rsa at the beginning, add yourname@hostname at the last. note: not delete== in the last and you must change "yourname" and "hostname" for you, In my case, is uaskh@mycomputer,yourname is that you want to log in your vps .when all these things have done,you could to upload public-key to uaskh's home~/.ssh/authorized_keys by cat public-key >> ~/.ssh/authorized_keys then sudo chmod 700 ~/.ssh sudo chmod 600 ~/.ssh/authorized_keys then you must to modify /etc/ssh/sshd_config, RSAAuthentication yes PubkeyAuthentication yes AuthorizedKeysFile .ssh/authorized_keys my operating system is CentOS 7,This is my first time to anwser question,I will try my efforts to do ,Thank you!

Sorting arrays in NumPy by column

From the NumPy mailing list, here's another solution:

>>> a
array([[1, 2],
       [0, 0],
       [1, 0],
       [0, 2],
       [2, 1],
       [1, 0],
       [1, 0],
       [0, 0],
       [1, 0],
      [2, 2]])
>>> a[np.lexsort(np.fliplr(a).T)]
array([[0, 0],
       [0, 0],
       [0, 2],
       [1, 0],
       [1, 0],
       [1, 0],
       [1, 0],
       [1, 2],
       [2, 1],
       [2, 2]])

How to handle checkboxes in ASP.NET MVC forms?

HtmlHelper adds an hidden input to notify the controller about Unchecked status. So to have the correct checked status:

bool bChecked = form[key].Contains("true");

How do you set the width of an HTML Helper TextBox in ASP.NET MVC?

The original answer is no longer working as written:

<%=Html.TextBox("test", new { style="width:50px" })%> 

will get you a text box with "{ style="width:50px" }" as its text content.

To adjust this for the current release of MVC 1.0, use the following script (note the addition of the second parameter - I have mine starting as blank, adjust accordingly based on your needs):

<%=Html.TextBox("test", "", new { style="width:50px" })%> 

HTTP Request in Kotlin

Using only the standard library with minimal code!

thread {
    val jsonStr = try { URL(url).readText() } catch (ex: Exception) { return@thread }
    runOnUiThread { displayOrWhatever(jsonStr) }
}

This starts a GET request on a new thread, leaving the UI thread to respond to user input. However, we can only modify UI elements from the main/UI thread, so we actually need a runOnUiThread block to show the result to our user. This enqueues our display code to be run on the UI thread soon.

The try/catch is there so your app won't crash if you make a request with your phone's internet off. Add your own error handling (e.g. showing a Toast) as you please.

.readText() is not part of the java.net.URL class but a Kotlin extension method, Kotlin "glues" this method onto URL. This is enough for plain GET requests, but for more control and POST requests you need something like the Fuel library.

How can I view an object with an alert()

alert( JSON.stringify(product) );

Setting a divs background image to fit its size?

Set your css to this

img {
    max-width:100%,
    max-height100%
}

How to validate an email address in JavaScript

Here is a solution that works and includes validation/notification fuctionality in a form:

You can run it at this link

JAVASCRIPT

(function() {
  'use strict';

  window.addEventListener('load', function() {
    var form = document.getElementById('needs-validation');
    form.addEventListener('submit', function(event) {
      if (form.checkValidity() === false) {
        event.preventDefault();
      }
      form.classList.add('was-validated');
      event.preventDefault();              
    }, false);
  }, false);
})();

HTML

<p class='title'>
    <b>Email validation</b>
  <hr size="30px;">
</p>
<br>

<form id="needs-validation" novalidate>
  <p class='form_text'>Try it out!</p>
  <div class="form-row">
    <div class="col-12">
      <input type="email" class="form-control" placeholder="Email Address" required>
        <div class="invalid-feedback">
          Please enter a valid email address.
        </div>
    </div>
  <div class="row">
    <div class="col-12">
      <button type="submit" 
          class="btn btn-default btn-block">Sign up now
      </button>
    </div>
   </div>
</form>

Python regular expressions return true/false

If you really need True or False, just use bool

>>> bool(re.search("hi", "abcdefghijkl"))
True
>>> bool(re.search("hi", "abcdefgijkl"))
False

As other answers have pointed out, if you are just using it as a condition for an if or while, you can use it directly without wrapping in bool()

Plotting in a non-blocking way with Matplotlib

The Python package drawnow allows to update a plot in real time in a non blocking way.
It also works with a webcam and OpenCV for example to plot measures for each frame.
See the original post.

How to get item's position in a list?

What about the following?

print testlist.index(element)

If you are not sure whether the element to look for is actually in the list, you can add a preliminary check, like

if element in testlist:
    print testlist.index(element)

or

print(testlist.index(element) if element in testlist else None)

or the "pythonic way", which I don't like so much because code is less clear, but sometimes is more efficient,

try:
    print testlist.index(element)
except ValueError:
    pass

Unable to load script from assets index.android.bundle on windows

It may be caused by unlinked assets in your React Native project code base, like when you renames your project application/bundle id or adds an external package without link it properly, for example.

Simply try it in your project root directory:

react-native link

react-native run-android

Arrays in type script

You can also do this as well (shorter cut) instead of having to do instance declaration. You do this in JSON instead.

class Book {
    public BookId: number;
    public Title: string;
    public Author: string;
    public Price: number;
    public Description: string;
}

var bks: Book[] = [];

 bks.push({BookId: 1, Title:"foo", Author:"foo", Price: 5, Description: "foo"});   //This is all done in JSON.

How can I fix assembly version conflicts with JSON.NET after updating NuGet package references in a new ASP.NET MVC 5 project?

Veverke mentioned that it is possible to disable generation of binding redirects by setting AutoGEneratedBindingRedirects to false. Not sure if it's a new thing since this question was posted, but there is an "Skip applying binding redirects" option in Tools/Options/Nuget Packet Manager, which can be toggled. By default it is off, meaning the redirects will be applied. However if you do this, you will have to manage any necessary binding redirects manually.

Parsing JSON objects for HTML table

Loop over each object, push in string array and join them. Append in target table, it is better.

$(document).ready(function () {
$.getJSON(url,
function (json) {
    var tr=[];
    for (var i = 0; i < json.length; i++) {
        tr.push('<tr>');
        tr.push("<td>" + json[i].User_Name + "</td>");
        tr.push("<td>" + json[i].score + "</td>");
        tr.push("<td>" + json[i].team + "</td>");
        tr.push('</tr>');
    }
    $('table').append($(tr.join('')));
});

View's SELECT contains a subquery in the FROM clause

Looks to me as MySQL 3.6 gives the following error while MySQL 3.7 no longer errors out. I am yet to find anything in the documentation regarding this fix.

Prevent users from submitting a form by hitting Enter

I needed to prevent only specific inputs from submitting, so I used a class selector, to let this be a "global" feature wherever I need it.

<input id="txtEmail" name="txtEmail" class="idNoEnter" .... />

And this jQuery code:

$('.idNoEnter').keydown(function (e) {
  if (e.keyCode == 13) {
    e.preventDefault();
  }
});

Alternatively, if keydown is insufficient:

$('.idNoEnter').on('keypress keydown keyup', function (e) {
   if (e.keyCode == 13) {
     e.preventDefault();
   }
});

Some notes:

Modifying various good answers here, the Enter key seems to work for keydown on all the browsers. For the alternative, I updated bind() to the on() method.

I'm a big fan of class selectors, weighing all the pros and cons and performance discussions. My naming convention is 'idSomething' to indicate jQuery is using it as an id, to separate it from CSS styling.

How to redirect cin and cout to files?

Here is a short code snippet for shadowing cin/cout useful for programming contests:

#include <bits/stdc++.h>

using namespace std;

int main() {
    ifstream cin("input.txt");
    ofstream cout("output.txt");

    int a, b;   
    cin >> a >> b;
    cout << a + b << endl;
}

This gives additional benefit that plain fstreams are faster than synced stdio streams. But this works only for the scope of single function.

Global cin/cout redirect can be written as:

#include <bits/stdc++.h>

using namespace std;

void func() {
    int a, b;
    std::cin >> a >> b;
    std::cout << a + b << endl;
}

int main() {
    ifstream cin("input.txt");
    ofstream cout("output.txt");

    // optional performance optimizations    
    ios_base::sync_with_stdio(false);
    std::cin.tie(0);

    std::cin.rdbuf(cin.rdbuf());
    std::cout.rdbuf(cout.rdbuf());

    func();
}

Note that ios_base::sync_with_stdio also resets std::cin.rdbuf. So the order matters.

See also Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

Std io streams can also be easily shadowed for the scope of single file, which is useful for competitive programming:

#include <bits/stdc++.h>

using std::endl;

std::ifstream cin("input.txt");
std::ofstream cout("output.txt");

int a, b;

void read() {
    cin >> a >> b;
}

void write() {
    cout << a + b << endl;
}

int main() {
    read();
    write();
}

But in this case we have to pick std declarations one by one and avoid using namespace std; as it would give ambiguity error:

error: reference to 'cin' is ambiguous
     cin >> a >> b;
     ^
note: candidates are: 
std::ifstream cin
    ifstream cin("input.txt");
             ^
    In file test.cpp
std::istream std::cin
    extern istream cin;  /// Linked to standard input
                   ^

See also How do you properly use namespaces in C++?, Why is "using namespace std" considered bad practice? and How to resolve a name collision between a C++ namespace and a global function?

Can I bind an array to an IN() condition?

Is it so important to use IN statement? Try to use FIND_IN_SET op.

For example, there is a query in PDO like that

SELECT * FROM table WHERE FIND_IN_SET(id, :array)

Then you only need to bind an array of values, imploded with comma, like this one

$ids_string = implode(',', $array_of_smth); // WITHOUT WHITESPACES BEFORE AND AFTER THE COMMA
$stmt->bindParam('array', $ids_string);

and it's done.

UPD: As some people pointed out in comments to this answer, there are some issues which should be stated explciitly.

  1. FIND_IN_SET doesn't use index in a table, and it is still not implemented yet - see this record in the MYSQL bug tracker. Thanks to @BillKarwin for the notice.
  2. You can't use a string with comma inside as a value of the array for search. It is impossible to parse such string in the right way after implode since you use comma symbol as a separator. Thanks to @VaL for the note.

In fine, if you are not heavily dependent on indexes and do not use strings with comma for search, my solution will be much easier, simpler, and faster than solutions listed above.

How to terminate a window in tmux?

While you asked how to kill a window resp. pane, I often wouldn't want to kill it but simply to get it back to a working state (the layout of panes is of importance to me, killing a pane destroys it so I must recreate it); tmux provides the respawn commands to that effect: respawn-pane resp. respawn-window. Just that people like me may find this solution here.

Select columns from result set of stored procedure

As it's been mentioned in the question, it's hard to define the 80 column temp table before executing the stored procedure.

So the other way around this is to populate the table based on the stored procedure result set.

SELECT * INTO #temp FROM OPENROWSET('SQLNCLI', 'Server=localhost;Trusted_Connection=yes;'
                                   ,'EXEC MyStoredProc')

If you are getting any error, you need to enable ad hoc distributed queries by executing following query.

sp_configure 'Show Advanced Options', 1
GO
RECONFIGURE
GO
sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
GO

To execute sp_configure with both parameters to change a configuration option or to run the RECONFIGURE statement, you must be granted the ALTER SETTINGS server-level permission

Now you can select your specific columns from the generated table

SELECT col1, col2
FROM #temp

How do you tell if caps lock is on using JavaScript?

You can give it a try.. Added a working example. When focus is on input, turning on caps lock makes the led go red otherwise green. (Haven't tested on mac/linux)

NOTE: Both versions are working for me. Thanks for constructive inputs in the comments.

OLD VERSION: https://jsbin.com/mahenes/edit?js,output

Also, here is a modified version (can someone test on mac and confirm)

NEW VERSION: https://jsbin.com/xiconuv/edit?js,output

NEW VERSION:

function isCapslock(e) {
  const IS_MAC = /Mac/.test(navigator.platform);

  const charCode = e.charCode;
  const shiftKey = e.shiftKey;

  if (charCode >= 97 && charCode <= 122) {
    capsLock = shiftKey;
  } else if (charCode >= 65 && charCode <= 90
    && !(shiftKey && IS_MAC)) {
    capsLock = !shiftKey;
  }

  return capsLock;
}

OLD VERSION:

function isCapslock(e) {
  e = (e) ? e : window.event;

  var charCode = false;
  if (e.which) {
    charCode = e.which;
  } else if (e.keyCode) {
    charCode = e.keyCode;
  }

  var shifton = false;
  if (e.shiftKey) {
    shifton = e.shiftKey;
  } else if (e.modifiers) {
    shifton = !!(e.modifiers & 4);
  }

  if (charCode >= 97 && charCode <= 122 && shifton) {
    return true;
  }

  if (charCode >= 65 && charCode <= 90 && !shifton) {
    return true;
  }

  return false;
}

For international characters, additional check can be added for the following keys as needed. You have to get the keycode range for characters you are interested in, may be by using a keymapping array which will hold all the valid use case keys you are addressing...

uppercase A-Z or 'Ä', 'Ö', 'Ü', lowercase a-Z or 0-9 or 'ä', 'ö', 'ü'

The above keys are just sample representation.

How to create a video from images with FFmpeg?

cat *.png | ffmpeg -f image2pipe -i - output.mp4

from wiki

Best approach to converting Boolean object to string in java

If you are sure that your value is not null you can use third option which is

String str3 = b.toString();

and its code looks like

public String toString() {
    return value ? "true" : "false";
}

If you want to be null-safe use String.valueOf(b) which code looks like

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

so as you see it will first test for null and later invoke toString() method on your object.


Calling Boolean.toString(b) will invoke

public static String toString(boolean b) {
    return b ? "true" : "false";
}

which is little slower than b.toString() since JVM needs to first unbox Boolean to boolean which will be passed as argument to Boolean.toString(...), while b.toString() reuses private boolean value field in Boolean object which holds its state.

Run JavaScript code on window close or page refresh?

The event is called beforeunload, so you can assign a function to window.onbeforeunload.

How to force uninstallation of windows service

The following will work without restarting the machine:

  1. Search the Registry \ HKEY_LOCAL_MACHINE for < Your Service Name > (both keys and values)
  2. Set "Legacy" value to 0

Can't escape the backslash with regex?

The backslash \ is the escape character for regular expressions. Therefore a double backslash would indeed mean a single, literal backslash.

\ (backslash) followed by any of [\^$.|?*+(){} escapes the special character to suppress its special meaning.

ref : http://www.regular-expressions.info/reference.html

Referencing another schema in Mongoose

It sounds like the populate method is what your looking for. First make small change to your post schema:

var postSchema = new Schema({
    name: String,
    postedBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
    dateCreated: Date,
    comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});

Then make your model:

var Post = mongoose.model('Post', postSchema);

Then, when you make your query, you can populate references like this:

Post.findOne({_id: 123})
.populate('postedBy')
.exec(function(err, post) {
    // do stuff with post
});

Form Submit jQuery does not work

The NUMBER ONE error is having ANYTHING with the reserved word submit as ID or NAME in your form.

If you plan to call .submit() on the form AND the form has submit as id or name on any form element, then you need to rename that form element, since the form’s submit method/handler is shadowed by the name/id attribute.


Several other things:

As mentioned, you need to submit the form using a simpler event than the jQuery one

BUT you also need to cancel the clicks on the links

Why, by the way, do you have two buttons? Since you use jQuery to submit the form, you will never know which of the two buttons were clicked unless you set a hidden field on click.

<form action="deletprofil.php" id="form_id" method="post">
  <div data-role="controlgroup" data-filter="true" data-input="#filterControlgroup-input">
  <button type="submit" value="1" class="ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Anlegen</button>
  <button type="submit" value="2" class="ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Bnlegen</button>
  </div>
</form> 

 $(function(){
    $("#NOlink, #OKlink").on("click", function(e) {
        e.preventDefault(); // cancel default action
        $("#popupDialog").popup('close');
        if (this.id=="OKlink") { 
          document.getElementById("form_id").submit(); // or $("#form_id")[0].submit();
        }
    });

    $('#form_id').on('submit', function(e){
      e.preventDefault();
      $("#popupDialog").popup('open');
    });
});    

Judging from your comments, I think you really want to do this:

<form action="deletprofil.php" id="form_id" method="post">
  <input type="hidden" id="whichdelete" name="whichdelete" value="" />
  <div data-role="controlgroup" data-filter="true" data-input="#filterControlgroup-input">
  <button type="button" value="1" class="delete ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Anlegen</button>
  <button type="button" value="2" class="delete ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Bnlegen</button>
  </div>
</form> 

 $(function(){
    $("#NOlink, #OKlink").on("click", function(e) {
        e.preventDefault(); // cancel default action
        $("#popupDialog").popup('close');
        if (this.id=="OKlink") { 
          // trigger the submit event, not the event handler
          document.getElementById("form_id").submit(); // or $("#form_id")[0].submit();
        }
    });
    $(".delete").on("click", function(e) {
        $("#whichdelete").val(this.value);
    });
    $('#form_id').on('submit', function(e){
      e.preventDefault();
      $("#popupDialog").popup('open');
    });
});  

SSL handshake fails with - a verisign chain certificate - that contains two CA signed certificates and one self-signed certificate

About the server can deliver to the clients the root cert or not, extracted from the RFC-5246 'The Transport Layer Security (TLS) Protocol Version 1.2' doc it says:

certificate_list
This is a sequence (chain) of certificates. The sender's certificate MUST come first in the list. Each following certificate MUST directly certify the one preceding it. Because certificate validation requires that root keys be distributed independently, the self-signed certificate that specifies the root certificate authority MAY be omitted from the chain, under the
assumption that the remote end must already possess it in order to validate it in any case.

About the term 'MAY', extracted from the RFC-2119 "Best Current Practice" says:

5.MAY
This word, or the adjective "OPTIONAL", mean that an item is truly optional. One vendor may choose to include the item because a
particular marketplace requires it or because the vendor feels that
it enhances the product while another vendor may omit the same item.
An implementation which does not include a particular option MUST be
prepared to interoperate with another implementation which does
include the option, though perhaps with reduced functionality. In the same vein an implementation which does include a particular option
MUST be prepared to interoperate with another implementation which
does not include the option (except, of course, for the feature the
option provides.)

In conclusion, the root may be at the certification path delivered by the server in the handshake.

A practical use.
Think about, not in navigator user terms, but on a transfer tool at a server in a militarized zone with limited internet access.
The server, playing the client role at the transfer, receives all the certs path from the server.
All the certs in the chain should be checked to be trusted, root included.
The only way to check this is the root be included at the certs path in transfer time, being matched against a previously declared as 'trusted' local copy of them.

How can I preview a merge in git?

Maybe this can help you ? git-diff-tree - Compares the content and mode of blobs found via two tree objects

Python urllib2 Basic Auth Problem

The problem could be that the Python libraries, per HTTP-Standard, first send an unauthenticated request, and then only if it's answered with a 401 retry, are the correct credentials sent. If the Foursquare servers don't do "totally standard authentication" then the libraries won't work.

Try using headers to do authentication:

import urllib2, base64

request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.b64encode('%s:%s' % (username, password))
request.add_header("Authorization", "Basic %s" % base64string)   
result = urllib2.urlopen(request)

Had the same problem as you and found the solution from this thread: http://forums.shopify.com/categories/9/posts/27662

Ajax Upload image

HTML Code

<div class="rCol"> 
     <div id ="prv" style="height:auto; width:auto; float:left; margin-bottom: 28px; margin-left: 200px;"></div>
       </div>
    <div class="rCol" style="clear:both;">

    <label > Upload Photo : </label> 
    <input type="file" id="file" name='file' onChange=" return submitForm();">
    <input type="hidden" id="filecount" value='0'>

Here is Ajax Code:

function submitForm() {

    var fcnt = $('#filecount').val();
    var fname = $('#filename').val();
    var imgclean = $('#file');
    if(fcnt<=5)
    {
    data = new FormData();
    data.append('file', $('#file')[0].files[0]);

    var imgname  =  $('input[type=file]').val();
     var size  =  $('#file')[0].files[0].size;

    var ext =  imgname.substr( (imgname.lastIndexOf('.') +1) );
    if(ext=='jpg' || ext=='jpeg' || ext=='png' || ext=='gif' || ext=='PNG' || ext=='JPG' || ext=='JPEG')
    {
     if(size<=1000000)
     {
    $.ajax({
      url: "<?php echo base_url() ?>/upload.php",
      type: "POST",
      data: data,
      enctype: 'multipart/form-data',
      processData: false,  // tell jQuery not to process the data
      contentType: false   // tell jQuery not to set contentType
    }).done(function(data) {
       if(data!='FILE_SIZE_ERROR' || data!='FILE_TYPE_ERROR' )
       {
        fcnt = parseInt(fcnt)+1;
        $('#filecount').val(fcnt);
        var img = '<div class="dialog" id ="img_'+fcnt+'" ><img src="<?php echo base_url() ?>/local_cdn/'+data+'"><a href="#" id="rmv_'+fcnt+'" onclick="return removeit('+fcnt+')" class="close-classic"></a></div><input type="hidden" id="name_'+fcnt+'" value="'+data+'">';
        $('#prv').append(img);
        if(fname!=='')
        {
          fname = fname+','+data;
        }else
        {
          fname = data;
        }
         $('#filename').val(fname);
          imgclean.replaceWith( imgclean = imgclean.clone( true ) );
       }
       else
       {
         imgclean.replaceWith( imgclean = imgclean.clone( true ) );
         alert('SORRY SIZE AND TYPE ISSUE');
       }

    });
    return false;
  }//end size
  else
  {
      imgclean.replaceWith( imgclean = imgclean.clone( true ) );//Its for reset the value of file type
    alert('Sorry File size exceeding from 1 Mb');
  }
  }//end FILETYPE
  else
  {
     imgclean.replaceWith( imgclean = imgclean.clone( true ) );
    alert('Sorry Only you can uplaod JPEG|JPG|PNG|GIF file type ');
  }
  }//end filecount
  else
  {    imgclean.replaceWith( imgclean = imgclean.clone( true ) );
     alert('You Can not Upload more than 6 Photos');
  }
}

Here is PHP code :

$filetype = array('jpeg','jpg','png','gif','PNG','JPEG','JPG');
   foreach ($_FILES as $key )
    {

          $name =time().$key['name'];

          $path='local_cdn/'.$name;
          $file_ext =  pathinfo($name, PATHINFO_EXTENSION);
          if(in_array(strtolower($file_ext), $filetype))
          {
            if($key['name']<1000000)
            {

             @move_uploaded_file($key['tmp_name'],$path);
             echo $name;

            }
           else
           {
               echo "FILE_SIZE_ERROR";
           }
        }
        else
        {
            echo "FILE_TYPE_ERROR";
        }// Its simple code.Its not with proper validation.

Here upload and preview part done.Now if you want to delete and remove image from page and folder both then code is here for deletion. Ajax Part:

function removeit (arg) {
       var id  = arg;
       // GET FILE VALUE
       var fname = $('#filename').val();
       var fcnt = $('#filecount').val();
        // GET FILE VALUE

       $('#img_'+id).remove();
       $('#rmv_'+id).remove();
       $('#img_'+id).css('display','none');

        var dname  =  $('#name_'+id).val();
        fcnt = parseInt(fcnt)-1;
        $('#filecount').val(fcnt);
        var fname = fname.replace(dname, "");
        var fname = fname.replace(",,", "");
        $('#filename').val(fname);
        $.ajax({
          url: 'delete.php',
          type: 'POST',
          data:{'name':dname},
          success:function(a){
            console.log(a);
            }
        });
    } 

Here is PHP part(delete.php):

$path='local_cdn/'.$_POST['name'];

   if(@unlink($path))
   {
     echo "Success";
   }
   else
   {
     echo "Failed";
   }

How to make the webpack dev server run on port 80 and on 0.0.0.0 to make it publicly accessible?

I tried the solutions above, but had no luck. I noticed this line in my project's package.json:

 "bin": {
"webpack-dev-server": "bin/webpack-dev-server.js"

},

I looked at bin/webpack-dev-server.js and found this line:

.describe("port", "The port").default("port", 8080)

I changed the port to 3000. A bit of a brute force approach, but it worked for me.

jQuery AutoComplete Trigger Change Event

this will work,too

$("#CompanyList").autocomplete({
  source : yourSource,
  change : yourChangeHandler
})

// deprecated
//$("#CompanyList").data("autocomplete")._trigger("change")
// use this now
$("#CompanyList").data("ui-autocomplete")._trigger("change")

TortoiseGit-git did not exit cleanly (exit code 1)

first login on git then before push take the pull. issue will be resolved

BATCH file asks for file or folder

Referencing XCopy Force File

For forcing files, we could use pipeline "echo F |":

C:\Trash>xcopy 23.txt 24.txt
Does 24.txt specify a file name
or directory name on the target
(F = file, D = directory)?

C:\Trash>echo F | xcopy 23.txt 24.txt
Does 24.txt specify a file name
or directory name on the target
(F = file, D = directory)? F
C:23.txt
1 File(s) copied

For forcing a folder, we could use /i parameter for xcopy or using a backslash() at the end of the destination folder.

How can I change the text inside my <span> with jQuery?

Syntax:

  • return the element's text content: $(selector).text()
  • set the element's text content to content: $(selector).text(content)
  • set the element's text content using a callback function: $(selector).text(function(index, curContent))

JQuery - Change the text of a span element

How to send a pdf file directly to the printer using JavaScript?

This is actually a lot easier using a dataURI, because you can just call print on the returned window object.

// file is a File object, this will also take a blob
const dataUrl = window.URL.createObjectURL(file);

// Open the window
const pdfWindow = window.open(dataUrl);

// Call print on it
pdfWindow.print();

This opens the pdf in a new tab and then pops the print dialog up.

Finding a substring within a list in Python

print [s for s in list if sub in s]

If you want them separated by newlines:

print "\n".join(s for s in list if sub in s)

Full example, with case insensitivity:

mylist = ['abc123', 'def456', 'ghi789', 'ABC987', 'aBc654']
sub = 'abc'

print "\n".join(s for s in mylist if sub.lower() in s.lower())

IF a == true OR b == true statement

check this Twig Reference.

You can do it that simple:

{% if (a or b) %}
    ...
{% endif %}

Remove all child nodes from a parent?

A other users suggested,

.empty()

is good enought, because it removes all descendant nodes (both tag-nodes and text-nodes) AND all kind of data stored inside those nodes. See the JQuery's API empty documentation.

If you wish to keep data, like event handlers for example, you should use

.detach()

as described on the JQuery's API detach documentation.

The method .remove() could be usefull for similar purposes.

How to read until EOF from cin in C++

You can use the std::istream::getline() (or preferably the version that works on std::string) function to get an entire line. Both have versions that allow you to specify the delimiter (end of line character). The default for the string version is '\n'.

How to re import an updated package while in Python Interpreter?

dragonfly's answer worked for me (python 3.4.3).

import sys
del sys.modules['module_name']

Here is a lower level solution :

exec(open("MyClass.py").read(), globals())

Curl not recognized as an internal or external command, operable program or batch file

Method 1:\

add "C:\Program Files\cURL\bin" path into system variables Path right-click My Computer and click Properties >advanced > Environment Variables enter image description here

Method 2: (if method 1 not work then)

simple open command prompt with "run as administrator"

Clear terminal in Python

If all you need is to clear the screen, this is probably good enough. The problem is there's not even a 100% cross platform way of doing this across linux versions. The problem is the implementations of the terminal all support slightly different things. I'm fairly sure that "clear" will work everywhere. But the more "complete" answer is to use the xterm control characters to move the cursor, but that requires xterm in and of itself.

Without knowing more of your problem, your solution seems good enough.

How to add calendar events in Android?

Google calendar is the "native" calendar app. As far as I know, all phones come with a version of it installed, and the default SDK provides a version.

You might check out this tutorial for working with it.

Execute Python script via crontab

As you have mentioned it doesn't change anything.

First, you should redirect both standard input and standard error from the crontab execution like below:

*/2 * * * * /usr/bin/python /home/souza/Documets/Listener/listener.py > /tmp/listener.log 2>&1

Then you can view the file /tmp/listener.log to see if the script executed as you expected.

Second, I guess what you mean by change anything is by watching the files created by your program:

f = file('counter', 'r+w')
json_file = file('json_file_create_server.json', 'r+w')

The crontab job above won't create these file in directory /home/souza/Documets/Listener, as the cron job is not executed in this directory, and you use relative path in the program. So to create this file in directory /home/souza/Documets/Listener, the following cron job will do the trick:

*/2 * * * * cd /home/souza/Documets/Listener && /usr/bin/python listener.py > /tmp/listener.log 2>&1

Change to the working directory and execute the script from there, and then you can view the files created in place.

How to map to multiple elements with Java 8 streams?

It's an interesting question, because it shows that there are a lot of different approaches to achieve the same result. Below I show three different implementations.


Default methods in Collection Framework: Java 8 added some methods to the collections classes, that are not directly related to the Stream API. Using these methods, you can significantly simplify the implementation of the non-stream implementation:

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    Map<String, DataSet> result = new HashMap<>();
    multiDataPoints.forEach(pt ->
        pt.keyToData.forEach((key, value) ->
            result.computeIfAbsent(
                key, k -> new DataSet(k, new ArrayList<>()))
            .dataPoints.add(new DataPoint(pt.timestamp, value))));
    return result.values();
}

Stream API with flatten and intermediate data structure: The following implementation is almost identical to the solution provided by Stuart Marks. In contrast to his solution, the following implementation uses an anonymous inner class as intermediate data structure.

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .flatMap(mdp -> mdp.keyToData.entrySet().stream().map(e ->
            new Object() {
                String key = e.getKey();
                DataPoint dataPoint = new DataPoint(mdp.timestamp, e.getValue());
            }))
        .collect(
            collectingAndThen(
                groupingBy(t -> t.key, mapping(t -> t.dataPoint, toList())),
                m -> m.entrySet().stream().map(e -> new DataSet(e.getKey(), e.getValue())).collect(toList())));
}

Stream API with map merging: Instead of flattening the original data structures, you can also create a Map for each MultiDataPoint, and then merge all maps into a single map with a reduce operation. The code is a bit simpler than the above solution:

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .map(mdp -> mdp.keyToData.entrySet().stream()
            .collect(toMap(e -> e.getKey(), e -> asList(new DataPoint(mdp.timestamp, e.getValue())))))
        .reduce(new HashMap<>(), mapMerger())
        .entrySet().stream()
        .map(e -> new DataSet(e.getKey(), e.getValue()))
        .collect(toList());
}

You can find an implementation of the map merger within the Collectors class. Unfortunately, it is a bit tricky to access it from the outside. Following is an alternative implementation of the map merger:

<K, V> BinaryOperator<Map<K, List<V>>> mapMerger() {
    return (lhs, rhs) -> {
        Map<K, List<V>> result = new HashMap<>();
        lhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
        rhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
        return result;
    };
}

I'm getting favicon.ico error

You can provide your own image and reference it in the head, for example:

<link rel="shortcut icon" href="images/favicon.ico">

Creating the Singleton design pattern in PHP5

/**
 * Singleton class
 *
 */
final class UserFactory
{
    /**
     * Call this method to get singleton
     *
     * @return UserFactory
     */
    public static function Instance()
    {
        static $inst = null;
        if ($inst === null) {
            $inst = new UserFactory();
        }
        return $inst;
    }

    /**
     * Private ctor so nobody else can instantiate it
     *
     */
    private function __construct()
    {

    }
}

To use:

$fact = UserFactory::Instance();
$fact2 = UserFactory::Instance();

$fact == $fact2;

But:

$fact = new UserFactory()

Throws an error.

See http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static to understand static variable scopes and why setting static $inst = null; works.

Where does gcc look for C and C++ header files?

The set of paths where the compiler looks for the header files can be checked by the command:-

cpp -v

If you declare #include "" , the compiler first searches in current directory of source file and if not found, continues to search in the above retrieved directories.

If you declare #include <> , the compiler searches directly in those directories obtained from the above command.

Source:- http://commandlinefanatic.com/cgi-bin/showarticle.cgi?article=art026

Convert Rtf to HTML

UPDATED:

I got home and tried the below code and it does not work. For anyone wondering, the clipboard does not just magically convert stuff like I'd hoped. Rather, it allows an application to sort of "upload" a data object with a variety of paste formats, and then then you paste (which in my metaphor would be the "download") the program being pasted into specifies its preferred format. I personally ended up using this code, which has been recommended previously, and it was enormously easy to use and very effective. After you have imported the code (in VStudio, Project -> Add Existing Files) you then just go html to rtf like this:

return HtmlToRtfConverter.ConvertHtmlToRtf(myRtfString);

or the opposite direction:

return RtfToHtmlConverter.ConvertHtmlToRtf(myHtmlString);

(below is my previous incorrect answer, in case anyone is interested in the chronology of this answer haha)

Most if not all of the above answers provide comprehensive, often Library-based solutions to the problem at hand. I am away from my computer and thus cannot test the idea, but one alternative, cheap and vaguely hack-y method would be the following.

private string HTMLFromRtf(string rtfString)
{
            Clipboard.SetData(DataFormats.Rtf, rtfString);
            return Clipboard.GetData(DataFormats.Html);         
}

Again, not totally sure if this would work, but just messing around with some html on my iPhone I suspect it would. Documentation is here. More in depth explanation/docs RE the getting and setting of data models in the clipboard can be found here.

(Yes I am fully aware I'm here years later, but I assume this question is one which some people still want answered).

How to assign multiple classes to an HTML container?

From the standard

7.5.2 Element identifiers: the id and class attributes

Attribute definitions

id = name [CS]
This attribute assigns a name to an element. This name must be unique in a document.

class = cdata-list [CS]
This attribute assigns a class name or set of class names to an element. Any number of elements may be assigned the same class name or names. Multiple class names must be separated by white space characters.

Yes, just put a space between them.

<article class="column wrapper">

Of course, there are many things you can do with CSS inheritance. Here is an article for further reading.

Replacing a fragment with another fragment inside activity group

you can use simple code its work for transaction

Fragment newFragment = new MainCategoryFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame_NavButtom, newFragment);
ft.commit(); 

Listen to port via a Java socket

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

$ nc -l 4000

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

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

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

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

Automapper missing type map configuration or unsupported mapping - Error

I found the solution, Thanks all for reply.

category = (Categoies)AutoMapper.Mapper.Map(viewModel, category, typeof(CategoriesViewModel), typeof(Categoies));

But, I have already dont know the reason. I cant understand fully.

Changing Locale within the app itself

Through the original question is not exactly about the locale itself all other locale related questions are referencing to this one. That's why I wanted to clarify the issue here. I used this question as a starting point for my own locale switching code and found out that the method is not exactly correct. It works, but only until any configuration change (e.g. screen rotation) and only in that particular Activity. Playing with a code for a while I have ended up with the following approach:

I have extended android.app.Application and added the following code:

public class MyApplication extends Application
{
    private Locale locale = null;

    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);
        if (locale != null)
        {
            newConfig.locale = locale;
            Locale.setDefault(locale);
            getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics());
        }
    }

    @Override
    public void onCreate()
    {
        super.onCreate();

        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);

        Configuration config = getBaseContext().getResources().getConfiguration();

        String lang = settings.getString(getString(R.string.pref_locale), "");
        if (! "".equals(lang) && ! config.locale.getLanguage().equals(lang))
        {
            locale = new Locale(lang);
            Locale.setDefault(locale);
            config.locale = locale;
            getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
        }
    }
}

This code ensures that every Activity will have custom locale set and it will not be reset on rotation and other events.

I have also spent a lot of time trying to make the preference change to be applied immediately but didn't succeed: the language changed correctly on Activity restart, but number formats and other locale properties were not applied until full application restart.

Changes to AndroidManifest.xml

Don't forget to add android:configChanges="layoutDirection|locale" to every activity at AndroidManifest, as well as the android:name=".MyApplication" to the <application> element.

Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve?

  1. If you have released to Apple TestFlight for testing

    You have to click the link each time and select No, only after that, your tester can see the build. This is quite annoying if you want to get your build delivered as soon as possible.

    enter image description here

  2. Do this for the next build, (If do this before the build then this error will not occur)

The solution is add the following setting to your iOS Info.plist:

    <key>ITSAppUsesNonExemptEncryption</key>
    <false/>

enter image description here

Can not add "Missing Compliance", see this Missing Compliance

HTML5 tag for horizontal line break

Simply use hr tag in HTML file and add below code in CSS file .

    hr {
       display: block;
       position: relative;
       padding: 0;
       margin: 8px auto;
       height: 0;
       width: 100%;
       max-height: 0;
       font-size: 1px;
       line-height: 0;
       clear: both;
       border: none;
       border-top: 1px solid #aaaaaa;
       border-bottom: 1px solid #ffffff;
    }

it works perfectly .

How to subtract 30 days from the current datetime in mysql?

SELECT date_format(current_date - INTERVAL 50 DAY,'%d-%b-%Y')

You can format by using date format in SQL.

Javascript add leading zeroes to date

I wrapped the correct answer of this question in a function that can add multiple leading zero's but defaults to adding 1 zero.

function zeroFill(nr, depth){
  depth = (depth === undefined)? 1 : depth;

  var zero = "0";
  for (var i = 0; i < depth; ++i) {
    zero += "0";
  }

  return (zero + nr).slice(-(depth + 1));
}

for working with numbers only and not more than 2 digits, this is also an approach:

function zeroFill(i) {
    return (i < 10 ? '0' : '') + i
  }

How to close a GUI when I push a JButton?

Add your button:

JButton close = new JButton("Close");

Add an ActionListener:

close.addActionListner(new CloseListener());

Add a class for the Listener implementing the ActionListener interface and override its main function:

private class CloseListener implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
        //DO SOMETHING
        System.exit(0);
    }
}

This might be not the best way, but its a point to start. The class for example can be made public and not as a private class inside another one.

How to run PyCharm in Ubuntu - "Run in Terminal" or "Run"?

For Pycharm CE 2018.3 and Ubuntu 18.04 with snap installation:

env BAMF_DESKTOP_FILE_HINT=/var/lib/snapd/desktop/applications/pycharm-community_pycharm-community.desktop /snap/bin/pycharm-community %f

I get this command from KDE desktop launch icon.

pychar-ce-command

Sorry for the language but I am a Spanish developer so I have my system in Spanish.

How to create threads in nodejs

Every node.js process is single threaded by design. Therefore to get multiple threads, you have to have multiple processes (As some other posters have pointed out, there are also libraries you can link to that will give you the ability to work with threads in Node, but no such capability exists without those libraries. See answer by Shawn Vincent referencing https://github.com/audreyt/node-webworker-threads)

You can start child processes from your main process as shown here in the node.js documentation: http://nodejs.org/api/child_process.html. The examples are pretty good on this page and are pretty straight forward.

Your parent process can then watch for the close event on any process it started and then could force close the other processes you started to achieve the type of one fail all stop strategy you are talking about.

Also see: Node.js on multi-core machines

"google is not defined" when using Google Maps V3 in Firefox remotely

Changed the

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API"> 
      function(){
            myMap()
                }
</script>

and made it

<script type="text/javascript">
      function(){
            myMap()
                }
</script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API"></script>

It worked :)

Selecting multiple columns in a Pandas dataframe

In the latest version of Pandas there is an easy way to do exactly this. Column names (which are strings) can be sliced in whatever manner you like.

columns = ['b', 'c']
df1 = pd.DataFrame(df, columns=columns)

CodeIgniter removing index.php from url

Besides these answers, one can just, add index.php or edit it (if it is already there) - for security you want to disable index.php anyway, from listing the files in your website directory - then change the content into

<?php
   header('location:your_required_starting.php'); 
?>

Each GROUP BY expression must contain at least one column that is not an outer reference

To start with you can't do this:

having rid!=MAX(rid)

The HAVING clause can only contain things which are attributes of the aggregate groups.

In addition, 1, 2, 3 is not valid in GROUP BY in SQL Server - I think that's only valid in ORDER BY.

Can you explain why this isn't what you are looking for:

select 
LEFT(SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000), PATINDEX('%[^0-9]%', SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000))-1),
qvalues.name,
qvalues.compound,
MAX(qvalues.rid)
 from batchinfo join qvalues on batchinfo.rowid=qvalues.rowid
where LEN(datapath)>4
group by LEFT(SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000), PATINDEX('%[^0-9]%', SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000))-1),
qvalues.name,
qvalues.compound

How to read Data from Excel sheet in selenium webdriver

i have used following method to use input data from excel sheet: Need to import following as well

import jxl.Workbook;

then

Workbook wBook = Workbook.getWorkbook(new File("E:\\Testdata\\ShellData.xls"));
//get sheet
jxl.Sheet Sheet = wBook.getSheet(0); 
//Now in application i have given my Username and Password input in following way
driver.findElement(By.xpath("//input[@id='UserName']")).sendKeys(Sheet.getCell(0, i).getContents());
driver.findElement(By.xpath("//input[@id='Password']")).sendKeys(Sheet.getCell(1, i).getContents());
driver.findElement(By.xpath("//input[@name='Login']")).click();

it will Work

How to get UTF-8 working in Java webapps?

Previous responses didn't work with my problem. It was only in production, with tomcat and apache mod_proxy_ajp. Post body lost non ascii chars by ? The problem finally was with JVM defaultCharset (US-ASCII in a default instalation: Charset dfset = Charset.defaultCharset();) so, the solution was run tomcat server with a modifier to run the JVM with UTF-8 as default charset:

JAVA_OPTS="$JAVA_OPTS -Dfile.encoding=UTF-8" 

(add this line to catalina.sh and service tomcat restart)

Maybe you must also change linux system variable (edit ~/.bashrc and ~/.profile for permanent change, see https://perlgeek.de/en/article/set-up-a-clean-utf8-environment)

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8

export LANGUAGE=en_US.UTF-8

Adding items in a Listbox with multiple columns

By using the List property.

ListBox1.AddItem "foo"
ListBox1.List(ListBox1.ListCount - 1, 1) = "bar"

How to remove empty lines with or without whitespace in Python

Surprised a multiline re.sub has not been suggested (Oh, because you've already split your string... But why?):

>>> import re
>>> a = "Foo\n \nBar\nBaz\n\n   Garply\n  \n"
>>> print a
Foo

Bar
Baz

        Garply


>>> print(re.sub(r'\n\s*\n','\n',a,re.MULTILINE))
Foo
Bar
Baz
        Garply

>>> 

Easy way to print Perl array? (with a little formatting)

You can simply print it.

@a = qw(abc def hij);

print "@a";

You will got:

abc def hij

Changing website favicon dynamically

According to WikiPedia, you can specify which favicon file to load using the link tag in the head section, with a parameter of rel="icon".

For example:

 <link rel="icon" type="image/png" href="/path/image.png">

I imagine if you wanted to write some dynamic content for that call, you would have access to cookies so you could retrieve your session information that way and present appropriate content.

You may fall foul of file formats (IE reportedly only supports it's .ICO format, whilst most everyone else supports PNG and GIF images) and possibly caching issues, both on the browser and through proxies. This would be because of the original itention of favicon, specifically, for marking a bookmark with a site's mini-logo.

How to parse/read a YAML file into a Python object?

If your YAML file looks like this:

# tree format
treeroot:
    branch1:
        name: Node 1
        branch1-1:
            name: Node 1-1
    branch2:
        name: Node 2
        branch2-1:
            name: Node 2-1

And you've installed PyYAML like this:

pip install PyYAML

And the Python code looks like this:

import yaml
with open('tree.yaml') as f:
    # use safe_load instead load
    dataMap = yaml.safe_load(f)

The variable dataMap now contains a dictionary with the tree data. If you print dataMap using PrettyPrint, you will get something like:

{
    'treeroot': {
        'branch1': {
            'branch1-1': {
                'name': 'Node 1-1'
            },
            'name': 'Node 1'
        },
        'branch2': {
            'branch2-1': {
                'name': 'Node 2-1'
            },
            'name': 'Node 2'
        }
    }
}

So, now we have seen how to get data into our Python program. Saving data is just as easy:

with open('newtree.yaml', "w") as f:
    yaml.dump(dataMap, f)

You have a dictionary, and now you have to convert it to a Python object:

class Struct:
    def __init__(self, **entries): 
        self.__dict__.update(entries)

Then you can use:

>>> args = your YAML dictionary
>>> s = Struct(**args)
>>> s
<__main__.Struct instance at 0x01D6A738>
>>> s...

and follow "Convert Python dict to object".

For more information you can look at pyyaml.org and this.

What is the difference between an expression and a statement in Python?

An expression is something that can be reduced to a value, for example "1+3" is an expression, but "foo = 1+3" is not.

It's easy to check:

print(foo = 1+3)

If it doesn't work, it's a statement, if it does, it's an expression.

Another statement could be:

class Foo(Bar): pass

as it cannot be reduced to a value.

Correct way to focus an element in Selenium WebDriver using Java

This code actually doesn't provide focus:

new Actions(driver).moveToElement(element).perform();

It provides a hover effect.

Additionally, the JS code .focus() requires that the window be active in order to work.

js.executeScript("element.focus();");

I have found that this code works:

element.sendKeys(Keys.SHIFT);

For my own code, I use both:

element.sendKeys(Keys.SHIFT);
js.executeScript("element.focus();");

Check whether values in one data frame column exist in a second data frame

Use %in% as follows

A$C %in% B$C

Which will tell you which values of column C of A are in B.

What is returned is a logical vector. In the specific case of your example, you get:

A$C %in% B$C
# [1]  TRUE FALSE  TRUE  TRUE

Which you can use as an index to the rows of A or as an index to A$C to get the actual values:

# as a row index
A[A$C %in% B$C,  ]  # note the comma to indicate we are indexing rows

# as an index to A$C
A$C[A$C %in% B$C]
[1] 1 3 4  # returns all values of A$C that are in B$C

We can negate it too:

A$C[!A$C %in% B$C]
[1] 2   # returns all values of A$C that are NOT in B$C



If you want to know if a specific value is in B$C, use the same function:

  2 %in% B$C   # "is the value 2 in B$C ?"  
  # FALSE

  A$C[2] %in% B$C  # "is the 2nd element of A$C in B$C ?"  
  # FALSE

Is it possible to make a Tree View with Angular?

Another example based off the original source, with a sample tree structure already in place (easier to see how it works IMO) and a filter to search the tree:

JSFiddle

React.js create loop through Array

As @Alexander solves, the issue is one of async data load - you're rendering immediately and you will not have participants loaded until the async ajax call resolves and populates data with participants.

The alternative to the solution they provided would be to prevent render until participants exist, something like this:

    render: function() {
        if (!this.props.data.participants) {
            return null;
        }
        return (
            <ul className="PlayerList">
            // I'm the Player List {this.props.data}
            // <Player author="The Mini John" />
            {
                this.props.data.participants.map(function(player) {
                    return <li key={player}>{player}</li>
                })
            }
            </ul>
        );
    }

How can I center text (horizontally and vertically) inside a div block?

This works for me (tested OK!):

HTML:

<div class="mydiv">
    <p>Item to be centered!</p>
</div>

CSS:

.mydiv {
    height: 100%; /* Or other */
    position: relative;
}

.mydiv p {
    margin: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-right: -50%;
    transform: translate(-50%, -50%); /* To compensate own width and height */
}

You can choose other values than 50%. For example, 25% to center at 25% of parent.

How do I simulate a hover with a touch in touch enabled browsers?

To answer your main question: “How do I simulate a hover with a touch in touch enabled browsers?”

Simply allow ‘clicking’ the element (by tapping the screen), and then trigger the hover event using JavaScript.

var p = document.getElementsByTagName('p')[0];
p.onclick = function() {
 // Trigger the `hover` event on the paragraph
 p.onhover.call(p);
};

This should work, as long as there’s a hover event on your device (even though it normally isn’t used).

Update: I just tested this technique on my iPhone and it seems to work fine. Try it out here: http://jsfiddle.net/mathias/YS7ft/show/light/

If you want to use a ‘long touch’ to trigger hover instead, you can use the above code snippet as a starting point and have fun with timers and stuff ;)

How to create a DB link between two oracle instances

Creation of DB Link

CREATE DATABASE LINK dblinkname
CONNECT TO $usename
IDENTIFIED BY $password
USING '$sid';

(Note: sid is being passed between single quotes above. )

Example Queries for above DB Link

select * from tableA@dblinkname;

insert into tableA(select * from tableA@dblinkname);

latex tabular width the same as the textwidth

The tabularx package gives you

  1. the total width as a first parameter, and
  2. a new column type X, all X columns will grow to fill up the total width.

For your example:

\usepackage{tabularx}
% ...    
\begin{document}
% ...

\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF &  simulation & jsp\\
\hline
\end{tabularx}

How do I get the entity that represents the current user in Symfony2?

$this->container->get('security.token_storage')->getToken()->getUser();

python pandas dataframe columns convert to dict key and value

If lakes is your DataFrame, you can do something like

area_dict = dict(zip(lakes.area, lakes.count))

What does `return` keyword mean inside `forEach` function?

From the Mozilla Developer Network:

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

Early termination may be accomplished with:

The other Array methods: every(), some(), find(), and findIndex() test the array elements with a predicate returning a truthy value to determine if further iteration is required.

Failed to find 'ANDROID_HOME' environment variable

In Windows, If you are running this command from VS code terminal and Even after setting up all the environment variable (i.e.build-tools, platform-tools, tools) it is not working trying running the same command from external cmd terminal. In my case even after starting a new VS code terminal, it was not able to take the updated Environment path.

It worked when I ran the same command from Windows cmd.

How to compare two dates along with time in java

Since Date implements Comparable<Date>, it is as easy as:

date1.compareTo(date2);

As the Comparable contract stipulates, it will return a negative integer/zero/positive integer if date1 is considered less than/the same as/greater than date2 respectively (ie, before/same/after in this case).

Note that Date has also .after() and .before() methods which will return booleans instead.

Ruby: How to post a file via HTTP as multipart/form-data?

Another one using only standard libraries:

uri = URI('https://some.end.point/some/path')
request = Net::HTTP::Post.new(uri)
request['Authorization'] = 'If you need some headers'
form_data = [['photos', photo.tempfile]] # or File.open() in case of local file

request.set_form form_data, 'multipart/form-data'
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| # pay attention to use_ssl if you need it
  http.request(request)
end

Tried a lot of approaches but only this was worked for me.

Toggle visibility property of div

It's better if you check visibility like this: if($('#video-over').is(':visible'))

What is the SSIS package and what does it do?

For Latest Info About SSIS > https://docs.microsoft.com/en-us/sql/integration-services/sql-server-integration-services

From the above referenced site:

Microsoft Integration Services is a platform for building enterprise-level data integration and data transformations solutions. Use Integration Services to solve complex business problems by copying or downloading files, loading data warehouses, cleansing and mining data, and managing SQL Server objects and data.

Integration Services can extract and transform data from a wide variety of sources such as XML data files, flat files, and relational data sources, and then load the data into one or more destinations.

Integration Services includes a rich set of built-in tasks and transformations, graphical tools for building packages, and the Integration Services Catalog database, where you store, run, and manage packages.

You can use the graphical Integration Services tools to create solutions without writing a single line of code. You can also program the extensive Integration Services object model to create packages programmatically and code custom tasks and other package objects.

Getting Started with SSIS - http://msdn.microsoft.com/en-us/sqlserver/bb671393.aspx

If you are Integration Services Information Worker - http://msdn.microsoft.com/en-us/library/ms141667.aspx

If you are Integration Services Administrator - http://msdn.microsoft.com/en-us/library/ms137815.aspx

If you are Integration Services Developer - http://msdn.microsoft.com/en-us/library/ms137709.aspx

If you are Integration Services Architect - http://msdn.microsoft.com/en-us/library/ms142161.aspx

Overview of SSIS - http://msdn.microsoft.com/en-us/library/ms141263.aspx

Integration Services How-to Topics - http://msdn.microsoft.com/en-us/library/ms141767.aspx

Online Internet Explorer Simulators

You could try Firebug Lite

It's a pure JavaScript-implementation of Firebug that runs directly in any browser (at least in all major ones: IE6+, Firefox, Opera, Safari and Chrome)

You'll still need the VM to actually run IE, but at least you'll get a quicker testing cycle.

Jmeter - Run .jmx file through command line and get the summary report in a excel

Navigate to the jmeter/bin directory from command line and

jmeter -n -t <YourTestScript.jmx> -l <TestScriptsResults.jtl>

DataTable, How to conditionally delete rows

I don't have a windows box handy to try this but I think you can use a DataView and do something like so:

DataView view = new DataView(ds.Tables["MyTable"]);
view.RowFilter = "MyValue = 42"; // MyValue here is a column name

// Delete these rows.
foreach (DataRowView row in view)
{
  row.Delete();
}

I haven't tested this, though. You might give it a try.

PL/SQL ORA-01422: exact fetch returns more than requested number of rows

It can also be due to a duplicate entry in any of the tables that are used.

stop service in android

To stop the service we must use the method stopService():

  Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
  //startService(myService);
  stopService(myService);

then the method onDestroy() in the service is called:

  @Override
    public void onDestroy() {

        Log.i(TAG, "onCreate() , service stopped...");
    }

Here is a complete example including how to stop the service.

How to convert password into md5 in jquery?

Download and include this plugin

<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/md5.js"></script>

and use like

if(CryptoJS.MD5($("#txtOldPassword").val())) != oldPassword) {

}

//Following lines shows md5 value
//var hash = CryptoJS.MD5("Message");
//alert(hash);

git pull keeping local changes

Update: this literally answers the question asked, but I think KurzedMetal's answer is really what you want.

Assuming that:

  1. You're on the branch master
  2. The upstream branch is master in origin
  3. You have no uncommitted changes

.... you could do:

# Do a pull as usual, but don't commit the result:
git pull --no-commit

# Overwrite config/config.php with the version that was there before the merge
# and also stage that version:
git checkout HEAD config/config.php

# Create the commit:
git commit -F .git/MERGE_MSG

You could create an alias for that if you need to do it frequently. Note that if you have uncommitted changes to config/config.php, this would throw them away.

Unescape HTML entities in Javascript?

You can use Lodash unescape / escape function https://lodash.com/docs/4.17.5#unescape

import unescape from 'lodash/unescape';

const str = unescape('fred, barney, &amp; pebbles');

str will become 'fred, barney, & pebbles'

Div side by side without float

You can also use CSS3 flexbox layout, which is well supported nowadays.

.container {
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-between;
    background:black;
    height:400px;
    width:450px;
}

.left {
    flex: 0 0 300px;
    background:blue;
    height:200px;
}

.right {
    flex: 0 1 100px;
    background:green;
    height:300px;
}

See Example (with legacy styles for maximum compatiblity) & Learn more about flexbox.

How to start Activity in adapter?

For newer versions of sdk you have to set flag activity task.

public void onClick(View v)
 {
     Intent myactivity = new Intent(context.getApplicationContext(), OtherActivity.class);
     myactivity.addFlags(FLAG_ACTIVITY_NEW_TASK);
     context.getApplicationContext().startActivity(myactivity);
 }

How to format current time using a yyyyMMddHHmmss format?

Time package in Golang has some methods that might be worth looking.

func (Time) Format

func (t Time) Format(layout string) string Format returns a textual representation of the time value formatted according to layout, which defines the format by showing how the reference time,

Mon Jan 2 15:04:05 -0700 MST 2006 would be displayed if it were the value; it serves as an example of the desired output. The same display rules will then be applied to the time value. Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard and convenient representations of the reference time. For more information about the formats and the definition of the reference time, see the documentation for ANSIC and the other constants defined by this package.

Source (http://golang.org/pkg/time/#Time.Format)

I also found an example of defining the layout (http://golang.org/src/pkg/time/example_test.go)

func ExampleTime_Format() {
        // layout shows by example how the reference time should be represented.
        const layout = "Jan 2, 2006 at 3:04pm (MST)"
        t := time.Date(2009, time.November, 10, 15, 0, 0, 0, time.Local)
        fmt.Println(t.Format(layout))
        fmt.Println(t.UTC().Format(layout))
        // Output:
    // Nov 10, 2009 at 3:00pm (PST)
        // Nov 10, 2009 at 11:00pm (UTC)
    }

Show Youtube video source into HTML5 video tag?

how about doing it the way hooktube does it? they don't actually use the video URL for the html5 element, but the google video redirector url that calls upon that video. check out here's how they present some despacito random video...

<video id="player-obj" controls="" src="https://redirector.googlevideo.com/videoplayback?ratebypass=yes&amp;mt=1510077993----SKIPPED----amp;utmg=ytap1,,hd720"><source>Your browser does not support HTML5 video.</video>

the code is for the following video page https://hooktube.com/watch?v=72UO0v5ESUo

youtube to mp3 on the other hand has turned into extremely monetized monster that returns now download.html on half of video download requests... annoying...

the 2 links in this answer are to my personal experiences with both resources. how hooktube is nice and fresh and actually helps avoid censorship and geo restrictions.. check it out, it's pretty cool. and youtubeinmp4 is a popup monster now known as ConvertInMp4...

ISO C++ forbids comparison between pointer and integer [-fpermissive]| [c++]

char a[2] defines an array of char's. a is a pointer to the memory at the beginning of the array and using == won't actually compare the contents of a with 'ab' because they aren't actually the same types, 'ab' is integer type. Also 'ab' should be "ab" otherwise you'll have problems here too. To compare arrays of char you'd want to use strcmp.

Something that might be illustrative is looking at the typeid of 'ab':

#include <iostream>
#include <typeinfo>
using namespace std;
int main(){
    int some_int =5;
    std::cout << typeid('ab').name() << std::endl;
    std::cout << typeid(some_int).name() << std::endl;
    return 0;
}

on my system this returns:

i
i

showing that 'ab' is actually evaluated as an int.

If you were to do the same thing with a std::string then you would be dealing with a class and std::string has operator == overloaded and will do a comparison check when called this way.

If you wish to compare the input with the string "ab" in an idiomatic c++ way I suggest you do it like so:

#include <iostream>
#include <string>
using namespace std;
int main(){
    string a;
    cout<<"enter ab ";
    cin>>a;
    if(a=="ab"){
         cout<<"correct";
    }
    return 0;
}

This one is due to:

if(a=='ab') , here, a is const char* type (ie : array of char)

'ab' is a constant value,which isn't evaluated as string (because of single quote) but will be evaluated as integer.

Since char is a primitive type inherited from C, no operator == is defined.

the good code should be:

if(strcmp(a,"ab")==0) , then you'll compare a const char* to another const char* using strcmp.

Datetime in C# add days

DateTime is immutable. That means you cannot change it's state and have to assign the result of an operation to a variable.

endDate = endDate.AddDays(addedDays);

jQuery event to trigger action when a div is made visible

a hide/show event trigger based on Glenns ideea: removed toggle because it fires show/hide and we don't want 2fires for one event

$(function(){
    $.each(["show","hide", "toggleClass", "addClass", "removeClass"], function(){
        var _oldFn = $.fn[this];
        $.fn[this] = function(){
            var hidden = this.find(":hidden").add(this.filter(":hidden"));
            var visible = this.find(":visible").add(this.filter(":visible"));
            var result = _oldFn.apply(this, arguments);
            hidden.filter(":visible").each(function(){
                $(this).triggerHandler("show");
            });
            visible.filter(":hidden").each(function(){
                $(this).triggerHandler("hide");
            });
            return result;
        }
    });
});

How To Get The Current Year Using Vba

Try =Year(Now()) and format the cell as General.

Youtube autoplay not working on mobile devices with embedded HTML5 player

Have a look on code below. Tested and found working on Mobile and Tablet devices.

<!-- 1. The <iframe> (video player) will replace this <div> tag. -->
<div id="player"></div>

<script>
  // 2. This code loads the IFrame Player API code asynchronously.
  var tag = document.createElement('script');

  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      height: '390',
      width: '640',
      videoId: 'M7lc1UVf-VE',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {
    event.target.playVideo();
  }

  // 5. The API calls this function when the player's state changes.
  //    The function indicates that when playing a video (state=1),
  //    the player should play for six seconds and then stop.
  var done = false;
  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING && !done) {
      setTimeout(stopVideo, 6000);
      done = true;
    }
  }
  function stopVideo() {
    player.stopVideo();
  }
</script>

Generate an HTML Response in a Java Servlet

You need to have a doGet method as:

public void doGet(HttpServletRequest request,
        HttpServletResponse response)
throws IOException, ServletException
{
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Hola</title>");
    out.println("</head>");
    out.println("<body bgcolor=\"white\">");
    out.println("</body>");
    out.println("</html>");
}

You can see this link for a simple hello world servlet

WebSocket with SSL

1 additional caveat (besides the answer by kanaka/peter): if you use WSS, and the server certificate is not acceptable to the browser, you may not get any browser rendered dialog (like it happens for Web pages). This is because WebSockets is treated as a so-called "subresource", and certificate accept / security exception / whatever dialogs are not rendered for subresources.

Reference excel worksheet by name?

To expand on Ryan's answer, when you are declaring variables (using Dim) you can cheat a little bit by using the predictive text feature in the VBE, as in the image below. screenshot of predictive text in VBE

If it shows up in that list, then you can assign an object of that type to a variable. So not just a Worksheet, as Ryan pointed out, but also a Chart, Range, Workbook, Series and on and on.

You set that variable equal to the object you want to manipulate and then you can call methods, pass it to functions, etc, just like Ryan pointed out for this example. You might run into a couple snags when it comes to collections vs objects (Chart or Charts, Range or Ranges, etc) but with trial and error you'll get it for sure.

Rails 4: List of available datatypes

You might also find it useful to know generally what these data types are used for:

There's also references used to create associations. But, I'm not sure this is an actual data type.

New Rails 4 datatypes available in PostgreSQL:

  • :hstore - storing key/value pairs within a single value (learn more about this new data type)
  • :array - an arrangement of numbers or strings in a particular row (learn more about it and see examples)
  • :cidr_address - used for IPv4 or IPv6 host addresses
  • :inet_address - used for IPv4 or IPv6 host addresses, same as cidr_address but it also accepts values with nonzero bits to the right of the netmask
  • :mac_address - used for MAC host addresses

Learn more about the address datatypes here and here.

Also, here's the official guide on migrations: http://edgeguides.rubyonrails.org/migrations.html

How to install toolbox for MATLAB

Use ver it will list all the installed toolboxes and versions of the toolbox.

How to close existing connections to a DB

This should disconnect everyone else, and leave you as the only user:

alter database YourDb set single_user with rollback immediate

Note: Don't forget

alter database YourDb set MULTI_USER

after you're done!

On - window.location.hash - Change?

The only way to really do this (and is how the 'reallysimplehistory' does this), is by setting an interval that keeps checking the current hash, and comparing it against what it was before, we do this and let subscribers subscribe to a changed event that we fire if the hash changes.. its not perfect but browsers really don't support this event natively.


Update to keep this answer fresh:

If you are using jQuery (which today should be somewhat foundational for most) then a nice solution is to use the abstraction that jQuery gives you by using its events system to listen to hashchange events on the window object.

$(window).on('hashchange', function() {
  //.. work ..
});

The nice thing here is you can write code that doesn't need to even worry about hashchange support, however you DO need to do some magic, in form of a somewhat lesser known jQuery feature jQuery special events.

With this feature you essentially get to run some setup code for any event, the first time somebody attempts to use the event in any way (such as binding to the event).

In this setup code you can check for native browser support and if the browser doesn't natively implement this, you can setup a single timer to poll for changes, and trigger the jQuery event.

This completely unbinds your code from needing to understand this support problem, the implementation of a special event of this kind is trivial (to get a simple 98% working version), but why do that when somebody else has already.

Stored procedure - return identity as output parameter or scalar

Another option would be as the return value for the stored procedure (I don't suggest this though, as that's usually best for error values).

I've included it as both when it's inserting a single row in cases where the stored procedure was being consumed by both other SQL procedures and a front-end which couldn't work with OUTPUT parameters (IBATIS in .NET I believe):

CREATE PROCEDURE My_Insert
    @col1            VARCHAR(20),
    @new_identity    INT    OUTPUT
AS
BEGIN
    SET NOCOUNT ON

    INSERT INTO My_Table (col1)
    VALUES (@col1)

    SELECT @new_identity = SCOPE_IDENTITY()

    SELECT @new_identity AS id

    RETURN
END

The output parameter is easier to work with in T-SQL when calling from other stored procedures IMO, but some programming languages have poor or no support for output parameters and work better with result sets.

Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true

const mongoose = require('mongoose');

mongoose
  .connect(connection_string, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
    useFindAndModify: false,
  })
  .then((con) => {
    console.log("connected to db");
  });

try to use this

Maven error: Not authorized, ReasonPhrase:Unauthorized

The problem here was a typo error in the password used, which was not easily identified due to the characters / letters used in the password.

What are the "spec.ts" files generated by Angular CLI for?

The .spec.ts files are for unit tests for individual components. You can run Karma task runner through ng test. In order to see code coverage of unit test cases for particular components run ng test --code-coverage

What does the "@" symbol do in SQL?

The @CustID means it's a parameter that you will supply a value for later in your code. This is the best way of protecting against SQL injection. Create your query using parameters, rather than concatenating strings and variables. The database engine puts the parameter value into where the placeholder is, and there is zero chance for SQL injection.

How do I put the image on the right side of the text in a UIButton?

Do Yourself. Xcode10, swift4,

For programmatically UI design

enter image description here

 lazy var buttonFilter : ButtonRightImageLeftTitle = {
    var button = ButtonRightImageLeftTitle()
    button.setTitle("Playfir", for: UIControl.State.normal)
    button.setImage(UIImage(named: "filter"), for: UIControl.State.normal)
    button.backgroundColor = UIColor.red
    button.contentHorizontalAlignment = .left
    button.titleLabel?.font = UIFont.systemFont(ofSize: 16)
    return button
}()

Edge inset values are applied to a rectangle to shrink or expand the area represented by that rectangle. Typically, edge insets are used during view layout to modify the view’s frame. Positive values cause the frame to be inset (or shrunk) by the specified amount. Negative values cause the frame to be outset (or expanded) by the specified amount.

class ButtonRightImageLeftTitle: UIButton {

    override func layoutSubviews() {
        super.layoutSubviews()

        guard imageView != nil else { return }

        imageEdgeInsets = UIEdgeInsets(top: 5, left: (bounds.width - 35), bottom: 5, right: 5)
        titleEdgeInsets = UIEdgeInsets(top: 0, left: -((imageView?.bounds.width)! + 10), bottom: 0, right: 0 )

    }
}

for StoryBoard UI design

enter image description here enter image description here

Delete a closed pull request from GitHub

There is no way you can delete a pull request yourself -- you and the repo owner (and all users with push access to it) can close it, but it will remain in the log. This is part of the philosophy of not denying/hiding what happened during development.

However, if there are critical reasons for deleting it (this is mainly violation of Github Terms of Service), Github support staff will delete it for you.

Whether or not they are willing to delete your PR for you is something you can easily ask them, just drop them an email at [email protected]

UPDATE: Currently Github requires support requests to be created here: https://support.github.com/contact

Python webbrowser.open() to open Chrome browser

In the case of Windows, the path uses a UNIX-style path, so make the backslash into forward slashes.

webbrowser.get("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s").open("http://google.com")

See: Python: generic webbrowser.get().open() for chrome.exe does not work

I do not want to inherit the child opacity from the parent in CSS

My answer is not about static parent-child layout, its about animations.

I was doing an svg demo today, and i needed svg to be inside div (because svg is created with parent's div width and height, to animate the path around), and this parent div needed to be invisible during svg path animation (and then this div was supposed to animate opacity from 0 to 1, it's the most important part). And because parent div with opacity: 0 was hiding my svg, i came across this hack with visibility option (child with visibility: visible can be seen inside parent with visibility: hidden):

.main.invisible .test {
  visibility: hidden;
}
.main.opacity-zero .test {
  opacity: 0;
  transition: opacity 0s !important;
}
.test { // parent div
  transition: opacity 1s;
}
.test-svg { // child svg
  visibility: visible;
}

And then, in js, you removing .invisible class with timeout function, adding .opacity-zero class, trigger layout with something like whatever.style.top; and removing .opacity-zero class.

var $main = $(".main");
  setTimeout(function() {
    $main.addClass('opacity-zero').removeClass("invisible");
    $(".test-svg").hide();
    $main.css("top");
    $main.removeClass("opacity-zero");
  }, 3000);

Better to check this demo http://codepen.io/suez/pen/54bbb2f09e8d7680da1af2faa29a0aef?editors=011

Get city name using geolocation

_x000D_
_x000D_
$.ajax({_x000D_
  url: "https://geolocation-db.com/jsonp",_x000D_
  jsonpCallback: "callback",_x000D_
  dataType: "jsonp",_x000D_
  success: function(location) {_x000D_
    $('#country').html(location.country_name);_x000D_
    $('#state').html(location.state);_x000D_
    $('#city').html(location.city);_x000D_
    $('#latitude').html(location.latitude);_x000D_
    $('#longitude').html(location.longitude);_x000D_
    $('#ip').html(location.IPv4);_x000D_
  }_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div>Country: <span id="country"></span></div>_x000D_
  <div>State: <span id="state"></span></div>_x000D_
    <div>City: <span id="city"></span></div>_x000D_
      <div>Latitude: <span id="latitude"></span></div>_x000D_
        <div>Longitude: <span id="longitude"></span></div>_x000D_
          <div>IP: <span id="ip"></span></div>
_x000D_
_x000D_
_x000D_

Using html5 geolocation requires user permission. In case you don't want this, go for an external locator like https://geolocation-db.com IPv6 is supported. No restrictions and unlimited requests allowed.

Example

For a pure javascript example, without using jQuery, check out this answer.

Insert entire DataTable into database at once instead of row by row?

I would prefer user defined data type : it is super fast.

Step 1 : Create User Defined Table in Sql Server DB

CREATE TYPE [dbo].[udtProduct] AS TABLE(
  [ProductID] [int] NULL,
  [ProductName] [varchar](50) NULL,
  [ProductCode] [varchar](10) NULL
)
GO

Step 2 : Create Stored Procedure with User Defined Type

CREATE PROCEDURE ProductBulkInsertion 
@product udtProduct readonly
AS
BEGIN
    INSERT INTO Product
    (ProductID,ProductName,ProductCode)
    SELECT ProductID,ProductName,ProductCode
    FROM @product
END

Step 3 : Execute Stored Procedure from c#

SqlCommand sqlcmd = new SqlCommand("ProductBulkInsertion", sqlcon);
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Parameters.AddWithValue("@product", productTable);
sqlcmd.ExecuteNonQuery();

Possible Issue : Alter User Defined Table

Actually there is no sql server command to alter user defined type But in management studio you can achieve this from following steps

1.generate script for the type.(in new query window or as a file) 2.delete user defied table. 3.modify the create script and then execute.

How to compare only date in moment.js

In my case i did following code for compare 2 dates may it will help you ...

_x000D_
_x000D_
var date1 = "2010-10-20";_x000D_
var date2 = "2010-10-20";_x000D_
var time1 = moment(date1).format('YYYY-MM-DD');_x000D_
var time2 = moment(date2).format('YYYY-MM-DD');_x000D_
if(time2 > time1){_x000D_
 console.log('date2 is Greter than date1');_x000D_
}else if(time2 > time1){_x000D_
 console.log('date2 is Less than date1');_x000D_
}else{_x000D_
 console.log('Both date are same');_x000D_
}
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
_x000D_
_x000D_

Count how many files in directory PHP

Working Demo

<?php

$directory = "../images/team/harry/"; // dir location
if (glob($directory . "*.*") != false)
{
 $filecount = count(glob($directory . "*.*"));
 echo $filecount;
}
else
{
 echo 0;
}

?>

Adding gif image in an ImageView in android

We can easily add animated gif image on imageview using Ion library.

Tutorial video :: https://www.youtube.com/watch?v=IqKtpdeIpjA

ImageView image = (ImageView)findViewById(R.id.image_gif);
Ion.with(image).load("http://mygifimage.gif");

What is NODE_ENV and how to use it in Express?

NODE_ENV is an environment variable made popular by the express web server framework. When a node application is run, it can check the value of the environment variable and do different things based on the value. NODE_ENV specifically is used (by convention) to state whether a particular environment is a production or a development environment. A common use-case is running additional debugging or logging code if running in a development environment.

Accessing NODE_ENV

You can use the following code to access the environment variable yourself so that you can perform your own checks and logic:

var environment = process.env.NODE_ENV

Assume production if you don't recognise the value:

var isDevelopment = environment === 'development'

if (isDevelopment) {
  setUpMoreVerboseLogging()
}

You can alternatively using express' app.get('env') function, but note that this is NOT RECOMMENDED as it defaults to "development", which may result in development code being accidentally run in a production environment - it's much safer if your app throws an error if this important value is not set (or if preferred, defaults to production logic as above).

Be aware that if you haven't explicitly set NODE_ENV for your environment, it will be undefined if you access it from process.env, there is no default.

Setting NODE_ENV

How to actually set the environment variable varies from operating system to operating system, and also depends on your user setup.

If you want to set the environment variable as a one-off, you can do so from the command line:

  • linux & mac: export NODE_ENV=production
  • windows: $env:NODE_ENV = 'production'

In the long term, you should persist this so that it isn't unset if you reboot - rather than list all the possible methods to do this, I'll let you search how to do that yourself!

Convention has dictated that there are two 'main' values you should use for NODE_ENV, either production or development, all lowercase. There's nothing to stop you from using other values, (test, for example, if you wish to use some different logic when running automated tests), but be aware that if you are using third-party modules, they may explicitly compare with 'production' or 'development' to determine what to do, so there may be side effects that aren't immediately obvious.

Finally, note that it's a really bad idea to try to set NODE_ENV from within a node application itself - if you do, it will only be applied to the process from which it was set, so things probably won't work like you'd expect them to. Don't do it - you'll regret it.

Make: how to continue after a command fails?

To get make to actually ignore errors on a single line, you can simply suffix it with ; true, setting the return value to 0. For example:

rm .lambda .lambda_t .activity .activity_t_lambda 2>/dev/null; true

This will redirect stderr output to null, and follow the command with true (which always returns 0, causing make to believe the command succeeded regardless of what actually happened), allowing program flow to continue.

Converting Symbols, Accent Letters to English Alphabet

Reposting my post from How do I remove diacritics (accents) from a string in .NET?

This method works fine in java (purely for the purpose of removing diacritical marks aka accents).

It basically converts all accented characters into their deAccented counterparts followed by their combining diacritics. Now you can use a regex to strip off the diacritics.

import java.text.Normalizer;
import java.util.regex.Pattern;

public String deAccent(String str) {
    String nfdNormalizedString = Normalizer.normalize(str, Normalizer.Form.NFD); 
    Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
    return pattern.matcher(nfdNormalizedString).replaceAll("");
}

What does collation mean?

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

Collation is the assembly of written information into a standard order. (...) A collation algorithm such as the Unicode collation algorithm defines an order through the process of comparing two given character strings and deciding which should come before the other.

Find size of object instance in bytes in c#

For unmanaged types aka value types, structs:

        Marshal.SizeOf(object);

For managed objects the closer i got is an approximation.

        long start_mem = GC.GetTotalMemory(true);

        aclass[] array = new aclass[1000000];
        for (int n = 0; n < 1000000; n++)
            array[n] = new aclass();

        double used_mem_median = (GC.GetTotalMemory(false) - start_mem)/1000000D;

Do not use serialization.A binary formatter adds headers, so you can change your class and load an old serialized file into the modified class.

Also it won't tell you the real size in memory nor will take into account memory alignment.

[Edit] By using BiteConverter.GetBytes(prop-value) recursivelly on every property of your class you would get the contents in bytes, that doesn't count the weight of the class or references but is much closer to reality. I would recommend to use a byte array for data and an unmanaged proxy class to access values using pointer casting if size matters, note that would be non-aligned memory so on old computers is gonna be slow but HUGE datasets on MODERN RAM is gonna be considerably faster, as minimizing the size to read from RAM is gonna be a bigger impact than unaligned.

How to adjust gutter in Bootstrap 3 grid system?

(Posted on behalf of the OP).

I believe I figured it out.

In my case, I added [class*="col-"] {padding: 0 7.5px;};.

Then added .row {margin: 0 -7.5px;}.

This works pretty well, except there is 1px margin on both sides. So I just make .row {margin: 0 -7.5px;} to .row {margin: 0 -8.5px;}, then it works perfectly.

I have no idea why there is a 1px margin. Maybe someone can explain it?

See the sample I created:

Demo
Code

How to split a string literal across multiple lines in C / Objective-C?

One more solution for the pile, change your .m file to .mm so that it becomes Objective-C++ and use C++ raw literals, like this:

const char *sql_query = R"(SELECT word_id
                           FROM table1, table2
                           WHERE table2.word_id = table1.word_id
                           ORDER BY table1.word ASC)";

Raw literals ignore everything until the termination sequence, which in the default case is parenthesis-quote.

If the parenthesis-quote sequence has to appear in the string somewhere, you can easily specify a custom delimiter too, like this:

const char *sql_query = R"T3RM!N8(
                                  SELECT word_id
                                  FROM table1, table2
                                  WHERE table2.word_id = table1.word_id
                                  ORDER BY table1.word ASC
                         )T3RM!N8";

How do I remove a library from the arduino environment?

I had to look for them in C:\Users\Dell\AppData\Local\Arduino15\

I had to take help from the "date created" and "date modified" attributes to identify which libraries to delete.

But the names still show in the IDE... But it is something I can live with for now.

LaTeX: Multiple authors in a two-column article

I put together a little test here:

\documentclass[10pt,twocolumn]{article}

\title{Article Title}
\author{
    First Author\\
    Department\\
    school\\
    email@edu
  \and
    Second Author\\
    Department\\
    school\\
    email@edu
    \and
    Third Author\\
    Department\\
    school\\
    email@edu
    \and
    Fourth Author\\
    Department\\
    school\\
    email@edu
}
\date{\today}

\begin{document}

\maketitle

\begin{abstract}
\ldots
\end{abstract}

\section{Introduction}
\ldots

\end{document}

Things to note, the title, author and date fields are declared before \begin{document}. Also, the multicol package is likely unnecessary in this case since you have declared twocolumn in the document class.

This example puts all four authors on the same line, but if your authors have longer names, departments or emails, this might cause it to flow over onto another line. You might be able to change the font sizes around a little bit to make things fit. This could be done by doing something like {\small First Author}. Here's a more detailed article on \LaTeX font sizes:

https://engineering.purdue.edu/ECN/Support/KB/Docs/LaTeXChangingTheFont

To italicize you can use {\it First Name} or \textit{First Name}.

Be careful though, if the document is meant for publication often times journals or conference proceedings have their own formatting guidelines so font size trickery might not be allowed.

How to convert An NSInteger to an int?

Ta da:

NSInteger myInteger = 42;
int myInt = (int) myInteger;

NSInteger is nothing more than a 32/64 bit int. (it will use the appropriate size based on what OS/platform you're running)

How to remove part of a string?

Easiest way I think is:

var s = yourString.replace(/.*_/g,"_");

CodeIgniter 500 Internal Server Error

You're trying to remove index.php from your site URL's, correct?

Try setting your $config['uri_protocol'] to REQUEST_URI instead of AUTO.

How do I kill background processes / jobs when my shell script exits?

trap 'kill $(jobs -p)' EXIT

I would make only minor changes to Johannes' answer and use jobs -pr to limit the kill to running processes and add a few more signals to the list:

trap 'kill $(jobs -pr)' SIGINT SIGTERM EXIT

Error: Segmentation fault (core dumped)

In my case I imported pyxlsd module before module wich works with db Mysql. After I did put Mysql module first(upper in code) it became to work like a clock. Think there was some namespace issue.

How to click on hidden element in Selenium WebDriver?

First store that element in object, let's say element and then write following code to click on that hidden element:

JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", element);

Pass multiple parameters to rest API - Spring

you can pass multiple params in url like

http://localhost:2000/custom?brand=dell&limit=20&price=20000&sort=asc

and in order to get this query fields , you can use map like

    @RequestMapping(method = RequestMethod.GET, value = "/custom")
    public String controllerMethod(@RequestParam Map<String, String> customQuery) {

        System.out.println("customQuery = brand " + customQuery.containsKey("brand"));
        System.out.println("customQuery = limit " + customQuery.containsKey("limit"));
        System.out.println("customQuery = price " + customQuery.containsKey("price"));
        System.out.println("customQuery = other " + customQuery.containsKey("other"));
        System.out.println("customQuery = sort " + customQuery.containsKey("sort"));

        return customQuery.toString();
    }

Localhost not working in chrome and firefox

I found that when I had this issue that I had to delete the application.config file from my solution. I was pulling the code from co-worker's repository whose config file was mapping to their local computer resources (and not my own). In addition to that, I had to create a new virtual directory as explained in the previous answers.

typescript: error TS2693: 'Promise' only refers to a type, but is being used as a value here

Please be aware that if you are running the tsc command with a file name ie:

tsc testfile.ts

then the tsconfig.json compiler configuration file is ignored. The solution is to run either the tsc command on its own, in which case all .ts files in the directory will be compiled, unless you have edited the tsconfig.json to include a set of files.

see 'using the files property'... https://www.typescriptlang.org/docs/handbook/tsconfig-json.html

How do you copy and paste into Git Bash

console2 ( http://sourceforge.net/projects/console/ ) is my go to terminal front end.

it add great features like copy/paste, resizable windows, and tabs. you can also integrate as many "terminals" as you want into the app. i personally use cmd (the basic windows prompt), mingW/msysGit, and i have shortcuts for diving directly into the python and mysql interpreters.

the "shell" argument i use for git (on a win7 machine) is:

C:\Windows\SysWOW64\cmd.exe /c ""C:\Program Files (x86)\Git\bin\sh.exe" --login -i"

How to Completely Uninstall Xcode and Clear All Settings

Before taking such drastic measures, quit Xcode and follow all the instructions here for cleaning out the caches:

How to Empty Caches and Clean All Targets Xcode 4

If that doesn't help, and you decide you really need a clean installation of Xcode, then, in addition to all of the stuff in that answer, trash the Xcode app itself, plus trash your ~/Library/Developer folder and your ~/Library/Preferences/com.apple.dt.Xcode.plist file. I think that should just about do it.

dbms_lob.getlength() vs. length() to find blob size in oracle

length and dbms_lob.getlength return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength will return the number of bytes, which may differ from the number of characters in a multi-byte character set.

As the documentation doesn't specify what happens when you apply length on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength.

How to use code to open a modal in Angular 2?

Include jQuery as usual inside script tags in index.html.

After all the imports but before declaring @Component, add:

declare var $: any;

Now you are free to use jQuery anywhere in your Angular 2 TypeScript code:

$("#myModal").modal('show');

Reference: https://stackoverflow.com/a/38246116/2473022

php create object without class

you can always use new stdClass(). Example code:

   $object = new stdClass();
   $object->property = 'Here we go';

   var_dump($object);
   /*
   outputs:

   object(stdClass)#2 (1) {
      ["property"]=>
      string(10) "Here we go"
    }
   */

Also as of PHP 5.4 you can get same output with:

$object = (object) ['property' => 'Here we go'];

How to do a simple file search in cmd

You can search in windows by DOS and explorer GUI.

DOS:

1) DIR

2) ICACLS (searches for files and folders to set ACL on them)

3) cacls ..................................................

2) example

icacls c:*ntoskrnl*.* /grant system:(f) /c /t ,then use PMON from sysinternals to monitor what folders are denied accesss. The result contains

access path contains your drive

process name is explorer.exe

those were filters youu must apply

How to Validate Google reCaptcha on Form Submit

One issue I came up with that prevented these two files from working correctly was with my php.ini file for the website. Make sure this property is properly set, as follows:

allow_url_fopen = 

How to test the `Mosquitto` server?

Start the Mosquitto Broker
Open the terminal and type

mosquitto_sub -h 127.0.0.1 -t topic

Open another terminal and type
mosquitto_pub -h 127.0.0.1 -t topic -m "Hello"

Now you can switch to the previous terminal and there you can able to see the "Hello" Message.One terminal acts as publisher and another one subscriber.

How to determine if a String has non-alphanumeric characters?

string.matches("^\\W*$"); should do what you want, but it does not include whitespace. string.matches("^(?:\\W|\\s)*$"); does match whitespace as well.

CSS selector for text input fields?

You can use :text Selector to select all inputs with type text

Working Fiddle

$(document).ready(function () {
    $(":text").css({    //or $("input:text")
        'background': 'green',
        'color':'#fff'
    });
});

:text is a jQuery extension and not part of the CSS specification, queries using :text cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use [type="text"] instead. This will work for IE6+.

$("[type=text]").css({  // or $("input[type=text]")
    'background': 'green',
    'color':'#fff'
});

CSS

[type=text] // or input[type=text] 
{
    background: green;
}

What's sizeof(size_t) on 32-bit vs the various 64-bit data models?

size_t is 64 bit normally on 64 bit machine

how do you pass images (bitmaps) between android activities using bundles?

in first.java

Intent i = new Intent(this, second.class);
                    i.putExtra("uri",uri);
                    startActivity(i);

in second.java

Bundle bd = getIntent().getExtras();
        Uri uri = bd.getParcelable("uri");
        Log.e("URI", uri.toString());
        try {
            Bitmap bitmap = Media.getBitmap(this.getContentResolver(), uri);
            imageView.setImageBitmap(bitmap);

        } 
        catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

“Origin null is not allowed by Access-Control-Allow-Origin” error for request made by application running from a file:// URL

If you are doing local testing or calling the file from something like file:// then you need to disable browser security.

On MAC: open -a Google\ Chrome --args --disable-web-security

Getting value GET OR POST variable using JavaScript?

When i had the issue i saved the value into a hidden input:

in html body:

    <body>
    <?php 
    if (isset($_POST['Id'])){
      $fid= $_POST['Id']; 
    }
    ?>

... then put the hidden input on the page and write the value $fid with php echo

    <input type=hidden id ="fid" name=fid value="<?php echo $fid ?>">

then in $(document).ready( function () {

    var postId=document.getElementById("fid").value;

so i got my hidden url parameter in php an js.

How to save password when using Subversion from the console

To add to Heath's answer: It looks like Subversion 1.6 disabled storing passwords by default if it can't store them in encrypted form. You can allow storing unencrypted passwords by explicitly setting password-stores = (that is, to the empty value) in ~/.subversion/config.

To check which password store subversion uses, look in ~/.subversion/auth/svn.simple. This contains several files, each a hash table with a simple key/value encoding. The svn:realmstring in each file identifies which realm that file is for. If the file has

K 8
passtype
V 6
simple

then it stores the password in plain text somewhere in that file, in a K 8 password entry. Else, it tries to use one of the configured password-stores.

iPhone hide Navigation Bar only on first page

Hiding navigation bar only on first page can be achieved through storyboard as well. On storyboard, goto Navigation Controller Scene->Navigation Bar. And select 'Hidden' property from the Attributes inspector. This will hide navigation bar starting from first viewcontroller until its made visible for the required viewcontroller.

Navigation bar can be set back to visible in ViewController's ViewWillAppear callback.

-(void)viewWillAppear:(BOOL)animated {

    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [super viewWillAppear:animated];                                                  
}

What is the difference between rb and r+b modes in file objects

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

Source: Reading and Writing Files

Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object

Another possible solution, that worked for me:

Currently, react-router-redux is in beta and npm returns 4.x, but not 5.x. But the @types/react-router-redux returned 5.x. So there were undefined variables used.

Forcing NPM/Yarn to use 5.x solved it for me.

How is using OnClickListener interface different via XML and Java code?

using XML, you need to set the onclick listener yourself. First have your class implements OnClickListener then add the variable Button button1; then add this to your onCreate()

button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);

when you implement OnClickListener you need to add the inherited method onClick() where you will handle your clicks

Unix command-line JSON parser?

If you're looking for a portable C compiled tool:

http://stedolan.github.com/jq/

From the website:

jq is like sed for JSON data - you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text.

jq can mangle the data format that you have into the one that you want with very little effort, and the program to do so is often shorter and simpler than you’d expect.

Tutorial: http://stedolan.github.com/jq/tutorial/
Manual: http://stedolan.github.com/jq/manual/
Download: http://stedolan.github.com/jq/download/

Check if list contains element that contains a string and get that element

I have not seen bool option in other answers so I hope below code will help someone.

Just use Any()

string myString = "test";
bool exists = myList
             .Where(w => w.COLUMN_TO_CHECK.Contains(myString)).Any();

What is the Oracle equivalent of SQL Server's IsNull() function?

Instead of ISNULL(), use NVL().

T-SQL:

SELECT ISNULL(SomeNullableField, 'If null, this value') FROM SomeTable

PL/SQL:

SELECT NVL(SomeNullableField, 'If null, this value') FROM SomeTable

Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document'

You are allowed to use IDs that start with a digit in your HTML5 documents:

The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.

There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.

But querySelector method uses CSS3 selectors for querying the DOM and CSS3 doesn't support ID selectors that start with a digit:

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit.

Use a value like b22 for the ID attribute and your code will work.

Since you want to select an element by ID you can also use .getElementById method:

document.getElementById('22')