Programs & Examples On #Dataflowtask

C++ catching all exceptions

  1. Can you run your JNI-using Java application from a console window (launch it from a java command line) to see if there is any report of what may have been detected before the JVM was crashed. When running directly as a Java window application, you may be missing messages that would appear if you ran from a console window instead.

  2. Secondly, can you stub your JNI DLL implementation to show that methods in your DLL are being entered from JNI, you are returning properly, etc?

  3. Just in case the problem is with an incorrect use of one of the JNI-interface methods from the C++ code, have you verified that some simple JNI examples compile and work with your setup? I'm thinking in particular of using the JNI-interface methods for converting parameters to native C++ formats and turning function results into Java types. It is useful to stub those to make sure that the data conversions are working and you are not going haywire in the COM-like calls into the JNI interface.

  4. There are other things to check, but it is hard to suggest any without knowing more about what your native Java methods are and what the JNI implementation of them is trying to do. It is not clear that catching an exception from the C++ code level is related to your problem. (You can use the JNI interface to rethrow the exception as a Java one, but it is not clear from what you provide that this is going to help.)

Only numbers. Input number in React

one line of code

<input value={this.state.financialGoal} onChange={event => this.setState({financialGoal: event.target.value.replace(/\D/,'')})}/>

while installing vc_redist.x64.exe, getting error "Failed to configure per-machine MSU package."

The OS failed to install the required update Windows8.1-KB2999226-x64.msu. However I tried to find the particular update from -

C:\ProgramData\Package Cache\469A82B09E217DDCF849181A586DF1C97C0C5C85\packages\Patch\amd64\Windows8.1-KB2999226-x64.msu.

I couldn't find it there so I installed the kb2999226 update from here (Windows 10 Universal C runtime)

Then I installed the update according to my OS and after that It was working fine.

How to access private data members outside the class without making "friend"s?

access private members outside class ....only for study purpose .... This program accepts all the below conditions "I dont want to create member function for above class A. And also i dont want to inherit the above class A. I dont want to change the specifier of iData."

//here member function is used only to input and output the private values ... //void hack() is defined outside the class...

//GEEK MODE....;)
#include<iostream.h>
#include<conio.h>

    class A
    {
    private :int iData,x;
    public: void get()             //enter the values
        {cout<<"Enter iData : ";
            cin>>iData;cout<<"Enter x : ";cin>>x;}

        void put()                               //displaying values
    {cout<<endl<<"sum = "<<iData+x;}
};

void hack();        //hacking function

void main()
{A obj;clrscr();
obj.get();obj.put();hack();obj.put();getch();
}

void hack()         //hack begins
{int hck,*ptr=&hck;
cout<<endl<<"Enter value of private data (iData or x) : ";
cin>>hck;     //enter the value assigned for iData or x
for(int i=0;i<5;i++)
{ptr++;
if(*ptr==hck)
{cout<<"Private data hacked...!!!\nChange the value : ";
cin>>*ptr;cout<<hck<<" Is chaged to : "<<*ptr;
return;}
}cout<<"Sorry value not found.....";
}

How to get root view controller?

As suggested here by @0x7fffffff, if you have UINavigationController it can be easier to do:

YourViewController *rootController =
    (YourViewController *)
        [self.navigationController.viewControllers objectAtIndex: 0];

The code in the answer above returns UINavigation controller (if you have it) and if this is what you need, you can use self.navigationController.

prevent iphone default keyboard when focusing an <input>

I asked a similar question here and got a fantastic answer - use the iPhone native datepicker - it's great.

How to turn off iPhone keypad for a specified input field on web page

Synopsis / pseudo-code:

if small screen mobile device 

  set field type to "date" - e.g. document.getElementById('my_field').type = "date";
  // input fields of type "date" invoke the iPhone datepicker.

else

  init datepicker - e.g. $("#my_field").datepicker();

The reason for dynamically setting the field type to "date" is that Opera will pop up its own native datepicker otherwise, and I'm assuming you want to show the datepicker consistently on desktop browsers.

Best way to generate a random float in C#

Here is another way that I came up with: Let's say you want to get a float between 5.5 and 7, with 3 decimals.

float myFloat;
int myInt;
System.Random rnd = new System.Random();

void GenerateFloat()
{
myInt = rnd.Next(1, 2000);
myFloat = (myInt / 1000) + 5.5f;
}

That way you will always get a bigger number than 5.5 and a smaller number than 7.

Formatting DataBinder.Eval data

There is an optional overload for DataBinder.Eval to supply formatting:

<%# DataBinder.Eval(Container.DataItem, "expression"[, "format"]) %>

The format parameter is a String value, using the value placeholder replacement syntax (called composite formatting) like this:

<asp:Label id="lblNewsDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "publishedDate", "{0:dddd d MMMM}") %>'</label>

Kubernetes pod gets recreated when deleted

Many answers here tells to delete a specific k8s object, but you can delete multiple objects at once, instead of one by one:

kubectl delete deployments,jobs,services,pods --all -n <namespace>

In my case, I'm running OpenShift cluster with OLM - Operator Lifecycle Manager. OLM is the one who controls the deployment, so when I deleted the deployment, it was not sufficient to stop the pods from restarting.

Only when I deleted OLM and its subscription, the deployment, services and pods were gone.

First list all k8s objects in your namespace:

$ kubectl get all -n openshift-submariner

NAME                                       READY   STATUS    RESTARTS   AGE
pod/submariner-operator-847f545595-jwv27   1/1     Running   0          8d  
NAME                                  TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)    AGE
service/submariner-operator-metrics   ClusterIP   101.34.190.249   <none>        8383/TCP   8d
NAME                                  READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/submariner-operator   1/1     1            1           8d
NAME                                             DESIRED   CURRENT   READY   AGE
replicaset.apps/submariner-operator-847f545595   1         1         1       8d

OLM is not listed with get all, so I search for it specifically:

$ kubectl get olm -n openshift-submariner

NAME                                                      AGE
operatorgroup.operators.coreos.com/openshift-submariner   8d
NAME                                                             DISPLAY      VERSION
clusterserviceversion.operators.coreos.com/submariner-operator   Submariner   0.0.1 

Now delete all objects, including OLMs, subscriptions, deployments, replica-sets, etc:

$ kubectl delete olm,svc,rs,rc,subs,deploy,jobs,pods --all -n openshift-submariner

operatorgroup.operators.coreos.com "openshift-submariner" deleted
clusterserviceversion.operators.coreos.com "submariner-operator" deleted
deployment.extensions "submariner-operator" deleted
subscription.operators.coreos.com "submariner" deleted
service "submariner-operator-metrics" deleted
replicaset.extensions "submariner-operator-847f545595" deleted
pod "submariner-operator-847f545595-jwv27" deleted

List objects again - all gone:

$ kubectl get all -n openshift-submariner
No resources found.

$ kubectl get olm -n openshift-submariner
No resources found.

Regex allow a string to only contain numbers 0 - 9 and limit length to 45

codaddict has provided the right answer. As for what you've tried, I'll explain why they don't make the cut:

  • [0-9]{1,45} is almost there, however it matches a 1-to-45-digit string even if it occurs within another longer string containing other characters. Hence you need ^ and $ to restrict it to an exact match.

  • ^[0-9]{45}*$ matches an exactly-45-digit string, repeated 0 or any number of times (*). That means the length of the string can only be 0 or a multiple of 45 (90, 135, 180...).

How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

Alternatively, if you can customize your server response, you could return a 403 Forbidden.

The browser will not open the authentication popup and the jquery callback will be called.

Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support

I encountered a similar issue trying to use xlrd in jupyter notebook. I notice you are using a virtual environment and that was the key to my issue as well. I had xlrd installed in my venv, but I had not properly installed a kernel for that virtual environment in my notebook.

To get it to work, I created my virtual environment and activated it.

Then... pip install ipykernel

And then... ipython kernel install --user --name=myproject

Finally, start jupyter notebooks and when you create a new notebook, select the name you created (in this example, 'myproject')

Hope that helps.

Java Program to test if a character is uppercase/lowercase/number/vowel

 Char input;

 if (input.matches("^[a-zA-Z]+$")) 
 {
     if (Character.isLowerCase(input))
     {
        // lowercase
     } 
     else
     { 
        // uppercase
     }

     if (input.matches("[^aeiouAEIOU]"))
     {
          // vowel
     }
     else 
     {
         // consonant
     }
 }
 else if (input.matches("^(0|[1-9][0-9]*)$"))
 {
       // number
 }
 else
 {
     // invalid
 }

Create Directory if it doesn't exist with Ruby

Simple way:

directory_name = "name"
Dir.mkdir(directory_name) unless File.exists?(directory_name)

Saving response from Requests to file

You can use the response.text to write to a file:

import requests

files = {'f': ('1.pdf', open('1.pdf', 'rb'))}
response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)
response.raise_for_status() # ensure we notice bad responses
file = open("resp_text.txt", "w")
file.write(response.text)
file.close()
file = open("resp_content.txt", "w")
file.write(response.text)
file.close()

How the single threaded non blocking IO model works in Node.js

Node.js uses libuv behind the scenes. libuv has a thread pool (of size 4 by default). Therefore Node.js does use threads to achieve concurrency.

However, your code runs on a single thread (i.e., all of the callbacks of Node.js functions will be called on the same thread, the so called loop-thread or event-loop). When people say "Node.js runs on a single thread" they are really saying "the callbacks of Node.js run on a single thread".

Error : getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443

I have a fresh Windows 10 installed on my PC and tried this on the command line and it works like a charm:

npm config rm https-proxy

Can you have multiple $(document).ready(function(){ ... }); sections?

Yes it is possible but you can better use a div #mydiv and use both

$(document).ready(function(){});

//and

$("#mydiv").ready(function(){});

@font-face not working

By using the .. operator, you've have duplicated the folder path - and will get something like this : /wp-content/themes/wp-content/themes/twentysixteen/fonts/.

Use the console in your browser to see for this error.

Where do I put image files, css, js, etc. in Codeigniter?

Regardless of where you put the CSS file you can simply use the CodeIgniter "html" helper called link_tag(). You would apply this helper something like this:

echo link_tag('folder/subfolder/stylesheet.css');

It is up to you to locate the CSS file in the most appropriate place (in your opinion). You would have to either autoload the "html" helper or separately load it in to use it.

People keep suggesting the usage of base_url() to achieve this but it is actually not really the "CodeIgniter" way to do it (I think this question has a few duplicates). That will work but one of the reasons for using a framework is to use the pre-made functions within it.

There are many helpers in codeigniter to do this kind of thing.

import dat file into R

The dat file has some lines of extra information before the actual data. Skip them with the skip argument:

read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
           header=TRUE, skip=3)

An easy way to check this if you are unfamiliar with the dataset is to first use readLines to check a few lines, as below:

readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
          n=10)
# [1] "Ozone data from CZ03 2009"   "Local time: GMT + 0"        
# [3] ""                            "Date        Hour      Value"
# [5] "01.01.2009 00:00       34.3" "01.01.2009 01:00       31.9"
# [7] "01.01.2009 02:00       29.9" "01.01.2009 03:00       28.5"
# [9] "01.01.2009 04:00       32.9" "01.01.2009 05:00       20.5"

Here, we can see that the actual data starts at [4], so we know to skip the first three lines.

Update

If you really only wanted the Value column, you could do that by:

as.vector(
    read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
               header=TRUE, skip=3)$Value)

Again, readLines is useful for helping us figure out the actual name of the columns we will be importing.

But I don't see much advantage to doing that over reading the whole dataset in and extracting later.

How do I get this javascript to run every second?

You can use setTimeout to run the function/command once or setInterval to run the function/command at specified intervals.

var a = setTimeout("alert('run just one time')",500);
var b = setInterval("alert('run each 3 seconds')",3000);

//To abort the interval you can use this:
clearInterval(b);

Count a list of cells with the same background color

Yes VBA is the way to go.

But, if you don't need to have a cell with formula that auto-counts/updates the number of cells with a particular colour, an alternative is simply to use the 'Find and Replace' function and format the cell to have the appropriate colour fill.

Hitting 'Find All' will give you the total number of cells found at the bottom left of the dialogue box.

enter image description here

This becomes especially useful if your search range is massive. The VBA script will be very slow but the 'Find and Replace' function will still be very quick.

Converting a generic list to a CSV string

in 3.5, i was still able to do this. Its much more simpler and doesnt need lambda.

String.Join(",", myList.ToArray<string>());

grep using a character vector with multiple patterns

Take away the spaces. So do:

matches <- unique(grep("A1|A9|A6", myfile$Letter, value=TRUE, fixed=TRUE))

Regex to match only uppercase "words" with some exceptions

For the first case you propose you can use: '[[:blank:]]+[A-Z0-9]+[[:blank:]]+', for example:

echo "The thing P1 must connect to the J236 thing in the Foo position" | grep -oE '[[:blank:]]+[A-Z0-9]+[[:blank:]]+'

In the second case maybe you need to use something else and not a regex, maybe a script with a dictionary of technical words...

Cheers, Fernando

How to determine the number of days in a month in SQL Server?

select  datediff(day, 
        dateadd(day, 0, dateadd(month, ((2013 - 1900) * 12) + 3 - 1, 0)),
        dateadd(day, 0, dateadd(month, ((2013  - 1900) * 12) + 3, 0))
        )

Nice Simple and does not require creating any functions Work Fine

Sending SMS from PHP

You need to subscribe to a SMS gateway. There are thousands of those (try searching with google) and they are usually not free. For example this one has support for PHP.

Combining multiple commits before pushing in Git

You probably want to use Interactive Rebasing, which is described in detail in that link.

You can find other good resources if you search for "git rebase interactive".

How to handle back button in activity

You should use:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ECLAIR
            && keyCode == KeyEvent.KEYCODE_BACK
            && event.getRepeatCount() == 0) {
        // Take care of calling this method on earlier versions of
        // the platform where it doesn't exist.
        onBackPressed();
    }

    return super.onKeyDown(keyCode, event);
}

@Override
public void onBackPressed() {
    // This will be called either automatically for you on 2.0
    // or later, or by the code above on earlier versions of the
    // platform.
    return;
}

As defined here: http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html

If you are using an older version to compile the code, replace android.os.Build.VERSION_CODES.ECLAIR by 5 (you can add a private int named ECLAIR for example)

What is the difference between json.dump() and json.dumps() in python?

The functions with an s take string parameters. The others take file streams.

How do I install imagemagick with homebrew?

You could try:

brew update && brew install imagemagick

How to wait till the response comes from the $http request, in angularjs?

I was having the same problem and none if these worked for me. Here is what did work though...

app.factory('myService', function($http) {
    var data = function (value) {
            return $http.get(value);
    }

    return { data: data }
});

and then the function that uses it is...

vm.search = function(value) {

        var recieved_data = myService.data(value);

        recieved_data.then(
            function(fulfillment){
                vm.tags = fulfillment.data;
            }, function(){
                console.log("Server did not send tag data.");
        });
    };

The service isn't that necessary but I think its a good practise for extensibility. Most of what you will need for one will for any other, especially when using APIs. Anyway I hope this was helpful.

Checking if element exists with Python Selenium

None of the solutions provided seemed at all easiest to me, so I'd like to add my own way.

Basically, you get the list of the elements instead of just the element and then count the results; if it's zero, then it doesn't exist. Example:

if driver.find_elements_by_css_selector('#element'):
    print "Element exists"

Notice the "s" in find_elements_by_css_selector to make sure it can be countable.

EDIT: I was checking the len( of the list, but I recently learned that an empty list is falsey, so you don't need to get the length of the list at all, leaving for even simpler code.

Also, another answer says that using xpath is more reliable, which is just not true. See What is the difference between css-selector & Xpath? which is better(according to performance & for cross browser testing)?

Soft keyboard open and close listener in an activity in Android

For Activity:

    final View activityRootView = findViewById(R.id.activityRoot);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();

                activityRootView.getWindowVisibleDisplayFrame(r);

                int heightDiff = view.getRootView().getHeight() - (r.bottom - r.top);
                if (heightDiff > 100) { 
                 //enter your code here
                }else{
                 //enter code for hid
                }
            }
        });

For Fragment:

    view = inflater.inflate(R.layout.live_chat_fragment, null);
view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                //r will be populated with the coordinates of your view that area still visible.
                view.getWindowVisibleDisplayFrame(r);

                int heightDiff = view.getRootView().getHeight() - (r.bottom - r.top);
                if (heightDiff > 500) { // if more than 100 pixels, its probably a keyboard...

                }
            }
        });

MINGW64 "make build" error: "bash: make: command not found"

Try using cmake itself. In the build directory, run:

cmake --build .

Parsing command-line arguments in C

Yet another alternative is The Lean Mean C++ Option Parser:

http://optionparser.sourceforge.net

It is a header-only library (just a single header file, in fact) and unlike all the other suggestions it is also freestanding, i.e. it has no dependencies whatsoever. In particular there's no dependency on the STL. It does not even use exceptions or anything else that requires library support. This means it can be linked with plain C or other languages without introducing "foreign" libraries.

Like boost::program_options its API offers convenient direct access to options, i.e. you can write code like this

if (options[HELP]) ... ;

and

int verbosity = options[VERBOSE].count();

Unlike boost::program_options however this is simply using an array indexed with a (user-provided) enum. This offers the convenience of an associative container without the weight.

It's well documented and has a company-friendly license (MIT).

TLMC++OP includes a nice formatter for usage messages that can do line-wrapping and column alignment which is useful if you're localizing your program, because it ensures that the output will look good even in languages that have longer messages. It also saves you the nuisance of manually formatting your usage for 80 columns.

Open files always in a new tab

Open in new Tab Solution:

  1. Open the command palette by: Cmd + Shift + K
  2. Open settings file by: Preferences: Open Settings (JSON)
  3. Under user setting, enable Tabs by: "workbench.editor.showTabs": true

how to sort an ArrayList in ascending order using Collections and Comparator

Use the default version:

Collections.sort(myarrayList);

Of course this requires that your Elements implement Comparable, but the same holds true for the version you mentioned.

BTW: you should use generics in your code, that way you get compile-time errors if your class doesn't implement Comparable. And compile-time errors are much better than the runtime errors you'll get otherwise.

List<MyClass> list = new ArrayList<MyClass>();
// now fill up the list

// compile error here unless MyClass implements Comparable
Collections.sort(list); 

How to convert ActiveRecord results into an array of hashes

For current ActiveRecord (4.2.4+) there is a method to_hash on the Result object that returns an array of hashes. You can then map over it and convert to symbolized hashes:

# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
      {"id" => 2, "title" => "title_2", "body" => "body_2"},
      ...
     ]

result.to_hash.map(&:symbolize_keys)
# => [{:id => 1, :title => "title_1", :body => "body_1"},
      {:id => 2, :title => "title_2", :body => "body_2"},
      ...
     ]

See the ActiveRecord::Result docs for more info.

How to get the separate digits of an int number?

I see all the answer are ugly and not very clean.

I suggest you use a little bit of recursion to solve your problem. This post is very old, but it might be helpful to future coders.

public static void recursion(int number) {
    if(number > 0) {
        recursion(number/10);
        System.out.printf("%d   ", (number%10));
    }
}

Output:

Input: 12345

Output: 1   2   3   4   5 

List of All Locales and Their Short Codes?

While accepted answer is pretty complete (I used myself in similar question that arised to me), I think it is worth to put the whole supported language codes and variations, as well as encodings, and point user to a file which is present in almost any linux distributions, in case he simply wants a quicker answer and no internet for example.

This is the file /usr/share/i18n/SUPPORTED and its contents:

aa_DJ.UTF-8 UTF-8
aa_DJ ISO-8859-1
aa_ER UTF-8
aa_ER@saaho UTF-8
aa_ET UTF-8
af_ZA.UTF-8 UTF-8
af_ZA ISO-8859-1
am_ET UTF-8
an_ES.UTF-8 UTF-8
an_ES ISO-8859-15
ar_AE.UTF-8 UTF-8
ar_AE ISO-8859-6
ar_BH.UTF-8 UTF-8
ar_BH ISO-8859-6
ar_DZ.UTF-8 UTF-8
ar_DZ ISO-8859-6
ar_EG.UTF-8 UTF-8
ar_EG ISO-8859-6
ar_IN UTF-8
ar_IQ.UTF-8 UTF-8
ar_IQ ISO-8859-6
ar_JO.UTF-8 UTF-8
ar_JO ISO-8859-6
ar_KW.UTF-8 UTF-8
ar_KW ISO-8859-6
ar_LB.UTF-8 UTF-8
ar_LB ISO-8859-6
ar_LY.UTF-8 UTF-8
ar_LY ISO-8859-6
ar_MA.UTF-8 UTF-8
ar_MA ISO-8859-6
ar_OM.UTF-8 UTF-8
ar_OM ISO-8859-6
ar_QA.UTF-8 UTF-8
ar_QA ISO-8859-6
ar_SA.UTF-8 UTF-8
ar_SA ISO-8859-6
ar_SD.UTF-8 UTF-8
ar_SD ISO-8859-6
ar_SY.UTF-8 UTF-8
ar_SY ISO-8859-6
ar_TN.UTF-8 UTF-8
ar_TN ISO-8859-6
ar_YE.UTF-8 UTF-8
ar_YE ISO-8859-6
az_AZ UTF-8
as_IN UTF-8
ast_ES.UTF-8 UTF-8
ast_ES ISO-8859-15
be_BY.UTF-8 UTF-8
be_BY CP1251
be_BY@latin UTF-8
bem_ZM UTF-8
ber_DZ UTF-8
ber_MA UTF-8
bg_BG.UTF-8 UTF-8
bg_BG CP1251
bho_IN UTF-8
bn_BD UTF-8
bn_IN UTF-8
bo_CN UTF-8
bo_IN UTF-8
br_FR.UTF-8 UTF-8
br_FR ISO-8859-1
br_FR@euro ISO-8859-15
brx_IN UTF-8
bs_BA.UTF-8 UTF-8
bs_BA ISO-8859-2
byn_ER UTF-8
ca_AD.UTF-8 UTF-8
ca_AD ISO-8859-15
ca_ES.UTF-8 UTF-8
ca_ES ISO-8859-1
ca_ES@euro ISO-8859-15
ca_FR.UTF-8 UTF-8
ca_FR ISO-8859-15
ca_IT.UTF-8 UTF-8
ca_IT ISO-8859-15
crh_UA UTF-8
cs_CZ.UTF-8 UTF-8
cs_CZ ISO-8859-2
csb_PL UTF-8
cv_RU UTF-8
cy_GB.UTF-8 UTF-8
cy_GB ISO-8859-14
da_DK.UTF-8 UTF-8
da_DK ISO-8859-1
de_AT.UTF-8 UTF-8
de_AT ISO-8859-1
de_AT@euro ISO-8859-15
de_BE.UTF-8 UTF-8
de_BE ISO-8859-1
de_BE@euro ISO-8859-15
de_CH.UTF-8 UTF-8
de_CH ISO-8859-1
de_DE.UTF-8 UTF-8
de_DE ISO-8859-1
de_DE@euro ISO-8859-15
de_LU.UTF-8 UTF-8
de_LU ISO-8859-1
de_LU@euro ISO-8859-15
dv_MV UTF-8
dz_BT UTF-8
el_GR.UTF-8 UTF-8
el_GR ISO-8859-7
el_CY.UTF-8 UTF-8
el_CY ISO-8859-7
en_AG UTF-8
en_AU.UTF-8 UTF-8
en_AU ISO-8859-1
en_BW.UTF-8 UTF-8
en_BW ISO-8859-1
en_CA.UTF-8 UTF-8
en_CA ISO-8859-1
en_DK.UTF-8 UTF-8
en_DK ISO-8859-1
en_GB.UTF-8 UTF-8
en_GB ISO-8859-1
en_HK.UTF-8 UTF-8
en_HK ISO-8859-1
en_IE.UTF-8 UTF-8
en_IE ISO-8859-1
en_IE@euro ISO-8859-15
en_IN UTF-8
en_NG UTF-8
en_NZ.UTF-8 UTF-8
en_NZ ISO-8859-1
en_PH.UTF-8 UTF-8
en_PH ISO-8859-1
en_SG.UTF-8 UTF-8
en_SG ISO-8859-1
en_US.UTF-8 UTF-8
en_US ISO-8859-1
en_ZA.UTF-8 UTF-8
en_ZA ISO-8859-1
en_ZM UTF-8
en_ZW.UTF-8 UTF-8
en_ZW ISO-8859-1
es_AR.UTF-8 UTF-8
es_AR ISO-8859-1
es_BO.UTF-8 UTF-8
es_BO ISO-8859-1
es_CL.UTF-8 UTF-8
es_CL ISO-8859-1
es_CO.UTF-8 UTF-8
es_CO ISO-8859-1
es_CR.UTF-8 UTF-8
es_CR ISO-8859-1
es_CU UTF-8
es_DO.UTF-8 UTF-8
es_DO ISO-8859-1
es_EC.UTF-8 UTF-8
es_EC ISO-8859-1
es_ES.UTF-8 UTF-8
es_ES ISO-8859-1
es_ES@euro ISO-8859-15
es_GT.UTF-8 UTF-8
es_GT ISO-8859-1
es_HN.UTF-8 UTF-8
es_HN ISO-8859-1
es_MX.UTF-8 UTF-8
es_MX ISO-8859-1
es_NI.UTF-8 UTF-8
es_NI ISO-8859-1
es_PA.UTF-8 UTF-8
es_PA ISO-8859-1
es_PE.UTF-8 UTF-8
es_PE ISO-8859-1
es_PR.UTF-8 UTF-8
es_PR ISO-8859-1
es_PY.UTF-8 UTF-8
es_PY ISO-8859-1
es_SV.UTF-8 UTF-8
es_SV ISO-8859-1
es_US.UTF-8 UTF-8
es_US ISO-8859-1
es_UY.UTF-8 UTF-8
es_UY ISO-8859-1
es_VE.UTF-8 UTF-8
es_VE ISO-8859-1
et_EE.UTF-8 UTF-8
et_EE ISO-8859-1
et_EE.ISO-8859-15 ISO-8859-15
eu_ES.UTF-8 UTF-8
eu_ES ISO-8859-1
eu_ES@euro ISO-8859-15
fa_IR UTF-8
ff_SN UTF-8
fi_FI.UTF-8 UTF-8
fi_FI ISO-8859-1
fi_FI@euro ISO-8859-15
fil_PH UTF-8
fo_FO.UTF-8 UTF-8
fo_FO ISO-8859-1
fr_BE.UTF-8 UTF-8
fr_BE ISO-8859-1
fr_BE@euro ISO-8859-15
fr_CA.UTF-8 UTF-8
fr_CA ISO-8859-1
fr_CH.UTF-8 UTF-8
fr_CH ISO-8859-1
fr_FR.UTF-8 UTF-8
fr_FR ISO-8859-1
fr_FR@euro ISO-8859-15
fr_LU.UTF-8 UTF-8
fr_LU ISO-8859-1
fr_LU@euro ISO-8859-15
fur_IT UTF-8
fy_NL UTF-8
fy_DE UTF-8
ga_IE.UTF-8 UTF-8
ga_IE ISO-8859-1
ga_IE@euro ISO-8859-15
gd_GB.UTF-8 UTF-8
gd_GB ISO-8859-15
gez_ER UTF-8
gez_ER@abegede UTF-8
gez_ET UTF-8
gez_ET@abegede UTF-8
gl_ES.UTF-8 UTF-8
gl_ES ISO-8859-1
gl_ES@euro ISO-8859-15
gu_IN UTF-8
gv_GB.UTF-8 UTF-8
gv_GB ISO-8859-1
ha_NG UTF-8
he_IL.UTF-8 UTF-8
he_IL ISO-8859-8
hi_IN UTF-8
hne_IN UTF-8
hr_HR.UTF-8 UTF-8
hr_HR ISO-8859-2
hsb_DE ISO-8859-2
hsb_DE.UTF-8 UTF-8
ht_HT UTF-8
hu_HU.UTF-8 UTF-8
hu_HU ISO-8859-2
hy_AM UTF-8
hy_AM.ARMSCII-8 ARMSCII-8
id_ID.UTF-8 UTF-8
id_ID ISO-8859-1
ig_NG UTF-8
ik_CA UTF-8
is_IS.UTF-8 UTF-8
is_IS ISO-8859-1
it_CH.UTF-8 UTF-8
it_CH ISO-8859-1
it_IT.UTF-8 UTF-8
it_IT ISO-8859-1
it_IT@euro ISO-8859-15
iu_CA UTF-8
iw_IL.UTF-8 UTF-8
iw_IL ISO-8859-8
ja_JP.EUC-JP EUC-JP
ja_JP.UTF-8 UTF-8
ka_GE.UTF-8 UTF-8
ka_GE GEORGIAN-PS
kk_KZ.UTF-8 UTF-8
kk_KZ PT154
kl_GL.UTF-8 UTF-8
kl_GL ISO-8859-1
km_KH UTF-8
kn_IN UTF-8
ko_KR.EUC-KR EUC-KR
ko_KR.UTF-8 UTF-8
kok_IN UTF-8
ks_IN UTF-8
ks_IN@devanagari UTF-8
ku_TR.UTF-8 UTF-8
ku_TR ISO-8859-9
kw_GB.UTF-8 UTF-8
kw_GB ISO-8859-1
ky_KG UTF-8
lb_LU UTF-8
lg_UG.UTF-8 UTF-8
lg_UG ISO-8859-10
li_BE UTF-8
li_NL UTF-8
lij_IT UTF-8
lo_LA UTF-8
lt_LT.UTF-8 UTF-8
lt_LT ISO-8859-13
lv_LV.UTF-8 UTF-8
lv_LV ISO-8859-13
mag_IN UTF-8
mai_IN UTF-8
mg_MG.UTF-8 UTF-8
mg_MG ISO-8859-15
mhr_RU UTF-8
mi_NZ.UTF-8 UTF-8
mi_NZ ISO-8859-13
mk_MK.UTF-8 UTF-8
mk_MK ISO-8859-5
ml_IN UTF-8
mn_MN UTF-8
mr_IN UTF-8
ms_MY.UTF-8 UTF-8
ms_MY ISO-8859-1
mt_MT.UTF-8 UTF-8
mt_MT ISO-8859-3
my_MM UTF-8
nan_TW@latin UTF-8
nb_NO.UTF-8 UTF-8
nb_NO ISO-8859-1
nds_DE UTF-8
nds_NL UTF-8
ne_NP UTF-8
nl_AW UTF-8
nl_BE.UTF-8 UTF-8
nl_BE ISO-8859-1
nl_BE@euro ISO-8859-15
nl_NL.UTF-8 UTF-8
nl_NL ISO-8859-1
nl_NL@euro ISO-8859-15
nn_NO.UTF-8 UTF-8
nn_NO ISO-8859-1
nr_ZA UTF-8
nso_ZA UTF-8
oc_FR.UTF-8 UTF-8
oc_FR ISO-8859-1
om_ET UTF-8
om_KE.UTF-8 UTF-8
om_KE ISO-8859-1
or_IN UTF-8
os_RU UTF-8
pa_IN UTF-8
pa_PK UTF-8
pap_AN UTF-8
pl_PL.UTF-8 UTF-8
pl_PL ISO-8859-2
ps_AF UTF-8
pt_BR.UTF-8 UTF-8
pt_BR ISO-8859-1
pt_PT.UTF-8 UTF-8
pt_PT ISO-8859-1
pt_PT@euro ISO-8859-15
ro_RO.UTF-8 UTF-8
ro_RO ISO-8859-2
ru_RU.KOI8-R KOI8-R
ru_RU.UTF-8 UTF-8
ru_RU ISO-8859-5
ru_UA.UTF-8 UTF-8
ru_UA KOI8-U
rw_RW UTF-8
sa_IN UTF-8
sc_IT UTF-8
sd_IN UTF-8
sd_IN@devanagari UTF-8
se_NO UTF-8
shs_CA UTF-8
si_LK UTF-8
sid_ET UTF-8
sk_SK.UTF-8 UTF-8
sk_SK ISO-8859-2
sl_SI.UTF-8 UTF-8
sl_SI ISO-8859-2
so_DJ.UTF-8 UTF-8
so_DJ ISO-8859-1
so_ET UTF-8
so_KE.UTF-8 UTF-8
so_KE ISO-8859-1
so_SO.UTF-8 UTF-8
so_SO ISO-8859-1
sq_AL.UTF-8 UTF-8
sq_AL ISO-8859-1
sq_MK UTF-8
sr_ME UTF-8
sr_RS UTF-8
sr_RS@latin UTF-8
ss_ZA UTF-8
st_ZA.UTF-8 UTF-8
st_ZA ISO-8859-1
sv_FI.UTF-8 UTF-8
sv_FI ISO-8859-1
sv_FI@euro ISO-8859-15
sv_SE.UTF-8 UTF-8
sv_SE ISO-8859-1
sw_KE UTF-8
sw_TZ UTF-8
ta_IN UTF-8
ta_LK UTF-8
te_IN UTF-8
tg_TJ.UTF-8 UTF-8
tg_TJ KOI8-T
th_TH.UTF-8 UTF-8
th_TH TIS-620
ti_ER UTF-8
ti_ET UTF-8
tig_ER UTF-8
tk_TM UTF-8
tl_PH.UTF-8 UTF-8
tl_PH ISO-8859-1
tn_ZA UTF-8
tr_CY.UTF-8 UTF-8
tr_CY ISO-8859-9
tr_TR.UTF-8 UTF-8
tr_TR ISO-8859-9
ts_ZA UTF-8
tt_RU UTF-8
tt_RU@iqtelif UTF-8
ug_CN UTF-8
uk_UA.UTF-8 UTF-8
uk_UA KOI8-U
unm_US UTF-8
ur_IN UTF-8
ur_PK UTF-8
uz_UZ ISO-8859-1
uz_UZ@cyrillic UTF-8
ve_ZA UTF-8
vi_VN UTF-8
wa_BE ISO-8859-1
wa_BE@euro ISO-8859-15
wa_BE.UTF-8 UTF-8
wae_CH UTF-8
wal_ET UTF-8
wo_SN UTF-8
xh_ZA.UTF-8 UTF-8
xh_ZA ISO-8859-1
yi_US.UTF-8 UTF-8
yi_US CP1255
yo_NG UTF-8
yue_HK UTF-8
zh_CN.GB18030 GB18030
zh_CN.GBK GBK
zh_CN.UTF-8 UTF-8
zh_CN GB2312
zh_HK.UTF-8 UTF-8
zh_HK BIG5-HKSCS
zh_SG.UTF-8 UTF-8
zh_SG.GBK GBK
zh_SG GB2312
zh_TW.EUC-TW EUC-TW
zh_TW.UTF-8 UTF-8
zh_TW BIG5
zu_ZA.UTF-8 UTF-8
zu_ZA ISO-8859-1

Converting file into Base64String and back again

For Java, consider using Apache Commons FileUtils:

/**
 * Convert a file to base64 string representation
 */
public String fileToBase64(File file) throws IOException {
    final byte[] bytes = FileUtils.readFileToByteArray(file);
    return Base64.getEncoder().encodeToString(bytes);
}

/**
 * Convert base64 string representation to a file
 */
public void base64ToFile(String base64String, String filePath) throws IOException {
    byte[] bytes = Base64.getDecoder().decode(base64String);
    FileUtils.writeByteArrayToFile(new File(filePath), bytes);
}

Where does Oracle SQL Developer store connections?

for macOS

/Users/joseluisbz/.sqldeveloper/system18.1.0.095.1630/o.jdeveloper.db.connection/connections.xml

unsigned int vs. size_t

Type size_t must be big enough to store the size of any possible object. Unsigned int doesn't have to satisfy that condition.

For example in 64 bit systems int and unsigned int may be 32 bit wide, but size_t must be big enough to store numbers bigger than 4G

How to read html from a url in python 3

Try the 'requests' module, it's much simpler.

#pip install requests for installation

import requests

url = 'https://www.google.com/'
r = requests.get(url)
r.text

more info here > http://docs.python-requests.org/en/master/

how to calculate percentage in python

This is because (100/500) is an integer expression yielding 0.

Try

per = 100.0 * tota / 500

there's no need for the float() call, since using a floating-point literal (100.0) will make the entire expression floating-point anyway.

UINavigationBar custom back button without title

I have been using this solution since iOS 5 or so without any problems. I made a utility function that I call in my view controllers. You need to do it either in viewDidLoad or any point after that.

void updateBackButtonTextForViewController(UIViewController *viewController, NSString *text)
{
    if(! viewController.navigationItem.backBarButtonItem)
    {
        viewController.navigationItem.backBarButtonItem =
        [[UIBarButtonItem alloc] initWithTitle:text
                                         style:UIBarButtonItemStylePlain
                                        target:nil action:nil];
    }
    else
    {
        viewController.navigationItem.backBarButtonItem.title = text;
    }
}

In some cases the navigation item may already exist, in other cases it needs to be created. This accounts for both of those cases without messing with the navigation item title. It allows you to remove the title by simply passing in @"".

Split string into array of characters?

You can just assign the string to a byte array (the reverse is also possible). The result is 2 numbers for each character, so Xmas converts to a byte array containing {88,0,109,0,97,0,115,0}
or you can use StrConv

Dim bytes() as Byte
bytes = StrConv("Xmas", vbFromUnicode)

which will give you {88,109,97,115} but in that case you cannot assign the byte array back to a string.
You can convert the numbers in the byte array back to characters using the Chr() function

How can I align the columns of tables in Bash?

Use column command:

column -t -s' ' filename

Changing ViewPager to enable infinite page scrolling

Its hacked by CustomPagerAdapter:

MainActivity.java:

import android.content.Context;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private List<String> numberList = new ArrayList<String>();
    private CustomPagerAdapter mCustomPagerAdapter;
    private ViewPager mViewPager;
    private Handler handler;
    private Runnable runnable;

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

        numberList.clear();
        for (int i = 0; i < 10; i++) {
        numberList.add(""+i);
        }

        mViewPager = (ViewPager)findViewById(R.id.pager);
        mCustomPagerAdapter = new CustomPagerAdapter(MainActivity.this);
        EndlessPagerAdapter mAdapater = new EndlessPagerAdapter(mCustomPagerAdapter);
        mViewPager.setAdapter(mAdapater);


        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                int modulo = position%numberList.size();
                Log.i("Current ViewPager View's Position", ""+modulo);

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        handler = new Handler();
        runnable = new Runnable() {
            @Override
            public void run() {

                mViewPager.setCurrentItem(mViewPager.getCurrentItem()+1);
                handler.postDelayed(runnable, 1000);
            }
        };

        handler.post(runnable);

    }

    @Override
    protected void onDestroy() {
        if(handler!=null){
            handler.removeCallbacks(runnable);
        }
        super.onDestroy();
    }

    private class CustomPagerAdapter extends PagerAdapter {

        Context mContext;
        LayoutInflater mLayoutInflater;

        public CustomPagerAdapter(Context context) {
            mContext = context;
            mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return numberList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == ((LinearLayout) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View itemView = mLayoutInflater.inflate(R.layout.row_item_viewpager, container, false);

            TextView textView = (TextView) itemView.findViewById(R.id.txtItem);
            textView.setText(numberList.get(position));
            container.addView(itemView);
            return itemView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((LinearLayout) object);
        }
    }

    private class EndlessPagerAdapter extends PagerAdapter {

        private static final String TAG = "EndlessPagerAdapter";
        private static final boolean DEBUG = false;

        private final PagerAdapter mPagerAdapter;

        EndlessPagerAdapter(PagerAdapter pagerAdapter) {
            if (pagerAdapter == null) {
                throw new IllegalArgumentException("Did you forget initialize PagerAdapter?");
            }
            if ((pagerAdapter instanceof FragmentPagerAdapter || pagerAdapter instanceof FragmentStatePagerAdapter) && pagerAdapter.getCount() < 3) {
                throw new IllegalArgumentException("When you use FragmentPagerAdapter or FragmentStatePagerAdapter, it only supports >= 3 pages.");
            }
            mPagerAdapter = pagerAdapter;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            if (DEBUG) Log.d(TAG, "Destroy: " + getVirtualPosition(position));
            mPagerAdapter.destroyItem(container, getVirtualPosition(position), object);

            if (mPagerAdapter.getCount() < 4) {
                mPagerAdapter.instantiateItem(container, getVirtualPosition(position));
            }
        }

        @Override
        public void finishUpdate(ViewGroup container) {
            mPagerAdapter.finishUpdate(container);
        }

        @Override
        public int getCount() {
            return Integer.MAX_VALUE; // this is the magic that we can scroll infinitely.
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mPagerAdapter.getPageTitle(getVirtualPosition(position));
        }

        @Override
        public float getPageWidth(int position) {
            return mPagerAdapter.getPageWidth(getVirtualPosition(position));
        }

        @Override
        public boolean isViewFromObject(View view, Object o) {
            return mPagerAdapter.isViewFromObject(view, o);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            if (DEBUG) Log.d(TAG, "Instantiate: " + getVirtualPosition(position));
            return mPagerAdapter.instantiateItem(container, getVirtualPosition(position));
        }

        @Override
        public Parcelable saveState() {
            return mPagerAdapter.saveState();
        }

        @Override
        public void restoreState(Parcelable state, ClassLoader loader) {
            mPagerAdapter.restoreState(state, loader);
        }

        @Override
        public void startUpdate(ViewGroup container) {
            mPagerAdapter.startUpdate(container);
        }

        int getVirtualPosition(int realPosition) {
            return realPosition % mPagerAdapter.getCount();
        }

        PagerAdapter getPagerAdapter() {
            return mPagerAdapter;
        }

    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="180dp">
    </android.support.v4.view.ViewPager>

</RelativeLayout>

row_item_viewpager.xml:

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/txtItem"
        android:textAppearance="@android:style/TextAppearance.Large"/>

</LinearLayout>

Done

C++ program converts fahrenheit to celsius

The answer has already been found although I would also like to share my answer:

int main(void)
{
using namespace std;

short tempC;
cout << "Please enter a Celsius value: ";
cin >> tempC;
double tempF = convert(tempC);
cout << tempC << " degrees Celsius is " << tempF << " degrees Fahrenheit." << endl;
cin.get();
cin.get();
return 0;

}

int convert(short nT)
{
return nT * 1.8 + 32;
}

This is a more proper way to do this; however, it is slightly more complex then what you were going for.

Set div height equal to screen size

try this

$(document).ready(function(){
    $('#content').height($(window).height());
});

how to realize countifs function (excel) in R

Given a dataset

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

you can subset rows

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

etc.

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

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

What are Unwind segues for and how do you use them?

Swift iOS:

Step 1: define this method into your MASTER controller view. in which you want to go back:

//pragma mark - Unwind Seques
@IBAction func goToSideMenu(segue: UIStoryboardSegue) {

    println("Called goToSideMenu: unwind action")

}

Step 2: (StoryBoard) Right click on you SLAVE/CHILD EXIT button and Select "goToSideMenu" As action to Connect you Button on which you will click to return back to you MASTER controller view:

enter image description here step 3: Build and Run ...

Hibernate JPA Sequence (non-Id)

Looks like thread is old, I just wanted to add my solution here(Using AspectJ - AOP in spring).

Solution is to create a custom annotation @InjectSequenceValue as follows.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface InjectSequenceValue {
    String sequencename();
}

Now you can annotate any field in entity, so that the underlying field (Long/Integer) value will be injected at runtime using the nextvalue of the sequence.

Annotate like this.

//serialNumber will be injected dynamically, with the next value of the serialnum_sequence.
 @InjectSequenceValue(sequencename = "serialnum_sequence") 
  Long serialNumber;

So far we have marked the field we need to inject the sequence value.So we will look how to inject the sequence value to the marked fields, this is done by creating the point cut in AspectJ.

We will trigger the injection just before the save/persist method is being executed.This is done in the below class.

@Aspect
@Configuration
public class AspectDefinition {

    @Autowired
    JdbcTemplate jdbcTemplate;


    //@Before("execution(* org.hibernate.session.save(..))") Use this for Hibernate.(also include session.save())
    @Before("execution(* org.springframework.data.repository.CrudRepository.save(..))") //This is for JPA.
    public void generateSequence(JoinPoint joinPoint){

        Object [] aragumentList=joinPoint.getArgs(); //Getting all arguments of the save
        for (Object arg :aragumentList ) {
            if (arg.getClass().isAnnotationPresent(Entity.class)){ // getting the Entity class

                Field[] fields = arg.getClass().getDeclaredFields();
                for (Field field : fields) {
                    if (field.isAnnotationPresent(InjectSequenceValue.class)) { //getting annotated fields

                        field.setAccessible(true); 
                        try {
                            if (field.get(arg) == null){ // Setting the next value
                                String sequenceName=field.getAnnotation(InjectSequenceValue.class).sequencename();
                                long nextval=getNextValue(sequenceName);
                                System.out.println("Next value :"+nextval); //TODO remove sout.
                                field.set(arg, nextval);
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

        }
    }

    /**
     * This method fetches the next value from sequence
     * @param sequence
     * @return
     */

    public long getNextValue(String sequence){
        long sequenceNextVal=0L;

        SqlRowSet sqlRowSet= jdbcTemplate.queryForRowSet("SELECT "+sequence+".NEXTVAL as value FROM DUAL");
        while (sqlRowSet.next()){
            sequenceNextVal=sqlRowSet.getLong("value");

        }
        return  sequenceNextVal;
    }
}

Now you can annotate any Entity as below.

@Entity
@Table(name = "T_USER")
public class UserEntity {

    @Id
    @SequenceGenerator(sequenceName = "userid_sequence",name = "this_seq")
    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "this_seq")
    Long id;
    String userName;
    String password;

    @InjectSequenceValue(sequencename = "serialnum_sequence") // this will be injected at the time of saving.
    Long serialNumber;

    String name;
}

How do I update pip itself from inside my virtual environment?

I had installed Python in C:\Python\Python36 so I went to the Windows command prompt and typed "cd C:\Python\Python36 to get to the right directory. Then entered the "python -m install --upgrade pip" all good!

Hive load CSV with commas in quoted fields

ORG.APACHE.HADOOP.HIVE.SERDE2.OPENCSVSERDE Serde worked for me. My delimiter was '|' and one of the columns is enclosed in double quotes.

Query:

CREATE EXTERNAL TABLE EMAIL(MESSAGE_ID STRING, TEXT STRING, TO_ADDRS STRING, FROM_ADDRS STRING, SUBJECT STRING, DATE STRING)
ROW FORMAT SERDE 'ORG.APACHE.HADOOP.HIVE.SERDE2.OPENCSVSERDE'
WITH SERDEPROPERTIES (
     "SEPARATORCHAR" = "|",
     "QUOTECHAR"     = "\"",
     "ESCAPECHAR"    = "\""
)    
STORED AS TEXTFILE location '/user/abc/csv_folder';

mysqli::mysqli(): (HY000/2002): Can't connect to local MySQL server through socket 'MySQL' (2)

Please check the following file

%SystemRoot%\system32\drivers\etc\host

The line which bind the host name with ip is probably missing a line which bind them togather

127.0.0.1  localhost

If the given line is missing. Add the line in the file


Could you also check your MySQL database's user table and tell us the host column value for the user which you are using. You should have user privilege for both the host "127.0.0.1" and "localhost" and use % as it is a wild char for generic host name.

Error while installing json gem 'mkmf.rb can't find header files for ruby'

On Mac 10.14, the header files don't seem to be installed in the correct place. Rather than changing paths like the other fixes, I was able to just run this:

open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

Follow the instructions and it resolved this problem for me.

Expected initializer before function name

You are missing a semicolon at the end of your 'struct' definition.

Also,

*sotrudnik

needs to be

sotrudnik*

WARNING: sanitizing unsafe style value url

Based on the docs at https://angular.io/api/platform-browser/DomSanitizer, the right way to do this seems to be to use sanitize. At least in Angular 7 (don't know if this changed from before). This worked for me:

import { Component, OnInit, Input, SecurityContext } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

constructor(
    private sanitizer: DomSanitizer
) { }

this.sanitizer.sanitize(SecurityContext.STYLE, 'url(' + this.image + ')');

Re SecurityContext, see https://angular.io/api/core/SecurityContext. Basically it's just this enum:

enum SecurityContext {
  NONE: 0
  HTML: 1
  STYLE: 2
  SCRIPT: 3
  URL: 4
  RESOURCE_URL: 5
}

Installing a plain plugin jar in Eclipse 3.5

This is how you can go about it:

  1. Close Eclipse
  2. Download a jar plugin (let's assume its testNG.jar)
  3. Copy testNG.jar to a certain folder (say C:\Project\resources\plugins)
  4. In your Eclipse installation folder, there is a folder named dropins (could be C:\eclipse\dropins), create a .link file in that folder, (like plugins.link)
  5. Open this file with any text editor and enter this one line:
    path=C:/Project/resources/plugins
  6. Save the file and start Eclipse.

And you are good to go!

Please do not forget to change your backward slashes in your plugins folder path to forward slashes on step 5. I used to forget and it would take my time unnecessarily.

Restore the mysql database from .frm files

Copy all file and replace to /var/lib/mysql , after that you must change owner of files to mysql this is so important if mariadb.service restart has been faild

chown -R mysql:mysql /var/lib/mysql/*

and

chmod -R 700 /var/lib/mysql/*

Pandas: Subtracting two date columns and the result being an integer

How about:

df_test['Difference'] = (df_test['First_Date'] - df_test['Second Date']).dt.days

This will return difference as int if there are no missing values(NaT) and float if there is.

Safest way to convert float to integer in python?

math.floor will always return an integer number and thus int(math.floor(some_float)) will never introduce rounding errors.

The rounding error might already be introduced in math.floor(some_large_float), though, or even when storing a large number in a float in the first place. (Large numbers may lose precision when stored in floats.)

Combining "LIKE" and "IN" for SQL Server

Effectively, the IN statement creates a series of OR statements... so

SELECT * FROM table WHERE column IN (1, 2, 3)

Is effectively

SELECT * FROM table WHERE column = 1 OR column = 2 OR column = 3

And sadly, that is the route you'll have to take with your LIKE statements

SELECT * FROM table
WHERE column LIKE 'Text%' OR column LIKE 'Hello%' OR column LIKE 'That%'

warning: incompatible implicit declaration of built-in function ‘xyz’

In the case of some programs, these errors are normal and should not be fixed.

I get these error messages when compiling the program phrap (for example). This program happens to contain code that modifies or replaces some built in functions, and when I include the appropriate header files to fix the warnings, GCC instead generates a bunch of errors. So fixing the warnings effectively breaks the build.

If you got the source as part of a distribution that should compile normally, the errors might be normal. Consult the documentation to be sure.

PHP function to build query string from array

Implode will combine an array into a string for you, but to make an SQL query out a kay/value pair you'll have to write your own function.

difference between primary key and unique key

A primary key has the semantic of identifying the row of a database. Therefore there can be only one primary key for a given table, while there can be many unique keys.

Also for the same reason a primary key cannot be NULL (at least in Oracle, not sure about other databases)

Since it identifies the row it should never ever change. Changing primary keys are bound to cause serious pain and probably eternal damnation.

Therefor in most cases you want some artificial id for primary key which isn't used for anything but identifying single rows in the table.

Unique keys on the other hand may change as much as you want.

How do I plot list of tuples in Python?

As others have answered, scatter() or plot() will generate the plot you want. I suggest two refinements to answers that are already here:

  1. Use numpy to create the x-coordinate list and y-coordinate list. Working with large data sets is faster in numpy than using the iteration in Python suggested in other answers.

  2. Use pyplot to apply the logarithmic scale rather than operating directly on the data, unless you actually want to have the logs.

    import matplotlib.pyplot as plt
    import numpy as np
    
    data = [(2, 10), (3, 100), (4, 1000), (5, 100000)]
    data_in_array = np.array(data)
    '''
    That looks like array([[     2,     10],
                           [     3,    100],
                           [     4,   1000],
                           [     5, 100000]])
    '''
    
    transposed = data_in_array.T
    '''
    That looks like array([[     2,      3,      4,      5],
                           [    10,    100,   1000, 100000]])
    '''    
    
    x, y = transposed 
    
    # Here is the OO method
    # You could also the state-based methods of pyplot
    fig, ax = plt.subplots(1,1) # gets a handle for the AxesSubplot object
    ax.plot(x, y, 'ro')
    ax.plot(x, y, 'b-')
    ax.set_yscale('log')
    fig.show()
    

result

I've also used ax.set_xlim(1, 6) and ax.set_ylim(.1, 1e6) to make it pretty.

I've used the object-oriented interface to matplotlib. Because it offers greater flexibility and explicit clarity by using names of the objects created, the OO interface is preferred over the interactive state-based interface.

Convert array to string in NodeJS

You can also cast an array to a string like...

newStr = String(aa);

I also agree with Tor Valamo's answer, console.log should have no problem with arrays, no need to convert to a string unless you're debugging something or just curious.

How to set width of mat-table column in angular?

using css we can adjust specific column width which i put in below code.

user.component.css

table{
 width: 100%;
}

.mat-column-username {
  word-wrap: break-word !important;
  white-space: unset !important;
  flex: 0 0 28% !important;
  width: 28% !important;
  overflow-wrap: break-word;
  word-wrap: break-word;

  word-break: break-word;

  -ms-hyphens: auto;
  -moz-hyphens: auto;
  -webkit-hyphens: auto;
  hyphens: auto;
}

.mat-column-emailid {
  word-wrap: break-word !important;
  white-space: unset !important;
  flex: 0 0 25% !important;
  width: 25% !important;
  overflow-wrap: break-word;
  word-wrap: break-word;

  word-break: break-word;

  -ms-hyphens: auto;
  -moz-hyphens: auto;
  -webkit-hyphens: auto;
  hyphens: auto;
}

.mat-column-contactno {
  word-wrap: break-word !important;
  white-space: unset !important;
  flex: 0 0 17% !important;
  width: 17% !important;
  overflow-wrap: break-word;
  word-wrap: break-word;

  word-break: break-word;

  -ms-hyphens: auto;
  -moz-hyphens: auto;
  -webkit-hyphens: auto;
  hyphens: auto;
}

.mat-column-userimage {
  word-wrap: break-word !important;
  white-space: unset !important;
  flex: 0 0 8% !important;
  width: 8% !important;
  overflow-wrap: break-word;
  word-wrap: break-word;

  word-break: break-word;

  -ms-hyphens: auto;
  -moz-hyphens: auto;
  -webkit-hyphens: auto;
  hyphens: auto;
}

.mat-column-userActivity {
  word-wrap: break-word !important;
  white-space: unset !important;
  flex: 0 0 10% !important;
  width: 10% !important;
  overflow-wrap: break-word;
  word-wrap: break-word;

  word-break: break-word;

  -ms-hyphens: auto;
  -moz-hyphens: auto;
  -webkit-hyphens: auto;
  hyphens: auto;
}

How to remove rows with any zero value

Using tidyverse/dplyr, you can also remove rows with any zero value in a subset of variables:

# variables starting with Mac must be non-zero
filter_at(df, vars(starts_with("Mac")), all_vars((.) != 0))

# variables x, y, and z must be non-zero
filter_at(df, vars(x, y, z), all_vars((.) != 0))

# all numeric variables must be non-zero
filter_if(df, is.numeric, all_vars((.) != 0))

Using Intent in an Android application to show another activity

Add this line to your AndroidManifest.xml:

<activity android:name=".OrderScreen" /> 

Get all mysql selected rows into an array

I would suggest the use of MySQLi or MySQL PDO for performance and security purposes, but to answer the question:

while($row = mysql_fetch_assoc($result)){
     $json[] = $row;
}

echo json_encode($json);

If you switched to MySQLi you could do:

$query = "SELECT * FROM table";
$result = mysqli_query($db, $query);

$json = mysqli_fetch_all ($result, MYSQLI_ASSOC);
echo json_encode($json );

No connection could be made because the target machine actively refused it 127.0.0.1

If you have this while Fiddler is running -> in Fiddler, go to 'Rules' and disable 'Automatically Authenticate' and it should work again.

Using an if statement to check if a div is empty

If you want a quick demo how you check for empty divs I'd suggest you to try this link:

http://html-tuts.com/check-if-html-element-is-empty-or-has-children-tags/


Below you have some short examples:

Using CSS

If your div is empty without anything even no white-space, you can use CSS:

.someDiv:empty {
    display: none;
}

Unfortunately there is no CSS selector that selects the previous sibling element. There is only for the next sibling element: x ~ y

.someDiv:empty ~ .anotherDiv {
    display: none;
}

Using jQuery

Checking text length of element with text() function

if ( $('#leftmenu').text().length == 0 ) {
    // length of text is 0
}

Check if element has any children tags inside

if ( $('#leftmenu').children().length == 0 ) {
    // div has no other tags inside it
}

Check for empty elements if they have white-space

if ( $.trim( $('.someDiv').text() ).length == 0 ) {
    // white-space trimmed, div is empty
}

CSS3 100vh not constant in mobile browser

You can do this by adding following script and style

  function appHeight() {
    const doc = document.documentElement
    doc.style.setProperty('--vh', (window.innerHeight*.01) + 'px');
  }

  window.addEventListener('resize', appHeight);
  appHeight();

Style

.module {
  height: 100vh; /* Fallback for browsers that do not support Custom Properties */
  height: calc(var(--vh, 1vh) * 100);
}

What is Common Gateway Interface (CGI)?

The idea behind CGI is that a program/script (whether Perl or even C) receives input via STDIN (the request data) and outputs data via STDOUT (echo, printf statements).

The reason most PHP scripts don't qualify is that they are run under the PHP Apache module.

Returning binary file from controller in ASP.NET Web API

While the suggested solution works fine, there is another way to return a byte array from the controller, with response stream properly formatted :

  • In the request, set header "Accept: application/octet-stream".
  • Server-side, add a media type formatter to support this mime type.

Unfortunately, WebApi does not include any formatter for "application/octet-stream". There is an implementation here on GitHub: BinaryMediaTypeFormatter (there are minor adaptations to make it work for webapi 2, method signatures changed).

You can add this formatter into your global config :

HttpConfiguration config;
// ...
config.Formatters.Add(new BinaryMediaTypeFormatter(false));

WebApi should now use BinaryMediaTypeFormatter if the request specifies the correct Accept header.

I prefer this solution because an action controller returning byte[] is more comfortable to test. Though, the other solution allows you more control if you want to return another content-type than "application/octet-stream" (for example "image/gif").

Convert INT to VARCHAR SQL

SELECT cast(CAST([field_name] AS bigint) as nvarchar(255)) FROM table_name

Display Parameter(Multi-value) in Report

You can use the "Join" function to create a single string out of the array of labels, like this:

=Join(Parameters!Product.Label, ",")

Throw HttpResponseException or return Request.CreateErrorResponse?

Another case for when to use HttpResponseException instead of Response.CreateResponse(HttpStatusCode.NotFound), or other error status code, is if you have transactions in action filters and you want the transactions to be rolled back when returning an error response to the client.

Using Response.CreateResponse will not roll the transaction back, whereas throwing an exception will.

Maven: how to override the dependency added by a library

Simply specify the version in your current pom. The version specified here will override other.

Forcing a version
A version will always be honoured if it is declared in the current POM with a particular version - however, it should be noted that this will also affect other poms downstream if it is itself depended on using transitive dependencies.


Resources :

Encrypting & Decrypting a String in C#

Try this class:

public class DataEncryptor
{
    TripleDESCryptoServiceProvider symm;

    #region Factory
    public DataEncryptor()
    {
        this.symm = new TripleDESCryptoServiceProvider();
        this.symm.Padding = PaddingMode.PKCS7;
    }
    public DataEncryptor(TripleDESCryptoServiceProvider keys)
    {
        this.symm = keys;
    }

    public DataEncryptor(byte[] key, byte[] iv)
    {
        this.symm = new TripleDESCryptoServiceProvider();
        this.symm.Padding = PaddingMode.PKCS7;
        this.symm.Key = key;
        this.symm.IV = iv;
    }

    #endregion

    #region Properties
    public TripleDESCryptoServiceProvider Algorithm
    {
        get { return symm; }
        set { symm = value; }
    }
    public byte[] Key
    {
        get { return symm.Key; }
        set { symm.Key = value; }
    }
    public byte[] IV
    {
        get { return symm.IV; }
        set { symm.IV = value; }
    }

    #endregion

    #region Crypto

    public byte[] Encrypt(byte[] data) { return Encrypt(data, data.Length); }
    public byte[] Encrypt(byte[] data, int length)
    {
        try
        {
            // Create a MemoryStream.
            var ms = new MemoryStream();

            // Create a CryptoStream using the MemoryStream 
            // and the passed key and initialization vector (IV).
            var cs = new CryptoStream(ms,
                symm.CreateEncryptor(symm.Key, symm.IV),
                CryptoStreamMode.Write);

            // Write the byte array to the crypto stream and flush it.
            cs.Write(data, 0, length);
            cs.FlushFinalBlock();

            // Get an array of bytes from the 
            // MemoryStream that holds the 
            // encrypted data.
            byte[] ret = ms.ToArray();

            // Close the streams.
            cs.Close();
            ms.Close();

            // Return the encrypted buffer.
            return ret;
        }
        catch (CryptographicException ex)
        {
            Console.WriteLine("A cryptographic error occured: {0}", ex.Message);
        }
        return null;
    }

    public string EncryptString(string text)
    {
        return Convert.ToBase64String(Encrypt(Encoding.UTF8.GetBytes(text)));
    }

    public byte[] Decrypt(byte[] data) { return Decrypt(data, data.Length); }
    public byte[] Decrypt(byte[] data, int length)
    {
        try
        {
            // Create a new MemoryStream using the passed 
            // array of encrypted data.
            MemoryStream ms = new MemoryStream(data);

            // Create a CryptoStream using the MemoryStream 
            // and the passed key and initialization vector (IV).
            CryptoStream cs = new CryptoStream(ms,
                symm.CreateDecryptor(symm.Key, symm.IV),
                CryptoStreamMode.Read);

            // Create buffer to hold the decrypted data.
            byte[] result = new byte[length];

            // Read the decrypted data out of the crypto stream
            // and place it into the temporary buffer.
            cs.Read(result, 0, result.Length);
            return result;
        }
        catch (CryptographicException ex)
        {
            Console.WriteLine("A cryptographic error occured: {0}", ex.Message);
        }
        return null;
    }

    public string DecryptString(string data)
    {
        return Encoding.UTF8.GetString(Decrypt(Convert.FromBase64String(data))).TrimEnd('\0');
    }

    #endregion

}

and use it like this:

string message="A very secret message here.";
DataEncryptor keys=new DataEncryptor();
string encr=keys.EncryptString(message);

// later
string actual=keys.DecryptString(encr);

Internet Explorer cache location

If you are using Dot.Net then the code you need is

Environment.GetFolderPath(Environment.SpecialFolder.InternetCache)

Click my name if you want the code to delete these files plus FireFox temp files and Flash shared object/Flash Cookies

Keep CMD open after BAT file executes

In Windows add '& Pause' to the end of your command in the file.

Good tool to visualise database schema?

I found SchemaSpy quite good - you have to run the script every time schema changes but it is not so big deal.

As pointed out in the comments there is also a GUI for it.

Another nice tool is SchemaCrawler.

Turn a single number into single digits Python

This can be done quite easily if you:

  1. Use str to convert the number into a string so that you can iterate over it.

  2. Use a list comprehension to split the string into individual digits.

  3. Use int to convert the digits back into integers.

Below is a demonstration:

>>> n = 43365644
>>> [int(d) for d in str(n)]
[4, 3, 3, 6, 5, 6, 4, 4]
>>>

How to Maximize window in chrome using webDriver (python)

I do the following:

from selenium import webdriver
browser = webdriver.Chrome('C:\chromedriver.exe')
browser.maximize_window()

'Invalid update: invalid number of rows in section 0

Here is some code from above added with actual action code (point 1 and 2);

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { _, _, completionHandler in

        // 1. remove object from your array
        scannedItems.remove(at: indexPath.row)
        // 2. reload the table, otherwise you get an index out of bounds crash
        self.tableView.reloadData()

        completionHandler(true)
    }
    deleteAction.backgroundColor = .systemOrange
    let configuration = UISwipeActionsConfiguration(actions: [deleteAction])
    configuration.performsFirstActionWithFullSwipe = true
    return configuration
}

Does svn have a `revert-all` command?

There is a command

svn revert -R .

OR
you can use the --depth=infinity, which is actually same as above:

svn revert --depth=infinity 

svn revert is inherently dangerous, since its entire purpose is to throw away data—namely, your uncommitted changes. Once you've reverted, Subversion provides no way to get back those uncommitted changes

Invalid character in identifier

If your keyboard is set to English US (International) rather than English US the double quotation marks don't work. This is why the single quotation marks worked in your case.

Why doesn't git recognize that my file has been changed, therefore git add not working

Had a funky thing like this happening. Eclipse Kepler's git plugin was automatically marking all my project folders as ignored in the .gitignore folder.

When I would got to commit on the Team menu, they would all set back to ignored. As far as I can tell, this was because I'd set them as derived in the parent project. Unmarking them as dervied fixed this. I'd never seen this before on Indigo. Hope it helps someon.

Parse an URL in JavaScript

I wrote a javascript url parsing library, URL.js, you can use it for this.

Example:

url.parse("http://mysite.com/form_image_edit.php?img_id=33").get.img_id === "33"

Better way to generate array of all letters in the alphabet

Finally you are getting a char array with alphabet. Why did you do so hard way using a loop ?

It is just

char[] alphabet=new char[]{'a','b',.........,'z'}

Filtering JSON array using jQuery grep()

var data = {
    "items": [{
        "id": 1,
        "category": "cat1"
    }, {
        "id": 2,
        "category": "cat2"
    }, {
        "id": 3,
        "category": "cat1"
    }]
};

var returnedData = $.grep(data.items, function (element, index) {
    return element.id == 1;
});


alert(returnedData[0].id + "  " + returnedData[0].category);

The returnedData is returning an array of objects, so you can access it by array index.

http://jsfiddle.net/wyfr8/913/

What is define([ , function ]) in JavaScript?

define() is part of the AMD spec of js

See:

Edit: Also see Claudio's answer below. Likely the more relevant explanation.

Import pfx file into particular certificate store from command line

In newer version of windows the Certuil has [CertificateStoreName] where we can give the store name. In earlier version windows this was not possible.

Installing *.pfx certificate: certutil -f -p "" -enterprise -importpfx root ""

Installing *.cer certificate: certutil -addstore -enterprise -f -v root ""

For more details below command can be executed in windows cmd. C:>certutil -importpfx -? Usage: CertUtil [Options] -importPFX [CertificateStoreName] PFXFile [Modifiers]

Java String.split() Regex

Can you invert your regex so split by the non operation characters?

String ops[] = string.split("[a-z]")
// ops == [+, -, *, /, <, >, >=, <=, == ]   

This obviously doesn't return the variables in the array. Maybe you can interleave two splits (one by the operators, one by the variables)

System.out.println() shortcut on Intellij IDEA

On MAC you can do sout + return or ?+j (cmd+j) opens live template suggestions, enter sout to choose System.out.println();

CSS: background-color only inside the margin

I needed something similar, and came up with using the :before (or :after) pseudoclasses:

#mydiv {
   background-color: #fbb;
   margin-top: 100px;
   position: relative;
}
#mydiv:before {
   content: "";
   background-color: #bfb;
   top: -100px;
   height: 100px;
   width: 100%;
   position: absolute;
}

JSFiddle

How to generate a create table script for an existing table in phpmyadmin?

Use the following query in sql tab:

SHOW CREATE TABLE your_table_name

Press GO button

After show table, above the table ( +options ) Hyperlink.

Press +options Hyperlink then appear some options select (Full texts) press GO button.

Show sql quaery.

regular expression: match any word until first space

Derived from the answer of @SilentGhost I would use:

^([\S]+)

Check out this interactive regexr.com page to see the result and explanation for the suggested solution.

How to use a wildcard in the classpath to add multiple jars?

If you mean that you have an environment variable named CLASSPATH, I'd say that's your mistake. I don't have such a thing on any machine with which I develop Java. CLASSPATH is so tied to a particular project that it's impossible to have a single, correct CLASSPATH that works for all.

I set CLASSPATH for each project using either an IDE or Ant. I do a lot of web development, so each WAR and EAR uses their own CLASSPATH.

It's ignored by IDEs and app servers. Why do you have it? I'd recommend deleting it.

How do I convert a javascript object array to a string array of the object attribute I want?

You can use this function:

function createStringArray(arr, prop) {
   var result = [];
   for (var i = 0; i < arr.length; i += 1) {
      result.push(arr[i][prop]);
   }
   return result;
}

Just pass the array of objects and the property you need. The script above will work even in old EcmaScript implementations.

Reading JSON from a file?

Here is a copy of code which works fine for me

import json

with open("test.json") as json_file:
    json_data = json.load(json_file)
    print(json_data)

with the data

{
    "a": [1,3,"asdf",true],
    "b": {
        "Hello": "world"
    }
}

you may want to wrap your json.load line with a try catch because invalid JSON will cause a stacktrace error message.

error: package com.android.annotations does not exist

You can find here the official javadoc of the support-annotationslibrary.

Error:(3, 31) error: package com.android.annotations does not exist

As you can see all the classes are in the same package android.support.annotation and not com.android.annotations.

Error:(7, 2) error: cannot find symbol class NonNullByDefault

Also the class NonNullByDefault doesn't exist in that package.

Node.js + Nginx - What now?

Nginx works as a front end server, which in this case proxies the requests to a node.js server. Therefore you need to setup an nginx config file for node.

This is what I have done in my Ubuntu box:

Create the file yourdomain.com at /etc/nginx/sites-available/:

vim /etc/nginx/sites-available/yourdomain.com

In it you should have something like:

# the IP(s) on which your node server is running. I chose port 3000.
upstream app_yourdomain {
    server 127.0.0.1:3000;
    keepalive 8;
}

# the nginx server instance
server {
    listen 80;
    listen [::]:80;
    server_name yourdomain.com www.yourdomain.com;
    access_log /var/log/nginx/yourdomain.com.log;

    # pass the request to the node.js server with the correct headers
    # and much more can be added, see nginx config options
    location / {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_set_header X-NginX-Proxy true;

      proxy_pass http://app_yourdomain/;
      proxy_redirect off;
    }
 }

If you want nginx (>= 1.3.13) to handle websocket requests as well, add the following lines in the location / section:

proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";

Once you have this setup you must enable the site defined in the config file above:

cd /etc/nginx/sites-enabled/ 
ln -s /etc/nginx/sites-available/yourdomain.com yourdomain.com

Create your node server app at /var/www/yourdomain/app.js and run it at localhost:3000

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');

Test for syntax mistakes:

nginx -t

Restart nginx:

sudo /etc/init.d/nginx restart

Lastly start the node server:

cd /var/www/yourdomain/ && node app.js

Now you should see "Hello World" at yourdomain.com

One last note with regards to starting the node server: you should use some kind of monitoring system for the node daemon. There is an awesome tutorial on node with upstart and monit.

Passing parameters on button action:@selector

tl;dr: Use Blocks

For Obj-C, for example, there's a CocoaPod SHControlBlocks, whose usage would be:

[self.btnFirst SH_addControlEvents:UIControlEventTouchDown withBlock:^(UIControl *sender) {
    [weakSelf performSegueWithIdentifier:@"second" sender:nil];
    NSLog(@"first");
  }];

For Swift, I love the pod Actions, which allows blocks for UIControls [1]:

// UIControl
let button = UIButton()
button.add(event: .touchUpInside) {
    print("Button tapped")
    playMusic(from: speakers_mp4, withSongAtPosition: indexPath.row)
}

Not that anyone is reading a 3-year old thread. ::crickets::

[1] And UIView, UITextField, UIGestureRecognizer, UIBarButtonItem, Timer (formally NSTimer), and NotificationCenter (formally NSNotificationCenter).

Location of the mongodb database on mac

I had the same problem, with version 3.4.2

to run it (if you installed it with homebrew) run the process like this:

$ mongod --dbpath /usr/local/var/mongodb

jquery - check length of input field?

That doesn't work because, judging by the rest of the code, the initial value of the text input is "Default text" - which is more than one character, and so your if condition is always true.

The simplest way to make it work, it seems to me, is to account for this case:

    var value = $(this).val();
    if ( value.length > 0 && value != "Default text" ) ...

How, in general, does Node.js handle 10,000 concurrent requests?

If you have to ask this question then you're probably unfamiliar with what most web applications/services do. You're probably thinking that all software do this:

user do an action
       ¦
       v
 application start processing action
   +--> loop ...
          +--> busy processing
 end loop
   +--> send result to user

However, this is not how web applications, or indeed any application with a database as the back-end, work. Web apps do this:

user do an action
       ¦
       v
 application start processing action
   +--> make database request
          +--> do nothing until request completes
 request complete
   +--> send result to user

In this scenario, the software spend most of its running time using 0% CPU time waiting for the database to return.

Multithreaded network app:

Multithreaded network apps handle the above workload like this:

request --> spawn thread
              +--> wait for database request
                     +--> answer request
request --> spawn thread
              +--> wait for database request
                     +--> answer request
request --> spawn thread
              +--> wait for database request
                     +--> answer request

So the thread spend most of their time using 0% CPU waiting for the database to return data. While doing so they have had to allocate the memory required for a thread which includes a completely separate program stack for each thread etc. Also, they would have to start a thread which while is not as expensive as starting a full process is still not exactly cheap.

Singlethreaded event loop

Since we spend most of our time using 0% CPU, why not run some code when we're not using CPU? That way, each request will still get the same amount of CPU time as multithreaded applications but we don't need to start a thread. So we do this:

request --> make database request
request --> make database request
request --> make database request
database request complete --> send response
database request complete --> send response
database request complete --> send response

In practice both approaches return data with roughly the same latency since it's the database response time that dominates the processing.

The main advantage here is that we don't need to spawn a new thread so we don't need to do lots and lots of malloc which would slow us down.

Magic, invisible threading

The seemingly mysterious thing is how both the approaches above manage to run workload in "parallel"? The answer is that the database is threaded. So our single-threaded app is actually leveraging the multi-threaded behaviour of another process: the database.

Where singlethreaded approach fails

A singlethreaded app fails big if you need to do lots of CPU calculations before returning the data. Now, I don't mean a for loop processing the database result. That's still mostly O(n). What I mean is things like doing Fourier transform (mp3 encoding for example), ray tracing (3D rendering) etc.

Another pitfall of singlethreaded apps is that it will only utilise a single CPU core. So if you have a quad-core server (not uncommon nowdays) you're not using the other 3 cores.

Where multithreaded approach fails

A multithreaded app fails big if you need to allocate lots of RAM per thread. First, the RAM usage itself means you can't handle as many requests as a singlethreaded app. Worse, malloc is slow. Allocating lots and lots of objects (which is common for modern web frameworks) means we can potentially end up being slower than singlethreaded apps. This is where node.js usually win.

One use-case that end up making multithreaded worse is when you need to run another scripting language in your thread. First you usually need to malloc the entire runtime for that language, then you need to malloc the variables used by your script.

So if you're writing network apps in C or go or java then the overhead of threading will usually not be too bad. If you're writing a C web server to serve PHP or Ruby then it's very easy to write a faster server in javascript or Ruby or Python.

Hybrid approach

Some web servers use a hybrid approach. Nginx and Apache2 for example implement their network processing code as a thread pool of event loops. Each thread runs an event loop simultaneously processing requests single-threaded but requests are load-balanced among multiple threads.

Some single-threaded architectures also use a hybrid approach. Instead of launching multiple threads from a single process you can launch multiple applications - for example, 4 node.js servers on a quad-core machine. Then you use a load balancer to spread the workload amongst the processes.

In effect the two approaches are technically identical mirror-images of each other.

JavaFX open new window

If you just want a button to open up a new window, then something like this works:

btnOpenNewWindow.setOnAction(new EventHandler<ActionEvent>() {
    public void handle(ActionEvent event) {
        Parent root;
        try {
            root = FXMLLoader.load(getClass().getClassLoader().getResource("path/to/other/view.fxml"), resources);
            Stage stage = new Stage();
            stage.setTitle("My New Stage Title");
            stage.setScene(new Scene(root, 450, 450));
            stage.show();
            // Hide this current window (if this is what you want)
            ((Node)(event.getSource())).getScene().getWindow().hide();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Converting bytes to megabytes

BTW: Hard drive manufacturers don't count as authorities on this one!

Oh, yes they do (and the definition they assume from the S.I. is the correct one). On a related issue, see this post on CodingHorror.

How can I create a correlation matrix in R?

There are other ways to achieve this here: (Plot correlation matrix into a graph), but I like your version with the correlations in the boxes. Is there a way to add the variable names to the x and y column instead of just those index numbers? For me, that would make this a perfect solution. Thanks!

edit: I was trying to comment on the post by [Marc in the box], but I clearly don't know what I'm doing. However, I did manage to answer this question for myself.

if d is the matrix (or the original data frame) and the column names are what you want, then the following works:

axis(1, 1:dim(d)[2], colnames(d), las=2)
axis(2, 1:dim(d)[2], colnames(d), las=2)

las=0 would flip the names back to their normal position, mine were long, so I used las=2 to make them perpendicular to the axis.

edit2: to suppress the image() function printing numbers on the grid (otherwise they overlap your variable labels), add xaxt='n', e.g.:

image(x=seq(dim(x)[2]), y=seq(dim(y)[2]), z=COR, col=rev(heat.colors(20)), xlab="x column", ylab="y column", xaxt='n')

Reorder bars in geom_bar ggplot2 by value

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here


Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

How to open an Excel file in C#?

you should open like this

        Excel.Application xlApp ;
        Excel.Workbook xlWorkBook ;
        Excel.Worksheet xlWorkSheet ;
        object misValue = System.Reflection.Missing.Value;

        xlApp = new Excel.ApplicationClass();
        xlWorkBook = xlApp.Workbooks.Open("csharp.net-informations.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

source : http://csharp.net-informations.com/excel/csharp-open-excel.htm

ruden

NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

i had the same error while working with hibernate, i had added below dependency in my pom.xml that solved the problem

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.10</version>
    </dependency>

reference https://mvnrepository.com/artifact/org.slf4j/slf4j-api

jQuery selectors on custom data attributes using HTML5

$("ul[data-group='Companies'] li[data-company='Microsoft']") //Get all elements with data-company="Microsoft" below "Companies"

$("ul[data-group='Companies'] li:not([data-company='Microsoft'])") //get all elements with data-company!="Microsoft" below "Companies"

Look in to jQuery Selectors :contains is a selector

here is info on the :contains selector

Using if(isset($_POST['submit'])) to not display echo when script is open is not working

You never named your submit button, so as far as the form is concerned it's just an action.

Either:

  1. Name the submit button (<input type="submit" name="submit" ... />)
  2. Test if (!empty($_POST)) instead to detect when data has been posted.

Remember that keys in the $_POST superglobal only appear for named input elements. So, unless the element has the name attribute, it won't come through to $_POST (or $_GET/$_REQUEST)

How can I get Maven to stop attempting to check for updates for artifacts from a certain group from maven-central-repo?

Something that is now available in maven as well is

mvn goal --no-snapshot-updates

or in short

mvn goal -nsu

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

One more important thing to note!!! In example above it's described how to use

$.ajax({
    type     : 'POST',
    dataType : 'json', 
    url      : 'another-remote-server',
    ...
});

JQuery 1.6 and lower has a bug with cross-domain XHR. According to Firebug no requests except OPTIONS were sent. No POST. At all.

Spent 5 hours testing/tuning my code. Adding a lot of headers on the remote server (script). Without any effect. But later, I've updated JQuery lib to 1.6.4, and everything works like a charm.

SQLAlchemy insert or update example

assuming certain column names...

INSERT one

newToner = Toner(toner_id = 1,
                    toner_color = 'blue',
                    toner_hex = '#0F85FF')

dbsession.add(newToner)   
dbsession.commit()

INSERT multiple

newToner1 = Toner(toner_id = 1,
                    toner_color = 'blue',
                    toner_hex = '#0F85FF')

newToner2 = Toner(toner_id = 2,
                    toner_color = 'red',
                    toner_hex = '#F01731')

dbsession.add_all([newToner1, newToner2])   
dbsession.commit()

UPDATE

q = dbsession.query(Toner)
q = q.filter(Toner.toner_id==1)
record = q.one()
record.toner_color = 'Azure Radiance'

dbsession.commit()

or using a fancy one-liner using MERGE

record = dbsession.merge(Toner( **kwargs))

List of lists into numpy array

Just use pandas

list(pd.DataFrame(listofstuff).melt().values)

this only works for a list of lists

if you have a list of list of lists you might want to try something along the lines of

lists(pd.DataFrame(listofstuff).melt().apply(pd.Series).melt().values)

Get a list of all the files in a directory (recursive)

This is what I came up with for a gradle build script:

task doLast {
    ext.FindFile = { list, curPath ->
        def files = file(curPath).listFiles().sort()

        files.each {  File file ->

            if (file.isFile()) {
                list << file
            }
            else {
                list << file  // If you want the directories in the list

                list = FindFile( list, file.path) 
            }
        }
        return list
    }

    def list = []
    def theFile = FindFile(list, "${project.projectDir}")

    list.each {
        println it.path
    }
}

How to search by key=>value in a multidimensional array in PHP

if (isset($array[$key]) && $array[$key] == $value)

A minor imporvement to the fast version.

What is the correct way to represent null XML elements?

You use xsi:nil when your schema semantics indicate that an element has a default value, and that the default value should be used if the element isn't present. I have to assume that there are smart people to whom the preceding sentence is not a self-evidently terrible idea, but it sounds like nine kinds of bad to me. Every XML format I've ever worked with represents null values by omitting the element. (Or attribute, and good luck marking an attribute with xsi:nil.)

Detect changes in the DOM

How about extending a jquery for this?

   (function () {
        var ev = new $.Event('remove'),
            orig = $.fn.remove;
        var evap = new $.Event('append'),
           origap = $.fn.append;
        $.fn.remove = function () {
            $(this).trigger(ev);
            return orig.apply(this, arguments);
        }
        $.fn.append = function () {
            $(this).trigger(evap);
            return origap.apply(this, arguments);
        }
    })();
    $(document).on('append', function (e) { /*write your logic here*/ });
    $(document).on('remove', function (e) { /*write your logic here*/ });

Jquery 1.9+ has built support for this(I have heard not tested).

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

Flyway is comparing the checksum of the SQL script with that of the previously run checksum. This exception typically occurs if you change a SQL script that has already been applied by Flyway, thus causing a checksum mismatch.

If this is development, you can drop your database and start the migrations from scratch.

If you're in production, never edit SQL scripts that have already been applied. Only create new SQL scripts going forward.

How to solve javax.net.ssl.SSLHandshakeException Error?

SSLHandshakeException can be resolved 2 ways.

  1. Incorporating SSL

    • Get the SSL (by asking the source system administrator, can also be downloaded by openssl command, or any browsers downloads the certificates)

    • Add the certificate into truststore (cacerts) located at JRE/lib/security

    • provide the truststore location in vm arguments as "-Djavax.net.ssl.trustStore="

  2. Ignoring SSL

    For this #2, please visit my other answer on another stackoverflow website: How to ingore SSL verification Ignore SSL Certificate Errors with Java

How to return JSon object

You only have one row to serialize. Try something like this :

List<results> resultRows = new List<results>

resultRows.Add(new results{id = 1, value="ABC", info="ABC"});
resultRows.Add(new results{id = 2, value="XYZ", info="XYZ"});

string json = JavaScriptSerializer.Serialize(new { results = resultRows});
  • Edit to match OP's original json output

** Edit 2 : sorry, but I missed that he was using JSON.NET. Using the JavaScriptSerializer the above code produces this result :

{"results":[{"id":1,"value":"ABC","info":"ABC"},{"id":2,"value":"XYZ","info":"XYZ"}]}

How to programmatically set the Image source

myImg.Source = new BitmapImage(new Uri(@"component/Images/down.png", UriKind.RelativeOrAbsolute)); 

Don't forget to set Build Action to "Content", and Copy to output directory to "Always".

Merge two (or more) lists into one, in C# .NET

Assuming you want a list containing all of the products for the specified category-Ids, you can treat your query as a projection followed by a flattening operation. There's a LINQ operator that does that: SelectMany.

// implicitly List<Product>
var products = new[] { CategoryId1, CategoryId2, CategoryId3 }
                     .SelectMany(id => GetAllProducts(id))
                     .ToList();

In C# 4, you can shorten the SelectMany to: .SelectMany(GetAllProducts)

If you already have lists representing the products for each Id, then what you need is a concatenation, as others point out.

Validating Phone Numbers Using Javascript

<html>
<title>Practice Session</title>
<body>           
<form name="RegForm" onsubmit="return validate()" method="post">  
<p>Name: <input type="text" name="Name"> </p><br>        
<p>Contact: <input type="text" name="Telephone"> </p><br>   
<p><input type="submit" value="send" name="Submit"></p>          
</form> 
</body>
<script> 
function validate()                                    
{ 
var name = document.forms["RegForm"]["Name"];                
var phone = document.forms["RegForm"]["Telephone"];  
if (name.value == "")                                  
{ 
window.alert("Please enter your name."); 
name.focus();
return false;
}
else if(isNaN(name.value) /*"%d[10]"*/)
{
alert("name confirmed");
}
else{ 
window.alert("please enter character"); 
}   
if (phone.value == "")                           
{ 
window.alert("Please enter your telephone number."); 
phone.focus();
return false; 
} 
else if(!isNaN(phone.value) /*phone.value == isNaN(phone.value)*/)
{
alert("number confirmed");
}
else{
window.alert("please enter numbers only");
}   
}
</script> 
</html>

Parsing JSON from URL

 import org.apache.commons.httpclient.util.URIUtil;
 import org.apache.commons.io.FileUtils;
 import groovy.json.JsonSlurper;
 import java.io.File;

    tmpDir = "/defineYourTmpDir"
    URL url = new URL("http://yourOwnURL.com/file.json");
    String path = tmpDir + "/tmpRemoteJson" + ".json";
    remoteJsonFile = new File(path);
    remoteJsonFile.deleteOnExit(); 
    FileUtils.copyURLToFile(url, remoteJsonFile);
    String fileTMPPath = remoteJsonFile.getPath();

    def inputTMPFile = new File(fileTMPPath);
    remoteParsedJson = new JsonSlurper().parseText(inputTMPFile.text);

Convert UTC to local time in Rails 3

If you're actually doing it just because you want to get the user's timezone then all you have to do is change your timezone in you config/applications.rb.

Like this:

Rails, by default, will save your time record in UTC even if you specify the current timezone.

config.time_zone = "Singapore"

So this is all you have to do and you're good to go.

Can't compare naive and aware datetime.now() <= challenge.datetime_end

Disable time zone. Use challenge.datetime_start.replace(tzinfo=None);

You can also use replace(tzinfo=None) for other datetime.

if challenge.datetime_start.replace(tzinfo=None) <= datetime.now().replace(tzinfo=None) <= challenge.datetime_end.replace(tzinfo=None):

What programming languages can one use to develop iPhone, iPod Touch and iPad (iOS) applications?

objective-c is the primary language used.

i believe there is a mono touch framework that can be used with c#

Adobe also is working in some tools, one is this iPhone Packager which can utilize actionscript code

Printing the correct number of decimal points with cout

With <iomanip>, you can use std::fixed and std::setprecision

Here is an example

#include <iostream>
#include <iomanip>

int main()
{
    double d = 122.345;

    std::cout << std::fixed;
    std::cout << std::setprecision(2);
    std::cout << d;
}

And you will get output

122.34

Oracle SQL convert date format from DD-Mon-YY to YYYYMM

As offer_date is an number, and is of lower accuracy than your real dates, this may work...
- Convert your real date to a string of format YYYYMM
- Conver that value to an INT
- Compare the result you your offer_date

SELECT
  *
FROM
  offers
WHERE
    offer_date = (SELECT CAST(to_char(create_date, 'YYYYMM') AS INT) FROM customers where id = '12345678')
AND offer_rate > 0 

Also, by doing all the manipulation on the create_date you only do the processing on one value.

Additionally, had you manipulated the offer_date you would not be able to utilise any index on that field, and so force SCANs instead of SEEKs.

Change Toolbar color in Appcompat 21

For people who are using AppCompatActivity with Toolbar as white background. Do use this code.

Updated: December, 2017

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:theme="@style/ThemeOverlay.AppCompat.Light">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar_edit"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:popupTheme="@style/AppTheme.AppBarOverlay"
        app:title="Edit Your Profile"/>

</android.support.design.widget.AppBarLayout>

Why does javascript map function return undefined?

You can implement like a below logic. Suppose you want an array of values.

let test = [ {name:'test',lastname:'kumar',age:30},
             {name:'test',lastname:'kumar',age:30},
             {name:'test3',lastname:'kumar',age:47},
             {name:'test',lastname:'kumar',age:28},
             {name:'test4',lastname:'kumar',age:30},
             {name:'test',lastname:'kumar',age:29}]

let result1 = test.map(element => 
              { 
                 if (element.age === 30) 
                 {
                    return element.lastname;
                 }
              }).filter(notUndefined => notUndefined !== undefined);

output : ['kumar','kumar','kumar']

Best way to compare two complex objects

Based off a few answers already given here I decided to mostly back JoelFan's answer. I love extension methods and these have been working great for me when none of the other solutions would using them to compare my complex classes.

Extension Methods

using System.IO;
using System.Xml.Serialization;

static class ObjectHelpers
{
    public static string SerializeObject<T>(this T toSerialize)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());

        using (StringWriter textWriter = new StringWriter())
        {
            xmlSerializer.Serialize(textWriter, toSerialize);
            return textWriter.ToString();
        }
    }

    public static bool EqualTo(this object obj, object toCompare)
    {
        if (obj.SerializeObject() == toCompare.SerializeObject())
            return true;
        else
            return false;
    }

    public static bool IsBlank<T>(this T obj) where T: new()
    {
        T blank = new T();
        T newObj = ((T)obj);

        if (newObj.SerializeObject() == blank.SerializeObject())
            return true;
        else
            return false;
    }

}

Usage Examples

if (record.IsBlank())
    throw new Exception("Record found is blank.");

if (record.EqualTo(new record()))
    throw new Exception("Record found is blank.");

How to get Android crash logs?

You can try this from the console:

adb logcat --buffer=crash 

More info on this option:

adb logcat --help

...

  -b <buffer>, --buffer=<buffer>         Request alternate ring buffer, 'main',
                  'system', 'radio', 'events', 'crash', 'default' or 'all'.
                  Multiple -b parameters or comma separated list of buffers are
                  allowed. Buffers interleaved. Default -b main,system,crash.

I can't access http://localhost/phpmyadmin/

What you need to do is to add phpmyadmin to the apache configuration:???????

sudo nano /etc/apache2/apache2.conf

Add the phpmyadmin config to the file:

Include /etc/phpmyadmin/apache.conf

Then restart apache:

sudo service apache2 restart

On ubuntu 18.0.1, I think you can just navigate to the apache2 config file and include the phpmyadmin config file as shown above, then restart apache

http://127.0.0.1/phpmyadmin/

Converting year and month ("yyyy-mm" format) to a date?

Try this. (Here we use text=Lines to keep the example self contained but in reality we would replace it with the file name.)

Lines <- "2009-01  12
2009-02  310
2009-03  2379
2009-04  234
2009-05  14
2009-08  1
2009-09  34
2009-10  2386"

library(zoo)
z <- read.zoo(text = Lines, FUN = as.yearmon)
plot(z)

The X axis is not so pretty with this data but if you have more data in reality it might be ok or you can use the code for a fancy X axis shown in the examples section of ?plot.zoo .

The zoo series, z, that is created above has a "yearmon" time index and looks like this:

> z
Jan 2009 Feb 2009 Mar 2009 Apr 2009 May 2009 Aug 2009 Sep 2009 Oct 2009 
      12      310     2379      234       14        1       34     2386 

"yearmon" can be used alone as well:

> as.yearmon("2000-03")
[1] "Mar 2000"

Note:

  1. "yearmon" class objects sort in calendar order.

  2. This will plot the monthly points at equally spaced intervals which is likely what is wanted; however, if it were desired to plot the points at unequally spaced intervals spaced in proportion to the number of days in each month then convert the index of z to "Date" class: time(z) <- as.Date(time(z)) .

How to delete specific rows and columns from a matrix in a smarter way?

> S = matrix(c(1,2,3,4,5,2,1,2,3,4,3,2,1,2,3,4,3,2,1,2,5,4,3,2,1),ncol = 5,byrow = TRUE);S
[,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    2    1    2    3    4
[3,]    3    2    1    2    3
[4,]    4    3    2    1    2
[5,]    5    4    3    2    1
> S<-S[,-2]
> S
[,1] [,2] [,3] [,4]
[1,]    1    3    4    5
[2,]    2    2    3    4
[3,]    3    1    2    3
[4,]    4    2    1    2
[5,]    5    3    2    1

Just use the command S <- S[,-2] to remove the second column. Similarly to delete a row, for example, to delete the second row use S <- S[-2,].

How to convert 2D float numpy array to 2D int numpy array?

Some numpy functions for how to control the rounding: rint, floor,trunc, ceil. depending how u wish to round the floats, up, down, or to the nearest int.

>>> x = np.array([[1.0,2.3],[1.3,2.9]])
>>> x
array([[ 1. ,  2.3],
       [ 1.3,  2.9]])
>>> y = np.trunc(x)
>>> y
array([[ 1.,  2.],
       [ 1.,  2.]])
>>> z = np.ceil(x)
>>> z
array([[ 1.,  3.],
       [ 2.,  3.]])
>>> t = np.floor(x)
>>> t
array([[ 1.,  2.],
       [ 1.,  2.]])
>>> a = np.rint(x)
>>> a
array([[ 1.,  2.],
       [ 1.,  3.]])

To make one of this in to int, or one of the other types in numpy, astype (as answered by BrenBern):

a.astype(int)
array([[1, 2],
       [1, 3]])

>>> y.astype(int)
array([[1, 2],
       [1, 2]])

Python NameError: name is not defined

You must define the class before creating an instance of the class. Move the invocation of Something to the end of the script.

You can try to put the cart before the horse and invoke procedures before they are defined, but it will be an ugly hack and you will have to roll your own as defined here:

Make function definition in a python file order independent

How to get text from EditText?

Put this in your MainActivity:

{
    public EditText bizname, storeno, rcpt, item, price, tax, total;
    public Button click, click2;
    int contentView;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.main_activity );
        bizname = (EditText) findViewById( R.id.editBizName );
        item = (EditText) findViewById( R.id.editItem );
        price = (EditText) findViewById( R.id.editPrice );
        tax = (EditText) findViewById( R.id.editTax );
        total = (EditText) findViewById( R.id.editTotal );
        click = (Button) findViewById( R.id.button );
    }
}

Put this under a button or something

public void clickBusiness(View view) {
    checkPermsOfStorage( this );

    bizname = (EditText) findViewById( R.id.editBizName );
    item = (EditText) findViewById( R.id.editItem );
    price = (EditText) findViewById( R.id.editPrice );
    tax = (EditText) findViewById( R.id.editTax );
    total = (EditText) findViewById( R.id.editTotal );
    String x = ("\nItem/Price: " + item.getText() + price.getText() + "\nTax/Total" + tax.getText() + total.getText());
    Toast.makeText( this, x, Toast.LENGTH_SHORT ).show();
    try {
        this.WriteBusiness(bizname,storeno,rcpt,item,price,tax,total);
        String vv = tax.getText().toString();
        System.console().printf( "%s", vv );
        //new XMLDivisionWriter(getString(R.string.SDDoc) + "/tax_div_business.xml");
    } catch (ReflectiveOperationException e) {
        e.printStackTrace();
    }
}

There! The debate is settled!

C++ - How to append a char to char*?

char ch = 't';
char chArray[2];
sprintf(chArray, "%c", ch);
char chOutput[10]="tes";
strcat(chOutput, chArray);
cout<<chOutput;

OUTPUT:

test

How do I get the current date in Cocoa

You need to do something along the lines of the following:

NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:now];
NSLog(@"%d", [components hour]);

And so on.

Can't access 127.0.0.1

If it's a DNS problem, you could try:

  • ipconfig /flushdns
  • ipconfig /registerdns

If this doesn't fix it, you could try editing the hosts file located here:

C:\Windows\System32\drivers\etc\hosts

And ensure that this line (and no other line referencing localhost) is in there:

127.0.0.1 localhost

How to import popper.js?

It turns out that Popper.js doesn't provide compiled files on its GitHub repository. Therefore, one has to compile the project on his/her own or download compiled files from CDNs. It cannot be automatically imported.

How to remove any URL within a string in Python

This worked for me:

import re
thestring = "text1\ntext2\nhttp://url.com/bla1/blah1/\ntext3\ntext4\nhttp://url.com/bla2/blah2/\ntext5\ntext6"

URLless_string = re.sub(r'\w+:\/{2}[\d\w-]+(\.[\d\w-]+)*(?:(?:\/[^\s/]*))*', '', thestring)
print URLless_string

Result:

text1
text2

text3
text4

text5
text6

Can I use jQuery with Node.js?

None of these solutions has helped me in my Electron App.

My solution (workaround):

npm install jquery

In your index.js file:

var jQuery = $ = require('jquery');

In your .js files write yours jQuery functions in this way:

jQuery(document).ready(function() {

mkdir -p functionality in Python

I think Asa's answer is essentially correct, but you could extend it a little to act more like mkdir -p, either:

import os

def mkdir_path(path):
    if not os.access(path, os.F_OK):
        os.mkdirs(path)

or

import os
import errno

def mkdir_path(path):
    try:
        os.mkdirs(path)
    except os.error, e:
        if e.errno != errno.EEXIST:
            raise

These both handle the case where the path already exists silently but let other errors bubble up.

Is it possible to import a whole directory in sass using @import?

You might want to retain source order then you can just use this.

@import
  'foo',
  'bar';

I prefer this.

Practical uses of git reset --soft?

A great reason to use 'git reset --soft <sha1>' is to move HEAD in a bare repo.

If you try to use the --mixed or --hard option, you'll get an error since you're trying to modify and working tree and/or index that does not exist.

Note: You will need to do this directly from the bare repo.

Note Again: You will need to make sure the branch you want to reset in the bare repo is the active branch. If not, follow VonC's answer on how to update the active branch in a bare repo when you have direct access to the repo.

Calling stored procedure from another stored procedure SQL Server

Simply call test2 from test1 like:

EXEC test2 @newId, @prod, @desc;

Make sure to get @id using SCOPE_IDENTITY(), which gets the last identity value inserted into an identity column in the same scope:

SELECT @newId = SCOPE_IDENTITY()

Use grep to report back only line numbers

try:

grep -n "text to find" file.ext | cut -f1 -d:

how to get session id of socket.io client in Client

Try this way.

                var socket = io.connect('http://...');
                console.log(socket.Socket.sessionid);

Why does an onclick property set with setAttribute fail to work in IE?

There is a LARGE collection of attributes you can't set in IE using .setAttribute() which includes every inline event handler.

See here for details:

http://webbugtrack.blogspot.com/2007/08/bug-242-setattribute-doesnt-always-work.html

Android - Best and safe way to stop thread

Currently and unfortunately we can't do anything to stop the thread....

Adding something to Matt's answer we can call interrupt() but that doesn't stop thread... Just tells the system to stop the thread when system wants to kill some threads. Rest is done by system, and we can check it by calling interrupted().

[p.s. : If you are really going with interrupt() I would ask you to do some experiments with a short sleep after calling interrupt()]

Changing the width of Bootstrap popover

To change width you can use css

For fixed size wanted

.popover{
    width:200px;
    height:250px;    
}

For max width wanted:

.popover{
    max-width:200px;
    height:250px;    
}

jsfiddle: http://jsfiddle.net/Rqx8T/2/

WAMP server, localhost is not working

The simplest solution is to disable the IIS service from the services snapin

(use the start menu -> search programs and files -> services.msc to launch the snapin )

This will stop IIS using port 80. Then change Apache back to using port 80.

Changing specific text's color using NSMutableAttributedString in Swift

Swift 4.1

NSAttributedStringKey.foregroundColor

for example if you want to change font in NavBar:

self.navigationController?.navigationBar.titleTextAttributes = [ NSAttributedStringKey.font: UIFont.systemFont(ofSize: 22), NSAttributedStringKey.foregroundColor: UIColor.white]

find: missing argument to -exec

A -exec command must be terminated with a ; (so you usually need to type \; or ';' to avoid interpretion by the shell) or a +. The difference is that with ;, the command is called once per file, with +, it is called just as few times as possible (usually once, but there is a maximum length for a command line, so it might be split up) with all filenames. See this example:

$ cat /tmp/echoargs
#!/bin/sh
echo $1 - $2 - $3
$ find /tmp/foo -exec /tmp/echoargs {} \;
/tmp/foo - -
/tmp/foo/one - -
/tmp/foo/two - -
$ find /tmp/foo -exec /tmp/echoargs {} +
/tmp/foo - /tmp/foo/one - /tmp/foo/two

Your command has two errors:

First, you use {};, but the ; must be a parameter of its own.

Second, the command ends at the &&. You specified “run find, and if that was successful, remove the file named {};.“. If you want to use shell stuff in the -exec command, you need to explicitly run it in a shell, such as -exec sh -c 'ffmpeg ... && rm'.

However you should not add the {} inside the bash command, it will produce problems when there are special characters. Instead, you can pass additional parameters to the shell after -c command_string (see man sh):

$ ls
$(echo damn.)
$ find * -exec sh -c 'echo "{}"' \;
damn.
$ find * -exec sh -c 'echo "$1"' - {} \;
$(echo damn.)

You see the $ thing is evaluated by the shell in the first example. Imagine there was a file called $(rm -rf /) :-)

(Side note: The - is not needed, but the first variable after the command is assigned to the variable $0, which is a special variable normally containing the name of the program being run and setting that to a parameter is a little unclean, though it won't cause any harm here probably, so we set that to just - and start with $1.)

So your command could be something like

find -exec bash -c 'ffmpeg -i "$1" -sameq "$1".mp3 && rm "$1".mp3' - {} \;

But there is a better way. find supports and and or, so you may do stuff like find -name foo -or -name bar. But that also works with -exec, which evaluates to true if the command exits successfully, and to false if not. See this example:

$ ls
false  true
$ find * -exec {} \; -and -print
true

It only runs the print if the command was successfully, which it did for true but not for false.

So you can use two exec statements chained with an -and, and it will only execute the latter if the former was run successfully.

Set order of columns in pandas dataframe

Try indexing (so you want a generic solution not only for this, so index order can be just what you want):

l=[0,2,1] # index order
frame=frame[[frame.columns[i] for i in l]]

Now:

print(frame)

Is:

   one thing second thing  other thing
0          1           0.1           a
1          2           0.2           e
2          3           1.0           i
3          4           2.0           o

C# Get a control's position on a form

You can use the controls PointToScreen method to get the absolute position with respect to the screen.

You can do the Forms PointToScreen method, and with basic math, get the control's position.

Get folder name from full file path

This can also be done like so;

var directoryName = System.IO.Path.GetFileName(@"c:\projects\roott\wsdlproj\devlop\beta2\text");

How to redirect from one URL to another URL?

Why javascript?

http://www.instant-web-site-tools.com/html-redirect.html

<html>
<meta http-equiv="REFRESH" content="0;url=http://www.URL2.com"> 
</html>

Unless I'm missunderstanding...

Why use #ifndef CLASS_H and #define CLASS_H in .h file but not in .cpp?

That's the distinction between declaration and definition. Header files typically include just the declaration, and the source file contains the definition.

In order to use something you only need to know it's declaration not it's definition. Only the linker needs to know the definition.

So this is why you will include a header file inside one or more source files but you won't include a source file inside another.

Also you mean #include and not import.

MySQL's now() +1 day

Try doing: INSERT INTO table(data, date) VALUES ('$data', now() + interval 1 day)

How to check if a String contains any letter from a to z?

You could use RegEx:

Regex.IsMatch(hello, @"^[a-zA-Z]+$");

If you don't like that, you can use LINQ:

hello.All(Char.IsLetter);

Or, you can loop through the characters, and use isAlpha:

Char.IsLetter(character);

Declaring a python function with an array parameters and passing an array argument to the function call?

What you have is on the right track.

def dosomething( thelist ):
    for element in thelist:
        print element

dosomething( ['1','2','3'] )
alist = ['red','green','blue']
dosomething( alist )  

Produces the output:

1
2
3
red
green
blue

A couple of things to note given your comment above: unlike in C-family languages, you often don't need to bother with tracking the index while iterating over a list, unless the index itself is important. If you really do need the index, though, you can use enumerate(list) to get index,element pairs, rather than doing the x in range(len(thelist)) dance.

how to get rid of notification circle in right side of the screen?

This stuff comes from ES file explorer

Just go into this app > settings

Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good

Parse query string in JavaScript

I wanted a simple function that took a URL as an input and returned a map of the query params. If I were to improve this function, I would support the standard for array data in the URL, and or nested variables.

This should work back and for with the jQuery.param( qparams ) function.

function getQueryParams(url){
    var qparams = {},
        parts = (url||'').split('?'),
        qparts, qpart,
        i=0;

    if(parts.length <= 1 ){
        return qparams;
    }else{
        qparts = parts[1].split('&');
        for(i in qparts){

            qpart = qparts[i].split('=');
            qparams[decodeURIComponent(qpart[0])] = 
                           decodeURIComponent(qpart[1] || '');
        }
    }

    return qparams;
};

How to run .NET Core console app from the command line

Go to ...\bin\Debug\net5.0 (net5.0 can also be something like "netcoreapp2.2" depending on the framework you use.)

enter image description here

Open the power shell by clicking on it like shown in the picture.

Type in powershell: .\yourApp.exe

You don't need dotnet publish just make sure you build it before to include all changes.

How do I pre-populate a jQuery Datepicker textbox with today's date?

$(function()
{
$('.date-pick').datePicker().val(new Date().asString()).trigger('change');
});

Source: http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/datePickerDefaultToday.html

How to set the Android progressbar's height?

From this tutorial:

<style name="CustomProgressBarHorizontal" parent="android:Widget.ProgressBar.Horizontal">
      <item name="android:progressDrawable">@drawable/custom_progress_bar_horizontal</item>
      <item name="android:minHeight">10dip</item>
      <item name="android:maxHeight">20dip</item>
</style>

Then simply apply the style to your progress bars or better, override the default style in your theme to style all of your app's progress bars automatically.

The difference you are seeing in the screenshots is because the phones/emulators are using a difference Android version (latest is the theme from ICS (Holo), top is the original theme).

Python extending with - using super() Python 3 vs Python 2

Another python3 implementation that involves the use of Abstract classes with super(). You should remember that

super().__init__(name, 10)

has the same effect as

Person.__init__(self, name, 10)

Remember there's a hidden 'self' in super(), So the same object passes on to the superclass init method and the attributes are added to the object that called it. Hence super()gets translated to Person and then if you include the hidden self, you get the above code frag.

from abc import ABCMeta, abstractmethod
class Person(metaclass=ABCMeta):
    name = ""
    age = 0

    def __init__(self, personName, personAge):
        self.name = personName
        self.age = personAge

    @abstractmethod
    def showName(self):
        pass

    @abstractmethod
    def showAge(self):
        pass


class Man(Person):

    def __init__(self, name, height):
        self.height = height
        # Person.__init__(self, name, 10)
        super().__init__(name, 10)  # same as Person.__init__(self, name, 10)
        # basically used to call the superclass init . This is used incase you want to call subclass init
        # and then also call superclass's init.
        # Since there's a hidden self in the super's parameters, when it's is called,
        # the superclasses attributes are a part of the same object that was sent out in the super() method

    def showIdentity(self):
        return self.name, self.age, self.height

    def showName(self):
        pass

    def showAge(self):
        pass


a = Man("piyush", "179")
print(a.showIdentity())

label or @html.Label ASP.net MVC 4

The helpers are there mainly to help you display labels, form inputs, etc for the strongly typed properties of your model. By using the helpers and Visual Studio Intellisense, you can greatly reduce the number of typos that you could make when generating a web page.

With that said, you can continue to create your elements manually for both properties of your view model or items that you want to display that are not part of your view model.

Which Protocols are used for PING?

Internet Control Message Protocol

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

ICMP is built on top of a bunch of other protocols, so in that sense your TA is correct. However, ping itself is ICMP.

Securely storing passwords for use in python script

I typically have a secrets.py that is stored separately from my other python scripts and is not under version control. Then whenever required, you can do from secrets import <required_pwd_var>. This way you can rely on the operating systems in-built file security system without re-inventing your own.

Using Base64 encoding/decoding is also another way to obfuscate the password though not completely secure

More here - Hiding a password in a python script (insecure obfuscation only)

How can I get the named parameters from a URL using Flask?

url:

http://0.0.0.0:5000/user/name/

code:

@app.route('/user/<string:name>/', methods=['GET', 'POST'])
def user_view(name):
    print(name)

(Edit: removed spaces in format string)

'module' has no attribute 'urlencode'

import urllib.parse
urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})

Return positions of a regex match() in Javascript?

function trimRegex(str, regex){
    return str.substr(str.match(regex).index).split('').reverse().join('').substr(str.match(regex).index).split('').reverse().join('');
}

let test = '||ab||cd||';
trimRegex(test, /[^|]/);
console.log(test); //output: ab||cd

or

function trimChar(str, trim, req){
    let regex = new RegExp('[^'+trim+']');
    return str.substr(str.match(regex).index).split('').reverse().join('').substr(str.match(regex).index).split('').reverse().join('');
}

let test = '||ab||cd||';
trimChar(test, '|');
console.log(test); //output: ab||cd

How do you upload a file to a document library in sharepoint?

I used this article to allow to c# to access to a sharepoint site.

http://www.thesharepointguide.com/access-office-365-using-a-console-application/

Basically you create a ClientId and ClientSecret keys to access to the site with c#

Hope this can help you!

How do I redirect to the previous action in ASP.NET MVC?

Pass a returnUrl parameter (url encoded) to the change and login actions and inside redirect to this given returnUrl. Your login action might look something like this:

public ActionResult Login(string returnUrl) 
{
    // Do something...
    return Redirect(returnUrl);
}

Oracle SQL Developer - tables cannot be seen

The identity used to create the connection defines what tables you can see in Oracle. Did you provide different credentials when setting up the connection for the new version?

How do I abort the execution of a Python script?

You can either use:

import sys
sys.exit(...)

or:

raise SystemExit(...)

The optional parameter can be an exit code or an error message. Both methods are identical. I used to prefer sys.exit, but I've lately switched to raising SystemExit, because it seems to stand out better among the rest of the code (due to the raise keyword).

Turn off textarea resizing

//CSS:
.textarea {
    resize: none;
    min-width: //-> Integer number of pixels
    min-height: //-> Integer number of pixels
    max-width: //-> min-width
    max-height: //-> min-height
}

above code works on most browsers

//HTML:
<textarea id='textarea' draggable='false'></textarea>

do both for it to work on the maximum number of browsers

How to get an array of specific "key" in multidimensional array without looping

Since PHP 5.5, you can use array_column:

$ids = array_column($users, 'id');

This is the preferred option on any modern project. However, if you must support PHP<5.5, the following alternatives exist:

Since PHP 5.3, you can use array_map with an anonymous function, like this:

$ids = array_map(function ($ar) {return $ar['id'];}, $users);

Before (Technically PHP 4.0.6+), you must create an anonymous function with create_function instead:

$ids = array_map(create_function('$ar', 'return $ar["id"];'), $users);