Programs & Examples On #Visual styles

Calling method using JavaScript prototype

if you define a function like this (using OOP)

function Person(){};
Person.prototype.say = function(message){
   console.log(message);
}

there is two ways to call a prototype function: 1) make an instance and call the object function:

var person = new Person();
person.say('hello!');

and the other way is... 2) is calling the function directly from the prototype:

Person.prototype.say('hello there!');

Resize image proportionally with MaxHeight and MaxWidth constraints

Much longer solution, but accounts for the following scenarios:

  1. Is the image smaller than the bounding box?
  2. Is the Image and the Bounding Box square?
  3. Is the Image square and the bounding box isn't
  4. Is the image wider and taller than the bounding box
  5. Is the image wider than the bounding box
  6. Is the image taller than the bounding box

    private Image ResizePhoto(FileInfo sourceImage, int desiredWidth, int desiredHeight)
    {
        //throw error if bouning box is to small
        if (desiredWidth < 4 || desiredHeight < 4)
            throw new InvalidOperationException("Bounding Box of Resize Photo must be larger than 4X4 pixels.");            
        var original = Bitmap.FromFile(sourceImage.FullName);
    
        //store image widths in variable for easier use
        var oW = (decimal)original.Width;
        var oH = (decimal)original.Height;
        var dW = (decimal)desiredWidth;
        var dH = (decimal)desiredHeight;
    
        //check if image already fits
        if (oW < dW && oH < dH)
            return original; //image fits in bounding box, keep size (center with css) If we made it bigger it would stretch the image resulting in loss of quality.
    
        //check for double squares
        if (oW == oH && dW == dH)
        {
            //image and bounding box are square, no need to calculate aspects, just downsize it with the bounding box
            Bitmap square = new Bitmap(original, (int)dW, (int)dH);
            original.Dispose();
            return square;
        }
    
        //check original image is square
        if (oW == oH)
        {
            //image is square, bounding box isn't.  Get smallest side of bounding box and resize to a square of that center the image vertically and horizontally with Css there will be space on one side.
            int smallSide = (int)Math.Min(dW, dH);
            Bitmap square = new Bitmap(original, smallSide, smallSide);
            original.Dispose();
            return square;
        }
    
        //not dealing with squares, figure out resizing within aspect ratios            
        if (oW > dW && oH > dH) //image is wider and taller than bounding box
        {
            var r = Math.Min(dW, dH) / Math.Min(oW, oH); //two dimensions so figure out which bounding box dimension is the smallest and which original image dimension is the smallest, already know original image is larger than bounding box
            var nH = oH * r; //will downscale the original image by an aspect ratio to fit in the bounding box at the maximum size within aspect ratio.
            var nW = oW * r;
            var resized = new Bitmap(original, (int)nW, (int)nH);
            original.Dispose();
            return resized;
        }
        else
        {
            if (oW > dW) //image is wider than bounding box
            {
                var r = dW / oW; //one dimension (width) so calculate the aspect ratio between the bounding box width and original image width
                var nW = oW * r; //downscale image by r to fit in the bounding box...
                var nH = oH * r;
                var resized = new Bitmap(original, (int)nW, (int)nH);
                original.Dispose();
                return resized;
            }
            else
            {
                //original image is taller than bounding box
                var r = dH / oH;
                var nH = oH * r;
                var nW = oW * r;
                var resized = new Bitmap(original, (int)nW, (int)nH);
                original.Dispose();
                return resized;
            }
        }
    }
    

Why does z-index not work?

Your elements need to have a position attribute. (e.g. absolute, relative, fixed) or z-index won't work.

Change the Theme in Jupyter Notebook?

Follow these steps

Install jupyterthemes with pip:

pip install jupyterthemes

Then Choose the themes from the following and set them using the following command, Once you have installed successfully, Many of us thought we need to start the jupyter server again, just refresh the page.

Set the theme with the following command:

jt -t <theme-name>

Available themes:

  • onedork
  • grade3
  • oceans16
  • chesterish
  • monokai
  • solarizedl
  • solarizedd

Screens of the available themes are also available in the Github repository.

Anaconda / Python: Change Anaconda Prompt User Path

In both: Anaconda prompt and the old cmd.exe, you change your directory by first changing to the drive you want, by simply writing its name followed by a ':', exe: F: , which will take you to the drive named 'F' on your machine. Then using the command cd to navigate your way inside that drive as you normally would.

Git commit with no commit message

Git requires a commit to have a comment, otherwise it wont accept the commit.

You can configure a default template with git as your default commit message or can look up the --allow-empty-message flag in git. I think (not 100% sure) you can reconfigure git to accept empty commit messages (which isn´t such a good idea). Normally each commit should be a bit of work which is described by your message.

Setting individual axis limits with facet_wrap and scales = "free" in ggplot2

I am not sure I understand what you want, but based on what I understood

the x scale seems to be the same, it is the y scale that is not the same, and that is because you specified scales ="free"

you can specify scales = "free_x" to only allow x to be free (in this case it is the same as pred has the same range by definition)

p <- ggplot(plot, aes(x = pred, y = value)) + geom_point(size = 2.5) + theme_bw()
p <- p + facet_wrap(~variable, scales = "free_x")

worked for me, see the picture

enter image description here

I think you were making it too difficult - I do seem to remember one time defining the limits based on a formula with min and max and if faceted I think it used only those values, but I can't find the code

Controlling mouse with Python

Linux

from Xlib import X, display
d = display.Display()
s = d.screen()
root = s.root
root.warp_pointer(300,300)
d.sync()

Source: Python mouse move in 5 lines of code (Linux only).

Test for array of string type in TypeScript

You cannot test for string[] in the general case but you can test for Array quite easily the same as in JavaScript https://stackoverflow.com/a/767492/390330

If you specifically want for string array you can do something like:

if (Array.isArray(value)) {
   var somethingIsNotString = false;
   value.forEach(function(item){
      if(typeof item !== 'string'){
         somethingIsNotString = true;
      }
   })
   if(!somethingIsNotString && value.length > 0){
      console.log('string[]!');
   }
}

How to multiply a BigDecimal by an integer in Java

If I were you, I would set the scale of the BigDecimal so that I dont end up on lengthy numbers. The integer 2 in the BigDecimal initialization below sets the scale.

Since you have lots of mismatch of data type, I have changed it accordingly to adjust.

class Payment   
{
      BigDecimal itemCost=new BigDecimal(BigInteger.ZERO,  2);
      BigDecimal totalCost=new BigDecimal(BigInteger.ZERO,  2);

     public BigDecimal calculateCost(int itemQuantity,BigDecimal itemPrice)
       { 
           BigDecimal   itemCost = itemPrice.multiply(new BigDecimal(itemQuantity)); 
             return totalCost.add(itemCost); 
       }
  }

BigDecimals are Object , not primitives, so make sure you initialize itemCost and totalCost , otherwise it can give you nullpointer while you try to add on totalCost or itemCost

How do I measure the execution time of JavaScript code with callbacks?

Invoking console.time('label') will record the current time in milliseconds, then later calling console.timeEnd('label') will display the duration from that point.

The time in milliseconds will be automatically printed alongside the label, so you don't have to make a separate call to console.log to print a label:

console.time('test');
//some code
console.timeEnd('test'); //Prints something like that-> test: 11374.004ms

For more information, see Mozilla's developer docs on console.time.

Good tool for testing socket connections?

Try Wireshark or WebScarab second is better for interpolating data into the exchange (not sure Wireshark even can). Anyway, one of them should be able to help you out.

How do I remove a specific element from a JSONArray?

In case if someone returns with the same question for Android platform, you cannot use the inbuilt remove() method if you are targeting for Android API-18 or less. The remove() method is added on API level 19. Thus, the best possible thing to do is to extend the JSONArray to create a compatible override for the remove() method.

public class MJSONArray extends JSONArray {

    @Override
    public Object remove(int index) {

        JSONArray output = new JSONArray();     
        int len = this.length(); 
        for (int i = 0; i < len; i++)   {
            if (i != index) {
                try {
                    output.put(this.get(i));
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
            }
        } 
        return output;
        //return this; If you need the input array in case of a failed attempt to remove an item.
     }
}

EDIT As Daniel pointed out, handling an error silently is bad style. Code improved.

How does lock work exactly?

The lock statement is translated by C# 3.0 to the following:

var temp = obj;

Monitor.Enter(temp);

try
{
    // body
}
finally
{
    Monitor.Exit(temp);
}

In C# 4.0 this has changed and it is now generated as follows:

bool lockWasTaken = false;
var temp = obj;
try
{
    Monitor.Enter(temp, ref lockWasTaken);
    // body
}
finally
{
    if (lockWasTaken)
    {
        Monitor.Exit(temp); 
    }
}

You can find more info about what Monitor.Enter does here. To quote MSDN:

Use Enter to acquire the Monitor on the object passed as the parameter. If another thread has executed an Enter on the object but has not yet executed the corresponding Exit, the current thread will block until the other thread releases the object. It is legal for the same thread to invoke Enter more than once without it blocking; however, an equal number of Exit calls must be invoked before other threads waiting on the object will unblock.

The Monitor.Enter method will wait infinitely; it will not time out.

How to fix 'Microsoft Excel cannot open or save any more documents'

If none of the above worked, try these as well:

  • In Component services >Computes >My Computer>Dcom config>Microsoft Excel Application>Properties, go to security tab, click on customize on all three sections and add the user that want to run the application, and give full permissions to the user.

  • Go to C:\Windows\Temp make sure it exists and it doesn't prompt you for entering.

Working with time DURATION, not time of day

Use format d "days" h:mm:ss or [h]:mm:ss, depending on your needs.

Say you have a duration of 30h 12m 54s:

  • h:mm:ss -> 6:12:54 (not correct for a duration)
  • [h]:mm:ss -> 30:12:54
  • d "days" h:mm:ss -> 1 days 6:12:54

Variations are possible: I like something like d"d" h"h" mm"m" ss"s" which formats as 1d 6h 12m 54s.

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

The more secure option would be to add allowedHosts to your Webpack config like this:

module.exports = {
devServer: {
 allowedHosts: [
  'host.com',
  'subdomain.host.com',
  'subdomain2.host.com',
  'host2.com'
   ]
  }
};

The array contains all allowed host, you can also specify subdomians. check out more here

OnClickListener in Android Studio

Button button= (Button) findViewById(R.id.standingsButton);
button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        startActivity(new Intent(MainActivity.this,StandingsActivity.class));
    }
});

This code is not in any method. If you want to use it, it must be within a method like OnCreate()

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button button= (Button) findViewById(R.id.standingsButton);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this,StandingsActivity.class));
        }
    });
}

What is the difference between include and require in Ruby?

From the Metaprogramming Ruby book,

The require() method is quite similar to load(), but it’s meant for a different purpose. You use load() to execute code, and you use require() to import libraries.

@ variables in Ruby on Rails

A tutorial about What is Variable Scope? presents some details quite well, just enclose the related here.


+------------------+----------------------+
| Name Begins With |    Variable Scope    |
+------------------+----------------------+
| $                | A global variable    |
| @                | An instance variable |
| [a-z] or _       | A local variable     |
| [A-Z]            | A constant           |
| @@               | A class variable     |
+------------------+----------------------+

how to prevent css inherit

The short story is that it's not possible to do what you want here. There's no CSS rule which is to "ignore some other rule". The only way around it is to write a more-specific CSS rule for the inner elements which reverts it to how it was before, which is a pain in the butt.

Take the example below:

<div class="red"> <!-- ignore the semantics, it's an example, yo! -->
    <p class="blue">
        Blue text blue text!
        <span class="notBlue">this shouldn't be blue</span>
    </p>
</div>
<div class="green">
    <p class="blue">
        Blue text!
        <span class="notBlue">blah</span>
    </p>
</div>

There's no way to make the .notBlue class revert to the parent styling. The best you can do is this:

.red, .red .notBlue {
    color: red;
}
.green, .green .notBlue {
    color: green;
}

How to check if input date is equal to today's date?

A simple date comparison in pure JS should be sufficient:

// Create date from input value
var inputDate = new Date("11/21/2011");

// Get today's date
var todaysDate = new Date();

// call setHours to take the time out of the comparison
if(inputDate.setHours(0,0,0,0) == todaysDate.setHours(0,0,0,0)) {
    // Date equals today's date
}

Here's a working JSFiddle.

How to read strings from a Scanner in a Java console application?

What you can do is use delimeter as new line. Till you press enter key you will be able to read it as string.

Scanner sc = new Scanner(System.in);
sc.useDelimiter(System.getProperty("line.separator"));

Hope this helps.

How to create enum like type in TypeScript?

As of TypeScript 0.9 (currently an alpha release) you can use the enum definition like this:

enum TShirtSize {
  Small,
  Medium,
  Large
}

var mySize = TShirtSize.Large;

By default, these enumerations will be assigned 0, 1 and 2 respectively. If you want to explicitly set these numbers, you can do so as part of the enum declaration.

Listing 6.2 Enumerations with explicit members

enum TShirtSize {
  Small = 3,
  Medium = 5,
  Large = 8
}

var mySize = TShirtSize.Large;

Both of these examples lifted directly out of TypeScript for JavaScript Programmers.

Note that this is different to the 0.8 specification. The 0.8 specification looked like this - but it was marked as experimental and likely to change, so you'll have to update any old code:

Disclaimer - this 0.8 example would be broken in newer versions of the TypeScript compiler.

enum TShirtSize {
  Small: 3,
  Medium: 5,
  Large: 8
}

var mySize = TShirtSize.Large;

Handling click events on a drawable within an EditText

I've taked the solution of @AZ_ and converted it in a kotlin extension function:

So copy this in your code:

@SuppressLint("ClickableViewAccessibility")
fun EditText.setDrawableRightTouch(setClickListener: () -> Unit) {
    this.setOnTouchListener(View.OnTouchListener { _, event ->
        val DRAWABLE_LEFT = 0
        val DRAWABLE_TOP = 1
        val DRAWABLE_RIGHT = 2
        val DRAWABLE_BOTTOM = 3
        if (event.action == MotionEvent.ACTION_UP) {
            if (event.rawX >= this.right - this.compoundDrawables[DRAWABLE_RIGHT].bounds.width()
            ) {
                setClickListener()
                return@OnTouchListener true
            }
        }
        false
    })
}

You can use it just calling the setDrawableRightTouch function on your EditText:

yourEditText.setDrawableRightTouch {
    //your code
}

how to convert string into dictionary in python 3.*?

  1. literal_eval, a somewhat safer version of eval (will only evaluate literals ie strings, lists etc):

    from ast import literal_eval
    
    python_dict = literal_eval("{'a': 1}")
    
  2. json.loads but it would require your string to use double quotes:

    import json
    
    python_dict = json.loads('{"a": 1}')
    

HTML text input field with currency symbol

For bootstrap its works

<span class="form-control">$ <input type="text"/></span>

Don't use class="form-control" in input field.

Map HTML to JSON

I got few links sometime back while reading on ExtJS full framework in itself is JSON.

http://www.thomasfrank.se/xml_to_json.html

http://camel.apache.org/xmljson.html

online XML to JSON converter : http://jsontoxml.utilities-online.info/

UPDATE BTW, To get JSON as added in question, HTML need to have type & content tags in it too like this or you need to use some xslt transformation to add these elements while doing JSON conversion

<?xml version="1.0" encoding="UTF-8" ?>
<type>div</type>
<content>
    <type>span</type>
    <content>Text2</content>
</content>
<content>Text2</content>

What EXACTLY is meant by "de-referencing a NULL pointer"?

Dereferencing just means reading the memory value at a given address. So when you have a pointer to something, to dereference the pointer means to read or write the data that the pointer points to.

In C, the unary * operator is the dereferencing operator. If x is a pointer, then *x is what x points to. The unary & operator is the address-of operator. If x is anything, then &x is the address at which x is stored in memory. The * and & operators are inverses of each other: if x is any data, and y is any pointer, then these equations are always true:

*(&x) == x
&(*y) == y

A null pointer is a pointer that does not point to any valid data (but it is not the only such pointer). The C standard says that it is undefined behavior to dereference a null pointer. This means that absolutely anything could happen: the program could crash, it could continue working silently, or it could erase your hard drive (although that's rather unlikely).

In most implementations, you will get a "segmentation fault" or "access violation" if you try to do so, which will almost always result in your program being terminated by the operating system. Here's one way a null pointer could be dereferenced:

int *x = NULL;  // x is a null pointer
int y = *x;     // CRASH: dereference x, trying to read it
*x = 0;         // CRASH: dereference x, trying to write it

And yes, dereferencing a null pointer is pretty much exactly like a NullReferenceException in C# (or a NullPointerException in Java), except that the langauge standard is a little more helpful here. In C#, dereferencing a null reference has well-defined behavior: it always throws a NullReferenceException. There's no way that your program could continue working silently or erase your hard drive like in C (unless there's a bug in the language runtime, but again that's incredibly unlikely as well).

angular 2 ngIf and CSS transition/animation

Am using angular 5 and for an ngif to work for me that is in a ngfor, I had to use animateChild and in the user-detail component I used the *ngIf="user.expanded" to show hide user and it worked for entering a leaving

 <div *ngFor="let user of users" @flyInParent>
  <ly-user-detail [user]= "user" @flyIn></user-detail>
</div>

//the animation file


export const FLIP_TRANSITION = [ 
trigger('flyInParent', [
    transition(':enter, :leave', [
      query('@*', animateChild())
    ])
  ]),
  trigger('flyIn', [
    state('void', style({width: '100%', height: '100%'})),
    state('*', style({width: '100%', height: '100%'})),
    transition(':enter', [
      style({
        transform: 'translateY(100%)',
        position: 'fixed'
      }),
      animate('0.5s cubic-bezier(0.35, 0, 0.25, 1)', style({transform: 'translateY(0%)'}))
    ]),
    transition(':leave', [
      style({
        transform: 'translateY(0%)',
        position: 'fixed'
      }),
      animate('0.5s cubic-bezier(0.35, 0, 0.25, 1)', style({transform: 'translateY(100%)'}))
    ])
  ])
];

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

Prevent saving changes that require table re-creation

Five swift clicks

Prevent saving changes that require table re-creation in five clicks

  1. Tools
  2. Options
  3. Designers
  4. Prevent saving changes that require table re-creation
  5. OK.

After saving, repeat the proceudure to re-tick the box. This safe-guards against accidental data loss.

Further explanation

  • By default SQL Server Management Studio prevents the dropping of tables, because when a table is dropped its data contents are lost.*

  • When altering a column's datatype in the table Design view, when saving the changes the database drops the table internally and then re-creates a new one.

*Your specific circumstances will not pose a consequence since your table is empty. I provide this explanation entirely to improve your understanding of the procedure.

How to retrieve form values from HTTPPOST, dictionary or?

The answers are very good but there is another way in the latest release of MVC and .NET that I really like to use, instead of the "old school" FormCollection and Request keys.


Consider a HTML snippet contained within a form tag that either does an AJAX or FORM POST.

<input type="hidden"   name="TrackingID" 
<input type="text"     name="FirstName"  id="firstnametext" />
<input type="checkbox" name="IsLegal"  value="Do you accept terms and conditions?" />

Your controller will actually parse the form data and try to deliver it to you as parameters of the defined type. I included checkbox because it is a tricky one. It returns text "on" if checked and null if not checked. The requirement though is that these defined variables MUST exists (unless nullable(remember though that string is nullable)) otherwise the AJAX or POST back will fail.

[HttpPost]
public ActionResult PostBack(int TrackingID, string FirstName, string IsLegal){
    MyData.SaveRequest(TrackingID,FirstName, IsLegal == null ? false : true);
}

You can also post back a model without using any razor helpers. I have come across that this is needed some times.

public Class HomeModel
{
  public int HouseNumber { get; set; }
  public string StreetAddress { get; set; }
}

The HTML markup will simply be ...

<input type="text" name="variableName.HouseNumber" id="whateverid" >

and your controller(Razor Engine) will intercept the Form Variable "variableName" (name is as you like but keep it consistent) and try to build it up and cast it to MyModel.

[HttpPost]
public ActionResult PostBack(HomeModel variableName){
    postBack.HouseNumber; //The value user entered
    postBack.StreetAddress; //the default value of NULL.
}

When a controller is expecting a Model (in this case HomeModel) you do not have to define ALL the fields as the parser will just leave them at default, usually NULL. The nice thing is you can mix and match various models on the Mark-up and the post back parse will populate as much as possible. You do not need to define a model on the page or use any helpers.

TIP: The name of the parameter in the controller is the name defined in the HTML mark-up "name=" not the name of the Model but the name of the expected variable in the !


Using List<> is bit more complex in its mark-up.

<input type="text" name="variableNameHere[0].HouseNumber" id="id"           value="0">
<input type="text" name="variableNameHere[1].HouseNumber" id="whateverid-x" value="1">
<input type="text" name="variableNameHere[2].HouseNumber"                   value="2">
<input type="text" name="variableNameHere[3].HouseNumber" id="whateverid22" value="3">

Index on List<> MUST always be zero based and sequential. 0,1,2,3.

[HttpPost]
public ActionResult PostBack(List<HomeModel> variableNameHere){
     int counter = MyHomes.Count()
     foreach(var home in MyHomes)
     { ... }
}

Using IEnumerable<> for non zero based and non sequential indices post back. We need to add an extra hidden input to help the binder.

<input type="hidden" name="variableNameHere.Index" value="278">
<input type="text" name="variableNameHere[278].HouseNumber" id="id"      value="3">

<input type="hidden" name="variableNameHere.Index" value="99976">
<input type="text" name="variableNameHere[99976].HouseNumber" id="id3"   value="4">

<input type="hidden" name="variableNameHere.Index" value="777">
<input type="text" name="variableNameHere[777].HouseNumber" id="id23"    value="5">

And the code just needs to use IEnumerable and call ToList()

[HttpPost]
public ActionResult PostBack(IEnumerable<MyModel> variableNameHere){
     int counter = variableNameHere.ToList().Count()
     foreach(var home in variableNameHere)
     { ... }
}

It is recommended to use a single Model or a ViewModel (Model contianing other models to create a complex 'View' Model) per page. Mixing and matching as proposed could be considered bad practice, but as long as it works and is readable its not BAD. It does however, demonstrate the power and flexiblity of the Razor engine.

So if you need to drop in something arbitrary or override another value from a Razor helper, or just do not feel like making your own helpers, for a single form that uses some unusual combination of data, you can quickly use these methods to accept extra data.

TypeScript and array reduce function

Reduce() is..

  • The reduce() method reduces the array to a single value.
  • The reduce() method executes a provided function for each value of the array (from left-to-right).
  • The return value of the function is stored in an accumulator (result/total).

It was ..

let array=[1,2,3];
function sum(acc,val){ return acc+val;} // => can change to (acc,val)=>acc+val
let answer= array.reduce(sum); // answer is 6

Change to

let array=[1,2,3];
let answer=arrays.reduce((acc,val)=>acc+val);

Also you can use in

  1. find max
    let array=[5,4,19,2,7];
    function findMax(acc,val)
    {
     if(val>acc){
       acc=val; 
     }
    }

    let biggest=arrays.reduce(findMax); // 19
  1. find an element that not repeated.
    arr = [1, 2, 5, 4, 6, 8, 9, 2, 1, 4, 5, 8, 9]
    v = 0
    for i in range(len(arr)):
    v = v ^ arr[i]
    print(value)  //6

Android ListView selected item stay highlighted

I found the proper way. It's very simple. In resource describe following:

android:choiceMode="singleChoice"
android:listSelector="#666666"

(or you may specify a resource link instead of color value)

Programmatical:

listView.setSelector(Drawable selector);
listView.setSelector(int resourceId);
listView.setChoiceMode(int mode);

mode can be one of these: AbsListView.CHOICE_MODE_SINGLE, AbsListView.CHOICE_MODE_MULTIPLE, AbsListView.CHOICE_MODE_NONE (default)

(AbsListView is the abstract ancestor for the ListView class)

P.S. manipulations with onItemClick and changing view background are bankrupt, because a view itself is a temporary object. Hence you must not to track a view.

If our list is long enough, the views associated with scrolled out items will be removed from hierarchy, and will be recreated when those items will shown again (with cached display options, such as background). So, the view we have tracked is now not an actual view of the item, and changing its background does nothing to the actual item view. As a result we have multiple items selected.

PowerShell Connect to FTP server and get files

Remote pick directory path should be the exact path on the ftp server you are tryng to access.. here is the script to download files from the server.. you can add or modify with SSLMode..

#ftp server 
$ftp = "ftp://example.com/" 
$user = "XX" 
$pass = "XXX"
$SetType = "bin"  
$remotePickupDir = Get-ChildItem 'c:\test' -recurse
$webclient = New-Object System.Net.WebClient 

$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)  
foreach($item in $remotePickupDir){ 
    $uri = New-Object System.Uri($ftp+$item.Name) 
    #$webclient.UploadFile($uri,$item.FullName)
    $webclient.DownloadFile($uri,$item.FullName)
}

How to read pdf file and write it to outputStream

You can use PdfBox from Apache which is simple to use and has good performance.

Here is an example of extracting text from a PDF file (you can read more here) :

import java.io.*;
import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.util.*;

public class PDFTest {

 public static void main(String[] args){
 PDDocument pd;
 BufferedWriter wr;
 try {
         File input = new File("C:\\Invoice.pdf");  // The PDF file from where you would like to extract
         File output = new File("C:\\SampleText.txt"); // The text file where you are going to store the extracted data
         pd = PDDocument.load(input);
         System.out.println(pd.getNumberOfPages());
         System.out.println(pd.isEncrypted());
         pd.save("CopyOfInvoice.pdf"); // Creates a copy called "CopyOfInvoice.pdf"
         PDFTextStripper stripper = new PDFTextStripper();
         wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output)));
         stripper.writeText(pd, wr);
         if (pd != null) {
             pd.close();
         }
        // I use close() to flush the stream.
        wr.close();
 } catch (Exception e){
         e.printStackTrace();
        } 
     }
}

UPDATE:

You can get the text using PDFTextStripper:

PDFTextStripper reader = new PDFTextStripper();
String pageText = reader.getText(pd); // PDDocument object created

PHP find difference between two datetimes

You can simply use datetime diff and format for calculating difference.

<?php
$datetime1 = new DateTime('2009-10-11 12:12:00');
$datetime2 = new DateTime('2009-10-13 10:12:00');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%Y-%m-%d %H:%i:%s');
?>

For more information OF DATETIME format, refer: here
You can change the interval format in the way,you want.

Here is the working example

P.S. These features( diff() and format()) work with >=PHP 5.3.0 only

"An access token is required to request this resource" while accessing an album / photo with Facebook php sdk

To get the actual access_token, you can also do pro grammatically via the following PHP code:

 require 'facebook.php';

 $facebook = new Facebook(array(
   'appId'  => 'YOUR_APP_ID',
   'secret' => 'YOUR_APP_SECRET',
 ));

 // Get User ID
 $user = $facebook->getUser();

 if ($user) {
   try {
     $user_profile = $facebook->api('/me');
     $access_token = $facebook->getAccessToken();
   } catch (FacebookApiException $e) {
     error_log($e);
     $user = null;
   }
 }

How to detect the character encoding of a text file?

You can't depend on the file having a BOM. UTF-8 doesn't require it. And non-Unicode encodings don't even have a BOM. There are, however, other ways to detect the encoding.

UTF-32

BOM is 00 00 FE FF (for BE) or FF FE 00 00 (for LE).

But UTF-32 is easy to detect even without a BOM. This is because the Unicode code point range is restricted to U+10FFFF, and thus UTF-32 units always have the pattern 00 {00-10} xx xx (for BE) or xx xx {00-10} 00 (for LE). If the data has a length that's a multiple of 4, and follows one of these patterns, you can safely assume it's UTF-32. False positives are nearly impossible due to the rarity of 00 bytes in byte-oriented encodings.

US-ASCII

No BOM, but you don't need one. ASCII can be easily identified by the lack of bytes in the 80-FF range.

UTF-8

BOM is EF BB BF. But you can't rely on this. Lots of UTF-8 files don't have a BOM, especially if they originated on non-Windows systems.

But you can safely assume that if a file validates as UTF-8, it is UTF-8. False positives are rare.

Specifically, given that the data is not ASCII, the false positive rate for a 2-byte sequence is only 3.9% (1920/49152). For a 7-byte sequence, it's less than 1%. For a 12-byte sequence, it's less than 0.1%. For a 24-byte sequence, it's less than 1 in a million.

UTF-16

BOM is FE FF (for BE) or FF FE (for LE). Note that the UTF-16LE BOM is found at the start of the UTF-32LE BOM, so check UTF-32 first.

If you happen to have a file that consists mainly of ISO-8859-1 characters, having half of the file's bytes be 00 would also be a strong indicator of UTF-16.

Otherwise, the only reliable way to recognize UTF-16 without a BOM is to look for surrogate pairs (D[8-B]xx D[C-F]xx), but non-BMP characters are too rarely-used to make this approach practical.

XML

If your file starts with the bytes 3C 3F 78 6D 6C (i.e., the ASCII characters "<?xml"), then look for an encoding= declaration. If present, then use that encoding. If absent, then assume UTF-8, which is the default XML encoding.

If you need to support EBCDIC, also look for the equivalent sequence 4C 6F A7 94 93.

In general, if you have a file format that contains an encoding declaration, then look for that declaration rather than trying to guess the encoding.

None of the above

There are hundreds of other encodings, which require more effort to detect. I recommend trying Mozilla's charset detector or a .NET port of it.

A reasonable default

If you've ruled out the UTF encodings, and don't have an encoding declaration or statistical detection that points to a different encoding, assume ISO-8859-1 or the closely related Windows-1252. (Note that the latest HTML standard requires a “ISO-8859-1” declaration to be interpreted as Windows-1252.) Being Windows' default code page for English (and other popular languages like Spanish, Portuguese, German, and French), it's the most commonly encountered encoding other than UTF-8.

JQuery - Get select value

val() returns the value of the <select> element, i.e. the value attribute of the selected <option> element.

Since you actually want the inner text of the selected <option> element, you should match that element and use text() instead:

var nationality = $("#dancerCountry option:selected").text();

Difference between Visual Basic 6.0 and VBA

It's VBA. VBA means Visual Basic for Applications, and it is used for macros on Office documents. It doesn't have access to VB.NET features, so it's more like a modified version of VB6, with add-ons to be able to work on the document (like Worksheet in VBA for Excel).

using jQuery .animate to animate a div from right to left?

so the .animate method works only if you have given a position attribute to an element, if not it didn't move?

for example i've seen that if i declare the div but i declare nothing in the css, it does not assume his default position and it does not move it into the page, even if i declare property margin: x w y z;

How to display loading image while actual image is downloading

Just add a background image to all images using css:

img {
  background: url('loading.gif') no-repeat;
}

What's the difference between implementation and compile in Gradle?

tl;dr

Just replace:

  • compile with implementation (if you don't need transitivity) or api (if you need transitivity)
  • testCompile with testImplementation
  • debugCompile with debugImplementation
  • androidTestCompile with androidTestImplementation
  • compileOnly is still valid. It was added in 3.0 to replace provided and not compile. (provided introduced when Gradle didn't have a configuration name for that use-case and named it after Maven's provided scope.)

It is one of the breaking changes coming with Android Gradle plugin 3.0 that Google announced at IO17.

The compile configuration is now deprecated and should be replaced by implementation or api

From the Gradle documentation:

dependencies {
    api 'commons-httpclient:commons-httpclient:3.1'
    implementation 'org.apache.commons:commons-lang3:3.5'
}

Dependencies appearing in the api configurations will be transitively exposed to consumers of the library, and as such will appear on the compile classpath of consumers.

Dependencies found in the implementation configuration will, on the other hand, not be exposed to consumers, and therefore not leak into the consumers' compile classpath. This comes with several benefits:

  • dependencies do not leak into the compile classpath of consumers anymore, so you will never accidentally depend on a transitive dependency
  • faster compilation thanks to reduced classpath size
  • less recompilations when implementation dependencies change: consumers would not need to be recompiled
  • cleaner publishing: when used in conjunction with the new maven-publish plugin, Java libraries produce POM files that distinguish exactly between what is required to compile against the library and what is required to use the library at runtime (in other words, don't mix what is needed to compile the library itself and what is needed to compile against the library).

The compile configuration still exists, but should not be used as it will not offer the guarantees that the api and implementation configurations provide.


Note: if you are only using a library in your app module -the common case- you won't notice any difference.
you will only see the difference if you have a complex project with modules depending on each other, or you are creating a library.

How do I execute cmd commands through a batch file?

@echo off
title Command Executer
color 1b

echo Command Executer by: YourNameHere
echo #################################
: execute
echo Please Type A Command Here:
set /p cmd=Command:
%cmd%
goto execute

List Git aliases

Another alternative (purely something I find easy to remember):

git config --list | grep alias

GCD to perform task in main thread

For the asynchronous dispatch case you describe above, you shouldn't need to check if you're on the main thread. As Bavarious indicates, this will simply be queued up to be run on the main thread.

However, if you attempt to do the above using a dispatch_sync() and your callback is on the main thread, your application will deadlock at that point. I describe this in my answer here, because this behavior surprised me when moving some code from -performSelectorOnMainThread:. As I mention there, I created a helper function:

void runOnMainQueueWithoutDeadlocking(void (^block)(void))
{
    if ([NSThread isMainThread])
    {
        block();
    }
    else
    {
        dispatch_sync(dispatch_get_main_queue(), block);
    }
}

which will run a block synchronously on the main thread if the method you're in isn't currently on the main thread, and just executes the block inline if it is. You can employ syntax like the following to use this:

runOnMainQueueWithoutDeadlocking(^{
    //Do stuff
});

Truncate with condition

As a response to your question: "i want to reset all the data and keep last 30 days inside the table."

you can create an event. Check https://dev.mysql.com/doc/refman/5.7/en/event-scheduler.html

For example:

CREATE EVENT DeleteExpiredLog
ON SCHEDULE EVERY 1 DAY
DO
DELETE FROM log WHERE date < DATE_SUB(NOW(), INTERVAL 30 DAY);

Will run a daily cleanup in your table, keeping the last 30 days data available

How to make canvas responsive

try using max-width: 100%; on your canvas.

canvas {
  max-width: 100%;
}

In C#, how to check whether a string contains an integer?

You could use char.IsDigit:

     bool isIntString = "your string".All(char.IsDigit)

Will return true if the string is a number

    bool containsInt = "your string".Any(char.IsDigit)

Will return true if the string contains a digit

How should strace be used?

In simple words, strace traces all system calls issued by a program along with their return codes. Think things such as file/socket operations and a lot more obscure ones.

It is most useful if you have some working knowledge of C since here system calls would more accurately stand for standard C library calls.

Let's say your program is /usr/local/bin/cough. Simply use:

strace /usr/local/bin/cough <any required argument for cough here>

or

strace -o <out_file> /usr/local/bin/cough <any required argument for cough here>

to write into 'out_file'.

All strace output will go to stderr (beware, the sheer volume of it often asks for a redirection to a file). In the simplest cases, your program will abort with an error and you'll be able to see what where its last interactions with the OS in strace output.

More information should be available with:

man strace

How to exit if a command failed?

Provided my_command is canonically designed, ie returns 0 when succeeds, then && is exactly the opposite of what you want. You want ||.

Also note that ( does not seem right to me in bash, but I cannot try from where I am. Tell me.

my_command || {
    echo 'my_command failed' ;
    exit 1; 
}

How can I exit from a javascript function?

Use this when if satisfies

do

return true;

Linux configure/make, --prefix?

In my situation, --prefix= failed to update the path correctly under some warnings or failures. please see the below link for the answer. https://stackoverflow.com/a/50208379/1283198

Float a div in top right corner without overlapping sibling header

This worked for me:

h1 {
    display: inline;
    overflow: hidden;
}
div {
    position: relative;
    float: right;
}

It's similar to the approach of the media object, by Stubbornella.

Edit: As they comment below, you need to place the element that's going to float before the element that's going to wrap (the one in your first fiddle)

Where is the php.ini file on a Linux/CentOS PC?

You can find the path to php.ini in the output of phpinfo(). See under "Loaded Configuration File".

enter image description here

bootstrap 3 wrap text content within div for horizontal alignment

Add the following style to your h3 elements:

word-wrap: break-word;

This will cause the long URLs in them to wrap. The default setting for word-wrap is normal, which will wrap only at a limited set of split tokens (e.g. whitespaces, hyphens), which are not present in a URL.

Understanding `scale` in R

I thought I would contribute by providing a concrete example of the practical use of the scale function. Say you have 3 test scores (Math, Science, and English) that you want to compare. Maybe you may even want to generate a composite score based on each of the 3 tests for each observation. Your data could look as as thus:

student_id <- seq(1,10)
math <- c(502,600,412,358,495,512,410,625,573,522)
science <- c(95,99,80,82,75,85,80,95,89,86)
english <- c(25,22,18,15,20,28,15,30,27,18)
df <- data.frame(student_id,math,science,english)

Obviously it would not make sense to compare the means of these 3 scores as the scale of the scores are vastly different. By scaling them however, you have more comparable scoring units:

z <- scale(df[,2:4],center=TRUE,scale=TRUE)

You could then use these scaled results to create a composite score. For instance, average the values and assign a grade based on the percentiles of this average. Hope this helped!

Note: I borrowed this example from the book "R In Action". It's a great book! Would definitely recommend.

Group by month and year in MySQL

This is how I do it:

GROUP BY  EXTRACT(YEAR_MONTH FROM t.summaryDateTime);

SQLite equivalent to ISNULL(), NVL(), IFNULL() or COALESCE()

Try this

ifnull(X,Y)  

e.g

select ifnull(InfoDetail,'') InfoDetail; -- this will replace null with ''
select ifnull(NULL,'THIS IS NULL');-- More clearly....

The ifnull() function returns a copy of its first non-NULL argument, or NULL if both arguments are NULL. Ifnull() must have exactly 2 arguments. The ifnull() function is equivalent to coalesce() with two arguments.

Angular 5, HTML, boolean on checkbox is checked

Here is my answer,

In row.model.ts

export interface Row {
   otherProperty : type;
   checked : bool;
   otherProperty : type;
   ...
}

In .html

<tr class="even" *ngFor="let item of rows">
   <input [checked]="item.checked" type="checkbox">
</tr>

In .ts

rows : Row[] = [];

update the rows in component.ts

What tool to use to draw file tree diagram

Graphviz - from the web page:

The Graphviz layout programs take descriptions of graphs in a simple text language, and make diagrams in several useful formats such as images and SVG for web pages, Postscript for inclusion in PDF or other documents; or display in an interactive graph browser. (Graphviz also supports GXL, an XML dialect.)

It's the simplest and most productive tool I've found to create a variety of boxes-and-lines diagrams. I have and use Visio and OmniGraffle, but there's always the temptation to make "just one more adjustment".

It's also quite easy to write code to produce the "dot file" format that Graphiz consumes, so automated diagram production is also nicely within reach.

Connection refused on docker container

In Windows, you also normally need to run command line as administrator.

As standard-user:

docker build -t myimage -f Dockerfile .
Sending build context to Docker daemon  106.8MB
Step 1/1 : FROM mcr.microsoft.com/dotnet/core/runtime:3.0
Get https://mcr.microsoft.com/v2/: dial tcp: lookup mcr.microsoft.com on [::1]:53: read udp [::1]:45540->[::1]:53: read: 
>>>connection refused

But as an administrator.

docker build -t myimage -f Dockerfile .
Sending build context to Docker daemon  106.8MB
Step 1/1 : FROM mcr.microsoft.com/dotnet/core/runtime:3.0
3.0: Pulling from dotnet/core/runtime
68ced04f60ab: Pull complete                                                                                             e936bd534ffb: Pull complete                                                                                             caf64655bcbb: Pull complete                                                                                             d1927dbcbcab: Pull complete                                                                                             Digest: sha256:e0c67764f530a9cad29a09816614c0129af8fe3bd550eeb4e44cdaddf8f5aa40
Status: Downloaded newer image for mcr.microsoft.com/dotnet/core/runtime:3.0
 ---> f059cd71a22a
Successfully built f059cd71a22a
Successfully tagged myimage:latest

Pretty git branch graphs

gitg: a gtk-based repository viewer, that's new but interesting and useful
http://git.gnome.org/browse/gitg
I use it currently

PostgreSQL wildcard LIKE for any of a list of words

One 'elegant' solution would be to use full text search: http://www.postgresql.org/docs/9.0/interactive/textsearch.html. Then you would use full text search queries.

How do I set adaptive multiline UILabel text?

Programmatically in Swift 5 with Xcode 10.2

Building on top of @La masse's solution, but using autolayout to support rotation

Set anchors for the view's position (left, top, centerY, centerX, etc). You can also set the width anchor or set the frame.width dynamically with the UIScreen extension provided (to support rotation)

label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
self.view.addSubview(label)
// SET AUTOLAYOUT ANCHORS
label.translatesAutoresizingMaskIntoConstraints = false
label.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 20).isActive = true
label.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -20).isActive = true
label.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 20).isActive = true
// OPTIONALLY, YOU CAN USE THIS INSTEAD OF THE WIDTH ANCHOR (OR LEFT/RIGHT)
// label.frame.size = CGSize(width: UIScreen.absoluteWidth() - 40.0, height: 0)
label.text = "YOUR LONG TEXT GOES HERE"
label.sizeToFit()

If setting frame.width dynamically using UIScreen:

extension UIScreen {   // OPTIONAL IF USING A DYNAMIC FRAME WIDTH
    class func absoluteWidth() -> CGFloat {
        var width: CGFloat
        if UIScreen.main.bounds.width > UIScreen.main.bounds.height {
            width = self.main.bounds.height // Landscape
        } else {
            width = self.main.bounds.width // Portrait
        }
        return width
    }
}

What version of Python is on my Mac?

If you have both Python2 and Python3 installed on your Mac, you can use

python --version

to check the version of Python2, and

python3 --version

to check the version of Python3.

However, if only Python3 is installed, then your system might use python instead of python3 for Python3. In this case, you can just use

python --version

to check the version of Python3.

Simulate string split function in Excel formula

=IFERROR(LEFT(A3, FIND(" ", A3, 1)), A3)

This will firstly check if the cell contains a space, if it does it will return the first value from the space, otherwise it will return the cell value.

Edit

Just to add to the above formula, as it stands if there is no value in the cell it would return 0. If you are looking to display a message or something to tell the user it is empty you could use the following:

=IF(IFERROR(LEFT(A3, FIND(" ", A3, 1)), A3)=0, "Empty", IFERROR(LEFT(A3, FIND(" ", A3, 1)), A3))

How do I remove trailing whitespace using a regular expression?

To remove trailing whitespace while also preserving whitespace-only lines, you want the regex to only remove trailing whitespace after non-whitespace characters. So you need to first check for a non-whitespace character. This means that the non-whitespace character will be included in the match, so you need to include it in the replacement.

Regex: ([^ \t\r\n])[ \t]+$

Replacement: \1 or $1, depending on the IDE

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

It is generally expected that modules of code such as .cpp files are compiled once and linked to in multiple projects, to avoid unnecessary repetitive compilation of logic. For example, g++ -o class.cpp would produce class.o which you could then link from multiple projects to using g++ main.cpp class.o.

We could use #include as our linker, as you seem to be implying, but that would just be silly when we know how to link properly using our compiler with less keystrokes and less wasteful repetition of compilation, rather than our code with more keystrokes and more wasteful repetition of compilation...

The header files are still required to be included into each of the multiple projects, however, because this provides the interface for each module. Without these headers the compiler wouldn't know about any of the symbols introduced by the .o files.

It is important to realise that the header files are what introduce the definitions of symbols for those modules; once that is realised then it makes sense that multiple inclusions could cause redefinitions of symbols (which causes errors), so we use include guards to prevent such redefinitions.

How do you print in a Go test using the "testing" package?

t.Log() will not show up until after the test is complete, so if you're trying to debug a test that is hanging or performing badly it seems you need to use fmt.

Yes: that was the case up to Go 1.13 (August 2019) included.

And that was followed in golang.org issue 24929

Consider the following (silly) automated tests:

func TestFoo(t *testing.T) {
    t.Parallel()

  for i := 0; i < 15; i++ {
        t.Logf("%d", i)
        time.Sleep(3 * time.Second)
    }
}

func TestBar(t *testing.T) {
    t.Parallel()

  for i := 0; i < 15; i++ {
        t.Logf("%d", i)
        time.Sleep(2 * time.Second)
    }
}

func TestBaz(t *testing.T) {
    t.Parallel()

  for i := 0; i < 15; i++ {
        t.Logf("%d", i)
        time.Sleep(1 * time.Second)
    }
}

If I run go test -v, I get no log output until all of TestFoo is done, then no output until all of TestBar is done, and again no more output until all of TestBaz is done.
This is fine if the tests are working, but if there is some sort of bug, there are a few cases where buffering log output is problematic:

  • When iterating locally, I want to be able to make a change, run my tests, see what's happening in the logs immediately to understand what's going on, hit CTRL+C to shut the test down early if necessary, make another change, re-run the tests, and so on.
    If TestFoo is slow (e.g., it's an integration test), I get no log output until the very end of the test. This significantly slows down iteration.
  • If TestFoo has a bug that causes it to hang and never complete, I'd get no log output whatsoever. In these cases, t.Log and t.Logf are of no use at all.
    This makes debugging very difficult.
  • Moreover, not only do I get no log output, but if the test hangs too long, either the Go test timeout kills the test after 10 minutes, or if I increase that timeout, many CI servers will also kill off tests if there is no log output after a certain amount of time (e.g., 10 minutes in CircleCI).
    So now my tests are killed and I have nothing in the logs to tell me what happened.

But for (possibly) Go 1.14 (Q1 2020): CL 127120

testing: stream log output in verbose mode

The output now is:

=== RUN   TestFoo
=== PAUSE TestFoo
=== RUN   TestBar
=== PAUSE TestBar
=== RUN   TestGaz
=== PAUSE TestGaz
=== CONT  TestFoo
    TestFoo: main_test.go:14: hello from foo
=== CONT  TestGaz
=== CONT  TestBar
    TestGaz: main_test.go:38: hello from gaz
    TestBar: main_test.go:26: hello from bar
    TestFoo: main_test.go:14: hello from foo
    TestBar: main_test.go:26: hello from bar
    TestGaz: main_test.go:38: hello from gaz
    TestFoo: main_test.go:14: hello from foo
    TestGaz: main_test.go:38: hello from gaz
    TestBar: main_test.go:26: hello from bar
    TestFoo: main_test.go:14: hello from foo
    TestGaz: main_test.go:38: hello from gaz
    TestBar: main_test.go:26: hello from bar
    TestGaz: main_test.go:38: hello from gaz
    TestFoo: main_test.go:14: hello from foo
    TestBar: main_test.go:26: hello from bar
--- PASS: TestFoo (1.00s)
--- PASS: TestGaz (1.00s)
--- PASS: TestBar (1.00s)
PASS
ok      dummy/streaming-test    1.022s

It is indeed in Go 1.14, as Dave Cheney attests in "go test -v streaming output":

In Go 1.14, go test -v will stream t.Log output as it happens, rather than hoarding it til the end of the test run.

Under Go 1.14 the fmt.Println and t.Log lines are interleaved, rather than waiting for the test to complete, demonstrating that test output is streamed when go test -v is used.

Advantage, according to Dave:

This is a great quality of life improvement for integration style tests that often retry for long periods when the test is failing.
Streaming t.Log output will help Gophers debug those test failures without having to wait until the entire test times out to receive their output.

How to save a Seaborn plot into a file

Its also possible to just create a matplotlib figure object and then use plt.savefig(...):

from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd

df = sns.load_dataset('iris')
plt.figure() # Push new figure on stack
sns_plot = sns.pairplot(df, hue='species', size=2.5)
plt.savefig('output.png') # Save that figure

Git merge reports "Already up-to-date" though there is a difference

If merging branch A into branch B reports "Already up to date", reverse is not always true. It is true only if branch B is descendant of branch A, otherwise branch B simply can have changes that aren't in A.

Example:

  1. You create branches A and B off master
  2. You make some changes in master and merge these changes only into branch B (not updating or forgetting to update branch A).
  3. You make some changes in branch A and merge A to B.

At this point merging A to B reports "Already up to date" but the branches are different because branch B has updates from master while branch A does not.

How to write some data to excel file(.xlsx)

It is possible to write to an excel file without opening it using the Microsoft.Jet.OLEDB.4.0 and OleDb. Using OleDb, it behaves as if you were writing to a table using sql.

Here is the code I used to create and write to an new excel file. No extra references are needed

var connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\SomePath\ExcelWorkBook.xls;Extended Properties=Excel 8.0";
using (var excelConnection = new OleDbConnection(connectionString))
{
    // The excel file does not need to exist, opening the connection will create the
    // excel file for you
    if (excelConnection.State != ConnectionState.Open) { excelConnection.Open(); }

    // data is an object so it works with DBNull.Value
    object propertyOneValue = "cool!";
    object propertyTwoValue = "testing";

    var sqlText = "CREATE TABLE YourTableNameHere ([PropertyOne] VARCHAR(100), [PropertyTwo] INT)";

    // Executing this command will create the worksheet inside of the workbook
    // the table name will be the new worksheet name
    using (var command = new OleDbCommand(sqlText, excelConnection)) { command.ExecuteNonQuery(); }

    // Add (insert) data to the worksheet
    var commandText = $"Insert Into YourTableNameHere ([PropertyOne], [PropertyTwo]) Values (@PropertyOne, @PropertyTwo)";

    using (var command = new OleDbCommand(commandText, excelConnection))
    {
        // We need to allow for nulls just like we would with
        // sql, if your data is null a DBNull.Value should be used
        // instead of null 
        command.Parameters.AddWithValue("@PropertyOne", propertyOneValue ?? DBNull.Value);
        command.Parameters.AddWithValue("@PropertyTwo", propertyTwoValue ?? DBNull.Value);

        command.ExecuteNonQuery();
    }
}

How to cast Object to boolean?

If the object is actually a Boolean instance, then just cast it:

boolean di = (Boolean) someObject;

The explicit cast will do the conversion to Boolean, and then there's the auto-unboxing to the primitive value. Or you can do that explicitly:

boolean di = ((Boolean) someObject).booleanValue();

If someObject doesn't refer to a Boolean value though, what do you want the code to do?

Create ArrayList from array

Use below script

Object[] myNum = {10, 20, 30, 40};
List<Object> newArr = new ArrayList<>(Arrays.asList(myNum));

Android: how to draw a border to a LinearLayout

Extend LinearLayout/RelativeLayout and use it straight on the XML

package com.pkg_name ;
...imports...
public class LinearLayoutOutlined extends LinearLayout {
    Paint paint;    

    public LinearLayoutOutlined(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        setWillNotDraw(false) ;
        paint = new Paint();
    }
    public LinearLayoutOutlined(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        setWillNotDraw(false) ;
        paint = new Paint();
    }
    @Override
    protected void onDraw(Canvas canvas) {
        /*
        Paint fillPaint = paint;
        fillPaint.setARGB(255, 0, 255, 0);
        fillPaint.setStyle(Paint.Style.FILL);
        canvas.drawPaint(fillPaint) ;
        */

        Paint strokePaint = paint;
        strokePaint.setARGB(255, 255, 0, 0);
        strokePaint.setStyle(Paint.Style.STROKE);
        strokePaint.setStrokeWidth(2);  
        Rect r = canvas.getClipBounds() ;
        Rect outline = new Rect( 1,1,r.right-1, r.bottom-1) ;
        canvas.drawRect(outline, strokePaint) ;
    }

}

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

<com.pkg_name.LinearLayoutOutlined
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
    android:layout_width=...
    android:layout_height=...
   >
   ... your widgets here ...

</com.pkg_name.LinearLayoutOutlined>

How to generate a unique hash code for string input in android...?

It depends on what you mean:

  • As mentioned String.hashCode() gives you a 32 bit hash code.

  • If you want (say) a 64-bit hashcode you can easily implement it yourself.

  • If you want a cryptographic hash of a String, the Java crypto libraries include implementations of MD5, SHA-1 and so on. You'll typically need to turn the String into a byte array, and then feed that to the hash generator / digest generator. For example, see @Bryan Kemp's answer.

  • If you want a guaranteed unique hash code, you are out of luck. Hashes and hash codes are non-unique.

A Java String of length N has 65536 ^ N possible states, and requires an integer with 16 * N bits to represent all possible values. If you write a hash function that produces integer with a smaller range (e.g. less than 16 * N bits), you will eventually find cases where more than one String hashes to the same integer; i.e. the hash codes cannot be unique. This is called the Pigeonhole Principle, and there is a straight forward mathematical proof. (You can't fight math and win!)

But if "probably unique" with a very small chance of non-uniqueness is acceptable, then crypto hashes are a good answer. The math will tell you how big (i.e. how many bits) the hash has to be to achieve a given (low enough) probability of non-uniqueness.

Efficiently sorting a numpy array in descending order?

Unfortunately when you have a complex array, only np.sort(temp)[::-1] works properly. The two other methods mentioned here are not effective.

Can I assume (bool)true == (int)1 for any C++ compiler?

I've found different compilers return different results on true. I've also found that one is almost always better off comparing a bool to a bool instead of an int. Those ints tend to change value over time as your program evolves and if you assume true as 1, you can get bitten by an unrelated change elsewhere in your code.

What is a good way to handle exceptions when trying to read a file in python?

Adding to @Josh's example;

fName = [FILE TO OPEN]
if os.path.exists(fName):
    with open(fName, 'rb') as f:
        #add you code to handle the file contents here.
elif IOError:
    print "Unable to open file: "+str(fName)

This way you can attempt to open the file, but if it doesn't exist (if it raises an IOError), alert the user!

Xcode error: Code signing is required for product type 'Application' in SDK 'iOS 10.0'

Xcode 11.4

Click on: 1. Your project 2. Signing & Capabilities 3. Select your Team.

enter image description here

pandas: multiple conditions while indexing data frame - unexpected behavior

A little mathematical logic theory here:

"NOT a AND NOT b" is the same as "NOT (a OR b)", so:

"a NOT -1 AND b NOT -1" is equivalent of "NOT (a is -1 OR b is -1)", which is opposite (Complement) of "(a is -1 OR b is -1)".

So if you want exact opposite result, df1 and df2 should be as below:

df1 = df[(df.a != -1) & (df.b != -1)]
df2 = df[(df.a == -1) | (df.b == -1)]

Put a Delay in Javascript

Use a AJAX function which will call a php page synchronously and then in that page you can put the php usleep() function which will act as a delay.

function delay(t){

var xmlhttp;

if (window.XMLHttpRequest)

{// code for IE7+, Firefox, Chrome, Opera, Safari

xmlhttp=new XMLHttpRequest();

}

else

{// code for IE6, IE5

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}

xmlhttp.open("POST","http://www.hklabs.org/files/delay.php?time="+t,false);

//This will call the page named delay.php and the response will be sent to a division with ID as "response"

xmlhttp.send();

document.getElementById("response").innerHTML=xmlhttp.responseText;

}

http://www.hklabs.org/articles/put-delay-in-javascript

Ignore 'Security Warning' running script from command line

You want to set the execution policy on your machine using Set-ExecutionPolicy:

Set-ExecutionPolicy Unrestricted

You may want to investigate the various execution policies to see which one is right for you. Take a look at the "help about_signing" for more information.

Failed to execute 'atob' on 'Window'

Here I got the error: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.

Because you didn't pass a base64-encoded string. Look at your functions: both download and dataURItoBlob do expect a data URI for some reason; you however are passing a plain html markup string to download in your example.

Not only is HTML invalid as base64, you are calling .split(',')[1] on it which will yield undefined - and "undefined" is not a valid base64-encoded string either.

I don't know, but I read that I need to encode my string to base64

That doesn't make much sense to me. You want to encode it somehow, only to decode it then?

What should I call and how?

Change the interface of your download function back to where it received the filename and text arguments.

Notice that the BlobBuilder does not only support appending whole strings (so you don't need to create those ArrayBuffer things), but also is deprecated in favor of the Blob constructor.

Can I put a name on my saved file?

Yes. Don't use the Blob constructor, but the File constructor.

function download(filename, text) {
    try {
        var file = new File([text], filename, {type:"text/plain"});
    } catch(e) {
        // when File constructor is not supported
        file = new Blob([text], {type:"text/plain"});
    }
    var url  = window.URL.createObjectURL(file);
    …
}

download('test.html', "<html>" + document.documentElement.innerHTML + "</html>");

See JavaScript blob filename without link on what to do with that object url, just setting the current location to it doesn't work.

requestFeature() must be called before adding content

In my case I showed DialogFragment in Activity. In this dialog fragment I wrote as in DialogFragment remove black border:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setStyle(STYLE_NO_FRAME, 0)
}

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    super.onCreateDialog(savedInstanceState)

    val dialog = Dialog(context!!, R.style.ErrorDialogTheme)
    val inflater = LayoutInflater.from(context)
    val view = inflater.inflate(R.layout.fragment_error_dialog, null, false)
    dialog.setTitle(null)
    dialog.setCancelable(true)
    dialog.setContentView(view)
    return dialog
}

Either remove setStyle(STYLE_NO_FRAME, 0) in onCreate() or chande/remove onCreateDialog. Because dialog settings have changed after the dialog has been created.

MavenError: Failed to execute goal on project: Could not resolve dependencies In Maven Multimodule project

My solution:

  1. remove all projects in current workspace
  2. import all again
  3. maven update project (Alt + F5) -> Select All and check Force Update of Snapshots/Releases
  4. maven build (Ctrl + B) until there is nothing to build

It worked for me after the second try.

Given a DateTime object, how do I get an ISO 8601 date in string format?

Use:

private void TimeFormats()
{
    DateTime localTime = DateTime.Now;
    DateTime utcTime = DateTime.UtcNow;
    DateTimeOffset localTimeAndOffset = new DateTimeOffset(localTime, TimeZoneInfo.Local.GetUtcOffset(localTime));

    //UTC
    string strUtcTime_o = utcTime.ToString("o");
    string strUtcTime_s = utcTime.ToString("s");
    string strUtcTime_custom = utcTime.ToString("yyyy-MM-ddTHH:mm:ssK");

    //Local
    string strLocalTimeAndOffset_o = localTimeAndOffset.ToString("o");
    string strLocalTimeAndOffset_s = localTimeAndOffset.ToString("s");
    string strLocalTimeAndOffset_custom = utcTime.ToString("yyyy-MM-ddTHH:mm:ssK");

    //Output
    Response.Write("<br/>UTC<br/>");
    Response.Write("strUtcTime_o: " + strUtcTime_o + "<br/>");
    Response.Write("strUtcTime_s: " + strUtcTime_s + "<br/>");
    Response.Write("strUtcTime_custom: " + strUtcTime_custom + "<br/>");

    Response.Write("<br/>Local Time<br/>");
    Response.Write("strLocalTimeAndOffset_o: " + strLocalTimeAndOffset_o + "<br/>");
    Response.Write("strLocalTimeAndOffset_s: " + strLocalTimeAndOffset_s + "<br/>");
    Response.Write("strLocalTimeAndOffset_custom: " + strLocalTimeAndOffset_custom + "<br/>");

}

OUTPUT

UTC
    strUtcTime_o: 2012-09-17T22:02:51.4021600Z
    strUtcTime_s: 2012-09-17T22:02:51
    strUtcTime_custom: 2012-09-17T22:02:51Z

Local Time
    strLocalTimeAndOffset_o: 2012-09-17T15:02:51.4021600-07:00
    strLocalTimeAndOffset_s: 2012-09-17T15:02:51
    strLocalTimeAndOffset_custom: 2012-09-17T22:02:51Z

Sources:

Increasing heap space in Eclipse: (java.lang.OutOfMemoryError)

You may want to close open projects in your Project Explorer. You can do this by right-clicking an open project, and selecting "Close Project".

This is what worked for me after I noticed that I had to periodically increase the heap size in my_directory\eclipse\eclipse.ini.

Hope this helps! Peace!

Java Generics With a Class & an Interface - Together

Actually, you can do what you want. If you want to provide multiple interfaces or a class plus interfaces, you have to have your wildcard look something like this:

<T extends ClassA & InterfaceB>

See the Generics Tutorial at sun.com, specifically the Bounded Type Parameters section, at the bottom of the page. You can actually list more than one interface if you wish, using & InterfaceName for each one that you need.

This can get arbitrarily complicated. To demonstrate, see the JavaDoc declaration of Collections#max, which (wrapped onto two lines) is:

public static <T extends Object & Comparable<? super T>> T
                                           max(Collection<? extends T> coll)

why so complicated? As said in the Java Generics FAQ: To preserve binary compatibility.

It looks like this doesn't work for variable declaration, but it does work when putting a generic boundary on a class. Thus, to do what you want, you may have to jump through a few hoops. But you can do it. You can do something like this, putting a generic boundary on your class and then:

class classB { }
interface interfaceC { }

public class MyClass<T extends classB & interfaceC> {
    Class<T> variable;
}

to get variable that has the restriction that you want. For more information and examples, check out page 3 of Generics in Java 5.0. Note, in <T extends B & C>, the class name must come first, and interfaces follow. And of course you can only list a single class.

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 3 2: ordinal not in range(128)

As here str(u'\u2013') is causing error so use isinstance(foo,basestring) to check for unicode/string, if not of type base string convert it into Unicode and then apply encode

if isinstance(foo,basestring):
    foo.encode('utf8')
else:
    unicode(foo).encode('utf8')

further read

How to return a string from a C++ function?

string str1, str2, str3;

cout << "These are the strings: " << endl;
cout << "str1: \"the dog jumped over the fence\"" << endl;
cout << "str2: \"the\"" << endl;
cout << "str3: \"that\"" << endl << endl;

From this, I see that you have not initialized str1, str2, or str3 to contain the values that you are printing. I might suggest doing so first:

string str1 = "the dog jumped over the fence", 
       str2 = "the",
       str3 = "that";

cout << "These are the strings: " << endl;
cout << "str1: \"" << str1 << "\"" << endl;
cout << "str2: \"" << str2 << "\"" << endl;
cout << "str3: \"" << str3 << "\"" << endl << endl;

Difference between Activity and FragmentActivity

FragmentActivity is part of the support library, while Activity is the framework's default class. They are functionally equivalent.

You should always use FragmentActivity and android.support.v4.app.Fragment instead of the platform default Activity and android.app.Fragment classes. Using the platform defaults mean that you are relying on whatever implementation of fragments is used in the device you are running on. These are often multiple years old, and contain bugs that have since been fixed in the support library.

How to clear the interpreter console?

How about this for a clear

- os.system('cls')

That is about as short as could be!

C++ style cast from unsigned char * to const char *

Hope it help. :)

const unsigned attribName = getname();
const unsigned attribVal = getvalue();
const char *attrName=NULL, *attrVal=NULL;
attrName = (const char*) attribName;
attrVal = (const char*) attribVal;

make: *** No rule to make target `all'. Stop

Your makefile should ideally be named makefile, not make. Note that you can call your makefile anything you like, but as you found, you then need the -f option with make to specify the name of the makefile. Using the default name of makefile just makes life easier.

How can I specify a [DllImport] path at runtime?

Contrary to the suggestions by some of the other answers, using the DllImport attribute is still the correct approach.

I honestly don't understand why you can't do just like everyone else in the world and specify a relative path to your DLL. Yes, the path in which your application will be installed differs on different people's computers, but that's basically a universal rule when it comes to deployment. The DllImport mechanism is designed with this in mind.

In fact, it isn't even DllImport that handles it. It's the native Win32 DLL loading rules that govern things, regardless of whether you're using the handy managed wrappers (the P/Invoke marshaller just calls LoadLibrary). Those rules are enumerated in great detail here, but the important ones are excerpted here:

Before the system searches for a DLL, it checks the following:

  • If a DLL with the same module name is already loaded in memory, the system uses the loaded DLL, no matter which directory it is in. The system does not search for the DLL.
  • If the DLL is on the list of known DLLs for the version of Windows on which the application is running, the system uses its copy of the known DLL (and the known DLL's dependent DLLs, if any). The system does not search for the DLL.

If SafeDllSearchMode is enabled (the default), the search order is as follows:

  1. The directory from which the application loaded.
  2. The system directory. Use the GetSystemDirectory function to get the path of this directory.
  3. The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched.
  4. The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
  5. The current directory.
  6. The directories that are listed in the PATH environment variable. Note that this does not include the per-application path specified by the App Paths registry key. The App Paths key is not used when computing the DLL search path.

So, unless you're naming your DLL the same thing as a system DLL (which you should obviously not be doing, ever, under any circumstances), the default search order will start looking in the directory from which your application was loaded. If you place the DLL there during the install, it will be found. All of the complicated problems go away if you just use relative paths.

Just write:

[DllImport("MyAppDll.dll")] // relative path; just give the DLL's name
static extern bool MyGreatFunction(int myFirstParam, int mySecondParam);

But if that doesn't work for whatever reason, and you need to force the application to look in a different directory for the DLL, you can modify the default search path using the SetDllDirectory function.
Note that, as per the documentation:

After calling SetDllDirectory, the standard DLL search path is:

  1. The directory from which the application loaded.
  2. The directory specified by the lpPathName parameter.
  3. The system directory. Use the GetSystemDirectory function to get the path of this directory.
  4. The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched.
  5. The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
  6. The directories that are listed in the PATH environment variable.

So as long as you call this function before you call the function imported from the DLL for the first time, you can modify the default search path used to locate DLLs. The benefit, of course, is that you can pass a dynamic value to this function that is computed at run-time. That isn't possible with the DllImport attribute, so you will still use a relative path (the name of the DLL only) there, and rely on the new search order to find it for you.

You'll have to P/Invoke this function. The declaration looks like this:

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool SetDllDirectory(string lpPathName);

ADB.exe is obsolete and has serious performance problems

I faced the same issue, and I tried following things, which didn't work:

  1. Deleting the existing AVD and creating a new one.

  2. Uninstall latest-existing and older versions (if you have) of SDK-Tools and SDK-Build-Tools and installing new ones.

What worked for me was uninstalling and re-installing latest PLATFORM-TOOLS, where adb actually resides.

Setting up enviromental variables in Windows 10 to use java and javac

if you have any version problems (javac -version=15.0.1, java -version=1.8.0)
windows search : edit environment variables for your account
then delete these in your windows Environment variable: system variable: Path
C:\Program Files (x86)\Common Files\Oracle\Java\javapath
C:\Program Files\Common Files\Oracle\Java\javapath

then if you're using java 15
environment variable: system variable : Path
add path C:\Program Files\Java\jdk-15.0.1\bin
is enough

if you're using java 8

  • create JAVA_HOME
  • environment variable: system variable : JAVA_HOME
    JAVA_HOME = C:\Program Files\Java\jdk1.8.0_271
  • environment variable: system variable : Path
    add path = %JAVA_HOME%\bin
  • How to get current url in view in asp.net core 1.0

    If you're looking to also get the port number out of the request you'll need to access it through the Request.Host property for AspNet Core.

    The Request.Host property is not simply a string but, instead, an object that holds both the host domain and the port number. If the port number is specifically written out in the URL (i.e. "https://example.com:8080/path/to/resource"), then calling Request.Host will give you the host domain and the port number like so: "example.com:8080".

    If you only want the value for the host domain or only want the value for the port number then you can access those properties individually (i.e. Request.Host.Host or Request.Host.Port).

    Django - makemigrations - No changes detected

    My problem was much simpler than the above answers and probably a far more common reason as long as your project is already set up and working. In one of my applications that had been working for a long time, migrations seemed wonky, so in a hurry, I did the following:

    rm -r */migrations/*
    rm db.sqlite3
    python3 manage.py makemigrations
    No changes detected
    

    Whaat??

    I had mistakenly also removed all the __init__.py files :( - Everything was working again after I went in and:

    touch ads1/migrations/__init__.py
    

    For each of my applications then the makemigrations worked again.

    It turns out that I had manually created a new application by copying another and forgot to put the __init__.py in the migrations folder and that confinved me that everything was wonky - leading my making it worse with an rm -r as described above.

    Hope this helps someone from swearing at the "No changes detected" error for a few hours.

    How to change the length of a column in a SQL Server table via T-SQL

    So, let's say you have this table:

    CREATE TABLE YourTable(Col1 VARCHAR(10))
    

    And you want to change Col1 to VARCHAR(20). What you need to do is this:

    ALTER TABLE YourTable
    ALTER COLUMN Col1 VARCHAR(20)
    

    That'll work without problems since the length of the column got bigger. If you wanted to change it to VARCHAR(5), then you'll first gonna need to make sure that there are not values with more chars on your column, otherwise that ALTER TABLE will fail.

    How to combine two or more querysets in a Django view?

    The big downside of your current approach is its inefficiency with large search result sets, as you have to pull down the entire result set from the database each time, even though you only intend to display one page of results.

    In order to only pull down the objects you actually need from the database, you have to use pagination on a QuerySet, not a list. If you do this, Django actually slices the QuerySet before the query is executed, so the SQL query will use OFFSET and LIMIT to only get the records you will actually display. But you can't do this unless you can cram your search into a single query somehow.

    Given that all three of your models have title and body fields, why not use model inheritance? Just have all three models inherit from a common ancestor that has title and body, and perform the search as a single query on the ancestor model.

    Find the number of downloads for a particular app in apple appstore

    Updated answer now that xyo.net has been bought and shut down.

    appannie.com and similarweb.com are the best options now. Thanks @rinogo for the original suggestion!

    Outdated answer:

    Site is still buggy, but this is by far the best that I've found. Not sure if it's accurate, but at least they give you numbers that you can guess off of! They have numbers for Android, iOS (iPhone and iPad) and even Windows!

    xyo.net

    count distinct values in spreadsheet

    This works if you just want the count of unique values in e.g. the following range

    =counta(unique(B4:B21))
    

    HTTP Request in Kotlin

    You can use kohttp library. It is a Kotlin DSL HTTP client. It supports the features of square.okhttp and provides a clear DSL for them. KoHttp async calls are powered by coroutines.

    httpGet extension function

    val response: Response = "https://google.com/search?q=iphone".httpGet()
    

    you can also use async call with coroutines

    val response: Deferred<Response> = "https://google.com/search?q=iphone".asyncHttpGet()
    

    or DSL function for more complex requests

    val response: Response = httpGet {
        host = "google.com"
        path = "/search"
        param {
           "q" to "iphone"
           "safe" to "off"
       }
    }
    

    You can find more details in docs

    To get it with gradle use

    implementation 'io.github.rybalkinsd:kohttp:0.12.0'
    

    PHP Unset Session Variable

    You can unset session variable using:

    1. session_unset - Frees all session variables (It is equal to using: $_SESSION = array(); for older deprecated code)
    2. unset($_SESSION['Products']); - Unset only Products index in session variable. (Remember: You have to use like a function, not as you used)
    3. session_destroy — Destroys all data registered to a session

    To know the difference between using session_unset and session_destroy, read this SO answer. That helps.

    Sorting a vector in descending order

    Use the first:

    std::sort(numbers.begin(), numbers.end(), std::greater<int>());
    

    It's explicit of what's going on - less chance of misreading rbegin as begin, even with a comment. It's clear and readable which is exactly what you want.

    Also, the second one may be less efficient than the first given the nature of reverse iterators, although you would have to profile it to be sure.

    How to delete a whole folder and content?

    Safest code I know:

    private boolean recursiveRemove(File file) {
        if(file == null  || !file.exists()) {
            return false;
        }
    
        if(file.isDirectory()) {
            File[] list = file.listFiles();
    
            if(list != null) {
    
                for(File item : list) {
                    recursiveRemove(item);
                }
    
            }
        }
    
        if(file.exists()) {
            file.delete();
        }
    
        return !file.exists();
    }
    

    Checks the file exists, handles nulls, checks the directory was actually deleted

    How to get domain URL and application name?

    The application name come from getContextPath.

    I find this graphic from Agile Software Craftsmanship HttpServletRequest Path Decoding sorts out all the different methods that are available:

    enter image description here

    jQuery Ajax calls and the Html.AntiForgeryToken()

    Here is the easiest way I've seen. Note: Make sure you have "@Html.AntiForgeryToken()" in your View

      $("a.markAsDone").click(function (event) {
            event.preventDefault();
            var sToken = document.getElementsByName("__RequestVerificationToken")[0].value;
            $.ajax({
                url: $(this).attr("rel"),
                type: "POST",
                contentType: "application/x-www-form-urlencoded",
                data: { '__RequestVerificationToken': sToken, 'id': parseInt($(this).attr("title")) }
            })
            .done(function (data) {
                //Process MVC Data here
            })
            .fail(function (jqXHR, textStatus, errorThrown) {
                //Process Failure here
            });
        });
    

    Cannot set property 'display' of undefined

    document.getElementsByClassName('btn-pageMenu') delivers a nodeList. You should use: document.getElementsByClassName('btn-pageMenu')[0].style.display (if it's the first element from that list you want to change.

    If you want to change style.display for all nodes loop through the list:

    var elems = document.getElementsByClassName('btn-pageMenu');
    for (var i=0;i<elems.length;i+=1){
      elems[i].style.display = 'block';
    }
    

    to be complete: if you use jquery it is as simple as:

    ?$('.btn-pageMenu').css('display'???????????????????????????,'block');??????
    

    Python: How to ignore an exception and proceed?

    Try this:

    try:
        blah()
    except:
        pass
    

    Decrementing for loops

    a = " ".join(str(i) for i in range(10, 0, -1))
    print (a)
    

    How to use if - else structure in a batch file?

    AFAIK you can't do an if else in batch like you can in other languages, it has to be nested if's.

    Using nested if's your batch would look like

    IF %F%==1 IF %C%==1(
        ::copying the file c to d
        copy "%sourceFile%" "%destinationFile%"
        ) ELSE (
            IF %F%==1 IF %C%==0(
            ::moving the file c to d
            move "%sourceFile%" "%destinationFile%"
            ) ELSE (
                IF %F%==0 IF %C%==1(
                ::copying a directory c from d, /s:  bos olanlar hariç, /e:bos olanlar dahil
                xcopy "%sourceCopyDirectory%" "%destinationCopyDirectory%" /s/e
                ) ELSE (
                    IF %F%==0 IF %C%==0(
                    ::moving a directory
                    xcopy /E "%sourceMoveDirectory%" "%destinationMoveDirectory%"
                    rd /s /q "%sourceMoveDirectory%"
                    )
                )
            )
        )
    

    or as James suggested, chain your if's, however I think the proper syntax is

    IF %F%==1 IF %C%==1(
        ::copying the file c to d
        copy "%sourceFile%" "%destinationFile%"
        )
    

    AWS Lambda import module error in python

    @nithin, AWS released layers concept inside Lambda functions. You can create your layer and there you can upload as much as libraries and then you can connect the layer with the lambda functions. For more details: https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html

    How to properly ignore exceptions

    When you just want to do a try catch without handling the exception, how do you do it in Python?

    It depends on what you mean by "handling."

    If you mean to catch it without taking any action, the code you posted will work.

    If you mean that you want to take action on an exception without stopping the exception from going up the stack, then you want something like this:

    try:
        do_something()
    except:
        handle_exception()
        raise  #re-raise the exact same exception that was thrown
    

    Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

    This exception is probably caused by optimistic locking (or by a bug in your code). You're probably using it without knowing. And your pseudo-code (which should be replaced by real code to be able to diagnose the problem) is wrong. Hibernate saves all the modifications done to attached entities automatically. You shouldn't ever call update, merge or saveOrUpdate on an attached entity. Just do

    Email email = session.get(emailId);
    email.setSubject(subject);
    

    No need to call update. Hibernate will flush the changes automatically before committing the transaction.

    Convert pem key to ssh-rsa format

    The following script would obtain the ci.jenkins-ci.org public key certificate in base64-encoded DER format and convert it to an OpenSSH public key file. This code assumes that a 2048-bit RSA key is used and draws a lot from this Ian Boyd's answer. I've explained a bit more how it works in comments to this article in Jenkins wiki.

    echo -n "ssh-rsa " > jenkins.pub
    curl -sfI https://ci.jenkins-ci.org/ | grep -i X-Instance-Identity | tr -d \\r | cut -d\  -f2 | base64 -d | dd bs=1 skip=32 count=257 status=none | xxd -p -c257 | sed s/^/00000007\ 7373682d727361\ 00000003\ 010001\ 00000101\ / | xxd -p -r | base64 -w0 >> jenkins.pub
    echo >> jenkins.pub
    

    ORA-30926: unable to get a stable set of rows in the source tables

    A further clarification to the use of DISTINCT to resolve error ORA-30926 in the general case:

    You need to ensure that the set of data specified by the USING() clause has no duplicate values of the join columns, i.e. the columns in the ON() clause.

    In OP's example where the USING clause only selects a key, it was sufficient to add DISTINCT to the USING clause. However, in the general case the USING clause may select a combination of key columns to match on and attribute columns to be used in the UPDATE ... SET clause. Therefore in the general case, adding DISTINCT to the USING clause will still allow different update rows for the same keys, in which case you will still get the ORA-30926 error.

    This is an elaboration of DCookie's answer and point 3.1 in Tagar's answer, which from my experience may not be immediately obvious.

    How can I get the assembly file version

    UPDATE: As mentioned by Richard Grimes in my cited post, @Iain and @Dmitry Lobanov, my answer is right in theory but wrong in practice.

    As I should have remembered from countless books, etc., while one sets these properties using the [assembly: XXXAttribute], they get highjacked by the compiler and placed into the VERSIONINFO resource.

    For the above reason, you need to use the approach in @Xiaofu's answer as the attributes are stripped after the signal has been extracted from them.


    public static string GetProductVersion()
    {
      var attribute = (AssemblyVersionAttribute)Assembly
        .GetExecutingAssembly()
        .GetCustomAttributes( typeof(AssemblyVersionAttribute), true )
        .Single();
       return attribute.InformationalVersion;
    }
    

    (From http://bytes.com/groups/net/420417-assemblyversionattribute - as noted there, if you're looking for a different attribute, substitute that into the above)

    Which is preferred: Nullable<T>.HasValue or Nullable<T> != null?

    The compiler replaces null comparisons with a call to HasValue, so there is no real difference. Just do whichever is more readable/makes more sense to you and your colleagues.

    How to take the nth digit of a number in python

    First treat the number like a string

    number = 9876543210
    number = str(number)
    

    Then to get the first digit:

    number[0]
    

    The fourth digit:

    number[3]
    

    EDIT:

    This will return the digit as a character, not as a number. To convert it back use:

    int(number[0])
    

    R define dimensions of empty data frame

    If only the column names are available like :

    cnms <- c("Nam1","Nam2","Nam3")
    

    To create an empty data frame with the above variable names, first create a data.frame object:

    emptydf <- data.frame()
    

    Now call zeroth element of every column, thus creating an empty data frame with the given variable names:

    for( i in 1:length(cnms)){
         emptydf[0,eval(cnms[i])]
     }
    

    JUnit tests pass in Eclipse but fail in Maven Surefire

    It is most likely that your configuration files are in src/main/resources, while they must be under src/test/resources to work properly under maven.

    https://cwiki.apache.org/UIMA/differences-between-running-unit-tests-in-eclipse-and-in-maven.html

    I'm replying this after two years 'cause I couldn't find this answer here and I think it is the right one.

    How to check the extension of a filename in a bash script?

    You just can't be sure on a Unix system, that a .txt file truly is a text file. Your best bet is to use "file". Maybe try using:

    file -ib "$file"
    

    Then you can use a list of MIME types to match against or parse the first part of the MIME where you get stuff like "text", "application", etc.

    How to find the Target *.exe file of *.appref-ms

    ClickOnce applications are stored under the user's profile at %LocalAppData%\Apps\2.0\.

    From there, use the search function to find your application.

    Clear variable in python

    The del keyword would do.

    >>> a=1
    >>> a
    1
    >>> del a
    >>> a
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'a' is not defined
    

    But in this case I vote for self.left = None

    React img tag issue with url and class

    var Hello = React.createClass({
        render: function() {
          return (
            <div className="divClass">
               <img src={this.props.url} alt={`${this.props.title}'s picture`}  className="img-responsive" />
               <span>Hello {this.props.name}</span>
            </div>
          );
        }
    });
    

    What is the function __construct used for?

    __construct() is the method name for the constructor. The constructor is called on an object after it has been created, and is a good place to put initialisation code, etc.

    class Person {
    
        public function __construct() {
            // Code called for each new Person we create
        }
    
    }
    
    $person = new Person();
    

    A constructor can accept parameters in the normal manner, which are passed when the object is created, e.g.

    class Person {
    
        public $name = '';
    
        public function __construct( $name ) {
            $this->name = $name;
        }
    
    }
    
    $person = new Person( "Joe" );
    echo $person->name;
    

    Unlike some other languages (e.g. Java), PHP doesn't support overloading the constructor (that is, having multiple constructors which accept different parameters). You can achieve this effect using static methods.

    Note: I retrieved this from the log of the (at time of this writing) accepted answer.

    Reading Properties file in Java


    You can find information on this page:
    http://www.mkyong.com/java/java-properties-file-examples/

    Properties prop = new Properties();
    try {
        //load a properties file from class path, inside static method
        prop.load(App.class.getClassLoader().getResourceAsStream("config.properties"));
    
        //get the property value and print it out
        System.out.println(prop.getProperty("database"));
        System.out.println(prop.getProperty("dbuser"));
        System.out.println(prop.getProperty("dbpassword"));
    
    } 
    catch (IOException ex) {
        ex.printStackTrace();
    }
    

    T-SQL string replace in Update

    update YourTable
        set YourColumn = replace(YourColumn, '@domain2', '@domain1')
        where charindex('@domain2', YourColumn) <> 0
    

    How to clear a textbox using javascript

    use sth like

    <input type="text" name="yourName" placeholder="A new value" />

    File Upload with Angular Material

    I find a way to avoid styling my own choose file button.

    Because I'm using flowjs for resumable upload, I'm able to use the "flow-btn" directive from ng-flow, which gives a choose file button with material design style.

    Note that wrapping the input element inside a md-button won't work.

    What is a segmentation fault?

    Wikipedia's Segmentation_fault page has a very nice description about it, just pointing out the causes and reasons. Have a look into the wiki for a detailed description.

    In computing, a segmentation fault (often shortened to segfault) or access violation is a fault raised by hardware with memory protection, notifying an operating system (OS) about a memory access violation.

    The following are some typical causes of a segmentation fault:

    • Dereferencing NULL pointers – this is special-cased by memory management hardware
    • Attempting to access a nonexistent memory address (outside process's address space)
    • Attempting to access memory the program does not have rights to (such as kernel structures in process context)
    • Attempting to write read-only memory (such as code segment)

    These in turn are often caused by programming errors that result in invalid memory access:

    • Dereferencing or assigning to an uninitialized pointer (wild pointer, which points to a random memory address)

    • Dereferencing or assigning to a freed pointer (dangling pointer, which points to memory that has been freed/deallocated/deleted)

    • A buffer overflow.

    • A stack overflow.

    • Attempting to execute a program that does not compile correctly. (Some compilers will output an executable file despite the presence of compile-time errors.)

    Converting cv::Mat to IplImage*

    One problem might be: when using external ipl and defining HAVE_IPL in your project, the ctor

    _IplImage::_IplImage(const cv::Mat& m)
    {
        CV_Assert( m.dims <= 2 );
        cvInitImageHeader(this, m.size(), cvIplDepth(m.flags), m.channels());
        cvSetData(this, m.data, (int)m.step[0]);
    }
    

    found in ../OpenCV/modules/core/src/matrix.cpp is not used/instanciated and conversion fails.

    You may reimplement it in a way similar to :

    IplImage& FromMat(IplImage& img, const cv::Mat& m)
    {
        CV_Assert(m.dims <= 2);
        cvInitImageHeader(&img, m.size(), cvIplDepth(m.flags), m.channels());
        cvSetData(&img, m.data, (int)m.step[0]);
        return img;
    }
    
    IplImage img;
    FromMat(img,myMat);
    

    How to return a specific element of an array?

    I want to return odd numbers of an array

    If i read that correctly, you want something like this?

    List<Integer> getOddNumbers(int[] integers) {
      List<Integer> oddNumbers = new ArrayList<Integer>();
      for (int i : integers)
        if (i % 2 != 0)
          oddNumbers.add(i);
      return oddNumbers;
    }
    

    How can I read large text files in Python, line by line, without loading it into memory?

    I couldn't believe that it could be as easy as @john-la-rooy's answer made it seem. So, I recreated the cp command using line by line reading and writing. It's CRAZY FAST.

    #!/usr/bin/env python3.6
    
    import sys
    
    with open(sys.argv[2], 'w') as outfile:
        with open(sys.argv[1]) as infile:
            for line in infile:
                outfile.write(line)
    

    How to cut a string after a specific character in unix

    For completeness, using cut

    cut -d : -f 2 <<< $var
    

    And using only bash:

    IFS=: read a b <<< $var ; echo $b
    

    C# : Passing a Generic Object

    You need to define something in the interface, such as:

    public interface ITest
    {
        string Name { get; }
    }
    

    Implement ITest in your classes:

    public class MyClass1 : ITest
    {
        public string Name { get { return "Test1"; } }
    }
    
    public class MyClass2 : ITest
    {
        public string Name { get { return "Test2"; } }
    }
    

    Then restrict your generic Print function, to ITest:

    public void Print<T>(T test) where T : ITest
    {
    }
    

    How can I submit a POST form using the <a href="..."> tag?

    You need to use javascript for this.

    <form id="form1" action="showMessage.jsp" method="post">
        <a href="javascript:;" onclick="document.getElementById('form1').submit();"><%=n%></a>
        <input type="hidden" name="mess" value=<%=n%>/>
    </form>
    

    TypeError: p.easing[this.easing] is not a function

    I got this error today whilst trying to initiate a slide effect on a div. Thanks to the answer from 'I Hate Lazy' above (which I've upvoted), I went looking for a custom jQuery UI script, and you can in fact build your own file directly on the jQuery ui website http://jqueryui.com/download/. All you have to do is mark the effect(s) that you're looking for and then download.

    I was looking for the slide effect. So I first unchecked all the checkboxes, then clicked on the 'slide effect' checkbox and the page automatically then checks those other components necessary to make the slide effect work. Very simple.

    easeOutBounce is an easing effect, for which you'll need to check the 'Effects Core' checkbox.

    ascending/descending in LINQ - can one change the order via parameter?

    In terms of how this is implemented, this changes the method - from OrderBy/ThenBy to OrderByDescending/ThenByDescending. However, you can apply the sort separately to the main query...

    var qry = from .... // or just dataList.AsEnumerable()/AsQueryable()
    
    if(sortAscending) {
        qry = qry.OrderBy(x=>x.Property);
    } else {
        qry = qry.OrderByDescending(x=>x.Property);
    }
    

    Any use? You can create the entire "order" dynamically, but it is more involved...

    Another trick (mainly appropriate to LINQ-to-Objects) is to use a multiplier, of -1/1. This is only really useful for numeric data, but is a cheeky way of achieving the same outcome.

    PHP compare time

    To see of the curent time is greater or equal to 14:08:10 do this:

    if (time() >= strtotime("14:08:10")) {
      echo "ok";
    }
    

    Depending on your input sources, make sure to account for timezone.

    See PHP time() and PHP strtotime()

    base64 encoded images in email signatures

    Important

    My answer below shows how to embed images using data URIs. This is useful for the web, but will not work reliably for most email clients. For email purposes be sure to read Shadow2531's answer.


    Base-64 data is legal in an img tag and I believe your question is how to properly insert such an image tag.

    You can use an online tool or a few lines of code to generate the base 64 string.

    The syntax to source the image from inline data is:

    <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
    AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
    9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">
    

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

    Firebase TIMESTAMP to date and Time

    I converted to this format

    let timestamp = '1452488445471';
    let newDate = new Date(timestamp * 1000)
    let Hours = newDate.getHours()
    let Minutes = newDate.getMinutes()
    const HourComplete = Hours + ':' + Minutes
    let formatedTime = HourComplete
    console.log(formatedTime)
    

    How to mark a method as obsolete or deprecated?

    To mark as obsolete with a warning:

    [Obsolete]
    private static void SomeMethod()
    

    You get a warning when you use it:

    Obsolete warning is shown

    And with IntelliSense:

    Obsolete warning with IntelliSense

    If you want a message:

    [Obsolete("My message")]
    private static void SomeMethod()
    

    Here's the IntelliSense tool tip:

    IntelliSense shows the obsolete message

    Finally if you want the usage to be flagged as an error:

    [Obsolete("My message", true)]
    private static void SomeMethod()
    

    When used this is what you get:

    Method usage is displayed as an error

    Note: Use the message to tell people what they should use instead, not why it is obsolete.

    Find object in list that has attribute equal to some value (that meets any condition)

    I just ran into a similar problem and devised a small optimization for the case where no object in the list meets the requirement.(for my use-case this resulted in major performance improvement):

    Along with the list test_list, I keep an additional set test_value_set which consists of values of the list that I need to filter on. So here the else part of agf's solution becomes very-fast.

    How to create a QR code reader in a HTML5 website?

    Reader they show at http://www.webqr.com/index.html works like a charm, but literaly, you need the one on the webpage, the github version it's really hard to make it work, however, it is possible. The best way to go is reverse-engineer the example shown at the webpage.

    However, to edit and get the full potential out of it, it's not so easy. At some point I may post the stripped-down reverse-engineered QR reader, but in the meantime have some fun hacking the code.

    Happy coding.

    How to fix the Eclipse executable launcher was unable to locate its companion shared library for windows 7?

    In my case, i had copied a plugins folder into workspace from a collegue. Becaouse it was an unzipped folder, the structure was like 'pluginsfolder inside a plugins folder2 . so make sure that all the plugins are directly located under the toppest plugins folder at the workspace.

    Set Google Maps Container DIV width and height 100%

    If you can't affect your parents elements (like in a nested components situation) you can use height: 100vh which will make it a full window (=view) height;

    jQuery - Appending a div to body, the body is the object?

    Instead use use appendTo. append or appendTo returns a jQuery object so you don't have to wrap it inside $().

    var holdyDiv = $('<div />').appendTo('body');
    holdyDiv.attr('id', 'holdy');
    

    .appendTo() reference: http://api.jquery.com/appendTo/

    Alernatively you can try this also.

    $('<div />', { id: 'holdy' }).appendTo('body');
                   ^
                 (Here you can specify any attribute/value pair you want)
    

    Selecting with complex criteria from pandas.DataFrame

    Another solution is to use the query method:

    import pandas as pd
    
    from random import randint
    df = pd.DataFrame({'A': [randint(1, 9) for x in xrange(10)],
                       'B': [randint(1, 9) * 10 for x in xrange(10)],
                       'C': [randint(1, 9) * 100 for x in xrange(10)]})
    print df
    
       A   B    C
    0  7  20  300
    1  7  80  700
    2  4  90  100
    3  4  30  900
    4  7  80  200
    5  7  60  800
    6  3  80  900
    7  9  40  100
    8  6  40  100
    9  3  10  600
    
    print df.query('B > 50 and C != 900')
    
       A   B    C
    1  7  80  700
    2  4  90  100
    4  7  80  200
    5  7  60  800
    

    Now if you want to change the returned values in column A you can save their index:

    my_query_index = df.query('B > 50 & C != 900').index
    

    ....and use .iloc to change them i.e:

    df.iloc[my_query_index, 0] = 5000
    
    print df
    
          A   B    C
    0     7  20  300
    1  5000  80  700
    2  5000  90  100
    3     4  30  900
    4  5000  80  200
    5  5000  60  800
    6     3  80  900
    7     9  40  100
    8     6  40  100
    9     3  10  600
    

    Print PDF directly from JavaScript

    Download the Print.js from http://printjs.crabbly.com/

    $http({
        url: "",
        method: "GET",
        headers: {
            "Content-type": "application/pdf"
        },
        responseType: "arraybuffer"
    }).success(function (data, status, headers, config) {
        var pdfFile = new Blob([data], {
            type: "application/pdf"
        });
        var pdfUrl = URL.createObjectURL(pdfFile);
        //window.open(pdfUrl);
        printJS(pdfUrl);
        //var printwWindow = $window.open(pdfUrl);
        //printwWindow.print();
    }).error(function (data, status, headers, config) {
        alert("Sorry, something went wrong")
    });
    

    jQuery Validate - Enable validation for hidden fields

    Make sure to put

     $.validator.setDefaults({ ignore: '' });
    

    NOT inside $(document).ready

    What's the simplest way to extend a numpy array in 2 dimensions?

    maybe you need this.

    >>> x = np.array([11,22])
    >>> y = np.array([18,7,6])
    >>> z = np.array([1,3,5])
    >>> np.concatenate((x,y,z))
    array([11, 22, 18,  7,  6,  1,  3,  5])
    

    Get URL query string parameters

    This code and notation is not mine. Evan K solves a multi value same name query with a custom function ;) is taken from:

    http://php.net/manual/en/function.parse-str.php#76792 Credits go to Evan K.

    It bears mentioning that the parse_str builtin does NOT process a query string in the CGI standard way, when it comes to duplicate fields. If multiple fields of the same name exist in a query string, every other web processing language would read them into an array, but PHP silently overwrites them:

    <?php
    # silently fails to handle multiple values
    parse_str('foo=1&foo=2&foo=3');
    
    # the above produces:
    $foo = array('foo' => '3');
    ?>
    

    Instead, PHP uses a non-standards compliant practice of including brackets in fieldnames to achieve the same effect.

    <?php
    # bizarre php-specific behavior
    parse_str('foo[]=1&foo[]=2&foo[]=3');
    
    # the above produces:
    $foo = array('foo' => array('1', '2', '3') );
    ?>
    

    This can be confusing for anyone who's used to the CGI standard, so keep it in mind. As an alternative, I use a "proper" querystring parser function:

    <?php
    function proper_parse_str($str) {
      # result array
      $arr = array();
    
      # split on outer delimiter
      $pairs = explode('&', $str);
    
      # loop through each pair
      foreach ($pairs as $i) {
        # split into name and value
        list($name,$value) = explode('=', $i, 2);
        
        # if name already exists
        if( isset($arr[$name]) ) {
          # stick multiple values into an array
          if( is_array($arr[$name]) ) {
            $arr[$name][] = $value;
          }
          else {
            $arr[$name] = array($arr[$name], $value);
          }
        }
        # otherwise, simply stick it in a scalar
        else {
          $arr[$name] = $value;
        }
      }
    
      # return result array
      return $arr;
    }
    
    $query = proper_parse_str($_SERVER['QUERY_STRING']);
    ?>
    

    How do I count a JavaScript object's attributes?

    There's no easy answer, because Object — which every object in JavaScript derives from — includes many attributes automatically, and the exact set of attributes you get depends on the particular interpreter and what code has executed before yours. So, you somehow have to separate the ones you defined from those you got "for free."

    Here's one way:

    var foo = {"key1": "value1", "key2": "value2", "key3": "value3"};
    Object.prototype.foobie = 'bletch'; // add property to foo that won't be counted
    
    var count = 0;
    for (var k in foo) {
        if (foo.hasOwnProperty(k)) {
           ++count;
        }
    }
    alert("Found " + count + " properties specific to foo");
    

    The second line shows how other code can add properties to all Object derivatives. If you remove the hasOwnProperty() check inside the loop, the property count will go up to at least 4. On a page with other JavaScript besides this code, it could be higher than 4, if that other code also modifies the Object prototype.

    Daemon not running. Starting it now on port 5037

    This worked for me: Open task manager (of your OS) and kill adb.exe process. Now start adb again, now adb should start normally.

    Understanding generators in Python

    It helps to make a clear distinction between the function foo, and the generator foo(n):

    def foo(n):
        yield n
        yield n+1
    

    foo is a function. foo(6) is a generator object.

    The typical way to use a generator object is in a loop:

    for n in foo(6):
        print(n)
    

    The loop prints

    # 6
    # 7
    

    Think of a generator as a resumable function.

    yield behaves like return in the sense that values that are yielded get "returned" by the generator. Unlike return, however, the next time the generator gets asked for a value, the generator's function, foo, resumes where it left off -- after the last yield statement -- and continues to run until it hits another yield statement.

    Behind the scenes, when you call bar=foo(6) the generator object bar is defined for you to have a next attribute.

    You can call it yourself to retrieve values yielded from foo:

    next(bar)    # Works in Python 2.6 or Python 3.x
    bar.next()   # Works in Python 2.5+, but is deprecated. Use next() if possible.
    

    When foo ends (and there are no more yielded values), calling next(bar) throws a StopInteration error.

    Press TAB and then ENTER key in Selenium WebDriver

    In javascript (node.js) this works for me:

    describe('UI', function() {
    
    describe('gets results from Bing', function() {
        this.timeout(10000);
    
        it('makes a search', function(done) {
            var driver = new webdriver.Builder().
            withCapabilities(webdriver.Capabilities.chrome()).
            build();
    
    
            driver.get('http://bing.com');
            var input = driver.findElement(webdriver.By.name('q'));
            input.sendKeys('something');
            input.sendKeys(webdriver.Key.ENTER);
    
            driver.wait(function() {
                driver.findElement(webdriver.By.className('sb_count')).
                    getText().
                    then(function(result) {
                      console.log('result: ', result);
                      done();
                });
            }, 8000);
    
    
        });
      });
    });
    

    For tab use webdriver.Key.TAB

    NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver

    In my case none of the above solutions didn't help:

    Root cause: incompatible version of gcc

    Solution:

    1. sudo apt install --reinstall gcc
    2. sudo apt-get --purge -y remove 'nvidia*'
    3  sudo apt install nvidia-driver-450 
    4. sudo reboot
    

    System: AWS EC2 18.04 instance

    Solution source: https://forums.developer.nvidia.com/t/nvidia-smi-has-failed-in-ubuntu-18-04/68288/4

    How to open a workbook specifying its path

    Workbooks.open("E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm")

    Or, in a more structured way...

    Sub openwb()
        Dim sPath As String, sFile As String
        Dim wb As Workbook
    
        sPath = "E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\"
        sFile = sPath & "D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm"
    
        Set wb = Workbooks.Open(sFile)
    End Sub
    

    Alert after page load

    Another option to resolve issue described in OP which I encountered on recent bootcamp training is using window.setTimeout to wrap around the code which is bothersome. My understanding is that it delays the execution of the function for the specified time period (500ms in this case), allowing enough time for the page to load. So, for example:

    <script type = "text/javascript">
                window.setTimeout(function(){
                    alert("Hello World!");
                }, 500); 
    </script>
    

    Cannot find pkg-config error

    Try

    Form inside a table

    A form is not allowed to be a child element of a table, tbody or tr. Attempting to put one there will tend to cause the browser to move the form to it appears after the table (while leaving its contents — table rows, table cells, inputs, etc — behind).

    You can have an entire table inside a form. You can have a form inside a table cell. You cannot have part of a table inside a form.

    Use one form around the entire table. Then either use the clicked submit button to determine which row to process (to be quick) or process every row (allowing bulk updates).

    HTML 5 introduces the form attribute. This allows you to provide one form per row outside the table and then associate all the form control in a given row with one of those forms using its id.

    How to delete a file or folder?


    Path objects from the Python 3.4+ pathlib module also expose these instance methods:

    .NET obfuscation tools/strategy

    SmartAssembly is great,I was used in most of my projects

    Disable mouse scroll wheel zoom on embedded Google Maps

    This will give you a responsive Google Map that will stop the scrolling on the iframe, but once clicked on will let you zoom.

    Copy and paste this into your html but replace the iframe link with your own. He's an article on it with an example: Disable the mouse scroll wheel zoom on embedded Google Map iframes

    <style>
        .overlay {
        background:transparent;
        position:relative;
        width:100%; /* your iframe width */
        height:480px; /* your iframe height */
        top:480px; /* your iframe height */
        margin-top:-480px; /* your iframe height */
        }
    </style>
    <div class="overlay" onClick="style.pointerEvents='none'"></div>
    <iframe src="https://mapsengine.google.com/map/embed?mid=some_map_id" width="100%" height="480"></iframe>
    

    Modal width (increase)

    Bootstrap 3

    You can create or just override default bootstrap modal-lgby doing below:

    .modal-lg {
        max-width: 80%;
    }
    

    If not working just add !important so it would look like below

    .modal-lg {
        max-width: 80% !important;
    }
    

    Now call the modal-lg.

    <div class="modal-dialog modal-lg" role="document">
     <!-- some modal content --->
    </div
    

    For Bootstrap 4 refer to @kitsu.eb answer. Also note that using bootstrap 4 utilities might break the responsiveness.

    How to access to the parent object in c#

    I would give the parent an ID, and store the parentID in the child object, so that you can pull information about the parent as needed without creating a parent-owns-child/child-owns-parent loop.

    Set new id with jQuery

    Use .val() not attr('value').

    Format Date time in AngularJS

    Here are a few popular examples:

    <div>{{myDate | date:'M/d/yyyy'}}</div> 7/4/2014

    <div>{{myDate | date:'yyyy-MM-dd'}}</div> 2014-07-04

    <div>{{myDate | date:'M/d/yyyy HH:mm:ss'}}</div> 7/4/2014 12:01:59

    How to set the Default Page in ASP.NET?

    Tip #84: Did you know… How to set a Start page for your Web Site in Visual Web Developer?

    Simply right click on the page you want to be the start page and say "set as start page".

    As noted in the comment below by Adam Tuliper - MSFT, this only works for debugging, not deployment.

    How to import a Python class that is in a directory above?

    from ..subpkg2 import mod

    Per the Python docs: When inside a package hierarchy, use two dots, as the import statement doc says:

    When specifying what module to import you do not have to specify the absolute name of the module. When a module or package is contained within another package it is possible to make a relative import within the same top package without having to mention the package name. By using leading dots in the specified module or package after from you can specify how high to traverse up the current package hierarchy without specifying exact names. One leading dot means the current package where the module making the import exists. Two dots means up one package level. Three dots is up two levels, etc. So if you execute from . import mod from a module in the pkg package then you will end up importing pkg.mod. If you execute from ..subpkg2 import mod from within pkg.subpkg1 you will import pkg.subpkg2.mod. The specification for relative imports is contained within PEP 328.

    PEP 328 deals with absolute/relative imports.

    UTF-8, UTF-16, and UTF-32

    As mentioned, the difference is primarily the size of the underlying variables, which in each case get larger to allow more characters to be represented.

    However, fonts, encoding and things are wickedly complicated (unnecessarily?), so a big link is needed to fill in more detail:

    http://www.cs.tut.fi/~jkorpela/chars.html#ascii

    Don't expect to understand it all, but if you don't want to have problems later it's worth learning as much as you can, as early as you can (or just getting someone else to sort it out for you).

    Paul.

    Pass entire form as data in jQuery Ajax function

    A good jQuery option to do this is through FormData. This method is also suited when sending files through a form!

    <form id='test' method='post' enctype='multipart/form-data'>
       <input type='text' name='testinput' id='testinput'>
       <button type='submit'>submit</button>
    </form>
    

    Your send function in jQuery would look like this:

    $( 'form#test' ).submit( function(){
       var data = new FormData( $( 'form#test' )[ 0 ] );
    
       $.ajax( {
          processData: false,
          contentType: false,
    
          data: data,
          dataType: 'json',
          type: $( this ).attr( 'method' );
          url: 'yourapi.php',
          success: function( feedback ){
             console.log( "the feedback from your API: " + feedback );
          }
    });
    

    to add data to your form you can either use a hidden input in your form, or you add it on the fly:

    var data = new FormData( $( 'form#test' )[ 0 ] );
    data.append( 'command', 'value_for_command' );
    

    How to set Bullet colors in UL/LI html lists via CSS without using any images or span tags

    I am adding my solution to this problem.

    I don't want to use image and validator will punish you for using negative values in CSS, so I go this way:

    ul          { list-style:none; padding:0; margin:0; }
    
    li          { padding-left:0.75em; position:relative; }
    
    li:before       { content:"•"; color:#e60000; position:absolute; left:0em; }
    

    How to utilize date add function in Google spreadsheet?

    In a fresh spreadsheet (US locale) with 12/19/11 in A1 and DT 30 in B1 then:

    =A1+right(B1,2)
    

    in say C1 returns 1/18/12.

    As a string function RIGHT returns Text but that can be coerced into a number when adding. In adding a number to dates unity is treated as one day. Within (very wide) limits, months and even years are adjusted automatically.

    Save and retrieve image (binary) from SQL Server using Entity Framework 6

    Convert the image to a byte[] and store that in the database.


    Add this column to your model:

    public byte[] Content { get; set; }
    

    Then convert your image to a byte array and store that like you would any other data:

    public byte[] ImageToByteArray(System.Drawing.Image imageIn)
    {
        using(var ms = new MemoryStream())
        {
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
    
            return ms.ToArray();
        }
    }
    
    public Image ByteArrayToImage(byte[] byteArrayIn)
    {
         using(var ms = new MemoryStream(byteArrayIn))
         {
             var returnImage = Image.FromStream(ms);
    
             return returnImage;
         }
    }
    

    Source: Fastest way to convert Image to Byte array

    var image = new ImageEntity()
    {
       Content = ImageToByteArray(image)
    };
    
    _context.Images.Add(image);
    _context.SaveChanges();
    

    When you want to get the image back, get the byte array from the database and use the ByteArrayToImage and do what you wish with the Image

    This stops working when the byte[] gets to big. It will work for files under 100Mb

    How to apply a CSS filter to a background image

    Please check the below code:-

    _x000D_
    _x000D_
    .backgroundImageCVR{_x000D_
     position:relative;_x000D_
     padding:15px;_x000D_
    }_x000D_
    .background-image{_x000D_
     position:absolute;_x000D_
     left:0;_x000D_
     right:0;_x000D_
     top:0;_x000D_
     bottom:0;_x000D_
     background:url('http://www.planwallpaper.com/static/images/colorful-triangles-background_yB0qTG6.jpg');_x000D_
     background-size:cover;_x000D_
     z-index:1;_x000D_
     -webkit-filter: blur(10px);_x000D_
      -moz-filter: blur(10px);_x000D_
      -o-filter: blur(10px);_x000D_
      -ms-filter: blur(10px);_x000D_
      filter: blur(10px); _x000D_
    }_x000D_
    .content{_x000D_
     position:relative;_x000D_
     z-index:2;_x000D_
     color:#fff;_x000D_
    }
    _x000D_
    <div class="backgroundImageCVR">_x000D_
        <div class="background-image"></div>_x000D_
        <div class="content">_x000D_
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis aliquam erat in ante malesuada, facilisis semper nulla semper. Phasellus sapien neque, faucibus in malesuada quis, lacinia et libero. Sed sed turpis tellus. Etiam ac aliquam tortor, eleifend rhoncus metus. Ut turpis massa, sollicitudin sit amet molestie a, posuere sit amet nisl. Mauris tincidunt cursus posuere. Nam commodo libero quis lacus sodales, nec feugiat ante posuere. Donec pulvinar auctor commodo. Donec egestas diam ut mi adipiscing, quis lacinia mauris condimentum. Quisque quis odio venenatis, venenatis nisi a, vehicula ipsum. Etiam at nisl eu felis vulputate porta.</p>_x000D_
          <p>Fusce ut placerat eros. Aliquam consequat in augue sed convallis. Donec orci urna, tincidunt vel dui at, elementum semper dolor. Donec tincidunt risus sed magna dictum, quis luctus metus volutpat. Donec accumsan et nunc vulputate accumsan. Vestibulum tempor, erat in mattis fringilla, elit urna ornare nunc, vel pretium elit sem quis orci. Vivamus condimentum dictum tempor. Nam at est ante. Sed lobortis et lorem in sagittis. In suscipit in est et vehicula.</p>_x000D_
        </div>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    Is it possible to read from a InputStream with a timeout?

    I would question the problem statement rather than just accept it blindly. You only need timeouts from the console or over the network. If the latter you have Socket.setSoTimeout() and HttpURLConnection.setReadTimeout() which both do exactly what is required, as long as you set them up correctly when you construct/acquire them. Leaving it to an arbitrary point later in the application when all you have is the InputStream is poor design leading to a very awkward implementation.

    Unbalanced calls to begin/end appearance transitions for <UITabBarController: 0x197870>

    I fixed this error by changing animated from YES to NO.

    From:

    [tabBarController presentModalViewController:viewController animated:YES];
    

    To:

    [tabBarController presentModalViewController:viewController animated:NO];
    

    SVN remains in conflict?

    I had similar issue, this is how it was solved

    xyz@ip :~/formsProject_SVN$ svn resolved formsProj/templates/search

    Resolved conflicted state of 'formsProj/templates/search'

    Now update your project

    xyz@ip:~/formsProject_SVN$ svn update

    Updating '.':

    Select: (mc) keep affected local moves, (r) mark resolved (breaks moves), (p) postpone, (q) quit resolution, (h) help: r (select "r" option to resolve)

    Resolved conflicted state of 'formsProj/templates/search'

    Summary of conflicts: Tree conflicts: 0 remaining (and 1 already resolved)

    dlib installation on Windows 10

    It is basically a two-step process:

    1. install cmap
    pip install cmap
    
    1. install dlib
    pip install https://pypi.python.org/packages/da/06/bd3e241c4eb0a662914b3b4875fc52dd176a9db0d4a2c915ac2ad8800e9e/dlib-19.7.0-cp36-cp36m-win_amd64.whl#md5=b7330a5b2d46420343fbed5df69e6a3f
    

    How to Read and Write from the Serial Port

    SerialPort (RS-232 Serial COM Port) in C# .NET
    This article explains how to use the SerialPort class in .NET to read and write data, determine what serial ports are available on your machine, and how to send files. It even covers the pin assignments on the port itself.

    Example Code:

    using System;
    using System.IO.Ports;
    using System.Windows.Forms;
    
    namespace SerialPortExample
    {
      class SerialPortProgram
      {
        // Create the serial port with basic settings
        private SerialPort port = new SerialPort("COM1",
          9600, Parity.None, 8, StopBits.One);
    
        [STAThread]
        static void Main(string[] args)
        { 
          // Instatiate this class
          new SerialPortProgram();
        }
    
        private SerialPortProgram()
        {
          Console.WriteLine("Incoming Data:");
    
          // Attach a method to be called when there
          // is data waiting in the port's buffer
          port.DataReceived += new 
            SerialDataReceivedEventHandler(port_DataReceived);
    
          // Begin communications
          port.Open();
    
          // Enter an application loop to keep this thread alive
          Application.Run();
        }
    
        private void port_DataReceived(object sender,
          SerialDataReceivedEventArgs e)
        {
          // Show all the incoming data in the port's buffer
          Console.WriteLine(port.ReadExisting());
        }
      }
    }
    

    Remove border from buttons

    Add this as css,

    button[type=submit]{border:none;}
    

    How to get the innerHTML of selectable jquery element?

    Use .val() instead of .innerHTML for getting value of selected option

    Use .text() for getting text of selected option

    Thanks for correcting :)

    Func vs. Action vs. Predicate

    Func - When you want a delegate for a function that may or may not take parameters and returns a value. The most common example would be Select from LINQ:

    var result = someCollection.Select( x => new { x.Name, x.Address });
    

    Action - When you want a delegate for a function that may or may not take parameters and does not return a value. I use these often for anonymous event handlers:

    button1.Click += (sender, e) => { /* Do Some Work */ }
    

    Predicate - When you want a specialized version of a Func that evaluates a value against a set of criteria and returns a boolean result (true for a match, false otherwise). Again, these are used in LINQ quite frequently for things like Where:

    var filteredResults = 
        someCollection.Where(x => x.someCriteriaHolder == someCriteria);
    

    I just double checked and it turns out that LINQ doesn't use Predicates. Not sure why they made that decision...but theoretically it is still a situation where a Predicate would fit.

    How do I debug Node.js applications?

    Enable VS Code preference Auto Attach from File -> Preferences -> Settings -> Search for Auto Attach and set it On, open the console (ctrl + *) or from the menu Terminal -> New Terminal, set a breakpoint in your code, type in the command

    node --inspect <name of your file>
    

    This will start the debugging and the VS Code will show the Debug menu.

    Note: Auto Attach is also very helpful if you are working with node cluster worker threads.

    How to search for an element in a golang slice

    As other guys commented before you can write your own procedure with anonymous function to solve this issue.

    I used two ways to solve it:

    func Find(slice interface{}, f func(value interface{}) bool) int {
        s := reflect.ValueOf(slice)
        if s.Kind() == reflect.Slice {
            for index := 0; index < s.Len(); index++ {
                if f(s.Index(index).Interface()) {
                    return index
                }
            }
        }
        return -1
    }
    

    Uses example:

    type UserInfo struct {
        UserId          int
    }
    
    func main() {
        var (
            destinationList []UserInfo
            userId      int = 123
        )
        
        destinationList = append(destinationList, UserInfo { 
            UserId          : 23,
        }) 
        destinationList = append(destinationList, UserInfo { 
            UserId          : 12,
        }) 
        
        idx := Find(destinationList, func(value interface{}) bool {
            return value.(UserInfo).UserId == userId
        })
        
        if idx < 0 {
            fmt.Println("not found")
        } else {
            fmt.Println(idx)    
        }
    }
    

    Second method with less computational cost:

    func Search(length int, f func(index int) bool) int {
        for index := 0; index < length; index++ {
            if f(index) {
                return index
            }
        }
        return -1
    }
    

    Uses example:

    type UserInfo struct {
        UserId          int
    }
    
    func main() {
        var (
            destinationList []UserInfo
            userId      int = 123
        )
        
        destinationList = append(destinationList, UserInfo { 
            UserId          : 23,
        }) 
        destinationList = append(destinationList, UserInfo { 
            UserId          : 123,
        }) 
        
        idx := Search(len(destinationList), func(index int) bool {
            return destinationList[index].UserId == userId
        })
        
        if  idx < 0 {
            fmt.Println("not found")
        } else {
            fmt.Println(idx)    
        }
    }
    

    How to print pandas DataFrame without index

    python 2.7

    print df.to_string(index=False)
    

    python 3

    print(df.to_string(index=False))
    

    Print content of JavaScript object?

    Javascript for all!

    String.prototype.repeat = function(num) {
        if (num < 0) {
            return '';
        } else {
            return new Array(num + 1).join(this);
        }
    };
    
    function is_defined(x) {
        return typeof x !== 'undefined';
    }
    
    function is_object(x) {
        return Object.prototype.toString.call(x) === "[object Object]";
    }
    
    function is_array(x) {
        return Object.prototype.toString.call(x) === "[object Array]";
    }
    
    /**
     * Main.
     */
    function xlog(v, label) {
        var tab = 0;
    
        var rt = function() {
            return '    '.repeat(tab);
        };
    
        // Log Fn
        var lg = function(x) {
            // Limit
            if (tab > 10) return '[...]';
            var r = '';
            if (!is_defined(x)) {
                r = '[VAR: UNDEFINED]';
            } else if (x === '') {
                r = '[VAR: EMPTY STRING]';
            } else if (is_array(x)) {
                r = '[\n';
                tab++;
                for (var k in x) {
                    r += rt() + k + ' : ' + lg(x[k]) + ',\n';
                }
                tab--;
                r += rt() + ']';
            } else if (is_object(x)) {
                r = '{\n';
                tab++;
                for (var k in x) {
                    r += rt() + k + ' : ' + lg(x[k]) + ',\n';
                }
                tab--;
                r += rt() + '}';
            } else {
                r = x;
            }
            return r;
        };
    
        // Space
        document.write('\n\n');
    
        // Log
        document.write('< ' + (is_defined(label) ? (label + ' ') : '') + Object.prototype.toString.call(v) + ' >\n' + lg(v));
    };
    
    
    
    // Demo //
    
    var o = {
        'aaa' : 123,
        'bbb' : 'zzzz',
        'o' : {
            'obj1' : 'val1',
            'obj2' : 'val2',
            'obj3' : [1, 3, 5, 6],
            'obj4' : {
                'a' : 'aaaa',
                'b' : null
            }
        },
        'a' : [ 'asd', 123, false, true ],
        'func' : function() {
            alert('test');
        },
        'fff' : false,
        't' : true,
        'nnn' : null
    };
    
    xlog(o, 'Object'); // With label
    xlog(o); // Without label
    
    xlog(['asd', 'bbb', 123, true], 'ARRAY Title!');
    
    var no_definido;
    xlog(no_definido, 'Undefined!');
    
    xlog(true);
    
    xlog('', 'Empty String');
    

    jQuery: Check if button is clicked

    jQuery(':button').click(function () {
        if (this.id == 'button1') {
            alert('Button 1 was clicked');
        }
        else if (this.id == 'button2') {
            alert('Button 2 was clicked');
        }
    });
    

    EDIT:- This will work for all buttons.

    Basic http file downloading and saving to disk in python?

    For Python3+ URLopener is deprecated. And when used you will get error as below:

    url_opener = urllib.URLopener() AttributeError: module 'urllib' has no attribute 'URLopener'

    So, try:

    import urllib.request 
    urllib.request.urlretrieve(url, filename)
    

    Java program to connect to Sql Server and running the sample query From Eclipse

    you forgotten to add the sqlserver.jar in eclipse external library follow the process to add jar files

    1. Right click on your project.
    2. click buildpath
    3. click configure bulid path
    4. click add external jar and then give the path of jar

    How do you add an action to a button programmatically in xcode

    Swift answer:

    myButton.addTarget(self, action: "click:", for: .touchUpInside)
    
    func click(sender: UIButton) {
        print("click")
    }
    

    Documentation: https://developer.apple.com/documentation/uikit/uicontrol/1618259-addtarget