Programs & Examples On #Rubyosa

Best way to store data locally in .NET (C#)

In my experience in most cases JSON in a file is enough (mostly you need to store an array or an object or just a single number or string). I rarely need SQLite (which needs more time for setting it up and using it, most of the times it's overkill).

Spring CORS No 'Access-Control-Allow-Origin' header is present

I also had messages like No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.

I had configured cors properly, but what was missing in webflux in RouterFuncion was accept and contenttype headers APPLICATION_JSON like in this piece of code:

@Bean
RouterFunction<ServerResponse> routes() {
    return route(POST("/create")
                              .and(accept(APPLICATION_JSON))
                              .and(contentType(APPLICATION_JSON)), serverRequest -> create(serverRequest);
}

Python: Continuing to next iteration in outer loop

for i in ...:
    for j in ...:
        for k in ...:
            if something:
                # continue loop i

In a general case, when you have multiple levels of looping and break does not work for you (because you want to continue one of the upper loops, not the one right above the current one), you can do one of the following

Refactor the loops you want to escape from into a function

def inner():
    for j in ...:
        for k in ...:
            if something:
                return


for i in ...:
    inner()

The disadvantage is that you may need to pass to that new function some variables, which were previously in scope. You can either just pass them as parameters, make them instance variables on an object (create a new object just for this function, if it makes sense), or global variables, singletons, whatever (ehm, ehm).

Or you can define inner as a nested function and let it just capture what it needs (may be slower?)

for i in ...:
    def inner():
        for j in ...:
            for k in ...:
                if something:
                    return
    inner()

Use exceptions

Philosophically, this is what exceptions are for, breaking the program flow through the structured programming building blocks (if, for, while) when necessary.

The advantage is that you don't have to break the single piece of code into multiple parts. This is good if it is some kind of computation that you are designing while writing it in Python. Introducing abstractions at this early point may slow you down.

Bad thing with this approach is that interpreter/compiler authors usually assume that exceptions are exceptional and optimize for them accordingly.

class ContinueI(Exception):
    pass


continue_i = ContinueI()

for i in ...:
    try:
        for j in ...:
            for k in ...:
                if something:
                    raise continue_i
    except ContinueI:
        continue

Create a special exception class for this, so that you don't risk accidentally silencing some other exception.

Something else entirely

I am sure there are still other solutions.

How do I execute code AFTER a form has loaded?

You could use the "Shown" event: MSDN - Form.Shown

"The Shown event is only raised the first time a form is displayed; subsequently minimizing, maximizing, restoring, hiding, showing, or invalidating and repainting will not raise this event."

How can I check if a string represents an int, without using try/except?

Greg Hewgill's approach was missing a few components: the leading "^" to only match the start of the string, and compiling the re beforehand. But this approach will allow you to avoid a try: exept:

import re
INT_RE = re.compile(r"^[-]?\d+$")
def RepresentsInt(s):
    return INT_RE.match(str(s)) is not None

I would be interested why you are trying to avoid try: except?

How do I correctly clean up a Python object?

atexit.register is the standard way as has already been mentioned in ostrakach's answer.

However, it must be noted that the order in which objects might get deleted cannot be relied upon as shown in example below.

import atexit

class A(object):

    def __init__(self, val):
        self.val = val
        atexit.register(self.hello)

    def hello(self):
        print(self.val)


def hello2():
    a = A(10)

hello2()    
a = A(20)

Here, order seems legitimate in terms of reverse of the order in which objects were created as program gives output as :

20
10

However when, in a larger program, python's garbage collection kicks in object which is out of it's lifetime would get destructed first.

How do you implement a class in C?

If you only want one class, use an array of structs as the "objects" data and pass pointers to them to the "member" functions. You can use typedef struct _whatever Whatever before declaring struct _whatever to hide the implementation from client code. There's no difference between such an "object" and the C standard library FILE object.

If you want more than one class with inheritance and virtual functions, then it's common to have pointers to the functions as members of the struct, or a shared pointer to a table of virtual functions. The GObject library uses both this and the typedef trick, and is widely used.

There's also a book on techniques for this available online - Object Oriented Programming with ANSI C.

How to get numeric value from a prompt box?

parseInt() or parseFloat() are functions in JavaScript which can help you convert the values into integers or floats respectively.

Syntax:

 parseInt(string, radix);
 parseFloat(string); 
  • string: the string expression to be parsed as a number.
  • radix: (optional, but highly encouraged) the base of the numeral system to be used - a number between 2 and 36.

Example:

 var x = prompt("Enter a Value", "0");
 var y = prompt("Enter a Value", "0");
 var num1 = parseInt(x);
 var num2 = parseInt(y);

After this you can perform which ever calculations you want on them.

Python - Join with newline

You have to print it:

In [22]: "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
Out[22]: 'I\nwould\nexpect\nmultiple\nlines'

In [23]: print "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
I
would
expect
multiple
lines

Best C# API to create PDF

Update:

I'm not sure when or if the license changed for the iText# library, but it is licensed under AGPL which means it must be licensed if included with a closed-source product. The question does not (currently) require free or open-source libraries. One should always investigate the license type of any library used in a project.


I have used iText# with success in .NET C# 3.5; it is a port of the open source Java library for PDF generation and it's free.

There is a NuGet package available for iTextSharp version 5 and the official developer documentation, as well as C# examples, can be found at itextpdf.com

Font.createFont(..) set color and size (java.awt.Font)

Font's don't have a color; only when using the font you can set the color of the component. For example, when using a JTextArea:

JTextArea txt = new JTextArea();
Font font = new Font("Verdana", Font.BOLD, 12);
txt.setFont(font);
txt.setForeground(Color.BLUE);

According to this link, the createFont() method creates a new Font object with a point size of 1 and style PLAIN. So, if you want to increase the size of the Font, you need to do this:

 Font font = Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf"));
 return font.deriveFont(12f);

What is the "double tilde" (~~) operator in JavaScript?

It hides the intention of the code.

It's two single tilde operators, so it does a bitwise complement (bitwise not) twice. The operations take out each other, so the only remaining effect is the conversion that is done before the first operator is applied, i.e. converting the value to an integer number.

Some use it as a faster alternative to Math.floor, but the speed difference is not that dramatic, and in most cases it's just micro optimisation. Unless you have a piece of code that really needs to be optimised, you should use code that descibes what it does instead of code that uses a side effect of a non-operation.

Update 2011-08:

With optimisation of the JavaScript engine in browsers, the performance for operators and functions change. With current browsers, using ~~ instead of Math.floor is somewhat faster in some browsers, and not faster at all in some browsers. If you really need that extra bit of performance, you would need to write different optimised code for each browser.

See: tilde vs floor

CodeIgniter - Correct way to link to another page in a view

Best and easiest way is to use anchor tag in CodeIgniter like eg.

<?php 
    $this->load->helper('url'); 
    echo anchor('name_of_controller_file/function_name_if_any', 'Sign Out', array('class' => '', 'id' => '')); 
?>

Refer https://www.codeigniter.com/user_guide/helpers/url_helper.html for details

This will surely work.

How can I get a channel ID from YouTube?

You can use this website to obtain a channelId

https://commentpicker.com/youtube-channel-id.php

How to deal with "data of class uneval" error from ggplot2?

Another cause is accidentally putting the data=... inside the aes(...) instead of outside:

RIGHT:
ggplot(data=df[df$var7=='9-06',], aes(x=lifetime,y=rep_rate,group=mdcp,color=mdcp) ...)

WRONG:
ggplot(aes(data=df[df$var7=='9-06',],x=lifetime,y=rep_rate,group=mdcp,color=mdcp) ...)

In particular this can happen when you prototype your plot command with qplot(), which doesn't use an explicit aes(), then edit/copy-and-paste it into a ggplot()

qplot(data=..., x=...,y=..., ...)

ggplot(data=..., aes(x=...,y=...,...))

It's a pity ggplot's error message isn't Missing 'data' argument! instead of this cryptic nonsense, because that's what this message often means.

Change visibility of ASP.NET label with JavaScript

If you wait until the page is loaded, and then set the button's display to none, that should work. Then you can make it visible at a later point.

How to trigger HTML button when you press Enter in textbox?

$(document).ready(function(){
    $('#TextBoxId').keypress(function(e){
      if(e.keyCode==13)
      $('#linkadd').click();
    });
});

GlobalConfiguration.Configure() not present after Web API 2 and .NET 4.5.1 migration

It needs the system.web.http.webhost which is part of this package. I fixed this by installing the following package:

PM> Install-Package Microsoft.AspNet.WebApi.WebHost 

or search for it in nuget https://www.nuget.org/packages/Microsoft.AspNet.WebApi.WebHost/5.1.0

python ValueError: invalid literal for float()

I had a similar issue reading the serial output from a digital scale. I was reading [3:12] out of a 18 characters long output string.

In my case sometimes there is a null character "\x00" (NUL) which magically appears in the scale's reply string and is not printed.

I was getting the error:

> '     0.00'
> 3 0 fast loop, delta =  10.0 weight =  0.0 
> '     0.00'
> 1 800 fast loop, delta = 10.0 weight =  0.0 
> '     0.00'
> 6 0 fast loop, delta =  10.0 weight =  0.0
> '     0\x00.0' 
> Traceback (most recent call last):
>   File "measure_weight_speed.py", line 172, in start
>     valueScale = float(answer_string) 
>     ValueError: invalid literal for float(): 0

After some research I wrote few lines of code that work in my case.

replyScale = scale_port.read(18)
answer = replyScale[3:12]
answer_decode = answer.replace("\x00", "")
answer_strip = str(answer_decode.strip())
print(repr(answer_strip))
valueScale = float(answer_strip)

The answers in these posts helped:

  1. How to get rid of \x00 in my array of bytes?
  2. Invalid literal for float(): 0.000001, how to fix error?

Convert string date to timestamp in Python

>>> int(datetime.datetime.strptime('01/12/2011', '%d/%m/%Y').strftime("%s"))
1322683200

How to concatenate strings in a Windows batch file?

Note that the variables @fname or @ext can be simply concatenated. This:

forfiles /S /M *.pdf /C "CMD /C REN @path @fname_old.@ext"

renames all PDF files to "filename_old.pdf"

Read Excel sheet in Powershell

There is the possibility of making something really more cool!

# Powershell 
$xl = new-object -ComObject excell.application
$doc=$xl.workbooks.open("Filepath")
$doc.Sheets.item(1).rows |
% { ($_.value2 | Select-Object -first 3 | Select-Object -last 2) -join "," }

Join two data frames, select all columns from one and some columns from the other

Not sure if the most efficient way, but this worked for me:

from pyspark.sql.functions import col

df1.alias('a').join(df2.alias('b'),col('b.id') == col('a.id')).select([col('a.'+xx) for xx in a.columns] + [col('b.other1'),col('b.other2')])

The trick is in:

[col('a.'+xx) for xx in a.columns] : all columns in a

[col('b.other1'),col('b.other2')] : some columns of b

How to take a first character from the string

Try this:

Dim s = "RAJAN"
Dim firstChar = s(0)

You can even do this:

Dim firstChar = "RAJAN"(0)

How to convert milliseconds to seconds with precision

Surely you just need:

double seconds = milliseconds / 1000.0;

There's no need to manually do the two parts separately - you just need floating point arithmetic, which the use of 1000.0 (as a double literal) forces. (I'm assuming your milliseconds value is an integer of some form.)

Note that as usual with double, you may not be able to represent the result exactly. Consider using BigDecimal if you want to represent 100ms as 0.1 seconds exactly. (Given that it's a physical quantity, and the 100ms wouldn't be exact in the first place, a double is probably appropriate, but...)

Radio buttons and label to display in same line

Put them both to display:inline.

How can I install Python's pip3 on my Mac?

If you're using Python 3, just execute python3 get-pip.py . It is just a simple command.

HTML5 and frameborder

This works

iframe{
    border-width: 0px;
}

Angular CLI - Please add a @NgModule annotation when using latest

The problem is the import of ProjectsListComponent in your ProjectsModule. You should not import that, but add it to the export array, if you want to use it outside of your ProjectsModule.

Other issues are your project routes. You should add these to an exportable variable, otherwise it's not AOT compatible. And you should -never- import the BrowserModule anywhere else but in your AppModule. Use the CommonModule to get access to the *ngIf, *ngFor...etc directives:

@NgModule({
  declarations: [
     ProjectsListComponent
  ],
  imports: [
    CommonModule,
    RouterModule.forChild(ProjectRoutes)
  ],
  exports: [
     ProjectsListComponent
  ]
})

export class ProjectsModule {}

project.routes.ts

export const ProjectRoutes: Routes = [
      { path: 'projects', component: ProjectsListComponent }
]

Batch Renaming of Files in a Directory

Such renaming is quite easy, for example with os and glob modules:

import glob, os

def rename(dir, pattern, titlePattern):
    for pathAndFilename in glob.iglob(os.path.join(dir, pattern)):
        title, ext = os.path.splitext(os.path.basename(pathAndFilename))
        os.rename(pathAndFilename, 
                  os.path.join(dir, titlePattern % title + ext))

You could then use it in your example like this:

rename(r'c:\temp\xx', r'*.doc', r'new(%s)')

The above example will convert all *.doc files in c:\temp\xx dir to new(%s).doc, where %s is the previous base name of the file (without extension).

How to create Gmail filter searching for text only at start of subject line?

I was wondering how to do this myself; it seems Gmail has since silently implemented this feature. I created the following filter:

Matches: subject:([test])
Do this: Skip Inbox

And then I sent a message with the subject

[test] foo

And the message was archived! So it seems all that is necessary is to create a filter for the subject prefix you wish to handle.

Setting custom UITableViewCells height

Thanks to all the posts on this topic, there are some really helpful ways to adjust the rowHeight of a UITableViewCell.

Here is a compilation of some of the concepts from everyone else that really helps when building for the iPhone and iPad. You can also access different sections and adjust them according to the varying sizes of views.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
    int cellHeight = 0;

    if ([indexPath section] == 0) 
    {
        cellHeight = 16;
        settingsTable.rowHeight = cellHeight;
    }
    else if ([indexPath section] == 1)
    {
        cellHeight = 20;
        settingsTable.rowHeight = cellHeight;
    }

    return cellHeight;
}
else
{
    int cellHeight = 0;

    if ([indexPath section] == 0) 
    {
        cellHeight = 24;
        settingsTable.rowHeight = cellHeight;
    }
    else if ([indexPath section] == 1)
    {
        cellHeight = 40;
        settingsTable.rowHeight = cellHeight;
    }

    return cellHeight;
}
return 0;
} 

How to execute a stored procedure within C# program

Please check out Crane (I'm the author)

https://www.nuget.org/packages/Crane/

SqlServerAccess sqlAccess = new SqlServerAccess("your connection string");
var result = sqlAccess.Command().ExecuteNonQuery("StoredProcedureName");

Also has a bunch of other features you might like.

Interactive shell using Docker Compose

If the yml is called docker-compose.yml it can be launched with a simple $ docker-compose up. The corresponding attachment of a terminal can be simply (consider that the yml has specified a service called myservice):

$ docker-compose exec myservice sh

However, if you are using a different yml file name, such as docker-compose-mycompose.yml, it should be launched using $ docker-compose -f docker-compose-mycompose.yml up. To attach an interactive terminal you have to specify the yml file too, just like:

$ docker-compose -f docker-compose-mycompose.yml exec myservice sh

Find a file with a certain extension in folder

As per my understanding, this can be done in two ways :

1) You can use Directory Class with Getfiles method and traverse across all files to check our required extension.

Directory.GetFiles("your_folder_path)[i].Contains("*.txt")

2) You can use Path Class with GetExtension Method which takes file path as a parameter and verifies the extension.To get the file path, just have a looping condition that will fetch a single file and return the filepath that can be used for verification.

Path.GetExtension(your_file_path).Equals(".json")

Note : Both the logic has to be inside a looping condition.

Installing specific laravel version with composer create-project

If you want to use a stable version of your preferred Laravel version of choice, use:

composer create-project --prefer-dist laravel/laravel project-name "5.5.*"

That will pick out the most recent or best update of version 5.5.* (5.5.28)

Difference between classification and clustering in data mining?

There are two definitions in data mining "Supervised" and "Unsupervised". When someone tells the computer, algorithm, code, ... that this thing is like an apple and that thing is like an orange, this is supervised learning and using supervised learning (like tags for each sample in a data set) for classifying the data, you'll get classification. But on the other hand if you let the computer find out what is what and differentiate between features of the given data set, in fact learning unsupervised, for classifying the data set this would be called clustering. In this case data that are fed to the algorithm don't have tags and the algorithm should find out different classes.

How can I call the 'base implementation' of an overridden virtual method?

It's impossible if the method is declared in the derived class as overrides. to do that, the method in the derived class should be declared as new:

public class Base {

    public virtual string X() {
        return "Base";
    }
}
public class Derived1 : Base
{
    public new string X()
    {
        return "Derived 1";
    }
}

public class Derived2 : Base 
{
    public override string X() {
        return "Derived 2";
    }
}

Derived1 a = new Derived1();
Base b = new Derived1();
Base c = new Derived2();
a.X(); // returns Derived 1
b.X(); // returns Base
c.X(); // returns Derived 2

See fiddle here

Why does Java have transient fields?

The transient keyword in Java is used to indicate that a field should not be part of the serialization (which means saved, like to a file) process.

From the Java Language Specification, Java SE 7 Edition, Section 8.3.1.3. transient Fields:

Variables may be marked transient to indicate that they are not part of the persistent state of an object.

For example, you may have fields that are derived from other fields, and should only be done so programmatically, rather than having the state be persisted via serialization.

Here's a GalleryImage class which contains an image and a thumbnail derived from the image:

class GalleryImage implements Serializable
{
    private Image image;
    private transient Image thumbnailImage;

    private void generateThumbnail()
    {
        // Generate thumbnail.
    }

    private void readObject(ObjectInputStream inputStream)
            throws IOException, ClassNotFoundException
    {
        inputStream.defaultReadObject();
        generateThumbnail();
    }    
}

In this example, the thumbnailImage is a thumbnail image that is generated by invoking the generateThumbnail method.

The thumbnailImage field is marked as transient, so only the original image is serialized rather than persisting both the original image and the thumbnail image. This means that less storage would be needed to save the serialized object. (Of course, this may or may not be desirable depending on the requirements of the system -- this is just an example.)

At the time of deserialization, the readObject method is called to perform any operations necessary to restore the state of the object back to the state at which the serialization occurred. Here, the thumbnail needs to be generated, so the readObject method is overridden so that the thumbnail will be generated by calling the generateThumbnail method.

For additional information, the Discover the secrets of the Java Serialization API article (which was originally available on the Sun Developer Network) has a section which discusses the use of and presents a scenario where the transient keyword is used to prevent serialization of certain fields.

How to execute Python scripts in Windows?

Simply run the command:

C:>python .\file_name.py

Assuming the file name is within same folder and Python has already been added to environment variables.

How to convert a column of DataTable to a List

I do just like below, after you set your column AsEnumarable you can sort, order or how you want.

 _dataTable.AsEnumerable().Select(p => p.Field<string>("ColumnName")).ToList();

Do HTTP POST methods send data as a QueryString?

The best way to visualize this is to use a packet analyzer like Wireshark and follow the TCP stream. HTTP simply uses TCP to send a stream of data starting with a few lines of HTTP headers. Often this data is easy to read because it consists of HTML, CSS, or XML, but it can be any type of data that gets transfered over the internet (Executables, Images, Video, etc).

For a GET request, your computer requests a specific URL and the web server usually responds with a 200 status code and the the content of the webpage is sent directly after the HTTP response headers. This content is the same content you would see if you viewed the source of the webpage in your browser. The query string you mentioned is just part of the URL and gets included in the HTTP GET request header that your computer sends to the web server. Below is an example of an HTTP GET request to http://accel91.citrix.com:8000/OA_HTML/OALogout.jsp?menu=Y, followed by a 302 redirect response from the server. Some of the HTTP Headers are wrapped due to the size of the viewing window (these really only take one line each), and the 302 redirect includes a simple HTML webpage with a link to the redirected webpage (Most browsers will automatically redirect any 302 response to the URL listed in the Location header instead of displaying the HTML response):

HTTP GET with 302 redirect

For a POST request, you may still have a query string, but this is uncommon and does not have anything to do with the data that you are POSTing. Instead, the data is included directly after the HTTP headers that your browser sends to the server, similar to the 200 response that the web server uses to respond to a GET request. In the case of POSTing a simple web form this data is encoded using the same URL encoding that a query string uses, but if you are using a SOAP web service it could also be encoded using a multi-part MIME format and XML data.

For example here is what an HTTP POST to an XML based SOAP web service located at http://192.168.24.23:8090/msh looks like in Wireshark Follow TCP Stream:

HTTP POST TCP Stream

How to create unit tests easily in eclipse

Check out this discussion [How to automatically generate junits?]

If you are starting new and its a java application then Spring ROO looks very interesting too!

Hope that helps.

ant warning: "'includeantruntime' was not set"

As @Daniel Kutik mentioned, presetdef is a good option. Especially if one is working on a project with many build.xml files which one cannot, or prefers not to, edit (e.g., those from third-parties.)

To use presetdef, add these lines in your top-level build.xml file:

  <presetdef name="javac">
    <javac includeantruntime="false" />
  </presetdef>

Now all subsequent javac tasks will essentially inherit includeantruntime="false". If your projects do actually need ant runtime libraries, you can either add them explicitly to your build files OR set includeantruntime="true". The latter will also get rid of warnings.

Subsequent javac tasks can still explicitly change this if desired, for example:

<javac destdir="out" includeantruntime="true">
  <src path="foo.java" />
  <src path="bar.java" />
</javac>

I'd recommend against using ANT_OPTS. It works, but it defeats the purpose of the warning. The warning tells one that one's build might behave differently on another system. Using ANT_OPTS makes this even more likely because now every system needs to use ANT_OPTS in the same way. Also, ANT_OPTS will apply globally, suppressing warnings willy-nilly in all your projects

Oracle timestamp data type

The number in parentheses specifies the precision of fractional seconds to be stored. So, (0) would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.

So an unspecified value would store a date like:

TIMESTAMP 24-JAN-2012 08.00.05.993847 AM

And specifying (0) stores only:

TIMESTAMP(0) 24-JAN-2012 08.00.05 AM

See Oracle documentation on data types.

Show hide div using codebehind

Another method (which it appears no-one has mentioned thus far), is to add an additional KeyValue pair to the element's Style array. i.e

Div.Style.Add("display", "none");

This has the added benefit of merely hiding the element, rather than preventing it from being written to the DOM to begin with - unlike the "Visible" property. i.e.

Div.Visible = false

results in the div never being written to the DOM.

Edit: This should be done in the 'code-behind', I.e. The *.aspx.cs file.

Take a full page screenshot with Firefox on the command-line

Update 2018-07-23

As was just pointed out in the comments, this question was about getting a screenshot from the command line. Sorry, I just read over that. So here is the correct answer:

As of Firefox 57 you can create a screenshot in headless mode like this:

firefox -screenshot https://developer.mozilla.com

Read more in the documentation.

Update 2017-06-15

As of Firefox 55 there is Firefox Screenshots as a more flexible alternative. As of Firefox 57 Screenshots can capture a full page, too.

Original answer

Since Firefox 32 there is also a full page screenshot button in the developer tools (F12). If it is not enabled go to the developer tools settings (gear button) and choose "Take a fullpage screenshot" at the "Available Toolbox Buttons" section.

developer tools toolbar source: developer.mozilla.org

By default the screenshots are saved in the download directory. This works similar to screenshot --fullpage in the toolbar.

What does it mean if a Python object is "subscriptable" or not?

As a corollary to the earlier answers here, very often this is a sign that you think you have a list (or dict, or other subscriptable object) when you do not.

For example, let's say you have a function which should return a list;

def gimme_things():
    if something_happens():
        return ['all', 'the', 'things']

Now when you call that function, and something_happens() for some reason does not return a True value, what happens? The if fails, and so you fall through; gimme_things doesn't explicitly return anything -- so then in fact, it will implicitly return None. Then this code:

things = gimme_things()
print("My first thing is {0}".format(things[0]))

will fail with "NoneType object is not subscriptable" because, well, things is None and so you are trying to do None[0] which doesn't make sense because ... what the error message says.

There are two ways to fix this bug in your code -- the first is to avoid the error by checking that things is in fact valid before attempting to use it;

things = gimme_things()
if things:
    print("My first thing is {0}".format(things[0]))
else:
    print("No things")  # or raise an error, or do nothing, or ...

or equivalently trap the TypeError exception;

things = gimme_things()
try:
    print("My first thing is {0}".format(things[0]))
except TypeError:
    print("No things")  # or raise an error, or do nothing, or ...

Another is to redesign gimme_things so that you make sure it always returns a list. In this case, that's probably the simpler design because it means if there are many places where you have a similar bug, they can be kept simple and idiomatic.

def gimme_things():
    if something_happens():
        return ['all', 'the', 'things']
    else:  # make sure we always return a list, no matter what!
        logging.info("Something didn't happen; return empty list")
        return []

Of course, what you put in the else: branch depends on your use case. Perhaps you should raise an exception when something_happens() fails, to make it more obvious and explicit where something actually went wrong? Adding exceptions to your own code is an important way to let yourself know exactly what's up when something fails!

(Notice also how this latter fix still doesn't completely fix the bug -- it prevents you from attempting to subscript None but things[0] is still an IndexError when things is an empty list. If you have a try you can do except (TypeError, IndexError) to trap it, too.)

Getting Cannot bind argument to parameter 'Path' because it is null error in powershell

  1. PM>Uninstall-Package EntityFramework -Force
  2. PM>Iinstall-Package EntityFramework -Pre -Version 6.0.0

I solve this problem with this code in NugetPackageConsole.and it works.The problem was in the version. i thikn it will help others.

If a DOM Element is removed, are its listeners also removed from memory?

regarding jQuery:

the .remove() method takes elements out of the DOM. Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use .detach() instead.

Reference: http://api.jquery.com/remove/

jQuery v1.8.2 .remove() source code:

remove: function( selector, keepData ) {
    var elem,
        i = 0;

    for ( ; (elem = this[i]) != null; i++ ) {
        if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
            if ( !keepData && elem.nodeType === 1 ) {
                jQuery.cleanData( elem.getElementsByTagName("*") );
                jQuery.cleanData( [ elem ] );
            }

            if ( elem.parentNode ) {
                elem.parentNode.removeChild( elem );
            }
        }
    }

    return this;
}

apparently jQuery uses node.removeChild()

According to this : https://developer.mozilla.org/en-US/docs/DOM/Node.removeChild ,

The removed child node still exists in memory, but is no longer part of the DOM. You may reuse the removed node later in your code, via the oldChild object reference.

ie event listeners might get removed, but node still exists in memory.

What does an exclamation mark mean in the Swift language?

john is an optional var and it can contain a nil value. To ensure that the value isn't nil use a ! at the end of the var name.

From documentation

“Once you’re sure that the optional does contain a value, you can access its underlying value by adding an exclamation mark (!) to the end of the optional’s name. The exclamation mark effectively says, “I know that this optional definitely has a value; please use it.”

Another way to check non nil value is (optional unwrapping)

    if let j = json {
        // do something with j
    }

How to convert int[] to Integer[] in Java?

  1. Convert int[] to Integer[]

    public static Integer[] toConvertInteger(int[] ids) {
    
      Integer[] newArray = new Integer[ids.length];
         for (int i = 0; i < ids.length; i++) {
           newArray[i] = Integer.valueOf(ids[i]);
         }
       return newArray;
    }
    
  2. Convert Integer[] to int[]

    public static int[] toint(Integer[] WrapperArray) {
    
       int[] newArray = new int[WrapperArray.length];
          for (int i = 0; i < WrapperArray.length; i++) {
             newArray[i] = WrapperArray[i].intValue();
          }
       return newArray;
    }
    

Secure hash and salt for PHP passwords

Though the question has been answered, I just want to reiterate that salts used for hashing should be random and not like email address as suggested in first answer.

More explanation is available at- http://www.pivotalsecurity.com/blog/password-hashing-salt-should-it-be-random/

Recently I had a discussion whether password hashes salted with random bits are more secure than the one salted with guessable or known salts. Let’s see: If the system storing password is compromised as well as the system which stores the random salt, the attacker will have access to hash as well as salt, so whether the salt is random or not, doesn’t matter. The attacker will can generate pre-computed rainbow tables to crack the hash. Here comes the interesting part- it is not so trivial to generate pre-computed tables. Let us take example of WPA security model. Your WPA password is actually never sent to Wireless Access Point. Instead, it is hashed with your SSID (the network name- like Linksys, Dlink etc). A very good explanation of how this works is here. In order to retrieve password from hash, you will need to know the password as well as salt (network name). Church of Wifi has already pre-computed hash tables which has top 1000 SSIDs and about 1 million passwords. The size is of all tables is about 40 GB. As you can read on their site, someone used 15 FGPA arrays for 3 days to generate these tables. Assuming victim is using the SSID as “a387csf3" and password as “123456", will it be cracked by those tables? No! .. it cannot. Even if the password is weak, the tables don’t have hashes for SSID a387csf3. This is the beauty of having random salt. It will deter crackers who thrive upon pre-computed tables. Can it stop a determined hacker? Probably not. But using random salts does provide additional layer of defense. While we are on this topic, let us discuss additional advantage of storing random salts on a separate system. Scenario #1 : Password hashes are stored on system X and salt values used for hashing are stored on system Y. These salt values are guessable or known (e.g. username) Scenario#2 : Password hashes are stored on system X and salt values used for hashing are stored on system Y. These salt values are random. In case system X has been compromised, as you can guess, there is a huge advantage of using random salt on a separate system (Scenario #2) . The attacker will need to guess addition values to be able to crack hashes. If a 32 bit salt is used, 2^32= 4,294,967,296 (about 4.2 billion) iterations will can be required for each password guessed.

Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

I know its too late now. However even today if you are having trouble accessing cross thread controls? This is the shortest answer till date :P

Invoke(new Action(() =>
                {
                    label1.Text = "WooHoo!!!";
                }));

This is how i access any form control from a thread.

Validate form field only on submit or user input

You can use angularjs form state form.$submitted. Initially form.$submitted value will be false and will became true after successful form submit.

Django auto_now and auto_now_add

As for your Admin display, see this answer.

Note: auto_now and auto_now_add are set to editable=False by default, which is why this applies.

What is the difference between MVC and MVVM?

In very short - in MVC Controler is aware of (controls) view, while in MVVM, ViewModel is unaware of who consumes it. ViewModel exposes its observable properties and actions to whoever might be interested in using it. That fact makes testing easier since there is no reference to UI within ViewModel.

The Eclipse executable launcher was unable to locate its companion launcher jar windows

I just had this problem and it seems to be related to permissions somehow. I initially unzipped it to my Program Files folder, in Windows 8. After unzipping it directly to C: the program started normally.

Portable way to check if directory exists [Windows/Linux, C]

With C++17 you can use std::filesystem::is_directory function (https://en.cppreference.com/w/cpp/filesystem/is_directory). It accepts a std::filesystem::path object which can be constructed with a unicode path.

Simple JavaScript problem: onClick confirm not preventing default action

First of all, delete is a reserved word in javascript, I'm surprised this even executes for you (When I test it in Firefox, I get a syntax error)

Secondly, your HTML looks weird - is there a reason you're closing the opening anchor tags with /> instead of just > ?

Is there an eval() function in Java?

As there are many answers, I'm adding my implementation on top of eval() method with some additional features like support for factorial, evaluating complex expressions etc.

package evaluation;

import java.math.BigInteger;
import java.util.EmptyStackException;
import java.util.Scanner;
import java.util.Stack;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class EvalPlus {
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        System.out.println("This Evaluation is based on BODMAS rule\n");
        evaluate();
    }

    private static void evaluate() {
        StringBuilder finalStr = new StringBuilder();
        System.out.println("Enter an expression to evaluate:");
        String expr = scanner.nextLine(); 
        if(isProperExpression(expr)) {
            expr = replaceBefore(expr);
            char[] temp = expr.toCharArray();
            String operators = "(+-*/%)";
            for(int i = 0; i < temp.length; i++) {
                if((i == 0 && temp[i] != '*') || (i == temp.length-1 && temp[i] != '*' && temp[i] != '!')) {
                    finalStr.append(temp[i]);
                } else if((i > 0 && i < temp.length -1) || (i==temp.length-1 && temp[i] == '!')) {
                    if(temp[i] == '!') {
                        StringBuilder str = new StringBuilder();
                        for(int k = i-1; k >= 0; k--) {
                            if(Character.isDigit(temp[k])) {
                                str.insert(0, temp[k] );
                            } else {
                                break;
                            }
                        }
                        Long prev = Long.valueOf(str.toString());
                        BigInteger val = new BigInteger("1");
                        for(Long j = prev; j > 1; j--) {
                            val = val.multiply(BigInteger.valueOf(j));
                        }
                        finalStr.setLength(finalStr.length() - str.length());
                        finalStr.append("(" + val + ")");
                        if(temp.length > i+1) {
                            char next = temp[i+1];
                            if(operators.indexOf(next) == -1) { 
                                finalStr.append("*");
                            }
                        }
                    } else {
                        finalStr.append(temp[i]);
                    }
                }
            }
            expr = finalStr.toString();
            if(expr != null && !expr.isEmpty()) {
                ScriptEngineManager mgr = new ScriptEngineManager();
                ScriptEngine engine = mgr.getEngineByName("JavaScript");
                try {
                    System.out.println("Result: " + engine.eval(expr));
                    evaluate();
                } catch (ScriptException e) {
                    System.out.println(e.getMessage());
                }
            } else {
                System.out.println("Please give an expression");
                evaluate();
            }
        } else {
            System.out.println("Not a valid expression");
            evaluate();
        }
    }

    private static String replaceBefore(String expr) {
        expr = expr.replace("(", "*(");
        expr = expr.replace("+*", "+").replace("-*", "-").replace("**", "*").replace("/*", "/").replace("%*", "%");
        return expr;
    }

    private static boolean isProperExpression(String expr) {
        expr = expr.replaceAll("[^()]", "");
        char[] arr = expr.toCharArray();
        Stack<Character> stack = new Stack<Character>();
        int i =0;
        while(i < arr.length) {
            try {
                if(arr[i] == '(') {
                    stack.push(arr[i]);
                } else {
                    stack.pop();
                }
            } catch (EmptyStackException e) {
                stack.push(arr[i]);
            }
            i++;
        }
        return stack.isEmpty();
    }
}

Please find the updated gist anytime here. Also comment if any issues are there. Thanks.

In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?

And how can you convert back again from ascii to byte array ?

i followed following code to convert to ascii given by Jemenake.

public static String toHexString(byte[] bytes) {
    char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    char[] hexChars = new char[bytes.length * 2];
    int v;
    for ( int j = 0; j < bytes.length; j++ ) {
        v = bytes[j] & 0xFF;
        hexChars[j*2] = hexArray[v/16];
        hexChars[j*2 + 1] = hexArray[v%16];
    }
    return new String(hexChars);
}

How to add multiple files to Git at the same time

step1.

git init

step2.

a) for all files

git add -a

b) only specific folder

git add <folder1> <folder2> <etc.>

step3.

git commit -m "Your message about the commit"

step4.

enter image description here

git remote add origin https://github.com/yourUsername/yourRepository.git

step5.

git push -u origin master
git push origin master

if you are face this error than

 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'https://github.com/harishkumawat2610/Qt5-with-C-plus-plus.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

Use this command

git push --force origin master

Failed to connect to camera service

Few things:

  1. Why are your use-permissions and use-features tags in your activity tag. Generally, permissions are included as direct children of your <manifest> tag. This could be part of the problem.

  2. According to the android camera open documentation, a runtime exception is thrown:

    if connection to the camera service fails (for example, if the camera is in use by another process or device policy manager has disabled the camera)

    Have you tried checking if the camera is being used by something else or if your policy manager has some setting where the camera is turned off?

  3. Don't forget the <uses-feature android:name="android.hardware.camera.autofocus" /> for autofocus.

While I'm not sure if any of these will directly help you, I think they're worth investigating if for no other reason than to simply rule out. Due diligence if you will.

EDIT As mentioned in the comments below, the solution was to move the uses-permissions up to above the application tag.

How to perform an SQLite query within an Android application?

Try this, this works for my code name is a String:

cursor = rdb.query(true, TABLE_PROFILE, new String[] { ID,
    REMOTEID, FIRSTNAME, LASTNAME, EMAIL, GENDER, AGE, DOB,
    ROLEID, NATIONALID, URL, IMAGEURL },                    
    LASTNAME + " like ?", new String[]{ name+"%" }, null, null, null, null);

Extracting just Month and Year separately from Pandas Datetime column

@KieranPC's solution is the correct approach for Pandas, but is not easily extendible for arbitrary attributes. For this, you can use getattr within a generator comprehension and combine using pd.concat:

# input data
list_of_dates = ['2012-12-31', '2012-12-29', '2012-12-30']
df = pd.DataFrame({'ArrivalDate': pd.to_datetime(list_of_dates)})

# define list of attributes required    
L = ['year', 'month', 'day', 'dayofweek', 'dayofyear', 'weekofyear', 'quarter']

# define generator expression of series, one for each attribute
date_gen = (getattr(df['ArrivalDate'].dt, i).rename(i) for i in L)

# concatenate results and join to original dataframe
df = df.join(pd.concat(date_gen, axis=1))

print(df)

  ArrivalDate  year  month  day  dayofweek  dayofyear  weekofyear  quarter
0  2012-12-31  2012     12   31          0        366           1        4
1  2012-12-29  2012     12   29          5        364          52        4
2  2012-12-30  2012     12   30          6        365          52        4

jQuery getJSON save result into variable

$.getJSon expects a callback functions either you pass it to the callback function or in callback function assign it to global variale.

var globalJsonVar;

    $.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
               //do some thing with json  or assign global variable to incoming json. 
                globalJsonVar=json;
          });

IMO best is to call the callback function. which is nicer to eyes, readability aspects.

$.getJSON("http://127.0.0.1:8080/horizon-update", callbackFuncWithData);

function callbackFuncWithData(data)
{
 // do some thing with data 
}

Regex Match all characters between two strings

Lazy Quantifier Needed

Resurrecting this question because the regex in the accepted answer doesn't seem quite correct to me. Why? Because

(?<=This is)(.*)(?=sentence)

will match my first sentence. This is my second in This is my first sentence. This is my second sentence.

See demo.

You need a lazy quantifier between the two lookarounds. Adding a ? makes the star lazy.

This matches what you want:

(?<=This is).*?(?=sentence)

See demo. I removed the capture group, which was not needed.

DOTALL Mode to Match Across Line Breaks

Note that in the demo the "dot matches line breaks mode" (a.k.a.) dot-all is set (see how to turn on DOTALL in various languages). In many regex flavors, you can set it with the online modifier (?s), turning the expression into:

(?s)(?<=This is).*?(?=sentence)

Reference

Overwriting txt file in java

The easiest way to overwrite a text file is to use a public static field.

this will overwrite the file every time because your only using false the first time through.`

public static boolean appendFile;

Use it to allow only one time through the write sequence for the append field of the write code to be false.

// use your field before processing the write code

appendFile = False;

File fnew=new File("../playlist/"+existingPlaylist.getText()+".txt");
String source = textArea.getText();
System.out.println(source);
FileWriter f2;

try {
     //change this line to read this

    // f2 = new FileWriter(fnew,false);

    // to read this
    f2 = new FileWriter(fnew,appendFile); // important part
    f2.write(source);

    // change field back to true so the rest of the new data will
    // append to the new file.

    appendFile = true;

    f2.close();
 } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
 }           

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

 public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);

       //custom toolbaar
       getSupportActionBar().setTitle("Abhijeet");

    }
}

ListView with Add and Delete Buttons in each Row in android

public class UserCustomAdapter extends ArrayAdapter<User> {
 Context context;
 int layoutResourceId;
 ArrayList<User> data = new ArrayList<User>();

 public UserCustomAdapter(Context context, int layoutResourceId,
   ArrayList<User> data) {
  super(context, layoutResourceId, data);
  this.layoutResourceId = layoutResourceId;
  this.context = context;
  this.data = data;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  View row = convertView;
  UserHolder holder = null;

  if (row == null) {
   LayoutInflater inflater = ((Activity) context).getLayoutInflater();
   row = inflater.inflate(layoutResourceId, parent, false);
   holder = new UserHolder();
   holder.textName = (TextView) row.findViewById(R.id.textView1);
   holder.textAddress = (TextView) row.findViewById(R.id.textView2);
   holder.textLocation = (TextView) row.findViewById(R.id.textView3);
   holder.btnEdit = (Button) row.findViewById(R.id.button1);
   holder.btnDelete = (Button) row.findViewById(R.id.button2);
   row.setTag(holder);
  } else {
   holder = (UserHolder) row.getTag();
  }
  User user = data.get(position);
  holder.textName.setText(user.getName());
  holder.textAddress.setText(user.getAddress());
  holder.textLocation.setText(user.getLocation());
  holder.btnEdit.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Log.i("Edit Button Clicked", "**********");
    Toast.makeText(context, "Edit button Clicked",
      Toast.LENGTH_LONG).show();
   }
  });
  holder.btnDelete.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Log.i("Delete Button Clicked", "**********");
    Toast.makeText(context, "Delete button Clicked",
      Toast.LENGTH_LONG).show();
   }
  });
  return row;

 }

 static class UserHolder {
  TextView textName;
  TextView textAddress;
  TextView textLocation;
  Button btnEdit;
  Button btnDelete;
 }
}

Hey Please have a look here-

I have same answer here on my blog ..

How to permanently export a variable in Linux?

If it suits anyone, here are some brief guidelines for adding environment variables permanently.

vi ~/.bash_profile

Add the variables to the file:

export DISPLAY=:0
export JAVA_HOME=~/opt/openjdk11

Immediately apply all changes:

source ~/.bash_profile

Source: https://www.serverlab.ca/tutorials/linux/administration-linux/how-to-set-environment-variables-in-linux/

Datagridview full row selection but get single cell value

this get me the text value of exact cell in data grid view

private void dataGridView_SelectionChanged(object sender, EventArgs e)
    {
        label1.Text = dataGridView.CurrentRow.Cells[#].Value.ToString();
    }

you can see it in label and change # wih the index of the exact cell you want

How to write multiple conditions in Makefile.am with "else if"

As you've discovered, you can't do that. You can do:

libtest_LIBS = 

...

if HAVE_CLIENT
libtest_LIBS += libclient.la
endif

if HAVE_SERVER
libtest_LIBS += libserver.la
endif

How can I alias a default import in JavaScript?

defaultMember already is an alias - it doesn't need to be the name of the exported function/thing. Just do

import alias from 'my-module';

Alternatively you can do

import {default as alias} from 'my-module';

but that's rather esoteric.

What to do about Eclipse's "No repository found containing: ..." error messages?

I just got it when installing Maven support in Eclipse for Java EE developers Helios. Solution was just to run Eclipse as Administrator, update went fine after

How can I list the scheduled jobs running in my database?

The DBA views are restricted. So you won't be able to query them unless you're connected as a DBA or similarly privileged user.

The ALL views show you the information you're allowed to see. Normally that would be jobs you've submitted, unless you have additional privileges.

The privileges you need are defined in the Admin Guide. Find out more.

So, either you need a DBA account or you need to chat with your DBA team about getting access to the information you need.

Loop through Map in Groovy?

Quite simple with a closure:

def map = [
           'iPhone':'iWebOS',
           'Android':'2.3.3',
           'Nokia':'Symbian',
           'Windows':'WM8'
           ]

map.each{ k, v -> println "${k}:${v}" }

How do I make the return type of a method generic?

 private static T[] prepareArray<T>(T[] arrayToCopy, T value)
    {
        Array.Copy(arrayToCopy, 1, arrayToCopy, 0, arrayToCopy.Length - 1);
        arrayToCopy[arrayToCopy.Length - 1] = value;
        return (T[])arrayToCopy;
    }

I was performing this throughout my code and wanted a way to put it into a method. I wanted to share this here because I didn't have to use the Convert.ChangeType for my return value. This may not be a best practice but it worked for me. This method takes in an array of generic type and a value to add to the end of the array. The array is then copied with the first value stripped and the value taken into the method is added to the end of the array. The last thing is that I return the generic array.

Delete item from state array in react

const array = [...this.state.people];
array.splice(i, 1);
this.setState({people: array});         

Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF

Simply delete the tables that are dragged into your .dbml file and re-drag them again. Then Clean solution>Rebuild solution> Build solution.

Thats what worked for me.

I didnt made the table on my own, I was using VS and SSMS, I followed this link for ASP.NET Identity:https://docs.microsoft.com/en-us/aspnet/identity/overview/getting-started/adding-aspnet-identity-to-an-empty-or-existing-web-forms-project

How to remove single character from a String

One possibility:

String result = str.substring(0, index) + str.substring(index+1);

Note that the result is a new String (as well as two intermediate String objects), because Strings in Java are immutable.

Permission denied when launch python script via bash

I solved my problem. it's just the version of python which the interpreter reads off the first line. removing to version numbers did it for me, i.e.

#!/usr/bin/python2.7 --> #!/usr/bin/python

IF... OR IF... in a windows batch file

I don't think so. Just use two IFs and GOTO the same label:

IF cond1 GOTO foundit
IF cond2 GOTO foundit

ECHO Didn't found it
GOTO end

:foundit
ECHO Found it!

:end

what does mysql_real_escape_string() really do?

The mysql_real_escape_string() helps you escape special characters such as single quote etc that users may submit to your script. You need to escape such characters because that comes in handy when you want to avoid SQL Injection.

I would sugggest you to check out:

mysql_real_escape_string() versus Prepared Statements

To be on much safer side, you need to go for Prepared Statements instead as demonstrated through above article.

How to percent-encode URL parameters in Python?

My answer is similar to Paolo's answer.

I think module requests is much better. It's based on urllib3. You can try this:

>>> from requests.utils import quote
>>> quote('/test')
'/test'
>>> quote('/test', safe='')
'%2Ftest'

Where to download Microsoft Visual c++ 2003 redistributable

Another way:

using Unofficial (Full Size: 26.1 MB) VC++ All in one that contained your needed files:

http://www.wincert.net/forum/topic/9790-aio-microsoft-visual-bcfj-redistributable-x86x64/

OR (Smallest 5.10 MB) Microsoft Visual Basic/C++ Runtimes 1.1.1 RePacked Here:

http://www.wincert.net/forum/topic/9794-bonus-microsoft-visual-basicc-runtimes-111/

Share data between AngularJS controllers

Simplest Solution:

I have used an AngularJS service.

Step1: I have created an AngularJS service named SharedDataService.

myApp.service('SharedDataService', function () {
     var Person = {
        name: ''

    };
    return Person;
});

Step2: Create two controllers and use the above created service.

//First Controller
myApp.controller("FirstCtrl", ['$scope', 'SharedDataService',
   function ($scope, SharedDataService) {
   $scope.Person = SharedDataService;
   }]);

//Second Controller
myApp.controller("SecondCtrl", ['$scope', 'SharedDataService',
   function ($scope, SharedDataService) {
   $scope.Person = SharedDataService;
   }]);

Step3: Simply use the created controllers in the view.

<body ng-app="myApp">

<div ng-controller="FirstCtrl">
<input type="text" ng-model="Person.name">
<br>Input is : <strong>{{Person.name}}</strong>
</div>

<hr>

<div ng-controller="SecondCtrl">
Input should also be here: {{Person.name}}
</div>

</body>

To see working solution to this problem please press the link below

https://codepen.io/wins/pen/bmoYLr

.html file:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body ng-app="myApp">

  <div ng-controller="FirstCtrl">
    <input type="text" ng-model="Person.name">
    <br>Input is : <strong>{{Person.name}}</strong>
   </div>

<hr>

  <div ng-controller="SecondCtrl">
    Input should also be here: {{Person.name}}
  </div>

//Script starts from here

<script>

var myApp = angular.module("myApp",[]);
//create SharedDataService
myApp.service('SharedDataService', function () {
     var Person = {
        name: ''

    };
    return Person;
});

//First Controller
myApp.controller("FirstCtrl", ['$scope', 'SharedDataService',
    function ($scope, SharedDataService) {
    $scope.Person = SharedDataService;
    }]);

//Second Controller
myApp.controller("SecondCtrl", ['$scope', 'SharedDataService',
    function ($scope, SharedDataService) {
    $scope.Person = SharedDataService;
}]);

</script>


</body>
</html>

Set a default parameter value for a JavaScript function

As per the syntax

function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) {
   statements
}

you can define the default value of formal parameters. and also check undefined value by using typeof function.

How do I redirect users after submit button click?

// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com/SpecificAction.php");

// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com/SpecificAction.php";

Microsoft.Office.Core Reference Missing

If you are not able to find PIA for Office 2013 then follow these steps:

  1. Click on Solution Explorer in Visual Studio
  2. Right click on your project name (not solution name)
  3. Select 'Manage Nuget packages'
  4. Click on Browse and search for PIA 2013, choose the shown PIA and click on Install.....

And you are done.

How to create a signed APK file using Cordova command line interface?

Build cordova release APK file in cmd.

KEY STORE FILE PATH: keystore file path (F:/cordova/myApp/xxxxx.jks)

KEY STORE PASSWORD: xxxxx

KEY STORE ALIAS: xxxxx

KEY STORE ALIAS PASSWORD: xxxxx

PATH OF zipalign.exe: zipalign.exe file path (C:\Users\xxxx\AppData\Local\Android\sdk\build-tools\25.0.2\zipalign)

ANDROID UNSIGNED APK NAME: android-release-unsigned.apk

ANDROID RELEASE APK NAME: android-release.apk

Run below steps in cmd (run as administrator)

  1. cordova build --release android
  2. go to android-release-unsigned.apk file location (PROJECT\platforms\android\build\outputs\apk)
  3. jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore <KEY STORE FILE PATH> <ANDROID UNSIGNED APK NAME> <KEY STORE ALIAS>
  4. <PATH OF zipalign.exe> -v 4 <ANDROID UNSIGNED APK NAME> <ANDROID RELEASE APK NAME>

T-SQL Cast versus Convert

You should also not use CAST for getting the text of a hash algorithm. CAST(HASHBYTES('...') AS VARCHAR(32)) is not the same as CONVERT(VARCHAR(32), HASHBYTES('...'), 2). Without the last parameter, the result would be the same, but not a readable text. As far as I know, You cannot specify that last parameter in CAST.

SQL Query to concatenate column values from multiple rows in Oracle

  1. LISTAGG delivers the best performance if sorting is a must(00:00:05.85)

    SELECT pid, LISTAGG(Desc, ' ') WITHIN GROUP (ORDER BY seq) AS description FROM B GROUP BY pid;

  2. COLLECT delivers the best performance if sorting is not needed(00:00:02.90):

    SELECT pid, TO_STRING(CAST(COLLECT(Desc) AS varchar2_ntt)) AS Vals FROM B GROUP BY pid;

  3. COLLECT with ordering is bit slower(00:00:07.08):

    SELECT pid, TO_STRING(CAST(COLLECT(Desc ORDER BY Desc) AS varchar2_ntt)) AS Vals FROM B GROUP BY pid;

All other techniques were slower.

Make DateTimePicker work as TimePicker only in WinForms

...or alternatively if you only want to show a portion of the time value use "Custom":

timePicker = new DateTimePicker();
timePicker.Format = DateTimePickerFormat.Custom;
timePicker.CustomFormat = "HH:mm"; // Only use hours and minutes
timePicker.ShowUpDown = true;

Embedding JavaScript engine into .NET

You can use Rhino a Mozilla Javascript engine written on Java, and use it with IKVM , here are some instructions

Instructions:https://www.codeproject.com/Articles/41792/Embedding-JavaScript-into-C-with-Rhino-and-IKVM

Float a DIV on top of another DIV

.close-image {
    cursor: pointer;
    display: block;
    float: right;
    position: relative;
    top: 22px;
    z-index: 1;
}

I think this might be what you are looking for.

How do I accomplish an if/else in mustache.js?

This is something you solve in the "controller", which is the point of logicless templating.

// some function that retreived data through ajax
function( view ){

   if ( !view.avatar ) {
      // DEFAULTS can be a global settings object you define elsewhere
      // so that you don't have to maintain these values all over the place
      // in your code.
      view.avatar = DEFAULTS.AVATAR;
   }

   // do template stuff here

}

This is actually a LOT better then maintaining image url's or other media that might or might not change in your templates, but takes some getting used to. The point is to unlearn template tunnel vision, an avatar img url is bound to be used in other templates, are you going to maintain that url on X templates or a single DEFAULTS settings object? ;)

Another option is to do the following:

// augment view
view.hasAvatar = !!view.avatar;
view.noAvatar = !view.avatar;

And in the template:

{{#hasAvatar}}
    SHOW AVATAR
{{/hasAvatar}}
{{#noAvatar}}
    SHOW DEFAULT
{{/noAvatar}}

But that's going against the whole meaning of logicless templating. If that's what you want to do, you want logical templating and you should not use Mustache, though do give it yourself a fair chance of learning this concept ;)

How to interactively (visually) resolve conflicts in SourceTree / git

When the Resolve Conflicts->Content Menu are disabled, one may be on the Pending files list. We need to select the Conflicted files option from the drop down (top)

hope it helps

Explicit vs implicit SQL joins

In my experience, using the cross-join-with-a-where-clause syntax often produces a brain damaged execution plan, especially if you are using a Microsoft SQL product. The way that SQL Server attempts to estimate table row counts, for instance, is savagely horrible. Using the inner join syntax gives you some control over how the query is executed. So from a practical point of view, given the atavistic nature of current database technology, you have to go with the inner join.

PHP Using RegEx to get substring of a string

$matches = array();
preg_match('/id=([0-9]+)\?/', $url, $matches);

This is safe for if the format changes. slandau's answer won't work if you ever have any other numbers in the URL.

php.net/preg-match

Handling exceptions from Java ExecutorService tasks

I'm using VerboseRunnable class from jcabi-log, which swallows all exceptions and logs them. Very convenient, for example:

import com.jcabi.log.VerboseRunnable;
scheduler.scheduleWithFixedDelay(
  new VerboseRunnable(
    Runnable() {
      public void run() { 
        // the code, which may throw
      }
    },
    true // it means that all exceptions will be swallowed and logged
  ),
  1, 1, TimeUnit.MILLISECONDS
);

Cannot start GlassFish 4.1 from within Netbeans 8.0.1 Service area

You will get like this error

error ss

Try the following steps

1. Open Command Prompt (Press Windows key and type "cmd" and hit Enter) Then type this command as show in picture

netstat -aon | find ":8080" | find "LISTENING" cmd command

  1. Now open Task Manager (Press Windows key and type "Task Manager" and hit Enter) In that, go to Details Tab and under PID Column, search for the number you found in cmd

task manager

  1. Right Click on that program and select end process

java: run a function after a specific number of seconds

ScheduledThreadPoolExecutor has this ability, but it's quite heavyweight.

Timer also has this ability but opens several thread even if used only once.

Here's a simple implementation with a test (signature close to Android's Handler.postDelayed()):

public class JavaUtil {
    public static void postDelayed(final Runnable runnable, final long delayMillis) {
        final long requested = System.currentTimeMillis();
        new Thread(new Runnable() {
            @Override
            public void run() {
                // The while is just to ignore interruption.
                while (true) {
                    try {
                        long leftToSleep = requested + delayMillis - System.currentTimeMillis();
                        if (leftToSleep > 0) {
                            Thread.sleep(leftToSleep);
                        }
                        break;
                    } catch (InterruptedException ignored) {
                    }
                }
                runnable.run();
            }
        }).start();
    }
}

Test:

@Test
public void testRunsOnlyOnce() throws InterruptedException {
    long delay = 100;
    int num = 0;
    final AtomicInteger numAtomic = new AtomicInteger(num);
    JavaUtil.postDelayed(new Runnable() {
        @Override
        public void run() {
            numAtomic.incrementAndGet();
        }
    }, delay);
    Assert.assertEquals(num, numAtomic.get());
    Thread.sleep(delay + 10);
    Assert.assertEquals(num + 1, numAtomic.get());
    Thread.sleep(delay * 2);
    Assert.assertEquals(num + 1, numAtomic.get());
}

How to change values in a tuple?

i did this:

list = [1,2,3,4,5]
tuple = (list)

and to change, just do

list[0]=6

and u can change a tuple :D

here is it copied exactly from IDLE

>>> list=[1,2,3,4,5,6,7,8,9]

>>> tuple=(list)

>>> print(tuple)

[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> list[0]=6

>>> print(tuple)

[6, 2, 3, 4, 5, 6, 7, 8, 9]

Generate a random date between two other dates

In python:

>>> from dateutil.rrule import rrule, DAILY
>>> import datetime, random
>>> random.choice(
                 list(
                     rrule(DAILY, 
                           dtstart=datetime.date(2009,8,21), 
                           until=datetime.date(2010,10,12))
                     )
                 )
datetime.datetime(2010, 2, 1, 0, 0)

(need python dateutil library – pip install python-dateutil)

java.io.FileNotFoundException: (Access is denied)

You cannot open and read a directory, use the isFile() and isDirectory() methods to distinguish between files and folders. You can get the contents of folders using the list() and listFiles() methods (for filenames and Files respectively) you can also specify a filter that selects a subset of files listed.

What is the difference between README and README.md in GitHub projects?

.md stands for markdown and is generated at the bottom of your github page as html.

Typical syntax includes:

Will become a heading
==============

Will become a sub heading
--------------

*This will be Italic*

**This will be Bold**

- This will be a list item
- This will be a list item

    Add a indent and this will end up as code

For more details: http://daringfireball.net/projects/markdown/

How to reference Microsoft.Office.Interop.Excel dll?

You have to check which version of Excel you are targeting?

If you are targeting Excel 2010 use version 14 (as per Grant's screenshot answer), Excel 2007 use version 12 . You can not support Excel 2003 using vS2012 as they do not have the correct Interop dll installed.

ERROR 2003 (HY000): Can't connect to MySQL server on localhost (10061)

Check Mysqld.exe file is in your bin folder. if it is not there , just copy that file from any other computer and paste it on your bin folder.Just double click. Then run mysql.its solved

How can I use Bash syntax in Makefile targets?

One way that also works is putting it this way in the first line of the your target:

your-target: $(eval SHELL:=/bin/bash)
    @echo "here shell is $$0"

Spring Boot: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean

Try this

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
    public static void main(String[] args) {
       SpringApplication.run(ScheduledTasks.class, args);
    }
}

Finding length of char array

sizeof returns the size of the type of the variable in bytes. So in your case it's returning the size of your char[7] which is 7 * sizeof(char). Since sizeof(char) = 1, the result is 7.

Expanding this to another example:

int intArr[5];
printf("sizeof(intArr)=%u", sizeof(intArr));

would yield 5 * sizeof(int), so you'd get the result "20" (At least on a regular 32bit platform. On others sizeof(int) might differ)

To return to your problem:

It seems like, that what you want to know is the length of the string which is contained inside your array and not the total array size.

By definition C-Strings have to be terminated with a trailing '\0' (0-Byte). So to get the appropriate length of the string contained within your array, you have to first terminate the string, so that you can tell when it's finished. Otherwise there would be now way to know.

All standard functions build upon this definition, so if you call strlen to retrieve the str ing len gth, it will iterate through the given array until it finds the first 0-byte, which in your case would be the very first element.

Another thing you might need to know that only because you don't fill the remaining elements of your char[7] with a value, they actually do contain random undefined values.

Hope that helped.

How can I inspect element in chrome when right click is disabled?

Press F12 to Inspect Element and Ctrl+U to View Page Source

Python - Move and overwrite files and folders

This will go through the source directory, create any directories that do not already exist in destination directory, and move files from source to the destination directory:

import os
import shutil

root_src_dir = 'Src Directory\\'
root_dst_dir = 'Dst Directory\\'

for src_dir, dirs, files in os.walk(root_src_dir):
    dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1)
    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)
    for file_ in files:
        src_file = os.path.join(src_dir, file_)
        dst_file = os.path.join(dst_dir, file_)
        if os.path.exists(dst_file):
            # in case of the src and dst are the same file
            if os.path.samefile(src_file, dst_file):
                continue
            os.remove(dst_file)
        shutil.move(src_file, dst_dir)

Any pre-existing files will be removed first (via os.remove) before being replace by the corresponding source file. Any files or directories that already exist in the destination but not in the source will remain untouched.

How does the bitwise complement operator (~ tilde) work?

First we have to split the given digit into its binary digits and then reverse it by adding at the last binary digit.After this execution we have to give opposite sign to the previous digit that which we are finding the complent ~2=-3 Explanation: 2s binary form is 00000010 changes to 11111101 this is ones complement ,then complented 00000010+1=00000011 which is the binary form of three and with -sign I.e,-3

How to set value in @Html.TextBoxFor in Razor syntax?

I tried replacing value with Value and it worked out. It has set the value in input tag now.

Querying Datatable with where condition

Something like this...

var res = from row in myDTable.AsEnumerable()
where row.Field<int>("EmpID") == 5 &&
(row.Field<string>("EmpName") != "abc" ||
row.Field<string>("EmpName") != "xyz")
select row;

See also LINQ query on a DataTable

How to change the scrollbar color using css

Your css will only work in IE browser. And the css suggessted by hayk.mart will olny work in webkit browsers. And by using different css hacks you can't style your browsers scroll bars with a same result.

So, it is better to use a jQuery/Javascript plugin to achieve a cross browser solution with a same result.

Solution:

By Using jScrollPane a jQuery plugin, you can achieve a cross browser solution

See This Demo

Can not deserialize instance of java.lang.String out of START_OBJECT token

If you do not want to define a separate class for nested json , Defining nested json object as JsonNode should work ,for example :

{"id":2,"socket":"0c317829-69bf-43d6-b598-7c0c550635bb","type":"getDashboard","data":{"workstationUuid":"ddec1caa-a97f-4922-833f-632da07ffc11"},"reply":true}

@JsonProperty("data")
    private JsonNode data;

How do you count the elements of an array in java

Isn't it just: System.out.println(Array.length);? Because this is what it seems like you are looking for.

Laravel 5 not finding css files

<link rel="stylesheet" href="/css/bootstrap.min.css">if you are using laravel 5 or 6 you should create folder css and call it with

it works for me

How to delete a file from SD card?

Change for Android 4.4+

Apps are not allowed to write (delete, modify ...) to external storage except to their package-specific directories.

As Android documentation states:

"Apps must not be allowed to write to secondary external storage devices, except in their package-specific directories as allowed by synthesized permissions."

However nasty workaround exists (see code below). Tested on Samsung Galaxy S4, but this fix does't work on all devices. Also I wouldn’t count on this workaround being available in future versions of Android.

There is a great article explaining (4.4+) external storage permissions change.

You can read more about workaround here. Workaround source code is from this site.

public class MediaFileFunctions 
{
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static boolean deleteViaContentProvider(Context context, String fullname) 
    { 
      Uri uri=getFileUri(context,fullname); 

      if (uri==null) 
      {
         return false;
      }

      try 
      { 
         ContentResolver resolver=context.getContentResolver(); 

         // change type to image, otherwise nothing will be deleted 
         ContentValues contentValues = new ContentValues(); 
         int media_type = 1; 
         contentValues.put("media_type", media_type); 
         resolver.update(uri, contentValues, null, null); 

         return resolver.delete(uri, null, null) > 0; 
      } 
      catch (Throwable e) 
      { 
         return false; 
      } 
   }

   @TargetApi(Build.VERSION_CODES.HONEYCOMB)
   private static Uri getFileUri(Context context, String fullname) 
   {
      // Note: check outside this class whether the OS version is >= 11 
      Uri uri = null; 
      Cursor cursor = null; 
      ContentResolver contentResolver = null;

      try
      { 
         contentResolver=context.getContentResolver(); 
         if (contentResolver == null)
            return null;

         uri=MediaStore.Files.getContentUri("external"); 
         String[] projection = new String[2]; 
         projection[0] = "_id"; 
         projection[1] = "_data"; 
         String selection = "_data = ? ";    // this avoids SQL injection 
         String[] selectionParams = new String[1]; 
         selectionParams[0] = fullname; 
         String sortOrder = "_id"; 
         cursor=contentResolver.query(uri, projection, selection, selectionParams, sortOrder); 

         if (cursor!=null) 
         { 
            try 
            { 
               if (cursor.getCount() > 0) // file present! 
               {   
                  cursor.moveToFirst(); 
                  int dataColumn=cursor.getColumnIndex("_data"); 
                  String s = cursor.getString(dataColumn); 
                  if (!s.equals(fullname)) 
                     return null; 
                  int idColumn = cursor.getColumnIndex("_id"); 
                  long id = cursor.getLong(idColumn); 
                  uri= MediaStore.Files.getContentUri("external",id); 
               } 
               else // file isn't in the media database! 
               {   
                  ContentValues contentValues=new ContentValues(); 
                  contentValues.put("_data",fullname); 
                  uri = MediaStore.Files.getContentUri("external"); 
                  uri = contentResolver.insert(uri,contentValues); 
               } 
            } 
            catch (Throwable e) 
            { 
               uri = null; 
            }
            finally
            {
                cursor.close();
            }
         } 
      } 
      catch (Throwable e) 
      { 
         uri=null; 
      } 
      return uri; 
   } 
}

ASP.NET MVC5/IIS Express unable to debug - Code Not Running

I have solved this issue for me. Try to change all Deny values to Allow in file %SYSTEM_DRIVE%\Program Files\IIS Express\AppServer\applicationhost.xml. Please, take into account what IIS Express Web Server you are using in Visual Studio Settings, 32 bit or 64 bit, that means I have to check the file in different folders. Then restart Visual Studio. I don't know about security issues for those config lines, so change them at your own risk, but it has solved my problem.

<section name="asp" overrideModeDefault="Allow" />
<section name="caching" overrideModeDefault="Allow" />
<section name="cgi" overrideModeDefault="Allow" />
<section name="defaultDocument" overrideModeDefault="Allow" />
<section name="directoryBrowse" overrideModeDefault="Allow" />
<section name="fastCgi" allowDefinition="AppHostOnly" overrideModeDefault="Allow" />
<section name="globalModules" allowDefinition="AppHostOnly" overrideModeDefault="Allow" />
<section name="handlers" overrideModeDefault="Allow" />
<section name="httpCompression" overrideModeDefault="Allow" />
<section name="httpErrors" overrideModeDefault="Allow" />
<section name="httpLogging" overrideModeDefault="Allow" />
<section name="httpProtocol" overrideModeDefault="Allow" />

etc.

Print "hello world" every X seconds

What he said. You can handle the exceptions however you like, but Thread.sleep(miliseconds); is the best route to take.

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

Upload failed You need to use a different version code for your APK because you already have one with version code 2

android:versionCode="28"

Your previous versionCode was 28. You should increment it by 1 to 29.

android:versionCode="29"

Presumably, your previous app versions were 1 through 28. By releasing with versionCode 3, you are conflicting with a previous version of your app that was already released with this versionCode.

Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?

To use arrow functions with function.prototype.call, I made a helper function on the object prototype:

  // Using
  // @func = function() {use this here} or This => {use This here}
  using(func) {
    return func.call(this, this);
  }

usage

  var obj = {f:3, a:2}
  .using(This => This.f + This.a) // 5

Edit

You don't NEED a helper. You could do:

var obj = {f:3, a:2}
(This => This.f + This.a).call(undefined, obj); // 5

error: Libtool library used but 'LIBTOOL' is undefined

For folks who ended up here and are using CYGWIN, install following packages in cygwin and re-run:

  • cygwin32-libtool
  • libtool
  • libtool-debuginfo

How can I tell jackson to ignore a property for which I don't have control over the source code?

Using Java Class

new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

Using Annotation

@JsonIgnoreProperties(ignoreUnknown=true)

Methods vs Constructors in Java

In Java, classes you write are Objects. Constructors construct those objects. For example if I have an Apple.class like so:

public class Apple {
    //instance variables
    String type; // macintosh, green, red, ...

    /**
     * This is the default constructor that gets called when you use
     * Apple a = new Apple(); which creates an Apple object named a.
     */

    public Apple() {
        // in here you initialize instance variables, and sometimes but rarely
        // do other functionality (at least with basic objects)
        this.type = "macintosh"; // the 'this' keyword refers to 'this' object. so this.type refers to Apple's 'type' instance variable.
    }

    /**
     * this is another constructor with a parameter. You can have more than one
     * constructor as long as they have different parameters. It creates an Apple
     * object when called using Apple a = new Apple("someAppleType");
     */
    public Apple(String t) {
        // when the constructor is called (i.e new Apple() ) this code is executed
        this.type = t;
    }

    /**
     * methods in a class are functions. They are whatever functionality needed
     * for the object
     */
    public String someAppleRelatedMethod(){
        return "hello, Apple class!";
    }

    public static void main(String[] args) {
        // construct an apple
        Apple a = new Apple("green");
        // 'a' is now an Apple object and has all the methods and
        // variables of the Apple class.
        // To use a method from 'a':
        String temp = a.someAppleRelatedMethod();
        System.out.println(temp);
        System.out.println("a's type is " + a.type);
    }
}

Hopefully I explained everything in the comments of the code, but here is a summary: Constructors 'construct' an object of type of the class. The constructor must be named the same thing as the class. They are mostly used for initializing instance varibales Methods are functionality of the objects.

Define static method in source-file with declaration in header-file in C++

Remove static keyword in method definition. Keep it just in your class definition.

static keyword placed in .cpp file means that a certain function has a static linkage, ie. it is accessible only from other functions in the same file.

Create an ArrayList of unique values

Create an Arraylist of unique values

You could use Set.toArray() method.

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

http://docs.oracle.com/javase/6/docs/api/java/util/Set.html

PostgreSQL: How to change PostgreSQL user password?

I believe the best way to change the password is simply to use:

\password

in the Postgres console.

Per ALTER USER documentation:

Caution must be exercised when specifying an unencrypted password with this command. The password will be transmitted to the server in cleartext, and it might also be logged in the client's command history or the server log. psql contains a command \password that can be used to change a role's password without exposing the cleartext password.

Note: ALTER USER is an alias for ALTER ROLE

How to set character limit on the_content() and the_excerpt() in wordpress

wp_trim_words() This function trims text to a certain number of words and returns the trimmed text.

$excerpt = wp_trim_words( get_the_content(), 40, '<a href="'.get_the_permalink().'">More Link</a>');

Get truncated string with specified width using mb_strimwidth() php function.

$excerpt = mb_strimwidth( strip_tags(get_the_content()), 0, 100, '...' );

Using add_filter() method of WordPress on the_content filter hook.

add_filter( "the_content", "limit_content_chr" );
function limit_content_chr( $content ){
    if ( 'post' == get_post_type() ) {
        return mb_strimwidth( strip_tags($content), 0, 100, '...' );
    } else {
        return $content;
    }
}

Using custom php function to limit content characters.

function limit_content_chr( $content, $limit=100 ) {
    return mb_strimwidth( strip_tags($content), 0, $limit, '...' );
}

// using above function in template tags
echo limit_content_chr( get_the_content(), 50 );

Cannot create cache directory .. or directory is not writable. Proceeding without cache in Laravel

When you installed composer pretty sure you used $ sudo command because of that the ~/.composer folder was created by the root.

Run this to fix the issue:

$ sudo chown -R $USER $HOME/.composer

class method generates "TypeError: ... got multiple values for keyword argument ..."

I want to add one more answer :

It happens when you try to pass positional parameter with wrong position order along with keyword argument in calling function.

there is difference between parameter and argument you can read in detail about here Arguments and Parameter in python

def hello(a,b=1, *args):
   print(a, b, *args)


hello(1, 2, 3, 4,a=12)

since we have three parameters :

a is positional parameter

b=1 is keyword and default parameter

*args is variable length parameter

so we first assign a as positional parameter , means we have to provide value to positional argument in its position order, here order matter. but we are passing argument 1 at the place of a in calling function and then we are also providing value to a , treating as keyword argument. now a have two values :

one is positional value: a=1

second is keyworded value which is a=12

Solution

We have to change hello(1, 2, 3, 4,a=12) to hello(1, 2, 3, 4,12) so now a will get only one positional value which is 1 and b will get value 2 and rest of values will get *args (variable length parameter)

additional information

if we want that *args should get 2,3,4 and a should get 1 and b should get 12

then we can do like this
def hello(a,*args,b=1): pass hello(1, 2, 3, 4,b=12)

Something more :

def hello(a,*c,b=1,**kwargs):
    print(b)
    print(c)
    print(a)
    print(kwargs)

hello(1,2,1,2,8,9,c=12)

output :

1

(2, 1, 2, 8, 9)

1

{'c': 12}

How can I align all elements to the left in JPanel?

The easiest way I've found to place objects on the left is using FlowLayout.

JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));

adding a component normally to this panel will place it on the left

Check if String contains only letters

First import Pattern :

import java.util.regex.Pattern;

Then use this simple code:

String s = "smith23";
if (Pattern.matches("[a-zA-Z]+",s)) { 
  // Do something
  System.out.println("Yes, string contains letters only");
}else{
  System.out.println("Nope, Other characters detected");    
}

This will output:

Nope, Other characters detected

UnsatisfiedDependencyException: Error creating bean with name

Check out the table structure of Client table, if there is a mismatch between table structure in db and the entity, you would get this error..

I had this error which was coming due to datatype mismatch of primary key between db table and the entity ...

Facebook Architecture

"Knowing about sites which handles such massive traffic gives lots of pointers for architects etc. to keep in mind certain stuff while designing new sites"

I think you can probably learn a lot from the design of Facebook, just as you can from the design of any successful large software system. However, it seems to me that you should not keep the current design of Facebook in mind when designing new systems.

Why do you want to be able to handle the traffic that Facebook has to handle? Odds are that you will never have to, no matter how talented a programmer you may be. Facebook itself was not designed from the start for such massive scalability, which is perhaps the most important lesson to learn from it.

If you want to learn about a non-trivial software system I can recommend the book "Dissecting a C# Application" about the development of the SharpDevelop IDE. It is out of print, but it is available for free online. The book gives you a glimpse into a real application and provides insights about IDEs which are useful for a programmer.

Differences between strong and weak in Objective-C

strong: assigns the incoming value to it, it will retain the incoming value and release the existing value of the instance variable

weak: will assign the incoming value to it without retaining it.

So the basic difference is the retaining of the new variable. Generaly you want to retain it but there are situations where you don't want to have it otherwise you will get a retain cycle and can not free the memory the objects. Eg. obj1 retains obj2 and obj2 retains obj1. To solve this kind of situation you use weak references.

Update a table using JOIN in SQL Server?

I had the same issue.. and you don't need to add a physical column.. cuz now you will have to maintain it.. what you can do is add a generic column in the select query:

EX:

select tb1.col1, tb1.col2, tb1.col3 ,
( 
select 'Match' from table2 as tbl2
where tbl1.col1 = tbl2.col1 and tab1.col2 = tbl2.col2
)  
from myTable as tbl1

remove duplicates from sql union

If you are using T-SQL then it appears from previous posts that UNION removes duplicates. But if you are not, you could use distinct. This doesn't quite feel right to me either but it could get you the result you are looking for

SELECT DISTINCT *
FROM
(
select * from calls
left join users a on calls.assigned_to= a.user_id
where a.dept = 4 
union
select * from calls
left join users r on calls.requestor_id= r.user_id
where r.dept = 4
)a

How to Clone Objects

MemberwiseClone is a good way to do a shallow copy as others have suggested. It is protected however, so if you want to use it without changing the class, you have to access it via reflection. Reflection however is slow. So if you are planning to clone a lot of objects it might be worthwhile to cache the result:

public static class CloneUtil<T>
{
    private static readonly Func<T, object> clone;

    static CloneUtil()
    {
        var cloneMethod = typeof(T).GetMethod("MemberwiseClone", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
        clone = (Func<T, object>)cloneMethod.CreateDelegate(typeof(Func<T, object>));
    }

    public static T ShallowClone(T obj) => (T)clone(obj);
}

public static class CloneUtil
{
    public static T ShallowClone<T>(this T obj) => CloneUtil<T>.ShallowClone(obj);
}

You can call it like this:

Person b = a.ShallowClone();

Remove an array element and shift the remaining ones

You can't achieve what you want with arrays. Use vectors instead, and read about the std::remove algorithm. Something like:

std::remove(array, array+5, 3)

will work on your array, but it will not shorten it (why -- because it's impossible). With vectors, it'd be something like

v.erase(std::remove(v.begin(), v.end(), 3), v.end())

Ways to save enums in database

You can use an extra value in the enum constant that can survive both name changes and resorting of the enums:

public enum MyEnum {
    MyFirstValue(10),
    MyFirstAndAHalfValue(15),
    MySecondValue(20);

    public int getId() {
        return id;
    }
    public static MyEnum of(int id) {
        for (MyEnum e : values()) {
            if (id == e.id) {
                return e;
            }
        }
        return null;
    }
    MyEnum(int id) {
        this.id = id;
    }
    private final int id;
}

To get the id from the enum:

int id = MyFirstValue.getId();

To get the enum from an id:

MyEnum e = MyEnum.of(id);

I suggest using values with no meaning to avoid confusion if the enum names have to be changed.

In the above example, I've used some variant of "Basic row numbering" leaving spaces so the numbers will likely stay in the same order as the enums.

This version is faster than using a secondary table, but it makes the system more dependent on code and source code knowledge.

To remedy that, you can set up a table with the enum ids in the database as well. Or go the other way and pick ids for the enums from a table as you add rows to it.

Sidenote: Always verify that you are not designing something that should be stored in a database table and maintained as a regular object though. If you can imagine that you have to add new constants to the enum at this point, when you are setting it up, that's an indication you may be better off creating a regular object and a table instead.

Javascript onload not working

There's nothing wrong with include file in head. It seems you forgot to add;. Please try this one:

<body onload="imageRefreshBig();">

But as per my knowledge semicolons are optional. You can try with ; but better debug code and see if chrome console gives any error.

I hope this helps.

Java using scanner enter key pressed

This works using java.util.Scanner and will take multiple "enter" keystrokes:

    Scanner scanner = new Scanner(System.in);
    String readString = scanner.nextLine();
    while(readString!=null) {
        System.out.println(readString);

        if (readString.isEmpty()) {
            System.out.println("Read Enter Key.");
        }

        if (scanner.hasNextLine()) {
            readString = scanner.nextLine();
        } else {
            readString = null;
        }
    }

To break it down:

Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();

These lines initialize a new Scanner that is reading from the standard input stream (the keyboard) and reads a single line from it.

    while(readString!=null) {
        System.out.println(readString);

While the scanner is still returning non-null data, print each line to the screen.

        if (readString.isEmpty()) {
            System.out.println("Read Enter Key.");
        }

If the "enter" (or return, or whatever) key is supplied by the input, the nextLine() method will return an empty string; by checking to see if the string is empty, we can determine whether that key was pressed. Here the text Read Enter Key is printed, but you could perform whatever action you want here.

        if (scanner.hasNextLine()) {
            readString = scanner.nextLine();
        } else {
            readString = null;
        }

Finally, after printing the content and/or doing something when the "enter" key is pressed, we check to see if the scanner has another line; for the standard input stream, this method will "block" until either the stream is closed, the execution of the program ends, or further input is supplied.

did you register the component correctly? For recursive components, make sure to provide the "name" option

In my case (quasar and command quasar dev for testing), I just forgot to restart dev Quasar command.

It seemed to me that components was automatically loaded when any change was done. But in this case, I reused component in another page and I got this message.

how to use Spring Boot profiles

I'm not sure I fully understand the question but I'll attempt to answer by providing a few details about profiles in Spring Boot.

For your #1 example, according to the docs you can select the profile using the Spring Boot Maven plugin using -Drun.profiles.

Edit: For Spring Boot 2.0+ run has been renamed to spring-boot.run and run.profiles has been renamed to spring-boot.run.profiles

mvn spring-boot:run -Dspring-boot.run.profiles=dev

https://docs.spring.io/spring-boot/docs/2.0.1.RELEASE/maven-plugin/examples/run-profiles.html

From your #2 example, you are defining the active profile after the name of the jar. You need to provide the JVM argument before the name of the jar you are running.

java -jar -Dspring.profiles.active=dev XXX.jar

General info:

You mention that you have both an application.yml and a application-dev.yml. Running with the dev profile will actually load both config files. Values from application-dev.yml will override the same values provided by application.yml but values from both yml files will be loaded.

There are also multiple ways to define the active profile.

You can define them as you did, using -Dspring.profiles.active when running your jar. You can also set the profile using a SPRING_PROFILES_ACTIVE environment variable or a spring.profiles.active system property.

More info can be found here: https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto-set-active-spring-profiles

Making href (anchor tag) request POST instead of GET?

Using jQuery it is very simple assuming the URL you wish to post to is on the same server or has implemented CORS

$(function() {
  $("#employeeLink").on("click",function(e) {
    e.preventDefault(); // cancel the link itself
    $.post(this.href,function(data) {
      $("#someContainer").html(data);
    });
  });
});

If you insist on using frames which I strongly discourage, have a form and submit it with the link

<form action="employee.action" method="post" target="myFrame" id="myForm"></form>

and use (in plain JS)

 window.addEventListener("load",function() {
   document.getElementById("employeeLink").addEventListener("click",function(e) {
     e.preventDefault(); // cancel the link
     document.getElementById("myForm").submit(); // but make sure nothing has name or ID="submit"
   });
 });

Without a form we need to make one

 window.addEventListener("load",function() {
   document.getElementById("employeeLink").addEventListener("click",function(e) {
     e.preventDefault(); // cancel the actual link
     var myForm = document.createElement("form");
     myForm.action=this.href;// the href of the link
     myForm.target="myFrame";
     myForm.method="POST";
     myForm.submit();
   });
 });

SSH to Vagrant box in Windows?

very simple, once you install Vagrant manager and virtual box, try installing cygwin on windows but while installing cygwin, make sure to select the SSH package, VIM package which will enable your system to login to your VM from cygwin after spinning up your machine through vagrant.

Bootstrap close responsive menu "on click"

I really liked Jake Taylor's idea of doing it without additional JavaScript and taking advantage of Bootstrap's collapse toggle. I found you can fix the "flickering" issue present when the menu isn't in collapsed mode by modifying the data-target selector slightly to include the in class. So it looks like this:

<li><a href="#Products" data-toggle="collapse" data-target=".navbar-collapse.in">Products</a></li>

I didn't test it with nested dropdowns/menus, so YMMV.

How to "flatten" a multi-dimensional array to simple one in PHP?

Another method from PHP's user comments (simplified) and here:

function array_flatten_recursive($array) { 
   if (!$array) return false;
   $flat = array();
   $RII = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
   foreach ($RII as $value) $flat[] = $value;
   return $flat;
}

The big benefit of this method is that it tracks the depth of the recursion, should you need that while flattening.
This will output:

$array = array( 
    'A' => array('B' => array( 1, 2, 3)), 
    'C' => array(4, 5) 
); 
print_r(array_flatten_recursive($array)); 

#Returns: 
Array ( 
    [0] => 1 
    [1] => 2 
    [2] => 3 
    [3] => 4 
    [4] => 5 
)

How to use auto-layout to move other views when a view is hidden?

Just use UIStackView and everything will be work fine. No need to worry about other constraint, UIStackView will handle the space automatically.

Using two CSS classes on one element

If you want to apply styles only to an element which is its parents' first child, is it better to use :first-child pseudo-class

.social:first-child{
    border-bottom: dotted 1px #6d6d6d;
    padding-top: 0;
}
.social{
    border: 0;
    width: 330px;
    height: 75px;
    float: right;
    text-align: left;
    padding: 10px 0;
}

Then, the rule .social has both common styles and the last element's styles.

And .social:first-child overrides them with first element's styles.

You could also use :last-child selector, but :first-childis more supported by old browsers: see https://developer.mozilla.org/en-US/docs/CSS/:first-child#Browser_compatibility and https://developer.mozilla.org/es/docs/CSS/:last-child#Browser_compatibility.

How to print current date on python3?

The following seems to work:

import datetime
print (datetime.datetime.now().strftime("%y"))

The datetime.data object that it wants is on the "left" of the dot rather than the right. You need an instance of the datetime to call the method on, which you get through now()

Python dictionary : TypeError: unhashable type: 'list'

It works fine : http://codepad.org/5KgO0b1G, your aSourceDictionary variable may have other datatype than dict

aSourceDictionary = { 'abc' : [1,2,3] , 'ccd' : [4,5] }
aTargetDictionary = {}
for aKey in aSourceDictionary:
        aTargetDictionary[aKey] = []
        aTargetDictionary[aKey].extend(aSourceDictionary[aKey])
print aTargetDictionary

Oracle insert if not exists statement

Another approach would be to leverage the INSERT ALL syntax from oracle,

INSERT ALL 
    INTO table1(email, campaign_id) VALUES (email, campaign_id)
WITH source_data AS
 (SELECT '[email protected]' email,100 campaign_id
  FROM   dual
  UNION ALL
  SELECT '[email protected]' email,200 campaign_id
  FROM   dual)      
SELECT email
      ,campaign_id
FROM   source_data src
WHERE  NOT EXISTS (SELECT 1
        FROM   table1 dest
        WHERE  src.email = dest.email
        AND    src.campaign_id = dest.campaign_id);

INSERT ALL also allow us to perform a conditional insert into multiple tables based on a sub query as source.

There are some really clean and nice examples are there to refer.

  1. oracletutorial.com
  2. oracle-base.com/

'Found the synthetic property @panelState. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.'

My problem was that my @angular/platform-browser was on version 2.3.1

npm install @angular/platform-browser@latest --save

Upgrading to 4.4.6 did the trick and added /animations folder under node_modules/@angular/platform-browser

How to style a div to be a responsive square?

It is as easy as specifying a padding bottom the same size as the width in percent. So if you have a width of 50%, just use this example below

id or class{
    width: 50%;
    padding-bottom: 50%;
}

Here is a jsfiddle http://jsfiddle.net/kJL3u/2/

Edited version with responsive text: http://jsfiddle.net/kJL3u/394

How to install Laravel's Artisan?

Explanation: When you install a new laravel project on your folder(for example myfolder) using the composer, it installs the complete laravel project inside your folder(myfolder/laravel) than artisan is inside laravel.that's, why you see an error,

Could not open input file: artisan

Solution: You have to go inside by command prompt to that location or move laravel files inside your folder.

decompiling DEX into Java sourcecode

Since no one mentioned this, there's one more tool: DED homepage

Install how-to and some explanations: Installation.

It was used in a quite interesting study of the security of top market apps(not really related, just if you're curious): A Survey of Android Application Security

Does "display:none" prevent an image from loading?

Hi guys I was struggling with the same issue, how to not load an image on mobile.

But I figured out a good solution. First make an img tag and then load a blank svg in the src attribute. Now you can set your URL to the image as an inline style with content: url('link to your image');. Now wrap your img tag in a wrapper of your choice.

<div class="test">
  <img src="data:image/svg+xml,%3Csvg%20xmlns=%22http://www.w3.org/2000/??svg%22/%3E" style="content:url('https://blog.prepscholar.com/hubfs/body_testinprogress.gif?t=1495225010554')">
</div>

  @media only screen and (max-width: 800px) {
      .test{
       display: none;
      }
    }

Set the wrapper to display none on the breakpoint where you dont want to load the image. The inline css of the img tag is now ignored since the style of an element wrapped in a wrapper with display none will be ignored, therefore the image is not loaded, until you reach a breakpoint where the wrapper has display block.

There you go, really easy way not to load an img on mobile breakpoint :)

Check out this codepen, for a working example: http://codepen.io/fennefoss/pen/jmXjvo

Javascript extends class

Douglas Crockford has some very good explanations of inheritance in JavaScript:

  1. prototypal inheritance: the 'natural' way to do things in JavaScript
  2. classical inheritance: closer to what you find in most OO languages, but kind of runs against the grain of JavaScript

python modify item in list, save back in list

You need to use the enumerate function: python docs

for place, item in enumerate(list):
    if "foo" in item:
        item = replace_all(item, replaceDictionary)
        list[place] = item
        print item

Also, it's a bad idea to use the word list as a variable, due to it being a reserved word in python.

Since you had problems with enumerate, an alternative from the itertools library:

for place, item in itertools.zip(itertools.count(0), list):
    if "foo" in item:
        item = replace_all(item, replaceDictionary)
        list[place] = item
        print item

Maven – Always download sources and javadocs

In my case the "settings.xml" solution didn't work so I use this command in order to download all the sources:

mvn dependency:sources

You also can use it with other maven commands, for example:

mvn clean install dependency:sources -Dmaven.test.skip=true

To download all documentation, use the following command:

mvn dependency:resolve -Dclassifier=javadoc

Angularjs - simple form submit

_x000D_
_x000D_
var app = angular.module( "myApp", [] );_x000D_
_x000D_
app.controller( "myCtrl", ["$scope", function($scope) {_x000D_
_x000D_
    $scope.submit_form = function(formData) {_x000D_
_x000D_
        $scope.formData = formData;_x000D_
_x000D_
        console.log(formData); // object_x000D_
        console.log(JSON.stringify(formData)); // string_x000D_
_x000D_
        $scope.form = {}; // clear ng-model form_x000D_
_x000D_
    }_x000D_
_x000D_
}] );
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="myCtrl">_x000D_
_x000D_
    <form ng-submit="submit_form(form)" >_x000D_
_x000D_
        Firstname: <input type="text" ng-model="form.firstname" /><br />_x000D_
        Lastname: <input type="text" ng-model="form.lastname" /><br />_x000D_
_x000D_
        <hr />_x000D_
_x000D_
        <input type="submit" value="Submit" />_x000D_
_x000D_
    </form>_x000D_
_x000D_
    <hr />          _x000D_
_x000D_
    <p>Firstname: {{ form.firstname }}</p>_x000D_
    <p>Lastname: {{ form.lastname }}</p>_x000D_
_x000D_
    <pre>Submit Form: {{ formData }} </pre>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Codepen

How to create nested directories using Mkdir in Golang?

An utility method like the following can be used to solve this.

import (
  "os"
  "path/filepath"
  "log"
)

func ensureDir(fileName string) {
  dirName := filepath.Dir(fileName)
  if _, serr := os.Stat(dirName); serr != nil {
    merr := os.MkdirAll(dirName, os.ModePerm)
    if merr != nil {
        panic(merr)
    }
  }
}



func main() {
  _, cerr := os.Create("a/b/c/d.txt")
  if cerr != nil {
    log.Fatal("error creating a/b/c", cerr)
  }
  log.Println("created file in a sub-directory.")
}

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

For Windows, first install the git base from here: https://git-scm.com/downloads

Next, set the environment variable:

  1. Press Windows+R and type sysdm.cpl
  2. Select advance -> Environment variable
  3. Select path-> edit the path and paste the below line:
C:\Program Files\Git\git-bash.exe

To test it, open the command window: press Windows+R, type cmd and then type ssh.

How to push a new folder (containing other folders and files) to an existing git repo?

You need to git add my_project to stage your new folder. Then git add my_project/* to stage its contents. Then commit what you've staged using git commit and finally push your changes back to the source using git push origin master (I'm assuming you wish to push to the master branch).

Eclipse error: "The import XXX cannot be resolved"

pom.xml

If it's a Maven project, go to pom.xml and remove all the dependency jars. Save it. Project will automatically build.

Then add dependency jars again (you can do Ctrl+Z). Save it. Project will automatically build and you won't see that error.

Where is body in a nodejs http.get response?

If you want to use .get you can do it like this

http.get(url, function(res){
    res.setEncoding('utf8');
    res.on('data', function(chunk){
        console.log(chunk);
    });

});

How to insert multiple rows from a single query using eloquent/fluent

It is really easy to do a bulk insert in Laravel with or without the query builder. You can use the following official approach.

Entity::upsert([
    ['name' => 'Pierre Yem Mback', 'city' => 'Eseka', 'salary' => 10000000],
    ['name' => 'Dial rock 360', 'city' => 'Yaounde', 'salary' => 20000000],
    ['name' => 'Ndibou La Menace', 'city' => 'Dakar', 'salary' => 40000000]
], ['name', 'city'], ['salary']);

Passing string to a function in C - with or without pointers?

The accepted convention of passing C-strings to functions is to use a pointer:

void function(char* name)

When the function modifies the string you should also pass in the length:

void function(char* name, size_t name_length)

Your first example:

char *functionname(char *string name[256])

passes an array of pointers to strings which is not what you need at all.

Your second example:

char functionname(char string[256])

passes an array of chars. The size of the array here doesn't matter and the parameter will decay to a pointer anyway, so this is equivalent to:

char functionname(char *string)

See also this question for more details on array arguments in C.

How do I parse a string into a number with Dart?

you can parse string with int.parse('your string value');.

Example:- int num = int.parse('110011'); print(num); // prints 110011 ;

java.time.format.DateTimeParseException: Text could not be parsed at index 21

If your input always has a time zone of "zulu" ("Z" = UTC), then you can use DateTimeFormatter.ISO_INSTANT (implicitly):

final Instant parsed = Instant.parse(dateTime);

If time zone varies and has the form of "+01:00" or "+01:00:00" (when not "Z"), then you can use DateTimeFormatter.ISO_OFFSET_DATE_TIME:

DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
final ZonedDateTime parsed = ZonedDateTime.parse(dateTime, formatter);

If neither is the case, you can construct a DateTimeFormatter in the same manner as DateTimeFormatter.ISO_OFFSET_DATE_TIME is constructed.


Your current pattern has several problems:

  • not using strict mode (ResolverStyle.STRICT);
  • using yyyy instead of uuuu (yyyy will not work in strict mode);
  • using 12-hour hh instead of 24-hour HH;
  • using only one digit S for fractional seconds, but input has three.

Remove trailing zeros

A very low level approach, but I belive this would be the most performant way by only using fast integer calculations (and no slow string parsing and culture sensitive methods):

public static decimal Normalize(this decimal d)
{
    int[] bits = decimal.GetBits(d);

    int sign = bits[3] & (1 << 31);
    int exp = (bits[3] >> 16) & 0x1f;

    uint a = (uint)bits[2]; // Top bits
    uint b = (uint)bits[1]; // Middle bits
    uint c = (uint)bits[0]; // Bottom bits

    while (exp > 0 && ((a % 5) * 6 + (b % 5) * 6 + c) % 10 == 0)
    {
        uint r;
        a = DivideBy10((uint)0, a, out r);
        b = DivideBy10(r, b, out r);
        c = DivideBy10(r, c, out r);
        exp--;
    }

    bits[0] = (int)c;
    bits[1] = (int)b;
    bits[2] = (int)a;
    bits[3] = (exp << 16) | sign;
    return new decimal(bits);
}

private static uint DivideBy10(uint highBits, uint lowBits, out uint remainder)
{
    ulong total = highBits;
    total <<= 32;
    total = total | (ulong)lowBits;

    remainder = (uint)(total % 10L);
    return (uint)(total / 10L);
}

Access restriction: Is not accessible due to restriction on required library ..\jre\lib\rt.jar

I ran into something similar, I think that the cause of the warning is Eclipse trying to discourage you from using the internal com.sun packages that are installed as part of your workspace JRE but which are not part of the public Java API.

As Justin says in his answer, changing your compiler settings can hide the warning. A more fine-grained approach is to modify your build path to explicitly allow access to the package in question:

  1. Open the Libraries tab of the Java Build Path project property window.
  2. Expand the JRE System Library entry.
  3. Select "Access rules" and hit the Edit button.
  4. Click the Add button in the resulting dialog.
  5. For the new access rule, set the resolution to Accessible and the pattern to "com/sun/xml/internal/**".

After adding this access rule, your project should build without these warning.

Referencing a string in a string array resource with xml

Unfortunately:

  • It seems you can not reference a single item from an array in values/arrays.xml with XML. Of course you can in Java, but not XML. There's no information on doing so in the Android developer reference, and I could not find any anywhere else.

  • It seems you can't use an array as a key in the preferences layout. Each key has to be a single value with it's own key name.

What I want to accomplish: I want to be able to loop through the 17 preferences, check if the item is checked, and if it is, load the string from the string array for that preference name.

Here's the code I was hoping would complete this task:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());  
ArrayAdapter<String> itemsArrayList = new ArrayAdapter<String>(getBaseContext(),   android.R.layout.simple_list_item_1);  
String[] itemNames = getResources().getStringArray(R.array.itemNames_array);  


for (int i = 0; i < 16; i++) {  
    if (prefs.getBoolean("itemKey[i]", true)) {  
        itemsArrayList.add(itemNames[i]);  
    }  
} 

What I did:

  • I set a single string for each of the items, and referenced the single strings in the . I use the single string reference for the preferences layout checkbox titles, and the array for my loop.

  • To loop through the preferences, I just named the keys like key1, key2, key3, etc. Since you reference a key with a string, you have the option to "build" the key name at runtime.

Here's the new code:

for (int i = 0; i < 16; i++) {  
        if (prefs.getBoolean("itemKey" + String.valueOf(i), true)) {  
        itemsArrayList.add(itemNames[i]);  
    }  
}

Best practice for Django project working directory structure

Here is what I follow on My system.

  1. All Projects: There is a projects directory in my home folder i.e. ~/projects. All the projects rest inside it.

  2. Individual Project: I follow a standardized structure template used by many developers called django-skel for individual projects. It basically takes care of all your static file and media files and all.

  3. Virtual environment: I have a virtualenvs folder inside my home to store all virtual environments in the system i.e. ~/virtualenvs . This gives me flexibility that I know what all virtual environments I have and can look use easily

The above 3 are the main partitions of My working environment.

All the other parts you mentioned are mostly dependent on project to project basis (i.e. you might use different databases for different projects). So they should reside in their individual projects.

How can I determine the current CPU utilization from the shell?

You can use top or ps commands to check the CPU usage.

using top : This will show you the cpu stats

top -b -n 1 |grep ^Cpu

using ps: This will show you the % cpu usage for each process.

ps -eo pcpu,pid,user,args | sort -r -k1 | less

Also, you can write a small script in bash or perl to read /proc/stat and calculate the CPU usage.

Going through a text file line by line in C

In addition to the other answers, on a recent C library (Posix 2008 compliant), you could use getline. See this answer (to a related question).

Make a div fill up the remaining width

Up-to-date solution (October 2014) : ready for fluid layouts


Introduction:

This solution is even simpler than the one provided by Leigh. It is actually based on it.

Here you can notice that the middle element (in our case, with "content__middle" class) does not have any dimensional property specified - no width, nor padding, nor margin related property at all - but only an overflow: auto; (see note 1).

The great advantage is that now you can specify a max-width and a min-width to your left & right elements. Which is fantastic for fluid layouts.. hence responsive layout :-)

note 1: versus Leigh's answer where you need to add the margin-left & margin-right properties to the "content__middle" class.


Code with non-fluid layout:

Here the left & right elements (with classes "content__left" and "content__right") have a fixed width (in pixels): hence called non-fluid layout.

Live Demo on http://jsbin.com/qukocefudusu/1/edit?html,css,output

<style>
    /*
     * [1] & [3] "floats" makes the 2 divs align themselves respectively right & left
     * [2] "overflow: auto;" makes this div take the remaining width
     */
    .content {
        width: 100%;
    }
    .content__left {
        width: 100px;
        float: left; /* [1] */
        background-color: #fcc;
    }
    .content__middle {
        background-color: #cfc;
        overflow: auto; /* [2] */
    }
    .content__right {
        width: 100px;
        float: right; /* [3] */
        background-color: #ccf;
    }
</style>

<div class="content">
    <div class="content__left">
        left div<br/>left div<br/>left div<br/>left div<br/>left div<br/>left div<br/>
    </div>
    <div class="content__right">
        right div<br/>right div<br/>right div<br/>right div<br/>
    </div>
    <div class="content__middle">
        middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br />bit taller
    </div>
</div>

Code with fluid layout:

Here the left & right elements (with classes "content__left" and "content__right") have a variable width (in percentages) but also a minimum and maximum width: hence called fluid layout.

Live Demo in a fluid layout with the max-width properties http://jsbin.com/runahoremuwu/1/edit?html,css,output

<style>
    /*
     * [1] & [3] "floats" makes the 2 divs align themselves respectively right & left
     * [2] "overflow: auto;" makes this div take the remaining width
     */
    .content { 
        width: 100%; 
    }
    .content__left { 
        width: 20%; 
        max-width: 170px;  
        min-width: 40px;  
        float: left; /* [1] */
        background-color: #fcc; 
     }
    .content__middle { 
        background-color: #cfc; 
        overflow: auto; /* [2] */
    }
    .content__right { 
        width: 20%; 
        max-width: 250px; 
        min-width: 80px; 
        float: right; /* [3] */
        background-color: #ccf; 
    }
</style>

<div class="content">
    <div class="content__left">
        max-width of 170px & min-width of 40px<br />left div<br/>left div<br/>left div<br/>left div<br/>left div<br/>left div<br/>
    </div>
    <div class="content__right">
        max-width of 250px & min-width of 80px<br />right div<br/>right div<br/>right div<br/>right div<br/>
    </div>
    <div class="content__middle">
        middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br />bit taller
    </div>
</div>

Browser Support

Tested on BrowserStack.com on the following web browsers:

  • IE7 to IE11
  • Ff 20, Ff 28
  • Safari 4.0 (windows XP), Safari 5.1 (windows XP)
  • Chrome 20, Chrome 25, Chrome 30, Chrome 33,
  • Opera 20

Pandas every nth row

I'd use iloc, which takes a row/column slice, both based on integer position and following normal python syntax. If you want every 5th row:

df.iloc[::5, :]

how to create a logfile in php?

Please check this code, it works fine for me.

$data = array('shopid'=>3,'version'=> 1,'value=>1');  //here $data is dummy varaible

error_log(print_r($data,true), 3, $_SERVER['DOCUMENT_ROOT']."/your-file-name.log");

//In $data we can mention the error messege and create the log

What does string::npos mean in this code?

Value of string::npos is 18446744073709551615. Its a value returned if there is no string found.

2D character array initialization in C

I think what you originally meant to do was to make an array only of characters, not of pointers:

char options[2][100];

options[0][0]='t';
options[0][1]='e';
options[0][2]='s';
options[0][3]='t';
options[0][4]='1';
options[0][5]='\0';  /* NUL termination of C string */

/* A standard C library function which copies strings. */
strcpy(options[1], "test2");

The code above shows two distinct methods of setting the character values in memory you have set aside to contain characters.

How do I style (css) radio buttons and labels?

For any CSS3-enabled browser you can use an adjacent sibling selector for styling your labels

input:checked + label {
    color: white;
}  

MDN's browser compatibility table says essentially all of the current, popular browsers (Chrome, IE, Firefox, Safari), on both desktop and mobile, are compatible.

Difference between angle bracket < > and double quotes " " while including header files in C++?

When you use angle brackets, the compiler searches for the file in the include path list. When you use double quotes, it first searches the current directory (i.e. the directory where the module being compiled is) and only then it'll search the include path list.

So, by convention, you use the angle brackets for standard includes and the double quotes for everything else. This ensures that in the (not recommended) case in which you have a local header with the same name as a standard header, the right one will be chosen in each case.

Convert sqlalchemy row object to python dict

A solution that works with inherited classes too:

from itertools import chain
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()


class Mixin(object):
    def as_dict(self):
        tables = [base.__table__ for base in self.__class__.__bases__ if base not in [Base, Mixin]]
        tables.append(self.__table__)
        return {c.name: getattr(self, c.name) for c in chain.from_iterable([x.columns for x in tables])}

bootstrap 4 row height

Use the sizing utility classes...

  • h-50 = height 50%
  • h-100 = height 100%

http://www.codeply.com/go/Y3nG0io2uE

 <div class="container">
        <div class="row">
            <div class="col-md-8 col-lg-6 B">
                <div class="card card-inverse card-primary">
                    <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
                </div>
            </div>
            <div class="col-md-4 col-lg-3 G">
                <div class="row h-100">
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse card-success h-100">

                        </div>
                    </div>
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse bg-success h-100">

                        </div>
                    </div>
                    <div class="col-md-12 h-50">
                        <div class="card card-inverse bg-danger h-100">

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the d-flex flex-column on the row, and h-100 on the child cols.

<div class="container">
    <div class="row">
        <div class="col-md-8 col-lg-6 B">
            <div class="card card-inverse card-primary">
                <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
            </div>
        </div>
        <div class="col-md-4 col-lg-3 G ">
            <div class="row d-flex flex-column h-100">
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-12 h-100">
                    <div class="card bg-danger h-100">

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

https://www.codeply.com/go/tgzFAH8vaW

How should I make my VBA code compatible with 64-bit Windows?

This work for me:

#If VBA7 And Win64 Then
    Private Declare PtrSafe Function ShellExecuteA Lib "Shell32.dll" _
        (ByVal hwnd As Long, _
        ByVal lpOperation As String, _
        ByVal lpFile As String, _
       ByVal lpParameters As String, _
        ByVal lpDirectory As String, _
        ByVal nShowCmd As Long) As Long
#Else

    Private Declare Function ShellExecuteA Lib "Shell32.dll" _
        (ByVal hwnd As Long, _
        ByVal lpOperation As String, _
        ByVal lpFile As String, _
        ByVal lpParameters As String, _
        ByVal lpDirectory As String, _
        ByVal nShowCmd As Long) As Long
#End If

Thanks Jon49 for insight.

How to get files in a relative path in C#

To make sure you have the application's path (and not just the current directory), use this:

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getcurrentprocess.aspx

Now you have a Process object that represents the process that is running.

Then use Process.MainModule.FileName:

http://msdn.microsoft.com/en-us/library/system.diagnostics.processmodule.filename.aspx

Finally, use Path.GetDirectoryName to get the folder containing the .exe:

http://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname.aspx

So this is what you want:

string folder = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\Archive\";
string filter = "*.zip";
string[] files = Directory.GetFiles(folder, filter);

(Notice that "\Archive\" from your question is now @"\Archive\": you need the @ so that the \ backslashes aren't interpreted as the start of an escape sequence)

Hope that helps!

good example of Javadoc

I use a small set of documentation patterns:

  • always documenting about thread-safety
  • always documenting immutability
  • javadoc with examples (like Formatter)
  • @Deprecation with WHY and HOW to replace the annotated element

How to dump only specific tables from MySQL?

If you're in local machine then use this command

/usr/local/mysql/bin/mysqldump -h127.0.0.1 --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

For remote machine, use below one

/usr/local/mysql/bin/mysqldump -h [remoteip] --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

How do I get 'date-1' formatted as mm-dd-yyyy using PowerShell?

I think this is only partially true. Changing the format seems to switch the date to a string object which then has no methods like AddDays to manipulate it. So to make this work, you have to switch it back to a date. For example:

Get-Date (Get-Date).AddDays(-1) -format D

What's the best way to store Phone number in Django models

I will describe what I use:

Validation: string contains more than 5 digits.

Cleaning: removing all non digits symbols, write in db only numbers. I'm lucky, because in my country (Russia) everybody has phone numbers with 10 digits. So I store in db only 10 diits. If you are writing multi-country application, then you should make a comprehensive validation.

Rendering: I write custom template tag to render it in template nicely. Or even render it like a picture - it is more safe to prevent sms spam.