Programs & Examples On #Ou

OU stands for Organizational Unit. It's used in directories in general and in LDAP (Lightweight Directory Access Protocol), particularly to point out the main attribute of the organizationalUnit class.

LDAP root query syntax to search more than one specific OU

The answer is NO you can't. Why?

Because the LDAP standard describes a LDAP-SEARCH as kind of function with 4 parameters:

  1. The node where the search should begin, which is a Distinguish Name (DN)
  2. The attributes you want to be brought back
  3. The depth of the search (base, one-level, subtree)
  4. The filter

You are interested in the filter. You've got a summary here (it's provided by Microsoft for Active Directory, it's from a standard). The filter is composed, in a boolean way, by expression of the type Attribute Operator Value.

So the filter you give does not mean anything.

On the theoretical point of view there is ExtensibleMatch that allows buildind filters on the DN path, but it's not supported by Active Directory.

As far as I know, you have to use an attribute in AD to make the distinction for users in the two OUs.

It can be any existing discriminator attribute, or, for example the attribute called OU which is inherited from organizationalPerson class. you can set it (it's not automatic, and will not be maintained if you move the users) with "staff" for some users and "vendors" for others and them use the filter:

(&(objectCategory=person)(|(ou=staff)(ou=vendors)))

When to use <span> instead <p>?

A practical explanation: By default, <p> </p> will add line breaks before and after the enclosed text (so it creates a paragraph). <span> does not do this, that is why it is called inline.

What is the difference between origin and upstream on GitHub?

after cloning a fork you have to explicitly add a remote upstream, with git add remote "the original repo you forked from". This becomes your upstream, you mostly fetch and merge from your upstream. Any other business such as pushing from your local to upstream should be done using pull request.

CSS Div stretch 100% page height

You can cheat using Faux Columns Or you can use some CSS trickery

Which JDK version (Language Level) is required for Android Studio?

Answer Clarification - Android Studio supports JDK8

The following is an answer to the question "What version of Java does Android support?" which is different from "What version of Java can I use to run Android Studio?" which is I believe what was actually being asked. For those looking to answer the 2nd question, you might find Using Android Studio with Java 1.7 helpful.

Also: See http://developer.android.com/sdk/index.html#latest for Android Studio system requirements. JDK8 is actually a requirement for PC and linux (as of 5/14/16).


Java 8 update (3/19/14)

Because I'd assume this question will start popping up soon with the release yesterday: As of right now, there's no set date for when Android will support Java 8.

Here's a discussion over at /androiddev - http://www.reddit.com/r/androiddev/comments/22mh0r/does_android_have_any_plans_for_java_8/

If you really want lambda support, you can checkout Retrolambda - https://github.com/evant/gradle-retrolambda. I've never used it, but it seems fairly promising.

Another Update: Android added Java 7 support

Android now supports Java 7 (minus try-with-resource feature). You can read more about the Java 7 features here: https://stackoverflow.com/a/13550632/413254. If you're using gradle, you can add the following in your build.gradle:

android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

Older response

I'm using Java 7 with Android Studio without any problems (OS X - 10.8.4). You need to make sure you drop the project language level down to 6.0 though. See the screenshot below.

enter image description here

What tehawtness said below makes sense, too. If they're suggesting JDK 6, it makes sense to just go with JDK 6. Either way will be fine.

enter image description here


Update: See this SO post -- https://stackoverflow.com/a/9567402/413254

T-SQL: Using a CASE in an UPDATE statement to update certain columns depending on a condition

You can't use a condition to change the structure of your query, just the data involved. You could do this:

update table set
    columnx = (case when condition then 25 else columnx end),
    columny = (case when condition then columny else 25 end)

This is semantically the same, but just bear in mind that both columns will always be updated. This probably won't cause you any problems, but if you have a high transactional volume, then this could cause concurrency issues.

The only way to do specifically what you're asking is to use dynamic SQL. This is, however, something I'd encourage you to stay away from. The solution above will almost certainly be sufficient for what you're after.

BeautifulSoup: extract text from anchor tag

This will help:

from bs4 import BeautifulSoup

data = '''<div class="image">
        <a href="http://www.example.com/eg1">Content1<img  
        src="http://image.example.com/img1.jpg" /></a>
        </div>
        <div class="image">
        <a href="http://www.example.com/eg2">Content2<img  
        src="http://image.example.com/img2.jpg" /> </a>
        </div>'''

soup = BeautifulSoup(data)

for div in soup.findAll('div', attrs={'class':'image'}):
    print(div.find('a')['href'])
    print(div.find('a').contents[0])
    print(div.find('img')['src'])

If you are looking into Amazon products then you should be using the official API. There is at least one Python package that will ease your scraping issues and keep your activity within the terms of use.

How to print (using cout) a number in binary form?

Reusable function:

template<typename T>
static std::string toBinaryString(const T& x)
{
    std::stringstream ss;
    ss << std::bitset<sizeof(T) * 8>(x);
    return ss.str();
}

Usage:

int main(){
  uint16_t x=8;
  std::cout << toBinaryString(x);
}

This works with all kind of integers.

CSS3 100vh not constant in mobile browser

A nice read about the problem and its possible solutions can be found in this blog post: Addressing the iOS Address Bar in 100vh Layouts

The solution I ended up in my React application is utilising the react-div-100vh library described in the post above.

"Could not find bundler" error

For anyone encountering this issue with Capistrano: capistrano isn't able to locate the bundler. The reason might be that you installed bundler under some other gemset where the Capistrano isn't even looking.

  1. List your gemsets.

rvm gemset list

  1. Use a particular gemset.

rvm use 'my_get_set'

  1. Install bundler under that gemset.

gem install bundler

Then, try again with the deploy task.

System.BadImageFormatException: Could not load file or assembly

My cause was different I referenced a web service then I got this message.

Then I changed my target .Net Framework 4.0 to .Net Framework 2.0 and re-refer my webservice. After a few changes problem solved. There is no error worked fine.

hope this helps!

Why can't I do <img src="C:/localfile.jpg">?

I see two possibilities for what you are trying to do:

  1. You want your webpage, running on a server, to find the file on the computer that you originally designed it?

  2. You want it to fetch it from the pc that is viewing at the page?

Option 1 just doesn't make sense :)

Option 2 would be a security hole, the browser prohibits a web page (served from the web) from loading content on the viewer's machine.

Kyle Hudson told you what you need to do, but that is so basic that I find it hard to believe this is all you want to do.

How to do error logging in CodeIgniter (PHP)

CodeIgniter has some error logging functions built in.

  • Make your /application/logs folder writable
  • In /application/config/config.php set
    $config['log_threshold'] = 1;
    or use a higher number, depending on how much detail you want in your logs
  • Use log_message('error', 'Some variable did not contain a value.');
  • To send an email you need to extend the core CI_Exceptions class method log_exceptions(). You can do this yourself or use this. More info on extending the core here

See http://www.codeigniter.com/user_guide/general/errors.html

Tomcat base URL redirection

Name your webapp WAR “ROOT.war” or containing folder “ROOT”

Assign an initial value to radio button as checked

If you are using react-redux for your application and if you want to show data which is in the redux store, you can set "checked" option as below.

<label>Male</label>

 <input
   type="radio"
   name="gender"
   defaultChecked={this.props.gender == "0"}
 />



 <label>Female</label>
 <input
   type="radio"
   name="gender"
   defaultChecked={this.props.gender == "1"}
 />

What could cause java.lang.reflect.InvocationTargetException?

This describes something like,

InvocationTargetException is a checked exception that wraps an exception thrown by an invoked method or constructor. As of release 1.4, this exception has been retrofitted to conform to the general purpose exception-chaining mechanism. The "target exception" that is provided at construction time and accessed via the getTargetException() method is now known as the cause, and may be accessed via the Throwable.getCause() method, as well as the aforementioned "legacy method."

Can I have onScrollListener for a ScrollView?

If you want to know the scroll position of a view, then you can use the following extension function on View class:

fun View?.onScroll(callback: (x: Int, y: Int) -> Unit) {
    var oldX = 0
    var oldY = 0
    this?.viewTreeObserver?.addOnScrollChangedListener {
        if (oldX != scrollX || oldY != scrollY) {
            callback(scrollX, scrollY)
            oldX = scrollX
            oldY = scrollY
        }
    }
}

Adding and reading from a Config file

Configuration configManager = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
KeyValueConfigurationCollection confCollection = configManager.AppSettings.Settings;

confCollection["YourKey"].Value = "YourNewKey";


configManager.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configManager.AppSettings.SectionInformation.Name);

Laravel migration table field's type change

2018 Solution, still other answers are valid but you dont need to use any dependency:

First you have to create a new migration:

php artisan make:migration change_appointment_time_column_type

Then in that migration file up(), try:

    Schema::table('appointments', function ($table) {
        $table->string('time')->change();
    });

If you donot change the size default will be varchar(191) but If you want to change size of the field:

    Schema::table('appointments', function ($table) {
        $table->string('time', 40)->change();
    });

Then migrate the file by:

php artisan migrate

more info from doc.

What is the difference between Tomcat, JBoss and Glassfish?

Tomcat is just a servlet container, i.e. it implements only the servlets and JSP specification. Glassfish and JBoss are full Java EE servers (including stuff like EJB, JMS, ...), with Glassfish being the reference implementation of the latest Java EE 6 stack, but JBoss in 2010 was not fully supporting it yet.

Android - How To Override the "Back" button so it doesn't Finish() my Activity?

I think what you want is not to override the back button (that just doesn't seem like a good idea - Android OS defines that behavior, why change it?), but to use the Activity Lifecycle and persist your settings/data in the onSaveInstanceState(Bundle) event.

@Override
onSaveInstanceState(Bundle frozenState) {
    frozenState.putSerializable("object_key",
        someSerializableClassYouWantToPersist);
    // etc. until you have everything important stored in the bundle
}

Then you use onCreate(Bundle) to get everything out of that persisted bundle and recreate your state.

@Override
onCreate(Bundle savedInstanceState) {
    if(savedInstanceState!=null){ //It could be null if starting the app.
        mCustomObject = savedInstanceState.getSerializable("object_key");
    }
    // etc. until you have reloaded everything you stored
}

Consider the above psuedo-code to point you in the right direction. Reading up on the Activity Lifecycle should help you determine the best way to accomplish what you're looking for.

What is the difference between readonly="true" & readonly="readonly"?

I'm not sure how they're functionally different. My current batch of OS X browsers don't show any difference.

I would assume they are all functionally the same due to legacy HTML attribute handling. Back in the day, any flag (Boolean) attribute need only be present, sans value, eg

<input readonly>
<option selected>

When XHTML came along, this syntax wasn't valid and values were required. Whilst the W3 specified using the attribute name as the value, I'm guessing most browser vendors decided to simply check for attribute existence.

How to append in a json file in Python?

Assuming you have a test.json file with the following content:

{"67790": {"1": {"kwh": 319.4}}}

Then, the code below will load the json file, update the data inside using dict.update() and dump into the test.json file:

import json

a_dict = {'new_key': 'new_value'}

with open('test.json') as f:
    data = json.load(f)

data.update(a_dict)

with open('test.json', 'w') as f:
    json.dump(data, f)

Then, in test.json, you'll have:

{"new_key": "new_value", "67790": {"1": {"kwh": 319.4}}}

Hope this is what you wanted.

How can I delete a service in Windows?

If they are .NET created services you can use the installutil.exe with the /u switch its in the .net framework folder like C:\Windows\Microsoft.NET\Framework64\v2.0.50727

Can I have a video with transparent background using HTML5 video tag?

webm format is the best solution for Chrome > 29, but it is not supported in Firefox IE and Safari, the best solution is using Flash (wmode="transparent"). but you have to forget "ios".

How to ignore conflicts in rpm installs

From the context, the conflict was caused by the version of the package.
Let's take a look the manual about rpm:

--force
    Same as using --replacepkgs, --replacefiles, and --oldpackage.

--oldpackage
    Allow an upgrade to replace a newer package with an older one.

So, you can execute the command rpm -Uvh info-4.13a-2.rpm --force to solve your issue.

'mvn' is not recognized as an internal or external command, operable program or batch file

In Windows 10, I had to run the windows command prompt (cmd) as administrator. Doing that solved this problem for me.

How to add white spaces in HTML paragraph

If you really need then you can use i.e. &nbsp; entity to do that, but remember that fonts used to render your page are usually proportional, so "aligning" with spaces does not really work and looks ugly.

How to make a new List in Java

List list = new ArrayList();

Or with generics

List<String> list = new ArrayList<String>();

You can, of course, replace string with any type of variable, such as Integer, also.

Server configuration is missing in Eclipse

From project explorer ,just make sure that Servers is not closed enter image description here

application/x-www-form-urlencoded or multipart/form-data?

I agree with much that Manuel has said. In fact, his comments refer to this url...

http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4

... which states:

The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

However, for me it would come down to tool/framework support.

  • What tools and frameworks do you expect your API users to be building their apps with?
  • Do they have frameworks or components they can use that favour one method over the other?

If you get a clear idea of your users, and how they'll make use of your API, then that will help you decide. If you make the upload of files hard for your API users then they'll move away, of you'll spend a lot of time on supporting them.

Secondary to this would be the tool support YOU have for writing your API and how easy it is for your to accommodate one upload mechanism over the other.

Dilemma: when to use Fragments vs Activities:

There's more to this than you realize, you have to remember than an activity that is launched does not implicitly destroy the calling activity. Sure, you can set it up such that your user clicks a button to go to a page, you start that page's activity and destroy the current one. This causes a lot of overhead. The best guide I can give you is:

** Start a new activity only if it makes sense to have the main activity and this one open at the same time (think of multiple windows).

A great example of when it makes sense to have multiple activities is Google Drive. The main activity provides a file explorer. When a file is opened, a new activity is launched to view that file. You can press the recent apps button which will allow you to go back to the browser without closing the opened document, then perhaps even open another document in parallel to the first.

Python: "Indentation Error: unindent does not match any outer indentation level"

I am using gedit basic version that comes with Ubuntu 11.10. I had the same error. This is mainly caused when you mix spaces with tabs.

A good way to differentiate as to which lines have problem would be to go to: 1. edit 2. preferences 3. editor 4. check "automatic indentation" 5. increase the indentation to 12 or some big number

after doing the fifth step you will be able to see the lines of your code that are relly causing problem (these are the lines that have a mix of space and tab)

Make the entire code convention as just TAB or just SPACE (this has to be done manually line by line)

Hope this helps...

Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style

If you are using WebStorm and you are on Windows i would recommend you to click settings/editor/code style/general tab and select "windows(\r\n) from the dropdown menu.These steps will also apply for Rider.

enter image description here

lists and arrays in VBA

You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.

Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String

'Assign data to first item in array
compArray(1) = "asdf"

'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"

'Prints "ErrorState"
Debug.Print Computers("Computer Name")

Collections cannot be sorted so if you need to sort data you will probably want to use an array.

Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx

Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx

Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!

Edit:

Sub ArrayExample()
    Dim subject As String
    Dim TestArray() As String
    Dim counter As Long

    subject = "Example"
    counter = Len(subject)

    ReDim TestArray(1 To counter) As String

    For counter = 1 To Len(subject)
        TestArray(counter) = Right(Left(subject, counter), 1)
    Next
End Sub

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

For me, the clue was the "org.codehaus.mojo:exec-maven-plugin:1.2.1:exec".
The only place this was referenced was in the "Run project" action under Project Properties=>Actions.

When I changed this action to match the HelloFXMLWithMaven sample project (available in Netbeans 11.1): "clean javafx:run" then executing the Run goal was able to proceed.

Note, I also had to update the pom file's javafx-maven-plugin to also match the sample project but with the mainClass changed for my project.

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

While dbenham's answer is pretty good, relying on IF DEFINED can get you in loads of trouble if the variable you're checking isn't an environment variable. Script variables don't get this special treatment.

While this might seem like some ludicrous undocumented BS, doing a simple shell query of IF with IF /? reveals that,

The DEFINED conditional works just like EXIST except it takes an environment variable name and returns true if the environment variable is defined.

In regards to answering this question, is there a reason to not just use a simple flag after a series of evaluations? That seems the most flexible OR check to me, both in regards to underlying logic and readability. For example:

Set Evaluated_True=false

IF %condition_1%==true (Set Evaluated_True=true)
IF %some_string%=="desired result" (Set Evaluated_True=true)
IF %set_numerical_variable% EQ %desired_numerical_value% (Set Evaluated_True=true)

IF %Evaluated_True%==true (echo This is where you do your passing logic) ELSE (echo This is where you do your failing logic)

Obviously, they can be any sort of conditional evaluation, but I'm just sharing a few examples.

If you wanted to have it all on one line, written-wise, you could just chain them together with && like:

Set Evaluated_True=false

IF %condition_1%==true (Set Evaluated_True=true) && IF %some_string%=="desired result" (Set Evaluated_True=true) && IF %set_numerical_variable% EQ %desired_numerical_value% (Set Evaluated_True=true)

IF %Evaluated_True%==true (echo This is where you do your passing logic) ELSE (echo This is where you do your failing logic)

offsetting an html anchor to adjust for fixed header

I'm facing this problem in a TYPO3 website, where all "Content Elements" are wrapped with something like:

<div id="c1234" class="contentElement">...</div>

and i changed the rendering so it renders like this:

<div id="c1234" class="anchor"></div>
<div class="contentElement">...</div>

And this CSS:

.anchor{
    position: relative;
    top: -50px;
}

The fixed topbar being 40px high, now the anchors work again and start 10px under the topbar.

Only drawback of this technique is you can no longer use :target.

Is it possible to append to innerHTML without destroying descendants' event listeners?

There is another alternative: using setAttribute rather than adding an event listener. Like this:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
    <meta charset="utf-8">_x000D_
    <title>Demo innerHTML and event listeners</title>_x000D_
<style>_x000D_
    div {_x000D_
        border: 1px solid black;_x000D_
        padding: 10px;_x000D_
    }_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
    <div>_x000D_
        <span>Click here.</span>_x000D_
    </div>_x000D_
    <script>_x000D_
        document.querySelector('span').setAttribute("onclick","alert('Hi.')");_x000D_
        document.querySelector('div').innerHTML += ' Added text.';_x000D_
    </script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

I am getting "java.lang.ClassNotFoundException: com.google.gson.Gson" error even though it is defined in my classpath

I had the same problem when developing a KNIME Node/plugin in the Eclipse environment. The solution was not only to add the gson.jar as an externar JAR to the build path, it was also required to go to plugin.xml, then the Dependencies tab and add com.google.gson as a required plugin.

How can I remove text within parentheses with a regex?

The pattern that matches substrings in parentheses having no other ( and ) characters in between (like (xyz 123) in Text (abc(xyz 123)) is

\([^()]*\)

Details:

  • \( - an opening round bracket (note that in POSIX BRE, ( should be used, see sed example below)
  • [^()]* - zero or more (due to the * Kleene star quantifier) characters other than those defined in the negated character class/POSIX bracket expression, that is, any chars other than ( and )
  • \) - a closing round bracket (no escaping in POSIX BRE allowed)

Removing code snippets:

  • JavaScript: string.replace(/\([^()]*\)/g, '')
  • PHP: preg_replace('~\([^()]*\)~', '', $string)
  • Perl: $s =~ s/\([^()]*\)//g
  • Python: re.sub(r'\([^()]*\)', '', s)
  • C#: Regex.Replace(str, @"\([^()]*\)", string.Empty)
  • VB.NET: Regex.Replace(str, "\([^()]*\)", "")
  • Java: s.replaceAll("\\([^()]*\\)", "")
  • Ruby: s.gsub(/\([^()]*\)/, '')
  • R: gsub("\\([^()]*\\)", "", x)
  • Lua: string.gsub(s, "%([^()]*%)", "")
  • Bash/sed: sed 's/([^()]*)//g'
  • Tcl: regsub -all {\([^()]*\)} $s "" result
  • C++ std::regex: std::regex_replace(s, std::regex(R"(\([^()]*\))"), "")
  • Objective-C:
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\([^()]*\\)" options:NSRegularExpressionCaseInsensitive error:&error]; NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""];
  • Swift: s.replacingOccurrences(of: "\\([^()]*\\)", with: "", options: [.regularExpression])

What does it mean "No Launcher activity found!"

In Eclipse when can do this:

enter image description here

But it is preferable make the corresponding changes inside the Android manifest file.

Change language for bootstrap DateTimePicker

all you are right! other way to getting !

https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/locales/bootstrap-datepicker.ru.min.js

You can find out all languages on there https://cdnjs.com/libraries/bootstrap-datepicker

https://labs.maarch.org/maarch/maarchRM/commit/3299d1e7ed25018b48715e16a42d52c288b4da3e

How to call Oracle MD5 hash function?

I would do:

select DBMS_CRYPTO.HASH(rawtohex('foo') ,2) from dual;

output:

DBMS_CRYPTO.HASH(RAWTOHEX('FOO'),2)
--------------------------------------------------------------------------------
ACBD18DB4CC2F85CEDEF654FCCC4A4D8

assigning column names to a pandas series

You can create a dict and pass this as the data param to the dataframe constructor:

In [235]:

df = pd.DataFrame({'Gene':s.index, 'count':s.values})
df
Out[235]:
   Gene  count
0  Ezh2      2
1  Hmgb      7
2  Irf1      1

Alternatively you can create a df from the series, you need to call reset_index as the index will be used and then rename the columns:

In [237]:

df = pd.DataFrame(s).reset_index()
df.columns = ['Gene', 'count']
df
Out[237]:
   Gene  count
0  Ezh2      2
1  Hmgb      7
2  Irf1      1

ORACLE and TRIGGERS (inserted, updated, deleted)

I've changed my code like this and it works:

CREATE or REPLACE TRIGGER test001
  AFTER INSERT OR UPDATE OR DELETE ON tabletest001
  REFERENCING OLD AS old_buffer NEW AS new_buffer 
  FOR EACH ROW WHEN (new_buffer.field1 = 'HBP00' OR old_buffer.field1 = 'HBP00') 

DECLARE
      Operation       NUMBER;
      CustomerCode    CHAR(10 BYTE);
BEGIN

IF DELETING THEN 
  Operation := 3;
  CustomerCode := :old_buffer.field1;
END IF;

IF INSERTING THEN 
  Operation := 1;
  CustomerCode := :new_buffer.field1;
END IF;

IF UPDATING THEN 
  Operation := 2;
  CustomerCode := :new_buffer.field1;
END IF;    

// DO SOMETHING ...

EXCEPTION
    WHEN OTHERS THEN ErrorCode := SQLCODE;

END;

Why is it faster to check if dictionary contains the key, rather than catch the exception in case it doesn't?

Dictionaries are specifically designed to do super fast key lookups. They are implemented as hashtables and the more entries the faster they are relative to other methods. Using the exception engine is only supposed to be done when your method has failed to do what you designed it to do because it is a large set of object that give you a lot of functionality for handling errors. I built an entire library class once with everything surrounded by try catch blocks once and was appalled to see the debug output which contained a seperate line for every single one of over 600 exceptions!

Read properties file outside JAR file

I did it by other way.

Properties prop = new Properties();
    try {

        File jarPath=new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
        String propertiesPath=jarPath.getParentFile().getAbsolutePath();
        System.out.println(" propertiesPath-"+propertiesPath);
        prop.load(new FileInputStream(propertiesPath+"/importer.properties"));
    } catch (IOException e1) {
        e1.printStackTrace();
    }
  1. Get Jar file path.
  2. Get Parent folder of that file.
  3. Use that path in InputStreamPath with your properties file name.

DataGridView checkbox column - value and functionality

  1. There is no way to do that directly. Once you have your data in the grid, you can loop through the rows and check each box like this:

    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        row.Cells[CheckBoxColumn1.Name].Value = true;
    }
    
  2. The Click event might look something like this:

    private void button1_Click(object sender, EventArgs e)
    {
        List<DataGridViewRow> rows_with_checked_column = new List<DataGridViewRow>();
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (Convert.ToBoolean(row.Cells[CheckBoxColumn1.Name].Value) == true)
            {
                rows_with_checked_column.Add(row);
            }
        }
        // Do what you want with the check rows
    }
    

How do I center list items inside a UL element?

Another way to do this:

<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>

ul {
  width: auto;
  display: table;
  margin-left: auto;
  margin-right: auto;
}

ul li {
  float: left;
  list-style: none;
  margin-right: 1rem;
}

http://jsfiddle.net/f6qgf24m/

Run Jquery function on window events: load, resize, and scroll?

You can bind listeners to one common functions -

$(window).bind("load resize scroll",function(e){
  // do stuff
});

Or another way -

$(window).bind({
     load:function(){

     },
     resize:function(){

     },
     scroll:function(){

    }
});

Alternatively, instead of using .bind() you can use .on() as bind directly maps to on(). And maybe .bind() won't be there in future jquery versions.

$(window).on({
     load:function(){

     },
     resize:function(){

     },
     scroll:function(){

    }
});

jQuery.inArray(), how to use it right?

If we want to check an element is inside a set of elements we can do for example:

var checkboxes_checked = $('input[type="checkbox"]:checked');

// Whenever a checkbox or input text is changed
$('input[type="checkbox"], input[type="text"]').change(function() {
    // Checking if the element was an already checked checkbox
    if($.inArray( $(this)[0], checkboxes_checked) !== -1) {
        alert('this checkbox was already checked');
    }
}

Subversion stuck due to "previous operation has not finished"?

I was facing this problem after adding a jar which is already in the SVN and I added the new Version of it with the same name.

In Eclipse I tried this

  1. Right click on folder > Team > Refresh/Cleanup.
  2. Clean, build and refresh my application.
  3. Restart the Eclipse.

Using above steps I am able to Synchronize.

Error 1046 No database Selected, how to resolve?

Assuming you are using the command line:

1. Find Database

show databases;

Example of a database list

2. Select a database from the list

e.g. USE classicmodels; and you should be off to the races! (Obviously, you'll have to use the correctly named database in your list.

Why is this error occurring?

Mysql requires you to select the particular database you are working on. I presume it is a design decision they made: it avoids a lot of potential problems: e.g. it is entirely possible, for you to use the same table names across multiple databases e.g. a users table. In order to avoid these types of issues, they probably thought: "let's make users select the database they want".

Compiler warning - suggest parentheses around assignment used as truth value

It's just a 'safety' warning. It is a relatively common idiom, but also a relatively common error when you meant to have == in there. You can make the warning go away by adding another set of parentheses:

while ((list = list->next))

Error System.Data.OracleClient requires Oracle client software version 8.1.7 or greater when installs setup

It is a security issue, so to fix it simply do the following:

  1. Go to the Oracle Client folder.
  2. Right Click on the folder.
  3. On security Tab, Add "Authenticated Users" and give this account Read & Execute permission.
  4. Apply this security for all folders, Subfolders and Files (IMPORTANT).
  5. Don't Forget to REBOOT your Machine; if you forgot to do this you will still face the same problem unless you restart your machine.

http://blogs.msdn.com/b/fabdulwahab/archive/2011/11/13/system-data-oracleclient-requires-oracle-client-software-version-8-1-7-or-greater.aspx

Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)

In my case I hade to change from:

plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-kapt'
    **apply plugin :'com.google.gms.google-services'**
}

to

plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-kapt'
    id 'com.google.gms.google-services'
}

How do I append a node to an existing XML file in java

To append a new data element,just do this...

Document doc = docBuilder.parse(is);        
Node root=doc.getFirstChild();
Element newserver=doc.createElement("new_server");
root.appendChild(newserver);

easy.... 'is' is an InputStream object. rest is similar to your code....tried it just now...

Change a branch name in a Git repo

If you're currently on the branch you want to rename:

git branch -m new_name 

Or else:

git branch -m old_name new_name 

You can check with:

git branch -a

As you can see, only the local name changed Now, to change the name also in the remote you must do:

git push origin :old_name

This removes the branch, then upload it with the new name:

git push origin new_name

Source: https://web.archive.org/web/20150929104013/http://blog.changecong.com:80/2012/10/rename-a-remote-branch-on-github

Renaming column names of a DataFrame in Spark Scala

Sometime we have the column name is below format in SQLServer or MySQL table

Ex  : Account Number,customer number

But Hive tables do not support column name containing spaces, so please use below solution to rename your old column names.

Solution:

val renamedColumns = df.columns.map(c => df(c).as(c.replaceAll(" ", "_").toLowerCase()))
df = df.select(renamedColumns: _*)

Update OpenSSL on OS X with Homebrew

In a terminal, run:

export PATH=/usr/local/bin:$PATH
brew link --force openssl

You may have to unlink openssl first if you get a warning: brew unlink openssl

This ensures we're linking the correct openssl for this situation. (and doesn't mess with .profile)

Hat tip to @Olaf's answer and @Felipe's comment. Some people - such as myself - may have some pretty messed up PATH vars.

Difference between string and text in rails?

Use string for shorter field, like names, address, phone, company

Use Text for larger content, comments, content, paragraphs.

My general rule, if it's something that is more than one line, I typically go for text, if it's a short 2-6 words, I go for string.

The official rule is 255 for a string. So, if your string is more than 255 characters, go for text.

How to filter data in dataview

DataView view = new DataView();
view.Table = DataSet1.Tables["Suppliers"];
view.RowFilter = "City = 'Berlin'";
view.RowStateFilter = DataViewRowState.ModifiedCurrent;
view.Sort = "CompanyName DESC";

// Simple-bind to a TextBox control
Text1.DataBindings.Add("Text", view, "CompanyName");

Ref: http://www.csharp-examples.net/dataview-rowfilter/

http://msdn.microsoft.com/en-us/library/system.data.dataview.rowfilter.aspx

java.lang.NoClassDefFoundError: Could not initialize class XXX

I had the same exception - but only while running in debug mode, this is how I solved the problem (after 3 whole days): in the build.gradle i had : "multiDexEnabled true" set in the defaultConfig section.

        defaultConfig {
    applicationId "com.xxx.yyy"
    minSdkVersion 15
    targetSdkVersion 28
    versionCode 5123
    versionName "5123"
    // Enabling multidex support.
    multiDexEnabled true
}

but apparently this wasn't enough. but when i changed:

public class MyAppClass  extends Application 

to:

public class MyAppClass  extends MultiDexApplication 

this solved it. hope this will help someone

How to display svg icons(.svg files) in UI using React Component?

You can directly use .svg extension with img tag if the image is remotely hosted.

ReactDOM.render(
  <img src={"http://s.cdpn.io/3/kiwi.svg"}/>,
  document.getElementById('root')
);

Here is the fiddle: http://codepen.io/srinivasdamam-1471688843/pen/ZLNYdy?editors=0110

Note: If you are using any web app bundlers (like Webpack) you need to have related file loader.

Truncate string in Laravel blade templates

In Laravel 4 & 5 (up to 5.7), you can use str_limit, which limits the number of characters in a string.

While in Laravel 5.8 up, you can use the Str::limit helper.

//For Laravel 4 to Laravel 5.5
{{ str_limit($string, $limit = 150, $end = '...') }}
//For Laravel 5.5 upwards
{{ \Illuminate\Support\Str::limit($string, 150, $end='...') }}

For more Laravel helper functions http://laravel.com/docs/helpers#strings

Import CSV file with mixed data types

Use xlsread, it works just as well on .csv files as it does on .xls files. Specify that you want three outputs:

[num char raw] = xlsread('your_filename.csv')

and it will give you an array containing only the numeric data (num), an array containing only the character data (char) and an array that contains all data types in the same format as the .csv layout (raw).

Check if a String contains a special character

Pattern p = Pattern.compile("[\\p{Alpha}]*[\\p{Punct}][\\p{Alpha}]*");
        Matcher m = p.matcher("Afsff%esfsf098");
        boolean b = m.matches();

        if (b == true)
           System.out.println("There is a sp. character in my string");
        else
            System.out.println("There is no sp. char.");

How to use Bootstrap modal using the anchor tag for Register?

Here is a link to W3Schools that answers your question https://www.w3schools.com/bootstrap/bootstrap_ref_js_modal.asp

Note: For anchor tag elements, omit data-target, and use href="#modalID" instead:

I hope that helps

What is the most efficient way to create a dictionary of two pandas Dataframe columns?

I found a faster way to solve the problem, at least on realistically large datasets using: df.set_index(KEY).to_dict()[VALUE]

Proof on 50,000 rows:

df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB'))
df['A'] = df['A'].apply(chr)

%timeit dict(zip(df.A,df.B))
%timeit pd.Series(df.A.values,index=df.B).to_dict()
%timeit df.set_index('A').to_dict()['B']

Output:

100 loops, best of 3: 7.04 ms per loop  # WouterOvermeire
100 loops, best of 3: 9.83 ms per loop  # Jeff
100 loops, best of 3: 4.28 ms per loop  # Kikohs (me)

WCF - How to Increase Message Size Quota

Another important thing to consider from my experience..

I would strongly advice NOT to maximize maxBufferPoolSize, because buffers from the pool are never released until the app-domain (ie the Application Pool) recycles.

A period of high traffic could cause a lot of memory to be used and never released.

More details here:

How to pass dictionary items as function arguments in python?

*data interprets arguments as tuples, instead you have to pass **data which interprets the arguments as dictionary.

data = {'school':'DAV', 'class': '7', 'name': 'abc', 'city': 'pune'}


def my_function(**data):
    schoolname  = data['school']
    cityname = data['city']
    standard = data['class']
    studentname = data['name']

You can call the function like this:

my_function(**data)

Loop through each row of a range in Excel

Something like this:

Dim rng As Range
Dim row As Range
Dim cell As Range

Set rng = Range("A1:C2")

For Each row In rng.Rows
  For Each cell in row.Cells
    'Do Something
  Next cell
Next row

Cannot read property 'push' of undefined when combining arrays

order is an Object, not an Array().

push() is for arrays.

Refer to this post

Try this though(but your subobjects have to be Arrays()):

var order = new Array();

// initialize order; n = index
order[n] = new Array();

// and then you can perform push()
order[n].push(some_value);

Or you can just use order as an array of non-array objects:

var order = new Array();

order.push(a[n]);

Cannot attach the file *.mdf as database

"Cannot attach the file 'C:\Github\TestService\TestService\App_data\TestService.mdf" as database 'TestService'

When you meet the above error message, Please do the following steps.

  1. Open SQL Server Object Explorer
  2. Click refresh button.
  3. Expand (localdb)\MSSQLLocalDB(SQL Server 12.x.xxxxx - xxxxx\xxxx)
  4. Expand Database
  5. Please remove existed same name database
  6. Click right button and then delete
  7. Go back to your Package Manage Console
  8. Update-Database

VarBinary vs Image SQL Server Data Type to Store Binary Data?

There is also the rather spiffy FileStream, introduced in SQL Server 2008.

Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304'

I tried all of that things and it doesn't worked for me.

I Just installed SAPCrystalReport in my computer and it's working now.

Get Number of Rows returned by ResultSet in Java

In my case, I needed to get the total rows from a ResultSet and also access the ResultSet values ??if the total rows did not reach the limit of an XLS file.

For that, I had to make two adjustments to my code:

1) Change in object construction PreparedStatement

A default ResultSet object has a cursor that moves forward only. Thus, you can iterate through it only once and only from the first row to the last row. It is possible to produce ResultSet objects that are scrollable. The following code fragment illustrates how to make a result set that is scrollable and insensitive to updates by others.

PreparedStatement ps = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, 
ResultSet.CONCUR_READ_ONLY);

2) Get total rows. The following code fragment illustrates how:

ResultSet rs = ps.executeQuery();
rs.last();
int totalRowsResult = rs.getRow();

PS: If the number of records of the query result is too large, you may run out of memory on the Java server by getting an exception: java.lang.OutOfMemoryError: Java heap space. This exception will occur when executing the rs.last () method

3) Access again the ResultSet and you don't get the message: exhaused result set. So, vou need reset the result set to the top, using rs.first() or rs.absolute(1). The following code fragment illustrates how:

rs.first();
System.out.println(rs.getString(1));

Difference between "enqueue" and "dequeue"

These are terms usually used when describing a "FIFO" queue, that is "first in, first out". This works like a line. You decide to go to the movies. There is a long line to buy tickets, you decide to get into the queue to buy tickets, that is "Enqueue". at some point you are at the front of the line, and you get to buy a ticket, at which point you leave the line, that is "Dequeue".

Input type "number" won't resize

What you want is maxlength.

Valid for text, search, url, tel, email, and password, it defines the maximum number of characters (as UTF-16 code units) the user can enter into the field. This must be an integer value 0 or higher. If no maxlength is specified, or an invalid value is specified, the field has no maximum length. This value must also be greater than or equal to the value of minlength.

You might consider using one of these input types.

Access to the path is denied

In my case I had to add a .NET Authorization Rule for the web site in IIS.

I added a rule to allow anonymous users.

.NET Authorization Rules

Can a main() method of class be invoked from another class in java

If you want to call the main method of another class you can do it this way assuming I understand the question.

public class MyClass {

    public static void main(String[] args) {

        System.out.println("main() method of MyClass");
        OtherClass obj = new OtherClass();
    }
}

class OtherClass {

    public OtherClass() {

        // Call the main() method of MyClass
        String[] arguments = new String[] {"123"};
        MyClass.main(arguments);
    }
}

Update statement with inner join on Oracle

UPDATE (SELECT T.FIELD A, S.FIELD B
FROM TABLE_T T INNER JOIN TABLE_S S
ON T.ID = S.ID)
SET B = A;

A and B are alias fields, you do not need to point the table.

ng-repeat finish event

I did it this way.

Create the directive

function finRepeat() {
    return function(scope, element, attrs) {
        if (scope.$last){
            // Here is where already executes the jquery
            $(document).ready(function(){
                $('.materialboxed').materialbox();
                $('.tooltipped').tooltip({delay: 50});
            });
        }
    }
}

angular
    .module("app")
    .directive("finRepeat", finRepeat);

After you add it on the label where this ng-repeat

<ul>
    <li ng-repeat="(key, value) in data" fin-repeat> {{ value }} </li>
</ul>

And ready with that will be run at the end of the ng-repeat.

How to get single value from this multi-dimensional PHP array

You can also use array_column(). It's available from PHP 5.5: php.net/manual/en/function.array-column.php

It returns the values from a single column of the array, identified by the column_key. Optionally, you may provide an index_key to index the values in the returned array by the values from the index_key column in the input array.

print_r(array_column($myarray, 'email'));

Share application "link" in Android

finally, this code is worked for me to open the email client from android device. try this snippet.

Intent testIntent = new Intent(Intent.ACTION_VIEW);
                    Uri data = Uri.parse("mailto:?subject=" + "Feedback" + "&body=" + "Write Feedback here....." + "&to=" + "[email protected]");
                    testIntent.setData(data);
                    startActivity(testIntent);

Using Spring 3 autowire in a standalone Java application

Spring is moving away from XML files and uses annotations heavily. The following example is a simple standalone Spring application which uses annotation instead of XML files.

package com.zetcode.bean;

import org.springframework.stereotype.Component;

@Component
public class Message {

   private String message = "Hello there!";

   public void setMessage(String message){

      this.message  = message;
   }

   public String getMessage(){

      return message;
   }
}

This is a simple bean. It is decorated with the @Component annotation for auto-detection by Spring container.

package com.zetcode.main;

import com.zetcode.bean.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan(basePackages = "com.zetcode")
public class Application {

    public static void main(String[] args) {

        ApplicationContext context
                = new AnnotationConfigApplicationContext(Application.class);

        Application p = context.getBean(Application.class);
        p.start();
    }

    @Autowired
    private Message message;
    private void start() {
        System.out.println("Message: " + message.getMessage());
    }
}

This is the main Application class. The @ComponentScan annotation searches for components. The @Autowired annotation injects the bean into the message variable. The AnnotationConfigApplicationContext is used to create the Spring application context.

My Standalone Spring tutorial shows how to create a standalone Spring application with both XML and annotations.

Dynamically change color to lighter or darker by percentage CSS (Javascript)

I found a PHP class that let me do this server side. I just output an inline CSS color style for whatever I need to be lighter/darker. Works great.

http://www.barelyfitz.com/projects/csscolor/

(note that the class uses PEAR for throwing errors, but I didn't want to include PEAR just to modify colors, so I just removed all the PEAR references)

I turned it into a static class with static methods so I can call "lighten" & "darken" functions directly without creating a new object.

Sample usage:

$original_color = 'E58D8D';  
$lighter_color = Css::lighten($original_color, .7);  
$darker_color = Css::darken($original_color, .7);

How to add "active" class to wp_nav_menu() current menu item (simple way)

If you want the 'active' in the html:

header with html and php:

        <?php
        $menu_items = wp_get_nav_menu_items( 'main_nav' ); // id or name of menu
        foreach ( (array) $menu_items as $key => $menu_item ) {
            if ( ! $menu_item->menu_item_parent ) {
                echo "<li class=" . vince_check_active_menu($menu_item) . "><a href='$menu_item->url'>";
                echo $menu_item->title;
                echo "</a></li>";
            }
        }
        ?>

functions.php:

function vince_check_active_menu( $menu_item ) {
    $actual_link = ( isset( $_SERVER['HTTPS'] ) ? "https" : "http" ) . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    if ( $actual_link == $menu_item->url ) {
        return 'active';
    }
    return '';
}

convert string to number node.js

Using parseInt() is a bad idea mainly because it never fails. Also because some results can be unexpected, like in the case of INFINITY.
Below is the function for handling unexpected behaviour.

function cleanInt(x) {
    x = Number(x);
    return x >= 0 ? Math.floor(x) : Math.ceil(x);
}

See results of below test cases.

console.log("CleanInt: ", cleanInt('xyz'), " ParseInt: ", parseInt('xyz'));
console.log("CleanInt: ", cleanInt('123abc'), " ParseInt: ", parseInt('123abc'));
console.log("CleanInt: ", cleanInt('234'), " ParseInt: ", parseInt('234'));
console.log("CleanInt: ", cleanInt('-679'), " ParseInt: ", parseInt('-679'));
console.log("CleanInt: ", cleanInt('897.0998'), " ParseInt: ", parseInt('897.0998'));
console.log("CleanInt: ", cleanInt('Infinity'), " ParseInt: ", parseInt('Infinity'));

result:

CleanInt:  NaN  ParseInt:  NaN
CleanInt:  NaN  ParseInt:  123
CleanInt:  234  ParseInt:  234
CleanInt:  -679  ParseInt:  -679
CleanInt:  897  ParseInt:  897
CleanInt:  Infinity  ParseInt:  NaN

This table does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available

Make sure all your tables have one primary key. I forgot to add a primary key to one table and that solved this problem for me. :)

Are static class variables possible in Python?

Static and Class Methods

As the other answers have noted, static and class methods are easily accomplished using the built-in decorators:

class Test(object):

    # regular instance method:
    def MyMethod(self):
        pass

    # class method:
    @classmethod
    def MyClassMethod(klass):
        pass

    # static method:
    @staticmethod
    def MyStaticMethod():
        pass

As usual, the first argument to MyMethod() is bound to the class instance object. In contrast, the first argument to MyClassMethod() is bound to the class object itself (e.g., in this case, Test). For MyStaticMethod(), none of the arguments are bound, and having arguments at all is optional.

"Static Variables"

However, implementing "static variables" (well, mutable static variables, anyway, if that's not a contradiction in terms...) is not as straight forward. As millerdev pointed out in his answer, the problem is that Python's class attributes are not truly "static variables". Consider:

class Test(object):
    i = 3  # This is a class attribute

x = Test()
x.i = 12   # Attempt to change the value of the class attribute using x instance
assert x.i == Test.i  # ERROR
assert Test.i == 3    # Test.i was not affected
assert x.i == 12      # x.i is a different object than Test.i

This is because the line x.i = 12 has added a new instance attribute i to x instead of changing the value of the Test class i attribute.

Partial expected static variable behavior, i.e., syncing of the attribute between multiple instances (but not with the class itself; see "gotcha" below), can be achieved by turning the class attribute into a property:

class Test(object):

    _i = 3

    @property
    def i(self):
        return type(self)._i

    @i.setter
    def i(self,val):
        type(self)._i = val

## ALTERNATIVE IMPLEMENTATION - FUNCTIONALLY EQUIVALENT TO ABOVE ##
## (except with separate methods for getting and setting i) ##

class Test(object):

    _i = 3

    def get_i(self):
        return type(self)._i

    def set_i(self,val):
        type(self)._i = val

    i = property(get_i, set_i)

Now you can do:

x1 = Test()
x2 = Test()
x1.i = 50
assert x2.i == x1.i  # no error
assert x2.i == 50    # the property is synced

The static variable will now remain in sync between all class instances.

(NOTE: That is, unless a class instance decides to define its own version of _i! But if someone decides to do THAT, they deserve what they get, don't they???)

Note that technically speaking, i is still not a 'static variable' at all; it is a property, which is a special type of descriptor. However, the property behavior is now equivalent to a (mutable) static variable synced across all class instances.

Immutable "Static Variables"

For immutable static variable behavior, simply omit the property setter:

class Test(object):

    _i = 3

    @property
    def i(self):
        return type(self)._i

## ALTERNATIVE IMPLEMENTATION - FUNCTIONALLY EQUIVALENT TO ABOVE ##
## (except with separate methods for getting i) ##

class Test(object):

    _i = 3

    def get_i(self):
        return type(self)._i

    i = property(get_i)

Now attempting to set the instance i attribute will return an AttributeError:

x = Test()
assert x.i == 3  # success
x.i = 12         # ERROR

One Gotcha to be Aware of

Note that the above methods only work with instances of your class - they will not work when using the class itself. So for example:

x = Test()
assert x.i == Test.i  # ERROR

# x.i and Test.i are two different objects:
type(Test.i)  # class 'property'
type(x.i)     # class 'int'

The line assert Test.i == x.i produces an error, because the i attribute of Test and x are two different objects.

Many people will find this surprising. However, it should not be. If we go back and inspect our Test class definition (the second version), we take note of this line:

    i = property(get_i) 

Clearly, the member i of Test must be a property object, which is the type of object returned from the property function.

If you find the above confusing, you are most likely still thinking about it from the perspective of other languages (e.g. Java or c++). You should go study the property object, about the order in which Python attributes are returned, the descriptor protocol, and the method resolution order (MRO).

I present a solution to the above 'gotcha' below; however I would suggest - strenuously - that you do not try to do something like the following until - at minimum - you thoroughly understand why assert Test.i = x.i causes an error.

REAL, ACTUAL Static Variables - Test.i == x.i

I present the (Python 3) solution below for informational purposes only. I am not endorsing it as a "good solution". I have my doubts as to whether emulating the static variable behavior of other languages in Python is ever actually necessary. However, regardless as to whether it is actually useful, the below should help further understanding of how Python works.

UPDATE: this attempt is really pretty awful; if you insist on doing something like this (hint: please don't; Python is a very elegant language and shoe-horning it into behaving like another language is just not necessary), use the code in Ethan Furman's answer instead.

Emulating static variable behavior of other languages using a metaclass

A metaclass is the class of a class. The default metaclass for all classes in Python (i.e., the "new style" classes post Python 2.3 I believe) is type. For example:

type(int)  # class 'type'
type(str)  # class 'type'
class Test(): pass
type(Test) # class 'type'

However, you can define your own metaclass like this:

class MyMeta(type): pass

And apply it to your own class like this (Python 3 only):

class MyClass(metaclass = MyMeta):
    pass

type(MyClass)  # class MyMeta

Below is a metaclass I have created which attempts to emulate "static variable" behavior of other languages. It basically works by replacing the default getter, setter, and deleter with versions which check to see if the attribute being requested is a "static variable".

A catalog of the "static variables" is stored in the StaticVarMeta.statics attribute. All attribute requests are initially attempted to be resolved using a substitute resolution order. I have dubbed this the "static resolution order", or "SRO". This is done by looking for the requested attribute in the set of "static variables" for a given class (or its parent classes). If the attribute does not appear in the "SRO", the class will fall back on the default attribute get/set/delete behavior (i.e., "MRO").

from functools import wraps

class StaticVarsMeta(type):
    '''A metaclass for creating classes that emulate the "static variable" behavior
    of other languages. I do not advise actually using this for anything!!!

    Behavior is intended to be similar to classes that use __slots__. However, "normal"
    attributes and __statics___ can coexist (unlike with __slots__). 

    Example usage: 

        class MyBaseClass(metaclass = StaticVarsMeta):
            __statics__ = {'a','b','c'}
            i = 0  # regular attribute
            a = 1  # static var defined (optional)

        class MyParentClass(MyBaseClass):
            __statics__ = {'d','e','f'}
            j = 2              # regular attribute
            d, e, f = 3, 4, 5  # Static vars
            a, b, c = 6, 7, 8  # Static vars (inherited from MyBaseClass, defined/re-defined here)

        class MyChildClass(MyParentClass):
            __statics__ = {'a','b','c'}
            j = 2  # regular attribute (redefines j from MyParentClass)
            d, e, f = 9, 10, 11   # Static vars (inherited from MyParentClass, redefined here)
            a, b, c = 12, 13, 14  # Static vars (overriding previous definition in MyParentClass here)'''
    statics = {}
    def __new__(mcls, name, bases, namespace):
        # Get the class object
        cls = super().__new__(mcls, name, bases, namespace)
        # Establish the "statics resolution order"
        cls.__sro__ = tuple(c for c in cls.__mro__ if isinstance(c,mcls))

        # Replace class getter, setter, and deleter for instance attributes
        cls.__getattribute__ = StaticVarsMeta.__inst_getattribute__(cls, cls.__getattribute__)
        cls.__setattr__ = StaticVarsMeta.__inst_setattr__(cls, cls.__setattr__)
        cls.__delattr__ = StaticVarsMeta.__inst_delattr__(cls, cls.__delattr__)
        # Store the list of static variables for the class object
        # This list is permanent and cannot be changed, similar to __slots__
        try:
            mcls.statics[cls] = getattr(cls,'__statics__')
        except AttributeError:
            mcls.statics[cls] = namespace['__statics__'] = set() # No static vars provided
        # Check and make sure the statics var names are strings
        if any(not isinstance(static,str) for static in mcls.statics[cls]):
            typ = dict(zip((not isinstance(static,str) for static in mcls.statics[cls]), map(type,mcls.statics[cls])))[True].__name__
            raise TypeError('__statics__ items must be strings, not {0}'.format(typ))
        # Move any previously existing, not overridden statics to the static var parent class(es)
        if len(cls.__sro__) > 1:
            for attr,value in namespace.items():
                if attr not in StaticVarsMeta.statics[cls] and attr != ['__statics__']:
                    for c in cls.__sro__[1:]:
                        if attr in StaticVarsMeta.statics[c]:
                            setattr(c,attr,value)
                            delattr(cls,attr)
        return cls
    def __inst_getattribute__(self, orig_getattribute):
        '''Replaces the class __getattribute__'''
        @wraps(orig_getattribute)
        def wrapper(self, attr):
            if StaticVarsMeta.is_static(type(self),attr):
                return StaticVarsMeta.__getstatic__(type(self),attr)
            else:
                return orig_getattribute(self, attr)
        return wrapper
    def __inst_setattr__(self, orig_setattribute):
        '''Replaces the class __setattr__'''
        @wraps(orig_setattribute)
        def wrapper(self, attr, value):
            if StaticVarsMeta.is_static(type(self),attr):
                StaticVarsMeta.__setstatic__(type(self),attr, value)
            else:
                orig_setattribute(self, attr, value)
        return wrapper
    def __inst_delattr__(self, orig_delattribute):
        '''Replaces the class __delattr__'''
        @wraps(orig_delattribute)
        def wrapper(self, attr):
            if StaticVarsMeta.is_static(type(self),attr):
                StaticVarsMeta.__delstatic__(type(self),attr)
            else:
                orig_delattribute(self, attr)
        return wrapper
    def __getstatic__(cls,attr):
        '''Static variable getter'''
        for c in cls.__sro__:
            if attr in StaticVarsMeta.statics[c]:
                try:
                    return getattr(c,attr)
                except AttributeError:
                    pass
        raise AttributeError(cls.__name__ + " object has no attribute '{0}'".format(attr))
    def __setstatic__(cls,attr,value):
        '''Static variable setter'''
        for c in cls.__sro__:
            if attr in StaticVarsMeta.statics[c]:
                setattr(c,attr,value)
                break
    def __delstatic__(cls,attr):
        '''Static variable deleter'''
        for c in cls.__sro__:
            if attr in StaticVarsMeta.statics[c]:
                try:
                    delattr(c,attr)
                    break
                except AttributeError:
                    pass
        raise AttributeError(cls.__name__ + " object has no attribute '{0}'".format(attr))
    def __delattr__(cls,attr):
        '''Prevent __sro__ attribute from deletion'''
        if attr == '__sro__':
            raise AttributeError('readonly attribute')
        super().__delattr__(attr)
    def is_static(cls,attr):
        '''Returns True if an attribute is a static variable of any class in the __sro__'''
        if any(attr in StaticVarsMeta.statics[c] for c in cls.__sro__):
            return True
        return False

Using margin:auto to vertically-align a div

_x000D_
_x000D_
.black {_x000D_
    display:flex;_x000D_
    flex-direction: column;_x000D_
    height: 200px;_x000D_
    background:grey_x000D_
}_x000D_
.message {_x000D_
    background:yellow;_x000D_
    width:200px;_x000D_
    padding:10px;_x000D_
    margin: auto auto;_x000D_
}
_x000D_
<div class="black">_x000D_
    <div class="message">_x000D_
        This is a popup message._x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to extract week number in sql

Use 'dd-mon-yyyy' if you are using the 2nd date format specified in your answer. Ex:

to_date(<column name>,'dd-mon-yyyy')

package R does not exist

Sample: My package is com.example.mypc.f01, to fix error you add line below to Activity:

import com.example.mypc.f01.R;

Python: Assign Value if None Exists

If you mean a variable at the module level then you can use "globals":

if "var1" not in globals():
    var1 = 4

but the common Python idiom is to initialize it to say None (assuming that it's not an acceptable value) and then testing with if var1 is not None.

Generating Random Passwords

public string Sifre_Uret(int boy, int noalfa)
{

    //  01.03.2016   
    // Genel amaçli sifre üretme fonksiyonu


    //Fonskiyon 128 den büyük olmasina izin vermiyor.
    if (boy > 128 ) { boy = 128; }
    if (noalfa > 128) { noalfa = 128; }
    if (noalfa > boy) { noalfa = boy; }


    string passch = System.Web.Security.Membership.GeneratePassword(boy, noalfa);

    //URL encoding ve Url Pass + json sorunu yaratabilecekler pass ediliyor.
    //Microsoft Garanti etmiyor. Alfa Sayisallar Olabiliyorimis . !@#$%^&*()_-+=[{]};:<>|./?.
    //https://msdn.microsoft.com/tr-tr/library/system.web.security.membership.generatepassword(v=vs.110).aspx


    //URL ve Json ajax lar için filtreleme
    passch = passch.Replace(":", "z");
    passch = passch.Replace(";", "W");
    passch = passch.Replace("'", "t");
    passch = passch.Replace("\"", "r");
    passch = passch.Replace("/", "+");
    passch = passch.Replace("\\", "e");

    passch = passch.Replace("?", "9");
    passch = passch.Replace("&", "8");
    passch = passch.Replace("#", "D");
    passch = passch.Replace("%", "u");
    passch = passch.Replace("=", "4");
    passch = passch.Replace("~", "1");

    passch = passch.Replace("[", "2");
    passch = passch.Replace("]", "3");
    passch = passch.Replace("{", "g");
    passch = passch.Replace("}", "J");


    //passch = passch.Replace("(", "6");
    //passch = passch.Replace(")", "0");
    //passch = passch.Replace("|", "p");
    //passch = passch.Replace("@", "4");
    //passch = passch.Replace("!", "u");
    //passch = passch.Replace("$", "Z");
    //passch = passch.Replace("*", "5");
    //passch = passch.Replace("_", "a");

    passch = passch.Replace(",", "V");
    passch = passch.Replace(".", "N");
    passch = passch.Replace("+", "w");
    passch = passch.Replace("-", "7");





    return passch;



}

How to tackle daylight savings using TimeZone in Java

This is the problem to start with:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("EST"));

The 3-letter abbreviations should be wholeheartedly avoided in favour of TZDB zone IDs. EST is Eastern Standard Time - and Standard time never observes DST; it's not really a full time zone name. It's the name used for part of a time zone. (Unfortunately I haven't come across a good term for this "half time zone" concept.)

You want a full time zone name. For example, America/New_York is in the Eastern time zone:

TimeZone zone = TimeZone.getTimeZone("America/New_York");
DateFormat format = DateFormat.getDateTimeInstance();
format.setTimeZone(zone);

System.out.println(format.format(new Date()));

How do I pass data to Angular routed components?

Solution with ActiveRoute (if you want pass object by route - use JSON.stringfy/JSON.parse):

Prepare object before sending:

export class AdminUserListComponent {

  users : User[];

  constructor( private router : Router) { }

  modifyUser(i) {

    let navigationExtras: NavigationExtras = {
      queryParams: {
          "user": JSON.stringify(this.users[i])
      }
    };

    this.router.navigate(["admin/user/edit"],  navigationExtras);
  }

}

Receive your object in destination component:

export class AdminUserEditComponent  {

  userWithRole: UserWithRole;      

  constructor( private route: ActivatedRoute) {}

  ngOnInit(): void {
    super.ngOnInit();

      this.route.queryParams.subscribe(params => {
        this.userWithRole.user = JSON.parse(params["user"]);
      });
  }

}

Best way to implement keyboard shortcuts in a Windows Forms application?

You probably forgot to set the form's KeyPreview property to True. Overriding the ProcessCmdKey() method is the generic solution:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
  if (keyData == (Keys.Control | Keys.F)) {
    MessageBox.Show("What the Ctrl+F?");
    return true;
  }
  return base.ProcessCmdKey(ref msg, keyData);
}

Control the dashed border stroke length and distance between strokes

I just recently had the same problem. I have made this work around, hope it will help someone.

HTML + tailwind

<div class="dashed-border h-14 w-full relative rounded-lg">
    <div class="w-full h-full rounded-lg bg-page z-10 relative">
        Content goes here...
    <div>
</div>

CSS

.dashed-border::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  width: 100%;
  height: calc(100% + 4px);
  transform: translateY(-50%);
  background-image: linear-gradient(to right, #333 50%, transparent 50%);
  background-size: 16px;
  z-index: 0;
  border-radius: 0.5rem;
}
.dashed-border::after {
  content: '';
  position: absolute;
  left: 50%;
  top: 0;
  height: 100%;
  width: calc(100% + 4px);
  transform: translateX(-50%);
  background-image: linear-gradient(to bottom, #333 50%, transparent 50%);
  background-size: 4px 16px;
  z-index: 1;
  border-radius: 0.5rem;
}

iPad Safari scrolling causes HTML elements to disappear and reappear with a delay

This is the complete answer to my question. I had originally marked @Colin Williams' answer as the correct answer, as it helped me get to the complete solution. A community member, @Slipp D. Thompson edited my question, after about 2.5 years of me having asked it, and told me I was abusing SO's Q & A format. He also told me to separately post this as the answer. So here's the complete answer that solved my problem:

@Colin Williams, thank you! Your answer and the article you linked out to gave me a lead to try something with CSS.

So, I was using translate3d before. It produced unwanted results. Basically, it would chop off and NOT RENDER elements that were offscreen, until I interacted with them. So, basically, in landscape orientation, half of my site that was offscreen was not being shown. This is a iPad web app, owing to which I was in a fix.

Applying translate3d to relatively positioned elements solved the problem for those elements, but other elements stopped rendering, once offscreen. The elements that I couldn't interact with (artwork) would never render again, unless I reloaded the page.

The complete solution:

*:not(html) {
    -webkit-transform: translate3d(0, 0, 0);
}

Now, although this might not be the most "efficient" solution, it was the only one that works. Mobile Safari does not render the elements that are offscreen, or sometimes renders erratically, when using -webkit-overflow-scrolling: touch. Unless a translate3d is applied to all other elements that might go offscreen owing to that scroll, those elements will be chopped off after scrolling.

So, thanks again, and hope this helps some other lost soul. This surely helped me big time!

Compare two List<T> objects for equality, ignoring order

This worked for me:
If you are comparing two lists of objects depend upon single entity like ID, and you want a third list which matches that condition, then you can do the following:

var list3 = List1.Where(n => !List2.select(n1 => n1.Id).Contains(n.Id));

Refer: MSDN - C# Compare Two lists of objects

Regular Expression to select everything before and up to a particular text

Up to and including txt you would need to change your regex like so:

^(.*?\\.txt)

'react-scripts' is not recognized as an internal or external command

I have tried many of the solutions to this problem found on line, but in my case nothing worked except for reinstalling NVM for Windows (which I am using to manage multiple Node versions). In the installer, it detects installed Node versions and asks the user if they wish for NVM to control them. I said yes and NVM fixed all PATH issues. As a result, things worked as before. This issue may have multiple causes, but corrupted PATH is definitely one of them and (re)installing NVM fixes PATH.

Display HTML form values in same page after submit using Ajax

_x000D_
_x000D_
var tasks = [];_x000D_
var descs = [];_x000D_
_x000D_
// Get the modal_x000D_
var modal = document.getElementById('myModal');_x000D_
_x000D_
// Get the button that opens the modal_x000D_
var btn = document.getElementById("myBtn");_x000D_
_x000D_
// Get the <span> element that closes the modal_x000D_
var span = document.getElementsByClassName("close")[0];_x000D_
_x000D_
// When the user clicks the button, open the modal _x000D_
btn.onclick = function() {_x000D_
  modal.style.display = "block";_x000D_
}_x000D_
_x000D_
// When the user clicks on <span> (x), close the modal_x000D_
span.onclick = function() {_x000D_
  modal.style.display = "none";_x000D_
}_x000D_
_x000D_
// When the user clicks anywhere outside of the modal, close it_x000D_
window.onclick = function(event) {_x000D_
  if (event.target == modal) {_x000D_
    modal.style.display = "none";_x000D_
  }_x000D_
}_x000D_
var rowCount = 1;_x000D_
_x000D_
function addTasks() {_x000D_
  var temp = 'style .fa fa-trash';_x000D_
  tasks.push(document.getElementById("taskname").value);_x000D_
  descs.push(document.getElementById("taskdesc").value);_x000D_
  var table = document.getElementById("tasksTable");_x000D_
  var row = table.insertRow(rowCount);_x000D_
  var cell1 = row.insertCell(0);_x000D_
  var cell2 = row.insertCell(1);_x000D_
  var cell3 = row.insertCell(2);_x000D_
  var cell4 = row.insertCell(3);_x000D_
  cell1.innerHTML = tasks[rowCount - 1];_x000D_
  cell2.innerHTML = descs[rowCount - 1];_x000D_
  cell3.innerHTML = getDate();_x000D_
  cell4.innerHTML = '<td class="fa fa-trash"></td>';_x000D_
  rowCount++;_x000D_
  modal.style.display = "none";_x000D_
}_x000D_
_x000D_
_x000D_
function getDate() {_x000D_
  var today = new Date();_x000D_
  var dd = today.getDate();_x000D_
  var mm = today.getMonth() + 1; //January is 0!_x000D_
_x000D_
  var yyyy = today.getFullYear();_x000D_
_x000D_
  if (dd < 10) {_x000D_
    dd = '0' + dd;_x000D_
  }_x000D_
  if (mm < 10) {_x000D_
    mm = '0' + mm;_x000D_
  }_x000D_
  var today = dd + '-' + mm + '-' + yyyy.toString().slice(2);_x000D_
  return today;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
  <!-- Trigger/Open The Modal -->_x000D_
  <div style="background-color:#0F0F8C ;height:45px">_x000D_
    <h2 style="color: white">LOGO</h2>_x000D_
  </div>_x000D_
  <div>_x000D_
    <button id="myBtn">&emsp;+ Add Task &emsp;</button>_x000D_
  </div>_x000D_
  <div>_x000D_
    <table id="tasksTable">_x000D_
      <thead>_x000D_
        <tr style="background-color:rgba(201, 196, 196, 0.86)">_x000D_
          <th style="width: 150px;">Name</th>_x000D_
          <th style="width: 250px;">Desc</th>_x000D_
          <th style="width: 120px">Date</th>_x000D_
          <th style="width: 120px class=fa fa-trash"></th>_x000D_
        </tr>_x000D_
_x000D_
      </thead>_x000D_
      <tbody></tbody>_x000D_
    </table>_x000D_
  </div>_x000D_
  <!-- The Modal -->_x000D_
  <div id="myModal" class="modal">_x000D_
_x000D_
    <!-- Modal content -->_x000D_
    <div class="modal-content">_x000D_
_x000D_
      <div class="modal-header">_x000D_
_x000D_
        <span class="close">&times;</span>_x000D_
        <h3> Add Task</h3>_x000D_
      </div>_x000D_
_x000D_
      <div class="modal-body">_x000D_
        <table style="padding: 28px 50px">_x000D_
          <tr>_x000D_
            <td style="width:150px">Name:</td>_x000D_
            <td><input type="text" name="name" id="taskname" style="width: -webkit-fill-available"></td>_x000D_
          </tr>_x000D_
          <tr>_x000D_
            <td>_x000D_
              Desc:_x000D_
            </td>_x000D_
            <td>_x000D_
              <textarea name="desc" id="taskdesc" cols="60" rows="10"></textarea>_x000D_
            </td>_x000D_
          </tr>_x000D_
        </table>_x000D_
      </div>_x000D_
_x000D_
      <div class="modal-footer">_x000D_
        <button type="submit" value="submit" style="float: right;" onclick="addTasks()">SUBMIT</button>_x000D_
        <br>_x000D_
        <br>_x000D_
        <br>_x000D_
      </div>_x000D_
_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Create an array of integers property in Objective-C

This should work:

@interface MyClass
{
    int _doubleDigits[10]; 
}

@property(readonly) int *doubleDigits;

@end

@implementation MyClass

- (int *)doubleDigits
{
    return _doubleDigits;
}

@end

How do you determine a processing time in Python?

If all you want is the time between two points in code (and it seems that's what you want) I have written tic() toc() functions ala Matlab's implementation. The basic use case is:

tic()

''' some code that runs for an interesting amount of time '''

toc()

# OUTPUT:
# Elapsed time is: 32.42123 seconds

Super, incredibly easy to use, a sort of fire-and-forget kind of code. It's available on Github's Gist https://gist.github.com/tyleha/5174230

OpenCV Python rotate image by X degrees around specific point

Here's an example for rotating about an arbitrary point (x,y) using only openCV

def rotate_about_point(x, y, degree, image):
    rot_mtx = cv.getRotationMatrix2D((x, y), angle, 1)
    abs_cos = abs(rot_mtx[0, 0])
    abs_sin = abs(rot_mtx[0, 1])
    rot_wdt = int(frm_hgt * abs_sin + frm_wdt * abs_cos)
    rot_hgt = int(frm_hgt * abs_cos + frm_wdt * abs_sin)
    rot_mtx += np.asarray([[0, 0, -lftmost_x],
                           [0, 0, -topmost_y]])
    rot_img = cv.warpAffine(image, rot_mtx, (rot_wdt, rot_hgt),
                            borderMode=cv.BORDER_CONSTANT)
    return rot_img

How do I display local image in markdown?

The best solution is to provide a path relative to the folder where the md document is located.

Probably a browser is in trouble when it tries to resolve the absolute path of a local file. That can be solved by accessing the file trough a webserver, but even in that situation, the image path has to be right.

Having a folder at the same level of the document, containing all the images, is the cleanest and safest solution. It will load on GitHub, local, local webserver.

images_folder/img.jpg  < works


/images_folder/img.jpg  < this will work on webserver's only (please read the note!)

Using the absolute path, the image will be accessible only with a url like this: http://hostname.doesntmatter/image_folder/img.jpg

How to use SQL LIKE condition with multiple values in PostgreSQL?

Following query helped me. Instead of using LIKE, you can use ~*.

select id, name from hosts where name ~* 'julia|lena|jack';

How do you log content of a JSON object in Node.js?

Try this one:

console.log("Session: %j", session);

If the object could be converted into JSON, that will work.

ASP.net Getting the error "Access to the path is denied." while trying to upload files to my Windows Server 2008 R2 Web server

Verify what are you attempting to write. I was having the same issue, but I realized i was trying to write a byte array with length of 0.

It doesn't make sense to me, but I get: "Access to the path "

Find non-ASCII characters in varchar columns using SQL Server

running the various solutions on some real world data - 12M rows varchar length ~30, around 9k dodgy rows, no full text index in play, the patIndex solution is the fastest, and it also selects the most rows.

(pre-ran km. to set the cache to a known state, ran the 3 processes, and finally ran km again - the last 2 runs of km gave times within 2 seconds)

patindex solution by Gerhard Weiss -- Runtime 0:38, returns 9144 rows

select dodgyColumn from myTable fcc
WHERE  patindex('%[^ !-~]%' COLLATE Latin1_General_BIN,dodgyColumn ) >0

the substring-numbers solution by MT. -- Runtime 1:16, returned 8996 rows

select dodgyColumn from myTable fcc
INNER JOIN dbo.Numbers32k dn ON dn.number<(len(fcc.dodgyColumn ))
WHERE ASCII(SUBSTRING(fcc.dodgyColumn , dn.Number, 1))<32 
    OR ASCII(SUBSTRING(fcc.dodgyColumn , dn.Number, 1))>127

udf solution by Deon Robertson -- Runtime 3:47, returns 7316 rows

select dodgyColumn 
from myTable 
where dbo.udf_test_ContainsNonASCIIChars(dodgyColumn , 1) = 1

Call to undefined function App\Http\Controllers\ [ function name ]

If they are in the same controller class, it would be:

foreach ( $characters as $character) {
    $num += $this->getFactorial($index) * $index;
    $index ++;
}

Otherwise you need to create a new instance of the class, and call the method, ie:

$controller = new MyController();
foreach ( $characters as $character) {
    $num += $controller->getFactorial($index) * $index;
    $index ++;
}

Trim last 3 characters of a line WITHOUT using sed, or perl, etc

what do you mean don't want to use sed/awk for speed purposes? sed/awk are faster than the shell's while read loop for processing files.

$ sed 's/[ \t]*\*$//' file
1234567890
1234567891

$ sed 's/..\*$//' file
1234567890
1234567891

with bash shell

while read -r a b
do
 echo $a
done <file

How to start and stop android service from a adb shell?

You should set the android:exported attribute of the service to "true", in order to allow other components to invoke it. In the AndroidManifest.xml file, add the following attribute:

<service android:exported="true" ></service>

Then, you should be able to start the service via adb:

adb shell am startservice com.package.name/.YourServiceName

For more info about the android:exported attribute see this page.

Internal Error 500 Apache, but nothing in the logs?

Please Note: The original poster was not specifically asking about PHP. All the php centric answers make large assumptions not relevant to the actual question.

The default error log as opposed to the scripts error logs usually has the (more) specific error. often it will be permissions denied or even an interpreter that can't be found.

This means the fault almost always lies with your script. e.g you uploaded a perl script but didnt give it execute permissions? or perhaps it was corrupted in a linux environment if you write the script in windows and then upload it to the server without the line endings being converted you will get this error.

in perl if you forget

print "content-type: text/html\r\n\r\n";

you will get this error

There are many reasons for it. so please first check your error log and then provide some more information.

The default error log is often in /var/log/httpd/error_log or /var/log/apache2/error.log.

The reason you look at the default error logs (as indicated above) is because errors don't always get posted into the custom error log as defined in the virtual host.

Assumes linux and not necessarily perl

Do I need to compile the header files in a C program?

I think we do need preprocess(maybe NOT call the compile) the head file. Because from my understanding, during the compile stage, the head file should be included in c file. For example, in test.h we have

typedef enum{
    a,
    b,
    c
}test_t

and in test.c we have

void foo()
{
    test_t test;
    ...
}

during the compile, i think the compiler will put the code in head file and c file together and code in head file will be pre-processed and substitute the code in c file. Meanwhile, we'd better to define the include path in makefile.

Change selected value of kendo ui dropdownlist

It's possible to "natively" select by value:

dropdownlist.select(1);

AngularJS : Clear $watch

Ideally, every custom watch should be removed when you leave the scope.

It helps in better memory management and better app performance.

// call to $watch will return a de-register function
var listener = $scope.$watch(someVariableToWatch, function(....));

$scope.$on('$destroy', function() {
    listener(); // call the de-register function on scope destroy
});

CSS text-overflow in a table cell?

It seems that if you specify table-layout: fixed; on the table element, then your styles for td should take effect. This will also affect how the cells are sized, though.

Sitepoint discusses the table-layout methods a little here: http://reference.sitepoint.com/css/tableformatting

How do I concatenate const/literal strings in C?

In C, "strings" are just plain char arrays. Therefore, you can't directly concatenate them with other "strings".

You can use the strcat function, which appends the string pointed to by src to the end of the string pointed to by dest:

char *strcat(char *dest, const char *src);

Here is an example from cplusplus.com:

char str[80];
strcpy(str, "these ");
strcat(str, "strings ");
strcat(str, "are ");
strcat(str, "concatenated.");

For the first parameter, you need to provide the destination buffer itself. The destination buffer must be a char array buffer. E.g.: char buffer[1024];

Make sure that the first parameter has enough space to store what you're trying to copy into it. If available to you, it is safer to use functions like: strcpy_s and strcat_s where you explicitly have to specify the size of the destination buffer.

Note: A string literal cannot be used as a buffer, since it is a constant. Thus, you always have to allocate a char array for the buffer.

The return value of strcat can simply be ignored, it merely returns the same pointer as was passed in as the first argument. It is there for convenience, and allows you to chain the calls into one line of code:

strcat(strcat(str, foo), bar);

So your problem could be solved as follows:

char *foo = "foo";
char *bar = "bar";
char str[80];
strcpy(str, "TEXT ");
strcat(str, foo);
strcat(str, bar);

How to find files modified in last x minutes (find -mmin does not work as expected)

I can reproduce your problem if there are no files in the directory that were modified in the last hour. In that case, find . -mmin -60 returns nothing. The command find . -mmin -60 |xargs ls -l, however, returns every file in the directory which is consistent with what happens when ls -l is run without an argument.

To make sure that ls -l is only run when a file is found, try:

find . -mmin -60 -type f -exec ls -l {} +

How do I replace a character at a particular index in JavaScript?

In Javascript strings are immutable so you have to do something like

var x = "Hello world"
x = x.substring(0, i) + 'h' + x.substring(i+1);

To replace the character in x at i with 'h'

How do I remove documents using Node.js Mongoose?

Update: .remove() is depreciated but this still works for older versions

YourSchema.remove({
    foo: req.params.foo
}, function(err, _) {
    if (err) return res.send(err)
    res.json({
        message: `deleted ${ req.params.foo }`
    })
});

Generating 8-character only UUIDs

I do not think that it is possible but you have a good workaround.

  1. cut the end of your UUID using substring()
  2. use code new Random(System.currentTimeMillis()).nextInt(99999999); this will generate random ID up to 8 characters long.
  3. generate alphanumeric id:

    char[] chars = "abcdefghijklmnopqrstuvwxyzABSDEFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray();
    Random r = new Random(System.currentTimeMillis());
    char[] id = new char[8];
    for (int i = 0;  i < 8;  i++) {
        id[i] = chars[r.nextInt(chars.length)];
    }
    return new String(id);
    

JavaScript: Class.method vs. Class.prototype.method

Yes, the first function has no relationship with an object instance of that constructor function, you can consider it like a 'static method'.

In JavaScript functions are first-class objects, that means you can treat them just like any object, in this case, you are only adding a property to the function object.

The second function, as you are extending the constructor function prototype, it will be available to all the object instances created with the new keyword, and the context within that function (the this keyword) will refer to the actual object instance where you call it.

Consider this example:

// constructor function
function MyClass () {
  var privateVariable; // private member only available within the constructor fn

  this.privilegedMethod = function () { // it can access private members
    //..
  };
}

// A 'static method', it's just like a normal function 
// it has no relation with any 'MyClass' object instance
MyClass.staticMethod = function () {};

MyClass.prototype.publicMethod = function () {
  // the 'this' keyword refers to the object instance
  // you can access only 'privileged' and 'public' members
};

var myObj = new MyClass(); // new object instance

myObj.publicMethod();
MyClass.staticMethod();

Struct with template variables in C++

The problem is you can't template a typedef, also there is no need to typedef structs in C++.

The following will do what you need

template <typename T> 
struct array { 
  size_t x; 
  T *ary; 
}; 

How to use OpenFileDialog to select a folder?

this should be the most obvious and straight forward way

using (var dialog = new System.Windows.Forms.FolderBrowserDialog())
{

   System.Windows.Forms.DialogResult result = dialog.ShowDialog();

   if(result == System.Windows.Forms.DialogResult.OK)
   {
      selectedFolder = dialog.SelectedPath;
   }

}

What datatype to use when storing latitude and longitude data in SQL databases?

You can easily store a lat/lon decimal number in an unsigned integer field, instead of splitting them up in a integer and decimal part and storing those separately as somewhat suggested here using the following conversion algorithm:

as a stored mysql function:

CREATE DEFINER=`r`@`l` FUNCTION `PositionSmallToFloat`(s INT) 
RETURNS decimal(10,7)
DETERMINISTIC
RETURN if( ((s > 0) && (s >> 31)) , (-(0x7FFFFFFF - 
(s & 0x7FFFFFFF))) / 600000, s / 600000)

and back

CREATE DEFINER=`r`@`l` FUNCTION `PositionFloatToSmall`(s DECIMAL(10,7)) 
RETURNS int(10)
DETERMINISTIC
RETURN s * 600000

That needs to be stored in an unsigned int(10), this works in mysql as well as in sqlite which is typeless.

through experience, I find that this works really fast, if all you need to to is store coordinates and retrieve those to do some math with.

in php those 2 functions look like

function LatitudeSmallToFloat($LatitudeSmall){
   if(($LatitudeSmall>0)&&($LatitudeSmall>>31)) 
     $LatitudeSmall=-(0x7FFFFFFF-($LatitudeSmall&0x7FFFFFFF))-1;
   return (float)$LatitudeSmall/(float)600000;
}

and back again:

function LatitudeFloatToSmall($LatitudeFloat){
   $Latitude=round((float)$LatitudeFloat*(float)600000);
   if($Latitude<0) $Latitude+=0xFFFFFFFF;
   return $Latitude;
}

This has some added advantage as well in term of creating for example memcached unique keys with integers. (ex: to cache a geocode result). Hope this adds value to the discussion.

Another application could be when you are without GIS extensions and simply want to keep a few million of those lat/lon pairs, you can use partitions on those fields in mysql to benefit from the fact they are integers:

Create Table: CREATE TABLE `Locations` (
  `lat` int(10) unsigned NOT NULL,
  `lon` int(10) unsigned NOT NULL,
  `location` text,
  PRIMARY KEY (`lat`,`lon`) USING BTREE,
  KEY `index_location` (`locationText`(30))
) ENGINE=InnoDB DEFAULT CHARSET=utf8
/*!50100 PARTITION BY KEY ()
PARTITIONS 100 */

svn over HTTP proxy

In /etc/subversion/servers you are setting http-proxy-host, which has nothing to do with svn:// which connects to a different server usually running on port 3690 started by svnserve command.

If you have access to the server, you can setup svn+ssh:// as explained here.

Update: You could also try using connect-tunnel, which uses your HTTPS proxy server to tunnel connections:

connect-tunnel -P proxy.company.com:8080 -T 10234:svn.example.com:3690

Then you would use

svn checkout svn://localhost:10234/path/to/trunk

Python method for reading keypress?

I was also trying to achieve this. From above codes, what I understood was that you can call getch() function multiple times in order to get both bytes getting from the function. So the ord() function is not necessary if you are just looking to use with byte objects.

while True :
    if m.kbhit() :
        k = m.getch()
        if b'\r' == k :
            break
        elif k == b'\x08'or k == b'\x1b':
            # b'\x08' => BACKSPACE
            # b'\x1b' => ESC
            pass
        elif k == b'\xe0' or k == b'\x00':
            k = m.getch()
            if k in [b'H',b'M',b'K',b'P',b'S',b'\x08']:
                # b'H' => UP ARROW
                # b'M' => RIGHT ARROW
                # b'K' => LEFT ARROW
                # b'P' => DOWN ARROW
                # b'S' => DELETE
                pass
            else:
                print(k.decode(),end='')
        else:
            print(k.decode(),end='')

This code will work print any key until enter key is pressed in CMD or IDE (I was using VS CODE) You can customize inside the if for specific keys if needed

How to get the list of all database users

SELECT name FROM sys.database_principals WHERE
type_desc = 'SQL_USER' AND default_schema_name = 'dbo'

This selects all the users in the SQL server that the administrator created!

Upload File With Ajax XmlHttpRequest

  1. There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.
  2. xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

    var formData = new FormData();
    formData.append("thefile", file);
    xhr.send(formData);
    

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.

From an array of objects, extract value of a property as array

Function map is a good choice when dealing with object arrays. Although there have been a number of good answers posted already, the example of using map with combination with filter might be helpful.

In case you want to exclude the properties which values are undefined or exclude just a specific property, you could do the following:

    var obj = {value1: "val1", value2: "val2", Ndb_No: "testing", myVal: undefined};
    var keysFiltered = Object.keys(obj).filter(function(item){return !(item == "Ndb_No" || obj[item] == undefined)});
    var valuesFiltered = keysFiltered.map(function(item) {return obj[item]});

https://jsfiddle.net/ohea7mgk/

javax.servlet.ServletException cannot be resolved to a type in spring web app

<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.3.2-b02</version>
    <scope>provided</scope>
</dependency>

worked for me.

Using success/error/finally/catch with Promises in AngularJS

I do it like Bradley Braithwaite suggests in his blog:

app
    .factory('searchService', ['$q', '$http', function($q, $http) {
        var service = {};

        service.search = function search(query) {
            // We make use of Angular's $q library to create the deferred instance
            var deferred = $q.defer();

            $http
                .get('http://localhost/v1?=q' + query)
                .success(function(data) {
                    // The promise is resolved once the HTTP call is successful.
                    deferred.resolve(data);
                })
                .error(function(reason) {
                    // The promise is rejected if there is an error with the HTTP call.
                    deferred.reject(reason);
                });

            // The promise is returned to the caller
            return deferred.promise;
        };

        return service;
    }])
    .controller('SearchController', ['$scope', 'searchService', function($scope, searchService) {
        // The search service returns a promise API
        searchService
            .search($scope.query)
            .then(function(data) {
                // This is set when the promise is resolved.
                $scope.results = data;
            })
            .catch(function(reason) {
                // This is set in the event of an error.
                $scope.error = 'There has been an error: ' + reason;
            });
    }])

Key Points:

  • The resolve function links to the .then function in our controller i.e. all is well, so we can keep our promise and resolve it.

  • The reject function links to the .catch function in our controller i.e. something went wrong, so we can’t keep our promise and need to reject it.

It is quite stable and safe and if you have other conditions to reject the promise you can always filter your data in the success function and call deferred.reject(anotherReason) with the reason of the rejection.

As Ryan Vice suggested in the comments, this may not be seen as useful unless you fiddle a bit with the response, so to speak.

Because success and error are deprecated since 1.4 maybe it is better to use the regular promise methods then and catch and transform the response within those methods and return the promise of that transformed response.

I am showing the same example with both approaches and a third in-between approach:

success and error approach (success and error return a promise of an HTTP response, so we need the help of $q to return a promise of data):

function search(query) {
  // We make use of Angular's $q library to create the deferred instance
  var deferred = $q.defer();

  $http.get('http://localhost/v1?=q' + query)
  .success(function(data,status) {
    // The promise is resolved once the HTTP call is successful.
    deferred.resolve(data);              
  })

  .error(function(reason,status) {
    // The promise is rejected if there is an error with the HTTP call.
    if(reason.error){
      deferred.reject({text:reason.error, status:status});
    }else{
      //if we don't get any answers the proxy/api will probably be down
      deferred.reject({text:'whatever', status:500});
    }
  });

  // The promise is returned to the caller
  return deferred.promise;
};

then and catch approach (this is a bit more difficult to test, because of the throw):

function search(query) {

  var promise=$http.get('http://localhost/v1?=q' + query)

  .then(function (response) {
    // The promise is resolved once the HTTP call is successful.
    return response.data;
  },function(reason) {
    // The promise is rejected if there is an error with the HTTP call.
    if(reason.statusText){
      throw reason;
    }else{
      //if we don't get any answers the proxy/api will probably be down
      throw {statusText:'Call error', status:500};
    }

  });

  return promise;
}

There is a halfway solution though (this way you can avoid the throw and anyway you'll probably need to use $q to mock the promise behavior in your tests):

function search(query) {
  // We make use of Angular's $q library to create the deferred instance
  var deferred = $q.defer();

  $http.get('http://localhost/v1?=q' + query)

  .then(function (response) {
    // The promise is resolved once the HTTP call is successful.
    deferred.resolve(response.data);
  },function(reason) {
    // The promise is rejected if there is an error with the HTTP call.
    if(reason.statusText){
      deferred.reject(reason);
    }else{
      //if we don't get any answers the proxy/api will probably be down
      deferred.reject({statusText:'Call error', status:500});
    }

  });

  // The promise is returned to the caller
  return deferred.promise;
}

Any kind of comments or corrections are welcome.

How does java do modulus calculations with negative numbers?

Your result is wrong for Java. Please provide some context how you arrived at it (your program, implementation and version of Java).

From the Java Language Specification

15.17.3 Remainder Operator %
[...]
The remainder operation for operands that are integers after binary numeric promotion (§5.6.2) produces a result value such that (a/b)*b+(a%b) is equal to a.
15.17.2 Division Operator /
[...]
Integer division rounds toward 0.

Since / is rounded towards zero (resulting in zero), the result of % should be negative in this case.

Convert Rows to columns using 'Pivot' in SQL Server

This is what you can do:

SELECT * 
FROM yourTable
PIVOT (MAX(xCount) 
       FOR Week in ([1],[2],[3],[4],[5],[6],[7])) AS pvt

DEMO

Best practice for Django project working directory structure

I don't like to create a new settings/ directory. I simply add files named settings_dev.py and settings_production.py so I don't have to edit the BASE_DIR. The approach below increase the default structure instead of changing it.

mysite/                   # Project
    conf/
        locale/
            en_US/
            fr_FR/
            it_IT/
    mysite/
        __init__.py
        settings.py
        settings_dev.py
        settings_production.py
        urls.py
        wsgi.py
    static/
        admin/
            css/           # Custom back end styles
        css/               # Project front end styles
        fonts/
        images/
        js/
        sass/
    staticfiles/
    templates/             # Project templates
        includes/
            footer.html
            header.html
        index.html
    myapp/                 # Application
        core/
        migrations/
            __init__.py
        templates/         # Application templates
            myapp/
                index.html
        static/
            myapp/
                js/  
                css/
                images/
        __init__.py
        admin.py
        apps.py
        forms.py
        models.py
        models_foo.py
        models_bar.py
        views.py
    templatetags/          # Application with custom context processors and template tags
        __init__.py
        context_processors.py
        templatetags/
            __init__.py
            templatetag_extras.py
    gulpfile.js
    manage.py
    requirements.txt

I think this:

    settings.py
    settings_dev.py
    settings_production.py

is better than this:

    settings/__init__.py
    settings/base.py
    settings/dev.py
    settings/production.py

This concept applies to other files as well.


I usually place node_modules/ and bower_components/ in the project directory within the default static/ folder.

Sometime a vendor/ directory for Git Submodules but usually I place them in the static/ folder.

int to unsigned int conversion

This conversion is well defined and will yield the value UINT_MAX - 61. On a platform where unsigned int is a 32-bit type (most common platforms, these days), this is precisely the value that others are reporting. Other values are possible, however.

The actual language in the standard is

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2^n where n is the number of bits used to represent the unsigned type).

SQL Server - after insert trigger - update another column in the same table

Yes, it will recursively call your trigger unless you turn the recursive triggers setting off:

ALTER DATABASE db_name SET RECURSIVE_TRIGGERS OFF 

MSDN has a good explanation of the behavior at http://msdn.microsoft.com/en-us/library/aa258254(SQL.80).aspx under the Recursive Triggers heading.

How do I execute a MS SQL Server stored procedure in java/jsp, returning table data?

Frequently we deal with other fellow java programmers work which create these Stored Procedure. and we do not want to mess around with it. but there is possibility you get the result set where these exec sample return 0 (almost Stored procedure call returning zero).

check this sample :

public void generateINOUT(String USER, int DPTID){

    try {


        conUrl = JdbcUrls + dbServers +";databaseName="+ dbSrcNames+";instance=MSSQLSERVER";

        con = DriverManager.getConnection(conUrl,dbUserNames,dbPasswords);
        //stat = con.createStatement();
        con.setAutoCommit(false); 
        Statement st = con.createStatement(); 

        st.executeUpdate("DECLARE @RC int\n" +
                "DECLARE @pUserID nvarchar(50)\n" +
                "DECLARE @pDepartmentID int\n" +
                "DECLARE @pStartDateTime datetime\n" +
                "DECLARE @pEndDateTime datetime\n" +
                "EXECUTE [AccessManager].[dbo].[SP_GenerateInOutDetailReportSimple] \n" +
                ""+USER +
                "," +DPTID+
                ",'"+STARTDATE +
                "','"+ENDDATE+"'");

        ResultSet rs = st.getGeneratedKeys();

        while (rs.next()){
              String userID = rs.getString("UserID");
              Timestamp timeIN = rs.getTimestamp("timeIN");
              Timestamp timeOUT = rs.getTimestamp ("timeOUT");
              int totTime = rs.getInt ("totalTime");
              int pivot = rs.getInt ("pivotvalue");

              timeINS = sdz.format(timeIN);
              userIN.add(timeINS);

              timeOUTS = sdz.format(timeOUT);
              userOUT.add(timeOUTS);

              System.out.println("User : "+userID+" |IN : "+timeIN+" |OUT : "+timeOUT+"| Total Time : "+totTime+" | PivotValue : "+pivot);
        }

        con.commit();

    }catch (Exception e) {
        e.printStackTrace();
        System.out.println(e);
        if (e.getCause() != null) {
        e.getCause().printStackTrace();}
    }  
}

I came to this solutions after few days trial and error, googling and get confused ;) it execute below Stored Procedure :

USE [AccessManager]
GO
/****** Object:  StoredProcedure [dbo].[SP_GenerateInOutDetailReportSimple]    
Script Date: 04/05/2013 15:54:11 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO


ALTER PROCEDURE [dbo].[SP_GenerateInOutDetailReportSimple]
(
@pUserID nvarchar(50),
@pDepartmentID int,
@pStartDateTime datetime,
@pEndDateTime datetime
)
AS


Declare @ErrorCode int
Select @ErrorCode = @@Error

Declare @TransactionCountOnEntry int
If @ErrorCode = 0
Begin
    Select @TransactionCountOnEntry = @@TranCount
    BEGIN TRANSACTION
End


If @ErrorCode = 0
Begin       

    -- Create table variable instead of SQL temp table because report wont pick up the temp table
    DECLARE @tempInOutDetailReport TABLE
    (
        UserID nvarchar(50),
        LogDate datetime,   
        LogDay varchar(20), 
        TimeIN datetime,
        TimeOUT datetime,
        TotalTime int,
        RemarkTimeIn nvarchar(100),
        RemarkTimeOut nvarchar(100),
        TerminalIPTimeIn varchar(50),
        TerminalIPTimeOut varchar(50),
        TerminalSNTimeIn nvarchar(50),
        TerminalSNTimeOut nvarchar(50),
        PivotValue int
    )           

    -- Declare variables for the while loop
    Declare @LogUserID nvarchar(50)
    Declare @LogEventID nvarchar(50)
    Declare @LogTerminalSN nvarchar(50)
    Declare @LogTerminalIP nvarchar(50)
    Declare @LogRemark nvarchar(50)
    Declare @LogTimestamp datetime  
    Declare @LogDay nvarchar(20)

    -- Filter off userID, departmentID, StartDate and EndDate if specified, only process the remaining logs
    -- Note: order by user then timestamp
    Declare LogCursor Cursor For 
    Select distinct access_event_logs.USERID, access_event_logs.EVENTID, 
        access_event_logs.TERMINALSN, access_event_logs.TERMINALIP,
        access_event_logs.REMARKS, access_event_logs.LOCALTIMESTAMP, Datename(dw,access_event_logs.LOCALTIMESTAMP) AS WkDay
    From access_event_logs
        Left Join access_user on access_user.User_ID = access_event_logs.USERID
        Left Join access_user_dept on access_user.User_ID = access_user_dept.User_ID
    Where ((Dept_ID = @pDepartmentID) OR (@pDepartmentID IS NULL))
        And ((access_event_logs.USERID LIKE '%' + @pUserID + '%') OR (@pUserID IS NULL)) 
        And ((access_event_logs.LOCALTIMESTAMP >= @pStartDateTime ) OR (@pStartDateTime IS NULL)) 
        And ((access_event_logs.LOCALTIMESTAMP < DATEADD(day, 1, @pEndDateTime) ) OR (@pEndDateTime IS NULL)) 
        And (access_event_logs.USERID != 'UNKNOWN USER') -- Ignore UNKNOWN USER
    Order by access_event_logs.USERID, access_event_logs.LOCALTIMESTAMP

    Open LogCursor

    Fetch Next 
    From LogCursor
    Into @LogUserID, @LogEventID, @LogTerminalSN, @LogTerminalIP, @LogRemark, @LogTimestamp, @LogDay

    -- Temp storage for IN event details
    Declare @InEventUserID nvarchar(50)
    Declare @InEventDay nvarchar(20)
    Declare @InEventTimestamp datetime
    Declare @InEventRemark nvarchar(100)
    Declare @InEventTerminalIP nvarchar(50)
    Declare @InEventTerminalSN nvarchar(50)

    -- Temp storage for OUT event details
    Declare @OutEventUserID nvarchar(50)        
    Declare @OutEventTimestamp datetime
    Declare @OutEventRemark nvarchar(100)
    Declare @OutEventTerminalIP nvarchar(50)
    Declare @OutEventTerminalSN nvarchar(50)

    Declare @CurrentUser varchar(50) -- used to indicate when we change user group
    Declare @CurrentDay varchar(50) -- used to indicate when we change day
    Declare @FirstEvent int -- indicate the first event we received     
    Declare @ReceiveInEvent int -- indicate we have received an IN event
    Declare @PivotValue int -- everytime we change user or day - we reset it (reporting purpose), if same user..keep increment its value
    Declare @CurrTrigger varchar(50) -- used to keep track of the event of the current event log trigger it is handling 
    Declare @CurrTotalHours int -- used to keep track of total hours of the day of the user

    Declare @FirstInEvent datetime
    Declare @FirstInRemark nvarchar(100)
    Declare @FirstInTerminalIP nvarchar(50)
    Declare @FirstInTerminalSN nvarchar(50)
    Declare @FirstRecord int -- indicate another day of same user

    Set @PivotValue = 0 -- initialised
    Set @CurrentUser = '' -- initialised
    Set @FirstEvent = 1 -- initialised
    Set @ReceiveInEvent = 0 -- initialised  
    Set @CurrTrigger = '' -- Initialised    
    Set @CurrTotalHours = 0 -- initialised
    Set @FirstRecord = 1 -- initialised
    Set @CurrentDay = '' -- initialised

    While @@FETCH_STATUS = 0
    Begin
        -- use to track current log trigger
        Set @CurrTrigger =LOWER(@LogEventID)

        If (@CurrentUser != '' And @CurrentUser != @LogUserID) -- new batch of user
        Begin
            If @ReceiveInEvent = 1  -- previous IN event is not cleared (no OUT is found)
            Begin
                -- Check day
                If (@CurrentDay != @InEventDay) -- change to another day                    
                    Set @PivotValue = 0 -- Reset                        

                Else -- same day
                    Set @PivotValue = @PivotValue + 1 -- increment
                Set @CurrentDay = @InEventDay -- update the day

                -- invalid row (only has IN event)
                Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, RemarkTimeIn, TerminalIPTimeIn, 
                    TerminalSNTimeIn, PivotValue, LogDate )
                values( @InEventUserID, @InEventDay, @InEventTimestamp, @InEventRemark, @InEventTerminalIP, 
                    @InEventTerminalSN, @PivotValue, DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))                                                         
            End                 

            Set @FirstEvent = 1 -- Reset flag (we are having a new user group)
            Set @ReceiveInEvent = 0 -- Reset
            Set @PivotValue = 0 -- Reset
            --Set @CurrentDay = '' -- Reset
        End

        If LOWER(@LogEventID) = 'in' -- IN event
        Begin           
            If @ReceiveInEvent = 1  -- previous IN event is not cleared (no OUT is found)
            Begin
                -- Check day
                If (@CurrentDay != @InEventDay) -- change to another day
                Begin
                    Set @PivotValue = 0 -- Reset

                    --Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
                    --  RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
                    --  LogDate)
                    --values( @LogUserID, @CurrentDay, @FirstInEvent, @LogTimestamp,  @CurrTotalHours,
                    --  @FirstInRemark, @LogRemark, @FirstInTerminalIP, @LogTerminalIP, @FirstInTerminalSN, @LogTerminalSN, @PivotValue,
                    --  DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))  
                End
                Else
                    Set @PivotValue = @PivotValue + 1 -- increment
                Set @CurrentDay = @InEventDay -- update the day


                -- invalid row (only has IN event)
                Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, RemarkTimeIn, TerminalIPTimeIn, 
                    TerminalSNTimeIn, PivotValue, LogDate )
                values( @InEventUserID, @InEventDay, @InEventTimestamp, @InEventRemark, @InEventTerminalIP, 
                    @InEventTerminalSN, @PivotValue, DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))                     
            End         

            If((@CurrentDay != @LogDay And @CurrentDay != '') Or (@CurrentUser != @LogUserID And @CurrentUser != '') )
            Begin

                    Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
                        RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
                        LogDate)
                    values( @CurrentUser, @CurrentDay, @FirstInEvent, @OutEventTimestamp, @CurrTotalHours,
                        @FirstInRemark, @OutEventRemark, @FirstInTerminalIP, @OutEventTerminalIP, @FirstInTerminalSN, @LogTerminalSN, @PivotValue,
                        DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))      

                Set @FirstRecord = 1
            End
            -- Save it
            Set @InEventUserID = @LogUserID                         
            Set @InEventDay = @LogDay
            Set @InEventTimestamp = @LogTimeStamp
            Set @InEventRemark = @LogRemark
            Set @InEventTerminalIP = @LogTerminalIP
            Set @InEventTerminalSN = @LogTerminalSN

            If (@FirstRecord = 1) -- save for first in event record of the day
            Begin
                Set @FirstInEvent = @LogTimestamp
                Set @FirstInRemark = @LogRemark
                Set @FirstInTerminalIP = @LogTerminalIP
                Set @FirstInTerminalSN = @LogTerminalSN
                Set @CurrTotalHours = 0 --initialise total hours for another day
            End

            Set @FirstRecord = 0 -- no more first record of the day
            Set @ReceiveInEvent = 1 -- indicate we have received an "IN" event
            Set @FirstEvent = 0  -- no more "first" event
        End
        Else If LOWER(@LogEventID) = 'out' -- OUT event
        Begin
            If @FirstEvent = 1 -- the first OUT record when change users 
            Begin
                -- Check day
                If (@CurrentDay != @LogDay) -- change to another day
                    Set @PivotValue = 0 -- Reset
                Else
                    Set @PivotValue = @PivotValue + 1 -- increment
                Set @CurrentDay = @LogDay -- update the day

                -- Only an OUT event (no IN event) - invalid record but we show it anyway
                Insert into @tempInOutDetailReport( UserID, LogDay, TimeOUT, RemarkTimeOut, TerminalIPTimeOut, TerminalSNTimeOut,
                    PivotValue, LogDate )
                values( @LogUserID, @LogDay, @LogTimestamp, @LogRemark, @LogTerminalIP, @LogTerminalSN, @PivotValue,
                    DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @LogTimestamp)))                                              

                Set @FirstEvent = 0 -- not "first" anymore
            End
            Else -- Not first event
            Begin       

                If @ReceiveInEvent = 1 -- if there are IN event previously
                Begin           
                    -- Check day
                    If (@CurrentDay != @InEventDay) -- change to another day                        
                        Set @PivotValue = 0 -- Reset                        
                    Else
                        Set @PivotValue = @PivotValue + 1 -- increment
                    Set @CurrentDay = @InEventDay -- update the day     
                    Set @CurrTotalHours = @CurrTotalHours +  DATEDIFF(second,@InEventTimestamp, @LogTimeStamp) -- update total time             

                    Set @OutEventRemark = @LogRemark
                    Set @OutEventTerminalIP = @LogTerminalIP
                    Set @OutEventTerminalSN = @LogTerminalSN
                    Set @OutEventTimestamp = @LogTimestamp          
                    -- valid row
                    --Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
                    --  RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
                    --  LogDate)
                    --values( @LogUserID, @InEventDay, @InEventTimestamp, @LogTimestamp,  Datediff(second, @InEventTimestamp, @LogTimeStamp),
                    --  @InEventRemark, @LogRemark, @InEventTerminalIP, @LogTerminalIP, @InEventTerminalSN, @LogTerminalSN, @PivotValue,
                    --  DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))                      

                    Set @ReceiveInEvent = 0 -- Reset
                End
                Else -- no IN event previously
                Begin
                    -- Check day
                    If (@CurrentDay != @LogDay) -- change to another day
                        Set @PivotValue = 0 -- Reset
                    Else
                        Set @PivotValue = @PivotValue + 1 -- increment
                    Set @CurrentDay = @LogDay -- update the day                         

                    -- invalid row (only has OUT event)
                    Insert into @tempInOutDetailReport( UserID, LogDay, TimeOUT, RemarkTimeOut, TerminalIPTimeOut, TerminalSNTimeOut,
                        PivotValue, LogDate )
                    values( @LogUserID, @LogDay, @LogTimestamp, @LogRemark, @LogTerminalIP, @LogTerminalSN, @PivotValue,
                        DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @LogTimestamp)) )             
                End             
            End         
        End

        Set @CurrentUser = @LogUserID -- update user        

        Fetch Next 
        From LogCursor
        Into @LogUserID, @LogEventID, @LogTerminalSN, @LogTerminalIP, @LogRemark, @LogTimestamp, @LogDay
    End 

    -- Need to handle the last log if its IN log as it will not be processed by the while loop
    if @CurrTrigger='in'
    Begin 
    -- Check day
            If (@CurrentDay != @InEventDay) -- change to another day
                Set @PivotValue = 0 -- Reset
            Else -- same day
                Set @PivotValue = @PivotValue + 1 -- increment
            Set @CurrentDay = @InEventDay -- update the day

            -- invalid row (only has IN event)
            Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, RemarkTimeIn, TerminalIPTimeIn, 
                TerminalSNTimeIn, PivotValue, LogDate )
            values( @InEventUserID, @InEventDay, @InEventTimestamp, @InEventRemark, @InEventTerminalIP, 
                    @InEventTerminalSN, @PivotValue, DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))     
    End
    else if @CurrTrigger = 'out'
    Begin
        Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
        RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
        LogDate)
        values( @LogUserID, @CurrentDay, @FirstInEvent, @LogTimestamp,  @CurrTotalHours,
        @FirstInRemark, @LogRemark, @FirstInTerminalIP, @LogTerminalIP, @FirstInTerminalSN, @LogTerminalSN, @PivotValue,
        DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))  
    End

    Close LogCursor
    Deallocate LogCursor

    Select * 
    From @tempInOutDetailReport tempTable
        Left Join access_user on access_user.User_ID = tempTable.UserID
    Order By tempTable.UserID, LogDate


End



If @@TranCount > @TransactionCountOnEntry
Begin
     If @ErrorCode = 0
            COMMIT TRANSACTION
     Else
            ROLLBACK TRANSACTION
End

return @ErrorCode

you will get the "java SQL Code" by right click on stored procedure in your database. something like this :

DECLARE @RC int
DECLARE @pUserID nvarchar(50)
DECLARE @pDepartmentID int
DECLARE @pStartDateTime datetime
DECLARE @pEndDateTime datetime

-- TODO: Set parameter values here.

EXECUTE @RC = [AccessManager].[dbo].[SP_GenerateInOutDetailReportSimple] 
@pUserID,@pDepartmentID,@pStartDateTime,@pEndDateTime
GO

check the query String I've done, that is your homework ;) so sorry answering this long, this is my first answer since I register few weeks ago to get answer.

Firebase FCM notifications click_action payload

there is dual method for fcm fcm messaging notification and app notification in first your app reciever only message notification with body ,title and you can add color ,vibration not working,sound default. in 2nd you can full control what happen when you recieve message example onMessageReciever(RemoteMessage rMessage){ notification.setContentTitle(rMessage.getData().get("yourKey")); } you will recieve data with(yourKey) but that not from fcm message that from fcm cloud functions reguard

How to check for valid email address?

For check of email use email_validator

from email_validator import validate_email, EmailNotValidError

def check_email(email):
    try:
        v = validate_email(email)  # validate and get info
        email = v["email"]  # replace with normalized form
        print("True")
    except EmailNotValidError as e:
        # email is not valid, exception message is human-readable
        print(str(e))

check_email("test@gmailcom")

Connection Strings for Entity Framework

Unfortunately, combining multiple entity contexts into a single named connection isn't possible. If you want to use named connection strings from a .config file to define your Entity Framework connections, they will each have to have a different name. By convention, that name is typically the name of the context:

<add name="ModEntity" connectionString="metadata=res://*/ModEntity.csdl|res://*/ModEntity.ssdl|res://*/ModEntity.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=SomeServer;Initial Catalog=SomeCatalog;Persist Security Info=True;User ID=Entity;Password=SomePassword;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />
<add name="Entity" connectionString="metadata=res://*/Entity.csdl|res://*/Entity.ssdl|res://*/Entity.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=SOMESERVER;Initial Catalog=SOMECATALOG;Persist Security Info=True;User ID=Entity;Password=Entity;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />

However, if you end up with namespace conflicts, you can use any name you want and simply pass the correct name to the context when it is generated:

var context = new Entity("EntityV2");

Obviously, this strategy works best if you are using either a factory or dependency injection to produce your contexts.

Another option would be to produce each context's entire connection string programmatically, and then pass the whole string in to the constructor (not just the name).

// Get "Data Source=SomeServer..."
var innerConnectionString = GetInnerConnectionStringFromMachinConfig();
// Build the Entity Framework connection string.
var connectionString = CreateEntityConnectionString("Entity", innerConnectionString);
var context = new EntityContext(connectionString);

How about something like this:

Type contextType = typeof(test_Entities);
string innerConnectionString = ConfigurationManager.ConnectionStrings["Inner"].ConnectionString;
string entConnection = 
    string.Format(
        "metadata=res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl;provider=System.Data.SqlClient;provider connection string=\"{1}\"",
        contextType.Name,
        innerConnectionString);
object objContext = Activator.CreateInstance(contextType, entConnection);
return objContext as test_Entities; 

... with the following in your machine.config:

<add name="Inner" connectionString="Data Source=SomeServer;Initial Catalog=SomeCatalog;Persist Security Info=True;User ID=Entity;Password=SomePassword;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />

This way, you can use a single connection string for every context in every project on the machine.

Does JSON syntax allow duplicate keys in an object?

In C# if you deserialise to a Dictionary<string, string> it takes the last key value pair:

string json = @"{""a"": ""x"", ""a"": ""y""}";
var d = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
// { "a" : "y" }

if you try to deserialise to

class Foo
{
    [JsonProperty("a")]
    public string Bar { get; set; }

    [JsonProperty("a")]
    public string Baz { get; set; }
}

var f = JsonConvert.DeserializeObject<Foo>(json);

you get a Newtonsoft.Json.JsonSerializationException exception.

How to check for Is not Null And Is not Empty string in SQL server?

For some kind of reason my NULL values where of data length 8. That is why none of the abovementioned seemed to work. If you encounter the same problem, use the following code:

--Check the length of your NULL values
SELECT DATALENGTH(COLUMN) as length_column
FROM your_table

--Filter the length of your NULL values (8 is used as example)
WHERE DATALENGTH(COLUMN) > 8

How to set HTML5 required attribute in Javascript?

What matters isn't the attribute but the property, and its value is a boolean.

You can set it using

 document.getElementById("edName").required = true;

How to fix UITableView separator on iOS 7?

This is default by iOS7 design. try to do the below:

[tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];

You can set the 'Separator Inset' from the storyboard:

enter image description here

enter image description here

Logging POST data from $request_body

Ok. So finally I was able to log the post data and return a 200. It's kind of a hacky solution that I'm not too proud of which basically overrides the natural behavior for error_page, but my inexperience of nginx plus timelines lead me to this solution:

location /bk {
  if ($request_method != POST) {
    return 405;
  }
  proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_redirect off;
  proxy_pass $scheme://127.0.0.1:$server_port/success;
  log_format my_tracking $request_body;
  access_log  /mnt/logs/nginx/my_tracking.access.log my_tracking;
}
location /success {
  return 200;
}
error_page   500 502 503 504  /50x.html;
location = /50x.html {
  root   /var/www/nginx-default;
  log_format my_tracking $request_body;
  access_log  /mnt/logs/nginx/my_tracking.access.log my_tracking_2;
}

Now according to that config, it would seem that the proxy pass would return a 200 all the time. Occasionally I would get 500 but when I threw in an error_log to see what was going on, all of my request_body data was in there and I couldn't see a problem. So I caught that and wrote to the same log. Since nginx doesn't like the same name for the tracking variable, I just used my_tracking_2 and wrote to the same log as when it returns a 200. Definitely not the most elegant solution and I welcome any better solution. I've seen the post module, but in my scenario, I couldn't recompile from source.

Specify system property to Maven project

If your test and webapp are in the same Maven project, you can use a property in the project POM. Then you can filter certain files which will allow Maven to set the property in those files. There are different ways to filter, but the most common is during the resources phase - http://books.sonatype.com/mvnref-book/reference/resource-filtering-sect-description.html

If the test and webapp are in different Maven projects, you can put the property in settings.xml, which is in your maven repository folder (C:\Documents and Settings\username.m2) on Windows. You will still need to use filtering or some other method to read the property into your test and webapp.

Editor does not contain a main type

Add a main method method inside the class to overcome this problem. I was facing the same issue regarding this.Now Including the main method inside my code i resolved my problem.

Can Mysql Split a column?

As an addendum to this, I've strings of the form: Some words 303

where I'd like to split off the numerical part from the tail of the string. This seems to point to a possible solution:

http://lists.mysql.com/mysql/222421

The problem however, is that you only get the answer "yes, it matches", and not the start index of the regexp match.

Can an interface extend multiple interfaces in Java?

An interface can extend multiple interfaces.

A class can implement multiple interfaces.

However, a class can only extend a single class.

Careful how you use the words extends and implements when talking about interface and class.

How to determine a user's IP address in node

req.connection has been deprecated since [email protected]. Using req.connection.removeAddress to get the client IP might still work but is discouraged.

Luckily, req.socket.remoteAddress has been there since [email protected] and is a perfect replacement:

The string representation of the remote IP address. For example, '74.125.127.100' or '2001:4860:a005::68'. Value may be undefined if the socket is destroyed (for example, if the client disconnected).

Update React component every second

Owing to changes in React V16 where componentWillReceiveProps() has been deprecated, this is the methodology that I use for updating a component. Notice that the below example is in Typescript and uses the static getDerivedStateFromProps method to get the initial state and updated state whenever the Props are updated.

    class SomeClass extends React.Component<Props, State> {
  static getDerivedStateFromProps(nextProps: Readonly<Props>): Partial<State> | null {
    return {
      time: nextProps.time
    };
  }

  timerInterval: any;

  componentDidMount() {
    this.timerInterval = setInterval(this.tick.bind(this), 1000);
  }

  tick() {
    this.setState({ time: this.props.time });
  }

  componentWillUnmount() {
    clearInterval(this.timerInterval);
  }

  render() {
    return <div>{this.state.time}</div>;
  }
}

Java Date vs Calendar

A little bit late at party, but Java has a new Date Time API in JDK 8. You may want to upgrade your JDK version and embrace the standard. No more messy date/calendar, no more 3rd party jars.

"E: Unable to locate package python-pip" on Ubuntu 18.04

Try following command sequence on Ubuntu terminal:

sudo apt-get install software-properties-common
sudo apt-add-repository universe
sudo apt-get update
sudo apt-get install python-pip

Resolve promises one after another (i.e. in sequence)?

On the basis of the question's title, "Resolve promises one after another (i.e. in sequence)?", we might understand that the OP is more interested in the sequential handling of promises on settlement than sequential calls per se.

This answer is offered :

  • to demonstrate that sequential calls are not necessary for sequential handling of responses.
  • to expose viable alternative patterns to this page's visitors - including the OP if he is still interested over a year later.
  • despite the OP's assertion that he does not want to make calls concurrently, which may genuinely be the case but equally may be an assumption based on the desire for sequential handling of responses as the title implies.

If concurrent calls are genuinely not wanted then see Benjamin Gruenbaum's answer which covers sequential calls (etc) comprehensively.

If however, you are interested (for improved performance) in patterns which allow concurrent calls followed by sequential handling of responses, then please read on.

It's tempting to think you have to use Promise.all(arr.map(fn)).then(fn) (as I have done many times) or a Promise lib's fancy sugar (notably Bluebird's), however (with credit to this article) an arr.map(fn).reduce(fn) pattern will do the job, with the advantages that it :

  • works with any promise lib - even pre-compliant versions of jQuery - only .then() is used.
  • affords the flexibility to skip-over-error or stop-on-error, whichever you want with a one line mod.

Here it is, written for Q.

var readFiles = function(files) {
    return files.map(readFile) //Make calls in parallel.
    .reduce(function(sequence, filePromise) {
        return sequence.then(function() {
            return filePromise;
        }).then(function(file) {
            //Do stuff with file ... in the correct sequence!
        }, function(error) {
            console.log(error); //optional
            return sequence;//skip-over-error. To stop-on-error, `return error` (jQuery), or `throw  error` (Promises/A+).
        });
    }, Q()).then(function() {
        // all done.
    });
};

Note: only that one fragment, Q(), is specific to Q. For jQuery you need to ensure that readFile() returns a jQuery promise. With A+ libs, foreign promises will be assimilated.

The key here is the reduction's sequence promise, which sequences the handling of the readFile promises but not their creation.

And once you have absorbed that, it's maybe slightly mind-blowing when you realise that the .map() stage isn't actually necessary! The whole job, parallel calls plus serial handling in the correct order, can be achieved with reduce() alone, plus the added advantage of further flexibility to :

  • convert from parallel async calls to serial async calls by simply moving one line - potentially useful during development.

Here it is, for Q again.

var readFiles = function(files) {
    return files.reduce(function(sequence, f) {
        var filePromise = readFile(f);//Make calls in parallel. To call sequentially, move this line down one.
        return sequence.then(function() {
            return filePromise;
        }).then(function(file) {
            //Do stuff with file ... in the correct sequence!
        }, function(error) {
            console.log(error); //optional
            return sequence;//Skip over any errors. To stop-on-error, `return error` (jQuery), or `throw  error` (Promises/A+).
        });
    }, Q()).then(function() {
        // all done.
    });
};

That's the basic pattern. If you wanted also to deliver data (eg the files or some transform of them) to the caller, you would need a mild variant.

Keep values selected after form submission

<form method="get" action="">
 <select name="name" value="<?php echo $_GET['name'];?>">
   <option value="a">a</option>
   <option value="b">b</option>
 </select>
 <select name="location" value="<?php echo $_GET['location'];?>">
   <option value="x">x</option>
   <option value="y">y</option>
 </select>
   <input type="submit" value="Submit" class="submit" />
</form>

Redirect parent window from an iframe action

It is possible to redirect from an iframe, but not to get information from the parent.

How to test if parameters exist in rails

Just pieced this together for the same problem:

before_filter :validate_params

private

def validate_params
  return head :bad_request unless params_present?
end

def params_present?  
  Set.new(%w(one two three)) <= (Set.new(params.keys)) &&
  params.values.all?
end

the first line checks if our target keys are present in the params' keys using the <= subset? operator. Enumerable.all? without block per default returns false if any value is nil or false.

Draw path between two points using Google Maps Android API v2

Try below solution to draw path with animation and also get time and distance between two points.

DirectionHelper.java

public class DirectionHelper {

    public List<List<HashMap<String, String>>> parse(JSONObject jObject) {

        List<List<HashMap<String, String>>> routes = new ArrayList<>();
        JSONArray jRoutes;
        JSONArray jLegs;
        JSONArray jSteps;
        JSONObject jDistance = null;
        JSONObject jDuration = null;

        try {

            jRoutes = jObject.getJSONArray("routes");

            /** Traversing all routes */
            for (int i = 0; i < jRoutes.length(); i++) {
                jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
                List path = new ArrayList<>();

                /** Traversing all legs */
                for (int j = 0; j < jLegs.length(); j++) {

                    /** Getting distance from the json data */
                    jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
                    HashMap<String, String> hmDistance = new HashMap<String, String>();
                    hmDistance.put("distance", jDistance.getString("text"));

                    /** Getting duration from the json data */
                    jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
                    HashMap<String, String> hmDuration = new HashMap<String, String>();
                    hmDuration.put("duration", jDuration.getString("text"));

                    /** Adding distance object to the path */
                    path.add(hmDistance);

                    /** Adding duration object to the path */
                    path.add(hmDuration);

                    jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");

                    /** Traversing all steps */
                    for (int k = 0; k < jSteps.length(); k++) {
                        String polyline = "";
                        polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
                        List<LatLng> list = decodePoly(polyline);

                        /** Traversing all points */
                        for (int l = 0; l < list.size(); l++) {
                            HashMap<String, String> hm = new HashMap<>();
                            hm.put("lat", Double.toString((list.get(l)).latitude));
                            hm.put("lng", Double.toString((list.get(l)).longitude));
                            path.add(hm);
                        }
                    }
                    routes.add(path);
                }
            }

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


        return routes;
    }

    //Method to decode polyline points
    private List<LatLng> decodePoly(String encoded) {

        List<LatLng> poly = new ArrayList<>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;

        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng p = new LatLng((((double) lat / 1E5)),
                    (((double) lng / 1E5)));
            poly.add(p);
        }

        return poly;
    }
}

GetPathFromLocation.java

public class GetPathFromLocation extends AsyncTask<String, Void, List<List<HashMap<String, String>>>> {

    private Context context;
    private String TAG = "GetPathFromLocation";
    private LatLng source, destination;
    private ArrayList<LatLng> wayPoint;
    private GoogleMap mMap;
    private boolean animatePath, repeatDrawingPath;
    private DirectionPointListener resultCallback;
    private ProgressDialog progressDialog;

    //https://www.mytrendin.com/draw-route-two-locations-google-maps-android/
    //https://www.androidtutorialpoint.com/intermediate/google-maps-draw-path-two-points-using-google-directions-google-map-android-api-v2/

    public GetPathFromLocation(Context context, LatLng source, LatLng destination, ArrayList<LatLng> wayPoint, GoogleMap mMap, boolean animatePath, boolean repeatDrawingPath, DirectionPointListener resultCallback) {
        this.context = context;
        this.source = source;
        this.destination = destination;
        this.wayPoint = wayPoint;
        this.mMap = mMap;
        this.animatePath = animatePath;
        this.repeatDrawingPath = repeatDrawingPath;
        this.resultCallback = resultCallback;
    }

    synchronized public String getUrl(LatLng source, LatLng dest, ArrayList<LatLng> wayPoint) {

        String url = "https://maps.googleapis.com/maps/api/directions/json?sensor=false&mode=driving&origin="
                + source.latitude + "," + source.longitude + "&destination=" + dest.latitude + "," + dest.longitude;
        for (int centerPoint = 0; centerPoint < wayPoint.size(); centerPoint++) {
            if (centerPoint == 0) {
                url = url + "&waypoints=optimize:true|" + wayPoint.get(centerPoint).latitude + "," + wayPoint.get(centerPoint).longitude;
            } else {
                url = url + "|" + wayPoint.get(centerPoint).latitude + "," + wayPoint.get(centerPoint).longitude;
            }
        }
        url = url + "&key=" + context.getResources().getString(R.string.google_api_key);

        return url;
    }

    public int getRandomColor() {
        Random rnd = new Random();
        return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("Please wait...");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected List<List<HashMap<String, String>>> doInBackground(String... url) {

        String data;

        try {
            InputStream inputStream = null;
            HttpURLConnection connection = null;
            try {
                URL directionUrl = new URL(getUrl(source, destination, wayPoint));
                connection = (HttpURLConnection) directionUrl.openConnection();
                connection.connect();
                inputStream = connection.getInputStream();

                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer stringBuffer = new StringBuffer();

                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                }

                data = stringBuffer.toString();
                bufferedReader.close();

            } catch (Exception e) {
                Log.e(TAG, "Exception : " + e.toString());
                return null;
            } finally {
                inputStream.close();
                connection.disconnect();
            }
            Log.e(TAG, "Background Task data : " + data);

            //Second AsyncTask

            JSONObject jsonObject;
            List<List<HashMap<String, String>>> routes = null;

            try {
                jsonObject = new JSONObject(data);
                // Starts parsing data
                DirectionHelper helper = new DirectionHelper();
                routes = helper.parse(jsonObject);
                Log.e(TAG, "Executing Routes : "/*, routes.toString()*/);

                return routes;

            } catch (Exception e) {
                Log.e(TAG, "Exception in Executing Routes : " + e.toString());
                return null;
            }

        } catch (Exception e) {
            Log.e(TAG, "Background Task Exception : " + e.toString());
            return null;
        }
    }

    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        super.onPostExecute(result);

        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

        ArrayList<LatLng> points;
        PolylineOptions lineOptions = null;
        String distance = "";
        String duration = "";

        // Traversing through all the routes
        for (int i = 0; i < result.size(); i++) {
            points = new ArrayList<>();
            lineOptions = new PolylineOptions();

            // Fetching i-th route
            List<HashMap<String, String>> path = result.get(i);

            // Fetching all the points in i-th route
            for (int j = 0; j < path.size(); j++) {
                HashMap<String, String> point = path.get(j);

                if (j == 0) {    // Get distance from the list
                    distance = (String) point.get("distance");
                    continue;
                } else if (j == 1) { // Get duration from the list
                    duration = (String) point.get("duration");
                    continue;
                }

                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);

                points.add(position);
            }

            // Adding all the points in the route to LineOptions
            lineOptions.addAll(points);
            lineOptions.width(8);
            lineOptions.color(Color.RED);
            //lineOptions.color(getRandomColor());

            if (animatePath) {
                final ArrayList<LatLng> finalPoints = points;
                ((AppCompatActivity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        PolylineOptions polylineOptions;
                        final Polyline greyPolyLine, blackPolyline;
                        final ValueAnimator polylineAnimator;

                        LatLngBounds.Builder builder = new LatLngBounds.Builder();
                        for (LatLng latLng : finalPoints) {
                            builder.include(latLng);
                        }
                        polylineOptions = new PolylineOptions();
                        polylineOptions.color(Color.RED);
                        polylineOptions.width(8);
                        polylineOptions.startCap(new SquareCap());
                        polylineOptions.endCap(new SquareCap());
                        polylineOptions.jointType(ROUND);
                        polylineOptions.addAll(finalPoints);
                        greyPolyLine = mMap.addPolyline(polylineOptions);

                        polylineOptions = new PolylineOptions();
                        polylineOptions.width(8);
                        polylineOptions.color(Color.WHITE);
                        polylineOptions.startCap(new SquareCap());
                        polylineOptions.endCap(new SquareCap());
                        polylineOptions.zIndex(5f);
                        polylineOptions.jointType(ROUND);

                        blackPolyline = mMap.addPolyline(polylineOptions);
                        polylineAnimator = ValueAnimator.ofInt(0, 100);
                        polylineAnimator.setDuration(5000);
                        polylineAnimator.setInterpolator(new LinearInterpolator());
                        polylineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                            @Override
                            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                                List<LatLng> points = greyPolyLine.getPoints();
                                int percentValue = (int) valueAnimator.getAnimatedValue();
                                int size = points.size();
                                int newPoints = (int) (size * (percentValue / 100.0f));
                                List<LatLng> p = points.subList(0, newPoints);
                                blackPolyline.setPoints(p);
                            }
                        });

                        polylineAnimator.addListener(new Animator.AnimatorListener() {
                            @Override
                            public void onAnimationStart(Animator animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animator animation) {
                                if (repeatDrawingPath) {
                                    List<LatLng> greyLatLng = greyPolyLine.getPoints();
                                    if (greyLatLng != null) {
                                        greyLatLng.clear();

                                    }
                                    polylineAnimator.start();
                                }
                            }

                            @Override
                            public void onAnimationCancel(Animator animation) {
                                polylineAnimator.cancel();
                            }

                            @Override
                            public void onAnimationRepeat(Animator animation) {
                            }
                        });
                        polylineAnimator.start();
                    }
                });
            }

            Log.e(TAG, "PolylineOptions Decoded");
        }

        // Drawing polyline in the Google Map for the i-th route
        if (resultCallback != null && lineOptions != null)
            resultCallback.onPath(lineOptions, distance, duration);
    }
}

DirectionPointListener

public interface DirectionPointListener {
    public void onPath(PolylineOptions polyLine,String distance,String duration);
}

Now draw path using below code in your Activity

private GoogleMap mMap;
private ArrayList<LatLng> wayPoint = new ArrayList<>();
private SupportMapFragment mapFragment;

mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

@Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                LatLngBounds.Builder builder = new LatLngBounds.Builder();

                /*Add Source Marker*/
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(source);
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
                mMap.addMarker(markerOptions);
                builder.include(source);

                /*Add Destination Marker*/
                markerOptions = new MarkerOptions();
                markerOptions.position(destination);
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
                mMap.addMarker(markerOptions);
                builder.include(destination);

                LatLngBounds bounds = builder.build();

                int width = mapFragment.getView().getMeasuredWidth();
                int height = mapFragment.getView().getMeasuredHeight();
                int padding = (int) (width * 0.15); // offset from edges of the map 10% of screen

                CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);

                mMap.animateCamera(cu);

                new GetPathFromLocation(context, source, destination, wayPoint, mMap, true, false, new DirectionPointListener() {
                    @Override
                    public void onPath(PolylineOptions polyLine, String distance, String duration) {
                        mMap.addPolyline(polyLine);
                        Log.e(TAG, "onPath :: Distance :: " + distance + " Duration :: " + duration);

                        binding.txtDistance.setText(String.format(" %s", distance));
                        binding.txtDuration.setText(String.format(" %s", duration));
                    }
                }).execute();
            }
        });
    }

OutPut

enter image description here

I hope this can help you!

Thank You.

Android – Listen For Incoming SMS Messages

@Mike M. and I found an issue with the accepted answer (see our comments):

Basically, there is no point in going through the for loop if we are not concatenating the multipart message each time:

for (int i = 0; i < msgs.length; i++) {
    msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
    msg_from = msgs[i].getOriginatingAddress();
    String msgBody = msgs[i].getMessageBody();
}

Notice that we just set msgBody to the string value of the respective part of the message no matter what index we are on, which makes the entire point of looping through the different parts of the SMS message useless, since it will just be set to the very last index value. Instead we should use +=, or as Mike noted, StringBuilder:

All in all, here is what my SMS receiving code looks like:

if (myBundle != null) {
    Object[] pdus = (Object[]) myBundle.get("pdus"); // pdus is key for SMS in bundle

    //Object [] pdus now contains array of bytes
    messages = new SmsMessage[pdus.length];
    for (int i = 0; i < messages.length; i++) {
         messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); //Returns one message, in array because multipart message due to sms max char
         Message += messages[i].getMessageBody(); // Using +=, because need to add multipart from before also
    }

    contactNumber = messages[0].getOriginatingAddress(); //This could also be inside the loop, but there is no need
}

Just putting this answer out there in case anyone else has the same confusion.

SQL Server function to return minimum date (January 1, 1753)

This is what I use to get the minimum date in SQL Server. Please note that it is globalisation friendly:

CREATE FUNCTION [dbo].[DateTimeMinValue]()
RETURNS datetime
AS
BEGIN
  RETURN (SELECT
    CAST('17530101' AS datetime))
END

Call using:

SELECT [dbo].[DateTimeMinValue]()

Ruby Array find_first object?

use array detect method if you wanted to return first value where block returns true

[1,2,3,11,34].detect(&:even?) #=> 2

OR

[1,2,3,11,34].detect{|i| i.even?} #=> 2

If you wanted to return all values where block returns true then use select

[1,2,3,11,34].select(&:even?)  #=> [2, 34]

Set selected option of select box

$('#gate').val('Gateway 2').prop('selected', true);

What does LINQ return when the results are empty

It won't throw exception, you'll get an empty list.

Convert audio files to mp3 using ffmpeg

For batch processing files in folder:

for i in *.wav; do ffmpeg -i "$i" -f mp3 "${i%}.mp3"; done

This script converts all "wav" files in folder to mp3 files and adds mp3 extension

ffmpeg have to be installed. (See other answers)

View tabular file such as CSV from command line

Tabview: lightweight python curses command line CSV file viewer (and also other tabular Python data, like a list of lists) is here on Github

Features:

  • Python 2.7+, 3.x
  • Unicode support
  • Spreadsheet-like view for easily visualizing tabular data
  • Vim-like navigation (h,j,k,l, g(top), G(bottom), 12G goto line 12, m - mark, ' - goto mark, etc.)
  • Toggle persistent header row
  • Dynamically resize column widths and gap
  • Sort ascending or descending by any column. 'Natural' order sort for numeric values.
  • Full-text search, n and p to cycle between search results
  • 'Enter' to view the full cell contents
  • Yank cell contents to clipboard
  • F1 or ? for keybindings
  • Can also use from python command line to visualize any tabular data (e.g. list-of-lists)

Background position, margin-top?

#div-name

{

  background-image: url('../images/background-art-main.jpg');
  background-position: top right 50px;
  background-repeat: no-repeat;
}

How to check what version of jQuery is loaded?

You can just check if the jQuery object exists:

if( typeof jQuery !== 'undefined' ) ... // jQuery loaded

jQuery().jquery has the version number.

As for the prefix, jQuery should always work. If you want to use $ you can wrap your code to a function and pass jQuery to it as the parameter:

(function( $ ) {
    $( '.class' ).doSomething();  // works always
})( jQuery )

How to redirect on another page and pass parameter in url from table?

Bind the button, this is done with jQuery:

$("#my-table input[type='button']").click(function(){
    var parameter = $(this).val();
    window.location = "http://yoursite.com/page?variable=" + parameter;
});

Converting camel case to underscore case in ruby

Receiver converted to snake case: http://rubydoc.info/gems/extlib/0.9.15/String#snake_case-instance_method

This is the Support library for DataMapper and Merb. (http://rubygems.org/gems/extlib)

def snake_case
  return downcase if match(/\A[A-Z]+\z/)
  gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2').
  gsub(/([a-z])([A-Z])/, '\1_\2').
  downcase
end

"FooBar".snake_case           #=> "foo_bar"
"HeadlineCNNNews".snake_case  #=> "headline_cnn_news"
"CNN".snake_case              #=> "cnn"

Python find min max and average of a list (array)

Only a teacher would ask you to do something silly like this. You could provide an expected answer. Or a unique solution, while the rest of the class will be (yawn) the same...

from operator import lt, gt
def ultimate (l,op,c=1,u=0):
    try:
        if op(l[c],l[u]): 
            u = c
        c += 1
        return ultimate(l,op,c,u)
    except IndexError:
        return l[u]
def minimum (l):
    return ultimate(l,lt)
def maximum (l):
    return ultimate(l,gt)

The solution is simple. Use this to set yourself apart from obvious choices.

How can I create C header files

  1. Open your favorite text editor
  2. Create a new file named whatever.h
  3. Put your function prototypes in it

DONE.

Example whatever.h

#ifndef WHATEVER_H_INCLUDED
#define WHATEVER_H_INCLUDED
int f(int a);
#endif

Note: include guards (preprocessor commands) added thanks to luke. They avoid including the same header file twice in the same compilation. Another possibility (also mentioned on the comments) is to add #pragma once but it is not guaranteed to be supported on every compiler.

Example whatever.c

#include "whatever.h"

int f(int a) { return a + 1; }

And then you can include "whatever.h" into any other .c file, and link it with whatever.c's object file.

Like this:

sample.c

#include "whatever.h"

int main(int argc, char **argv)
{
    printf("%d\n", f(2)); /* prints 3 */
    return 0;
}

To compile it (if you use GCC):

$ gcc -c whatever.c -o whatever.o
$ gcc -c sample.c -o sample.o

To link the files to create an executable file:

$ gcc sample.o whatever.o -o sample

You can test sample:

$ ./sample
3
$

Multiline text in JLabel

You can also use a JXLabel from the SwingX library.

JXLabel multiline = new JXLabel("this is a \nMultiline Text");
multiline.setLineWrap(true);

Fast way to discover the row count of a table in PostgreSQL

In Oracle, you could use rownum to limit the number of rows returned. I am guessing similar construct exists in other SQLs as well. So, for the example you gave, you could limit the number of rows returned to 500001 and apply a count(*) then:

SELECT (case when cnt > 500000 then 500000 else cnt end) myCnt
FROM (SELECT count(*) cnt FROM table WHERE rownum<=500001)

Body of Http.DELETE request in Angular2

The http.delete(url, options) does accept a body. You just need to put it within the options object.

http.delete('/api/something', new RequestOptions({
   headers: headers,
   body: anyObject
}))

Reference options interface: https://angular.io/api/http/RequestOptions

UPDATE:

The above snippet only works for Angular 2.x, 4.x and 5.x.

For versions 6.x onwards, Angular offers 15 different overloads. Check all overloads here: https://angular.io/api/common/http/HttpClient#delete

Usage sample:

const options = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
  }),
  body: {
    id: 1,
    name: 'test',
  },
};

this.httpClient
  .delete('http://localhost:8080/something', options)
  .subscribe((s) => {
    console.log(s);
  });

How to select an element inside "this" in jQuery?

$( this ).find( 'li.target' ).css("border", "3px double red");

or

$( this ).children( 'li.target' ).css("border", "3px double red");

Use children for immediate descendants, or find for deeper elements.

Import a module from a relative path

This also works, and is much simpler than anything with the sys module:

with open("C:/yourpath/foobar.py") as f:
    eval(f.read())

MySQL, update multiple tables with one query

Let's say I have Table1 with primary key _id and a boolean column doc_availability; Table2 with foreign key _id and DateTime column last_update and I want to change the availability of a document with _id 14 in Table1 to 0 i.e unavailable and update Table2 with the timestamp when the document was last updated. The following query would do the task:

UPDATE Table1, Table2 
SET doc_availability = 0, last_update = NOW() 
WHERE Table1._id = Table2._id AND Table1._id = 14

Functional programming vs Object Oriented programming

  1. If you're in a heavily concurrent environment, then pure functional programming is useful. The lack of mutable state makes concurrency almost trivial. See Erlang.

  2. In a multiparadigm language, you may want to model some things functionally if the existence of mutable state is must an implementation detail, and thus FP is a good model for the problem domain. For example, see list comprehensions in Python or std.range in the D programming language. These are inspired by functional programming.

How is an HTTP POST request made in node.js?

There are dozens of open-source libraries available that you can use to making an HTTP POST request in Node.

1. Axios (Recommended)

const axios = require('axios');

const data = {
    name: 'John Doe',
    job: 'Content Writer'
};

axios.post('https://reqres.in/api/users', data)
    .then((res) => {
        console.log(`Status: ${res.status}`);
        console.log('Body: ', res.data);
    }).catch((err) => {
        console.error(err);
    });

2. Needle

const needle = require('needle');

const data = {
    name: 'John Doe',
    job: 'Content Writer'
};

needle('post', 'https://reqres.in/api/users', data, {json: true})
    .then((res) => {
        console.log(`Status: ${res.statusCode}`);
        console.log('Body: ', res.body);
    }).catch((err) => {
        console.error(err);
    });

3. Request

const request = require('request');

const options = {
    url: 'https://reqres.in/api/users',
    json: true,
    body: {
        name: 'John Doe',
        job: 'Content Writer'
    }
};

request.post(options, (err, res, body) => {
    if (err) {
        return console.log(err);
    }
    console.log(`Status: ${res.statusCode}`);
    console.log(body);
});

4. Native HTTPS Module

const https = require('https');

const data = JSON.stringify({
    name: 'John Doe',
    job: 'Content Writer'
});

const options = {
    hostname: 'reqres.in',
    path: '/api/users',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Content-Length': data.length
    }
};


const req = https.request(options, (res) => {
    let data = '';

    console.log('Status Code:', res.statusCode);

    res.on('data', (chunk) => {
        data += chunk;
    });

    res.on('end', () => {
        console.log('Body: ', JSON.parse(data));
    });

}).on("error", (err) => {
    console.log("Error: ", err.message);
});

req.write(data);
req.end();

For details, check out this article.

What is your favorite C programming trick?

I'm fond of using = {0}; to initialize structures without needing to call memset.

struct something X = {0};

This will initialize all of the members of the struct (or array) to zero (but not any padding bytes - use memset if you need to zero those as well).

But you should be aware there are some issues with this for large, dynamically allocated structures.

How can I convert String[] to ArrayList<String>

List<String> list = Arrays.asList(array);

The list returned will be backed by the array, it acts like a bridge, so it will be fixed-size.

What is (functional) reactive programming?

Check out Rx, Reactive Extensions for .NET. They point out that with IEnumerable you are basically 'pulling' from a stream. Linq queries over IQueryable/IEnumerable are set operations that 'suck' the results out of a set. But with the same operators over IObservable you can write Linq queries that 'react'.

For example, you could write a Linq query like (from m in MyObservableSetOfMouseMovements where m.X<100 and m.Y<100 select new Point(m.X,m.Y)).

and with the Rx extensions, that's it: You have UI code that reacts to the incoming stream of mouse movements and draws whenever you're in the 100,100 box...

PHP Accessing Parent Class Variable

all the properties and methods of the parent class is inherited in the child class so theoretically you can access them in the child class but beware using the protected keyword in your class because it throws a fatal error when used in the child class.
as mentioned in php.net

The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.

How to draw a rectangle around a region of interest in python

please don't try with the old cv module, use cv2:

import cv2

cv2.rectangle(img, (x1, y1), (x2, y2), (255,0,0), 2)


x1,y1 ------
|          |
|          |
|          |
--------x2,y2

[edit] to append the follow-up questions below:

cv2.imwrite("my.png",img)

cv2.imshow("lalala", img)
k = cv2.waitKey(0) # 0==wait forever

Declare a constant array

From Effective Go:

Constants in Go are just that—constant. They are created at compile time, even when defined as locals in functions, and can only be numbers, characters (runes), strings or booleans. Because of the compile-time restriction, the expressions that define them must be constant expressions, evaluatable by the compiler. For instance, 1<<3 is a constant expression, while math.Sin(math.Pi/4) is not because the function call to math.Sin needs to happen at run time.

Slices and arrays are always evaluated during runtime:

var TestSlice = []float32 {.03, .02}
var TestArray = [2]float32 {.03, .02}
var TestArray2 = [...]float32 {.03, .02}

[...] tells the compiler to figure out the length of the array itself. Slices wrap arrays and are easier to work with in most cases. Instead of using constants, just make the variables unaccessible to other packages by using a lower case first letter:

var ThisIsPublic = [2]float32 {.03, .02}
var thisIsPrivate = [2]float32 {.03, .02}

thisIsPrivate is available only in the package it is defined. If you need read access from outside, you can write a simple getter function (see Getters in golang).

How to implement a binary tree?

import random

class TreeNode:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
        self.p = None

class BinaryTree:
    def __init__(self):
        self.root = None

    def length(self):
        return self.size

    def inorder(self, node):
        if node == None:
            return None
        else:
            self.inorder(node.left)
            print node.key,
            self.inorder(node.right)

    def search(self, k):
        node = self.root
        while node != None:
            if node.key == k:
                return node
            if node.key > k:
                node = node.left
            else:
                node = node.right
        return None

    def minimum(self, node):
        x = None
        while node.left != None:
            x = node.left
            node = node.left
        return x

    def maximum(self, node):
        x = None
        while node.right != None:
            x = node.right
            node = node.right
        return x

    def successor(self, node):
        parent = None
        if node.right != None:
            return self.minimum(node.right)
        parent = node.p
        while parent != None and node == parent.right:
            node = parent
            parent = parent.p
        return parent

    def predecessor(self, node):
        parent = None
        if node.left != None:
            return self.maximum(node.left)
        parent = node.p
        while parent != None and node == parent.left:
            node = parent
            parent = parent.p
        return parent

    def insert(self, k):
        t = TreeNode(k)
        parent = None
        node = self.root
        while node != None:
            parent = node
            if node.key > t.key:
                node = node.left
            else:
                node = node.right
        t.p = parent
        if parent == None:
            self.root = t
        elif t.key < parent.key:
            parent.left = t
        else:
            parent.right = t
        return t


    def delete(self, node):
        if node.left == None:
            self.transplant(node, node.right)
        elif node.right == None:
            self.transplant(node, node.left)
        else:
            succ = self.minimum(node.right)
            if succ.p != node:
                self.transplant(succ, succ.right)
                succ.right = node.right
                succ.right.p = succ
            self.transplant(node, succ)
            succ.left = node.left
            succ.left.p = succ

    def transplant(self, node, newnode):
        if node.p == None:
            self.root = newnode
        elif node == node.p.left:
            node.p.left = newnode
        else:
            node.p.right = newnode
        if newnode != None:
            newnode.p = node.p

How can I check if a string is null or empty in PowerShell?

If it is a parameter in a function, you can validate it with ValidateNotNullOrEmpty as you can see in this example:

Function Test-Something
{
    Param(
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string]$UserName
    )

    #stuff todo
}

getting the last item in a javascript object

if you mean get the last key alphabetically, you can (garanteed) :

var obj = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };
var keys = Object.keys(obj);
keys.sort();
var lastkey = keys.pop() // c
var lastvalue = obj[lastkey] // 'carrot'

YouTube API to fetch all videos on a channel

Below is a Python alternative that does not require any special packages. By providing the channel id it returns a list of video links for that channel. Please note that you need an API Key for it to work.

import urllib
import json

def get_all_video_in_channel(channel_id):
    api_key = YOUR API KEY

    base_video_url = 'https://www.youtube.com/watch?v='
    base_search_url = 'https://www.googleapis.com/youtube/v3/search?'

    first_url = base_search_url+'key={}&channelId={}&part=snippet,id&order=date&maxResults=25'.format(api_key, channel_id)

    video_links = []
    url = first_url
    while True:
        inp = urllib.urlopen(url)
        resp = json.load(inp)

        for i in resp['items']:
            if i['id']['kind'] == "youtube#video":
                video_links.append(base_video_url + i['id']['videoId'])

        try:
            next_page_token = resp['nextPageToken']
            url = first_url + '&pageToken={}'.format(next_page_token)
        except:
            break
    return video_links

Meaning of ${project.basedir} in pom.xml

${project.basedir} is the root directory of your project.

${project.build.directory} is equivalent to ${project.basedir}/target

as it is defined here: https://github.com/apache/maven/blob/trunk/maven-model-builder/src/main/resources/org/apache/maven/model/pom-4.0.0.xml#L53

scp via java

The openssh project lists several Java alternatives, Trilead SSH for Java seems to fit what you're asking for.

Update date + one year in mysql

For multiple interval types use a nested construction as in:

 UPDATE table SET date = DATE_ADD(DATE_ADD(date, INTERVAL 1 YEAR), INTERVAL 1 DAY)

For updating a given date in the column date to 1 year + 1 day

How can I disable a specific LI element inside a UL?

I usualy use <li> to include <a> link. I disabled click action writing like this; You may not include <a> link, then you will ignore my post.

_x000D_
_x000D_
a.noclick       {_x000D_
  pointer-events: none;_x000D_
}
_x000D_
<a class="noclick" href="#">this is disabled</a>
_x000D_
_x000D_
_x000D_