Programs & Examples On #Context switching

When to use Task.Delay, when to use Thread.Sleep?

if the current thread is killed and you use Thread.Sleep and it is executing then you might get a ThreadAbortException. With Task.Delay you can always provide a cancellation token and gracefully kill it. Thats one reason I would choose Task.Delay. see http://social.technet.microsoft.com/wiki/contents/articles/21177.visual-c-thread-sleep-vs-task-delay.aspx

I also agree efficiency is not paramount in this case.

Truncate (not round) decimal places in SQL Server

Do you want the decimal or not?

If not, use

select ceiling(@value),floor(@value)

If you do it with 0 then do a round:

select round(@value,2)

How to remove item from a JavaScript object

_x000D_
_x000D_
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

this deletes test.blue

Declare global variables in Visual Studio 2010 and VB.NET

None of these answers seem to be changing anything for me.

I am converting an old Excel program to VB 2008. Of course, there are many Excel specific things to change, but something that is causing a headache seems to be this whole "Public" issue.

I have about 40 arrays all being referenced by about 20 modules. The arrays form the foundation of the entire project and are addressed by just about every procedure.

In Excel, I simply had to declare them all as Public. Worked great. No problem. But in VB2008, I'm finding it quite an issue. It is absurd to think that I have to go through thousands of lines of code merely to tell each reference where the Public has been declared. But even willing to do that, none of the schemes being proposed seems to help at all.

It appears that "Public" merely means "Public within this one module". Adding "Shared" seems to do nothing to change that. Adding the module name or anything else doesn't seem to change that. Each module insists that I declare all arrays (and about 100 other fundamental variables) within each module (a seemingly backward advance). And the "Imports" bit doesn't seem to know what I am talking about either, "cannot be found".

I have to sympathize with the questioner. Something seems terribly amiss with all of this.

ffmpeg usage to encode a video to H264 codec format

I used these options to convert to the H.264/AAC .mp4 format for HTML5 playback (I think it may help other guys with this problem in some way):

ffmpeg -i input.flv -vcodec mpeg4 -acodec aac output.mp4

UPDATE

As @LordNeckbeard mentioned, the previous line will produce MPEG-4 Part 2 (back in 2012 that worked somehow, I don't remember/understand why). Use the libx264 encoder to produce the proper video with H.264/AAC. To test the output file you can just drag it to a browser window and it should playback just fine.

ffmpeg -i input.flv -vcodec libx264 -acodec aac output.mp4

How to select Python version in PyCharm?

File -> Settings

Preferences->Project Interpreter->Python Interpreters

If it's not listed add it.

enter image description here

How to check if a socket is connected/disconnected in C#?

As Alexander Logger pointed out in zendars answer, you have to send something to be completely sure. In case your connected partner does not read on this socket at all, you can use the following code.

bool SocketConnected(Socket s)
{
  // Exit if socket is null
  if (s == null)
    return false;
  bool part1 = s.Poll(1000, SelectMode.SelectRead);
  bool part2 = (s.Available == 0);
  if (part1 && part2)
    return false;
  else
  {
    try
    {
      int sentBytesCount = s.Send(new byte[1], 1, 0);
      return sentBytesCount == 1;
    }
    catch
    {
      return false;
    }
  }
}

But even then it might take a few seconds until a broken network cable or something similar is detected.

How to decode JWT Token?

  var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
  var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
  var claims = new[]
  {
      new Claim(JwtRegisteredClaimNames.Email, model.UserName),
      new Claim(JwtRegisteredClaimNames.NameId, model.Id.ToString()),
  };
  var token = new JwtSecurityToken(_config["Jwt:Issuer"],
      _config["Jwt:Issuer"],
      claims,
      expires: DateTime.Now.AddMinutes(30),
      signingCredentials: creds);

Then extract content

 var handler = new JwtSecurityTokenHandler();
 string authHeader = Request.Headers["Authorization"];
 authHeader = authHeader.Replace("Bearer ", "");
 var jsonToken = handler.ReadToken(authHeader);
 var tokenS = handler.ReadToken(authHeader) as JwtSecurityToken;
 var id = tokenS.Claims.First(claim => claim.Type == "nameid").Value;

Exploring Docker container's file system

For an already running container, you can do:

dockerId=$(docker inspect -f {{.Id}} [docker_id_or_name])

cd /var/lib/docker/btrfs/subvolumes/$dockerId

You need to be root in order to cd into that dir. If you are not root, try 'sudo su' before running the command.

Edit: Following v1.3, see Jiri's answer - it is better.

Finding out current index in EACH loop (Ruby)

x.each_with_index { |v, i| puts "current index...#{i}" }

How to remove application from app listings on Android Developer Console

enter image description here

From Google Play Console, Select your app. Select Store Presence and select Pricing and Distribution from the side menu. There is a toggle switch to Publish and Unpublish app. Select UnPublish and click Submit Update Button in the top right corner.

Javascript reduce on array of objects

Array reduce function takes three parameters i.e, initialValue(default it's 0) , accumulator and current value . By default the value of initialValue will be "0" . which is taken by accumulator

Let's see this in code .

var arr =[1,2,4] ;
arr.reduce((acc,currVal) => acc + currVal ) ; 
// (remember Initialvalue is 0 by default )

//first iteration** : 0 +1 => Now accumulator =1;
//second iteration** : 1 +2 => Now accumulator =3;
//third iteration** : 3 + 4 => Now accumulator = 7;
No more array properties now the loop breaks .
// solution = 7

Now same example with initial Value :

var initialValue = 10;
var arr =[1,2,4] ;
arr.reduce((acc,currVal) => acc + currVal,initialValue ) ; 
/
// (remember Initialvalue is 0 by default but now it's 10 )

//first iteration** : 10 +1 => Now accumulator =11;
//second iteration** : 11 +2 => Now accumulator =13;
//third iteration** : 13 + 4 => Now accumulator = 17;
No more array properties now the loop breaks .
//solution=17

Same applies for the object arrays as well(the current stackoverflow question) :

var arr = [{x:1},{x:2},{x:4}]
arr.reduce(function(acc,currVal){return acc + currVal.x}) 
// destructing {x:1} = currVal;
Now currVal is object which have all the object properties .So now 
currVal.x=>1 
//first iteration** : 0 +1 => Now accumulator =1;
//second iteration** : 1 +2 => Now accumulator =3;
//third iteration** : 3 + 4 => Now accumulator = 7;
No more array properties now the loop breaks 
//solution=7

ONE THING TO BARE IN MIND is InitialValue by default is 0 and can be given anything i mean {},[] and number

linux execute command remotely

 ssh user@machine 'bash -s' < local_script.sh

or you can just

 ssh user@machine "remote command to run" 

How to form tuple column from two columns in Pandas

I'd like to add df.values.tolist(). (as long as you don't mind to get a column of lists rather than tuples)

import pandas as pd
import numpy as np

size = int(1e+07)
df = pd.DataFrame({'a': np.random.rand(size), 'b': np.random.rand(size)}) 

%timeit df.values.tolist()
1.47 s ± 38.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit list(zip(df.a,df.b))
1.92 s ± 131 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

$(form).ajaxSubmit is not a function

I'm guessing you don't have a jquery form plugin included. ajaxSubmit isn't a core jquery function, I believe.

Something like this : http://jquery.malsup.com/form/

UPD

<script src="http://malsup.github.com/jquery.form.js"></script> 

Using GroupBy, Count and Sum in LINQ Lambda Expressions

    var ListByOwner = list.GroupBy(l => l.Owner)
                          .Select(lg => 
                                new { 
                                    Owner = lg.Key, 
                                    Boxes = lg.Count(),
                                    TotalWeight = lg.Sum(w => w.Weight), 
                                    TotalVolume = lg.Sum(w => w.Volume) 
                                });

How to find all the dependencies of a table in sql server

This question is old but thought I'd add here.. https://www.simple-talk.com/sql/t-sql-programming/dependencies-and-references-in-sql-server/ talks about different options pros and cons and provides stored proc (It_Depends) that produces tree like result of dependencies very similar to SSMS

enter image description here

Name [jdbc/mydb] is not bound in this Context

For those who use Tomcat with Bitronix, this will fix the problem:

The error indicates that no handler could be found for your datasource 'jdbc/mydb', so you'll need to make sure your tomcat server refers to your bitronix configuration files as needed.

In case you're using btm-config.properties and resources.properties files to configure the datasource, specify these two JVM arguments in tomcat:

(if you already used them, make sure your references are correct):

  • btm.root
  • bitronix.tm.configuration

e.g.

-Dbtm.root="C:\Program Files\Apache Software Foundation\Tomcat 7.0.59" 
-Dbitronix.tm.configuration="C:\Program Files\Apache Software Foundation\Tomcat 7.0.59\conf\btm-config.properties" 

Now, restart your server and check the log.

Unable to import a module that is definitely installed

Something that worked for me was:

python -m pip install -user {package name}

The command does not require sudo. This was tested on OSX Mojave.

How do I check the difference, in seconds, between two dates?

Another approach is to use timestamp values:

end_time.timestamp() - start_time.timestamp()

What is the difference between "Form Controls" and "ActiveX Control" in Excel 2010?

Google is full of information on this. As Hans Passant said, Form controls are built in to Excel whereas ActiveX controls are loaded separately.

Generally you'll use Forms controls, they're simpler. ActiveX controls allow for more flexible design and should be used when the job just can't be done with a basic Forms control.

Many user's computers by default won't trust ActiveX, and it will be disabled; this sometimes needs to be manually added to the trust center. ActiveX is a microsoft-based technology and, as far as I'm aware, is not supported on the Mac. This is something you'll have to also consider, should you (or anyone you provide a workbook to) decide to use it on a Mac.

OS specific instructions in CMAKE: How to?

In General

You can detect and specify variables for several operating systems like that:

Detect Microsoft Windows

if(WIN32)
    # for Windows operating system in general
endif()

Or:

if(MSVC OR MSYS OR MINGW)
    # for detecting Windows compilers
endif()

Detect Apple MacOS

if(APPLE)
    # for MacOS X or iOS, watchOS, tvOS (since 3.10.3)
endif()

Detect Unix and Linux

if(UNIX AND NOT APPLE)
    # for Linux, BSD, Solaris, Minix
endif()

Your specific linker issue

To solve your issue with the Windows-specific wsock32 library, just remove it from other systems, like that:

if(WIN32)
    target_link_libraries(${PROJECT_NAME} bioutils wsock32)
else
    target_link_libraries(${PROJECT_NAME} bioutils)
endif()

How to use UIPanGestureRecognizer to move object? iPhone/iPad

-(IBAction)Method
{
      UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
      [panRecognizer setMinimumNumberOfTouches:1];
      [panRecognizer setMaximumNumberOfTouches:1];
      [ViewMain addGestureRecognizer:panRecognizer];
      [panRecognizer release];
}
- (Void)handlePan:(UIPanGestureRecognizer *)recognizer
{

     CGPoint translation = [recognizer translationInView:self.view];
     recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x, 
                                     recognizer.view.center.y + translation.y);
     [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];

     if (recognizer.state == UIGestureRecognizerStateEnded) {

         CGPoint velocity = [recognizer velocityInView:self.view];
         CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
         CGFloat slideMult = magnitude / 200;
         NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult);

         float slideFactor = 0.1 * slideMult; // Increase for more of a slide
         CGPoint finalPoint = CGPointMake(recognizer.view.center.x + (velocity.x * slideFactor), 
                                     recognizer.view.center.y + (velocity.y * slideFactor));
         finalPoint.x = MIN(MAX(finalPoint.x, 0), self.view.bounds.size.width);
         finalPoint.y = MIN(MAX(finalPoint.y, 0), self.view.bounds.size.height);

         [UIView animateWithDuration:slideFactor*2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
             recognizer.view.center = finalPoint;
         } completion:nil];

    }

}

How to force 'cp' to overwrite directory instead of creating another one inside?

The following command ensures dotfiles (hidden files) are included in the copy:

$ cp -Rf foo/. bar

Is there a "goto" statement in bash?

There is one more ability to achieve a desired results: command trap. It can be used to clean-up purposes for example.

tsconfig.json: Build:No inputs were found in config file

I got the same error and in my case it was because vscode couldn't recognize .ts file.

It was seeing it as text file and I had to rename it to remove one letter and add it back to make it work.

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

I had same problem, but I knew it had worked OK in other cases, so I reduced the problem to this:

parent.OtherRelatedItems.Clear();  //this worked OK on SaveChanges() - items were being deleted from DB
parent.ProblematicItems.Clear();   // this was causing the mentioned exception on SaveChanges()
  • OtherRelatedItems had a composite Primary Key (parentId + some local column) and worked OK
  • ProblematicItems had their own single-column Primary Key, and the parentId was only a FK. This was causing the exception after Clear().

All I had to do was to make the ParentId a part of composite PK to indicate that the children can't exist without a parent. I used DB-first model, added the PK and marked the parentId column as EntityKey (so, I had to update it both in DB and EF - not sure if EF alone would be enough).

I made RequestId part of the PK And then updated the EF model, AND set the other property as part of Entity Key

Once you think about it, it's a very elegant distinction that EF uses to decide if children "make sense" without a parent (in this case Clear() won't delete them and throw exception unless you set the ParentId to something else/special), or - like in the original question - we expect the items to be deleted once they are removed from the parent.

What does "dereferencing" a pointer mean?

Code and explanation from Pointer Basics:

The dereference operation starts at the pointer and follows its arrow over to access its pointee. The goal may be to look at the pointee state or to change the pointee state. The dereference operation on a pointer only works if the pointer has a pointee -- the pointee must be allocated and the pointer must be set to point to it. The most common error in pointer code is forgetting to set up the pointee. The most common runtime crash because of that error in the code is a failed dereference operation. In Java the incorrect dereference will be flagged politely by the runtime system. In compiled languages such as C, C++, and Pascal, the incorrect dereference will sometimes crash, and other times corrupt memory in some subtle, random way. Pointer bugs in compiled languages can be difficult to track down for this reason.

void main() {   
    int*    x;  // Allocate the pointer x
    x = malloc(sizeof(int));    // Allocate an int pointee,
                            // and set x to point to it
    *x = 42;    // Dereference x to store 42 in its pointee   
}

Write values in app.config file

On Framework 4.5 the AppSettings.Settings["key"] part of ConfigurationManager is read only so I had to first Remove the key then Add it again using the following:

Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);

config.AppSettings.Settings.Remove("MySetting");
config.AppSettings.Settings.Add("MySetting", "some value");

config.Save(ConfigurationSaveMode.Modified);

Don't worry, you won't get an exception if you try to Remove a key that doesn't exist.

This post gives some good advice

HttpClient does not exist in .net 4.0: what can I do?

Referring to the answers above, I am only adding this to help clarify things. It is possible to use HttpClient from .Net 4.0, and you have to install the package from here

However, the text is very confusion and contradicts itself.

This package is not supported in Visual Studio 2010, and is only required for projects targeting .NET Framework 4.5, Windows 8, or Windows Phone 8.1 when consuming a library that uses this package.

But underneath it states that these are the supported platforms.

Supported Platforms:

  • .NET Framework 4

  • Windows 8

  • Windows Phone 8.1

  • Windows Phone Silverlight 7.5

  • Silverlight 4

  • Portable Class Libraries

Ignore what it ways about targeting .Net 4.5. This is wrong. The package is all about using HttpClient in .Net 4.0. However, you may need to use VS2012 or higher. Not sure if it works in VS2010, but that may be worth testing.

How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?

In my case this started happening after a Windows Update, turns out the windows update turned off Internet Information Services which was making it appear that my API was unable to hit the break-point that I had set, but what was actually happening was that IIS was failing to start and therefore my application code wasn't actually running.

Double check that Internet Information Services is enabled in the Windows Features menu.

Instructions for IIS:

  • control panel
  • Programs
  • open or close windows features
  • tick internet information services
  • restart visual studio

If using IIS Express:

Open 'Add/Remove Programs' from the old control panel and run a repair on IIS Express Or you might go Control Panel ->> Programs ->> Programs and Features ->> Turn Windows features on or off ->> Internet Information Services and check the parent Internet Information Services folder.

I got this answer here: Specified argument was out of the range of valid values. Parameter name: site

Vim delete blank lines

:v/./d

or

:g/^$/d

or

:%!cat -s

How to select an option from drop down using Selenium WebDriver C#?

 var select = new SelectElement(elementX);
 select.MoveToElement(elementX).Build().Perform();

  var click = (
       from sel in select
       let value = "College"
       select value
       );

Count number of tables in Oracle

try:

SELECT COUNT(*) FROM USER_TABLES;

Well i dont have oracle on my machine, i run mysql (OP comment)

at the time of writing, this site was great for testing on a variety of database types.

Hibernate Delete query

instead of using

session.delete(object)

use

getHibernateTemplate().delete(object)

In both place for select query and also for delete use getHibernateTemplate()

In select query you have to use DetachedCriteria or Criteria

Example for select query

List<foo> fooList = new ArrayList<foo>();
DetachedCriteria queryCriteria = DetachedCriteria.forClass(foo.class);
queryCriteria.add(Restrictions.eq("Column_name",restriction));
fooList = getHibernateTemplate().findByCriteria(queryCriteria);

In hibernate avoid use of session,here I am not sure but problem occurs just because of session use

VBA copy cells value and format

This page from Microsoft's Excel VBA documentation helped me: https://docs.microsoft.com/en-us/office/vba/api/excel.xlpastetype

It gives a bunch of options to customize how you paste. For instance, you could xlPasteAll (probably what you're looking for), or xlPasteAllUsingSourceTheme, or even xlPasteAllExceptBorders.

jQuery ajax post file field

This should help. How can I upload files asynchronously?

As the post suggest I recommend a plugin located here http://malsup.com/jquery/form/#code-samples

Is the buildSessionFactory() Configuration method deprecated in Hibernate

or

public class Hbutil {

    private static SessionFactory sessionFactory;
    private static ServiceRegistry serviceRegistry;

    private static SessionFactory configureSessionFactory() throws HibernateException {
        Configuration configuration = new Configuration();
        configuration.configure();
        serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();        
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        return sessionFactory;
    }

    public static SessionFactory getSessionFactory() {
        return configureSessionFactory();

    }
}

INSTALL_FAILED_NO_MATCHING_ABIS when install apk

The comment of @enl8enmentnow should be an answer to fix the problem using genymotion:

If you have this problem on Genymotion even when using the ARM translator it is because you are creating an x86 virtual device like the Google Nexus 10. Pick an ARM virtual device instead, like one of the Custom Tablets.

Input text dialog Android

How about this EXAMPLE? It seems straightforward.

final EditText txtUrl = new EditText(this);

// Set the default text to a link of the Queen
txtUrl.setHint("http://www.librarising.com/astrology/celebs/images2/QR/queenelizabethii.jpg");

new AlertDialog.Builder(this)
  .setTitle("Moustachify Link")
  .setMessage("Paste in the link of an image to moustachify!")
  .setView(txtUrl)
  .setPositiveButton("Moustachify", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
      String url = txtUrl.getText().toString();
      moustachify(null, url);
    }
  })
  .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
    }
  })
  .show(); 

How do I resolve "Cannot find module" error using Node.js?

In my case I had UNMET PEER DEPENDENCY redux@^3.0.0 causing this error message, see all of them and install missing modules again using --save

npm install redux --save

Cannot start session without errors in phpMyAdmin

In my case it was the wrong ownership for /var/lib/php/session. I changed that to the Apache user and group (the user and group that the webserver runs as) and all was well.

How to list all the available keyspaces in Cassandra?

I suggest a combination of grep and awk:

root@DC1-Node1:/home# nodetool tablestats | grep "Keyspace :" | awk -F ":" '{print $2}'
 system_traces
 system
 system_distributed
 system_schema
 device_tool
 system_tool

Using CMake to generate Visual Studio C++ project files

As Alex says, it works very well. The only tricky part is to remember to make any changes in the cmake files, rather than from within Visual Studio. So on all platforms, the workflow is similar to if you'd used plain old makefiles.

But it's fairly easy to work with, and I've had no issues with cmake generating invalid files or anything like that, so I wouldn't worry too much.

How do I apply a diff patch on Windows?

Apply Patch

With TortoiseMerge:

  1. Find and open an existing SVN repo directory
  2. Create a new directory named "merges", if it does not exist already
  3. Copy the file onto which you want to apply the .patch file
  4. ADD and COMMIT to the svn repository before you continue to the next step
  5. Right click on merges and choose Apply patch...
  6. Double click the file from list
  7. The patched file with diff is displayed on the right pane
  8. Click on that pane and hit Save or export with File->Save As...

Alternative screeny if you Open from TortoiseMerge. In the screeny below, directory refers to the "merges" directory mentioned at step 2 above: Screeny

Screenshot of WinMerge GUI: Screeny

How do I check for vowels in JavaScript?

benchmark

I think you can safely say a for loop is faster.

I do admit that a regexp looks cleaner in terms of code. If it's a real bottleneck then use a for loop, otherwise stick with the regular expression for reasons of "elegance"

If you want to go for simplicity then just use

function isVowel(c) {
    return ['a', 'e', 'i', 'o', 'u'].indexOf(c.toLowerCase()) !== -1
}

Disabling browser caching for all browsers from ASP.NET

For what it's worth, I just had to handle this in my ASP.NET MVC 3 application. Here is the code block I used in the Global.asax file to handle this for all requests.

    protected void Application_BeginRequest()
    {
        //NOTE: Stopping IE from being a caching whore
        HttpContext.Current.Response.Cache.SetAllowResponseInBrowserHistory(false);
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        HttpContext.Current.Response.Cache.SetNoStore();
        Response.Cache.SetExpires(DateTime.Now);
        Response.Cache.SetValidUntilExpires(true);
    }

How to open a new tab using Selenium WebDriver

How to open a new tab using Selenium WebDriver with Java for Chrome:

ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-extensions");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.navigate().to("https://google.com");
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_T);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_T);

The above code will disable first extensions and using the robot class, a new tab will open.

Does MySQL ignore null values on unique constraints?

Yes, MySQL allows multiple NULLs in a column with a unique constraint.

CREATE TABLE table1 (x INT NULL UNIQUE);
INSERT table1 VALUES (1);
INSERT table1 VALUES (1);   -- Duplicate entry '1' for key 'x'
INSERT table1 VALUES (NULL);
INSERT table1 VALUES (NULL);
SELECT * FROM table1;

Result:

x
NULL
NULL
1

This is not true for all databases. SQL Server 2005 and older, for example, only allows a single NULL value in a column that has a unique constraint.

Tomcat - maxThreads vs maxConnections

Tomcat can work in 2 modes:

  • BIO – blocking I/O (one thread per connection)
  • NIOnon-blocking I/O (many more connections than threads)

Tomcat 7 is BIO by default, although consensus seems to be "don't use Bio because Nio is better in every way". You set this using the protocol parameter in the server.xml file.

  • BIO will be HTTP/1.1 or org.apache.coyote.http11.Http11Protocol
  • NIO will be org.apache.coyote.http11.Http11NioProtocol

If you're using BIO then I believe they should be more or less the same.

If you're using NIO then actually "maxConnections=1000" and "maxThreads=10" might even be reasonable. The defaults are maxConnections=10,000 and maxThreads=200. With NIO, each thread can serve any number of connections, switching back and forth but retaining the connection so you don't need to do all the usual handshaking which is especially time-consuming with HTTPS but even an issue with HTTP. You can adjust the "keepAlive" parameter to keep connections around for longer and this should speed everything up.

Have nginx access_log and error_log log to STDOUT and STDERR of master process

When running Nginx in a Docker container, be aware that a volume mounted over the log dir defeats the purpose of creating a softlink between the log files and stdout/stderr in your Dockerfile, as described in @Boeboe 's answer.

In that case you can either create the softlink in your entrypoint (executed after volumes are mounted) or not use a volume at all (e.g. when logs are already collected by a central logging system).

Default value for field in Django model

Set editable to False and default to your default value.

http://docs.djangoproject.com/en/stable/ref/models/fields/#editable

b = models.CharField(max_length=7, default='0000000', editable=False)

Also, your id field is unnecessary. Django will add it automatically.

How to check if a variable is null or empty string or all whitespace in JavaScript?

Old question, but I think it deservers a simpler answer.

You can simply do:

var addr = "  ";

if (addr && addr.trim()) {

    console.log("I'm not null, nor undefined, nor empty string, nor string composed of whitespace only.");

}

Android Studio suddenly cannot resolve symbols

Struggled with the same problem for a couple hours this morning. Building my project from command line seems to have done the trick for me.

Exact steps -

  1. Cloned fresh repository (no Android studio files are in repo)
  2. Built debug project from command line ( ./gradlew clean assembleDebug )
  3. Open Android Studio, import project

To check if it worked, look in your projects exploded-bundles folder, inspect a library and find the classes.jar. If it is expandable, then everything is going to be ok.

edit - I found after doing a clean within Android studio, it broke again. So if you have to clean, you will need to do this process again.

Search for a particular string in Oracle clob column

You can use the way like @Florin Ghita has suggested. But remember dbms_lob.substr has a limit of 4000 characters in the function For example :

dbms_lob.substr(clob_value_column,4000,1)

Otherwise you will find ORA-22835 (buffer too small)

You can also use the other sql way :

SELECT * FROM   your_table WHERE  clob_value_column LIKE '%your string%';

Note : There are performance problems associated with both the above ways like causing Full Table Scans, so please consider about Oracle Text Indexes as well:

https://docs.oracle.com/en/database/oracle/oracle-database/12.2/ccapp/indexing-with-oracle-text.html

Android getActivity() is undefined

In my application, it was enough to use:

myclassname.this

In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

That's the non-null assertion operator. It is a way to tell the compiler "this expression cannot be null or undefined here, so don't complain about the possibility of it being null or undefined." Sometimes the type checker is unable to make that determination itself.

It is explained here:

A new ! post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operation x! produces a value of the type of x with null and undefined excluded. Similar to type assertions of the forms <T>x and x as T, the ! non-null assertion operator is simply removed in the emitted JavaScript code.

I find the use of the term "assert" a bit misleading in that explanation. It is "assert" in the sense that the developer is asserting it, not in the sense that a test is going to be performed. The last line indeed indicates that it results in no JavaScript code being emitted.

R apply function with multiple parameters

To further generalize @Alexander's example, outer is relevant in cases where a function must compute itself on each pair of vector values:

vars1<-c(1,2,3)
vars2<-c(10,20,30)
mult_one<-function(var1,var2)
{
   var1*var2
}
outer(vars1,vars2,mult_one)

gives:

> outer(vars1, vars2, mult_one)
     [,1] [,2] [,3]
[1,]   10   20   30
[2,]   20   40   60
[3,]   30   60   90

R dplyr: Drop multiple columns

If you have a special character in the column names, either select or select_may not work as expected. This property of dplyr of using ".". To refer to the data set in the question, the following line can be used to solve this problem:

drop.cols <- c('Sepal.Length', 'Sepal.Width')
  iris %>% .[,setdiff(names(.),drop.cols)]

Post to another page within a PHP script

CURL method is very popular so yes it is good to use it. You could also explain more those codes with some extra comments because starters could understand them.

how to realize countifs function (excel) in R

Given a dataset

df <- data.frame( sex = c('M', 'M', 'F', 'F', 'M'), 
                  occupation = c('analyst', 'dentist', 'dentist', 'analyst', 'cook') )

you can subset rows

df[df$sex == 'M',] # To get all males
df[df$occupation == 'analyst',] # All analysts

etc.

If you want to get number of rows, just call the function nrow such as

nrow(df[df$sex == 'M',])

What is JSON and why would I use it?

We have to do a project on college and we faced a very big problem, it is called Same Origin Policy. Amog other things, it makes that your XMLHttpRequest method from Javascript can't make requests to domains other than the domain that your site is on.

For example you can't make request to www.otherexample.com if your site is on www.example.com. JSONRequest allows that, but you will get result in JSON format if that site allows that(for example it has a web service that returns messages in JSON). That is one problem where you could use JSON perhaps.

Here is something practical: Yahoo JSON

Importing class/java files in Eclipse

You can import a bunch of .java files to your existing project without creating a new project. Here are the steps:

  1. Right-click on the Default Package in the Project Manager pane underneath your project and choose Import
  2. An Import Wizard window will display. Choose File system and select the Next button
  3. You are now prompted to choose a file
  4. Simply browse your folder with .java files in it
  5. Select desired .java files
  6. Click on Finish to finish the import wizard

Check the following webpage for more information: http://people.cs.uchicago.edu/~kaharris/10200/tutorials/eclipse/Step_04.html

How to add multiple font files for the same font?

If you are using Google fonts I would suggest the following.

If you want the fonts to run from your localhost or server you need to download the files.

Instead of downloading the ttf packages in the download links, use the live link they provide, for example:

http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,300italic,400italic,600italic

Paste the URL in your browser and you should get a font-face declaration similar to the first answer.

Open the URLs provided, download and rename the files.

Stick the updated font-face declarations with relative paths to the woff files in your CSS, and you are done.

PHP 7 simpleXML

I had the same problem and I'm using Ubuntu 15.10.

In my case, to solve this issue, I installed the package php7.0-xml using the Synaptic package manager, which include SimpleXml. So, after restart my Apache server, my problem was solved. This package came in the Debian version and you can find it here: https://packages.debian.org/sid/php7.0-xml.

What is two way binding?

McGarnagle has a great answer, and you'll want to be accepting his, but I thought I'd mention (since you asked) how databinding works.

It's generally implemented by firing events whenever a change is made to the data, which then causes listeners (e.g. the UI) to be updated.

Two-way binding works by doing this twice, with a bit of care taken to ensure that you don't wind up stuck in an event loop (where the update from the event causes another event to be fired).

I was gonna put this in a comment, but it was getting pretty long...

How can I undo a mysql statement that I just executed?

For some instrutions, like ALTER TABLE, this is not possible with MySQL, even with transactions (1 and 2).

Posting form to different MVC post action depending on the clicked submit button

You can choose the url where the form must be posted (and thus, the invoked action) in different ways, depending on the browser support:

In this way you don't need to do anything special on the server side.

Of course, you can use Url extensions methods in your Razor to specify the form action.

For browsers supporting HMTL5: simply define your submit buttons like this:

<input type='submit' value='...' formaction='@Url.Action(...)' />

For older browsers I recommend using an unobtrusive script like this (include it in your "master layout"):

$(document).on('click', '[type="submit"][data-form-action]', function (event) {
  var $this = $(this);
  var formAction = $this.attr('data-form-action');
  $this.closest('form').attr('action', formAction);
});

NOTE: This script will handle the click for any element in the page that has type=submit and data-form-action attributes. When this happens, it takes the value of data-form-action attribute and set the containing form's action to the value of this attribute. As it's a delegated event, it will work even for HTML loaded using AJAX, without taking extra steps.

Then you simply have to add a data-form-action attribute with the desired action URL to your button, like this:

<input type='submit' data-form-action='@Url.Action(...)' value='...'/>

Note that clicking the button changes the form's action, and, right after that, the browser posts the form to the desired action.

As you can see, this requires no custom routing, you can use the standard Url extension methods, and you have nothing special to do in modern browsers.

Python name 'os' is not defined

Just add:

import os

in the beginning, before:

from settings import PROJECT_ROOT

This will import the python's module os, which apparently is used later in the code of your module without being imported.

Check if an object exists

You can use:

try:
   # get your models
except ObjectDoesNotExist:
   # do something

Uploading multiple files using formData()

To upload multiple files with angular form data, make sure you have this in your component.html

Upload Documents

                <div class="row">


                  <div class="col-md-4">
                     &nbsp; <small class="text-center">  Driver  Photo</small>
                    <div class="form-group">
                      <input  (change)="onFileSelected($event, 'profilepic')"  type="file" class="form-control" >
                    </div>
                  </div>

                  <div class="col-md-4">
                     &nbsp; <small> Driver ID</small>
                    <div class="form-group">
                      <input  (change)="onFileSelected($event, 'id')"  type="file" class="form-control" >
                    </div>
                  </div>

                  <div class="col-md-4">
                    &nbsp; <small>Driving Permit</small>
                    <div class="form-group">
                      <input type="file"  (change)="onFileSelected($event, 'drivingpermit')" class="form-control"  />
                    </div>
                  </div>
                </div>



                <div class="row">
                    <div class="col-md-6">
                       &nbsp; <small>Car Registration</small>
                      <div class="form-group">
                        <div class="input-group mb-4">
                            <input class="form-control" 
                (change)="onFileSelected($event, 'carregistration')" type="file"> <br>
                        </div>
                      </div>
                    </div>

                    <div class="col-md-6">
                        <small id="li"> Car Insurance</small>
                      <div class="form-group">
                        <div class="input-group mb-4">
                          <input class="form-control" (change)="onFileSelected($event, 

                         'insurancedocs')"   type="file">
                        </div>
                      </div>
                    </div>

                  </div>


                <div style="align-items:c" class="modal-footer">
                    <button type="button" class="btn btn-secondary" data- 
                  dismiss="modal">Close</button>
                    <button class="btn btn-primary"  (click)="uploadFiles()">Upload 
                  Files</button>
                  </div>
              </form>

In your componenet.ts file declare array selected files like this

selectedFiles = [];

// array of selected files

onFileSelected(event, type) {
    this.selectedFiles.push({ type, file: event.target.files[0] });
  }

//in the upload files method, append your form data like this

uploadFiles() {
    const formData = new FormData(); 

    this.selectedFiles.forEach(file => {
      formData.append(file.type, file.file, file.file.name); 
    });
    formData.append("driverid", this.driverid);

    this.driverService.uploadDriverDetails(formData).subscribe(
      res => {
        console.log(res); 

      },
      error => console.log(error.message)
    );
  }

NOTE: I hope this solution works for you friends

Simple way to convert datarow array to datatable

Why not iterate through your DataRow array and add (using DataRow.ImportRow, if necessary, to get a copy of the DataRow), something like:

foreach (DataRow row in rowArray) {
   dataTable.ImportRow(row);
}

Make sure your dataTable has the same schema as the DataRows in your DataRow array.

Visual studio code CSS indentation and formatting

Install HookyQR.beautify extension. It will beautify your javascript, JSON, CSS, Sass, and HTML in Visual Studio Code. It is the most use extensions for this purpose

How do I get the function name inside a function in PHP?

If you are using PHP 5 you can try this:

function a() {
    $trace = debug_backtrace();
    echo $trace[0]["function"];
}

Use of 'prototype' vs. 'this' in JavaScript?

I believe that @Matthew Crumley is right. They are functionally, if not structurally, equivalent. If you use Firebug to look at the objects that are created using new, you can see that they are the same. However, my preference would be the following. I'm guessing that it just seems more like what I'm used to in C#/Java. That is, define the class, define the fields, constructor, and methods.

var A = function() {};
A.prototype = {
    _instance_var: 0,

    initialize: function(v) { this._instance_var = v; },

    x: function() {  alert(this._instance_var); }
};

EDIT Didn't mean to imply that the scope of the variable was private, I was just trying to illustrate how I define my classes in javascript. Variable name has been changed to reflect this.

Are there benefits of passing by pointer over passing by reference in C++?

Clarifications to the preceding posts:


References are NOT a guarantee of getting a non-null pointer. (Though we often treat them as such.)

While horrifically bad code, as in take you out behind the woodshed bad code, the following will compile & run: (At least under my compiler.)

bool test( int & a)
{
  return (&a) == (int *) NULL;
}

int
main()
{
  int * i = (int *)NULL;
  cout << ( test(*i) ) << endl;
};

The real issue I have with references lies with other programmers, henceforth termed IDIOTS, who allocate in the constructor, deallocate in the destructor, and fail to supply a copy constructor or operator=().

Suddenly there's a world of difference between foo(BAR bar) and foo(BAR & bar). (Automatic bitwise copy operation gets invoked. Deallocation in destructor gets invoked twice.)

Thankfully modern compilers will pick up this double-deallocation of the same pointer. 15 years ago, they didn't. (Under gcc/g++, use setenv MALLOC_CHECK_ 0 to revisit the old ways.) Resulting, under DEC UNIX, in the same memory being allocated to two different objects. Lots of debugging fun there...


More practically:

  • References hide that you are changing data stored someplace else.
  • It's easy to confuse a Reference with a Copied object.
  • Pointers make it obvious!

html tables & inline styles

Forget float, margin and html 3/5. The mail is very obsolete. You need do all with table. One line = one table. You need margin or padding ? Do another column.

Codepen

Example : i need one line with 1 One Picture of 40*40 2 One margin of 10 px 3 One text of 400px

I start my line :

<table style=" background-repeat:no-repeat; width:450px;margin:0;" cellpadding="0" cellspacing="0" border="0">
   <tr style="height:40px; width:450px; margin:0;">
     <td style="height:40px; width:40px; margin:0;">
        <img src="" style="width=40px;height40;margin:0;display:block"
     </td>
     <td style="height:40px; width:10px; margin:0;">        
     </td>
     <td style="height:40px; width:400px; margin:0;">
     <p style=" margin:0;"> my text   </p>
     </td>
   </tr>
</table>

Converting string to double in C#

private double ConvertToDouble(string s)
    {
        char systemSeparator = Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalSeparator[0];
        double result = 0;
        try
        {
            if (s != null)
                if (!s.Contains(","))
                    result = double.Parse(s, CultureInfo.InvariantCulture);
                else
                    result = Convert.ToDouble(s.Replace(".", systemSeparator.ToString()).Replace(",", systemSeparator.ToString()));
        }
        catch (Exception e)
        {
            try
            {
                result = Convert.ToDouble(s);
            }
            catch
            {
                try
                {
                    result = Convert.ToDouble(s.Replace(",", ";").Replace(".", ",").Replace(";", "."));
                }
                catch {
                    throw new Exception("Wrong string-to-double format");
                }
            }
        }
        return result;
    }

and successfully passed tests are:

        Debug.Assert(ConvertToDouble("1.000.007") == 1000007.00);
        Debug.Assert(ConvertToDouble("1.000.007,00") == 1000007.00);
        Debug.Assert(ConvertToDouble("1.000,07") == 1000.07);
        Debug.Assert(ConvertToDouble("1,000,007") == 1000007.00);
        Debug.Assert(ConvertToDouble("1,000,000.07") == 1000000.07);
        Debug.Assert(ConvertToDouble("1,007") == 1.007);
        Debug.Assert(ConvertToDouble("1.07") == 1.07);
        Debug.Assert(ConvertToDouble("1.007") == 1007.00);
        Debug.Assert(ConvertToDouble("1.000.007E-08") == 0.07);
        Debug.Assert(ConvertToDouble("1,000,007E-08") == 0.07);

How can I get a list of locally installed Python modules?

I needed to find the specific version of packages available by default in AWS Lambda. I did so with a mashup of ideas from this page. I'm sharing it for posterity.

import pkgutil

__version__ = '0.1.1'

def get_ver(name):
    try:
        return str(__import__(name).__version__)
    except:
        return None

def lambda_handler(event, context):
    return {
        'statusCode': 200,
        'body': [{
                   'path': m.module_finder.path,
                   'name': m.name,
                   'version': get_ver(m.name),
                 } for m in list(pkgutil.iter_modules())
                 #if m.module_finder.path == "/var/runtime" # Uncomment this if you only care about a certain path
                ],
    }

What I discovered is that the provided boto3 library was way out of date and it wasn't my fault that my code was failing. I just needed to add boto3 and botocore to my project. But without this I would have been banging my head thinking my code was bad.

{
  "statusCode": 200,
  "body": [
    {
      "path": "/var/task",
      "name": "lambda_function",
      "version": "0.1.1"
    },
    {
      "path": "/var/runtime",
      "name": "bootstrap",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "boto3",
      "version": "1.9.42"
    },
    {
      "path": "/var/runtime",
      "name": "botocore",
      "version": "1.12.42"
    },
    {
      "path": "/var/runtime",
      "name": "dateutil",
      "version": "2.7.5"
    },
    {
      "path": "/var/runtime",
      "name": "docutils",
      "version": "0.14"
    },
    {
      "path": "/var/runtime",
      "name": "jmespath",
      "version": "0.9.3"
    },
    {
      "path": "/var/runtime",
      "name": "lambda_runtime_client",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "lambda_runtime_exception",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "lambda_runtime_marshaller",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "s3transfer",
      "version": "0.1.13"
    },
    {
      "path": "/var/runtime",
      "name": "six",
      "version": "1.11.0"
    },
    {
      "path": "/var/runtime",
      "name": "test_bootstrap",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "test_lambda_runtime_client",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "test_lambda_runtime_marshaller",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "urllib3",
      "version": "1.24.1"
    },
    {
      "path": "/var/lang/lib/python3.7",
      "name": "__future__",
      "version": null
    },
...

What I discovered was also different from what they officially publish. At the time of writing this:

  • Operating system – Amazon Linux
  • AMI – amzn-ami-hvm-2017.03.1.20170812-x86_64-gp2
  • Linux kernel – 4.14.77-70.59.amzn1.x86_64
  • AWS SDK for JavaScript – 2.290.0\
  • SDK for Python (Boto 3) – 3-1.7.74 botocore-1.10.74

click() event is calling twice in jquery

I solved this problem by change the element type. instead of button I place input, and this problem don't occur more.

instesd of:

<button onclick="doSomthing()">click me</button>

replace with:

<input onclick="doSomthing()" value="click me">

How can I show a hidden div when a select option is selected?

you can use the following common function.

<div>
     <select class="form-control" 
             name="Extension for area validity sought for" 
             onchange="CommonShowHide('txtc1opt2', this, 'States')"
     >
         <option value="All India">All India</option>
         <option value="States">States</option>
     </select>

     <input type="text" 
            id="txtc1opt2" 
            style="display:none;" 
            name="Extension for area validity sought for details" 
            class="form-control" 
            value="" 
            placeholder="">

</div>
<script>
    function CommonShowHide(ElementId, element, value) {
         document
             .getElementById(ElementId)
             .style
             .display = element.value == value ? 'block' : 'none';
    }
</script>

How to disable text selection highlighting

In the solutions in previous answers selection is stopped, but the user still thinks you can select text because the cursor still changes. To keep it static, you'll have to set your CSS cursor:

_x000D_
_x000D_
.noselect {_x000D_
    cursor: default;_x000D_
    -webkit-touch-callout: none;_x000D_
    -webkit-user-select: none;_x000D_
    -khtml-user-select: none;_x000D_
    -moz-user-select: none;_x000D_
    -ms-user-select: none;_x000D_
    user-select: none;_x000D_
}
_x000D_
<p>_x000D_
  Selectable text._x000D_
</p>_x000D_
<p class="noselect">_x000D_
  Unselectable text._x000D_
</p>
_x000D_
_x000D_
_x000D_

This will make your text totally flat, like it would be in a desktop application.

Determine SQL Server Database Size

According to SQL2000 help, sp_spaceused includes data and indexes.

This script should do:

CREATE TABLE #t (name SYSNAME, rows CHAR(11), reserved VARCHAR(18), 
data VARCHAR(18), index_size VARCHAR(18), unused VARCHAR(18))

EXEC sp_msforeachtable 'INSERT INTO #t EXEC sp_spaceused ''?'''
-- SELECT * FROM #t ORDER BY name
-- SELECT name, CONVERT(INT, SUBSTRING(data, 1, LEN(data)-3)) FROM #t ORDER BY name
SELECT SUM(CONVERT(INT, SUBSTRING(data, 1, LEN(data)-3))) FROM #t
DROP TABLE #t

PHP - Indirect modification of overloaded property

I was receiving this notice for doing this:

$var = reset($myClass->my_magic_property);

This fixed it:

$tmp = $myClass->my_magic_property;
$var = reset($tmp);

jquery can't get data attribute value

Iyap . Its work Case sensitive in data name data-x10

var variable = $('#myButton').data("x10"); // we get the value of custom data attribute

javascript popup alert on link click

In order to do this you need to attach the handler to a specific anchor on the page. For operations like this it's much easier to use a standard framework like jQuery. For example if I had the following HTML

HTML:

<a id="theLink">Click Me</a>

I could use the following jQuery to hookup an event to that specific link.

// Use ready to ensure document is loaded before running javascript
$(document).ready(function() {

  // The '#theLink' portion is a selector which matches a DOM element
  // with the id 'theLink' and .click registers a call back for the 
  // element being clicked on 
  $('#theLink').click(function (event) {

    // This stops the link from actually being followed which is the 
    // default action 
    event.preventDefault();

    var answer confirm("Please click OK to continue");
    if (!answer) {
      window.location="http://www.continue.com"
    }
  });

});

Standard Android Button with a different color

You can now also use appcompat-v7's AppCompatButton with the backgroundTint attribute:

<android.support.v7.widget.AppCompatButton
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:backgroundTint="#ffaa00"/>

Echo newline in Bash prints literal \n

This works for me in Raspbian,

echo -e "hello\\nworld"

how to pass command line arguments to main method dynamically

If you want to launch VM by sending arguments, you should send VM arguments and not Program arguments.

Program arguments are arguments that are passed to your application, which are accessible via the "args" String array parameter of your main method. VM arguments are arguments such as System properties that are passed to the JavaSW interpreter. The Debug configuration above is essentially equivalent to:

java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3

The VM arguments go after the call to your Java interpreter (ie, 'java') and before the Java class. Program arguments go after your Java class.

Consider a program ArgsTest.java:

package test;

import java.io.IOException;

    public class ArgsTest {

        public static void main(String[] args) throws IOException {

            System.out.println("Program Arguments:");
            for (String arg : args) {
                System.out.println("\t" + arg);
            }

            System.out.println("System Properties from VM Arguments");
            String sysProp1 = "sysProp1";
            System.out.println("\tName:" + sysProp1 + ", Value:" + System.getProperty(sysProp1));
            String sysProp2 = "sysProp2";
            System.out.println("\tName:" + sysProp2 + ", Value:" + System.getProperty(sysProp2));

        }
    }

If given input as,

java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3 

in the commandline, in project bin folder would give the following result:

Program Arguments:
  pro1
  pro2
  pro3
System Properties from VM Arguments
  Name:sysProp1, Value:sp1
  Name:sysProp2, Value:sp2

Database cluster and load balancing

Database clustering is a bit of an ambiguous term, some vendors consider a cluster having two or more servers share the same storage, some others call a cluster a set of replicated servers.

Replication defines the method by which a set of servers remain synchronized without having to share the storage being able to be geographically disperse, there are two main ways of going about it:

  • master-master (or multi-master) replication: Any server can update the database. It is usually taken care of by a different module within the database (or a whole different software running on top of them in some cases).

    Downside is that it is very hard to do well, and some systems lose ACID properties when in this mode of replication.

    Upside is that it is flexible and you can support the failure of any server while still having the database updated.

  • master-slave replication: There is only a single copy of authoritative data, which is the pushed to the slave servers.

    Downside is that it is less fault tolerant, if the master dies, there are no further changes in the slaves.

    Upside is that it is easier to do than multi-master and it usually preserve ACID properties.

Load balancing is a different concept, it consists distributing the queries sent to those servers so the load is as evenly distributed as possible. It is usually done at the application layer (or with a connection pool). The only direct relation between replication and load balancing is that you need some replication to be able to load balance, else you'd have a single server.

Keep getting No 'Access-Control-Allow-Origin' error with XMLHttpRequest

Remove:

httpRequest.setRequestHeader( 'Access-Control-Allow-Origin', '*');

... and add:

httpRequest.withCredentials = false;

Arguments to main in C

The signature of main is:

int main(int argc, char **argv);

argc refers to the number of command line arguments passed in, which includes the actual name of the program, as invoked by the user. argv contains the actual arguments, starting with index 1. Index 0 is the program name.

So, if you ran your program like this:

./program hello world

Then:

  • argc would be 3.
  • argv[0] would be "./program".
  • argv[1] would be "hello".
  • argv[2] would be "world".

Access all Environment properties as a Map or Properties object

The other answers have pointed out the solution for the majority of cases involving PropertySources, but none have mentioned that certain property sources are unable to be casted into useful types.

One such example is the property source for command line arguments. The class that is used is SimpleCommandLinePropertySource. This private class is returned by a public method, thus making it extremely tricky to access the data inside the object. I had to use reflection in order to read the data and eventually replace the property source.

If anyone out there has a better solution, I would really like to see it; however, this is the only hack I have gotten to work.

Virtual/pure virtual explained

In a C++ class, virtual is the keyword which designates that, a method can be overridden (i.e. implemented by) a subclass. For example:

class Shape 
{
  public:
    Shape();
    virtual ~Shape();

    std::string getName() // not overridable
    {
      return m_name;
    }

    void setName( const std::string& name ) // not overridable
    {
      m_name = name;
    }

  protected:
    virtual void initShape() // overridable
    {
      setName("Generic Shape");
    }

  private:
    std::string m_name;
};

In this case a subclass can override the the initShape function to do some specialized work:

class Square : public Shape
{
  public: 
    Square();
    virtual ~Square();

  protected:
    virtual void initShape() // override the Shape::initShape function
    {
      setName("Square");
    }
}

The term pure virtual refers to virtual functions that need to be implemented by a subclass and have not been implemented by the base class. You designate a method as pure virtual by using the virtual keyword and adding a =0 at the end of the method declaration.

So, if you wanted to make Shape::initShape pure virtual you would do the following:

class Shape 
{
 ...
    virtual void initShape() = 0; // pure virtual method
 ... 
};

By adding a pure virtual method to your class you make the class an abstract base class which is very handy for separating interfaces from implementation.

Sql Server equivalent of a COUNTIF aggregate function

I usually do what Josh recommended, but brainstormed and tested a slightly hokey alternative that I felt like sharing.

You can take advantage of the fact that COUNT(ColumnName) doesn't count NULLs, and use something like this:

SELECT COUNT(NULLIF(0, myColumn))
FROM AD_CurrentView

NULLIF - returns NULL if the two passed in values are the same.

Advantage: Expresses your intent to COUNT rows instead of having the SUM() notation. Disadvantage: Not as clear how it is working ("magic" is usually bad).

How to make an HTTP POST web request

Yet another way of doing it:

using (HttpClient httpClient = new HttpClient())
using (MultipartFormDataContent form = new MultipartFormDataContent())
{
    form.Add(new StringContent(param1), "param1");
    form.Add(new StringContent(param2), "param2");
    using (HttpResponseMessage response = await httpClient.PostAsync(url, form))
    {
        response.EnsureSuccessStatusCode();
        string res = await response.Content.ReadAsStringAsync();
        return res;
    }
}

This way you can easily post a stream.

HTML5 placeholder css padding

Setting line-height: 0px; fixed it for me in Chrome

tslint / codelyzer / ng lint error: "for (... in ...) statements must be filtered with an if statement"

I think this message is not about avoiding to use switch. Instead it wants you to check for hasOwnProperty. The background can be read here: https://stackoverflow.com/a/16735184/1374488

Set default option in mat-select

Working StackBlitz

No need to use ngModel or Forms

In your html:

 <mat-form-field>
  <mat-select [(value)]="selected" placeholder="Mode">
    <mat-option value="domain">Domain</mat-option>
    <mat-option value="exact">Exact</mat-option>
  </mat-select>
</mat-form-field>

and in your component just set your public property selected to the default:

selected = 'domain';

Cut off text in string after/before separator in powershell

I had a dir full of files including some that were named invoice no-product no.pdf and wanted to sort these by product no, so...

get-childitem *.pdf | sort-object -property @{expression={$\_.name.substring($\_.name.indexof("-")+1)}}

Note that in the absence of a - this sorts by $_.name

Add new item in existing array in c#.net

You can expand on the answer provided by @Stephen Chung by using his LINQ based logic to create an extension method using a generic type.

public static class CollectionHelper
{
    public static IEnumerable<T> Add<T>(this IEnumerable<T> sequence, T item)
    {
        return (sequence ?? Enumerable.Empty<T>()).Concat(new[] { item });
    }

    public static T[] AddRangeToArray<T>(this T[] sequence, T[] items)
    {
        return (sequence ?? Enumerable.Empty<T>()).Concat(items).ToArray();
    }

    public static T[] AddToArray<T>(this T[] sequence, T item)
    {
        return Add(sequence, item).ToArray();
    }

}

You can then call it directly on the array like this.

    public void AddToArray(string[] options)
    {
        // Add one item
        options = options.AddToArray("New Item");

        // Add a 
        options = options.AddRangeToArray(new string[] { "one", "two", "three" });

        // Do stuff...
    }

Admittedly, the AddRangeToArray() method seems a bit overkill since you have the same functionality with Concat() but this way the end code can "work" with the array directly as opposed to this:

options = options.Concat(new string[] { "one", "two", "three" }).ToArray();

SVN upgrade working copy

On MacOS:

  1. Get the latest compiled SVN client binaries from here.
  2. Install.
  3. Add binaries to path (the last installation screen explains how).
  4. Open terminal and run the following command on your project directory:

    svn upgrade

Can enums be subclassed to add new elements?

I suggest you take the other way around approach.

Instead of extending the existing enumeration, create a larger one and create a subset of it. For exemple if you had an enumeration called PET and you wanted to extend it to ANIMAL you should do this instead:

public enum ANIMAL {
    WOLF,CAT, DOG
} 
EnumSet<ANIMAL> pets = EnumSet.of(ANIMAL.CAT, ANIMAL.DOG);

Be careful, pets is not an immutable collections, you might want to use Guava or Java9 for more safety.

How to install PyQt5 on Windows?

You can easily install it using Anaconda. At first install Anaconda or Miniconda on you system (download from here) and then install the pyqt as follow:

conda install pyqt

It works for both version of python (2 and 3).

Converting HTML to PDF using PHP?

If you wish to create a pdf from php, pdflib will help you (as some others suggested).

Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.

So, the options I know are:

DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.

HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.

Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:

wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.

htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.

Go to next item in ForEach-Object

You just have to replace the break with a return statement.

Think of the code inside the Foreach-Object as an anonymous function. If you have loops inside the function, just use the control keywords applying to the construction (continue, break, ...).

MySQL: Invalid use of group function

You need to use HAVING, not WHERE.

The difference is: the WHERE clause filters which rows MySQL selects. Then MySQL groups the rows together and aggregates the numbers for your COUNT function.

HAVING is like WHERE, only it happens after the COUNT value has been computed, so it'll work as you expect. Rewrite your subquery as:

(                  -- where that pid is in the set:
SELECT c2.pid                  -- of pids
FROM Catalog AS c2             -- from catalog
WHERE c2.pid = c1.pid
HAVING COUNT(c2.sid) >= 2)

ERROR 1064 (42000): You have an error in your SQL syntax; Want to configure a password as root being the user

While using mysql version 8.0 + , use the following syntax to update root password after starting mysql daemon with --skip-grant-tables option

UPDATE user SET PASSWORD FOR 'root'@'localhost' = PASSWORD('your_new_password')

Accessing bash command line args $@ vs $*

$@ is same as $*, but each parameter is a quoted string, that is, the parameters are passed on intact, without interpretation or expansion. This means, among other things, that each parameter in the argument list is seen as a separate word.

Of course, "$@" should be quoted.

http://tldp.org/LDP/abs/html/internalvariables.html#ARGLIST

using CASE in the WHERE clause

SELECT *
FROM logs
WHERE pw='correct'
  AND CASE
          WHEN id<800 THEN success=1
          ELSE 1=1
      END
  AND YEAR(TIMESTAMP)=2011

Append data to a POST NSURLRequest

Any one looking for a swift solution

let url = NSURL(string: "http://www.apple.com/")
let request = NSMutableURLRequest(URL: url!)
request.HTTPBody = "company=Locassa&quality=AWESOME!".dataUsingEncoding(NSUTF8StringEncoding)

How to make PDF file downloadable in HTML link?

I know I am very late to answer this but I found a hack to do this in javascript.

function downloadFile(src){
    var link=document.createElement('a');
    document.body.appendChild(link);
    link.href= src;
    link.download = '';
    link.click();
}

Selecting the last value of a column

Regarding @Jon_Schneider's comment, if the column has blank cells just use COUNTA()

=INDEX(G2:G; COUNT**A**(G2:G))

How to delete a file or folder?

My personal preference is to work with pathlib objects - it offers a more pythonic and less error-prone way to interact with the filesystem, especially if You develop cross-platform code.

In that case, You might use pathlib3x - it offers a backport of the latest (at the date of writing this answer Python 3.10.a0) Python pathlib for Python 3.6 or newer, and a few additional functions like "copy", "copy2", "copytree", "rmtree" etc ...

It also wraps shutil.rmtree:

$> python -m pip install pathlib3x
$> python
>>> import pathlib3x as pathlib

# delete a directory tree
>>> my_dir_to_delete=pathlib.Path('c:/temp/some_dir')
>>> my_dir_to_delete.rmtree(ignore_errors=True)

# delete a file
>>> my_file_to_delete=pathlib.Path('c:/temp/some_file.txt')
>>> my_file_to_delete.unlink(missing_ok=True)

you can find it on github or PyPi


Disclaimer: I'm the author of the pathlib3x library.

MySQL JOIN the most recent row only?

It's a good idea that logging actual data into "customer_data" table. With this data you can select all data from "customer_data" table as you wish.

IDENTITY_INSERT is set to OFF - How to turn it ON?

I believe it needs to be done in a single query batch. Basically, the GO statements are breaking your commands into multiple batches and that is causing the issue. Change it to this:

SET IDENTITY_INSERT tbl_content ON
/* GO */

...insert command...

SET IDENTITY_INSERT tbl_content OFF
GO

How to find the operating system version using JavaScript?

var OSName = "Unknown";
if (window.navigator.userAgent.indexOf("Windows NT 10.0")!= -1) OSName="Windows 10";
if (window.navigator.userAgent.indexOf("Windows NT 6.3") != -1) OSName="Windows 8.1";
if (window.navigator.userAgent.indexOf("Windows NT 6.2") != -1) OSName="Windows 8";
if (window.navigator.userAgent.indexOf("Windows NT 6.1") != -1) OSName="Windows 7";
if (window.navigator.userAgent.indexOf("Windows NT 6.0") != -1) OSName="Windows Vista";
if (window.navigator.userAgent.indexOf("Windows NT 5.1") != -1) OSName="Windows XP";
if (window.navigator.userAgent.indexOf("Windows NT 5.0") != -1) OSName="Windows 2000";
if (window.navigator.userAgent.indexOf("Mac")            != -1) OSName="Mac/iOS";
if (window.navigator.userAgent.indexOf("X11")            != -1) OSName="UNIX";
if (window.navigator.userAgent.indexOf("Linux")          != -1) OSName="Linux";

Use basic authentication with jQuery and Ajax

Or, simply use the headers property introduced in 1.5:

headers: {"Authorization": "Basic xxxx"}

Reference: jQuery Ajax API

MemoryStream - Cannot access a closed Stream

The problem is this block:

using (var sr = new StreamReader(ms))
{
    Console.WriteLine(sr.ReadToEnd());                        
}

When the StreamReader is closed (after leaving the using), it closes it's underlying stream as well, so now the MemoryStream is closed. When the StreamWriter gets closed, it tries to flush everything to the MemoryStream, but it is closed.

You should consider not putting the StreamReader in a using block.

finding the type of an element using jQuery

The following will return true if the element is an input:

$("#elementId").is("input") 

or you can use the following to get the name of the tag:

$("#elementId").get(0).tagName

Python vs Bash - In which kind of tasks each one outruns the other performance-wise?

Performance-wise bash outperforms python in the process startup time.

Here are some measurements from my core i7 laptop running Linux Mint:

Starting process                       Startup time

empty /bin/sh script                   1.7 ms
empty /bin/bash script                 2.8 ms
empty python script                    11.1 ms
python script with a few libs*         110 ms

*Python loaded libs are: os, os.path, json, time, requests, threading, subprocess

This shows a huge difference however bash execution time degrades quickly if it has to do anything sensible since it usually must call external processes.

If you care about performance use bash only for:

  • really simple and frequently called scripts
  • scripts that mainly call other processes
  • when you need minimal friction between manual administrative actions and scripting - fast check a few commands and place them in the file.sh

How to click a href link using Selenium

To click() on the element with text as App Configuration you can use either of the following Locator Strategies:

  • linkText:

    driver.findElement(By.linkText("App Configuration")).click();
    
  • cssSelector:

    driver.findElement(By.cssSelector("a[href='/docs/configuration']")).click();
    
  • xpath:

    driver.findElement(By.xpath("//a[@href='/docs/configuration' and text()='App Configuration']")).click();
    

Ideally, to click() on the element you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:

  • linkText:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.linkText("App Configuration"))).click();
    
  • cssSelector:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("a[href='/docs/configuration']"))).click();
    
  • xpath:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@href='/docs/configuration' and text()='App Configuration']"))).click();
    

References

You can find a couple of relevant detailed discussions in:

What is the difference between class and instance methods?

Take for example a game where lots of cars are spawned.. each belongs to the class CCar. When a car is instantiated, it makes a call to

[CCar registerCar:self]

So the CCar class, can make a list of every CCar instantiated. Let's say the user finishes a level, and wants to remove all cars... you could either: 1- Go through a list of every CCar you created manually, and do whicheverCar.remove(); or 2- Add a removeAllCars method to CCar, which will do that for you when you call [CCar removeAllCars]. I.e. allCars[n].remove();

Or for example, you allow the user to specify a default font size for the whole app, which is loaded and saved at startup. Without the class method, you might have to do something like

fontSize = thisMenu.getParent().fontHandler.getDefaultFontSize();

With the class method, you could get away with [FontHandler getDefaultFontSize].

As for your removeVowels function, you'll find that languages like C# actually have both with certain methods such as toLower or toUpper.

e.g. myString.removeVowels() and String.removeVowels(myString) (in ObjC that would be [String removeVowels:myString]).

In this case the instance likely calls the class method, so both are available. i.e.

public function toLower():String{
  return String.toLower();
}

public static function toLower( String inString):String{
 //do stuff to string..
 return newString;
}

basically, myString.toLower() calls [String toLower:ownValue]

There's no definitive answer, but if you feel like shoving a class method in would improve your code, give it a shot, and bear in mind that a class method will only let you use other class methods/variables.

Map enum in JPA with fixed values?

For versions earlier than JPA 2.1, JPA provides only two ways to deal with enums, by their name or by their ordinal. And the standard JPA doesn't support custom types. So:

  • If you want to do custom type conversions, you'll have to use a provider extension (with Hibernate UserType, EclipseLink Converter, etc). (the second solution). ~or~
  • You'll have to use the @PrePersist and @PostLoad trick (the first solution). ~or~
  • Annotate getter and setter taking and returning the int value ~or~
  • Use an integer attribute at the entity level and perform a translation in getters and setters.

I'll illustrate the latest option (this is a basic implementation, tweak it as required):

@Entity
@Table(name = "AUTHORITY_")
public class Authority implements Serializable {

    public enum Right {
        READ(100), WRITE(200), EDITOR (300);

        private int value;

        Right(int value) { this.value = value; }    

        public int getValue() { return value; }

        public static Right parse(int id) {
            Right right = null; // Default
            for (Right item : Right.values()) {
                if (item.getValue()==id) {
                    right = item;
                    break;
                }
            }
            return right;
        }

    };

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

    @Column(name = "RIGHT_ID")
    private int rightId;

    public Right getRight () {
        return Right.parse(this.rightId);
    }

    public void setRight(Right right) {
        this.rightId = right.getValue();
    }

}

How to align matching values in two columns in Excel, and bring along associated values in other columns

assuming the item numbers are unique, a VLOOKUP should get you the information you need.

first value would be =VLOOKUP(E1,A:B,2,FALSE), and the same type of formula to retrieve the second value would be =VLOOKUP(E1,C:D,2,FALSE). Wrap them in an IFERROR if you want to return anything other than #N/A if there is no corresponding value in the item column(s)

How to customize an end time for a YouTube video?

Youtube doesn't provide any option for an end time, but there alternative sites that provide this, like Tubechop. Otherwise try writing a function that either pauses video/skips to next when your when your video has played its desired duration.

OR: using the Youtube Javascript player API, you could do something like this:

function onPlayerStateChange(evt) {
    if (evt.data == YT.PlayerState.PLAYING && !done) {
        setTimeout(stopVideo, 6000);
        done = true;
    }
}

Youtube API blog

Creating a Menu in Python

It looks like you've just finished step 3. Instead of running a function, you just print out a statement. A function is defined in the following way:

def addstudent():
    print("Student Added.")

then called by writing addstudent().

I would recommend using a while loop for your input. You can define the menu option outside the loop, put the print statement inside the loop, and do while(#valid option is not picked), then put the if statements after the while. Or you can do a while loop and continue the loop if a valid option is not selected.

Additionally, a dictionary is defined in the following way:

my_dict = {key:definition,...}

Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel

try using this one

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-WebRequest -Uri https://apod.nasa.gov/apod/

How to get all privileges back to the root user in MySQL?

If you facing grant permission access denied problem, you can try mysql to fix the problem:

grant all privileges on . to root@'localhost' identified by 'Your password';

grant all privileges on . to root@'IP ADDRESS' identified by 'Your password?';

your can try this on any mysql user, its working.

Use below command to login mysql with iP address.

mysql -h 10.0.0.23 -u root -p

How do I increase the RAM and set up host-only networking in Vagrant?

To increase the memory or CPU count when using Vagrant 2, add this to your Vagrantfile

Vagrant.configure("2") do |config|
    # usual vagrant config here

    config.vm.provider "virtualbox" do |v|
        v.memory = 1024
        v.cpus = 2
    end
end

Printing newlines with print() in R

An alternative to cat() is writeLines():

> writeLines("File not supplied.\nUsage: ./program F=filename")
File not supplied.
Usage: ./program F=filename
>

An advantage is that you don't have to remember to append a "\n" to the string passed to cat() to get a newline after your message. E.g. compare the above to the same cat() output:

> cat("File not supplied.\nUsage: ./program F=filename")
File not supplied.
Usage: ./program F=filename>

and

> cat("File not supplied.\nUsage: ./program F=filename","\n")
File not supplied.
Usage: ./program F=filename
>

The reason print() doesn't do what you want is that print() shows you a version of the object from the R level - in this case it is a character string. You need to use other functions like cat() and writeLines() to display the string. I say "a version" because precision may be reduced in printed numerics, and the printed object may be augmented with extra information, for example.

Make install, but not to default directories?

It could be dependent upon what is supported by the module you are trying to compile. If your makefile is generated by using autotools, use:

--prefix=<myinstalldir>

when running the ./configure

some packages allow you to also override when running:

make prefix=<myinstalldir>

however, if your not using ./configure, only way to know for sure is to open up the makefile and check. It should be one of the first few variables at the top.

Possible to perform cross-database queries with PostgreSQL?

In case someone needs a more involved example on how to do cross-database queries, here's an example that cleans up the databasechangeloglock table on every database that has it:

CREATE EXTENSION IF NOT EXISTS dblink;

DO 
$$
DECLARE database_name TEXT;
DECLARE conn_template TEXT;
DECLARE conn_string TEXT;
DECLARE table_exists Boolean;
BEGIN
    conn_template = 'user=myuser password=mypass dbname=';

    FOR database_name IN
        SELECT datname FROM pg_database
        WHERE datistemplate = false
    LOOP
        conn_string = conn_template || database_name;

        table_exists = (select table_exists_ from dblink(conn_string, '(select Count(*) > 0 from information_schema.tables where table_name = ''databasechangeloglock'')') as (table_exists_ Boolean));
        IF table_exists THEN
            perform dblink_exec(conn_string, 'delete from databasechangeloglock');
        END IF;     
    END LOOP;

END
$$

The system cannot find the file specified in java

Try to list all files' names in the directory by calling:

File file = new File(".");
for(String fileNames : file.list()) System.out.println(fileNames);

and see if you will find your files in the list.

Cannot resolve symbol 'AppCompatActivity'

This is the lifesaver code I found somewhere(sorry don't remember the origin). Add it to build.gradle (Module:app). You can replace the version to the relevant.

configurations.all {

    resolutionStrategy.eachDependency { DependencyResolveDetails details -
        def requested = details.requested

 if (requested.group == 'com.android.support') {

            if (!requested.name.startsWith("multidex")) {
                details.useVersion '27.1.1'
            }
        } else if (requested.group == "com.google.android.gms") {
            details.useVersion '15.0.0'
        } else if (requested.group == "com.google.firebase") {
            details.useVersion '15.0.0'
        }
    }
}

Remove substring from the string

If I'm interpreting right, this question seems to ask for something like a minus (-) operation between strings, i.e. the opposite of the built-in plus (+) operation (concatenation).

Unlike the previous answers, I'm trying to define such an operation that must obey the property:

IF c = a + b THEN c - a = b AND c - b = a

We need only three built-in Ruby methods to achieve this:

'abracadabra'.partition('abra').values_at(0,2).join == 'cadabra'.

I won't explain how it works because it can be easily understood running one method at a time.

Here is a proof of concept code:

# minus_string.rb
class String
  def -(str)
    partition(str).values_at(0,2).join
  end
end

# Add the following code and issue 'ruby minus_string.rb' in the console to test
require 'minitest/autorun'

class MinusString_Test < MiniTest::Test

  A,B,C='abra','cadabra','abracadabra'

  def test_C_eq_A_plus_B
    assert C == A + B
  end

  def test_C_minus_A_eq_B
    assert C - A == B
  end

  def test_C_minus_B_eq_A
    assert C - B == A
  end

end

One last word of advice if you're using a recent Ruby version (>= 2.0): use Refinements instead of monkey-patching String like in the previous example.

It is as easy as:

module MinusString
  refine String do
    def -(str)
      partition(str).values_at(0,2).join
    end
  end
end

and add using MinusString before the blocks where you need it.

How to concatenate variables into SQL strings

You could make use of Prepared Stements like this.

set @query = concat( "select name from " );
set @query = concat( "table_name"," [where condition] " );

prepare stmt from @like_q;
execute stmt;

How to reverse an animation on mouse out after hover

creating a reversed animation is kinda an overkill to a simple problem, what u need is

animation-direction: reverse

however this wont work on its own because animation spec is so dump that they forgot to add a way to restart the animation so here is how you do it with the help of js

_x000D_
_x000D_
let item = document.querySelector('.item')_x000D_
_x000D_
// play normal_x000D_
item.addEventListener('mouseover', () => {_x000D_
  item.classList.add('active')_x000D_
})_x000D_
_x000D_
// play in reverse_x000D_
item.addEventListener('mouseout', () => {_x000D_
  item.style.opacity = 0 // avoid showing the init style while switching the 'active' class_x000D_
_x000D_
  item.classList.add('in-active')_x000D_
  item.classList.remove('active')_x000D_
_x000D_
  // force dom update_x000D_
  setTimeout(() => {_x000D_
    item.classList.add('active')_x000D_
    item.style.opacity = ''_x000D_
  }, 5)_x000D_
_x000D_
  item.addEventListener('animationend', onanimationend)_x000D_
})_x000D_
_x000D_
function onanimationend() {_x000D_
  item.classList.remove('active', 'in-active')_x000D_
  item.removeEventListener('animationend', onanimationend)_x000D_
}
_x000D_
@keyframes spin {_x000D_
  0% {_x000D_
    transform: rotateY(0deg);_x000D_
  }_x000D_
  100% {_x000D_
    transform: rotateY(180deg);_x000D_
  }_x000D_
}_x000D_
_x000D_
div {_x000D_
  background: black;_x000D_
  padding: 1rem;_x000D_
  display: inline-block;_x000D_
}_x000D_
_x000D_
.item {_x000D_
  /* because span cant be animated */_x000D_
  display: block;_x000D_
  color: yellow;_x000D_
  font-size: 2rem;_x000D_
}_x000D_
_x000D_
.item.active {_x000D_
  animation: spin 1s forwards;_x000D_
  animation-timing-function: ease-in-out;_x000D_
}_x000D_
_x000D_
.item.in-active {_x000D_
  animation-direction: reverse;_x000D_
}
_x000D_
<div>_x000D_
  <span class="item">ABC</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Working with dictionaries/lists in R

Shorter variation of Dirk's answer:

# Create a Color Palette Dictionary 
> color <- c('navy.blue', 'gold', 'dark.gray')
> hex <- c('#336A91', '#F3C117', '#7F7F7F')

> # Create List
> color_palette <- as.list(hex)
> # Name List Items
> names(color_palette) <- color
> 
> color_palette
$navy.blue
[1] "#336A91"

$gold
[1] "#F3C117"

$dark.gray
[1] "#7F7F7F"

jQuery UI accordion that keeps multiple sections open?

Even simpler, have it labeled in each li tag's class attribute and have jquery to loop through each li to initialize the accordion.

How can I post an array of string to ASP.NET MVC Controller without a form?

I modified my response to include the code for a test app I did.

Update: I have updated the jQuery to set the 'traditional' setting to true so this will work again (per @DustinDavis' answer).

First the javascript:

function test()
{
    var stringArray = new Array();
    stringArray[0] = "item1";
    stringArray[1] = "item2";
    stringArray[2] = "item3";
    var postData = { values: stringArray };

    $.ajax({
        type: "POST",
        url: "/Home/SaveList",
        data: postData,
        success: function(data){
            alert(data.Result);
        },
        dataType: "json",
        traditional: true
    });
}

And here's the code in my controller class:

public JsonResult SaveList(List<String> values)
{
    return Json(new { Result = String.Format("Fist item in list: '{0}'", values[0]) });
}

When I call that javascript function, I get an alert saying "First item in list: 'item1'". Hope this helps!

CSS Font "Helvetica Neue"

You can use http://www.fontsquirrel.com/fontface/generator to encode any font for websites. It'll generate the code to include the font.

I don't really use it for fonts over 30px. They look much better as an image (because images are anti-aliased, and some browsers don't anti-alias fonts in the browser).

See: http://www.truetype-typography.com/ttalias.htm

Hope that helps...

alternative to "!is.null()" in R

You may be better off working out what value type your function or code accepts, and asking for that:

if (is.integer(aVariable))
{
  do whatever
}

This may be an improvement over isnull, because it provides type checking. On the other hand, it may reduce the genericity of your code.

Alternatively, just make the function you want:

is.defined = function(x)!is.null(x)

jQuery looping .each() JSON key/value not working

Since you have an object, not a jQuery wrapper, you need to use a different variant of $.each()

$.each(json, function (key, data) {
    console.log(key)
    $.each(data, function (index, data) {
        console.log('index', data)
    })
})

Demo: Fiddle

Difference between "include" and "require" in php

You find the differences explained in the detailed PHP manual on the page of require:

require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue.

See @efritz's answer for an example

Oracle : how to subtract two dates and get minutes of the result

I think you can adapt the function to substract the two timestamps:

return  EXTRACT(MINUTE FROM 
  TO_TIMESTAMP(to_char(p_date1,'DD-MON-YYYY HH:MI:SS'),'DD-MON-YYYY HH24:MI:SS')
-
  TO_TIMESTAMP(to_char(p_date2,'DD-MON-YYYY HH:MI:SS'),'DD-MON-YYYY HH24:MI:SS')
);

I think you could simplify it by just using CAST(p_date as TIMESTAMP).

return  EXTRACT(MINUTE FROM cast(p_date1 as TIMESTAMP) - cast(p_date2 as TIMESTAMP));

Remember dates and timestamps are big ugly numbers inside Oracle, not what we see in the screen; we don't need to tell him how to read them. Also remember timestamps can have a timezone defined; not in this case.

how to convert integer to string?

NSArray *myArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3]];

Update for new Objective-C syntax:

NSArray *myArray = @[@1, @2, @3];

Those two declarations are identical from the compiler's perspective.

if you're just wanting to use an integer in a string for putting into a textbox or something:

int myInteger = 5;
NSString* myNewString = [NSString stringWithFormat:@"%i", myInteger];

jQuery Combobox/select autocomplete?

jQuery 1.8.1 has an example of this under autocomplete. It's very easy to implement.

JavaScript equivalent to printf/String.Format

The PHPJS project has written JavaScript implementations for many of PHP's functions. Since PHP's sprintf() function is basically the same as C's printf(), their JavaScript implementation of it should satisfy your needs.

How do I get today's date in C# in mm/dd/yyyy format?

string today = DateTime.Today.ToString("M/d");

Passing parameters in rails redirect_to

You can pass arbitrary objects to the template with the flash parameter.

 redirect_to :back, flash: {new_solution_errors: solution.errors}

And then access them in the template via the hash.

<% flash[:new_solution_errors].each do |err| %>

C - freeing structs

free is not enough, free just marks the memory as unused, the struct data will be there until overwriting. For safety, set the pointer to NULL after free.

Ex:

if (testPerson) {
    free(testPerson);
    testPerson = NULL;
}

struct is similar like an array, it is a block of memory. You can access to struct member via its offset. The first struct's member is placed at offset 0 so the address of first struct's member is same as the address of struct.

How to get image width and height in OpenCV?

You can use rows and cols:

cout << "Width : " << src.cols << endl;
cout << "Height: " << src.rows << endl;

or size():

cout << "Width : " << src.size().width << endl;
cout << "Height: " << src.size().height << endl;

Should I write script in the body or the head of the html?

Head, or before closure of body tag. When DOM loads JS is then executed, that is exactly what jQuery document.ready does.

php random x digit number

The following code generates a 4 digits random number:

echo sprintf( "%04d", rand(0,9999));

How to iterate through a String

Using Guava (r07) you can do this:

for(char c : Lists.charactersOf(someString)) { ... }

This has the convenience of using foreach while not copying the string to a new array. Lists.charactersOf returns a view of the string as a List.

Posting a File and Associated Data to a RESTful WebService preferably as JSON

I know that this thread is quite old, however, I am missing here one option. If you have metadata (in any format) that you want to send along with the data to upload, you can make a single multipart/related request.

The Multipart/Related media type is intended for compound objects consisting of several inter-related body parts.

You can check RFC 2387 specification for more in-depth details.

Basically each part of such a request can have content with different type and all parts are somehow related (e.g. an image and it metadata). The parts are identified by a boundary string, and the final boundary string is followed by two hyphens.

Example:

POST /upload HTTP/1.1
Host: www.hostname.com
Content-Type: multipart/related; boundary=xyz
Content-Length: [actual-content-length]

--xyz
Content-Type: application/json; charset=UTF-8

{
    "name": "Sample image",
    "desc": "...",
    ...
}

--xyz
Content-Type: image/jpeg

[image data]
[image data]
[image data]
...
--foo_bar_baz--

Get a Div Value in JQuery

if you div looks like this:

<div id="someId">Some Value</div>

you could retrieve it with jquery like this:

$('#someId').text()

Convert timestamp to string

try this

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String string  = dateFormat.format(new Date());
System.out.println(string);

you can create any format see this

jQuery: Scroll down page a set increment (in pixels) on click?

var y = $(window).scrollTop();  //your current y position on the page
$(window).scrollTop(y+150);

Deserializing JSON Object Array with Json.net

You can create a new model to Deserialize your Json CustomerJson:

public class CustomerJson
{
    [JsonProperty("customer")]
    public Customer Customer { get; set; }
}

public class Customer
{
    [JsonProperty("first_name")]
    public string Firstname { get; set; }

    [JsonProperty("last_name")]
    public string Lastname { get; set; }

    ...
}

And you can deserialize your json easily :

JsonConvert.DeserializeObject<List<CustomerJson>>(json);

Hope it helps !

Documentation: Serializing and Deserializing JSON

How to make a variable accessible outside a function?

$.getJSON is an asynchronous request, meaning the code will continue to run even though the request is not yet done. You should trigger the second request when the first one is done, one of the choices you seen already in ComFreek's answer.

Alternatively you could use jQuery's $.when/.then(), similar to this:

var input = "netuetamundis";  var sID;  $(document).ready(function () {     $.when($.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/" + input + "?api_key=API_KEY_HERE", function () {         obj = name;         sID = obj.id;         console.log(sID);     })).then(function () {         $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function (stats) {             console.log(stats);         });     }); }); 

This would be more open for future modification and separates out the responsibility for the first call to know about the second call.

The first call can simply complete and do it's own thing not having to be aware of any other logic you may want to add, leaving the coupling of the logic separated.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

Exception clearly indicates the problem.

CompteDAOHib: No default constructor found

For spring to instantiate your bean, you need to provide a empty constructor for your class CompteDAOHib.

omp parallel vs. omp parallel for

I am seeing starkly different runtimes when I take a for loop in g++ 4.7.0 and using

std::vector<double> x;
std::vector<double> y;
std::vector<double> prod;

for (int i = 0; i < 5000000; i++)
{
   double r1 = ((double)rand() / double(RAND_MAX)) * 5;
   double r2 = ((double)rand() / double(RAND_MAX)) * 5;
   x.push_back(r1);
   y.push_back(r2);
}

int sz = x.size();

#pragma omp parallel for

for (int i = 0; i< sz; i++)
   prod[i] = x[i] * y[i];

the serial code (no openmp ) runs in 79 ms. the "parallel for" code runs in 29 ms. If I omit the for and use #pragma omp parallel, the runtime shoots up to 179ms, which is slower than serial code. (the machine has hw concurrency of 8)

the code links to libgomp

Style child element when hover on parent

Yes, you can do this use this below code it may help you.

_x000D_
_x000D_
.parentDiv{_x000D_
margin : 25px;_x000D_
_x000D_
}_x000D_
.parentDiv span{_x000D_
  display : block;_x000D_
  padding : 10px;_x000D_
  text-align : center;_x000D_
  border: 5px solid #000;_x000D_
  margin : 5px;_x000D_
}_x000D_
_x000D_
.parentDiv div{_x000D_
padding:30px;_x000D_
border: 10px solid green;_x000D_
display : inline-block;_x000D_
align : cente;_x000D_
}_x000D_
_x000D_
.parentDiv:hover{_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
.parentDiv:hover .childDiv1{_x000D_
border: 10px solid red;_x000D_
}_x000D_
_x000D_
.parentDiv:hover .childDiv2{_x000D_
border: 10px solid yellow;_x000D_
} _x000D_
.parentDiv:hover .childDiv3{_x000D_
border: 10px solid orange;_x000D_
}
_x000D_
<div class="parentDiv">_x000D_
<span>Hover me to change Child Div colors</span>_x000D_
  <div class="childDiv1">_x000D_
    First Div Child_x000D_
  </div>_x000D_
  <div class="childDiv2">_x000D_
    Second Div Child_x000D_
  </div>_x000D_
  <div class="childDiv3">_x000D_
    Third Div Child_x000D_
  </div>_x000D_
  <div class="childDiv4">_x000D_
    Fourth Div Child_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to parse a CSV file in Bash?

You need to use IFS instead of -d:

while IFS=, read -r col1 col2
do
    echo "I got:$col1|$col2"
done < myfile.csv

Note that for general purpose CSV parsing you should use a specialized tool which can handle quoted fields with internal commas, among other issues that Bash can't handle by itself. Examples of such tools are cvstool and csvkit.

custom facebook share button

You can use facebook javascript sdk. First add FB Js SDK to your code (please refer to https://developers.facebook.com/docs/javascript)

window.fbAsyncInit = function(){
FB.init({
    appId: 'xxxxx', status: true, cookie: true, xfbml: true }); 
};
(function(d, debug){var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
    if(d.getElementById(id)) {return;}
    js = d.createElement('script'); js.id = id; 
    js.async = true;js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js";
    ref.parentNode.insertBefore(js, ref);}(document, /*debug*/ false));
function postToFeed(title, desc, url, image){
var obj = {method: 'feed',link: url, picture: 'http://www.url.com/images/'+image,name: title,description: desc};
function callback(response){}
FB.ui(obj, callback);
}

So when you want to share something

<a href="someurl.com/some-article" data-image="article-1.jpg" data-title="Article Title" data-desc="Some description for this article" class="btnShare">Share</a>

And finally JS to handle click:

$('.btnShare').click(function(){
elem = $(this);
postToFeed(elem.data('title'), elem.data('desc'), elem.prop('href'), elem.data('image'));

return false;
});

Import an existing git project into GitLab?

git clone --mirror [email protected]:username/repo-name.git

git remote add gitlab ssh://[email protected]/username/repo.git

git push -f --tags gitlab refs/heads/*:refs/heads/*

It is better to do it over ssh, the https might won't work

How can I remove a key from a Python dictionary?

You can use a dictionary comprehension to create a new dictionary with that key removed:

>>> my_dict = {k: v for k, v in my_dict.items() if k != 'key'}

You can delete by conditions. No error if key doesn't exist.

Understanding `scale` in R

It provides nothing else but a standardization of the data. The values it creates are known under several different names, one of them being z-scores ("Z" because the normal distribution is also known as the "Z distribution").

More can be found here:

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

How to parse XML using jQuery?

I assume you are loading the XML from an external file. With $.ajax(), it's quite simple actually:

$.ajax({
    url: 'xmlfile.xml',
    dataType: 'xml',
    success: function(data){
        // Extract relevant data from XML
        var xml_node = $('Pages',data);
        console.log( xml_node.find('Page[Name="test"] > controls > test').text() );
    },
    error: function(data){
        console.log('Error loading XML data');
    }
});

Also, you should be consistent about the XML node naming. You have both lowercase and capitalized node names (<Page> versus <page>) which can be confusing when you try to use XML tree selectors.

CSS: Set a background color which is 50% of the width of the window

I have used :after and it is working in all major browsers. please check the link. just need to careful for the z-index as after is having position absolute.

<div class="splitBg">
    <div style="max-width:960px; margin:0 auto; padding:0 15px; box-sizing:border-box;">
        <div style="float:left; width:50%; position:relative; z-index:10;">
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.
        </div>
        <div style="float:left; width:50%; position:relative; z-index:10;">
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, 
        </div>
        <div style="clear:both;"></div>
    </div>
</div>`
css

    .splitBg{
        background-color:#666;
        position:relative;
        overflow:hidden;
        }
    .splitBg:after{
        width:50%;
        position:absolute;
        right:0;
        top:0;
        content:"";
        display:block;
        height:100%;
        background-color:#06F;
        z-index:1;
        }

fiddle link

Django set default form values

Other solution: Set initial after creating the form:

form.fields['tank'].initial = 123

bootstrap responsive table content wrapping

just simply use as below and it will word wrap any long text within a table . No need to anything else

<td style="word-wrap: break-word;min-width: 160px;max-width: 160px;">long long comments</td>

How can I create a dropdown menu from a List in Tkinter?

To create a "drop down menu" you can use OptionMenu in tkinter

Example of a basic OptionMenu:

from Tkinter import *

master = Tk()

variable = StringVar(master)
variable.set("one") # default value

w = OptionMenu(master, variable, "one", "two", "three")
w.pack()

mainloop()

More information (including the script above) can be found here.


Creating an OptionMenu of the months from a list would be as simple as:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

mainloop()

In order to retrieve the value the user has selected you can simply use a .get() on the variable that we assigned to the widget, in the below case this is variable:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

def ok():
    print ("value is:" + variable.get())

button = Button(master, text="OK", command=ok)
button.pack()

mainloop()

I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.

Make Div overlay ENTIRE page (not just viewport)?

First of all, I think you've misunderstood what the viewport is. The viewport is the area a browser uses to render web pages, and you cannot in any way build your web sites to override this area in any way.

Secondly, it seems that the reason that your overlay-div won't cover the entire viewport is because you have to remove all margins on BODY and HTML.

Try adding this at the top of your stylesheet - it resets all margins and paddings on all elements. Makes further development easier:

* { margin: 0; padding: 0; }

Edit: I just understood your question better. Position: fixed; will probably work out for you, as Jonathan Sampson have written.

How to get response from S3 getObject in Node.js?

Alternatively you could use minio-js client library get-object.js

var Minio = require('minio')

var s3Client = new Minio({
  endPoint: 's3.amazonaws.com',
  accessKey: 'YOUR-ACCESSKEYID',
  secretKey: 'YOUR-SECRETACCESSKEY'
})

var size = 0
// Get a full object.
s3Client.getObject('my-bucketname', 'my-objectname', function(e, dataStream) {
  if (e) {
    return console.log(e)
  }
  dataStream.on('data', function(chunk) {
    size += chunk.length
  })
  dataStream.on('end', function() {
    console.log("End. Total size = " + size)
  })
  dataStream.on('error', function(e) {
    console.log(e)
  })
})

Disclaimer: I work for Minio Its open source, S3 compatible object storage written in golang with client libraries available in Java, Python, Js, golang.

Get MIME type from filename extension

To make the post more comprehensive, for .NET Core devs there is FileExtensionContentTypeProvider class, which covers the official MIME content types.

It works behind the scene - sets ContentType in the Http Response headers based on the filename extension.

In case you need special MIME types, see example on customising the MIME types:

public void Configure(IApplicationBuilder app)
{
    // Set up custom content types -associating file extension to MIME type
    var provider = new FileExtensionContentTypeProvider();
    // Add new mappings
    provider.Mappings[".myapp"] = "application/x-msdownload";
    provider.Mappings[".htm3"] = "text/html";
    provider.Mappings[".image"] = "image/png";
    // Replace an existing mapping
    provider.Mappings[".rtf"] = "application/x-msdownload";
    // Remove MP4 videos.
    provider.Mappings.Remove(".mp4");

    app.UseStaticFiles(new StaticFileOptions()
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", "images")),
        RequestPath = new PathString("/MyImages"),
        ContentTypeProvider = provider
    });

    app.UseDirectoryBrowser(new DirectoryBrowserOptions()
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", "images")),
        RequestPath = new PathString("/MyImages")
    });
}

How can I enable Assembly binding logging?

Instead of Creating New Application Pool,You can go to your Existing application Pool->Right click Advance setting->Enable 32-bit Application-----Set to TRUE

Why is a ConcurrentModificationException thrown and how to debug it

Note that the selected answer cannot be applied to your context directly before some modification, if you are trying to remove some entries from the map while iterating the map just like me.

I just give my working example here for newbies to save their time:

HashMap<Character,Integer> map=new HashMap();
//adding some entries to the map
...
int threshold;
//initialize the threshold
...
Iterator it=map.entrySet().iterator();
while(it.hasNext()){
    Map.Entry<Character,Integer> item=(Map.Entry<Character,Integer>)it.next();
    //it.remove() will delete the item from the map
    if((Integer)item.getValue()<threshold){
        it.remove();
    }

ORA-12154 could not resolve the connect identifier specified

Please let me repeat what Stephen said since I missed it the first time myself. The TNS_ADMIN environment variable and ORACLE_HOME is set to C:\instantclient_11_2 and th tnsnames.ora file is in there. Found the answer on this link.

Removing carriage return and new-line from the end of a string in c#

If there's always a single CRLF, then:

myString = myString.Substring(0, myString.Length - 2);

If it may or may not have it, then:

Regex re = new Regex("\r\n$");
re.Replace(myString, "");

Both of these (by design), will remove at most a single CRLF. Cache the regex for performance.

How can I count text lines inside an DOM element? Can I?

Clone the container object and write 2 letters and calculate the height. This return the real height with all style applied, line height, etc. Now, calculate the height object / the size of a letter. In Jquery, the height excelude the padding, margin and border, it is great to calculate the real height of each line:

other = obj.clone();
other.html('a<br>b').hide().appendTo('body');
size = other.height() / 2;
other.remove();
lines = obj.height() /  size;

If you use a rare font with different height of each letter, this does not works. But works with all normal fonts, like Arial, mono, comics, Verdana, etc. Test with your font.

Example:

<div id="content" style="width: 100px">hello how are you? hello how are you? hello how are you?</div>
<script type="text/javascript">
$(document).ready(function(){

  calculate = function(obj){
    other = obj.clone();
    other.html('a<br>b').hide().appendTo('body');
    size = other.height() / 2;
    other.remove();
    return obj.height() /  size;
  }

  n = calculate($('#content'));
  alert(n + ' lines');
});
</script>

Result: 6 Lines

Works in all browser without rare functions out of standards.

Check: https://jsfiddle.net/gzceamtr/

How do you remove a Cookie in a Java Servlet

The proper way to remove a cookie is to set the max age to 0 and add the cookie back to the HttpServletResponse object.

Most people don't realize or forget to add the cookie back onto the response object. By doing that it will expire and remove the cookie immediately.

...retrieve cookie from HttpServletRequest
cookie.setMaxAge(0);
response.addCookie(cookie);

How to return JSON with ASP.NET & jQuery

This structure works for me - I used it in a small tasks management application.

The controller:

public JsonResult taskCount(string fDate)
{
  // do some stuff based on the date

  // totalTasks is a count of the things I need to do today
  // tasksDone is a count of the tasks I actually did
  // pcDone is the percentage of tasks done

  return Json(new {
    totalTasks = totalTasks,
    tasksDone = tasksDone,
    percentDone = pcDone
  });
}

In the AJAX call I access the data like this:

.done(function (data) {
  // data.totalTasks
  // data.tasksDone
  // data.percentDone
});

Prevent a webpage from navigating away using JavaScript

The equivalent to the accepted answer in jQuery 1.11:

$(window).on("beforeunload", function () {
    return "Please don't leave me!";
});

JSFiddle example

altCognito's answer used the unload event, which happens too late for JavaScript to abort the navigation.

Truncate Decimal number not Round Off

A function to truncate an arbitrary number of decimals:

public decimal Truncate(decimal number, int digits)
{
  decimal stepper = (decimal)(Math.Pow(10.0, (double)digits));
  int temp = (int)(stepper * number);
  return (decimal)temp / stepper;
}

SQL Insert Query Using C#

Try

String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id,@username, @password, @email)";
using(SqlConnection connection = new SqlConnection(connectionString))
using(SqlCommand command = new SqlCommand(query, connection))
{
    //a shorter syntax to adding parameters
    command.Parameters.Add("@id", SqlDbType.NChar).Value = "abc";

    command.Parameters.Add("@username", SqlDbType.NChar).Value = "abc";

    //a longer syntax for adding parameters
    command.Parameters.Add("@password", SqlDbType.NChar).Value = "abc";

    command.Parameters.Add("@email", SqlDbType.NChar).Value = "abc";

    //make sure you open and close(after executing) the connection
    connection.Open();
    command.ExecuteNonQuery();
}

Why does Node.js' fs.readFile() return a buffer instead of string?

Async:

fs.readFile('test.txt', 'utf8', callback);

Sync:

var content = fs.readFileSync('test.txt', 'utf8');

What is the difference between private and protected members of C++ classes?

private members are only accessible from within the class, protected members are accessible in the class and derived classes. It's a feature of inheritance in OO languages.

You can have private, protected and public inheritance in C++, which will determine what derived classes can access in the inheritance hierarchy. C# for example only has public inheritance.

How to convert a command-line argument to int?

Since this answer was somehow accepted and thus will appear at the top, although it's not the best, I've improved it based on the other answers and the comments.

The C way; simplest, but will treat any invalid number as 0:

#include <cstdlib>

int x = atoi(argv[1]);

The C way with input checking:

#include <cstdlib>

errno = 0;
char *endptr;
long int x = strtol(argv[1], &endptr, 10);
if (endptr == argv[1]) {
  std::cerr << "Invalid number: " << argv[1] << '\n';
} else if (*endptr) {
  std::cerr << "Trailing characters after number: " << argv[1] << '\n';
} else if (errno == ERANGE) {
  std::cerr << "Number out of range: " << argv[1] << '\n';
}

The C++ iostreams way with input checking:

#include <sstream>

std::istringstream ss(argv[1]);
int x;
if (!(ss >> x)) {
  std::cerr << "Invalid number: " << argv[1] << '\n';
} else if (!ss.eof()) {
  std::cerr << "Trailing characters after number: " << argv[1] << '\n';
}

Alternative C++ way since C++11:

#include <stdexcept>
#include <string>

std::string arg = argv[1];
try {
  std::size_t pos;
  int x = std::stoi(arg, &pos);
  if (pos < arg.size()) {
    std::cerr << "Trailing characters after number: " << arg << '\n';
  }
} catch (std::invalid_argument const &ex) {
  std::cerr << "Invalid number: " << arg << '\n';
} catch (std::out_of_range const &ex) {
  std::cerr << "Number out of range: " << arg << '\n';
}

All four variants assume that argc >= 2. All accept leading whitespace; check isspace(argv[1][0]) if you don't want that. All except atoi reject trailing whitespace.

How to loop over grouped Pandas dataframe?

df.groupby('l_customer_id_i').agg(lambda x: ','.join(x)) does already return a dataframe, so you cannot loop over the groups anymore.

In general:

  • df.groupby(...) returns a GroupBy object (a DataFrameGroupBy or SeriesGroupBy), and with this, you can iterate through the groups (as explained in the docs here). You can do something like:

    grouped = df.groupby('A')
    
    for name, group in grouped:
        ...
    
  • When you apply a function on the groupby, in your example df.groupby(...).agg(...) (but this can also be transform, apply, mean, ...), you combine the result of applying the function to the different groups together in one dataframe (the apply and combine step of the 'split-apply-combine' paradigm of groupby). So the result of this will always be again a DataFrame (or a Series depending on the applied function).

How can I get new selection in "select" in Angular 2?

In Angular 5 I did with the following way. get the object $event.value instead of $event.target.value

<mat-form-field color="warn">
   <mat-select (ngModelChange)="onChangeTown($event)" class="form-width" formControlName="branch" [(ngModel)]="branch" placeholder="Enter branch">
     <mat-option *ngFor="let branch of branchs" [value]="branch.value">
                  {{ branch.name }}
     </mat-option>
   </mat-select>
</mat-form-field>

onChangeTown(event): void {
  const selectedTown = event;
  console.log('selectedTown: ', selectedTown);
}

Checking if a folder exists using a .bat file

For a file:

if exist yourfilename (
  echo Yes 
) else (
  echo No
)

Replace yourfilename with the name of your file.

For a directory:

if exist yourfoldername\ (
  echo Yes 
) else (
  echo No
)

Replace yourfoldername with the name of your folder.

A trailing backslash (\) seems to be enough to distinguish between directories and ordinary files.

Creating a div element in jQuery

$(HTMLelement) can success it. If you want an epmty div use it as $('<div></div>');. Also you can set the other elements by the same method. If you want to change inner HTML after created you can use html() method. For get outerHTML as string you can use is like this :

var element = $('<div/>');
var innerHTML = element.html(); // if you want set new HTML use it like this element.html('<b>new HTML</b>');
var outerHTML = element[0].outerHTML;

Convert seconds to hh:mm:ss in Python

Besides the fact that Python has built in support for dates and times (see bigmattyh's response), finding minutes or hours from seconds is easy:

minutes = seconds / 60
hours = minutes / 60

Now, when you want to display minutes or seconds, MOD them by 60 so that they will not be larger than 59

How do I read a string entered by the user in C?

I think the best and safest way to read strings entered by the user is using getline()

Here's an example how to do this:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
    char *buffer = NULL;
    int read;
    unsigned int len;
    read = getline(&buffer, &len, stdin);
    if (-1 != read)
        puts(buffer);
    else
        printf("No line read...\n");

    printf("Size read: %d\n Len: %d\n", read, len);
    free(buffer);
    return 0;
}