Programs & Examples On #Delayed job

A Ruby library to queue and defer processing of slow methods like sending email and image resizing.

getaddrinfo: nodename nor servname provided, or not known

I restarted my computer (Mac Mountain Lion) and the problem fixed itself. Something having to do with the shell thinking it was disconnected from the internet I think.

Restarting your shell in some definite way may solve this problem as well. Simply opening up a new session/window however did not work.

Java current machine name and logged in user?

To get the currently logged in user path:

System.getProperty("user.home");

How to get all registered routes in Express?

I published a package that prints all middleware as well as routes, really useful when trying to audit an express application. You mount the package as middleware, so it even prints out itself:

https://github.com/ErisDS/middleware-stack-printer

It prints a kind of tree like:

- middleware 1
- middleware 2
- Route /thing/
- - middleware 3
- - controller (HTTP VERB)  

C++ IDE for Linux?

I recommend you read The Art Of UNIX Progranmming. It will frame your mind into using the environment as your IDE.

How do I remove leading whitespace in Python?

To remove everything before a certain character, use a regular expression:

re.sub(r'^[^a]*', '')

to remove everything up to the first 'a'. [^a] can be replaced with any character class you like, such as word characters.

Swap two variables without using a temporary variable

For completeness, here is the binary XOR swap:

int x = 42;
int y = 51236;
x ^= y;
y ^= x;
x ^= y;

This works for all atomic objects/references, as it deals directly with the bytes, but may require an unsafe context to work on decimals or, if you're feeling really twisted, pointers. And it may be slower than a temp variable in some circumstances as well.

show loading icon until the page is load?

HTML

<body>
    <div id="load"></div>
    <div id="contents">
          jlkjjlkjlkjlkjlklk
    </div>
</body>

JS

document.onreadystatechange = function () {
  var state = document.readyState
  if (state == 'interactive') {
       document.getElementById('contents').style.visibility="hidden";
  } else if (state == 'complete') {
      setTimeout(function(){
         document.getElementById('interactive');
         document.getElementById('load').style.visibility="hidden";
         document.getElementById('contents').style.visibility="visible";
      },1000);
  }
}

CSS

#load{
    width:100%;
    height:100%;
    position:fixed;
    z-index:9999;
    background:url("https://www.creditmutuel.fr/cmne/fr/banques/webservices/nswr/images/loading.gif") no-repeat center center rgba(0,0,0,0.25)
}

Note:
you wont see any loading gif if your page is loaded fast, so use this code on a page with high loading time, and i also recommend to put your js on the bottom of the page.

DEMO

http://jsfiddle.net/6AcAr/ - with timeout(only for demo)
http://jsfiddle.net/47PkH/ - no timeout(use this for actual page)

update

http://jsfiddle.net/d9ngT/

Force sidebar height 100% using CSS (with a sticky bottom image)?

use body background if you are using fixed width sidebar give the same width image as your side bar. also put background-repeat:repeat-y in your css codes.

How to convert string date to Timestamp in java?

You can even try this.

   String date="09/08/1980";    // take a string  date
    Timestamp ts=null;  //declare timestamp
    Date d=new Date(date); // Intialize date with the string date
    if(d!=null){  // simple null check
        ts=new java.sql.Timestamp(d.getTime()); // convert gettime from date and assign it to your timestamp.
    }

XmlSerializer: remove unnecessary xsi and xsd namespaces

I'm using:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        const string DEFAULT_NAMESPACE = "http://www.something.org/schema";
        var serializer = new XmlSerializer(typeof(Person), DEFAULT_NAMESPACE);
        var namespaces = new XmlSerializerNamespaces();
        namespaces.Add("", DEFAULT_NAMESPACE);

        using (var stream = new MemoryStream())
        {
            var someone = new Person
            {
                FirstName = "Donald",
                LastName = "Duck"
            };
            serializer.Serialize(stream, someone, namespaces);
            stream.Position = 0;
            using (var reader = new StreamReader(stream))
            {
                Console.WriteLine(reader.ReadToEnd());
            }
        }
    }
}

To get the following XML:

<?xml version="1.0"?>
<Person xmlns="http://www.something.org/schema">
  <FirstName>Donald</FirstName>
  <LastName>Duck</LastName>
</Person>

If you don't want the namespace, just set DEFAULT_NAMESPACE to "".

C++ Convert string (or char*) to wstring (or wchar_t*)

int StringToWString(std::wstring &ws, const std::string &s)
{
    std::wstring wsTmp(s.begin(), s.end());

    ws = wsTmp;

    return 0;
}

Select 2 columns in one and combine them

if one of the column is number i have experienced the oracle will think '+' as sum operator instead concatenation.

eg:

select (id + name) as one from table 1; (id is numeric) 

throws invalid number exception

in such case you can || operator which is concatenation.

select (id || name) as one from table 1;

Pad left or right with string.format (not padleft or padright) with arbitrary string

Edit: I misunderstood your question, I thought you were asking how to pad with spaces.

What you are asking is not possible using the string.Format alignment component; string.Format always pads with whitespace. See the Alignment Component section of MSDN: Composite Formatting.

According to Reflector, this is the code that runs inside StringBuilder.AppendFormat(IFormatProvider, string, object[]) which is called by string.Format:

int repeatCount = num6 - str2.Length;
if (!flag && (repeatCount > 0))
{
    this.Append(' ', repeatCount);
}
this.Append(str2);
if (flag && (repeatCount > 0))
{
    this.Append(' ', repeatCount);
}

As you can see, blanks are hard coded to be filled with whitespace.

Keras input explanation: input_shape, units, batch_size, dim, etc

Input Dimension Clarified:

Not a direct answer, but I just realized the word Input Dimension could be confusing enough, so be wary:

It (the word dimension alone) can refer to:

a) The dimension of Input Data (or stream) such as # N of sensor axes to beam the time series signal, or RGB color channel (3): suggested word=> "InputStream Dimension"

b) The total number /length of Input Features (or Input layer) (28 x 28 = 784 for the MINST color image) or 3000 in the FFT transformed Spectrum Values, or

"Input Layer / Input Feature Dimension"

c) The dimensionality (# of dimension) of the input (typically 3D as expected in Keras LSTM) or (#RowofSamples, #of Senors, #of Values..) 3 is the answer.

"N Dimensionality of Input"

d) The SPECIFIC Input Shape (eg. (30,50,50,3) in this unwrapped input image data, or (30, 250, 3) if unwrapped Keras:

Keras has its input_dim refers to the Dimension of Input Layer / Number of Input Feature

model = Sequential()
model.add(Dense(32, input_dim=784))  #or 3 in the current posted example above
model.add(Activation('relu'))

In Keras LSTM, it refers to the total Time Steps

The term has been very confusing, is correct and we live in a very confusing world!!

I find one of the challenge in Machine Learning is to deal with different languages or dialects and terminologies (like if you have 5-8 highly different versions of English, then you need to very high proficiency to converse with different speakers). Probably this is the same in programming languages too.

Git 'fatal: Unable to write new index file'

Here is what worked for me:

Context:

  1. Building a project on a server

  2. git status returns a HEAD detached at <commit-SHA>

  3. What ever operation I did locally, I had this error. More specifically:

    • git checkout
    • git reset HEAD --hard

Solution

  1. Simply removed file <work-dir>/.git/index.
  2. A git status would indicate that all files in the projet are not tracked (no surprise here).
  3. git reset HEAD --hard
  4. Back to HEAD detached at <commit-SHA> when doing a git status, but then you should be able to
  5. git checkout <some-branch>

and you're back on track!

!! IMPORTANT !!

This works only because I am "merly" building. No precious modification has been performed on the code. If you are actually in "dev-time", then I would recommand to save your work first or go for another method.

Hope it will help :).

PHP - Get bool to echo false when false

This will print out boolean value as it is, instead of 1/0.

    $bool = false;

    echo json_encode($bool);   //false

Why is "npm install" really slow?

I am using Linux and have nvm and working with more than 7 version of node As of my experience I experienced the same situation with my latest project (actually not hours but minutes as I can't wait hours because of hourly project :))

Disclaimer: don't try below option until you know how cache clean works

npm cache clean --force

and then all working fine for me so it's looks like sometimes npm's cache gets confused with different versions of Node.

Official documentation of Npm cache can be found here

What's the difference between MyISAM and InnoDB?

The main differences between InnoDB and MyISAM ("with respect to designing a table or database" you asked about) are support for "referential integrity" and "transactions".

If you need the database to enforce foreign key constraints, or you need the database to support transactions (i.e. changes made by two or more DML operations handled as single unit of work, with all of the changes either applied, or all the changes reverted) then you would choose the InnoDB engine, since these features are absent from the MyISAM engine.

Those are the two biggest differences. Another big difference is concurrency. With MyISAM, a DML statement will obtain an exclusive lock on the table, and while that lock is held, no other session can perform a SELECT or a DML operation on the table.

Those two specific engines you asked about (InnoDB and MyISAM) have different design goals. MySQL also has other storage engines, with their own design goals.

So, in choosing between InnoDB and MyISAM, the first step is in determining if you need the features provided by InnoDB. If not, then MyISAM is up for consideration.

A more detailed discussion of differences is rather impractical (in this forum) absent a more detailed discussion of the problem space... how the application will use the database, how many tables, size of the tables, the transaction load, volumes of select, insert, updates, concurrency requirements, replication features, etc.


The logical design of the database should be centered around data analysis and user requirements; the choice to use a relational database would come later, and even later would the choice of MySQL as a relational database management system, and then the selection of a storage engine for each table.

font-weight is not working properly?

In my case, I was using Google's Roboto font. So I had to import it at the beginning of my page with its proper weights.

<link href = "https://fonts.googleapis.com/css?family=Roboto+Mono|Roboto+Slab|Roboto:300,400,500,700" rel = "stylesheet" />

How to bind RadioButtons to an enum?

You can create the radio buttons dynamically, ListBox can help you do that, without converters, quite simple.

The concrete steps are below:

  • create a ListBox and set the ItemsSource for the listbox as the enum MyLovelyEnum and binding the SelectedItem of the ListBox to the VeryLovelyEnum property.
  • then the Radio Buttons for each ListBoxItem will be created.
  • Step 1: add the enum to static resources for your Window, UserControl or Grid etc.
    <Window.Resources>
        <ObjectDataProvider MethodName="GetValues"
                            ObjectType="{x:Type system:Enum}"
                            x:Key="MyLovelyEnum">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="local:MyLovelyEnum" />
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>
  • Step 2: Use the List Box and Control Template to populate each item inside as Radio button
    <ListBox ItemsSource="{Binding Source={StaticResource MyLovelyEnum}}" SelectedItem="{Binding VeryLovelyEnum, Mode=TwoWay}" >
        <ListBox.Resources>
            <Style TargetType="{x:Type ListBoxItem}">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate>
                            <RadioButton
                                Content="{TemplateBinding ContentPresenter.Content}"
                                IsChecked="{Binding Path=IsSelected,
                                RelativeSource={RelativeSource TemplatedParent},
                                Mode=TwoWay}" />
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ListBox.Resources>
    </ListBox>

The advantage is: if someday your enum class changes, you do not need to update the GUI (XAML file).

References: https://brianlagunas.com/a-better-way-to-data-bind-enums-in-wpf/

Send email using java

The short answer - No.

The long answer - no, since the code relies on the presence of a SMTP server running on the local machine, and listening on port 25. The SMTP server (technically the MTA or Mail Transfer Agent) is responsible for communicating with the Mail User Agent (MUA, which in this case is the Java process) to receive outgoing emails.

Now, MTAs are typically responsible for receiving mails from users for a particular domain. So, for the domain gmail.com, it would be the Google mail servers that are responsible for authenticating mail user agents and hence transferring of mails to inboxes on the GMail servers. I'm not sure if GMail trusts open mail relay servers, but it is certainly not an easy task to perform authentication on behalf on Google, and then relay mail to the GMail servers.

If you read the JavaMail FAQ on using JavaMail to accessing GMail, you'll notice that the hostname and the port happen to be pointing to the GMail servers, and certainly not to localhost. If you intend to use your local machine, you'll need to perform either relaying or forwarding.

You'll probably need to understand the SMTP protocol in depth if you intend to get anywhere when it comes to SMTP. You can start with the Wikipedia article on SMTP, but any further progress will actually necessitate programming against a SMTP server.

C#: Limit the length of a string?

Use Remove()...

string foo = "1234567890";
int trimLength = 5;

if (foo.Length > trimLength) foo = foo.Remove(trimLength);

// foo is now "12345"

JQuery: if div is visible

You can use .is(':visible')

Selects all elements that are visible.

For example:

if($('#selectDiv').is(':visible')){

Also, you can get the div which is visible by:

$('div:visible').callYourFunction();

Live example:

_x000D_
_x000D_
console.log($('#selectDiv').is(':visible'));_x000D_
console.log($('#visibleDiv').is(':visible'));
_x000D_
#selectDiv {_x000D_
  display: none;  _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="selectDiv"></div>_x000D_
<div id="visibleDiv"></div>
_x000D_
_x000D_
_x000D_

Passing an Array as Arguments, not an Array, in PHP

For sake of completeness, as of PHP 5.1 this works, too:

<?php
function title($title, $name) {
    return sprintf("%s. %s\r\n", $title, $name);
}
$function = new ReflectionFunction('title');
$myArray = array('Dr', 'Phil');
echo $function->invokeArgs($myArray);  // prints "Dr. Phil"
?>

See: http://php.net/reflectionfunction.invokeargs

For methods you use ReflectionMethod::invokeArgs instead and pass the object as first parameter.

How does Tomcat locate the webapps directory?

Find server.xml at $CATALINA_BASE/conf/server.xml

Find appBase attribute in <Host> element

by default it will be something like : <Host name="localhost" appBase="webapps ...>

Change appBase to your required path. There are different way people put it, but I use

/c:/myfolder/newwebapps

Remember, no slash at the end, but at start. Also note it's direction as well.

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

If you are using NHibernate, check that appropriate DateTime properties that are nullable are set to nullable in the mappings.

When should I use cross apply over inner join?

This is perhaps an old question, but I still love the power of CROSS APPLY to simplify the re-use of logic and to provide a "chaining" mechanism for results.

I've provided a SQL Fiddle below which shows a simple example of how you can use CROSS APPLY to perform complex logical operations on your data set without things getting at all messy. It's not hard to extrapolate from here more complex calculations.

http://sqlfiddle.com/#!3/23862/2

Do I cast the result of malloc?

This is what The GNU C Library Reference manual says:

You can store the result of malloc into any pointer variable without a cast, because ISO C automatically converts the type void * to another type of pointer when necessary. But the cast is necessary in contexts other than assignment operators or if you might want your code to run in traditional C.

And indeed the ISO C11 standard (p347) says so:

The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object with a fundamental alignment requirement and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated)

Swift: Sort array of objects alphabetically

In the closure you pass to sort, compare the properties you want to sort by. Like this:

movieArr.sorted { $0.name < $1.name }

or the following in the cases that you want to bypass cases:

movieArr.sorted { $0.name.lowercased() < $1.name.lowercased() }

Sidenote: Typically only types start with an uppercase letter; I'd recommend using name and date, not Name and Date.


Example, in a playground:

class Movie {
    let name: String
    var date: Int?

    init(_ name: String) {
        self.name = name
    }
}

var movieA = Movie("A")
var movieB = Movie("B")
var movieC = Movie("C")

let movies = [movieB, movieC, movieA]
let sortedMovies = movies.sorted { $0.name < $1.name }
sortedMovies

sortedMovies will be in the order [movieA, movieB, movieC]

Swift5 Update

channelsArray = channelsArray.sorted { (channel1, channel2) -> Bool in
            let channelName1 = channel1.name
            let channelName2 = channel2.name
            return (channelName1.localizedCaseInsensitiveCompare(channelName2) == .orderedAscending)

UIView Hide/Show with animation

To fade out:

Objective-C

[UIView animateWithDuration:0.3 animations:^{
    button.alpha = 0;
} completion: ^(BOOL finished) {//creates a variable (BOOL) called "finished" that is set to *YES* when animation IS completed.
    button.hidden = finished;//if animation is finished ("finished" == *YES*), then hidden = "finished" ... (aka hidden = *YES*)
}];

Swift 2

UIView.animateWithDuration(0.3, animations: {
    button.alpha = 0
}) { (finished) in
    button.hidden = finished
}

Swift 3, 4, 5

UIView.animate(withDuration: 0.3, animations: {
    button.alpha = 0
}) { (finished) in
    button.isHidden = finished
}

To fade in:

Objective-C

button.alpha = 0;
button.hidden = NO;
[UIView animateWithDuration:0.3 animations:^{
    button.alpha = 1;
}];

Swift 2

button.alpha = 0
button.hidden = false
UIView.animateWithDuration(0.3) {
    button.alpha = 1
}

Swift 3, 4, 5

button.alpha = 0
button.isHidden = false
UIView.animate(withDuration: 0.3) {
    button.alpha = 1
}

How to open html file?

import codecs
f=codecs.open("test.html", 'r')
print f.read()

Try something like this.

How can I access a hover state in reactjs?

I know the accepted answer is great but for anyone who is looking for a hover like feel you can use setTimeout on mouseover and save the handle in a map (of let's say list ids to setTimeout Handle). On mouseover clear the handle from setTimeout and delete it from the map

onMouseOver={() => this.onMouseOver(someId)}
onMouseOut={() => this.onMouseOut(someId)

And implement the map as follows:

onMouseOver(listId: string) {
  this.setState({
    ... // whatever
  });

  const handle = setTimeout(() => {
    scrollPreviewToComponentId(listId);
  }, 1000); // Replace 1000ms with any time you feel is good enough for your hover action
  this.hoverHandleMap[listId] = handle;
}

onMouseOut(listId: string) {
  this.setState({
    ... // whatever
  });

  const handle = this.hoverHandleMap[listId];
  clearTimeout(handle);
  delete this.hoverHandleMap[listId];
}

And the map is like so,

hoverHandleMap: { [listId: string]: NodeJS.Timeout } = {};

I prefer onMouseOver and onMouseOut because it also applies to all the children in the HTMLElement. If this is not required you may use onMouseEnter and onMouseLeave respectively.

How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error

In my case , issue was completely different. I have two classes let's say c1 & c2. Between C1 & C2 dependency is OneToMany. Now if i am saving C1 in DB it was throwing above error.

Resolution of this problem was to get first C2's id from consumer request and find C2 via repository call.Afterwards save c2 into C1 object .Now if i am saving C1, it's working fine.

How to display custom view in ActionBar?

For example, you can define a layout file which contains a EditText element.

<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/searchfield"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:inputType="textFilter" >

</EditText> 

you can do

public class MainActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ActionBar actionBar = getActionBar();
    // add the custom view to the action bar
    actionBar.setCustomView(R.layout.actionbar_view);
    EditText search = (EditText) actionBar.getCustomView().findViewById(R.id.searchfield);
    search.setOnEditorActionListener(new OnEditorActionListener() {

      @Override
      public boolean onEditorAction(TextView v, int actionId,
          KeyEvent event) {
        Toast.makeText(MainActivity.this, "Search triggered",
            Toast.LENGTH_LONG).show();
        return false;
      }
    });
    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM
        | ActionBar.DISPLAY_SHOW_HOME);


    }

Conversion failed when converting date and/or time from character string while inserting datetime

I had this issue when trying to concatenate getdate() into a string that I was inserting into an nvarchar field.

I did some casting to get around it:

 INSERT INTO [SYSTEM_TABLE] ([SYSTEM_PROP_TAG],[SYSTEM_PROP_VAL]) VALUES 
   (
    'EMAIL_HEADER',
    '<h2>111 Any St.<br />Anywhere, ST 11111</h2><br />' + 
        CAST(CAST(getdate() AS datetime2) AS nvarchar) + 
    '<br /><br /><br />'
   )

That's a sanitized example. The key portion of that is:

...' + CAST(CAST(getdate() AS datetime2) AS nvarchar) + '...

Casted the date as datetime2, then as nvarchar to concatenate it.

pull access denied repository does not exist or may require docker login

November 2020 and later

If this error is new, and pulling from Docker Hub worked in the past, note Docker Hub now introduced rate limiting in Nov 2020

You will frequently see messages like:

Warning: No authentication provided, using CircleCI credentials for pulls from Docker Hub.

From Circle CI and other similar tools that use Docker Hub. Or:

Error response from daemon: pull access denied for cimg/mongo, repository does not exist or may require 'docker login': denied: requested access to the resource is denied

You'll need to specify the credentials used to fetch the image:

For CircleCI users:

      - image: circleci/mongo:4.4.2

        # Needed to pull down Mongo images from Docker hub
        # Get from https://hub.docker.com/
        # Set up at https://app.circleci.com/pipelines/github/org/sapp
        auth:
          username: $DOCKERHUB_USERNAME
          password: $DOCKERHUB_PASSWORD

How to select rows with one or more nulls from a pandas DataFrame without listing columns explicitly?

[Updated to adapt to modern pandas, which has isnull as a method of DataFrames..]

You can use isnull and any to build a boolean Series and use that to index into your frame:

>>> df = pd.DataFrame([range(3), [0, np.NaN, 0], [0, 0, np.NaN], range(3), range(3)])
>>> df.isnull()
       0      1      2
0  False  False  False
1  False   True  False
2  False  False   True
3  False  False  False
4  False  False  False
>>> df.isnull().any(axis=1)
0    False
1     True
2     True
3    False
4    False
dtype: bool
>>> df[df.isnull().any(axis=1)]
   0   1   2
1  0 NaN   0
2  0   0 NaN

[For older pandas:]

You could use the function isnull instead of the method:

In [56]: df = pd.DataFrame([range(3), [0, np.NaN, 0], [0, 0, np.NaN], range(3), range(3)])

In [57]: df
Out[57]: 
   0   1   2
0  0   1   2
1  0 NaN   0
2  0   0 NaN
3  0   1   2
4  0   1   2

In [58]: pd.isnull(df)
Out[58]: 
       0      1      2
0  False  False  False
1  False   True  False
2  False  False   True
3  False  False  False
4  False  False  False

In [59]: pd.isnull(df).any(axis=1)
Out[59]: 
0    False
1     True
2     True
3    False
4    False

leading to the rather compact:

In [60]: df[pd.isnull(df).any(axis=1)]
Out[60]: 
   0   1   2
1  0 NaN   0
2  0   0 NaN

Radio button validation in javascript

In addition to the Javascript solutions above, you can also use an HTML 5 solution by marking the radio buttons as required in the markup. This will eliminate the need for any Javascript and let the browser do the work for you.

See HTML5: How to use the "required" attribute with a "radio" input field for more information on how to do this well.

Optional args in MATLAB functions

A good way of going about this is not to use nargin, but to check whether the variables have been set using exist('opt', 'var').

Example:

function [a] = train(x, y, opt)
    if (~exist('opt', 'var'))
        opt = true;
    end
end

See this answer for pros of doing it this way: How to check whether an argument is supplied in function call?

Error Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35

I found the problem. Instead of adding a class (.cs) file by mistake I had added a Web API Controller class which added a configuration file in my solution. And that configuration file was looking for the mentioned DLL (Microsoft.Web.Infrastructure 1.0.0.0). It worked when I removed that file, cleaned the application and then published.

Generating a unique machine id

For one of my applications, I either use the computer name if it is non-domain computer, or the domain machine account SID for domain computers. Mark Russinovich talks about it in this blog post, Machine SID:

The final case where SID duplication would be an issue is if a distributed application used machine SIDs to uniquely identify computers. No Microsoft software does so and using the machine SID in that way doesn’t work just for the fact that all DC’s have the same machine SID. Software that relies on unique computer identities either uses computer names or computer Domain SIDs (the SID of the computer accounts in the Domain).

You can access the domain machine account SID via LDAP or System.DirectoryServices.

Python: One Try Multiple Except

Yes, it is possible.

try:
   ...
except FirstException:
   handle_first_one()

except SecondException:
   handle_second_one()

except (ThirdException, FourthException, FifthException) as e:
   handle_either_of_3rd_4th_or_5th()

except Exception:
   handle_all_other_exceptions()

See: http://docs.python.org/tutorial/errors.html

The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)

What is the difference between Set and List?

List :

  1. List is ordered grouping elements
  2. List provides positional access in the elements of the collections.
  3. We can store duplicate elements in the list.
  4. List implements ArrayList, LinkedList, Vector and Stack.
  5. List can store multiple null elements.

Set :

  1. Unorderd grouping elements.
  2. Set doesn’t provides positional access in the elements of the collections.
  3. We can’t store duplicate elements in the set.
  4. Set implement HashSet and LinkedHashSet interfaces.
  5. Set can store only one null elements.

html form - make inputs appear on the same line

This test shows three blocks of two blocks together on the same line.

_x000D_
_x000D_
.group {
    display:block;
    box-sizing:border-box;
}
.group>div {
    display:inline-block;
    padding-bottom:4px;
}
.group>div>span,.group>div>div {
    width:200px;
    height:40px;
    text-align: center;
    padding-top:20px;
    padding-bottom:0px;
    display:inline-block;
    border:1px solid black;
    background-color:blue;
    color:white;
}

input[type=text] {
    height:1em;
}
_x000D_
<div class="group">
    <div>
        <span>First Name</span>
        <span><input type="text"/></span>
    </div>
    <div>
        <div>Last Name</div>
        <div><input type="text"/></div>
    </div>
    <div>
        <div>Address</div>
        <div><input type="text"/></div>
    </div>
</div>
_x000D_
_x000D_
_x000D_

MemoryStream - Cannot access a closed Stream

Since .net45 you can use the LeaveOpen constructor argument of StreamWriter and still use the using statement. Example:

using (var ms = new MemoryStream())
{
    using (var sw = new StreamWriter(ms, Encoding.UTF8, 1024, true))
    {
        sw.WriteLine("data");
        sw.WriteLine("data 2");    
    }

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

WaitAll vs WhenAll

What do they do:

  • Internally both do the same thing.

What's the difference:

  • WaitAll is a blocking call
  • WhenAll - not - code will continue executing

Use which when:

  • WaitAll when cannot continue without having the result
  • WhenAll when what just to be notified, not blocked

Stick button to right side of div

It depends on what exactly you want to achieve.

If you just want to have it on the right, then I'd recommend against using position absolute, because it opens a whole can of worms down the line.

The HTML can also be unchanged:

HTML

<div>
    <h1> Ok </h1>
    <button type='button'>Button</button>
</div>

the CSS then should be something along the lines of:

CSS

div {
    background: purple;
    overflow: hidden;
}

div h1 {
    text-align: center;
    display: inline-block;
    width: 100%;
    margin-right: -50%;
}

div button {
    float: right;
}

You can see it in action here: http://jsfiddle.net/azhH5/

If you can change the HTML, then it gets a bit simpler:

HTML

<div>
    <button type='button'>Button</button>
    <h1> Ok </h1>
</div>

CSS

div {
    background: purple;
    overflow: hidden;
}

div h1 {
    text-align: center;
}

div button {
    float: right;
    margin-left: -50%;
}

You can see it in action: http://jsfiddle.net/8WA3k/1/

If you want to have the button on the same line as the Text, you can achieve it by doing this:

HTML

<div>
    <button type='button'>Button</button>
    <h1> Ok </h1>
</div>

CSS

div {
    background: purple;
    overflow: hidden;
}

div h1 {
    text-align: center;
}

div button {
    float: right;
    margin-left: -50%;
    margin-top: 2em;
}

You an see that in action here: http://jsfiddle.net/EtqVh/1/

Cleary in the lest example you'd have to adjust the margin-top for the specified font-size of the <h1>

EDIT:

As you can see, it doesn't get popped out of the <div>, it's till inside. this is achieved by two things: the negative margin on the <button>, and the overflow: hidden; on the <div>

EDIT 2:

I just saw that you also want it to be a bit away from the margin on the right. That's easily achievable with this method. Just add margin-right: 1em; to the <button>, like this:

div {
    background: purple;
    overflow: hidden;
}

div h1 {
    text-align: center;
}

div button {
    float: right;
    margin-left: -50%;
    margin-top: 2em;
    margin-right: 1em;
}

You can see it in action here: http://jsfiddle.net/QkvGb/

Is JavaScript a pass-by-reference or pass-by-value language?

A very detailed explanation about copying, passing and comparing by value and by reference is in this chapter of the "JavaScript: The Definitive Guide" book.

Before we leave the topic of manipulating objects and arrays by reference, we need to clear up a point of nomenclature.

The phrase "pass by reference" can have several meanings. To some readers, the phrase refers to a function invocation technique that allows a function to assign new values to its arguments and to have those modified values visible outside the function. This is not the way the term is used in this book.

Here, we mean simply that a reference to an object or array -- not the object itself -- is passed to a function. A function can use the reference to modify properties of the object or elements of the array. But if the function overwrites the reference with a reference to a new object or array, that modification is not visible outside of the function.

Readers familiar with the other meaning of this term may prefer to say that objects and arrays are passed by value, but the value that is passed is actually a reference rather than the object itself.

Cannot execute script: Insufficient memory to continue the execution of the program

sqlcmd -S mamxxxxxmu\sqlserverr -U sa -P x1123 -d QLDB -i D:\qldbscript.sql

  • Open command prompt in run as administrator

  • enter above command

"mamxxxxxmu" is computer name "sqlserverr" is server name "sa" is username of server "x1123" is password of server "QLDB" is database name "D:\qldbscript.sql" is sql script file to execute in database

Adding a Button to a WPF DataGrid

Check this out:

XAML:

<DataGrid Name="DataGrid1">
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Click="ChangeText">Show/Hide</Button>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

Method:

private void ChangeText(object sender, RoutedEventArgs e)
{
    DemoModel model = (sender as Button).DataContext as DemoModel;
    model.DynamicText = (new Random().Next(0, 100).ToString());
}

Class:

class DemoModel : INotifyPropertyChanged
{
    protected String _text;
    public String Text
    {
        get { return _text; }
        set { _text = value; RaisePropertyChanged("Text"); }
    }

    protected String _dynamicText;
    public String DynamicText
    {
        get { return _dynamicText; }
        set { _dynamicText = value; RaisePropertyChanged("DynamicText"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void RaisePropertyChanged(String propertyName)
    {
        PropertyChangedEventHandler temp = PropertyChanged;
        if (temp != null)
        {
            temp(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Initialization Code:

ObservableCollection<DemoModel> models = new ObservableCollection<DemoModel>();
models.Add(new DemoModel() { Text = "Some Text #1." });
models.Add(new DemoModel() { Text = "Some Text #2." });
models.Add(new DemoModel() { Text = "Some Text #3." });
models.Add(new DemoModel() { Text = "Some Text #4." });
models.Add(new DemoModel() { Text = "Some Text #5." });
DataGrid1.ItemsSource = models;

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?

The linked list holds operations on the shared data structure.

For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).

In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.

In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.

How can two strings be concatenated?

help.search() is a handy function, e.g.

> help.search("concatenate")

will lead you to paste().

Spring - download response as a file

//JAVA PART

@RequestMapping(value = "/report-excel", method = RequestMethod.GET)
    public ResponseEntity<byte[]> getReportExcel(@RequestParam("bookingStatusType") String bookingStatusType,
            @RequestParam("endDate") String endDate, @RequestParam("product") String product, @RequestParam("startDate") String startDate)throws IOException, ParseException {

//Generate Excel from DTO using any logic after that do the following
byte[] body = wb.getBytes();
HttpHeaders header = new HttpHeaders();
        header.setContentType(new MediaType("application", "xlsx"));
        header.set("Content-Disposition", "inline; filename=" + fileName);
        header.setCacheControl("must-revalidate, post-check=0, pre-check=0");
        header.setContentLength(body.length);

 return new ResponseEntity<byte[]>(body, header, HttpStatus.OK);
}



//HTML PART
<html>
<head>
<title>Test</title>
<meta http-equiv="content-type" content="application/x-www-form-urlencoded; charset=UTF-8">
</head>
<body>
  <form name="downloadXLS" method="get" action="http://localhost:8080/rest/report-excel" enctype="multipart/form-data">
    <input type="text" name="bookingStatusType" value="SALES"></input>
    <input type="text" name="endDate" value="abcd"></input>
    <input type="text" name="product" value="FLIGHT"></input>
    <input type="text" name="startDate" value="abcd"></input>
    <input onclick="document.downloadXLS.submit()" value="Submit"></input>
  </form>
</body>
</html>

How do I call a JavaScript function on page load?

Your original question was unclear, assuming Kevin's edit/interpretation is correct then this first option doesn't apply

The typical options is using the onload event:

<body onload="javascript:SomeFunction()">
....

You can also place your javascript at the very end of the body; it won't start executing until the doc is complete.

<body>
  ...
  <script type="text/javascript">
    SomeFunction();
  </script>
</body>

And, another options, is to consider using a JS framework which intrinsically does this:

// jQuery
$(document).ready( function () {
  SomeFunction();
});

AttributeError: 'str' object has no attribute 'strftime'

You should use datetime object, not str.

>>> from datetime import datetime
>>> cr_date = datetime(2013, 10, 31, 18, 23, 29, 227)
>>> cr_date.strftime('%m/%d/%Y')
'10/31/2013'

To get the datetime object from the string, use datetime.datetime.strptime:

>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2013, 10, 31, 18, 23, 29, 227)
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f').strftime('%m/%d/%Y')
'10/31/2013'

Recursive file search using PowerShell

I use this to find files and then have PowerShell display the entire path of the results:

dir -Path C:\FolderName -Filter FileName.fileExtension -Recurse | %{$_.FullName}

You can always use the wildcard * in the FolderName and/or FileName.fileExtension. For example:

dir -Path C:\Folder* -Filter File*.file* -Recurse | %{$_.FullName}

The above example will search any folder in the C:\ drive beginning with the word Folder. So if you have a folder named FolderFoo and FolderBar PowerShell will show results from both of those folders.

The same goes for the file name and file extension. If you want to search for a file with a certain extension, but don't know the name of the file, you can use:

dir -Path C:\FolderName -Filter *.fileExtension -Recurse | %{$_.FullName}

Or vice versa:

dir -Path C:\FolderName -Filter FileName.* -Recurse | %{$_.FullName}

How to add parameters to an external data query in Excel which can't be displayed graphically?

YES - solution is to save workbook in to XML file (eg. 'XML Spreadsheet 2003') and edit this file as text in notepad! use "SEARCH" function of notepad to find query text and change your data to "?".

save and open in excel, try refresh data and excel will be monit about parameters.

Add custom headers to WebView resource requests - android

Use this:

webView.getSettings().setUserAgentString("User-Agent");

Java List.contains(Object with field value equal to x)

Binary Search

You can use Collections.binarySearch to search an element in your list (assuming the list is sorted):

Collections.binarySearch(list, new YourObject("a1", "b",
                "c"), new Comparator<YourObject>() {

            @Override
            public int compare(YourObject o1, YourObject o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });

which will return a negative number if the object is not present in the collection or else it will return the index of the object. With this you can search for objects with different searching strategies.

How do I shutdown, restart, or log off Windows via a bat file?

Another small tip: when going the batch file route, I like to be able to abort it in case I run it accidentally. So the batch file invokes the shutdown but leaves you at the command prompt afterwards.

@echo off
echo Shutting down in 10 seconds. Please type "shutdown /a" to abort.
cmd.exe /K shutdown /f /t 10 /r

Plus, since it's on a timer, you get about the same thrill as you do when hunting in The Oregon Trail.

Fill drop down list on selection of another drop down list

enter image description here

enter image description here

enter image description here

Model:

namespace MvcApplicationrazor.Models
{
    public class CountryModel
    {
        public List<State> StateModel { get; set; }
        public SelectList FilteredCity { get; set; }
    }
    public class State
    {
        public int Id { get; set; }
        public string StateName { get; set; }
    }
    public class City
    {
        public int Id { get; set; }
        public int StateId { get; set; }
        public string CityName { get; set; }
    }
}   

Controller:

public ActionResult Index()
        {
            CountryModel objcountrymodel = new CountryModel();
            objcountrymodel.StateModel = new List<State>();
            objcountrymodel.StateModel = GetAllState();
            return View(objcountrymodel);
        }


        //Action result for ajax call
        [HttpPost]
        public ActionResult GetCityByStateId(int stateid)
        {
            List<City> objcity = new List<City>();
            objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
            SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
            return Json(obgcity);
        }
        // Collection for state
        public List<State> GetAllState()
        {
            List<State> objstate = new List<State>();
            objstate.Add(new State { Id = 0, StateName = "Select State" });
            objstate.Add(new State { Id = 1, StateName = "State 1" });
            objstate.Add(new State { Id = 2, StateName = "State 2" });
            objstate.Add(new State { Id = 3, StateName = "State 3" });
            objstate.Add(new State { Id = 4, StateName = "State 4" });
            return objstate;
        }
        //collection for city
        public List<City> GetAllCity()
        {
            List<City> objcity = new List<City>();
            objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
            objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
            objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
            objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
            objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
            objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
            return objcity;
        }

View:

@model MvcApplicationrazor.Models.CountryModel
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
    function GetCity(_stateId) {
        var procemessage = "<option value='0'> Please wait...</option>";
        $("#ddlcity").html(procemessage).show();
        var url = "/Test/GetCityByStateId/";

        $.ajax({
            url: url,
            data: { stateid: _stateId },
            cache: false,
            type: "POST",
            success: function (data) {
                var markup = "<option value='0'>Select City</option>";
                for (var x = 0; x < data.length; x++) {
                    markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                }
                $("#ddlcity").html(markup).show();
            },
            error: function (reponse) {
                alert("error : " + reponse);
            }
        });

    }
</script>
<h4>
 MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
    @Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
    <br />
    <br />
    <select id="ddlcity" name="ddlcity" style="width: 200px">

    </select>

    <br /><br />
  }

NPM Install Error:Unexpected end of JSON input while parsing near '...nt-webpack-plugin":"0'

This happens something due to cache or outdated version of Node Package Manager i just updated my NPM it works fine here is command to update Npm to latest version

npm i npm@latest -g

after updating NPM run your desired command

How to return data from PHP to a jQuery ajax call

I figured it out. Need to use echo in PHP instead of return.

<?php 
  $output = some_function();
  echo $output;
?> 

And the jQ:

success: function(data) {
  doSomething(data);
}

Why are hexadecimal numbers prefixed with 0x?

It's a prefix to indicate the number is in hexadecimal rather than in some other base. The C programming language uses it to tell compiler.

Example:

0x6400 translates to 6*16^3 + 4*16^2 + 0*16^1 +0*16^0 = 25600. When compiler reads 0x6400, It understands the number is hexadecimal with the help of 0x term. Usually we can understand by (6400)16 or (6400)8 or whatever ..

For binary it would be:

0b00000001

Hope I have helped in some way.

Good day!

Start a fragment via Intent within a Fragment

Try this it may help you:

public void ButtonClick(View view) {
    Fragment mFragment = new YourNextFragment(); 
    getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, mFragment).commit();
}

Why doesn't calling a Python string method do anything unless you assign its output?

All string functions as lower, upper, strip are returning a string without modifying the original. If you try to modify a string, as you might think well it is an iterable, it will fail.

x = 'hello'
x[0] = 'i' #'str' object does not support item assignment

There is a good reading about the importance of strings being immutable: Why are Python strings immutable? Best practices for using them

CSS vertical-align: text-bottom;

Modern solution

Flexbox was created for exactly these kind of problems:

_x000D_
_x000D_
#container {_x000D_
    height: 150px;/*Only for the demo.*/_x000D_
    background-color:green;/*Only for the demo.*/_x000D_
    display: flex;_x000D_
    justify-content: center;_x000D_
    align-items: flex-end;_x000D_
}
_x000D_
<div id="container">_x000D_
    <span>Text align to center bottom.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Old school solution

If you don't want to mess with table displays, then you can create a <div> inside a relatively positioned parent container, place it to the bottom with absolute positioning, then make it 100% wide, so you can text-align it to the center:

_x000D_
_x000D_
#container {_x000D_
    height: 150px;/*Only for the demo.*/_x000D_
    background-color:green;/*Only for the demo.*/_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
#text {_x000D_
    position: absolute;_x000D_
    bottom: 0;_x000D_
    width: 100%;_x000D_
    text-align: center;_x000D_
}
_x000D_
<div id="container">_x000D_
    <span id="text">Text align to center bottom.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to create a new schema/new user in Oracle Database 11g?

It's a working example:

CREATE USER auto_exchange IDENTIFIED BY 123456;
GRANT RESOURCE TO auto_exchange;
GRANT CONNECT TO auto_exchange;
GRANT CREATE VIEW TO auto_exchange;
GRANT CREATE SESSION TO auto_exchange;
GRANT UNLIMITED TABLESPACE TO auto_exchange;

How can I capture packets in Android?

It's probably worth mentioning that for http/https some people proxy their browser traffic through Burp/ZAP or another intercepting "attack proxy". A thread that covers options for this on Android devices can be found here: https://android.stackexchange.com/questions/32366/which-browser-does-support-proxies

php check if array contains all array values from another array

Look at array_intersect().

$containsSearch = count(array_intersect($search_this, $all)) == count($search_this);

Display an image into windows forms

There could be many reasons for this. A few that come up quickly to my mind:

  1. Did you call this routine AFTER InitializeComponent()?
  2. Is the path syntax you are using correct? Does it work if you try it in the debugger? Try using backslash (\) instead of Slash (/) and see.
  3. This may be due to side-effects of some other code in your form. Try using the same code in a blank Form (with just the constructor and this function) and check.

Making a triangle shape using xml definitions?

You can use vector drawables.

If your minimum API is lower than 21, Android Studio automatically creates PNG bitmaps for those lower versions at build time (see Vector Asset Studio). If you use the support library, Android even manages "real vectors" down to API 7 (more on that in the update of this post at the bottom).

A red upwards pointing triangle would be:

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:height="100dp"
    android:width="100dp"
    android:viewportHeight="100"
    android:viewportWidth="100" >
    <group
        android:name="triableGroup">
        <path
            android:name="triangle"
            android:fillColor="#FF0000"
            android:pathData="m 50,0 l 50,100 -100,0 z" />
    </group>
</vector>

Add it to your layout and remember to set clipChildren="false" if you rotate the triangle.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipChildren="false">

    <ImageView
        android:layout_width="130dp"
        android:layout_height="100dp"
        android:rotation="0"
        android:layout_centerInParent="true"
        android:background="@drawable/triangle"/>

</RelativeLayout>

enter image description here

Change the size (width/height) of the triangle by setting the Views layout_width/layout_height attributes. This way you can also get an eqilateral triagle if you do the math correct.

UPDATE 25.11.2017

If you use the support library you can use real vectors (instead if bitmap creation) as far back as API 7. Simply add:

vectorDrawables.useSupportLibrary = true

do your defaultConfig in your module's build.gradle.

Then set the (vector xml) drawable like this:

<ImageView
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    app:srcCompat="@drawable/triangle" />

Everything is documented very nicely on the Vector Asset Studio page.

Ever since this feature I've been working entirely without bitmaps in terms of icons. This also reduces APK size quite a bit.

This could be due to the service endpoint binding not using the HTTP protocol

My problem was too many items were being passed between client and server. I had to change this settings in the behavior on both sides.

<dataContractSerializer maxItemsInObjectGraph="2147483646"/>

SQL Statement with multiple SETs and WHEREs

NO!

You'll need to handle those individually

Update [table]
Set ID = 111111259
WHERE ID = 2555

Update [table]
Set ID = 111111261
WHERE ID = 2724

--...

printf \t option

That's something controlled by your terminal, not by printf.

printf simply sends a \t to the output stream (which can be a tty, a file etc), it doesn't send a number of spaces.

Get single row result with Doctrine NativeQuery

->getSingleScalarResult() will return a single value, instead of an array.

Fatal error: Maximum execution time of 30 seconds exceeded

All the answers above are correct, but I use a simple way to avoid it in some cases.

Just put this command in the begining of your script:

set_time_limit(0);

How to round down to nearest integer in MySQL?

It can be done in the following two ways:

  • select floor(desired_field_value) from table
  • select round(desired_field_value-0.5) from table

The 2nd-way explanation: Assume 12345.7344 integer. So, 12345.7344 - 0.5 = 12345.2344 and rounding off the result will be 12345.

React - How to get parameter value from query string?

React Router v4

const urlParams = new URLSearchParams(this.props.location.search)
const key = urlParams.get('__firebase_request_key')

Please note that it is currently experimental.

Check browser compatibility here: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams#Browser_compatibility

JavaScript blob filename without link

This is my solution. From my point of view, you can not bypass the <a>.

_x000D_
_x000D_
function export2json() {_x000D_
  const data = {_x000D_
    a: '111',_x000D_
    b: '222',_x000D_
    c: '333'_x000D_
  };_x000D_
  const a = document.createElement("a");_x000D_
  a.href = URL.createObjectURL(_x000D_
    new Blob([JSON.stringify(data, null, 2)], {_x000D_
      type: "application/json"_x000D_
    })_x000D_
  );_x000D_
  a.setAttribute("download", "data.json");_x000D_
  document.body.appendChild(a);_x000D_
  a.click();_x000D_
  document.body.removeChild(a);_x000D_
}
_x000D_
<button onclick="export2json()">Export data to json file</button>
_x000D_
_x000D_
_x000D_

How to start activity in another application?

If you guys are facing "Permission Denial: starting Intent..." error or if the app is getting crash without any reason during launching the app - Then use this single line code in Manifest

android:exported="true"

Please be careful with finish(); , if you missed out it the app getting frozen. if its mentioned the app would be a smooth launcher.

finish();

The other solution only works for two activities that are in the same application. In my case, application B doesn't know class com.example.MyExampleActivity.class in the code, so compile will fail.

I searched on the web and found something like this below, and it works well.

Intent intent = new Intent();
intent.setComponent(new ComponentName("com.example", "com.example.MyExampleActivity"));
startActivity(intent);

You can also use the setClassName method:

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.hotfoot.rapid.adani.wheeler.android", "com.hotfoot.rapid.adani.wheeler.android.view.activities.MainActivity");
startActivity(intent);
finish();

You can also pass the values from one app to another app :

Intent launchIntent = getApplicationContext().getPackageManager().getLaunchIntentForPackage("com.hotfoot.rapid.adani.wheeler.android.LoginActivity");
if (launchIntent != null) {
    launchIntent.putExtra("AppID", "MY-CHILD-APP1");
    launchIntent.putExtra("UserID", "MY-APP");
    launchIntent.putExtra("Password", "MY-PASSWORD");
    startActivity(launchIntent);
    finish();
} else {
    Toast.makeText(getApplicationContext(), " launch Intent not available", Toast.LENGTH_SHORT).show();
}

TypeError: list indices must be integers or slices, not str

I had same error and the mistake was that I had added list and dictionary into the same list (object) and when I used to iterate over the list of dictionaries and use to hit a list (type) object then I used to get this error.

Its was a code error and made sure that I only added dictionary objects to that list and list typed object into the list, this solved my issue as well.

What's the difference between Thread start() and Runnable run()

The difference is that Thread.start() starts a thread that calls the run() method, while Runnable.run() just calls the run() method on the current thread.

Tomcat 8 Maven Plugin for Java 8

groupId and Mojo name change Since version 2.0-beta-1 tomcat mojos has been renamed to tomcat6 and tomcat7 with the same goals.

You must configure your pom to use this new groupId:

<pluginManagement>
  <plugins>
    <plugin>
      <groupId>org.apache.tomcat.maven</groupId>
      <artifactId>tomcat6-maven-plugin</artifactId>
      <version>2.3-SNAPSHOT</version>
    </plugin>
    <plugin>
      <groupId>org.apache.tomcat.maven</groupId>
      <artifactId>tomcat7-maven-plugin</artifactId>
      <version>2.3-SNAPSHOT</version>
    </plugin>
  </plugins>
</pluginManagement>

Or add the groupId in your settings.xml

.... org.apache.tomcat.maven ....

java.io.FileNotFoundException: class path resource cannot be opened because it does not exist

We can also try this solution

ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:app-context.xml");

in this the spring automatically finds the class in the class path itself

Javascript to check whether a checkbox is being checked or unchecked

To toggle a checkbox or you can use

element.checked = !element.checked;

so you could use

if (attribute == elementName)
{
    arrChecks[i].checked = !arrChecks[i].checked;
} else {
    arrChecks[i].checked = false;
}

Auto start print html page using javascript

<body onload="window.print()"> or window.onload = function() { window.print(); }

What are the differences between WCF and ASMX web services?

ASMX Web services can only be invoked by HTTP (traditional webservice with .asmx). While WCF Service or a WCF component can be invoked by any protocol (like http, tcp etc.) and any transport type.

Second, ASMX web services are not flexible. However, WCF Services are flexible. If you make a new version of the service then you need to just expose a new end. Therefore, services are agile and which is a very practical approach looking at the current business trends.

We develop WCF as contracts, interface, operations, and data contracts. As the developer we are more focused on the business logic services and need not worry about channel stack. WCF is a unified programming API for any kind of services so we create the service and use configuration information to set up the communication mechanism like HTTP/TCP/MSMQ etc

Increment a value in Postgres

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill';

If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill'
  AND total = 203;

iPhone Debugging: How to resolve 'failed to get the task for process'?

Check ur code signing section.make sure that the code signing is iPhoneDeveloper code signe

Access-Control-Allow-Origin Multiple Origin Domains?

If you try so many code examples like me to make it work using CORS, it is worth to mention that you have to clear your cache first to try if it actually works, similiar to issues like when old images are still present, even if it's deleted on the server (because it is still saved in your cache).

For example CTRL + SHIFT + DEL in Google Chrome to delete your cache.

This helped me using this code after trying many pure .htaccess solutions and this seemed the only one working (at least for me):

    Header add Access-Control-Allow-Origin "http://google.com"
    Header add Access-Control-Allow-Headers "authorization, origin, user-token, x-requested-with, content-type"
    Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

    <FilesMatch "\.(ttf|otf|eot|woff)$">
        <IfModule mod_headers.c>
            SetEnvIf Origin "http(s)?://(www\.)?(google.com|staging.google.com|development.google.com|otherdomain.com|dev02.otherdomain.net)$" AccessControlAllowOrigin=$0
            Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
        </IfModule>
    </FilesMatch>

Also note that it is widely spread that many solutions say you have to type Header set ... but it is Header add .... Hope this helps someone having the same troubles for some hours now like me.

onClick not working on mobile (touch)

better to use touchstart event with .on() jQuery method:

$(window).load(function() { // better to use $(document).ready(function(){
    $('.List li').on('click touchstart', function() {
        $('.Div').slideDown('500');
    });
});

And i don't understand why you are using $(window).load() method because it waits for everything on a page to be loaded, this tend to be slow, while you can use $(document).ready() method which does not wait for each element on the page to be loaded first.

Why am I seeing "TypeError: string indices must be integers"?

This can happen if a comma is missing. I ran into it when I had a list of two-tuples, each of which consisted of a string in the first position, and a list in the second. I erroneously omitted the comma after the first component of a tuple in one case, and the interpreter thought I was trying to index the first component.

What are the differences between Mustache.js and Handlebars.js?

—In addition to using "this" for handlebars, and the nested variable within variable block for mustache, you can also use the nested dot in a block for mustache:

    {{#variable}}<span class="text">{{.}}</span>{{/variable}}

Dynamically Changing log4j log level

I have used this method with success to reduce the verbosity of the "org.apache.http" logs:

ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("org.apache.http");
logger.setLevel(Level.TRACE);
logger.setAdditive(false);

How do I create a folder in a GitHub repository?

Simple Steps:

Step 1: Click on Create new File

Click "Create new file" under the "Add file" dropdown


Step 2: Enter the folder name that you want, then press /

Enter folder name inside text field


Step 3: Enter a sample file name. You must enter some text.

Enter sample file name


Step 4: Click Commit new file to create the folder

Click "Commit new file"


Step 5: Your folder is created!

Folder appears inside repository home page

How to make an HTTP get request with parameters

The WebRequest object seems like too much work for me. I prefer to use the WebClient control.

To use this function you just need to create two NameValueCollections holding your parameters and request headers.

Consider the following function:

    private static string DoGET(string URL,NameValueCollection QueryStringParameters = null, NameValueCollection RequestHeaders = null)
    {
        string ResponseText = null;
        using (WebClient client = new WebClient())
        {
            try
            {
                if (RequestHeaders != null)
                {
                    if (RequestHeaders.Count > 0)
                    {
                        foreach (string header in RequestHeaders.AllKeys)
                            client.Headers.Add(header, RequestHeaders[header]);
                    }
                }
                if (QueryStringParameters != null)
                {
                    if (QueryStringParameters.Count > 0)
                    {
                        foreach (string parm in QueryStringParameters.AllKeys)
                            client.QueryString.Add(parm, QueryStringParameters[parm]);
                    }
                }
                byte[] ResponseBytes = client.DownloadData(URL);
                ResponseText = Encoding.UTF8.GetString(ResponseBytes);
            }
            catch (WebException exception)
            {
                if (exception.Response != null)
                {
                    var responseStream = exception.Response.GetResponseStream();

                    if (responseStream != null)
                    {
                        using (var reader = new StreamReader(responseStream))
                        {
                            Response.Write(reader.ReadToEnd());
                        }
                    }
                }
            }
        }
        return ResponseText;
    }

Add your querystring parameters (if required) as a NameValueCollection like so.

        NameValueCollection QueryStringParameters = new NameValueCollection();
        QueryStringParameters.Add("id", "123");
        QueryStringParameters.Add("category", "A");

Add your http headers (if required) as a NameValueCollection like so.

        NameValueCollection RequestHttpHeaders = new NameValueCollection();
        RequestHttpHeaders.Add("Authorization", "Basic bGF3c2912XBANzg5ITppc2ltCzEF");

Using command line arguments in VBscript

Set args = Wscript.Arguments

For Each arg In args
  Wscript.Echo arg
Next

From a command prompt, run the script like this:

CSCRIPT MyScript.vbs 1 2 A B "Arg with spaces"

Will give results like this:

1
2
A
B
Arg with spaces

Disable Enable Trigger SQL server for a table

I wanted to share something that helped me out. Idea credit goes to @Siavash and @Shahab Naseer.

I needed something where I could script disable and re enable of triggers for a particular table. I normally try and stay away from tiggers, but sometimes they could be good to use.

I took the script above and added a join to the sysobjects so I could filter by table name. This script will disable a trigger or triggers for a table.

select 'alter table '+ (select Schema_name(schema_id) from sys.objects o 
where o.object_id = parent_id) + '.'+object_name(parent_id) + ' ENABLE TRIGGER '+ t.Name as EnableScript,*
from sys.triggers t 
INNER JOIN dbo.sysobjects DS ON DS.id = t.parent_id 
where is_disabled = 0 AND DS.name = 'tblSubContact'

How to get the date from jQuery UI datepicker

Try this, works like charm, gives the date you have selected. onsubmit form try to get this value:-

var date = $("#scheduleDate").datepicker({ dateFormat: 'dd,MM,yyyy' }).val();

Reference here

React JSX: selecting "selected" on selected <select> option

Here is the latest example of how to do it. From react docs, plus auto-binding "fat-arrow" method syntax.

class FlavorForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: 'coconut'};
  }

  handleChange = (event) =>
    this.setState({value: event.target.value});

  handleSubmit = (event) => {
    alert('Your favorite flavor is: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Pick your favorite flavor:
          <select value={this.state.value} onChange={this.handleChange}>
            <option value="grapefruit">Grapefruit</option>
            <option value="lime">Lime</option>
            <option value="coconut">Coconut</option>
            <option value="mango">Mango</option>
          </select>
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
} 

CSS3 Fade Effect

The scrolling effect is cause by specifying the generic 'background' property in your css instead of the more specific background-image. By setting the background property, the animation will transition between all properties.. Background-Color, Background-Image, Background-Position.. Etc Thus causing the scrolling effect..

E.g.

a {
-webkit-transition-property: background-image 300ms ease-in 200ms;
-moz-transition-property: background-image 300ms ease-in 200ms;
-o-transition-property: background-image 300ms ease-in 200ms;
transition: background-image 300ms ease-in 200ms;
}

Should I use SVN or Git?

After doing more research, and reviewing this link: https://git.wiki.kernel.org/articles/g/i/t/GitSvnComparison_cb82.html

(Some extracts below):

  • It's incredibly fast. No other SCM that I have used has been able to keep up with it, and I've used a lot, including Subversion, Perforce, darcs, BitKeeper, ClearCase and CVS.
  • It's fully distributed. The repository owner can't dictate how I work. I can create branches and commit changes while disconnected on my laptop, then later synchronize that with any number of other repositories.
  • Synchronization can occur over many media. An SSH channel, over HTTP via WebDAV, by FTP, or by sending emails holding patches to be applied by the recipient of the message. A central repository isn't necessary, but can be used.
  • Branches are even cheaper than they are in Subversion. Creating a branch is as simple as writing a 41 byte file to disk. Deleting a branch is as simple as deleting that file.
  • Unlike Subversion branches carry along their complete history. without having to perform a strange copy and walk through the copy. When using Subversion I always found it awkward to look at the history of a file on branch that occurred before the branch was created. from #git: spearce: I don't understand one thing about SVN in the page. I made a branch i SVN and browsing the history showed the whole history a file in the branch
  • Branch merging is simpler and more automatic in Git. In Subversion you need to remember what was the last revision you merged from so you can generate the correct merge command. Git does this automatically, and always does it right. Which means there's less chance of making a mistake when merging two branches together.
  • Branch merges are recorded as part of the proper history of the repository. If I merge two branches together, or if I merge a branch back into the trunk it came from, that merge operation is recorded as part of the repostory history as having been performed by me, and when. It's hard to dispute who performed the merge when it's right there in the log.
  • Creating a repository is a trivial operation: mkdir foo; cd foo; git init That's it. Which means I create a Git repository for everything these days. I tend to use one repository per class. Most of those repositories are under 1 MB in disk as they only store lecture notes, homework assignments, and my LaTeX answers.
  • The repository's internal file formats are incredible simple. This means repair is very easy to do, but even better because it's so simple its very hard to get corrupted. I don't think anyone has ever had a Git repository get corrupted. I've seen Subversion with fsfs corrupt itself. And I've seen Berkley DB corrupt itself too many times to trust my code to the bdb backend of Subversion.
  • Git's file format is very good at compressing data, despite it's a very simple format. The Mozilla project's CVS repository is about 3 GB; it's about 12 GB in Subversion's fsfs format. In Git it's around 300 MB.

After reading all this, I'm convinced that Git is the way to go (although a little bit of learning curve exists). I have used Git and SVN on Windows platforms as well.

I'd love to hear what others have to say after reading the above?

How do I scroll a row of a table into view (element.scrollintoView) using jQuery?

var rowpos = $('#table tr:last').position();

$('#container').scrollTop(rowpos.top);

should do the trick!

Set order of columns in pandas dataframe

You could also do something like df = df[['x', 'y', 'a', 'b']]

import pandas as pd
frame = pd.DataFrame({'one thing':[1,2,3,4],'second thing':[0.1,0.2,1,2],'other thing':['a','e','i','o']})
frame = frame[['second thing', 'other thing', 'one thing']]
print frame
   second thing other thing  one thing
0           0.1           a          1
1           0.2           e          2
2           1.0           i          3
3           2.0           o          4

Also, you can get the list of columns with:

cols = list(df.columns.values)

The output will produce something like this:

['x', 'y', 'a', 'b']

Which is then easy to rearrange manually.

jQuery show/hide not working

Demo

_x000D_
_x000D_
$( '.expand' ).click(function() {_x000D_
  $( '.img_display_content' ).toggle();_x000D_
});
_x000D_
.wrap {_x000D_
    margin-left:auto;_x000D_
    margin-right:auto;_x000D_
    width:40%;_x000D_
}_x000D_
_x000D_
.img_display_header {_x000D_
    height:20px;_x000D_
    background-color:#CCC;_x000D_
    display:block;_x000D_
    border:#333 solid 1px;_x000D_
    margin-bottom: 2px;_x000D_
}_x000D_
_x000D_
.expand {_x000D_
 float:right;_x000D_
 height: 100%;_x000D_
 padding-right:5px;_x000D_
 cursor:pointer;_x000D_
}_x000D_
_x000D_
.img_display_content {_x000D_
    width: 100%;_x000D_
    height:100px;   _x000D_
    background-color:#0F3;_x000D_
    margin-top: -2px;_x000D_
    display:none;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="wrap">_x000D_
<div class="img_display_header">_x000D_
<div class="expand">+</div>_x000D_
</div>_x000D_
<div class="img_display_content"></div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://api.jquery.com/toggle/
"Display or hide the matched elements."

This is much shorter in code than using show() and hide() methods.

Java - Change int to ascii

The most simple way is using type casting:

public char toChar(int c) {
    return (char)c;
}

select certain columns of a data table

Here's working example with anonymous output record, if you have any questions place a comment below:                    

public partial class Form1 : Form
{
    DataTable table;
    public Form1()
    {
        InitializeComponent();
        #region TestData
        table = new DataTable();
        table.Clear();
        for (int i = 1; i < 12; ++i)
            table.Columns.Add("Col" + i);
        for (int rowIndex = 0; rowIndex < 5; ++rowIndex)
        {
            DataRow row = table.NewRow();
            for (int i = 0; i < table.Columns.Count; ++i)
                row[i] = String.Format("row:{0},col:{1}", rowIndex, i);
            table.Rows.Add(row);
        }
        #endregion
        bind();
    }

    public void bind()
    {
        var filtered = from t in table.AsEnumerable()
                       select new
                       {
                           col1 = t.Field<string>(0),//column of index 0 = "Col1"
                           col2 = t.Field<string>(1),//column of index 1 = "Col2"
                           col3 = t.Field<string>(5),//column of index 5 = "Col6"
                           col4 = t.Field<string>(6),//column of index 6 = "Col7"
                           col5 = t.Field<string>(4),//column of index 4 = "Col3"
                       };
        filteredData.AutoGenerateColumns = true;
        filteredData.DataSource = filtered.ToList();
    }
}

How to pretty print nested dictionaries?

I'm just returning to this question after taking sth's answer and making a small but very useful modification. This function prints all keys in the JSON tree as well as the size of leaf nodes in that tree.

def print_JSON_tree(d, indent=0):
    for key, value in d.iteritems():
        print '    ' * indent + unicode(key),
        if isinstance(value, dict):
            print; print_JSON_tree(value, indent+1)
        else:
            print ":", str(type(d[key])).split("'")[1], "-", str(len(unicode(d[key])))

It's really nice when you have large JSON objects and want to figure out where the meat is. Example:

>>> print_JSON_tree(JSON_object)
key1
    value1 : int - 5
    value2 : str - 16
    key2
       value1 : str - 34
       value2 : list - 5623456

This would tell you that most of the data you care about is probably inside JSON_object['key1']['key2']['value2'] because the length of that value formatted as a string is very large.

How to generate class diagram from project in Visual Studio 2013?

For creating real UML class diagrams:

In Visual Studio 2013 Ultimate you can do this without any external tools.

  • In the menu, click on Architecture, New Diagram Select UML Class Diagram
  • This will ask you to create a new Modeling Project if you don't have one already.

You will have a empty UMLClassDiagram.classdiagram.

  • Again, go to Architecture, Windows, Architecture Explorer.
  • A window will pop up with your namespaces, Choose Class View.
  • Then a list of sub-namespaces will appear, if any. Choose one, select the classes and drag them to the empty UMLClassDiagram1.classdiagram window.

Reference: Create UML Class Diagrams from Code

lvalue required as left operand of assignment

if (strcmp("hello", "hello") = 0)

Is trying to assign 0 to function return value which isn't lvalue.

Function return values are not lvalue (no storage for it), so any attempt to assign value to something that is not lvalue result in error.

Best practice to avoid such mistakes in if conditions is to use constant value on left side of comparison, so even if you use "=" instead "==", constant being not lvalue will immediately give error and avoid accidental value assignment and causing false positive if condition.

What function is to replace a substring from a string in C?

The optimizer should eliminate most of the local variables. The tmp pointer is there to make sure strcpy doesn't have to walk the string to find the null. tmp points to the end of result after each call. (See Shlemiel the painter's algorithm for why strcpy can be annoying.)

// You must free the result if result is non-NULL.
char *str_replace(char *orig, char *rep, char *with) {
    char *result; // the return string
    char *ins;    // the next insert point
    char *tmp;    // varies
    int len_rep;  // length of rep (the string to remove)
    int len_with; // length of with (the string to replace rep with)
    int len_front; // distance between rep and end of last rep
    int count;    // number of replacements

    // sanity checks and initialization
    if (!orig || !rep)
        return NULL;
    len_rep = strlen(rep);
    if (len_rep == 0)
        return NULL; // empty rep causes infinite loop during count
    if (!with)
        with = "";
    len_with = strlen(with);

    // count the number of replacements needed
    ins = orig;
    for (count = 0; tmp = strstr(ins, rep); ++count) {
        ins = tmp + len_rep;
    }

    tmp = result = malloc(strlen(orig) + (len_with - len_rep) * count + 1);

    if (!result)
        return NULL;

    // first time through the loop, all the variable are set correctly
    // from here on,
    //    tmp points to the end of the result string
    //    ins points to the next occurrence of rep in orig
    //    orig points to the remainder of orig after "end of rep"
    while (count--) {
        ins = strstr(orig, rep);
        len_front = ins - orig;
        tmp = strncpy(tmp, orig, len_front) + len_front;
        tmp = strcpy(tmp, with) + len_with;
        orig += len_front + len_rep; // move to next "end of rep"
    }
    strcpy(tmp, orig);
    return result;
}

How to run a Python script in the background even after I logout SSH?

If what you need is that the process should run forever no matter whether you are logged in or not, consider running the process as a daemon.

supervisord is a great out of the box solution that can be used to daemonize any process. It has another controlling utility supervisorctl that can be used to monitor processes that are being run by supervisor.

You don't have to write any extra code or modify existing scripts to make this work. Moreover, verbose documentation makes this process much simpler.

After scratching my head for hours around python-daemon, supervisor is the solution that worked for me in minutes.

Hope this helps someone trying to make python-daemon work

How to get a shell environment variable in a makefile?

for those who want some official document to confirm the behavior

Variables in make can come from the environment in which make is run. Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment. (If the ‘-e’ flag is specified, then values from the environment override assignments in the makefile.

https://www.gnu.org/software/make/manual/html_node/Environment.html

C# Call a method in a new thread

As far as I understand you need mean terminate as Thread.Abort() right? In this case, you can just exit the Foo(). Or you can use Process to catch the thread.

Thread myThread = new Thread(DoWork);

myThread.Abort();

myThread.Start(); 

Process example:

using System;
using System.Diagnostics;
using System.ComponentModel;
using System.Threading;
using Microsoft.VisualBasic;

class PrintProcessClass
{

    private Process myProcess = new Process();
    private int elapsedTime;
    private bool eventHandled;

    // Print a file with any known extension.
    public void PrintDoc(string fileName)
    {

        elapsedTime = 0;
        eventHandled = false;

        try
        {
            // Start a process to print a file and raise an event when done.
            myProcess.StartInfo.FileName = fileName;
            myProcess.StartInfo.Verb = "Print";
            myProcess.StartInfo.CreateNoWindow = true;
            myProcess.EnableRaisingEvents = true;
            myProcess.Exited += new EventHandler(myProcess_Exited);
            myProcess.Start();

        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred trying to print \"{0}\":" + "\n" + ex.Message, fileName);
            return;
        }

        // Wait for Exited event, but not more than 30 seconds.
        const int SLEEP_AMOUNT = 100;
        while (!eventHandled)
        {
            elapsedTime += SLEEP_AMOUNT;
            if (elapsedTime > 30000)
            {
                break;
            }
            Thread.Sleep(SLEEP_AMOUNT);
        }
    }

    // Handle Exited event and display process information.
    private void myProcess_Exited(object sender, System.EventArgs e)
    {

        eventHandled = true;
        Console.WriteLine("Exit time:    {0}\r\n" +
            "Exit code:    {1}\r\nElapsed time: {2}", myProcess.ExitTime, myProcess.ExitCode, elapsedTime);
    }

    public static void Main(string[] args)
    {

        // Verify that an argument has been entered.
        if (args.Length <= 0)
        {
            Console.WriteLine("Enter a file name.");
            return;
        }

        // Create the process and print the document.
        PrintProcessClass myPrintProcess = new PrintProcessClass();
        myPrintProcess.PrintDoc(args[0]);
    }
}

Combining COUNT IF AND VLOOK UP EXCEL

You can combine this all into one formula, but you need to use a regular IF first to find out if the VLOOKUP came back with something, then use your COUNTIF if it did.

=IF(ISERROR(VLOOKUP(B1,Sheet2!A1:A9,1,FALSE)),"Not there",COUNTIF(Sheet2!A1:A9,B1))

In this case, Sheet2-A1:A9 is the range I was searching, and Sheet1-B1 had the value I was looking for ("To retire" in your case).

How do I search for names with apostrophe in SQL Server?

SELECT     *
FROM Header WHERE (userID LIKE '%''%')

How to generate unique IDs for form labels in React?

This solutions works fine for me.

utils/newid.js:

let lastId = 0;

export default function(prefix='id') {
    lastId++;
    return `${prefix}${lastId}`;
}

And I can use it like this:

import newId from '../utils/newid';

React.createClass({
    componentWillMount() {
        this.id = newId();
    },
    render() {
        return (
            <label htmlFor={this.id}>My label</label>
            <input id={this.id} type="text"/>
        );
    }
});

But it won’t work in isomorphic apps.

Added 17.08.2015. Instead of custom newId function you can use uniqueId from lodash.

Updated 28.01.2016. It’s better to generate ID in componentWillMount.

How can I change image source on click with jQuery?

It switches back because by default, when you click a link, it follows the link and loads the page. In your case, you don't want that. You can prevent it either by doing e.preventDefault(); (like Neal mentioned) or by returning false :

$(function() {
 $('.menulink').click(function(){
   $("#bg").attr('src',"img/picture1.jpg");
   return false;
 });
});

Interesting question on the differences between prevent default and return false.

In this case, return false will work just fine because the event doesn't need to be propagated.

Java: Calling a super method which calls an overridden method

this always refers to currently executing object.

To further illustrate the point here is a simple sketch:

+----------------+
|  Subclass      |
|----------------|
|  @method1()    |
|  @method2()    |
|                |
| +------------+ |
| | Superclass | |
| |------------| |
| | method1()  | |
| | method2()  | |
| +------------+ |
+----------------+

If you have an instance of the outer box, a Subclass object, wherever you happen to venture inside the box, even into the Superclass 'area', it is still the instance of the outer box.

What's more, in this program there is only one object that gets created out of the three classes, so this can only ever refer to one thing and it is:

enter image description here

as shown in the Netbeans 'Heap Walker'.

set dropdown value by text using jquery

$("#HowYouKnow").val("GOOGLE");

Python list sort in descending order

This will give you a sorted version of the array.

sorted(timestamps, reverse=True)

If you want to sort in-place:

timestamps.sort(reverse=True)

Print range of numbers on same line

Though the answer has been given for the question. I would like to add, if in case we need to print numbers without any spaces then we can use the following code

        for i in range(1,n):
            print(i,end="")

Use of REPLACE in SQL Query for newline/ carriage return characters

There are probably embedded tabs (CHAR(9)) etc. as well. You can find out what other characters you need to replace (we have no idea what your goal is) with something like this:

DECLARE @var NVARCHAR(255), @i INT;

SET @i = 1;

SELECT @var = AccountType FROM dbo.Account
  WHERE AccountNumber = 200
  AND AccountType LIKE '%Daily%';

CREATE TABLE #x(i INT PRIMARY KEY, c NCHAR(1), a NCHAR(1));

WHILE @i <= LEN(@var)
BEGIN
  INSERT #x 
    SELECT SUBSTRING(@var, @i, 1), ASCII(SUBSTRING(@var, @i, 1));

  SET @i = @i + 1;
END

SELECT i,c,a FROM #x ORDER BY i;

You might also consider doing better cleansing of this data before it gets into your database. Cleaning it every time you need to search or display is not the best approach.

How to remove all leading zeroes in a string

I don't think preg_replace is the answer.. old thread but just happen to looking for this today. ltrim and (int) casting is the winner.

<?php
 $numString = "0000001123000";
 $actualInt = "1123000";

 $fixed_str1 = preg_replace('/000+/','',$numString);
 $fixed_str2 = ltrim($numString, '0');
 $fixed_str3 = (int)$numString;

 echo $numString . " Original";
 echo "<br>"; 
 echo $fixed_str1 . " Fix1";
 echo "<br>"; 
 echo $fixed_str2 . " Fix2";
 echo "<br>";
 echo $fixed_str3 . " Fix3";
 echo "<br>";
 echo $actualInt . " Actual integer in string";

 //output

 0000001123000 Origina
 1123 Fix1
 1123000 Fix2
 1123000 Fix3
 1123000 Actual integer in tring

How to use absolute path in twig functions

From Symfony2 documentation: Absolute URLs for assets were introduced in Symfony 2.5.

If you need absolute URLs for assets, you can set the third argument (or the absolute argument) to true:

Example:

<img src="{{ asset('images/logo.png', absolute=true) }}" alt="Symfony!" />

Why is textarea filled with mysterious white spaces?

I know its late but may help others.

use this in when document indentation is required.

$('document').ready(function()
{
    $('textarea').each(function(){
            $(this).val($(this).val().trim());
        }
    );
});

same question

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

How to fix the "java.security.cert.CertificateException: No subject alternative names present" error?

I also faced the same issue with a self signed certificate . By referring to few of the above solutions , i tried regenerating the certificate with the correct CN i.e the IP Address of the server .But still it didn't work for me . Finally i tried regenerating the certificate by adding the SAN address to it via the below mentioned command

**keytool -genkey -keyalg RSA -keystore keystore.jks -keysize 2048 -alias <IP_ADDRESS> -ext san=ip:<IP_ADDRESS>**

After that i started my server and downloaded the client certificates via the below mentioned openssl command

**openssl s_client -showcerts -connect <IP_ADDRESS>:443 < /dev/null | openssl x509 -outform PEM > myCert.pem**

Then i imported this client certificate to the java default keystore file (cacerts) of my client machine by the below mentioned command

**keytool -import -trustcacerts -keystore /home/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.242.b08-1.el7.x86_64/jre/lib/security/cacerts -alias <IP_ADDRESS> -file ./mycert.pem**

Removing pip's cache?

On Mac OS (Mavericks), I had to delete /tmp/pip-build/

Convert Set to List without creating new List

We can use following one liner in Java 8:

List<String> list = set.stream().collect(Collectors.toList());

Here is one small example:

public static void main(String[] args) {
        Set<String> set = new TreeSet<>();
        set.add("A");
        set.add("B");
        set.add("C");
        List<String> list = set.stream().collect(Collectors.toList());
}

How to output in CLI during execution of PHP Unit tests?

I had to modify source code for this code to work so you need to add URL for this forked repos to composer for this will work

class TestCase extends \PHPUnit_Framework_TestCase
{
    /**
     *  Save last response
     * @var Response|null A Response instance
     */
    static $lastResponse;
    /**
     *  Modify to save response
     *
     * @param  string $method
     * @param  string $uri
     * @param  array $parameters
     * @param  array $files
     * @param  array $server
     * @param  string $content
     * @param  bool $changeHistory
     * @return \Illuminate\Http\Response
     */
    final public function call(
        $method,
        $uri,
        $parameters = [],
        $files = [],
        $server = [],
        $content = null,
        $changeHistory = true
    ) {

        $response = parent::call($method, $uri, $parameters, $files, $server, $content, $changeHistory);
        static::$lastResponse = $this->client->getResponse();
        return $response;
    }


    /**
     * Modify message to add response text
     *
     * @param mixed $value
     * @param PHPUnit_Framework_Constraint $constraint
     * @param string $message
     * @since  Method available since Release 3.0.0
     */
    final public static function assertThat($value, PHPUnit_Framework_Constraint $constraint, $message = '')
    {
        $message .= PHP_EOL . static::$lastResponse . PHP_EOL;
        parent::assertThat($value, $constraint, $message);
    }
}

CSS3 Spin Animation

For the guys who still search some cool and easy spinner, we have multiple exemples of spinner on fontawesome site : https://fontawesome.com/v4.7.0/examples/

You just have to inspect the spinner you want with your debugger and copy the css styles.

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

The function has to be declared before it's getting called. This could be done in various ways:

  • Write down the prototype in a header
    Use this if the function shall be callable from several source files. Just write your prototype
    int Fibonacci(int number);
    down in a .h file (e.g. myfunctions.h) and then #include "myfunctions.h" in the C code.

  • Move the function before it's getting called the first time
    This means, write down the function
    int Fibonacci(int number){..}
    before your main() function

  • Explicitly declare the function before it's getting called the first time
    This is the combination of the above flavors: type the prototype of the function in the C file before your main() function

As an additional note: if the function int Fibonacci(int number) shall only be used in the file where it's implemented, it shall be declared static, so that it's only visible in that translation unit.

How does the communication between a browser and a web server take place?

The links for specifications of each aspect of the question is as follows:

  • GET, POST verbs (among others) - The HTTP Specification exhaustively discusses all aspects of HTTP communication (the protocol for communication between the web server and the browser). It explains the Request message and Response message protocols.

  • Cookies - are set by attaching a Set-Cookie HTTP Header to the HTTP response.

  • QueryStrings - are the part of the URL in the HTTP request that follow the first occurrence of a "?" character. The linked specification is for section 3.4 of the URI specification.

  • Sessions - HTTP is a synchronous, stateless protocol. Sessions, or the illusion of state, can be created by (1) using cookies to store state data as plain text on the client's computer, (2) passing data-values in the URL and querystring of the request, (3) submitting POST requests with a collection of values that may indicate state and, (4) storing state information by a server-side persistence mechanism that is retrieved by a session-key (the session key is resolved from either the cookie, URL/Querystring or POST value collection.

An explanation of HTTP can go on for days, but I have attempted to provide a concise yet conceptually complete answer, and include the appropriate links for further reading of official specifications.

How to set menu to Toolbar in Android

You can achieve this by two methods

  1. Using XML
  2. Using java

Using XML Add this attribute to toolbar XML app:menu = "menu_name"

Using java By overriding onCreateOptionMenu(Menu menu)

public class MainActivity extends AppCompatActivity { 

  private Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
}
@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.demo_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }
}

for more details or implementating click on the menu go through this article https://bedevelopers.tech/android-toolbar-implementation-using-android-studio/

How do I redirect a user when a button is clicked?

You can easily wrap your button tag with tag.Using Url.Action() HTML Helper this will get to navigate to one page to another.

<a href='@Url.Action("YourAction", "YourController")'>
    <input type='button' value='Dummy Button' />
</a>

If you want to navigate with javascript onclick() function then use

<input type='button' value='Dummy Button' onclick='window.location = "@Url.Action("YourAction", "YourController")";' />

I just assigned a variable, but echo $variable shows something else

In addition to other issues caused by failing to quote, -n and -e can be consumed by echo as arguments. (Only the former is legal per the POSIX spec for echo, but several common implementations violate the spec and consume -e as well).

To avoid this, use printf instead of echo when details matter.

Thus:

$ vars="-e -n -a"
$ echo $vars      # breaks because -e and -n can be treated as arguments to echo
-a
$ echo "$vars"
-e -n -a

However, correct quoting won't always save you when using echo:

$ vars="-n"
$ echo $vars
$ ## not even an empty line was printed

...whereas it will save you with printf:

$ vars="-n"
$ printf '%s\n' "$vars"
-n

How can I restore the MySQL root user’s full privileges?

i also remove privileges of root and database not showing in mysql console when i was a root user, so changed user by mysql>mysql -u 'userName' -p; and password;

UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';

FLUSH PRIVILEGES;

after this command it all show database's in root .

Thanks

How can I add new item to the String array?

From arrays

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You've seen an example of arrays already, in the main method of the "Hello World!" application. This section discusses arrays in greater detail.

enter image description here

So in the case of a String array, once you create it with some length, you can't modify it, but you can add elements until you fill it.

String[] arr = new String[10]; // 10 is the length of the array.
arr[0] = "kk";
arr[1] = "pp";
...

So if your requirement is to add many objects, it's recommended that you use Lists like:

List<String> a = new ArrayList<String>();
a.add("kk");
a.add("pp"); 

Merge r brings error "'by' must specify uniquely valid columns"

Rather give names of the column on which you want to merge:

exporttab <- merge(x=dwd_nogap, y=dwd_gap, by.x='x1', by.y='x2', fill=-9999)

sendmail: how to configure sendmail on ubuntu?

When you typed in sudo sendmailconfig, you should have been prompted to configure sendmail.

For reference, the files that are updated during configuration are located at the following (in case you want to update them manually):

/etc/mail/sendmail.conf
/etc/cron.d/sendmail
/etc/mail/sendmail.mc

You can test sendmail to see if it is properly configured and setup by typing the following into the command line:

$ echo "My test email being sent from sendmail" | /usr/sbin/sendmail [email protected]

The following will allow you to add smtp relay to sendmail:

#Change to your mail config directory:
cd /etc/mail

#Make a auth subdirectory
mkdir auth
chmod 700 auth

#Create a file with your auth information to the smtp server
cd auth
touch client-info

#In the file, put the following, matching up to your smtp server:
AuthInfo:your.isp.net "U:root" "I:user" "P:password"

#Generate the Authentication database, make both files readable only by root
makemap hash client-info < client-info
chmod 600 client-info
cd ..

Add the following lines to sendmail.mc, but before the MAILERDEFINITIONS. Make sure you update your smtp server.

define(`SMART_HOST',`your.isp.net')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
FEATURE(`authinfo',`hash -o /etc/mail/auth/client-info.db')dnl

Invoke creation sendmail.cf (alternatively run make -C /etc/mail):

m4 sendmail.mc > sendmail.cf

Restart the sendmail daemon:

service sendmail restart

Encapsulation vs Abstraction?

Abstraction is the concept of describing something in simpler terms, i.e abstracting away the details, in order to focus on what is important (This is also seen in abstract art, for example, where the artist focuses on the building blocks of images, such as colour or shapes). The same idea translates to OOP by using an inheritance hierarchy, where more abstract concepts are at the top and more concrete ideas, at the bottom, build upon their abstractions. At its most abstract level there is no implementation details at all and perhaps very few commonalities, which are added as the abstraction decreases.

As an example, at the top might be an interface with a single method, then the next level, provides several abstract classes, which may or may not fill in some of the details about the top level, but branches by adding their own abstract methods, then for each of these abstract classes are concrete classes providing implementations of all the remaining methods.

Encapsulation is a technique. It may or may not be for aiding in abstraction, but it is certainly about information hiding and/or organisation. It demands data and functions be grouped in some way - of course good OOP practice demands that they should be grouped by abstraction. However, there are other uses which just aid in maintainability etc.

Specifying row names when reading in a file

If you used read.table() (or one of it's ilk, e.g. read.csv()) then the easy fix is to change the call to:

read.table(file = "foo.txt", row.names = 1, ....)

where .... are the other arguments you needed/used. The row.names argument takes the column number of the data file from which to take the row names. It need not be the first column. See ?read.table for details/info.

If you already have the data in R and can't be bothered to re-read it, or it came from another route, just set the rownames attribute and remove the first variable from the object (assuming obj is your object)

rownames(obj) <- obj[, 1]  ## set rownames
obj <- obj[, -1]           ## remove the first variable

How to compile a 32-bit binary on a 64-bit linux machine with gcc/cmake

In later versions of CMake, one way to do it on each target is:

set_target_properties(MyTarget PROPERTIES COMPILE_FLAGS "-m32" LINK_FLAGS "-m32")

I don't know of a way to do it globally.

Listview Scroll to the end of the list after updating the list

Using : Set the head of the list to it bottom lv.setStackFromBottom(true);

Worked for me and the list is scrolled to the bottom automatically when it is first brought into visibility. The list then scrolls as it should with TRANSCRIPT_MODE_ALWAYS_SCROLL.

Get selected element's outer HTML

Here is a very optimized outerHTML plugin for jquery: (http://jsperf.com/outerhtml-vs-jquery-clone-hack/5 => the 2 others fast code snippets are not compatible with some browsers like FF < 11)

(function($) {

  var DIV = document.createElement("div"),
      outerHTML;

  if ('outerHTML' in DIV) {
    outerHTML = function(node) {
      return node.outerHTML;
    };
  } else {
    outerHTML = function(node) {
      var div = DIV.cloneNode();
      div.appendChild(node.cloneNode(true));
      return div.innerHTML;
    };
  }

  $.fn.outerHTML = function() {
    return this.length ? outerHTML(this[0]) : void(0);
  };

})(jQuery);

@Andy E => I don't agree with you. outerHMTL doesn't need a getter AND a setter: jQuery already give us 'replaceWith'...

@mindplay => Why are you joining all outerHTML? jquery.html return only the HTML content of the FIRST element.

(Sorry, don't have enough reputation to write comments)

Running Python code in Vim

Keep in mind that you're able to repeat the last used command with @:, so that's all you'd need to repeat are those two character.

Or you could save the string w !python into one of the registers (like "a for example) and then hit :<C-R>a<CR> to insert the contents of register a into the commandline and run it.

Or you can do what I do and map <leader>z to :!python %<CR> to run the current file.

Find size of object instance in bytes in c#

This is impossible to do at runtime.

There are various memory profilers that display object size, though.

EDIT: You could write a second program that profiles the first one using the CLR Profiling API and communicates with it through remoting or something.

How to access parent scope from within a custom directive *with own scope* in AngularJS?

If you are using ES6 Classes and ControllerAs syntax, you need to do something slightly different.

See the snippet below and note that vm is the ControllerAs value of the parent Controller as used in the parent HTML

myApp.directive('name', function() {
  return {
    // no scope definition
    link : function(scope, element, attrs, ngModel) {

        scope.vm.func(...)

bash: mkvirtualenv: command not found

On Windows 7 and Git Bash this helps me:

  1. Create a ~/.bashrc file (under your user home folder)
  2. Add line export WORKON_HOME=$HOME/.virtualenvs (you must create this folder if it doesn't exist)
  3. Add line source "C:\Program Files (x86)\Python36-32\Scripts\virtualenvwrapper.sh" (change path for your virtualenvwrapper.sh)

Restart your git bash and mkvirtualenv command now will work nicely.

Sqlite or MySql? How to decide?

The sqlite team published an article explaining when to use sqlite that is great read. Basically, you want to avoid using sqlite when you have a lot of write concurrency or need to scale to terabytes of data. In many other cases, sqlite is a surprisingly good alternative to a "traditional" database such as MySQL.

How to give a pandas/matplotlib bar graph custom colors

I found the easiest way is to use the colormap parameter in .plot() with one of the preset color gradients:

df.plot(kind='bar', stacked=True, colormap='Paired')

enter image description here

You can find a large list of preset colormaps here.

colormaps

How to redirect cin and cout to files?

Just write

#include <cstdio>
#include <iostream>
using namespace std;

int main()
{
    freopen("output.txt","w",stdout);
    cout<<"write in file";
    return 0;
}

Center Oversized Image in Div

It's simple with some flex and overflow set to hidden.

enter image description here

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        div {
            height: 150px;
            width: 150px;
            border: 2px solid red;
        
            overflow: hidden;
            display: flex;
            align-items: center;
            justify-content: center;
        }
    </style>
</head>
<body>
    <div>
        <img src="sun.jpg" alt="">
    </div>
</body>
</html>

Working Soap client example

The response of acdcjunior it was awesome, I just expand his explanation with the next code, where you can see how iterate over the XML elements.

public class SOAPClientSAAJ {

public static void main(String args[]) throws Exception {
    // Create SOAP Connection
    SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection soapConnection = soapConnectionFactory.createConnection();

    // Send SOAP Message to SOAP Server
    String url = "http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx";
    SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);



    SOAPPart soapPart=soapResponse.getSOAPPart();
    // SOAP Envelope
    SOAPEnvelope envelope=soapPart.getEnvelope();
    SOAPBody soapBody = envelope.getBody();

    @SuppressWarnings("unchecked")
    Iterator<Node> itr=soapBody.getChildElements();
    while (itr.hasNext()) {

        Node node=(Node)itr.next();
        if (node.getNodeType()==Node.ELEMENT_NODE) {
            System.out.println("reading Node.ELEMENT_NODE");
            Element ele=(Element)node;
            System.out.println("Body childs : "+ele.getLocalName());

            switch (ele.getNodeName()) {

          case "VerifyEmailResponse":
             NodeList statusNodeList = ele.getChildNodes();

             for(int i=0;i<statusNodeList.getLength();i++){
               Element emailResult = (Element) statusNodeList.item(i);
               System.out.println("VerifyEmailResponse childs : "+emailResult.getLocalName());
                switch (emailResult.getNodeName()) {

                case "VerifyEmailResult":
                    NodeList emailResultList = emailResult.getChildNodes();

                    for(int j=0;j<emailResultList.getLength();j++){
                      Element emailResponse = (Element) emailResultList.item(j);
                      System.out.println("VerifyEmailResult childs : "+emailResponse.getLocalName());
                       switch (emailResponse.getNodeName()) {
                       case "ResponseText":
                           System.out.println(emailResponse.getTextContent());
                           break;
                        case "ResponseCode":
                          System.out.println(emailResponse.getTextContent());
                           break;
                        case "LastMailServer":
                          System.out.println(emailResponse.getTextContent());
                          break;
                        case "GoodEmail":
                          System.out.println(emailResponse.getTextContent());
                       default:
                          break;
                       }
                    }
                    break;
                default:
                   break;
                }
             }


             break;


          default:
             break;
          }

        } else if (node.getNodeType()==Node.TEXT_NODE) {
            System.out.println("reading Node.TEXT_NODE");
            //do nothing here most likely, as the response nearly never has mixed content type
            //this is just for your reference
        }
    }
    // print SOAP Response
    System.out.println("Response SOAP Message:");
    soapResponse.writeTo(System.out);

    soapConnection.close();
}

private static SOAPMessage createSOAPRequest() throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    String serverURI = "http://ws.cdyne.com/";

    // SOAP Envelope
    SOAPEnvelope envelope = soapPart.getEnvelope();
    envelope.addNamespaceDeclaration("example", serverURI);

    /*
    Constructed SOAP Request Message:
    <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:example="http://ws.cdyne.com/">
        <SOAP-ENV:Header/>
        <SOAP-ENV:Body>
            <example:VerifyEmail>
                <example:email>[email protected]</example:email>
                <example:LicenseKey>123</example:LicenseKey>
            </example:VerifyEmail>
        </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>
     */

    // SOAP Body
    SOAPBody soapBody = envelope.getBody();
    SOAPElement soapBodyElem = soapBody.addChildElement("VerifyEmail", "example");
    SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("email", "example");
    soapBodyElem1.addTextNode("[email protected]");
    SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("LicenseKey", "example");
    soapBodyElem2.addTextNode("123");

    MimeHeaders headers = soapMessage.getMimeHeaders();
    headers.addHeader("SOAPAction", serverURI  + "VerifyEmail");

    soapMessage.saveChanges();

    /* Print the request message */
    System.out.println("Request SOAP Message:");
    soapMessage.writeTo(System.out);
    System.out.println("");
    System.out.println("------");

    return soapMessage;
}

}

Difference between Pragma and Cache-Control headers?

Pragma is the HTTP/1.0 implementation and cache-control is the HTTP/1.1 implementation of the same concept. They both are meant to prevent the client from caching the response. Older clients may not support HTTP/1.1 which is why that header is still in use.

Vue Js - Loop via v-for X times (in a range)

I have solved it with Dov Benjamin's help like that:

<ul>
  <li v-for="(n,index) in 2">{{ object.price }}</li>
</ul>

And another method, for both V1.x and 2.x of vue.js

Vue 1:

<p v-for="item in items | limitBy 10">{{ item }}</p>

Vue2:

// Via slice method in computed prop

<p v-for="item in filteredItems">{{ item }}</p>

computed: {
   filteredItems: function () {
     return this.items.slice(0, 10)
     }
  }

Private Variables and Methods in Python

The double underscore. It mangles the name in such a way that it can't be accessed simply through __fieldName from outside the class, which is what you want to begin with if they're to be private. (Though it's still not very hard to access the field.)

class Foo:
    def __init__(self):
        self.__privateField = 4;
        print self.__privateField # yields 4 no problem

foo = Foo()
foo.__privateField
# AttributeError: Foo instance has no attribute '__privateField'

It will be accessible through _Foo__privateField instead. But it screams "I'M PRIVATE DON'T TOUCH ME", which is better than nothing.

How to replace existing value of ArrayList element in Java

Use the set method to replace the old value with a new one.

list.set( 2, "New" );

Use string contains function in oracle SQL query

The answer of ADTC works fine, but I've find another solution, so I post it here if someone wants something different.

I think ADTC's solution is better, but mine's also works.

Here is the other solution I found

select p.name
from   person p
where  instr(p.name,chr(8211)) > 0; --contains the character chr(8211) 
                                    --at least 1 time

Thank you.

How to avoid soft keyboard pushing up my layout?

For future readers.

I wanted specific control over this issue, so this is what I did:

From a fragment or activity, hide your other views (that aren't needed while the keyboard is up), then restore them to solve this problem:

rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
     @Override
     public void onGlobalLayout() {
        Rect r = new Rect();
        rootView.getWindowVisibleDisplayFrame(r);
        int heightDiff = rootView.getRootView().getHeight() - (r.bottom - r.top);

        if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard...
           //ok now we know the keyboard is up...
           view_one.setVisibility(View.GONE);
           view_two.setVisibility(View.GONE);

        } else {
           //ok now we know the keyboard is down...
           view_one.setVisibility(View.VISIBLE);
           view_two.setVisibility(View.VISIBLE);       
        }
     }
});

Make a UIButton programmatically in Swift

In Swift We Can Make A button programmatically by writing this code in our viewcontroller.swift file...

import UIKit

class ViewController: UIViewController
{  
private let firstbutton:UIButton = UIButton()

override func viewDidLoad() {
    super.viewDidLoad()
    self.firstbutton = UIButton.buttonWithType(UIButtonType.Custom) as? UIButton
    self.firstbutton!.frame = CGRectMake(100, 200, 100, 100)
    self.firstbutton!.backgroundColor = UIColor.redColor()
    self.firstbutton!.setTitle("My Button", forState: UIControlState.Normal)
    self.firstbutton!.addTarget(self, action:#selector(self.firstButtonClicked), forControlEvents: .TouchUpInside)
    self.view.addSubview(firstbutton!)
    }

func firstButtonClicked(){
   print("First Button Clicked")
}

Jquery insert new row into table at a certain index

try this:

$("table#myTable tr").last().after(data);

How to query all the GraphQL type fields without writing a long query?

Package graphql-type-json supports custom-scalars type JSON. Use it can show all the field of your json objects. Here is the link of the example in ApolloGraphql Server. https://www.apollographql.com/docs/apollo-server/schema/scalars-enums/#custom-scalars

Select Pandas rows based on list index

Another way (although it is a longer code) but it is faster than the above codes. Check it using %timeit function:

df[df.index.isin([1,3])]

PS: You figure out the reason

enter image description here

Recommended way of making React component/div draggable

I would like to add a 3rd Scenario

The moving position is not saved in any way. Think of it as a mouse movement - your cursor is not a React-component, right?

All you do, is to add a prop like "draggable" to your component and a stream of the dragging events that will manipulate the dom.

setXandY: function(event) {
    // DOM Manipulation of x and y on your node
},

componentDidMount: function() {
    if(this.props.draggable) {
        var node = this.getDOMNode();
        dragStream(node).onValue(this.setXandY);  //baconjs stream
    };
},

In this case, a DOM manipulation is an elegant thing (I never thought I'd say this)

How to use a WSDL

I would fire up Visual Studio, create a web project (or console app - doesn't matter).

For .Net Standard:

  1. I would right-click on the project and pick "Add Service Reference" from the Add context menu.
  2. I would click on Advanced, then click on Add Service Reference.
  3. I would get the complete file path of the wsdl and paste into the address bar. Then fire the Arrow (go button).
  4. If there is an error trying to load the file, then there must be a broken and unresolved url the file needs to resolve as shown below: enter image description here Refer to this answer for information on how to fix: Stackoverflow answer to: Unable to create service reference for wsdl file

If there is no error, you should simply set the NameSpace you want to use to access the service and it'll be generated for you.

For .Net Core

  1. I would right click on the project and pick Connected Service from the Add context menu.
  2. I would select Microsoft WCF Web Service Reference Provider from the list.
  3. I would press browse and select the wsdl file straight away, Set the namespace and I am good to go. Refer to the error fix url above if you encounter any error.

Any of the methods above will generate a simple, very basic WCF client for you to use. You should find a "YourservicenameClient" class in the generated code.

For reference purpose, the generated cs file can be found in your Obj/debug(or release)/XsdGeneratedCode and you can still find the dlls in the TempPE folder.

The created Service(s) should have methods for each of the defined methods on the WSDL contract.

Instantiate the client and call the methods you want to call - that's all there is!

YourServiceClient client = new YourServiceClient();
client.SayHello("World!");

If you need to specify the remote URL (not using the one created by default), you can easily do this in the constructor of the proxy client:

YourServiceClient client = new YourServiceClient("configName", "remoteURL");

where configName is the name of the endpoint to use (you will use all the settings except the URL), and the remoteURL is a string representing the URL to connect to (instead of the one contained in the config).

jQuery - Getting form values for ajax POST

var data={
 userName: $('#userName').val(),
 email: $('#email').val(),
 //add other properties similarly
}

and

$.ajax({
        type: "POST",
        url: "http://rt.ja.com/includes/register.php?submit=1",
        data: data

        success: function(html)
        {   
            //alert(html);
            $('#userError').html(html);
            $("#userError").html(userChar);
            $("#userError").html(userTaken);
        }
    });

You dont have to bother about anything else. jquery will handle the serialization etc. also you can append the submit query string parameter submit=1 into the data json object.

Pushing value of Var into an Array

Off the top of my head I think it should be done like this:

var veggies = "carrot";
var fruitvegbasket = [];
fruitvegbasket.push(veggies);

Best way to center a <div> on a page vertically and horizontally?

2018 way using CSS Grid:

.parent{
    display: grid;
    place-items: center center;
}

Check for browser support, Caniuse suggests it works from Chrome 57, FF 52, Opera 44, Safari 10.1, Edge 16. I didn't check myself.

See snippet below:

_x000D_
_x000D_
.parent{
    display: grid;
    place-items: center center;
    /*place-items is a shorthand for align-items and justify-items*/
    
    height: 200px;
    border: 1px solid black;
    background: gainsboro;
}

.child{
    background: white;
}
_x000D_
<div class="parent">
    <div class="child">Centered!</div>
</div>
_x000D_
_x000D_
_x000D_

how do you pass images (bitmaps) between android activities using bundles?

If you pass it as a Parcelable, you're bound to get a JAVA BINDER FAILURE error. So, the solution is this: If the bitmap is small, like, say, a thumbnail, pass it as a byte array and build the bitmap for display in the next activity. For instance:

in your calling activity...

Intent i = new Intent(this, NextActivity.class);
Bitmap b; // your bitmap
ByteArrayOutputStream bs = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 50, bs);
i.putExtra("byteArray", bs.toByteArray());
startActivity(i);

...and in your receiving activity

if(getIntent().hasExtra("byteArray")) {
    ImageView previewThumbnail = new ImageView(this);
    Bitmap b = BitmapFactory.decodeByteArray(
        getIntent().getByteArrayExtra("byteArray"),0,getIntent().getByteArrayExtra("byteArray").length);        
    previewThumbnail.setImageBitmap(b);
}

A TypeScript GUID class?

I found this https://typescriptbcl.codeplex.com/SourceControl/latest

here is the Guid version they have in case the link does not work later.

module System {
    export class Guid {
        constructor (public guid: string) {
            this._guid = guid;
        }

        private _guid: string;

        public ToString(): string {
            return this.guid;
        }

        // Static member
        static MakeNew(): Guid {
            var result: string;
            var i: string;
            var j: number;

            result = "";
            for (j = 0; j < 32; j++) {
                if (j == 8 || j == 12 || j == 16 || j == 20)
                    result = result + '-';
                i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
                result = result + i;
            }
            return new Guid(result);
        }
    }
}

Change the mouse cursor on mouse over to anchor-like style

If you want to do this in jQuery instead of CSS, you basically follow the same process.

Assuming you have some <div id="target"></div>, you can use the following code:

$("#target").hover(function() {
    $(this).css('cursor','pointer');
}, function() {
    $(this).css('cursor','auto');
});

and that should do it.

Remove shadow below actionbar

I have this same problem, and I have successfully solved this problem. All you have to do is just change the elevation to 0 floating point value in that activity in which you want to remove the elevation.

If you want to change it in an activity called MyActivity.java so you have to get the ActionBar first.

First import the ActionBar class

import android.support.v7.app.ActionBar;

after importing you have to initialize a variable of action bar and set its elevation to 0.

 private ActionBar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    .
    .
    toolbar=getSupportActionBar();
    toolbar.setElevation(0);
    .
    .
    }

Is it not possible to stringify an Error using JSON.stringify?

There is a great Node.js package for that: serialize-error.

npm install serialize-error

It handles well even nested Error objects.

import {serializeError} from 'serialize-error';

JSON.stringify(serializeError(error));

Docs: https://www.npmjs.com/package/serialize-error

How can I convert string to datetime with format specification in JavaScript?

time = "2017-01-18T17:02:09.000+05:30"

t = new Date(time)

hr = ("0" + t.getHours()).slice(-2);
min = ("0" + t.getMinutes()).slice(-2);
sec = ("0" + t.getSeconds()).slice(-2);

t.getFullYear()+"-"+t.getMonth()+1+"-"+t.getDate()+" "+hr+":"+min+":"+sec

Working with Enums in android

Android's preferred approach is int constants enforced with @IntDef:

public static final int GENDER_MALE = 1;
public static final int GENDER_FEMALE = 2;

@Retention(RetentionPolicy.SOURCE)
@IntDef ({GENDER_MALE, GENDER_FEMALE})
public @interface Gender{}

// Example usage...
void exampleFunc(@Gender int gender) {
  switch(gender) {
  case GENDER_MALE:

     break;
  case GENDER_FEMALE:
     // TODO
     break;
  }
}

Docs: https://developer.android.com/studio/write/annotations.html#enum-annotations

Single Form Hide on Startup

In the designer, set the form's Visible property to false. Then avoid calling Show() until you need it.

A better paradigm is to not create an instance of the form until you need it.

How to get Database Name from Connection String using SqlConnectionStringBuilder

You can use the provider-specific ConnectionStringBuilder class (within the appropriate namespace), or System.Data.Common.DbConnectionStringBuilder to abstract the connection string object if you need to. You'd need to know the provider-specific keywords used to designate the information you're looking for, but for a SQL Server example you could do either of these two things:

System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder(connectionString);

string server = builder.DataSource;
string database = builder.InitialCatalog;

or

System.Data.Common.DbConnectionStringBuilder builder = new System.Data.Common.DbConnectionStringBuilder();

builder.ConnectionString = connectionString;

string server = builder["Data Source"] as string;
string database = builder["Initial Catalog"] as string;

Append values to a set in Python

For me, in Python 3, it's working simply in this way:

keep = keep.union((0,1,2,3,4,5,6,7,8,9,10))

I don't know if it may be correct...

Convert Long into Integer

try this:

Int i = Long.valueOf(L)// L: Long Value

How to Delete node_modules - Deep Nested Folder in Windows

On Windows Platform the simplest way is to use the terminal.
Please Run the command RMDIR /Q/S foldername to delete the folder and all of its subfolders.

Example: RMDIR /Q/S node_modules

The Above Command deletes node_modules folder and its subfolders.
For information please visit this https://www.ghacks.net/2017/07/18/how-to-delete-large-folders-in-windows-super-fast/

Prevent content from expanding grid items

By default, a grid item cannot be smaller than the size of its content.

Grid items have an initial size of min-width: auto and min-height: auto.

You can override this behavior by setting grid items to min-width: 0, min-height: 0 or overflow with any value other than visible.

From the spec:

6.6. Automatic Minimum Size of Grid Items

To provide a more reasonable default minimum size for grid items, this specification defines that the auto value of min-width / min-height also applies an automatic minimum size in the specified axis to grid items whose overflow is visible. (The effect is analogous to the automatic minimum size imposed on flex items.)

Here's a more detailed explanation covering flex items, but it applies to grid items, as well:

This post also covers potential problems with nested containers and known rendering differences among major browsers.


To fix your layout, make these adjustments to your code:

.month-grid {
  display: grid;
  grid-template: repeat(6, 1fr) / repeat(7, 1fr);
  background: #fff;
  grid-gap: 2px;
  min-height: 0;  /* NEW */
  min-width: 0;   /* NEW; needed for Firefox */
}

.day-item {
  padding: 10px;
  background: #DFE7E7;
  overflow: hidden;  /* NEW */
  min-width: 0;      /* NEW; needed for Firefox */
}

jsFiddle demo


1fr vs minmax(0, 1fr)

The solution above operates at the grid item level. For a container level solution, see this post:

How to get the index of a maximum element in a NumPy array along one axis

There is argmin() and argmax() provided by numpy that returns the index of the min and max of a numpy array respectively.

Say e.g for 1-D array you'll do something like this

_x000D_
_x000D_
import numpy as np

a = np.array([50,1,0,2])

print(a.argmax()) # returns 0
print(a.argmin()) # returns 2
_x000D_
_x000D_
_x000D_

And similarly for multi-dimensional array

_x000D_
_x000D_
import numpy as np

a = np.array([[0,2,3],[4,30,1]])

print(a.argmax()) # returns 4
print(a.argmin()) # returns 0
_x000D_
_x000D_
_x000D_

Note that these will only return the index of the first occurrence.

JAXB :Need Namespace Prefix to all the elements

marshaller.setProperty only works on the JAX-B marshaller from Sun. The question was regarding the JAX-B marshaller from SpringSource, which does not support setProperty.

How to set the opacity/alpha of a UIImage?

I just needed to do this, but thought Steven's solution would be slow. This should hopefully use graphics HW. Create a category on UIImage:

- (UIImage *)imageByApplyingAlpha:(CGFloat) alpha {
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGRect area = CGRectMake(0, 0, self.size.width, self.size.height);

    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -area.size.height);

    CGContextSetBlendMode(ctx, kCGBlendModeMultiply);

    CGContextSetAlpha(ctx, alpha);

    CGContextDrawImage(ctx, area, self.CGImage);

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;
}

How to find longest string in the table column data

The easiest way is:

select top 1 CR
from table t
order by len(CR) desc

Note that this will only return one value if there are multiple with the same longest length.

Read all files in a folder and apply a function to each data frame

Here is a tidyverse option that might not the most elegant, but offers some flexibility in terms of what is included in the summary:

library(tidyverse)
dir_path <- '~/path/to/data/directory/'
file_pattern <- 'Df\\.[0-9]\\.csv' # regex pattern to match the file name format

read_dir <- function(dir_path, file_name){
  read_csv(paste0(dir_path, file_name)) %>% 
    mutate(file_name = file_name) %>%                # add the file name as a column              
    gather(variable, value, A:B) %>%                 # convert the data from wide to long
    group_by(file_name, variable) %>% 
    summarize(sum = sum(value, na.rm = TRUE),
              min = min(value, na.rm = TRUE),
              mean = mean(value, na.rm = TRUE),
              median = median(value, na.rm = TRUE),
              max = max(value, na.rm = TRUE))
  }

df_summary <- 
  list.files(dir_path, pattern = file_pattern) %>% 
  map_df(~ read_dir(dir_path, .))

df_summary
# A tibble: 8 x 7
# Groups:   file_name [?]
  file_name variable   sum   min  mean median   max
  <chr>     <chr>    <int> <dbl> <dbl>  <dbl> <dbl>
1 Df.1.csv  A           34     4  5.67    5.5     8
2 Df.1.csv  B           22     1  3.67    3       9
3 Df.2.csv  A           21     1  3.5     3.5     6
4 Df.2.csv  B           16     1  2.67    2.5     5
5 Df.3.csv  A           30     0  5       5      11
6 Df.3.csv  B           43     1  7.17    6.5    15
7 Df.4.csv  A           21     0  3.5     3       8
8 Df.4.csv  B           42     1  7       6      16

AngularJS: Basic example to use authentication in Single Page Application

I think that every JSON response should contain a property (e.g. {authenticated: false}) and the client has to test it everytime: if false, then the Angular controller/service will "redirect" to the login page.

And what happen if the user catch de JSON and change the bool to True?

I think you should never rely on client side to do these kind of stuff. If the user is not authenticated, the server should just redirect to a login/error page.

How can I iterate over an enum?

For MS compilers:

#define inc_enum(i) ((decltype(i)) ((int)i + 1))

enum enumtype { one, two, three, count};
for(enumtype i = one; i < count; i = inc_enum(i))
{ 
    dostuff(i); 
}

Note: this is a lot less code than the simple templatized custom iterator answer.

You can get this to work with GCC by using typeof instead of decltype, but I don't have that compiler handy at the moment to make sure it compiles.

How to set focus on an input field after rendering?

Ben Carp solution in typescript

React 16.8 + Functional component - useFocus hook

export const useFocus = (): [React.MutableRefObject<HTMLInputElement>, VoidFunction] => {
  const htmlElRef = React.useRef<HTMLInputElement>(null);
  const setFocus = React.useCallback(() => {
    if (htmlElRef.current) htmlElRef.current.focus();
  }, [htmlElRef]);

  return React.useMemo(() => [htmlElRef, setFocus], [htmlElRef, setFocus]);
};

Ruby - test for array

[1,2,3].is_a? Array evaluates to true.

ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224)

@aravk33 's answer is absolutely correct.

I was going through the same problem. I had a data set of 2450 images. I just could not figure out why I was facing this issue.

Check the dimensions of all the images in your training data.

Add the following snippet while appending your image into your list:

if image.shape==(1,512,512):
    trainx.append(image)

How to gettext() of an element in Selenium Webdriver

You need to print the result of the getText(). You're currently printing the object TxtBoxContent.

getText() will only get the inner text of an element. To get the value, you need to use getAttribute().

WebElement TxtBoxContent = driver.findElement(By.id(WebelementID));
System.out.println("Printing " + TxtBoxContent.getAttribute("value"));

Laravel Fluent Query Builder Join with subquery

I was looking for a solution to quite a related problem: finding the newest records per group which is a specialization of a typical greatest-n-per-group with N = 1.

The solution involves the problem you are dealing with here (i.e., how to build the query in Eloquent) so I am posting it as it might be helpful for others. It demonstrates a cleaner way of sub-query construction using powerful Eloquent fluent interface with multiple join columns and where condition inside joined sub-select.

In my example I want to fetch the newest DNS scan results (table scan_dns) per group identified by watch_id. I build the sub-query separately.

The SQL I want Eloquent to generate:

SELECT * FROM `scan_dns` AS `s`
INNER JOIN (
  SELECT x.watch_id, MAX(x.last_scan_at) as last_scan
  FROM `scan_dns` AS `x`
  WHERE `x`.`watch_id` IN (1,2,3,4,5,42)
  GROUP BY `x`.`watch_id`) AS ss
ON `s`.`watch_id` = `ss`.`watch_id` AND `s`.`last_scan_at` = `ss`.`last_scan`

I did it in the following way:

// table name of the model
$dnsTable = (new DnsResult())->getTable();

// groups to select in sub-query
$ids = collect([1,2,3,4,5,42]);

// sub-select to be joined on
$subq = DnsResult::query()
    ->select('x.watch_id')
    ->selectRaw('MAX(x.last_scan_at) as last_scan')
    ->from($dnsTable . ' AS x')
    ->whereIn('x.watch_id', $ids)
    ->groupBy('x.watch_id');
$qqSql = $subq->toSql();  // compiles to SQL

// the main query
$q = DnsResult::query()
    ->from($dnsTable . ' AS s')
    ->join(
        DB::raw('(' . $qqSql. ') AS ss'),
        function(JoinClause $join) use ($subq) {
            $join->on('s.watch_id', '=', 'ss.watch_id')
                 ->on('s.last_scan_at', '=', 'ss.last_scan')
                 ->addBinding($subq->getBindings());  
                 // bindings for sub-query WHERE added
        });

$results = $q->get();

UPDATE:

Since Laravel 5.6.17 the sub-query joins were added so there is a native way to build the query.

$latestPosts = DB::table('posts')
                   ->select('user_id', DB::raw('MAX(created_at) as last_post_created_at'))
                   ->where('is_published', true)
                   ->groupBy('user_id');

$users = DB::table('users')
        ->joinSub($latestPosts, 'latest_posts', function ($join) {
            $join->on('users.id', '=', 'latest_posts.user_id');
        })->get();