Programs & Examples On #Icefaces

ICEfaces is a JSF component library. It offers an Ajax framework for developing and deploying rich enterprise applications.

Dealing with "java.lang.OutOfMemoryError: PermGen space" error

I've been butting my head against this problem while deploying and undeploying a complex web application too, and thought I'd add an explanation and my solution.

When I deploy an application on Apache Tomcat, a new ClassLoader is created for that app. The ClassLoader is then used to load all the application's classes, and on undeploy, everything's supposed to go away nicely. However, in reality it's not quite as simple.

One or more of the classes created during the web application's life holds a static reference which, somewhere along the line, references the ClassLoader. As the reference is originally static, no amount of garbage collecting will clean this reference up - the ClassLoader, and all the classes it's loaded, are here to stay.

And after a couple of redeploys, we encounter the OutOfMemoryError.

Now this has become a fairly serious problem. I could make sure that Tomcat is restarted after each redeploy, but that takes down the entire server, rather than just the application being redeployed, which is often not feasible.

So instead I've put together a solution in code, which works on Apache Tomcat 6.0. I've not tested on any other application servers, and must stress that this is very likely not to work without modification on any other application server.

I'd also like to say that personally I hate this code, and that nobody should be using this as a "quick fix" if the existing code can be changed to use proper shutdown and cleanup methods. The only time this should be used is if there's an external library your code is dependent on (In my case, it was a RADIUS client) that doesn't provide a means to clean up its own static references.

Anyway, on with the code. This should be called at the point where the application is undeploying - such as a servlet's destroy method or (the better approach) a ServletContextListener's contextDestroyed method.

//Get a list of all classes loaded by the current webapp classloader
WebappClassLoader classLoader = (WebappClassLoader) getClass().getClassLoader();
Field classLoaderClassesField = null;
Class clazz = WebappClassLoader.class;
while (classLoaderClassesField == null && clazz != null) {
    try {
        classLoaderClassesField = clazz.getDeclaredField("classes");
    } catch (Exception exception) {
        //do nothing
    }
    clazz = clazz.getSuperclass();
}
classLoaderClassesField.setAccessible(true);

List classes = new ArrayList((Vector)classLoaderClassesField.get(classLoader));

for (Object o : classes) {
    Class c = (Class)o;
    //Make sure you identify only the packages that are holding references to the classloader.
    //Allowing this code to clear all static references will result in all sorts
    //of horrible things (like java segfaulting).
    if (c.getName().startsWith("com.whatever")) {
        //Kill any static references within all these classes.
        for (Field f : c.getDeclaredFields()) {
            if (Modifier.isStatic(f.getModifiers())
                    && !Modifier.isFinal(f.getModifiers())
                    && !f.getType().isPrimitive()) {
                try {
                    f.setAccessible(true);
                    f.set(null, null);
                } catch (Exception exception) {
                    //Log the exception
                }
            }
        }
    }
}

classes.clear();

in a "using" block is a SqlConnection closed on return or exception?

Dispose simply gets called when you leave the scope of using. The intention of "using" is to give developers a guaranteed way to make sure that resources get disposed.

From MSDN:

A using statement can be exited either when the end of the using statement is reached or if an exception is thrown and control leaves the statement block before the end of the statement.

What's the difference between dependencies, devDependencies and peerDependencies in npm package.json file?

Dependencies vs dev dependencies

Dev dependencies are modules which are only required during development whereas dependencies are required at runtime. If you are deploying your application, dependencies has to be installed, or else your app simply will not work. Libraries that you call from your code that enables the program to run can be considered as dependencies.

Eg- React , React - dom

Dev dependency modules need not be installed in the production server since you are not gonna develop in that machine .compilers that covert your code to javascript , test frameworks and document generators can be considered as dev-dependencies since they are only required during development .

Eg- ESLint , Babel , webpack

@FYI,

mod-a
  dev-dependents:
    - mod-b
  dependents:
    - mod-c

mod-d
?  dev-dependents:
    - mod-e
  dependents:
    - mod-a

----

npm install mod-d

installed modules:
  - mod-d
  - mod-a
  - mod-c

----

checkout the mod-d code repository

npm install

installed modules:
  - mod-a
  - mod-c
  - mod-e

If you are publishing to npm, then it is important that you use the correct flag for the correct modules. If it is something that your npm module needs to function, then use the "--save" flag to save the module as a dependency. If it is something that your module doesn't need to function but it is needed for testing, then use the "--save-dev" flag.

# For dependent modules
?npm install dependent-module --save

?# For dev-dependent modules
np?m install development-module --save-dev

How to resolve conflicts in EGit

GIT has the most irritating way of resolving conflicts (Unlike svn where you can simply compare and do the changes). I strongly feel git has complex conflict resolution process. If I were to resolve, I would simply take another code from GIT as fresh, add my changes and commit them. It simple and not so process oriented.

Getting only response header from HTTP POST using curl

Maybe it is little bit of an extreme, but I am using this super short version:

curl -svo. <URL>

Explanation:

-v print debug information (which does include headers)

-o. send web page data (which we want to ignore) to a certain file, . in this case, which is a directory and is an invalid destination and makes the output to be ignored.

-s no progress bar, no error information (otherwise you would see Warning: Failed to create the file .: Is a directory)

warning: result always fails (in terms of error code, if reachable or not). Do not use in, say, conditional statements in shell scripting...

Removing NA observations with dplyr::filter()

If someone is here in 2020, after making all the pipes, if u pipe %>% na.exclude will take away all the NAs in the pipe!

How to split the name string in mysql?

There is no string split function in MySQL. so you have to create your own function. This will help you. More details at this link.

Function:

CREATE FUNCTION SPLIT_STR(
  x VARCHAR(255),
  delim VARCHAR(12),
  pos INT
)
RETURNS VARCHAR(255)
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
       LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
       delim, '');

Usage:

SELECT SPLIT_STR(string, delimiter, position)

Example:

SELECT SPLIT_STR('a|bb|ccc|dd', '|', 3) as third;

+-------+
| third |
+-------+
| ccc   |
+-------+

How to initialize log4j properly?

If you just get rid of everything (e.g. if you are in tests)

org.apache.log4j.BasicConfigurator.configure(new NullAppender());

Is String.Contains() faster than String.IndexOf()?

From a little reading, it appears that under the hood the String.Contains method simply calls String.IndexOf. The difference is String.Contains returns a boolean while String.IndexOf returns an integer with (-1) representing that the substring was not found.

I would suggest writing a little test with 100,000 or so iterations and see for yourself. If I were to guess, I'd say that IndexOf may be slightly faster but like I said it just a guess.

Jeff Atwood has a good article on strings at his blog. It's more about concatenation but may be helpful nonetheless.

Access to Image from origin 'null' has been blocked by CORS policy

For local development you could serve the files with a simple web server.

With Python installed, go into the folder where your project is served, like cd my-project/. And then use python -m SimpleHTTPServer which would make index.html and it's JavaScript files available at localhost:8000.

RecyclerView vs. ListView

RecyclerView was created as a ListView improvement, so yes, you can create an attached list with ListView control, but using RecyclerView is easier as it:

  1. Reuses cells while scrolling up/down - this is possible with implementing View Holder in the ListView adapter, but it was an optional thing, while in the RecycleView it's the default way of writing adapter.

  2. Decouples list from its container - so you can put list items easily at run time in the different containers (linearLayout, gridLayout) with setting LayoutManager.

Example:

mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
//or
mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
  1. Animates common list actions - Animations are decoupled and delegated to ItemAnimator.

There is more about RecyclerView, but I think these points are the main ones.

So, to conclude, RecyclerView is a more flexible control for handling "list data" that follows patterns of delegation of concerns and leaves for itself only one task - recycling items.

How to program a delay in Swift 3

I like one-line notation for GCD, it's more elegant:

    DispatchQueue.main.asyncAfter(deadline: .now() + 42.0) {
        // do stuff 42 seconds later
    }

Also, in iOS 10 we have new Timer methods, e.g. block initializer:

(so delayed action may be canceled)

    let timer = Timer.scheduledTimer(withTimeInterval: 42.0, repeats: false) { (timer) in
        // do stuff 42 seconds later
    }

Btw, keep in mind: by default, timer is added to the default run loop mode. It means timer may be frozen when the user is interacting with the UI of your app (for example, when scrolling a UIScrollView) You can solve this issue by adding the timer to the specific run loop mode:

RunLoop.current.add(timer, forMode: .common)

At this blog post you can find more details.

Is it possible to make desktop GUI application in .NET Core?

I'm working on a project that might help: https://github.com/gkmo/CarloSharp

The following application is written in .NET with the UI in HTML, JavaScript, and CSS (Angular).

Enter image description here

'Must Override a Superclass Method' Errors after importing a project into Eclipse

If nothing of the above helps, make sure you have a proper "Execution environment" selected, and not an "Alternate JRE".

To be found under:

Project -> Build Path -> Libraries

Select the JRE System Library and click Edit....

If "Alternate JRE ..." is selected, change it to a fitting "Execution Environment" like JavaSE-1.8 (jre1.8.0_60). No idea why, but this will solve it.

ActionBarActivity cannot resolve a symbol

If the same error occurs in ADT/Eclipse

Add Action Bar Sherlock library in your project.

Now, to remove the "import The import android.support.v7 cannot be resolved" error download a jar file named as android-support-v7-appcompat.jar and add it in your project lib folder.

This will surely removes your both errors.

How to compare dates in datetime fields in Postgresql?

Use Date convert to compare with date: Try This:

select * from table 
where TO_DATE(to_char(timespanColumn,'YYYY-MM-DD'),'YYYY-MM-DD') = to_timestamp('2018-03-26', 'YYYY-MM-DD')

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

You should replace WebDriver wb = new FirefoxDriver(); with driver = new FirefoxDriver(); in your @Before Annotation.

As you are accessing driver object with null or you can make wb reference variable as global variable.

How to set a Postgresql default value datestamp like 'YYYYMM'?

Right. Better to use a function:

CREATE OR REPLACE FUNCTION yyyymm() RETURNS text
    LANGUAGE 'plpgsql' AS $$
DECLARE
    retval text;
    m integer;
BEGIN
    retval := EXTRACT(year from current_timestamp);
    m := EXTRACT(month from current_timestamp);
    IF m < 10 THEN retval := retval || '0'; END IF;
    RETURN retval || m;
END $$;

SELECT yyyymm();

DROP TABLE foo;
CREATE TABLE foo (
    key             int PRIMARY KEY,
    colname text DEFAULT yyyymm()
    );
INSERT INTO foo (key) VALUES (0);
SELECT * FROM FOO;

This gives me

 key | colname 
-----+---------
   0 | 200905

Make sure you run createlang plpgsql from the Unix command line, if necessary.

How to use ClassLoader.getResources() correctly?

Here is code based on bestsss' answer:

    Enumeration<URL> en = getClass().getClassLoader().getResources(
            "META-INF");
    List<String> profiles = new ArrayList<>();
    while (en.hasMoreElements()) {
        URL url = en.nextElement();
        JarURLConnection urlcon = (JarURLConnection) (url.openConnection());
        try (JarFile jar = urlcon.getJarFile();) {
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                String entry = entries.nextElement().getName();
                System.out.println(entry);
            }
        }
    }

Can you use a trailing comma in a JSON object?

Simple, cheap, easy to read, and always works regardless of the specs.

$delimiter = '';
for ....  {
    print $delimiter.$whatever
    $delimiter = ',';
}

The redundant assignment to $delim is a very small price to pay. Also works just as well if there is no explicit loop but separate code fragments.

how to display none through code behind

I believe this should work:

login_div.Attributes.Add("style","display:none");

Escape double quotes in parameter

I'm calling powershell from cmd, and passing quotes and neither escapes here worked. The grave accent worked to escape double quotes on this Win 10 surface pro.

>powershell.exe "echo la`"" >> test
>type test
la"

Below are outputs I got for other characters to escape a double quote:

la\
la^
la
la~

Using another quote to escape a quote resulted in no quotes. As you can see, the characters themselves got typed, but didn't escape the double quotes.

Adjusting HttpWebRequest Connection Timeout in C#

Sorry for tacking on to an old thread, but I think something that was said above may be incorrect/misleading.

From what I can tell .Timeout is NOT the connection time, it is the TOTAL time allowed for the entire life of the HttpWebRequest and response. Proof:

I Set:

.Timeout=5000
.ReadWriteTimeout=32000

The connect and post time for the HttpWebRequest took 26ms

but the subsequent call HttpWebRequest.GetResponse() timed out in 4974ms thus proving that the 5000ms was the time limit for the whole send request/get response set of calls.

I didn't verify if the DNS name resolution was measured as part of the time as this is irrelevant to me since none of this works the way I really need it to work--my intention was to time out quicker when connecting to systems that weren't accepting connections as shown by them failing during the connect phase of the request.

For example: I'm willing to wait 30 seconds on a connection request that has a chance of returning a result, but I only want to burn 10 seconds waiting to send a request to a host that is misbehaving.

Environment variable substitution in sed

You can use other characters besides "/" in substitution:

sed "s#$1#$2#g" -i FILE

Examples of Algorithms which has O(1), O(n log n) and O(log n) complexities

The complexity of software application is not measured and is not written in big-O notation. It is only useful to measure algorithm complexity and to compare algorithms in the same domain. Most likely, when we say O(n), we mean that it's "O(n) comparisons" or "O(n) arithmetic operations". That means, you can't compare any pair of algorithms or applications.

What's the difference between emulation and simulation?

Here's an example - we recently developed a simulation model to measure the remote transmission response time of a yet-to-be-developed system. An emulation analysis would not have given us the answer in time to upgrade the bandwidth capacity so simulation was our approach. Because we were mostly interested in determining bandwidth needs, we cared primarily about transaction size and volume, not the processing of the system. The simulation model was on a stand-alone piece of software that was designed to model discrete-event processes. To summarize in response to your question, emulation is a type of simulation. But, in this case, simulation was NOT an emulation because it didn't fully represent the new system, only the size and volume of transactions.

Checking if a key exists in a JavaScript object?

Quick Answer

How do I check if a particular key exists in a JavaScript object or array? If a key doesn't exist and I try to access it, will it return false? Or throw an error?

Accessing directly a missing property using (associative) array style or object style will return an undefined constant.

The slow and reliable in operator and hasOwnProperty method

As people have already mentioned here, you could have an object with a property associated with an "undefined" constant.

 var bizzareObj = {valid_key:  undefined};

In that case, you will have to use hasOwnProperty or in operator to know if the key is really there. But, but at what price?

so, I tell you...

in operator and hasOwnProperty are "methods" that use the Property Descriptor mechanism in Javascript (similar to Java reflection in the Java language).

http://www.ecma-international.org/ecma-262/5.1/#sec-8.10

The Property Descriptor type is used to explain the manipulation and reification of named property attributes. Values of the Property Descriptor type are records composed of named fields where each field’s name is an attribute name and its value is a corresponding attribute value as specified in 8.6.1. In addition, any field may be present or absent.

On the other hand, calling an object method or key will use Javascript [[Get]] mechanism. That is a far way faster!

Benchmark

http://jsperf.com/checking-if-a-key-exists-in-a-javascript-array

Comparing key access in JS.

Using in operator
var result = "Impression" in array;

The result was

12,931,832 ±0.21% ops/sec      92% slower 
Using hasOwnProperty
var result = array.hasOwnProperty("Impression")

The result was

16,021,758 ±0.45% ops/sec     91% slower
Accessing elements directly (brackets style)
var result = array["Impression"] === undefined

The result was

168,270,439 ±0.13 ops/sec     0.02% slower 
Accessing elements directly (object style)
var result = array.Impression  === undefined;

The result was

168,303,172 ±0.20%     fastest

EDIT: What is the reason to assign to a property the undefined value?

That question puzzles me. In Javascript, there are at least two references for absent objects to avoid problems like this: null and undefined.

null is the primitive value that represents the intentional absence of any object value, or in short terms, the confirmed lack of value. On the other hand, undefined is an unknown value (not defined). If there is a property that will be used later with a proper value consider use null reference instead of undefined because in the initial moment the property is confirmed to lack value.

Compare:

var a = {1: null}; 
console.log(a[1] === undefined); // output: false. I know the value at position 1 of a[] is absent and this was by design, i.e.:  the value is defined. 
console.log(a[0] === undefined); // output: true. I cannot say anything about a[0] value. In this case, the key 0 was not in a[].

Advice

Avoid objects with undefined values. Check directly whenever possible and use null to initialize property values. Otherwise, use the slow in operator or hasOwnProperty() method.

EDIT: 12/04/2018 - NOT RELEVANT ANYMORE

As people have commented, modern versions of the Javascript engines (with firefox exception) have changed the approach for access properties. The current implementation is slower than the previous one for this particular case but the difference between access key and object is neglectable.

How can I right-align text in a DataGridView column?

you can edit all the columns at once by using this simple code via Foreach loop

        foreach (DataGridViewColumn item in datagridview1.Columns)
        {
            item.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
        }

Length of array in function argument

Best example is here

thanks #define SIZE 10

void size(int arr[SIZE])
{
    printf("size of array is:%d\n",sizeof(arr));
}

int main()
{
    int arr[SIZE];
    size(arr);
    return 0;
}

How to print something to the console in Xcode?

3 ways to do this:

In C Language (Command Line Tool) Works with Objective C, too:

printf("Hello World");

In Objective C:

NSLog(@"Hello, World!");

In Objective C with variables:

NSString * myString = @"Hello World";
NSLog(@"%@", myString);

In the code with variables, the variable created with class, NSString was outputted be NSLog. The %@ represents text as a variable.

CSS vertical-align: text-bottom;

if your text doesn't spill over two rows then you can do line-height: ; in your CSS, the more line-height you give, the lower on the container it will hold.

App store link for "rate/review this app"

For >= iOS8: (Simplified @EliBud's answer).

#define APP_STORE_ID 1108885113

- (void)rateApp{
    static NSString *const iOSAppStoreURLFormat = @"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=%d";

    NSURL *appStoreURL = [NSURL URLWithString:[NSString stringWithFormat:iOSAppStoreURLFormat, APP_STORE_ID]];

    if ([[UIApplication sharedApplication] canOpenURL:appStoreURL]) {
        [[UIApplication sharedApplication] openURL:appStoreURL];
    }
}

Python: Select subset from list based on index set

Matlab and Scilab languages offer a simpler and more elegant syntax than Python for the question you're asking, so I think the best you can do is to mimic Matlab/Scilab by using the Numpy package in Python. By doing this the solution to your problem is very concise and elegant:

from numpy import *
property_a = array([545., 656., 5.4, 33.])
property_b = array([ 1.2,  1.3, 2.3, 0.3])
good_objects = [True, False, False, True]
good_indices = [0, 3]
property_asel = property_a[good_objects]
property_bsel = property_b[good_indices]

Numpy tries to mimic Matlab/Scilab but it comes at a cost: you need to declare every list with the keyword "array", something which will overload your script (this problem doesn't exist with Matlab/Scilab). Note that this solution is restricted to arrays of number, which is the case in your example.

Change background position with jQuery

Sets new value for backgroundPosition on the carousel div when a li in the submenu div is hovered. Removes the backgroundPosition when hovering ends and resets backgroundPosition to old value.

$('#submenu li').hover(function() {
    if ($('#carousel').data('oldbackgroundPosition')==undefined) {
        $('#carousel').data('oldbackgroundPosition', $('#carousel').css('backgroundPosition'));
    }
    $('#carousel').css('backgroundPosition', [enternewvaluehere]);
},
function() {
    var reset = '';
    if ($('#carousel').data('oldbackgroundPosition') != undefined) {
        reset = $('#carousel').data('oldbackgroundPosition');
        $('#carousel').removeData('oldbackgroundPosition');
    }
    $('#carousel').css('backgroundPosition', reset);
});

Best way to get all selected checkboxes VALUES in jQuery

You want the :checkbox:checked selector and map to create an array of the values:

var checkedValues = $('input:checkbox:checked').map(function() {
    return this.value;
}).get();

If your checkboxes have a shared class it would be faster to use that instead, eg. $('.mycheckboxes:checked'), or for a common name $('input[name="Foo"]:checked')

- Update -

If you don't need IE support then you can now make the map() call more succinct by using an arrow function:

var checkedValues = $('input:checkbox:checked').map((i, el) => el.value).get();

How can I use a reportviewer control in an asp.net mvc 3 razor view?

the documentations refers to an ASP.NET application.
You can try and have a look at my answer here.
I have an example attached to my reply.
Another example for ASP.NET MVC3 can be found here.

Any tools to generate an XSD schema from an XML instance document?

If you have .Net installed, a tool to generate XSD schemas and classes is already included by default.
For me, the XSD tool is installed under the following structure. This may differ depending on your installation directory.

C:\Program Files\Microsoft Visual Studio 8\VC>xsd
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 2.0.50727.42]
Copyright (C) Microsoft Corporation. All rights reserved.

xsd.exe -
   Utility to generate schema or class files from given source.

xsd.exe <schema>.xsd /classes|dataset [/e:] [/l:] [/n:] [/o:] [/s] [/uri:]
xsd.exe <assembly>.dll|.exe [/outputdir:] [/type: [...]]
xsd.exe <instance>.xml [/outputdir:]
xsd.exe <schema>.xdr [/outputdir:]

Normally the classes and schemas that this tool generates work rather well, especially if you're going to be consuming them in a .Net language

I typically take the XML document that I'm after, push it through the XSD tool with the /o:<your path> flag to generate a schema (xsd) and then push the xsd file back through the tool using the /classes /L:VB (or CS) /o:<your path> flags to get classes that I can import and use in my day to day .Net projects

Load a bitmap image into Windows Forms using open file dialog

private void button1_Click(object sender, EventArgs e)
{
    OpenFileDialog open = new OpenFileDialog();
    if (open.ShowDialog() == DialogResult.OK)
        pictureBox1.Image = Bitmap.FromFile(open.FileName);
}

Two Radio Buttons ASP.NET C#

In order to make it work, you have to set property GroupName of both radio buttons to the same value:

<asp:RadioButton id="rbMetric" runat="server" GroupName="measurementSystem"></asp:RadioButton>
<asp:RadioButton id="rbUS" runat="server" GroupName="measurementSystem"></asp:RadioButton>

Personally, I prefer to use a RadioButtonList:

<asp:RadioButtonList ID="rblMeasurementSystem" runat="server">
    <asp:ListItem Text="Metric" Value="metric" />
    <asp:ListItem Text="US" Value="us" />
</asp:RadioButtonList>

How does C#'s random number generator work?

I was just wondering how the random number generator in C# works.

That's implementation-specific, but the wikipedia entry for pseudo-random number generators should give you some ideas.

I was also curious how I could make a program that generates random WHOLE INTEGER numbers from 1-100.

You can use Random.Next(int, int):

Random rng = new Random();
for (int i = 0; i < 10; i++)
{
    Console.WriteLine(rng.Next(1, 101));
}

Note that the upper bound is exclusive - which is why I've used 101 here.

You should also be aware of some of the "gotchas" associated with Random - in particular, you should not create a new instance every time you want to generate a random number, as otherwise if you generate lots of random numbers in a short space of time, you'll see a lot of repeats. See my article on this topic for more details.

Does the join order matter in SQL?

for regular Joins, it doesn't. TableA join TableB will produce the same execution plan as TableB join TableA (so your C and D examples would be the same)

for left and right joins it does. TableA left Join TableB is different than TableB left Join TableA, BUT its the same than TableB right Join TableA

How to insert an object in an ArrayList at a specific position

Here is the simple arraylist example for insertion at specific index

ArrayList<Integer> str=new ArrayList<Integer>();
    str.add(0);
    str.add(1);
    str.add(2);
    str.add(3); 
    //Result = [0, 1, 2, 3]
    str.add(1, 11);
    str.add(2, 12);
    //Result = [0, 11, 12, 1, 2, 3]

Input from the keyboard in command line application

edit As of Swift 2.2 the standard library includes readLine. I'll also note Swift switched to markdown doc comments. Leaving my original answer for historical context.

Just for completeness, here is a Swift implementation of readln I've been using. It has an optional parameter to indicate the maximum number of bytes you want to read (which may or may not be the length of the String).

This also demonstrates the proper use of swiftdoc comments - Swift will generate a <project>.swiftdoc file and Xcode will use it.

///reads a line from standard input
///
///:param: max specifies the number of bytes to read
///
///:returns: the string, or nil if an error was encountered trying to read Stdin
public func readln(max:Int = 8192) -> String? {
    assert(max > 0, "max must be between 1 and Int.max")

    var buf:Array<CChar> = []
    var c = getchar()
    while c != EOF && c != 10 && buf.count < max {
        buf.append(CChar(c))
        c = getchar()
    }

    //always null terminate
    buf.append(CChar(0))

    return buf.withUnsafeBufferPointer { String.fromCString($0.baseAddress) }
}

PYTHONPATH vs. sys.path

I hate PYTHONPATH. I find it brittle and annoying to set on a per-user basis (especially for daemon users) and keep track of as project folders move around. I would much rather set sys.path in the invoke scripts for standalone projects.

However sys.path.append isn't the way to do it. You can easily get duplicates, and it doesn't sort out .pth files. Better (and more readable): site.addsitedir.

And script.py wouldn't normally be the more appropriate place to do it, as it's inside the package you want to make available on the path. Library modules should certainly not be touching sys.path themselves. Instead, you'd normally have a hashbanged-script outside the package that you use to instantiate and run the app, and it's in this trivial wrapper script you'd put deployment details like sys.path-frobbing.

Running SSH Agent when starting Git Bash on Windows

Put this in your ~/.bashrc (or a file that's source'd from it) which will stop it from being run multiple times unnecessarily per shell:

if [ -z "$SSH_AGENT_PID" ]; then
        eval `ssh-agent -s`
fi

And then add "AddKeysToAgent yes" to ~/.ssh/config:

Host *
    AddKeysToAgent yes

ssh to your server (or git pull) normally and you'll only be asked for password/passphrase once per session.

MySQL : ERROR 1215 (HY000): Cannot add foreign key constraint

The syntax of FOREIGN KEY for CREATE TABLE is structured as follows:

FOREIGN KEY (index_col_name)
        REFERENCES table_name (index_col_name,...)

So your MySQL DDL should be:

 create table course (
        course_id varchar(7),
        title varchar(50),
        dept_name varchar(20),
        credits numeric(2 , 0 ),
        primary key (course_id),
        FOREIGN KEY (dept_name)
            REFERENCES department (dept_name)
    );

Also, in the department table dept_name should be VARCHAR(20)

More information can be found in the MySQL documentation

Is it acceptable and safe to run pip install under sudo?

Use a virtual environment:

$ virtualenv myenv
.. some output ..
$ source myenv/bin/activate
(myenv) $ pip install what-i-want

You only use sudo or elevated permissions when you want to install stuff for the global, system-wide Python installation.

It is best to use a virtual environment which isolates packages for you. That way you can play around without polluting the global python install.

As a bonus, virtualenv does not need elevated permissions.

Passing environment-dependent variables in webpack

To add to the bunch of answers personally I prefer the following:

const webpack = require('webpack');
const prod = process.argv.indexOf('-p') !== -1;

module.exports = {
  ...
  plugins: [
    new webpack.DefinePlugin({
      process: {
        env: {
          NODE_ENV: prod? `"production"`: '"development"'
        }
      }
    }),
    ...
  ]
};

Using this there is no funky env variable or cross-platform problems (with env vars). All you do is run the normal webpack or webpack -p for dev or production respectively.

Reference: Github issue

How do I create an empty array/matrix in NumPy?

For creating an empty NumPy array without defining its shape:

  1. arr = np.array([])
    

    (this is preferred, because you know you will be using this as a NumPy array)

  2.  arr = []   # and use it as NumPy array later by converting it
     arr = np.asarray(arr)
    

NumPy converts this to np.ndarray type afterward, without extra [] 'dimension'.

How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

If you really want a copy of the underlying bytes of a string, you can use a function like the one that follows. However, you shouldn't please read on to find out why.

[DllImport(
        "msvcrt.dll",
        EntryPoint = "memcpy",
        CallingConvention = CallingConvention.Cdecl,
        SetLastError = false)]
private static extern unsafe void* UnsafeMemoryCopy(
    void* destination,
    void* source,
    uint count);

public static byte[] GetUnderlyingBytes(string source)
{
    var length = source.Length * sizeof(char);
    var result = new byte[length];
    unsafe
    {
        fixed (char* firstSourceChar = source)
        fixed (byte* firstDestination = result)
        {
            var firstSource = (byte*)firstSourceChar;
            UnsafeMemoryCopy(
                firstDestination,
                firstSource,
                (uint)length);
        }
    }

    return result;
}

This function will get you a copy of the bytes underlying your string, pretty quickly. You'll get those bytes in whatever way they are encoding on your system. This encoding is almost certainly UTF-16LE but that is an implementation detail you shouldn't have to care about.

It would be safer, simpler and more reliable to just call,

System.Text.Encoding.Unicode.GetBytes()

In all likelihood this will give the same result, is easier to type, and the bytes will round-trip, as well as a byte representation in Unicode can, with a call to

System.Text.Encoding.Unicode.GetString()

How to exit git log or git diff

In this case, as snarly suggested, typing q is the intended way to quit git log (as with most other pagers or applications that use pagers).

However normally, if you just want to abort a command that is currently executing, you can try ctrl+c (doesn't seem to work for git log, however) or ctrl+z (although in bash, ctrl-z will freeze the currently running foreground process, which can then be thawed as a background process with the bg command).

Python dictionary : TypeError: unhashable type: 'list'

This is indeed rather odd.

If aSourceDictionary were a dictionary, I don't believe it is possible for your code to fail in the manner you describe.

This leads to two hypotheses:

  1. The code you're actually running is not identical to the code in your question (perhaps an earlier or later version?)

  2. aSourceDictionary is in fact not a dictionary, but is some other structure (for example, a list).

Java heap terminology: young, old and permanent generations?

This seems like a common misunderstanding. In Oracle's JVM, the permanent generation is not part of the heap. It's a separate space for class definitions and related data. In Java 6 and earlier, interned strings were also stored in the permanent generation. In Java 7, interned strings are stored in the main object heap.

Here is a good post on permanent generation.

I like the descriptions given for each space in Oracle's guide on JConsole:

For the HotSpot Java VM, the memory pools for serial garbage collection are the following.

  • Eden Space (heap): The pool from which memory is initially allocated for most objects.
  • Survivor Space (heap): The pool containing objects that have survived the garbage collection of the Eden space.
  • Tenured Generation (heap): The pool containing objects that have existed for some time in the survivor space.
  • Permanent Generation (non-heap): The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas.
  • Code Cache (non-heap): The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code.

Java uses generational garbage collection. This means that if you have an object foo (which is an instance of some class), the more garbage collection events it survives (if there are still references to it), the further it gets promoted. It starts in the young generation (which itself is divided into multiple spaces - Eden and Survivor) and would eventually end up in the tenured generation if it survived long enough.

how to check if object already exists in a list

Simply use Contains method. Note that it works based on the equality function Equals

bool alreadyExist = list.Contains(item);

https connection using CURL from command line

I actually had this kind of problem and I solve it by these steps:

  1. Get the bundle of root CA certificates from here: https://curl.haxx.se/ca/cacert.pem and save it on local

  2. Find the php.ini file

  3. Set the curl.cainfo to be the path of the certificates. So it will something like:

curl.cainfo = /path/of/the/keys/cacert.pem

How can I truncate a string to the first 20 words in PHP?

function getShortString($string,$wordCount,$etc = true) 
{
     $expString = explode(' ',$string);
     $wordsInString = count($expString);
     if($wordsInString >= $wordCount )
     {
         $shortText = '';
         for($i=0; $i < $wordCount-1; $i++)
         {
             $shortText .= $expString[$i].' ';
         }
         return  $etc ? $shortText.='...' : $shortText; 
     }
     else return $string;
} 

Maven Java EE Configuration Marker with Java Server Faces 1.2

Eclipse is buggy on factes screen and at times doesn't update the config files in workspace. There are two options one can try :

  1. Go to org.eclipse.wst.common.project.facet.core.xml file located inside .settings folder of eclipse project. Go and manually delete the JSF facet entry. you can also update other facets as well.

  2. Right click project and go to properties->Maven-->Java EE Integeration. choose options : enable project specific settings, Enable Java EE configuration, Maven archiver generates files under the build directory

Apache default VirtualHost

I had the same issue. I could fix it by adding the following in httpd.conf itself before the IncludeOptional directives for virtual hosts. Now localhost and the IP 192.168.x.x both points to the default test page of Apache. All other virtual hosts are working as expected.

<VirtualHost *:80>
    DocumentRoot /var/www/html
</VirtualHost>

Reference: https://httpd.apache.org/docs/2.4/vhosts/name-based.html#defaultvhost

Newline in markdown table?

Use <br/> . For example:

Change log, upgrade version

Dependency | Old version | New version |
---------- | ----------- | -----------
Spring Boot | `1.3.5.RELEASE` | `1.4.3.RELEASE`
Gradle | `2.13` | `3.2.1`
Gradle plugin <br/>`com.gorylenko.gradle-git-properties` | `1.4.16` | `1.4.17`
`org.webjars:requirejs` | `2.2.0` | `2.3.2`
`org.webjars.npm:stompjs` | `2.3.3` | `2.3.3`
`org.webjars.bower:sockjs-client` | `1.1.0` | `1.1.1`

URL: https://github.com/donhuvy/lsb/wiki

Using Mockito to stub and execute methods for testing

You've nearly got it. The problem is that the Class Under Test (CUT) is not built for unit testing - it has not really been TDD'd.

Think of it like this…

  • I need to test a function of a class - let's call it myFunction
  • That function makes a call to a function on another class/service/database
  • That function also calls another method on the CUT

In the unit test

  • Should create a concrete CUT or @Spy on it
  • You can @Mock all of the other class/service/database (i.e. external dependencies)
  • You could stub the other function called in the CUT but it is not really how unit testing should be done

In order to avoid executing code that you are not strictly testing, you could abstract that code away into something that can be @Mocked.

In this very simple example, a function that creates an object will be difficult to test

public void doSomethingCool(String foo) {
    MyObject obj = new MyObject(foo);

    // can't do much with obj in a unit test unless it is returned
}

But a function that uses a service to get MyObject is easy to test, as we have abstracted the difficult/impossible to test code into something that makes this method testable.

public void doSomethingCool(String foo) {
    MyObject obj = MyObjectService.getMeAnObject(foo);
}

as MyObjectService can be mocked and also verified that .getMeAnObject() is called with the foo variable.

How to query data out of the box using Spring data JPA by both Sort and Pageable?

Spring Pageable has a Sort included. So if your request has the values it will return a sorted pageable.

request: domain.com/endpoint?sort=[FIELDTOSORTBY]&[FIELDTOSORTBY].dir=[ASC|DESC]&page=0&size=20

That should return a sorted pageable by field provided in the provided order.

Foreign Key naming scheme

This is probably over-kill, but it works for me. It helps me a great deal when I am dealing with VLDBs especially. I use the following:

CONSTRAINT [FK_ChildTableName_ChildColName_ParentTableName_PrimaryKeyColName]

Of course if for some reason you are not referencing a primary key you must be referencing a column contained in a unique constraint, in this case:

CONSTRAINT [FK_ChildTableName_ChildColumnName_ParentTableName_ColumnInUniqueConstaintName]

Can it be long, yes. Has it helped keep info clear for reports, or gotten me a quick jump on that the potential issue is during a prod-alert 100% would love to know peoples thoughts on this naming convention.

jQuery click not working for dynamically created items

You have to add click event to an exist element. You can not add event to dom elements dynamic created. I you want to add event to them, you should bind event to an existed element using ".on".

$('p').on('click','selector_you_dynamic_created',function(){...});

.delegate should work,too.

MySQL SELECT DISTINCT multiple columns

Both your queries are correct and should give you the right answer.

I would suggest the following query to troubleshoot your problem.

SELECT DISTINCT a,b,c,d,count(*) Count FROM my_table GROUP BY a,b,c,d
order by count(*) desc

That is add count(*) field. This will give you idea how many rows were eliminated using the group command.

Disable double-tap "zoom" option in browser on touch devices

Using CSS touch-events: none Completly takes out all the touch events. Just leaving this here in case someone also has this problems, took me 2 hours to find this solution and it's only one line of css. https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action

How to swap String characters in Java?

Since String objects are immutable, going to a char[] via toCharArray, swapping the characters, then making a new String from char[] via the String(char[]) constructor would work.

The following example swaps the first and second characters:

String originalString = "abcde";

char[] c = originalString.toCharArray();

// Replace with a "swap" function, if desired:
char temp = c[0];
c[0] = c[1];
c[1] = temp;

String swappedString = new String(c);

System.out.println(originalString);
System.out.println(swappedString);

Result:

abcde
bacde

Validate that end date is greater than start date with jQuery

function endDate(){
    $.validator.addMethod("endDate", function(value, element) {
      var params = '.startDate';
        if($(element).parent().parent().find(params).val()!=''){
           if (!/Invalid|NaN/.test(new Date(value))) {
               return new Date(value) > new Date($(element).parent().parent().find(params).val());
            }
       return isNaN(value) && isNaN($(element).parent().parent().find(params).val()) || (parseFloat(value) > parseFloat($(element).parent().parent().find(params).val())) || value == "";              
      }else{
        return true;
      }
      },jQuery.format('must be greater than start date'));

}

function startDate(){
            $.validator.addMethod("startDate", function(value, element) {
            var params = '.endDate';
            if($(element).parent().parent().parent().find(params).val()!=''){
                 if (!/Invalid|NaN/.test(new Date(value))) {
                  return new Date(value) < new Date($(element).parent().parent().parent().find(params).val());
            }
           return isNaN(value) && isNaN($(element).parent().parent().find(params).val()) || (parseFloat(value) < parseFloat($(element).parent().parent().find(params).val())) || value == "";
                 }
                        else{
                     return true;
}

    }, jQuery.format('must be less than end date'));
}

Hope this will help :)

What is the difference between parseInt(string) and Number(string) in JavaScript?

The first one takes two parameters:

parseInt(string, radix)

The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.

If the radix parameter is omitted, JavaScript assumes the following:

  • If the string begins with "0x", the
    radix is 16 (hexadecimal)
  • If the string begins with "0", the radix is 8 (octal). This feature
    is deprecated
  • If the string begins with any other value, the radix is 10 (decimal)

The other function you mentioned takes only one parameter:

Number(object)

The Number() function converts the object argument to a number that represents the object's value.

If the value cannot be converted to a legal number, NaN is returned.

PHP get dropdown value and text

$animals = array('--Select Animal--', 'Cat', 'Dog', 'Cow');
$selected_key = $_POST['animal'];
$selected_val = $animals[$_POST['animal']];

Use your $animals list to generate your dropdown list; you now can get the key & the value of that key.

Node.js - EJS - including a partial

In Express 4.x I used the following to load ejs:

  var path = require('path');

  // Set the default templating engine to ejs
  app.set('view engine', 'ejs');
  app.set('views', path.join(__dirname, 'views'));

  // The views/index.ejs exists in the app directory
  app.get('/hello', function (req, res) {
    res.render('index', {title: 'title'});
  });

Then you just need two files to make it work - views/index.ejs:

<%- include partials/navigation.ejs %>

And the views/partials/navigation.ejs:

<ul><li class="active">...</li>...</ul>

You can also tell Express to use ejs for html templates:

var path = require('path');
var EJS  = require('ejs');

app.engine('html', EJS.renderFile);

// Set the default templating engine to ejs
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

// The views/index.html exists in the app directory
app.get('/hello', function (req, res) {
  res.render('index.html', {title: 'title'});
});

Finally you can also use the ejs layout module:

var EJSLayout = require('express-ejs-layouts');
app.use(EJSLayout);

This will use the views/layout.ejs as your layout.

Mapping over values in a python dictionary

While my original answer missed the point (by trying to solve this problem with the solution to Accessing key in factory of defaultdict), I have reworked it to propose an actual solution to the present question.

Here it is:

class walkableDict(dict):
  def walk(self, callback):
    try:
      for key in self:
        self[key] = callback(self[key])
    except TypeError:
      return False
    return True

Usage:

>>> d = walkableDict({ k1: v1, k2: v2 ... })
>>> d.walk(f)

The idea is to subclass the original dict to give it the desired functionality: "mapping" a function over all the values.

The plus point is that this dictionary can be used to store the original data as if it was a dict, while transforming any data on request with a callback.

Of course, feel free to name the class and the function the way you want (the name chosen in this answer is inspired by PHP's array_walk() function).

Note: Neither the try-except block nor the return statements are mandatory for the functionality, they are there to further mimic the behavior of the PHP's array_walk.

When to use LinkedList over ArrayList in Java?

Joshua Bloch, the author of LinkedList:

Does anyone actually use LinkedList? I wrote it, and I never use it.

Link: https://twitter.com/joshbloch/status/583813919019573248

I'm sorry for the answer for being not that informative as the other answers, but I thought it would be the most interesting and self-explanatory.

How can I make a JPA OneToOne relation lazy

Most efficient mapping of a one-to-one association You can avoid all these problems and get rid of the foreign key column by using the same primary key value for both associated entities. You can do that by annotating the owning side of the association with @MapsId.

@Entity
public class Book {
 
    @Id
    @GeneratedValue
    private Long id;
 
    @OneToOne(mappedBy = "book", fetch = FetchType.LAZY, optional = false)
    private Manuscript manuscript;
 
    ...
}


@Entity
public class Manuscript {
 
    @Id
    private Long id;
 
    @OneToOne
    @MapsId
    @JoinColumn(name = "id")
    private Book book;
 
    ...
}


Book b = em.find(Book.class, 100L);
Manuscript m = em.find(Manuscript.class, b.getId());

More Detail click on this url

Pushing an existing Git repository to SVN

I just want to share some of my experience with the accepted answer. I did all steps and all was fine before I ran the last step:

git svn dcommit

$ git svn dcommit

Use of uninitialized value $u in substitution (s///) at /usr/lib/perl5/vendor_perl/5.22/Git/SVN.pm line 101.

Use of uninitialized value $u in concatenation (.) or string at /usr/lib/perl5/vendor_perl/5.22/Git/SVN.pm line 101. refs/remotes/origin/HEAD: 'https://192.168.2.101/svn/PROJECT_NAME' not found in ''

I found the thread https://github.com/nirvdrum/svn2git/issues/50 and finally the solution which I applied in the following file in line 101 /usr/lib/perl5/vendor_perl/5.22/Git/SVN.pm

I replaced

$u =~ s!^\Q$url\E(/|$)!! or die

with

if (!$u) {
    $u = $pathname;
} 
else {
       $u =~ s!^\Q$url\E(/|$)!! or die
      "$refname: '$url' not found in '$u'\n";
}

This fixed my issue.

Using dig to search for SPF records

The dig utility is pretty convenient to use. The order of the arguments don't really matter.I'll show you some easy examples.
To get all root name servers use

# dig

To get a TXT record of a specific host use

# dig example.com txt
# dig host.example.com txt

To query a specific name server just add @nameserver.tld

# dig host.example.com txt @a.iana-servers.net

The SPF RFC4408 says that SPF records can be stored as SPF or TXT. However nearly all use only TXT records at the moment. So you are pretty safe if you only fetch TXT records.

I made a SPF checker for visualising the SPF records of a domain. It might help you to understand SPF records better. You can find it here: http://spf.myisp.ch

Android Error Building Signed APK: keystore.jks not found for signing config 'externalOverride'

open key.properties and check your path is correct. (replace from \ to /)

example:-

replace from "storeFile=D:\Projects\Flutter\Key\key.jks" to "storeFile=D:/Projects/Flutter/Key/key.jks"

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

It worked only after removing the eclipse folder and all related folders like .p2, .eclipse (in my case they are at different location where I have saved eclipse installer) etc. and after re-downloading the eclipse, it worked.

How to write loop in a Makefile?

The following will do it if, as I assume by your use of ./a.out, you're on a UNIX-type platform.

for number in 1 2 3 4 ; do \
    ./a.out $$number ; \
done

Test as follows:

target:
    for number in 1 2 3 4 ; do \
        echo $$number ; \
    done

produces:

1
2
3
4

For bigger ranges, use:

target:
    number=1 ; while [[ $$number -le 10 ]] ; do \
        echo $$number ; \
        ((number = number + 1)) ; \
    done

This outputs 1 through 10 inclusive, just change the while terminating condition from 10 to 1000 for a much larger range as indicated in your comment.

Nested loops can be done thus:

target:
    num1=1 ; while [[ $$num1 -le 4 ]] ; do \
        num2=1 ; while [[ $$num2 -le 3 ]] ; do \
            echo $$num1 $$num2 ; \
            ((num2 = num2 + 1)) ; \
        done ; \
        ((num1 = num1 + 1)) ; \
    done

producing:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
4 1
4 2
4 3

How do I get the fragment identifier (value after hash #) from a URL?

Use the following JavaScript to get the value after hash (#) from a URL. You don't need to use jQuery for that.

var hash = location.hash.substr(1);

I have got this code and tutorial from here - How to get hash value from URL using JavaScript

Cut Java String at a number of character

Jakarta Commons StringUtils.abbreviate(). If, for some reason you don't want to use a 3rd-party library, at least copy the source code.

One big benefit of this over the other answers to date is that it won't throw if you pass in a null.

How to fix date format in ASP .NET BoundField (DataFormatString)?

Formatting depends on the server's culture setting. If you use en-US culture, you can use Short Date Pattern like {0:d}

For example, it formats 6/15/2009 1:45:30 to 6/15/2009

You can check more formats from BoundField.DataFormatString

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

You have to add a ToolTip control to your form first. Then you can set the text it should display for other controls.

Here's a screenshot showing the designer after adding a ToolTip control which is named toolTip1:

enter image description here

Java error: Only a type can be imported. XYZ resolves to a package

Well, you are not really providing enough details on your webapp but my guess is that you have a JSP with something like that:

<%@ page import="java.util.*,x.y.Z"%> 

And x.y.Z can't be found on the classpath (i.e. is not present under WEB-INF/classes nor in a JAR of WEB-INF/lib).

Double check that the WAR you deploy on Tomcat has the following structure:

my-webapp
|-- META-INF
|   `-- MANIFEST.MF
|-- WEB-INF
|   |-- classes
|   |   |-- x
|   |   |   `-- y
|   |   |       `-- Z.class
|   |   `-- another
|   |       `-- packagename
|   |           `-- AnotherClass.class
|   |-- lib
|   |   |-- ajar.jar
|   |   |-- bjar.jar
|   |   `-- zjar.jar
|   `-- web.xml
|-- a.jsp
|-- b.jsp
`-- index.jsp

Or that the JAR that bundles x.y.Z.class is present under WEB-INF/lib.

Namenode not getting started

If anyone using hadoop1.2.1 version and not able to run namenode, go to core-site.xml, and change dfs.default.name to fs.default.name.

And then format the namenode using $hadoop namenode -format.

Finally run the hdfs using start-dfs.sh and check for service using jps..

Pass variables to AngularJS controller, best practice?

You could use ng-init in an outer div:

<div ng-init="param='value';">
    <div ng-controller="BasketController" >
        <label>param: {{value}}</label>
    </div>
</div>  

The parameter will then be available in your controller's scope:

function BasketController($scope) {
        console.log($scope.param);
}

How can I make a time delay in Python?

You can use the sleep() function in the time module. It can take a float argument for sub-second resolution.

from time import sleep
sleep(0.1) # Time in seconds

Iterator Loop vs index loop

With a vector iterators do no offer any real advantage. The syntax is uglier, longer to type and harder to read.

Iterating over a vector using iterators is not faster and is not safer (actually if the vector is possibly resized during the iteration using iterators will put you in big troubles).

The idea of having a generic loop that works when you will change later the container type is also mostly nonsense in real cases. Unfortunately the dark side of a strictly typed language without serious typing inference (a bit better now with C++11, however) is that you need to say what is the type of everything at each step. If you change your mind later you will still need to go around and change everything. Moreover different containers have very different trade-offs and changing container type is not something that happens that often.

The only case in which iteration should be kept if possible generic is when writing template code, but that (I hope for you) is not the most frequent case.

The only problem present in your explicit index loop is that size returns an unsigned value (a design bug of C++) and comparison between signed and unsigned is dangerous and surprising, so better avoided. If you use a decent compiler with warnings enabled there should be a diagnostic on that.

Note that the solution is not to use an unsiged as the index, because arithmetic between unsigned values is also apparently illogical (it's modulo arithmetic, and x-1 may be bigger than x). You instead should cast the size to an integer before using it. It may make some sense to use unsigned sizes and indexes (paying a LOT of attention to every expression you write) only if you're working on a 16 bit C++ implementation (16 bit was the reason for having unsigned values in sizes).

As a typical mistake that unsigned size may introduce consider:

void drawPolyline(const std::vector<P2d>& points)
{
    for (int i=0; i<points.size()-1; i++)
        drawLine(points[i], points[i+1]);
}

Here the bug is present because if you pass an empty points vector the value points.size()-1 will be a huge positive number, making you looping into a segfault. A working solution could be

for (int i=1; i<points.size(); i++)
    drawLine(points[i - 1], points[i]);

but I personally prefer to always remove unsinged-ness with int(v.size()).

PS: If you really don't want to think by to yourself to the implications and simply want an expert to tell you then consider that a quite a few world recognized C++ experts agree and expressed opinions on that unsigned values are a bad idea except for bit manipulations.

Discovering the ugliness of using iterators in the case of iterating up to second-last is left as an exercise for the reader.

Hive Alter table change Column Name

alter table table_name change old_col_name new_col_name new_col_type;

Here is the example

hive> alter table test change userVisit userVisit2 STRING;      
    OK
    Time taken: 0.26 seconds
    hive> describe test;                                      
    OK
    uservisit2              string                                      
    category                string                                      
    uuid                    string                                      
    Time taken: 0.213 seconds, Fetched: 3 row(s)

Recursion or Iteration?

Stack overflow will only occur if you're programming in a language that doesn't have in built memory management.... Otherwise, make sure you have something in your function (or a function call, STDLbs, etc). Without recursion it would simply not be possible to have things like... Google or SQL, or any place one must efficiently sort through large data structures (classes) or databases.

Recursion is the way to go if you want to iterate through files, pretty sure that's how 'find * | ?grep *' works. Kinda dual recursion, especially with the pipe (but don't do a bunch of syscalls like so many like to do if it's anything you're going to put out there for others to use).

Higher level languages and even clang/cpp may implement it the same in the background.

How do I `jsonify` a list in Flask?

This is working for me. Which version of Flask are you using?

from flask import jsonify

...

@app.route('/test/json')
def test_json():
    list = [
            {'a': 1, 'b': 2},
            {'a': 5, 'b': 10}
           ]
    return jsonify(results = list)

Correct redirect URI for Google API and OAuth 2.0

There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.

You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.

When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.

How do I find out which DOM element has the focus?

I liked the approach used by Joel S, but I also love the simplicity of document.activeElement. I used jQuery and combined the two. Older browsers that don't support document.activeElement will use jQuery.data() to store the value of 'hasFocus'. Newer browsers will use document.activeElement. I assume that document.activeElement will have better performance.

(function($) {
var settings;
$.fn.focusTracker = function(options) {
    settings = $.extend({}, $.focusTracker.defaults, options);

    if (!document.activeElement) {
        this.each(function() {
            var $this = $(this).data('hasFocus', false);

            $this.focus(function(event) {
                $this.data('hasFocus', true);
            });
            $this.blur(function(event) {
                $this.data('hasFocus', false);
            });
        });
    }
    return this;
};

$.fn.hasFocus = function() {
    if (this.length === 0) { return false; }
    if (document.activeElement) {
        return this.get(0) === document.activeElement;
    }
    return this.data('hasFocus');
};

$.focusTracker = {
    defaults: {
        context: 'body'
    },
    focusedElement: function(context) {
        var focused;
        if (!context) { context = settings.context; }
        if (document.activeElement) {
            if ($(document.activeElement).closest(context).length > 0) {
                focused = document.activeElement;
            }
        } else {
            $(':visible:enabled', context).each(function() {
                if ($(this).data('hasFocus')) {
                    focused = this;
                    return false;
                }
            });
        }
        return $(focused);
    }
};
})(jQuery);

2 ways for "ClearContents" on VBA Excel, but 1 work fine. Why?

For numerical addressing of cells try to enable S1O1 checkbox in MS Excel settings. It is the second tab from top (i.e. Formulas), somewhere mid-page in my Hungarian version.

If enabled, it handles VBA addressing in both styles, i.e. Range("A1:B10") and Range(Cells(1, 1), Cells(10, 2)). I assume it handles Range("A1:B10") style only, if not enabled.

Good luck!

(Note, that Range("A1:B10") represents a 2x10 square, while Range(Cells(1, 1), Cells(10, 2)) represents 10x2. Using column numbers instead of letters will not affect the order of addresing.)

How to find the maximum value in an array?

Iterate over the Array. First initialize the maximum value to the first element of the array and then for each element optimize it if the element under consideration is greater.

How to pass ArrayList<CustomeObject> from one activity to another?

Use this code to pass arraylist<customobj> to anthother Activity

firstly serialize our contact bean

public class ContactBean implements Serializable {
      //do intialization here
}

Now pass your arraylist

 Intent intent = new Intent(this,name of activity.class);
 contactBean=(ConactBean)_arraylist.get(position);
 intent.putExtra("contactBeanObj",conactBean);
 _activity.startActivity(intent);

Polynomial time and exponential time

O(n^2) is polynomial time. The polynomial is f(n) = n^2. On the other hand, O(2^n) is exponential time, where the exponential function implied is f(n) = 2^n. The difference is whether the function of n places n in the base of an exponentiation, or in the exponent itself.

Any exponential growth function will grow significantly faster (long term) than any polynomial function, so the distinction is relevant to the efficiency of an algorithm, especially for large values of n.

How to search a string in a single column (A) in excel using VBA

Below are two methods that are superior to looping. Both handle a "no-find" case.

  1. The VBA equivalent of a normal function VLOOKUP with error-handling if the variable doesn't exist (INDEX/MATCH may be a better route than VLOOKUP, ie if your two columns A and B were in reverse order, or were far apart)
  2. VBAs FIND method (matching a whole string in column A given I use the xlWhole argument)

    Sub Method1()
    Dim strSearch As String
    Dim strOut As String
    Dim bFailed As Boolean
    
    strSearch = "trees"
    
    On Error Resume Next
    strOut = Application.WorksheetFunction.VLookup(strSearch, Range("A:B"), 2, False)
    If Err.Number <> 0 Then bFailed = True
    On Error GoTo 0
    
    If Not bFailed Then
    MsgBox "corresponding value is " & vbNewLine & strOut
    Else
    MsgBox strSearch & " not found"
    End If
    End Sub
    
    Sub Method2()
        Dim rng1 As Range
        Dim strSearch As String
        strSearch = "trees"
        Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole)
        If Not rng1 Is Nothing Then
            MsgBox "Find has matched " & strSearch & vbNewLine & "corresponding cell is " & rng1.Offset(0, 1)
        Else
            MsgBox strSearch & " not found"
        End If
    End Sub
    

Convert double/float to string

Go and look at the printf() implementation with "%f" in some C library.

Convert java.util.Date to String

One Line option

This option gets a easy one-line to write the actual date.

Please, note that this is using Calendar.class and SimpleDateFormat, and then it's not logical to use it under Java8.

yourstringdate =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());

Nested iframes, AKA Iframe Inception

Thing is, the code you provided won't work because the <iframe> element has to have a "src" property, like:

<iframe id="uploads" src="http://domain/page.html"></iframe>

It's ok to use .contents() to get the content:

$('#uploads).contents() will give you access to the second iframe, but if that iframe is "INSIDE" the http://domain/page.html document the #uploads iframe loaded.

To test I'm right about this, I created 3 html files named main.html, iframe.html and noframe.html and then selected the div#element just fine with:

$('#uploads').contents().find('iframe').contents().find('#element');

There WILL be a delay in which the element will not be available since you need to wait for the iframe to load the resource. Also, all iframes have to be on the same domain.

Hope this helps ...

Here goes the html for the 3 files I used (replace the "src" attributes with your domain and url):

main.html

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>main.html example</title>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

    <script>
        $(function () {
            console.log( $('#uploads').contents().find('iframe').contents().find('#element') ); // nothing at first

            setTimeout( function () {
                console.log( $('#uploads').contents().find('iframe').contents().find('#element') ); // wait and you'll have it
            }, 2000 );

        });
    </script>
</head>
<body>
    <iframe id="uploads" src="http://192.168.1.70/test/iframe.html"></iframe>
</body>

iframe.html

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>iframe.html example</title>
</head>
<body>
    <iframe src="http://192.168.1.70/test/noframe.html"></iframe>
</body>

noframe.html

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>noframe.html example</title>
</head>
<body>
    <div id="element">some content</div>
</body>

How to remove an iOS app from the App Store

Steps to Remove app from App Store

  1. Click the My Apps section.
  2. Select the app you'd like to remove.
  3. Click the Pricing tab from the app listing page.
  4. Click the "specific territories" link.
  5. In the drop-down section that appears below, click "Deselect All' at the top right. This will uncheck every territory below.
  6. A confirmation message will appear at the top of the screen.
  7. Return to the My Apps section by clicking the navigation button at the top left.
  8. The application status has changed to "Developer Removed From Sale."
  9. Within 24 hours (though usually less) your app will no longer appear in the App Store.

enter image description here

Logging levels - Logback - rule-of-thumb to assign log levels

My approach, i think coming more from an development than an operations point of view, is:

  • Error means that the execution of some task could not be completed; an email couldn't be sent, a page couldn't be rendered, some data couldn't be stored to a database, something like that. Something has definitively gone wrong.
  • Warning means that something unexpected happened, but that execution can continue, perhaps in a degraded mode; a configuration file was missing but defaults were used, a price was calculated as negative, so it was clamped to zero, etc. Something is not right, but it hasn't gone properly wrong yet - warnings are often a sign that there will be an error very soon.
  • Info means that something normal but significant happened; the system started, the system stopped, the daily inventory update job ran, etc. There shouldn't be a continual torrent of these, otherwise there's just too much to read.
  • Debug means that something normal and insignificant happened; a new user came to the site, a page was rendered, an order was taken, a price was updated. This is the stuff excluded from info because there would be too much of it.
  • Trace is something i have never actually used.

XOR operation with two strings in java

Pay attention:

A Java char corresponds to a UTF-16 code unit, and in some cases two consecutive chars (a so-called surrogate pair) are needed for one real Unicode character (codepoint).

XORing two valid UTF-16 sequences (i.e. Java Strings char by char, or byte by byte after encoding to UTF-16) does not necessarily give you another valid UTF-16 string - you may have unpaired surrogates as a result. (It would still be a perfectly usable Java String, just the codepoint-concerning methods could get confused, and the ones that convert to other encodings for output and similar.)

The same is valid if you first convert your Strings to UTF-8 and then XOR these bytes - here you quite probably will end up with a byte sequence which is not valid UTF-8, if your Strings were not already both pure ASCII strings.

Even if you try to do it right and iterate over your two Strings by codepoint and try to XOR the codepoints, you can end up with codepoints outside the valid range (for example, U+FFFFF (plane 15) XOR U+10000 (plane 16) = U+1FFFFF (which would the last character of plane 31), way above the range of existing codepoints. And you could also end up this way with codepoints reserved for surrogates (= not valid ones).

If your strings only contain chars < 128, 256, 512, 1024, 2048, 4096, 8192, 16384, or 32768, then the (char-wise) XORed strings will be in the same range, and thus certainly not contain any surrogates. In the first two cases you could also encode your String as ASCII or Latin-1, respectively, and have the same XOR-result for the bytes. (You still can end up with control chars, which may be a problem for you.)


What I'm finally saying here: don't expect the result of encrypting Strings to be a valid string again - instead, simply store and transmit it as a byte[] (or a stream of bytes). (And yes, convert to UTF-8 before encrypting, and from UTF-8 after decrypting).

performSelector may cause a leak because its selector is unknown

In the LLVM 3.0 compiler in Xcode 4.2 you can suppress the warning as follows:

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
    [self.ticketTarget performSelector: self.ticketAction withObject: self];
#pragma clang diagnostic pop

If you're getting the error in several places, and want to use the C macro system to hide the pragmas, you can define a macro to make it easier to suppress the warning:

#define SuppressPerformSelectorLeakWarning(Stuff) \
    do { \
        _Pragma("clang diagnostic push") \
        _Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"") \
        Stuff; \
        _Pragma("clang diagnostic pop") \
    } while (0)

You can use the macro like this:

SuppressPerformSelectorLeakWarning(
    [_target performSelector:_action withObject:self]
);

If you need the result of the performed message, you can do this:

id result;
SuppressPerformSelectorLeakWarning(
    result = [_target performSelector:_action withObject:self]
);

Git Bash won't run my python files?

Here is the SOLUTION

If you get Response:

  1. bash: python: command not found OR
  2. bash: conda: command not found

To the following Commands: when you execute python or python -V conda or conda --version in your Git/Terminal window

Background: This is because you either

  1. Installed Python in a location on your C Drive (C:) which is not directly in your program files folder.
  2. Installed Python maybe on the D Drive (D:) and your computer by default searches for it on your C:
  3. You have been told to go to your environment variables (located if you do a search for environment variables on your machines start menu) and change the "Path" variable on your computer and this still does not fix the problem.

Solution:

  1. At the command prompt, paste this command export PATH="$PATH:/c/Python36". That will tell Windows where to find Python. (This assumes that you installed it in C:\Python36)

  2. If you installed python on your D drive, paste this command export PATH="$PATH:/d/Python36".

  3. Then at the command prompt, paste python or python -V and you will see the version of Python installed and now you should not get Python 3.6.5

  4. Assuming that it worked correctly you will want to set up git bash so that it always knows where to find python. To do that, enter the following command: echo 'export PATH="$PATH:/d/Python36"' > .bashrc

Permanent Solution

  1. Go to BASH RC Source File (located on C: / C Drive in “C:\Users\myname”)

  2. Make sure your BASH RC Source File is receiving direction from your Bash Profile Source File, you can do this by making sure that your BASH RC Source File contains this line of code: source ~/.bash_profile

  3. Go to BASH Profile Source File (located on C: / C Drive in “C:\Users\myname”)

  4. Enter line: export PATH="$PATH:/D/PROGRAMMING/Applications/PYTHON/Python365" (assuming this is the location where Python version 3.6.5 is installed)

  5. This should take care of the problem permanently. Now whenever you open your Git Bash Terminal Prompt and enter “python” or “python -V” it should return the python version

Is there a 'foreach' function in Python 3?

Yes, although it uses the same syntax as a for loop.

for x in ['a', 'b']: print(x)

WPF - add static items to a combo box

You can also add items in code:

cboWhatever.Items.Add("SomeItem");

Also, to add something where you control display/value, (almost categorically needed in my experience) you can do so. I found a good stackoverflow reference here:

Key Value Pair Combobox in WPF

Sum-up code would be something like this:

ComboBox cboSomething = new ComboBox();
cboSomething.DisplayMemberPath = "Key";
cboSomething.SelectedValuePath = "Value";
cboSomething.Items.Add(new KeyValuePair<string, string>("Something", "WhyNot"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Deus", "Why"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Flirptidee", "Stuff"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Fernum", "Blictor"));

What is the best way to create a string array in python?

In python, you wouldn't normally do what you are trying to do. But, the below code will do it:

strs = ["" for x in range(size)]

OR is not supported with CASE Statement in SQL Server

That format requires you to use either:

CASE ebv.db_no 
  WHEN 22978 THEN 'WECS 9500' 
  WHEN 23218 THEN 'WECS 9500'  
  WHEN 23219 THEN 'WECS 9500' 
  ELSE 'WECS 9520' 
END as wecs_system 

Otherwise, use:

CASE  
  WHEN ebv.db_no IN (22978, 23218, 23219) THEN 'WECS 9500' 
  ELSE 'WECS 9520' 
END as wecs_system 

Get value of multiselect box using jQuery or pure JS

You could do like this too.

<form action="ResultsDulith.php" id="intermediate" name="inputMachine[]" multiple="multiple" method="post">
    <select id="selectDuration" name="selectDuration[]" multiple="multiple"> 
        <option value="1 WEEK" >Last 1 Week</option>
        <option value="2 WEEK" >Last 2 Week </option>
        <option value="3 WEEK" >Last 3 Week</option>
         <option value="4 WEEK" >Last 4 Week</option>
          <option value="5 WEEK" >Last 5 Week</option>
           <option value="6 WEEK" >Last 6 Week</option>
    </select>
     <input type="submit"/> 
</form>

Then take the multiple selection from following PHP code below. It print the selected multiple values accordingly.

$shift=$_POST['selectDuration'];

print_r($shift);

How do you put an image file in a json object?

The JSON format can contain only those types of value:

  • string
  • number
  • object
  • array
  • true
  • false
  • null

An image is of the type "binary" which is none of those. So you can't directly insert an image into JSON. What you can do is convert the image to a textual representation which can then be used as a normal string.

The most common way to achieve that is with what's called base64. Basically, instead of encoding it as 1 and 0s, it uses a range of 64 characters which makes the textual representation of it more compact. So for example the number '64' in binary is represented as 1000000, while in base64 it's simply one character: =.

There are many ways to encode your image in base64 depending on if you want to do it in the browser or not.

Note that if you're developing a web application, it will be way more efficient to store images separately in binary form, and store paths to those images in your JSON or elsewhere. That also allows your client's browser to cache the images.

Pandas read in table without headers

In order to read a csv in that doesn't have a header and for only certain columns you need to pass params header=None and usecols=[3,6] for the 4th and 7th columns:

df = pd.read_csv(file_path, header=None, usecols=[3,6])

See the docs

How to properly highlight selected item on RecyclerView?

Decision with Interfaces and Callbacks. Create Interface with select and unselect states:

public interface ItemTouchHelperViewHolder {
    /**
     * Called when the {@link ItemTouchHelper} first registers an item as being moved or swiped.
     * Implementations should update the item view to indicate it's active state.
     */
    void onItemSelected();


    /**
     * Called when the {@link ItemTouchHelper} has completed the move or swipe, and the active item
     * state should be cleared.
     */
    void onItemClear();
}

Implement interface in ViewHolder:

   public static class ItemViewHolder extends RecyclerView.ViewHolder implements
            ItemTouchHelperViewHolder {

        public LinearLayout container;
        public PositionCardView content;

        public ItemViewHolder(View itemView) {
            super(itemView);
            container = (LinearLayout) itemView;
            content = (PositionCardView) itemView.findViewById(R.id.content);

        }

               @Override
    public void onItemSelected() {
        /**
         * Here change of item
         */
        container.setBackgroundColor(Color.LTGRAY);
    }

    @Override
    public void onItemClear() {
        /**
         * Here change of item
         */
        container.setBackgroundColor(Color.WHITE);
    }
}

Run state change on Callback:

public class ItemTouchHelperCallback extends ItemTouchHelper.Callback {

    private final ItemTouchHelperAdapter mAdapter;

    public ItemTouchHelperCallback(ItemTouchHelperAdapter adapter) {
        this.mAdapter = adapter;
    }

    @Override
    public boolean isLongPressDragEnabled() {
        return true;
    }

    @Override
    public boolean isItemViewSwipeEnabled() {
        return true;
    }

    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
        int swipeFlags = ItemTouchHelper.END;
        return makeMovementFlags(dragFlags, swipeFlags);
    }

    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
        ...
    }

    @Override
    public void onSwiped(final RecyclerView.ViewHolder viewHolder, int direction) {
        ...
    }

    @Override
    public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
        if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
            if (viewHolder instanceof ItemTouchHelperViewHolder) {
                ItemTouchHelperViewHolder itemViewHolder =
                        (ItemTouchHelperViewHolder) viewHolder;
                itemViewHolder.onItemSelected();
            }
        }
        super.onSelectedChanged(viewHolder, actionState);
    }

    @Override
    public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        super.clearView(recyclerView, viewHolder);
        if (viewHolder instanceof ItemTouchHelperViewHolder) {
            ItemTouchHelperViewHolder itemViewHolder =
                    (ItemTouchHelperViewHolder) viewHolder;
            itemViewHolder.onItemClear();
        }
    }   
}

Create RecyclerView with Callback (example):

mAdapter = new BuyItemsRecyclerListAdapter(MainActivity.this, positionsList, new ArrayList<BuyItem>());
positionsList.setAdapter(mAdapter);
positionsList.setLayoutManager(new LinearLayoutManager(this));
ItemTouchHelper.Callback callback = new ItemTouchHelperCallback(mAdapter);
mItemTouchHelper = new ItemTouchHelper(callback);
mItemTouchHelper.attachToRecyclerView(positionsList);

See more in article of iPaulPro: https://medium.com/@ipaulpro/drag-and-swipe-with-recyclerview-6a6f0c422efd#.6gh29uaaz

Print JSON parsed object?

If you're working in js on a server, just a little more gymnastics goes a long way... Here's my ppos (pretty-print-on-server):

ppos = (object, space = 2) => JSON.stringify(object, null, space).split('\n').forEach(s => console.log(s));

which does a bang-up job of creating something I can actually read when I'm writing server code.

WebDriver: check if an element exists?

you can do an assertion.

see the example

driver.asserts().assertElementFound("Page was not loaded",
By.xpath("//div[@id='actionsContainer']"),Constants.LOOKUP_TIMEOUT);

you can use this this is native :

public static void waitForElementToAppear(Driver driver, By selector, long timeOutInSeconds, String timeOutMessage) {
    try {
      WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
      wait.until(ExpectedConditions.visibilityOfElementLocated(selector));
    } catch (TimeoutException e) {
      throw new IllegalStateException(timeOutMessage);
    }
  }

Best Practice: Access form elements by HTML id or name attribute?

name field works well. It provides a reference to the elements.

parent.children - Will list all elements with a name field of the parent. parent.elements - Will list only form elements such as input-text, text-area, etc

_x000D_
_x000D_
var form = document.getElementById('form-1');_x000D_
console.log(form.children.firstname)_x000D_
console.log(form.elements.firstname)_x000D_
console.log(form.elements.progressBar); // undefined_x000D_
console.log(form.children.progressBar);_x000D_
console.log(form.elements.submit); // undefined
_x000D_
<form id="form-1">_x000D_
  <input type="text" name="firstname" />_x000D_
  <input type="file" name="file" />_x000D_
  <progress name="progressBar" value="20" min="0" max="100" />_x000D_
  <textarea name="address"></textarea>_x000D_
  <input type="submit" name="submit" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Note: For .elements to work, the parent needs to be a <form> tag. Whereas, .children will work on any HTML-element - such as <div>, <span>, etc.

Good Luck...

Rendering an array.map() in React

You are not returning. Change to

this.state.data.map(function(item, i){
  console.log('test');
  return <li>Test</li>;
})

POST request send json data java HttpUrlConnection

You can use this code for connect and request using http and json

try {
         
        URL url = new URL("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet"
                + "&key="+key
                + "&access_token=" + access_token);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
 
        String input = "{ \"snippet\": {\"playlistId\": \"WL\",\"resourceId\": {\"videoId\": \""+videoId+"\",\"kind\": \"youtube#video\"},\"position\": 0}}";
 
        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();
 
        if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
            throw new RuntimeException("Failed : HTTP error code : "
                + conn.getResponseCode());
        }
 
        BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));
 
        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }
 
        conn.disconnect();
 
      } catch (MalformedURLException e) {
 
        e.printStackTrace();
 
      } catch (IOException e) {
 
        e.printStackTrace();
 
     }

How can I generate an MD5 hash?

private String hashuj(String dane) throws ServletException{
    try {
        MessageDigest m = MessageDigest.getInstance("MD5");
        byte[] bufor = dane.getBytes();
        m.update(bufor,0,bufor.length);
        BigInteger hash = new BigInteger(1,m.dige`enter code here`st());
        return String.format("%1$032X", hash);

    } catch (NoSuchAlgorithmException nsae) {
        throw new ServletException("Algorytm szyfrowania nie jest obslugiwany!");
    }
}

Getting Textbox value in Javascript

<script type="text/javascript" runat="server">
 public void Page_Load(object Sender, System.EventArgs e)
    {
        double rad=0.0;
        TextBox1.Attributes.Add("Visible", "False");
        if (TextBox1.Text != "") 
        rad = Convert.ToDouble(TextBox1.Text);    
        Button1.Attributes.Add("OnClick","alert("+ rad +")");
    }
</script>

<asp:Button ID="Button1" runat="server" Text="Diameter" 
            style="z-index: 1; left: 133px; top: 181px; position: absolute" />
<asp:TextBox ID="TextBox1" Visible="True" Text="" runat="server" 
            AutoPostBack="true" 
            style="z-index: 1; left: 134px; top: 133px; position: absolute" ></asp:TextBox>

use the help of this, hope it will be usefull

Select datatype of the field in postgres

You can get data types from the information_schema (8.4 docs referenced here, but this is not a new feature):

=# select column_name, data_type from information_schema.columns
-# where table_name = 'config';
    column_name     | data_type 
--------------------+-----------
 id                 | integer
 default_printer_id | integer
 master_host_enable | boolean
(3 rows)

Get current URL/URI without some of $_GET variables

In Yii2 you can do:

use yii\helpers\Url;
$withoutLg = Url::current(['lg'=>null], true);

More info: https://www.yiiframework.com/doc/api/2.0/yii-helpers-baseurl#current%28%29-detail

EF Core add-migration Build Failed

Just got into this issue. In my case, I was debugging my code and it was making my migrations fail.

Since in Visual Studio Code, the debugger is so low-profile (only a small bar), I didn't realize about this until I read some questions and decided to look better.

What is the difference between partitioning and bucketing a table in Hive ?

Hive Partitioning:

Partition divides large amount of data into multiple slices based on value of a table column(s).

Assume that you are storing information of people in entire world spread across 196+ countries spanning around 500 crores of entries. If you want to query people from a particular country (Vatican city), in absence of partitioning, you have to scan all 500 crores of entries even to fetch thousand entries of a country. If you partition the table based on country, you can fine tune querying process by just checking the data for only one country partition. Hive partition creates a separate directory for a column(s) value.

Pros:

  1. Distribute execution load horizontally
  2. Faster execution of queries in case of partition with low volume of data. e.g. Get the population from "Vatican city" returns very fast instead of searching entire population of world.

Cons:

  1. Possibility of too many small partition creations - too many directories.
  2. Effective for low volume data for a given partition. But some queries like group by on high volume of data still take long time to execute. e.g. Grouping of population of China will take long time compared to grouping of population in Vatican city. Partition is not solving responsiveness problem in case of data skewing towards a particular partition value.

Hive Bucketing:

Bucketing decomposes data into more manageable or equal parts.

With partitioning, there is a possibility that you can create multiple small partitions based on column values. If you go for bucketing, you are restricting number of buckets to store the data. This number is defined during table creation scripts.

Pros

  1. Due to equal volumes of data in each partition, joins at Map side will be quicker.
  2. Faster query response like partitioning

Cons

  1. You can define number of buckets during table creation but loading of equal volume of data has to be done manually by programmers.

How do I drop a function if it already exists?

IF EXISTS (
    SELECT * FROM sysobjects WHERE id = object_id(N'function_name') 
    AND xtype IN (N'FN', N'IF', N'TF')
)
    DROP FUNCTION function_name
GO

If you want to avoid the sys* tables, you could instead do (from here in example A):

IF object_id(N'function_name', N'FN') IS NOT NULL
    DROP FUNCTION function_name
GO

The main thing to catch is what type of function you are trying to delete (denoted in the top sql by FN, IF and TF):

  • FN = Scalar Function
  • IF = Inlined Table Function
  • TF = Table Function

How to execute an SSIS package from .NET?

Here is how to set variables in the package from code -

using Microsoft.SqlServer.Dts.Runtime;

private void Execute_Package()
    {           
        string pkgLocation = @"c:\test.dtsx";

        Package pkg;
        Application app;
        DTSExecResult pkgResults;
        Variables vars;

        app = new Application();
        pkg = app.LoadPackage(pkgLocation, null);

        vars = pkg.Variables;
        vars["A_Variable"].Value = "Some value";               

        pkgResults = pkg.Execute(null, vars, null, null, null);

        if (pkgResults == DTSExecResult.Success)
            Console.WriteLine("Package ran successfully");
        else
            Console.WriteLine("Package failed");
    }

Remove multiple objects with rm()

Or using regular expressions

"rmlike" <- function(...) {
  names <- sapply(
    match.call(expand.dots = FALSE)$..., as.character)
  names = paste(names,collapse="|")
  Vars <- ls(1)
  r <- Vars[grep(paste("^(",names,").*",sep=""),Vars)]
  rm(list=r,pos=1)
}

rmlike(temp)

PUT and POST getting 405 Method Not Allowed Error for Restful Web Services

I same thing happen with me, If your code is correct and then also give 405 error. this error due to some authorization problem. go to authorization menu and change to "Inherit auth from parent".

Authorization Type options menu Authorization Inherit auth from parent selected

What is the purpose of a plus symbol before a variable?

The + operator returns the numeric representation of the object. So in your particular case, it would appear to be predicating the if on whether or not d is a non-zero number.

Reference here. And, as pointed out in comments, here.

Getting View's coordinates relative to the root layout

Incase someone is still trying to figure this out. This is how you get the center X and Y of the view.

    int pos[] = new int[2];
    view.getLocationOnScreen(pos);
    int centerX = pos[0] + view.getMeasuredWidth() / 2;
    int centerY = pos[1] + view.getMeasuredHeight() / 2;

How do you access a website running on localhost from iPhone browser

If you're on a mac make sure to edit your /etc/hosts file. Find the IP address per instructions above and add the following line to that file

172.x.xx.x.x outer

After that, the steps above worked: navigate to the right page in my iphone browser, visit http://172.x.xx.x.x:port http://www.imore.com/how-edit-your-macs-hosts-file-and-why-you-would-want

How do I run a Python program?

What I just did, to open a simple python script by double clicking. I just added a batch file to the directory containing the script:

@echo off
python exercise.py
pause>nul

(I have the python executable on my system path. If not one would need include its complete path of course.)

Then I just can double click on the batch file to run the script. The third line keeps the cmd window from being dismissed as soon as the script ends, so you can see the results. :) When you're done just close the command window.

How to run or debug php on Visual Studio Code (VSCode)

To debug php with vscode,you need these things:

  1. vscode with php debuge plugin(XDebug) installed;
  2. php with XDebug.so/XDebug.dll downloaded and configured;
  3. a web server,such as apache/nginx or just nothing(use the php built-in server)

you can gently walk through step 1 and 2,by following the vscode official guide.It is fully recommended to use XDebug installation wizard to verify your XDebug configuration.

If you want to debug without a standalone web server,the php built-in maybe a choice.Start the built-in server by php -S localhost:port -t path/to/your/project command,setting your project dir as document root.You can refer to this post for more details.

How can I count the number of characters in a Bash variable

jcomeau@intrepid:~$ mystring="one two three four five"
jcomeau@intrepid:~$ echo "string length: ${#mystring}"
string length: 23

link Couting characters, words, lenght of the words and total lenght in a sentence

Corrupted Access .accdb file: "Unrecognized Database Format"

Well, I have tried something I hope it helps ..

They changed the schema a little bit ..

Use the following :

1- Change the AccessDataSource to SQLDataSource in the toolbox.

2- In the drop down menu choose your access database (xxxx.accdb or xxxx.mdb)

3- Next -> Next -> Test Query -> Finish.

Worked for me.

unix diff side-to-side results?

You can simply use:

diff -y fileA.txt fileB.txt | colordiff

It shows the output splitted in two colums and colorized! (colordiff)

Calling variable defined inside one function from another function

The simplest option is to use a global variable. Then create a function that gets the current word.

current_word = ''
def oneFunction(lists):
    global current_word
    word=random.choice(lists[category])
    current_word = word

def anotherFunction():
    for letter in get_word():              
          print("_",end=" ")

 def get_word():
      return current_word

The advantage of this is that maybe your functions are in different modules and need to access the variable.

Remove new lines from string and replace with one empty space

You should use str_replace for its speed and using double quotes with an array

str_replace(array("\r\n","\r"),"",$string);

how can I Update top 100 records in sql server

this piece of code can do its job

UPDATE TOP (100) table_name set column_name = value;

If you want to show the last 100 records, you can use this if you need.

With OrnekWith
as
(
Select Top(100) * from table_name Order By ID desc
)
Update table_name Set column_name = value;

How to create a JavaScript callback for knowing when an image is loaded?

You can use the .complete property of the Javascript image class.

I have an application where I store a number of Image objects in an array, that will be dynamically added to the screen, and as they're loading I write updates to another div on the page. Here's a code snippet:

var gAllImages = [];

function makeThumbDivs(thumbnailsBegin, thumbnailsEnd)
{
    gAllImages = [];

    for (var i = thumbnailsBegin; i < thumbnailsEnd; i++) 
    {
        var theImage = new Image();
        theImage.src = "thumbs/" + getFilename(globals.gAllPageGUIDs[i]);
        gAllImages.push(theImage);

        setTimeout('checkForAllImagesLoaded()', 5);
        window.status="Creating thumbnail "+(i+1)+" of " + thumbnailsEnd;

        // make a new div containing that image
        makeASingleThumbDiv(globals.gAllPageGUIDs[i]);
    }
}

function checkForAllImagesLoaded()
{
    for (var i = 0; i < gAllImages.length; i++) {
        if (!gAllImages[i].complete) {
            var percentage = i * 100.0 / (gAllImages.length);
            percentage = percentage.toFixed(0).toString() + ' %';

            userMessagesController.setMessage("loading... " + percentage);
            setTimeout('checkForAllImagesLoaded()', 20);
            return;
        }
    }

    userMessagesController.setMessage(globals.defaultTitle);
}

Selecting multiple classes with jQuery

// Due to this Code ): Syntax problem.    
$('.myClass', '.myOtherClass').removeClass('theclass'); 

According to jQuery documentation: https://api.jquery.com/multiple-selector/

When can select multiple classes in this way:

jQuery(“selector1, selector2, selectorN”) // double Commas. // IS valid.
jQuery('selector1, selector2, selectorN') // single Commas. // Is valid.

by enclosing all the selectors in a single '...' ' or double commas, "..."

So in your case the correct way to call multiple classes is:

$('.myClass', '.myOtherClass').removeClass('theclass'); // your Code // Invalid.
$('.myClass , .myOtherClass').removeClass('theclass');  // Correct Code // Is valid.

How does Tomcat locate the webapps directory?

I'm using Tomcat through XAMPP which might have been the cause of this problem. When I changed appBase="C:/Java Project/", for example, I kept getting "This localhost page can't be found" in the browser.

I had to add a folder called ROOT inside the Java Project folder and then it worked. Any files you're working on have to be inside this ROOT folder but you need to leave appBase="C:/Java Project/" as changing it to appBase="C:/Java Project/ROOT" will cause "This localhost page can't be found" to be displayed again.

Maybe needing the ROOT folder is obvious to more experienced Java developers but it wasn't for me so hopefully this helps anyone else encountering the same problem.

How to use jQuery to call an ASP.NET web service?

Here is an example to call your webservice using jQuery.get:

$.get("http://domain.com/webservice.asmx", { name: "John", time: "2pm" },
  function(data){
    alert("Data Loaded: " + data);
  });

In the example above, we call "webservice.asmx", passing two parameters: name and time. Then, getting the service output in the call back function.

How do you select a particular option in a SELECT element in jQuery?

   $(elem).find('option[value="' + value + '"]').attr("selected", "selected");

Find duplicate characters in a String and count the number of occurances using Java

I solved this with 2 dimensional array. Input: aaaabbbcdefggggh Output:a4b3cdefg4h

int[][] arr = new int[10][2];
    String st = "aaaabbbcdefggggh";
    char[] stArr = st.toCharArray();
    int i = 0;
    int j = 0;
    for (int k = 0; k < stArr.length; k++) {
        if (k == 0) {
            arr[i][j] = stArr[k];
            arr[i][j + 1] = 1;
        } else {
            if (arr[i][j] == stArr[k]) {
                arr[i][j + 1] = arr[i][j + 1] + 1;
            } else {
                arr[++i][j] = stArr[k];
                arr[i][j + 1] = 1;
            }
        }
    }
    System.out.print(arr.length);
    String output = "";
    for (int m = 0; m < arr.length; m++) {
        if (arr[m][1] > 0) {
            String character = Character.toString((char) arr[m][0]);
            String cnt = arr[m][1] > 1 ? String.valueOf(arr[m][1]) : "";
            output = output + character + cnt;

        }
    }
    System.out.print(output);

How to check if a variable is set in Bash?

There are many ways to do this with the following being one of them:

if [ -z "$1" ]

This succeeds if $1 is null or unset

Using AND/OR in if else PHP statement

You have 2 issues here.

  1. use == for comparison. You've used = which is for assignment.

  2. use && for "and" and || for "or". and and or will work but they are unconventional.

Can there be an apostrophe in an email address?

Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.

How to merge a Series and DataFrame

If df is a pandas.DataFrame then df['new_col']= Series list_object of length len(df) will add the or Series list_object as a column named 'new_col'. df['new_col']= scalar (such as 5 or 6 in your case) also works and is equivalent to df['new_col']= [scalar]*len(df)

So a two-line code serves the purpose:

df = pd.DataFrame({'a':[1, 2], 'b':[3, 4]})
s = pd.Series({'s1':5, 's2':6})
for x in s.index:    
    df[x] = s[x]

Output: 
   a  b  s1  s2
0  1  3   5   6
1  2  4   5   6

PDO error message?

From the manual:

If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object. If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling).

The prepare statement likely caused an error because the db would be unable to prepare the statement. Try testing for an error immediately after you prepare your query and before you execute it.

$qry = '
    INSERT INTO non-existant-table (id, score) 
    SELECT id, 40 
    FROM another-non-existant-table
    WHERE description LIKE "%:search_string%"
    AND available = "yes"
    ON DUPLICATE KEY UPDATE score = score + 40
';
$sth = $this->pdo->prepare($qry);
print_r($this->pdo->errorInfo());

How can we print line numbers to the log in java

The code posted by @simon.buchan will work...

Thread.currentThread().getStackTrace()[2].getLineNumber()

But if you call it in a method it will always return the line number of the line in the method so rather use the code snippet inline.

Config Error: This configuration section cannot be used at this path

In my case, I got this error because I was operating on the wrong configuration file.

I was doing this:

Configuration config = serverManager.GetWebConfiguration(websiteName);
ConfigurationSection serverRuntimeSection = config.GetSection("system.webServer/serverRuntime");
serverRuntimeSection["alternateHostName"] = hostname;

instead of the correct code:

Configuration config = serverManager.GetApplicationHostConfiguration();
ConfigurationSection serverRuntimeSection = configApp.GetSection("system.webServer/serverRuntime", websiteName);
serverRuntimeSection["alternateHostName"] = hostname;

in other words, I was trying to operate on the website's web.config instead of the global file C:\Windows\System32\inetsrv\config\applicationHost.config, which has a section (or can have a section) for the website. The setting I was trying to change exists only in the applicationHost.config file.

Java ArrayList clear() function

data.removeAll(data); will do the work, I think.

Typescript import/as vs import/require?

import * as express from "express";

This is the suggested way of doing it because it is the standard for JavaScript (ES6/2015) since last year.

In any case, in your tsconfig.json file, you should target the module option to commonjs which is the format supported by nodejs.

What I can do to resolve "1 commit behind master"?

If your branch is behind by master then do:

git checkout master (you are switching your branch to master)
git pull 
git checkout yourBranch (switch back to your branch)
git merge master

After merging it, check if there is a conflict or not.
If there is NO CONFLICT then:

git push

If there is a conflict then fix your file(s), then:

git add yourFile(s)
git commit -m 'updating my branch'
git push

How can I get file extensions with JavaScript?

return filename.replace(/\.([a-zA-Z0-9]+)$/, "$1");

edit: Strangely (or maybe it's not) the $1 in the second argument of the replace method doesn't seem to work... Sorry.

How can I post data as form data instead of a request payload?

As of AngularJS v1.4.0, there is a built-in $httpParamSerializer service that converts any object to a part of a HTTP request according to the rules that are listed on the docs page.

It can be used like this:

$http.post('http://example.com', $httpParamSerializer(formDataObj)).
    success(function(data){/* response status 200-299 */}).
    error(function(data){/* response status 400-999 */});

Remember that for a correct form post, the Content-Type header must be changed. To do this globally for all POST requests, this code (taken from Albireo's half-answer) can be used:

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

To do this only for the current post, the headers property of the request-object needs to be modified:

var req = {
 method: 'POST',
 url: 'http://example.com',
 headers: {
   'Content-Type': 'application/x-www-form-urlencoded'
 },
 data: $httpParamSerializer(formDataObj)
};

$http(req);

How do I install PyCrypto on Windows?

In general

vcvarsall.bat is part of the Visual C++ compiler, you need that to install what you are trying to install. Don't even try to deal with MingGW if your Python was compiled with Visual Studio toolchain and vice versa. Even the version of the Microsoft tool chain is important. Python compiled with VS 2008 won't work with extensions compiled with VS 2010!

You have to compile PyCrypto with the same compiler that the version of Python was compiled with. Google for "Unable to find vcvarsall.bat" because that is the root of your problem, it is a very common problem with compiling Python extensions on Windows.

There is a lot of information and a lot to read to get this right on whatever system you are on with this link.

Beware using Visual Studio 2010 or not using Visual Studio 2008

As far as I know the following is still true. This was posted in the link above in June, 2010 referring to trying to build extensions with VS 2010 Express against the Python installers available on python.org.

Be careful if you do this. Python 2.6 and 2.7 from python.org are built with Visual Studio 2008 compilers. You will need to link with the same CRT (msvcr90.dll) as Python.

Visual Studio 2010 Express links with the wrong CRT version: msvcr100.dll.

If you do this, you must also re-build Python with Visual Studio 2010 Express. You cannot use the standard Python binary installer for Windows. Nor can you use any C/C++ extensions built with a different compiler than Visual Studio 2010 (Express).

Opinion: This is one reason I abandoned Windows for all serious development work for OSX!

How do I set multipart in axios with react?

Here's how I do file upload in react using axios

import React from 'react'
import axios, { post } from 'axios';

class SimpleReactFileUpload extends React.Component {

  constructor(props) {
    super(props);
    this.state ={
      file:null
    }
    this.onFormSubmit = this.onFormSubmit.bind(this)
    this.onChange = this.onChange.bind(this)
    this.fileUpload = this.fileUpload.bind(this)
  }

  onFormSubmit(e){
    e.preventDefault() // Stop form submit
    this.fileUpload(this.state.file).then((response)=>{
      console.log(response.data);
    })
  }

  onChange(e) {
    this.setState({file:e.target.files[0]})
  }

  fileUpload(file){
    const url = 'http://example.com/file-upload';
    const formData = new FormData();
    formData.append('file',file)
    const config = {
        headers: {
            'content-type': 'multipart/form-data'
        }
    }
    return  post(url, formData,config)
  }

  render() {
    return (
      <form onSubmit={this.onFormSubmit}>
        <h1>File Upload</h1>
        <input type="file" onChange={this.onChange} />
        <button type="submit">Upload</button>
      </form>
   )
  }
}



export default SimpleReactFileUpload

Source

apache mod_rewrite is not working or not enabled

On centOS7 I changed the file /etc/httpd/conf/httpd.conf

from AllowOverride None to AllowOverride All

How do I write a SQL query for a specific date range and date time using SQL Server 2008?

DATE(readingstamp) BETWEEN '2016-07-21' AND '2016-07-31' AND TIME(readingstamp) BETWEEN '08:00:00' AND '17:59:59'

simply separate the casting of date and time

A monad is just a monoid in the category of endofunctors, what's the problem?

Note: No, this isn't true. At some point there was a comment on this answer from Dan Piponi himself saying that the cause and effect here was exactly the opposite, that he wrote his article in response to James Iry's quip. But it seems to have been removed, perhaps by some compulsive tidier.

Below is my original answer.


It's quite possible that Iry had read From Monoids to Monads, a post in which Dan Piponi (sigfpe) derives monads from monoids in Haskell, with much discussion of category theory and explicit mention of "the category of endofunctors on Hask" . In any case, anyone who wonders what it means for a monad to be a monoid in the category of endofunctors might benefit from reading this derivation.

What is the best way to check for Internet connectivity using .NET?

Another option is the Network List Manager API which is available for Vista and Windows 7. MSDN article here. In the article is a link to download code samples which allow you to do this:

AppNetworkListUser nlmUser = new AppNetworkListUser();
Console.WriteLine("Is the machine connected to internet? " + nlmUser.NLM.IsConnectedToInternet.ToString());

Be sure to add a reference to Network List 1.0 Type Library from the COM tab... which will show up as NETWORKLIST.

What's NSLocalizedString equivalent in Swift?

By using this way its possible to create a different implementation for different types (i.e. Int or custom classes like CurrencyUnit, ...). Its also possible to scan for this method invoke using the genstrings utility. Simply add the routine flag to the command

genstrings MyCoolApp/Views/SomeView.swift -s localize -o .

extension:

import UIKit

extension String {
    public static func localize(key: String, comment: String) -> String {
        return NSLocalizedString(key, comment: comment)
    }
}

usage:

String.localize("foo.bar", comment: "Foo Bar Comment :)")

Git error when trying to push -- pre-receive hook declined

I had this issue when trying to merge changes with file size greater than what remote repository allowed (in my case it was GitHub)

Role/Purpose of ContextLoaderListener in Spring?

Listener class - Listens on an event (Eg.. Server startup/shutdown)

ContextLoaderListener -

  1. Listens during server start up/shutdown
  2. Takes the Spring configuration files as input and creates the beans as per configuration and make it ready (destroys the bean during shutdown)
  3. Configuration files can be provided like this in web.xml

    <param-name>contextConfigLocation</param-name>  
    <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>  
    

How can I update NodeJS and NPM to the next versions?

Use n module from npm in order to upgrade node . n is a node helper package that installs or updates a given node.js version.

sudo npm cache clean -f
sudo npm install -g n
sudo n stable
sudo ln -sf /usr/local/n/versions/node/<VERSION>/bin/node /usr/bin/nodejs

NOTE that the default installation for nodejs is in the /usr/bin/nodejs and not /usr/bin/node

To upgrade to latest version (and not current stable) version, you can use

sudo n latest

To undo:

sudo apt-get install --reinstall nodejs-legacy     # fix /usr/bin/node
sudo n rm 6.0.0     # replace number with version of Node that was installed
sudo npm uninstall -g n

If you get the following error bash: /usr/bin/node: No such file or directory then the path you have entered at

sudo ln -sf /usr/local/n/versions/node/<VERSION>/bin/node /usr/bin/nodejs

if wrong. so make sure to check if the update nodejs has been installed at the above path and the version you are entered is correct.

I would advise strongly against doing this on a production instance. It can seriously mess stuff up with your global npm packages and your ability to install new one.

Java 8, Streams to find the duplicate elements

Basic example. First-half builds the frequency-map, second-half reduces it to a filtered list. Probably not as efficient as Dave's answer, but more versatile (like if you want to detect exactly two etc.)

List<Integer> duplicates = IntStream.of( 1, 2, 3, 2, 1, 2, 3, 4, 2, 2, 2 )
   .boxed()
   .collect( Collectors.groupingBy( Function.identity(), Collectors.counting() ) )
   .entrySet()
   .stream()
   .filter( p -> p.getValue() > 1 )
   .map( Map.Entry::getKey )
   .collect( Collectors.toList() );

Android Studio - Device is connected but 'offline'

Download and Install your device driver manually through visiting manufacturer website like :Samsung,micromax,intex etc.

How to disable margin-collapsing?

I know that this is a very old post but just wanted to say that using flexbox on a parent element would disable margin collapsing for its child elements.

How to pass multiple parameters from ajax to mvc controller?

Try this;

function X (id,parameter1,parameter2,...) {
    $.ajax({

            url: '@Url.Action("Actionre", "controller")',+ id,
            type: "Get",
            data: { parameter1: parameter1, parameter2: parameter2,...}

    }).done(function(result) {

        your code...
    });
}

So controller method would looks like :

public ActionResult ActionName(id,parameter1, parameter2,...)
{
   Your Code .......
}

How can I modify a saved Microsoft Access 2007 or 2010 Import Specification?

Tim Lentine's answer seems to be true even in the full release. There is just one other thing I would like to mention.

If you complete your import without going into "Advanced..." and saving the spec, but you do save the import for reuse at the end of the wizard (new feature AFAIK), you will not be able to go back and edit that spec. It is built into the "Saved Import". This may be what Knox was referring to.

You can, however, do a partial work around:

  1. Import a new file (or the same one all over again) but,
  2. This time choose to append, instead of making a new
  3. Click OK.
  4. Go into "advanced" All your column heading and data-types will be there.
  5. Now you can make the changes you need and save the spec inside that dialog. Then cancel out of that import (that is not what you wanted anyway, right?)
  6. You can then use that spec for any further imports. It's not a full solution, but saves some of the work.

How is the AND/OR operator represented as in Regular Expressions?

I'm going to assume you want to build a the regex dynamically to contain other words than part1 and part2, and that you want order not to matter. If so you can use something like this:

((^|, )(part1|part2|part3))+$

Positive matches:

part1
part2, part1
part1, part2, part3

Negative matches:

part1,           //with and without trailing spaces.
part3, part2, 
otherpart1

How to set the initial zoom/width for a webview

Try using a wide viewport:

 webview.getSettings().setUseWideViewPort(true);

Gradients on UIView and UILabels On iPhone

You could also use a graphic image one pixel wide as the gradient, and set the view property to expand the graphic to fill the view (assuming you are thinking of a simple linear gradient and not some kind of radial graphic).

Export tables to an excel spreadsheet in same directory

For people who find this via search engines, you do not need VBA. You can just:

1.) select the query or table with your mouse
2.) click export data from the ribbon
3.) click excel from the export subgroup
4.) follow the wizard to select the output file and location.

Easiest way to convert month name to month number in JS ? (Jan = 01)

I usually used to make a function:

function getMonth(monthStr){
    return new Date(monthStr+'-1-01').getMonth()+1
}

And call it like :

getMonth('Jan');
getMonth('Feb');
getMonth('Dec');

Git credential helper - update password

Solution using command line for Windows, Linux, and MacOS

If you have updated your GitHub password on the GitHub server, in the first attempt of the git fetch/pull/push command it generates the authentication failed message.

Execute the same git fetch/pull/push command a second time and it prompts for credentials (username and password). Enter the username and the new updated password of the GitHub server and login will be successful.

Even I had this problem, and I performed the above steps and done!!

How to mount the android img file under linux?

Another option would be to use the File Explorer in DDMS (Eclipse SDK), you can see the whole file system there and download/upload files to the desired place. That way you don't have to mount and deal with images. Just remember to set your device as USB debuggable (from Developer Tools)

Put content in HttpResponseMessage object?

No doubt that you are correct Florin. I was working on this project, and found that this piece of code:

product = await response.Content.ReadAsAsync<Product>();

Could be replaced with:

response.Content = new StringContent(string product);

How to write files to assets folder or raw folder in android?

You Can't write JSON file while in assets. as already described assets are read-only. But you can copy assets (json file/anything else in assets ) to local storage of mobile and then edit(write/read) from local storage. More storage options like shared Preference(for small data) and sqlite database(for large data) are available.

How to access array elements in a Django template?

when you render a request tou coctext some information: for exampel:

return render(request, 'path to template',{'username' :username , 'email'.email})

you can acces to it on template like this : for variabels :

{% if username %}{{ username }}{% endif %}

for array :

{% if username %}{{ username.1 }}{% endif %}
{% if username %}{{ username.2 }}{% endif %}

you can also name array objects in views.py and ten use it like:

{% if username %}{{ username.first }}{% endif %}

if there is other problem i wish to help you

Mac SQLite editor

Sqliteman is my current preference: It uses QT, so it's cross-platform. Since I develop on Windows, Linux and OS X, it helps to have the same tools available on each.

I also tried SQLite Admin (Windows, so irrelevant to the question anyway) for a while, but it seems unmaintained these days, and has the most annoying hotkeys of any application I've ever used - Ctrl-S clears the current query, with no hope of undo.

Updating MySQL primary key

You can use the IGNORE keyword too, example:

 update IGNORE table set primary_field = 'value'...............

How to get current formatted date dd/mm/yyyy in Javascript and append it to an input

To get current date/time in javascript:

var date = new Date();

If you need milliseconds for easy server-side interpretation use

var value = date.getTime();

For formatting dates into a user readable string see this

Then just write to hidden field:

document.getElementById("DATE").value = value;

TypeError: module.__init__() takes at most 2 arguments (3 given)

Your error is happening because Object is a module, not a class. So your inheritance is screwy.

Change your import statement to:

from Object import ClassName

and your class definition to:

class Visitor(ClassName):

or

change your class definition to:

class Visitor(Object.ClassName):
   etc

R memory management / cannot allocate vector of size n Mb

Consider whether you really need all this data explicitly, or can the matrix be sparse? There is good support in R (see Matrix package for e.g.) for sparse matrices.

Keep all other processes and objects in R to a minimum when you need to make objects of this size. Use gc() to clear now unused memory, or, better only create the object you need in one session.

If the above cannot help, get a 64-bit machine with as much RAM as you can afford, and install 64-bit R.

If you cannot do that there are many online services for remote computing.

If you cannot do that the memory-mapping tools like package ff (or bigmemory as Sascha mentions) will help you build a new solution. In my limited experience ff is the more advanced package, but you should read the High Performance Computing topic on CRAN Task Views.

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

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

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

Taken from comments in this post:

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

Note: For later versions of @angular/material:

Nowadays you should instead write:

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

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

Show / hide div on click with CSS

Fiddle to your heart's content

HTML

<div>
<a tabindex="1" class="testA">Test A</a> | <a tabindex="2" class="testB">Test B</a>
<div class="hiddendiv" id="testA">1</div>
<div class="hiddendiv" id="testB">2</div>
</div>

CSS

.hiddendiv {display: none; }
.testA:focus ~ #testA {display: block; }
.testB:focus ~ #testB {display: block; }

Benefits

You can put your menu links horizontally = one after the other in HTML code, and then you can put all the content one after another in the HTML code, after the menu.

In other words - other solutions offer an accordion approach where you click a link and the content appears immediately after the link. The next link then appears after that content.

With this approach you don't get the accordion effect. Rather, all links remain in a fixed position and clicking any link simply updates the displayed content. There is also no limitation on content height.

How it works

In your HTML, you first have a DIV. Everything else sits inside this DIV. This is important - it means every element in your solution (in this case, A for links, and DIV for content), is a sibling to every other element.

Secondly, the anchor tags (A) have a tabindex property. This makes them clickable and therefore they can get focus. We need that for the CSS to work. These could equally be DIVs but I like using A for links - and they'll be styled like my other anchors.

Third, each menu item has a unique class name. This is so that in the CSS we can identify each menu item individually.

Fourth, every content item is a DIV, and has the class="hiddendiv". However each each content item has a unique id.

In your CSS, we set all .hiddendiv elements to display:none; - that is, we hide them all.

Secondly, for each menu item we have a line of CSS. This means if you add more menu items (ie. and more hidden content), you will have to update your CSS, yes.

Third, the CSS is saying that when .testA gets focus (.testA:focus) then the corresponding DIV, identified by ID (#testA) should be displayed.

Last, when I just said "the corresponding DIV", the trick here is the tilde character (~) - this selector will select a sibling element, and it does not have to be the very next element, that matches the selector which, in this case, is the unique ID value (#testA).

It is this tilde that makes this solution different than others offered and this lets you simply update some "display panel" with different content, based on clicking one of those links, and you are not as constrained when it comes to where/how you organise your HTML. All you need, though, is to ensure your hidden DIVs are contained within the same parent element as your clickable links.

Season to taste.

Arduino error: does not name a type?

The only thing you have to do is adding this line to your sketch

#include <SPI.h>

before #include <Adafruit_MAX31855.h>.

Composer: Command Not Found

I am using CentOS and had same problem.

I changed /usr/local/bin/composer to /usr/bin/composer and it worked.

Run below command :

curl -sS https://getcomposer.org/installer | php sudo mv composer.phar /usr/bin/composer

Verify Composer is installed or not

composer --version

"Continue" (to next iteration) on VBScript

Your suggestion would work, but using a Do loop might be a little more readable.

This is actually an idiom in C - instead of using a goto, you can have a do { } while (0) loop with a break statement if you want to bail out of the construct early.

Dim i

For i = 0 To 10
    Do
        If i = 4 Then Exit Do
        WScript.Echo i
    Loop While False
Next

As crush suggests, it looks a little better if you remove the extra indentation level.

Dim i

For i = 0 To 10: Do
    If i = 4 Then Exit Do
    WScript.Echo i
Loop While False: Next

How To Set Up GUI On Amazon EC2 Ubuntu server

For LXDE/Lubuntu


1. connect to your instance (local forwarding port 5901)

ssh -L 5901:localhost:5901 -i "xxx.pem" [email protected]

2. Install packages

sudo apt update && sudo apt upgrade
sudo apt-get install xorg lxde vnc4server lubuntu-desktop

3. Create /etc/lightdm/lightdm.conf

sudo nano /etc/lightdm/lightdm.conf

4. Copy and paste the following into the lightdm.conf and save

[SeatDefaults]
allow-guest=false
user-session=LXDE
#user-session=Lubuntu

5. setup vncserver (you will be asked to create a password for the vncserver)

vncserver
sudo echo "lxpanel & /usr/bin/lxsession -s LXDE &" >> ~/.vnc/xstartup

6. Restart your instance and reconnect

sudo reboot
ssh -L 5901:localhost:5901 -i "xxx.pem" [email protected]

7. Start vncserver

vncserver -geometry 1280x800

8. In your Remote Desktop Client (e.g. Remmina) set Server to localhost:5901 and protocol to VNC

How to set default font family for entire Android app

To change your app font follow the following steps:

  1. Inside res directory create a new directory and name it font.
  2. Insert your font .ttf/.otf inside the font folder, Make sure the font name is lower case letters and underscore only.
  3. Inside res -> values -> styles.xml inside <resources> -> <style> add your font <item name="android:fontFamily">@font/font_name</item>.

enter image description here

Now all your app text should be in the font that you add.

TypeError: only length-1 arrays can be converted to Python scalars while plot showing

Take note of what is printed for x. You are trying to convert an array (basically just a list) into an int. length-1 would be an array of a single number, which I assume numpy just treats as a float. You could do this, but it's not a purely-numpy solution.

EDIT: I was involved in a post a couple of weeks back where numpy was slower an operation than I had expected and I realised I had fallen into a default mindset that numpy was always the way to go for speed. Since my answer was not as clean as ayhan's, I thought I'd use this space to show that this is another such instance to illustrate that vectorize is around 10% slower than building a list in Python. I don't know enough about numpy to explain why this is the case but perhaps someone else does?

import numpy as np
import matplotlib.pyplot as plt
import datetime

time_start = datetime.datetime.now()

# My original answer
def f(x):
    rebuilt_to_plot = []
    for num in x:
        rebuilt_to_plot.append(np.int(num))
    return rebuilt_to_plot

for t in range(10000):
    x = np.arange(1, 15.1, 0.1)
    plt.plot(x, f(x))

time_end = datetime.datetime.now()

# Answer by ayhan
def f_1(x):
    return np.int(x)

for t in range(10000):
    f2 = np.vectorize(f_1)
    x = np.arange(1, 15.1, 0.1)
    plt.plot(x, f2(x))

time_end_2 = datetime.datetime.now()

print time_end - time_start
print time_end_2 - time_end

JavaScript REST client Library

jQuery has JSON-REST plugin with REST style of URI parameter templates. According to its description example of using is the followin: $.Read("/{b}/{a}", { a:'foo', b:'bar', c:3 }) becomes a GET to "/bar/foo?c=3".

jQuery val is undefined?

I just ran across this myself yesterday on a project I was working on. I'm my specific case, it was not exactly what the input was named, but how the ID was named.

<input id="user_info[1][last_name]" ..... />
var last_name = $("#user_info[1][last_name]").val() // returned undefined

Removing the brackets solved the issue:

<input id="user_info1_last_name" ..... />
var last_name = $("#user_info1_last_name").val() // returned "MyLastNameValue"

Anyway, probably a no brainer for some people, but in case this helps anyone else... there you go!

:-) - Drew

Javascript reduce() on Object

Since it hasnt really been confirmed in an answer yet, Underscore's reduce also works for this.

_.reduce({ 
    a: {value:1}, 
    b: {value:2}, 
    c: {value:3} 
}, function(prev, current){
    //prev is either first object or total value
    var total = prev.value || prev

    return total + current.value
})

Note, _.reduce will return the only value (object or otherwise) if the list object only has one item, without calling iterator function.

_.reduce({ 
    a: {value:1} 
}, function(prev, current){
    //not called
})

//returns {value: 1} instead of 1