Programs & Examples On #Javax.script

A scripting API consists of interfaces and classes that define Java Scripting Engines and provides a framework for their use in Java applications.

Call external javascript functions from java code

try {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        System.out.println("okay1");
        FileInputStream fileInputStream = new FileInputStream("C:/Users/Kushan/eclipse-workspace/sureson.lk/src/main/webapp/js/back_end_response.js");
        System.out.println("okay2");
        if (fileInputStream != null){
         BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
         engine.eval(reader);
         System.out.println("okay3");
        // Invocable javascriptEngine = null;
         System.out.println("okay4");
        Invocable invocableEngine = (Invocable)engine;
         System.out.println("okay5");
         int x=0;
         System.out.println("invocableEngine is : "+invocableEngine);
         Object object = invocableEngine.invokeFunction("backend_message",x);

         System.out.println("okay6");
        }
        }catch(Exception e) {
            System.out.println("erroe when calling js function"+ e);
        }

Printing Exception Message in java

try {
} catch (javax.script.ScriptException ex) {
// System.out.println(ex.getMessage());
}

How to retrieve checkboxes values in jQuery

If you want to insert the value of any checkbox immediately as it is being checked then this should work for you:

$(":checkbox").click(function(){
  $("#id").text(this.value)
})

Error 500: Premature end of script headers

Check your line endings! If you see an error about the file not being found, followed by this "premature of end headers" error in your Apache log - it may be that you have Windows line endings in your script in instead of Unix style. I ran into that problem / solution.

Offset a background image from the right using CSS

If you would like to use this for adding arrows/other icons to a button for example then you could use css pseudo-elements?

If it's really a background-image for the whole button, I tend to incorporate the spacing into the image, and just use

background-position: right 0;

But if I have to add for example a designed arrow to a button, I tend to have this html:

<a href="[url]" class="read-more">Read more</a>

And tend to do the following with CSS:

.read-more{
    position: relative;
    padding: 6px 15px 6px 35px;//to create space on the right
    font-size: 13px;
    font-family: Arial;
}

.read-more:after{
    content: '';
    display: block;
    width: 10px;
    height: 15px;
    background-image: url('../images/btn-white-arrow-right.png');
    position: absolute;
    right: 12px;
    top: 10px;
}

By using the :after selector, I add a element using CSS just to contain this small icon. You could do the same by just adding a span or <i> element inside the a-element. But I think this is a cleaner way of adding icons to buttons and it is cross-browser supported.

you can check out the fiddle here: http://codepen.io/anon/pen/PNzYzZ

How to convert a byte array to Stream

Easy, simply wrap a MemoryStream around it:

Stream stream = new MemoryStream(buffer);

How to prevent Browser cache on Angular 2 site?

A combination of @Jack's answer and @ranierbit's answer should do the trick.

Set the ng build flag for --output-hashing so:

ng build --output-hashing=all

Then add this class either in a service or in your app.module

@Injectable()
export class NoCacheHeadersInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler) {
        const authReq = req.clone({
            setHeaders: {
                'Cache-Control': 'no-cache',
                 Pragma: 'no-cache'
            }
        });
        return next.handle(authReq);    
    }
}

Then add this to your providers in your app.module:

providers: [
  ... // other providers
  {
    provide: HTTP_INTERCEPTORS,
    useClass: NoCacheHeadersInterceptor,
    multi: true
  },
  ... // other providers
]

This should prevent caching issues on live sites for client machines

Get started with Latex on Linux

LaTeX comes with most Linux distributions in the form of the teTeX distribution. Find all packages with 'teTeX' in the name and install them.

  • Most editors such as vim or emacs come with TeX editing modes. You can also get WYSIWIG-ish front-ends (technically WYSIWYM), of which perhaps the best known is LyX.

  • The best quick intro to LaTeX is Oetiker's 'The not so short intro to LaTeX'

  • LaTeX works like a compiler. You compile the LaTeX document (which can include other files), which generates a file called a .dvi (device independent). This can be post-processed to various formats (including PDF) with various post-processors.

  • To do PDF, use dvips and use the flag -PPDF (IIRC - I don't have a makefile to hand) to produce a PS with font rendering set up for conversion to pdf. PDF conversion can then be done with ps2pdf or distiller (if you have this).

  • The best format for including graphics in this environment is eps (Encapsulated Postscript) although not all software produces well-behaved postscript. Photographs in jpeg or other formats can be included using various mechanisms.

CSS position:fixed inside a positioned element

I achieved to have an element with a fixed position (wiewport) but relative to the width of its parent.

I just had to wrap my fixed element and give the parent a width 100%. At the same time, the wrapped fixed element and the parent are in a div which width changes depending on the page, containing the content of the website. With this approach I can have the fixed element always at the same distance of the content, depending on the width of this one. In my case this was a 'to top' button, always showing at 15px from the bottom and 15px right from the content.

https://codepen.io/rafaqf/pen/MNqWKB

<div class="body">
  <div class="content">
    <p>Some content...</p>
    <div class="top-wrapper">
      <a class="top">Top</a>
    </div>
  </div>
</div>

.content {
  width: 600px; /*change this width to play with the top element*/
  background-color: wheat;
  height: 9999px;
  margin: auto;
  padding: 20px;
}
.top-wrapper {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  z-index: 9;
  .top {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 60px;
    height: 60px;
    border-radius: 100%;
    background-color: yellowgreen;
    position: fixed;
    bottom: 20px;
    margin-left: 100px;
    cursor: pointer;
    &:hover {
      opacity: .6;
    }
  }
}

How to pass parameters or arguments into a gradle task

You should consider passing the -P argument in invoking Gradle.

From Gradle Documentation :

--project-prop Sets a project property of the root project, for example -Pmyprop=myvalue. See Section 14.2, “Gradle properties and system properties”.

Considering this build.gradle

task printProp << {
    println customProp
}

Invoking Gradle -PcustomProp=myProp will give this output :

$ gradle -PcustomProp=myProp printProp
:printProp
myProp

BUILD SUCCESSFUL

Total time: 3.722 secs

This is the way I found to pass parameters.

How to "pull" from a local branch into another one?

you have to tell git where to pull from, in this case from the current directory/repository:

git pull . master

but when working locally, you usually just call merge (pull internally calls merge):

git merge master

Windows batch: call more than one command in a FOR loop?

SilverSkin and Anders are both correct. You can use parentheses to execute multiple commands. However, you have to make sure that the commands themselves (and their parameters) do not contain parentheses. cmd greedily searches for the first closing parenthesis, instead of handling nested sets of parentheses gracefully. This may cause the rest of the command line to fail to parse, or it may cause some of the parentheses to get passed to the commands (e.g. DEL myfile.txt)).

A workaround for this is to split the body of the loop into a separate function. Note that you probably need to jump around the function body to avoid "falling through" into it.

FOR /r %%X IN (*.txt) DO CALL :loopbody %%X
REM Don't "fall through" to :loopbody.
GOTO :EOF

:loopbody
ECHO %1
DEL %1
GOTO :EOF

How to display line numbers in 'less' (GNU)

From the manual:

-N or --LINE-NUMBERS Causes a line number to be displayed at the beginning of each line in the display.

You can also toggle line numbers without quitting less by typing -N.

It is possible to toggle any of less's command line options in this way.

Git and nasty "error: cannot lock existing info/refs fatal"

I fixed this by doing the following

git branch --unset-upstream
rm .git/refs/remotes/origin/{branch}
git gc --prune=now
git branch --set-upstream-to=origin/{branch} {branch}
#or git push --set-upstream origin {branch}
git pull

This assuming that your local and remote branches are aligned and you are just getting the refs error as non fatal.

How can a divider line be added in an Android RecyclerView?

Alright, if don't need your divider color to be changed just apply alpha to the divider decorations.

Example for GridLayoutManager with transparency:

DividerItemDecoration horizontalDividerItemDecoration = new DividerItemDecoration(WishListActivity.this,
                DividerItemDecoration.HORIZONTAL);
        horizontalDividerItemDecoration.getDrawable().setAlpha(50);
        DividerItemDecoration verticalDividerItemDecoration = new DividerItemDecoration(WishListActivity.this,
                DividerItemDecoration.VERTICAL);
        verticalDividerItemDecoration.getDrawable().setAlpha(50);
        my_recycler.addItemDecoration(horizontalDividerItemDecoration);
        my_recycler.addItemDecoration(verticalDividerItemDecoration);

You can still change the color of dividers by just setting color filters to it.

Example for GridLayoutManager by setting tint:

DividerItemDecoration horizontalDividerItemDecoration = new DividerItemDecoration(WishListActivity.this,
                DividerItemDecoration.HORIZONTAL);
        horizontalDividerItemDecoration.getDrawable().setTint(getResources().getColor(R.color.colorAccent));
        DividerItemDecoration verticalDividerItemDecoration = new DividerItemDecoration(WishListActivity.this,
                DividerItemDecoration.VERTICAL);
        verticalDividerItemDecoration.getDrawable().setAlpha(50);
        my_recycler.addItemDecoration(horizontalDividerItemDecoration);
        my_recycler.addItemDecoration(verticalDividerItemDecoration);

Additionally you can also try setting color filter,

 horizontalDividerItemDecoration.getDrawable().setColorFilter(colorFilter);

Encode URL in JavaScript?

You have three options:

  • escape() will not encode: @*/+

  • encodeURI() will not encode: ~!@#$&*()=:/,;?+'

  • encodeURIComponent() will not encode: ~!*()'

But in your case, if you want to pass a URL into a GET parameter of other page, you should use escape or encodeURIComponent, but not encodeURI.

See Stack Overflow question Best practice: escape, or encodeURI / encodeURIComponent for further discussion.

Zero an array in C code

int arr[20] = {0} would be easiest if it only needs to be done once.

Error "can't load package: package my_prog: found packages my_prog and main"

Also, if all you are trying to do is break up the main.go file into multiple files, then just name the other files "package main" as long as you only define the main function in one of those files, you are good to go.

How to restore a SQL Server 2012 database to SQL Server 2008 R2?

As has been mentioned already, you cannot use the "Back up" and "Restore" features to go from a SQL Server 2012 DB to a SQL Server 2008 DB. A program I wrote, SQL Server Scripter, will however connect to a SQL Server database and script out a database, its schema and data. It can be git cloned from BitBucket, and compiled with Visual Studio 2010 or later (if it's a later version, just open the .csproj).

Java: how to use UrlConnection to post request with authorization?

I ran into this problem today and none of the solutions posted here worked. However, the code posted here worked for a POST request:

// HTTP POST request
private void sendPost() throws Exception {

    String url = "https://selfsolve.apple.com/wcResults.do";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    //print result
    System.out.println(response.toString());

}

It turns out that it's not the authorization that's the problem. In my case, it was an encoding problem. The content-type I needed was application/json but from the Java documentation:

static String encode(String s, String enc)
Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme.

The encode function translates the string into application/x-www-form-urlencoded.

Now if you don't set a Content-Type, you may get a 415 Unsupported Media Type error. If you set it to application/json or anything that's not application/x-www-form-urlencoded, you get an IOException. To solve this, simply avoid the encode method.

For this particular scenario, the following should work:

String data = "product[title]=" + title +
                "&product[content]=" + content + 
                "&product[price]=" + price.toString() +
                "&tags=" + tags;

Another small piece of information that might be helpful as to why the code breaks when creating the buffered reader is because the POST request actually only gets executed when conn.getInputStream() is called.

Removing whitespace from strings in Java

public static void main(String[] args) {        
    String s = "name=john age=13 year=2001";
    String t = s.replaceAll(" ", "");
    System.out.println("s: " + s + ", t: " + t);
}

Output:
s: name=john age=13 year=2001, t: name=johnage=13year=2001

Python loop that also accesses previous and next values

Pythonic and elegant way:

objects = [1, 2, 3, 4, 5]
value = 3
if value in objects:
   index = objects.index(value)
   previous_value = objects[index-1]
   next_value = objects[index+1] if index + 1 < len(objects) else None

Address already in use: JVM_Bind java

I was having this problem too. For me, I couldn't start/stop openfire (it said it was stopped, but everything was still running)

sudo /etc/init.d/openfire stop
sudo /etc/init.d/openfire start

Also, restarting apache did not help either

sudo /etc/init.d/apache2 restart

The errors were inside:

/opt/openfire/logs/stderror.log
Error creating server listener on port 5269: Address already in use
Error creating server listener on port 5222: Address already in use

The way I fixed this, I had to actually turn off the server inside the admin area for my host.

jQuery - If element has class do this

First, you're missing some parentheses in your conditional:

if ($("#about").hasClass("opened")) {
  $("#about").animate({right: "-700px"}, 2000);
}

But you can also simplify this to:

$('#about.opened').animate(...);

If #about doesn't have the opened class, it won't animate.

If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)

HTML5 input type range show range value

I have a solution that involves (Vanilla) JavaScript, but only as a library. You habe to include it once and then all you need to do is set the appropriate source attribute of the number inputs.

The source attribute should be the querySelectorAll selector of the range input you want to listen to.

It even works with selectcs. And it works with multiple listeners. And it works in the other direction: change the number input and the range input will adjust. And it will work on elements added later onto the page (check https://codepen.io/HerrSerker/pen/JzaVQg for that)

Tested in Chrome, Firefox, Edge and IE11

_x000D_
_x000D_
;(function(){_x000D_
  _x000D_
  function emit(target, name) {_x000D_
    var event_x000D_
    if (document.createEvent) {_x000D_
      event = document.createEvent("HTMLEvents");_x000D_
      event.initEvent(name, true, true);_x000D_
    } else {_x000D_
      event = document.createEventObject();_x000D_
      event.eventType = name;_x000D_
    }_x000D_
_x000D_
    event.eventName = name;_x000D_
_x000D_
    if (document.createEvent) {_x000D_
      target.dispatchEvent(event);_x000D_
    } else {_x000D_
      target.fireEvent("on" + event.eventType, event);_x000D_
    }    _x000D_
  }_x000D_
_x000D_
  var outputsSelector = "input[type=number][source],select[source]";_x000D_
  _x000D_
  function onChange(e) {_x000D_
    var outputs = document.querySelectorAll(outputsSelector)_x000D_
    for (var index = 0; index < outputs.length; index++) {_x000D_
      var item = outputs[index]_x000D_
      var source = document.querySelector(item.getAttribute('source'));_x000D_
      if (source) {_x000D_
        if (item === e.target) {_x000D_
          source.value = item.value_x000D_
          emit(source, 'input')_x000D_
          emit(source, 'change')_x000D_
        }_x000D_
_x000D_
        if (source === e.target) {_x000D_
          item.value = source.value_x000D_
        }_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  document.addEventListener('change', onChange)_x000D_
  document.addEventListener('input', onChange)_x000D_
}());
_x000D_
<div id="div">_x000D_
  <input name="example" type="range" max="2250000" min="-200000" value="0" step="50000">_x000D_
  <input id="example-value" type="number" max="2250000" min="-200000" value="0" step="50000" source="[name=example]">_x000D_
  <br>_x000D_
_x000D_
  <input name="example2" type="range" max="2240000" min="-160000" value="0" step="50000">_x000D_
  <input type="number" max="2240000" min="-160000" value="0" step="50000" source="[name=example2]">_x000D_
  <input type="number" max="2240000" min="-160000" value="0" step="50000" source="[name=example2]">_x000D_
  <br>_x000D_
  _x000D_
  <input name="example3" type="range" max="20" min="0" value="10" step="1">_x000D_
  <select source="[name=example3]">_x000D_
    <option value="0">0</option>_x000D_
    <option value="1">1</option>_x000D_
    <option value="2">2</option>_x000D_
    <option value="3">3</option>_x000D_
    <option value="4">4</option>_x000D_
    <option value="5">5</option>_x000D_
    <option value="6">6</option>_x000D_
    <option value="7">7</option>_x000D_
    <option value="8">8</option>_x000D_
    <option value="9">9</option>_x000D_
    <option value="10">10</option>_x000D_
    <option value="11">11</option>_x000D_
    <option value="12">12</option>_x000D_
    <option value="13">13</option>_x000D_
    <option value="14">14</option>_x000D_
    <option value="15">15</option>_x000D_
    <option value="16">16</option>_x000D_
    <option value="17">17</option>_x000D_
    <option value="18">18</option>_x000D_
    <option value="19">19</option>_x000D_
    <option value="20">20</option>_x000D_
  </select>_x000D_
  <br>_x000D_
  _x000D_
</div>_x000D_
<br>
_x000D_
_x000D_
_x000D_

Access to the path is denied

Make Directory savehere to be virtual directory and give read/write permission from control panel

Unique random string generation

If you want an alphanumeric strings with lowercase and uppercase characters ([a-zA-Z0-9]), you can use Convert.ToBase64String() for a fast and simple solution.

As for uniqueness, check out the birthday problem to calculate how likely a collission is given (A) the length of the strings generated and (B) the number of strings generated.

Random random = new Random();

int outputLength = 10;
int byteLength = (int)Math.Ceiling(3f / 4f * outputLength); // Base64 uses 4 characters for every 3 bytes of data; so in random bytes we need only 3/4 of the desired length
byte[] randomBytes = new byte[byteLength];
string output;
do
{
    random.NextBytes(randomBytes); // Fill bytes with random data
    output = Convert.ToBase64String(randomBytes); // Convert to base64
    output = output.Substring(0, outputLength); // Truncate any superfluous characters and/or padding
} while (output.Contains('/') || output.Contains('+')); // Repeat if we contain non-alphanumeric characters (~25% chance if length=10; ~50% chance if length=20; ~35% chance if length=32)

What exactly is OAuth (Open Authorization)?

OAuth is an open standard for authorization, commonly used as a way for Internet users to log into third party websites using their Microsoft, Google, Facebook or Twitter accounts without exposing their password.

Pick any kind of file via an Intent in Android

This gives me the best result:

    Intent intent;
    if (android.os.Build.MANUFACTURER.equalsIgnoreCase("samsung")) {
        intent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
        intent.putExtra("CONTENT_TYPE", "*/*");
        intent.addCategory(Intent.CATEGORY_DEFAULT);
    } else {

        String[] mimeTypes =
                {"application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .doc & .docx
                        "application/vnd.ms-powerpoint", "application/vnd.openxmlformats-officedocument.presentationml.presentation", // .ppt & .pptx
                        "application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xls & .xlsx
                        "text/plain",
                        "application/pdf",
                        "application/zip", "application/vnd.android.package-archive"};

        intent = new Intent(Intent.ACTION_GET_CONTENT); // or ACTION_OPEN_DOCUMENT
        intent.setType("*/*");
        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
    }

What is the difference between a Docker image and a container?

*In docker, an image is an immutable file that holds the source code and information needed for a docker app to run. It can exist independent of a container.

*Docker containers are virtualized environments created during runtime and require images to run. The docker website has an image that kind of shows this relationship:

docs.docker.com image

How to get the first column of a pandas DataFrame as a Series?

You can get the first column as a Series by following code:

x[x.columns[0]]

If a folder does not exist, create it

Use the below code. I use this code for file copy and creating a new folder.

string fileToCopy = "filelocation\\file_name.txt";
String server = Environment.UserName;
string newLocation = "C:\\Users\\" + server + "\\Pictures\\Tenders\\file_name.txt";
string folderLocation = "C:\\Users\\" + server + "\\Pictures\\Tenders\\";
bool exists = System.IO.Directory.Exists(folderLocation);

if (!exists)
{
   System.IO.Directory.CreateDirectory(folderLocation);
   if (System.IO.File.Exists(fileToCopy))
   {
     MessageBox.Show("file copied");
     System.IO.File.Copy(fileToCopy, newLocation, true);
   }
   else
   {
      MessageBox.Show("no such files");
   }
}

Is it possible to use jQuery to read meta tags

jQuery now supports .data();, so if you have

<div id='author' data-content='stuff!'>

use

var author = $('#author').data("content"); // author = 'stuff!'

Using a scanner to accept String input and storing in a String Array

One of the problem with this code is here :

name += contactName[];

This instruction won't insert anything in the array. Instead it will concatenate the current value of the variable name with the string representation of the contactName array.

Instead use this:

contactName[index] = name;

this instruction will store the variable name in the contactName array at the index index.

The second problem you have is that you don't have the variable index.

What you can do is a loop with 12 iterations to fill all your arrays. (and index will be your iteration variable)

how do I create an array in jquery?

your question makes no sense. you are asking how to turn a hash into an array. You cant.

you can make a list of values, or make a list of keys, and neither of these have anything to do with jquery, this is pure javascript

How to convert string to double with proper cultureinfo

You can convert the value user provides to a double and store it again as nvarchar, with the aid of FormatProviders. CultureInfo is a typical FormatProvider. Assuming you know the culture you are operating,

System.Globalization.CultureInfo EnglishCulture = new System.Globalization.CultureInfo("en-EN");
System.Globalization.CultureInfo GermanCulture = new System.Globalization.CultureInfo("de-de");

will suffice to do the neccesary transformation, like;

double val;
if(double.TryParse("65,89875", System.Globalization.NumberStyles.Float, GermanCulture,  out val))
{
    string valInGermanFormat = val.ToString(GermanCulture);
    string valInEnglishFormat = val.ToString(EnglishCulture);
}

if(double.TryParse("65.89875", System.Globalization.NumberStyles.Float, EnglishCulture,  out val))
{
    string valInGermanFormat = val.ToString(GermanCulture);
    string valInEnglishFormat = val.ToString(EnglishCulture);
}

How to determine the Boost version on a system?

@Vertexwahns answer, but written in bash. For the people who are lazy:

boost_version=$(cat /usr/include/boost/version.hpp | grep define | grep "BOOST_VERSION " | cut -d' ' -f3)
echo "installed boost version: $(echo "$boost_version / 100000" | bc).$(echo "$boost_version / 100 % 1000" | bc).$(echo "$boost_version % 100 " | bc)"

Gives me installed boost version: 1.71.0

How to use continue in jQuery each() loop?

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration. -- jQuery.each() | jQuery API Documentation

How to split one string into multiple strings separated by at least one space in bash shell?

Did you try just passing the string variable to a for loop? Bash, for one, will split on whitespace automatically.

sentence="This is   a sentence."
for word in $sentence
do
    echo $word
done

 

This
is
a
sentence.

Column name or number of supplied values does not match table definition

Update to SQL server 2016/2017/…
We have some stored procedures in place to import and export databases.
In the sp we use (amongst other things) RESTORE FILELISTONLY FROM DISK where we create a table "#restoretemp" for the restore from file.

With SQL server 2016, MS has added a field SnapshotURL nvarchar(360) (restore url Azure) what has caused the error message.
After I have enhanced the additional field, the restore has worked again.
Code snipped (see last field):

 SET @query = 'RESTORE FILELISTONLY FROM DISK = ' + QUOTENAME(@BackupFile , '''')
CREATE TABLE #restoretemp
(
LogicalName nvarchar(128)
,PhysicalName nvarchar(128)
,[Type] char(1)
,FileGroupName nvarchar(128)
,[Size] numeric(20,0)
,[MaxSize] numeric(20,0)
,FileID bigint
,CreateLSN numeric(25,0)
,DropLSN numeric(25,0) NULL
,UniqueID uniqueidentifier
,ReadOnlyLSN numeric(25,0)
,ReadWriteLSN numeric(25,0)
,BackupSizeInByte bigint
,SourceBlockSize int
,FilegroupID int
,LogGroupGUID uniqueidentifier NULL
,DifferentialBaseLSN numeric(25,0)
,DifferentialbaseGUID uniqueidentifier
,IsReadOnly bit
,IsPresent bit
,TDEThumbprint varbinary(32)
-- Added field 01.10.2018 needed from SQL Server 2016 (Azure URL)
,SnapshotURL nvarchar(360)
)

INSERT #restoretemp EXEC (@query)
SET @errorstat = @@ERROR
if @errorstat <> 0 
Begin
if @Rueckgabe = 0 SET @Rueckgabe = 6
End
Print @Rueckgabe

Where is virtualenvwrapper.sh after pip install?

in my case: /home/username/.local/bin/virtualenvwrapper.sh

Unable to locate an executable at "/usr/bin/java/bin/java" (-1)

In MacOS Catalina, run

sudo nano ~/.bash_profile

In bash_profile, add:

export JAVA_HOME=$(/usr/libexec/java_home)
source ~/.bash_profile

Verify by running java --version

IIS Request Timeout on long ASP.NET operation

Remove ~ character in location so

path="~/Admin/SomePage.aspx"

becomes

path="Admin/SomePage.aspx"

Diff files present in two different directories

In practice the question often arises together with some constraints. In that case following solution template may come in handy.

cd dir1
find . \( -name '*.txt' -o -iname '*.md' \) | xargs -i diff -u '{}' 'dir2/{}'

Getting byte array through input type = file

This is a long post, but I was tired of all these examples that weren't working for me because they used Promise objects or an errant this that has a different meaning when you are using Reactjs. My implementation was using a DropZone with reactjs, and I got the bytes using a framework similar to what is posted at this following site, when nothing else above would work: https://www.mokuji.me/article/drop-upload-tutorial-1 . There were 2 keys, for me:

  1. You have to get the bytes from the event object, using and during a FileReader's onload function.
  2. I tried various combinations, but in the end, what worked was:

    const bytes = e.target.result.split('base64,')[1];

Where e is the event. React requires const, you could use var in plain Javascript. But that gave me the base64 encoded byte string.

So I'm just going to include the applicable lines for integrating this as if you were using React, because that's how I was building it, but try to also generalize this, and add comments where necessary, to make it applicable to a vanilla Javascript implementation - caveated that I did not use it like that in such a construct to test it.

These would be your bindings at the top, in your constructor, in a React framework (not relevant to a vanilla Javascript implementation):

this.uploadFile = this.uploadFile.bind(this);
this.processFile = this.processFile.bind(this);
this.errorHandler = this.errorHandler.bind(this);
this.progressHandler = this.progressHandler.bind(this);

And you'd have onDrop={this.uploadFile} in your DropZone element. If you were doing this without React, this is the equivalent of adding the onclick event handler you want to run when you click the "Upload File" button.

<button onclick="uploadFile(event);" value="Upload File" />

Then the function (applicable lines... I'll leave out my resetting my upload progress indicator, etc.):

uploadFile(event){
    // This is for React, only
    this.setState({
      files: event,
    });
    console.log('File count: ' + this.state.files.length);

    // You might check that the "event" has a file & assign it like this 
    // in vanilla Javascript:
    // var files = event.target.files;
    // if (!files && files.length > 0)
    //     files = (event.dataTransfer ? event.dataTransfer.files : 
    //            event.originalEvent.dataTransfer.files);

    // You cannot use "files" as a variable in React, however:
    const in_files = this.state.files;

    // iterate, if files length > 0
    if (in_files.length > 0) {
      for (let i = 0; i < in_files.length; i++) {
      // use this, instead, for vanilla JS:
      // for (var i = 0; i < files.length; i++) {
        const a = i + 1;
        console.log('in loop, pass: ' + a);
        const f = in_files[i];  // or just files[i] in vanilla JS

        const reader = new FileReader();
        reader.onerror = this.errorHandler;
        reader.onprogress = this.progressHandler;
        reader.onload = this.processFile(f);
        reader.readAsDataURL(f);
      }      
   }
}

There was this question on that syntax, for vanilla JS, on how to get that file object:

JavaScript/HTML5/jQuery Drag-And-Drop Upload - "Uncaught TypeError: Cannot read property 'files' of undefined"

Note that React's DropZone will already put the File object into this.state.files for you, as long as you add files: [], to your this.state = { .... } in your constructor. I added syntax from an answer on that post on how to get your File object. It should work, or there are other posts there that can help. But all that Q/A told me was how to get the File object, not the blob data, itself. And even if I did fileData = new Blob([files[0]]); like in sebu's answer, which didn't include var with it for some reason, it didn't tell me how to read that blob's contents, and how to do it without a Promise object. So that's where the FileReader came in, though I actually tried and found I couldn't use their readAsArrayBuffer to any avail.

You will have to have the other functions that go along with this construct - one to handle onerror, one for onprogress (both shown farther below), and then the main one, onload, that actually does the work once a method on reader is invoked in that last line. Basically you are passing your event.dataTransfer.files[0] straight into that onload function, from what I can tell.

So the onload method calls my processFile() function (applicable lines, only):

processFile(theFile) {
  return function(e) {
    const bytes = e.target.result.split('base64,')[1];
  }
}

And bytes should have the base64 bytes.

Additional functions:

errorHandler(e){
    switch (e.target.error.code) {
      case e.target.error.NOT_FOUND_ERR:
        alert('File not found.');
        break;
      case e.target.error.NOT_READABLE_ERR:
        alert('File is not readable.');
        break;
      case e.target.error.ABORT_ERR:
        break;    // no operation
      default:
        alert('An error occurred reading this file.');
        break;
    }
  }

progressHandler(e) {
    if (e.lengthComputable){
      const loaded = Math.round((e.loaded / e.total) * 100);
      let zeros = '';

      // Percent loaded in string
      if (loaded >= 0 && loaded < 10) {
        zeros = '00';
      }
      else if (loaded < 100) {
        zeros = '0';
      }

      // Display progress in 3-digits and increase bar length
      document.getElementById("progress").textContent = zeros + loaded.toString();
      document.getElementById("progressBar").style.width = loaded + '%';
    }
  }

And applicable progress indicator markup:

<table id="tblProgress">
  <tbody>
    <tr>
      <td><b><span id="progress">000</span>%</b> <span className="progressBar"><span id="progressBar" /></span></td>
    </tr>                    
  </tbody>
</table>

And CSS:

.progressBar {
  background-color: rgba(255, 255, 255, .1);
  width: 100%;
  height: 26px;
}
#progressBar {
  background-color: rgba(87, 184, 208, .5);
  content: '';
  width: 0;
  height: 26px;
}

EPILOGUE:

Inside processFile(), for some reason, I couldn't add bytes to a variable I carved out in this.state. So, instead, I set it directly to the variable, attachments, that was in my JSON object, RequestForm - the same object as my this.state was using. attachments is an array so I could push multiple files. It went like this:

  const fileArray = [];
  // Collect any existing attachments
  if (RequestForm.state.attachments.length > 0) {
    for (let i=0; i < RequestForm.state.attachments.length; i++) {
      fileArray.push(RequestForm.state.attachments[i]);
    }
  }
  // Add the new one to this.state
  fileArray.push(bytes);
  // Update the state
  RequestForm.setState({
    attachments: fileArray,
  });

Then, because this.state already contained RequestForm:

this.stores = [
  RequestForm,    
]

I could reference it as this.state.attachments from there on out. React feature that isn't applicable in vanilla JS. You could build a similar construct in plain JavaScript with a global variable, and push, accordingly, however, much easier:

var fileArray = new Array();  // place at the top, before any functions

// Within your processFile():
var newFileArray = [];
if (fileArray.length > 0) {
  for (var i=0; i < fileArray.length; i++) {
    newFileArray.push(fileArray[i]);
  }
}
// Add the new one
newFileArray.push(bytes);
// Now update the global variable
fileArray = newFileArray;

Then you always just reference fileArray, enumerate it for any file byte strings, e.g. var myBytes = fileArray[0]; for the first file.

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

I think fontsize: command in YAML only works for LaTeX / pdf. Apart, in standard latex classes (article, book, and report) only three font sizes are accepted (10pt, 11pt, and 12pt).

Regarding appearance (different font types and colors), you can specify a theme:. See Appearance and Style.

I guess, what you are looking for is your own css. Make a file called style.css, save it in the same folder as your .Rmd and include it in the YAML header:

---
output:
  html_document:
    css: style.css
---

In the css-file you define your font-type and size:

/* Whole document: */
body{
  font-family: Helvetica;
  font-size: 16pt;
}
/* Headers */
h1,h2,h3,h4,h5,h6{
  font-size: 24pt;
}

pass array to method Java

There is an important point of arrays that is often not taught or missed in java classes. When arrays are passed to a function, then another pointer is created to the same array ( the same pointer is never passed ). You can manipulate the array using both the pointers, but once you assign the second pointer to a new array in the called method and return back by void to calling function, then the original pointer still remains unchanged.

You can directly run the code here : https://www.compilejava.net/

import java.util.Arrays;

public class HelloWorld
{
    public static void main(String[] args)
    {
        int Main_Array[] = {20,19,18,4,16,15,14,4,12,11,9};
        Demo1.Demo1(Main_Array);
        // THE POINTER Main_Array IS NOT PASSED TO Demo1
        // A DIFFERENT POINTER TO THE SAME LOCATION OF Main_Array IS PASSED TO Demo1

        System.out.println("Main_Array = "+Arrays.toString(Main_Array));
        // outputs : Main_Array = [20, 19, 18, 4, 16, 15, 14, 4, 12, 11, 9]
        // Since Main_Array points to the original location,
        // I cannot access the results of Demo1 , Demo2 when they are void.
        // I can use array clone method in Demo1 to get the required result,
        // but it would be faster if Demo1 returned the result to main
    }
}

public class Demo1
{
    public static void Demo1(int A[])
    {
        int B[] = new int[A.length];
        System.out.println("B = "+Arrays.toString(B)); // output : B = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        Demo2.Demo2(A,B);
        System.out.println("B = "+Arrays.toString(B)); // output : B = [9999, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        System.out.println("A = "+Arrays.toString(A)); // output : A = [20, 19, 18, 4, 16, 15, 14, 4, 12, 11, 9]

        A = B;
        // A was pointing to location of Main_Array, now it points to location of B
        // Main_Array pointer still keeps pointing to the original location in void main

        System.out.println("A = "+Arrays.toString(A)); // output : A = [9999, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        // Hence to access this result from main, I have to return it to main
    }
}
public class Demo2
{
    public static void Demo2(int AAA[],int BBB[])
    {
        BBB[0] = 9999;
        // BBB points to the same location as B in Demo1, so whatever I do
        // with BBB, I am manipulating the location. Since B points to the
        // same location, I can access the results from B
    }
}

Python TypeError: not enough arguments for format string

I got the same error when using % as a percent character in my format string. The solution to this is to double up the %%.

Setting default value in select drop-down using Angularjs

You can do it with following code(track by),

<select ng-model="modelName" ng-options="data.name for data in list track by data.id" ></select>

How to make a div 100% height of the browser window

Stupidly easy solution which supports cross-domain and also supports browser re-size.

<div style="height: 100vh;">
   <iframe src="..." width="100%" height="80%"></iframe>
</div>

Adjust the iframe height property as required (leave the div height property at 100vh).

Why 80%? In my real-world scenario I have a header inside the div, before the iframe, which consumes some vertical space - so I set the iframe to use 80% instead of 100% (otherwise it would be the height of the containing div, but start after the header, and overflow out the bottom of the div).

javascript get child by id

document.getElementById('child') should return you the correct element - remember that id's need to be unique across a document to make it valid anyway.

edit : see this page - ids MUST be unique.

edit edit : alternate way to solve the problem :

<div onclick="test('child1')">
    Test
    <div id="child1">child</div>
</div>

then you just need the test() function to look up the element by id that you passed in.

Finding what branch a Git commit came from

A poor man's option is to use the tool tig1 on HEAD, search for the commit, and then visually follow the line from that commit back up until a merge commit is seen. The default merge message should specify what branch is getting merged to where :)

1 Tig is an ncurses-based text-mode interface for Git. It functions mainly as a Git repository browser, but it can also assist in staging changes for commit at chunk level and act as a pager for output from various Git commands.

Javascript Array.sort implementation?

I think that would depend on what browser implementation you are refering to.

Every browser type has it's own javascript engine implementation, so it depends. You could check the sourcecode repos for Mozilla and Webkit/Khtml for different implementations.

IE is closed source however, so you may have to ask somebody at microsoft.

How to convert a ruby hash object to JSON?

You can also use JSON.generate:

require 'json'

JSON.generate({ foo: "bar" })
=> "{\"foo\":\"bar\"}"

Or its alias, JSON.unparse:

require 'json'

JSON.unparse({ foo: "bar" })
=> "{\"foo\":\"bar\"}"

How to call a function within class?

Since these are member functions, call it as a member function on the instance, self.

def isNear(self, p):
    self.distToPoint(p)
    ...

post ajax data to PHP and return data

 $.ajax({
            type: "POST",
            data: {data:the_id},
            url: "http://localhost/test/index.php/data/count_votes",
            success: function(data){
               //data will contain the vote count echoed by the controller i.e.  
                 "yourVoteCount"
              //then append the result where ever you want like
              $("span#votes_number").html(data); //data will be containing the vote count which you have echoed from the controller

                }
            });

in the controller

$data = $_POST['data'];  //$data will contain the_id
//do some processing
echo "yourVoteCount";

Clarification

i think you are confusing

{data:the_id}

with

success:function(data){

both the data are different for your own clarity sake you can modify it as

success:function(vote_count){
$(span#someId).html(vote_count);

VS2010 command prompt gives error: Cannot determine the location of the VS Common Tools folder

So this is probably waaaaaay late to the party but the actual problem is an error or rather the repetition of the same error in three batch files.

C:\Program Files(x86)\Microsoft Visual Studio 10.0\Common7\Tools\VCVarsQueryRegistry.bat

C:\Program Files(x86)\Microsoft Visual Studio 10.0\Common7\Tools\vsvars32.bat

C:\Program Files(x86)\Microsoft Visual Studio 10.0\VC\bin\vcvars32.bat

The pattern of the error is everywhere a for loop is used to loop through registry values. It looks like this:

@for /F "tokens=1,2*" %%i in ('reg query "%1\SOFTWARE\Microsoft\VisualStudio\SxS\VS7" /v "10.0"') DO (
    @if "%%i"=="10.0" (
        @SET "VS100COMNTOOLS=%%k"
    )
)

The problem is the second occurrence of %%i. The way the loop construct works is the first %% variable is the first token, the next is the second and so on. So the second %%i should be a %%j (or whatever you want) so that it points to the value that would possibly be a "10.0". You can tell the developer wanted to use i,j,k as the values because in the enclosed @SET in the if, they use %%k. Which would be the path.

So, in short, go through all these types of loops in the three files above and change the second occurrence of %%i to %%k and everything will work like it's supposed to. So it should look like this:

@for /F "tokens=1,2*" %%i in ('reg query "%1\SOFTWARE\Microsoft\VisualStudio\SxS\VS7" /v "10.0"') DO (
    @if "%%j"=="10.0" (
        @SET "VS100COMNTOOLS=%%k"
    )
)

Hope this helps. Not sure if this applies to all versions. I only know that it does apply to VS 2010 (SP1).

Swift alert view with OK and Cancel: which button tapped?

You can easily do this by using UIAlertController

let alertController = UIAlertController(
       title: "Your title", message: "Your message", preferredStyle: .alert)
let defaultAction = UIAlertAction(
       title: "Close Alert", style: .default, handler: nil)
//you can add custom actions as well 
alertController.addAction(defaultAction)

present(alertController, animated: true, completion: nil)

.

Reference: iOS Show Alert

Ignore fields from Java object dynamically while sending as JSON from Spring MVC

If I were you and wanted to do so, I wouldn't use my User entity in Controller layer.Instead I create and use UserDto (Data transfer object) to communicate with business(Service) layer and Controller. You can use Apache BeanUtils(copyProperties method) to copy data from User entity to UserDto.

Black transparent overlay on image hover with only CSS?

See what I've done here: http://jsfiddle.net/dyarbrough93/c8wEC/

First off, you never set the dimensions of the overlay, meaning it wasn't showing up in the first place. Secondly, I recommend just changing the z-index of the overlay when you hover over the image. Change the opacity / color of the overlay to suit your needs.

.image { position: relative; width: 200px; height: 200px;}
.image img { max-width: 100%; max-height: 100%; }
.overlay { position: absolute; top: 0; left: 0; background-color: gray; z-index: -10; width: 200px; height: 200px; opacity: 0.5}
.image:hover .overlay { z-index: 10}

How to bind Dataset to DataGridView in windows application

use like this :-

gridview1.DataSource = ds.Tables[0]; <-- Use index or your table name which you want to bind
gridview1.DataBind();

I hope it helps!!

Maven: How to rename the war file for the project?

You need to configure the war plugin:

<project>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.3</version>
        <configuration>
          <warName>bird.war</warName>
        </configuration>
      </plugin>
    </plugins>
  </build>
  ...
</project>

More info here

Setting graph figure size

A different approach.
On the figure() call specify properties or modify the figure handle properties after h = figure().

This creates a full screen figure based on normalized units.
figure('units','normalized','outerposition',[0 0 1 1])

The units property can be adjusted to inches, centimeters, pixels, etc.

See figure documentation.

SQL - The conversion of a varchar data type to a datetime data type resulted in an out-of-range value

I've had the same problem and determined that this issue arises because SQL Server does not perform comparisons on characters converted to integers in an identical manner. In my test, I've found that some comparisons of converted characters, such as the exclamation point, will return type conversion errors, while other comparisons of converted characters, such as the space, will be determined to be out of range.

This sample code tests the different possible scenarios and presents a solution using nested REPLACE statements. The REPLACE determines if there are any characters in the string that are not numerals or the slash, and, if any exist, the length of the string will be greater than zero, thereby indicating that there are 'bad' characters and the date is invalid.

DECLARE @str varchar(10)
SET @str = '12/10/2012'
IF convert(int, substring(@str,4,2)) <= 31 AND convert(int, substring(@str,4,2)) >= 1
    PRINT @str+': Passed Test'
    ELSE PRINT @str+': Failed Test'
GO

DECLARE @str varchar(10)
SET @str = '12/10/2012' 
PRINT 'Number of characters in ' + @str + ' that are not numerals or a slash (0 means the date is valid; all values greater than 0 indicate a problem): ' + convert(varchar(5),len(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(@str,'0',''),'1',''),'2',''),'3',''),'4',''),'5',''),'6',''),'7',''), '8',''),'9',''),'/',''),' ','+'))) --replace space with a + to avoid empty string
PRINT ''
GO

DECLARE @str varchar(10)
SET @str = '12/!0/2012'
    IF convert(int, substring(@str,4,2)) <= 31 AND convert(int, substring(@str,4,2)) >= 1
        PRINT @str+': Passed Test'
        ELSE PRINT @str+': Failed Test'
GO

DECLARE @str varchar(10)
SET @str = '12/!0/2012' 
PRINT 'Number of characters in ' + @str + ' that are not numerals or a slash (0 means the date is valid; all values greater than 0 indicate a problem): ' + convert(varchar(5),len(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(@str,'0',''),'1',''),'2',''),'3',''),'4',''),'5',''),'6',''),'7',''), '8',''),'9',''),'/',''),' ','+'))) --replace space with a + to avoid empty string
PRINT ''
GO

DECLARE @str varchar(10)
SET @str = '12/  /2012'
IF convert(int, substring(@str,4,2)) <= 31 AND convert(int, substring(@str,4,2)) >= 1
    PRINT @str+': Passed Test'
    ELSE PRINT @str+': Failed Test'
GO

DECLARE @str varchar(10)
SET @str = '12/  /2012' 
PRINT 'Number of characters in ' + @str + ' that are not numerals or a slash (0 means the date is valid; all values greater than 0 indicate a problem): ' + convert(varchar(5),len(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(@str,'0',''),'1',''),'2',''),'3',''),'4',''),'5',''),'6',''),'7',''), '8',''),'9',''),'/',''),' ','+'))) --replace space with a + to avoid empty string

Output:

--Output
--12/10/2012: Passed Test
--Number of characters in 12/10/2012 that are not numerals or a slash (0 means the date is valid; all values greater than 0 indicate a problem): 0

--Msg 245, Level 16, State 1, Line 4
--Conversion failed when converting the varchar value '!0' to data type int.
--Number of characters in 12/!0/2012 that are not numerals or a slash (0 means the date is valid; all values greater than 0 indicate a problem): 1

--12/  /2012: Failed Test
--Number of characters in 12/  /2012 that are not numerals or a slash (0 means the date is valid; all values greater than 0 indicate a problem): 2

Set default time in bootstrap-datetimepicker

By using Moment.js, i able to set the default time

var defaultStartTime = moment(new Date());
var _startTimeStr = "02:00 PM"


    if (moment(_startTimeStr, 'HH:mm a').isValid()) {
        var hr = moment(_startTimeStr, 'HH:mm a').hour();
        var min = moment(_startTimeStr, 'HH:mm a').minutes();

        defaultStartTime = defaultStartTime.hours(hr).minutes(min);
    }

$('#StartTime').datetimepicker({
    pickDate: false,
    defaultDate: defaultStartTime
});

Use child_process.execSync but keep output in console

You can pass the parent´s stdio to the child process if that´s what you want:

require('child_process').execSync(
    'rsync -avAXz --info=progress2 "/src" "/dest"',
    {stdio: 'inherit'}
);

How to get all keys with their values in redis

There is no native way of doing this.

The Redis command documentation contains no native commands for getting the key and value of multiple keys.

The most native way of doing this would be to load a lua script into your redis using the SCRIPT LOAD command or the EVAL command.

Bash Haxx solution

A workaround would be to use some bash magic, like this:

echo 'keys YOURKEY*' | redis-cli | sed 's/^/get /' | redis-cli 

This will output the data from all the keys which begin with YOURKEY

Note that the keys command is a blocking operation and should be used with care.

How to import JsonConvert in C# application?

right click on the project and select Manage NuGet Packages.. In that select Json.NET and install

After installation,

use the following namespace

using Newtonsoft.Json;

then use the following to deserialize

JsonConvert.DeserializeObject

Fatal error: Call to undefined function mysql_connect()

This Code Can Help You

<?php 

$servername = "localhost";
$username = "root";
$password = "";


$con = new mysqli($servername, $username, $password);

?>

But Change The "servername","username" and "password"

SEVERE: Unable to create initial connections of pool - tomcat 7 with context.xml file

When you encounter exceptions like this, the most useful information is generally at the bottom of the stacktrace:

Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
  at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
  ...
  at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:246)

The problem is that Tomcat can't find com.mysql.jdbc.Driver. This is usually caused by the JAR containing the MySQL driver not being where Tomcat expects to find it (namely in the webapps/<yourwebapp>/WEB-INF/lib directory).

ReferenceError: describe is not defined NodeJs

OP asked about running from node not from mocha. This is a very common use case, see Using Mocha Programatically

This is what injected describe and it into my tests.

mocha.ui('bdd').run(function (failures) {
    process.on('exit', function () {
      process.exit(failures);
    });
  });

I tried tdd like in the docs, but that didn't work, bdd worked though.

login to remote using "mstsc /admin" with password

Re-posted as an answer: Found an alternative (Tested in Win8):

cmdkey /generic:"<server>" /user:"<user>" /pass:"<pass>"

Run that and if you run:

mstsc /v:<server>

You should not get an authentication prompt.

ansible : how to pass multiple commands

If a value in YAML begins with a curly brace ({), the YAML parser assumes that it is a dictionary. So, for cases like this where there is a (Jinja2) variable in the value, one of the following two strategies needs to be adopted to avoiding confusing the YAML parser:

Quote the whole command:

- command: "{{ item }} chdir=/src/package/"
  with_items:
  - ./configure
  - /usr/bin/make
  - /usr/bin/make install    

or change the order of the arguments:

- command: chdir=/src/package/ {{ item }}
  with_items:
  - ./configure
  - /usr/bin/make
  - /usr/bin/make install

Thanks for @RamondelaFuente alternative suggestion.

Remote origin already exists on 'git push' to a new repository

You need to check the origin and add if not exists.

if ! git config remote.origin.url >/dev/null; then
    git remote add origin [email protected]:john/doe.git
fi

Create file check.sh, paste the script update your git repository URL and run ./check.sh.

C# Enum - How to Compare Value

Comparision:

if (userProfile.AccountType == AccountType.Retailer)
{
    //your code
}

In case to prevent the NullPointerException you could add the following condition before comparing the AccountType:

if(userProfile != null)
{
    if (userProfile.AccountType == AccountType.Retailer)
    {
       //your code
    }
}

or shorter version:

if (userProfile !=null && userProfile.AccountType == AccountType.Retailer)
{
    //your code
}

Error sending json in POST to web API service

I had all my settings covered in the accepted answer. The problem I had was that I was trying to update the Entity Framework entity type "Task" like:

public IHttpActionResult Post(Task task)

What worked for me was to create my own entity "DTOTask" like:

public IHttpActionResult Post(DTOTask task)

Force hide address bar in Chrome on Android

window.scrollTo(0,1);

this will help you but this javascript is may not work in all browsers

Is there a JSON equivalent of XQuery/XPath?

If you're like me and you just want to do path-based lookups, but don't care about real XPath, lodash's _.get() can work. Example from lodash docs:

var object = { 'a': [{ 'b': { 'c': 3 } }] };

_.get(object, 'a[0].b.c');
// ? 3

_.get(object, ['a', '0', 'b', 'c']);
// ? 3

_.get(object, 'a.b.c', 'default');
// ? 'default'

Reference to non-static member function must be called

You may want to have a look at https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types, especially [33.1] Is the type of "pointer-to-member-function" different from "pointer-to-function"?

Aligning a float:left div to center?

CSS Flexbox is well supported these days. Go here for a good tutorial on flexbox.

This works fine in all newer browsers:

_x000D_
_x000D_
#container {_x000D_
  display:         flex;_x000D_
  flex-wrap:       wrap;_x000D_
  justify-content: center;_x000D_
}_x000D_
_x000D_
.block {_x000D_
  width:              150px;_x000D_
  height:             150px;_x000D_
  background-color:   #cccccc;_x000D_
  margin:             10px;        _x000D_
}
_x000D_
<div id="container">_x000D_
  <div class="block">1</div>    _x000D_
  <div class="block">2</div>    _x000D_
  <div class="block">3</div>    _x000D_
  <div class="block">4</div>    _x000D_
  <div class="block">5</div>        _x000D_
</div>
_x000D_
_x000D_
_x000D_

Some may ask why not use display: inline-block? For simple things it is fine, but if you got complex code within the blocks, the layout may not be correctly centered anymore. Flexbox is more stable than float left.

XML Serialize generic list of serializable objects

Below is a Util class in my project:

namespace Utils
{
    public static class SerializeUtil
    {
        public static void SerializeToFormatter<F>(object obj, string path) where F : IFormatter, new()
        {
            if (obj == null)
            {
                throw new NullReferenceException("obj Cannot be Null.");
            }

            if (obj.GetType().IsSerializable == false)
            {
                //  throw new 
            }
            IFormatter f = new F();
            SerializeToFormatter(obj, path, f);
        }

        public static T DeserializeFromFormatter<T, F>(string path) where F : IFormatter, new()
        {
            T t;
            IFormatter f = new F();
            using (FileStream fs = File.OpenRead(path))
            {
                t = (T)f.Deserialize(fs);
            }
            return t;
        }

        public static void SerializeToXML<T>(string path, object obj)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            using (FileStream fs = File.Create(path))
            {
                xs.Serialize(fs, obj);
            }
        }

        public static T DeserializeFromXML<T>(string path)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            using (FileStream fs = File.OpenRead(path))
            {
                return (T)xs.Deserialize(fs);
            }
        }

        public static T DeserializeFromXml<T>(string xml)
        {
            T result;

            var ser = new XmlSerializer(typeof(T));
            using (var tr = new StringReader(xml))
            {
                result = (T)ser.Deserialize(tr);
            }
            return result;
        }


        private static void SerializeToFormatter(object obj, string path, IFormatter formatter)
        {
            using (FileStream fs = File.Create(path))
            {
                formatter.Serialize(fs, obj);
            }
        }
    }
}

How can I convert a string with dot and comma into a float in Python

Just replace, with replace().

f = float("123,456.908".replace(',','')) print(type(f)

type() will show you that it has converted into a float

Change Orientation of Bluestack : portrait/landscape mode

New version 4.100.x.xxxx

Try this:

More Apps > Android Settings > Accessibility > Auto-rotate screen = Enabled

enter image description here

comparing two strings in ruby

var1 is a regular string, whereas var2 is an array, this is how you should compare (in this case):

puts var1 == var2[0]

Position DIV relative to another DIV?

First set position of the parent DIV to relative (specifying the offset, i.e. left, top etc. is not necessary) and then apply position: absolute to the child DIV with the offset you want.
It's simple and should do the trick well.

TextView bold via xml file?

just use

android:textStyle="bold"

WPF Databinding: How do I access the "parent" data context?

You could try something like this:

...Binding="{Binding RelativeSource={RelativeSource FindAncestor, 
AncestorType={x:Type Window}}, Path=DataContext.AllowItemCommand}" ...

Slack clean all messages (~8K) in a channel

There is a slack tool to delete all slack messages on your workspace. Check it out: https://www.messagebender.com

How to stop docker under Linux

In my case, it was neither systemd nor a cron job, but it was snap. So I had to run:

sudo snap stop docker
sudo snap remove docker

... and the last command actually never ended, I don't know why: this snap thing is really a pain. So I also ran:

sudo apt purge snap

:-)

Exists Angularjs code/naming conventions?

Update : STYLE GUIDE is now on Angular docs.

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

If you are looking for an opinionated style guide for syntax, conventions, and structuring AngularJS applications, then step right in. The styles contained here are based on my experience with AngularJS, presentations, training courses and working in teams.

The purpose of this style guide is to provide guidance on building AngularJS applications by showing the conventions I use and, more importantly, why I choose them.

- John Papa

Here is the Awesome Link (Latest and Up-to-date) : AngularJS Style Guide

How to get char from string by index?

In [1]: x = "anmxcjkwnekmjkldm!^%@(*)#_+@78935014712jksdfs"
In [2]: len(x)
Out[2]: 45

Now, For positive index ranges for x is from 0 to 44 (i.e. length - 1)

In [3]: x[0]
Out[3]: 'a'
In [4]: x[45]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)

/home/<ipython console> in <module>()

IndexError: string index out of range

In [5]: x[44]
Out[5]: 's'

For Negative index, index ranges from -1 to -45

In [6]: x[-1]
Out[6]: 's'
In [7]: x[-45]
Out[7]: 'a

For negative index, negative [length -1] i.e. the last valid value of positive index will give second list element as the list is read in reverse order,

In [8]: x[-44]
Out[8]: 'n'

Other, index's examples,

In [9]: x[1]
Out[9]: 'n'
In [10]: x[-9]
Out[10]: '7'

Shortcut for echo "<pre>";print_r($myarray);echo "</pre>";

This is the shortest:

echo '<pre>',print_r($arr,1),'</pre>';

The closing tag can also be omitted.

How to plot vectors in python using matplotlib

This may also be achieved using matplotlib.pyplot.quiver, as noted in the linked answer;

plt.quiver([0, 0, 0], [0, 0, 0], [1, -2, 4], [1, 2, -7], angles='xy', scale_units='xy', scale=1)
plt.xlim(-10, 10)
plt.ylim(-10, 10)
plt.show()

mpl output

Hiding and Showing TabPages in tabControl

I prefer to make the flat style appearance: https://stackoverflow.com/a/25192153/5660876

    tabControl1.Appearance = TabAppearance.FlatButtons;
    tabControl1.ItemSize = new Size(0, 1);
    tabControl1.SizeMode = TabSizeMode.Fixed;

But there is a pixel that is shown at every tabPage, so if you delete all the text of every tabpage, then the tabs become invisible perfectly at run-time.

    foreach (TabPage tab in tabControl1.TabPages)
    {
        tab.Text = "";
    }

After that i use a treeview, to change through the tabpages... clicking on the nodes.

How to get active user's UserDetails

Preamble: Since Spring-Security 3.2 there is a nice annotation @AuthenticationPrincipal described at the end of this answer. This is the best way to go when you use Spring-Security >= 3.2.

When you:

  • use an older version of Spring-Security,
  • need to load your custom User Object from the Database by some information (like the login or id) stored in the principal or
  • want to learn how a HandlerMethodArgumentResolver or WebArgumentResolver can solve this in an elegant way, or just want to an learn the background behind @AuthenticationPrincipal and AuthenticationPrincipalArgumentResolver (because it is based on a HandlerMethodArgumentResolver)

then keep on reading — else just use @AuthenticationPrincipal and thank to Rob Winch (Author of @AuthenticationPrincipal) and Lukas Schmelzeisen (for his answer).

(BTW: My answer is a bit older (January 2012), so it was Lukas Schmelzeisen that come up as the first one with the @AuthenticationPrincipal annotation solution base on Spring Security 3.2.)


Then you can use in your controller

public ModelAndView someRequestHandler(Principal principal) {
   User activeUser = (User) ((Authentication) principal).getPrincipal();
   ...
}

That is ok if you need it once. But if you need it several times its ugly because it pollutes your controller with infrastructure details, that normally should be hidden by the framework.

So what you may really want is to have a controller like this:

public ModelAndView someRequestHandler(@ActiveUser User activeUser) {
   ...
}

Therefore you only need to implement a WebArgumentResolver. It has a method

Object resolveArgument(MethodParameter methodParameter,
                   NativeWebRequest webRequest)
                   throws Exception

That gets the web request (second parameter) and must return the User if its feels responsible for the method argument (the first parameter).

Since Spring 3.1 there is a new concept called HandlerMethodArgumentResolver. If you use Spring 3.1+ then you should use it. (It is described in the next section of this answer))

public class CurrentUserWebArgumentResolver implements WebArgumentResolver{

   Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) {
        if(methodParameter is for type User && methodParameter is annotated with @ActiveUser) {
           Principal principal = webRequest.getUserPrincipal();
           return (User) ((Authentication) principal).getPrincipal();
        } else {
           return WebArgumentResolver.UNRESOLVED;
        }
   }
}

You need to define the Custom Annotation -- You can skip it if every instance of User should always be taken from the security context, but is never a command object.

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ActiveUser {}

In the configuration you only need to add this:

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"
    id="applicationConversionService">
    <property name="customArgumentResolver">
        <bean class="CurrentUserWebArgumentResolver"/>
    </property>
</bean>

@See: Learn to customize Spring MVC @Controller method arguments

It should be noted that if you're using Spring 3.1, they recommend HandlerMethodArgumentResolver over WebArgumentResolver. - see comment by Jay


The same with HandlerMethodArgumentResolver for Spring 3.1+

public class CurrentUserHandlerMethodArgumentResolver
                               implements HandlerMethodArgumentResolver {

     @Override
     public boolean supportsParameter(MethodParameter methodParameter) {
          return
              methodParameter.getParameterAnnotation(ActiveUser.class) != null
              && methodParameter.getParameterType().equals(User.class);
     }

     @Override
     public Object resolveArgument(MethodParameter methodParameter,
                         ModelAndViewContainer mavContainer,
                         NativeWebRequest webRequest,
                         WebDataBinderFactory binderFactory) throws Exception {

          if (this.supportsParameter(methodParameter)) {
              Principal principal = webRequest.getUserPrincipal();
              return (User) ((Authentication) principal).getPrincipal();
          } else {
              return WebArgumentResolver.UNRESOLVED;
          }
     }
}

In the configuration, you need to add this

<mvc:annotation-driven>
      <mvc:argument-resolvers>
           <bean class="CurrentUserHandlerMethodArgumentResolver"/>         
      </mvc:argument-resolvers>
 </mvc:annotation-driven>

@See Leveraging the Spring MVC 3.1 HandlerMethodArgumentResolver interface


Spring-Security 3.2 Solution

Spring Security 3.2 (do not confuse with Spring 3.2) has own build in solution: @AuthenticationPrincipal (org.springframework.security.web.bind.annotation.AuthenticationPrincipal) . This is nicely described in Lukas Schmelzeisen`s answer

It is just writing

ModelAndView someRequestHandler(@AuthenticationPrincipal User activeUser) {
    ...
 }

To get this working you need to register the AuthenticationPrincipalArgumentResolver (org.springframework.security.web.bind.support.AuthenticationPrincipalArgumentResolver) : either by "activating" @EnableWebMvcSecurity or by registering this bean within mvc:argument-resolvers - the same way I described it with may Spring 3.1 solution above.

@See Spring Security 3.2 Reference, Chapter 11.2. @AuthenticationPrincipal


Spring-Security 4.0 Solution

It works like the Spring 3.2 solution, but in Spring 4.0 the @AuthenticationPrincipal and AuthenticationPrincipalArgumentResolver was "moved" to an other package:

(But the old classes in its old packges still exists, so do not mix them!)

It is just writing

import org.springframework.security.core.annotation.AuthenticationPrincipal;
ModelAndView someRequestHandler(@AuthenticationPrincipal User activeUser) {
    ...
}

To get this working you need to register the (org.springframework.security.web.method.annotation.) AuthenticationPrincipalArgumentResolver : either by "activating" @EnableWebMvcSecurity or by registering this bean within mvc:argument-resolvers - the same way I described it with may Spring 3.1 solution above.

<mvc:annotation-driven>
    <mvc:argument-resolvers>
        <bean class="org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver" />
    </mvc:argument-resolvers>
</mvc:annotation-driven>

@See Spring Security 5.0 Reference, Chapter 39.3 @AuthenticationPrincipal

How to Write text file Java

In java 7 can now do

try(BufferedWriter w = ....)
{
  w.write(...);
}
catch(IOException)
{
}

and w.close will be done automatically

Adding to the classpath on OSX

If your shell is tcsh or csh, you can set it in /etc/profile. Open terminal, "vim /etc/profile" and add the following line:

setenv CLASSPATH (insert your classpath here)

Python data structure sort list alphabetically

You can use built-in sorted function.

print sorted(['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue'])

SQL Plus change current directory

I think that the SQLPATH environment variable is the best way for this - if you have multiple paths, enter them separated by semi-colons (;). Keep in mind that if there are script files named the same in among the directories, the first one encountered (by order the paths are entered) will be executed, the second one will be ignored.

How can I make an "are you sure" prompt in a Windows batchfile?

The choice command is not available everywhere. With newer Windows versions, the set command has the /p option you can get user input

SET /P variable=[promptString]

see set /? for more info

Generating a unique machine id

I hate to be the guy who says, "you're just doing it wrong" (I always hate that guy ;) but...

Does it have to be repeatably generated for the unique machine? Could you just assign the identifier or do a public/private key? Maybe if you could generate and store the value, you could access it from both OS installs on the same disk?

You've probably explored these options and they doesn't work for you, but if not, it's something to consider.

If it's not a matter of user trust, you could just use MAC addresses.

Rails ActiveRecord date between

Rails 5.1 introduced a new date helper method all_day, see: https://github.com/rails/rails/pull/24930

>> Date.today.all_day
=> Wed, 26 Jul 2017 00:00:00 UTC +00:00..Wed, 26 Jul 2017 23:59:59 UTC +00:00

If you are using Rails 5.1, the query would look like:

Comment.where(created_at: @selected_date.all_day)

Does Notepad++ show all hidden characters?

Yes, it does. The way to enable this depends on your version of Notepad++. On newer versions you can use:

Menu View ? Show Symbol ? *Show All Characters`

or

Menu View ? Show Symbol ? Show White Space and TAB

(Thanks to bers' comment and bkaid's answers below for these updated locations.)


On older versions you can look for:

Menu View ? Show all characters

or

Menu View ? Show White Space and TAB

Formatting a field using ToText in a Crystal Reports formula field

I think you are looking for ToText(CCur(@Price}/{ValuationReport.YestPrice}*100-100))

You can use CCur to convert numbers or string to Curency formats. CCur(number) or CCur(string)


I think this may be what you are looking for,

Replace (ToText(CCur({field})),"$" , "") that will give the parentheses for negative numbers

It is a little hacky, but I'm not sure CR is very kind in the ways of formatting

Can vue-router open a link in a new tab?

Just write this code in your routing file :

{
  name: 'Google',
  path: '/google',
  beforeEnter() {                    
                window.open("http://www.google.com", 
                '_blank');
            }
}

How can I go back/route-back on vue-router?

If you're using Vuex you can use https://github.com/vuejs/vuex-router-sync

Just initialize it in your main file with:

import VuexRouterSync from 'vuex-router-sync';
VuexRouterSync.sync(store, router);

Each route change will update route state object in Vuex. You can next create getter to use the from Object in route state or just use the state (better is to use getters, but it's other story https://vuex.vuejs.org/en/getters.html), so in short it would be (inside components methods/values):

this.$store.state.route.from.fullPath

You can also just place it in <router-link> component:

<router-link :to="{ path: $store.state.route.from.fullPath }"> 
  Back 
</router-link>

So when you use code above, link to previous path would be dynamically generated.

How to make a simple rounded button in Storyboard?

Short Answer: YES

You can absolutely make a simple rounded button without the need of an additional background image or writing any code for the same. Just follow the screenshot given below, to set the runtime attributes for the button, to get the desired result.

It won't show in the Storyboard but it will work fine when you run the project.

enter image description here

Note:
The 'Key Path' layer.cornerRadius and value is 5. The value needs to be changed according to the height and width of the button. The formula for it is the height of button * 0.50. So play around the value to see the expected rounded button in the simulator or on the physical device. This procedure will look tedious when you have more than one button to be rounded in the storyboard.

Using classes with the Arduino

On Arduino 1.0, this compiles just fine:

class A
{
  public:
   int x;
   virtual void f() { x=1; }
};

class B : public A
{
  public:
    int y;
    virtual void f() { x=2; }
};


A *a;
B *b;
const int TEST_PIN = 10;

void setup()
{
   a=new A(); 
   b=new B();
   pinMode(TEST_PIN,OUTPUT);
}

void loop()
{
   a->f();
   b->f();
   digitalWrite(TEST_PIN,(a->x == b->x) ? HIGH : LOW);
}

jQuery Refresh/Reload Page if Ajax Success after time

var val = $.parseJSON(data);
if(val.success == true)
{
 setTimeout(function(){ location.reload(); }, 5000);

}

How to clear browsing history using JavaScript?

to disable back function of the back button:

window.addEventListener('popstate', function (event) {
  history.pushState(null, document.title, location.href);
});

Stratified Train/Test-split in scikit-learn

[update for 0.17]

See the docs of sklearn.model_selection.train_test_split:

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y,
                                                    stratify=y, 
                                                    test_size=0.25)

[/update for 0.17]

There is a pull request here. But you can simply do train, test = next(iter(StratifiedKFold(...))) and use the train and test indices if you want.

In reactJS, how to copy text to clipboard?

The simplest way will be use the react-copy-to-clipboard npm package.

You can install it with the following command

npm install --save react react-copy-to-clipboard

Use it in the following manner.

const App = React.createClass({
  getInitialState() {
    return {value: '', copied: false};
  },


  onChange({target: {value}}) {
    this.setState({value, copied: false});
  },


  onCopy() {
    this.setState({copied: true});
  },


  render() {
    return (
      <div>

          <input value={this.state.value} size={10} onChange={this.onChange} />

        <CopyToClipboard text={this.state.value} onCopy={this.onCopy}>
          <button>Copy</button>
        </CopyToClipboard>

                <div>
        {this.state.copied ? <span >Copied.</span> : null}
                </div>
        <br />

        <input type="text" />

      </div>
    );
  }
});

ReactDOM.render(<App />, document.getElementById('container'));

A detailed explanation is provided at the following link

https://www.npmjs.com/package/react-copy-to-clipboard

Here is a running fiddle.

Subprocess changing directory

If you need to change directory, run a command and get the std output as well:

import os
import logging as log
from subprocess import check_output, CalledProcessError, STDOUT
log.basicConfig(level=log.DEBUG)

def cmd_std_output(cd_dir_path, cmd):
    cmd_to_list = cmd.split(" ")
    try:
        if cd_dir_path:
            os.chdir(os.path.abspath(cd_dir_path))
        output = check_output(cmd_to_list, stderr=STDOUT).decode()
        return output
    except CalledProcessError as e:
        log.error('e: {}'.format(e))
def get_last_commit_cc_cluster():
    cd_dir_path = "/repos/cc_manager/cc_cluster"
    cmd = "git log --name-status HEAD^..HEAD --date=iso"
    result = cmd_std_output(cd_dir_path, cmd)
    return result

log.debug("Output: {}".format(get_last_commit_cc_cluster()))

Output: "commit 3b3daaaaaaaa2bb0fc4f1953af149fa3921e\nAuthor: user1<[email protected]>\nDate:   2020-04-23 09:58:49 +0200\n\n

split string in two on given index and return both parts

If code elegance ranks higher than the performance hit of regex, then

'1234567'.match(/^(.*)(.{3})/).slice(1).join(',')
=> "1234,567"

There's a lot of room to further modify the regex to be more precise.

If join() doesn't work then you might need to use map with a closure, at which point the other answers here may be less bytes and line noise.

CSS root directory

I use a relative path solution,

./../../../../../images/img.png

every ../ will take you one folder up towards the root. Hope this helps..

Difference Between Select and SelectMany

Without getting too technical - database with many Organizations, each with many Users:-

var orgId = "123456789";

var userList1 = db.Organizations
                   .Where(a => a.OrganizationId == orgId)
                   .SelectMany(a => a.Users)
                   .ToList();

var userList2 = db.Users
                   .Where(a => a.OrganizationId == orgId)
                   .ToList();

both return the same ApplicationUser list for the selected Organization.

The first "projects" from Organization to Users, the second queries the Users table directly.

Ranges of floating point datatype in C?

As dasblinkenlight already answered, the numbers come from the way that floating point numbers are represented in IEEE-754, and Andreas has a nice breakdown of the maths.

However - be careful that the precision of floating point numbers isn't exactly 6 or 15 significant decimal digits as the table suggests, since the precision of IEEE-754 numbers depends on the number of significant binary digits.

  • float has 24 significant binary digits - which depending on the number represented translates to 6-8 decimal digits of precision.

  • double has 53 significant binary digits, which is approximately 15 decimal digits.

Another answer of mine has further explanation if you're interested.

Mysql Compare two datetime fields

Your query apparently returned all correct dates, even considering the time.

If you're still not happy with the results, give DATEDIFF a shot and look for negaive/positive results between the two dates.

Make sure your mydate column is a datetime type.

How can I find out which server hosts LDAP on my windows domain?

AD registers Service Location (SRV) resource records in its DNS server which you can query to get the port and the hostname of the responsible LDAP server in your domain.

Just try this on the command-line:

C:\> nslookup 
> set types=all
> _ldap._tcp.<<your.AD.domain>>
_ldap._tcp.<<your.AD.domain>>  SRV service location:
      priority       = 0
      weight         = 100
      port           = 389
      svr hostname   = <<ldap.hostname>>.<<your.AD.domain>>

(provided that your nameserver is the AD nameserver which should be the case for the AD to function properly)

Please see Active Directory SRV Records and Windows 2000 DNS white paper for more information.

How to use ADB Shell when Multiple Devices are connected? Fails with "error: more than one device and emulator"

For Windows, here's a quick 1 liner example of how to install a file..on multiple devices

FOR /F "skip=1"  %x IN ('adb devices') DO start adb -s %x install -r myandroidapp.apk

If you plan on including this in a batch file, replace %x with %%x, as below

FOR /F "skip=1"  %%x IN ('adb devices') DO start adb -s %%x install -r myandroidapp.apk

What range of values can integer types store in C++

To find out the limits on your system:

#include <iostream>
#include <limits>
int main(int, char **) {
  std::cout
    << static_cast< int >(std::numeric_limits< char >::max()) << "\n"
    << static_cast< int >(std::numeric_limits< unsigned char >::max()) << "\n"
    << std::numeric_limits< short >::max() << "\n"
    << std::numeric_limits< unsigned short >::max() << "\n"
    << std::numeric_limits< int >::max() << "\n"
    << std::numeric_limits< unsigned int >::max() << "\n"
    << std::numeric_limits< long >::max() << "\n"
    << std::numeric_limits< unsigned long >::max() << "\n"
    << std::numeric_limits< long long >::max() << "\n"
    << std::numeric_limits< unsigned long long >::max() << "\n";
}

Note that long long is only legal in C99 and in C++11.

Failed to execute 'createObjectURL' on 'URL':

Video with fall back:

try {
  video.srcObject = mediaSource;
} catch (error) {
  video.src = URL.createObjectURL(mediaSource);
}
video.play();

From: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/srcObject

Keeping ASP.NET Session Open / Alive

I use JQuery to perform a simple AJAX call to a dummy HTTP Handler that does nothing but keeping my Session alive:

function setHeartbeat() {
    setTimeout("heartbeat()", 5*60*1000); // every 5 min
}

function heartbeat() {
    $.get(
        "/SessionHeartbeat.ashx",
        null,
        function(data) {
            //$("#heartbeat").show().fadeOut(1000); // just a little "red flash" in the corner :)
            setHeartbeat();
        },
        "json"
    );
}

Session handler can be as simple as:

public class SessionHeartbeatHttpHandler : IHttpHandler, IRequiresSessionState
{
    public bool IsReusable { get { return false; } }

    public void ProcessRequest(HttpContext context)
    {
        context.Session["Heartbeat"] = DateTime.Now;
    }
}

The key is to add IRequiresSessionState, otherwise Session won't be available (= null). The handler can of course also return a JSON serialized object if some data should be returned to the calling JavaScript.

Made available through web.config:

<httpHandlers>
    <add verb="GET,HEAD" path="SessionHeartbeat.ashx" validate="false" type="SessionHeartbeatHttpHandler"/>
</httpHandlers>

added from balexandre on August 14th, 2012

I liked so much of this example, that I want to improve with the HTML/CSS and the beat part

change this

//$("#heartbeat").show().fadeOut(1000); // just a little "red flash" in the corner :)

into

beatHeart(2); // just a little "red flash" in the corner :)

and add

// beat the heart 
// 'times' (int): nr of times to beat
function beatHeart(times) {
    var interval = setInterval(function () {
        $(".heartbeat").fadeIn(500, function () {
            $(".heartbeat").fadeOut(500);
        });
    }, 1000); // beat every second

    // after n times, let's clear the interval (adding 100ms of safe gap)
    setTimeout(function () { clearInterval(interval); }, (1000 * times) + 100);
}

HTML and CSS

<div class="heartbeat">&hearts;</div>

/* HEARBEAT */
.heartbeat {
    position: absolute;
    display: none;
    margin: 5px;
    color: red;
    right: 0;
    top: 0;
}

here is a live example for only the beating part: http://jsbin.com/ibagob/1/

What does [object Object] mean? (JavaScript)

The alert() function can't output an object in a read-friendly manner. Try using console.log(object) instead, and fire up your browser's console to debug.

Laravel 4: Redirect to a given url

Yes, it's

use Illuminate\Support\Facades\Redirect;

return Redirect::to('http://heera.it');

Check the documentation.

Update: Redirect::away('url') (For external link, Laravel Version 4.19):

public function away($path, $status = 302, $headers = array())
{
    return $this->createRedirect($path, $status, $headers);
}

How to get thread id from a thread pool?

You can use Thread.getCurrentThread.getId(), but why would you want to do that when LogRecord objects managed by the logger already have the thread Id. I think you are missing a configuration somewhere that logs the thread Ids for your log messages.

Using Get-childitem to get a list of files modified in the last 3 days

Here's a minor update to the solution provided by Dave Sexton. Many times you need multiple filters. The Filter parameter can only take a single string whereas the -Include parameter can take a string array. if you have a large file tree it also makes sense to only get the date to compare with once, not for each file. Here's my updated version:

$compareDate = (Get-Date).AddDays(-3)    
@(Get-ChildItem -Path c:\pstbak\*.* -Filter '*.pst','*.mdb' -Recurse | Where-Object { $_.LastWriteTime -gt $compareDate}).Count

How to save an HTML5 Canvas as an image on a server?

Here is an example of how to achieve what you need:

  1. Draw something (taken from canvas tutorial)

_x000D_
_x000D_
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');

  // begin custom shape
  context.beginPath();
  context.moveTo(170, 80);
  context.bezierCurveTo(130, 100, 130, 150, 230, 150);
  context.bezierCurveTo(250, 180, 320, 180, 340, 150);
  context.bezierCurveTo(420, 150, 420, 120, 390, 100);
  context.bezierCurveTo(430, 40, 370, 30, 340, 50);
  context.bezierCurveTo(320, 5, 250, 20, 250, 50);
  context.bezierCurveTo(200, 5, 150, 20, 170, 80);

  // complete custom shape
  context.closePath();
  context.lineWidth = 5;
  context.fillStyle = '#8ED6FF';
  context.fill();
  context.strokeStyle = 'blue';
  context.stroke();
</script>
_x000D_
_x000D_
_x000D_

  1. Convert canvas image to URL format (base64)

    var dataURL = canvas.toDataURL();

  2. Send it to your server via Ajax

_x000D_
_x000D_
    $.ajax({
      type: "POST",
      url: "script.php",
      data: { 
         imgBase64: dataURL
      }
    }).done(function(o) {
      console.log('saved'); 
      // If you want the file to be visible in the browser 
      // - please modify the callback in javascript. All you
      // need is to return the url to the file, you just saved 
      // and than put the image in your browser.
    });
_x000D_
_x000D_
_x000D_

  1. Save base64 on your server as an image (here is how to do this in PHP, the same ideas is in every language. Server side in PHP can be found here):

REST API Best practice: How to accept list of parameter values as input

First:

I think you can do it 2 ways

http://our.api.com/Product/<id> : if you just want one record

http://our.api.com/Product : if you want all records

http://our.api.com/Product/<id1>,<id2> :as James suggested can be an option since what comes after the Product tag is a parameter

Or the one I like most is:

You can use the the Hypermedia as the engine of application state (HATEOAS) property of a RestFul WS and do a call http://our.api.com/Product that should return the equivalent urls of http://our.api.com/Product/<id> and call them after this.

Second

When you have to do queries on the url calls. I would suggest using HATEOAS again.

1) Do a get call to http://our.api.com/term/pumas/productType/clothing/color/black

2) Do a get call to http://our.api.com/term/pumas/productType/clothing,bags/color/black,red

3) (Using HATEOAS) Do a get call to `http://our.api.com/term/pumas/productType/ -> receive the urls all clothing possible urls -> call the ones you want (clothing and bags) -> receive the possible color urls -> call the ones you want

instanceof Vs getClass( )

getClass() has the restriction that objects are only equal to other objects of the same class, the same run time type, as illustrated in the output of below code:

class ParentClass{
}
public class SubClass extends ParentClass{
    public static void main(String []args){
        ParentClass parentClassInstance = new ParentClass();
        SubClass subClassInstance = new SubClass();
        if(subClassInstance instanceof ParentClass){
            System.out.println("SubClass extends ParentClass. subClassInstance is instanceof ParentClass");
        }
        if(subClassInstance.getClass() != parentClassInstance.getClass()){
            System.out.println("Different getClass() return results with subClassInstance and parentClassInstance ");
        }
    }
}

Outputs:

SubClass extends ParentClass. subClassInstance is instanceof ParentClass.

Different getClass() return results with subClassInstance and parentClassInstance.

Programmatically Hide/Show Android Soft Keyboard

Did you try InputMethodManager.SHOW_IMPLICIT in first window.

and for hiding in second window use InputMethodManager.HIDE_IMPLICIT_ONLY

EDIT :

If its still not working then probably you are putting it at the wrong place. Override onFinishInflate() and show/hide there.

@override
public void onFinishInflate() {
     /* code to show keyboard on startup */
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(mUserNameEdit, InputMethodManager.SHOW_IMPLICIT);
}

How to stretch in width a WPF user control to its window?

What container are you adding the UserControl to? Generally when you add controls to a Grid, they will stretch to fill the available space (unless their row/column is constrained to a certain width).

How do I convert an integer to string as part of a PostgreSQL query?

Because the number can be up to 15 digits, you'll need to cast to an 64 bit (8-byte) integer. Try this:

SELECT * FROM table
WHERE myint = mytext::int8

The :: cast operator is historical but convenient. Postgres also conforms to the SQL standard syntax

myint = cast ( mytext as int8)

If you have literal text you want to compare with an int, cast the int to text:

SELECT * FROM table
WHERE myint::varchar(255) = mytext

Batch files: List all files in a directory with relative paths

This answer will not work correctly with root paths containing equal signs (=). (Thanks @dbenham for pointing that out.)


EDITED: Fixed the issue with paths containing !, again spotted by @dbenham (thanks!).

Alternatively to calculating the length and extracting substrings you could use a different approach:

  • store the root path;

  • clear the root path from the file paths.

Here's my attempt (which worked for me):

@ECHO OFF
SETLOCAL DisableDelayedExpansion
SET "r=%__CD__%"
FOR /R . %%F IN (*) DO (
  SET "p=%%F"
  SETLOCAL EnableDelayedExpansion
  ECHO(!p:%r%=!
  ENDLOCAL
)

The r variable is assigned with the current directory. Unless the current directory is the root directory of a disk drive, it will not end with \, which we amend by appending the character. (No longer the case, as the script now reads the __CD__ variable, whose value always ends with \ (thanks @jeb!), instead of CD.)

In the loop, we store the current file path into a variable. Then we output the variable, stripping the root path along the way.

Makefile, header dependencies

Here's a two-liner:

CPPFLAGS = -MMD
-include $(OBJS:.c=.d)

This works with the default make recipe, as long as you have a list of all your object files in OBJS.

How to create a new instance from a class object in Python

Just call the "type" built in using three parameters, like this:

ClassName = type("ClassName", (Base1, Base2,...), classdictionary)

update as stated in the comment bellow this is not the answer to this question at all. I will keep it undeleted, since there are hints some people get here trying to dynamically create classes - which is what the line above does.

To create an object of a class one has a reference too, as put in the accepted answer, one just have to call the class:

instance = ClassObject()

The mechanism for instantiation is thus:

Python does not use the new keyword some languages use - instead it's data model explains the mechanism used to create an instantance of a class when it is called with the same syntax as any other callable:

Its class' __call__ method is invoked (in the case of a class, its class is the "metaclass" - which is usually the built-in type). The normal behavior of this call is to invoke the (pseudo) static __new__ method on the class being instantiated, followed by its __init__. The __new__ method is responsible for allocating memory and such, and normally is done by the __new__ of object which is the class hierarchy root.

So calling ClassObject() invokes ClassObject.__class__.call() (which normally will be type.__call__) this __call__ method will receive ClassObject itself as the first parameter - a Pure Python implementation would be like this: (the cPython version is of course, done in C, and with lots of extra code for cornercases and optimizations)

class type:
    ...
    def __call__(cls, *args, **kw):
          constructor = getattr(cls, "__new__")
          instance = constructor(cls) if constructor is object.__new__ else constructor(cls, *args, **kw)
          instance.__init__(cls, *args, **kw)
          return instance

(I don't recall seeing on the docs the exact justification (or mechanism) for suppressing extra parameters to the root __new__ and passing it to other classes - but it is what happen "in real life" - if object.__new__ is called with any extra parameters it raises a type error - however, any custom implementation of a __new__ will get the extra parameters normally)

Reading From A Text File - Batch

Your code "for /f "tokens=* delims=" %%x in (a.txt) do echo %%x" will work on most Windows Operating Systems unless you have modified commands.

So you could instead "cd" into the directory to read from before executing the "for /f" command to follow out the string. For instance if the file "a.txt" is located at C:\documents and settings\%USERNAME%\desktop\a.txt then you'd use the following.

cd "C:\documents and settings\%USERNAME%\desktop"
for /f "tokens=* delims=" %%x in (a.txt) do echo %%x
echo.
echo.
echo.
pause >nul
exit

But since this doesn't work on your computer for x reason there is an easier and more efficient way of doing this. Using the "type" command.

@echo off
color a
cls
cd "C:\documents and settings\%USERNAME%\desktop"
type a.txt
echo.
echo.
pause >nul
exit

Or if you'd like them to select the file from which to write in the batch you could do the following.

@echo off
:A
color a
cls
echo Choose the file that you want to read.
echo.
echo.
tree
echo.
echo.
echo.
set file=
set /p file=File:
cls
echo Reading from %file%
echo.
type %file%
echo.
echo.
echo.
set re=
set /p re=Y/N?:
if %re%==Y goto :A
if %re%==y goto :A
exit

How to play .wav files with java

Another way of doing it with AudioInputStream:

import java.io.File;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.swing.JDialog;
import javax.swing.JFileChooser;

public class CoreJavaSound extends Object implements LineListener {
    File soundFile;

    JDialog playingDialog;

    Clip clip;

    public static void main(String[] args) throws Exception {
        CoreJavaSound s = new CoreJavaSound();
    }

    public CoreJavaSound() throws Exception {
        JFileChooser chooser = new JFileChooser();
        chooser.showOpenDialog(null);
        soundFile = chooser.getSelectedFile();

        System.out.println("Playing " + soundFile.getName());

        Line.Info linfo = new Line.Info(Clip.class);
        Line line = AudioSystem.getLine(linfo);
        clip = (Clip) line;
        clip.addLineListener(this);
        AudioInputStream ais = AudioSystem.getAudioInputStream(soundFile);
        clip.open(ais);
        clip.start();
    }

    public void update(LineEvent le) {
        LineEvent.Type type = le.getType();
        if (type == LineEvent.Type.OPEN) {
            System.out.println("OPEN");
        } else if (type == LineEvent.Type.CLOSE) {
            System.out.println("CLOSE");
            System.exit(0);
        } else if (type == LineEvent.Type.START) {
            System.out.println("START");
            playingDialog.setVisible(true);
        } else if (type == LineEvent.Type.STOP) {
            System.out.println("STOP");
            playingDialog.setVisible(false);
            clip.close();
        }
    }
}

Is there a way to cast float as a decimal without rounding and preserving its precision?

Try SELECT CAST(field1 AS DECIMAL(10,2)) field1 and replace 10,2 with whatever precision you need.

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

Just for simplifying and clarifying the proper usage of ALTER SEQUENCE and SELECT setval for resetting the sequence:

ALTER SEQUENCE sequence_name RESTART WITH 1;

is equivalent to

SELECT setval('sequence_name', 1, FALSE);

Either of the statements may be used to reset the sequence and you can get the next value by nextval('sequence_name') as stated here also:

nextval('sequence_name')

Bash Shell Script - Check for a flag and grab its value

Try shFlags -- Advanced command-line flag library for Unix shell scripts.

http://code.google.com/p/shflags/

It is very good and very flexible.

FLAG TYPES: This is a list of the DEFINE_*'s that you can do. All flags take a name, default value, help-string, and optional 'short' name (one-letter name). Some flags have other arguments, which are described with the flag.

DEFINE_string: takes any input, and intreprets it as a string.

DEFINE_boolean: typically does not take any argument: say --myflag to set FLAGS_myflag to true, or --nomyflag to set FLAGS_myflag to false. Alternately, you can say --myflag=true or --myflag=t or --myflag=0 or --myflag=false or --myflag=f or --myflag=1 Passing an option has the same affect as passing the option once.

DEFINE_float: takes an input and intreprets it as a floating point number. As shell does not support floats per-se, the input is merely validated as being a valid floating point value.

DEFINE_integer: takes an input and intreprets it as an integer.

SPECIAL FLAGS: There are a few flags that have special meaning: --help (or -?) prints a list of all the flags in a human-readable fashion --flagfile=foo read flags from foo. (not implemented yet) -- as in getopt(), terminates flag-processing

EXAMPLE USAGE:

-- begin hello.sh --
 ! /bin/sh
. ./shflags
DEFINE_string name 'world' "somebody's name" n
FLAGS "$@" || exit $?
eval set -- "${FLAGS_ARGV}"
echo "Hello, ${FLAGS_name}."
-- end hello.sh --

$ ./hello.sh -n Kate
Hello, Kate.

Note: I took this text from shflags documentation

Get Row Index on Asp.net Rowcommand event

ImageButton \ Button etc.

CommandArgument='<%# Container.DataItemIndex%>' 

code-behind

protected void gvProductsList_RowCommand(object sender, GridViewCommandEventArgs e)
{
    int index = e.CommandArgument;
}

Running stages in parallel with Jenkins workflow / pipeline

that syntax is now deprecated, you will get this error:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 14: Expected a stage @ line 14, column 9.
       parallel firstTask: {
       ^

WorkflowScript: 14: Stage does not have a name @ line 14, column 9.
       parallel secondTask: {
       ^

2 errors

You should do something like:

stage("Parallel") {
    steps {
        parallel (
            "firstTask" : {
                //do some stuff
            },
            "secondTask" : {
                // Do some other stuff in parallel
            }
        )
    }
}

Just to add the use of node here, to distribute jobs across multiple build servers/ VMs:

pipeline {
  stages {
    stage("Work 1"){
     steps{
      parallel ( "Build common Library":   
            {
              node('<Label>'){
                  /// your stuff
                  }
            },

        "Build Utilities" : {
            node('<Label>'){
               /// your stuff
              }
           }
         )
    }
}

All VMs should be labelled as to use as a pool.

ImportError: Cannot import name X

You have circular dependent imports. physics.py is imported from entity before class Ent is defined and physics tries to import entity that is already initializing. Remove the dependency to physics from entity module.

How can I see the size of a GitHub repository before cloning it?

If you're trying to find out the size of your own repositories.

All you have to do is go to GitHub settings repositories and you see all the sizes right there in the browser no extra work needed.

https://github.com/settings/repositories

Save Screen (program) output to a file

The following might be useful (tested on: Linux/Ubuntu 12.04 (Precise Pangolin)):

cat /dev/ttyUSB0

Using the above, you can then do all the re-directions that you need. For example, to dump output to your console while saving to your file, you'd do:

cat /dev/ttyUSB0 | tee console.log

Does the Java &= operator apply & or &&?

see 15.22.2 of the JLS. For boolean operands, the & operator is boolean, not bitwise. The only difference between && and & for boolean operands is that for && it is short circuited (meaning that the second operand isn't evaluated if the first operand evaluates to false).

So in your case, if b is a primitive, a = a && b, a = a & b, and a &= b all do the same thing.

ImportError: No module named 'django.core.urlresolvers'

To solve this either you down-grade the Django to any version lesser than 2.0. pip install Django==1.11.29.

How to efficiently check if variable is Array or Object (in NodeJS & V8)?

If its just about detecting whether or not you're dealing with an Object, I could think of

Object.getPrototypeOf( obj ) === Object.prototype

However, this would probably fail for non-object primitive values. Actually there is nothing wrong with invoking .toString() to retreive the [[cclass]] property. You can even create a nice syntax like

var type = Function.prototype.call.bind( Object.prototype.toString );

and then use it like

if( type( obj ) === '[object Object]' ) { }

It might not be the fastest operation but I don't think the performance leak there is too big.

Javascript - Open a given URL in a new tab by clicking a button

Adding target="_blank" should do it:

<a id="myLink" href="www.google.com" target="_blank">google</a>

How to use Simple Ajax Beginform in Asp.net MVC 4?

Simple example: Form with textbox and Search button.

If you write "name" into the textbox and submit form, it will brings you patients with "name" in table.

View:

@using (Ajax.BeginForm("GetPatients", "Patient", new AjaxOptions {//GetPatients is name of method in PatientController
    InsertionMode = InsertionMode.Replace, //target element(#patientList) will be replaced
    UpdateTargetId = "patientList",
    LoadingElementId = "loader" // div with .gif loader - that is shown when data are loading   
}))
{
    string patient_Name = "";
    @Html.EditorFor(x=>patient_Name) //text box with name and id, that it will pass to controller
    <input  type="submit" value="Search" />
}

@* ... *@
<div id="loader" class=" aletr" style="display:none">
    Loading...<img src="~/Images/ajax-loader.gif" />
</div>
@Html.Partial("_patientList") @* this is view with patient table. Same view you will return from controller *@

_patientList.cshtml:

@model IEnumerable<YourApp.Models.Patient>

<table id="patientList" >
<tr>
    <th>
        @Html.DisplayNameFor(model => model.Name)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Number)
    </th>       
</tr>
@foreach (var patient in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => patient.Name)
    </td>
    <td>
        @Html.DisplayFor(modelItem => patient.Number)
    </td>
</tr>
}
</table>

Patient.cs

public class Patient
{
   public string Name { get; set; }
   public int Number{ get; set; }
}

PatientController.cs

public PartialViewResult GetPatients(string patient_Name="")
{
   var patients = yourDBcontext.Patients.Where(x=>x.Name.Contains(patient_Name))
   return PartialView("_patientList", patients);
}

And also as TSmith said in comments, don´t forget to install jQuery Unobtrusive Ajax library through NuGet.

Invalid date in safari

Use the below format, it would work on all the browsers

var year = 2016;
var month = 02;           // month varies from 0-11 (Jan-Dec)
var day = 23;

month = month<10?"0"+month:month;        // to ensure YYYY-MM-DD format
day = day<10?"0"+day:day;

dateObj = new Date(year+"-"+month+"-"+day);

alert(dateObj); 

//Your output would look like this "Wed Mar 23 2016 00:00:00 GMT+0530 (IST)"

//Note this would be in the current timezone in this case denoted by IST, to convert to UTC timezone you can include

alert(dateObj.toUTCSting);

//Your output now would like this "Tue, 22 Mar 2016 18:30:00 GMT"

Note that now the dateObj shows the time in GMT format, also note that the date and time have been changed correspondingly.

The "toUTCSting" function retrieves the corresponding time at the Greenwich meridian. This it accomplishes by establishing the time difference between your current timezone to the Greenwich Meridian timezone.

In the above case the time before conversion was 00:00 hours and minutes on the 23rd of March in the year 2016. And after conversion from GMT+0530 (IST) hours to GMT (it basically subtracts 5.30 hours from the given timestamp in this case) the time reflects 18.30 hours on the 22nd of March in the year 2016 (exactly 5.30 hours behind the first time).

Further to convert any date object to timestamp you can use

alert(dateObj.getTime());

//output would look something similar to this "1458671400000"

This would give you the unique timestamp of the time

How to display Toast in Android?

This worked for me:

Toast.makeText(getBaseContext(), "your text here" , Toast.LENGTH_SHORT ).show();

Using Notepad++ to validate XML against an XSD

  1. In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager then find Xml Tools plugin. Tick the box and click Install

    enter image description here

  2. Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now).
    Following dialog will open: enter image description here

  3. Click on .... Point to XSD file and I am pretty sure you'll be able to handle things from here.

Hope this saves you some time.

EDIT: Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
In version 7.7.1 plugin manager is back under a different guise... Plugin Admin so now you can simply update notepad++ and have it back.

enter image description here

yii2 redirect in controller action does not work?

here is another way to do this

if(!Yii::$app->request->getIsPost()) {
    return Yii::$app->getResponse()->redirect(array('/user/index',302));
}

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) symfony2

'default' => env('DB_CONNECTION', 'mysql'),

add this in your code

How to pass data from child component to its parent in ReactJS?

React.createClass method has been deprecated in the new version of React, you can do it very simply in the following way make one functional component and another class component to maintain state:

Parent:

_x000D_
_x000D_
const ParentComp = () => {_x000D_
  _x000D_
  getLanguage = (language) => {_x000D_
    console.log('Language in Parent Component: ', language);_x000D_
  }_x000D_
  _x000D_
  <ChildComp onGetLanguage={getLanguage}_x000D_
};
_x000D_
_x000D_
_x000D_

Child:

_x000D_
_x000D_
class ChildComp extends React.Component {_x000D_
    state = {_x000D_
      selectedLanguage: ''_x000D_
    }_x000D_
    _x000D_
    handleLangChange = e => {_x000D_
        const language = e.target.value;_x000D_
        thi.setState({_x000D_
          selectedLanguage = language;_x000D_
        });_x000D_
        this.props.onGetLanguage({language}); _x000D_
    }_x000D_
_x000D_
    render() {_x000D_
        const json = require("json!../languages.json");_x000D_
        const jsonArray = json.languages;_x000D_
        const selectedLanguage = this.state;_x000D_
        return (_x000D_
            <div >_x000D_
                <DropdownList ref='dropdown'_x000D_
                    data={jsonArray} _x000D_
                    value={tselectedLanguage}_x000D_
                    caseSensitive={false} _x000D_
                    minLength={3}_x000D_
                    filter='contains'_x000D_
                    onChange={this.handleLangChange} />_x000D_
            </div>            _x000D_
        );_x000D_
    }_x000D_
};
_x000D_
_x000D_
_x000D_

Injecting $scope into an angular service function()

Instead of trying to modify the $scope within the service, you can implement a $watch within your controller to watch a property on your service for changes and then update a property on the $scope. Here is an example you might try in a controller:

angular.module('cfd')
    .controller('MyController', ['$scope', 'StudentService', function ($scope, StudentService) {

        $scope.students = null;

        (function () {
            $scope.$watch(function () {
                return StudentService.students;
            }, function (newVal, oldVal) {
                if ( newValue !== oldValue ) {
                    $scope.students = newVal;
                }
            });
        }());
    }]);

One thing to note is that within your service, in order for the students property to be visible, it needs to be on the Service object or this like so:

this.students = $http.get(path).then(function (resp) {
  return resp.data;
});

Disable developer mode extensions pop up in Chrome

Can't be disabled. Quoting: "Sorry, we know it is annoying, but you the malware writers..."

Your only options are: adapt your automated tests to this new behavior, or upload the offending script to Chrome Web Store (which can be done in an "unlisted" fashion).

Where is the Docker daemon log?

If your OS is using systemd then you can view docker daemon log with:

sudo journalctl -fu docker.service

Save text file UTF-8 encoded with VBA

Here is another way to do this - using the API function WideCharToMultiByte:

Option Explicit

Private Declare Function WideCharToMultiByte Lib "kernel32.dll" ( _
  ByVal CodePage As Long, _
  ByVal dwFlags As Long, _
  ByVal lpWideCharStr As Long, _
  ByVal cchWideChar As Long, _
  ByVal lpMultiByteStr As Long, _
  ByVal cbMultiByte As Long, _
  ByVal lpDefaultChar As Long, _
  ByVal lpUsedDefaultChar As Long) As Long

Private Sub getUtf8(ByRef s As String, ByRef b() As Byte)
Const CP_UTF8 As Long = 65001
Dim len_s As Long
Dim ptr_s As Long
Dim size As Long
  Erase b
  len_s = Len(s)
  If len_s = 0 Then _
    Err.Raise 30030, , "Len(WideChars) = 0"
  ptr_s = StrPtr(s)
  size = WideCharToMultiByte(CP_UTF8, 0, ptr_s, len_s, 0, 0, 0, 0)
  If size = 0 Then _
    Err.Raise 30030, , "WideCharToMultiByte() = 0"
  ReDim b(0 To size - 1)
  If WideCharToMultiByte(CP_UTF8, 0, ptr_s, len_s, VarPtr(b(0)), size, 0, 0) = 0 Then _
    Err.Raise 30030, , "WideCharToMultiByte(" & Format$(size) & ") = 0"
End Sub

Public Sub writeUtf()
Dim file As Integer
Dim s As String
Dim b() As Byte
  s = "äöüßµ@€|~{}[]²³\ .." & _
    " OMEGA" & ChrW$(937) & ", SIGMA" & ChrW$(931) & _
    ", alpha" & ChrW$(945) & ", beta" & ChrW$(946) & ", pi" & ChrW$(960) & vbCrLf
  file = FreeFile
  Open "C:\Temp\TestUtf8.txt" For Binary Access Write Lock Read Write As #file
  getUtf8 s, b
  Put #file, , b
  Close #file
End Sub

How to make circular background using css?

Keep it simple:

.circle
  {
    border-radius: 50%;
    width: 200px;
    height: 200px; 
  }

Width and height can be anything, as long as they're equal

@Transactional(propagation=Propagation.REQUIRED)

If you need a laymans explanation of the use beyond that provided in the Spring Docs

Consider this code...

class Service {
    @Transactional(propagation=Propagation.REQUIRED)
    public void doSomething() {
        // access a database using a DAO
    }
}

When doSomething() is called it knows it has to start a Transaction on the database before executing. If the caller of this method has already started a Transaction then this method will use that same physical Transaction on the current database connection.

This @Transactional annotation provides a means of telling your code when it executes that it must have a Transaction. It will not run without one, so you can make this assumption in your code that you wont be left with incomplete data in your database, or have to clean something up if an exception occurs.

Transaction management is a fairly complicated subject so hopefully this simplified answer is helpful

Finding second occurrence of a substring in a string in Java

int first = string.indexOf("is");
int second = string.indexOf("is", first + 1);

This overload starts looking for the substring from the given index.

How do I set up IntelliJ IDEA for Android applications?

You just need to install Android development kit from http://developer.android.com/sdk/installing/studio.html#Updating

and also Download and install Java JDK (Choose the Java platform)

define the environment variable in windows System setting https://confluence.atlassian.com/display/DOC/Setting+the+JAVA_HOME+Variable+in+Windows

Voila ! You are Donezo !

Select max value of each group

select * from (select * from table order by value desc limit 999999999) v group by v.name

How to initialize a JavaScript Date to a particular time zone

Background

JavaScript's Date object tracks time in UTC internally, but typically accepts input and produces output in the local time of the computer it's running on. It has very few facilities for working with time in other time zones.

The internal representation of a Date object is a single number, representing the number of milliseconds that have elapsed since 1970-01-01 00:00:00 UTC, without regard to leap seconds. There is no time zone or string format stored in the Date object itself. When various functions of the Date object are used, the computer's local time zone is applied to the internal representation. If the function produces a string, then the computer's locale information may be taken into consideration to determine how to produce that string. The details vary per function, and some are implementation-specific.

The only operations the Date object can do with non-local time zones are:

  • It can parse a string containing a numeric UTC offset from any time zone. It uses this to adjust the value being parsed, and stores the UTC equivalent. The original local time and offset are not retained in the resulting Date object. For example:

    var d = new Date("2020-04-13T00:00:00.000+08:00");
    d.toISOString()  //=> "2020-04-12T16:00:00.000Z"
    d.valueOf()      //=> 1586707200000  (this is what is actually stored in the object)
    
  • In environments that have implemented the ECMASCript Internationalization API (aka "Intl"), a Date object can produce a locale-specific string adjusted to a given time zone identifier. This is accomplished via the timeZone option to toLocaleString and its variations. Most implementations will support IANA time zone identifiers, such as 'America/New_York'. For example:

    var d = new Date("2020-04-13T00:00:00.000+08:00");
    d.toLocaleString('en-US', { timeZone: 'America/New_York' })
    //=> "4/12/2020, 12:00:00 PM"
    // (midnight in China on Apring 13th is noon in New York on April 12th)
    

    Most modern environments support the full set of IANA time zone identifiers (see the compatibility table here). However, keep in mind that the only identifier required to be supported by Intl is 'UTC', thus you should check carefully if you need to support older browsers or atypical environments (for example, lightweight IoT devices).

Libraries

There are several libraries that can be used to work with time zones. Though they still cannot make the Date object behave any differently, they typically implement the standard IANA timezone database and provide functions for using it in JavaScript. Modern libraries use the time zone data supplied by the Intl API, but older libraries typically have overhead, especially if you are running in a web browser, as the database can get a bit large. Some of these libraries also allow you to selectively reduce the data set, either by which time zones are supported and/or by the range of dates you can work with.

Here are the libraries to consider:

Intl-based Libraries

New development should choose from one of these implementations, which rely on the Intl API for their time zone data:

Non-Intl Libraries

These libraries are maintained, but carry the burden of packaging their own time zone data, which can be quite large.

* While Moment and Moment-Timezone were previously recommended, the Moment team now prefers users chose Luxon for new development.

Discontinued Libraries

These libraries have been officially discontinued and should no longer be used.

Future Proposals

The TC39 Temporal Proposal aims to provide a new set of standard objects for working with dates and times in the JavaScript language itself. This will include support for a time zone aware object.

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

Tested xcode 8 stable version ; Need to use var request variable with URLRequest() With thats you can easily fix that (bug)

var request = URLRequest(url:myUrl!) And

let task = URLSession.shared().dataTask(with: request as URLRequest) { }

Worked fine ! Thank you guys, i think help many people. !

Multiple modals overlay

The other solutions did not work for me out of the box. I think perhaps because I am using a more recent version of Bootstrap (3.3.2).... the overlay was appearing on top of the modal dialog.

I refactored the code a bit and commented out the part that was adjusting the modal-backdrop. This fixed the issue.

    var $body = $('body');
    var OPEN_MODALS_COUNT = 'fv_open_modals';
    var Z_ADJUSTED = 'fv-modal-stack';
    var defaultBootstrapModalZindex = 1040;

    // keep track of the number of open modals                   
    if ($body.data(OPEN_MODALS_COUNT) === undefined) {
        $body.data(OPEN_MODALS_COUNT, 0);
    }

    $body.on('show.bs.modal', '.modal', function (event)
    {
        if (!$(this).hasClass(Z_ADJUSTED))  // only if z-index not already set
        {
            // Increment count & mark as being adjusted
            $body.data(OPEN_MODALS_COUNT, $body.data(OPEN_MODALS_COUNT) + 1);
            $(this).addClass(Z_ADJUSTED);

            // Set Z-Index
            $(this).css('z-index', defaultBootstrapModalZindex + (1 * $body.data(OPEN_MODALS_COUNT)));

            //// BackDrop z-index   (Doesn't seem to be necessary with Bootstrap 3.3.2 ...)
            //$('.modal-backdrop').not( '.' + Z_ADJUSTED )
            //        .css('z-index', 1039 + (10 * $body.data(OPEN_MODALS_COUNT)))
            //        .addClass(Z_ADJUSTED);
        }
    });
    $body.on('hidden.bs.modal', '.modal', function (event)
    {
        // Decrement count & remove adjusted class
        $body.data(OPEN_MODALS_COUNT, $body.data(OPEN_MODALS_COUNT) - 1);
        $(this).removeClass(Z_ADJUSTED);
        // Fix issue with scrollbar being shown when any modal is hidden
        if($body.data(OPEN_MODALS_COUNT) > 0)
            $body.addClass('modal-open');
    });

As a side note, if you want to use this in AngularJs, just put the code inside of your module's .run() method.

Disable a textbox using CSS

**just copy paste this code and run you can see the textbox disabled **

<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title> 

<style>.container{float:left;width:200px;height:25px;position:relative;}
       .container input{float:left;width:200px;height:25px;}
       .overlay{display:block;width:208px;position:absolute;top:0px;left:0px;height:32px;} 
</style>
 </head>
<body>
      <div class="container">
       <input type="text" value="[email protected]" />
       <div class="overlay">
        </div>
       </div> 
</body>
</html>

Execute a terminal command from a Cocoa app

Or since Objective C is just C with some OO layer on top you can use the posix conterparts:

int execl(const char *path, const char *arg0, ..., const char *argn, (char *)0);
int execle(const char *path, const char *arg0, ..., const char *argn, (char *)0, char *const envp[]);
int execlp(const char *file, const char *arg0, ..., const char *argn, (char *)0);
int execlpe(const char *file, const char *arg0, ..., const char *argn, (char *)0, char *const envp[]);
int execv(const char *path, char *const argv[]);
int execve(const char *path, char *const argv[], char *const envp[]);
int execvp(const char *file, char *const argv[]);
int execvpe(const char *file, char *const argv[], char *const envp[]); 

They are included from unistd.h header file.

Adjust width of input field to its input

Quite simple:

oninput='this.style.width = (this.scrollWidth - N) + "px";'

Where N is some number (2 in the example, 17 on something I'm developing) that is determined experimentally.

Subtracting N prevents this strange extrenuous space from accumulating long before the text reaches the end of the text box.

Compare. Pay careful attention to how the size changes after even just the first character.

_x000D_
_x000D_
<p>Subtracting N:</p>    _x000D_
<input type="text" placeholder="enter lots of text here" oninput='this.style.width = (this.scrollWidth-2) + "px";'>_x000D_
_x000D_
<p>Not Subtracting N:</p>    _x000D_
<input type="text" placeholder="enter lots of text here" oninput='this.style.width = (this.scrollWidth) + "px";'>
_x000D_
_x000D_
_x000D_

Drop default constraint on a column in TSQL

This is how you would drop the constraint

ALTER TABLE <schema_name, sysname, dbo>.<table_name, sysname, table_name>
   DROP CONSTRAINT <default_constraint_name, sysname, default_constraint_name>
GO

With a script

-- t-sql scriptlet to drop all constraints on a table
DECLARE @database nvarchar(50)
DECLARE @table nvarchar(50)

set @database = 'dotnetnuke'
set @table = 'tabs'

DECLARE @sql nvarchar(255)
WHILE EXISTS(select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where constraint_catalog = @database and table_name = @table)
BEGIN
    select    @sql = 'ALTER TABLE ' + @table + ' DROP CONSTRAINT ' + CONSTRAINT_NAME 
    from    INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
    where    constraint_catalog = @database and 
            table_name = @table
    exec    sp_executesql @sql
END

Credits go to Jon Galloway http://weblogs.asp.net/jgalloway/archive/2006/04/12/442616.aspx

Python Selenium Chrome Webdriver

Here's a simpler solution: install python-chromedrive package, import it in your script, and it's done.

Step by step:
1. pip install chromedriver-binary
2. import the package

from selenium import webdriver
import chromedriver_binary  # Adds chromedriver binary to path

driver = webdriver.Chrome()
driver.get("http://www.python.org")

Reference: https://pypi.org/project/chromedriver-binary/

How to get the EXIF data from a file using C#

Recently, I used this .NET Metadata API. I have also written a blog post about it, that shows reading, updating, and removing the EXIF data from images using C#.

using (Metadata metadata = new Metadata("image.jpg"))
{
    IExif root = metadata.GetRootPackage() as IExif;
    if (root != null && root.ExifPackage != null)
    {
        Console.WriteLine(root.ExifPackage.DateTime);
     }
}

How can I mock an ES6 module import using Jest?

Adding more to Andreas' answer. I had the same problem with ES6 code, but I did not want to mutate the imports. That looked hacky. So I did this:

import myModule from '../myModule';
import dependency from '../dependency';
jest.mock('../dependency');

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    myModule(2);
  });
});

And added file dependency.js in the " __ mocks __" folder parallel to file dependency.js. This worked for me. Also, this gave me the option to return suitable data from the mock implementation. Make sure you give the correct path to the module you want to mock.

How to use a keypress event in AngularJS?

Here is what I figured out when I was building an app with a similar requirement, it doesn't require writing a directive and it's relatively simple to tell what it does:

<input type="text" ng-keypress="($event.charCode==13)?myFunction():return" placeholder="Will Submit on Enter">

What's the difference between process.cwd() vs __dirname?

As per node js doc process.cwd()

cwd is a method of global object process, returns a string value which is the current working directory of the Node.js process.

As per node js doc __dirname

The directory name of current script as a string value. __dirname is not actually a global but rather local to each module.

Let me explain with example,

suppose we have a main.js file resides inside C:/Project/main.js and running node main.js both these values return same file

or simply with following folder structure

Project 
+-- main.js
+--lib
   +-- script.js

main.js

console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project
console.log(__dirname===process.cwd())
// true

suppose we have another file script.js files inside a sub directory of project ie C:/Project/lib/script.js and running node main.js which require script.js

main.js

require('./lib/script.js')
console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project
console.log(__dirname===process.cwd())
// true

script.js

console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project\lib
console.log(__dirname===process.cwd())
// false

How to configure log4j to only keep log files for the last seven days?

Use the setting log4j.appender.FILE.RollingPolicy.FileNamePattern, e.g. log4j.appender.FILE.RollingPolicy.FileNamePattern=F:/logs/filename.log.%d{dd}.gz for keeping logs one month before rolling over.

I didn't wait for one month to check but I tried with mm (i.e. minutes) and confirmed it overwrites, so I am assuming it will work for all patterns.

Subprocess check_output returned non-zero exit status 1

The word check_ in the name means that if the command (the shell in this case that returns the exit status of the last command (yum in this case)) returns non-zero status then it raises CalledProcessError exception. It is by design. If the command that you want to run may return non-zero status on success then either catch this exception or don't use check_ methods. You could use subprocess.call in your case because you are ignoring the captured output, e.g.:

import subprocess

rc = subprocess.call(['grep', 'pattern', 'file'],
                     stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
if rc == 0: # found
   ...
elif rc == 1: # not found
   ...
elif rc > 1: # error
   ...

You don't need shell=True to run the commands from your question.

Iterating through a List Object in JSP

you can read empList directly in forEach tag.Try this

 <table>
       <c:forEach items="${sessionScope.empList}" var="employee">
            <tr>
                <td>Employee ID: <c:out value="${employee.eid}"/></td>
                <td>Employee Pass: <c:out value="${employee.ename}"/></td>  
            </tr>
        </c:forEach>
    </table>

Json.net serialize/deserialize derived types?

Since the question is so popular, it may be useful to add on what to do if you want to control the type property name and its value.

The long way is to write custom JsonConverters to handle (de)serialization by manually checking and setting the type property.

A simpler way is to use JsonSubTypes, which handles all the boilerplate via attributes:

[JsonConverter(typeof(JsonSubtypes), "Sound")]
[JsonSubtypes.KnownSubType(typeof(Dog), "Bark")]
[JsonSubtypes.KnownSubType(typeof(Cat), "Meow")]
public class Animal
{
    public virtual string Sound { get; }
    public string Color { get; set; }
}

public class Dog : Animal
{
    public override string Sound { get; } = "Bark";
    public string Breed { get; set; }
}

public class Cat : Animal
{
    public override string Sound { get; } = "Meow";
    public bool Declawed { get; set; }
}

How to zero pad a sequence of integers in bash so that all have the same width?

One way without using external process forking is string manipulation, in a generic case it would look like this:

#start value
CNT=1

for [whatever iterative loop, seq, cat, find...];do
   # number of 0s is at least the amount of decimals needed, simple concatenation
   TEMP="000000$CNT"
   # for example 6 digits zero padded, get the last 6 character of the string
   echo ${TEMP:(-6)}
   # increment, if the for loop doesn't provide the number directly
   TEMP=$(( TEMP + 1 ))
done

This works quite well on WSL as well, where forking is a really heavy operation. I had a 110000 files list, using printf "%06d" $NUM took over 1 minute, the solution above ran in about 1 second.

Remove useless zero digits from decimals in PHP

For everyone coming to this site having the same problem with commata instead, change:

$num = number_format($value, 1, ',', '');

to:

$num = str_replace(',0', '', number_format($value, 1, ',', '')); // e.g. 100,0 becomes 100


If there are two zeros to be removed, then change to:

$num = str_replace(',00', '', number_format($value, 2, ',', '')); // e.g. 100,00 becomes 100

More here: PHP number: decimal point visible only if needed

C++ - how to find the length of an integer

Would this be an efficient approach? Converting to a string and finding the length property?

int num = 123  
string strNum = to_string(num); // 123 becomes "123"
int length = strNum.length(); // length = 3
char array[3]; // or whatever you want to do with the length

What is the difference between a HashMap and a TreeMap?

HashMap is implemented by Hash Table while TreeMap is implemented by Red-Black tree. The main difference between HashMap and TreeMap actually reflect the main difference between a Hash and a Binary Tree , that is, when iterating, TreeMap guarantee can the key order which is determined by either element's compareTo() method or a comparator set in the TreeMap's constructor.

Take a look at following diagram.

enter image description here

How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

If you get an exception for : Invalid column type

Please use getNamedParameterJdbcTemplate() instead of getJdbcTemplate()

 List<Foo> foo = getNamedParameterJdbcTemplate().query("SELECT * FROM foo WHERE a IN (:ids)",parameters,
 getRowMapper());

Note that the second two arguments are swapped around.

Program "make" not found in PATH

Probably there are some files inside C:\cygwin\bin called xxxxxmake.exe, try renaming it to make.exe

Kill a postgresql session/connection

I use the following rake task to override the Rails drop_database method.

lib/database.rake

require 'active_record/connection_adapters/postgresql_adapter'
module ActiveRecord
  module ConnectionAdapters
    class PostgreSQLAdapter < AbstractAdapter
      def drop_database(name)
        raise "Nah, I won't drop the production database" if Rails.env.production?
        execute <<-SQL
          UPDATE pg_catalog.pg_database
          SET datallowconn=false WHERE datname='#{name}'
        SQL

        execute <<-SQL
          SELECT pg_terminate_backend(pg_stat_activity.pid)
          FROM pg_stat_activity
          WHERE pg_stat_activity.datname = '#{name}';
        SQL
        execute "DROP DATABASE IF EXISTS #{quote_table_name(name)}"
      end
    end
  end
end

Edit: This is for Postgresql 9.2+

Char array in a struct - incompatible assignment?

You can also initialise it like this:

struct name sara = { "Sara", "Black" };

Since (as a special case) you're allowed to initialise char arrays from string constants.

Now, as for what a struct actually is - it's a compound type composed of other values. What sara actually looks like in memory is a block of 20 consecutive char values (which can be referred to using sara.first, followed by 0 or more padding bytes, followed by another block of 20 consecutive char values (which can be referred to using sara.last). All other instances of the struct name type are laid out in the same way.

In this case, it is very unlikely that there is any padding, so a struct name is just a block of 40 characters, for which you have a name for the first 20 and the last 20.

You can find out how big a block of memory a struct name takes using sizeof(struct name), and you can find out where within that block of memory each member of the structure is placed at using offsetof(struct name, first) and offsetof(struct name, last).

How do I seed a random class to avoid getting duplicate random values

Bit late, but the implementation used by System.Random is Environment.TickCount:

public Random() 
  : this(Environment.TickCount) {
}

This avoids having to cast DateTime.UtcNow.Ticks from a long, which is risky anyway as it doesn't represent ticks since system start, but "the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001 (0:00:00 UTC on January 1, 0001, in the Gregorian calendar)".

Was looking for a good integer seed for the TestApi's StringFactory.GenerateRandomString

How to grant all privileges to root user in MySQL 8.0

1. grant privileges

mysql> GRANT ALL PRIVILEGES ON . TO 'root'@'%'WITH GRANT OPTION;

mysql> FLUSH PRIVILEGES

2. check user table:

mysql> use mysql

mysql> select host,user from user enter image description here

3.Modify the configuration file

mysql default bind ip:127.0.0.1, if we want to remote visit services,just delete config

#Modify the configuration file
vi /usr/local/etc/my.cnf

#Comment out the ip-address option
[mysqld]
# Only allow connections from localhost
#bind-address = 127.0.0.1

4.finally restart the services

brew services restart mysql

Convert String To date in PHP

For PHP 5.3 this should work. You may need to fiddle with passing $dateInfo['is_dst'], wasn't working for me anyhow.

$date = '05/Feb/2010:14:00:01';
$dateInfo = date_parse_from_format('d/M/Y:H:i:s', $date);
$unixTimestamp = mktime(
    $dateInfo['hour'], $dateInfo['minute'], $dateInfo['second'],
    $dateInfo['month'], $dateInfo['day'], $dateInfo['year'],
    $dateInfo['is_dst']
);

Versions prior, this should work.

$date = '05/Feb/2010:14:00:01';
$format = '@^(?P<day>\d{2})/(?P<month>[A-Z][a-z]{2})/(?P<year>\d{4}):(?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2})$@';
preg_match($format, $date, $dateInfo);
$unixTimestamp = mktime(
    $dateInfo['hour'], $dateInfo['minute'], $dateInfo['second'],
    date('n', strtotime($dateInfo['month'])), $dateInfo['day'], $dateInfo['year'],
    date('I')
);

You may not like regular expressions. You could annotate it, of course, but not everyone likes that either. So, this is an alternative.

$day = $date[0].$date[1];
$month = date('n', strtotime($date[3].$date[4].$date[5]));
$year = $date[7].$date[8].$date[9].$date[10];
$hour = $date[12].$date[13];
$minute = $date[15].$date[16];
$second = $date[18].$date[19];

Or substr, or explode, whatever you wish to parse that string.

Recursive query in SQL Server

Sample of the Recursive Level:

enter image description here

DECLARE @VALUE_CODE AS VARCHAR(5);

--SET @VALUE_CODE = 'A' -- Specify a level

WITH ViewValue AS
(
    SELECT ValueCode
    , ValueDesc
    , PrecedingValueCode
    FROM ValuesTable
    WHERE PrecedingValueCode IS NULL
    UNION ALL
    SELECT A.ValueCode
    , A.ValueDesc
    , A.PrecedingValueCode 
    FROM ValuesTable A
    INNER JOIN ViewValue V ON
        V.ValueCode = A.PrecedingValueCode
)

SELECT ValueCode, ValueDesc, PrecedingValueCode

FROM ViewValue

--WHERE PrecedingValueCode  = @VALUE_CODE -- Specific level

--WHERE PrecedingValueCode  IS NULL -- Root

SQL Logic Operator Precedence: And and Or

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

You can use parentheses to override rules of precedence.

Codeigniter displays a blank page instead of error messages

The error, In my case, was occurring because my Apache server was configured to run PHP as Fast CGI, I changed it to FPM and it worked.

ConnectivityManager getNetworkInfo(int) deprecated

Here's how I check if the current network is using cellular or not on the latest Android versions:

val isCellular: Boolean get() {
    val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        cm.getNetworkCapabilities(cm.activeNetwork).hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
    } else {
        cm.activeNetworkInfo?.type == ConnectivityManager.TYPE_MOBILE
    }
}

Convert integer to hex and hex to integer

Maksym Kozlenko has a nice solution, and others come close to unlocking it's full potential but then miss completely to realized that you can define any sequence of characters, and use it's length as the Base. Which is why I like this slightly modified version of his solution, because it can work for base 16, or base 17, and etc.

For example, what if you wanted letters and numbers, but don't like I's for looking like 1's and O's for looking like 0's. You can define any sequence this way. Below is a form of a "Base 36" that skips the I and O to create a "modified base 34". Un-comment the hex line instead to run as hex.

declare @value int = 1234567890

DECLARE @seq varchar(100) = '0123456789ABCDEFGHJKLMNPQRSTUVWXYZ' -- modified base 34
--DECLARE @seq varchar(100) = '0123456789ABCDEF' -- hex
DECLARE @result varchar(50)
DECLARE @digit char(1)
DECLARE @baseSize int = len(@seq)
DECLARE @workingValue int = @value

SET @result = SUBSTRING(@seq, (@workingValue%@baseSize)+1, 1)

WHILE @workingValue > 0
BEGIN
    SET @digit = SUBSTRING(@seq, ((@workingValue/@baseSize)%@baseSize)+1, 1)

    SET @workingValue = @workingValue/@baseSize
    IF @workingValue <> 0 SET @result = @digit + @result
END 

select @value as Value, @baseSize as BaseSize, @result as Result

Value, BaseSize, Result

1234567890, 34, T5URAA

I also moved value over to a working value, and then work from the working value copy, as a personal preference.

Below is additional for reversing the transformation, for any sequence, with the base defined as the length of the sequence.

declare @value varchar(50) = 'T5URAA'

DECLARE @seq varchar(100) = '0123456789ABCDEFGHJKLMNPQRSTUVWXYZ' -- modified base 34
--DECLARE @seq varchar(100) = '0123456789ABCDEF' -- hex
DECLARE @result int = 0
DECLARE @digit char(1)
DECLARE @baseSize int = len(@seq)
DECLARE @workingValue varchar(50) = @value

DECLARE @PositionMultiplier int = 1
DECLARE @digitPositionInSequence int = 0

WHILE len(@workingValue) > 0
BEGIN
    SET @digit = right(@workingValue,1)
    SET @digitPositionInSequence = CHARINDEX(@digit,@seq)
    SET @result = @result + ( (@digitPositionInSequence -1) * @PositionMultiplier)

    --select @digit, @digitPositionInSequence, @PositionMultiplier, @result

    SET @workingValue = left(@workingValue,len(@workingValue)-1)
    SET @PositionMultiplier = @PositionMultiplier * @baseSize
END 

select @value as Value, @baseSize as BaseSize, @result as Result