Programs & Examples On #Save

To store (data) in a computer or on a storage device.

Saving images in Python at a very high quality

Just to add my results, also using Matplotlib.

.eps made all my text bold and removed transparency. .svg gave me high-resolution pictures that actually looked like my graph.

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# Do the plot code
fig.savefig('myimage.svg', format='svg', dpi=1200)

I used 1200 dpi because a lot of scientific journals require images in 1200 / 600 / 300 dpi, depending on what the image is of. Convert to desired dpi and format in GIMP or Inkscape.

Obviously the dpi doesn't matter since .svg are vector graphics and have "infinite resolution".

how to save DOMPDF generated content to file?

I did test your code and the only problem I could see was the lack of permission given to the directory you try to write the file in to.

Give "write" permission to the directory you need to put the file. In your case it is the current directory.

Use "chmod" in linux.

Add "Everyone" with "write" enabled to the security tab of the directory if you are in Windows.

How can I save an image with PIL?

You should be able to simply let PIL get the filetype from extension, i.e. use:

j.save("C:/Users/User/Desktop/mesh_trans.bmp")

Sql Server 'Saving changes is not permitted' error ? Prevent saving changes that require table re-creation

From the Tools menu, click on Options, select Designers from the side menu and untick prevent changes that can lead to recreation of a table. Then save the changes

How to edit/save a file through Ubuntu Terminal

Within Nano use Ctrl+O to save and Ctrl+X to exit if you were wondering

Saving image to file

You can try with this code

Image.Save("myfile.png", ImageFormat.Png)

Link : http://msdn.microsoft.com/en-us/library/ms142147.aspx

How to make a browser display a "save as dialog" so the user can save the content of a string to a file on his system?

Solution using only javascript

function saveFile(fileName,urlFile){
    let a = document.createElement("a");
    a.style = "display: none";
    document.body.appendChild(a);
    a.href = urlFile;
    a.download = fileName;
    a.click();
    window.URL.revokeObjectURL(url);
    a.remove();
}

let textData = `El contenido del archivo
que sera descargado`;
let blobData = new Blob([textData], {type: "text/plain"});
let url = window.URL.createObjectURL(blobData);
//let url = "pathExample/localFile.png"; // LocalFileDownload
saveFile('archivo.txt',url);

How to save a bitmap on internal storage

You might be able to use the following for decoding, compressing and saving an image:

     @Override
     public void onClick(View view) {
                onItemSelected1();
                InputStream image_stream = null;
                try {
                    image_stream = getContentResolver().openInputStream(myUri);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

                Bitmap image= BitmapFactory.decodeStream(image_stream );
                // path to sd card
                File path=Environment.getExternalStorageDirectory();
                //create a file
                File  dir=new File(path+"/ComDec/");
                dir.mkdirs();
                Date date=new Date();
                File file=new File(dir,date+".jpg");

                OutputStream out=null;
                try{
                    out=new FileOutputStream(file);
                    image.compress(format,size,out);
                    out.flush();
                    out.close();


                    MediaStore.Images.Media.insertImage(getContentResolver(), image," yourTitle "," yourDescription");

                    image=null;


                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                Toast.makeText(SecondActivity.this,"Image Save Successfully",Toast.LENGTH_LONG).show();
            }
        });

How to save a base64 image to user's disk using JavaScript?

In JavaScript you cannot have the direct access to the filesystem. However, you can make browser to pop up a dialog window allowing the user to pick the save location. In order to do this, use the replace method with your Base64String and replace "image/png" with "image/octet-stream":

"data:image/png;base64,iVBORw0KG...".replace("image/png", "image/octet-stream");

Also, W3C-compliant browsers provide 2 methods to work with base64-encoded and binary data:

Probably, you will find them useful in a way...


Here is a refactored version of what I understand you need:

_x000D_
_x000D_
window.addEventListener('DOMContentLoaded', () => {_x000D_
  const img = document.getElementById('embedImage');_x000D_
  img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' +_x000D_
    'AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO' +_x000D_
    '9TXL0Y4OHwAAAABJRU5ErkJggg==';_x000D_
_x000D_
  img.addEventListener('load', () => button.removeAttribute('disabled'));_x000D_
  _x000D_
  const button = document.getElementById('saveImage');_x000D_
  button.addEventListener('click', () => {_x000D_
    window.location.href = img.src.replace('image/png', 'image/octet-stream');_x000D_
  });_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
  <img id="embedImage" alt="Red dot" />_x000D_
  <button id="saveImage" disabled="disabled">save image</button>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do I get the coordinate position after using jQuery drag and drop?

I would start with something like this. Then update that to use the position plugin and that should get you where you want to be.

PHP mPDF save file as PDF

This can be done like this. It worked fine for me. And also set the directory permissions to 777 or 775 if not set.

ob_clean();
$mpdf->Output('directory_name/pdf_file_name.pdf', 'F');

Write and read a list from file

If you don't need it to be human-readable/editable, the easiest solution is to just use pickle.

To write:

with open(the_filename, 'wb') as f:
    pickle.dump(my_list, f)

To read:

with open(the_filename, 'rb') as f:
    my_list = pickle.load(f)

If you do need them to be human-readable, we need more information.

If my_list is guaranteed to be a list of strings with no embedded newlines, just write them one per line:

with open(the_filename, 'w') as f:
    for s in my_list:
        f.write(s + '\n')

with open(the_filename, 'r') as f:
    my_list = [line.rstrip('\n') for line in f]

If they're Unicode strings rather than byte strings, you'll want to encode them. (Or, worse, if they're byte strings, but not necessarily in the same encoding as your system default.)

If they might have newlines, or non-printable characters, etc., you can use escaping or quoting. Python has a variety of different kinds of escaping built into the stdlib.

Let's use unicode-escape here to solve both of the above problems at once:

with open(the_filename, 'w') as f:
    for s in my_list:
        f.write((s + u'\n').encode('unicode-escape'))

with open(the_filename, 'r') as f:
    my_list = [line.decode('unicode-escape').rstrip(u'\n') for line in f]

You can also use the 3.x-style solution in 2.x, with either the codecs module or the io module:*

import io

with io.open(the_filename, 'w', encoding='unicode-escape') as f:
    f.writelines(line + u'\n' for line in my_list)

with open(the_filename, 'r') as f:
    my_list = [line.rstrip(u'\n') for line in f]

* TOOWTDI, so which is the one obvious way? It depends… For the short version: if you need to work with Python versions before 2.6, use codecs; if not, use io.

How to do a "Save As" in vba code, saving my current Excel workbook with datestamp?

Most likely the path you are trying to access does not exist. It seems you are trying to save to a relative location and you do not have an file extension in that string. If you need to use relative paths you can parse the path from ActiveWorkbook.FullName

EDIT: Better syntax would also be

ActiveWorkbook.SaveAs Filename:=myFileName, FileFormat:=xlWorkbookNormal

Saving numpy array to txt file row wise

Very very easy: [1,2,3]

A list is like a column.

1
2
3

If you want a list like a row, double corchete:

[[1, 2, 3]]  --->    1, 2, 3

and

[[1, 2, 3], [4, 5, 6]]  ---> 1, 2, 3
                             4, 5, 6

Finally:

np.savetxt("file", [['r1c1', 'r1c2'], ['r2c1', 'r2c2']], delimiter=';', fmt='%s')

Note, the comma between square brackets, inner list are elements of the outer list

Saving an Object (Data persistence)

You could use the pickle module in the standard library. Here's an elementary application of it to your example:

import pickle

class Company(object):
    def __init__(self, name, value):
        self.name = name
        self.value = value

with open('company_data.pkl', 'wb') as output:
    company1 = Company('banana', 40)
    pickle.dump(company1, output, pickle.HIGHEST_PROTOCOL)

    company2 = Company('spam', 42)
    pickle.dump(company2, output, pickle.HIGHEST_PROTOCOL)

del company1
del company2

with open('company_data.pkl', 'rb') as input:
    company1 = pickle.load(input)
    print(company1.name)  # -> banana
    print(company1.value)  # -> 40

    company2 = pickle.load(input)
    print(company2.name) # -> spam
    print(company2.value)  # -> 42

You could also define your own simple utility like the following which opens a file and writes a single object to it:

def save_object(obj, filename):
    with open(filename, 'wb') as output:  # Overwrites any existing file.
        pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)

# sample usage
save_object(company1, 'company1.pkl')

Update

Since this is such a popular answer, I'd like touch on a few slightly advanced usage topics.

cPickle (or _pickle) vs pickle

It's almost always preferable to actually use the cPickle module rather than pickle because the former is written in C and is much faster. There are some subtle differences between them, but in most situations they're equivalent and the C version will provide greatly superior performance. Switching to it couldn't be easier, just change the import statement to this:

import cPickle as pickle

In Python 3, cPickle was renamed _pickle, but doing this is no longer necessary since the pickle module now does it automatically—see What difference between pickle and _pickle in python 3?.

The rundown is you could use something like the following to ensure that your code will always use the C version when it's available in both Python 2 and 3:

try:
    import cPickle as pickle
except ModuleNotFoundError:
    import pickle

Data stream formats (protocols)

pickle can read and write files in several different, Python-specific, formats, called protocols as described in the documentation, "Protocol version 0" is ASCII and therefore "human-readable". Versions > 0 are binary and the highest one available depends on what version of Python is being used. The default also depends on Python version. In Python 2 the default was Protocol version 0, but in Python 3.8.1, it's Protocol version 4. In Python 3.x the module had a pickle.DEFAULT_PROTOCOL added to it, but that doesn't exist in Python 2.

Fortunately there's shorthand for writing pickle.HIGHEST_PROTOCOL in every call (assuming that's what you want, and you usually do), just use the literal number -1 — similar to referencing the last element of a sequence via a negative index. So, instead of writing:

pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)

You can just write:

pickle.dump(obj, output, -1)

Either way, you'd only have specify the protocol once if you created a Pickler object for use in multiple pickle operations:

pickler = pickle.Pickler(output, -1)
pickler.dump(obj1)
pickler.dump(obj2)
   etc...

Note: If you're in an environment running different versions of Python, then you'll probably want to explicitly use (i.e. hardcode) a specific protocol number that all of them can read (later versions can generally read files produced by earlier ones).

Multiple Objects

While a pickle file can contain any number of pickled objects, as shown in the above samples, when there's an unknown number of them, it's often easier to store them all in some sort of variably-sized container, like a list, tuple, or dict and write them all to the file in a single call:

tech_companies = [
    Company('Apple', 114.18), Company('Google', 908.60), Company('Microsoft', 69.18)
]
save_object(tech_companies, 'tech_companies.pkl')

and restore the list and everything in it later with:

with open('tech_companies.pkl', 'rb') as input:
    tech_companies = pickle.load(input)

The major advantage is you don't need to know how many object instances are saved in order to load them back later (although doing so without that information is possible, it requires some slightly specialized code). See the answers to the related question Saving and loading multiple objects in pickle file? for details on different ways to do this. Personally I like @Lutz Prechelt's answer the best. Here's it adapted to the examples here:

class Company:
    def __init__(self, name, value):
        self.name = name
        self.value = value

def pickled_items(filename):
    """ Unpickle a file of pickled data. """
    with open(filename, "rb") as f:
        while True:
            try:
                yield pickle.load(f)
            except EOFError:
                break

print('Companies in pickle file:')
for company in pickled_items('company_data.pkl'):
    print('  name: {}, value: {}'.format(company.name, company.value))

Save byte array to file

You can use:

File.WriteAllBytes("Foo.txt", arrBytes); // Requires System.IO

If you have an enumerable and not an array, you can use:

File.WriteAllBytes("Foo.txt", arrBytes.ToArray()); // Requires System.Linq

Save bitmap to location

The way I found to send PNG and transparency.

String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
                    "/CustomDir";
File dir = new File(file_path);
if(!dir.exists())
  dir.mkdirs();

String format = new SimpleDateFormat("yyyyMMddHHmmss",
       java.util.Locale.getDefault()).format(new Date());

File file = new File(dir, format + ".png");
FileOutputStream fOut;
try {
        fOut = new FileOutputStream(file);
        yourbitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
        fOut.flush();
        fOut.close();
     } catch (Exception e) {
        e.printStackTrace();
 }

Uri uri = Uri.fromFile(file);     
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "");
intent.putExtra(Intent.EXTRA_STREAM, uri);

startActivity(Intent.createChooser(intent,"Sharing something")));

Android Saving created bitmap to directory on sd card

just change the extension to .bmp.

Do this:

ByteArrayOutputStream bytes = new ByteArrayOutputStream();
_bitmapScaled.compress(Bitmap.CompressFormat.PNG, 40, bytes);

//you can create a new file name "test.BMP" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
                        + File.separator + "test.bmp")

It'll sound that I'm just fooling around, but try it once and it'll get saved in BMP format. Cheers!

Image, saved to sdcard, doesn't appear in Android's Gallery app

You need to give permissions to the Gallery app. Just long press the gallery app icon in the home screen and tap on 'APP INFO' that pops up at the top of the screen. Doing it will show the gallery app settings. Now go in Permissions tab and enable the storage, camera permissions by toggling it. Now go to your native gallery app and you will get the your saved images.

Saving Excel workbook to constant path with filename from two fields

Ok, at that time got it done with the help of a friend and the code looks like this.

Sub Saving()

Dim part1 As String

Dim part2 As String


part1 = Range("C5").Value

part2 = Range("C8").Value


ActiveWorkbook.SaveAs Filename:= _

"C:\-docs\cmat\Desktop\pieteikumi\" & part1 & " " & part2 & ".xlsm", FileFormat:= _
xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False

End Sub

How do I edit this part (FileFormat:= _ xlOpenXMLWorkbookMacroEnabled) for it to save as Excel 97-2013 Workbook, have tried several variations with no success. Thankyou

Seems, that I found the solution, but my idea is flawed. By doing this FileFormat:= _ xlOpenXMLWorkbook, it drops out a popup saying, the you cannot save this workbook as a file without Macro enabled. So, is this impossible?

Download file and automatically save it to folder

Well, your solution almost works. There are a few things to take into account to keep it simple:

  • Cancel the default navigation only for specific URLs you know a download will occur, or the user won't be able to navigate anywhere. This means you musn't change your website download URLs.

  • DownloadFileAsync doesn't know the name reported by the server in the Content-Disposition header so you have to specify one, or compute one from the original URL if that's possible. You cannot just specify the folder and expect the file name to be retrieved automatically.

  • You have to handle download server errors from the DownloadCompleted callback because the web browser control won't do it for you anymore.

Sample piece of code, that will download into the directory specified in textBox1, but with a random file name, and without any additional error handling:

private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e) {
    /* change this to match your URL. For example, if the URL always is something like "getfile.php?file=xxx", try e.Url.ToString().Contains("getfile.php?") */
    if (e.Url.ToString().EndsWith(".zip")) {
        e.Cancel = true;
        string filePath = Path.Combine(textBox1.Text, Path.GetRandomFileName());
        var client = new WebClient();
        client.DownloadFileCompleted += client_DownloadFileCompleted;
        client.DownloadFileAsync(e.Url, filePath);
    }
}

private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) {
    MessageBox.Show("File downloaded");
}

This solution should work but can be broken very easily. Try to consider some web service listing the available files for download and make a custom UI for it. It'll be simpler and you will control the whole process.

How to save a data frame as CSV to a user selected location using tcltk

Take a look at the write.csv or the write.table functions. You just have to supply the file name the user selects to the file parameter, and the dataframe to the x parameter:

write.csv(x=df, file="myFileName")

How To Save Canvas As An Image With canvas.toDataURL()?

Instead of imageElement.src = myImage; you should use window.location = myImage;

And even after that the browser will display the image itself. You can right click and use "Save Link" for downloading the image.

Check this link for more information.

Saving data to a file in C#

One liner:

System.IO.File.WriteAllText(@"D:\file.txt", content);

It creates the file if it doesn't exist and overwrites it if it exists. Make sure you have appropriate privileges to write to the location, otherwise you will get an exception.

https://msdn.microsoft.com/en-us/library/ms143375%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

Write string to text file and ensure it always overwrites the existing content.

How to save a figure in MATLAB from the command line?

imwrite(A,filename) writes image data A to the file specified by filename, inferring the file format from the extension

PHP - get base64 img string decode and save as jpg (resulting empty image )

Here's what finally worked for me. You'll have to convert the code to suit your own needs, but this will do it.

$fname = filter_input(INPUT_POST, "name");
$img = filter_input(INPUT_POST, "image");
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$img = base64_decode($img);

file_put_contents($fname, $img);

print "Image has been saved!";

How to dump raw RTSP stream to file?

With this command I had poor image quality

ffmpeg -i rtsp://192.168.XXX.XXX:554/live.sdp -vcodec copy -acodec copy -f mp4 -y MyVideoFFmpeg.mp4

With this, almost without delay, I got good image quality.

ffmpeg -i rtsp://192.168.XXX.XXX:554/live.sdp -b 900k -vcodec copy -r 60 -y MyVdeoFFmpeg.avi

How to save as a new file and keep working on the original one in Vim?

Use the :w command with a filename:

:w other_filename

Basic http file downloading and saving to disk in python?

A clean way to download a file is:

import urllib

testfile = urllib.URLopener()
testfile.retrieve("http://randomsite.com/file.gz", "file.gz")

This downloads a file from a website and names it file.gz. This is one of my favorite solutions, from Downloading a picture via urllib and python.

This example uses the urllib library, and it will directly retrieve the file form a source.

JavaScript: Create and save file

Tried this in the console, and it works.

var aFileParts = ['<a id="a"><b id="b">hey!</b></a>'];
var oMyBlob = new Blob(aFileParts, {type : 'text/html'}); // the blob
window.open(URL.createObjectURL(oMyBlob));

Storing Python dictionaries

If you want an alternative to pickle or json, you can use klepto.

>>> init = {'y': 2, 'x': 1, 'z': 3}
>>> import klepto
>>> cache = klepto.archives.file_archive('memo', init, serialized=False)
>>> cache        
{'y': 2, 'x': 1, 'z': 3}
>>>
>>> # dump dictionary to the file 'memo.py'
>>> cache.dump() 
>>> 
>>> # import from 'memo.py'
>>> from memo import memo
>>> print memo
{'y': 2, 'x': 1, 'z': 3}

With klepto, if you had used serialized=True, the dictionary would have been written to memo.pkl as a pickled dictionary instead of with clear text.

You can get klepto here: https://github.com/uqfoundation/klepto

dill is probably a better choice for pickling then pickle itself, as dill can serialize almost anything in python. klepto also can use dill.

You can get dill here: https://github.com/uqfoundation/dill

The additional mumbo-jumbo on the first few lines are because klepto can be configured to store dictionaries to a file, to a directory context, or to a SQL database. The API is the same for whatever you choose as the backend archive. It gives you an "archivable" dictionary with which you can use load and dump to interact with the archive.

What is the difference between --save and --save-dev?

A perfect example of this is:

$ npm install typescript --save-dev

In this case, you'd want to have Typescript (a javascript-parseable coding language) available for development, but once the app is deployed, it is no longer necessary, as all of the code has been transpiled to javascript. As such, it would make no sense to include it in the published app. Indeed, it would only take up space and increase download times.

Download a single folder or directory from a GitHub repo

I work with CentOS 7 servers on which I don't have root access, nor git, svn, etc (nor want to!) so made a python script to download any github folder: https://github.com/andrrrl/github-folder-downloader

Usage is simple, just copy the relevant part from a github project, let's say the project is https://github.com/MaxCDN/php-maxcdn/, and you want a folder where some source files are only, then you need to do something like:

$ python gdownload.py "/MaxCDN/php-maxcdn/tree/master/src" /my/target/dir/
(will create target folder if doesn't exist)

It requires lxml library, can be installed with easy_install lxml
If you don't have root access (like me) you can create a .pydistutils.py file into your $HOME dir with these contents: [install] user=1 And easy_install lxml will just work (ref: https://stackoverflow.com/a/33464597/591257).

How to count the occurrence of certain item in an ndarray?

To count the number of occurrences, you can use np.unique(array, return_counts=True):

In [75]: boo = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])

# use bool value `True` or equivalently `1`
In [77]: uniq, cnts = np.unique(boo, return_counts=1)
In [81]: uniq
Out[81]: array([0, 1])   #unique elements in input array are: 0, 1

In [82]: cnts
Out[82]: array([8, 4])   # 0 occurs 8 times, 1 occurs 4 times

Activity transition in Android

zoom in out animation

Intent i = new Intent(getApplicationContext(), LoginActivity.class);
 overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
startActivity(i);
finish();

zoom_enter

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:fromAlpha="0.0" android:toAlpha="1.0"
    android:duration="500" />

zoom_exit

<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:fromAlpha="1.0" android:toAlpha="0.0"
    android:fillAfter="true"
    android:duration="500" />

How to unlock android phone through ADB

If you have to click OK after entering your passcode, this command will unlock your phone:

adb shell input text XXXX && adb shell input keyevent 66

Where

  • XXXX is your passcode.
  • 66 is keycode of button OK.
  • adb shell input text XXXX will enter your passcode.
  • adb shell input keyevent 66 will simulate click the OK button

How do I use the ternary operator ( ? : ) in PHP as a shorthand for "if / else"?

Note that when using nested conditional operators, you may want to use parenthesis to avoid possible issues!

It looks like PHP doesn't work the same way as at least Javascript or C#.

$score = 15;
$age = 5;

// The following will return "Exceptional"
echo 'Your score is: ' . ($score > 10 ? ($age > 10 ? 'Average' : 'Exceptional') : ($age > 10 ? 'Horrible' : 'Average'));

// The following will return "Horrible"
echo 'Your score is: ' . ($score > 10 ? $age > 10 ? 'Average' : 'Exceptional' : $age > 10 ? 'Horrible' : 'Average');

The same code in Javascript and C# return "Exceptional" in both cases.

In the 2nd case, what PHP does is (or at least that's what I understand):

  1. is $score > 10? yes
  2. is $age > 10? no, so the current $age > 10 ? 'Average' : 'Exceptional' returns 'Exceptional'
  3. then, instead of just stopping the whole statement and returning 'Exceptional', it continues evaluating the next statement
  4. the next statement becomes 'Exceptional' ? 'Horrible' : 'Average' which returns 'Horrible', as 'Exceptional' is truthy

From the documentation: http://php.net/manual/en/language.operators.comparison.php

It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious.

How to disable scientific notation?

You can effectively remove scientific notation in printing with this code:

options(scipen=999)

How do I pass named parameters with Invoke-Command?

My solution to this was to write the script block dynamically with [scriptblock]:Create:

# Or build a complex local script with MARKERS here, and do substitutions
# I was sending install scripts to the remote along with MSI packages
# ...for things like Backup and AV protection etc.

$p1 = "good stuff"; $p2 = "better stuff"; $p3 = "best stuff"; $etc = "!"
$script = [scriptblock]::Create("MyScriptOnRemoteServer.ps1 $p1 $p2 $etc")
#strings get interpolated/expanded while a direct scriptblock does not

# the $parms are now expanded in the script block itself
# ...so just call it:
$result = invoke-command $computer -script $script

Passing arguments was very frustrating, trying various methods, e.g.,
-arguments, $using:p1, etc. and this just worked as desired with no problems.

Since I control the contents and variable expansion of the string which creates the [scriptblock] (or script file) this way, there is no real issue with the "invoke-command" incantation.

(It shouldn't be that hard. :) )

How to extract a floating number from a string

I think that you'll find interesting stuff in the following answer of mine that I did for a previous similar question:

https://stackoverflow.com/q/5929469/551449

In this answer, I proposed a pattern that allows a regex to catch any kind of number and since I have nothing else to add to it, I think it is fairly complete

How do you format a Date/Time in TypeScript?

Update (2020)

As pointed by @jonhF in the comments, MomentJs recommends to not use MomentJs anymore. Check https://momentjs.com/docs/

Instead, I'm keeping this list with my personal TOP 3 js date libraries for future reference.

Old comment

I suggest you to use MomentJS

With moment you can have lot of outputs, and this one 09/11/2015 16:16 is one of then.

How do I access call log for android?

To get Only Incoming Call history , the beneath code will help u:)

private void getCallDetailsAgil() {

    StringBuffer sb = new StringBuffer();
    Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null, null, null, null);
    int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
    int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
    int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
    int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
    sb.append("Call Details :");
    while (managedCursor.moveToNext()) {
        String phNumber = managedCursor.getString(number);
        String callType = managedCursor.getString(type);
        String callDate = managedCursor.getString(date);
        Date callDayTime = new Date(Long.valueOf(callDate));
        String callDuration = managedCursor.getString(duration);
        String dir = null;
        int dircode = Integer.parseInt(callType);


        switch (dircode) {
            case CallLog.Calls.OUTGOING_TYPE:
                dir = "OUTGOING";
                break;

            case CallLog.Calls.INCOMING_TYPE:
                dir = "INCOMING";
                sb.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- " + dir + " \nCall Date:--- " + callDayTime + " \nCall duration in sec :--- " + callDuration);
                sb.append("\n----------------------------------");
                miss_cal.setText(sb);
                break;

            case CallLog.Calls.MISSED_TYPE:
                dir = "MISSED";
                break;
        }
    }

    managedCursor.close();
} 

How to set a fixed width column with CSS flexbox

In case anyone wants to have a responsive flexbox with percentages (%) it is much easier for media queries.

flex-basis: 25%;

This will be a lot smoother when testing.

// VARIABLES
$screen-xs:                                         480px;
$screen-sm:                                         768px;
$screen-md:                                         992px;
$screen-lg:                                         1200px;
$screen-xl:                                         1400px;
$screen-xxl:                                        1600px;

// QUERIES
@media screen (max-width: $screen-lg) {
    flex-basis: 25%;
}

@media screen (max-width: $screen-md) {
    flex-basis: 33.33%;
}

How to run a python script from IDLE interactive shell?

In IDLE, the following works :-

_x000D_
_x000D_
import helloworld
_x000D_
_x000D_
_x000D_

I don't know much about why it works, but it does..

How can I auto increment the C# assembly version via our CI platform (Hudson)?

I am assuming one might also do this with a text template where you create the assembly attributes in question on the fly from the environment like AssemblyVersion.tt does below.

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ output extension=".cs" #>
<#
var build = Environment.GetEnvironmentVariable("BUILD_NUMBER");
build = build == null ? "0" : int.Parse(build).ToString();
var revision = Environment.GetEnvironmentVariable("SVN_REVISION");
revision = revision == null ? "0" : int.Parse(revision).ToString();    
#>
using System.Reflection;
[assembly: AssemblyVersion("1.0.<#=build#>.<#=revision#>")]
[assembly: AssemblyFileVersion("1.0.<#=build#>.<#=revision#>")]

WebView and HTML5 <video>

I know this thread is several months old, but I found a solution for playing the video inside the WebView without doing it fullscreen (but still in the media player...). So far, I didn't find any hint on this in the internet so maybe this is also interesting for others. I'm still struggling on some issues (i.e. placing the media player in the right section of the screen, don't know why I'm doing it wrong but it's a relatively small issue I think...).

In the Custom ChromeClient specify LayoutParams:

// 768x512 is the size of my video
FrameLayout.LayoutParams LayoutParameters = 
                                     new FrameLayout.LayoutParams (768, 512); 

My onShowCustomView method looks like this:

public void onShowCustomView(final View view, final CustomViewCallback callback) {
     // super.onShowCustomView(view, callback);
     if (view instanceof FrameLayout) {
         this.mCustomViewContainer = (FrameLayout) view;
         this.mCustomViewCallback = callback;
         this.mContentView = (WebView) this.kameha.findViewById(R.id.webview);
         if (this.mCustomViewContainer.getFocusedChild() instanceof VideoView) {
             this.mCustomVideoView = (VideoView) 
                                     this.mCustomViewContainer.getFocusedChild();
             this.mCustomViewContainer.setVisibility(View.VISIBLE);
             final int viewWidth = this.mContentView.getWidth();
             final int viewLeft = (viewWidth - 1024) / 2;
             // get the x-position for the video (I'm porting an iPad-Webapp to Xoom, 
             // so I can use those numbers... you have to find your own of course...
             this.LayoutParameters.leftMargin = viewLeft + 256; 
             this.LayoutParameters.topMargin = 128;
             // just add this view so the webview underneath will still be visible, 
             // but apply the LayoutParameters specified above
             this.kameha.addContentView(this.mCustomViewContainer, 
                                             this.LayoutParameters); 
             this.mCustomVideoView.setOnCompletionListener(this);
             this.mCustomVideoView.setOnErrorListener(this);
             // handle clicks on the screen (turning off the video) so you can still
             // navigate in your WebView without having the video lying over it
             this.mCustomVideoView.setOnFocusChangeListener(this); 
             this.mCustomVideoView.start();
         }
     }
 }

So, I hope I could help... I too had to play around with video-Encoding and saw different kinds of using the WebView with html5 video - in the end my working code was a wild mix of different code-parts I found in the internet and some things I had to figure out by myself. It really was a pain in the a*.

Change value of input and submit form in JavaScript

Here is simple code. You must set an id for your input. Here call it 'myInput':

var myform = document.getElementById('myform');
myform.onsubmit = function(){
    document.getElementById('myInput').value = '1';
    myform.submit();
};

Facebook Post Link Image

I know this question is old, but I recently dealt with the exact same problem and went round and round on it for a couple weeks. Multiple searches on Google turned up a lot of useful information, but most of it was focused on Open Graph tags, which I wasn't interested in using. Turns out my site had multiple issues, but here are some of the basics.

  1. As EightyEight said, make sure your HTML is valid - and the same goes for your javascript and server-side code (PHP, ASP, etc.). I had a small PHP error in a piece of code that was executing as a separate call to the server from the main page. Due to a number of bizarre coincidences, that code was generating a 500 error - but ONLY for IE6 and strict parsing engines like the W3C validator and the Facebook page crawler. The problem didn't appear in modern browsers (Chrome 4, FF 3.5, IE 8, etc) so I didn't see it right away, but older/stricter clients were showing the 500 every time and that was the main reason FB wasn't crawling our page (when everything else seemed to be correct).

  2. Regarding Randy's response, he's correct that Facebook will keep an old cached copy of your page long after you've updated it. FB claims it's only held for 24 hours, but I experienced much longer times than that. FORTUNATELY, FB has released their "URL Linter" tool that will show you a preview of how your page will appear when being shared on FB, and it will force FB to instantly update its cache of your page. This was a lifesaving tool. You can find it at http://developers.facebook.com/tools/lint/

  3. Regarding the URL Linter tool, be aware that each variation of a URL is cached separately on Facebook, so "www.example.com" is not the same as "example.com". Also, unique capitalization is stored as well, so "ExampleOne.com" is not the same as "exampleone.com". (This led to a lot of confusion between my client and myself when it appeared to me that the cache had been updated just fine and the client claimed they weren't seeing the updates. Turns out I was looking at exampleone.com and had used Linter to update the cache, but they were looking at exampleOne.com which I hadn't submitted to Linter. As a result, I ended up submitting quite a few variations of the URL to Linter just to cover the bases.)

  4. WyrdNEXUS's advice to use the image_src link tag is spot-on. This allows you to be sure that FB is scraping the best possible image for your page. There are some varying guidelines out there about what specs the image file should have, but I've successfully used a 128px square image and have seen a 130x97 image make it through as well. Here is Facebook's official documentation from http://developers.facebook.com/docs/reference/plugins/like/:

    Images must be at least 50 pixels by 50 pixels. Square images work best, but you are allowed to use images up to three times as wide as they are tall.

    Obviously, FB will resize a large image for you, but you'll almost always get better results if you resize it yourself beforehand.

  5. Regarding Mike Cooper's link to the eHow article, avoid using step #1 in that article. It was valid advice when the article was written and when Mike posted the link, but it's now better to use the URL Linter tool for previewing how your page will appear when being shared. By using Linter, you won't cause FB to cache a (potentially) bad copy of the page before you get a chance to tweak it.

Calculating the sum of two variables in a batch script

According to this helpful list of operators [an operator can be thought of as a mathematical expression] found here, you can tell the batch compiler that you are manipulating variables instead of fixed numbers by using the += operator instead of the + operator.

Hope I Helped!

Where is Developer Command Prompt for VS2013?

I used a modified version of this answer - based on my experiences adding it to VS 2010:

  1. Select Tools >> External Tools in Visual Studio
  2. Click Add
  3. Title: I use Visual Studio Command &Prompt
    • &P Makes P a alt-shortcut key (when menu active)
    • I originally used C, but that conflicts with the existing shortcut for Customize
  4. Command: C:\Windows\System32\cmd.exe
  5. Arguments: \k "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\vsvars32.bat
    • /k keeps a secondary session active so the window doesn’t close on the .bat file
  6. Initial Directory: I use $(ProjectDir) (from the dropdown)
  7. Click OK.

Now you have command prompt access under the Tools Menu.

See also: Add command prompt to Visual C# Express 2010

Should I use != or <> for not equal in T-SQL?

Although they function the same way, != means exactly "not equal to", while <> means greater than and less than the value stored.

Consider >= or <=, and this will make sense when factoring in your indexes to queries... <> will run faster in some cases (with the right index), but in some other cases (index free) they will run just the same.

This also depends on how your databases system reads the values != and <>. The database provider may just shortcut it and make them function the same, so there isn't any benefit either way.PostgreSQL and SQL Server do not shortcut this; it is read as it appears above.

Read remote file with node.js (http.get)

function(url,callback){
    request(url).on('data',(data) => {
        try{
            var json = JSON.parse(data);    
        }
        catch(error){
            callback("");
        }
        callback(json);
    })
}

You can also use this. This is to async flow. The error comes when the response is not a JSON. Also in 404 status code .

Android Support Design TabLayout: Gravity Center and Mode Scrollable

 <android.support.design.widget.TabLayout
                    android:id="@+id/tabList"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    app:tabMode="scrollable"/>

Multidimensional arrays in Swift

var array: Int[][] = [[1,2,3],[4,5,6],[7,8,9]]

for first in array {
    for second in first {
        println("value \(second)")
    }
}

To achieve what you're looking for you need to initialize the array to the correct template and then loop to add the row and column arrays:

var NumColumns = 27
var NumRows = 52
var array = Array<Array<Int>>()
var value = 1

for column in 0..NumColumns {
    var columnArray = Array<Int>()
    for row in 0..NumRows {
        columnArray.append(value++)
    }
    array.append(columnArray)
}

println("array \(array)")

Mocking static methods with Mockito

There is an easy solution by using java FunctionalInterface and then add that interface as dependency for the class you are trying to unit test.

FloatingActionButton example with Support Library

So in your build.gradle file, add this:

compile 'com.android.support:design:27.1.1'

AndroidX Note: Google is introducing new AndroidX extension libraries to replace the older Support Libraries. To use AndroidX, first make sure you've updated your gradle.properties file, edited build.gradle to set compileSdkVersion to 28 (or higher), and use the following line instead of the previous compile one.

implementation 'com.google.android.material:material:1.0.0'

Next, in your themes.xml or styles.xml or whatever, make sure you set this- it's your app's accent color-- and the color of your FAB unless you override it (see below):

        <item name="colorAccent">@color/floating_action_button_color</item>

In the layout's XML:

<RelativeLayout
 ...
 xmlns:app="http://schemas.android.com/apk/res-auto">

       <android.support.design.widget.FloatingActionButton
            android:id="@+id/myFAB"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_plus_sign"
            app:elevation="4dp"
            ... />

</RelativeLayout>

Or if you are using the AndroidX material library above, you'd instead use this:

<RelativeLayout
 ...
 xmlns:app="http://schemas.android.com/apk/res-auto">

       <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/myFAB"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:srcCompat="@drawable/ic_plus_sign"
            app:elevation="4dp"
            ... />

</RelativeLayout>

You can see more options in the docs (material docs here) (setRippleColor, etc.), but one of note is:

    app:fabSize="mini"

Another interesting one-- to change the background color of just one FAB, add:

    app:backgroundTint="#FF0000"

(for example to change it to red) to the XML above.

Anyway, in code, after the Activity/Fragment's view is inflated....

    FloatingActionButton myFab = (FloatingActionButton)  myView.findViewById(R.id.myFAB);
    myFab.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            doMyThing();
        }
    });

Observations:

  • If you have one of those buttons that's on a "seam" splitting two views (using a RelativeLayout, for example) with, say, a negative bottom layout margin to overlap the border, you'll notice an issue: the FAB's size is actually very different on lollipop vs. pre-lollipop. You can actually see this in AS's visual layout editor when you flip between APIs-- it suddenly "puffs out" when you switch to pre-lollipop. The reason for the extra size seems to be that the shadow expands the size of the view in every direction. So you have to account for this when you're adjusting the FAB's margins if it's close to other stuff.
  • Here's a way to remove or change the padding if there's too much:

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        RelativeLayout.LayoutParams p = (RelativeLayout.LayoutParams) myFab.getLayoutParams();
        p.setMargins(0, 0, 0, 0); // get rid of margins since shadow area is now the margin
        myFab.setLayoutParams(p);
    }
    
  • Also, I was going to programmatically place the FAB on the "seam" between two areas in a RelativeLayout by grabbing the FAB's height, dividing by two, and using that as the margin offset. But myFab.getHeight() returned zero, even after the view was inflated, it seemed. Instead I used a ViewTreeObserver to get the height only after it's laid out and then set the position. See this tip here. It looked like this:

        ViewTreeObserver viewTreeObserver = closeButton.getViewTreeObserver();
        if (viewTreeObserver.isAlive()) {
            viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                        closeButton.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    } else {
                        closeButton.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    }
                    // not sure the above is equivalent, but that's beside the point for this example...
                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) closeButton.getLayoutParams();
                    params.setMargins(0, 0, 16, -closeButton.getHeight() / 2); // (int left, int top, int right, int bottom)
                    closeButton.setLayoutParams(params);
                }
            });
        }
    

    Not sure if this is the right way to do it, but it seems to work.

  • It seems you can make the shadow-space of the button smaller by decreasing the elevation.
  • If you want the FAB on a "seam" you can use layout_anchor and layout_anchorGravity here is an example:

    <android.support.design.widget.FloatingActionButton
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        app:layout_anchor="@id/appbar"
        app:layout_anchorGravity="bottom|right|end"
        android:src="@drawable/ic_discuss"
        android:layout_margin="@dimen/fab_margin"
        android:clickable="true"/>
    

Remember that you can automatically have the button jump out of the way when a Snackbar comes up by wrapping it in a CoordinatorLayout.

More:

How to abort an interactive rebase if --abort doesn't work?

Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.

git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67

Then, abort the rebase again.

Generate table relationship diagram from existing schema (SQL Server)

SchemaCrawler for SQL Server can generate database diagrams, with the help of GraphViz. Foreign key relationships are displayed (and can even be inferred, using naming conventions), and tables and columns can be excluded using regular expressions.

why are there two different kinds of for loops in java?

The first is the original for loop. You initialize a variable, set a terminating condition, and provide a state incrementing/decrementing counter (There are exceptions, but this is the classic)

For that,

for (int i=0;i<myString.length;i++) { 
  System.out.println(myString[i]); 
}

is correct.

For Java 5 an alternative was proposed. Any thing that implements iterable can be supported. This is particularly nice in Collections. For example you can iterate the list like this

List<String> list = ....load up with stuff

for (String string : list) {
  System.out.println(string);
}

instead of

for (int i=0; i<list.size();i++) {
  System.out.println(list.get(i));
}

So it's just an alternative notation really. Any item that implements Iterable (i.e. can return an iterator) can be written that way.

What's happening behind the scenes is somethig like this: (more efficient, but I'm writing it explicitly)

Iterator<String> it = list.iterator();
while (it.hasNext()) {
  String string=it.next();
  System.out.println(string);
}

In the end it's just syntactic sugar, but rather convenient.

Laravel 5 - artisan seed [ReflectionException] Class SongsTableSeeder does not exist

Do not forgot that the composer dump-autoload works in relation with the autoload / classmap section of composer.json. Take care about that if you need to change seeders directory or use multiple directories to store seeders.

"autoload": {
    "classmap": [
      "database/seeds",
      "database/factories"
    ],
},

How can I make Flexbox children 100% height of their parent?

An idea would be that display:flex; with flex-direction: row; is filling the container div with .flex-1 and .flex-2, but that does not mean that .flex-2 has a default height:100%;, even if it is extended to full height.

And to have a child element (.flex-2-child) with height:100%;, you'll need to set the parent to height:100%; or use display:flex; with flex-direction: row; on the .flex-2 div too.

From what I know, display:flex will not extend all your child elements height to 100%.

A small demo, removed the height from .flex-2-child and used display:flex; on .flex-2: http://jsfiddle.net/2ZDuE/3/

How to display an error message in an ASP.NET Web Application

All you need is a control that you can set the text of, and an UpdatePanel if the exception occurs during a postback.

If occurs during a postback: markup:

<ajax:UpdatePanel id="ErrorUpdatePanel" runat="server" UpdateMode="Coditional">
<ContentTemplate>
<asp:TextBox id="ErrorTextBox" runat="server" />
</ContentTemplate>
</ajax:UpdatePanel>

code:

try
{
do something
}

catch(YourException ex)
{
this.ErrorTextBox.Text = ex.Message;
this.ErrorUpdatePanel.Update();
}

Oracle query to fetch column names

On Several occasions, we would need comma separated list of all the columns from a table in a schema. In such cases we can use this generic function which fetches the comma separated list as a string.

CREATE OR REPLACE FUNCTION cols(
    p_schema_name IN VARCHAR2,
    p_table_name  IN VARCHAR2)
  RETURN VARCHAR2
IS
  v_string VARCHAR2(4000);
BEGIN
  SELECT LISTAGG(COLUMN_NAME , ',' ) WITHIN GROUP (
  ORDER BY ROWNUM )
  INTO v_string
  FROM ALL_TAB_COLUMNS
  WHERE OWNER    = p_schema_name
  AND table_name = p_table_name;
  RETURN v_string;
END;
/

So, simply calling the function from the query yields a row with all the columns.

select cols('HR','EMPLOYEES') FROM DUAL;

EMPLOYEE_ID,FIRST_NAME,LAST_NAME,EMAIL,PHONE_NUMBER,HIRE_DATE,JOB_ID,SALARY,COMMISSION_PCT,MANAGER_ID,DEPARTMENT_ID

Note: LISTAGG will fail if the combined length of all columns exceed 4000 characters which is rare. For most cases , this will work.

How do you create a static class in C++?

Unlike other managed programming language, "static class" has NO meaning in C++. You can make use of static member function.

git push to specific branch

The answers in question you linked-to are all about configuring git so that you can enter very short git push commands and have them do whatever you want. Which is great, if you know what you want and how to spell that in Git-Ese, but you're new to git! :-)

In your case, Petr Mensik's answer is the (well, "a") right one. Here's why:

The command git push remote roots around in your .git/config file to find the named "remote" (e.g., origin). The config file lists:

  • where (URL-wise) that remote "lives" (e.g., ssh://hostname/path)
  • where pushes go, if different
  • what gets pushed, if you didn't say what branch(es) to push
  • what gets fetched when you run git fetch remote

When you first cloned the repo—whenever that was—git set up default values for some of these. The URL is whatever you cloned from and the rest, if set or unset, are all "reasonable" defaults ... or, hmm, are they?

The issue with these is that people have changed their minds, over time, as to what is "reasonable". So now (depending on your version of git and whether you've configured things in detail), git may print a lot of warnings about defaults changing in the future. Adding the name of the "branch to push"—amd_qlp_tester—(1) shuts it up, and (2) pushes just that one branch.

If you want to push more conveniently, you could do that with:

git push origin

or even:

git push

but whether that does what you want, depends on whether you agree with "early git authors" that the original defaults are reasonable, or "later git authors" that the original defaults aren't reasonable. So, when you want to do all the configuration stuff (eventually), see the question (and answers) you linked-to.

As for the name origin/amd_qlp_tester in the first place: that's actually a local entity (a name kept inside your repo), even though it's called a "remote branch". It's git's best guess at "where amd_qlp_tester is over there". Git updates it when it can.

Datetime format Issue: String was not recognized as a valid DateTime

You can use DateTime.ParseExact() method.

Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

DateTime date = DateTime.ParseExact("04/30/2013 23:00", 
                                    "MM/dd/yyyy HH:mm", 
                                    CultureInfo.InvariantCulture);

Here is a DEMO.

hh is for 12-hour clock from 01 to 12, HH is for 24-hour clock from 00 to 23.

For more information, check Custom Date and Time Format Strings

How do I create a datetime in Python from milliseconds?

Converting millis to datetime (UTC):

import datetime
time_in_millis = 1596542285000
dt = datetime.datetime.fromtimestamp(time_in_millis / 1000.0, tz=datetime.timezone.utc)

Converting datetime to string following the RFC3339 standard (used by Open API specification):

from rfc3339 import rfc3339
converted_to_str = rfc3339(dt, utc=True, use_system_timezone=False)
# 2020-08-04T11:58:05Z

How to sort by two fields in Java?

For a class Book like this:

package books;

public class Book {

    private Integer id;
    private Integer number;
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getNumber() {
        return number;
    }

    public void setNumber(Integer number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "book{" +
                "id=" + id +
                ", number=" + number +
                ", name='" + name + '\'' + '\n' +
                '}';
    }
}

sorting main class with mock objects

package books;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


public class Main {

    public static void main(String[] args) {
        System.out.println("Hello World!");

        Book b = new Book();

        Book c = new Book();

        Book d = new Book();

        Book e = new Book();

        Book f = new Book();

        Book g = new Book();
        Book g1 = new Book();
        Book g2 = new Book();
        Book g3 = new Book();
        Book g4 = new Book();




        b.setId(1);
        b.setNumber(12);
        b.setName("gk");

        c.setId(2);
        c.setNumber(12);
        c.setName("gk");

        d.setId(2);
        d.setNumber(13);
        d.setName("maths");

        e.setId(3);
        e.setNumber(3);
        e.setName("geometry");

        f.setId(3);
        f.setNumber(34);
        b.setName("gk");

        g.setId(3);
        g.setNumber(11);
        g.setName("gk");

        g1.setId(3);
        g1.setNumber(88);
        g1.setName("gk");
        g2.setId(3);
        g2.setNumber(91);
        g2.setName("gk");
        g3.setId(3);
        g3.setNumber(101);
        g3.setName("gk");
        g4.setId(3);
        g4.setNumber(4);
        g4.setName("gk");





        List<Book> allBooks = new ArrayList<Book>();

        allBooks.add(b);
        allBooks.add(c);
        allBooks.add(d);
        allBooks.add(e);
        allBooks.add(f);
        allBooks.add(g);
        allBooks.add(g1);
        allBooks.add(g2);
        allBooks.add(g3);
        allBooks.add(g4);



        System.out.println(allBooks.size());


        Collections.sort(allBooks, new Comparator<Book>() {

            @Override
            public int compare(Book t, Book t1) {
                int a =  t.getId()- t1.getId();

                if(a == 0){
                    int a1 = t.getNumber() - t1.getNumber();
                    return a1;
                }
                else
                    return a;
            }
        });
        System.out.println(allBooks);

    }


   }

how to get the host url using javascript from the current page

// will return the host name and port
var host = window.location.host; 

or possibly

var host = window.location.protocol + "//" + window.location.host;

or if you like concatenation

var protocol = location.protocol;
var slashes = protocol.concat("//");
var host = slashes.concat(window.location.host);

// or as you probably should do
var host = location.protocol.concat("//").concat(window.location.host);

// the above is the same as origin, e.g. "https://stackoverflow.com"
var host = window.location.origin;

If you have or expect custom ports use window.location.host instead of window.location.hostname

How to create a .gitignore file

In mac - you can just create a new text file. add content using https://www.gitignore.io/

save the file with file format as - Rich Text document with attachments. change file name to .gitingore and select use"." when a pop up comes as in the attached image.

NOTE : since it is a hidden file so you wont be able to see it in the directory. but it will be created.

see image

How can I beautify JSON programmatically?

Here's something that might be interesting for developers hacking (minified or obfuscated) JavaScript more frequently.

You can build your own CLI JavaScript beautifier in under 5 mins and have it handy on the command-line. You'll need Mozilla Rhino, JavaScript file of some of the JS beautifiers available online, small hack and a script file to wrap it all up.

I wrote an article explaining the procedure: Command-line JavaScript beautifier implemented in JavaScript.

How to check if a column exists before adding it to an existing table in PL/SQL?

Or, you can ignore the error:

declare
    column_exists exception;
    pragma exception_init (column_exists , -01430);
begin
    execute immediate 'ALTER TABLE db.tablename ADD columnname NVARCHAR2(30)';
    exception when column_exists then null;
end;
/

How to discover number of *logical* cores on Mac OS X?

You can do this using the sysctl utility:

sysctl -n hw.ncpu

Shortcut for creating single item list in C#

You can also do

new List<string>() { "string here" };

jQuery UI DatePicker - Change Date Format

I think the correct way to do this would be something like this:

var picker = $('.date-picker');
var date = $.datepicker.formatDate(
    picker.datepicker('option', 'dateFormat'),
    picker.datepicker('getDate'));

This way you make sure the format string is defined only once and you use the same formatter to translate the format string into the formatted date.

Can you get the number of lines of code from a GitHub repository?

If the question is "can you quickly get NUMBER OF LINES of a github repo", the answer is no as stated by the other answers.

However, if the question is "can you quickly check the SCALE of a project", I usually gauge a project by looking at its size. Of course the size will include deltas from all active commits, but it is a good metric as the order of magnitude is quite close.

E.g.

How big is the "docker" project?

In your browser, enter api.github.com/repos/ORG_NAME/PROJECT_NAME i.e. api.github.com/repos/docker/docker

In the response hash, you can find the size attribute:

{
    ...
    size: 161432,
    ...
}

This should give you an idea of the relative scale of the project. The number seems to be in KB, but when I checked it on my computer it's actually smaller, even though the order of magnitude is consistent. (161432KB = 161MB, du -s -h docker = 65MB)

Can I have an IF block in DOS batch file?

Maybe a bit late, but hope it hellps:

@echo off 

if %ERRORLEVEL% == 0 (
msg * 1st line WORKS FINE rem You can relpace msg * with any othe operation...
goto Continue1
)
:Continue1
If exist "C:\Python31" (
msg * 2nd line WORKS FINE rem You can relpace msg * with any othe operation...
    goto Continue2
)
:Continue2
If exist "C:\Python31\Lib\site-packages\PyQt4" (  
msg * 3th line WORKS FINE rem You can relpace msg * with any othe operation...
    goto Continue3
)
:Continue3
msg * 4th line WORKS FINE rem You can relpace msg * with any othe operation...
    goto Continue4
)
:Continue4
msg * "Tutto a posto" rem You can relpace msg * with any othe operation...
pause

iterating through json object javascript

My problem was actually a problem of bad planning with the JSON object rather than an actual logic issue. What I ended up doing was organize the object as follows, per a suggestion from user2736012.

{
"dialog":
{
    "trunks":[
    {
        "trunk_id" : "1",
        "message": "This is just a JSON Test"
    },
    {
        "trunk_id" : "2",
        "message": "This is a test of a bit longer text. Hopefully this will at the very least create 3 lines and trigger us to go on to another box. So we can test multi-box functionality, too."
    }
    ]
}
}

At that point, I was able to do a fairly simple for loop based on the total number of objects.

var totalMessages = Object.keys(messages.dialog.trunks).length;

    for ( var i = 0; i < totalMessages; i++)
    {
        console.log("ID: " + messages.dialog.trunks[i].trunk_id + " Message " + messages.dialog.trunks[i].message);
    }

My method for getting totalMessages is not supported in all browsers, though. For my project, it actually doesn't matter, but beware of that if you choose to use something similar to this.

How to change FontSize By JavaScript?

span.style.fontSize = "25px";

use this

Limit Get-ChildItem recursion depth

@scanlegentil I like this.
A little improvement would be:

$Depth = 2
$Path = "."

$Levels = "\*" * $Depth
$Folder = Get-Item $Path
$FolderFullName = $Folder.FullName
Resolve-Path $FolderFullName$Levels | Get-Item | ? {$_.PsIsContainer} | Write-Host

As mentioned, this would only scan the specified depth, so this modification is an improvement:

$StartLevel = 1 # 0 = include base folder, 1 = sub-folders only, 2 = start at 2nd level
$Depth = 2      # How many levels deep to scan
$Path = "."     # starting path

For ($i=$StartLevel; $i -le $Depth; $i++) {
    $Levels = "\*" * $i
    (Resolve-Path $Path$Levels).ProviderPath | Get-Item | Where PsIsContainer |
    Select FullName
}

TimeStamp on file name using PowerShell

You can insert arbitrary PowerShell script code in a double-quoted string by using a subexpression, for example, $() like so:

"C:\temp\mybackup $(get-date -f yyyy-MM-dd).zip"

And if you are getting the path from somewhere else - already as a string:

$dirName  = [io.path]::GetDirectoryName($path)
$filename = [io.path]::GetFileNameWithoutExtension($path)
$ext      = [io.path]::GetExtension($path)
$newPath  = "$dirName\$filename $(get-date -f yyyy-MM-dd)$ext"

And if the path happens to be coming from the output of Get-ChildItem:

Get-ChildItem *.zip | Foreach {
  "$($_.DirectoryName)\$($_.BaseName) $(get-date -f yyyy-MM-dd)$($_.extension)"}

'do...while' vs. 'while'

I used them a fair bit when I was in school, but not so much since.

In theory they are useful when you want the loop body to execute once before the exit condition check. The problem is that for the few instances where I don't want the check first, typically I want the exit check in the middle of the loop body rather than at the very end. In that case, I prefer to use the well-known for (;;) with an if (condition) exit; somewhere in the body.

In fact, if I'm a bit shaky on the loop exit condition, sometimes I find it useful to start writing the loop as a for (;;) {} with an exit statement where needed, and then when I'm done I can see if it can be "cleaned up" by moving initilizations, exit conditions, and/or increment code inside the for's parentheses.

Mailbox unavailable. The server response was: 5.7.1 Unable to relay Error

WE had this issue. everything was setup fine in terms of permissions and security.

after MUCH needling around in the haystack. the issue was some sort of heuristics. in the email body , anytime a certain email address was listed, we would get the above error message from our exchange server.

it took 2 days of crazy testing and hair pulling to find this.

so if you have checked everything out, try changing the email body to only the word 'test'. If after that, your email goes out fine, you are having some sort of spam/heuristic filter issue like we were

datetimepicker is not a function jquery

Keep in mind, the jQuery UI's datepicker is not initialized with datetimepicker(), there appears to be a plugin/addon here: http://trentrichardson.com/examples/timepicker/.

However, with just jquery-ui it's actually initialized as $("#example").datepicker(). See jQuery's demo site here: http://jqueryui.com/demos/datepicker/

   $(document).ready(function(){
        $("#example1").datepicker();
    });

To use the datetimepicker at the link referenced above, you will want to be certain that your scripts path is correct for the plugin.

angular ng-repeat in reverse

Sorry for bringing this up after a year, but there is an new, easier solution, which works for Angular v1.3.0-rc.5 and later.

It is mentioned in the docs: "If no property is provided, (e.g. '+') then the array element itself is used to compare where sorting". So, the solution will be:

ng-repeat="friend in friends | orderBy:'-'" or

ng-repeat="friend in friends | orderBy:'+':true"

This solution seems to be better because it does not modify an array and does not require additional computational resources (at least in our code). I've read all existing answers and still prefer this one to them.

How to get first and last day of week in Oracle?

@cem's answer, has a flaw, if sysdate is a sunday, it returns the monday following. Inspired by his answer, here is one tested against few weeks:

select 
    (sysdate - to_char(sysdate-1, 'd') + 1) first_day_of_week --A monday here
from dual

AVD Manager - No system image installed for this target

Open your Android SDK Manager and ensure that you download/install a system image for the API level you are developing with.

Basic CSS - how to overlay a DIV with semi-transparent DIV on top

For a div-Element you could just set the opacity via a class to enable or disable the effect.

.mute-all {
   opacity: 0.4;
}

How to remove all white spaces from a given text file

Try this:

tr -d " \t" <filename

See the manpage for tr(1) for more details.

How do you run a .bat file from PHP?

on my windows machine 8 machine running IIS 8 I can run the batch file just by putting the bats name and forgettig the path to it. Or by putting the bat in c:\windows\system32 don't ask me how it works but it does. LOL

$test=shell_exec("C:\windows\system32\cmd.exe /c $streamnumX.bat");

How can I select an element by name with jQuery?

Frameworks usually use bracket names in forms, like:

<input name=user[first_name] />

They can be accessed by:

// in JS:
this.querySelectorAll('[name="user[first_name]"]')

// in jQuery:
$('[name="user[first_name]"]')

// or by mask with escaped quotes:
this.querySelectorAll("[name*=\"[first_name]\"]")

How to get < span > value?

No jQuery tag, so I'm assuming pure JavaScript

var spanText = document.getElementById('targetSpanId').innerText;

Is what you need

But in your case:

var spans = document.getElementById('test').getElementsByTagName('span');//returns node-list of spans
for (var i=0;i<spans.length;i++)
{
    console.log(spans[i].innerText);//logs 1 for i === 0, 2 for i === 1 etc
}

Here's a fiddle

python - find index position in list based of partial string

Without enumerate():

>>> mylist = ["aa123", "bb2322", "aa354", "cc332", "ab334", "333aa"]
>>> l = [mylist.index(i) for i in mylist if 'aa' in i]
>>> l
[0, 2, 5]

Get pandas.read_csv to read empty values as empty string instead of nan

We have a simple argument in Pandas read_csv for this:

Use:

df = pd.read_csv('test.csv', na_filter= False)

Pandas documentation clearly explains how the above argument works.

Link

C - casting int to char and append char to char

You can use itoa function to convert the integer to a string.

You can use strcat function to append characters in a string at the end of another string.

If you want to convert a integer to a character, just do the following -

int a = 65;
char c = (char) a;

Note that since characters are smaller in size than integer, this casting may cause a loss of data. It's better to declare the character variable as unsigned in this case (though you may still lose data).

To do a light reading about type conversion, go here.

If you are still having trouble, comment on this answer.

Edit

Go here for a more suitable example of joining characters.

Also some more useful link is given below -

  1. http://www.cplusplus.com/reference/clibrary/cstring/strncat/
  2. http://www.cplusplus.com/reference/clibrary/cstring/strcat/

Second Edit

char msg[200];
int msgLength;
char rankString[200];

........... // Your message has arrived
msgLength = strlen(msg);
itoa(rank, rankString, 10); // I have assumed rank is the integer variable containing the rank id

strncat( msg, rankString, (200 - msgLength) );  // msg now contains previous msg + id

// You may loose some portion of id if message length + id string length is greater than 200

Third Edit

Go to this link. Here you will find an implementation of itoa. Use that instead.

When increasing the size of VARCHAR column on a large table could there be any problems?

Just wanted to add my 2 cents, since I googled this question b/c I found myself in a similar situation...

BE AWARE that while changing from varchar(xxx) to varchar(yyy) is a meta-data change indeed, but changing to varchar(max) is not. Because varchar(max) values (aka BLOB values - image/text etc) are stored differently on the disk, not within a table row, but "out of row". So the server will go nuts on a big table and become unresponsive for minutes (hours).

--no downtime
ALTER TABLE MyTable ALTER COLUMN [MyColumn] VARCHAR(1200)

--huge downtime
ALTER TABLE MyTable ALTER COLUMN [MyColumn] VARCHAR(max)

PS. same applies to nvarchar or course.

How can I create an editable combo box in HTML/Javascript?

I know this question is already answered, a long time ago, but this is for other people that may end up here and are having trouble finding what they need. I had trouble finding an existing plugin that did exactly what I needed, so I wrote my own jQuery UI plugin to accomplish this task. It's based on the combobox example on the jQuery UI site. Hopefully it might help someone.

https://github.com/tmooney3979/jquery.ui.combify

Half circle with CSS (border, outline only)

I use a percentage method to achieve

        border: 3px solid rgb(1, 1, 1);
        border-top-left-radius: 100% 200%;
        border-top-right-radius: 100% 200%;

"Primary Filegroup is Full" in SQL Server 2008 Standard for no apparent reason

I also ran into the same problem, where the initial dtabase size is set to 4Gb and autogrowth is set by 1Mb. The virtual encrypted TrueCrypt drive that the databse was on, seemed to have plenty of space.

I changed a couple of (the above) things:

  • I turned the Windows service for Sql Server Express from automatic to manual, so only the 'regular' Sql Server is running. (Even though I am running Sql Server 2008 R2 which should allow 10 GB.)
  • I changed the autogrowth from 1 MB to 10%
  • I changed the autogrowth increment-size from 10% to 1000 MB
  • I defragmented the drive
  • I shrank the database:
    • manually DBCC SHRINKDATABASE('...')
    • automatically right click on database | "properties" | "Auto Shrink" | "Truncate log on check point")

All to little avail (I could insert some more records, but soon ran into the same problem). The pagefile mentioned by Tobbi, made me try a larger virtual drive. (Even though my drive should not contain any such system files, since I run without it being mounted a lot of the time.)

  • I made a new larger virtual drive with TrueCrypt

When making this, I ran into a TrueCrypt-question, if I am going to store files larger than 4gb (as shown in this SuperUser question).

  • I told TrueCrypt I would store files larger than 4 GB

After these last two I was doing fine, and I am assuming this last one did the trick. I think TrueCrypt chooses an exfat file system (as described here), which limits all files to 4GB. (So I probably did not need to enlarge the drive after all, but I did anyway.)

This is probably a very rare border case, but maybe it is of help to somebody.

How to append the output to a file?

Use >> to append:

command >> file

Getting a random value from a JavaScript array

Say you want to choose a random item that is different from the last time (not really random, but still a common requirement)...

/**
 * Return a random element from an array that is
 * different than `last` (as long as the array has > 1 items). 
 * Return null if the array is empty.
*/
function getRandomDifferent(arr, last = undefined) {
  if (arr.length === 0) {
    return;
  } else if (arr.length === 1) {
    return arr[0];
  } else {
    let num = 0;
    do {
      num = Math.floor(Math.random() * arr.length);
    } while (arr[num] === last);
    return arr[num];
  }
}

Implement like this:

const arr = [1,2,3];
const r1 = getRandomDifferent(arr);
const r2 = getRandomDifferent(arr, r1); // r2 is different than r1.

How to add Options Menu to Fragment in Android

In the menu.xml you should add all the menu items. Then you can hide items that you don't want to see in the initial loading.

menu.xml

<item
    android:id="@+id/action_newItem"
    android:icon="@drawable/action_newItem"
    android:showAsAction="never"
    android:visible="false"
    android:title="@string/action_newItem"/>

Add setHasOptionsMenu(true) in the onCreate() method to invoke the menu items in your Fragment class.

FragmentClass.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

You don't need to override onCreateOptionsMenu in your Fragment class again. Menu items can be changed (Add/remove) by overriding onPrepareOptionsMenumethod available in Fragment.

@Override
public void onPrepareOptionsMenu(Menu menu) {
    menu.findItem(R.id.action_newItem).setVisible(true);
    super.onPrepareOptionsMenu(menu);

}

The multi-part identifier could not be bound

I was struggling with the same error message in SQL SERVER, since I had multiple joins, changing the order of the joins solved it for me.

Bash or KornShell (ksh)?

This is a bit of a Unix vs Linux battle. Most if not all Linux distributions have bash installed and ksh optional. Most Unix systems, like Solaris, AIX and HPUX have ksh as default.

Personally I always use ksh, I love the vi completion and I pretty much use Solaris for everything.

How do you remove duplicates from a list whilst preserving order?

Not to kick a dead horse (this question is very old and already has lots of good answers), but here is a solution using pandas that is quite fast in many circumstances and is dead simple to use.

import pandas as pd

my_list = [0, 1, 2, 3, 4, 1, 2, 3, 5]

>>> pd.Series(my_list).drop_duplicates().tolist()
# Output:
# [0, 1, 2, 3, 4, 5]

What is the common header format of Python files?

Also see PEP 263 if you are using a non-ascii characterset

Abstract

This PEP proposes to introduce a syntax to declare the encoding of a Python source file. The encoding information is then used by the Python parser to interpret the file using the given encoding. Most notably this enhances the interpretation of Unicode literals in the source code and makes it possible to write Unicode literals using e.g. UTF-8 directly in an Unicode aware editor.

Problem

In Python 2.1, Unicode literals can only be written using the Latin-1 based encoding "unicode-escape". This makes the programming environment rather unfriendly to Python users who live and work in non-Latin-1 locales such as many of the Asian countries. Programmers can write their 8-bit strings using the favorite encoding, but are bound to the "unicode-escape" encoding for Unicode literals.

Proposed Solution

I propose to make the Python source code encoding both visible and changeable on a per-source file basis by using a special comment at the top of the file to declare the encoding.

To make Python aware of this encoding declaration a number of concept changes are necessary with respect to the handling of Python source code data.

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given.

To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as:

      # coding=<encoding name>

or (using formats recognized by popular editors)

      #!/usr/bin/python
      # -*- coding: <encoding name> -*-

or

      #!/usr/bin/python
      # vim: set fileencoding=<encoding name> :

...

github changes not staged for commit

Have you tried

git add .

This recurses into sub-directories, whereas I don't think * does.

See here

Javascript change date into format of (dd/mm/yyyy)

This will ensure you get a two-digit day and month.

function formattedDate(d = new Date) {
  let month = String(d.getMonth() + 1);
  let day = String(d.getDate());
  const year = String(d.getFullYear());

  if (month.length < 2) month = '0' + month;
  if (day.length < 2) day = '0' + day;

  return `${day}/${month}/${year}`;
}

Or terser:

function formattedDate(d = new Date) {
  return [d.getDate(), d.getMonth()+1, d.getFullYear()]
      .map(n => n < 10 ? `0${n}` : `${n}`).join('/');
}

How to parse freeform street/postal address out of text, and into components

No code? For shame!

Here is a simple JavaScript address parser. It's pretty awful for every single reason that Matt gives in his dissertation above (which I almost 100% agree with: addresses are complex types, and humans make mistakes; better to outsource and automate this - when you can afford to).

But rather than cry, I decided to try:

This code works OK for parsing most Esri results for findAddressCandidate and also with some other (reverse)geocoders that return single-line address where street/city/state are delimited by commas. You can extend if you want or write country-specific parsers. Or just use this as case study of how challenging this exercise can be or at how lousy I am at JavaScript. I admit I only spent about thirty mins on this (future iterations could add caches, zip validation, and state lookups as well as user location context), but it worked for my use case: End user sees form that parses geocode search response into 4 textboxes. If address parsing comes out wrong (which is rare unless source data was poor) it's no big deal - the user gets to verify and fix it! (But for automated solutions could either discard/ignore or flag as error so dev can either support the new format or fix source data.)

_x000D_
_x000D_
/* _x000D_
address assumptions:_x000D_
- US addresses only (probably want separate parser for different countries)_x000D_
- No country code expected._x000D_
- if last token is a number it is probably a postal code_x000D_
-- 5 digit number means more likely_x000D_
- if last token is a hyphenated string it might be a postal code_x000D_
-- if both sides are numeric, and in form #####-#### it is more likely_x000D_
- if city is supplied, state will also be supplied (city names not unique)_x000D_
- zip/postal code may be omitted even if has city & state_x000D_
- state may be two-char code or may be full state name._x000D_
- commas: _x000D_
-- last comma is usually city/state separator_x000D_
-- second-to-last comma is possibly street/city separator_x000D_
-- other commas are building-specific stuff that I don't care about right now._x000D_
- token count:_x000D_
-- because units, street names, and city names may contain spaces token count highly variable._x000D_
-- simplest address has at least two tokens: 714 OAK_x000D_
-- common simple address has at least four tokens: 714 S OAK ST_x000D_
-- common full (mailing) address has at least 5-7:_x000D_
--- 714 OAK, RUMTOWN, VA 59201_x000D_
--- 714 S OAK ST, RUMTOWN, VA 59201_x000D_
-- complex address may have a dozen or more:_x000D_
--- MAGICICIAN SUPPLY, LLC, UNIT 213A, MAGIC TOWN MALL, 13 MAGIC CIRCLE DRIVE, LAND OF MAGIC, MA 73122-3412_x000D_
*/_x000D_
_x000D_
var rawtext = $("textarea").val();_x000D_
var rawlist = rawtext.split("\n");_x000D_
_x000D_
function ParseAddressEsri(singleLineaddressString) {_x000D_
  var address = {_x000D_
    street: "",_x000D_
    city: "",_x000D_
    state: "",_x000D_
    postalCode: ""_x000D_
  };_x000D_
_x000D_
  // tokenize by space (retain commas in tokens)_x000D_
  var tokens = singleLineaddressString.split(/[\s]+/);_x000D_
  var tokenCount = tokens.length;_x000D_
  var lastToken = tokens.pop();_x000D_
  if (_x000D_
    // if numeric assume postal code (ignore length, for now)_x000D_
    !isNaN(lastToken) ||_x000D_
    // if hyphenated assume long zip code, ignore whether numeric, for now_x000D_
    lastToken.split("-").length - 1 === 1) {_x000D_
    address.postalCode = lastToken;_x000D_
    lastToken = tokens.pop();_x000D_
  }_x000D_
_x000D_
  if (lastToken && isNaN(lastToken)) {_x000D_
    if (address.postalCode.length && lastToken.length === 2) {_x000D_
      // assume state/province code ONLY if had postal code_x000D_
      // otherwise it could be a simple address like "714 S OAK ST"_x000D_
      // where "ST" for "street" looks like two-letter state code_x000D_
      // possibly this could be resolved with registry of known state codes, but meh. (and may collide anyway)_x000D_
      address.state = lastToken;_x000D_
      lastToken = tokens.pop();_x000D_
    }_x000D_
    if (address.state.length === 0) {_x000D_
      // check for special case: might have State name instead of State Code._x000D_
      var stateNameParts = [lastToken.endsWith(",") ? lastToken.substring(0, lastToken.length - 1) : lastToken];_x000D_
_x000D_
      // check remaining tokens from right-to-left for the first comma_x000D_
      while (2 + 2 != 5) {_x000D_
        lastToken = tokens.pop();_x000D_
        if (!lastToken) break;_x000D_
        else if (lastToken.endsWith(",")) {_x000D_
          // found separator, ignore stuff on left side_x000D_
          tokens.push(lastToken); // put it back_x000D_
          break;_x000D_
        } else {_x000D_
          stateNameParts.unshift(lastToken);_x000D_
        }_x000D_
      }_x000D_
      address.state = stateNameParts.join(' ');_x000D_
      lastToken = tokens.pop();_x000D_
    }_x000D_
  }_x000D_
_x000D_
  if (lastToken) {_x000D_
    // here is where it gets trickier:_x000D_
    if (address.state.length) {_x000D_
      // if there is a state, then assume there is also a city and street._x000D_
      // PROBLEM: city may be multiple words (spaces)_x000D_
      // but we can pretty safely assume next-from-last token is at least PART of the city name_x000D_
      // most cities are single-name. It would be very helpful if we knew more context, like_x000D_
      // the name of the city user is in. But ignore that for now._x000D_
      // ideally would have zip code service or lookup to give city name for the zip code._x000D_
      var cityNameParts = [lastToken.endsWith(",") ? lastToken.substring(0, lastToken.length - 1) : lastToken];_x000D_
_x000D_
      // assumption / RULE: street and city must have comma delimiter_x000D_
      // addresses that do not follow this rule will be wrong only if city has space_x000D_
      // but don't care because Esri formats put comma before City_x000D_
      var streetNameParts = [];_x000D_
_x000D_
      // check remaining tokens from right-to-left for the first comma_x000D_
      while (2 + 2 != 5) {_x000D_
        lastToken = tokens.pop();_x000D_
        if (!lastToken) break;_x000D_
        else if (lastToken.endsWith(",")) {_x000D_
          // found end of street address (may include building, etc. - don't care right now)_x000D_
          // add token back to end, but remove trailing comma (it did its job)_x000D_
          tokens.push(lastToken.endsWith(",") ? lastToken.substring(0, lastToken.length - 1) : lastToken);_x000D_
          streetNameParts = tokens;_x000D_
          break;_x000D_
        } else {_x000D_
          cityNameParts.unshift(lastToken);_x000D_
        }_x000D_
      }_x000D_
      address.city = cityNameParts.join(' ');_x000D_
      address.street = streetNameParts.join(' ');_x000D_
    } else {_x000D_
      // if there is NO state, then assume there is NO city also, just street! (easy)_x000D_
      // reasoning: city names are not very original (Portland, OR and Portland, ME) so if user wants city they need to store state also (but if you are only ever in Portlan, OR, you don't care about city/state)_x000D_
      // put last token back in list, then rejoin on space_x000D_
      tokens.push(lastToken);_x000D_
      address.street = tokens.join(' ');_x000D_
    }_x000D_
  }_x000D_
  // when parsing right-to-left hard to know if street only vs street + city/state_x000D_
  // hack fix for now is to shift stuff around._x000D_
  // assumption/requirement: will always have at least street part; you will never just get "city, state"  _x000D_
  // could possibly tweak this with options or more intelligent parsing&sniffing_x000D_
  if (!address.city && address.state) {_x000D_
    address.city = address.state;_x000D_
    address.state = '';_x000D_
  }_x000D_
  if (!address.street) {_x000D_
    address.street = address.city;_x000D_
    address.city = '';_x000D_
  }_x000D_
_x000D_
  return address;_x000D_
}_x000D_
_x000D_
// get list of objects with discrete address properties_x000D_
var addresses = rawlist_x000D_
  .filter(function(o) {_x000D_
    return o.length > 0_x000D_
  })_x000D_
  .map(ParseAddressEsri);_x000D_
$("#output").text(JSON.stringify(addresses));_x000D_
console.log(addresses);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea>_x000D_
27488 Stanford Ave, Bowden, North Dakota_x000D_
380 New York St, Redlands, CA 92373_x000D_
13212 E SPRAGUE AVE, FAIR VALLEY, MD 99201_x000D_
1005 N Gravenstein Highway, Sebastopol CA 95472_x000D_
A. P. Croll &amp; Son 2299 Lewes-Georgetown Hwy, Georgetown, DE 19947_x000D_
11522 Shawnee Road, Greenwood, DE 19950_x000D_
144 Kings Highway, S.W. Dover, DE 19901_x000D_
Intergrated Const. Services 2 Penns Way Suite 405, New Castle, DE 19720_x000D_
Humes Realty 33 Bridle Ridge Court, Lewes, DE 19958_x000D_
Nichols Excavation 2742 Pulaski Hwy, Newark, DE 19711_x000D_
2284 Bryn Zion Road, Smyrna, DE 19904_x000D_
VEI Dover Crossroads, LLC 1500 Serpentine Road, Suite 100 Baltimore MD 21_x000D_
580 North Dupont Highway, Dover, DE 19901_x000D_
P.O. Box 778, Dover, DE 19903_x000D_
714 S OAK ST_x000D_
714 S OAK ST, RUM TOWN, VA, 99201_x000D_
3142 E SPRAGUE AVE, WHISKEY VALLEY, WA 99281_x000D_
27488 Stanford Ave, Bowden, North Dakota_x000D_
380 New York St, Redlands, CA 92373_x000D_
</textarea>_x000D_
<div id="output">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Add directives from directive in AngularJS

In cases where you have multiple directives on a single DOM element and where the order in which they’re applied matters, you can use the priority property to order their application. Higher numbers run first. The default priority is 0 if you don’t specify one.

EDIT: after the discussion, here's the complete working solution. The key was to remove the attribute: element.removeAttr("common-things");, and also element.removeAttr("data-common-things"); (in case users specify data-common-things in the html)

angular.module('app')
  .directive('commonThings', function ($compile) {
    return {
      restrict: 'A',
      replace: false, 
      terminal: true, //this setting is important, see explanation below
      priority: 1000, //this setting is important, see explanation below
      compile: function compile(element, attrs) {
        element.attr('tooltip', '{{dt()}}');
        element.attr('tooltip-placement', 'bottom');
        element.removeAttr("common-things"); //remove the attribute to avoid indefinite loop
        element.removeAttr("data-common-things"); //also remove the same attribute with data- prefix in case users specify data-common-things in the html

        return {
          pre: function preLink(scope, iElement, iAttrs, controller) {  },
          post: function postLink(scope, iElement, iAttrs, controller) {  
            $compile(iElement)(scope);
          }
        };
      }
    };
  });

Working plunker is available at: http://plnkr.co/edit/Q13bUt?p=preview

Or:

angular.module('app')
  .directive('commonThings', function ($compile) {
    return {
      restrict: 'A',
      replace: false,
      terminal: true,
      priority: 1000,
      link: function link(scope,element, attrs) {
        element.attr('tooltip', '{{dt()}}');
        element.attr('tooltip-placement', 'bottom');
        element.removeAttr("common-things"); //remove the attribute to avoid indefinite loop
        element.removeAttr("data-common-things"); //also remove the same attribute with data- prefix in case users specify data-common-things in the html

        $compile(element)(scope);
      }
    };
  });

DEMO

Explanation why we have to set terminal: true and priority: 1000 (a high number):

When the DOM is ready, angular walks the DOM to identify all registered directives and compile the directives one by one based on priority if these directives are on the same element. We set our custom directive's priority to a high number to ensure that it will be compiled first and with terminal: true, the other directives will be skipped after this directive is compiled.

When our custom directive is compiled, it will modify the element by adding directives and removing itself and use $compile service to compile all the directives (including those that were skipped).

If we don't set terminal:true and priority: 1000, there is a chance that some directives are compiled before our custom directive. And when our custom directive uses $compile to compile the element => compile again the already compiled directives. This will cause unpredictable behavior especially if the directives compiled before our custom directive have already transformed the DOM.

For more information about priority and terminal, check out How to understand the `terminal` of directive?

An example of a directive that also modifies the template is ng-repeat (priority = 1000), when ng-repeat is compiled, ng-repeat make copies of the template element before other directives get applied.

Thanks to @Izhaki's comment, here is the reference to ngRepeat source code: https://github.com/angular/angular.js/blob/master/src/ng/directive/ngRepeat.js

How to print the ld(linker) search path

The question is tagged Linux, but maybe this works as well under Linux?

gcc -Xlinker -v

Under Mac OS X, this prints:

@(#)PROGRAM:ld  PROJECT:ld64-224.1
configured to support archs: armv6 armv7 armv7s arm64 i386 x86_64 armv6m armv7m armv7em
Library search paths:
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/lib
Framework search paths:
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/System/Library/Frameworks/
[...]

The -Xlinker option of gcc above just passes -v to ld. However:

ld -v

doesn't print the search path.

Visualizing branch topology in Git

Git official site enlisted some third party platform specific GUI tools. Hit here git GUI Tools for Linux Platform

I have used gitg and GitKraken for linux platform. Both good to understand the commit tree

How to install a certificate in Xcode (preparing for app store submission)

These instructions are for XCode 6.4 (since I couldn't find the update for the recent versions even this was a bit outdated)

a) Part on the developers' website:

Sign in into: https://developer.apple.com/

Member Center

Certificates, Identifiers & Profiles

Certificates>All

Click "+" to add, and then follow the instructions. You will need to open "Keychain Access.app", there under "Keychain Access" menu > "Certificate Assistant>", choose "Request a Certificate From a Certificate Authority" etc.

b) XCode part:

After all, you need to go to XCode, and open XCode>Preferences..., choose your Apple ID > View Details... > click that rounded arrow to update as well as "+" to check for iOS Distribution or iOS Developer Signing Identities.

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (CodeIgniter + XML-RPC)

I find it useful when including or requiring _dbconnection.php_ and _functions.php in files that are actually processed, rather than including in the header. Which is included in itself.

So if your header and footer is included, simply include all your functional files before the header is included.

Can we call the function written in one JavaScript in another JS file?

You can call the function created in another js file from the file you are working in. So for this firstly you need to add the external js file into the html document as-

<html>
<head>
    <script type="text/javascript" src='path/to/external/js'></script>
</head>
<body>
........

The function defined in the external javascript file -

$.fn.yourFunctionName = function(){
    alert('function called succesfully for - ' + $(this).html() );
}

To call this function in your current file, just call the function as -

......
<script type="text/javascript">
    $(function(){
        $('#element').yourFunctionName();
    });
</script>

If you want to pass the parameters to the function, then define the function as-

$.fn.functionWithParameters = function(parameter1, parameter2){
        alert('Parameters passed are - ' + parameter1 + ' , ' + parameter2);
}

And call this function in your current file as -

$('#element').functionWithParameters('some parameter', 'another parameter');

How to export private key from a keystore of self-signed certificate

http://anandsekar.github.io/exporting-the-private-key-from-a-jks-keystore/

public class ExportPrivateKey {
        private File keystoreFile;
        private String keyStoreType;
        private char[] password;
        private String alias;
        private File exportedFile;

        public static KeyPair getPrivateKey(KeyStore keystore, String alias, char[] password) {
                try {
                        Key key=keystore.getKey(alias,password);
                        if(key instanceof PrivateKey) {
                                Certificate cert=keystore.getCertificate(alias);
                                PublicKey publicKey=cert.getPublicKey();
                                return new KeyPair(publicKey,(PrivateKey)key);
                        }
                } catch (UnrecoverableKeyException e) {
        } catch (NoSuchAlgorithmException e) {
        } catch (KeyStoreException e) {
        }
        return null;
        }

        public void export() throws Exception{
                KeyStore keystore=KeyStore.getInstance(keyStoreType);
                BASE64Encoder encoder=new BASE64Encoder();
                keystore.load(new FileInputStream(keystoreFile),password);
                KeyPair keyPair=getPrivateKey(keystore,alias,password);
                PrivateKey privateKey=keyPair.getPrivate();
                String encoded=encoder.encode(privateKey.getEncoded());
                FileWriter fw=new FileWriter(exportedFile);
                fw.write(“—–BEGIN PRIVATE KEY—–\n“);
                fw.write(encoded);
                fw.write(“\n“);
                fw.write(“—–END PRIVATE KEY—–”);
                fw.close();
        }


        public static void main(String args[]) throws Exception{
                ExportPrivateKey export=new ExportPrivateKey();
                export.keystoreFile=new File(args[0]);
                export.keyStoreType=args[1];
                export.password=args[2].toCharArray();
                export.alias=args[3];
                export.exportedFile=new File(args[4]);
                export.export();
        }
}

check output from CalledProcessError

If you want to get stdout and stderr back (including extracting it from the CalledProcessError in the event that one occurs), use the following:

import subprocess

command = ["ls", "-l"]
try:
    output = subprocess.check_output(command, stderr=subprocess.STDOUT).decode()
    success = True 
except subprocess.CalledProcessError as e:
    output = e.output.decode()
    success = False

print(output)

This is Python 2 and 3 compatible.

If your command is a string rather than an array, prefix this with:

import shlex
command = shlex.split(command)

ORA-00054: resource busy and acquire with NOWAIT specified

Depending on your situation, the table being locked may just be part of a normal operation & you don't want to just kill the blocking transaction. What you want to do is have your statement wait for the other resource. Oracle 11g has DDL timeouts which can be set to deal with this.

If you're dealing with 10g then you have to get more creative and write some PL/SQL to handle the re-try. Look at Getting around ORA-00054 in Oracle 10g This re-runs your statement when a resource_busy exception occurs.

How to check for a valid URL in Java?

Consider using the Apache Commons UrlValidator class

UrlValidator urlValidator = new UrlValidator();
urlValidator.isValid("http://my favorite site!");

There are several properties that you can set to control how this class behaves, by default http, https, and ftp are accepted.

How to display list of repositories from subversion server

If you enable svn via apache and a SVNParentPath directive, you can add a SVNListParentPath On directive to your svn location to get a list of all repositories.

Your apache conf should look similar to this:

<Location /svn>
  DAV svn
  SVNParentPath         "/net/svn/repositories"
  # optional auth stuff     

  SVNListParentPath On    #  <--- Add this line to enable listing of all repos
</Location>

How to remove non UTF-8 characters from text file

Your method must read byte by byte and fully understand and appreciate the byte wise construction of characters. The simplest method is to use an editor which will read anything but only output UTF-8 characters. Textpad is one choice.

How to read a file into a variable in shell?

In cross-platform, lowest-common-denominator sh you use:

#!/bin/sh
value=`cat config.txt`
echo "$value"

In bash or zsh, to read a whole file into a variable without invoking cat:

#!/bin/bash
value=$(<config.txt)
echo "$value"

Invoking cat in bash or zsh to slurp a file would be considered a Useless Use of Cat.

Note that it is not necessary to quote the command substitution to preserve newlines.

See: Bash Hacker's Wiki - Command substitution - Specialities.

How to use Session attributes in Spring-mvc

Use This method very simple easy to use

HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getNativeRequest();

                                                            request.getSession().setAttribute("errorMsg", "your massage");

in jsp once use then remove

<c:remove var="errorMsg" scope="session"/>      

Convert List to Pandas Dataframe Column

Example:

['Thanks You',
 'Its fine no problem',
 'Are you sure']

code block:

import pandas as pd
df = pd.DataFrame(lst)

Output:

    0
0   Thanks You
1   Its fine no problem
2   Are you sure

It is not recommended to remove the column names of the panda dataframe. but if you still want your data frame without header(as per the format you posted in the question) you can do this:

df = pd.DataFrame(lst)    
df.columns = ['']

Output will be like this:

0   Thanks You
1   Its fine no problem
2   Are you sure

or

df = pd.DataFrame(lst).to_string(header=False)

But the output will be a list instead of a dataframe:

0           Thanks You
1  Its fine no problem
2         Are you sure

Hope this helps!!

Synchronous request in Node.js

I'd use a recursive function with a list of apis

var APIs = [ '/api_1.php', '/api_2.php', '/api_3.php' ];
var host = 'www.example.com';

function callAPIs ( host, APIs ) {
  var API = APIs.shift();
  http.get({ host: host, path: API }, function(res) { 
    var body = '';
    res.on('data', function (d) {
      body += d; 
    });
    res.on('end', function () {
      if( APIs.length ) {
        callAPIs ( host, APIs );
      }
    });
  });
}

callAPIs( host, APIs );

edit: request version

var request = require('request');
var APIs = [ '/api_1.php', '/api_2.php', '/api_3.php' ];
var host = 'www.example.com';
var APIs = APIs.map(function (api) {
  return 'http://' + host + api;
});

function callAPIs ( host, APIs ) {
  var API = APIs.shift();
  request(API, function(err, res, body) { 
    if( APIs.length ) {
      callAPIs ( host, APIs );
    }
  });
}

callAPIs( host, APIs );

edit: request/async version

var request = require('request');
var async = require('async');
var APIs = [ '/api_1.php', '/api_2.php', '/api_3.php' ];
var host = 'www.example.com';
var APIs = APIs.map(function (api) {
  return 'http://' + host + api;
});

async.eachSeries(function (API, cb) {
  request(API, function (err, res, body) {
    cb(err);
  });
}, function (err) {
  //called when all done, or error occurs
});

how to display toolbox on the left side of window of Visual Studio Express for windows phone 7 development?

I had this problem with Blend for Visual Studio 2015. The Toolbox would just not appear anymore. This turns out to be because Blend is not Visual Studio!

(You can edit your code in Blend and build and run it... It certainly seems like Visual Studio, but it isn't. I'm not sure what the purpose of Blend is...)

You can tell you are in Blend if the task bar icon has big "B" in it. To switch from Blend to Visual Studio, go to View-> Edit in Visual Studio.... It will open up another application that looks just like Blend, except the Solution Explorer is on the right instead of the left, and now you have a toolbox...

Handling MySQL datetimes and timestamps in Java

BalusC gave a good description about the problem but it lacks a good end to end code that users can pick and test it for themselves.

Best practice is to always store date-time in UTC timezone in DB. Sql timestamp type does not have timezone info.

When writing datetime value to sql db

    //Convert the time into UTC and build Timestamp object.
    Timestamp ts = Timestamp.valueOf(LocalDateTime.now(ZoneId.of("UTC")));
    //use setTimestamp on preparedstatement
    preparedStatement.setTimestamp(1, ts);

When reading the value back from DB into java,

  1. Read it as it is in java.sql.Timestamp type.
  2. Decorate the DateTime value as time in UTC timezone using atZone method in LocalDateTime class.
  3. Then, change it to your desired timezone. Here I am changing it to Toronto timezone.

    ResultSet resultSet = preparedStatement.executeQuery();
    resultSet.next();
    Timestamp timestamp = resultSet.getTimestamp(1);
    ZonedDateTime timeInUTC = timestamp.toLocalDateTime().atZone(ZoneId.of("UTC"));
    LocalDateTime timeInToronto = LocalDateTime.ofInstant(timeInUTC.toInstant(), ZoneId.of("America/Toronto"));
    

C++ trying to swap values in a vector

after passing the vector by reference

swap(vector[position],vector[otherPosition]);

will produce the expected result.

Take n rows from a spark dataframe and pass to toPandas()

Try it:

def showDf(df, count=None, percent=None, maxColumns=0):
    if (df == None): return
    import pandas
    from IPython.display import display
    pandas.set_option('display.encoding', 'UTF-8')
    # Pandas dataframe
    dfp = None
    # maxColumns param
    if (maxColumns >= 0):
        if (maxColumns == 0): maxColumns = len(df.columns)
        pandas.set_option('display.max_columns', maxColumns)
    # count param
    if (count == None and percent == None): count = 10 # Default count
    if (count != None):
        count = int(count)
        if (count == 0): count = df.count()
        pandas.set_option('display.max_rows', count)
        dfp = pandas.DataFrame(df.head(count), columns=df.columns)
        display(dfp)
    # percent param
    elif (percent != None):
        percent = float(percent)
        if (percent >=0.0 and percent <= 1.0):
            import datetime
            now = datetime.datetime.now()
            seed = long(now.strftime("%H%M%S"))
            dfs = df.sample(False, percent, seed)
            count = df.count()
            pandas.set_option('display.max_rows', count)
            dfp = dfs.toPandas()    
            display(dfp)

Examples of usages are:

# Shows the ten first rows of the Spark dataframe
showDf(df)
showDf(df, 10)
showDf(df, count=10)

# Shows a random sample which represents 15% of the Spark dataframe
showDf(df, percent=0.15) 

Split string with PowerShell and do something with each token

To complement Justus Thane's helpful answer:

  • As Joey notes in a comment, PowerShell has a powerful, regex-based -split operator.

    • In its unary form (-split '...'), -split behaves like awk's default field splitting, which means that:
      • Leading and trailing whitespace is ignored.
      • Any run of whitespace (e.g., multiple adjacent spaces) is treated as a single separator.
  • In PowerShell v4+ an expression-based - and therefore faster - alternative to the ForEach-Object cmdlet became available: the .ForEach() array (collection) method, as described in this blog post (alongside the .Where() method, a more powerful, expression-based alternative to Where-Object).

Here's a solution based on these features:

PS> (-split '   One      for the money   ').ForEach({ "token: [$_]" })
token: [One]
token: [for]
token: [the]
token: [money]

Note that the leading and trailing whitespace was ignored, and that the multiple spaces between One and for were treated as a single separator.

Resizing an Image without losing any quality

I believe what you're looking to do is "Resize/Resample" your images. Here is a good site that gives instructions and provides a utility class(That I also happen to use):

http://www.codeproject.com/KB/GDI-plus/imgresizoutperfgdiplus.aspx

Indirectly referenced from required .class file

How are you adding your Weblogic classes to the classpath in Eclipse? Are you using WTP, and a server runtime? If so, is your server runtime associated with your project?

If you right click on your project and choose build path->configure build path and then choose the libraries tab. You should see the weblogic libraries associated here. If you do not you can click Add Library->Server Runtime. If the library is not there, then you first need to configure it. Windows->Preferences->Server->Installed runtimes

Authorize attribute in ASP.NET MVC

The tag in web.config is based on paths, whereas MVC works with controller actions and routes.

It is an architectural decision that might not make a lot of difference if you just want to prevent users that aren't logged in but makes a lot of difference when you try to apply authorization based in Roles and in cases that you want custom handling of types of Unauthorized.

The first case is covered from the answer of BobRock.

The user should have at least one of the following Roles to access the Controller or the Action

[Authorize(Roles = "Admin, Super User")]

The user should have both these roles in order to be able to access the Controller or Action

[Authorize(Roles = "Super User")]
[Authorize(Roles = "Admin")]

The users that can access the Controller or the Action are Betty and Johnny

[Authorize(Users = "Betty, Johnny")]

In ASP.NET Core you can use Claims and Policy principles for authorization through [Authorize].

options.AddPolicy("ElevatedRights", policy =>
                  policy.RequireRole("Administrator", "PowerUser", "BackupAdministrator"));

[Authorize(Policy = "ElevatedRights")]

The second comes very handy in bigger applications where Authorization might need to be implemented with different restrictions, process and handling according to the case. For this reason we can Extend the AuthorizeAttribute and implement different authorization alternatives for our project.

public class CustomAuthorizeAttribute: AuthorizeAttribute  
{  
    public override void OnAuthorization(AuthorizationContext filterContext)  
    {  }
}

The "correct-completed" way to do authorization in ASP.NET MVC is using the [Authorize] attribute.

Make a div fill the height of the remaining screen space

I wresteled with this for a while and ended up with the following:

Since it is easy to make the content DIV the same height as the parent but apparently difficult to make it the parent height minus the header height I decided to make content div full height but position it absolutely in the top left corner and then define a padding for the top which has the height of the header. This way the content displays neatly under the header and fills the whole remaining space:

body {
    padding: 0;
    margin: 0;
    height: 100%;
    overflow: hidden;
}

#header {
    position: absolute;
    top: 0;
    left: 0;
    height: 50px;
}

#content {
    position: absolute;
    top: 0;
    left: 0;
    padding-top: 50px;
    height: 100%;
}

Convert python long/int to fixed size byte array

i = 0x12345678
s = struct.pack('<I',i)
b = struct.unpack('BBBB',s)

Authentication failed for https://xxx.visualstudio.com/DefaultCollection/_git/project

If you are entering your credentials into the Visual Studio popup you might see an error that says "Login was not successful". However, this might not be true. Studio will open a browser window saying that it was in fact successful. There is then a dance between the browser and Studio where you need to accept / allow the authentication at certain points.

php/mySQL on XAMPP: password for phpMyAdmin and mysql_connect different?

You need to change the password directly in the database because at mysql the users and their profiles are saved in the database.

So there are several ways. At phpMyAdmin you simple go to user admin, choose root and change the password.

PHP Error: Function name must be a string

Try square braces with your $_COOKIE, not parenthesis. Like this:

<?php
if ($_COOKIE['CaptchaResponseValue'] == "false")
{
    header('Location: index.php');
    return;
}
?>

I also corrected your location header call a little too.

Regular expression for letters, numbers and - _

The pattern you want is something like (see it on rubular.com):

^[a-zA-Z0-9_.-]*$

Explanation:

  • ^ is the beginning of the line anchor
  • $ is the end of the line anchor
  • [...] is a character class definition
  • * is "zero-or-more" repetition

Note that the literal dash - is the last character in the character class definition, otherwise it has a different meaning (i.e. range). The . also has a different meaning outside character class definitions, but inside, it's just a literal .

References


In PHP

Here's a snippet to show how you can use this pattern:

<?php

$arr = array(
  'screen123.css',
  'screen-new-file.css',
  'screen_new.js',
  'screen new file.css'
);

foreach ($arr as $s) {
  if (preg_match('/^[\w.-]*$/', $s)) {
    print "$s is a match\n";
  } else {
    print "$s is NO match!!!\n";
  };
}

?>

The above prints (as seen on ideone.com):

screen123.css is a match
screen-new-file.css is a match
screen_new.js is a match
screen new file.css is NO match!!!

Note that the pattern is slightly different, using \w instead. This is the character class for "word character".

API references


Note on specification

This seems to follow your specification, but note that this will match things like ....., etc, which may or may not be what you desire. If you can be more specific what pattern you want to match, the regex will be slightly more complicated.

The above regex also matches the empty string. If you need at least one character, then use + (one-or-more) instead of * (zero-or-more) for repetition.

In any case, you can further clarify your specification (always helps when asking regex question), but hopefully you can also learn how to write the pattern yourself given the above information.

How to update and order by using ms sql

I have to offer this as a better approach - you don't always have the luxury of an identity field:

UPDATE m
SET [status]=10
FROM (
  Select TOP (10) *
  FROM messages
  WHERE [status]=0
  ORDER BY [priority] DESC
) m

You can also make the sub-query as complicated as you want - joining multiple tables, etc...

Why is this better? It does not rely on the presence of an identity field (or any other unique column) in the messages table. It can be used to update the top N rows from any table, even if that table has no unique key at all.

What does set -e mean in a bash script?

From help set :

  -e  Exit immediately if a command exits with a non-zero status.

But it's considered bad practice by some (bash FAQ and irc freenode #bash FAQ authors). It's recommended to use:

trap 'do_something' ERR

to run do_something function when errors occur.

See http://mywiki.wooledge.org/BashFAQ/105

Best way to remove the last character from a string built with stringbuilder

Just use

string.Join(",", yourCollection)

This way you don't need the StringBuilder and the loop.




Long addition about async case. As of 2019, it's not a rare setup when the data are coming asynchronously.

In case your data are in async collection, there is no string.Join overload taking IAsyncEnumerable<T>. But it's easy to create one manually, hacking the code from string.Join:

public static class StringEx
{
    public static async Task<string> JoinAsync<T>(string separator, IAsyncEnumerable<T> seq)
    {
        if (seq == null)
            throw new ArgumentNullException(nameof(seq));

        await using (var en = seq.GetAsyncEnumerator())
        {
            if (!await en.MoveNextAsync())
                return string.Empty;

            string firstString = en.Current?.ToString();

            if (!await en.MoveNextAsync())
                return firstString ?? string.Empty;

            // Null separator and values are handled by the StringBuilder
            var sb = new StringBuilder(256);
            sb.Append(firstString);

            do
            {
                var currentValue = en.Current;
                sb.Append(separator);
                if (currentValue != null)
                    sb.Append(currentValue);
            }
            while (await en.MoveNextAsync());
            return sb.ToString();
        }
    }
}

If the data are coming asynchronously but the interface IAsyncEnumerable<T> is not supported (like the mentioned in comments SqlDataReader), it's relatively easy to wrap the data into an IAsyncEnumerable<T>:

async IAsyncEnumerable<(object first, object second, object product)> ExtractData(
        SqlDataReader reader)
{
    while (await reader.ReadAsync())
        yield return (reader[0], reader[1], reader[2]);
}

and use it:

Task<string> Stringify(SqlDataReader reader) =>
    StringEx.JoinAsync(
        ", ",
        ExtractData(reader).Select(x => $"{x.first} * {x.second} = {x.product}"));

In order to use Select, you'll need to use nuget package System.Interactive.Async. Here you can find a compilable example.

I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely

The problem occurs because webpack-dev-server 2.4.4 adds a host check. You can disable it by adding this to your webpack config:

 devServer: {
    compress: true,
    disableHostCheck: true,   // That solved it

 }      

EDIT: Please note, this fix is insecure.

Please see the following answer for a secure solution: https://stackoverflow.com/a/43621275/5425585

How to debug Ruby scripts

Use Pry (GitHub).

Install via:

$ gem install pry
$ pry

Then add:

require 'pry'; binding.pry

into your program.

As of pry 0.12.2 however, there are no navigation commands such as next, break, etc. Some other gems additionally provide this, see for example pry-byedebug.

Declaring variables inside or outside of a loop

You have a risk of NullPointerException if your calculateStr() method returns null and then you try to call a method on str.

More generally, avoid having variables with a null value. It stronger for class attributes, by the way.

How can I consume a WSDL (SOAP) web service in Python?

Zeep is a decent SOAP library for Python that matches what you're asking for: http://docs.python-zeep.org

JAX-WS - Adding SOAP Headers

The best option (for my of course) is do it yourserfl. It means you can modify programattly all parts of the SOAP message

Binding binding = prov.getBinding();
   List<Handler> handlerChain = binding.getHandlerChain();
    handlerChain.add( new ModifyMessageHandler() );
    binding.setHandlerChain( handlerChain ); 

And the ModifyMessageHandler source could be

@Override
public boolean handleMessage( SOAPMessageContext context )
{
    SOAPMessage msg = context.getMessage(); 
    try
    {

        SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope();
        SOAPHeader header = envelope.addHeader();
        SOAPElement ele = header.addChildElement( new QName( "http://uri", "name_of_header" ) );
        ele.addTextNode( "value_of_header" );
        ele = header.addChildElement( new QName( "http://uri", "name_of_header" ) );
        ele.addTextNode( "value_of_header" );
        ele = header.addChildElement( new QName( "http://uri", "name_of_header" ) );
        ele.addTextNode( "value_of_header" );

...

I hope this helps you

How to remove "rows" with a NA value?

dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))

na.omit(dat)
  x1  x2
1  1 100
3  3 300
5  5 500

Vue.js getting an element within a component

The answers are not making it clear:

Use this.$refs.someName, but, in order to use it, you must add ref="someName" in the parent.

See demo below.

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  mounted: function() {_x000D_
    var childSpanClassAttr = this.$refs.someName.getAttribute('class');_x000D_
    _x000D_
    console.log('<span> was declared with "class" attr -->', childSpanClassAttr);_x000D_
  }_x000D_
})
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
  Parent._x000D_
  <span ref="someName" class="abc jkl xyz">Child Span</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

$refs and v-for

Notice that when used in conjunction with v-for, the this.$refs.someName will be an array:

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    ages: [11, 22, 33]_x000D_
  },_x000D_
  mounted: function() {_x000D_
    console.log("<span> one's text....:", this.$refs.mySpan[0].innerText);_x000D_
    console.log("<span> two's text....:", this.$refs.mySpan[1].innerText);_x000D_
    console.log("<span> three's text..:", this.$refs.mySpan[2].innerText);_x000D_
  }_x000D_
})
_x000D_
span { display: inline-block; border: 1px solid red; }
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
  Parent._x000D_
  <div v-for="age in ages">_x000D_
    <span ref="mySpan">Age is {{ age }}</span>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to color System.out.println output?

Check This Out: i used ANSI values with escape code and it probably not work in windows command prompt but in IDEs and Unix shell. you can also check 'Jansi' library here for windows support.

System.out.println("\u001B[35m" + "This text is PURPLE!" + "\u001B[0m");

How do I get into a Docker container's shell?

It is simple!

List out all your Docker images:

sudo docker images

On my system it showed the following output:

REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
bash                latest              922b9cc3ea5e        9 hours ago
14.03 MB
ubuntu              latest              7feff7652c69        5 weeks ago         81.15 MB

I have two Docker images on my PC. Let's say I want to run the first one.

sudo docker run -i -t ubuntu:latest /bin/bash

This will give you terminal control of the container. Now you can do all type of shell operations inside the container. Like doing ls will output all folders in the root of the file system.

bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

Convert String to Calendar Object in Java

Yes it would be bad practice to parse it yourself. Take a look at SimpleDateFormat, it will turn the String into a Date and you can set the Date into a Calendar instance.

Py_Initialize fails - unable to load the file system codec

I just ran into the exact same problem (same Python version, OS, code, etc).

You just have to copy Python's Lib/ directory in your program's working directory ( on VC it's the directory where the .vcproj is )

get the selected index value of <select> tag in php

$gender = $_POST['gender'];
echo $gender;  

it will echoes the selected value.

Can one do a for each loop in java in reverse order?

The Collections.reverse method actually returns a new list with the elements of the original list copied into it in reverse order, so this has O(n) performance with regards to the size of the original list.

As a more efficient solution, you could write a decorator that presents a reversed view of a List as an Iterable. The iterator returned by your decorator would use the ListIterator of the decorated list to walk over the elements in reverse order.

For example:

public class Reversed<T> implements Iterable<T> {
    private final List<T> original;

    public Reversed(List<T> original) {
        this.original = original;
    }

    public Iterator<T> iterator() {
        final ListIterator<T> i = original.listIterator(original.size());

        return new Iterator<T>() {
            public boolean hasNext() { return i.hasPrevious(); }
            public T next() { return i.previous(); }
            public void remove() { i.remove(); }
        };
    }

    public static <T> Reversed<T> reversed(List<T> original) {
        return new Reversed<T>(original);
    }
}

And you would use it like:

import static Reversed.reversed;

...

List<String> someStrings = getSomeStrings();
for (String s : reversed(someStrings)) {
    doSomethingWith(s);
}

Using $_POST to get select option value from HTML

Use this way:

$selectOption = $_POST['taskOption'];

But it is always better to give values to your <option> tags.

<select name="taskOption">
  <option value="1">First</option>
  <option value="2">Second</option>
  <option value="3">Third</option>
</select>

MongoError: connect ECONNREFUSED 127.0.0.1:27017

I had the same error because i had not installed mongoDB. Make sure that you have mongodb installed and if not, you can download it from here https://www.mongodb.com/download-center/community

PHPMyAdmin Default login password

Default is:

Username: root

Password: [null]

The Password is set to 'password' in some versions.

Split Div Into 2 Columns Using CSS

Best way to divide a div vertically --

#parent {
    margin: 0;
    width: 100%;
}
.left {
    float: left;
    width: 60%;
}
.right {
    overflow: hidden;
    width: 40%;
}

how do I join two lists using linq or lambda expressions

The way to do this using the Extention Methods, instead of the linq query syntax would be like this:

var results = workOrders.Join(plans,
  wo => wo.WorkOrderNumber,
  p => p.WorkOrderNumber,
  (order,plan) => new {order.WorkOrderNumber, order.WorkDescription, plan.ScheduledDate}
);

How to use relative paths without including the context root name?

This is a derivative of @Ralph suggestion that I've been using. Add the c:url to the top of your JSP.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:url value="/" var="root" />

Then just reference the root variable in your page:

<link rel="stylesheet" href="${root}templates/style/main.css">

Do I use <img>, <object>, or <embed> for SVG files?

I recommend using the combination of

<svg viewBox="" width="" height="">
<path fill="#xxxxxx" d="M203.3,71.6c-.........."></path>
</svg>

Getting the last element of a split string array

You can access the array index directly:

var csv = 'zero,one,two,three'; csv.split(',')[0]; //result: zero csv.split(',')[3]; //result: three

convert string date to java.sql.Date

worked for me too:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date parsed = null;
    try {
        parsed = sdf.parse("02/01/2014");
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    java.sql.Date data = new java.sql.Date(parsed.getTime());
    contato.setDataNascimento( data);

    // Contato DataNascimento era Calendar
    //contato.setDataNascimento(Calendar.getInstance());         

    // grave nessa conexão!!! 
    ContatoDao dao = new ContatoDao("mysql");           

    // método elegante 
    dao.adiciona(contato); 
    System.out.println("Banco: ["+dao.getNome()+"] Gravado! Data: "+contato.getDataNascimento());

Could not open input file: composer.phar

Instead of

php composer.phar create-project --repository-url="http://packages.zendframework.com" zendframework/skeleton-application path/to/install

use

php composer.phar create-project --repository-url="https://packages.zendframework.com" zendframework/skeleton-application path/to/install

Just add https instead of http in the URL. Though it's not a permanent solution, it does work.

How to use the unsigned Integer in Java 8 and Java 9?

There is no way how to declare an unsigned long or int in Java 8 or Java 9. But some methods treat them as if they were unsigned, for example:

static long values = Long.parseUnsignedLong("123456789012345678");

but this is not declaration of the variable.

Remove leading zeros from a number in Javascript

It is not clear why you want to do this. If you want to get the correct numerical value, you could use unary + [docs]:

value = +value;

If you just want to format the text, then regex could be better. It depends on the values you are dealing with I'd say. If you only have integers, then

input.value = +input.value;

is fine as well. Of course it also works for float values, but depending on how many digits you have after the point, converting it to a number and back to a string could (at least for displaying) remove some.

Set value of hidden field in a form using jQuery's ".val()" doesn't work

If you are searching for haml then this is the answer for hidden field to set value to a hidden field like

%input#forum_id.hidden

In your jquery just convert the value to string and then append it using attr property in jquery. hope this also works in other languages also.

$('#forum_id').attr('val',forum_id.toString());

Enums in Javascript with ES6

Check how TypeScript does it. Basically they do the following:

const MAP = {};

MAP[MAP[1] = 'A'] = 1;
MAP[MAP[2] = 'B'] = 2;

MAP['A'] // 1
MAP[1] // A

Use symbols, freeze object, whatever you want.

Can you Run Xcode in Linux?

The easiest option to do that is running a VM with a OSX copy.

Best way to get the max value in a Spark dataframe column

Max value for a particular column of a dataframe can be achieved by using -

your_max_value = df.agg({"your-column": "max"}).collect()[0][0]

How to use timeit module

Example of how to use Python REPL interpreter with function that accepts parameters.

>>> import timeit                                                                                         

>>> def naive_func(x):                                                                                    
...     a = 0                                                                                             
...     for i in range(a):                                                                                
...         a += i                                                                                        
...     return a                                                                                          

>>> def wrapper(func, *args, **kwargs):                                                                   
...     def wrapper():                                                                                    
...         return func(*args, **kwargs)                                                                  
...     return wrapper                                                                                    

>>> wrapped = wrapper(naive_func, 1_000)                                                                  

>>> timeit.timeit(wrapped, number=1_000_000)                                                              
0.4458435332577161                                                                                        

What is the correct SQL type to store a .Net Timespan with values > 24:00:00?

I would store the timespan.TotalSeconds in a float and then retrieve it using Timespan.FromSeconds(totalSeconds).

Depending on the resolution you need you could use TotalMilliseconds, TotalMinutes, TotalDays.

You could also adjust the precision of your float in the database.

It's not an exact value... but the nice thing about this is that it's easy to read and calculate in simple queries.

setInterval in a React app

Updated 10-second countdown using class Clock extends Component

import React, { Component } from 'react';

class Clock extends Component {
  constructor(props){
    super(props);
    this.state = {currentCount: 10}
  }
  timer() {
    this.setState({
      currentCount: this.state.currentCount - 1
    })
    if(this.state.currentCount < 1) { 
      clearInterval(this.intervalId);
    }
  }
  componentDidMount() {
    this.intervalId = setInterval(this.timer.bind(this), 1000);
  }
  componentWillUnmount(){
    clearInterval(this.intervalId);
  }
  render() {
    return(
      <div>{this.state.currentCount}</div>
    );
  }
}

module.exports = Clock;

How do I measure a time interval in C?

If your Linux system supports it, clock_gettime(CLOCK_MONOTONIC) should be a high resolution timer that is unaffected by system date changes (e.g. NTP daemons).

What's the simplest way of detecting keyboard input in a script from the terminal?

Inspired from code found above (credits), the simple blocking (aka not CPU consuming) macOS version I was looking for:

import termios
import sys
import fcntl
import os

def getKeyCode(blocking = True):
    fd = sys.stdin.fileno()
    oldterm = termios.tcgetattr(fd)
    newattr = termios.tcgetattr(fd)
    newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
    termios.tcsetattr(fd, termios.TCSANOW, newattr)
    if not blocking:
        oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
        fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
    try:
        return ord(sys.stdin.read(1))
    except IOError:
        return 0
    finally:
        termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
        if not blocking:
            fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)

def getKeyStroke():
    code  = getKeyCode()
    if code == 27:
        code2 = getKeyCode(blocking = False)
        if code2 == 0:
            return "esc"
        elif code2 == 91:
            code3 = getKeyCode(blocking = False)
            if code3 == 65:
                return "up"
            elif code3 == 66:
                return "down"
            elif code3 == 68:
                return "left"
            elif code3 == 67:
                return "right"
            else:
                return "esc?"
    elif code == 127:
        return "backspace"
    elif code == 9:
        return "tab"
    elif code == 10:
        return "return"
    elif code == 195 or code == 194:        
        code2 = getKeyCode(blocking = False)
        return chr(code)+chr(code2) # utf-8 char
    else:
        return chr(code)


while True:
    print getKeyStroke()

2017-11-09, EDITED: Not tested with Python 3

Generate random int value from 3 to 6

Nice and simple, from Pinal Dave's site:

http://blog.sqlauthority.com/2007/04/29/sql-server-random-number-generator-script-sql-query/

DECLARE @Random INT;
DECLARE @Upper INT;
DECLARE @Lower INT
SET @Lower = 3 ---- The lowest random number
SET @Upper = 7 ---- One more than the highest random number
SELECT @Random = ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0)
SELECT @Random

(I did make a slight change to the @Upper- to include the upper number, added 1.)

What is the difference between a stored procedure and a view?

A view is a simple way to save a complex SELECT in the database.

A store procedure is used when simple SQL just isn't enough. Store procedures contain variables, loops and calls to other stored procedures. It's a programming language, not a query language.

  1. Views are static. Think of them as new tables with a certain layout and the data in them is created on the fly using the query you created it with. As with any SQL table, you can sort and filter it with WHERE, GROUP BY and ORDER BY.

  2. The depends on what you do.

  3. The depends on the database. Simple views just run the query and filter the result. But databases like Oracle allow to create a "materialized" view which is basically a table which is updated automatically when the underlying data of the view changes.

    A materialized view allows you to create indexes on the columns of the view (especially on the computed columns which don't exist anywhere in the database).

  4. I don't understand what you're talking about.

Visual Studio: How to break on handled exceptions?

Took me a while to find the new place for expection settings, therefore a new answer.

Since Visual Studio 2015 you control which Exceptions to stop on in the Exception Settings Window (Debug->Windows->Exception Settings). The shortcut is still Ctrl-Alt-E.

The simplest way to handle custom exceptions is selecting "all exceptions not in this list".

Here is a screenshot from the english version:

enter image description here

Here is a screenshot from the german version:

enter image description here

What is the HTML tabindex attribute?

the values you set determine the order that your keyboard focus will move between elements on the website.

In the following example, the first time you press tab, your cursor will move to #foo, then #awesome, then #bar

<input id="foo" tabindex="1"  />
<input id="bar" tabindex="3"  />
<input id="awesome" tabindex="2"  />

If you have not defined tab indexes anywhere, the keyboard focus will follow the HTML tags of you page in the order in which they are defined in the HTML document.

If you tab more times than you have specified tabindexes for, the focus will move as if there were no tabindexes, i.e. in the order of appearance of the HTML tags

What is the difference between an int and a long in C++?

The C++ specification itself (old version but good enough for this) leaves this open.

There are four signed integer types: 'signed char', 'short int', 'int', and 'long int'. In this list, each type provides at least as much storage as those preceding it in the list. Plain ints have the natural size suggested by the architecture of the execution environment* ;

[Footnote: that is, large enough to contain any value in the range of INT_MIN and INT_MAX, as defined in the header <climits>. --- end foonote]

Convert pyspark string to date format

Update (1/10/2018):

For Spark 2.2+ the best way to do this is probably using the to_date or to_timestamp functions, which both support the format argument. From the docs:

>>> from pyspark.sql.functions import to_timestamp
>>> df = spark.createDataFrame([('1997-02-28 10:30:00',)], ['t'])
>>> df.select(to_timestamp(df.t, 'yyyy-MM-dd HH:mm:ss').alias('dt')).collect()
[Row(dt=datetime.datetime(1997, 2, 28, 10, 30))]

Original Answer (for Spark < 2.2)

It is possible (preferrable?) to do this without a udf:

from pyspark.sql.functions import unix_timestamp, from_unixtime

df = spark.createDataFrame(
    [("11/25/1991",), ("11/24/1991",), ("11/30/1991",)], 
    ['date_str']
)

df2 = df.select(
    'date_str', 
    from_unixtime(unix_timestamp('date_str', 'MM/dd/yyy')).alias('date')
)

print(df2)
#DataFrame[date_str: string, date: timestamp]

df2.show(truncate=False)
#+----------+-------------------+
#|date_str  |date               |
#+----------+-------------------+
#|11/25/1991|1991-11-25 00:00:00|
#|11/24/1991|1991-11-24 00:00:00|
#|11/30/1991|1991-11-30 00:00:00|
#+----------+-------------------+

Java converting Image to BufferedImage

One way to handle this is to create a new BufferedImage, and tell it's graphics object to draw your scaled image into the new BufferedImage:

final float FACTOR  = 4f;
BufferedImage img = ImageIO.read(new File("graphic.png"));
int scaleX = (int) (img.getWidth() * FACTOR);
int scaleY = (int) (img.getHeight() * FACTOR);
Image image = img.getScaledInstance(scaleX, scaleY, Image.SCALE_SMOOTH);
BufferedImage buffered = new BufferedImage(scaleX, scaleY, TYPE);
buffered.getGraphics().drawImage(image, 0, 0 , null);

That should do the trick without casting.

How do I fix the multiple-step OLE DB operation errors in SSIS?

Also check if the script has no batch seperator commands (remove the 'GO' statements on a single line).

Chrome Extension - Get DOM content

For those who tried gkalpak answer and it did not work,

be aware that chrome will add the content script to a needed page only when your extension enabled during chrome launch and also a good idea restart browser after making these changes

image size (drawable-hdpi/ldpi/mdpi/xhdpi)

See the image for reference :- (Soruce :- Android Studio-Image Assets option and Android Office Site )

enter image description here

What is the proper way to re-attach detached objects in Hibernate?

I did it that way in C# with NHibernate, but it should work the same way in Java:

public virtual void Attach()
{
    if (!HibernateSessionManager.Instance.GetSession().Contains(this))
    {
        ISession session = HibernateSessionManager.Instance.GetSession();
        using (ITransaction t = session.BeginTransaction())
        {
            session.Lock(this, NHibernate.LockMode.None);
            t.Commit();
        }
    }
}

First Lock was called on every object because Contains was always false. The problem is that NHibernate compares objects by database id and type. Contains uses the equals method, which compares by reference if it's not overwritten. With that equals method it works without any Exceptions:

public override bool Equals(object obj)
{
    if (this == obj) { 
        return true;
    } 
    if (GetType() != obj.GetType()) {
        return false;
    }
    if (Id != ((BaseObject)obj).Id)
    {
        return false;
    }
    return true;
}

Attribute Error: 'list' object has no attribute 'split'

what i did was a quick fix by converting readlines to string but i do not recommencement it but it works and i dont know if there are limitations or not

`def getQuakeData():
    filename = input("Please enter the quake file: ")
    readfile = open(filename, "r")
    readlines = str(readfile.readlines())

    Type = readlines.split(",")
    x = Type[1]
    y = Type[2]
    for points in Type:
        print(x,y)
getQuakeData()`

How do I make a Mac Terminal pop-up/alert? Applescript?

Simple Notification

osascript -e 'display notification "hello world!"'

Notification with title

osascript -e 'display notification "hello world!" with title "This is the title"'

Notify and make sound

osascript -e 'display notification "hello world!" with title "Greeting" sound name "Submarine"'

Notification with variables

osascript -e 'display notification "'"$TR_TORRENT_NAME has finished downloading!"'" with title " ? Transmission-daemon"'

credits: https://code-maven.com/display-notification-from-the-mac-command-line

How To Define a JPA Repository Query with a Join

You are experiencing this issue for two reasons.

  • The JPQL Query is not valid.
  • You have not created an association between your entities that the underlying JPQL query can utilize.

When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)

User.java

@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="iduser")
    private Long idUser;

    @Column(name="user_name")
    private String userName;

    @OneToOne()
    @JoinColumn(name="idarea")
    private Area area;

    public Long getIdUser() {
        return idUser;
    }

    public void setIdUser(Long idUser) {
        this.idUser = idUser;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Area getArea() {
        return area;
    }

    public void setArea(Area area) {
        this.area = area;
    }
}

Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:

@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")

While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.

Area.java

@Entity
@Table(name = "area")
public class Area {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="idarea")
    private Long idArea;

    @Column(name="area_name")
    private String areaName;

    @OneToOne(fetch=FetchType.LAZY, mappedBy="area")
    private User user;

    public Long getIdArea() {
        return idArea;
    }

    public void setIdArea(Long idArea) {
        this.idArea = idArea;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

Improve SQL Server query performance on large tables

There are a few issues with this query (and this apply to every query).

Lack of index

Lack of index on er101_upd_date_iso column is most important thing as Oded has already mentioned.

Without matching index (which lack of could cause table scan) there is no chance to run fast queries on big tables.

If you cannot add indexes (for various reasons including there is no point in creating index for just one ad-hoc query) I would suggest a few workarounds (which can be used for ad-hoc queries):

1. Use temporary tables

Create temporary table on subset (rows and columns) of data you are interested in. Temporary table should be much smaller that original source table, can be indexed easily (if needed) and can cached subset of data which you are interested in.

To create temporary table you can use code (not tested) like:

-- copy records from last month to temporary table
INSERT INTO
   #my_temporary_table
SELECT
    *
FROM
    er101_acct_order_dtl WITH (NOLOCK)
WHERE 
    er101_upd_date_iso > DATEADD(month, -1, GETDATE())

-- you can add any index you need on temp table
CREATE INDEX idx_er101_upd_date_iso ON #my_temporary_table(er101_upd_date_iso)

-- run other queries on temporary table (which can be indexed)
SELECT TOP 100
    * 
FROM 
    #my_temporary_table 
ORDER BY 
    er101_upd_date_iso DESC

Pros:

  • Easy to do for any subset of data.
  • Easy to manage -- it's temporary and it's table.
  • Doesn't affect overall system performance like view.
  • Temporary table can be indexed.
  • You don't have to care about it -- it's temporary :).

Cons:

  • It's snapshot of data -- but probably this is good enough for most ad-hoc queries.

2. Common table expression -- CTE

Personally I use CTE a lot with ad-hoc queries -- it's help a lot with building (and testing) a query piece by piece.

See example below (the query starting with WITH).

Pros:

  • Easy to build starting from big view and then selecting and filtering what really you need.
  • Easy to test.

Cons:

  • Some people dislike CDE -- CDE queries seem to be long and difficult to understand.

3. Create views

Similar to above, but create views instead of temporary tables (if you play often with the same queries and you have MS SQL version which supports indexed views.

You can create views or indexed views on subset of data you are interested in and run queries on view -- which should contain only interesting subset of data much smaller than the whole table.

Pros:

  • Easy to do.
  • It's up to date with source data.

Cons:

  • Possible only for defined subset of data.
  • Could be inefficient for large tables with high rate of updates.
  • Not so easy to manage.
  • Can affect overall system performance.
  • I am not sure indexed views are available in every version of MS SQL.

Selecting all columns

Running star query (SELECT * FROM) on big table is not good thing...

If you have large columns (like long strings) it takes a lot of time to read them from disk and pass by network.

I would try to replace * with column names which you really need.

Or, if you need all columns try to rewrite query to something like (using common data expression):

;WITH recs AS (
    SELECT TOP 100 
        id as rec_id -- select primary key only
    FROM 
        er101_acct_order_dtl 
    ORDER BY 
        er101_upd_date_iso DESC
)
SELECT
    er101_acct_order_dtl.*
FROM
    recs
    JOIN
      er101_acct_order_dtl
    ON
      er101_acct_order_dtl.id = recs.rec_id
ORDER BY 
    er101_upd_date_iso DESC 

Dirty reads

Last thing which could speed up the ad-hoc query is allowing dirty reads with table hint WITH (NOLOCK).

Instead of hint you can set transaction isolation level to read uncommited:

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

or set proper SQL Management Studio setting.

I assume for ad-hoc queries dirty reads is good enough.

How to sort an associative array by its values in Javascript?

Instead of correcting you on the semantics of an 'associative array', I think this is what you want:

function getSortedKeys(obj) {
    var keys = keys = Object.keys(obj);
    return keys.sort(function(a,b){return obj[b]-obj[a]});
}

for really old browsers, use this instead:

function getSortedKeys(obj) {
    var keys = []; for(var key in obj) keys.push(key);
    return keys.sort(function(a,b){return obj[b]-obj[a]});
}

You dump in an object (like yours) and get an array of the keys - eh properties - back, sorted descending by the (numerical) value of the, eh, values of the, eh, object.

This only works if your values are numerical. Tweek the little function(a,b) in there to change the sorting mechanism to work ascending, or work for string values (for example). Left as an exercise for the reader.

How to download a file from my server using SSH (using PuTTY on Windows)

if you install git with git bash, you get SCP available on windows.

Offline Speech Recognition In Android (JellyBean)

I would like to improve the guide that the answer https://stackoverflow.com/a/17674655/2987828 sends to its users, with images. It is the sentence "For those that it doesn't, this is the ‘guide’ I supply them with." that I want to improve.

The user should click on the four buttons highlighted in blue in these images:

Go to your Android Application Settings, select Languages and input, edit Settings of Google Voice typing, select Download Offline speech recognition, select your languages in the ALL tab.

Then the user can select any desired languages. When the download is done, he should disconnect from network, and then click on the "microphone" button of the keyboard.

It worked for me (android 4.1.2), then language recognition worked out of the box, without rebooting. I can now dictates instructions to the shell of Terminal Emulator ! And it is twice faster offline than online, on a padfone 2 from ASUS.

These images are licensed under cc by-sa 3.0 with attribution required to stackoverflow.com/a/21329845/2987828 ; you may hence add these images anywhere along with this attribution.

(This the standard policy of all images and texts at stackoverflow.com)

What's the difference between "end" and "exit sub" in VBA?

This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End and End Sub are not the same. They don't perform the same task.

End puts a stop to ALL code execution and you should almost always use Exit Sub (or Exit Function, respectively).

End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)

See also the MSDN dox for the End Statement

When executed, the End statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use the Stop statement instead. You can then resume execution while preserving the value of those variables.

Note The End statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.

Nor is End Sub and Exit Sub the same. End Sub can't be called in the same way Exit Sub can be, because the compiler doesn't allow it.

enter image description here

This again means you have to Exit Sub, which is a perfectly legal operation:

Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.

Additionally, and once you get the feel for how procedures work, obviously, End Sub does not clear any global variables. But it does clear local (Dim'd) variables:

End Sub
Terminates the definition of this procedure.

How to permanently export a variable in Linux?

On Ubuntu systems, use the following locations:

  1. System-wide persistent variables in the format of JAVA_PATH=/usr/local/java store in

    /etc/environment
    
  2. System-wide persistent variables that reference variables such as
    export PATH="$JAVA_PATH:$PATH" store in

    /etc/.bashrc
    
  3. User specific persistent variables in the format of PATH DEFAULT=/usr/bin:usr/local/bin store in

    ~/.pam_environment
    

For more details on #2, check this Ask Ubuntu answer. NOTE: #3 is the Ubuntu recommendation but may have security concerns in the real world.

how to remove new lines and returns from php string?

You need to place the \n in double quotes.
Inside single quotes it is treated as 2 characters '\' followed by 'n'

You need:

$str = str_replace("\n", '', $str);

A better alternative is to use PHP_EOL as:

$str = str_replace(PHP_EOL, '', $str);

Remove secure warnings (_CRT_SECURE_NO_WARNINGS) from projects by default in Visual Studio

Not automatically, no. You can create a project template as BlueWandered suggested or create a custom property sheet that you can use for your current and all future projects.

  1. Open up the Property Manager (View->Property Manager)
  2. In the Property Manager Right click on your project and select "Add New Project Property Sheet"
  3. Give it a name and create it in a common directory. The property sheet will be added to all build targets.
  4. Right click on the new property sheet and select "Properties". This will open up the properties and allow you to change the settings just like you would if you were editing them for a project.
  5. Go into "Common Properties->C/C++->Preprocessor"
  6. Edit the setting "Preprocessor Definitions" and add _CRT_SECURE_NO_WARNINGS.
  7. Save and you're done.

Now any time you create a new project, add this property sheet like so...

  1. Open up the Property Manager (View->Property Manager)
  2. In the Property Manager Right click on your project and select "Add Existing Project Property Sheet"

The benefit here is that not only do you get a single place to manage common settings but anytime you change the settings they get propagated to ALL projects that use it. This is handy if you have a lot of settings like _CRT_SECURE_NO_WARNINGS or libraries like Boost that you want to use in your projects.

How do synchronized static methods work in Java and can I use it for loading Hibernate entities?

To answer your question, yes it does: your synchronized method cannot be executed by more than one thread at a time.

ImportError: No module named pandas

I fixed the same problem with the below commands... Type python on your terminal. If you see python version 2.x then run these two commands to install pandas:

sudo python -m pip install wheel

and

sudo python -m pip install pandas

Else if you see python version 3.x then run these two commands to install pandas:

sudo python3 -m pip install wheel

and

sudo python3 -m pip install pandas

Good Luck!

I'm trying to use python in powershell

From the Python Guide, this is what worked for me (Python 2.7.9): [Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27\;C:\Python27\Scripts\", "User")

Printing an int list in a single line python3

If you write

a = [1, 2, 3, 4, 5]
print(*a, sep = ',')

You get this output: 1,2,3,4,5

Insert line break in wrapped cell via code

You could also use vbCrLf which corresponds to Chr(13) & Chr(10).

What are Maven goals and phases and what is their difference?

The definitions are detailed at the Maven site's page Introduction to the Build Lifecycle, but I have tried to summarize:

Maven defines 4 items of a build process:

  1. Lifecycle

    Three built-in lifecycles (aka build lifecycles): default, clean, site. (Lifecycle Reference)

  2. Phase

    Each lifecycle is made up of phases, e.g. for the default lifecycle: compile, test, package, install, etc.

  3. Plugin

    An artifact that provides one or more goals.

    Based on packaging type (jar, war, etc.) plugins' goals are bound to phases by default. (Built-in Lifecycle Bindings)

  4. Goal

    The task (action) that is executed. A plugin can have one or more goals.

    One or more goals need to be specified when configuring a plugin in a POM. Additionally, in case a plugin does not have a default phase defined, the specified goal(s) can be bound to a phase.

Maven can be invoked with:

  1. a phase (e.g clean, package)
  2. <plugin-prefix>:<goal> (e.g. dependency:copy-dependencies)
  3. <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal> (e.g. org.apache.maven.plugins:maven-compiler-plugin:3.7.0:compile)

with one or more combinations of any or all, e.g.:

mvn clean dependency:copy-dependencies package

Modifying location.hash without page scrolling

Here's my solution for history-enabled tabs:

    var tabContainer = $(".tabs"),
        tabsContent = tabContainer.find(".tabsection").hide(),
        tabNav = $(".tab-nav"), tabs = tabNav.find("a").on("click", function (e) {
                e.preventDefault();
                var href = this.href.split("#")[1]; //mydiv
                var target = "#" + href; //#myDiv
                tabs.each(function() {
                    $(this)[0].className = ""; //reset class names
                });
                tabsContent.hide();
                $(this).addClass("active");
                var $target = $(target).show();
                if ($target.length === 0) {
                    console.log("Could not find associated tab content for " + target);
                } 
                $target.removeAttr("id");
                // TODO: You could add smooth scroll to element
                document.location.hash = target;
                $target.attr("id", href);
                return false;
            });

And to show the last-selected tab:

var currentHashURL = document.location.hash;
        if (currentHashURL != "") { //a tab was set in hash earlier
            // show selected
            $(currentHashURL).show();
        }
        else { //default to show first tab
            tabsContent.first().show();
        }
        // Now set the tab to active
        tabs.filter("[href*='" + currentHashURL + "']").addClass("active");

Note the *= on the filter call. This is a jQuery-specific thing, and without it, your history-enabled tabs will fail.

How can I get the executing assembly version?

Product Version may be preferred if you're using versioning via GitVersion or other versioning software.

To get this from within your class library you can call System.Diagnostics.FileVersionInfo.ProductVersion:

using System.Diagnostics;
using System.Reflection;

//...

var assemblyLocation = Assembly.GetExecutingAssembly().Location;
var productVersion = FileVersionInfo.GetVersionInfo(assemblyLocation).ProductVersion

enter image description here

How do I use floating-point division in bash?

Well, before float was a time where fixed decimals logic was used:

IMG_WIDTH=100
IMG2_WIDTH=3
RESULT=$((${IMG_WIDTH}00/$IMG2_WIDTH))
echo "${RESULT:0:-2}.${RESULT: -2}"
33.33

Last line is a bashim, if not using bash, try this code instead:

IMG_WIDTH=100
IMG2_WIDTH=3
INTEGER=$(($IMG_WIDTH/$IMG2_WIDTH))
DECIMAL=$(tail -c 3 <<< $((${IMG_WIDTH}00/$IMG2_WIDTH)))
RESULT=$INTEGER.$DECIMAL
echo $RESULT
33.33

The rationale behind the code is: multiply by 100 before divide to get 2 decimals.

compilation error: identifier expected

You have not defined a method around your code.

import java.io.*;

public class details
{
    public static void main( String[] args )
    {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

In this case, I have assumed that you want your code to be executed in the main method of the class. It is, of course, possible that this code goes in any other method.

Regex: ignore case sensitivity

You can practice Regex In Visual Studio and Visual Studio Code using find/replace.

You need to select both Match Case and Regular Expressions for regex expressions with case. Else [A-Z] won't work.enter image description here

Visual Studio 2019 Community

Insert content into iFrame

Wait, are you really needing to render it using javascript?

Be aware that in HTML5 there is srcdoc, which can do that for you! (The drawback is that IE/EDGE does not support it yet https://caniuse.com/#feat=iframe-srcdoc)

See here [srcdoc]: https://www.w3schools.com/tags/att_iframe_srcdoc.asp

Another thing to note is that if you want to avoid the interference of the js code inside and outside you should consider using the sandbox mode.

See here [sandbox]: https://www.w3schools.com/tags/att_iframe_sandbox.asp

What are Keycloak's OAuth2 / OpenID Connect endpoints?

With version 1.9.3.Final, Keycloak has a number of OpenID endpoints available. These can be found at /auth/realms/{realm}/.well-known/openid-configuration. Assuming your realm is named demo, that endpoint will produce a JSON response similar to this.

{
  "issuer": "http://localhost:8080/auth/realms/demo",
  "authorization_endpoint": "http://localhost:8080/auth/realms/demo/protocol/openid-connect/auth",
  "token_endpoint": "http://localhost:8080/auth/realms/demo/protocol/openid-connect/token",
  "token_introspection_endpoint": "http://localhost:8080/auth/realms/demo/protocol/openid-connect/token/introspect",
  "userinfo_endpoint": "http://localhost:8080/auth/realms/demo/protocol/openid-connect/userinfo",
  "end_session_endpoint": "http://localhost:8080/auth/realms/demo/protocol/openid-connect/logout",
  "jwks_uri": "http://localhost:8080/auth/realms/demo/protocol/openid-connect/certs",
  "grant_types_supported": [
    "authorization_code",
    "implicit",
    "refresh_token",
    "password",
    "client_credentials"
  ],
  "response_types_supported": [
    "code",
    "none",
    "id_token",
    "token",
    "id_token token",
    "code id_token",
    "code token",
    "code id_token token"
  ],
  "subject_types_supported": [
    "public"
  ],
  "id_token_signing_alg_values_supported": [
    "RS256"
  ],
  "response_modes_supported": [
    "query",
    "fragment",
    "form_post"
  ],
  "registration_endpoint": "http://localhost:8080/auth/realms/demo/clients-registrations/openid-connect"
}

As far as I have found, these endpoints implement the Oauth 2.0 spec.

How do I flush the cin buffer?

I would prefer the C++ size constraints over the C versions:

// Ignore to the end of file
cin.ignore(std::numeric_limits<std::streamsize>::max())

// Ignore to the end of line
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

Had the exact same error in a procedure. It turns out the user running it (a technical user in our case) did not have sufficient rigths to create a temporary table.

EXEC sp_addrolemember 'db_ddladmin', 'username_here';

did the trick

Go build: "Cannot find package" (even though GOPATH is set)

It does not work because your foobar.go source file is not in a directory called foobar. go build and go install try to match directories, not source files.

  1. Set $GOPATH to a valid directory, e.g. export GOPATH="$HOME/go"
  2. Move foobar.go to $GOPATH/src/foobar/foobar.go and building should work just fine.

Additional recommended steps:

  1. Add $GOPATH/bin to your $PATH by: PATH="$GOPATH/bin:$PATH"
  2. Move main.go to a subfolder of $GOPATH/src, e.g. $GOPATH/src/test
  3. go install test should now create an executable in $GOPATH/bin that can be called by typing test into your terminal.

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

Override constructor of DbContext Try this :-

public DataContext(DbContextOptions<DataContext> option):base(option) {}

How to stop C++ console application from exiting immediately?

I usually just put a breakpoint on main()'s closing curly brace. When the end of the program is reached by whatever means the breakpoint will hit and you can ALT-Tab to the console window to view the output.

How to make function decorators and chain them together?

This answer has long been answered, but I thought I would share my Decorator class which makes writing new decorators easy and compact.

from abc import ABCMeta, abstractclassmethod

class Decorator(metaclass=ABCMeta):
    """ Acts as a base class for all decorators """

    def __init__(self):
        self.method = None

    def __call__(self, method):
        self.method = method
        return self.call

    @abstractclassmethod
    def call(self, *args, **kwargs):
        return self.method(*args, **kwargs)

For one I think this makes the behavior of decorators very clear, but it also makes it easy to define new decorators very concisely. For the example listed above, you could then solve it as:

class MakeBold(Decorator):
    def call():
        return "<b>" + self.method() + "</b>"

class MakeItalic(Decorator):
    def call():
        return "<i>" + self.method() + "</i>"

@MakeBold()
@MakeItalic()
def say():
   return "Hello"

You could also use it to do more complex tasks, like for instance a decorator which automatically makes the function get applied recursively to all arguments in an iterator:

class ApplyRecursive(Decorator):
    def __init__(self, *types):
        super().__init__()
        if not len(types):
            types = (dict, list, tuple, set)
        self._types = types

    def call(self, arg):
        if dict in self._types and isinstance(arg, dict):
            return {key: self.call(value) for key, value in arg.items()}

        if set in self._types and isinstance(arg, set):
            return set(self.call(value) for value in arg)

        if tuple in self._types and isinstance(arg, tuple):
            return tuple(self.call(value) for value in arg)

        if list in self._types and isinstance(arg, list):
            return list(self.call(value) for value in arg)

        return self.method(arg)


@ApplyRecursive(tuple, set, dict)
def double(arg):
    return 2*arg

print(double(1))
print(double({'a': 1, 'b': 2}))
print(double({1, 2, 3}))
print(double((1, 2, 3, 4)))
print(double([1, 2, 3, 4, 5]))

Which prints:

2
{'a': 2, 'b': 4}
{2, 4, 6}
(2, 4, 6, 8)
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

Notice that this example didn't include the list type in the instantiation of the decorator, so in the final print statement the method gets applied to the list itself, not the elements of the list.

WPF Label Foreground Color

I checked your XAML, it works fine - e.g. both labels have a gray foreground.
My guess is that you have some style which is affecting the way it looks...

Try moving your XAML to a brand-new window and see for yourself... Then, check if you have any themes or styles (in the Window.Resources for instance) which might be affecting the labels...

React.js: Set innerHTML vs dangerouslySetInnerHTML

Based on (dangerouslySetInnerHTML).

It's a prop that does exactly what you want. However they name it to convey that it should be use with caution

Find length of 2D array Python

Like this:

numrows = len(input)    # 3 rows in your example
numcols = len(input[0]) # 2 columns in your example

Assuming that all the sublists have the same length (that is, it's not a jagged array).

What operator is <> in VBA

Not Equal To


Before C came along and popularized !=, languages tended to use <> for not equal to.

At least, the various dialects of Basic did, and they predate C.

An even older and more unusual case is Fortran, which uses .NE., as in X .NE. Y.

Can gcc output C code after preprocessing?

Yes. Pass gcc the -E option. This will output preprocessed source code.

Comparing two arrays of objects, and exclude the elements who match values into new array in JS

well, this using lodash or vanilla javascript it depends on the situation.

but for just return the array that contains the duplicates it can be achieved by the following, offcourse it was taken from @1983

var result = result1.filter(function (o1) {
    return result2.some(function (o2) {
        return o1.id === o2.id; // return the ones with equal id
   });
});
// if you want to be more clever...
let result = result1.filter(o1 => result2.some(o2 => o1.id === o2.id));

How do I get column datatype in Oracle with PL-SQL with low privileges?

select t.data_type 
  from user_tab_columns t 
 where t.TABLE_NAME = 'xxx' 
   and t.COLUMN_NAME='aaa'

Bulk Insert into Oracle database: Which is better: FOR Cursor loop or a simple Select?

I would recommend the Select option because cursors take longer.
Also using the Select is much easier to understand for anyone who has to modify your query

Merging two images in C#/.NET

basically i use this in one of our apps: we want to overlay a playicon over a frame of a video:

Image playbutton;
try
{
    playbutton = Image.FromFile(/*somekindofpath*/);
}
catch (Exception ex)
{
    return;
}

Image frame;
try
{
    frame = Image.FromFile(/*somekindofpath*/);
}
catch (Exception ex)
{
    return;
}

using (frame)
{
    using (var bitmap = new Bitmap(width, height))
    {
        using (var canvas = Graphics.FromImage(bitmap))
        {
            canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
            canvas.DrawImage(frame,
                             new Rectangle(0,
                                           0,
                                           width,
                                           height),
                             new Rectangle(0,
                                           0,
                                           frame.Width,
                                           frame.Height),
                             GraphicsUnit.Pixel);
            canvas.DrawImage(playbutton,
                             (bitmap.Width / 2) - (playbutton.Width / 2),
                             (bitmap.Height / 2) - (playbutton.Height / 2));
            canvas.Save();
        }
        try
        {
            bitmap.Save(/*somekindofpath*/,
                        System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        catch (Exception ex) { }
    }
}

How can I make a TextArea 100% width without overflowing when padding is present in CSS?

If you're not too bothered about the width of the padding, this solution will actually keep the padding in percentages too..

textarea
{
    border:1px solid #999999;
    width:98%;
    margin:5px 0;
    padding:1%;
}

Not perfect, but you'll get some padding and the width adds up to 100% so its all good

How do I use a regex in a shell script?

I think this is what you want:

REGEX_DATE='^\d{2}[/-]\d{2}[/-]\d{4}$'

echo "$1" | grep -P -q $REGEX_DATE
echo $?

I've used the -P switch to get perl regex.

How to redirect a URL path in IIS?

Format the redirect URL in the following way:

stuff.mysite.org.uk$S$Q

The $S will say that any path must be applied to the new URL. $Q says that any parameter variables must be passed to the new URL.

In IIS 7.0, you must enable the option Redirect to exact destination. I believe there must be an option like this in IIS 6.0 too.

Retrieving an element from array list in Android?

In arraylist you have a positional order and not a nominal order, so you need to know in advance the element position you need to select or you must loop between elements until you find the element that you need to use. To do this you can use an iterator and an if, for example:

Iterator iter = list.iterator();
while (iter.hasNext())
{
    // if here          
    System.out.println("string " + iter.next());
}