Programs & Examples On #Gearman

Gearman is a system to farm out work to other machines, dispatching function calls to machines that are better suited to do work, to do work in parallel, to load balance lots of function calls, or to call functions between languages.

Get an array of list element contents in jQuery

var optionTexts = [];
$("ul li").each(function() { optionTexts.push($(this).text()) });

...should do the trick. To get the final output you're looking for, join() plus some concatenation will do nicely:

var quotedCSV = '"' + optionTexts.join('", "') + '"';

Good tool to visualise database schema?

I usually use SchemaSpy to do this, but recently I found a really simple article on sqlfairy that just uses the dump file to create the structure graph

HTML code for INR

SPAN class code. Stylesheet:

<link rel="stylesheet" type="text/css" href="http://cdn.webrupee.com/font">

Now use the below mentioned code to type Indian Rupee symbol,

<span class="WebRupee">Rs.</span>

Once the popular font families will be updated to Unicode 6.0.0, then you will be able to type Indian Rupee Symbol by typing ₹ in HTML editor.

grep without showing path/file:line

No need to find. If you are just looking for a pattern within a specific directory, this should suffice:

grep -hn FOO /your/path/*.bar

Where -h is the parameter to hide the filename, as from man grep:

-h, --no-filename

Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search.

Note that you were using

-H, --with-filename

Print the file name for each match. This is the default when there is more than one file to search.

Disable resizing of a Windows Forms form

Another way is to change properties "AutoSize" (set to True) and "AutosizeMode" (set to GrowAndShrink).

This has the effect of the form autosizing to the elements on it and never allowing the user to change its size.

How to access form methods and controls from a class in C#?

You need to make the members in the for the form class either public or, if the service class is in the same assembly, internal. Windows controls' visibility can be controlled through their Modifiers properties.

Note that it's generally considered a bad practice to explicitly tie a service class to a UI class. Rather you should create good interfaces between the service class and the form class. That said, for learning or just generally messing around, the earth won't spin off its axis if you expose form members for service classes.

rp

'cout' was not declared in this scope

Use std::cout, since cout is defined within the std namespace. Alternatively, add a using std::cout; directive.

How to get today's Date?

Is there are more correct way?

Yes, there is.

LocalDate.now( 
    ZoneId.of( "America/Montreal" ) 
).atStartOfDay(
    ZoneId.of( "America/Montreal" )
)

java.time

Java 8 and later now has the new java.time framework built-in. See Tutorial. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.

Examples

Some examples follow, using java.time. Note how they specify a time zone. If omitted, your JVM’s current default time zone. That default can vary, even changing at any moment during runtime, so I suggest you specify a time zone explicitly rather than rely implicitly on the default.

Here is an example of date-only, without time-of-day nor time zone.

ZoneId zonedId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zonedId );
System.out.println( "today : " + today );

today : 2015-10-19

Here is an example of getting current date-time.

ZoneId zonedId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now( zonedId );
System.out.println( "zdt : " + zdt );

When run:

zdt : 2015-10-19T18:07:02.910-04:00[America/Montreal]

First Moment Of The Day

The Question asks for the date-time where the time is set to zero. This assumes the first moment of the day is always the time 00:00:00.0 but that is not always the case. Daylight Saving Time (DST) and perhaps other anomalies mean the day may begin at a different time such as 01:00.0.

Fortunately, java.time has a facility to determine the first moment of a day appropriate to a particular time zone, LocalDate::atStartOfDay. Let's see some code using the LocalDate named today and the ZoneId named zoneId from code above.

ZonedDateTime todayStart = today.atStartOfDay( zoneId );

zdt : 2015-10-19T00:00:00-04:00[America/Montreal]

Interoperability

If you must have a java.util.Date for use with classes not yet updated to work with the java.time types, convert. Call the java.util.Date.from( Instant instant ) method.

java.util.Date date = java.util.Date.from( zdt.toInstant() );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

What is Dispatcher Servlet in Spring?

The job of the DispatcherServlet is to take an incoming URI and find the right combination of handlers (generally methods on Controller classes) and views (generally JSPs) that combine to form the page or resource that's supposed to be found at that location.

I might have

  • a file /WEB-INF/jsp/pages/Home.jsp
  • and a method on a class

    @RequestMapping(value="/pages/Home.html")
    private ModelMap buildHome() {
        return somestuff;
    }
    

The Dispatcher servlet is the bit that "knows" to call that method when a browser requests the page, and to combine its results with the matching JSP file to make an html document.

How it accomplishes this varies widely with configuration and Spring version.

There's also no reason the end result has to be web pages. It can do the same thing to locate RMI end points, handle SOAP requests, anything that can come into a servlet.

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

I found the InvokeRequired not reliable, so I simply use

if (!this.IsHandleCreated)
{
    this.CreateHandle();
}

How to condense if/else into one line in Python?

Python's if can be used as a ternary operator:

>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'

Convert utf8-characters to iso-88591 and back in PHP

First of all, don't use different encodings. It leads to a mess, and UTF-8 is definitely the one you should be using everywhere.

Chances are your input is not ISO-8859-1, but something else (ISO-8859-15, Windows-1252). To convert from those, use iconv or mb_convert_encoding.

Nevertheless, utf8_encode and utf8_decode should work for ISO-8859-1. It would be nice if you could post a link to a file or a uuencoded or base64 example string for which the conversion fails or yields unexpected results.

Why would $_FILES be empty when uploading files to PHP?

If you are using JQuery Mobile

Using a multipart form with a file input is not supported by Ajax. In this case you should decorate the parent form with data-ajax="false" to ensure the form is submitted properly to the server.

<form action="upload.php" method="post" enctype="multipart/form-data"  data-ajax="false">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>

Get everything after and before certain character in SQL Server

I have made a method which is much more general :

so :

DECLARE @a NVARCHAR(MAX)='images/test.jpg';


 --Touch here
DECLARE @keysValueToSearch NVARCHAR(4000) = '/'
DECLARE @untilThisCharAppears NVARCHAR(4000) = '.'
DECLARE @keysValueToSearchPattern NVARCHAR(4000) = '%' + @keysValueToSearch + '%'


 --Nothing to touch here     
SELECT SUBSTRING(
           @a,
           PATINDEX(@keysValueToSearchPattern, @a) + LEN(@keysValueToSearch),
           CHARINDEX(
               @untilThisCharAppears,
               @a,
               PATINDEX(@keysValueToSearchPattern, @a) + LEN(@keysValueToSearch)
           ) -(PATINDEX(@keysValueToSearchPattern, @a) + LEN(@keysValueToSearch))
       )

How to create own dynamic type or dynamic object in C#?

ExpandoObject is what are you looking for.

dynamic MyDynamic = new ExpandoObject(); // note, the type MUST be dynamic to use dynamic invoking.
MyDynamic.A = "A";
MyDynamic.B = "B";
MyDynamic.C = "C";
MyDynamic.TheAnswerToLifeTheUniverseAndEverything = 42;

Where can I find my Facebook application id and secret key?

From 2018:

Go to Settings -> Basic -> App Secret (type your password and you're ready to go).

Python non-greedy regexes

Would not \\(.*?\\) work? That is the non-greedy syntax.

AngularJS: Can't I set a variable value on ng-click?

You can use some thing like this

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div ng-app="" ng-init="btn1=false" ng-init="btn2=false">_x000D_
    <p>_x000D_
      <input type="submit" ng-disabled="btn1||btn2" ng-click="btn1=true" ng-model="btn1" />_x000D_
    </p>_x000D_
    <p>_x000D_
      <button ng-disabled="btn1||btn2" ng-model="btn2" ng-click="btn2=true">Click Me!</button>_x000D_
    </p>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

pandas get column average/mean

Mean for each column in df :

    A   B   C
0   5   3   8
1   5   3   9
2   8   4   9

df.mean()

A    6.000000
B    3.333333
C    8.666667
dtype: float64

and if you want average of all columns:

df.stack().mean()
6.0

Generating UNIQUE Random Numbers within a range

This is how I would do it.

$randnum1 = mt_rand(1,20);

$nomatch = 0;

while($nomatch == 0){

$randnum2 = mt_rand(1,20);

if($randnum2 != $randnum1){

$nomatch = 1;

}

}

$nomatch = 0;

while($nomatch == 0){

$randnum3 = mt_rand(1,20);

if(($randnum3 != $randnum1)and($randnum3 != $randnum2)){

$nomatch = 1;

}

}

Then you can echo the results to check

echo "Random numbers are " . $randnum1 . "," . $randnum2 . ", and " . $randnum3 . "\n";

Git: can't undo local changes (error: path ... is unmerged)

git checkout origin/[branch] .
git status

// Note dot (.) at the end. And all will be good

C++ Array Of Pointers

For example, if you want an array of int pointers it will be int* a[10]. It means that variable a is a collection of 10 int* s.

EDIT

I guess this is what you want to do:

class Bar
{
};

class Foo
{
public:

    //Takes number of bar elements in the pointer array
    Foo(int size_in);

    ~Foo();
    void add(Bar& bar);
private:

    //Pointer to bar array
    Bar** m_pBarArr;

    //Current fee bar index
    int m_index;
};

Foo::Foo(int size_in) : m_index(0)
{
    //Allocate memory for the array of bar pointers
    m_pBarArr = new Bar*[size_in];
}

Foo::~Foo()
{
    //Notice delete[] and not delete
    delete[] m_pBarArr;
    m_pBarArr = NULL;
}

void Foo::add(Bar &bar)
{
    //Store the pointer into the array. 
    //This is dangerous, you are assuming that bar object
    //is valid even when you try to use it
    m_pBarArr[m_index++] = &bar;
}

How to automatically convert strongly typed enum into int?

An extension to the answers from R. Martinho Fernandes and Class Skeleton: Their answers show how to use typename std::underlying_type<EnumType>::type or std::underlying_type_t<EnumType> to convert your enumeration value with a static_cast to a value of the underlying type. Compared to a static_cast to some specific integer type, like, static_cast<int> this has the benefit of being maintenance friendly, because when the underlying type changes, the code using std::underlying_type_t will automatically use the new type.

This, however, is sometimes not what you want: Assume you wanted to print out enumeration values directly, for example to std::cout, like in the following example:

enum class EnumType : int { Green, Blue, Yellow };
std::cout << static_cast<std::underlying_type_t<EnumType>>(EnumType::Green);

If you later change the underlying type to a character type, like, uint8_t, then the value of EnumType::Green will not be printed as a number, but as a character, which is most probably not what you want. Thus, you sometimes would rather convert the enumeration value into something like "underlying type, but with integer promotion where necessary".

It would be possible to apply the unary operator+ to the result of the cast to force integer promotion if necessary. However, you can also use std::common_type_t (also from header file <type_traits>) to do the following:

enum class EnumType : int { Green, Blue, Yellow };
std::cout << static_cast<std::common_type_t<int, std::underlying_type_t<EnumType>>>(EnumType::Green);

Preferrably you would wrap this expression in some helper template function:

template <class E>
constexpr std::common_type_t<int, std::underlying_type_t<E>>
enumToInteger(E e) {
    return static_cast<std::common_type_t<int, std::underlying_type_t<E>>>(e);
}

Which would then be more friendly to the eyes, be maintenance friendly with respect to changes to the underlying type, and without need for tricks with operator+:

std::cout << enumToInteger(EnumType::Green);

.NET HttpClient. How to POST string value?

Here I found this article which is send post request using JsonConvert.SerializeObject() & StringContent() to HttpClient.PostAsync data

static async Task Main(string[] args)
{
    var person = new Person();
    person.Name = "John Doe";
    person.Occupation = "gardener";

    var json = Newtonsoft.Json.JsonConvert.SerializeObject(person);
    var data = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");

    var url = "https://httpbin.org/post";
    using var client = new HttpClient();

    var response = await client.PostAsync(url, data);

    string result = response.Content.ReadAsStringAsync().Result;
    Console.WriteLine(result);
}

Haversine Formula in Python (Bearing and Distance between two GPS points)

The Y in atan2 is, by default, the first parameter. Here is the documentation. You will need to switch your inputs to get the correct bearing angle.

bearing = atan2(sin(lon2-lon1)*cos(lat2), cos(lat1)*sin(lat2)in(lat1)*cos(lat2)*cos(lon2-lon1))
bearing = degrees(bearing)
bearing = (bearing + 360) % 360

C++ float array initialization

You only initialize the first N positions to the values in braces and all others are initialized to 0. In this case, N is the number of arguments you passed to the initialization list, i.e.,

float arr1[10] = { };       // all elements are 0
float arr2[10] = { 0 };     // all elements are 0
float arr3[10] = { 1 };     // first element is 1, all others are 0
float arr4[10] = { 1, 2 };  // first element is 1, second is 2, all others are 0

What does '&' do in a C++ declaration?

In this context & is causing the function to take stringname by reference. The difference between references and pointers is:

  • When you take a reference to a variable, that reference is the variable you referenced. You don't need to dereference it or anything, working with the reference is sematically equal to working with the referenced variable itself.
  • NULL is not a valid value to a reference and will result in a compiler error. So generally, if you want to use an output parameter (or a pointer/reference in general) in a C++ function, and passing a null value to that parameter should be allowed, then use a pointer (or smart pointer, preferably). If passing a null value makes no sense for that function, use a reference.
  • You cannot 're-seat' a reference. While the value of a pointer can be changed to point at something else, a reference has no similar functionality. Once you take a variable by reference, you are effectively dealing with that variable directly. Just like you can't change the value of a by writing b = 4;. A reference's value is the value of whatever it referenced.

Java Date cut off time information

Just a quick update in light of the java.time classes now built into Java 8 and later.

LocalDateTime has a truncatedTo method that effectively addresses what you are talking about here:

LocalDateTime.now().truncatedTo(ChronoUnit.MINUTES)

This will express the current time down to minutes only:

2015-03-05T11:47

You may use a ChronoUnit (or a TemporalUnit) smaller than DAYS to execute the truncation (as the truncation is applied only to the time part of LocalDateTime, not to the date part).

Merge unequal dataframes and replace missing rows with 0

Or, as an alternative to @Chase's code, being a recent plyr fan with a background in databases:

require(plyr)
zz<-join(df1, df2, type="left")
zz[is.na(zz)] <- 0

! [rejected] master -> master (fetch first)

As it is stated in the Error message you have to "fetch first." This worked for me. Use the command:

  1. git fetch origin master

Then follow these steps to merge:

  1. git pull origin master
  2. git add .
  3. git commit -m 'your commit message'
  4. git push origin master

Loop through columns and add string lengths as new columns

You can use lapply to pass each column to str_length, then cbind it to your original data.frame...

library(stringr)

out <- lapply( df , str_length )    
df <- cbind( df , out )

#     col1     col2 col1 col2
#1     abc adf qqwe    3    8
#2    abcd        d    4    1
#3       a        e    1    1
#4 abcdefg        f    7    1

Matplotlib scatterplot; colour as a function of a third variable

In matplotlib grey colors can be given as a string of a numerical value between 0-1.
For example c = '0.1'

Then you can convert your third variable in a value inside this range and to use it to color your points.
In the following example I used the y position of the point as the value that determines the color:

from matplotlib import pyplot as plt

x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [125, 32, 54, 253, 67, 87, 233, 56, 67]

color = [str(item/255.) for item in y]

plt.scatter(x, y, s=500, c=color)

plt.show()

enter image description here

How to parse JSON and access results

If your $result variable is a string json like, you must use json_decode function to parse it as an object or array:

$result = '{"Cancelled":false,"MessageID":"402f481b-c420-481f-b129-7b2d8ce7cf0a","Queued":false,"SMSError":2,"SMSIncomingMessages":null,"Sent":false,"SentDateTime":"\/Date(-62135578800000-0500)\/"}';
$json = json_decode($result, true);
print_r($json);

OUTPUT

Array
(
    [Cancelled] => 
    [MessageID] => 402f481b-c420-481f-b129-7b2d8ce7cf0a
    [Queued] => 
    [SMSError] => 2
    [SMSIncomingMessages] => 
    [Sent] => 
    [SentDateTime] => /Date(-62135578800000-0500)/
)

Now you can work with $json variable as an array:

echo $json['MessageID'];
echo $json['SMSError'];
// other stuff

References:

How do I set proxy for chrome in python webdriver?

from selenium import webdriver
from selenium.webdriver.common.proxy import *

myProxy = "86.111.144.194:3128"
proxy = Proxy({
    'proxyType': ProxyType.MANUAL,
    'httpProxy': myProxy,
    'ftpProxy': myProxy,
    'sslProxy': myProxy,
    'noProxy':''})

driver = webdriver.Firefox(proxy=proxy)
driver.set_page_load_timeout(30)
driver.get('http://whatismyip.com')

How to use function srand() with time.h?

Try to call randomize() before rand() to initialize random generator.

(look at: srand() — why call it only once?)

How to convert Moment.js date to users local timezone?

Use utcOffset function.

var testDateUtc = moment.utc("2015-01-30 10:00:00");
var localDate = moment(testDateUtc).utcOffset(10 * 60); //set timezone offset in minutes
console.log(localDate.format()); //2015-01-30T20:00:00+10:00

How do I deserialize a complex JSON object in C# .NET?

I am using following:

    using System.Web.Script.Serialization;       

    ...

    public static T ParseResponse<T>(string data)
    {
        return new JavaScriptSerializer().Deserialize<T>(data);
    }

Cannot find libcrypto in Ubuntu

I solved this on 12.10 by installing libssl-dev.

sudo apt-get install libssl-dev

Add regression line equation and R^2 on graph

I changed a few lines of the source of stat_smooth and related functions to make a new function that adds the fit equation and R squared value. This will work on facet plots too!

library(devtools)
source_gist("524eade46135f6348140")
df = data.frame(x = c(1:100))
df$y = 2 + 5 * df$x + rnorm(100, sd = 40)
df$class = rep(1:2,50)
ggplot(data = df, aes(x = x, y = y, label=y)) +
  stat_smooth_func(geom="text",method="lm",hjust=0,parse=TRUE) +
  geom_smooth(method="lm",se=FALSE) +
  geom_point() + facet_wrap(~class)

enter image description here

I used the code in @Ramnath's answer to format the equation. The stat_smooth_func function isn't very robust, but it shouldn't be hard to play around with it.

https://gist.github.com/kdauria/524eade46135f6348140. Try updating ggplot2 if you get an error.

How do you tell if a string contains another string in POSIX sh?

See the manpage for the 'test' program. If you're just testing for the existence of a directory you would normally do something like so:

if test -d "String1"; then
  echo "String1 present"
end

If you're actually trying to match a string you can use bash expansion rules & wildcards as well:

if test -d "String*"; then
  echo "A directory starting with 'String' is present"
end

If you need to do something more complex you'll need to use another program like expr.

Best practice for localization and globalization of strings and labels

As far as I know, there's a good library called localeplanet for Localization and Internationalization in JavaScript. Furthermore, I think it's native and has no dependencies to other libraries (e.g. jQuery)

Here's the website of library: http://www.localeplanet.com/

Also look at this article by Mozilla, you can find very good method and algorithms for client-side translation: http://blog.mozilla.org/webdev/2011/10/06/i18njs-internationalize-your-javascript-with-a-little-help-from-json-and-the-server/

The common part of all those articles/libraries is that they use a i18n class and a get method (in some ways also defining an smaller function name like _) for retrieving/converting the key to the value. In my explaining the key means that string you want to translate and the value means translated string.
Then, you just need a JSON document to store key's and value's.

For example:

var _ = document.webL10n.get;
alert(_('test'));

And here the JSON:

{ test: "blah blah" }

I believe using current popular libraries solutions is a good approach.

How to get element by innerText

You could use xpath to accomplish this

var xpath = "//a[text()='SearchingText']";
var matchingElement = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

You can also search of an element containing some text using this xpath:

var xpath = "//a[contains(text(),'Searching')]";

JavaScript: How to find out if the user browser is Chrome?

_x000D_
_x000D_
console.log(JSON.stringify({_x000D_
  isAndroid: /Android/.test(navigator.userAgent),_x000D_
  isCordova: !!window.cordova,_x000D_
  isEdge: /Edge/.test(navigator.userAgent),_x000D_
  isFirefox: /Firefox/.test(navigator.userAgent),_x000D_
  isChrome: /Google Inc/.test(navigator.vendor),_x000D_
  isChromeIOS: /CriOS/.test(navigator.userAgent),_x000D_
  isChromiumBased: !!window.chrome && !/Edge/.test(navigator.userAgent),_x000D_
  isIE: /Trident/.test(navigator.userAgent),_x000D_
  isIOS: /(iPhone|iPad|iPod)/.test(navigator.platform),_x000D_
  isOpera: /OPR/.test(navigator.userAgent),_x000D_
  isSafari: /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent),_x000D_
  isTouchScreen: ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch,_x000D_
  isWebComponentsSupported: 'registerElement' in document && 'import' in document.createElement('link') && 'content' in document.createElement('template')_x000D_
}, null, '  '));
_x000D_
_x000D_
_x000D_

Embed an External Page Without an Iframe?

HTML Imports, part of the Web Components cast, is also a way to include HTML documents in other HTML documents. See http://www.html5rocks.com/en/tutorials/webcomponents/imports/

Python unittest - opposite of assertRaises?

def run_test(self):
    try:
        myFunc()
    except ExceptionType:
        self.fail("myFunc() raised ExceptionType unexpectedly!")

use localStorage across subdomains

This is how:

[November 2020 Update: This solution relies on being able to set document.domain. The ability to do that has now been deprecated, unfortunately.]

For sharing between subdomains of a given superdomain (e.g. example.com), there's a technique you can use in that situation. It can be applied to localStorage, IndexedDB, SharedWorker, BroadcastChannel, etc, all of which offer shared functionality between same-origin pages, but for some reason don't respect any modification to document.domain that would let them use the superdomain as their origin directly.

(1) Pick one "main" domain to for the data to belong to: i.e. either https://example.com or https://www.example.com will hold your localStorage data. Let's say you pick https://example.com.

(2) Use localStorage normally for that chosen domain's pages.

(3) On all https://www.example.com pages (the other domain), use javascript to set document.domain = "example.com";. Then also create a hidden <iframe>, and navigate it to some page on the chosen https://example.com domain (It doesn't matter what page, as long as you can insert a very little snippet of javascript on there. If you're creating the site, just make an empty page specifically for this purpose. If you're writing an extension or a Greasemonkey-style userscript and so don't have any control over pages on the example.com server, just pick the most lightweight page you can find and insert your script into it. Some kind of "not found" page would probably be fine).

(4) The script on the hidden iframe page need only (a) set document.domain = "example.com";, and (b) notify the parent window when this is done. After that, the parent window can access the iframe window and all its objects without restriction! So the minimal iframe page is something like:

<!doctype html>
<html>
<head>
  <script>
    document.domain = "example.com";
    window.parent.iframeReady();  // function defined & called on parent window
  </script>
</head>
<body></body>
</html>

If writing a userscript, you might not want to add externally-accessible functions such as iframeReady() to your unsafeWindow, so instead a better way to notify the main window userscript might be to use a custom event:

    window.parent.dispatchEvent(new CustomEvent("iframeReady"));

Which you'd detect by adding a listener for the custom "iframeReady" event to your main page's window.

(NOTE: You need to set document.domain = "example.com" even if the iframe's domain is already example.com: Assigning a value to document.domain implicitly sets the origin's port to null, and both ports must match for the iframe and its parent to be considered same-origin. See the note here: https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy#Changing_origin)

(5) Once the hidden iframe has informed its parent window that it's ready, script in the parent window can just use iframe.contentWindow.localStorage, iframe.contentWindow.indexedDB, iframe.contentWindow.BroadcastChannel, iframe.contentWindow.SharedWorker instead of window.localStorage, window.indexedDB, etc. ...and all these objects will be scoped to the chosen https://example.com origin - so they'll have the this same shared origin for all of your pages!

The most awkward part of this technique is that you have to wait for the iframe to load before proceeding. So you can't just blithely start using localStorage in your DOMContentLoaded handler, for example. Also you might want to add some error handling to detect if the hidden iframe fails to load correctly.

Obviously, you should also make sure the hidden iframe is not removed or navigated during the lifetime of your page... OTOH I don't know what the result of that would be, but very likely bad things would happen.

And, a caveat: setting/changing document.domain can be blocked using the Feature-Policy header, in which case this technique will not be usable as described.


However, there is a significantly more-complicated generalization of this technique, that can't be blocked by Feature-Policy, and that also allows entirely unrelated domains to share data, communications, and shared workers (i.e. not just subdomains off a common superdomain). @Mayank Jain already described it in their answer, namely:

The general idea is that, just as above, you create a hidden iframe to provide the correct origin for access; but instead of then just grabbing the iframe window's properties directly, you use script inside the iframe to do all of the work, and you communicate between the iframe and your main window only using postMessage() and addEventListener("message",...).

This works because postMessage() can be used even between different-origin windows. But it's also significantly more complicated because you have to pass everything through some kind of messaging infrastructure that you create between the iframe and the main window, rather than just using the localStorage, IndexedDB, etc. APIs directly in your main window's code.

Can we use join for two different database tables?

You could use Synonyms part in the database.

enter image description here

Then in view wizard from Synonyms tab find your saved synonyms and add to view and set inner join simply. enter image description here

How do you express binary literals in Python?

I've tried this in Python 3.6.9

Convert Binary to Decimal

>>> 0b101111
47

>>> int('101111',2)
47

Convert Decimal to binary

>>> bin(47)
'0b101111'

Place a 0 as the second parameter python assumes it as decimal.

>>> int('101111',0)
101111

Difference in Months between two dates in JavaScript

Calculate the difference between two dates include fraction of month (days).


var difference = (date2.getDate() - date1.getDate()) / 30 +
    date2.getMonth() - date1.getMonth() +
    (12 * (date2.getFullYear() - date1.getFullYear()));

For example:
date1: 24/09/2015 (24th Sept 2015)
date2: 09/11/2015 (9th Nov 2015)
the difference: 2.5 (months)

How to convert a column of DataTable to a List

1.Very Simple Code to iterate datatable and get columns in list.

2.code ==>>>

 foreach (DataColumn dataColumn in dataTable.Columns)
 {
    var list = dataTable.Rows.OfType<DataRow>()
     .Select(dataRow => dataRow.Field<string> 
       (dataColumn.ToString())).ToList();
 }

Proper use of 'yield return'

I would have used version 2 of the code in this case. Since you have the full-list of products available and that's what expected by the "consumer" of this method call, it would be required to send the complete information back to the caller.

If caller of this method requires "one" information at a time and the consumption of the next information is on-demand basis, then it would be beneficial to use yield return which will make sure the command of execution will be returned to the caller when a unit of information is available.

Some examples where one could use yield return is:

  1. Complex, step-by-step calculation where caller is waiting for data of a step at a time
  2. Paging in GUI - where user might never reach to the last page and only sub-set of information is required to be disclosed on current page

To answer your questions, I would have used the version 2.

Error: Uncaught (in promise): Error: Cannot match any routes Angular 2

This May be helpful:

//I personally prefer dynamic import (angular 8)
{ path: 'pages', loadChildren: () => import('./pages/pages.module').then(mod => mod.PageModule) }

In child routing it should look like: { path: 'about', component: AboutComponent },

Note that there is no pages in path of child routing and in routerLink or nsRouterLink it should look like routerLink="/pages/about"

I hope thi help someone out there.

How long would it take a non-programmer to learn C#, the .NET Framework, and SQL?

Build on what you already know and have a look at lot of job adverts. E.g I have seen jobs asking for WinForms/WPF AND electronics for the writing of a UI to control a custom bit of hardware.

You may find the “robotics” .net toolkit interesting.

.Net is now too big for anyone to learn both WEB and Desktop so you have to decide the way you are going to go. Web has lots more jobs, but there are very few people with good desktop stills.

Accessing Session Using ASP.NET Web API

MVC

For an MVC project make the following changes (WebForms and Dot Net Core answer down below):

WebApiConfig.cs

public static class WebApiConfig
{
    public static string UrlPrefix         { get { return "api"; } }
    public static string UrlPrefixRelative { get { return "~/api"; } }

    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: WebApiConfig.UrlPrefix + "/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Global.asax.cs

public class MvcApplication : System.Web.HttpApplication
{
    ...

    protected void Application_PostAuthorizeRequest()
    {
        if (IsWebApiRequest())
        {
            HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
        }
    }

    private bool IsWebApiRequest()
    {
        return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(WebApiConfig.UrlPrefixRelative);
    }

}

This solution has the added bonus that we can fetch the base URL in javascript for making the AJAX calls:

_Layout.cshtml

<body>
    @RenderBody()

    <script type="text/javascript">
        var apiBaseUrl = '@Url.Content(ProjectNameSpace.WebApiConfig.UrlPrefixRelative)';
    </script>

    @RenderSection("scripts", required: false) 

and then within our Javascript files/code we can make our webapi calls that can access the session:

$.getJSON(apiBaseUrl + '/MyApi')
   .done(function (data) {
       alert('session data received: ' + data.whatever);
   })
);

WebForms

Do the above but change the WebApiConfig.Register function to take a RouteCollection instead:

public static void Register(RouteCollection routes)
{
    routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: WebApiConfig.UrlPrefix + "/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

And then call the following in Application_Start:

WebApiConfig.Register(RouteTable.Routes);

Dot Net Core

Add the Microsoft.AspNetCore.Session NuGet package and then make the following code changes:

Startup.cs

Call the AddDistributedMemoryCache and AddSession methods on the services object within the ConfigureServices function:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    ...

    services.AddDistributedMemoryCache();
    services.AddSession();

and in the Configure function add a call to UseSession:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
ILoggerFactory loggerFactory)
{
    app.UseSession();
    app.UseMvc();

SessionController.cs

Within your controller, add a using statement at the top:

using Microsoft.AspNetCore.Http;

and then use the HttpContext.Session object within your code like so:

    [HttpGet("set/{data}")]
    public IActionResult setsession(string data)
    {
        HttpContext.Session.SetString("keyname", data);
        return Ok("session data set");
    }

    [HttpGet("get")]
    public IActionResult getsessiondata()
    {
        var sessionData = HttpContext.Session.GetString("keyname");
        return Ok(sessionData);
    }

you should now be able to hit:

http://localhost:1234/api/session/set/thisissomedata

and then going to this URL will pull it out:

http://localhost:1234/api/session/get

Plenty more info on accessing session data within dot net core here: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state

Performance Concerns

Read Simon Weaver's answer below regarding performance. If you're accessing session data inside a WebApi project it can have very serious performance consequence - I have seen ASP.NET enforce a 200ms delay for concurrent requests. This could add up and become disastrous if you have many concurrent requests.


Security Concerns

Make sure you are locking down resources per user - an authenticated user shouldn't be able to retrieve data from your WebApi that they don't have access to.

Read Microsoft's article on Authentication and Authorization in ASP.NET Web API - https://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api

Read Microsoft's article on avoiding Cross-Site Request Forgery hack attacks. (In short, check out the AntiForgery.Validate method) - https://www.asp.net/web-api/overview/security/preventing-cross-site-request-forgery-csrf-attacks

Adding a Scrollable JTextArea (Java)

You don't need two JScrollPanes.

Example:

JTextArea ta = new JTextArea();
JScrollPane sp = new JScrollPane(ta);  

// Add the scroll pane into the content pane
JFrame f = new JFrame();
f.getContentPane().add(sp);

X-Frame-Options: ALLOW-FROM in firefox and chrome

I posted this question and never saw the feedback (which came in several months after, it seems :).

As Kinlan mentioned, ALLOW-FROM is not supported in all browsers as an X-Frame-Options value.

The solution was to branch based on browser type. For IE, ship X-Frame-Options. For everyone else, ship X-Content-Security-Policy.

Hope this helps, and sorry for taking so long to close the loop!

Is it possible in Java to catch two exceptions in the same catch block?

Java 7 and later

Multiple-exception catches are supported, starting in Java 7.

The syntax is:

try {
     // stuff
} catch (Exception1 | Exception2 ex) {
     // Handle both exceptions
}

The static type of ex is the most specialized common supertype of the exceptions listed. There is a nice feature where if you rethrow ex in the catch, the compiler knows that only one of the listed exceptions can be thrown.


Java 6 and earlier

Prior to Java 7, there are ways to handle this problem, but they tend to be inelegant, and to have limitations.

Approach #1

try {
     // stuff
} catch (Exception1 ex) {
     handleException(ex);
} catch (Exception2 ex) {
     handleException(ex);
}

public void handleException(SuperException ex) {
     // handle exception here
}

This gets messy if the exception handler needs to access local variables declared before the try. And if the handler method needs to rethrow the exception (and it is checked) then you run into serious problems with the signature. Specifically, handleException has to be declared as throwing SuperException ... which potentially means you have to change the signature of the enclosing method, and so on.

Approach #2

try {
     // stuff
} catch (SuperException ex) {
     if (ex instanceof Exception1 || ex instanceof Exception2) {
         // handle exception
     } else {
         throw ex;
     }
}

Once again, we have a potential problem with signatures.

Approach #3

try {
     // stuff
} catch (SuperException ex) {
     if (ex instanceof Exception1 || ex instanceof Exception2) {
         // handle exception
     }
}

If you leave out the else part (e.g. because there are no other subtypes of SuperException at the moment) the code becomes more fragile. If the exception hierarchy is reorganized, this handler without an else may end up silently eating exceptions!

How to check if a file exists in a folder?

if (File.Exists(localUploadDirectory + "/" + fileName))
{                        
    `Your code here`
}

Retrieve all values from HashMap keys in an ArrayList Java

Java 8 solution for produce string like "key1: value1,key2: value2"

private static String hashMapToString(HashMap<String, String> hashMap) {

    return hashMap.keySet().stream()
            .map((key) -> key + ": " + hashMap.get(key))
            .collect(Collectors.joining(","));

}

and produce a list simple collect as list

private static List<String> hashMapToList(HashMap<String, String> hashMap) {

    return hashMap.keySet().stream()
            .map((key) -> key + ": " + hashMap.get(key))
            .collect(Collectors.toList());

}

MySQL Alter Table Add Field Before or After a field already present

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark` 
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          AFTER `<TABLE COLUMN BEFORE THIS COLUMN>`";

I believe you need to have ADD COLUMN and use AFTER, not BEFORE.

In case you want to place column at the beginning of a table, use the FIRST statement:

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          FIRST";

http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

How to determine device screen size category (small, normal, large, xlarge) using code?

Jeff Gilfelt's answer as a static helper method:

private static String getSizeName(Context context) {
    int screenLayout = context.getResources().getConfiguration().screenLayout;
    screenLayout &= Configuration.SCREENLAYOUT_SIZE_MASK;

    switch (screenLayout) {
    case Configuration.SCREENLAYOUT_SIZE_SMALL:
        return "small";
    case Configuration.SCREENLAYOUT_SIZE_NORMAL:
        return "normal";
    case Configuration.SCREENLAYOUT_SIZE_LARGE:
        return "large";
    case 4: // Configuration.SCREENLAYOUT_SIZE_XLARGE is API >= 9
        return "xlarge";
    default:
        return "undefined";
    }
}

Raise error in a Bash script

There are a couple more ways with which you can approach this problem. Assuming one of your requirement is to run a shell script/function containing a few shell commands and check if the script ran successfully and throw errors in case of failures.

The shell commands in generally rely on exit-codes returned to let the shell know if it was successful or failed due to some unexpected events.

So what you want to do falls upon these two categories

  • exit on error
  • exit and clean-up on error

Depending on which one you want to do, there are shell options available to use. For the first case, the shell provides an option with set -e and for the second you could do a trap on EXIT

Should I use exit in my script/function?

Using exit generally enhances readability In certain routines, once you know the answer, you want to exit to the calling routine immediately. If the routine is defined in such a way that it doesn’t require any further cleanup once it detects an error, not exiting immediately means that you have to write more code.

So in cases if you need to do clean-up actions on script to make the termination of the script clean, it is preferred to not to use exit.

Should I use set -e for error on exit?

No!

set -e was an attempt to add "automatic error detection" to the shell. Its goal was to cause the shell to abort any time an error occurred, but it comes with a lot of potential pitfalls for example,

  • The commands that are part of an if test are immune. In the example, if you expect it to break on the test check on the non-existing directory, it wouldn't, it goes through to the else condition

    set -e
    f() { test -d nosuchdir && echo no dir; }
    f
    echo survived
    
  • Commands in a pipeline other than the last one, are immune. In the example below, because the most recently executed (rightmost) command's exit code is considered ( cat) and it was successful. This could be avoided by setting by the set -o pipefail option but its still a caveat.

    set -e
    somecommand that fails | cat -
    echo survived 
    

Recommended for use - trap on exit

The verdict is if you want to be able to handle an error instead of blindly exiting, instead of using set -e, use a trap on the ERR pseudo signal.

The ERR trap is not to run code when the shell itself exits with a non-zero error code, but when any command run by that shell that is not part of a condition (like in if cmd, or cmd ||) exits with a non-zero exit status.

The general practice is we define an trap handler to provide additional debug information on which line and what cause the exit. Remember the exit code of the last command that caused the ERR signal would still be available at this point.

cleanup() {
    exitcode=$?
    printf 'error condition hit\n' 1>&2
    printf 'exit code returned: %s\n' "$exitcode"
    printf 'the command executing at the time of the error was: %s\n' "$BASH_COMMAND"
    printf 'command present on line: %d' "${BASH_LINENO[0]}"
    # Some more clean up code can be added here before exiting
    exit $exitcode
}

and we just use this handler as below on top of the script that is failing

trap cleanup ERR

Putting this together on a simple script that contained false on line 15, the information you would be getting as

error condition hit
exit code returned: 1
the command executing at the time of the error was: false
command present on line: 15

The trap also provides options irrespective of the error to just run the cleanup on shell completion (e.g. your shell script exits), on signal EXIT. You could also trap on multiple signals at the same time. The list of supported signals to trap on can be found on the trap.1p - Linux manual page

Another thing to notice would be to understand that none of the provided methods work if you are dealing with sub-shells are involved in which case, you might need to add your own error handling.

  • On a sub-shell with set -e wouldn't work. The false is restricted to the sub-shell and never gets propagated to the parent shell. To do the error handling here, add your own logic to do (false) || false

    set -e
    (false)
    echo survived
    
  • The same happens with trap also. The logic below wouldn't work for the reasons mentioned above.

    trap 'echo error' ERR
    (false)
    

How to render an array of objects in React?

import React from 'react';

class RentalHome extends React.Component{
    constructor(){
        super();
        this.state = {
            rentals:[{
                _id: 1,
                title: "Nice Shahghouse Biryani",
                city: "Hyderabad",
                category: "condo",
                image: "http://via.placeholder.com/350x250",
                numOfRooms: 4,
                shared: true,
                description: "Very nice apartment in center of the city.",
                dailyPrice: 43
              },
              {
                _id: 2,
                title: "Modern apartment in center",
                city: "Bangalore",
                category: "apartment",
                image: "http://via.placeholder.com/350x250",
                numOfRooms: 1,
                shared: false,
                description: "Very nice apartment in center of the city.",
                dailyPrice: 11
              },
              {
                _id: 3,
                title: "Old house in nature",
                city: "Patna",
                category: "house",
                image: "http://via.placeholder.com/350x250",
                numOfRooms: 5,
                shared: true,
                description: "Very nice apartment in center of the city.",
                dailyPrice: 23
              }]
        }
    }
    render(){
        const {rentals} = this.state;
        return(
            <div className="card-list">
                <div className="container">
                    <h1 className="page-title">Your Home All Around the World</h1>
                    <div className="row">
                        {
                            rentals.map((rental)=>{
                                return(
                                    <div key={rental._id} className="col-md-3">
                                        <div className="card bwm-card">
                                        <img 
                                        className="card-img-top" 
                                        src={rental.image}
                                        alt={rental.title} />
                                        <div className="card-body">
                                        <h6 className="card-subtitle mb-0 text-muted">
                                            {rental.shared} {rental.category} {rental.city}
                                        </h6>
                                        <h5 className="card-title big-font">
                                            {rental.title}
                                        </h5>
                                        <p className="card-text">
                                            ${rental.dailyPrice} per Night &#183; Free Cancelation
                                        </p>
                                        </div>
                                        </div>
                                    </div>
                                )
                            })
                        }
                        
                    </div>
                </div>
            </div>
        )
    }
}

export default RentalHome;

Iterating through a List Object in JSP

change the code to the following

<%! List eList = (ArrayList)session.getAttribute("empList");%>
....
<table>
    <%
    for(int i=0; i<eList.length;i++){%>
        <tr>
            <td><%= ((Employee)eList[i]).getEid() %></td>
            <td><%= ((Employee)eList[i]).getEname() %></td>  
        </tr>
      <%}%>
</table>

Storing and Retrieving ArrayList values from hashmap

Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
     Map.Entry pairs = (Map.Entry)it.next();

     if(pairs.getKey().equals("mango"))
     {
        map.put(pairs.getKey(), pairs.getValue().add(18));
     }

     else if(!map.containsKey("mango"))
     {
        List<Integer> ints = new ArrayList<Integer>();
        ints.add(18);
        map.put("mango",ints);
     }

     it.remove(); // avoids a ConcurrentModificationException
}

EDIT: So inside the while try this:

map.put(pairs.getKey(), pairs.getValue().add(number))

You are getting the error because you are trying to put an integer to the values, whereas it is expected an ArrayList.

EDIT 2: Then put the following inside your while loop:

if(pairs.getKey().equals("mango"))
{
    map.put(pairs.getKey(), pairs.getValue().add(18));
}

else if(!map.containsKey("mango"))
{
     List<Integer> ints = new ArrayList<Integer>();
     ints.add(18);
     map.put("mango",ints);
 }

EDIT 3: By reading your requirements, I come to think you may not need a loop. You may want to only check if the map contains the key mango, and if it does add 18, else create a new entry in the map with key mango and value 18.

So all you may need is the following, without the loop:

if(map.containsKey("mango"))
{
    map.put("mango", map.get("mango).add(18));
}

else
{
    List<Integer> ints = new ArrayList<Integer>();
    ints.add(18);
    map.put("mango", ints);
}

Add data dynamically to an Array

Let's say you have defined an empty array:

$myArr = array();

If you want to simply add an element, e.g. 'New Element to Array', write

$myArr[] = 'New Element to Array';

if you are calling the data from the database, below code will work fine

$sql = "SELECT $element FROM $table";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0)//if it finds any row
{
   while($result = mysql_fetch_object($query))
   {
      //adding data to the array
      $myArr[] = $result->$element;
   }
}

Removing nan values from an array

If you're using numpy for your arrays, you can also use

x = x[numpy.logical_not(numpy.isnan(x))]

Equivalently

x = x[~numpy.isnan(x)]

[Thanks to chbrown for the added shorthand]

Explanation

The inner function, numpy.isnan returns a boolean/logical array which has the value True everywhere that x is not-a-number. As we want the opposite, we use the logical-not operator, ~ to get an array with Trues everywhere that x is a valid number.

Lastly we use this logical array to index into the original array x, to retrieve just the non-NaN values.

Adding values to specific DataTable cells

If anyone is looking for an updated correct syntax for this as I was, try the following:

Example:
dg.Rows[0].Cells[6].Value = "test";

Copying files using rsync from remote server to local machine

If you have SSH access, you don't need to SSH first and then copy, just use Secure Copy (SCP) from the destination.

scp user@host:/path/file /localpath/file

Wild card characters are supported, so

scp user@host:/path/folder/* /localpath/folder

will copy all of the remote files in that folder.If copying more then one directory.

note -r will copy all sub-folders and content too.

How to check if NSString begins with a certain character

Use characterAtIndex:. If the first character is an asterisk, use substringFromIndex: to get the string sans '*'.

Mapping two integers to one, in a unique and deterministic way

For positive integers as arguments and where argument order doesn't matter:

  1. Here's an unordered pairing function:

    <x, y> = x * y + trunc((|x - y| - 1)^2 / 4) = <y, x>
    
  2. For x ? y, here's a unique unordered pairing function:

    <x, y> = if x < y:
               x * (y - 1) + trunc((y - x - 2)^2 / 4)
             if x > y:
               (x - 1) * y + trunc((x - y - 2)^2 / 4)
           = <y, x>
    

Apache Spark: The number of cores vs. the number of executors

Spark Dynamic allocation gives flexibility and allocates resources dynamically. In this number of min and max executors can be given. Also the number of executors that has to be launched at the starting of the application can also be given.

Read below on the same:

http://spark.apache.org/docs/latest/configuration.html#dynamic-allocation

Preventing scroll bars from being hidden for MacOS trackpad users in WebKit/Blink

For a one-page web application where I add scrollable sections dynamically, I trigger OSX's scrollbars by programmatically scrolling one pixel down and back up:

// Plain JS:
var el = document.getElementById('scrollable-section');
el.scrollTop = 1;
el.scrollTop = 0;

// jQuery:
$('#scrollable-section').scrollTop(1).scrollTop(0);

This triggers the visual cue fading in and out.

int object is not iterable?

Well, you want to process the string representing the number, iterating over the digits, not the number itself (which is an abstract entity that could be written differently, like "CX" in Roman numerals or "0x6e" hexadecimal (both for 110) or whatever).

Therefore:

inp = input('Enter a number:')

n = 0
for digit in inp:
     n = n + int(digit)
     print(n)

Note that the n = 0 is required (someplace before entry into the loop). You can't take the value of a variable which doesn't exist (and the right hand side of n = n + int(digit) takes the value of n). And if n does exist at that point, it might hold something completely unrelated to your present needs, leading to unexpected behaviour; you need to guard against that.

This solution makes no attempt to ensure that the input provided by the user is actually a number. I'll leave this problem for you to think about (hint: all that you need is there in the Python tutorial).

List of all unique characters in a string?

The simplest solution is probably:

In [10]: ''.join(set('aaabcabccd'))
Out[10]: 'acbd'

Note that this doesn't guarantee the order in which the letters appear in the output, even though the example might suggest otherwise.

You refer to the output as a "list". If a list is what you really want, replace ''.join with list:

In [1]: list(set('aaabcabccd'))
Out[1]: ['a', 'c', 'b', 'd']

As far as performance goes, worrying about it at this stage sounds like premature optimization.

How to remove all CSS classes using jQuery/JavaScript?

You can just try

$(document).ready(function() {
   $('body').find('#item').removeClass();
});

If you have to access to that element without class name, for example you have to add a new class name, you can do that:

$(document).ready(function() {
   $('body').find('#item').removeClass().addClass('class-name');
});

I use that function in my projet to remove and add class in a html builder. Good luck.

Selecting the last value of a column

In a column with blanks, you can get the last value with

=+sort(G:G,row(G:G)*(G:G<>""),)

Error retrieving parent for item: No resource found that matches the given name '@android:style/TextAppearance.Holo.Widget.ActionBar.Title'

<style name="Theme.IOSched" parent="android:style/Theme.Holo.Light">
    <item name="android:windowBackground">@drawable/window_background</item>
    <item name="android:actionBarStyle">@style/ActionBar</item>
</style>

you can not give your own color and backgroud in item windowBackground. give your color in your /color.xml file.

How do I move a table into a schema in T-SQL

ALTER SCHEMA TargetSchema 
    TRANSFER SourceSchema.TableName;

If you want to move all tables into a new schema, you can use the undocumented (and to be deprecated at some point, but unlikely!) sp_MSforeachtable stored procedure:

exec sp_MSforeachtable "ALTER SCHEMA TargetSchema TRANSFER ?"

Ref.: ALTER SCHEMA

SQL 2008: How do I change db schema to dbo

Select default option value from typescript angular 6

For reactive form, I managed to make it work by using the following example (47 can be replaced with other value or variable):

<div [formGroup]="form">
  <select formControlName="fieldName">
    <option
        *ngFor="let option of options; index as i"
        [selected]="option === 47"
    >
        {{ option }}
    </option>
  </select>
</div>

How to get response body using HttpURLConnection, when code other than 2xx is returned?

If the response code isn't 200 or 2xx, use getErrorStream() instead of getInputStream().

Change background color of selected item on a ListView

I'm also doing the similar thing: highlight the selected list item's background (change it to red) and set text color within the item to white.

I can think out a "simple but not efficient" way: maintain a selected item's position in the custom adapter, and change it in the ListView's OnItemClickListener implement:

// The OnItemClickListener implementation
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    mListViewAdapter.setSelectedItem(position);
}

// The custom Adapter
private int mSelectedPosition = -1;
public void setSelectedItem (int itemPosition) {
    mSelectedPosition = itemPosition;
    notifyDataSetChanged();
}

Then update the selected item's background and text color in getView() method.

// The custom Adapter
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ...
    if (position == mSelectedPosition) {
        // customize the selected item's background and sub views
        convertView.setBackgroundColor(YOUR_HIGHLIGHT_COLOR);
        textView.setTextColor(TEXT_COLOR);
    } else {
        ...
    }
}

After searching for a while, I found that many people mentioned about to set android:listSelector="YOUR_SELECTOR". After tried for a while, I found the simplest way to highlight selected ListView item's background can be done with only two lines set to the ListView's layout resource:

android:choiceMode="singleChoice"
android:listSelector="YOUR_COLOR"

There's also other way to make it work, like customize activatedBackgroundIndicator theme. But I think that would be a much more generic solution since it will affect the whole theme.

How do you dynamically add elements to a ListView on Android?

First, you have to add a ListView, an EditText and a button into your activity_main.xml.

Now, in your ActivityMain:

private EditText editTxt;
private Button btn;
private ListView list;
private ArrayAdapter<String> adapter;
private ArrayList<String> arrayList;

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

    editTxt = (EditText) findViewById(R.id.editText);
    btn = (Button) findViewById(R.id.button);
    list = (ListView) findViewById(R.id.listView);
    arrayList = new ArrayList<String>();

    // Adapter: You need three parameters 'the context, id of the layout (it will be where the data is shown),
    // and the array that contains the data
    adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, arrayList);

    // Here, you set the data in your ListView
    list.setAdapter(adapter);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // this line adds the data of your EditText and puts in your array
            arrayList.add(editTxt.getText().toString());
            // next thing you have to do is check if your adapter has changed
            adapter.notifyDataSetChanged();
        }
    });
}

This works for me, I hope I helped you

smtp configuration for php mail

PHP's mail() function does not have support for SMTP. You're going to need to use something like the PEAR Mail package.

Here is a sample SMTP mail script:

<?php
require_once("Mail.php");

$from = "Your Name <[email protected]>";
$to = "Their Name <[email protected]>";
$subject = "Subject";
$body = "Lorem ipsum dolor sit amet, consectetur adipiscing elit...";

$host = "mailserver.blahblah.com";
$username = "smtp_username";
$password = "smtp_password";

$headers = array('From' => $from, 'To' => $to, 'Subject' => $subject);

$smtp = Mail::factory('smtp', array ('host' => $host,
                                     'auth' => true,
                                     'username' => $username,
                                     'password' => $password));

$mail = $smtp->send($to, $headers, $body);

if ( PEAR::isError($mail) ) {
    echo("<p>Error sending mail:<br/>" . $mail->getMessage() . "</p>");
} else {
    echo("<p>Message sent.</p>");
}
?>

How can we convert an integer to string in AngularJs

.toString() is available, or just add "" to the end of the int

var x = 3,
    toString = x.toString(),
    toConcat = x + "";

Angular is simply JavaScript at the core.

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

There are great responses here. I would like to keep it short to memorize the difference between partition & buckets.

You generally partition on a less unique column. And bucketing on most unique column.

Example if you consider World population with country, person name and their bio-metric id as an example. As you can guess, country field would be the less unique column and bio-metric id would be the most unique column. So ideally you would need to partition the table by country and bucket it by bio-metric id.

Can I embed a custom font in an iPhone application?

It is very easy to add a new font on your existing iOS App.

You just need to add the font e.g. font.ttf into your Resource Folder.

Open your application info.plist. Add a new row as "Fonts provided by application" and type the font name as font.ttf.

And when setting the font do as setFont:"corresponding Font Name"

You can check whether your font is added or not by NSArray *check = [UIFont familyNames];.

It returns all the font your application support.

Spring Boot: Cannot access REST Controller on localhost (404)

Another solution in case it helps: in my case, the problem was that I had a @RequestMapping("/xxx") at class level (in my controller), and in the exposed services I had @PostMapping (value = "/yyyy") and @GetMapping (value = "/zzz"); once I commented the @RequestMapping("/xxx") and managed all at method level, worked like a charm.

foreach with index

The C# foreach doesn't have a built in index. You'll need to add an integer outside the foreach loop and increment it each time.

int i = -1;
foreach (Widget w in widgets)
{
   i++;
   // do something
}

Alternatively, you could use a standard for loop as follows:

for (int i = 0; i < widgets.Length; i++)
{
   w = widgets[i];
   // do something
}

Is it possible to insert HTML content in XML document?

You can include HTML content. One possibility is encoding it in BASE64 as you have mentioned.

Another might be using CDATA tags.

Example using CDATA:

<xml>
    <title>Your HTML title</title>
    <htmlData><![CDATA[<html>
        <head>
            <script/>
        </head>
        <body>
        Your HTML's body
        </body>
        </html>
     ]]>
    </htmlData>
</xml>

Please note:

CDATA's opening character sequence: <![CDATA[

CDATA's closing character sequence: ]]>

Create table variable in MySQL

They don't exist in MySQL do they? Just use a temp table:

CREATE PROCEDURE my_proc () BEGIN 

CREATE TEMPORARY TABLE TempTable (myid int, myfield varchar(100)); 
INSERT INTO TempTable SELECT tblid, tblfield FROM Table1; 

/* Do some more stuff .... */

From MySQL here

"You can use the TEMPORARY keyword when creating a table. A TEMPORARY table is visible only to the current connection, and is dropped automatically when the connection is closed. This means that two different connections can use the same temporary table name without conflicting with each other or with an existing non-TEMPORARY table of the same name. (The existing table is hidden until the temporary table is dropped.)"

How to get data out of a Node.js http get request

This is my solution, although for sure you can use a lot of modules that give you the object as a promise or similar. Anyway, you were missing another callback

function getData(callbackData){
  var http = require('http');
  var str = '';

  var options = {
        host: 'www.random.org',
        path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
  };

  callback = function(response) {

        response.on('data', function (chunk) {
              str += chunk;
        });

        response.on('end', function () {
              console.log(str);
          callbackData(str);
        });

        //return str;
  }

  var req = http.request(options, callback).end();

  // These just return undefined and empty
  console.log(req.data);
  console.log(str);
}

somewhere else

getData(function(data){
// YOUR CODE HERE!!!
})

Why use pointers?

Here's my anwser, and I won't promse to be an expert, but I've found pointers to be great in one of my libraries I'm trying to write. In this library (It's a graphics API with OpenGL:-)) you can create a triangle with vertex objects passed into them. The draw method takes these triangle objects, and well.. draws them based on the vertex objects i created. Well, its ok.

But, what if i change a vertex coordinate? Move it or something with moveX() in the vertex class? Well, ok, now i have to update the triangle, adding more methods and performance is being wasted because i have to update the triangle every time a vertex moves. Still not a big deal, but it's not that great.

Now, what if i have a mesh with tons of vertices and tons of triangles, and the mesh is rotateing, and moveing, and such. I'll have to update every triangle that uses these vertices, and probably every triangle in the scene because i wouldn't know which ones use which vertices. That's hugely computer intensive, and if I have several meshes ontop of a landscape, oh god! I'm in trouble, because im updateing every triangle almost every frame because these vertices are changing al the time!

With pointers, you don't have to update the triangles.

If I had three *Vertex objects per triangle class, not only am i saving room because a zillion triangles don't have three vertex objects which are large themselves, but also these pointers will always point to the Vertices they are meant to, no matter how often the vertices change. Since the pointers still point to the same vertex, the triangles don't change, and the update process is easier to handle. If I confused you, I wouldn't doubt it, I don't pretend to be an expert, just throwing my two cents into the discussion.

jQuery: Currency Format Number

_x000D_
_x000D_
var input=950000; _x000D_
var output=parseInt(input).toLocaleString(); _x000D_
alert(output);
_x000D_
_x000D_
_x000D_

Can't import database through phpmyadmin file size too large

Its due to PHP that has a file size restriction for uploads.

If you have terminal/shell access then the above answers @Kyotoweb will work.

one way to get it done is that you create an .htaccess/ini file file to change PHP settings to get the sql file uploaded through PHPmyAdmin.

php_value upload_max_filesize 120M //file size
php_value post_max_size 120M
php_value max_execution_time 200
php_value max_input_time 200

Note you should remove this file after upload.

Instagram API - How can I retrieve the list of people a user is following on Instagram

Shiva's answer doesn't apply anymore. The API call "/users/{user-id}/follows" is not supported by Instagram for some time (it was disabled in 2016).

For a while you were able to get only your own followers/followings with "/users/self/follows" endpoint, but Instagram disabled that feature in April 2018 (with the Cambridge Analytica issue). You can read about it here.

As far as I know (at this moment) there isn't a service available (official or unofficial) where you can get the followers/followings of a user (even your own).

How to break out of while loop in Python?

Don't use while True and break statements. It's bad programming.

Imagine you come to debug someone else's code and you see a while True on line 1 and then have to trawl your way through another 200 lines of code with 15 break statements in it, having to read umpteen lines of code for each one to work out what actually causes it to get to the break. You'd want to kill them...a lot.

The condition that causes a while loop to stop iterating should always be clear from the while loop line of code itself without having to look elsewhere.

Phil has the "correct" solution, as it has a clear end condition right there in the while loop statement itself.

Chrome: Uncaught SyntaxError: Unexpected end of input

Since it's an async operation the onreadystatechange may happen before the value has loaded in the responseText, try using a window.setTimeout(function () { JSON.parse(xhr.responseText); }, 1000); to see if the error persists? BOL

Can you force a React component to rerender without calling setState?

forceUpdate(); method will work but it is advisable to use setState();

Using pickle.dump - TypeError: must be str, not bytes

The output file needs to be opened in binary mode:

f = open('varstor.txt','w')

needs to be:

f = open('varstor.txt','wb')

How to make script execution wait until jquery is loaded

You can try onload event. It raised when all scripts has been loaded :

window.onload = function () {
   //jquery ready for use here
}

But keep in mind, that you may override others scripts where window.onload using.

Bi-directional Map in Java?

Apache commons collections has a BidiMap

SQL join format - nested inner joins

Since you've already received help on the query, I'll take a poke at your syntax question:

The first query employs some lesser-known ANSI SQL syntax which allows you to nest joins between the join and on clauses. This allows you to scope/tier your joins and probably opens up a host of other evil, arcane things.

Now, while a nested join cannot refer any higher in the join hierarchy than its immediate parent, joins above it or outside of its branch can refer to it... which is precisely what this ugly little guy is doing:

select
 count(*)
from Table1 as t1
join Table2 as t2
    join Table3 as t3
    on t2.Key = t3.Key                   -- join #1
    and t2.Key2 = t3.Key2 
on t1.DifferentKey = t3.DifferentKey     -- join #2  

This looks a little confusing because join #2 is joining t1 to t2 without specifically referencing t2... however, it references t2 indirectly via t3 -as t3 is joined to t2 in join #1. While that may work, you may find the following a bit more (visually) linear and appealing:

select
 count(*)
from Table1 as t1
    join Table3 as t3
        join Table2 as t2
        on t2.Key = t3.Key                   -- join #1
        and t2.Key2 = t3.Key2   
    on t1.DifferentKey = t3.DifferentKey     -- join #2

Personally, I've found that nesting in this fashion keeps my statements tidy by outlining each tier of the relationship hierarchy. As a side note, you don't need to specify inner. join is implicitly inner unless explicitly marked otherwise.

Pandas left outer join multiple dataframes on multiple columns

Merge them in two steps, df1 and df2 first, and then the result of that to df3.

In [33]: s1 = pd.merge(df1, df2, how='left', on=['Year', 'Week', 'Colour'])

I dropped year from df3 since you don't need it for the last join.

In [39]: df = pd.merge(s1, df3[['Week', 'Colour', 'Val3']],
                       how='left', on=['Week', 'Colour'])

In [40]: df
Out[40]: 
   Year Week Colour  Val1  Val2 Val3
0  2014    A    Red    50   NaN  NaN
1  2014    B    Red    60   NaN   60
2  2014    B  Black    70   100   10
3  2014    C    Red    10    20  NaN
4  2014    D  Green    20   NaN   20

[5 rows x 6 columns]

Android: Background Image Size (in Pixel) which Support All Devices

Check this. This image will show for all icon size for different screen sizes

Size

How do I show the changes which have been staged?

It should just be:

git diff --cached

--cached means show the changes in the cache/index (i.e. staged changes) against the current HEAD. --staged is a synonym for --cached.

--staged and --cached does not point to HEAD, just difference with respect to HEAD. If you cherry pick what to commit using git add --patch (or git add -p), --staged will return what is staged.

div inside table

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  <head>
    <title>test</title>
  </head>
  <body>
    <table>
      <tr>
        <td>
          <div>content</div>
        </td>
      </tr>
    </table>
  </body>
</html>

This document was successfully checked as XHTML 1.0 Transitional!

GroupBy pandas DataFrame and select most common value

The problem here is the performance, if you have a lot of rows it will be a problem.

If it is your case, please try with this:

import pandas as pd

source = pd.DataFrame({'Country' : ['USA', 'USA', 'Russia','USA'], 
              'City' : ['New-York', 'New-York', 'Sankt-Petersburg', 'New-York'],
              'Short_name' : ['NY','New','Spb','NY']})

source.groupby(['Country','City']).agg(lambda x:x.value_counts().index[0])

source.groupby(['Country','City']).Short_name.value_counts().groupby['Country','City']).first()

How to solve Permission denied (publickey) error when using Git?

This error can happen when you are accessing the SSH URL (Read/Write) instead of Git Read-Only URL but you have no write access to that repo.

Sometimes you just want to clone your own repo, e.g. deploy to a server. In this case you actually only need READ-ONLY access. But since that's your own repo, GitHub may display SSH URL if that's your preference. In this situation, if your remote host's public key is not in your GitHub SSH Keys, your access will be denied, which is expected to happen.

An equivalent case is when you try cloning someone else's repo to which you have no write access with SSH URL.

In a word, if your intent is to clone-only a repo, use HTTPS URL (https://github.com/{user_name}/{project_name}.git) instead of SSH URL ([email protected]:{user_name}/{project_name}.git), which avoids (unnecessary) public key validation.


Update: GitHub is displaying HTTPS as the default protocol now and this move can probably reduce possible misuse of SSH URLs.

Update rows in one table with data from another table based on one column in each being equal

You Could always use and leave out the "when not matched section"

merge into table1 FromTable   
   using table2 ToTable
     on     ( FromTable.field1 = ToTable.field1
          and  FromTable.field2 =ToTable.field2)
when Matched then
update set 
  ToTable.fieldr = FromTable.fieldx,
  ToTable.fields = FromTable.fieldy, 
  ToTable.fieldt =  FromTable.fieldz)
when not matched then
  insert  (ToTable.field1,
       ToTable.field2,
       ToTable.fieldr,
       ToTable.fields,
       ToTable.fieldt)
  values (FromTable.field1,
         FromTable.field2,
         FromTable.fieldx,
         FromTable.fieldy,
         FromTable.fieldz);

How do I convert a numpy array to (and display) an image?

Using pillow's fromarray, for example:

from PIL import Image
from numpy import *

im = array(Image.open('image.jpg'))
Image.fromarray(im).show()

Write and read a list from file

Let's define a list first:

lst=[1,2,3]

You can directly write your list to a file:

f=open("filename.txt","w")
f.write(str(lst))
f.close()

To read your list from text file first you read the file and store in a variable:

f=open("filename.txt","r")
lst=f.read()
f.close()

The type of variable lst is of course string. You can convert this string into array using eval function.

lst=eval(lst)

EF Code First "Invalid column name 'Discriminator'" but no inheritance

Another scenario where this occurs is when you have a base class and one or more subclasses, where at least one of the subclasses introduce extra properties:

class Folder {
  [key]
  public string Id { get; set; }

  public string Name { get; set; }
}

// Adds no props, but comes from a different view in the db to Folder:
class SomeKindOfFolder: Folder {
}

// Adds some props, but comes from a different view in the db to Folder:
class AnotherKindOfFolder: Folder {
  public string FolderAttributes { get; set; }
}

If these are mapped in the DbContext like below, the "'Invalid column name 'Discriminator'" error occurs when any type based on Folder base type is accessed:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  modelBuilder.Entity<Folder>().ToTable("All_Folders");
  modelBuilder.Entity<SomeKindOfFolder>().ToTable("Some_Kind_Of_Folders");
  modelBuilder.Entity<AnotherKindOfFolder>().ToTable("Another_Kind_Of_Folders");
}

I found that to fix the issue, we extract the props of Folder to a base class (which is not mapped in OnModelCreating()) like so - OnModelCreating should be unchanged:

class FolderBase {
  [key]
  public string Id { get; set; }

  public string Name { get; set; }
}

class Folder: FolderBase {
}

class SomeKindOfFolder: FolderBase {
}

class AnotherKindOfFolder: FolderBase {
  public string FolderAttributes { get; set; }
}

This eliminates the issue, but I don't know why!

MS SQL 2008 - get all table names and their row counts in a DB

SELECT sc.name +'.'+ ta.name TableName
 ,SUM(pa.rows) RowCnt
 FROM sys.tables ta
 INNER JOIN sys.partitions pa
 ON pa.OBJECT_ID = ta.OBJECT_ID
 INNER JOIN sys.schemas sc
 ON ta.schema_id = sc.schema_id
 WHERE ta.is_ms_shipped = 0 AND pa.index_id IN (1,0)
 GROUP BY sc.name,ta.name
 ORDER BY SUM(pa.rows) DESC

See this:

Android Location Manager, Get GPS location ,if no GPS then get to Network Provider location

You're saying that you need GPS location first if its available, but what you did is first you're getting location from network provider and then from GPS. This will get location from Network and GPS as well if both are available. What you can do is, write these cases in if..else if block. Similar to-

if( !isGPSEnabled && !isNetworkEnabled) {

// Can't get location by any way

} else {

    if(isGPSEnabled) {

    // get location from GPS

    } else if(isNetworkEnabled) {

    // get location from Network Provider

    }
}

So this will fetch location from GPS first (if available), else it will try to fetch location from Network Provider.

EDIT:

To make it better, I'll post a snippet. Consider it is in try-catch:

boolean gps_enabled = false;
boolean network_enabled = false;

LocationManager lm = (LocationManager) mCtx
                .getSystemService(Context.LOCATION_SERVICE);

gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

Location net_loc = null, gps_loc = null, finalLoc = null;

if (gps_enabled)
    gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
    net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

if (gps_loc != null && net_loc != null) {

    //smaller the number more accurate result will
    if (gps_loc.getAccuracy() > net_loc.getAccuracy()) 
        finalLoc = net_loc;
    else
        finalLoc = gps_loc;

        // I used this just to get an idea (if both avail, its upto you which you want to take as I've taken location with more accuracy)

} else {

    if (gps_loc != null) {
        finalLoc = gps_loc;
    } else if (net_loc != null) {
        finalLoc = net_loc;
    }
}

Now you check finalLoc for null, if not then return it. You can write above code in a function which returns the desired (finalLoc) location. I think this might help.

how to use ng-option to set default value of select element

Just to add up, I did something like this.

 <select class="form-control" data-ng-model="itemSelect" ng-change="selectedTemplate(itemSelect)" autofocus>
        <option value="undefined" [selected]="itemSelect.Name == undefined" disabled="disabled">Select template...</option>
        <option ng-repeat="itemSelect in templateLists" value="{{itemSelect.ID}}">{{itemSelect.Name}}</option></select>

PHP - Get array value with a numeric index

I am proposing my idea about it against any disadvantages array_values( ) function, because I think that is not a direct get function. In this way it have to create a copy of the values numerically indexed array and then access. If PHP does not hide a method that automatically translates an integer in the position of the desired element, maybe a slightly better solution might consist of a function that runs the array with a counter until it leads to the desired position, then return the element reached.

So the work would be optimized for very large array of sizes, since the algorithm would be best performing indices for small, stopping immediately. In the solution highlighted of array_values( ), however, it has to do with a cycle flowing through the whole array, even if, for e.g., I have to access $ array [1].

function array_get_by_index($index, $array) {

    $i=0;
    foreach ($array as $value) {
        if($i==$index) {
            return $value;
        }
        $i++;
    }
    // may be $index exceedes size of $array. In this case NULL is returned.
    return NULL;
}

How to set array length in c# dynamically

Does is need to be an array? If you use an ArrayList or one of the other objects available in C#, you won't have this limitation to content with. Hashtable, IDictionnary, IList, etc.. all allow a dynamic number of elements.

What is the SSIS package and what does it do?

For Latest Info About SSIS > https://docs.microsoft.com/en-us/sql/integration-services/sql-server-integration-services

From the above referenced site:

Microsoft Integration Services is a platform for building enterprise-level data integration and data transformations solutions. Use Integration Services to solve complex business problems by copying or downloading files, loading data warehouses, cleansing and mining data, and managing SQL Server objects and data.

Integration Services can extract and transform data from a wide variety of sources such as XML data files, flat files, and relational data sources, and then load the data into one or more destinations.

Integration Services includes a rich set of built-in tasks and transformations, graphical tools for building packages, and the Integration Services Catalog database, where you store, run, and manage packages.

You can use the graphical Integration Services tools to create solutions without writing a single line of code. You can also program the extensive Integration Services object model to create packages programmatically and code custom tasks and other package objects.

Getting Started with SSIS - http://msdn.microsoft.com/en-us/sqlserver/bb671393.aspx

If you are Integration Services Information Worker - http://msdn.microsoft.com/en-us/library/ms141667.aspx

If you are Integration Services Administrator - http://msdn.microsoft.com/en-us/library/ms137815.aspx

If you are Integration Services Developer - http://msdn.microsoft.com/en-us/library/ms137709.aspx

If you are Integration Services Architect - http://msdn.microsoft.com/en-us/library/ms142161.aspx

Overview of SSIS - http://msdn.microsoft.com/en-us/library/ms141263.aspx

Integration Services How-to Topics - http://msdn.microsoft.com/en-us/library/ms141767.aspx

Updating version numbers of modules in a multi-module Maven project

The solution given above worked for us as well for a long time:

mvn versions:set -DnewVersion=2.50.1-SNAPSHOT

However it stopped working yesterday, and we found it due to a recent bug in a the versions-maven-plugin

Our (temporary) workaround was to change the parent/pom.xml file as follows:

--- jackrabbit/oak/trunk/oak-parent/pom.xml 2020/08/13 13:43:11 1880829
+++ jackrabbit/oak/trunk/oak-parent/pom.xml 2020/08/13 15:17:59 1880830
@@ -329,6 +329,13 @@
           <artifactId>spotbugs-maven-plugin</artifactId>
           <version>3.1.11</version>
         </plugin>
+        
+        <plugin>
+          <groupId>org.codehaus.mojo</groupId>
+          <artifactId>versions-maven-plugin</artifactId>
+          <version>2.7</version>
+        </plugin>
+        

Use child_process.execSync but keep output in console

You can simply use .toString().

var result = require('child_process').execSync('rsync -avAXz --info=progress2 "/src" "/dest"').toString();
console.log(result);

This has been tested on Node v8.5.0, I'm not sure about previous versions. According to @etov, it doesn't work on v6.3.1 - I'm not sure about in-between.


Edit: Looking back on this, I've realised that it doesn't actually answer the specific question because it doesn't show the output to you 'live' — only once the command has finished running.

However, I'm leaving this answer here because I know quite a few people come across this question just looking for how to print the result of the command after execution.

Encode/Decode URLs in C++

The Windows API has the functions UrlEscape/UrlUnescape, exported by shlwapi.dll, for this task.

What is the purpose of the HTML "no-js" class?

The no-js class is used to style a webpage, dependent on whether the user has JS disabled or enabled in the browser.

As per the Modernizr docs:

no-js

By default, Modernizr will rewrite <html class="no-js"> to <html class="js">. This lets hide certain elements that should only be exposed in environments that execute JavaScript. If you want to disable this change, you can set enableJSClass to false in your config.

Getting a random value from a JavaScript array

Prototype Method

If you plan on getting a random value a lot, you might want to define a function for it.

First, put this in your code somewhere:

Array.prototype.sample = function(){
  return this[Math.floor(Math.random()*this.length)];
}

Now:

[1,2,3,4].sample() //=> a random element

Code released into the public domain under the terms of the CC0 1.0 license.

How to create an Explorer-like folder browser control?

Microsoft provides a walkthrough for creating a Windows Explorer style interface in C#.

There are also several examples on Code Project and other sites. Immediate examples are Explorer Tree, My Explorer, File Browser and Advanced File Explorer but there are others. Explorer Tree seems to look the best from the brief glance I took.

I used the search term windows explorer tree view C# in Google to find these links.

JPA and Hibernate - Criteria vs. JPQL or HQL

Criteria api provide one distinct feature that Neither SQL or HQL provides. ie. it allows compile time checking of a query.

What are some good SSH Servers for windows?

VanDyke VShell is the best Windows SSH Server I've ever worked with. It is kind of expensive though ($250). If you want a free solution, freeSSHd works okay. The CYGWIN solution is always an option, I've found, however, that it is a lot of work & overhead just to get SSH.

Manifest merger failed : uses-sdk:minSdkVersion 14

compile('com.android.support:support-v4:19.1.0'){
    force = true
}

Helped me, taken from here

Creating a jQuery object from a big HTML-string

As of jQuery 1.8 you can just use parseHtml to create your jQuery object:

var myString = "<div>Some stuff<div>Some more stuff<span id='theAnswer'>The stuff I am looking for</span></div></div>";
var $jQueryObject = $($.parseHTML(myString));

I've created a JSFidle that demonstrates this: http://jsfiddle.net/MCSyr/2/

It parses the arbitrary HTML string into a jQuery object, and uses find to display the result in a div.

ArrayList insertion and retrieval order

Yes, ArrayList is an ordered collection and it maintains the insertion order.

Check the code below and run it:

public class ListExample {

    public static void main(String[] args) {
        List<String> myList = new ArrayList<String>();
        myList.add("one");
        myList.add("two");
        myList.add("three");
        myList.add("four");
        myList.add("five");
    
        System.out.println("Inserted in 'order': ");
        printList(myList);
        System.out.println("\n");
        System.out.println("Inserted out of 'order': ");

        // Clear the list
        myList.clear();
    
        myList.add("four");
        myList.add("five");
        myList.add("one");
        myList.add("two");
        myList.add("three");
    
        printList(myList);
    }

    private static void printList(List<String> myList) {
        for (String string : myList) {
            System.out.println(string);
        }
    }
}

Produces the following output:

Inserted in 'order': 
one
two
three
four
five


Inserted out of 'order': 
four
five
one
two
three

For detailed information, please refer to documentation: List (Java Platform SE7)

Remove NaN from pandas series

If you have a pandas serie with NaN, and want to remove it (without loosing index):

serie = serie.dropna()

# create data for example
data = np.array(['g', 'e', 'e', 'k', 's']) 
ser = pd.Series(data)
ser.replace('e', np.NAN)
print(ser)

0      g
1    NaN
2    NaN
3      k
4      s
dtype: object

# the code
ser = ser.dropna()
print(ser)

0    g
3    k
4    s
dtype: object

import an array in python

Another option is numpy.genfromtxt, e.g:

import numpy as np
data = np.genfromtxt("myfile.dat",delimiter=",")

This will make data a numpy array with as many rows and columns as are in your file

How to add a color overlay to a background image?

background-image takes multiple values.

so a combination of just 1 color linear-gradient and css blend modes will do the trick.

.testclass {
    background-image: url("../images/image.jpg"), linear-gradient(rgba(0,0,0,0.5),rgba(0,0,0,0.5));
    background-blend-mode: overlay;
}

note that there is no support on IE/Edge for CSS blend-modes at all.

Messagebox with input field

You can do it by making form and displaying it using ShowDialogBox....

Form.ShowDialog Method - Shows the form as a modal dialog box.

Example:

public void ShowMyDialogBox()
{
   Form2 testDialog = new Form2();

   // Show testDialog as a modal dialog and determine if DialogResult = OK.
   if (testDialog.ShowDialog(this) == DialogResult.OK)
   {
      // Read the contents of testDialog's TextBox.
      this.txtResult.Text = testDialog.TextBox1.Text;
   }
   else
   {
      this.txtResult.Text = "Cancelled";
   }
   testDialog.Dispose();
}

How to get correct timestamp in C#

internal static string UnixToDate(int Timestamp, string ConvertFormat)
{
    DateTime ConvertedUnixTime = DateTimeOffset.FromUnixTimeSeconds(Timestamp).DateTime;
    return ConvertedUnixTime.ToString(ConvertFormat);
}

int Timestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;

Usage:

UnixToDate(1607013172, "HH:mm:ss"); // Output 16:32:52
Timestamp; // Output 1607013172

Round up to Second Decimal Place in Python

Updated answer:
The problem with my original answer, as pointed out in the comments by @jpm, is the behavior at the boundaries. Python 3 makes this even more difficult since it uses "bankers" rounding instead of "old school" rounding. However, in looking into this issue I discovered an even better solution using the decimal library.

import decimal

def round_up(x, place=0):
    context = decimal.getcontext()
    # get the original setting so we can put it back when we're done
    original_rounding = context.rounding
    # change context to act like ceil()
    context.rounding = decimal.ROUND_CEILING

    rounded = round(decimal.Decimal(str(x)), place)
    context.rounding = original_rounding
    return float(rounded)

Or if you really just want a one-liner:

import decimal
decimal.getcontext().rounding = decimal.ROUND_CEILING

# here's the one-liner
float(round(decimal.Decimal(str(0.1111)), ndigits=2))
>> 0.12

# Note: this only affects the rounding of `Decimal`
round(0.1111, ndigits=2)
>> 0.11

Here are some examples:

round_up(0.022499999999999999, 2)
>> 0.03
round_up(0.1111111111111000, 2)
>> 0.12
round_up(0.1111111111111000, 3)
>> 0.112

round_up(3.4)
>> 4.0

# @jpm - boundaries do what we want
round_up(0.1, 2)
>> 0.1
round_up(1.1, 2)
>> 1.1

# Note: this still rounds toward `inf`, not "away from zero"
round_up(2.049, 2)
>> 2.05
round_up(-2.0449, 2)
>> -2.04

We can use it to round to the left of the decimal as well:

round_up(11, -1)
>> 20

We don't multiply by 10, thereby avoiding the overflow mentioned in this answer.

round_up(1.01e308, -307)
>> 1.1e+308

Original Answer (Not recommended):
This depends on the behavior you want when considering positive and negative numbers, but if you want something that always rounds to a larger value (e.g. 2.0449 -> 2.05, -2.0449 -> -2.04) then you can do:

round(x + 0.005, 2)

or a little fancier:

def round_up(x, place):
    return round(x + 5 * 10**(-1 * (place + 1)), place)

This also seems to work as follows:

round(144, -1)
# 140
round_up(144, -1)
# 150
round_up(1e308, -307)
# 1.1e308

Indent multiple lines quickly in vi

In addition to the answer already given and accepted, it is also possible to place a marker and then indent everything from the current cursor to the marker.

Thus, enter ma where you want the top of your indented block, cursor down as far as you need and then type >'a (note that "a" can be substituted for any valid marker name). This is sometimes easier than 5>> or vjjj>.

C# static class why use?

Making a class static just prevents people from trying to make an instance of it. If all your class has are static members it is a good practice to make the class itself static.

Google maps API V3 method fitBounds()

LatLngBounds must be defined with points in (south-west, north-east) order. Your points are not in that order.

The general fix, especially if you don't know the points will definitely be in that order, is to extend an empty bounds:

var bounds = new google.maps.LatLngBounds();
bounds.extend(myPlace);
bounds.extend(Item_1);
map.fitBounds(bounds);

The API will sort out the bounds.

Calling a user defined function in jQuery

jQuery.fn.make_me_red = function() {
    return this.each(function() {
        this.style.color = 'red';
    });
};

$('a').make_me_red() // - instead of this you can use $(this).make_me_red() instead for better readability.

Find the differences between 2 Excel worksheets?

vlookup is your friend!

Position your column, one value per row, in column A of each spreadsheet. in column B of the larger sheet, type

=VLOOKUP(A1,'[Book2.xlsb]SheetName'!$A:$A,1,FALSE)

Then copy the formula down as far as your column of data runs.

Where the result of the formula is FALSE, that data is not in the other worksheet.

Copy directory contents into a directory with python

You can also use glob2 to recursively collect all paths (using ** subfolders wildcard) and then use shutil.copyfile, saving the paths

glob2 link: https://code.activestate.com/pypm/glob2/

How to access my localhost from another PC in LAN?

IP can be any LAN or WAN IP address. But you'll want to set your firewall connection allow it.

Device connection with webserver pc can be by LAN or WAN (i.e by wifi, connectify, adhoc, cable, mypublic wifi etc)

You should follow these steps:

  1. Go to the control panel
  2. Inbound rules > new rules
  3. Click port > next > specific local port > enter 8080 > next > allow the connection>
  4. Next > tick all (domain, private, public) > specify any name
  5. Now you can access your localhost by any device (laptop, mobile, desktop, etc).
  6. Enter ip address in browser url as 123.23.xx.xx:8080 to access localhost by any device.

This IP will be of that device which has the web server.

Display TIFF image in all web browser

Tiff images can be displayed directly onto IE and safari only.. no support of tiff images on chrome and firefox. you can encode the image and then display it on browser by decoding the encoded image to some other format. Hope this works for you

How to reset AUTO_INCREMENT in MySQL?

I suggest you to go to Query Browser and do the following:

  1. Go to schemata and find the table you want to alter.

  2. Right click and select copy create statement.

  3. Open a result tab and paste the create statement their.

  4. Go to the last line of the create statement and look for the Auto_Increment=N, (Where N is a current number for auto_increment field.)

  5. Replace N with 1.

  6. Press ctrl+enter.

Auto_increment should reset to one once you enter new row int the table.

I don't know what will happen if you try to add a row where an auto_increment field value already exist.

Collections.sort with multiple fields

Use Comparator interface with methods introduced in JDK1.8: comparing and thenComparing, or more concrete methods: comparingXXX and thenComparingXXX.

For example, if we wanna sort a list of persons by their id firstly, then age, then name:

            Comparator<Person> comparator = Comparator.comparingLong(Person::getId)
                    .thenComparingInt(Person::getAge)
                    .thenComparing(Person::getName);
            personList.sort(comparator);

How to get content body from a httpclient call?

If you are not wanting to use async you can add .Result to force the code to execute synchronously:

private string GetResponseString(string text)
{
    var httpClient = new HttpClient();

    var parameters = new Dictionary<string, string>();
    parameters["text"] = text;

    var response = httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters)).Result;
    var contents = response.Content.ReadAsStringAsync().Result;

    return contents;
 }  

Copy Paste in Bash on Ubuntu on Windows

For just copying (possibly long) texts to the Windows clipboard, I have found that just piping the output to clip.exe (including the .exe file extension) works fine for me. So:

$ echo "Hello World" | clip.exe

lets me paste Hello World using Ctrl-V anywhere else.

Now that I have posted this, I notice that related question Pipe from clipboard in linux subsytem for windows includes this and a command solution for pasting from the Windows clipboard as well.

APT command line interface-like yes/no input?

def question(question, answers):
    acceptable = False
    while not acceptable:
        print(question + "specify '%s' or '%s'") % answers
        answer = raw_input()
        if answer.lower() == answers[0].lower() or answers[0].lower():
            print('Answer == %s') % answer
            acceptable = True
    return answer

raining = question("Is it raining today?", ("Y", "N"))

This is how I'd do it.

Output

Is it raining today? Specify 'Y' or 'N'
> Y
answer = 'Y'

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

The $_post function need the name value like:

<input type="submit" value"Submit" name="example">

Call

$var = strip_tags($_POST['example']);
if (isset($var)){
    // your code here
}

Iterating C++ vector from the end to the beginning

As I don't want to introduce alien-like new C++ syntax, and I simply want to build up on existing primitives, the below snippets seems to work:

#include <vector>
#include <iostream>

int main (int argc,char *argv[])
{
    std::vector<int> arr{1,2,3,4,5};
    std::vector<int>::iterator it;

    // iterate forward
    for (it = arr.begin(); it != arr.end(); it++) {
        std::cout << *it << " ";
    }

    std::cout << "\n************\n";
 
    if (arr.size() > 0) {
        // iterate backward, simple Joe version
        it = arr.end() - 1;
        while (it != arr.begin()) {
            std::cout << *it << " ";
            it--;
        }
        std::cout << *it << " ";
    } 

    // iterate backwards, the C++ way
    std::vector<int>::reverse_iterator rit;
    for (rit = arr.rbegin(); rit != arr.rend(); rit++) {
        std::cout << *rit << " ";
    }

    return 0;
}

Retrieve version from maven pom.xml in code

There is also the method described in Easy way to display your apps version number using Maven:

Add this to pom.xml

<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-jar-plugin</artifactId>
      <configuration>
        <archive>
          <manifest>
            <mainClass>test.App</mainClass>
            <addDefaultImplementationEntries>
              true
            </addDefaultImplementationEntries>
          </manifest>
        </archive>
      </configuration>
    </plugin>
  </plugins>
</build>

Then use this:

App.class.getPackage().getImplementationVersion()

I have found this method to be simpler.

Unknown Column In Where Clause

SELECT user_name
FROM
(
SELECT name AS user_name
FROM   users
) AS test
WHERE  user_name = "john"

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 23: ordinal not in range(128)

I was getting this error when executing in python3,I got the same program working by simply executing in python2

The difference between the 'Local System' account and the 'Network Service' account?

Since there is so much confusion about functionality of standard service accounts, I'll try to give a quick run down.

First the actual accounts:

  • LocalService account (preferred)

    A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user.

    • Name: NT AUTHORITY\LocalService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the LocalService user account
    • has minimal privileges on the local computer
    • presents anonymous credentials on the network
    • SID: S-1-5-19
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-19)

     

  • NetworkService account

    Limited service account that is meant to run standard privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine (see caveat above).

    • NT AUTHORITY\NetworkService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the NetworkService user account
    • has minimal privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers
    • SID: S-1-5-20
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-20)
    • If trying to schedule a task using it, enter NETWORK SERVICE into the Select User or Group dialog

     

  • LocalSystem account (dangerous, don't use!)

    Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)

    • Name: .\LocalSystem (can also use LocalSystem or ComputerName\LocalSystem)
    • the account has no password (any password information you provide is ignored)
    • SID: S-1-5-18
    • does not have any profile of its own (HKCU represents the default user)
    • has extensive privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers

     

Above when talking about accessing the network, this refers solely to SPNEGO (Negotiate), NTLM and Kerberos and not to any other authentication mechanism. For example, processing running as LocalService can still access the internet.

The general issue with running as a standard out of the box account is that if you modify any of the default permissions you're expanding the set of things everything running as that account can do. So if you grant DBO to a database, not only can your service running as Local Service or Network Service access that database but everything else running as those accounts can too. If every developer does this the computer will have a service account that has permissions to do practically anything (more specifically the superset of all of the different additional privileges granted to that account).

It is always preferable from a security perspective to run as your own service account that has precisely the permissions you need to do what your service does and nothing else. However, the cost of this approach is setting up your service account, and managing the password. It's a balancing act that each application needs to manage.

In your specific case, the issue that you are probably seeing is that the the DCOM or COM+ activation is limited to a given set of accounts. In Windows XP SP2, Windows Server 2003, and above the Activation permission was restricted significantly. You should use the Component Services MMC snapin to examine your specific COM object and see the activation permissions. If you're not accessing anything on the network as the machine account you should seriously consider using Local Service (not Local System which is basically the operating system).


In Windows Server 2003 you cannot run a scheduled task as

  • NT_AUTHORITY\LocalService (aka the Local Service account), or
  • NT AUTHORITY\NetworkService (aka the Network Service account).

That capability only was added with Task Scheduler 2.0, which only exists in Windows Vista/Windows Server 2008 and newer.

A service running as NetworkService presents the machine credentials on the network. This means that if your computer was called mango, it would present as the machine account MANGO$:

enter image description here

How to convert Calendar to java.sql.Date in Java?

Use stmt.setDate(1, new java.sql.Date(cal.getTimeInMillis()))

How to convert JSON string to array

If you pass the JSON in your post to json_decode, it will fail. Valid JSON strings have quoted keys:

json_decode('{foo:"bar"}');         // this fails
json_decode('{"foo":"bar"}', true); // returns array("foo" => "bar")
json_decode('{"foo":"bar"}');       // returns an object, not an array.

SUM of grouped COUNT in SQL Query

I required having count(*) > 1 also. So, I wrote my own query after referring some the above queries

SYNTAX:

select sum(count) from (select count(`table_name`.`id`) as `count` from `table_name` where {some condition} group by {some_column} having count(`table_name`.`id`) > 1) as `tmp`;

Example:

select sum(count) from (select count(`table_name`.`id`) as `count` from `table_name` where `table_name`.`name` IS NOT NULL and `table_name`.`name` != '' group by `table_name`.`name` having count(`table_name`.`id`) > 1) as `tmp`;

How can I connect to MySQL on a WAMP server?

Change localhost:8080 to localhost:3306.

C++ wait for user input

Several ways to do so, here are some possible one-line approaches:

  1. Use getch() (need #include <conio.h>).

  2. Use getchar() (expected for Enter, need #include <iostream>).

  3. Use cin.get() (expected for Enter, need #include <iostream>).

  4. Use system("pause") (need #include <iostream>).

    PS: This method will also print Press any key to continue . . . on the screen. (seems perfect choice for you :))


Edit: As discussed here, There is no completely portable solution for this. Question 19.1 of the comp.lang.c FAQ covers this in some depth, with solutions for Windows, Unix-like systems, and even MS-DOS and VMS.

Adding to a vector of pair

Or you can use initialize list:

revenue.push_back({"string", map[i].second});

Count immediate child div elements using jQuery

$("#foo > div").length

jQuery has a .size() function which will return the number of times that an element appears but, as specified in the jQuery documentation, it is slower and returns the same value as the .length property so it is best to simply use the .length property. From here: http://www.electrictoolbox.com/get-total-number-matched-elements-jquery/

How do I detect if Python is running as a 64-bit application?

While it may work on some platforms, be aware that platform.architecture is not always a reliable way to determine whether python is running in 32-bit or 64-bit. In particular, on some OS X multi-architecture builds, the same executable file may be capable of running in either mode, as the example below demonstrates. The quickest safe multi-platform approach is to test sys.maxsize on Python 2.6, 2.7, Python 3.x.

$ arch -i386 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 2147483647)
>>> ^D
$ arch -x86_64 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 9223372036854775807)

jQuery/JavaScript to replace broken images

This has been frustrating me for years. My CSS fix sets a background image on the img. When a dynamic image src doesn't load to the foreground, a placeholder is visible on the img's bg. This works if your images have a default size (e.g. height, min-height, width and/or min-width).

You'll see the broken image icon but it's an improvement. Tested down to IE9 successfully. iOS Safari and Chrome don't even show a broken icon.

.dynamicContainer img {
  background: url('/images/placeholder.png');
  background-size: contain;
}

Add a little animation to give src time to load without a background flicker. Chrome fades in the background smoothly but desktop Safari doesn't.

.dynamicContainer img {
  background: url('/images/placeholder.png');
  background-size: contain;
  animation: fadein 1s;                     
}

@keyframes fadein {
  0%   { opacity: 0.0; }
  50%  { opacity: 0.5; }
  100% { opacity: 1.0; }
}

How to print a list with integers without the brackets, commas and no quotes?

If you're using Python 3, or appropriate Python 2.x version with from __future__ import print_function then:

data = [7, 7, 7, 7]
print(*data, sep='')

Otherwise, you'll need to convert to string and print:

print ''.join(map(str, data))

Export DataTable to Excel File

use this code...

    dt = city.GetAllCity();//your datatable
    string attachment = "attachment; filename=city.xls";
    Response.ClearContent();
    Response.AddHeader("content-disposition", attachment);
    Response.ContentType = "application/vnd.ms-excel";
    string tab = "";
    foreach (DataColumn dc in dt.Columns)
    {
        Response.Write(tab + dc.ColumnName);
        tab = "\t";
    }
    Response.Write("\n");
    int i;
    foreach (DataRow dr in dt.Rows)
    {
        tab = "";
        for (i = 0; i < dt.Columns.Count; i++)
        {
            Response.Write(tab + dr[i].ToString());
            tab = "\t";
        }
        Response.Write("\n");
    }
    Response.End();

Are static class variables possible in Python?

@dataclass definitions provide class-level names that are used to define the instance variables and the initialization method, __init__(). If you want class-level variable in @dataclass you should use typing.ClassVar type hint. The ClassVar type's parameters define the class-level variable's type.

from typing import ClassVar
from dataclasses import dataclass

@dataclass
class Test:
    i: ClassVar[int] = 10
    x: int
    y: int
    
    def __repr__(self):
        return f"Test({self.x=}, {self.y=}, {Test.i=})"

Usage examples:

> test1 = Test(5, 6)
> test2 = Test(10, 11)

> test1
Test(self.x=5, self.y=6, Test.i=10)
> test2
Test(self.x=10, self.y=11, Test.i=10)

Python basics printing 1 to 100

When you use count = count + 3 or count = count + 9 instead of count = count + 1, the value of count will never be 100, and hence it enters an infinite loop.

You could use the following code for your condition to work

while count < 100:

Now the loop will terminate when count >= 100.

Getting windbg without the whole WDK?

I was looking for the same thing for a quick operation and found this question. I needed both 32-bit and 64-bit versions.

This is an older version but the links are from the Microsoft servers, it should be safe. The link for 32-bit version is also in a previous answer but the version number i get on the install is different, maybe the same link is updated with a newer version since 2013.

Cheksums are generated both locally and on VirusTotal, they match.

Debugging Tools for Windows (x64) (6.12.2.633)(VirusTotal Scan): http://download.microsoft.com/download/A/6/A/A6AC035D-DA3F-4F0C-ADA4-37C8E5D34E3D/setup/WinSDKDebuggingTools_amd64/dbg_amd64.msi (SHA-256:2e491bb98850abf9b9d2627185b57e048ba9b2410d68303698ac68c2daad9e5d)

Debugging Tools for Windows (x86) (6.12.2.633)(VirusTotal Scan): http://download.microsoft.com/download/A/6/A/A6AC035D-DA3F-4F0C-ADA4-37C8E5D34E3D/setup/WinSDKDebuggingTools/dbg_x86.msi (SHA-256:5a0f43281e51405408a043e2f94dd51782ef29671307d3538cfdff5b0e69d115)

I tested the 64 bit debugger with a 64 bit program that was compiled some years ago (~2012) and it works. Test is done on Windows 10 Pro 64 bit (v2004 Build 19041.207).

How to convert string to long

String s = "1";

try {
   long l = Long.parseLong(s);       
} catch (NumberFormatException e) {
   System.out.println("NumberFormatException: " + e.getMessage());
}

Encrypt and decrypt a string in C#?

I want to give you my contribute, with my code for AES Rfc2898DeriveBytes (here the documentation) algorhytm, written in C# (.NET framework 4) and fully working also for limited platforms, as .NET Compact Framework for Windows Phone 7.0+ (not all platforms support every criptographic method of the .NET framework!).

I hope this can help anyone!

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

public static class Crypto
{
    private static readonly byte[] IVa = new byte[] { 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x11, 0x11, 0x12, 0x13, 0x14, 0x0e, 0x16, 0x17 };


    public static string Encrypt(this string text, string salt)
    {
        try
        {
            using (Aes aes = new AesManaged())
            {
                Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IVa, 0, IVa.Length), Encoding.UTF8.GetBytes(salt));
                aes.Key = deriveBytes.GetBytes(128 / 8);
                aes.IV = aes.Key;
                using (MemoryStream encryptionStream = new MemoryStream())
                {
                    using (CryptoStream encrypt = new CryptoStream(encryptionStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        byte[] cleanText = Encoding.UTF8.GetBytes(text);
                        encrypt.Write(cleanText, 0, cleanText.Length);
                        encrypt.FlushFinalBlock();
                    }

                    byte[] encryptedData = encryptionStream.ToArray();
                    string encryptedText = Convert.ToBase64String(encryptedData);


                    return encryptedText;
                }
            }
        }
        catch
        {
            return String.Empty;
        }
    }

    public static string Decrypt(this string text, string salt)
    {
        try
        {
            using (Aes aes = new AesManaged())
            {
                Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IVa, 0, IVa.Length), Encoding.UTF8.GetBytes(salt));
                aes.Key = deriveBytes.GetBytes(128 / 8);
                aes.IV = aes.Key;

                using (MemoryStream decryptionStream = new MemoryStream())
                {
                    using (CryptoStream decrypt = new CryptoStream(decryptionStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        byte[] encryptedData = Convert.FromBase64String(text);


                        decrypt.Write(encryptedData, 0, encryptedData.Length);
                        decrypt.Flush();
                    }

                    byte[] decryptedData = decryptionStream.ToArray();
                    string decryptedText = Encoding.UTF8.GetString(decryptedData, 0, decryptedData.Length);


                    return decryptedText;
                }
            }
        }
        catch
        {
            return String.Empty;
        }
        }
    }
}

Comparing a variable with a string python not working when redirecting from bash script

When you read() the file, you may get a newline character '\n' in your string. Try either

if UserInput.strip() == 'List contents': 

or

if 'List contents' in UserInput: 

Also note that your second file open could also use with:

with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile:     if UserInput.strip() == 'List contents': # or if s in f:         UserInputFile.write("ls")     else:         print "Didn't work" 

Python, add items from txt file into a list

#function call
read_names(names.txt)
#function def
def read_names(filename): 
with open(filename, 'r') as fileopen:
    name_list = [line.strip() for line in fileopen]
    print (name_list)

Put a Delay in Javascript

Unfortunately, setTimeout() is the only reliable way (not the only way, but the only reliable way) to pause the execution of the script without blocking the UI.

It's not that hard to use actually, instead of writing this:

var x = 1;

// Place mysterious code that blocks the thread for 100 ms.

x = x * 3 + 2;
var y = x / 2;

you use setTimeout() to rewrite it this way:

var x = 1;
var y = null; // To keep under proper scope

setTimeout(function() {
    x = x * 3 + 2;
    y = x / 2;
}, 100);

I understand that using setTimeout() involves more thought than a desirable sleep() function, but unfortunately the later doesn't exist. Many workarounds are there to try to implement such functions. Some using busy loops:

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

others using an XMLHttpRequest tied with a server script that sleeps for a amount of time before returning a result.

Unfortunately, those are workarounds and are likely to cause other problems (such as freezing browsers). It is recommended to simply stick with the recommended way, which is setTimeout()).

Using jq to parse and display multiple fields in a json serially

While both of the above answers work well if key,value are strings, I had a situation to append a string and integer (jq errors using the above expressions)

Requirement: To construct a url out below json

pradeep@seleniumframework>curl http://192.168.99.103:8500/v1/catalog/service/apache-443 | jq .[0]
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   251  100   251    0     0   155k      0 --:--:-- --:--:-- --:--:--  245k
{
  "Node": "myconsul",
  "Address": "192.168.99.103",
  "ServiceID": "4ce41e90ede4:compassionate_wozniak:443",
  "ServiceName": "apache-443",
  "ServiceTags": [],
  "ServiceAddress": "",
  "ServicePort": 1443,
  "ServiceEnableTagOverride": false,
  "CreateIndex": 45,
  "ModifyIndex": 45
}

Solution:

curl http://192.168.99.103:8500/v1/catalog/service/apache-443 |
jq '.[0] | "http://" + .Address + ":" + "\(.ServicePort)"'

Flutter: RenderBox was not laid out

I had a simmilar problem, but in my case I was put a row in the leading of the Listview, and it was consumming all the space, of course. I just had to take the Row out of the leading, and it was solved. I would recomend to check if the problem is a widget larger than its containner can have.

MVC which submit button has been pressed

To make it easier I will say you can change your buttons to the following:

<input name="btnSubmit" type="submit" value="Save" />
<input name="btnProcess" type="submit" value="Process" />

Your controller:

public ActionResult Create(string btnSubmit, string btnProcess)
{
    if(btnSubmit != null)
       // do something for the Button btnSubmit
    else 
       // do something for the Button btnProcess
}

How to find out the number of CPUs using python

These give you the hyperthreaded CPU count

  1. multiprocessing.cpu_count()
  2. os.cpu_count()

These give you the virtual machine CPU count

  1. psutil.cpu_count()
  2. numexpr.detect_number_of_cores()

Only matters if you works on VMs.

WebView link click open default browser

I had to do the same thing today and I have found a very useful answer on StackOverflow that I want to share here in case someone else needs it.

Source (from sven)

webView.setWebViewClient(new WebViewClient(){
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) {
            view.getContext().startActivity(
                new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
        } else {
            return false;
        }
    }
});

How do I format a date as ISO 8601 in moment.js?

var date = moment(new Date(), moment.ISO_8601);
console.log(date);

Handle Button click inside a row in RecyclerView

this is how I handle multiple onClick events inside a recyclerView:

Edit : Updated to include callbacks (as mentioned in other comments). I have used a WeakReference in the ViewHolder to eliminate a potential memory leak.

Define interface :

public interface ClickListener {

    void onPositionClicked(int position);
    
    void onLongClicked(int position);
}

Then the Adapter :

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    
    private final ClickListener listener;
    private final List<MyItems> itemsList;

    public MyAdapter(List<MyItems> itemsList, ClickListener listener) {
        this.listener = listener;
        this.itemsList = itemsList;
    }

    @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.my_row_layout), parent, false), listener);
    }

    @Override public void onBindViewHolder(MyViewHolder holder, int position) {
        // bind layout and data etc..
    }

    @Override public int getItemCount() {
        return itemsList.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {

        private ImageView iconImageView;
        private TextView iconTextView;
        private WeakReference<ClickListener> listenerRef;

        public MyViewHolder(final View itemView, ClickListener listener) {
            super(itemView);

            listenerRef = new WeakReference<>(listener);
            iconImageView = (ImageView) itemView.findViewById(R.id.myRecyclerImageView);
            iconTextView = (TextView) itemView.findViewById(R.id.myRecyclerTextView);

            itemView.setOnClickListener(this);
            iconTextView.setOnClickListener(this);
            iconImageView.setOnLongClickListener(this);
        }

        // onClick Listener for view
        @Override
        public void onClick(View v) {

            if (v.getId() == iconTextView.getId()) {
                Toast.makeText(v.getContext(), "ITEM PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(v.getContext(), "ROW PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
            }
            
            listenerRef.get().onPositionClicked(getAdapterPosition());
        }


        //onLongClickListener for view
        @Override
        public boolean onLongClick(View v) {

            final AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
            builder.setTitle("Hello Dialog")
                    .setMessage("LONG CLICK DIALOG WINDOW FOR ICON " + String.valueOf(getAdapterPosition()))
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });

            builder.create().show();
            listenerRef.get().onLongClicked(getAdapterPosition());
            return true;
        }
    }
}

Then in your activity/fragment - whatever you can implement : Clicklistener - or anonymous class if you wish like so :

MyAdapter adapter = new MyAdapter(myItems, new ClickListener() {
            @Override public void onPositionClicked(int position) {
                // callback performed on click
            }

            @Override public void onLongClicked(int position) {
                // callback performed on click
            }
        });

To get which item was clicked you match the view id i.e. v.getId() == whateverItem.getId()

Hope this approach helps!

How do I bind the enter key to a function in tkinter?

Another alternative is to use a lambda:

ent.bind("<Return>", (lambda event: name_of_function()))

Full code:

from tkinter import *
from tkinter.messagebox import showinfo

def reply(name):
    showinfo(title="Reply", message = "Hello %s!" % name)


top = Tk()
top.title("Echo")
top.iconbitmap("Iconshock-Folder-Gallery.ico")

Label(top, text="Enter your name:").pack(side=TOP)
ent = Entry(top)
ent.bind("<Return>", (lambda event: reply(ent.get())))
ent.pack(side=TOP)
btn = Button(top,text="Submit", command=(lambda: reply(ent.get())))
btn.pack(side=LEFT)

top.mainloop()

As you can see, creating a lambda function with an unused variable "event" solves the problem.

Chrome: console.log, console.debug are not working

Click “Default levels” right next to filter and do make sure that "Info" is checked.

Please see screenshot:

enter image description here

Java FileWriter how to write to next Line

I'm not sure if I understood correctly, but is this what you mean?

out.write("this is line 1");
out.newLine();
out.write("this is line 2");
out.newLine();
...

How to solve npm error "npm ERR! code ELIFECYCLE"

I am using react-create-app in Windows 10, on February 2nd, 2019 with latest NodeJS 11.9.0 and npm 6.7.0 (When you install NodeJS, the npm is existing). I think case of node packages are corrupted is rarely, the main cause permission.

At the beginning, I put project directory at Desktop, it is belong to C:\ driver. I move to another directory of another driver. Therefore, I remove "file permission" concern. Every work well and simple.

cd /d D:\
mkdir temp20190202
npx create-react-app my-app
cd my-app
npm start

It is ok, not put project folder in a directory of C:\ (or other driver what contains Windows Operating system).

Visual C++ executable and missing MSVCR100d.dll

I got the same error.

I was refering a VS2010 DLL in a VS2012 project.

Just recompiled the DLL on VS2012 and now everything is fine.

Find objects between two dates MongoDB

Using with Moment.js and Comparison Query Operators

  var today = moment().startOf('day');
  // "2018-12-05T00:00:00.00
  var tomorrow = moment(today).endOf('day');
  // ("2018-12-05T23:59:59.999

  Example.find(
  {
    // find in today
    created: { '$gte': today, '$lte': tomorrow }
    // Or greater than 5 days
    // created: { $lt: moment().add(-5, 'days') },
  }), function (err, docs) { ... });

.NET / C# - Convert char[] to string

Another alternative

char[] c = { 'R', 'o', 'c', 'k', '-', '&', '-', 'R', 'o', 'l', 'l' };
string s = String.Concat( c );

Debug.Assert( s.Equals( "Rock-&-Roll" ) );

Dynamically add script tag with src that may include document.write

the only way to do this is to replace document.write with your own function which will append elements to the bottom of your page. It is pretty straight forward with jQuery:

document.write = function(htmlToWrite) {
  $(htmlToWrite).appendTo('body');
}

If you have html coming to document.write in chunks like the question example you'll need to buffer the htmlToWrite segments. Maybe something like this:

document.write = (function() {
  var buffer = "";
  var timer;
  return function(htmlPieceToWrite) {
    buffer += htmlPieceToWrite;
    clearTimeout(timer);
    timer = setTimeout(function() {
      $(buffer).appendTo('body');
      buffer = "";
    }, 0)
  }
})()

Listing all extras of an Intent

The get(String key) method of Bundle returns an Object. Your best bet is to spin over the key set calling get(String) on each key and using toString() on the Object to output them. This will work best for primitives, but you may run into issues with Objects that do not implement a toString().

HTML: How to limit file upload to be only images?

You can only do this securely on the server-side. Using the "accept" attribute is good, but must also be validated on the server side lest users be able to cURL to your script without that limitation.

I suggest that you: discard any non-image file, warn the user, and redisplay the form.

Linux command to print directory structure in the form of a tree

Since I was not too happy with the output of other (non-tree) answers (see my comment at Hassou's answer), I tried to mimic trees output a bit more.

It's similar to the answer of Robert but the horizontal lines do not all start at the beginning, but where there are supposed to start. Had to use perl though, but in my case, on the system where I don't have tree, perl is available.

ls -aR | grep ":$" | perl -pe 's/:$//;s/[^-][^\/]*\//    /g;s/^    (\S)/+-- \1/;s/(^    |    (?= ))/¦   /g;s/    (\S)/+-- \1/'

Output (shortened):

.
+-- fd
+-- net
¦   +-- dev_snmp6
¦   +-- nfsfs
¦   +-- rpc
¦   ¦   +-- auth.unix.ip
¦   +-- stat
¦   +-- vlan
+-- ns
+-- task
¦   +-- 1310
¦   ¦   +-- net
¦   ¦   ¦   +-- dev_snmp6
¦   ¦   ¦   +-- rpc
¦   ¦   ¦   ¦   +-- auth.unix.gid
¦   ¦   ¦   ¦   +-- auth.unix.ip
¦   ¦   ¦   +-- stat
¦   ¦   ¦   +-- vlan
¦   ¦   +-- ns

Suggestions to avoid the superfluous vertical lines are welcome :-)

I still like Ben's solution in the comment of Hassou's answer very much, without the (not perfectly correct) lines it's much cleaner. For my use case I additionally removed the global indentation and added the option to also ls hidden files, like so:

ls -aR | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//  /g'

Output (shortened even more):

.
  fd
  net
    dev_snmp6
    nfsfs
    rpc
      auth.unix.ip
    stat
    vlan
  ns

How to initialize weights in PyTorch?

Single layer

To initialize the weights of a single layer, use a function from torch.nn.init. For instance:

conv1 = torch.nn.Conv2d(...)
torch.nn.init.xavier_uniform(conv1.weight)

Alternatively, you can modify the parameters by writing to conv1.weight.data (which is a torch.Tensor). Example:

conv1.weight.data.fill_(0.01)

The same applies for biases:

conv1.bias.data.fill_(0.01)

nn.Sequential or custom nn.Module

Pass an initialization function to torch.nn.Module.apply. It will initialize the weights in the entire nn.Module recursively.

apply(fn): Applies fn recursively to every submodule (as returned by .children()) as well as self. Typical use includes initializing the parameters of a model (see also torch-nn-init).

Example:

def init_weights(m):
    if type(m) == nn.Linear:
        torch.nn.init.xavier_uniform(m.weight)
        m.bias.data.fill_(0.01)

net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))
net.apply(init_weights)

Can't create handler inside thread that has not called Looper.prepare() inside AsyncTask for ProgressDialog

I had a similar issue but from reading this question I figured I could run on UI thread:

YourActivity.this.runOnUiThread(new Runnable() {
    public void run() {
        alertDialog.show();
    }
});

Seems to do the trick for me.

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

Things you can add to declarations: [] in modules

  • Pipe
  • Directive
  • Component

Pro Tip: The error message explains it - Please add a @Pipe/@Directive/@Component annotation.

How to get the size of a range in Excel

The Range object has both width and height properties, which are measured in points.

Python 2.7: %d, %s, and float()

See String Formatting Operations:

%d is the format code for an integer. %f is the format code for a float.

%s prints the str() of an object (What you see when you print(object)).

%r prints the repr() of an object (What you see when you print(repr(object)).

For a float %s, %r and %f all display the same value, but that isn't the case for all objects. The other fields of a format specifier work differently as well:

>>> print('%10.2s' % 1.123) # print as string, truncate to 2 characters in a 10-place field.
        1.
>>> print('%10.2f' % 1.123) # print as float, round to 2 decimal places in a 10-place field.
      1.12

fatal error: iostream.h no such file or directory

You should be using iostream without the .h.

Early implementations used the .h variants but the standard mandates the more modern style.