Programs & Examples On #Image enhancement

No value accessor for form control with name: 'recipient'

You should add the ngDefaultControl attribute to your input like this:

<md-input
    [(ngModel)]="recipient"
    name="recipient"
    placeholder="Name"
    class="col-sm-4"
    (blur)="addRecipient(recipient)"
    ngDefaultControl>
</md-input>

Taken from comments in this post:

angular2 rc.5 custom input, No value accessor for form control with unspecified name

Note: For later versions of @angular/material:

Nowadays you should instead write:

<md-input-container>
    <input
        mdInput
        [(ngModel)]="recipient"
        name="recipient"
        placeholder="Name"
        (blur)="addRecipient(recipient)">
</md-input-container>

See https://material.angular.io/components/input/overview

How can I implement the Iterable interface?

First off:

public class ProfileCollection implements Iterable<Profile> {

Second:

return m_Profiles.get(m_ActiveProfile);

increment date by one month

For anyone looking for an answer to any date format.

echo date_create_from_format('d/m/Y', '15/04/2017')->add(new DateInterval('P1M'))->format('d/m/Y');

Just change the date format.

PhoneGap Eclipse Issue - eglCodecCommon glUtilsParamSize: unknow param errors

@theczechsensation's solution is already half way there.

For those who like to exclude noisy log messages and keep the log to their app only this is the solution:

New Logcat Filter Settings

Add your exclusions to Log Tag like this: ^(?!(eglCodecCommon|tagToExclude))

Add your package name or prefix to Package Name: com.mycompany.

This way it is possible to filter for as many strings you like and keep the log to your package.

Prevent the keyboard from displaying on activity start

just add this on your Activity:

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
      if (getCurrentFocus() != null) {
           InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
           imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
      }
      return super.dispatchTouchEvent(ev);
}

Failed to import new Gradle project: failed to find Build Tools revision *.0.0

Try to run gradle at the command line first. It might prompt you to setup and environment variable:

export _JAVA_OPTIONS="-Xms256m -Xmx1024m"

Read more here: 1, 2


Further make sure that the Android SDK build tools (adb, aapt, dx, dx.jar) are available in the PATH. If not you can create symlinks at the appropriate locations. They changed with the release of new SDK versions. Here is a shell script which creates the symlinks within the $ANDROID_HOME folder for you.

Best GUI designer for eclipse?

well check out the eclipse distro easyeclipse at EasyEclipse. it has Visual editor project already added as a plugin, so no hassles of eclipse version compatibility.Plus the eclipse help section has a tutorial on VE.

mongodb count num of distinct values per field/key

I wanted a more concise answer and I came up with the following using the documentation at aggregates and group

db.countries.aggregate([{"$group": {"_id": "$country", "count":{"$sum": 1}}])

Can the "IN" operator use LIKE-wildcards (%) in Oracle?

Somewhat convoluted, but:

Select * from myTable m
join (SELECT a.COLUMN_VALUE || b.COLUMN_VALUE status
FROM   (TABLE(Sys.Dbms_Debug_Vc2coll('Done', 'Finished except', 'In Progress'))) a
JOIN (Select '%' COLUMN_VALUE from dual) b on 1=1) params
on params.status like m.status;

This was a solution for a very unique problem, but it might help someone. Essentially there is no "in like" statement and there was no way to get an index for the first variable_n characters of the column, so I made this to make a fast dynamic "in like" for use in SSRS.

The list content ('Done', 'Finished except', 'In Progress') can be variable.

javax.persistence.PersistenceException: No Persistence provider for EntityManager named customerManager

I was also facing the same issue when I was trying to get JPA entity manager configured in Tomcat 8. First I has an issue with the SystemException class not being found and hence the entityManagerFactory was not being created. I removed the hibernate entity manager dependency and then my entityManagerFactory was not able to lookup for the persistence provider. After going thru a lot of research and time got to know that hibernate entity manager is must to lookup for some configuration. Then put back the entity manager jar and then added JTA Api as a dependency and it worked fine.

Simulate low network connectivity for Android

Just go to Android device monitor from Android studio , then DDMS -> Emulator Control.There will be Speed and Latency properties.

What exactly is an instance in Java?

I think that Object = Instance. Reference is a "link" to an Object.

Car c = new Car();

variable c stores a reference to an object of type Car.

Nginx: Permission denied for nginx on Ubuntu

If i assume that your second code is the puppet config then i have a logical explaination, if the error and log files were create before, you can try this

sudo chown -R www-data:www-data /var/log/nginx;
sudo chmod -R 755 /var/log/nginx;

SyntaxError: Unexpected token o in JSON at position 1

Just above JSON.parse, use:

var newData = JSON.stringify(userData)

Total Number of Row Resultset getRow Method

The getRow() method will always yield 0 after a query:

ResultSet.getRow()

Retrieves the current row number.

Second, you output totalrec but never assign anything to it.

AngularJs: How to check for changes in file input fields?

I made a small directive to listen for file input changes.

View JSFiddle

view.html:

<input type="file" custom-on-change="uploadFile">

controller.js:

app.controller('myCtrl', function($scope){
    $scope.uploadFile = function(event){
        var files = event.target.files;
    };
});     

directive.js:

app.directive('customOnChange', function() {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      var onChangeHandler = scope.$eval(attrs.customOnChange);
      element.on('change', onChangeHandler);
      element.on('$destroy', function() {
        element.off();
      });

    }
  };
});

jQuery find events handlers registered with an object

As of jQuery 1.8, the event data is no longer available from the "public API" for data. Read this jQuery blog post. You should now use this instead:

jQuery._data( elem, "events" );

elem should be an HTML Element, not a jQuery object, or selector.

Please note, that this is an internal, 'private' structure, and shouldn't be modified. Use this for debugging purposes only.

In older versions of jQuery, you might have to use the old method which is:

jQuery( elem ).data( "events" );

Changing case in Vim

See the following methods:

 ~    : Changes the case of current character

 guu  : Change current line from upper to lower.

 gUU  : Change current LINE from lower to upper.

 guw  : Change to end of current WORD from upper to lower.

 guaw : Change all of current WORD to lower.

 gUw  : Change to end of current WORD from lower to upper.

 gUaw : Change all of current WORD to upper.

 g~~  : Invert case to entire line

 g~w  : Invert case to current WORD

 guG : Change to lowercase until the end of document.

Illegal string offset Warning PHP

Please try this way.... I have tested this code.... It works....

$memcachedConfig = array("host" => "127.0.0.1","port" => "11211");
print_r($memcachedConfig['host']);

When to use Common Table Expression (CTE)

Today we are going to learn about Common table expression that is a new feature which was introduced in SQL server 2005 and available in later versions as well.

Common table Expression :- Common table expression can be defined as a temporary result set or in other words its a substitute of views in SQL Server. Common table expression is only valid in the batch of statement where it was defined and cannot be used in other sessions.

Syntax of declaring CTE(Common table expression) :-

with [Name of CTE]
as
(
Body of common table expression
)

Lets take an example :-

CREATE TABLE Employee([EID] [int] IDENTITY(10,5) NOT NULL,[Name] [varchar](50) NULL)

insert into Employee(Name) values('Neeraj')
insert into Employee(Name) values('dheeraj')
insert into Employee(Name) values('shayam')
insert into Employee(Name) values('vikas')
insert into Employee(Name) values('raj')

CREATE TABLE DEPT(EID INT,DEPTNAME VARCHAR(100))
insert into dept values(10,'IT')
insert into dept values(15,'Finance')
insert into dept values(20,'Admin')
insert into dept values(25,'HR')
insert into dept values(10,'Payroll')

I have created two tables employee and Dept and inserted 5 rows in each table. Now I would like to join these tables and create a temporary result set to use it further.

With CTE_Example(EID,Name,DeptName)
as
(
select Employee.EID,Name,DeptName from Employee 
inner join DEPT on Employee.EID =DEPT.EID
)
select * from CTE_Example

Lets take each line of the statement one by one and understand.

To define CTE we write "with" clause, then we give a name to the table expression, here I have given name as "CTE_Example"

Then we write "As" and enclose our code in two brackets (---), we can join multiple tables in the enclosed brackets.

In the last line, I have used "Select * from CTE_Example" , we are referring the Common table expression in the last line of code, So we can say that Its like a view, where we are defining and using the view in a single batch and CTE is not stored in the database as an permanent object. But it behaves like a view. we can perform delete and update statement on CTE and that will have direct impact on the referenced table those are being used in CTE. Lets take an example to understand this fact.

With CTE_Example(EID,DeptName)
as
(
select EID,DeptName from DEPT 
)
delete from CTE_Example where EID=10 and DeptName ='Payroll'

In the above statement we are deleting a row from CTE_Example and it will delete the data from the referenced table "DEPT" that is being used in the CTE.

Recover unsaved SQL query scripts

You may be able to find them in one of these locations (depending on the version of Windows you are using).

Windows XP

C:\Documents and Settings\YourUsername\My Documents\SQL Server Management Studio\Backup Files\

Windows Vista/7/10

%USERPROFILE%\Documents\SQL Server Management Studio\Backup Files

OR

%USERPROFILE%\AppData\Local\Temp

Googled from this source and this source.

How to use a variable for a key in a JavaScript object literal?

ES6 / 2020

If you're trying to push data to an object using "key:value" from any other source, you can use something like this:

let obj = {}
let key = "foo"
let value = "bar"

obj[`${key}`] = value

// A `console.log(obj)` would return:
// {foo: "bar}

// A `typeof obj` would return:
// "object"

Hope this helps someone :)

Jupyter notebook not running code. Stuck on In [*]

The answers that state that your kernel is still executing the code in the cell are correct. You can see that by the small circle in the top right. If it is filled with a black/grey color, then it means it is still running.

I just want to add that I experienced a problem in JupyterHub where the code in the cell would just not execute. I stopped and restarted the kernel, shutdown and reloaded the notebook, but it still did not run.

What worked for me was literally copy pasting the same code to a new cell and deleting the old one. It then ran from the new cell.

Python Selenium Chrome Webdriver

You need to specify the path where your chromedriver is located.

  1. Download chromedriver for your desired platform from here.

  2. Place chromedriver on your system path, or where your code is.

  3. If not using a system path, link your chromedriver.exe (For non-Windows users, it's just called chromedriver):

    browser = webdriver.Chrome(executable_path=r"C:\path\to\chromedriver.exe")
    

    (Set executable_path to the location where your chromedriver is located.)

    If you've placed chromedriver on your System Path, you can shortcut by just doing the following:

    browser = webdriver.Chrome()

  4. If you're running on a Unix-based operating system, you may need to update the permissions of chromedriver after downloading it in order to make it executable:

    chmod +x chromedriver

  5. That's all. If you're still experiencing issues, more info can be found on this other StackOverflow article: Can't use chrome driver for Selenium

jQuery iframe load() event?

You may use the jquery's Contents method to get the content of the iframe.

In android app Toolbar.setTitle method has no effect – application name is shown as title

I tried to rename the toolbar from the fragment

It helped me, I hope to help someone else

Activity activity = this.getActivity();
Toolbar toolbar = (Toolbar) activity.findViewById(R.id.detail_toolbar);
        if (toolbar != null) {
            activity.setTitle("Title");
        }

//toolbar.setTitle("Title"); did not give the same results

Screenshot: enter image description here

On a CSS hover event, can I change another div's styling?

A pure solution without jQuery:

Javascript (Head)

function chbg(color) {
    document.getElementById('b').style.backgroundColor = color;
}   

HTML (Body)

<div id="a" onmouseover="chbg('red')" onmouseout="chbg('white')">This is element a</div>
<div id="b">This is element b</div>

JSFiddle: http://jsfiddle.net/YShs2/

How can I list all tags for a Docker image on a remote registry?

I've managed to get it working using curl:

curl -u <username>:<password> https://myrepo.example/v1/repositories/<username>/<image_name>/tags

Note that image_name should not contain user details etc. For example if you're pushing image named myrepo.example/username/x then image_name should be x.

What is the use of <<<EOD in PHP?

there are four types of strings available in php. They are single quotes ('), double quotes (") and Nowdoc (<<<'EOD') and heredoc(<<<EOD) strings

you can use both single quotes and double quotes inside heredoc string. Variables will be expanded just as double quotes.

nowdoc strings will not expand variables just like single quotes.

ref: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

SQL Inner join more than two tables

Here is a general SQL query syntax to join three or more table. This SQL query should work in all major relation database e.g. MySQL, Oracle, Microsoft SQLServer, Sybase and PostgreSQL :

SELECT t1.col, t3.col FROM table1 join table2 ON table1.primarykey = table2.foreignkey
                                  join table3 ON table2.primarykey = table3.foreignkey

We first join table 1 and table 2 which produce a temporary table with combined data from table1 and table2, which is then joined to table3. This formula can be extended for more than 3 tables to N tables, You just need to make sure that SQL query should have N-1 join statement in order to join N tables. like for joining two tables we require 1 join statement and for joining 3 tables we need 2 join statement.

How to use Oracle's LISTAGG function with a unique filter?

Super simple answer - solved!

my full answer here it is now built in in some oracle versions.

select group_id, 
regexp_replace(
    listagg(name, ',') within group (order by name)
    ,'([^,]+)(,\1)*(,|$)', '\1\3')
from demotable
group by group_id;  

This only works if you specify the delimiter to ',' not ', ' ie works only for no spaces after the comma. If you want spaces after the comma - here is a example how.

select 
replace(
    regexp_replace(
     regexp_replace('BBall, BBall, BBall, Football, Ice Hockey ',',\s*',',')            
    ,'([^,]+)(,\1)*(,|$)', '\1\3')
,',',', ') 
from dual

gives BBall, Football, Ice Hockey

Trigger an action after selection select2

See the documentation events section

Depending on the version, one of the snippets below should give you the event you want, alternatively just replace "select2-selecting" with "change".

Version 4.0 +

Events are now in format: select2:selecting (instead of select2-selecting)

Thanks to snakey for the notification that this has changed as of 4.0

$('#yourselect').on("select2:selecting", function(e) { 
   // what you would like to happen
});

Version Before 4.0

$('#yourselect').on("select2-selecting", function(e) { 
   // what you would like to happen
});

Just to clarify, the documentation for select2-selecting reads:

select2-selecting Fired when a choice is being selected in the dropdown, but before any modification has been made to the selection. This event is used to allow the user to reject selection by calling event.preventDefault()

whereas change has:

change Fired when selection is changed.

So change may be more appropriate for your needs, depending on whether you want the selection to complete and then do your event, or potentially block the change.

Allow anonymous authentication for a single folder in web.config?

The first approach to take is to modify your web.config using the <location> configuration tag, and <allow users="?"/> to allow anonymous or <allow users="*"/> for all:

<configuration>
   <location path="Path/To/Public/Folder">
      <system.web>
         <authorization>
            <allow users="?"/>
         </authorization>
      </system.web>
   </location>
</configuration>

If that approach doesn't work then you can take the following approach which requires making a small modification to the IIS applicationHost.config.

First, change the anonymousAuthentication section's overrideModeDefault from "Deny" to "Allow" in C:\Windows\System32\inetsrv\config\applicationHost.config:

<section name="anonymousAuthentication" overrideModeDefault="Allow" />

overrideMode is a security feature of IIS. If override is disallowed at the system level in applicationHost.config then there is nothing you can do in web.config to enable it. If you don't have this level of access on your target system you have to take up that discussion with your hosting provider or system administrator.

Second, after setting overrideModeDefault="Allow" then you can put the following in your web.config:

<location path="Path/To/Public/Folder">
  <system.webServer>
    <security>
      <authentication>
        <anonymousAuthentication enabled="true" />
      </authentication>
    </security>
  </system.webServer>
</location>

How to convert a string to utf-8 in Python

Might be a bit overkill, but when I work with ascii and unicode in same files, repeating decode can be a pain, this is what I use:

def make_unicode(input):
    if type(input) != unicode:
        input =  input.decode('utf-8')
    return input

Laravel assets url

Besides put all your assets in the public folder, you can use the HTML::image() Method, and only needs an argument which is the path to the image, relative on the public folder, as well:

{{ HTML::image('imgs/picture.jpg') }}

Which generates the follow HTML code:

<img src="http://localhost:8000/imgs/picture.jpg">

The link to other elements of HTML::image() Method: http://laravel-recipes.com/recipes/185/generating-an-html-image-element

How do I tar a directory of files and folders without including the directory itself?

If it's a Unix/Linux system, and you care about hidden files (which will be missed by *), you need to do:

cd my_directory
tar zcvf ../my_directory.tar.gz * .??*

I don't know what hidden files look like under Windows.

Installing Bower on Ubuntu

on Ubuntu 12.04 and the packaged version of NodeJs is too old to install Bower using the PPA

sudo add-apt-repository ppa:chris-lea/node.js 
sudo apt-get update
sudo apt-get -y install nodejs

When this has installed, check the version:

npm --version
1.4.3

Now install Bower:

sudo npm install -g bower

This will fetch and install Bower globally.

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

Try to run Maven from the command line or type "-X" in the text field - you can't break anything this way, at the worst, you'll get an error (I don't have Netbeans; in Eclipse, there is a checkbox "Debug" for this).

When running with debug output enabled, you should see the paths which the exec-maven-plugin plugin uses.

The next step would then be to copy the command into a command prompt or terminal and execute it manually to see if you get a useful error message there.

Python speed testing - Time Difference - milliseconds

time.time() / datetime is good for quick use, but is not always 100% precise. For that reason, I like to use one of the std lib profilers (especially hotshot) to find out what's what.

TCPDF not render all CSS properties

TCPDF 5.9.010 (2010-10-27) - Support for CSS properties 'border-spacing' and 'padding' for tables were added.

LINQ extension methods - Any() vs. Where() vs. Exists()

foreach (var item in model.Where(x => !model2.Any(y => y.ID == x.ID)).ToList())
{
enter code here
}

same work you also can do with Contains

secondly Where is give you new list of values. thirdly using Exist is not a good practice, you can achieve your target from Any and contains like

EmployeeDetail _E = Db.EmployeeDetails.where(x=>x.Id==1).FirstOrDefault();

Hope this will clear your confusion.

How to add an image to the emulator gallery in android studio?

It's a very old question but I will answer this for future references.

To add any file to emulator just drag and drop the file.

The file will be copied to downloads folder of internal storage.

To access the file

Go to settings

Click On Storage & USB

Click On Internal Storage

Click On Explore (at the end)

and you got it in the downloads folder

now you will get notification to setup virtual SD card, follow the setup. after the successful setup you will be able to see pictures in gallery.

Java: set timeout on a certain block of code?

If it is test code you want to time, then you can use the time attribute:

@Test(timeout = 1000)  
public void shouldTakeASecondOrLess()
{
}

If it is production code, there is no simple mechanism, and which solution you use depends upon whether you can alter the code to be timed or not.

If you can change the code being timed, then a simple approach is is to have your timed code remember it's start time, and periodically the current time against this. E.g.

long startTime = System.currentTimeMillis();
// .. do stuff ..
long elapsed = System.currentTimeMillis()-startTime;
if (elapsed>timeout)
   throw new RuntimeException("tiomeout");

If the code itself cannot check for timeout, you can execute the code on another thread, and wait for completion, or timeout.

    Callable<ResultType> run = new Callable<ResultType>()
    {
        @Override
        public ResultType call() throws Exception
        {
            // your code to be timed
        }
    };

    RunnableFuture future = new FutureTask(run);
    ExecutorService service = Executors.newSingleThreadExecutor();
    service.execute(future);
    ResultType result = null;
    try
    {
        result = future.get(1, TimeUnit.SECONDS);    // wait 1 second
    }
    catch (TimeoutException ex)
    {
        // timed out. Try to stop the code if possible.
        future.cancel(true);
    }
    service.shutdown();
}

How update the _id of one MongoDB Document?

To do it for your whole collection you can also use a loop (based on Niels example):

db.status.find().forEach(function(doc){ 
    doc._id=doc.UserId; db.status_new.insert(doc);
});
db.status_new.renameCollection("status", true);

In this case UserId was the new ID I wanted to use

How to change MySQL column definition?

Do you mean altering the table after it has been created? If so you need to use alter table, in particular:

ALTER TABLE tablename MODIFY COLUMN new-column-definition

e.g.

ALTER TABLE test MODIFY COLUMN locationExpect VARCHAR(120);

How to convert existing non-empty directory into a Git working directory and push files to a remote repository

This is how I do. I have added explanation to understand what the heck is going on.

Initialize Local Repository

  • first initialize Git with

    git init

  • Add all Files for version control with

    git add .

  • Create a commit with message of your choice

    git commit -m 'AddingBaseCode'

Initialize Remote Repository

  • Create a project on GitHub and copy the URL of your project . as shown below:

    enter image description here

Link Remote repo with Local repo

  • Now use copied URL to link your local repo with remote GitHub repo. When you clone a repository with git clone, it automatically creates a remote connection called origin pointing back to the cloned repository. The command remote is used to manage set of tracked repositories.

    git remote add origin https://github.com/hiteshsahu/Hassium-Word.git

Synchronize

  • Now we need to merge local code with remote code. This step is critical otherwise we won't be able to push code on GitHub. You must call 'git pull' before pushing your code.

    git pull origin master --allow-unrelated-histories

Commit your code

  • Finally push all changes on GitHub

    git push -u origin master

set font size in jquery

You can try another way like that:

<div class="content">
        Australia
    </div>

jQuery code:

$(".content").css({
    background: "#d1d1d1",
    fontSize: "30px"
})

Now you can add more css property as you want.

Angular 2 ngfor first, last, index loop

By this you can get any index in *ngFor loop in ANGULAR ...

<ul>
  <li *ngFor="let object of myArray; let i = index; let first = first ;let last = last;">
    <div *ngIf="first">
       // write your code...
    </div>

    <div *ngIf="last">
       // write your code...
    </div>
  </li>
</ul>

We can use these alias in *ngFor

  • index : number : let i = index to get all index of object.
  • first : boolean : let first = first to get first index of object.
  • last : boolean : let last = last to get last index of object.
  • odd : boolean : let odd = odd to get odd index of object.
  • even : boolean : let even = even to get even index of object.

How do I send a cross-domain POST request via JavaScript?

CORS is for you. CORS is "Cross Origin Resource Sharing", is a way to send cross domain request.Now the XMLHttpRequest2 and Fetch API both support CORS, and it can send both POST and GET request

But it has its limits.Server need to specific claim the Access-Control-Allow-Origin, and it can not be set to '*'.

And if you want any origin can send request to you, you need JSONP (also need to set Access-Control-Allow-Origin, but can be '*')

For lots of request way if you don't know how to choice, I think you need a full functional component to do that.Let me introduce a simple component https://github.com/Joker-Jelly/catta


If you are using modern browser (> IE9, Chrome, FF, Edge, etc.), Very Recommend you to use a simple but beauty component https://github.com/Joker-Jelly/catta.It have no dependence, Less than 3KB, and it support Fetch, AJAX and JSONP with same deadly sample syntax and options.

catta('./data/simple.json').then(function (res) {
  console.log(res);
});

It also it support all the way to import to your project, like ES6 module, CommonJS and even <script> in HTML.

print call stack in C or C++

Of course the next question is: will this be enough ?

The main disadvantage of stack-traces is that why you have the precise function being called you do not have anything else, like the value of its arguments, which is very useful for debugging.

If you have access to gcc and gdb, I would suggest using assert to check for a specific condition, and produce a memory dump if it is not met. Of course this means the process will stop, but you'll have a full fledged report instead of a mere stack-trace.

If you wish for a less obtrusive way, you can always use logging. There are very efficient logging facilities out there, like Pantheios for example. Which once again could give you a much more accurate image of what is going on.

javascript function wait until another function to finish

In my opinion, deferreds/promises (as you have mentionned) is the way to go, rather than using timeouts.

Here is an example I have just written to demonstrate how you could do it using deferreds/promises.

Take some time to play around with deferreds. Once you really understand them, it becomes very easy to perform asynchronous tasks.

Hope this helps!

$(function(){
    function1().done(function(){
        // function1 is done, we can now call function2
        console.log('function1 is done!');

        function2().done(function(){
            //function2 is done
            console.log('function2 is done!');
        });
    });
});

function function1(){
    var dfrd1 = $.Deferred();
    var dfrd2= $.Deferred();

    setTimeout(function(){
        // doing async stuff
        console.log('task 1 in function1 is done!');
        dfrd1.resolve();
    }, 1000);

    setTimeout(function(){
        // doing more async stuff
        console.log('task 2 in function1 is done!');
        dfrd2.resolve();
    }, 750);

    return $.when(dfrd1, dfrd2).done(function(){
        console.log('both tasks in function1 are done');
        // Both asyncs tasks are done
    }).promise();
}

function function2(){
    var dfrd1 = $.Deferred();
    setTimeout(function(){
        // doing async stuff
        console.log('task 1 in function2 is done!');
        dfrd1.resolve();
    }, 2000);
    return dfrd1.promise();
}

convert double to int

Convert.ToInt32 is the best way to convert

How can I find a specific element in a List<T>?

You can solve your problem most concisely with a predicate written using anonymous method syntax:

MyClass found = list.Find(item => item.GetID() == ID);

Re-ordering factor levels in data frame

Assuming your dataframe is mydf:

mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))

jQuery Scroll to bottom of page/iframe

A simple function that jumps (instantly scrolls) to the bottom of the whole page. It uses the built-in .scrollTop(). I haven’t tried to adapt this to work with individual page elements.

function jumpToPageBottom() {
    $('html, body').scrollTop( $(document).height() - $(window).height() );
}

Where is the Keytool application?

If you have Android installed in windows, you will also find it here: C:\Program Files\Android\jdk\microsoft_dist_openjdk_1.8.0.25\jre\bin

How can I drop a "not null" constraint in Oracle when I don't know the name of the constraint?

alter table MYTABLE modify (MYCOLUMN null);

In Oracle, not null constraints are created automatically when not null is specified for a column. Likewise, they are dropped automatically when the column is changed to allow nulls.

Clarifying the revised question: This solution only applies to constraints created for "not null" columns. If you specify "Primary Key" or a check constraint in the column definition without naming it, you'll end up with a system-generated name for the constraint (and the index, for the primary key). In those cases, you'd need to know the name to drop it. The best advice there is to avoid the scenario by making sure you specify a name for all constraints other than "not null". If you find yourself in the situation where you need to drop one of these constraints generically, you'll probably need to resort to PL/SQL and the data-definition tables.

What is the difference between _tmain() and main() in C++?

Ok, the question seems to have been answered fairly well, the UNICODE overload should take a wide character array as its second parameter. So if the command line parameter is "Hello" that would probably end up as "H\0e\0l\0l\0o\0\0\0" and your program would only print the 'H' before it sees what it thinks is a null terminator.

So now you may wonder why it even compiles and links.

Well it compiles because you are allowed to define an overload to a function.

Linking is a slightly more complex issue. In C, there is no decorated symbol information so it just finds a function called main. The argc and argv are probably always there as call-stack parameters just in case even if your function is defined with that signature, even if your function happens to ignore them.

Even though C++ does have decorated symbols, it almost certainly uses C-linkage for main, rather than a clever linker that looks for each one in turn. So it found your wmain and put the parameters onto the call-stack in case it is the int wmain(int, wchar_t*[]) version.

Why do I get access denied to data folder when using adb?

There are two things to remember if you want to browse everything on your device.

  1. You need to have a phone with root access in order to browse the data folder on an Android phone. That means either you have a developer device (ADP1 or an ION from Google I/O) or you've found a way to 'root' your phone some other way.
  2. You need to be running ADB in root mode, do this by executing: adb root

What good are SQL Server schemas?

I tend to agree with Brent on this one... see this discussion here. http://www.brentozar.com/archive/2010/05/why-use-schemas/

In short... schemas aren't terribly useful except for very specific use cases. Makes things messy. Do not use them if you can help it. And try to obey the K(eep) I(t) S(imple) S(tupid) rule.

How can I install Apache Ant on Mac OS X?

MacPorts will install ant for you in MacOSX 10.9. Just use

$ sudo port install apache-ant

and it will install.

GridView sorting: SortDirection always Ascending

Automatic bidirectional sorting only works with the SQL data source. Unfortunately, all the documentation in MSDN assumes you are using that, so GridView can get a bit frustrating.

The way I do it is by keeping track of the order on my own. For example:

    protected void OnSortingResults(object sender, GridViewSortEventArgs e)
    {
        // If we're toggling sort on the same column, we simply toggle the direction. Otherwise, ASC it is.
        // e.SortDirection is useless and unreliable (only works with SQL data source).
        if (_sortBy == e.SortExpression)
            _sortDirection = _sortDirection == SortDirection.Descending ? SortDirection.Ascending : SortDirection.Descending;
        else
            _sortDirection = SortDirection.Ascending;

        _sortBy = e.SortExpression;

        BindResults();
    }

scale fit mobile web content using viewport meta tag

Try adding a style="width:100%;" to the img tag. That way the image will fill up the entire width of the page, thus scaling down if the image is larger than the viewport.

What is "overhead"?

Overhead typically reffers to the amount of extra resources (memory, processor, time, etc.) that different programming algorithms take.

For example, the overhead of inserting into a balanced Binary Tree could be much larger than the same insert into a simple Linked List (the insert will take longer, use more processing power to balance the Tree, which results in a longer percieved operation time by the user).

How to implement endless list with RecyclerView?

This is how I do it, simple and short:

    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener()
    {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy)
        {
            if(!recyclerView.canScrollVertically(1) && dy != 0)
            {
                // Load more results here

            }
        }
    });

Data structure for maintaining tabular data in memory?

I personally wrote a lib for pretty much that quite recently, it is called BD_XML

as its most fundamental reason of existence is to serve as a way to send data back and forth between XML files and SQL databases.

It is written in Spanish (if that matters in a programming language) but it is very simple.

from BD_XML import Tabla

It defines an object called Tabla (Table), it can be created with a name for identification an a pre-created connection object of a pep-246 compatible database interface.

Table = Tabla('Animals') 

Then you need to add columns with the agregar_columna (add_column) method, with can take various key word arguments:

  • campo (field): the name of the field

  • tipo (type): the type of data stored, can be a things like 'varchar' and 'double' or name of python objects if you aren't interested in exporting to a data base latter.

  • defecto (default): set a default value for the column if there is none when you add a row

  • there are other 3 but are only there for database tings and not actually functional

like:

Table.agregar_columna(campo='Name', tipo='str')
Table.agregar_columna(campo='Year', tipo='date')
#declaring it date, time, datetime or timestamp is important for being able to store it as a time object and not only as a number, But you can always put it as a int if you don't care for dates
Table.agregar_columna(campo='Priority', tipo='int')

Then you add the rows with the += operator (or + if you want to create a copy with an extra row)

Table += ('Cat', date(1998,1,1), 1)
Table += {'Year':date(1998,1,1), 'Priority':2, Name:'Fish'}
#…
#The condition for adding is that is a container accessible with either the column name or the position of the column in the table

Then you can generate XML and write it to a file with exportar_XML (export_XML) and escribir_XML (write_XML):

file = os.path.abspath(os.path.join(os.path.dirname(__file__), 'Animals.xml'))
Table.exportar_xml()
Table.escribir_xml(file)

And then import it back with importar_XML (import_XML) with the file name and indication that you are using a file and not an string literal:

Table.importar_xml(file, tipo='archivo')
#archivo means file

Advanced

This are ways you can use a Tabla object in a SQL manner.

#UPDATE <Table> SET Name = CONCAT(Name,' ',Priority), Priority = NULL WHERE id = 2
for row in Table:
    if row['id'] == 2:
        row['Name'] += ' ' + row['Priority']
        row['Priority'] = None
print(Table)

#DELETE FROM <Table> WHERE MOD(id,2) = 0 LIMIT 1
n = 0
nmax = 1
for row in Table:
    if row['id'] % 2 == 0:
        del Table[row]
        n += 1
        if n >= nmax: break
print(Table)

this examples assume a column named 'id' but can be replaced width row.pos for your example.

if row.pos == 2:

The file can be download from:

https://bitbucket.org/WolfangT/librerias

Jenkins fails when running "service start jenkins"

Adding on to what has been already answered by Guna Sekaran. Jenkins need the user jenkins to be present in order to run the jenkins as a service.

To add user fire 'useradd jenkins' as root and fire 'passwd jenkins' as root before starting Jenkins as a service.

How to get the current URL within a Django template?

The below code helps me:

 {{ request.build_absolute_uri }}

Getting current device language in iOS?

For Swift 3:

NSLocale.preferredLanguages[0] as String

Achieving white opacity effect in html/css

If you can't use rgba due to browser support, and you don't want to include a semi-transparent white PNG, you will have to create two positioned elements. One for the white box, with opacity, and one for the overlaid text, solid.

_x000D_
_x000D_
body { background: red; }_x000D_
_x000D_
.box { position: relative; z-index: 1; }_x000D_
.box .back {_x000D_
    position: absolute; z-index: 1;_x000D_
    top: 0; left: 0; width: 100%; height: 100%;_x000D_
    background: white; opacity: 0.75;_x000D_
}_x000D_
.box .text { position: relative; z-index: 2; }_x000D_
_x000D_
body.browser-ie8 .box .back { filter: alpha(opacity=75); }
_x000D_
<!--[if lt IE 9]><body class="browser-ie8"><![endif]-->_x000D_
<!--[if gte IE 9]><!--><body><!--<![endif]-->_x000D_
    <div class="box">_x000D_
        <div class="back"></div>_x000D_
        <div class="text">_x000D_
            Lorem ipsum dolor sit amet blah blah boogley woogley oo._x000D_
        </div>_x000D_
    </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Run a Command Prompt command from Desktop Shortcut

Using the Drag and Drop method

  1. From the windows search bar type in cmd to pull up the windows bar operation.
  2. When the command line option is shown, right click it and select Open File Location.
  3. The file explorer opens and the shortcut link is highlighted in the folder. If it is not highlighted, then select it.
  4. Hold down the Control key and using the mouse drag the shortcut to the desktop. If you don't see Copy to Desktop while dragging and before dropping, then push down and hold the Control key until you see the message.
  5. Drop the link on the desktop.
  6. Change properties as needed.

How to detect page zoom level in all modern browsers?

This is for Chrome, in the wake of user800583 answer ...

I spent a few hours on this problem and have not found a better approach, but :

  • There are 16 'zoomLevel' and not 10
  • When Chrome is fullscreen/maximized the ratio is window.outerWidth/window.innerWidth, and when it is not, the ratio seems to be (window.outerWidth-16)/window.innerWidth, however the 1st case can be approached by the 2nd one.

So I came to the following ...

But this approach has limitations : for example if you play the accordion with the application window (rapidly enlarge and reduce the width of the window) then you will get gaps between zoom levels although the zoom has not changed (may be outerWidth and innerWidth are not exactly updated in the same time).

var snap = function (r, snaps)
{
    var i;
    for (i=0; i < 16; i++) { if ( r < snaps[i] ) return i; }
};
var w, l, r;
w = window.outerWidth, l = window.innerWidth;
return snap((w - 16) / l,
            [ 0.29, 0.42, 0.58, 0.71, 0.83, 0.95, 1.05, 1.18, 1.38, 1.63, 1.88, 2.25, 2.75, 3.5, 4.5, 100 ],
);

And if you want the factor :

var snap = function (r, snaps, ratios)
{
    var i;
    for (i=0; i < 16; i++) { if ( r < snaps[i] ) return eval(ratios[i]); }
};
var w, l, r;
w = window.outerWidth, l = window.innerWidth;
return snap((w - 16) / l,
            [ 0.29, 0.42, 0.58, 0.71, 0.83, 0.95, 1.05, 1.18, 1.38, 1.63, 1.88, 2.25, 2.75, 3.5, 4.5, 100 ],
            [ 0.25, '1/3', 0.5, '2/3', 0.75, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3, 4, 5 ]
);

'method' object is not subscriptable. Don't know what's wrong

You need to use parentheses: myList.insert([1, 2, 3]). When you leave out the parentheses, python thinks you are trying to access myList.insert at position 1, 2, 3, because that's what brackets are used for when they are right next to a variable.

Using comma as list separator with AngularJS

Just use Javascript's built-in join(separator) function for arrays:

<li ng-repeat="friend in friends">
  <b>{{friend.email.join(', ')}}</b>...
</li>

How can I test a PDF document if it is PDF/A compliant?

If you download the latest version of Adobe Acrobat Reader, it will tell you if your pdf is PDF/A compliant. Just open the PDF file and a big blue marking should appear.

OpenOffice supports PDF/A. For some reason "PDF/A-1" is called

"SelectPdfVersion"
internally in OpenOffice. Just add 1 to that value and your output should be PDF/A.

The different values can be

0 = PDFXNONE
1 = PDFX1A2001
2 = PDFX32002
3 = PDFA1A
4 = PDFA1B

You set

FilterData
to be a
HashMap('SelectPdfVersion',1) //1 for PDFX1A2001

Correct way to synchronize ArrayList in java

Yes it is the correct way, but the synchronised block is required if you want all the removals together to be safe - unless the queue is empty no removals allowed. My guess is that you just want safe queue and dequeue operations, so you can remove the synchronised block.

However, there are far advanced concurrent queues in Java such as ConcurrentLinkedQueue

unix sort descending order

If you only want to sort only on the 5th field then use -k5,5.

Also, use the -t command line switch to specify the delimiter to tab. Try this:

sort  -k5,5 -r -n -t \t filename

or if the above doesn't work (with the tab) this:

sort  -k5,5 -r -n -t $'\t' filename

The man page for sort states:

-t, --field-separator=SEP use SEP instead of non-blank to blank transition

Finally, this SO question Unix Sort with Tab Delimiter might be helpful.

Call parent method from child class c#

To follow up on the comment by suhendri to Rory McCrossan answer. Here is an Action delegate example:

In child add:

public Action UpdateProgress;  // In place of event handler declaration
                               // declare an Action delegate
.
.
.
private LoadData() {
    this.UpdateProgress();    // call to Action delegate - MyMethod in
                              // parent
}

In parent add:

// The 3 lines in the parent becomes:
ChildClass child = new ChildClass();
child.UpdateProgress = this.MyMethod;  // assigns MyMethod to child delegate

How to convert OutputStream to InputStream?

You will need an intermediate class which will buffer between. Each time InputStream.read(byte[]...) is called, the buffering class will fill the passed in byte array with the next chunk passed in from OutputStream.write(byte[]...). Since the sizes of the chunks may not be the same, the adapter class will need to store a certain amount until it has enough to fill the read buffer and/or be able to store up any buffer overflow.

This article has a nice breakdown of a few different approaches to this problem:

http://blog.ostermiller.org/convert-java-outputstream-inputstream

Get screenshot on Windows with Python?

Worth noting that ImageGrab only works on MSWindows.

For cross platform compatibility, a person may be best off with using the wxPython library. http://wiki.wxpython.org/WorkingWithImages#A_Flexible_Screen_Capture_App

import wx
wx.App()  # Need to create an App instance before doing anything
screen = wx.ScreenDC()
size = screen.GetSize()
bmp = wx.EmptyBitmap(size[0], size[1])
mem = wx.MemoryDC(bmp)
mem.Blit(0, 0, size[0], size[1], screen, 0, 0)
del mem  # Release bitmap
bmp.SaveFile('screenshot.png', wx.BITMAP_TYPE_PNG)

Select values of checkbox group with jQuery

mhata dzenyu mese. its actually

var selectedGroups  = new Array();
$(".user_group[checked]").each(function() {
    selectedGroups.push($(this).val());
});

Mysql password expired. Can't connect

Just open MySQL Workbench and choose [Instance] Startup/Shutdown and click on start server. It worked for me

How can I check if a file exists in Perl?

if(-e $base_path){print "Something";}

would do the trick

xcode-select active developer directory error

I was having an issue while trying to install packages using npm. I got the error: "sudo xcode-select -s /Applications//Xcode.app/Contents/Developer/"

To fix this

  • I opened Xcode.
  • Preferences
  • Locations
  • Selected the Command Lin Tools: Xcode 6.1.1

Now when installing packages with npm I no longer get errors.

How to do multiline shell script in Ansible

https://support.ansible.com/hc/en-us/articles/201957837-How-do-I-split-an-action-into-a-multi-line-format-

mentions YAML line continuations.

As an example (tried with ansible 2.0.0.2):

---
- hosts: all
  tasks:
    - name: multiline shell command
      shell: >
        ls --color
        /home
      register: stdout

    - name: debug output
      debug: msg={{ stdout }}

The shell command is collapsed into a single line, as in ls --color /home

Extend a java class from one file in another java file

What's missing from all the explanations is the fact that Java has a strict rule of class name = file name. Meaning if you have a class "Person", is must be in a file named "Person.java". Therefore, if one class tries to access "Person" the filename is not necessary, because it has got to be "Person.java".

Coming for C/C++, I have exact same issue. The answer is to create a new class (in a new file matching class name) and create a public string. This will be your "header" file. Then use that in your main file by using "extends" keyword.

Here is your answer:

  1. Create a file called Include.java. In this file, add this:

    public class Include {
        public static String MyLongString= "abcdef";
    }
    
  2. Create another file, say, User.java. In this file, put:

    import java.io.*;
    
    public class User extends Include {
        System.out.println(Include.MyLongString);
    }
    

HTML combo box with option to type an entry

Well it's 2016 and there is still no easy way to do a combo ... sure we have datalist but without safari/ios support it's not really usable. At least we have ES6 .. below is an attempt at a combo class that wraps a div or span, turning it into a combo by putting an input box on top of select and binding the relevant events.

see the code at: https://github.com/kofifus/Combo

(the code relies on the class pattern from https://github.com/kofifus/New)

Creating a combo is easy ! just pass a div to it's constructor:

_x000D_
_x000D_
let mycombo=Combo.New(document.getElementById('myCombo'));_x000D_
mycombo.options(['first', 'second', 'third']);_x000D_
_x000D_
mycombo.onchange=function(e, combo) {_x000D_
  let val=combo.value;_x000D_
  // let val=this.value; // same as above_x000D_
  alert(val);_x000D_
 }
_x000D_
<script src="https://rawgit.com/kofifus/New/master/new.min.js"></script>_x000D_
<script src="https://rawgit.com/kofifus/Combo/master/combo.min.js"></script>_x000D_
_x000D_
<div id="myCombo" style="width:100px;height:20px;"></div>
_x000D_
_x000D_
_x000D_

Postgres: INSERT if does not exist already

The solution in simple, but not immediatly.
If you want use this instruction, you must make one change to the db:

ALTER USER user SET search_path to 'name_of_schema';

after these changes "INSERT" will work correctly.

How do you stop tracking a remote branch in Git?

You can delete the remote-tracking branch using

git branch -d -r origin/<remote branch name>

as VonC mentions above. However, if you keep your local copy of the branch, git push will still try to push that branch (which could give you a non-fast-forward error as it did for ruffin). This is because the config push.default defaults to matching which means:

matching - push all matching branches. All branches having the same name in both ends are considered to be matching. This is the default.

(see http://git-scm.com/docs/git-config under push.default)

Seeing as this is probably not what you wanted when you deleted the remote-tracking branch, you can set push.default to upstream (or tracking if you have git < 1.7.4.3)

upstream - push the current branch to its upstream branch.

using

git config push.default upstream

and git will stop trying to push branches that you have "stopped tracking."

Note: The simpler solution would be to just rename your local branch to something else. That would eliminate some potential for confusion, as well.

Android getActivity() is undefined

In my application, it was enough to use:

myclassname.this

What is the Ruby <=> (spaceship) operator?

What is <=> ( The 'Spaceship' Operator )

According to the RFC that introduced the operator, $a <=> $b

 -  0 if $a == $b
 - -1 if $a < $b
 -  1 if $a > $b

 - Return 0 if values on either side are equal
 - Return 1 if value on the left is greater
 - Return -1 if the value on the right is greater

Example:

//Comparing Integers

echo 1 <=> 1; //ouputs 0
echo 3 <=> 4; //outputs -1
echo 4 <=> 3; //outputs 1

//String Comparison

echo "x" <=> "x"; // 0
echo "x" <=> "y"; //-1
echo "y" <=> "x"; //1

MORE:

// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1

// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1

// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1

echo "a" <=> "aa"; // -1
echo "zz" <=> "aa"; // 1

// Arrays
echo [] <=> []; // 0
echo [1, 2, 3] <=> [1, 2, 3]; // 0
echo [1, 2, 3] <=> []; // 1
echo [1, 2, 3] <=> [1, 2, 1]; // 1
echo [1, 2, 3] <=> [1, 2, 4]; // -1

// Objects
$a = (object) ["a" => "b"]; 
$b = (object) ["a" => "b"]; 
echo $a <=> $b; // 0

Make TextBox uneditable

This is for GridView.

 grid.Rows[0].Cells[1].ReadOnly = true;

Class Not Found: Empty Test Suite in IntelliJ

In Android Studio 3.0 +, sometimes UI tests are somehow interpreted as unit tests and it doesn't ask for target deployment selection. You can go to Edit Configuration and mark it as an Integration test and it would start working

java.lang.ClassNotFoundException: com.fasterxml.jackson.annotation.JsonInclude$Value

How about adding this to your pom.xml

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>${jackson.version}</version>
</dependency>

Display current time in 12 hour format with AM/PM

Use this SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm a");

enter image description here

Java docs for SimpleDateFormat

Notepad++ incrementally replace

Not sure about regex, but there is a way for you to do this in Notepad++, although it isn't very flexible.

In the example that you gave, hold Alt and select the column of numbers that you wish to change. Then go to Edit->Column Editor and select the Number to Insert radio button in the window that appears. Then specify your initial number and increment, and hit OK. It should write out the incremented numbers.

Note: this also works with the Multi-editing feature (selecting several locations while maintaining Ctrl key pressed).

This is, however, not anywhere near the flexibility that most people would find useful. Notepad++ is great, but if you want a truly powerful editor that can do things like this with ease, I'd say use Vim.

How do DATETIME values work in SQLite?

Store it in a field of type long. See Date.getTime() and new Date(long)

Java word count program

public class wordCOunt
{
public static void main(String ar[])
{
System.out.println("Simple Java Word Count Program");

    String str1 = "Today is Holdiay Day";

    int wordCount = 1;

    for (int i = 0; i < str1.length(); i++) 
    {
        if (str1.charAt(i) == ' '&& str1.charAt(i+1)!=' ') 
        {
            wordCount++;
        } 
    }

    System.out.println("Word count is = " +(str1.length()- wordCount));
}

}

JQuery - File attributes

<form id = "uploadForm" name = "uploadForm" enctype="multipart/form-data">
    <label for="uploadFile">Upload Your File</label>
     <input type="file" name="uploadFile" id="uploadFile">                  
</form>
<script>
    $('#uploadFile').change(function(){
        var fileName = this.files[0].name;
        var fileSize = this.files[0].size;
        var fileType = this.files[0].type;
        alert('FileName : ' + fileName + '\nFileSize : ' + fileSize + ' bytes');
    });
</script>

Note: To get the uploading file name means then use jquery val() method.

For Ex:

var fileName = $('#uploadFile').val();

I checked this above code before post, it works perfectly.!

How do I compare if a string is not equal to?

Either != or ne will work, but you need to get the accessor syntax and nested quotes sorted out.

<c:if test="${content.contentType.name ne 'MCE'}">
    <%-- snip --%>
</c:if>

What is the Difference Between read() and recv() , and Between send() and write()?

On Linux I also notice that :

Interruption of system calls and library functions by signal handlers
If a signal handler is invoked while a system call or library function call is blocked, then either:

  • the call is automatically restarted after the signal handler returns; or

  • the call fails with the error EINTR.

... The details vary across UNIX systems; below, the details for Linux.

If a blocked call to one of the following interfaces is interrupted by a signal handler, then the call is automatically restarted after the signal handler returns if the SA_RESTART flag was used; otherwise the call fails with the error EINTR:

  • read(2), readv(2), write(2), writev(2), and ioctl(2) calls on "slow" devices.

.....

The following interfaces are never restarted after being interrupted by a signal handler, regardless of the use of SA_RESTART; they always fail with the error EINTR when interrupted by a signal handler:

  • "Input" socket interfaces, when a timeout (SO_RCVTIMEO) has been set on the socket using setsockopt(2): accept(2), recv(2), recvfrom(2), recvmmsg(2) (also with a non-NULL timeout argument), and recvmsg(2).

  • "Output" socket interfaces, when a timeout (SO_RCVTIMEO) has been set on the socket using setsockopt(2): connect(2), send(2), sendto(2), and sendmsg(2).

Check man 7 signal for more details.


A simple usage would be use signal to avoid recvfrom blocking indefinitely.

An example from APUE:

#include "apue.h"
#include <netdb.h>
#include <errno.h>
#include <sys/socket.h>

#define BUFLEN      128
#define TIMEOUT     20

void
sigalrm(int signo)
{
}

void
print_uptime(int sockfd, struct addrinfo *aip)
{
    int     n;
    char    buf[BUFLEN];

    buf[0] = 0;
    if (sendto(sockfd, buf, 1, 0, aip->ai_addr, aip->ai_addrlen) < 0)
        err_sys("sendto error");
    alarm(TIMEOUT);
    //here
    if ((n = recvfrom(sockfd, buf, BUFLEN, 0, NULL, NULL)) < 0) {
        if (errno != EINTR)
            alarm(0);
        err_sys("recv error");
    }
    alarm(0);
    write(STDOUT_FILENO, buf, n);
}

int
main(int argc, char *argv[])
{
    struct addrinfo     *ailist, *aip;
    struct addrinfo     hint;
    int                 sockfd, err;
    struct sigaction    sa;

    if (argc != 2)
        err_quit("usage: ruptime hostname");
    sa.sa_handler = sigalrm;
    sa.sa_flags = 0;
    sigemptyset(&sa.sa_mask);
    if (sigaction(SIGALRM, &sa, NULL) < 0)
        err_sys("sigaction error");
    memset(&hint, 0, sizeof(hint));
    hint.ai_socktype = SOCK_DGRAM;
    hint.ai_canonname = NULL;
    hint.ai_addr = NULL;
    hint.ai_next = NULL;
    if ((err = getaddrinfo(argv[1], "ruptime", &hint, &ailist)) != 0)
        err_quit("getaddrinfo error: %s", gai_strerror(err));

    for (aip = ailist; aip != NULL; aip = aip->ai_next) {
        if ((sockfd = socket(aip->ai_family, SOCK_DGRAM, 0)) < 0) {
            err = errno;
        } else {
            print_uptime(sockfd, aip);
            exit(0);
        }
    }

    fprintf(stderr, "can't contact %s: %s\n", argv[1], strerror(err));
    exit(1);
}

How to get root directory in yii2

Supposing you have a writable "uploads" folder in your application:

You can define a param like this:

Yii::$app->params['uploadPath'] = realpath(Yii::$app->basePath) . '/uploads/';

Then you can simply use the parameter as:

$path1 = Yii::$app->params['uploadPath'] . $filename;

Just depending on if you are using advanced or simple template the base path will be (following the link provided by phazei):

Simple @app: Your application root directory

Advanced @app: Your application root directory (either frontend or backend or console depending on where you access it from)

This way the application will be more portable than using realpath(dirname(__FILE__).'/../../'));

moment.js get current time in milliseconds?

To get the current time's milliseconds, use http://momentjs.com/docs/#/get-set/millisecond/

var timeInMilliseconds = moment().milliseconds();

'ssh-keygen' is not recognized as an internal or external command

Just go to heroku.bat and add:

@SET PATH="D:\Program Files (x86)\Git\bin";%PATH% after @SET PATH=%HEROKU_RUBY%;%PATH%

in my case it's in D:\Program Files (x86)\Git\bin, change it to the path you've installed Git to. (i just left it with my path so it will be clearer on how to write this)

How to read fetch(PDO::FETCH_ASSOC);

PDOStatement::fetch returns a row from the result set. The parameter PDO::FETCH_ASSOC tells PDO to return the result as an associative array.

The array keys will match your column names. If your table contains columns 'email' and 'password', the array will be structured like:

Array
(
    [email] => '[email protected]'
    [password] => 'yourpassword'
)

To read data from the 'email' column, do:

$user['email'];

and for 'password':

$user['password'];

mysql error 1364 Field doesn't have a default values

As others said, this is caused by the STRICT_TRANS_TABLES SQL mode.

To check whether STRICT_TRANS_TABLES mode is enabled:

SHOW VARIABLES LIKE 'sql_mode';

To disable strict mode:

SET GLOBAL sql_mode='';

Linker error: "linker input file unused because linking not done", undefined reference to a function in that file

I think you are confused about how the compiler puts things together. When you use -c flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o files thus don't mix with -c, and compiler warns you about that. Symbols from object file are not moved to other object files like that.

All object files should be on the final linker invocation, which is not the case here, so linker (called via g++ front-end) complains about missing symbols.

Here's a small example (calling g++ explicitly for clarity):

PROG ?= myprog
OBJS = worker.o main.o

all: $(PROG)

.cpp.o:
        g++ -Wall -pedantic -ggdb -O2 -c -o $@ $<

$(PROG): $(OBJS)
        g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS)

There's also makedepend utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M gcc option for building make rules.

How to turn on front flash light programmatically in Android?

I have implemented this function in my application through fragments using SurfaceView. The link to this stackoverflow question and its answer can be found here

Hope this helps :)

How to install ADB driver for any android device?

I have found a solution by myself. I use the PDANet tool to find the driver automatically.

http://www.junefabrics.com/android/download.php

AngularJS Uploading An Image With ng-upload

In my case above mentioned methods work fine with php but when i try to upload files with these methods in node.js then i have some problem. So instead of using $http({..,..,...}) use the normal jquery ajax.

For select file use this

<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this)"/>

And in controller

$scope.uploadFile = function(element) {   
var data = new FormData();
data.append('file', $(element)[0].files[0]);
jQuery.ajax({
      url: 'brand/upload',
      type:'post',
      data: data,
      contentType: false,
      processData: false,
      success: function(response) {
      console.log(response);
      },
      error: function(jqXHR, textStatus, errorMessage) {
      alert('Error uploading: ' + errorMessage);
      }
 });   
};

Check cell for a specific letter or set of letters

You can use the following formula,

=IF(ISTEXT(REGEXEXTRACT(A1; "Bla")); "Yes";"No")

How do I push a new local branch to a remote Git repository and track it too?

For greatest flexibility, you could use a custom Git command. For example, create the following Python script somewhere in your $PATH under the name git-publish and make it executable:

#!/usr/bin/env python3

import argparse
import subprocess
import sys


def publish(args):
    return subprocess.run(['git', 'push', '--set-upstream', args.remote, args.branch]).returncode


def parse_args():
    parser = argparse.ArgumentParser(description='Push and set upstream for a branch')
    parser.add_argument('-r', '--remote', default='origin',
                        help="The remote name (default is 'origin')")
    parser.add_argument('-b', '--branch', help='The branch name (default is whatever HEAD is pointing to)',
                        default='HEAD')
    return parser.parse_args()


def main():
    args = parse_args()
    return publish(args)


if __name__ == '__main__':
    sys.exit(main())

Then git publish -h will show you usage information:

usage: git-publish [-h] [-r REMOTE] [-b BRANCH]

Push and set upstream for a branch

optional arguments:
  -h, --help            show this help message and exit
  -r REMOTE, --remote REMOTE
                        The remote name (default is 'origin')
  -b BRANCH, --branch BRANCH
                        The branch name (default is whatever HEAD is pointing to)

How to install PHP mbstring on CentOS 6.2

do the following:

sudo nano /etc/yum.repos.d/CentOS-Base.repo

under the section updates, comment out the mirrorlist line (put a # in front of the line), then on a new line write:

baseurl=http://centos.intergenia.de/$releasever/updates/$basearch/

now try:

yum install php-mbstring

(afterwards you'll probably want to uncomment the mirrorlist and comment out the baseurl)

How to remove old Docker containers

To get rid of your stopped container you can use:

docker rm <cointainer_id>

You can also use the name of the container:

docker rm <name>

If you want to get rid of all the stopped containers you can use the:

docker container prune

Or you can also use:

docker rm $(docker ps -aq -f status=exited)

You can use -v argument to delete any docker managed volumes that are not referenced any further

docker rm -v $(docker ps -aq -f status=exited)

You can also use --rm with the docker run. This will delete the container and the associated files when the container exists.

JQuery addclass to selected div, remove class if another div is selected

I had to transform the divs to list items otherwise all my divs would get that class and only the generated ones should get it Thanks everyone, I love this site and the helpful people on it !!!! You can follow the newbie school project at http://low-budgetwebservice.be/project/webbuilder.html suggestions are always welcome :). So this worked for me:

            /* Add Class Heading*/
            $(document).ready(function() {
            $( document ).on( 'click', 'ul#items li', function () { 
            $('ul#items li').removeClass('active'); 
            $(this).addClass('active');
            });
            });

Can table columns with a Foreign Key be NULL?

I also stuck on this issue. But I solved simply by defining the foreign key as unsigned integer. Find the below example-

CREATE TABLE parent (
   id int(10) UNSIGNED NOT NULL,
    PRIMARY KEY (id)
) ENGINE=INNODB;

CREATE TABLE child (
    id int(10) UNSIGNED NOT NULL,
    parent_id int(10) UNSIGNED DEFAULT NULL,
    FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE
) ENGINE=INNODB;

Javascript: console.log to html

This post has helped me a lot, and after a few iterations, this is what we use.

The idea is to post log messages and errors to HTML, for example if you need to debug JS and don't have access to the console.

You do need to change 'console.log' with 'logThis', as it is not recommended to change native functionality.

What you'll get:

  • A plain and simple 'logThis' function that will display strings and objects along with current date and time for each line
  • A dedicated window on top of everything else. (show it only when needed)
  • Can be used inside '.catch' to see relevant errors from promises.
  • No change of default console.log behavior
  • Messages will appear in the console as well.

_x000D_
_x000D_
function logThis(message) {
  // if we pass an Error object, message.stack will have all the details, otherwise give us a string
  if (typeof message === 'object') {
    message = message.stack || objToString(message);
  }

  console.log(message);

  // create the message line with current time
  var today = new Date();
  var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
  var time = today.getHours() + ':' + today.getMinutes() + ':' + today.getSeconds();
  var dateTime = date + ' ' + time + ' ';

  //insert line
  document.getElementById('logger').insertAdjacentHTML('afterbegin', dateTime + message + '<br>');
}

function objToString(obj) {
  var str = 'Object: ';
  for (var p in obj) {
    if (obj.hasOwnProperty(p)) {
      str += p + '::' + obj[p] + ',\n';
    }
  }
  return str;
}

const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

logThis(object1)
logThis('And all the roads we have to walk are winding, And all the lights that lead us there are blinding')
_x000D_
#logWindow {
  overflow: auto;
  position: absolute;
  width: 90%;
  height: 90%;
  top: 5%;
  left: 5%;
  right: 5%;
  bottom: 5%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 20;
}
_x000D_
<div id="logWindow">
  <pre id="logger"></pre>
</div>
_x000D_
_x000D_
_x000D_

Thanks this answer too, JSON.stringify() didn't work for this.

How to change href of <a> tag on button click through javascript

Exactly what Nick Carver did there but I think it would be best if used the DOM setAttribute method.

<script type="text/javascript">
   document.getElementById("myLink").onclick = function() {
   var link = document.getElementById("abc");
   link.setAttribute("href", "xyz.php");
   return false;
   }
</script>

It's one extra line of code but find it better structure-wise.

How to timeout a thread

I had the same problem. So i came up with a simple solution like this.

public class TimeoutBlock {

 private final long timeoutMilliSeconds;
    private long timeoutInteval=100;

    public TimeoutBlock(long timeoutMilliSeconds){
        this.timeoutMilliSeconds=timeoutMilliSeconds;
    }

    public void addBlock(Runnable runnable) throws Throwable{
        long collectIntervals=0;
        Thread timeoutWorker=new Thread(runnable);
        timeoutWorker.start();
        do{ 
            if(collectIntervals>=this.timeoutMilliSeconds){
                timeoutWorker.stop();
                throw new Exception("<<<<<<<<<<****>>>>>>>>>>> Timeout Block Execution Time Exceeded In "+timeoutMilliSeconds+" Milli Seconds. Thread Block Terminated.");
            }
            collectIntervals+=timeoutInteval;           
            Thread.sleep(timeoutInteval);

        }while(timeoutWorker.isAlive());
        System.out.println("<<<<<<<<<<####>>>>>>>>>>> Timeout Block Executed Within "+collectIntervals+" Milli Seconds.");
    }

    /**
     * @return the timeoutInteval
     */
    public long getTimeoutInteval() {
        return timeoutInteval;
    }

    /**
     * @param timeoutInteval the timeoutInteval to set
     */
    public void setTimeoutInteval(long timeoutInteval) {
        this.timeoutInteval = timeoutInteval;
    }
}

Guarantees that if block didn't execute within the time limit. the process will terminate and throws an exception.

example :

try {
        TimeoutBlock timeoutBlock = new TimeoutBlock(10 * 60 * 1000);//set timeout in milliseconds
        Runnable block=new Runnable() {

            @Override
            public void run() {
                //TO DO write block of code 
            }
        };

        timeoutBlock.addBlock(block);// execute the runnable block 

    } catch (Throwable e) {
        //catch the exception here . Which is block didn't execute within the time limit
    }

Self-reference for cell, column and row in worksheet functions

I don't see the need for Indirect, especially for conditional formatting.

The simplest way to self-reference a cell, row or column is to refer to it normally, e.g., "=A1" in cell A1, and make the reference partly or completely relative. For example, in a conditional formatting formula for checking whether there's a value in the first column of various cells' rows, enter the following with A1 highlighted and copy as necessary. The conditional formatting will always refer to column A for the row of each cell:

= $A1 <> ""

Angular2 use [(ngModel)] with [ngModelOptions]="{standalone: true}" to link to a reference to model's property

Using @angular/forms when you use a <form> tag it automatically creates a FormGroup.

For every contained ngModel tagged <input> it will create a FormControl and add it into the FormGroup created above; this FormControl will be named into the FormGroup using attribute name.

Example:

<form #f="ngForm">
    <input type="text" [(ngModel)]="firstFieldVariable" name="firstField">
    <span>{{ f.controls['firstField']?.value }}</span>
</form>

Said this, the answer to your question follows.

When you mark it as standalone: true this will not happen (it will not be added to the FormGroup).

Reference: https://github.com/angular/angular/issues/9230#issuecomment-228116474

Resizing an iframe based on content

iGoogle gadgets have to actively implement resizing, so my guess is in a cross-domain model you can't do this without the remote content taking part in some way. If your content can send a message with the new size to the container page using typical cross-domain communication techniques, then the rest is simple.

React Native - Image Require Module using Dynamic Names

Important Part here: We cannot concat the image name inside the require like [require('item'+vairable+'.png')]

Step 1: We create a ImageCollection.js file with the following collection of image properties

ImageCollection.js
================================
export default images={
    "1": require("./item1.png"),
    "2": require("./item2.png"),
    "3": require("./item3.png"),
    "4": require("./item4.png"),
    "5": require("./item5.png")
}

Step 2: Import image in your app and manipulate as necessary

class ListRepoApp extends Component {

    renderItem = ({item }) => (
        <View style={styles.item}>
            <Text>Item number :{item}</Text>
            <Image source={Images[item]}/>
        </View>
    );

    render () {
        const data = ["1","2","3","4","5"]
        return (
            <FlatList data={data} renderItem={this.renderItem}/>
        )
    }
}

export default ListRepoApp;

If you want a detailed explanation you could follow the link below Visit https://www.thelearninguy.com/react-native-require-image-using-dynamic-names

Courtesy : https://www.thelearninguy.com

HTML 5 video or audio playlist

You can add an event listener with 'ended' as the first param

Like this :

https://stackoverflow.com/a/2880950/6839331

How to add item to the beginning of List<T>?

Use List<T>.Insert

While not relevant to your specific example, if performance is important also consider using LinkedList<T> because inserting an item to the start of a List<T> requires all items to be moved over. See When should I use a List vs a LinkedList.

Null & empty string comparison in Bash

First of all, note you are not using the variable correctly:

if [ "pass_tc11" != "" ]; then
#     ^
#     missing $

Anyway, to check if a variable is empty or not you can use -z --> the string is empty:

if [ ! -z "$pass_tc11" ]; then
   echo "hi, I am not empty"
fi

or -n --> the length is non-zero:

if [ -n "$pass_tc11" ]; then
   echo "hi, I am not empty"
fi

From man test:

-z STRING

the length of STRING is zero

-n STRING

the length of STRING is nonzero

Samples:

$ [ ! -z "$var" ] && echo "yes"
$

$ var=""
$ [ ! -z "$var" ] && echo "yes"
$

$ var="a"
$ [ ! -z "$var" ] && echo "yes"
yes

$ var="a"
$ [ -n "$var" ] && echo "yes"
yes

Can I obtain method parameter name using Java reflection?

Yes.
Code must be compiled with Java 8 compliant compiler with option to store formal parameter names turned on (-parameters option).
Then this code snippet should work:

Class<String> clz = String.class;
for (Method m : clz.getDeclaredMethods()) {
   System.err.println(m.getName());
   for (Parameter p : m.getParameters()) {
    System.err.println("  " + p.getName());
   }
}

How to set the custom border color of UIView programmatically?

swift 3.0

self.uiTextView.layer.borderWidth = 0.5
    self.txtItemShortDes.layer.borderColor = UIColor(red:205.0/255.0, green:205.0/255.0, blue:205.0/255.0, alpha: 1.0).cgColor

Adding Table rows Dynamically in Android

change code of init like following,

public void init(){
    menuDB = new MenuDBAdapter(this);
    ll = (TableLayout) findViewById(R.id.displayLinear);
    ll.removeAllViews()

    for (int i = 0; i <2; i++) {
        TableRow row=(TableRow)findViewById(R.id.display_row);
        checkBox = new CheckBox(this);
        tv = new TextView(this);
        addBtn = new ImageButton(this);
        addBtn.setImageResource(R.drawable.add);
        minusBtn = new ImageButton(this);
        minusBtn.setImageResource(R.drawable.minus);
        qty = new TextView(this);
        checkBox.setText("hello");
        qty.setText("10");
        row.addView(checkBox);
        row.addView(minusBtn);
        row.addView(qty);
        row.addView(addBtn);
        ll.addView(row,i);

    }

How to switch to other branch in Source Tree to commit the code?

Hi I'm also relatively new but I can give you basic help.

  1. To switch to another branch use "Checkout". Just click on your branch and then on the button "checkout" at the top.

UPDATE 12.01.2016:

The bold line is the current branch.

You can also just double click a branch to use checkout.


  1. Your first answer I think depends on the repository you use (like github or bitbucket). Maybe the "Show hosted repository"-Button can help you (Left panel, bottom, right button = database with cog)

And here some helpful links:

Easy Git Guide

Git-flow - Git branching model

Tips on branching with sourcetree

WampServer orange icon

Before you can fix anything you need to know which service has not started, Apache or MySQL.

As the TEST PORT 80 utility is saying Apache is running its probably the MySQL service that has not started. Unless you have another Apache running!

So which service has not started???

If the wampmanager icon is not GREEN then one of the services ( Apache/MySQL ) has not started properly.

How to tell which service is not running if the wampmanager icon is orange.

Left click the wampmanager icon to reveal the menu-> Apache -> Service If the Start/Resume service menu is Green then Apache IS NOT running.

Left click the wampmanager icon to reveal the menu-> MySQL -> Service If the Start/Resume service menu is Green then MySQL IS NOT running.

If Apache is the service that is not running it is normally, but not always, because something else has captured port 80.

Now do, Left click the wampmanager icon to reveal the menu-> Apache -> Service -> Test port 80 This will launch a command window and display some information about what, if anything is using port 80.

Whatever it is should be re-configured to not use port 80 or uninstalled if you are not using it.

If port 80 is not the problem look for errors in the appropriate error log ( use the wamp manager menus to view the error logs )

If these do not exists or show no errors then also check the Windows Event Viewer Start -> Administrative Tools -> Event Viewer And look in the 'Windows Logs' -> Application' section accessed from the menu on the left of the dialog for error messages from Apache and or MySQL.

If its MYSQL that has not started.

Check the mysql error log by using the menus

wampmanager->MySQL->error log

Check the Windows Event log for messages from MYSQL

Check you dont have another MYSQL Server instance running.

How to Configure SKYPE so it does not require port 80 or 443

Run SKYPE then using the menus do this: Tools -> Options -> Advanced -> Connection Un-Check the checkbox next to 'Use port 80 and 443 as alternatives for incomming connections' Now restart SKYPE for these changes to take effect.

If you are running Windows 8 SKYPE comes as an app and this cannot ( as yet ) be configured in this way. However if you uninstall the SKYPE app and install SKYPE in the old way, you can reconfigure it, and it works just as well.

Force "git push" to overwrite remote files

Simple steps by using tortoisegit

GIT giving local files commit and pushing into git repository.

Steps :

1) stash changes stash name

2) pull

3) stash pop

4) commit 1 or more files and give commit changes description set author and Date

5) push

Why do I get "'property cannot be assigned" when sending an SMTP email?

mail.To and mail.From are readonly. Move them to the constructor.

using System.Net.Mail;

...

MailMessage mail = new MailMessage("[email protected]", "[email protected]");
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "smtp.gmail.com";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
client.Send(mail);

Jquery click not working with ipad

I usually use

.bind("click touchstart", function(){

});

instead of:

.click(function(){

});

That way you are binding the the correct event. It's also quicker, the touch responds much faster than click for some reason.

Setting the default page for ASP.NET (Visual Studio) server configuration

Go to the project's properties page, select the "Web" tab and on top (in the "Start Action" section), enter the page name in the "Specific Page" box. In your case index.aspx

How to get xdebug var_dump to show full object/array

These are configurable variables in php.ini:

; with sane limits
xdebug.var_display_max_depth = 10
xdebug.var_display_max_children = 256
xdebug.var_display_max_data = 1024 


; with no limits
; (maximum nesting is 1023)
xdebug.var_display_max_depth = -1 
xdebug.var_display_max_children = -1
xdebug.var_display_max_data = -1 

Of course, these may also be set at runtime via ini_set(), useful if you don't want to modify php.ini and restart your web server but need to quickly inspect something more deeply.

ini_set('xdebug.var_display_max_depth', '10');
ini_set('xdebug.var_display_max_children', '256');
ini_set('xdebug.var_display_max_data', '1024');

Xdebug settings are explained in the official documentation.

JavaScript: Difference between .forEach() and .map()

Diffrence between Foreach & map :

Map() : If you use map then map can return new array by iterating main array.

Foreach() : If you use Foreach then it can not return anything for each can iterating main array.

useFul link : use this link for understanding diffrence

https://codeburst.io/javascript-map-vs-foreach-f38111822c0f

How to find index of all occurrences of element in array?

This worked for me:

let array1 = [5, 12, 8, 130, 44, 12, 45, 12, 56];
let numToFind = 12
let indexesOf12 = [] // the number whose occurrence in the array we want to find

array1.forEach(function(elem, index, array) {
    if (elem === numToFind) {indexesOf12.push(index)}
    return indexesOf12
})

console.log(indexesOf12) // outputs [1, 5, 7]

How can I sort one set of data to match another set of data in Excel?

You can use VLOOKUP.

Assuming those are in columns A and B in Sheet1 and Sheet2 each, 22350 is in cell A2 of Sheet1, you can use:

=VLOOKUP(A2, Sheet2!A:B, 2, 0)

This will return you #N/A if there are no matches. Drag/Fill/Copy&Paste the formula to the bottom of your table and that should do it.

How can I bind to the change event of a textarea in jQuery?

bind is deprecated. Use on:

$("#textarea").on('change keyup paste', function() {
    // your code here
});

Note: The code above will fire multiple times, once for each matching trigger-type. To handle that, do something like this:

var oldVal = "";
$("#textarea").on("change keyup paste", function() {
    var currentVal = $(this).val();
    if(currentVal == oldVal) {
        return; //check to prevent multiple simultaneous triggers
    }

    oldVal = currentVal;
    //action to be performed on textarea changed
    alert("changed!");
});

jsFiddle Demo

How to uninstall Golang?

In MacOS, you can just do it with brew:

brew uninstall go
brew install go
brew upgrade go

Inheritance and init method in Python

In the first situation, Num2 is extending the class Num and since you are not redefining the special method named __init__() in Num2, it gets inherited from Num.

When a class defines an __init__() method, class instantiation automatically invokes __init__() for the newly-created class instance.

In the second situation, since you are redefining __init__() in Num2 you need to explicitly call the one in the super class (Num) if you want to extend its behavior.

class Num2(Num):
    def __init__(self,num):
        Num.__init__(self,num)
        self.n2 = num*2

Python spacing and aligning strings

You can use expandtabs to specify the tabstop, like this:

>>> print ('Location:'+'10-10-10-10'+'\t'+ 'Revision: 1'.expandtabs(30))
>>> print ('District: Tower'+'\t'+ 'Date: May 16, 2012'.expandtabs(30))
#Output:
Location:10-10-10-10          Revision: 1
District: Tower               Date: May 16, 2012

What does the Ellipsis object do?

In typer ... is used to create required parameters: The Argument class expects a default value, and if you pass the ... it will complain if the user does not pass the particular argument.

You could use None for the same if Ellipsis was not there, but this would remove the opportunity to express that None is the default value, in case that made any sense in your program.

Android SDK installation doesn't find JDK

Actual SETUP:

  • OS: Windows 8.1
  • JDK file: jdk-8u11-windows-x64.exe
  • ADT file: installer_r23.0.2-windows.exe

Install the x64 JDK, and try the back-next option first, and then try setting JAVA_HOME like the error message says, but if that doesn't work for you either, then try this:

Do as it says, set JAVA_HOME in your environment variables, but in the path use forward slashes instead of backslashes.

Seriously.

For me it failed when JAVA_HOME was C:\Program Files\Java\jdk1.6.0_31 but worked fine when it was C:/Program Files/Java/jdk1.6.0_31 - drove me nuts!

If this is not enough, also add to the beginning of the Environment Variable Path %JAVA_HOME%;

Updated values in System Environment Variables:

  • JAVA_HOME=C:/Program Files/Java/jdk1.8.0_11
  • JRE_HOME=C:/Program Files/Java/jre8
  • Path=%JAVA_HOME%;C:...

Git on Mac OS X v10.7 (Lion)

There are a couple of points to this answer.

Firstly, you don't need to install Xcode. The Git installer works perfectly well. However, if you want to use Git from within Xcode - it expects to find an installation under /usr/local/bin. If you have your own Git installed elsewhere - I've got a script that fixes this.

Second is to do with the path. My Git path used to be kept under /etc/paths.d/ However, a Mac OS X v10.7 (Lion) install overwrites the contents of this folder and the /etc/paths file as well. That's what happened to me and I got the same error. Recreating the path file fixed the problem.

How can I add a hint or tooltip to a label in C# Winforms?

yourToolTip = new ToolTip();
//The below are optional, of course,

yourToolTip.ToolTipIcon = ToolTipIcon.Info;
yourToolTip.IsBalloon = true;
yourToolTip.ShowAlways = true;

yourToolTip.SetToolTip(lblYourLabel,"Oooh, you put your mouse over me.");

Global variable Python classes

What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut or via an instance e.g. shape.lolwut but be careful while setting it as it will set an instance level attribute not class attribute

class Shape(object):
    lolwut = 1

shape = Shape()

print Shape.lolwut,  # 1
print shape.lolwut,  # 1

# setting shape.lolwut would not change class attribute lolwut 
# but will create it in the instance
shape.lolwut = 2

print Shape.lolwut,  # 1
print shape.lolwut,  # 2

# to change class attribute access it via class
Shape.lolwut = 3

print Shape.lolwut,  # 3
print shape.lolwut   # 2 

output:

1 1 1 2 3 2

Somebody may expect output to be 1 1 2 2 3 3 but it would be incorrect

JavaScript onclick redirect

Change the onclick from

onclick="javascript:SubmitFrm()"

to

onclick="SubmitFrm()"

Rebuild Docker container on file changes

After some research and testing, I found that I had some misunderstandings about the lifetime of Docker containers. Simply restarting a container doesn't make Docker use a new image, when the image was rebuilt in the meantime. Instead, Docker is fetching the image only before creating the container. So the state after running a container is persistent.

Why removing is required

Therefore, rebuilding and restarting isn't enough. I thought containers works like a service: Stopping the service, do your changes, restart it and they would apply. That was my biggest mistake.

Because containers are permanent, you have to remove them using docker rm <ContainerName> first. After a container is removed, you can't simply start it by docker start. This has to be done using docker run, which itself uses the latest image for creating a new container-instance.

Containers should be as independent as possible

With this knowledge, it's comprehensible why storing data in containers is qualified as bad practice and Docker recommends data volumes/mounting host directorys instead: Since a container has to be destroyed to update applications, the stored data inside would be lost too. This cause extra work to shutdown services, backup data and so on.

So it's a smart solution to exclude those data completely from the container: We don't have to worry about our data, when its stored safely on the host and the container only holds the application itself.

Why -rf may not really help you

The docker run command, has a Clean up switch called -rf. It will stop the behavior of keeping docker containers permanently. Using -rf, Docker will destroy the container after it has been exited. But this switch has two problems:

  1. Docker also remove the volumes without a name associated with the container, which may kill your data
  2. Using this option, its not possible to run containers in the background using -d switch

While the -rf switch is a good option to save work during development for quick tests, it's less suitable in production. Especially because of the missing option to run a container in the background, which would mostly be required.

How to remove a container

We can bypass those limitations by simply removing the container:

docker rm --force <ContainerName>

The --force (or -f) switch which use SIGKILL on running containers. Instead, you could also stop the container before:

docker stop <ContainerName>
docker rm <ContainerName>

Both are equal. docker stop is also using SIGTERM. But using --force switch will shorten your script, especially when using CI servers: docker stop throws an error if the container is not running. This would cause Jenkins and many other CI servers to consider the build wrongly as failed. To fix this, you have to check first if the container is running as I did in the question (see containerRunning variable).

Full script for rebuilding a Docker container

According to this new knowledge, I fixed my script in the following way:

#!/bin/bash
imageName=xx:my-image
containerName=my-container

docker build -t $imageName -f Dockerfile  .

echo Delete old container...
docker rm -f $containerName

echo Run new container...
docker run -d -p 5000:5000 --name $containerName $imageName

This works perfectly :)

CSS3 transition doesn't work with display property

max-height

.PrimaryNav-container {
...
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease;
...
}

.PrimaryNav.PrimaryNav--isOpen .PrimaryNav-container {
max-height: 300px;
}

https://www.codehive.io/boards/bUoLvRg

How do you read scanf until EOF in C?

Your code loops until it reads a single word, then exits. So if you give it multiple words it will read the first and exit, while if you give it an empty input, it will loop forever. In any case, it will only print random garbage from uninitialized memory. This is apparently not what you want, but what do you want? If you just want to read and print the first word (if it exists), use if:

if (scanf("%15s", word) == 1)
    printf("%s\n", word);

If you want to loop as long as you can read a word, use while:

while (scanf("%15s", word) == 1)
    printf("%s\n", word);

Also, as others have noted, you need to give the word array a size that is big enough for your scanf:

char word[16];

Others have suggested testing for EOF instead of checking how many items scanf matched. That's fine for this case, where scanf can't fail to match unless there's an EOF, but is not so good in other cases (such as trying to read integers), where scanf might match nothing without reaching EOF (if the input isn't a number) and return 0.

edit

Looks like you changed your question to match my code which works fine when I run it -- loops reading words until EOF is reached and then exits. So something else is going on with your code, perhaps related to how you are feeding it input as suggested by David

LINQ to Entities does not recognize the method

If anyone is looking for a VB.Net answer (as I was initially), here it is:

Public Function IsSatisfied() As Expression(Of Func(Of Charity, String, String, Boolean))

Return Function(charity, name, referenceNumber) (String.IsNullOrWhiteSpace(name) Or
                                                         charity.registeredName.ToLower().Contains(name.ToLower()) Or
                                                         charity.alias.ToLower().Contains(name.ToLower()) Or
                                                         charity.charityId.ToLower().Contains(name.ToLower())) And
                                                    (String.IsNullOrEmpty(referenceNumber) Or
                                                     charity.charityReference.ToLower().Contains(referenceNumber.ToLower()))
End Function

How to add headers to OkHttp request interceptor?

client = new OkHttpClient();

        Request request = new Request.Builder().header("authorization", token).url(url).build();
        MyWebSocketListener wsListener = new MyWebSocketListener(LudoRoomActivity.this);
        client.newWebSocket(request, wsListener);
        client.dispatcher().executorService().shutdown();

How to select between brackets (or quotes or ...) in Vim?

To select between the single quotes I usually do a vi' ("select inner single quotes").

Inside a parenthesis block, I use vib ("select inner block")

Inside a curly braces block you can use viB ("capital B")

To make the selections "inclusive" (select also the quotes, parenthesis or braces) you can use a instead of i.

You can read more about the Text object selections on the manual, or :help text-objects within vim.

MongoDB not equal to

If there is a null in an array and you want to avoid it:

db.test.find({"contain" : {$ne :[] }}).pretty()

Git copy changes from one branch to another

If you are using tortoise git.

please follow the below steps.

  1. Checkout BranchB
  2. Open project folder, go to TortoiseGit --> Pull
  3. In pull screen, Change the remote branch "BranchA" and click ok.
  4. Then right click again, go to TortoiseGit --> Push.

Now your changes moved from BranchA to BranchB

Char array to hex string C++

Here is something:

char const hex_chars[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

for( int i = data; i < data_length; ++i )
{
    char const byte = data[i];

    string += hex_chars[ ( byte & 0xF0 ) >> 4 ];
    string += hex_chars[ ( byte & 0x0F ) >> 0 ];
}

How can I use the apply() function for a single column?

Although the given responses are correct, they modify the initial data frame, which is not always desirable (and, given the OP asked for examples "using apply", it might be they wanted a version that returns a new data frame, as apply does).

This is possible using assign: it is valid to assign to existing columns, as the documentation states (emphasis is mine):

Assign new columns to a DataFrame.

Returns a new object with all original columns in addition to new ones. Existing columns that are re-assigned will be overwritten.

In short:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame([{'a': 15, 'b': 15, 'c': 5}, {'a': 20, 'b': 10, 'c': 7}, {'a': 25, 'b': 30, 'c': 9}])

In [3]: df.assign(a=lambda df: df.a / 2)
Out[3]: 
      a   b  c
0   7.5  15  5
1  10.0  10  7
2  12.5  30  9

In [4]: df
Out[4]: 
    a   b  c
0  15  15  5
1  20  10  7
2  25  30  9

Note that the function will be passed the whole dataframe, not only the column you want to modify, so you will need to make sure you select the right column in your lambda.

Reverting single file in SVN to a particular revision

The best way is to:

svn merge -c -RevisionToUndo ^/trunk

This will undo all files of the revision than simply revert those file you don't like to undo. Don't forget the dash (-) as prefix for the revision.

svn revert File1 File2

Now commit the changes back.

Saving an Object (Data persistence)

Quick example using company1 from your question, with python3.

import pickle

# Save the file
pickle.dump(company1, file = open("company1.pickle", "wb"))

# Reload the file
company1_reloaded = pickle.load(open("company1.pickle", "rb"))

However, as this answer noted, pickle often fails. So you should really use dill.

import dill

# Save the file
dill.dump(company1, file = open("company1.pickle", "wb"))

# Reload the file
company1_reloaded = dill.load(open("company1.pickle", "rb"))

Why is this rsync connection unexpectedly closed on Windows?

I saw this when changing rsync versions. In the older version, it worked to say:

rsync -e 'ssh ...

when the rsync.exe and ssh.exe were in the same directory.

With the newer version, I had to specify the path:

rsync -e './ssh ...

and it worked.

What is the inclusive range of float and double in Java?

Binary floating-point numbers have interesting precision characteristics, since the value is stored as a binary integer raised to a binary power. When dealing with sub-integer values (that is, values between 0 and 1), negative powers of two "round off" very differently than negative powers of ten.

For example, the number 0.1 can be represented by 1 x 10-1, but there is no combination of base-2 exponent and mantissa that can precisely represent 0.1 -- the closest you get is 0.10000000000000001.

So if you have an application where you are working with values like 0.1 or 0.01 a great deal, but where small (less than 0.000000000000001%) errors cannot be tolerated, then binary floating-point numbers are not for you.

Conversely, if powers of ten are not "special" to your application (powers of ten are important in currency calculations, but not in, say, most applications of physics), then you are actually better off using binary floating-point, since it's usually at least an order of magnitude faster, and it is much more memory efficient.

The article from the Python documentation on floating point issues and limitations does an excellent job of explaining this issue in an easy to understand form. Wikipedia also has a good article on floating point that explains the math behind the representation.

How to create an on/off switch with Javascript/CSS?

You mean something like IPhone checkboxes? Try Thomas Reynolds' iOS Checkboxes script:

Once the files are available to your site, activating the script is very easy:

...

$(document).ready(function() {
  $(':checkbox').iphoneStyle();
});

Results:

What's a simple way to get a text input popup dialog box on an iPhone

I would use a UIAlertView with a UITextField subview. You can either add the text field manually or, in iOS 5, use one of the new methods.

Static Classes In Java

In simple terms, Java supports the declaration of a class to be static only for the inner classes but not for the top level classes.

top level classes: A java project can contain more than one top level classes in each java source file, one of the classes being named after the file name. There are only three options or keywords allowed in front of the top level classes, public, abstract and final.

Inner classes: classes that are inside of a top level class are called inner classes, which is basically the concept of nested classes. Inner classes can be static. The idea making the inner classes static, is to take the advantage of instantiating the objects of inner classes without instantiating the object of the top level class. This is exactly the same way as the static methods and variables work inside of a top level class.

Hence Java Supports Static Classes at Inner Class Level (in nested classes)

And Java Does Not Support Static Classes at Top Level Classes.

I hope this gives a simpler solution to the question for basic understanding of the static classes in Java.

How do I convert a string to a number in PHP?

All suggestions lose the numeric type.

This seems to me a best practice:

function str2num($s){
// Returns a num or FALSE
    $return_value =  !is_numeric($s) ? false :               (intval($s)==floatval($s)) ? intval($s) :floatval($s);
    print "\nret=$return_value type=".gettype($return_value)."\n";
}

Unlocking tables if thread is lost

Here's what i do to FORCE UNLOCK FOR some locked tables in MySQL

1) Enter MySQL

mysql -u your_user -p

2) Let's see the list of locked tables

mysql> show open tables where in_use>0;

3) Let's see the list of the current processes, one of them is locking your table(s)

mysql> show processlist;

4) Let's kill one of these processes

mysql> kill put_process_id_here;

Add padding on view programmatically

use below method for setting padding dynamically

setPadding(int left, int top, int right, int bottom)

Example :

view.setPadding(2,2,2,2);

onClick function of an input type="button" not working

When I try:

<input type="button" id="moreFields" onclick="alert('The text will be show!!'); return false;" value="Give me more fields!"  />

It's worked well. So I think the problem is position of moreFields() function. Ensure that function will be define before your input tag.

Pls try:

<script type="text/javascript">
    function moreFields() {
        alert("The text will be show");
    }
</script>

<input type="button" id="moreFields" onclick="moreFields()" value="Give me more fields!"  />

Hope it helped.

What is the difference between JVM, JDK, JRE & OpenJDK?

JDK: The complete package which you need to write and run java code

OpenJDK: An independent implementation of JDK for making it much better

JVM: Converts Java code into bytecode and provides the specifications which tells how should a Java code be compiled, loaded, verified, checked for errors and executed.

JRE: Implementation of the JVM with which some Java libraries are used to Run the program

Count number of columns in a table row

If the colspan or rowspan is all set to 1, counting the children tds will give the correct answer. However, if there are spans, we cannot count the number of columns exactly, even by the maximum number of tds of the rows. Consider the following example:

_x000D_
_x000D_
var mytable = document.getElementById('table')_x000D_
for (var i=0; i < mytable.rows.length; ++i) {_x000D_
 document.write(mytable.rows[i].cells.length + "<br>");_x000D_
}
_x000D_
table, th, td {_x000D_
  border: 1px solid black;_x000D_
  border-collapse: collapse;_x000D_
  padding: 3px;_x000D_
}
_x000D_
<table id="table">_x000D_
    <thead>_x000D_
        <tr>_x000D_
            <th colspan="2">Header</th>_x000D_
            <th rowspan="2">Hi</th>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th>Month</th>_x000D_
            <th>Savings</th>_x000D_
        </tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <td colspan="2">hello</td>_x000D_
            <td>world</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>hello</td>_x000D_
            <td colspan="2">again</td>_x000D_
        </tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

jQuery: get parent tr for selected radio button

Try this.

You don't need to prefix attribute name by @ in jQuery selector. Use closest() method to get the closest parent element matching the selector.

$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');

You can simplify your method like this

function getSelectedRowGuid() {
    return GetRowGuid(
      $("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}

closest() - Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.

Xcode - Warning: Implicit declaration of function is invalid in C99

should call the function properly; like- Fibonacci:input

How to calculate the sum of the datatable column in asp.net?

Compute Sum of Column in Datatable , Works 100%

lbl_TotaAmt.Text = MyDataTable.Compute("Sum(BalAmt)", "").ToString();

if you want to have any conditions, use it like this

   lbl_TotaAmt.Text = MyDataTable.Compute("Sum(BalAmt)", "srno=1 or srno in(1,2)").ToString();

Difference between uint32 and uint32_t

uint32_t is defined in the standard, in

18.4.1 Header <cstdint> synopsis [cstdint.syn]

namespace std {
//...
typedef unsigned integer type uint32_t; // optional
//...
}

uint32 is not, it's a shortcut provided by some compilers (probably as typedef uint32_t uint32) for ease of use.

Best cross-browser method to capture CTRL+S with JQuery?

_x000D_
_x000D_
$(document).keydown(function(e) {_x000D_
    if ((e.key == 's' || e.key == 'S' ) && (e.ctrlKey || e.metaKey))_x000D_
    {_x000D_
        e.preventDefault();_x000D_
        alert("Ctrl-s pressed");_x000D_
        return false;_x000D_
    }_x000D_
    return true;_x000D_
}); 
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
Try pressing ctrl+s somewhere.
_x000D_
_x000D_
_x000D_

This is an up-to-date version of @AlanBellows's answer, replacing which with key. It also works even with Chrome's capital key glitch (where if you press Ctrl+S it sends capital S instead of s). Works in all modern browsers.

How to get the filename without the extension in Java?

The fluent way:

public static String fileNameWithOutExt (String fileName) {
    return Optional.of(fileName.lastIndexOf(".")).filter(i-> i >= 0)
            .map(i-> fileName.substring(0, i)).orElse(fileName);
}

CryptographicException 'Keyset does not exist', but only through WCF

I have faced this issue, my certificates where having private key but i was getting this error("Keyset does not exist")

Cause: Your web site is running under "Network services" account or having less privileges.

Solution: Change Application pool identity to "Local System", reset IIS and check again. If it starts working it is permission/Less privilege issue, you can impersonate then using other accounts too.

How do I enable/disable log levels in Android?

Stripping out the logging with proguard (see answer from @Christopher ) was easy and fast, but it caused stack traces from production to mismatch the source if there was any debug logging in the file.

Instead, here's a technique that uses different logging levels in development vs. production, assuming that proguard is used only in production. It recognizes production by seeing if proguard has renamed a given class name (in the example, I use "com.foo.Bar"--you would replace this with a fully-qualified class name that you know will be renamed by proguard).

This technique makes use of commons logging.

private void initLogging() {
    Level level = Level.WARNING;
    try {
        // in production, the shrinker/obfuscator proguard will change the
        // name of this class (and many others) so in development, this
        // class WILL exist as named, and we will have debug level
        Class.forName("com.foo.Bar");
        level = Level.FINE;
    } catch (Throwable t) {
        // no problem, we are in production mode
    }
    Handler[] handlers = Logger.getLogger("").getHandlers();
    for (Handler handler : handlers) {
        Log.d("log init", "handler: " + handler.getClass().getName());
        handler.setLevel(level);
    }
}

jquery simple image slideshow tutorial

I dont know why you havent marked on of these gr8 answers... here is another option which would enable you and anyone else visiting to control transition speed and pause time

JAVASCRIPT

$(function () {

    /* SET PARAMETERS */
    var change_img_time     = 5000; 
    var transition_speed    = 100;

    var simple_slideshow    = $("#exampleSlider"),
        listItems           = simple_slideshow.children('li'),
        listLen             = listItems.length,
        i                   = 0,

        changeList = function () {

            listItems.eq(i).fadeOut(transition_speed, function () {
                i += 1;
                if (i === listLen) {
                    i = 0;
                }
                listItems.eq(i).fadeIn(transition_speed);
            });

        };

    listItems.not(':first').hide();
    setInterval(changeList, change_img_time);

});

.

HTML

<ul id="exampleSlider">
    <li><img src="http://placehold.it/500x250" alt="" /></li>
    <li><img src="http://placehold.it/500x250" alt="" /></li>
    <li><img src="http://placehold.it/500x250" alt="" /></li>
    <li><img src="http://placehold.it/500x250" alt="" /></li>
</ul>

.
If your keeping this simple its easy to keep it resposive
best to visit the: DEMO

.
If you want something with special transition FX (Still responsive) - check this out
DEMO WITH SPECIAL FX

How can I roll back my last delete command in MySQL?

In MySQL:

start transaction;

savepoint sp1;

delete from customer where ID=1;

savepoint sp2;

delete from customer where ID=2;

rollback to sp2;

rollback to sp1;

How can I get the baseurl of site?

Try this:

string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + 
    Request.ApplicationPath.TrimEnd('/') + "/";

List<Map<String, String>> vs List<? extends Map<String, String>>

You cannot assign expressions with types such as List<NavigableMap<String,String>> to the first.

(If you want to know why you can't assign List<String> to List<Object> see a zillion other questions on SO.)

Indent starting from the second line of a paragraph with CSS

This worked for me:

p { margin-left: -2em; 
 text-indent: 2em 
 }

How to select rows with NaN in particular column?

Try the following:

df[df['Col2'].isnull()]

Accessing Session Using ASP.NET Web API

MVC

For an MVC project make the following changes (WebForms and Dot Net Core answer down below):

WebApiConfig.cs

public static class WebApiConfig
{
    public static string UrlPrefix         { get { return "api"; } }
    public static string UrlPrefixRelative { get { return "~/api"; } }

    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: WebApiConfig.UrlPrefix + "/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Global.asax.cs

public class MvcApplication : System.Web.HttpApplication
{
    ...

    protected void Application_PostAuthorizeRequest()
    {
        if (IsWebApiRequest())
        {
            HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
        }
    }

    private bool IsWebApiRequest()
    {
        return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(WebApiConfig.UrlPrefixRelative);
    }

}

This solution has the added bonus that we can fetch the base URL in javascript for making the AJAX calls:

_Layout.cshtml

<body>
    @RenderBody()

    <script type="text/javascript">
        var apiBaseUrl = '@Url.Content(ProjectNameSpace.WebApiConfig.UrlPrefixRelative)';
    </script>

    @RenderSection("scripts", required: false) 

and then within our Javascript files/code we can make our webapi calls that can access the session:

$.getJSON(apiBaseUrl + '/MyApi')
   .done(function (data) {
       alert('session data received: ' + data.whatever);
   })
);

WebForms

Do the above but change the WebApiConfig.Register function to take a RouteCollection instead:

public static void Register(RouteCollection routes)
{
    routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: WebApiConfig.UrlPrefix + "/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

And then call the following in Application_Start:

WebApiConfig.Register(RouteTable.Routes);

Dot Net Core

Add the Microsoft.AspNetCore.Session NuGet package and then make the following code changes:

Startup.cs

Call the AddDistributedMemoryCache and AddSession methods on the services object within the ConfigureServices function:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    ...

    services.AddDistributedMemoryCache();
    services.AddSession();

and in the Configure function add a call to UseSession:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
ILoggerFactory loggerFactory)
{
    app.UseSession();
    app.UseMvc();

SessionController.cs

Within your controller, add a using statement at the top:

using Microsoft.AspNetCore.Http;

and then use the HttpContext.Session object within your code like so:

    [HttpGet("set/{data}")]
    public IActionResult setsession(string data)
    {
        HttpContext.Session.SetString("keyname", data);
        return Ok("session data set");
    }

    [HttpGet("get")]
    public IActionResult getsessiondata()
    {
        var sessionData = HttpContext.Session.GetString("keyname");
        return Ok(sessionData);
    }

you should now be able to hit:

http://localhost:1234/api/session/set/thisissomedata

and then going to this URL will pull it out:

http://localhost:1234/api/session/get

Plenty more info on accessing session data within dot net core here: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state

Performance Concerns

Read Simon Weaver's answer below regarding performance. If you're accessing session data inside a WebApi project it can have very serious performance consequence - I have seen ASP.NET enforce a 200ms delay for concurrent requests. This could add up and become disastrous if you have many concurrent requests.


Security Concerns

Make sure you are locking down resources per user - an authenticated user shouldn't be able to retrieve data from your WebApi that they don't have access to.

Read Microsoft's article on Authentication and Authorization in ASP.NET Web API - https://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api

Read Microsoft's article on avoiding Cross-Site Request Forgery hack attacks. (In short, check out the AntiForgery.Validate method) - https://www.asp.net/web-api/overview/security/preventing-cross-site-request-forgery-csrf-attacks

What is a Python equivalent of PHP's var_dump()?

PHP's var_export() usually shows a serialized version of the object that can be exec()'d to re-create the object. The closest thing to that in Python is repr()

"For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval() [...]"

Sending an HTTP POST request on iOS

Sending an HTTP POST request on iOS (Objective c):

-(NSString *)postexample{

// SEND POST
NSString *url = [NSString stringWithFormat:@"URL"];
NSString *post = [NSString stringWithFormat:@"param=value"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];


NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"POST"];
[request setURL:[NSURL URLWithString:url]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSError *error = nil;
NSHTTPURLResponse *responseCode = nil;

//RESPONDE DATA 
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];

if([responseCode statusCode] != 200){
    NSLog(@"Error getting %@, HTTP status code %li", url, (long)[responseCode statusCode]);
    return nil;
}

//SEE RESPONSE DATA
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Response" message:[[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];

return [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
}

How to unstage large number of files without deleting the content

Warning: do not use the following command unless you want to lose uncommitted work!

Using git reset has been explained, but you asked for an explanation of the piped commands as well, so here goes:

git ls-files -z | xargs -0 rm -f
git diff --name-only --diff-filter=D -z | xargs -0 git rm --cached

The command git ls-files lists all files git knows about. The option -z imposes a specific format on them, the format expected by xargs -0, which then invokes rm -f on them, which means to remove them without checking for your approval.

In other words, "list all files git knows about and remove your local copy".

Then we get to git diff, which shows changes between different versions of items git knows about. Those can be changes between different trees, differences between local copies and remote copies, and so on.
As used here, it shows the unstaged changes; the files you have changed but haven't committed yet. The option --name-only means you want the (full) file names only and --diff-filter=D means you're interested in deleted files only. (Hey, didn't we just delete a bunch of stuff?) This then gets piped into the xargs -0 we saw before, which invokes git rm --cached on them, meaning that they get removed from the cache, while the working tree should be left alone — except that you've just removed all files from your working tree. Now they're removed from your index as well.

In other words, all changes, staged or unstaged, are gone, and your working tree is empty. Have a cry, checkout your files fresh from origin or remote, and redo your work. Curse the sadist who wrote these infernal lines; I have no clue whatsoever why anybody would want to do this.


TL;DR: you just hosed everything; start over and use git reset from now on.

Windows 7: unable to register DLL - Error Code:0X80004005

Use following command should work on windows 7. don't forget to enclose the dll name with full path in double quotations.

C:\Windows\SysWOW64>regsvr32 "c:\dll.name" 

How to subtract hours from a date in Oracle so it affects the day also

sysdate-(2/11)

A day consists of 24 hours. So, to subtract 2 hours from a day you need to divide it by 24:

DATE_value - 2/24

Using interval for the same:

DATE_value - interval '2' hour

Automated testing for REST Api

Frisby is a REST API testing framework built on node.js and Jasmine that makes testing API endpoints easy, fast, and fun. http://frisbyjs.com

Example:

var frisby = require('../lib/frisby');

var URL = 'http://localhost:3000/';
var URL_AUTH = 'http://username:password@localhost:3000/';

frisby.globalSetup({ // globalSetup is for ALL requests
  request: {
    headers: { 'X-Auth-Token': 'fa8426a0-8eaf-4d22-8e13-7c1b16a9370c' }
  }
});

frisby.create('GET user johndoe')
  .get(URL + '/users/3.json')
  .expectStatus(200)
  .expectJSONTypes({
    id: Number,
    username: String,
    is_admin: Boolean
  })
  .expectJSON({
    id: 3,
    username: 'johndoe',
    is_admin: false
  })
  // 'afterJSON' automatically parses response body as JSON and passes it as an argument
  .afterJSON(function(user) {
    // You can use any normal jasmine-style assertions here
    expect(1+1).toEqual(2);

    // Use data from previous result in next test
    frisby.create('Update user')
      .put(URL_AUTH + '/users/' + user.id + '.json', {tags: ['jasmine', 'bdd']})
      .expectStatus(200)
    .toss();
  })
.toss();

How to check if variable is array?... or something array-like

foreach can handle arrays and objects. You can check this with:

$can_foreach = is_array($var) || is_object($var);
if ($can_foreach) {
    foreach ($var as ...
}

You don't need to specifically check for Traversable as others have hinted it in their answers, because all objects - like all arrays - are traversable in PHP.

More technically:

foreach works with all kinds of traversables, i.e. with arrays, with plain objects (where the accessible properties are traversed) and Traversable objects (or rather objects that define the internal get_iterator handler).

(source)

Simply said in common PHP programming, whenever a variable is

  • an array
  • an object

and is not

  • NULL
  • a resource
  • a scalar

you can use foreach on it.

Java for loop multiple variables

change this line

for(int a = 0, b = 1; a<cards.length-1; b=a+1; a++;){ 

to

for(int a = 0, b = 1; a<cards.length-1, b=a+1; a++){

Quantile-Quantile Plot using SciPy

Using qqplot of statsmodels.api is another option:

Very basic example:

import numpy as np
import statsmodels.api as sm
import pylab

test = np.random.normal(0,1, 1000)

sm.qqplot(test, line='45')
pylab.show()

Result:

enter image description here

Documentation and more example are here

command/usr/bin/codesign failed with exit code 1- code sign error

Rebooting worked for me too. After upgrading to High Sierra I got tons of problems with password and it looks like I needed to enter the Password for the Keychain access to XCode.

C++ terminate called without an active exception

First you define a thread. And if you never call join() or detach() before calling the thread destructor, the program will abort.

As follows, calling a thread destructor without first calling join (to wait for it to finish) or detach is guarenteed to immediately call std::terminate and end the program.

Either implicitly detaching or joining a joinable() thread in its destructor could result in difficult to debug correctness (for detach) or performance (for join) bugs encountered only when an exception is raised. Thus the programmer must ensure that the destructor is never executed while the thread is still joinable.