Programs & Examples On #Fireworks

Adobe Fireworks is a bitmap and vector graphics editor aimed at web designers.

How can I drop a table if there is a foreign key constraint in SQL Server?

You have to drop the constraint before drop your table.

You can use those queries to find all FKs in your table and find the FKs in the tables in which your table is used.

Declare @SchemaName VarChar(200) = 'Your Schema name'
Declare @TableName VarChar(200) = 'Your Table Name'

-- Find FK in This table.
SELECT 
    ' IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = 
OBJECT_ID(N''' + 
      '[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']'
+ ''') AND parent_object_id = OBJECT_ID(N''' + 
      '[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + 
OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' +

    'ALTER TABLE ' +  OBJECT_SCHEMA_NAME(FK.parent_object_id) +
    '.[' + OBJECT_NAME(FK.parent_object_id) + 
    '] DROP CONSTRAINT ' + FK.name
    , S.name , O.name, OBJECT_NAME(FK.parent_object_id)
FROM sys.foreign_keys AS FK
INNER JOIN Sys.objects As O 
  ON (O.object_id = FK.parent_object_id )
INNER JOIN SYS.schemas AS S 
  ON (O.schema_id = S.schema_id)  
WHERE 
      O.name = @TableName
      And S.name = @SchemaName


-- Find the FKs in the tables in which this table is used
  SELECT 
    ' IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id =   
      OBJECT_ID(N''' + 
      '[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']'
  + ''') AND parent_object_id = OBJECT_ID(N''' + 
      '[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + 
 OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' +

    ' ALTER TABLE ' +  OBJECT_SCHEMA_NAME(FK.parent_object_id) +
    '.[' + OBJECT_NAME(FK.parent_object_id) + 
    '] DROP CONSTRAINT ' + FK.name
    , S.name , O.name, OBJECT_NAME(FK.parent_object_id)
FROM sys.foreign_keys AS FK
INNER JOIN Sys.objects As O 
  ON (O.object_id = FK.referenced_object_id )
INNER JOIN SYS.schemas AS S 
  ON (O.schema_id = S.schema_id)  
WHERE 
      O.name = @TableName
      And S.name = @SchemaName 

How to remove last n characters from every element in the R vector

Here's a way with gsub:

cs <- c("foo_bar","bar_foo","apple","beer")
gsub('.{3}$', '', cs)
# [1] "foo_" "bar_" "ap"   "b"

Can I make a <button> not submit a form?

Just use good old HTML:

<input type="button" value="Submit" />

Wrap it as the subject of a link, if you so desire:

<a href="http://somewhere.com"><input type="button" value="Submit" /></a>

Or if you decide you want javascript to provide some other functionality:

<input type="button" value="Cancel" onclick="javascript: someFunctionThatCouldIncludeRedirect();"/>

OSError: [WinError 193] %1 is not a valid Win32 application

I too faced same issue and following steps in resolution of this.

  1. I removed unnecessary python path from system except anaconda path.
  2. C:\Users<user-Name>\AppData\Roaming<python> = remove any unnecessary python files /folder. these files may interfere with current execution.

Regards Vj

Clear the entire history stack and start a new activity on Android

I spent a few hours on this too ... and agree that FLAG_ACTIVITY_CLEAR_TOP sounds like what you'd want: clear the entire stack, except for the activity being launched, so the Back button exits the application. Yet as Mike Repass mentioned, FLAG_ACTIVITY_CLEAR_TOP only works when the activity you're launching is already in the stack; when the activity's not there, the flag doesn't do anything.

What to do? Put the activity being launching in the stack with FLAG_ACTIVITY_NEW_TASK, which makes that activity the start of a new task on the history stack. Then add the FLAG_ACTIVITY_CLEAR_TOP flag.

Now, when FLAG_ACTIVITY_CLEAR_TOP goes to find the new activity in the stack, it'll be there and be pulled up before everything else is cleared.

Here's my logout function; the View parameter is the button to which the function's attached.

public void onLogoutClick(final View view) {
    Intent i = new Intent(this, Splash.class);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(i);
    finish();
}

Using ListView : How to add a header view?

You simply can't use View as a Header of ListView.

Because the view which is being passed in has to be inflated.

Look at my answer at Android ListView addHeaderView() nullPointerException for predefined Views for more info.

EDIT:

Look at this tutorial Android ListView and ListActivity - Tutorial .

EDIT 2: This link is broken Android ListActivity with a header or footer

How to use callback with useState hook in react

we can write customise function which will call the callBack function if any changes in the state

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const useStateCallbackWrapper = (initilValue, callBack) => {
  const [state, setState] = useState(initilValue);
  useEffect(() => callBack(state), [state]);
  return [state, setState];
};

const callBack = state => {
  console.log("---------------", state);
};
function App() {
  const [count, setCount] = useStateCallbackWrapper(0, callBack);
  return (
    <div className="App">
      <h1>{count}</h1>
      <button onClick={() => setCount(count + 1)}>+</button>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

`

MD5 is 128 bits but why is it 32 characters?

Those are hexidecimal digits, not characters. One digit = 4 bits.

Save internal file in my own internal folder in Android

The answer of Mintir4 is fine, I would also do the following to load the file.

FileInputStream fis = myContext.openFileInput(fn);
BufferedReader r = new BufferedReader(new InputStreamReader(fis));
String s = "";

while ((s = r.readLine()) != null) {
    txt += s;
}

r.close();

TypeScript Objects as Dictionary types as in C#

You can also use the Record type in typescript :

export interface nameInterface { 
    propName : Record<string, otherComplexInterface> 
}

What is 'PermSize' in Java?

The permament pool contains everything that is not your application data, but rather things required for the VM: typically it contains interned strings, the byte code of defined classes, but also other "not yours" pieces of data.

Difference between "as $key => $value" and "as $value" in PHP foreach

A very important place where it is REQUIRED to use the key => value pair in foreach loop is to be mentioned. Suppose you would want to add a new/sub-element to an existing item (in another key) in the $features array. You should do the following:

foreach($features as $key => $feature) {
    $features[$key]['new_key'] = 'new value';  
} 


Instead of this:

foreach($features as $feature) {
    $feature['new_key'] = 'new value';  
} 

The big difference here is that, in the first case you are accessing the array's sub-value via the main array itself with a key to the element which is currently being pointed to by the array pointer.

While in the second (which doesn't work for this purpose) you are assigning the sub-value in the array to a temporary variable $feature which is unset after each loop iteration.

Pass variables to AngularJS controller, best practice?

I'm not very advanced in AngularJS, but my solution would be to use a simple JS class for you cart (in the sense of coffee script) that extend Array.

The beauty of AngularJS is that you can pass you "model" object with ng-click like shown below.

I don't understand the advantage of using a factory, as I find it less pretty that a CoffeeScript class.

My solution could be transformed in a Service, for reusable purpose. But otherwise I don't see any advantage of using tools like factory or service.

class Basket extends Array
  constructor: ->

  add: (item) ->
    @push(item)

  remove: (item) ->
    index = @indexOf(item)
    @.splice(index, 1)

  contains: (item) ->
    @indexOf(item) isnt -1

  indexOf: (item) ->
    indexOf = -1
    @.forEach (stored_item, index) ->
      if (item.id is stored_item.id)
        indexOf = index
    return indexOf

Then you initialize this in your controller and create a function for that action:

 $scope.basket = new Basket()
 $scope.addItemToBasket = (item) ->
   $scope.basket.add(item)

Finally you set up a ng-click to an anchor, here you pass your object (retreived from the database as JSON object) to the function:

li ng-repeat="item in items"
  a href="#" ng-click="addItemToBasket(item)" 

Insert variable values in the middle of a string

1 You can use string.Replace method

var sample = "testtesttesttest#replace#testtesttest";
var result = sample.Replace("#replace#", yourValue);

2 You can also use string.Format

var result = string.Format("your right part {0} Your left Part", yourValue);

3 You can use Regex class

GROUP BY + CASE statement

Try adding the other two non COUNT columns to the GROUP BY:

select CURRENT_DATE-1 AS day, 
model.name, 
attempt.type, 
CASE WHEN attempt.result = 0 THEN 0 ELSE 1 END, 
count(*) 
from attempt attempt, prod_hw_id prod_hw_id, model model
where time >= '2013-11-06 00:00:00'  
AND time < '2013-11-07 00:00:00'
AND attempt.hard_id = prod_hw_id.hard_id
AND prod_hw_id.model_id = model.model_id
group by 1,2,3,4
order by model.name, attempt.type, attempt.result;

How to set order of repositories in Maven settings.xml

None of these answers were correct in my case.. the order seems dependent on the alphabetical ordering of the <id> tag, which is an arbitrary string. Hence this forced repo search order:

            <repository>
                <id>1_maven.apache.org</id>
                <releases>  <enabled>true</enabled>  </releases>
                <snapshots> <enabled>true</enabled> </snapshots>
                <url>https://repo.maven.apache.org/maven2</url>
                <layout>default</layout>
            </repository>

            <repository>
                <id>2_maven.oracle.com</id>
                <releases>  <enabled>true</enabled>  </releases>
                <snapshots> <enabled>false</enabled> </snapshots>
                <url>https://maven.oracle.com</url>
                <layout>default</layout>
            </repository>

Java using scanner enter key pressed

Scanner scan = new Scanner(System.in);
        int i = scan.nextInt();
        Double d = scan.nextDouble();


        String newStr = "";
        Scanner charScanner = new Scanner( System.in ).useDelimiter( "(\\b|\\B)" ) ;
        while( charScanner.hasNext() ) { 
            String  c = charScanner.next();

            if (c.equalsIgnoreCase("\r")) {
                break;
            }
            else {
                newStr += c;    
            }
        }

        System.out.println("String: " + newStr);
        System.out.println("Int: " + i);
        System.out.println("Double: " + d);

This code works fine

How do I install pip on macOS or OS X?

For those who have both python2 & python3 installed, here's the solution:

python2.7 -m ensurepip --default-pip

Additionally, if you wanna install pip for python3.6:

wget https://bootstrap.pypa.io/get-pip.py
sudo python3.6 get-pip.py

Difference between exit() and sys.exit() in Python

exit is a helper for the interactive shell - sys.exit is intended for use in programs.

The site module (which is imported automatically during startup, except if the -S command-line option is given) adds several constants to the built-in namespace (e.g. exit). They are useful for the interactive interpreter shell and should not be used in programs.


Technically, they do mostly the same: raising SystemExit. sys.exit does so in sysmodule.c:

static PyObject *
sys_exit(PyObject *self, PyObject *args)
{
    PyObject *exit_code = 0;
    if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
        return NULL;
    /* Raise SystemExit so callers may catch it or clean up. */
    PyErr_SetObject(PyExc_SystemExit, exit_code);
   return NULL;
}

While exit is defined in site.py and _sitebuiltins.py, respectively.

class Quitter(object):
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return 'Use %s() or %s to exit' % (self.name, eof)
    def __call__(self, code=None):
        # Shells like IDLE catch the SystemExit, but listen when their
        # stdin wrapper is closed.
        try:
            sys.stdin.close()
        except:
            pass
        raise SystemExit(code)
__builtin__.quit = Quitter('quit')
__builtin__.exit = Quitter('exit')

Note that there is a third exit option, namely os._exit, which exits without calling cleanup handlers, flushing stdio buffers, etc. (and which should normally only be used in the child process after a fork()).

How to disable the parent form when a child form is active?

Are you calling ShowDialog() or just Show() on your child form from the parent form?

ShowDialog will "block" the user from interacting with the form which is passed as a parameter to ShowDialog.

Within the parent you might call something like:

MyChildForm childForm = new MyChildForm();

childForm.ShowDialog(this);

where this is the parent form.

Export from pandas to_excel without row names (index)?

You need to set index=False in to_excel in order for it to not write the index column out, this semantic is followed in other Pandas IO tools, see http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html and http://pandas.pydata.org/pandas-docs/stable/io.html

How to initialize a vector in C++

With the new C++ standard (may need special flags to be enabled on your compiler) you can simply do:

std::vector<int> v { 34,23 };
// or
// std::vector<int> v = { 34,23 };

Or even:

std::vector<int> v(2);
v = { 34,23 };

On compilers that don't support this feature (initializer lists) yet you can emulate this with an array:

int vv[2] = { 12,43 };
std::vector<int> v(&vv[0], &vv[0]+2);

Or, for the case of assignment to an existing vector:

int vv[2] = { 12,43 };
v.assign(&vv[0], &vv[0]+2);

Like James Kanze suggested, it's more robust to have functions that give you the beginning and end of an array:

template <typename T, size_t N>
T* begin(T(&arr)[N]) { return &arr[0]; }
template <typename T, size_t N>
T* end(T(&arr)[N]) { return &arr[0]+N; }

And then you can do this without having to repeat the size all over:

int vv[] = { 12,43 };
std::vector<int> v(begin(vv), end(vv));

Replace last occurrence of a string in a string

Use the "$" on a reg expression to match the end of the string

$string = 'The quick brown fox jumps over the lazy fox';
echo preg_replace('/fox$/', 'dog', $string);

//output
'The quick brown fox jumps over the lazy dog'

Javascript: open new page in same window

I'd take that a slightly different way if I were you. Change the text link when the page loads, not on the click. I'll give the example in jQuery, but it could easily be done in vanilla javascript (though, jQuery is nicer)

$(function() {
    $('a[href$="url="]')    // all links whose href ends in "url="
        .each(function(i, el) {
            this.href += escape(document.location.href);
        })
    ;
});

and write your HTML like this:

<a href="http://example.com/submit.php?url=">...</a>

the benefits of this are that people can see what they're clicking on (the href is already set), and it removes the javascript from your HTML.

All this said, it looks like you're using PHP... why not add it in server-side?

Classes residing in App_Code is not accessible

Put this at the top of the other files where you want to access the class:

using CLIck10.App_Code;

OR access the class from other files like this:

CLIck10.App_Code.Glob

Not sure if that's your issue or not but if you were new to C# then this is an easy one to get tripped up on.

Update: I recently found that if I add an App_Code folder to a project, then I must close/reopen Visual Studio for it to properly recognize this "special" folder.

How to use Jquery how to change the aria-expanded="false" part of a dom element (Bootstrap)?

Since the question asked for either jQuery or vanilla JS, here's an answer with vanilla JS.

I've added some CSS to the demo below to change the button's font color to red when its aria-expanded is set to true

_x000D_
_x000D_
const button = document.querySelector('button');_x000D_
_x000D_
button.addEventListener('click', () => {_x000D_
  button.ariaExpanded = !JSON.parse(button.ariaExpanded);_x000D_
})
_x000D_
button[aria-expanded="true"] {_x000D_
  color: red;_x000D_
}
_x000D_
<button type="button" aria-expanded="false">Click me!</button>
_x000D_
_x000D_
_x000D_

What does the line "#!/bin/sh" mean in a UNIX shell script?

#!/bin/sh or #!/bin/bash has to be first line of the script because if you don't use it on the first line then the system will treat all the commands in that script as different commands. If the first line is #!/bin/sh then it will consider all commands as a one script and it will show the that this file is running in ps command and not the commands inside the file.

./echo.sh

ps -ef |grep echo
trainee   3036  2717  0 16:24 pts/0    00:00:00 /bin/sh ./echo.sh
root      3042  2912  0 16:24 pts/1    00:00:00 grep --color=auto echo

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

.NET does this for you. In your AssemblyInfo.cs file, set your assembly version to major.minor.* (for example: 1.0.*).

When you build your project the version is auto generated.

The build and revision numbers are generated based on the date, using the unix epoch, I believe. The build is based on the current day, and the revision is based on the number of seconds since midnight.

How to set the font style to bold, italic and underlined in an Android TextView?

I don't know about underline, but for bold and italic there is "bolditalic". There is no mention of underline here: http://developer.android.com/reference/android/widget/TextView.html#attr_android:textStyle

Mind you that to use the mentioned bolditalic you need to, and I quote from that page

Must be one or more (separated by '|') of the following constant values.

so you'd use bold|italic

You could check this question for underline: Can I underline text in an android layout?

How to position the div popup dialog to the center of browser screen?

You can use CSS3 'transform':

CSS:

.popup-bck{
  background-color: rgba(102, 102, 102, .5);
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 10;
}
.popup-content-box{
  background-color: white;
  position: fixed;
  top: 50%;
  left: 50%;
  z-index: 11;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}

HTML:

<div class="popup-bck"></div>
<div class="popup-content-box">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
</div>

*so you don't have to use margin-left: -width/2 px;

Error 'tunneling socket' while executing npm install

I faced similar and tried some of the techniques mentioned here. To overcome,

I performed a cleanup of duplicate entries in c:\users\<user name>\.npmrc

Hope it helps someone. Thanks,

android pinch zoom

For android 2.2+ (api level8), you can use ScaleGestureDetector.

you need a member:

private ScaleGestureDetector mScaleDetector;

in your constructor (or onCreate()) you add:

mScaleDetector = new ScaleGestureDetector(context, new OnScaleGestureListener() {
    @Override
    public void onScaleEnd(ScaleGestureDetector detector) {
    }
    @Override
    public boolean onScaleBegin(ScaleGestureDetector detector) {
        return true;
    }
    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        Log.d(LOG_KEY, "zoom ongoing, scale: " + detector.getScaleFactor());
        return false;
    }
});

You override onTouchEvent:

@Override
public boolean onTouchEvent(MotionEvent event) {
    mScaleDetector.onTouchEvent(event);
    return true;
}

If you draw your View by hand, in the onScale() you probably do store the scale factor in a member, then call invalidate() and use the scale factor when drawing in your onDraw(). Otherwise you can directly modify font sizes or things like that in the onScale().

What is the difference between background, backgroundTint, backgroundTintMode attributes in android layout xml?

The backgroundTint attribute will help you to add a tint(shade) to the background. You can provide a color value for the same in the form of - "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

The backgroundTintMode on the other hand will help you to apply the background tint. It must have constant values like src_over, src_in, src_atop, etc.

Refer this to get a clear idea of the the constant values that can be used. Search for the backgroundTint attribute and the description along with various attributes will be available.

How can I get the named parameters from a URL using Flask?

If you have a single argument passed in the URL you can do it as follows

from flask import request
#url
http://10.1.1.1:5000/login/alex

from flask import request
@app.route('/login/<username>', methods=['GET'])
def login(username):
    print(username)

In case you have multiple parameters:

#url
http://10.1.1.1:5000/login?username=alex&password=pw1

from flask import request
@app.route('/login', methods=['GET'])
    def login():
        username = request.args.get('username')
        print(username)
        password= request.args.get('password')
        print(password)

What you were trying to do works in case of POST requests where parameters are passed as form parameters and do not appear in the URL. In case you are actually developing a login API, it is advisable you use POST request rather than GET and expose the data to the user.

In case of post request, it would work as follows:

#url
http://10.1.1.1:5000/login

HTML snippet:

<form action="http://10.1.1.1:5000/login" method="POST">
  Username : <input type="text" name="username"><br>
  Password : <input type="password" name="password"><br>
  <input type="submit" value="submit">
</form>

Route:

from flask import request
@app.route('/login', methods=['POST'])
    def login():
        username = request.form.get('username')
        print(username)
        password= request.form.get('password')
        print(password)

How to set an button align-right with Bootstrap?

<div class="container">
    <div class="btn-block pull-right">
        <a href="#" class="btn btn-primary pull-right">Search</a>
        <a href="#" class="btn btn-primary pull-right">Apple</a>
        <a href="#" class="btn btn-primary pull-right">Sony</a>
    </div>
</div>

Inversion of Control vs Dependency Injection

IOC (Inversion of Control) is basically design pattern concept of removing dependencies and decoupling them to making the flow non-linear , and let the container / or another entity manage the provisioning of dependencies. It actually follow Hollywood principal “Don’t call us we will call you”. So summarizing the differences.

Inversion of control :- It’s a generic term to decouple the dependencies and delegate their provisioning , and this can be implemented in several ways (events, delegates etc).

Dependency injection :- DI is a subtype of IOC and is implemented by constructor injection, setter injection or method injection.

The following article describe this very neatly.

https://www.codeproject.com/Articles/592372/Dependency-Injection-DI-vs-Inversion-of-Control-IO

datetime datatype in java

+1 the recommendation for Joda-time. If you plan on doing anything more than a simple Hello World example, I suggest reading this:

Daylight saving time and time zone best practices

Why am I getting AttributeError: Object has no attribute

I got this error for multi-threading scenario (specifically when dealing with ZMQ). It turned out that socket was still being connected on one thread while another thread already started sending data. The events that occured due to another thread tried to access variables that weren't created yet. If your scenario involves multi-threading and if things work if you add bit of delay then you might have similar issue.

How to use group by with union in t-sql

You need to alias the subquery. Thus, your statement should be:

Select Z.id
From    (
        Select id, time
        From dbo.tablea
        Union All
        Select id, time
        From dbo.tableb
        ) As Z
Group By Z.id

Storing C++ template function definitions in a .CPP file

The problem you describe can be solved by defining the template in the header, or via the approach you describe above.

I recommend reading the following points from the C++ FAQ Lite:

They go into a lot of detail about these (and other) template issues.

How to get the current time in Python

Do

from time import time

t = time()
  • t - float number, good for time interval measurement.

There is some difference for Unix and Windows platforms.

how can I enable PHP Extension intl?

Use phpinfo() function to find php.ini file path, open php.ini file. Here search extension=php_intl.dll then remove semi-colon (;) beginning of that line.

After removing semi-colon (;) restart you webserver (apache).

How can I get the current array index in a foreach loop?

foreach($array as $key=>$value) {
    // do stuff
}

$key is the index of each $array element

Drop all the tables, stored procedures, triggers, constraints and all the dependencies in one sql statement

To drop all tables:

exec sp_MSforeachtable 'DROP TABLE ?'

This will, of course, drop all constraints, triggers etc., everything but the stored procedures.

For the stored procedures I'm afraid you will need another stored procedure stored in master.

How to insert text at beginning of a multi-line selection in vi/Vim

Mark the area to be comment as a visual block (<C-V)

and do c#<ESC>p

  1. change it to "#"
  2. put it back

If you do it often, define a short cut (example \q) in your .vimrc

:vmap \q c#<ESC>p

Difference between abstraction and encapsulation?

class Aeroplane : IFlyable, IFuelable, IMachine
{ // Aeroplane's Design says:
  // Aeroplane is a flying object
  // Aeroplane can be fueled
  // Aeroplane is a Machine
}
// But the code related to Pilot, or Driver of Aeroplane is not bothered 
// about Machine or Fuel. Hence,
// pilot code:
IFlyable flyingObj = new Aeroplane();
flyingObj.Fly();
// fighter Pilot related code
IFlyable flyingObj2 = new FighterAeroplane();
flyingObj2.Fly();
// UFO related code 
IFlyable ufoObj = new UFO();
ufoObj.Fly();
// **All the 3 Above codes are genaralized using IFlyable,
// Interface Abstraction**
// Fly related code knows how to fly, irrespective of the type of 
// flying object they are.

// Similarly, Fuel related code:
// Fueling an Aeroplane
IFuelable fuelableObj = new Aeroplane();
fuelableObj.FillFuel();
// Fueling a Car
IFuelable fuelableObj2 = new Car(); // class Car : IFuelable { }
fuelableObj2.FillFuel();

// ** Fueling code does not need know what kind of vehicle it is, so far 
// as it can Fill Fuel**

Set textbox to readonly and background color to grey in jquery

Can add disable like below and can get data on submit. something like this .. DEMO

Html

<input type="hidden" name="email" value="email" />
<input type="text" id="dis" class="disable" value="email"   name="email" >

JS

 $("#dis").attr('disabled','disabled');

CSS

    .disable { opacity : .35; background-color:lightgray; border:1px solid gray;}

How do I drag and drop files into an application?

Be aware of windows vista/windows 7 security rights - if you are running Visual Studio as administrator, you will not be able to drag files from a non-administrator explorer window into your program when you run it from within visual studio. The drag related events will not even fire! I hope this helps somebody else out there not waste hours of their life...

Why does Java have an "unreachable statement" compiler error?

It is Nanny. I feel .Net got this one right - it raises a warning for unreachable code, but not an error. It is good to be warned about it, but I see no reason to prevent compilation (especially during debugging sessions where it is nice to throw a return in to bypass some code).

What's the difference between a POST and a PUT HTTP REQUEST?

Define operations in terms of HTTP methods

The HTTP protocol defines a number of methods that assign semantic meaning to a request. The common HTTP methods used by most RESTful web APIs are:

GET retrieves a representation of the resource at the specified URI. The body of the response message contains the details of the requested resource.

POST creates a new resource at the specified URI. The body of the request message provides the details of the new resource. Note that POST can also be used to trigger operations that don't actually create resources.

PUT either creates or replaces the resource at the specified URI. The body of the request message specifies the resource to be created or updated.

PATCH performs a partial update of a resource. The request body specifies the set of changes to apply to the resource.

DELETE removes the resource at the specified URI.

The effect of a specific request should depend on whether the resource is a collection or an individual item. The following table summarizes the common conventions adopted by most RESTful implementations using the e-commerce example. Not all of these requests might be implemented—it depends on the specific scenario.

Resource POST GET PUT DELETE
/customers Create a new customer Retrieve all customers Bulk update of customers Remove all customers
/customers/1 Error Retrieve the details for customer 1 Update the details of customer 1 if it exists Remove customer 1
/customers/1/orders Create a new order for customer 1 Retrieve all orders for customer 1 Bulk update of orders for customer 1 Remove all orders for customer 1

The differences between POST, PUT, and PATCH can be confusing.

A POST request creates a resource. The server assigns a URI for the new resource and returns that URI to the client. In the REST model, you frequently apply POST requests to collections. The new resource is added to the collection. A POST request can also be used to submit data for processing to an existing resource, without any new resource being created.

A PUT request creates a resource or updates an existing resource. The client specifies the URI for the resource. The request body contains a complete representation of the resource. If a resource with this URI already exists, it is replaced. Otherwise, a new resource is created, if the server supports doing so. PUT requests are most frequently applied to resources that are individual items, such as a specific customer, rather than collections. A server might support updates but not creation via PUT. Whether to support creation via PUT depends on whether the client can meaningfully assign a URI to a resource before it exists. If not, then use POST to create resources and PUT or PATCH to update.

A PATCH request performs a partial update to an existing resource. The client specifies the URI for the resource. The request body specifies a set of changes to apply to the resource. This can be more efficient than using PUT, because the client only sends the changes, not the entire representation of the resource. Technically PATCH can also create a new resource (by specifying a set of updates to a "null" resource), if the server supports this.

PUT requests must be idempotent. If a client submits the same PUT request multiple times, the results should always be the same (the same resource will be modified with the same values). POST and PATCH requests are not guaranteed to be idempotent.

Set ImageView width and height programmatically?

If your image view is dynamic, the answer containing getLayout will fail with null-exception.

In that case the correct way is:

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(100, 100);
iv.setLayoutParams(layoutParams);

Get the value in an input text box

There is one important thing to mention:

$("#txt_name").val();

will return the current real value of a text field, for example if the user typed something there after a page load.

But:

$("#txt_name").attr('value')

will return value from DOM/HTML.

Android toolbar center title and custom font

To use a custom title in your Toolbar all you need to do is remember is that Toolbar is just a fancy ViewGroup so you can add a custom title like so:

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar_top"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:minHeight="?attr/actionBarSize"
    android:background="@color/action_bar_bkgnd"
    app:theme="@style/ToolBarTheme" >


     <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Toolbar Title"
        android:layout_gravity="center"
        android:id="@+id/toolbar_title" />


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

This means that you can style the TextView however you would like because it's just a regular TextView. So in your activity you can access the title like so:

Toolbar toolbarTop = (Toolbar) findViewById(R.id.toolbar_top);
TextView mTitle = (TextView) toolbarTop.findViewById(R.id.toolbar_title);

How to nicely format floating numbers to string without unnecessary decimal 0's

Format price with grouping, rounding, and no unnecessary zeroes (in double).

Rules:

  1. No zeroes at the end (2.0000 = 2; 1.0100000 = 1.01)
  2. Two digits maximum after a point (2.010 = 2.01; 0.20 = 0.2)
  3. Rounding after the 2nd digit after a point (1.994 = 1.99; 1.995 = 2; 1.006 = 1.01; 0.0006 -> 0)
  4. Returns 0 (null/-0 = 0)
  5. Adds $ (= $56/-$56)
  6. Grouping (101101.02 = $101,101.02)

More examples:

-99.985 = -$99.99

10 = $10

10.00 = $10

20.01000089 = $20.01

It is written in Kotlin as a fun extension of Double (because it is used in Android), but it can be converted to Java easily, because Java classes were used.

/**
 * 23.0 -> $23
 *
 * 23.1 -> $23.1
 *
 * 23.01 -> $23.01
 *
 * 23.99 -> $23.99
 *
 * 23.999 -> $24
 *
 * -0.0 -> $0
 *
 * -5.00 -> -$5
 *
 * -5.019 -> -$5.02
 */
fun Double?.formatUserAsSum(): String {
    return when {
        this == null || this == 0.0 -> "$0"
        this % 1 == 0.0 -> DecimalFormat("$#,##0;-$#,##0").format(this)
        else -> DecimalFormat("$#,##0.##;-$#,##0.##").format(this)
    }
}

How to use:

var yourDouble: Double? = -20.00
println(yourDouble.formatUserAsSum()) // will print -$20

yourDouble = null
println(yourDouble.formatUserAsSum()) // will print $0

About DecimalFormat: https://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html

How can I make grep print the lines below and above each matching line?

Use -B, -A or -C option

grep --help
...
-B, --before-context=NUM  print NUM lines of leading context
-A, --after-context=NUM   print NUM lines of trailing context
-C, --context=NUM         print NUM lines of output context
-NUM                      same as --context=NUM
...

LINK : fatal error LNK1104: cannot open file 'D:\...\MyProj.exe'

You might have not closed the the output. Close the output, clean and rebuild the file. You might be able to run the file now.

How do I read the first line of a file using cat?

There is plenty of good answer to this question. Just gonna drop another one into the basket if you wish to do it with lolcat

lolcat FileName.csv | head -n 1

How to position the form in the center screen?

Try using this:

this.setBounds(x,y,w,h);

How do I make case-insensitive queries on Mongodb?

  1. With Mongoose (and Node), this worked:

    • User.find({ email: /^[email protected]$/i })

    • User.find({ email: new RegExp(`^${emailVariable}$`, 'i') })

  2. In MongoDB, this worked:

Both lines are case-insensitive. The email in the DB could be [email protected] and both lines will still find the object in the DB.

Likewise, we could use /^[email protected]$/i and it would still find email: [email protected] in the DB.

How do I set a textbox's value using an anchor with jQuery?

I wrote this code snippet and it works fine:

<a href="#" class="clickable">Blah</a>
<input id="textbox">
<script type="text/javascript">
    $(document).ready(function(){
        $("a.clickable").click(function(event){
            event.preventDefault();
            $("input#textbox").val($(this).html());
        });  
    });
</script>

Maybe you forgot to give a class name "clickable" to your links?

What is the 'dynamic' type in C# 4.0 used for?

It makes it easier for static typed languages (CLR) to interoperate with dynamic ones (python, ruby ...) running on the DLR (dynamic language runtime), see MSDN:

For example, you might use the following code to increment a counter in XML in C#.

Scriptobj.SetProperty("Count", ((int)GetProperty("Count")) + 1);

By using the DLR, you could use the following code instead for the same operation.

scriptobj.Count += 1;

MSDN lists these advantages:

  • Simplifies Porting Dynamic Languages to the .NET Framework
  • Enables Dynamic Features in Statically Typed Languages
  • Provides Future Benefits of the DLR and .NET Framework
  • Enables Sharing of Libraries and Objects
  • Provides Fast Dynamic Dispatch and Invocation

See MSDN for more details.

What is a LAMP stack?

For anyone still looking into this in order to learn specifically what a stack is, the term "stack" is referring to a "solution stack." A solution stack is simply a complete set of software to address a given problem, usually by combining to provide the platform or infrastructure necessary. This term is the parent of both "server stack" and "web stack." Accordingly, a LAMP stack is a specific and complete set of software specifically aimed at serving dynamic content over the web.

Some extra reading:

https://www.techopedia.com/definition/28154/solution-stack https://en.wikipedia.org/wiki/Solution_stack

Handling urllib2's timeout? - Python

There are very few cases where you want to use except:. Doing this captures any exception, which can be hard to debug, and it captures exceptions including SystemExit and KeyboardInterupt, which can make your program annoying to use..

At the very simplest, you would catch urllib2.URLError:

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
    raise MyException("There was an error: %r" % e)

The following should capture the specific error raised when the connection times out:

import urllib2
import socket

class MyException(Exception):
    pass

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
    # For Python 2.6
    if isinstance(e.reason, socket.timeout):
        raise MyException("There was an error: %r" % e)
    else:
        # reraise the original error
        raise
except socket.timeout, e:
    # For Python 2.7
    raise MyException("There was an error: %r" % e)

How to list active connections on PostgreSQL?

SELECT * FROM pg_stat_activity WHERE datname = 'dbname' and state = 'active';

Since pg_stat_activity contains connection statistics of all databases having any state, either idle or active, database name and connection state should be included in the query to get the desired output.

Why does npm install say I have unmet dependencies?

I was trying to work on an automated deployment system that runs npm install, so a lot of these solutions wouldn't work for me in an automated fasion. I wasn't in a position to go deleting/re-creating node_modules/ nor could I easily change Node.js versions.

So I ended up running npm shrinkwrap - adding the npm-shrinkwrap.json file to my deployment bundle, and running installs from there. That fixed the problem for me; with the shrinkwrap file as a 'helper', npm seemed to be able to find the right packages and get them installed for me. (Shrinkwrap has other features as well, but this was what I needed it for in this particular case).

Allow anything through CORS Policy

Have a look at the rack-cors middleware. It will handle CORS headers in a configurable manner.

How can I make SQL case sensitive string comparison on MySQL?

You can use BINARY to case sensitive like this

select * from tb_app where BINARY android_package='com.Mtime';

unfortunately this sql can't use index, you will suffer a performance hit on queries reliant on that index

mysql> explain select * from tb_app where BINARY android_package='com.Mtime';
+----+-------------+--------+------------+------+---------------+------+---------+------+---------+----------+-------------+
| id | select_type | table  | partitions | type | possible_keys | key  | key_len | ref  | rows    | filtered | Extra       |
+----+-------------+--------+------------+------+---------------+------+---------+------+---------+----------+-------------+
|  1 | SIMPLE      | tb_app | NULL       | ALL  | NULL          | NULL | NULL    | NULL | 1590351 |   100.00 | Using where |
+----+-------------+--------+------------+------+---------------+------+---------+------+---------+----------+-------------+

Fortunately, I have a few tricks to solve this problem

mysql> explain select * from tb_app where android_package='com.Mtime' and BINARY android_package='com.Mtime';
+----+-------------+--------+------------+------+---------------------------+---------------------------+---------+-------+------+----------+-----------------------+
| id | select_type | table  | partitions | type | possible_keys             | key                       | key_len | ref   | rows | filtered | Extra                 |
+----+-------------+--------+------------+------+---------------------------+---------------------------+---------+-------+------+----------+-----------------------+
|  1 | SIMPLE      | tb_app | NULL       | ref  | idx_android_pkg           | idx_android_pkg           | 771     | const |    1 |   100.00 | Using index condition |
+----+-------------+--------+------------+------+---------------------------+---------------------------+---------+-------+------+----------+-----------------------+  

How to start an Android application from the command line?

adb shell
am start -n com.package.name/com.package.name.ActivityName

Or you can use this directly:

adb shell am start -n com.package.name/com.package.name.ActivityName

You can also specify actions to be filter by your intent-filters:

am start -a com.example.ACTION_NAME -n com.package.name/com.package.name.ActivityName

Regular Expressions- Match Anything

Try this:

I bought (.* )?sheep

or even

I bought .*sheep

Xcode: failed to get the task for process

Change the profile for code signing. Select your project, go to Build Settings > Code Signing Identity. Switch to other developer profile.

Populating a razor dropdownlist from a List<object> in MVC

Your call to DropDownListFor needs a few more parameters to flesh it out. You need a SelectList as in the following SO question:

MVC3 DropDownListFor - a simple example?

With what you have there, you've only told it where to store the data, not where to load the list from.

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

Using "includes" to test if the element already exists.

_x000D_
_x000D_
var arr = [1, 1, 4, 5, 5], darr = [], duplicates = [];_x000D_
_x000D_
for(var i = 0; i < arr.length; i++){_x000D_
  if(darr.includes(arr[i]) && !duplicates.includes(arr[i]))_x000D_
    duplicates.push(arr[i])_x000D_
  else_x000D_
    darr.push(arr[i]);_x000D_
}_x000D_
_x000D_
console.log(duplicates);
_x000D_
<h3>Array with duplicates</h3>_x000D_
<p>[1, 1, 4, 5, 5]</p>_x000D_
<h3>Array with distinct elements</h3>_x000D_
<p>[1, 4, 5]</p>_x000D_
<h3>duplicate values are</h3>_x000D_
<p>[1, 5]</p>
_x000D_
_x000D_
_x000D_

Message Queue vs. Web Services?

Message queues are asynchronous and can retry a number of times if delivery fails. Use a message queue if the requester doesn't need to wait for a response.

The phrase "web services" make me think of synchronous calls to a distributed component over HTTP. Use web services if the requester needs a response back.

How to write log to file

I usually print the logs on screen and write into a file as well. Hope this helps someone.

f, err := os.OpenFile("/tmp/orders.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
    log.Fatalf("error opening file: %v", err)
}
defer f.Close()
wrt := io.MultiWriter(os.Stdout, f)
log.SetOutput(wrt)
log.Println(" Orders API Called")

Scrollbar without fixed height/Dynamic height with scrollbar

I don't know if I got it right, but does this solve your problem?

I just changed the overflow-y: scroll;

#content{
    border: red solid 1px;
    overflow-y: scroll;
    height: 100px;
}

Edited

Then try to use percentage values like this: http://jsfiddle.net/6WAnd/19/

CSS markup:

#body {
    position: absolute;
    top; 150px;
    left: 150px;
    height: 98%;
    width: 500px;
    border: black dashed 2px;
}    
#head {
    border: green solid 1px;
    height: 15%;
}
#content{
    border: red solid 1px;
    overflow-y: scroll;
    height: 70%;
}
#foot {
    border: blue solid 1px;
    height: 15%;
}

How to edit Docker container files from the host?

The best way is:

  $ docker cp CONTAINER:FILEPATH LOCALFILEPATH
  $ vi LOCALFILEPATH
  $ docker cp LOCALFILEPATH CONTAINER:FILEPATH

Limitations with $ docker exec: it can only attach to a running container.

Limitations with $ docker run: it will create a new container.

How Can I Truncate A String In jQuery?

From: jQuery text truncation (read more style)

Try this:

var title = "This is your title";

var shortText = jQuery.trim(title).substring(0, 10)
    .split(" ").slice(0, -1).join(" ") + "...";

And you can also use a plugin:

As a extension of String

String.prototype.trimToLength = function(m) {
  return (this.length > m) 
    ? jQuery.trim(this).substring(0, m).split(" ").slice(0, -1).join(" ") + "..."
    : this;
};

Use as

"This is your title".trimToLength(10);

Adding text to ImageView in Android

Best Option to use text and image in a single view try this:

<TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:drawableBottom="@drawable/ic_launcher"

        android:text="TextView" />

How to generate XML from an Excel VBA macro?

This one more version - this will help in generic

Public strSubTag As String
Public iStartCol As Integer
Public iEndCol As Integer
Public strSubTag2 As String
Public iStartCol2 As Integer
Public iEndCol2 As Integer

Sub Create()
Dim strFilePath As String
Dim strFileName As String

'ThisWorkbook.Sheets("Sheet1").Range("C3").Activate
'strTag = ActiveCell.Offset(0, 1).Value
strFilePath = ThisWorkbook.Sheets("Sheet1").Range("B4").Value
strFileName = ThisWorkbook.Sheets("Sheet1").Range("B5").Value
strSubTag = ThisWorkbook.Sheets("Sheet1").Range("F3").Value
iStartCol = ThisWorkbook.Sheets("Sheet1").Range("F4").Value
iEndCol = ThisWorkbook.Sheets("Sheet1").Range("F5").Value

strSubTag2 = ThisWorkbook.Sheets("Sheet1").Range("G3").Value
iStartCol2 = ThisWorkbook.Sheets("Sheet1").Range("G4").Value
iEndCol2 = ThisWorkbook.Sheets("Sheet1").Range("G5").Value

Dim iCaptionRow As Integer
iCaptionRow = ThisWorkbook.Sheets("Sheet1").Range("B3").Value
'strFileName = ThisWorkbook.Sheets("Sheet1").Range("B4").Value
MakeXML iCaptionRow, iCaptionRow + 1, strFilePath, strFileName

End Sub


Sub MakeXML(iCaptionRow As Integer, iDataStartRow As Integer, sOutputFilePath As String, sOutputFileName As String)
    Dim Q As String
    Dim sOutputFileNamewithPath As String
    Q = Chr$(34)

    Dim sXML As String


    'sXML = sXML & "<rows>"

'    ''--determine count of columns
    Dim iColCount As Integer
    iColCount = 1

    While Trim$(Cells(iCaptionRow, iColCount)) > ""
        iColCount = iColCount + 1
    Wend


    Dim iRow As Integer
    Dim iCount  As Integer
    iRow = iDataStartRow
    iCount = 1
    While Cells(iRow, 1) > ""
        'sXML = sXML & "<row id=" & Q & iRow & Q & ">"
        sXML = "<?xml version=" & Q & "1.0" & Q & " encoding=" & Q & "UTF-8" & Q & "?>"
        For iCOl = 1 To iColCount - 1
          If (iStartCol = iCOl) Then
               sXML = sXML & "<" & strSubTag & ">"
          End If
          If (iEndCol = iCOl) Then
               sXML = sXML & "</" & strSubTag & ">"
          End If
         If (iStartCol2 = iCOl) Then
               sXML = sXML & "<" & strSubTag2 & ">"
          End If
          If (iEndCol2 = iCOl) Then
               sXML = sXML & "</" & strSubTag2 & ">"
          End If
           sXML = sXML & "<" & Trim$(Cells(iCaptionRow, iCOl)) & ">"
           sXML = sXML & Trim$(Cells(iRow, iCOl))
           sXML = sXML & "</" & Trim$(Cells(iCaptionRow, iCOl)) & ">"
        Next

        'sXML = sXML & "</row>"
        Dim nDestFile As Integer, sText As String

    ''Close any open text files
        Close

    ''Get the number of the next free text file
        nDestFile = FreeFile
        sOutputFileNamewithPath = sOutputFilePath & sOutputFileName & iCount & ".XML"
    ''Write the entire file to sText
        Open sOutputFileNamewithPath For Output As #nDestFile
        Print #nDestFile, sXML

        iRow = iRow + 1
        sXML = ""
        iCount = iCount + 1
    Wend
    'sXML = sXML & "</rows>"

    Close
End Sub

Display tooltip on Label's hover?

Tooltips in bootstrap are good, but there is also a very good tooltip function in jQuery UI, which you can read about here.

Example:

<label for="male" id="foo" title="Hello This Will Have Some Value">Hello...</label>

Then, assuming you have already referenced jQuery and jQueryUI libraries in your head, add a script element like this:

<script type="text/javascript">
$(document).ready(function(){
    $(this).tooltip();
});
</script>

This will display the contents of the title attribute as a tooltip when you rollover any element with a title attribute.

MySQL JDBC Driver 5.1.33 - Time Zone Issue

I have the same problem and i solved it append only "?serverTimezone=UTC" to my string connection.

#

sinossi my problem:

java.sql.SQLException: The server time zone value 'CEST' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.

my dbDriver = com.mysql.jdbc.Driver

my jar = mysql-connector-java-8.0.12.jar

my java = 1.8

my tomcat = Apache Tomcat Version 8.5.32

my MySql server = MySql ver.8.0.12 

Mockito matcher and array of primitives

I agree with Mutanos and Alecio. Further, one can check as many identical method calls as possible (verifying the subsequent calls in the production code, the order of the verify's does not matter). Here is the code:

import static org.mockito.AdditionalMatchers.*;

    verify(mockObject).myMethod(aryEq(new byte[] { 0 }));
    verify(mockObject).myMethod(aryEq(new byte[] { 1, 2 }));

jQuery - how to write 'if not equal to' (opposite of ==)

The opposite of the == compare operator is !=.

C++ error : terminate called after throwing an instance of 'std::bad_alloc'

Something throws an exception of type std::bad_alloc, indicating that you ran out of memory. This exception is propagated through until main, where it "falls off" your program and causes the error message you see.

Since nobody here knows what "RectInvoice", "rectInvoiceVector", "vect", "im" and so on are, we cannot tell you what exactly causes the out-of-memory condition. You didn't even post your real code, because w h looks like a syntax error.

Splitting string with pipe character ("|")

Using Pattern.quote()

String[] value_split = rat_values.split(Pattern.quote("|"));

//System.out.println(Arrays.toString(rat_values.split(Pattern.quote("|")))); //(FOR GETTING OUTPUT)

Using Escape characters(for metacharacters)

String[] value_split = rat_values.split("\\|");
//System.out.println(Arrays.toString(rat_values.split("\\|"))); //(FOR GETTING OUTPUT)

Using StringTokenizer(For avoiding regular expression issues)

public static String[] splitUsingTokenizer(String Subject, String Delimiters) 
{
     StringTokenizer StrTkn = new StringTokenizer(Subject, Delimiters);
     ArrayList<String> ArrLis = new ArrayList<String>(Subject.length());
     while(StrTkn.hasMoreTokens())
     {
       ArrLis.add(StrTkn.nextToken());
     }
     return ArrLis.toArray(new String[0]);
}

Using Pattern class(java.util.regex.Pattern)

Arrays.asList(Pattern.compile("\\|").split(rat_values))
//System.out.println(Arrays.asList(Pattern.compile("\\|").split(rat_values))); //(FOR GETTING OUTPUT)

Output

[Food 1 ,  Service 3 ,  Atmosphere 3 ,  Value for money 1 ]

The difference between sys.stdout.write and print?

>>> sys.stdout.write(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected a string or other character buffer object
>>> sys.stdout.write("a")
a>>> sys.stdout.write("a") ; print(1)
a1

Observing the example above:

  1. sys.stdout.write won't write non-string object, but print will

  2. sys.stdout.write won't add a new line symbol in the end, but print will

If we dive deeply,

sys.stdout is a file object which can be used for the output of print()

if file argument of print() is not specified, sys.stdout will be used

How to navigate back to the last cursor position in Visual Studio Code?

The answer for your question:

  1. Mac:
    (Alt+?) For backward and (Alt+?) For forward navigation
  2. Windows:
    (Ctrl+-) For backward and (Ctrl+Shift+-) For forward navigation
  3. Linux:
    (Ctrl+Alt+-) For backward and (Ctrl+Shift+-) For forward navigation


You can find out the current key-bindings following this link

You can even edit the key-binding as per your preference.

Bash script prints "Command Not Found" on empty lines

for executing that you must provide full path of that for example

/home/Manuel/mywrittenscript

How to convert a string to lower case in Bash?

For a standard shell (without bashisms) using only builtins:

uppers=ABCDEFGHIJKLMNOPQRSTUVWXYZ
lowers=abcdefghijklmnopqrstuvwxyz

lc(){ #usage: lc "SOME STRING" -> "some string"
    i=0
    while ([ $i -lt ${#1} ]) do
        CUR=${1:$i:1}
        case $uppers in
            *$CUR*)CUR=${uppers%$CUR*};OUTPUT="${OUTPUT}${lowers:${#CUR}:1}";;
            *)OUTPUT="${OUTPUT}$CUR";;
        esac
        i=$((i+1))
    done
    echo "${OUTPUT}"
}

And for upper case:

uc(){ #usage: uc "some string" -> "SOME STRING"
    i=0
    while ([ $i -lt ${#1} ]) do
        CUR=${1:$i:1}
        case $lowers in
            *$CUR*)CUR=${lowers%$CUR*};OUTPUT="${OUTPUT}${uppers:${#CUR}:1}";;
            *)OUTPUT="${OUTPUT}$CUR";;
        esac
        i=$((i+1))
    done
    echo "${OUTPUT}"
}

convert a JavaScript string variable to decimal/money

It is fairly risky to rely on javascript functions to compare and play with numbers. In javascript (0.1+0.2 == 0.3) will return false due to rounding errors. Use the math.js library.

Make Https call using HttpClient

Your code should be modified in this way:

httpClient.BaseAddress = new Uri("https://foobar.com/");

You have just to use the https: URI scheme. There's a useful page here on MSDN about the secure HTTP connections. Indeed:

Use the https: URI scheme

The HTTP Protocol defines two URI schemes:

http : Used for unencrypted connections.

https : Used for secure connections that should be encrypted. This option also uses digital certificates and certificate authorities to verify that the server is who it claims to be.

Moreover, consider that the HTTPS connections use a SSL certificate. Make sure your secure connection has this certificate otherwise the requests will fail.

EDIT:

Above code works fine for making http calls. But when I change the scheme to https it does not work, let me post the error.

What does it mean doesn't work? The requests fail? An exception is thrown? Clarify your question.

If the requests fail, then the issue should be the SSL certificate.

To fix the issue, you can use the class HttpWebRequest and then its property ClientCertificate. Furthermore, you can find here a useful sample about how to make a HTTPS request using the certificate.

An example is the following (as shown in the MSDN page linked before):

//You must change the path to point to your .cer file location. 
X509Certificate Cert = X509Certificate.CreateFromCertFile("C:\\mycert.cer");
// Handle any certificate errors on the certificate from the server.
ServicePointManager.CertificatePolicy = new CertPolicy();
// You must change the URL to point to your Web server.
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://YourServer/sample.asp");
Request.ClientCertificates.Add(Cert);
Request.UserAgent = "Client Cert Sample";
Request.Method = "GET";
HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();

How can I get the current stack trace in Java?

This is an old post, but here is my solution :

Thread.currentThread().dumpStack();

More info and more methods there : http://javarevisited.blogspot.fr/2013/04/how-to-get-current-stack-trace-in-java-thread.html

How to display a confirmation dialog when clicking an <a> link?

Just for fun, I'm going to use a single event on the whole document instead of adding an event to all the anchor tags:

document.body.onclick = function( e ) {
    // Cross-browser handling
    var evt = e || window.event,
        target = evt.target || evt.srcElement;

    // If the element clicked is an anchor
    if ( target.nodeName === 'A' ) {

        // Add the confirm box
        return confirm( 'Are you sure?' );
    }
};

This method would be more efficient if you had many anchor tags. Of course, it becomes even more efficient when you add this event to the container having all the anchor tags.

Running a cron every 30 seconds

Currently i'm using the below method. Works with no issues.

* * * * * /bin/bash -c ' for i in {1..X}; do YOUR_COMMANDS ; sleep Y ; done '

If you want to run every N seconds then X will be 60/N and Y will be N.

What are named pipes?

According to Wikipedia:

[...] A traditional pipe is "unnamed" because it exists anonymously and persists only for as long as the process is running. A named pipe is system-persistent and exists beyond the life of the process and must be "unlinked" or deleted once it is no longer being used. Processes generally attach to the named pipe (usually appearing as a file) to perform IPC (inter-process communication).

How to call a Parent Class's method from Child Class in Python?

ImmediateParentClass.frotz(self)

will be just fine, whether the immediate parent class defined frotz itself or inherited it. super is only needed for proper support of multiple inheritance (and then it only works if every class uses it properly). In general, AnyClass.whatever is going to look up whatever in AnyClass's ancestors if AnyClass doesn't define/override it, and this holds true for "child class calling parent's method" as for any other occurrence!

Getting a 'source: not found' error when using source in a bash script

In the POSIX standard, which /bin/sh is supposed to respect, the command is . (a single dot), not source. The source command is a csh-ism that has been pulled into bash.

Try

. $env_name/bin/activate

Or if you must have non-POSIX bash-isms in your code, use #!/bin/bash.

How to send a GET request from PHP?

Depending on whether your php setup allows fopen on URLs, you could also simply fopen the url with the get arguments in the string (such as http://example.com?variable=value )

Edit: Re-reading the question I'm not certain whether you're looking to pass variables or not - if you're not you can simply send the fopen request containg http://example.com/filename.xml - feel free to ignore the variable=value part

No restricted globals

Use react-router-dom library.

From there, import useLocation hook if you're using functional components:

import { useLocation } from 'react-router-dom';

Then append it to a variable:

Const location = useLocation();

You can then use it normally:

location.pathname

P.S: the returned location object has five properties only:

{ hash: "", key: "", pathname: "/" search: "", state: undefined__, }

How to return part of string before a certain character?

You fiddle already does the job ... maybe you try to get the string before the double colon? (you really should edit your question) Then the code would go like this:

str.substring(0, str.indexOf(":"));

Where 'str' represents the variable with your string inside.

Click here for JSFiddle Example

Javascript

var input_string = document.getElementById('my-input').innerText;
var output_element = document.getElementById('my-output');

var left_text = input_string.substring(0, input_string.indexOf(":"));

output_element.innerText = left_text;

Html

<p>
  <h5>Input:</h5>
  <strong id="my-input">Left Text:Right Text</strong>
  <h5>Output:</h5>
  <strong id="my-output">XXX</strong>
</p>

CSS

body { font-family: Calibri, sans-serif; color:#555; }
h5 { margin-bottom: 0.8em; }
strong {
  width:90%;
  padding: 0.5em 1em;
  background-color: cyan;
}
#my-output { background-color: gold; }

Get name of current class?

PEP 3155 introduced __qualname__, which was implemented in Python 3.3.

For top-level functions and classes, the __qualname__ attribute is equal to the __name__ attribute. For nested classes, methods, and nested functions, the __qualname__ attribute contains a dotted path leading to the object from the module top-level.

It is accessible from within the very definition of a class or a function, so for instance:

class Foo:
    print(__qualname__)

will effectively print Foo. You'll get the fully qualified name (excluding the module's name), so you might want to split it on the . character.

However, there is no way to get an actual handle on the class being defined.

>>> class Foo:
...     print('Foo' in globals())
... 
False

Why do I need to override the equals and hashCode methods in Java?

class A {
    int i;
    // Hashing Algorithm
    if even number return 0 else return 1
    // Equals Algorithm,
    if i = this.i return true else false
}
  • put('key','value') will calculate the hash value using hashCode() to determine the bucket and uses equals() method to find whether the value is already present in the Bucket. If not it will added else it will be replaced with current value
  • get('key') will use hashCode() to find the Entry (bucket) first and equals() to find the value in Entry

if Both are overridden,

Map<A>

Map.Entry 1 --> 1,3,5,...
Map.Entry 2 --> 2,4,6,...

if equals is not overridden

Map<A>

Map.Entry 1 --> 1,3,5,...,1,3,5,... // Duplicate values as equals not overridden
Map.Entry 2 --> 2,4,6,...,2,4,..

If hashCode is not overridden

Map<A>

Map.Entry 1 --> 1
Map.Entry 2 --> 2
Map.Entry 3 --> 3
Map.Entry 4 --> 1
Map.Entry 5 --> 2
Map.Entry 6 --> 3 // Same values are Stored in different hasCodes violates Contract 1
So on...

HashCode Equal Contract

  1. Two keys equal according to equal method should generate same hashCode
  2. Two Keys generating same hashCode need not be equal (In above example all even numbers generate same hash Code)

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

FormsModule should be added at imports array not declarations array.

  • imports array is for importing modules such as BrowserModule, FormsModule, HttpModule
  • declarations array is for your Components, Pipes, Directives

refer below change:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

Input text dialog Android

I found it cleaner and more reusable to extend AlertDialog.Builder to create a custom dialog class. This is for a dialog that asks the user to input a phone number. A preset phone number can also be supplied by calling setNumber() before calling show().

InputSenderDialog.java

public class InputSenderDialog extends AlertDialog.Builder {

    public interface InputSenderDialogListener{
        public abstract void onOK(String number);
        public abstract void onCancel(String number);
    }

    private EditText mNumberEdit;

    public InputSenderDialog(Activity activity, final InputSenderDialogListener listener) {
        super( new ContextThemeWrapper(activity, R.style.AppTheme) );

        @SuppressLint("InflateParams") // It's OK to use NULL in an AlertDialog it seems...
        View dialogLayout = LayoutInflater.from(activity).inflate(R.layout.dialog_input_sender_number, null);
        setView(dialogLayout);

        mNumberEdit = dialogLayout.findViewById(R.id.numberEdit);

        setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                if( listener != null )
                    listener.onOK(String.valueOf(mNumberEdit.getText()));

            }
        });

        setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                if( listener != null )
                    listener.onCancel(String.valueOf(mNumberEdit.getText()));
            }
        });
    }

    public InputSenderDialog setNumber(String number){
        mNumberEdit.setText( number );
        return this;
    }

    @Override
    public AlertDialog show() {
        AlertDialog dialog = super.show();
        Window window = dialog.getWindow();
        if( window != null )
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        return dialog;
    }
}

dialog_input_sender_number.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:padding="10dp">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        android:paddingBottom="20dp"
        android:text="Input phone number"
        android:textAppearance="@style/TextAppearance.AppCompat.Large" />

    <TextView
        android:id="@+id/numberLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@+id/title"
        app:layout_constraintLeft_toLeftOf="parent"
        android:text="Phone number" />

    <EditText
        android:id="@+id/numberEdit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@+id/numberLabel"
        app:layout_constraintLeft_toLeftOf="parent"
        android:inputType="phone" >
        <requestFocus />
    </EditText>

</android.support.constraint.ConstraintLayout>

Usage:

new InputSenderDialog(getActivity(), new InputSenderDialog.InputSenderDialogListener() {
    @Override
    public void onOK(final String number) {
        Log.d(TAG, "The user tapped OK, number is "+number);
    }

    @Override
    public void onCancel(String number) {
        Log.d(TAG, "The user tapped Cancel, number is "+number);
    }
}).setNumber(someNumberVariable).show();

How to test web service using command line curl

Answering my own question.

curl -X GET --basic --user username:password \
     https://www.example.com/mobile/resource

curl -X DELETE --basic --user username:password \
     https://www.example.com/mobile/resource

curl -X PUT --basic --user username:password -d 'param1_name=param1_value' \
     -d 'param2_name=param2_value' https://www.example.com/mobile/resource

POSTing a file and additional parameter

curl -X POST -F 'param_name=@/filepath/filename' \
     -F 'extra_param_name=extra_param_value' --basic --user username:password \
     https://www.example.com/mobile/resource

DataTables fixed headers misaligned with columns in wide tables

For bootstrap users, this fixed it for me:

   $($.fn.dataTable.tables(true)).DataTable()
      .columns.adjust()
      .fixedColumns().relayout();

See article here

How to center an iframe horizontally?

According to http://www.w3schools.com/css/css_align.asp, setting the left and right margins to auto specifies that they should split the available margin equally. The result is a centered element:

margin-left: auto;margin-right: auto;

python requests get cookies

If you need the path and thedomain for each cookie, which get_dict() is not exposes, you can parse the cookies manually, for instance:

[
    {'name': c.name, 'value': c.value, 'domain': c.domain, 'path': c.path}
    for c in session.cookies
]

How do I select which GPU to run a job on?

The problem was caused by not setting the CUDA_VISIBLE_DEVICES variable within the shell correctly.

To specify CUDA device 1 for example, you would set the CUDA_VISIBLE_DEVICES using

export CUDA_VISIBLE_DEVICES=1

or

CUDA_VISIBLE_DEVICES=1 ./cuda_executable

The former sets the variable for the life of the current shell, the latter only for the lifespan of that particular executable invocation.

If you want to specify more than one device, use

export CUDA_VISIBLE_DEVICES=0,1

or

CUDA_VISIBLE_DEVICES=0,1 ./cuda_executable

How to query MongoDB with "like"?

In Go and the mgo driver:

Collection.Find(bson.M{"name": bson.RegEx{"m", ""}}).All(&result)

where result is the struct instance of the sought after type

Docker-Compose with multiple services

The thing is that you are using the option -t when running your container.

Could you check if enabling the tty option (see reference) in your docker-compose.yml file the container keeps running?

version: '2'
services:
  ubuntu:
        build: .
        container_name: ubuntu
        volumes:
            - ~/sph/laravel52:/www/laravel
        ports:
          - "80:80"
        tty: true

How do I redirect in expressjs while passing some context?

Here s what I suggest without using any other dependency , just node and express, use app.locals, here s an example :

    app.get("/", function(req, res) {
        var context = req.app.locals.specialContext;
        req.app.locals.specialContext = null;
        res.render("home.jade", context); 
        // or if you are using ejs
        res.render("home", {context: context}); 
    });

    function middleware(req, res, next) {
        req.app.locals.specialContext = * your context goes here *
        res.redirect("/");
    }

Change the Value of h1 Element within a Form with JavaScript

Try:


document.getElementById("yourH1_element_Id").innerHTML = "yourTextHere";

How to read from stdin line by line in Node

process.stdin.pipe(process.stdout);

jQuery find and replace string

You could do something like this:

HTML

<div class="element">
   <span>Hi, I am Murtaza</span>
</div>


jQuery

$(".element span").text(function(index, text) { 
    return text.replace('am', 'am not'); 
});

How to send HTML email using linux command line

On OS X (10.9.4), cat works, and is easier if your email is already in a file:

cat email_template.html  | mail -s "$(echo -e "Test\nContent-Type: text/html")" [email protected]

CodeIgniter Disallowed Key Characters

I got this error when sending data from a rich text editor where I had included an ampersand. Replacing the ampersand with %26 - the URL encoding of ampersand - solved the problem. I also found that a jQuery ajax request configured like this magically solves the problem:

request = $.ajax({
        "url": url,
        type: "PUT",
        dataType: "json",
        data: json
    });

where the object json is, surprise, surprise, a JSON object containing a property with a value that contains an ampersand.

How to call controller from the button click in asp.net MVC 4

Try this:

@Html.ActionLink("DisplayText", "Action", "Controller", route, attribute)

in your code should be,

@Html.ActionLink("Search", "List", "Search", new{@class="btn btn-info", @id="addressSearch"})

How do I center a window onscreen in C#?

You can use the Screen.PrimaryScreen.Bounds to retrieve the size of the primary monitor (or inspect the Screen object to retrieve all monitors). Use those with MyForms.Bounds to figure out where to place your form.

AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

Don't use this pattern - This will end up causing more errors than it solves. Even though you think it fixed something, it didn't.

You can check if a $digest is already in progress by checking $scope.$$phase.

if(!$scope.$$phase) {
  //$digest or $apply
}

$scope.$$phase will return "$digest" or "$apply" if a $digest or $apply is in progress. I believe the difference between these states is that $digest will process the watches of the current scope and its children, and $apply will process the watchers of all scopes.

To @dnc253's point, if you find yourself calling $digest or $apply frequently, you may be doing it wrong. I generally find I need to digest when I need to update the scope's state as a result of a DOM event firing outside the reach of Angular. For example, when a twitter bootstrap modal becomes hidden. Sometimes the DOM event fires when a $digest is in progress, sometimes not. That's why I use this check.

I would love to know a better way if anyone knows one.


From comments: by @anddoutoi

angular.js Anti Patterns

  1. Don't do if (!$scope.$$phase) $scope.$apply(), it means your $scope.$apply() isn't high enough in the call stack.

Shuffle DataFrame rows

Here is another way:

df['rnd'] = np.random.rand(len(df)) df = df.sort_values(by='rnd', inplace=True).drop('rnd', axis=1)

COUNT DISTINCT with CONDITIONS

This may also work:

SELECT 
    COUNT(DISTINCT T.tag) as DistinctTag,
    COUNT(DISTINCT T2.tag) as DistinctPositiveTag
FROM Table T
    LEFT JOIN Table T2 ON T.tag = T2.tag AND T.entryID = T2.entryID AND T2.entryID > 0

You need the entryID condition in the left join rather than in a where clause in order to make sure that any items that only have a entryID of 0 get properly counted in the first DISTINCT.

Regex to split a CSV

I'm using this one, it works with coma separator and double quote escaping. Normally that's should solved your problem :

/(?<=^|,)(\"(?:[^"]+|"")*\"|[^,]*)(?:$|,)/g

How to check if an object is a certain type

In VB.NET, you need to use the GetType method to retrieve the type of an instance of an object, and the GetType() operator to retrieve the type of another known type.

Once you have the two types, you can simply compare them using the Is operator.

So your code should actually be written like this:

Sub FillCategories(ByVal Obj As Object)
    Dim cmd As New SqlCommand("sp_Resources_Categories", Conn)
    cmd.CommandType = CommandType.StoredProcedure
    Obj.DataSource = cmd.ExecuteReader
    If Obj.GetType() Is GetType(System.Web.UI.WebControls.DropDownList) Then

    End If
    Obj.DataBind()
End Sub

You can also use the TypeOf operator instead of the GetType method. Note that this tests if your object is compatible with the given type, not that it is the same type. That would look like this:

If TypeOf Obj Is System.Web.UI.WebControls.DropDownList Then

End If

Totally trivial, irrelevant nitpick: Traditionally, the names of parameters are camelCased (which means they always start with a lower-case letter) when writing .NET code (either VB.NET or C#). This makes them easy to distinguish at a glance from classes, types, methods, etc.

How can I test that a variable is more than eight characters in PowerShell?

Use the length property of the [String] type:

if ($dbUserName.length -gt 8) {
    Write-Output "Please enter more than 8 characters."
    $dbUserName = Read-Host "Re-enter database username"
}

Please note that you have to use -gt instead of > in your if condition. PowerShell uses the following comparison operators to compare values and test conditions:

  • -eq = equals
  • -ne = not equals
  • -lt = less than
  • -gt = greater than
  • -le = less than or equals
  • -ge = greater than or equals

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in

This error comes when there is error in your query syntax check field names table name, mean check your query syntax.

iPhone 5 CSS media query

None of the response works for me targeting a phonegapp App.

As the following link points, the solution below works.

@media screen and (device-height: 568px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 2) {
    // css here
}

Attach the Java Source Code

What worked for me (with JDK7) was the following:

  1. Download the openjdk-xy-sources.jar from GrepCode,
  2. rename the file to src.zip,
  3. copy src.zip to the root folder of the JRE/JDK added to eclipse (the one with bin and lib folders in it)
  4. restart eclipse

Alternatively, if you don't want to write to your JDK folder, you could also attach src.zip to (at least) rt.jar in eclipse in the Window | Preferences menu in Java | Installed JREs.

If you're not comfortable with downloading the sources from GrepCode, you could also get them from openJDK directly. This requires requires a bit more effort, though. Replace step one above by the following steps:

  1. Download the JDK sources from here,
  2. extract all folders from the zip file's *openjdk\jdk\src\share\classes* folder,
  3. create a file src.zip and add these folders to it,
  4. copy src.zip to the root folder of the JRE/JDK added to eclipse (the one with bin and lib folders in it)
  5. restart eclipse

A third alternative to acquire src.zip is to download the unofficial OpenJDK builds from here. The src.zip is contained within the downloaded zip.

Is it .yaml or .yml?

After reading a bunch of people's comments online about this, my first reaction was that this is basically one of those really unimportant debates. However, my initial interest was to find out the right format so I could be consistent with my file naming practice.

Long story short, the creator of YAML are saying .yaml, but personally I keep doing .yml. That just makes more sense to me. So I went on the journey to find affirmation and soon enough, I realise that docker uses .yml everywhere. I've been writing docker-compose.yml files all this time, while you keep seeing in kubernetes' docs kubectl apply -f *.yaml...

So, in conclusion, both formats are obviously accepted and if you are on the other end, (ie: writing systems that receive a YAML file as input) you should allow for both. That seems like another snake case versus camel case thingy...

Extension gd is missing from your system - laravel composer Update

For Windows : Uncomment this line in your php.ini file

;extension=php_gd2.dll

If the above step doesn't work uncomment the following line as well:

;extension=gd2

How to save .xlsx data to file as a blob

I've found a solution worked for me:

const handleDownload = async () => {
   const req = await axios({
     method: "get",
     url: `/companies/${company.id}/data`,
     responseType: "blob",
   });
   var blob = new Blob([req.data], {
     type: req.headers["content-type"],
   });
   const link = document.createElement("a");
   link.href = window.URL.createObjectURL(blob);
   link.download = `report_${new Date().getTime()}.xlsx`;
   link.click();
 };

I just point a responseType: "blob"

SQL: how to use UNION and order by a specific select?

@Adrian's answer is perfectly suitable, I just wanted to share another way of achieving the same result:

select nvl(a.id, b.id)
from a full outer join b on a.id = b.id
order by b.id;

Compiling a java program into an executable

The thing you can do is create a .bat that will execute the .jar file created, checking if there is a JRE present.

From Mitch useful link (source)

java -classpath myprogram.jar de.vogella.eclipse.ide.first.MyFirstClass

This can be used into your batch...

Flutter : Vertically center column

While using Column, use this inside the column widget :

mainAxisAlignment: MainAxisAlignment.center

It align its children(s) to the center of its parent Space is its main axis i.e. vertically

or, wrap the column with a Center widget:

Center(
  child: Column(
    children: <ListOfWidgets>,
  ),
)

if it doesn't resolve the issue wrap the parent container with a Expanded widget..

Expanded(
   child:Container(
     child: Column(
       mainAxisAlignment: MainAxisAlignment.center,
       children: children,
     ),
   ),
)

TextView Marquee not working

These attributes must be included in the textview tag in order to allow scrolling.

Everything else is optional.

android:focusable="true"
android:focusableInTouchMode="true"
android:layout_width="fill_parent"
android:ellipsize="marquee"

Updating GUI (WPF) using a different thread

As akjoshi and Julio say this is about dispatching an Action to update the GUI on the same thread as the GUI item but from the method that is handling the background data. You can see this code in specific form in akjoshi's answer above. This is a general version.

myTextBlock.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                   new Action(delegate() 
                                      {
                                      myTextBlock.Text = Convert.ToString(myDataObject.getMeData());
                                      }));

The critical part is to call the dispatcher of your UI object - that ensures you have the correct thread.

From personal experience it seems much easier to create and use the Action inline like this. Declaring it at class level gave me lots of problems with static/non-static contexts.

How to install plugin for Eclipse from .zip

My .zip file was formatted correctly (I think) but it wasn't working. Even unchecking "Group items by category" didn't work

To install it I did so:

  • unzip the .zip archive
  • Help -> Install New Software...
  • Add... -> Archive...
  • I selected the "content.jar" file

At this point Eclipse read the plugin correctly, I went ahead, accepted the conditions and then asked me to restart the IDE.

Compiling simple Hello World program on OS X via command line

You didn't specify what the error you're seeing is.

Is the problem that gcc is giving you an error, or that you can't run gcc at all?

If it's the latter, the most likely explanation is that you didn't check "UNIX Development Support" when you installed the development tools, so the command-line executables aren't installed in your path. Re-install the development tools, and make sure to click "customize" and check that box.

launch sms application with an intent

Here is the code that will open the SMS activity pre-populated with the phone number to which the SMS has to be sent. This works fine on emulator as well as the device.

Intent smsIntent = new Intent(Intent.ACTION_SENDTO);
smsIntent.addCategory(Intent.CATEGORY_DEFAULT);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.setData(Uri.parse("sms:" + phoneNumber));
startActivity(smsIntent);

Autoplay audio files on an iPad with HTML5

My solution is trigger from a real touch event in a prior menu. They don't force you to use a specific player interface of course. For my purposes, this works well. If you don't have an existing interface to use, afaik you're buggered. Maybe you could try tilt events or something...

Uncaught Typeerror: cannot read property 'innerHTML' of null

I had a similar problem, but I had the existing id, and as egiray said, I was calling DOM before it loaded and Javascript console was showing the same error, so I tried:

window.onload = (function(){myfuncname()});

and it starts working.

A potentially dangerous Request.Path value was detected from the client (*)

For me, I am working on .net 4.5.2 with web api 2.0, I have the same error, i set it just by adding requestPathInvalidCharacters="" in the requestPathInvalidCharacters you have to set not allowed characters else you have to remove characters that cause this problem.

<system.web>
     <httpRuntime targetFramework="4.5.2" requestPathInvalidCharacters="" />
     <pages  >
      <namespaces>
     ....
 </namespaces>
    </pages> 
  </system.web>

**Note that it is not a good practice, may be a post with this parameter as attribute of an object is better or try to encode the special character. -- After searching on best practice for designing rest api, i found that in search, sort and paginnation, we have to handle the query parameter like this

/companies?search=Digital%26Mckinsey

and this solve the problem when we encode & and remplace it on the url by %26 any way, on the server we receive the correct parameter Digital&Mckinsey

this link may help on best practice of designing rest web api https://hackernoon.com/restful-api-designing-guidelines-the-best-practices-60e1d954e7c9

What is the simplest way to get indented XML with line breaks from XmlDocument?

As adapted from Erika Ehrli's blog, this should do it:

XmlDocument doc = new XmlDocument();
doc.LoadXml("<item><name>wrench</name></item>");
// Save the document to a file and auto-indent the output.
using (XmlTextWriter writer = new XmlTextWriter("data.xml", null)) {
    writer.Formatting = Formatting.Indented;
    doc.Save(writer);
}

javascript regular expression to not match a word

function doesNotContainAbcOrDef(x) {
    return (x.match('abc') || x.match('def')) === null;
}

The application may be doing too much work on its main thread

taken from : Android UI : Fixing skipped frames

Anyone who begins developing android application sees this message on logcat “Choreographer(abc): Skipped xx frames! The application may be doing too much work on its main thread.” So what does it actually means, why should you be concerned and how to solve it.

What this means is that your code is taking long to process and frames are being skipped because of it, It maybe because of some heavy processing that you are doing at the heart of your application or DB access or any other thing which causes the thread to stop for a while.

Here is a more detailed explanation:

Choreographer lets apps to connect themselves to the vsync, and properly time things to improve performance.

Android view animations internally uses Choreographer for the same purpose: to properly time the animations and possibly improve performance.

Since Choreographer is told about every vsync events, I can tell if one of the Runnables passed along by the Choreographer.post* apis doesnt finish in one frame’s time, causing frames to be skipped.

In my understanding Choreographer can only detect the frame skipping. It has no way of telling why this happens.

The message “The application may be doing too much work on its main thread.” could be misleading.

source : Meaning of Choreographer messages in Logcat

Why you should be concerned

When this message pops up on android emulator and the number of frames skipped are fairly small (<100) then you can take a safe bet of the emulator being slow – which happens almost all the times. But if the number of frames skipped and large and in the order of 300+ then there can be some serious trouble with your code. Android devices come in a vast array of hardware unlike ios and windows devices. The RAM and CPU varies and if you want a reasonable performance and user experience on all the devices then you need to fix this thing. When frames are skipped the UI is slow and laggy, which is not a desirable user experience.

How to fix it

Fixing this requires identifying nodes where there is or possibly can happen long duration of processing. The best way is to do all the processing no matter how small or big in a thread separate from main UI thread. So be it accessing data form SQLite Database or doing some hardcore maths or simply sorting an array – Do it in a different thread

Now there is a catch here, You will create a new Thread for doing these operations and when you run your application, it will crash saying “Only the original thread that created a view hierarchy can touch its views“. You need to know this fact that UI in android can be changed by the main thread or the UI thread only. Any other thread which attempts to do so, fails and crashes with this error. What you need to do is create a new Runnable inside runOnUiThread and inside this runnable you should do all the operations involving the UI. Find an example here.

So we have Thread and Runnable for processing data out of main Thread, what else? There is AsyncTask in android which enables doing long time processes on the UI thread. This is the most useful when you applications are data driven or web api driven or use complex UI’s like those build using Canvas. The power of AsyncTask is that is allows doing things in background and once you are done doing the processing, you can simply do the required actions on UI without causing any lagging effect. This is possible because the AsyncTask derives itself from Activity’s UI thread – all the operations you do on UI via AsyncTask are done is a different thread from the main UI thread, No hindrance to user interaction.

So this is what you need to know for making smooth android applications and as far I know every beginner gets this message on his console.

How to auto-reload files in Node.js?

another simple solution is to use fs.readFile instead of using require you can save a text file contaning a json object, and create a interval on the server to reload this object.

pros:

  • no need to use external libs
  • relevant for production (reloading config file on change)
  • easy to implement

cons:

  • you can't reload a module - just a json containing key-value data

document.createElement("script") synchronously

Ironically, I have what you want, but want something closer to what you had.

I am loading things in dynamically and asynchronously, but with an load callback like so (using dojo and xmlhtpprequest)

  dojo.xhrGet({
    url: 'getCode.php',
    handleAs: "javascript",
    content : {
    module : 'my.js'
  },
  load: function() {
    myFunc1('blarg');
  },
  error: function(errorMessage) {
    console.error(errorMessage);
  }
});

For a more detailed explanation, see here

The problem is that somewhere along the line the code gets evaled, and if there's anything wrong with your code, the console.error(errorMessage); statement will indicate the line where eval() is, not the actual error. This is SUCH a big problem that I am actually trying to convert back to <script> statements (see here.

How to programmatically set the Image source

Try to assign the image that way instead:

imgFavorito.Source = new BitmapImage(new Uri(base.BaseUri, @"/Assets/favorited.png"));

ssh-copy-id no identities found error

You need to specify the key by using -i option.

ssh-copy-id -i your_public_key user@host

Thanks.

How do I get the picture size with PIL?

Note that PIL will not apply the EXIF rotation information (at least up to v7.1.1; used in many jpgs). A quick fix to accomodate this:

def get_image_dims(file_path):
    from PIL import Image as pilim
    im = pilim.open(file_path)
    # returns (w,h) after rotation-correction
    return im.size if im._getexif().get(274,0) < 5 else im.size[::-1]

Is False == 0 and True == 1 an implementation detail or is it guaranteed by the language?

In Python 2.x this is not guaranteed as it is possible for True and False to be reassigned. However, even if this happens, boolean True and boolean False are still properly returned for comparisons.

In Python 3.x True and False are keywords and will always be equal to 1 and 0.

Under normal circumstances in Python 2, and always in Python 3:

False object is of type bool which is a subclass of int:

object
   |
 int
   |
 bool

It is the only reason why in your example, ['zero', 'one'][False] does work. It would not work with an object which is not a subclass of integer, because list indexing only works with integers, or objects that define a __index__ method (thanks mark-dickinson).

Edit:

It is true of the current python version, and of that of Python 3. The docs for python 2 and the docs for Python 3 both say:

There are two types of integers: [...] Integers (int) [...] Booleans (bool)

and in the boolean subsection:

Booleans: These represent the truth values False and True [...] Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.

There is also, for Python 2:

In numeric contexts (for example when used as the argument to an arithmetic operator), they [False and True] behave like the integers 0 and 1, respectively.

So booleans are explicitly considered as integers in Python 2 and 3.

So you're safe until Python 4 comes along. ;-)

Bundler: Command not found

... also for Debian GNU/Linux 6.0 :)

export PATH=$PATH:/var/lib/gems/1.8/bin

Keyboard shortcut to "untab" (move a block of code to the left) in eclipse / aptana?

Don't know if anyone is still looking here, but you can do this by going to Window menu > Preferences, then open the General list, choose keys. Scroll down the list of keys until you see "Shift Left". Click that. Below that you'll see some boxes, one of which lets you bind a key. It won't accept Shift-Tab, so I bound it to Shift-`. Apply-and-close and you're all set.

Select first empty cell in column F starting from row 1. (without using offset )

Code of Sam is good but I think it need some correction,

Public Sub SelectFirstBlankCell()
    Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer
    Dim currentRowValue As String

    sourceCol = 6   'column F has a value of 6
    rowCount = Cells(Rows.Count, sourceCol).End(xlUp).Row

    'for every row, find the first blank cell and select it
    For currentRow = 1 To rowCount
        currentRowValue = Cells(currentRow, sourceCol).Value
        If IsEmpty(currentRowValue) Or currentRowValue = "" Then
            Cells(currentRow, sourceCol).Select
            Exit For 'This is missing...
        End If
    Next
End Sub

Thanks

How to convert a string to ASCII

For Any String try this:

string s = Console.ReadLine();
foreach( char c in s)
{
    Console.WriteLine(System.Convert.ToInt32(c));
}
Console.ReadKey();

How can I make an EXE file from a Python program?

I found this presentation to be very helpfull.

How I Distribute Python applications on Windows - py2exe & InnoSetup

From the site:

There are many deployment options for Python code. I'll share what has worked well for me on Windows, packaging command line tools and services using py2exe and InnoSetup. I'll demonstrate a simple build script which creates windows binaries and an InnoSetup installer in one step. In addition, I'll go over common errors which come up when using py2exe and hints on troubleshooting them. This is a short talk, so there will be a follow-up Open Space session to share experience and help each other solve distribution problems.

Undefined behavior and sequence points

In C99(ISO/IEC 9899:TC3) which seems absent from this discussion thus far the following steteents are made regarding order of evaluaiton.

[...]the order of evaluation of subexpressions and the order in which side effects take place are both unspecified. (Section 6.5 pp 67)

The order of evaluation of the operands is unspecified. If an attempt is made to modify the result of an assignment operator or to access it after the next sequence point, the behavior[sic] is undefined.(Section 6.5.16 pp 91)

Best Practice for Forcing Garbage Collection in C#

The best practise is to not force a garbage collection.

According to MSDN:

"It is possible to force garbage collection by calling Collect, but most of the time, this should be avoided because it may create performance issues. "

However, if you can reliably test your code to confirm that calling Collect() won't have a negative impact then go ahead...

Just try to make sure objects are cleaned up when you no longer need them. If you have custom objects, look at using the "using statement" and the IDisposable interface.

This link has some good practical advice with regards to freeing up memory / garbage collection etc:

http://msdn.microsoft.com/en-us/library/66x5fx1b.aspx

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

If you are interested ONLY on relative paths like: /dashboard, /about etc, See other answers.

If you want to open an absolute path like: https://www.google.com to a new tab, you have to know that Vue Router is NOT meant to handle those.

However, they seems to consider that as a feature-request. #1280. But until they do that,



Here is a little trick you can do to handle external links with vue-router.

  • Go to the router configuration (probably router.js) and add this code:
/* Vue Router is not meant to handle absolute urls. */
/* So whenever we want to deal with those, we can use this.$router.absUrl(url) */
Router.prototype.absUrl = function(url, newTab = true) {
  const link = document.createElement('a')
  link.href = url
  link.target = newTab ? '_blank' : ''
  if (newTab) link.rel = 'noopener noreferrer' // IMPORTANT to add this
  link.click()
}

Now, whenever we deal with absolute URLs we have a solution. For example to open google to a new tab

this.$router.absUrl('https://www.google.com)

Remember that whenever we open another page to a new tab we MUST use noopener noreferrer.

Read more here

or Here

Efficient way to remove ALL whitespace from String?

Try the replace method of the string in C#.

XML.Replace(" ", string.Empty);

Java ArrayList - Check if list is empty

Good practice nowadays is to use CollectionUtils from either Apache Commons or Spring Framework.

CollectionUtils.isEmpty(list))

Collections.emptyList() vs. new instance

Use Collections.emptyList() if you want to make sure that the returned list is never modified.

This is what is returned on calling emptyList():

/**
 * The empty list (immutable). 
 */
public static final List EMPTY_LIST = new EmptyList();

Are 2 dimensional Lists possible in c#?

Here's a little something that I made a while ago for a game engine I was working on. It was used as a local object variable holder. Basically, you use it as a normal list, but it holds the value at the position of what ever the string name is(or ID). A bit of modification, and you will have your 2D list.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GameEngineInterpreter
{
    public class VariableList<T>
    {
        private List<string> list1;
        private List<T> list2;

        /// <summary>
        /// Initialize a new Variable List
        /// </summary>
        public VariableList()
        {
            list1 = new List<string>();
            list2 = new List<T>();
        }

        /// <summary>
        /// Set the value of a variable. If the variable does not exist, then it is created
        /// </summary>
        /// <param name="variable">Name or ID of the variable</param>
        /// <param name="value">The value of the variable</param>
        public void Set(string variable, T value)
        {
            if (!list1.Contains(variable))
            {
                list1.Add(variable);
                list2.Add(value);
            }
            else
            {
                list2[list1.IndexOf(variable)] = value;
            }
        }

        /// <summary>
        /// Remove the variable if it exists
        /// </summary>
        /// <param name="variable">Name or ID of the variable</param>
        public void Remove(string variable)
        {
            if (list1.Contains(variable))
            {
                list2.RemoveAt(list1.IndexOf(variable));
                list1.RemoveAt(list1.IndexOf(variable));
            }
        }

        /// <summary>
        /// Clears the variable list
        /// </summary>
        public void Clear()
        {
            list1.Clear();
            list2.Clear();
        }

        /// <summary>
        /// Get the value of the variable if it exists
        /// </summary>
        /// <param name="variable">Name or ID of the variable</param>
        /// <returns>Value</returns>
        public T Get(string variable)
        {
            if (list1.Contains(variable))
            {
                return (list2[list1.IndexOf(variable)]);
            }
            else
            {
                return default(T);
            }
        }

        /// <summary>
        /// Get a string list of all the variables 
        /// </summary>
        /// <returns>List string</string></returns>
        public List<string> GetList()
        {
            return (list1);
        }
    }
}

Activity restart on rotation Android

It is very simple just do the following steps:

<activity
    android:name=".Test"
    android:configChanges="orientation|screenSize"
    android:screenOrientation="landscape" >
</activity>

This works for me :

Note: orientation depends on your requitement

Loading custom functions in PowerShell

You have to dot source them:

. .\build_funtions.ps1
. .\build_builddefs.ps1

Note the extra .

This heyscriptingguy article should be of help - How to Reuse Windows PowerShell Functions in Scripts

Problem with converting int to string in Linq to entities

With EF v4 you can use SqlFunctions.StringConvert. There is no overload for int so you need to cast to a double or a decimal. Your code ends up looking like this:

var items = from c in contacts
            select new ListItem
            {
                Value = SqlFunctions.StringConvert((double)c.ContactId).Trim(),
                Text = c.Name
            };

Pandas df.to_csv("file.csv" encode="utf-8") still gives trash characters for minus sign

Your "bad" output is UTF-8 displayed as CP1252.

On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:

df.to_csv('file.csv',encoding='utf-8-sig')

That encoder will add the BOM.

SQL Server dynamic PIVOT query?

The below code provides the results which replaces NULL to zero in the output.

Table creation and data insertion:

create table test_table
 (
 date nvarchar(10),
 category char(3),
 amount money
 )

 insert into test_table values ('1/1/2012','ABC',1000.00)
 insert into test_table values ('2/1/2012','DEF',500.00)
 insert into test_table values ('2/1/2012','GHI',800.00)
 insert into test_table values ('2/10/2012','DEF',700.00)
 insert into test_table values ('3/1/2012','ABC',1100.00)

Query to generate the exact results which also replaces NULL with zeros:

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX),
@PivotColumnNames AS NVARCHAR(MAX),
@PivotSelectColumnNames AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column
SELECT @PivotColumnNames= ISNULL(@PivotColumnNames + ',','')
+ QUOTENAME(category)
FROM (SELECT DISTINCT category FROM test_table) AS cat

--Get distinct values of the PIVOT Column with isnull
SELECT @PivotSelectColumnNames 
= ISNULL(@PivotSelectColumnNames + ',','')
+ 'ISNULL(' + QUOTENAME(category) + ', 0) AS '
+ QUOTENAME(category)
FROM (SELECT DISTINCT category FROM test_table) AS cat

--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
N'SELECT date, ' + @PivotSelectColumnNames + '
FROM test_table
pivot(sum(amount) for category in (' + @PivotColumnNames + ')) as pvt';

--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery

OUTPUT :

enter image description here

Spring Boot War deployed to Tomcat

Update 2018-02-03 with Spring Boot 1.5.8.RELEASE.

In pom.xml, you need to tell Spring plugin when it is building that it is a war file by change package to war, like this:

<packaging>war</packaging>

Also, you have to excluded the embedded tomcat while building the package by adding this:

    <!-- to deploy as a war in tomcat -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

The full runable example is in here https://www.surasint.com/spring-boot-create-war-for-tomcat/

How to center an element in the middle of the browser window?

Here is:

  • HTML+CSS only solution - no JavaScript needed
  • It does not require that you to know the content size in advance
  • The content stands centered on window resizing

And the example:

<!DOCTYPE html>
<html>
    <head>
        <title>HTML centering</title>

        <style type="text/css">
        <!--
        html, body, #tbl_wrap { height: 100%; width: 100%; padding: 0; margin: 0; }
        #td_wrap { vertical-align: middle; text-align: center; }
        -->
        </style>
    </head>

    <body>
        <table id="tbl_wrap"><tbody><tr><td id="td_wrap">
        <!-- START: Anything between these wrapper comment lines will be centered -->


<div style="border: 1px solid black; display: inline-block;">
This content will be centered.
</div>

        <!-- END: Anything between these wrapper comment lines will be centered -->
        </td></tr></tbody></table>
    </body>
</html>

Take a look at the original URL for full info: http://krustev.net/html_center_content.html

You can do whatever you like with this code. The only condition is that any derived work must have a reference to the original author.

error: src refspec master does not match any

This is happend to me once I forgot to add files. So I got the same error. All you need to do is add your files.

  1. Add your files => git add . or the name of the files you want to add. you supposed to init first your repo with git init.
  2. Commit your changes => git commit -m 'Initial Commit'.
  3. Now push your changes => git push -u origin master

Will using 'var' affect performance?

So, to be clear, it's a lazy coding style. I prefer native types, given the choice; I'll take that extra bit of "noise" to ensure I'm writing and reading exactly what I think I am at code/debug time. * shrug *

Regex (grep) for multi-line search needed

I am not very good in grep. But your problem can be solved using AWK command. Just see

awk '/select/,/from/' *.sql

The above code will result from first occurence of select till first sequence of from. Now you need to verify whether returned statements are having customername or not. For this you can pipe the result. And can use awk or grep again.

Is it possible to center text in select box?

2020, Im using:

select {
    text-align: center;
    text-align-last: center;
    -moz-text-align-last: center;
}

PIL image to array (numpy array to array) - Python

I use numpy.fromiter to invert a 8-greyscale bitmap, yet no signs of side-effects

import Image
import numpy as np

im = Image.load('foo.jpg')
im = im.convert('L')

arr = np.fromiter(iter(im.getdata()), np.uint8)
arr.resize(im.height, im.width)

arr ^= 0xFF  # invert
inverted_im = Image.fromarray(arr, mode='L')
inverted_im.show()

jQuery UI DatePicker to show year only

Try this way it will hide the calendar and show year only

$(function() {
    $( "#datepicker" ).datepicker({dateFormat: 'yy'});
    });?

CSS

.ui-datepicker-calendar {
   display: none;
}

DEMO ?

Find file in directory from command line

locate <file_pattern>

*** find will certainly work, and can target specific directories. However, this command is slower than the locate command. On a Linux OS, each morning a database is constructed that contains a list of all directory and files, and the locate command efficiently searches this database, so if you want to do a search for files that weren't created today, this would be the fastest way to accomplish such a task.

Why is exception.printStackTrace() considered bad practice?

It is not bad practice because something is 'wrong' about PrintStackTrace(), but because it's 'code smell'. Most of the time the PrintStackTrace() call is there because somebody failed to properly handle the exception. Once you deal with the exception in a proper way you generally don't care about the StackTrace any more.

Additionally, displaying the stacktrace on stderr is generally only useful when debugging, not in production because very often stderr goes nowhere. Logging it makes more sense. But just replacing PrintStackTrace() with logging the exception still leaves you with an application which failed but keeps running like nothing happened.

Using TortoiseSVN how do I merge changes from the trunk to a branch and vice versa?

The behavior depends on which version your repository has. Subversion 1.5 allows 4 types of merge:

  1. merge sourceURL1[@N] sourceURL2[@M] [WCPATH]
  2. merge sourceWCPATH1@N sourceWCPATH2@M [WCPATH]
  3. merge [-c M[,N...] | -r N:M ...] SOURCE[@REV] [WCPATH]
  4. merge --reintegrate SOURCE[@REV] [WCPATH]

Subversion before 1.5 only allowed the first 2 formats.

Technically you can perform all merges with the first two methods, but the last two enable subversion 1.5's merge tracking.

TortoiseSVN's options merge a range or revisions maps to method 3 when your repository is 1.5+ or to method one when your repository is older.

When merging features over to a release/maintenance branch you should use the 'Merge a range of revisions' command.

Only when you want to merge all features of a branch back to a parent branch (commonly trunk) you should look into using 'Reintegrate a branch'.

And the last command -Merge two different trees- is only usefull when you want to step outside the normal branching behavior. (E.g. Comparing different releases and then merging the differenct to yet another branch)

Git push results in "Authentication Failed"

If you are on windows and trying to push to a windows server which has domain users working as repository users (TFS), try getting into TFS URL (i.e. http:\\tfs) with IE. enter your domain account credentials and let the page appear.

CAUTION only use INTERNET EXPLORER! other browsers wont change your system credentials.

Now go to git bash and change your remote user for the repository like below :

git config user.name "domainName\userName"

And done, now you can push!

How can moment.js be imported with typescript?

via typings

Moment.js now supports TypeScript in v2.14.1.

See: https://github.com/moment/moment/pull/3280


Directly

Might not be the best answer, but this is the brute force way, and it works for me.

  1. Just download the actual moment.js file and include it in your project.
  2. For example, my project looks like this:

$ tree . +-- main.js +-- main.js.map +-- main.ts +-- moment.js

  1. And here's a sample source code:

```

import * as moment from 'moment';

class HelloWorld {
    public hello(input:string):string {
        if (input === '') {
            return "Hello, World!";
        }
        else {
            return "Hello, " + input + "!";
        }
    }
}

let h = new HelloWorld();
console.log(moment().format('YYYY-MM-DD HH:mm:ss'));
  1. Just use node to run main.js.

A generic error occurred in GDI+, JPEG Image to MemoryStream

SOLVED - I had this exact problem. The fix, for me, was to up the disk quota for IUSR on the IIS server. In this instance, we have a catalog app with images of items and such. The upload quota for the "Anonymous Web User" was set to 100MB, which is the default for this particular hosting company's IIS servers. I upped it to 400MB and was able to upload images without error.

This might not be your issue, but if it is, it's an easy fix.

How do I get the full path of the current file's directory?

USEFUL PATH PROPERTIES IN PYTHON:

 from pathlib import Path

    #Returns the path of the directory, where your script file is placed
    mypath = Path().absolute()
    print('Absolute path : {}'.format(mypath))

    #if you want to go to any other file inside the subdirectories of the directory path got from above method
    filePath = mypath/'data'/'fuel_econ.csv'
    print('File path : {}'.format(filePath))

    #To check if file present in that directory or Not
    isfileExist = filePath.exists()
    print('isfileExist : {}'.format(isfileExist))

    #To check if the path is a directory or a File
    isadirectory = filePath.is_dir()
    print('isadirectory : {}'.format(isadirectory))

    #To get the extension of the file
    fileExtension = mypath/'data'/'fuel_econ.csv'
    print('File extension : {}'.format(filePath.suffix))

OUTPUT: ABSOLUTE PATH IS THE PATH WHERE YOUR PYTHON FILE IS PLACED

Absolute path : D:\Study\Machine Learning\Jupitor Notebook\JupytorNotebookTest2\Udacity_Scripts\Matplotlib and seaborn Part2

File path : D:\Study\Machine Learning\Jupitor Notebook\JupytorNotebookTest2\Udacity_Scripts\Matplotlib and seaborn Part2\data\fuel_econ.csv

isfileExist : True

isadirectory : False

File extension : .csv

How to change a dataframe column from String type to Double type in PySpark?

the solution was simple -

toDoublefunc = UserDefinedFunction(lambda x: float(x),DoubleType())
changedTypedf = joindf.withColumn("label",toDoublefunc(joindf['show']))

How to Customize a Progress Bar In Android

in your xml

<ProgressBar
        android:id="@+id/progressBar1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        style="@style/CustomProgressBar" 
        android:layout_margin="5dip" />

And in res/values/styles.xml:

<resources> 
        <style name="CustomProgressBar" parent="android:Widget.ProgressBar.Horizontal">
          <item name="android:indeterminateOnly">false</item>
          <item name="android:progressDrawable">@drawable/custom_progress_bar_horizontal</item>
          <item name="android:minHeight">10dip</item>
          <item name="android:maxHeight">20dip</item>
        </style>       
    <style name="AppTheme" parent="android:Theme.Light" />
</resources>

And custom_progress_bar_horizontal is a xml stored in drawable folder which defines your custom progress bar. For more detail see this blog.

I hope this will help you.

How do I convert a string to enum in TypeScript?

For TS 3.9.x

var color : Color = Color[green as unknown as keyof typeof Color];

Git Clone - Repository not found

open Credential Manager -> look for your GIT devops profile -> click on it -> edit -> add user and password generated in DevOps and save.

Python function global variables?

You can directly access a global variable inside a function. If you want to change the value of that global variable, use "global variable_name". See the following example:

var = 1
def global_var_change():
      global var
      var = "value changed"
global_var_change() #call the function for changes
print var

Generally speaking, this is not a good programming practice. By breaking namespace logic, code can become difficult to understand and debug.

How to add a href link in PHP?

you have problems with " :

 <a href=<?php echo "'www.someotherwebsite.com'><img src='". url::file_loc('img'). "media/img/twitter.png' style='vertical-align: middle' border='0'></a>"; ?>

How to ping an IP address

InetAddress is not always return correct value. It is successful in case of Local Host but for other hosts this shows that the host is unreachable. Try using ping command as given below.

try {
    String cmd = "cmd /C ping -n 1 " + ip + " | find \"TTL\"";        
    Process myProcess = Runtime.getRuntime().exec(cmd);
    myProcess.waitFor();

    if(myProcess.exitValue() == 0) {

    return true;
    }
    else {
        return false;
    }
}
catch (Exception e) {
    e.printStackTrace();
    return false;
}

Curl to return http status code along with the response

Wow so many answers, cURL devs definitely left it to us as a home exercise :) Ok here is my take - a script that makes the cURL working as it's supposed to be, i.e.:

  • show the output as cURL would.
  • exit with non-zero code in case of HTTP response code not in 2XX range

Save it as curl-wrapper.sh:


#!/bin/bash

output=$(curl -w "\n%{http_code}" "$@")
res=$?

if [[ "$res" != "0" ]]; then
  echo -e "$output"
  exit $res
fi

if [[ $output =~ [^0-9]([0-9]+)$ ]]; then
    httpCode=${BASH_REMATCH[1]}
    body=${output:0:-${#httpCode}}

    echo -e "$body"

    if (($httpCode < 200 || $httpCode >= 300)); then
        # Remove this is you want to have pure output even in 
        # case of failure:
        echo
        echo "Failure HTTP response code: ${httpCode}"
        exit 1
    fi
else
    echo -e "$output"
    echo
    echo "Cannot get the HTTP return code"
    exit 1
fi

So then it's just business as usual, but instead of curl do ./curl-wrapper.sh:

So when the result falls in 200-299 range:

./curl-wrapper.sh www.google.com 
# ...the same output as pure curl would return...
echo $?
# 0

And when the result is out of in 200-299 range:

./curl-wrapper.sh www.google.com/no-such-page
# ...the same output as pure curl would return - plus the line
#    below with the failed HTTP code, this line can be removed if needed:
#
# Failure HTTP response code: 404
echo $?
# 1

Just do not pass "-w|--write-out" argument since that's what added inside the script

How can I count the number of elements with same class?

$('#maindivid').find('input .inputclass').length

Running a cron job on Linux every six hours

You should include a path to your command, since cron runs with an extensively cut-down environment. You won't have all the environment variables you have in your interactive shell session.

It's a good idea to specify an absolute path to your script/binary, or define PATH in the crontab itself. To help debug any issues I would also redirect stdout/err to a log file.

How to use Lambda in LINQ select statement

using LINQ query expression

 IEnumerable<SelectListItem> stores =
        from store in database.Stores
        where store.CompanyID == curCompany.ID
        select new SelectListItem { Value = store.Name, Text = store.ID };

 ViewBag.storeSelector = stores;

or using LINQ extension methods with lambda expressions

 IEnumerable<SelectListItem> stores = database.Stores
        .Where(store => store.CompanyID == curCompany.ID)
        .Select(store => new SelectListItem { Value = store.Name, Text = store.ID });

 ViewBag.storeSelector = stores;

Return value using String result=Command.ExecuteScalar() error occurs when result returns null

Try this one, if null set 0 or something

return command.ExecuteScalar() == DBNull.Value ? 0 : (double)command.ExecuteScalar();

Reading rows from a CSV file in Python

One can do it using pandas library.

Example:

import numpy as np
import pandas as pd

file = r"C:\Users\unknown\Documents\Example.csv"
df1 = pd.read_csv(file)
df1.head()

ERROR: Cannot open source file " "

  1. Copy the contents of the file,
  2. Create an .h file, give it the name of the original .h file
  3. Copy the contents of the original file to the newly created one
  4. Build it
  5. VOILA!!

JavaScript open in a new window, not tab

try that method.....

function popitup(url) {
       //alert(url);
       newwindow=window.open("http://www.zeeshanakhter.com","_blank","toolbar=yes,scrollbars=yes, resizable=yes, top=500, left=500, width=400, height=400");
       newwindow.moveTo(350,150);
   if (window.focus) 
          {
             newwindow.focus()
          }
   return false;
  }