Programs & Examples On #Upsert

For issues relating to performing upsert (combination update/insert) operations.

How do I UPDATE a row in a table or INSERT it if it doesn't exist?

SQLite supports replacing a row if it already exists:

INSERT OR REPLACE INTO [...blah...]

You can shorten this to

REPLACE INTO [...blah...]

This shortcut was added to be compatible with the MySQL REPLACE INTO expression.

How to UPSERT (MERGE, INSERT ... ON DUPLICATE UPDATE) in PostgreSQL?

I am trying to contribute with another solution for the single insertion problem with the pre-9.5 versions of PostgreSQL. The idea is simply to try to perform first the insertion, and in case the record is already present, to update it:

do $$
begin 
  insert into testtable(id, somedata) values(2,'Joe');
exception when unique_violation then
  update testtable set somedata = 'Joe' where id = 2;
end $$;

Note that this solution can be applied only if there are no deletions of rows of the table.

I do not know about the efficiency of this solution, but it seems to me reasonable enough.

Oracle: how to UPSERT (update or insert into a table?)

An alternative to MERGE (the "old fashioned way"):

begin
   insert into t (mykey, mystuff) 
      values ('X', 123);
exception
   when dup_val_on_index then
      update t 
      set    mystuff = 123 
      where  mykey = 'X';
end;   

Postgres: INSERT if does not exist already

If you say that many of your rows are identical you will end checking many times. You can send them and the database will determine if insert it or not with the ON CONFLICT clause as follows

  INSERT INTO Hundred (name,name_slug,status) VALUES ("sql_string += hundred  
  +",'" + hundred_slug + "', " + status + ") ON CONFLICT ON CONSTRAINT
  hundred_pkey DO NOTHING;" cursor.execute(sql_string);

Solutions for INSERT OR UPDATE on SQL Server

MS SQL Server 2008 introduces the MERGE statement, which I believe is part of the SQL:2003 standard. As many have shown it is not a big deal to handle one row cases, but when dealing with large datasets, one needs a cursor, with all the performance problems that come along. The MERGE statement will be much welcomed addition when dealing with large datasets.

Insert, on duplicate update in PostgreSQL?

PostgreSQL since version 9.5 has UPSERT syntax, with ON CONFLICT clause. with the following syntax (similar to MySQL)

INSERT INTO the_table (id, column_1, column_2) 
VALUES (1, 'A', 'X'), (2, 'B', 'Y'), (3, 'C', 'Z')
ON CONFLICT (id) DO UPDATE 
  SET column_1 = excluded.column_1, 
      column_2 = excluded.column_2;

Searching postgresql's email group archives for "upsert" leads to finding an example of doing what you possibly want to do, in the manual:

Example 38-2. Exceptions with UPDATE/INSERT

This example uses exception handling to perform either UPDATE or INSERT, as appropriate:

CREATE TABLE db (a INT PRIMARY KEY, b TEXT);

CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS
$$
BEGIN
    LOOP
        -- first try to update the key
        -- note that "a" must be unique
        UPDATE db SET b = data WHERE a = key;
        IF found THEN
            RETURN;
        END IF;
        -- not there, so try to insert the key
        -- if someone else inserts the same key concurrently,
        -- we could get a unique-key failure
        BEGIN
            INSERT INTO db(a,b) VALUES (key, data);
            RETURN;
        EXCEPTION WHEN unique_violation THEN
            -- do nothing, and loop to try the UPDATE again
        END;
    END LOOP;
END;
$$
LANGUAGE plpgsql;

SELECT merge_db(1, 'david');
SELECT merge_db(1, 'dennis');

There's possibly an example of how to do this in bulk, using CTEs in 9.1 and above, in the hackers mailing list:

WITH foos AS (SELECT (UNNEST(%foo[])).*)
updated as (UPDATE foo SET foo.a = foos.a ... RETURNING foo.id)
INSERT INTO foo SELECT foos.* FROM foos LEFT JOIN updated USING(id)
WHERE updated.id IS NULL;

See a_horse_with_no_name's answer for a clearer example.

INSERT IF NOT EXISTS ELSE UPDATE?

I believe you want UPSERT.

"INSERT OR REPLACE" without the additional trickery in that answer will reset any fields you don't specify to NULL or other default value. (This behavior of INSERT OR REPLACE is unlike UPDATE; it's exactly like INSERT, because it actually is INSERT; however if what you wanted is UPDATE-if-exists you probably want the UPDATE semantics and will be unpleasantly surprised by the actual result.)

The trickery from the suggested UPSERT implementation is basically to use INSERT OR REPLACE, but specify all fields, using embedded SELECT clauses to retrieve the current value for fields you don't want to change.

SQLite UPSERT / UPDATE OR INSERT

Here's an approach that doesn't require the brute-force 'ignore' which would only work if there was a key violation. This way works based on any conditions you specify in the update.

Try this...

-- Try to update any existing row
UPDATE players
SET age=32
WHERE user_name='steven';

-- If no update happened (i.e. the row didn't exist) then insert one
INSERT INTO players (user_name, age)
SELECT 'steven', 32
WHERE (Select Changes() = 0);

How It Works

The 'magic sauce' here is using Changes() in the Where clause. Changes() represents the number of rows affected by the last operation, which in this case is the update.

In the above example, if there are no changes from the update (i.e. the record doesn't exist) then Changes() = 0 so the Where clause in the Insert statement evaluates to true and a new row is inserted with the specified data.

If the Update did update an existing row, then Changes() = 1 (or more accurately, not zero if more than one row was updated), so the 'Where' clause in the Insert now evaluates to false and thus no insert will take place.

The beauty of this is there's no brute-force needed, nor unnecessarily deleting, then re-inserting data which may result in messing up downstream keys in foreign-key relationships.

Additionally, since it's just a standard Where clause, it can be based on anything you define, not just key violations. Likewise, you can use Changes() in combination with anything else you want/need anywhere expressions are allowed.

Insert into a MySQL table or update if exists

Any of these solution will work regarding your question:

INSERT IGNORE INTO table (id, name, age) VALUES (1, "A", 19);

or

INSERT INTO TABLE (id, name, age) VALUES(1, "A", 19) 
    ON DUPLICATE KEY UPDATE NAME = "A", AGE = 19;  

or

REPLACE INTO table (id, name, age) VALUES(1, "A", 19);

If you want to know in details regarding these statement visit this link

SQLite - UPSERT *not* INSERT or REPLACE

If you are generally doing updates I would ..

  1. Begin a transaction
  2. Do the update
  3. Check the rowcount
  4. If it is 0 do the insert
  5. Commit

If you are generally doing inserts I would

  1. Begin a transaction
  2. Try an insert
  3. Check for primary key violation error
  4. if we got an error do the update
  5. Commit

This way you avoid the select and you are transactionally sound on Sqlite.

SQLite "INSERT OR REPLACE INTO" vs. "UPDATE ... WHERE"

The insert or replace query would insert a new record if id=1 does not already exist.

The update query would only oudate id=1 if it aready exist, it would not create a new record if it didn't exist.

PostgreSQL INSERT ON CONFLICT UPDATE (upsert) use all excluded values

Postgres hasn't implemented an equivalent to INSERT OR REPLACE. From the ON CONFLICT docs (emphasis mine):

It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.

Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE applies more generally, since it lets you set new values based on preexisting data. For example:

INSERT INTO users (id, level)
VALUES (1, 0)
ON CONFLICT (id) DO UPDATE
SET level = users.level + 1;

Oracle - How to generate script from sql developer

Oracle SQL Developer > View > DBA > Select your connection > Expand > Security > Users > Right click your user > Create like > Fill in fields > Copy SQL script > Close

If your user has object privileges, do this also

Oracle SQL Developer > View > DBA > Select your connection > Expand > Security > Users > Double click your user > Object Privs > Select all data > Right click > Export > Export as text file

Edit that text file to grant object privileges to your user.

android: how to change layout on button click?

It is very simple, just do this:

t4.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {

            launchQuiz2();          // TODO Auto-generated method stub

        }

        private void launchQuiz2() {
            Intent i = new Intent(MainActivity.this, Quiz2.class);
            startActivity(i);
            // TODO Auto-generated method stub

        }

    });

Flex-box: Align last row to grid

It is possible to use "flex-start" and to add the margins manually. It requires some math-hacking but is definitely easy to do and make it easy to use with a CSS preprocessor like LESS.

See for example this LESS mixin:

.flexboxGridMixin(@columnNumber,@spacingPercent) {
  @contentPercent: 100% - @spacingPercent;
  @sideMargin: @spacingPercent/(@columnNumber*2);
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: flex-start;
  > * {
    box-sizing: border-box;
    width: @contentPercent/@columnNumber;
    margin-left: @sideMargin;
    margin-right: @sideMargin;
  }
}

And then it can easily be used to display a responsive grid layout:

ul {
  list-style: none;
  padding: 0;
  @spacing: 10%;
  @media only screen and (max-width: 499px) { .flexboxGridMixin(1,@spacing); }
  @media only screen and (min-width: 500px) { .flexboxGridMixin(2,@spacing); }
  @media only screen and (min-width: 700px) { .flexboxGridMixin(3,@spacing); }
  @media only screen and (min-width: 900px) { .flexboxGridMixin(4,@spacing); }
  @media only screen and (min-width: 1100px) { .flexboxGridMixin(5,@spacing); }
}

li {
  background: pink;
  height: 100px;
  margin-top: 20px;
}

Here is an example of

http://codepen.io/anon/pen/YyLqVB?editors=110

Where to find "Microsoft.VisualStudio.TestTools.UnitTesting" missing dll?

There is also a nice nuget package. It will pull the dll to your packages folder. You will need to add the reference to the dll manually.

NOTE: This package is not an official Microsoft package.

Check if all elements in a list are identical

Check if all elements equal to the first.

np.allclose(array, array[0])

jQuery find events handlers registered with an object

As of 1.9 there is no documented way to retrieve the events, other than to use the Migrate plugin to restore the old behavior. You could use the _.data() method as jps mentions, but that is an internal method. So just do the right thing and use the Migrate plugin if you need this functionality.

From the jQuery documentation on .data("events")

Prior to 1.9, .data("events") could be used to retrieve jQuery's undocumented internal event data structure for an element if no other code had defined a data element with the name "events". This special case has been removed in 1.9. There is no public interface to retrieve this internal data structure, and it remains undocumented. However, the jQuery Migrate plugin restores this behavior for code that depends upon it.

Example of SOAP request authenticated with WS-UsernameToken

Check this one (Password should be password):

<wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="SecurityToken-6138db82-5a4c-4bf7-915f-af7a10d9ae96">
  <wsse:Username>user</wsse:Username>
  <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">CBb7a2itQDgxVkqYnFtggUxtuqk=</wsse:Password>
  <wsse:Nonce>5ABcqPZWb6ImI2E6tob8MQ==</wsse:Nonce>
  <wsu:Created>2010-06-08T07:26:50Z</wsu:Created>
</wsse:UsernameToken>

First char to upper case

Comilation error is due arguments are not properly provided, replaceFirst accepts regx as initial arg. [a-z]{1} will match string of simple alpha characters of length 1.

Try this.

betterIdea = userIdea.replaceFirst("[a-z]{1}", userIdea.substring(0,1).toUpperCase())

How to make a .jar out from an Android Studio project

.jar file will be automatically generate when u compile/run your application.

You can find your class.jar file from root_folder/app/build/intermediates/bundles/debug

jar file location

How to convert InputStream to FileInputStream

You need something like:

    URL resource = this.getClass().getResource("/path/to/resource.res");
    File is = null;
    try {
        is = new File(resource.toURI());
    } catch (URISyntaxException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        FileInputStream input = new FileInputStream(is);
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

But it will work only within your IDE, not in runnable JAR. I had same problem explained here.

How to set a dropdownlist item as selected in ASP.NET?

Set dropdown property

selected="true"

Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia

Please check this: https://jsfiddle.net/wazb1jks/3/

_x000D_
_x000D_
navigator.getUserMedia(mediaConstraints, function(stream) {_x000D_
    window.streamReference = stream;_x000D_
}, onMediaError);
_x000D_
_x000D_
_x000D_

Stop Recording

_x000D_
_x000D_
function stopStream() {_x000D_
    if (!window.streamReference) return;_x000D_
_x000D_
    window.streamReference.getAudioTracks().forEach(function(track) {_x000D_
        track.stop();_x000D_
    });_x000D_
_x000D_
    window.streamReference.getVideoTracks().forEach(function(track) {_x000D_
        track.stop();_x000D_
    });_x000D_
_x000D_
    window.streamReference = null;_x000D_
}
_x000D_
_x000D_
_x000D_

Maintain/Save/Restore scroll position when returning to a ListView

Parcelable state;

@Override
public void onPause() {    
    // Save ListView state @ onPause
    Log.d(TAG, "saving listview state");
    state = listView.onSaveInstanceState();
    super.onPause();
}
...

@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    // Set new items
    listView.setAdapter(adapter);
    ...
    // Restore previous state (including selected item index and scroll position)
    if(state != null) {
        Log.d(TAG, "trying to restore listview state");
        listView.onRestoreInstanceState(state);
    }
}

Android - drawable with rounded corners at the top only

Building upon busylee's answer, this is how you can make a drawable that only has one unrounded corner (top-left, in this example):

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/white" />
            <!-- A numeric value is specified in "radius" for demonstrative purposes only,
                  it should be @dimen/val_name -->
            <corners android:radius="10dp" />
        </shape>
    </item>
    <!-- To keep the TOP-LEFT corner UNROUNDED set both OPPOSITE offsets (bottom+right): -->
    <item
        android:bottom="10dp"
        android:right="10dp">
        <shape android:shape="rectangle">
            <solid android:color="@color/white" />
        </shape>
    </item>
</layer-list>

Please note that the above drawable is not shown correctly in the Android Studio preview (2.0.0p7). To preview it anyway, create another view and use this as android:background="@drawable/...".

Using querySelectorAll to retrieve direct children

Does anyone know how to write a selector which gets just the direct children of the element that the selector is running on?

The correct way to write a selector that is "rooted" to the current element is to use :scope.

var myDiv = getElementById("myDiv");
var fooEls = myDiv.querySelectorAll(":scope > .foo");

However, browser support is limited and you'll need a shim if you want to use it. I built scopedQuerySelectorShim for this purpose.

Android WebView style background-color:transparent ignored on android 2.2

I was trying to put a transparent HTML overlay over my GL view but it has always black flickering which covers my GL view. After several days trying to get rid of this flickering I found this workaround which is acceptable for me (but a shame for android).

The problem is that I need hardware acceleration for my nice CSS animations and so webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); is not an option for me.

The trick was to put a second (empty) WebView between my GL view and the HTML overlay. This dummyWebView I told to render in SW mode, and now my HTML overlays renders smooth in HW and no more black flickering.

I don't know if this works on other devices than My Acer Iconia A700, but I hope I could help someone with this.

public class MyActivity extends Activity {

    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        RelativeLayout layout = new RelativeLayout(getApplication());
        setContentView(layout);

        MyGlView glView = new MyGlView(this);

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);

        dummyWebView = new WebView(this);
        dummyWebView.setLayoutParams(params);
        dummyWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        dummyWebView.loadData("", "text/plain", "utf8");
        dummyWebView.setBackgroundColor(0x00000000);

        webView = new WebView(this);
        webView.setLayoutParams(params);
        webView.loadUrl("http://10.0.21.254:5984/ui/index.html");
        webView.setBackgroundColor(0x00000000);


        layout.addView(glView);
        layout.addView(dummyWebView);
        layout.addView(webView);
    }
}

Display milliseconds in Excel

Right click on Cell B1 and choose Format Cells. In Custom, put the following in the text box labeled Type:

[h]:mm:ss.000 

To set this in code, you can do something like:

Range("A1").NumberFormat = "[h]:mm:ss.000"

That should give you what you're looking for.

NOTE: Specially formatted fields often require that the column width be wide enough for the entire contents of the formatted text. Otherwise, the text will display as ######.

How can I change the default Mysql connection timeout when connecting through python?

Do:

con.query('SET GLOBAL connect_timeout=28800')
con.query('SET GLOBAL interactive_timeout=28800')
con.query('SET GLOBAL wait_timeout=28800')

Parameter meaning (taken from MySQL Workbench in Navigator: Instance > Options File > Tab "Networking" > Section "Timeout Settings")

  • connect_timeout: Number of seconds the mysqld server waits for a connect packet before responding with 'Bad handshake'
  • interactive_timeout Number of seconds the server waits for activity on an interactive connection before closing it
  • wait_timeout Number of seconds the server waits for activity on a connection before closing it

BTW: 28800 seconds are 8 hours, so for a 10 hour execution time these values should be actually higher.

Google map V3 Set Center to specific Marker

If you want to center map onto a marker and you have the cordinate, something like click on a list item and the map should center on that coordinate then the following code will work:

In HTML:

<ul class="locationList" ng-repeat="LocationDetail in coordinateArray| orderBy:'LocationName'">
   <li>
      <div ng-click="focusMarker(LocationDetail)">
          <strong><div ng-bind="locationDetail.LocationName"></div></strong>
          <div ng-bind="locationDetail.AddressLine"></div>
          <div ng-bind="locationDetail.State"></div>
          <div ng-bind="locationDetail.City"></div>
      <div>
   </li>
</ul>

In Controller:

$scope.focusMarker = function (coords) {
    map.setCenter(new google.maps.LatLng(coords.Latitude, coords.Longitude));
    map.setZoom(14);
}

Location Object:

{
    "Name": "Taj Mahal",
    "AddressLine": "Tajganj",
    "City": "Agra",
    "State": "Uttar Pradesh",
    "PhoneNumber": "1234 12344",
    "Latitude": "27.173891",
    "Longitude": "78.042068"
}

How to convert image to byte array

For Converting an Image object to byte[] you can do as follows:

public static byte[] converterDemo(Image x)
{
    ImageConverter _imageConverter = new ImageConverter();
    byte[] xByte = (byte[])_imageConverter.ConvertTo(x, typeof(byte[]));
    return xByte;
}

Pass user defined environment variable to tomcat

For Unix & Mac systems, Go to /bin/setenv.sh inside tomcat folder

Add the below line

export JAVA_OPTS="$JAVA_OPTS -DAPP_MASTER_PASSWORD=mypass"

Now System.getProperty("APP_MASTER_PASSWORD") will return "mypass"

Convert array to JSON string in swift

If you're already using SwiftyJSON:

https://github.com/SwiftyJSON/SwiftyJSON

You can do this:

// this works with dictionaries too
let paramsDictionary = [
    "title": "foo",
    "description": "bar"
]
let paramsArray = [ "one", "two" ]
let paramsJSON = JSON(paramsArray)
let paramsString = paramsJSON.rawString(encoding: NSUTF8StringEncoding, options: nil)

SWIFT 3 UPDATE

 let paramsJSON = JSON(paramsArray)
 let paramsString = paramsJSON.rawString(String.Encoding.utf8, options: JSONSerialization.WritingOptions.prettyPrinted)!

JSON strings, which are good for transport, don't come up often because you can JSON encode an HTTP body. But one potential use-case for JSON stringify is Multipart Post, which AlamoFire nows supports.

excel formula to subtract number of days from a date

You can paste it like this:

= "2010-12-20" - 180

And don't forget to format the cell as a Date [CTRL]+[F1] / Number Tab

href="file://" doesn't work

%20 is the space between AmberCRO SOP.

Try -

href="http://file:///K:/AmberCRO SOP/2011-07-05/SOP-SOP-3.0.pdf"

Or rename the folder as AmberCRO-SOP and write it as -

href="http://file:///K:/AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf"

How can I change a button's color on hover?

a.button a:hover means "a link that's being hovered over that is a child of a link with the class button".

Go instead for a.button:hover.

Finding local maxima/minima with Numpy in a 1D numpy array

In SciPy >= 0.11

import numpy as np
from scipy.signal import argrelextrema

x = np.random.random(12)

# for local maxima
argrelextrema(x, np.greater)

# for local minima
argrelextrema(x, np.less)

Produces

>>> x
array([ 0.56660112,  0.76309473,  0.69597908,  0.38260156,  0.24346445,
    0.56021785,  0.24109326,  0.41884061,  0.35461957,  0.54398472,
    0.59572658,  0.92377974])
>>> argrelextrema(x, np.greater)
(array([1, 5, 7]),)
>>> argrelextrema(x, np.less)
(array([4, 6, 8]),)

Note, these are the indices of x that are local max/min. To get the values, try:

>>> x[argrelextrema(x, np.greater)[0]]

scipy.signal also provides argrelmax and argrelmin for finding maxima and minima respectively.

How to window.scrollTo() with a smooth effect

2018 Update

Now you can use just window.scrollTo({ top: 0, behavior: 'smooth' }) to get the page scrolled with a smooth effect.

_x000D_
_x000D_
const btn = document.getElementById('elem');_x000D_
_x000D_
btn.addEventListener('click', () => window.scrollTo({_x000D_
  top: 400,_x000D_
  behavior: 'smooth',_x000D_
}));
_x000D_
#x {_x000D_
  height: 1000px;_x000D_
  background: lightblue;_x000D_
}
_x000D_
<div id='x'>_x000D_
  <button id='elem'>Click to scroll</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Older solutions

You can do something like this:

_x000D_
_x000D_
var btn = document.getElementById('x');_x000D_
_x000D_
btn.addEventListener("click", function() {_x000D_
  var i = 10;_x000D_
  var int = setInterval(function() {_x000D_
    window.scrollTo(0, i);_x000D_
    i += 10;_x000D_
    if (i >= 200) clearInterval(int);_x000D_
  }, 20);_x000D_
})
_x000D_
body {_x000D_
  background: #3a2613;_x000D_
  height: 600px;_x000D_
}
_x000D_
<button id='x'>click</button>
_x000D_
_x000D_
_x000D_

ES6 recursive approach:

_x000D_
_x000D_
const btn = document.getElementById('elem');_x000D_
_x000D_
const smoothScroll = (h) => {_x000D_
  let i = h || 0;_x000D_
  if (i < 200) {_x000D_
    setTimeout(() => {_x000D_
      window.scrollTo(0, i);_x000D_
      smoothScroll(i + 10);_x000D_
    }, 10);_x000D_
  }_x000D_
}_x000D_
_x000D_
btn.addEventListener('click', () => smoothScroll());
_x000D_
body {_x000D_
  background: #9a6432;_x000D_
  height: 600px;_x000D_
}
_x000D_
<button id='elem'>click</button>
_x000D_
_x000D_
_x000D_

pandas get rows which are NOT in other dataframe

The currently selected solution produces incorrect results. To correctly solve this problem, we can perform a left-join from df1 to df2, making sure to first get just the unique rows for df2.

First, we need to modify the original DataFrame to add the row with data [3, 10].

df1 = pd.DataFrame(data = {'col1' : [1, 2, 3, 4, 5, 3], 
                           'col2' : [10, 11, 12, 13, 14, 10]}) 
df2 = pd.DataFrame(data = {'col1' : [1, 2, 3],
                           'col2' : [10, 11, 12]})

df1

   col1  col2
0     1    10
1     2    11
2     3    12
3     4    13
4     5    14
5     3    10

df2

   col1  col2
0     1    10
1     2    11
2     3    12

Perform a left-join, eliminating duplicates in df2 so that each row of df1 joins with exactly 1 row of df2. Use the parameter indicator to return an extra column indicating which table the row was from.

df_all = df1.merge(df2.drop_duplicates(), on=['col1','col2'], 
                   how='left', indicator=True)
df_all

   col1  col2     _merge
0     1    10       both
1     2    11       both
2     3    12       both
3     4    13  left_only
4     5    14  left_only
5     3    10  left_only

Create a boolean condition:

df_all['_merge'] == 'left_only'

0    False
1    False
2    False
3     True
4     True
5     True
Name: _merge, dtype: bool

Why other solutions are wrong

A few solutions make the same mistake - they only check that each value is independently in each column, not together in the same row. Adding the last row, which is unique but has the values from both columns from df2 exposes the mistake:

common = df1.merge(df2,on=['col1','col2'])
(~df1.col1.isin(common.col1))&(~df1.col2.isin(common.col2))
0    False
1    False
2    False
3     True
4     True
5    False
dtype: bool

This solution gets the same wrong result:

df1.isin(df2.to_dict('l')).all(1)

How to verify a method is called two times with mockito verify()

build gradle:

testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"

code:

interface MyCallback {
  fun someMethod(value: String)
}

class MyTestableManager(private val callback: MyCallback){
  fun perform(){
    callback.someMethod("first")
    callback.someMethod("second")
    callback.someMethod("third")
  }
}

test:

import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.mock
...
val callback: MyCallback = mock()
val manager = MyTestableManager(callback)
manager.perform()

val captor: KArgumentCaptor<String> = com.nhaarman.mockitokotlin2.argumentCaptor<String>()

verify(callback, times(3)).someMethod(captor.capture())

assertTrue(captor.allValues[0] == "first")
assertTrue(captor.allValues[1] == "second")
assertTrue(captor.allValues[2] == "third")

Where does mysql store data?

as @PhilHarvey said, you can use mysqld --verbose --help | grep datadir

Rotating x axis labels in R for barplot

Rotate the x axis labels with angle equal or smaller than 90 degrees using base graphics. Code adapted from the R FAQ:

par(mar = c(7, 4, 2, 2) + 0.2) #add room for the rotated labels

#use mtcars dataset to produce a barplot with qsec colum information
mtcars = mtcars[with(mtcars, order(-qsec)), ] #order mtcars data set by column "qsec"

end_point = 0.5 + nrow(mtcars) + nrow(mtcars) - 1 #this is the line which does the trick (together with barplot "space = 1" parameter)

barplot(mtcars$qsec, col = "grey50", 
        main = "",
        ylab = "mtcars - qsec", ylim = c(0,5 + max(mtcars$qsec)),
        xlab = "",
        space = 1)
#rotate 60 degrees (srt = 60)
text(seq(1.5, end_point, by = 2), par("usr")[3]-0.25, 
     srt = 60, adj = 1, xpd = TRUE,
     labels = paste(rownames(mtcars)), cex = 0.65)

enter image description here

Cannot open Windows.h in Microsoft Visual Studio

The right combination of Windows SDK Version and Platform Toolset needs to be selected Depends of course what toolset you have currently installed

SDK Version and Platform Toolset

Remove all whitespaces from NSString

stringByReplacingOccurrencesOfString will replace all white space with in the string non only the starting and end

Use

[YourString stringByTrimmingCharactersInSet:[NSCharacterSet  whitespaceAndNewlineCharacterSet]]

How do I export (and then import) a Subversion repository?

Excerpt from my Blog-Note-to-myself:

Now you can import a dump file e.g. if you are migrating between machines / subversion versions. e.g. if I had created a dump file from the source repository and load it into the new repository as shown below.

Commands for Unix-like systems (from terminal):

svnadmin dump /path/to/your/old/repo > backup.dump
svnadmin load /path/to/your/new/repo < backup.dump.dmp

Commands for Microsoft Windows systems (from cmd shell):

svnadmin dump C:\path\to\your\old\repo > backup.dump
svnadmin load C:\path\to\your\old\repo < backup.dump

Sending SMS from PHP

PHP by itself has no SMS module or functions and doesn't allow you to send SMS.

SMS ( Short Messaging System) is a GSM technology an you need a GSM provider that will provide this service for you and may have an PHP API implementation for it.

Usually people in telecom business use Asterisk to handle calls and sms programming.

Rethrowing exceptions in Java without losing the stack trace

You can also wrap the exception in another one AND keep the original stack trace by passing in the Exception as a Throwable as the cause parameter:

try
{
   ...
}
catch (Exception e)
{
     throw new YourOwnException(e);
}

How to pretty print nested dictionaries?

I wrote this simple code to print the general structure of a json object in Python.

def getstructure(data, tab = 0):
    if type(data) is dict:
        print ' '*tab + '{' 
        for key in data:
            print ' '*tab + '  ' + key + ':'
            getstructure(data[key], tab+4)
        print ' '*tab + '}'         
    elif type(data) is list and len(data) > 0:
        print ' '*tab + '['
        getstructure(data[0], tab+4)
        print ' '*tab + '  ...'
        print ' '*tab + ']'

the result for the following data

a = {'list':['a','b',1,2],'dict':{'a':1,2:'b'},'tuple':('a','b',1,2),'function':'p','unicode':u'\xa7',("tuple","key"):"valid"}
getstructure(a)

is very compact and looks like this:

{
  function:
  tuple:
  list:
    [
      ...
    ]
  dict:
    {
      a:
      2:
    }
  unicode:
  ('tuple', 'key'):
}

How to increase editor font size?

enter image description here

Ctrl + Shift + A --> enter Font size --> select Increase Font Size

this will open Dialog for Enter Action or option Name

enter Fonte Size it will show selection for select Increase Font Size

Done :)

Best /Fastest way to read an Excel Sheet into a DataTable?

You can use OpenXml SDK for *.xlsx files. It works very quickly. I made simple C# IDataReader implementation for this sdk. See here. Now you can easy read excel file to DataTable and you can import excel file to sql server database (use SqlBulkCopy). ExcelDataReader reads very fast. On my machine 10000 records less 3 sec and 60000 less 8 sec.

Read to DataTable example:

class Program
{
    static void Main(string[] args)
    {
        var dt = new DataTable();
        using (var reader = new ExcelDataReader(@"data.xlsx"))
            dt.Load(reader);

        Console.WriteLine("done: " + dt.Rows.Count);
        Console.ReadKey();
   }
}

jQuery location href

I think you are looking for:

window.location = 'http://someUrl.com';

It's not jQuery; it's pure JavaScript.

Removing trailing newline character from fgets() input

The elegant way:

Name[strcspn(Name, "\n")] = 0;

The slightly ugly way:

char *pos;
if ((pos=strchr(Name, '\n')) != NULL)
    *pos = '\0';
else
    /* input too long for buffer, flag error */

The slightly strange way:

strtok(Name, "\n");

Note that the strtok function doesn't work as expected if the user enters an empty string (i.e. presses only Enter). It leaves the \n character intact.

There are others as well, of course.

POST request via RestTemplate in JSON

If you don't want to map the JSON by yourself, you can do it as follows:

RestTemplate restTemplate = new RestTemplate();
restTemplate.setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter()));
ResponseEntity<String> result = restTemplate.postForEntity(uri, yourObject, String.class);

Pandas split column of lists into multiple columns

Based on the previous answers, here is another solution which returns the same result as df2.teams.apply(pd.Series) with a much faster run time:

pd.DataFrame([{x: y for x, y in enumerate(item)} for item in df2['teams'].values.tolist()], index=df2.index)

Timings:

In [1]:
import pandas as pd
d1 = {'teams': [['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],
                ['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG']]}
df2 = pd.DataFrame(d1)
df2 = pd.concat([df2]*1000).reset_index(drop=True)

In [2]: %timeit df2['teams'].apply(pd.Series)

8.27 s ± 2.73 s per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [3]: %timeit pd.DataFrame([{x: y for x, y in enumerate(item)} for item in df2['teams'].values.tolist()], index=df2.index)

35.4 ms ± 5.22 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Conversion failed when converting the nvarchar value ... to data type int

You got this Error because you tried to convert column DataType from String to int which is

leagal if and only if

you dont have row in that table with string content inside that column

so just make sure your previously inserted Rows is compatible with the new changes

2 "style" inline css img tags?

You don't need 2 style attributes - just use one:

<img src="http://img705.imageshack.us/img705/119/original120x75.png" 
                                     style="height:100px;width:100px;" alt="25"/>

Consider, however, using a CSS class instead:

CSS:

.100pxSquare
{
  width: 100px;
  height: 100px;
}

HTML:

<img src="http://img705.imageshack.us/img705/119/original120x75.png" 
                                          class="100pxSquare" alt="25"/>

Pip - Fatal error in launcher: Unable to create process using '"'

I solved it by following the steps from this website https://www.sysrecon.com/programming/python-pip-how-to-get-around-fatal-error-in-launcher-unable-to-create-process-using/

Update pip using: python -m pip install -U pip from command line after you've located the right directory in which python is installed in your machine.

Javascript ajax call on page onload

It's even easier to do without a library

window.onload = function() {
    // code
};

How to grant remote access to MySQL for a whole subnet?

Just a note of a peculiarity I faced:
Consider:

db server:  192.168.0.101
web server: 192.168.0.102

If you have a user defined in mysql.user as 'user'@'192.168.0.102' with password1 and another 'user'@'192.168.0.%' with password2,

then,

if you try to connect to the db server from the web server as 'user' with password2,

it will result in an 'Access denied' error because the single IP 'user'@'192.168.0.102' authentication is used over the wildcard 'user'@'192.168.0.%' authentication.

Vertical rulers in Visual Studio Code

In v1.43 is the ability to separately color the vertical rulers.

See issue Support multiple rulers with different colors - (in settings.json):

"editor.rulers": [
  {
    "column": 80,
    "color": "#ff00FF"
  },
  100,  // <- a ruler in the default color or as customized (with "editorRuler.foreground") at column 100
  {
    "column": 120,
    "color": "#ff0000"
  },
], 

Python append() vs. + operator on lists, why do these give different results?

To explain "why":

The + operation adds the array elements to the original array. The array.append operation inserts the array (or any object) into the end of the original array, which results in a reference to self in that spot (hence the infinite recursion).

The difference here is that the + operation acts specific when you add an array (it's overloaded like others, see this chapter on sequences) by concatenating the element. The append-method however does literally what you ask: append the object on the right-hand side that you give it (the array or any other object), instead of taking its elements.

An alternative

Use extend() if you want to use a function that acts similar to the + operator (as others have shown here as well). It's not wise to do the opposite: to try to mimic append with the + operator for lists (see my earlier link on why).

Little history

For fun, a little history: the birth of the array module in Python in February 1993. it might surprise you, but arrays were added way after sequences and lists came into existence.

Showing data values on stacked bar chart in ggplot2

From ggplot 2.2.0 labels can easily be stacked by using position = position_stack(vjust = 0.5) in geom_text.

ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
  geom_bar(stat = "identity") +
  geom_text(size = 3, position = position_stack(vjust = 0.5))

enter image description here

Also note that "position_stack() and position_fill() now stack values in the reverse order of the grouping, which makes the default stack order match the legend."


Answer valid for older versions of ggplot:

Here is one approach, which calculates the midpoints of the bars.

library(ggplot2)
library(plyr)

# calculate midpoints of bars (simplified using comment by @DWin)
Data <- ddply(Data, .(Year), 
   transform, pos = cumsum(Frequency) - (0.5 * Frequency)
)

# library(dplyr) ## If using dplyr... 
# Data <- group_by(Data,Year) %>%
#    mutate(pos = cumsum(Frequency) - (0.5 * Frequency))

# plot bars and add text
p <- ggplot(Data, aes(x = Year, y = Frequency)) +
     geom_bar(aes(fill = Category), stat="identity") +
     geom_text(aes(label = Frequency, y = pos), size = 3)

Resultant chart

Implementing a simple file download servlet

And to send a largFile

byte[] pdfData = getPDFData();

String fileType = "";

res.setContentType("application/pdf");

httpRes.setContentType("application/.pdf");
httpRes.addHeader("Content-Disposition", "attachment; filename=IDCards.pdf");
httpRes.setStatus(HttpServletResponse.SC_OK);
OutputStream out = res.getOutputStream();
System.out.println(pdfData.length);
         
out.write(pdfData);
System.out.println("sendDone");
out.flush();

Java 8 NullPointerException in Collectors.toMap

NullPointerException is by far the most frequently encountered exception (at least in my case). To avoid this I go defensive and add bunch of null checks and I end up having bloated and ugly code. Java 8 introduces Optional to handle null references so you can define nullable and non-nullable values.

That said, I would wrap all the nullable references in Optional container. We should also not break backward compatibility as well. Here is the code.

class Answer {
    private int id;
    private Optional<Boolean> answer;

    Answer() {
    }

    Answer(int id, Boolean answer) {
        this.id = id;
        this.answer = Optional.ofNullable(answer);
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    /**
     * Gets the answer which can be a null value. Use {@link #getAnswerAsOptional()} instead.
     *
     * @return the answer which can be a null value
     */
    public Boolean getAnswer() {
        // What should be the default value? If we return null the callers will be at higher risk of having NPE
        return answer.orElse(null);
    }

    /**
     * Gets the optional answer.
     *
     * @return the answer which is contained in {@code Optional}.
     */
    public Optional<Boolean> getAnswerAsOptional() {
        return answer;
    }

    /**
     * Gets the answer or the supplied default value.
     *
     * @return the answer or the supplied default value.
     */
    public boolean getAnswerOrDefault(boolean defaultValue) {
        return answer.orElse(defaultValue);
    }

    public void setAnswer(Boolean answer) {
        this.answer = Optional.ofNullable(answer);
    }
}

public class Main {
    public static void main(String[] args) {
        List<Answer> answerList = new ArrayList<>();

        answerList.add(new Answer(1, true));
        answerList.add(new Answer(2, true));
        answerList.add(new Answer(3, null));

        // map with optional answers (i.e. with null)
        Map<Integer, Optional<Boolean>> answerMapWithOptionals = answerList.stream()
                .collect(Collectors.toMap(Answer::getId, Answer::getAnswerAsOptional));

        // map in which null values are removed
        Map<Integer, Boolean> answerMapWithoutNulls = answerList.stream()
                .filter(a -> a.getAnswerAsOptional().isPresent())
                .collect(Collectors.toMap(Answer::getId, Answer::getAnswer));

        // map in which null values are treated as false by default
        Map<Integer, Boolean> answerMapWithDefaults = answerList.stream()
                .collect(Collectors.toMap(a -> a.getId(), a -> a.getAnswerOrDefault(false)));

        System.out.println("With Optional: " + answerMapWithOptionals);
        System.out.println("Without Nulls: " + answerMapWithoutNulls);
        System.out.println("Wit Defaults: " + answerMapWithDefaults);
    }
}

HTTP Status 504

I have had another issue giving me a 504. It's pretty far out but I'll write it up here for googlers and posterity...

I have a client calling an IIS hosted webservice hosted in another domain (Active Directory). There is not full trust between the client domain and the domain where the web services is hosted. One of the many challenges with the selective trust between these two domains is that Kerberos does not work when calling from one to the other.

In my case I was trying to call a service in another domain where I found out that a SPN was registered. Like this : http/myurl.test.local (just an example)

This forces the call to use Kerberos instead of letting it fall back to NTLM and this gave me a 405 back from the calling server.

After removing the spn and allowing the call to fall back to NTLM, it works fine.

As I said ... this is not something you are likely to run into, as most organizations do not venture into having such a selective trusts between two domains ... But it gives a 504 and caused me a few (more) gray hairs.

Unsigned values in C

Assign a int -1 to an unsigned: As -1 does not fit in the range [0...UINT_MAX], multiples of UINT_MAX+1 are added until the answer is in range. Evidently UINT_MAX is pow(2,32)-1 or 429496725 on OP's machine so a has the value of 4294967295.

    unsigned int a = -1;

The "%x", "%u" specifier expects a matching unsigned. Since these do not match, "If a conversion specification is invalid, the behavior is undefined. If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined." C11 §7.21.6.1 9. The printf specifier does not change b.

    printf("%x\n", b);  // UB
    printf("%u\n", b);  // UB

The "%d" specifier expects a matching int. Since these do not match, more UB.

    printf("%d\n", a);  // UB

Given undefined behavior, the conclusions are not supported.


both cases, the bytes are the same (ffffffff).

Even with the same bit pattern, different types may have different values. ffffffff as an unsigned has the value of 4294967295. As an int, depending signed integer encoding, it has the value of -1, -2147483647 or TBD. As a float it may be a NAN.

what is unsigned word for?

unsigned stores a whole number in the range [0 ... UINT_MAX]. It never has a negative value. If code needs a non-negative number, use unsigned. If code needs a counting number that may be +, - or 0, use int.


Update: to avoid a compiler warning about assigning a signed int to unsigned, use the below. This is an unsigned 1u being negated - which is well defined as above. The effect is the same as a -1, but conveys to the compiler direct intentions.

unsigned int a = -1u;

HTML/Javascript change div content

you can use following helper function:

function content(divSelector, value) {
    document.querySelector(divSelector).innerHTML = value;
}

content('#content',"whatever");

Where #content must be valid CSS selector

Here is working example.


Additionaly - today (2018.07.01) I made speed comparison for jquery and pure js solutions ( MacOs High Sierra 10.13.3 on Chrome 67.0.3396.99 (64-bit), Safari 11.0.3 (13604.5.6), Firefox 59.0.2 (64-bit) ):

document.getElementById("content").innerHTML = "whatever"; // pure JS
$('#content').html('whatever');                            // jQuery

enter image description here

The jquery solution was slower than pure js solution: 69% on firefox, 61% on safari, 56% on chrome. The fastest browser for pure js was firefox with 560M operations per second, the second was safari 426M, and slowest was chrome 122M.

So the winners are pure js and firefox (3x faster than chrome!)

You can test it in your machine: https://jsperf.com/js-jquery-html-content-change

Signtool error: No certificates were found that met all given criteria with a Windows Store App?

I had the same "After Private Key filter, 0 certs were left" message and spent too much of my life trying to figure out what the message meant.

The problem was that I had installed the certificate incorrectly in the Windows Certificate store so there was no private key associated with the code signing certificate.

What I should have done was this:

  1. Using either Firefox or Internet Explorer, submit the request to the issuer. This generates a PRIVATE KEY which is stored silently by the browser (a dialog appears for a fraction of a second in Firefox). Note that other browsers may not work: your life is too short to find out if they do.

  2. Submit the request, jump through the issuer's validation hoops and loops, sacrifice a goat, pray to the gods, submit a signed statement from your great grandparents, etc.

  3. Download the certificate (.crt) and import it into the same browser. The browser now has both the private key and the certificate.

  4. Export the certificate from the browser as a Personal Information Exchange (.p12) file. You will be asked to supply a password to protect this file.

  5. Keep a backup copy of the .p12 file.

  6. Run the Certificate Manager (certmgr.msc), right click on the Personal certificate store, select All Tasks/Import... and import the .p12 file into Windows. You will be asked for the password you used to protect the file. At this point, depending upon your security requirements, you can mark the key as exportable so you can restore a copy from the Windows store. You can also mark that a password is required before use if you want to break batch scripts.

  7. Run signtool successfully, breathe a sigh of relief, and ponder how much of your life you have wasted due to bad error messages and poor or missing documentation.

Python: Remove division decimal

There is a math function modf() that will break this up as well.

import math

print("math.modf(3.14159) : ", math.modf(3.14159))

will output a tuple: math.modf(3.14159) : (0.14159, 3.0)

This is useful if you want to keep both the whole part and decimal for reference like:

decimal, whole = math.modf(3.14159)

How to SHUTDOWN Tomcat in Ubuntu?

For a more graceful way, try the following:

Caveat: I'm running Debian 7, not Ubuntu, though it is a Debian derivative

If you're running Tomcat as a service, you can get a list of all running services by typing:

sudo service --status-all

I'm running Tomcat 7, which is displayed as tomcat7 in said list. Then, to shut it down just type:

sudo service tomcat7 stop

get next sequence value from database using hibernate

Interesting it works for you. When I tried your solution an error came up, saying that "Type mismatch: cannot convert from SQLQuery to Query". --> Therefore my solution looks like:

SQLQuery query = session.createSQLQuery("select nextval('SEQUENCE_NAME')");
Long nextValue = ((BigInteger)query.uniqueResult()).longValue();

With that solution I didn't run into performance problems.

And don't forget to reset your value, if you just wanted to know for information purposes.

    --nextValue;
    query = session.createSQLQuery("select setval('SEQUENCE_NAME'," + nextValue + ")");

Set timeout for webClient.DownloadFile()

Assuming you wanted to do this synchronously, using the WebClient.OpenRead(...) method and setting the timeout on the Stream that it returns will give you the desired result:

using (var webClient = new WebClient())
using (var stream = webClient.OpenRead(streamingUri))
{
     if (stream != null)
     {
          stream.ReadTimeout = Timeout.Infinite;
          using (var reader = new StreamReader(stream, Encoding.UTF8, false))
          {
               string line;
               while ((line = reader.ReadLine()) != null)
               {
                    if (line != String.Empty)
                    {
                        Console.WriteLine("Count {0}", count++);
                    }
                    Console.WriteLine(line);
               }
          }
     }
}

Deriving from WebClient and overriding GetWebRequest(...) to set the timeout @Beniamin suggested, didn't work for me as, but this did.

How to include clean target in Makefile?

The best thing is probably to create a variable that holds your binaries:

binaries=code1 code2

Then use that in the all-target, to avoid repeating:

all: clean $(binaries)

Now, you can use this with the clean-target, too, and just add some globs to catch object files and stuff:

.PHONY: clean

clean:
    rm -f $(binaries) *.o

Note use of the .PHONY to make clean a pseudo-target. This is a GNU make feature, so if you need to be portable to other make implementations, don't use it.

Entity Framework vs LINQ to SQL

Is LINQ to SQL Truly Dead? by Jonathan Allen for InfoQ.com

Matt Warren describes [LINQ to SQL] as something that "was never even supposed to exist." Essentially, it was just supposed to be stand-in to help them develop LINQ until the real ORM was ready.

...

The scale of Entity Framework caused it to miss the .NET 3.5/Visual Studio 2008 deadline. It was completed in time for the unfortunately named ".NET 3.5 Service Pack 1", which was more like a major release than a service pack.

...

Developers do not like [ADO.NET Entity Framework] because of the complexity.

...

as of .NET 4.0, LINQ to Entities will be the recommended data access solution for LINQ to relational scenarios.

How to exit from the application and show the home screen?

Here's what i did:

SomeActivity.java

 @Override
    public void onBackPressed() {
            Intent newIntent = new Intent(this,QuitAppActivity.class);
            newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(newIntent);
            finish();
    }

QuitAppActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      finish();
}

Basically what you did is cleared all activities from the stack and launch QuitAppActivity, that will finish the task.

Using "super" in C++

After migrating from Turbo Pascal to C++ back in the day, I used to do this in order to have an equivalent for the Turbo Pascal "inherited" keyword, which works the same way. However, after programming in C++ for a few years I stopped doing it. I found I just didn't need it very much.

SOAP or REST for Web Services?

It's nuanced.

If you need to have other systems interface with your services, than a lot of clients will be happier with SOAP, due to the layers of "verification" you have with the contracts, WSDL, and the SOAP standard.

For day-to-day systems calling into systems, I think that SOAP is a lot of unnecessary overhead when a simple HTML call will do.

How to use cookies in Python Requests

You can use a session object. It stores the cookies so you can make requests, and it handles the cookies for you

s = requests.Session() 
# all cookies received will be stored in the session object

s.post('http://www...',data=payload)
s.get('http://www...')

Docs: https://requests.readthedocs.io/en/master/user/advanced/#session-objects

You can also save the cookie data to an external file, and then reload them to keep session persistent without having to login every time you run the script:

How to save requests (python) cookies to a file?

Func delegate with no return type

All of the Func delegates take at least one parameter

That's not true. They all take at least one type argument, but that argument determines the return type.

So Func<T> accepts no parameters and returns a value. Use Action or Action<T> when you don't want to return a value.

.htaccess redirect all pages to new domain

There are various ways to do this and various redirects, I've listed them below:

301 (Permanent) Redirect: Point an entire site to a different URL on a permanent basis. This is the most common type of redirect and is useful in most situations. In this example, we are redirecting to the "example.com" domain:

# This allows you to redirect your entire website to any other domain
Redirect 301 / http://example.com/

302 (Temporary) Redirect: Point an entire site to a different temporary URL. This is useful for SEO purposes when you have a temporary landing page and plan to switch back to your main landing page at a later date:

# This allows you to redirect your entire website to any other domain
Redirect 302 / http://example.com/

Redirect index.html to a specific subfolder:

# This allows you to redirect index.html to a specific subfolder
Redirect /index.html http://example.com/newdirectory/

Redirect an old file to a new file path:

# Redirect old file path to new file path
Redirect /olddirectory/oldfile.html http://example.com/newdirectory/newfile.html

Redirect to a specific index page:

# Provide Specific Index Page (Set the default handler)
DirectoryIndex index.html

Download a file with Android, and showing the progress in a ProgressDialog

My personal advice is to use Progress Dialog and build up before execution , or initiate at OnPreExecute() , publish progress often if you use horizontal style of progress bar of the progress dialog. The remaining part is to optimize the algorithm of doInBackground.

How to do a logical OR operation for integer comparison in shell scripting?

This should work:

#!/bin/bash

if [ "$#" -eq 0 ] || [ "$#" -gt 1 ] ; then
    echo "hello"
fi

I'm not sure if this is different in other shells but if you wish to use <, >, you need to put them inside double parenthesis like so:

if (("$#" > 1))
 ...

File URL "Not allowed to load local resource" in the Internet Browser

Follow the below steps,

  1. npm install -g http-server, install the http-server in angular project.
  2. Go to file location which needs to be accessed and open cmd prompt, use cmd http-server ./
  3. Access any of the paths with port number in browser(ex: 120.0.0.1:8080) 4.now in your angular application use the path "http://120.0.0.1:8080/filename" Worked fine for me

How do I remove all .pyc files from a project?

rm -r recurses into directories, but only the directories you give to rm. It will also delete those directories. One solution is:

for i in $( find . -name *.pyc )
do
  rm $i
done

find will find all *.pyc files recursively in the current directory, and the for loop will iterate through the list of files found, removing each one.

Pretty printing JSON from Jackson 2.2's ObjectMapper

the IDENT_OUTPUT did not do anything for me, and to give a complete answer that works with my jackson 2.2.3 jars:

public static void main(String[] args) throws IOException {

byte[] jsonBytes = Files.readAllBytes(Paths.get("C:\\data\\testfiles\\single-line.json"));

ObjectMapper objectMapper = new ObjectMapper();

Object json = objectMapper.readValue( jsonBytes, Object.class );

System.out.println( objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString( json ) );
}

How to get CSS to select ID that begins with a string (not in Javascript)?

I'd do it like this:

[id^="product"] {
  ...
}

Ideally, use a class. This is what classes are for:

<div id="product176" class="product"></div>
<div id="product177" class="product"></div>
<div id="product178" class="product"></div>

And now the selector becomes:

.product {
  ...
}

doGet and doPost in Servlets

The servlet container's implementation of HttpServlet.service() method will automatically forward to doGet() or doPost() as necessary, so you shouldn't need to override the service method.

How to regex in a MySQL query

In my case (Oracle), it's WHERE REGEXP_LIKE(column, 'regex.*'). See here:

SQL Function

Description


REGEXP_LIKE

This function searches a character column for a pattern. Use this function in the WHERE clause of a query to return rows matching the regular expression you specify.

...

REGEXP_REPLACE

This function searches for a pattern in a character column and replaces each occurrence of that pattern with the pattern you specify.

...

REGEXP_INSTR

This function searches a string for a given occurrence of a regular expression pattern. You specify which occurrence you want to find and the start position to search from. This function returns an integer indicating the position in the string where the match is found.

...

REGEXP_SUBSTR

This function returns the actual substring matching the regular expression pattern you specify.

(Of course, REGEXP_LIKE only matches queries containing the search string, so if you want a complete match, you'll have to use '^$' for a beginning (^) and end ($) match, e.g.: '^regex.*$'.)

How do I rewrite URLs in a proxy response in NGINX

You may also need the following directive to be set before the first "sub_filter" for backend-servers with data compression:

proxy_set_header Accept-Encoding "";

Otherwise it may not work. For your example it will look like:

location /admin/ {
    proxy_pass http://localhost:8080/;
    proxy_set_header Accept-Encoding "";
    sub_filter "http://your_server/" "http://your_server/admin/";
    sub_filter_once off;
}

WooCommerce return product object by id

Use this method:

$_product = wc_get_product( $id );

Official API-docs: wc_get_product

How to pass value from <option><select> to form action

instead of trying to catch both POST and GET responses - you can have everything you want in the POST.

Your code:

<form method="POST" action="index.php?action=contact_agent&agent_id=">
  <select>
    <option value="1">Agent Homer</option>
    <option value="2">Agent Lenny</option>
    <option value="3">Agent Carl</option>
  </select>
</form>

can easily become:

<form method="POST" action="index.php">
  <input type="hidden" name="action" value="contact_agent">
  <select name="agent_id">
    <option value="1">Agent Homer</option>
    <option value="2">Agent Lenny</option>
    <option value="3">Agent Carl</option>
  </select>
  <button type="submit">Submit POST Data</button>
</form>

then in index.php - these values will be populated

$_POST['action'] // "contact_agent"
$_POST['agent_id'] // 1, 2 or 3 based on selection in form... 

What are bitwise shift (bit-shift) operators and how do they work?

The Bitwise operators are used to perform operations a bit-level or to manipulate bits in different ways. The bitwise operations are found to be much faster and are some times used to improve the efficiency of a program. Basically, Bitwise operators can be applied to the integer types: long, int, short, char and byte.

Bitwise Shift Operators

They are classified into two categories left shift and the right shift.

  • Left Shift(<<): The left shift operator, shifts all of the bits in value to the left a specified number of times. Syntax: value << num. Here num specifies the number of position to left-shift the value in value. That is, the << moves all of the bits in the specified value to the left by the number of bit positions specified by num. For each shift left, the high-order bit is shifted out (and ignored/lost), and a zero is brought in on the right. This means that when a left shift is applied to 32-bit compiler, bits are lost once they are shifted past bit position 31. If the compiler is of 64-bit then bits are lost after bit position 63.

enter image description here

Output: 6, Here the binary representation of 3 is 0...0011(considering 32-bit system) so when it shifted one time the leading zero is ignored/lost and all the rest 31 bits shifted to left. And zero is added at the end. So it became 0...0110, the decimal representation of this number is 6.

  • In the case of a negative number:

Code for Negative number.

Output: -2, In java negative number, is represented by 2's complement. SO, -1 represent by 2^32-1 which is equivalent to 1....11(Considering 32-bit system). When shifted one time the leading bit is ignored/lost and the rest 31 bits shifted to left and zero is added at the last. So it becomes, 11...10 and its decimal equivalent is -2. So, I think you get enough knowledge about the left shift and how its work.

  • Right Shift(>>): The right shift operator, shifts all of the bits in value to the right a specified of times. Syntax: value >> num, num specifies the number of positions to right-shift the value in value. That is, the >> moves/shift all of the bits in the specified value of the right the number of bit positions specified by num. The following code fragment shifts the value 35 to the right by two positions:

enter image description here

Output: 8, As a binary representation of 35 in a 32-bit system is 00...00100011, so when we right shift it two times the first 30 leading bits are moved/shifts to the right side and the two low-order bits are lost/ignored and two zeros are added at the leading bits. So, it becomes 00....00001000, the decimal equivalent of this binary representation is 8. Or there is a simple mathematical trick to find out the output of this following code: To generalize this we can say that, x >> y = floor(x/pow(2,y)). Consider the above example, x=35 and y=2 so, 35/2^2 = 8.75 and if we take the floor value then the answer is 8.

enter image description here

Output:

enter image description here

But remember one thing this trick is fine for small values of y if you take the large values of y it gives you incorrect output.

  • In the case of a negative number: Because of the negative numbers the Right shift operator works in two modes signed and unsigned. In signed right shift operator (>>), In case of a positive number, it fills the leading bits with 0. And In case of a negative number, it fills leading bits with 1. To keep the sign. This is called 'sign extension'.

enter image description here

Output: -5, As I explained above the compiler stores the negative value as 2's complement. So, -10 is represented as 2^32-10 and in binary representation considering 32-bit system 11....0110. When we shift/ move one time the first 31 leading bits got shifted in the right side and the low-order bit got lost/ignored. So, it becomes 11...0011 and the decimal representation of this number is -5 (How I know the sign of number? because the leading bit is 1). It is interesting to note that if you shift -1 right, the result always remains -1 since sign extension keeps bringing in more ones in the high-order bits.

  • Unsigned Right Shift(>>>): This operator also shifts bits to the right. The difference between signed and unsigned is the latter fills the leading bits with 1 if the number is negative and the former fills zero in either case. Now the question arises why we need unsigned right operation if we get the desired output by signed right shift operator. Understand this with an example, If you are shifting something that does not represent a numeric value, you may not want sign extension to take place. This situation is common when you are working with pixel-based values and graphics. In these cases, you will generally want to shift a zero into the high-order bit no matter what it's the initial value was.

enter image description here

Output: 2147483647, Because -2 is represented as 11...10 in a 32-bit system. When we shift the bit by one, the first 31 leading bit is moved/shifts in right and the low-order bit is lost/ignored and the zero is added to the leading bit. So, it becomes 011...1111 (2^31-1) and its decimal equivalent is 2147483647.

CSS change button style after click

If you're looking for a pure css option, try using the :focus pseudo class.

#style  {
    background-color: red;
}

#style:focus {     
    background-color:yellow;    
}

How can I pause setInterval() functions?

You shouldn't measure time in interval function. Instead just save time when timer was started and measure difference when timer was stopped/paused. Use setInterval only to update displayed value. So there is no need to pause timer and you will get best possible accuracy in this way.

Distinct() with lambda?

The Microsoft System.Interactive package has a version of Distinct that takes a key selector lambda. This is effectively the same as Jon Skeet's solution, but it may be helpful for people to know, and to check out the rest of the library.

I can't find my git.exe file in my Github folder

I found my git.exe here

C:\Program Files\Git\bin\git.exe

while installing git, it asks for the location. copy it and use it.

What is a word boundary in regex, does \b match hyphen '-'?

A word boundary, in most regex dialects, is a position between \w and \W (non-word char), or at the beginning or end of a string if it begins or ends (respectively) with a word character ([0-9A-Za-z_]).

So, in the string "-12", it would match before the 1 or after the 2. The dash is not a word character.

Getting java.net.SocketTimeoutException: Connection timed out in android

public JSONObject RequestWithHttpUrlConn(String _url, String param){

    HttpURLConnection con = null;
    URL url;
    String response = "";
    Scanner inStream = null;
    PrintWriter out = null;
    try {
        url = new URL(_url);
        con = (HttpURLConnection) url.openConnection();
        con.setDoOutput(true);
        con.setRequestMethod("POST");
        if(param != null){
            con.setFixedLengthStreamingMode(param.getBytes().length);
        }
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        out = new PrintWriter(con.getOutputStream());
        if(param != null){
            out.print(param);
        }
        out.flush();
        out.close();
        inStream = new Scanner(con.getInputStream());

        while(inStream.hasNextLine()){
            response+=(inStream.nextLine());
        }
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally{
        if(con != null){
            con.disconnect();
        }if(inStream != null){
            inStream.close();
        }if(out != null){
            out.flush();
            out.close();
        }
    }
}

cvc-elt.1: Cannot find the declaration of element 'MyElement'

After making the change suggested above by Martin, I was still getting the same error. I had to make an additional change to my parsing code. I was parsing the XML file via a DocumentBuilder as shown in the oracle docs: https://docs.oracle.com/javase/7/docs/api/javax/xml/validation/package-summary.html

// parse an XML document into a DOM tree
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = parser.parse(new File("example.xml"));

The problem was that DocumentBuilder is not namespace aware by default. The following additional change resolved the issue:

// parse an XML document into a DOM tree
DocumentBuilderFactory dmfactory = DocumentBuilderFactory.newInstance();
dmfactory.setNamespaceAware(true);

DocumentBuilder parser = dmfactory.newDocumentBuilder();
Document document = parser.parse(new File("example.xml"));

cordova run with ios error .. Error code 65 for command: xcodebuild with args:

I was getting the same error when I tried to do :

cordova build ios

except mine said ** ARCHIVE FAILED ** rather than ** BUILD FAILED **.

I fixed it by opening the projectName.xcodeproj file in Xcode and then adjusting these 2 settings :

  1. In Targets > General > Signing ensure you have selected a Team

enter image description here

  1. In Targets > Build Settings > (search for "bitcode") set Enable Bitcode to "Yes"

enter image description here

Then I quit out of Xcode and reran cordova build ios and it worked.

Can anonymous class implement interface?

Casting anonymous types to interfaces has been something I've wanted for a while but unfortunately the current implementation forces you to have an implementation of that interface.

The best solution around it is having some type of dynamic proxy that creates the implementation for you. Using the excellent LinFu project you can replace

select new
{
  A = value.A,
  B = value.C + "_" + value.D
};

with

 select new DynamicObject(new
 {
   A = value.A,
   B = value.C + "_" + value.D
 }).CreateDuck<DummyInterface>();

CASE (Contains) rather than equal statement

CASE WHEN ', ' + dbo.Table.Column +',' LIKE '%, lactulose,%' 
  THEN 'BP Medication' ELSE '' END AS [BP Medication]

The leading ', ' and trailing ',' are added so that you can handle the match regardless of where it is in the string (first entry, last entry, or anywhere in between).

That said, why are you storing data you want to search on as a comma-separated string? This violates all kinds of forms and best practices. You should consider normalizing your schema.

In addition: don't use 'single quotes' as identifier delimiters; this syntax is deprecated. Use [square brackets] (preferred) or "double quotes" if you must. See "string literals as column aliases" here: http://msdn.microsoft.com/en-us/library/bb510662%28SQL.100%29.aspx

EDIT If you have multiple values, you can do this (you can't short-hand this with the other CASE syntax variant or by using something like IN()):

CASE 
  WHEN ', ' + dbo.Table.Column +',' LIKE '%, lactulose,%' 
  WHEN ', ' + dbo.Table.Column +',' LIKE '%, amlodipine,%' 
  THEN 'BP Medication' ELSE '' END AS [BP Medication]

If you have more values, it might be worthwhile to use a split function, e.g.

USE tempdb;
GO

CREATE FUNCTION dbo.SplitStrings(@List NVARCHAR(MAX))
RETURNS TABLE
AS
   RETURN ( SELECT DISTINCT Item FROM
       ( SELECT Item = x.i.value('(./text())[1]', 'nvarchar(max)')
         FROM ( SELECT [XML] = CONVERT(XML, '<i>'
         + REPLACE(@List,',', '</i><i>') + '</i>').query('.')
           ) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y
       WHERE Item IS NOT NULL
   );
GO

CREATE TABLE dbo.[Table](ID INT, [Column] VARCHAR(255));
GO

INSERT dbo.[Table] VALUES
(1,'lactulose, Lasix (furosemide), oxazepam, propranolol, rabeprazole, sertraline,'),
(2,'lactulite, Lasix (furosemide), lactulose, propranolol, rabeprazole, sertraline,'),
(3,'lactulite, Lasix (furosemide), oxazepam, propranolol, rabeprazole, sertraline,'),
(4,'lactulite, Lasix (furosemide), lactulose, amlodipine, rabeprazole, sertraline,');

SELECT t.ID
  FROM dbo.[Table] AS t
  INNER JOIN dbo.SplitStrings('lactulose,amlodipine') AS s
  ON ', ' + t.[Column] + ',' LIKE '%, ' + s.Item + ',%'
  GROUP BY t.ID;
GO

Results:

ID
----
1
2
4

Add string in a certain position in Python

I think the above answers are fine, but I would explain that there are some unexpected-but-good side effects to them...

def insert(string_s, insert_s, pos_i=0):
    return string_s[:pos_i] + insert_s + string_s[pos_i:]

If the index pos_i is very small (too negative), the insert string gets prepended. If too long, the insert string gets appended. If pos_i is between -len(string_s) and +len(string_s) - 1, the insert string gets inserted into the correct place.

Jquery UI Datepicker not displaying

Had the same problem that the datepicker-DIV has been created but didnt get filled and show up on click. My fault was to give the input the class "hasDatepicker" staticly. jQuery-ui hat to set this class by its own. then it works for me.

Get the current language in device

Locale.getDefault().getDisplayLanguage()

will give you Written name for the Language, for example, English, Dutch, French

Locale.getDefault().getLanguage()

will give you language code, for instance: en, nl, fr

Both methods return String

Microsoft.ReportViewer.Common Version=12.0.0.0

Issue

Parser Error Message: Could not load file or assembly 'Microsoft.ReportViewer.WebForms / Winforms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified.

Cause

Microsoft ReportViewer runtime and SQL CLR Types for SQL Server 2014 is required to run and is missing from the server hosting Internet Information Services (IIS) or your application.

Resolution

Install the following packages on the IIS server and then restart the system:

Download Microsoft ReportViewer runtime

Download Microsoft SQL CLR types for SQL Server 2014

Once restarted connect to Web service / Your app again and verify that the error has been resolved.

Or you cant follow this link to read more.

jQuery: Change button text on click

In HTML:

<button type="button" id="AddButton" onclick="AddButtonClick()" class="btn btn-success btn-block ">Add</button> 

In Jquery write this function:

    function AddButtonClick(){ 
      //change text from add to Update
      $("#AddButton").text('Update');
    }

Where can I find a list of Mac virtual key codes?

Found an answer here.

So:

  • Command key is 55
  • Shift is 56
  • Caps Lock 57
  • Option is 58
  • Control is 59.

When should I use cross apply over inner join?

I guess it should be readability ;)

CROSS APPLY will be somewhat unique for people reading to tell them that a UDF is being used which will be applied to each row from the table on the left.

Ofcourse, there are other limitations where a CROSS APPLY is better used than JOIN which other friends have posted above.

How to print a string multiple times?

def repeat_char_rows_cols(char, rows, cols):
    return (char*cols + '\n')*rows

>>> print(repeat_char_rows_cols('@', 4, 2))
@@
@@
@@
@@

Object of class stdClass could not be converted to string - laravel

Try this simple in one line of code:-

$data= json_decode( json_encode($data), true);

Hope it helps :)

How to merge two PDF files into one in Java?

This is a ready to use code, merging four pdf files with itext.jar from http://central.maven.org/maven2/com/itextpdf/itextpdf/5.5.0/itextpdf-5.5.0.jar, more on http://tutorialspointexamples.com/

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * This class is used to merge two or more 
 * existing pdf file using iText jar.
 */
public class PDFMerger {

static void mergePdfFiles(List<InputStream> inputPdfList,
        OutputStream outputStream) throws Exception{
    //Create document and pdfReader objects.
    Document document = new Document();
    List<PdfReader> readers = 
            new ArrayList<PdfReader>();
    int totalPages = 0;

    //Create pdf Iterator object using inputPdfList.
    Iterator<InputStream> pdfIterator = 
            inputPdfList.iterator();

    // Create reader list for the input pdf files.
    while (pdfIterator.hasNext()) {
            InputStream pdf = pdfIterator.next();
            PdfReader pdfReader = new PdfReader(pdf);
            readers.add(pdfReader);
            totalPages = totalPages + pdfReader.getNumberOfPages();
    }

    // Create writer for the outputStream
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);

    //Open document.
    document.open();

    //Contain the pdf data.
    PdfContentByte pageContentByte = writer.getDirectContent();

    PdfImportedPage pdfImportedPage;
    int currentPdfReaderPage = 1;
    Iterator<PdfReader> iteratorPDFReader = readers.iterator();

    // Iterate and process the reader list.
    while (iteratorPDFReader.hasNext()) {
            PdfReader pdfReader = iteratorPDFReader.next();
            //Create page and add content.
            while (currentPdfReaderPage <= pdfReader.getNumberOfPages()) {
                  document.newPage();
                  pdfImportedPage = writer.getImportedPage(
                          pdfReader,currentPdfReaderPage);
                  pageContentByte.addTemplate(pdfImportedPage, 0, 0);
                  currentPdfReaderPage++;
            }
            currentPdfReaderPage = 1;
    }

    //Close document and outputStream.
    outputStream.flush();
    document.close();
    outputStream.close();

    System.out.println("Pdf files merged successfully.");
}

public static void main(String args[]){
    try {
        //Prepare input pdf file list as list of input stream.
        List<InputStream> inputPdfList = new ArrayList<InputStream>();
        inputPdfList.add(new FileInputStream("..\\pdf\\pdf_1.pdf"));
        inputPdfList.add(new FileInputStream("..\\pdf\\pdf_2.pdf"));
        inputPdfList.add(new FileInputStream("..\\pdf\\pdf_3.pdf"));
        inputPdfList.add(new FileInputStream("..\\pdf\\pdf_4.pdf"));


        //Prepare output stream for merged pdf file.
        OutputStream outputStream = 
                new FileOutputStream("..\\pdf\\MergeFile_1234.pdf");

        //call method to merge pdf files.
        mergePdfFiles(inputPdfList, outputStream);     
    } catch (Exception e) {
        e.printStackTrace();
    }
    }
}

How to close the current fragment by using Button like the back button?

From Fragment A, to go to B, replace A with B and use addToBackstack() before commit().

Now From Fragment B, to go to C, first use popBackStackImmediate(), this will bring back A. Now replace A with C, just like the first transaction.

Proper way to return JSON using node or Express

If you're using Express, you can use this:

res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({key:"value"}));

or just this

res.json({key:"value"});

Java method to sum any number of ints

You could do, assuming you have an array with value and array length: arrayVal[i], arrayLength:

int sum = 0;
for (int i = 0; i < arrayLength; i++) {
    sum += arrayVal[i];
}

System.out.println("the sum is" + sum);

I hope this helps.

How to count string occurrence in string?

Try it

<?php 
$str = "33,33,56,89,56,56";
echo substr_count($str, '56');
?>

<script type="text/javascript">
var temp = "33,33,56,89,56,56";
var count = temp.match(/56/g);  
alert(count.length);
</script>

ImportError: No module named 'pygame'

I was having the same trouble and I did

pip install pygame

and that worked for me!

intellij idea - Error: java: invalid source release 1.9

I have had the same problem. There is an answer:

  • 1.CTRL + ALT + SHIFT + S;
    1. Then go to "Modules";
    2. "Dependencies;
    3. Change "Module SDK".

Got it! Now u have Java 9!

I do not understand how execlp() works in Linux

this prototype:

  int execlp(const char *file, const char *arg, ...);

Says that execlp ìs a variable argument function. It takes 2 const char *. The rest of the arguments, if any, are the additional arguments to hand over to program we want to run - also char * - all these are C strings (and the last argument must be a NULL pointer)

So, the file argument is the path name of an executable file to be executed. arg is the string we want to appear as argv[0] in the executable. By convention, argv[0] is just the file name of the executable, normally it's set to the same as file.

The ... are now the additional arguments to give to the executable.

Say you run this from a commandline/shell:

$ ls

That'd be execlp("ls", "ls", (char *)NULL); Or if you run

$ ls -l /

That'd be execlp("ls", "ls", "-l", "/", (char *)NULL);

So on to execlp("/bin/sh", ..., "ls -l /bin/??", ...);

Here you are going to the shell, /bin/sh , and you're giving the shell a command to execute. That command is "ls -l /bin/??". You can run that manually from a commandline/shell:

 $ ls -l /bin/??

Now, how do you run a shell and tell it to execute a command ? You open up the documentation/man page for your shell and read it.

What you want to run is:

$ /bin/sh -c "ls -l /bin/??"

This becomes

  execlp("/bin/sh","/bin/sh", "-c", "ls -l /bin/??", (char *)NULL);

Side note: The /bin/?? is doing pattern matching, this pattern matching is done by the shell, and it expands to all files under /bin/ with 2 characters. If you simply did

  execlp("ls","ls", "-l", "/bin/??", (char *)NULL);

Probably nothing would happen (unless there's a file actually named /bin/??) as there's no shell that interprets and expands /bin/??

How to replace substrings in windows batch file

I have made a function for that, you only call it in a batch program within needing to code more.

The working is basically the same as the others, as it's the best way to do it.
Here's the link where I have that function

Why can a function modify some arguments as perceived by the caller, but not others?

You've got a number of answers already, and I broadly agree with J.F. Sebastian, but you might find this useful as a shortcut:

Any time you see varname =, you're creating a new name binding within the function's scope. Whatever value varname was bound to before is lost within this scope.

Any time you see varname.foo() you're calling a method on varname. The method may alter varname (e.g. list.append). varname (or, rather, the object that varname names) may exist in more than one scope, and since it's the same object, any changes will be visible in all scopes.

[note that the global keyword creates an exception to the first case]

Order of items in classes: Fields, Properties, Constructors, Methods

The closest you're likely to find is "Design Guidelines, Managed code and the .NET Framework" (http://blogs.msdn.com/brada/articles/361363.aspx) by Brad Abrams

Many standards are outlined here. The relevant section is 2.8 I think.

How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?

For Swift 3 and XCode 8, this worked. Follow below steps to achieve this:-

viewDidLoad()
    {
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        var width = UIScreen.main.bounds.width
        layout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
    width = width - 10
    layout.itemSize = CGSize(width: width / 2, height: width / 2)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        collectionView!.collectionViewLayout = layout
    }

The property 'value' does not exist on value of type 'HTMLElement'

A quick fix for this is use [ ] to select the attribute.

function greet(elementId) {
    var inputValue = document.getElementById(elementId)["value"];
    if(inputValue.trim() == "") {
        inputValue = "World";
    }
    document.getElementById("greet").innerText = greeter(inputValue);
}

I just try few methods and find out this solution,
I don't know what's the problem behind your original script.

For reference you may refer to Tomasz Nurkiewicz's post.

Javascript Date: next month

You'll probably find you're setting the date to Feb 31, 2009 (if today is Jan 31) and Javascript automagically rolls that into the early part of March.

Check the day of the month, I'd expect it to be 1, 2 or 3. If it's not the same as before you added a month, roll back by one day until the month changes again.

That way, the day "last day of Jan" becomes "last day of Feb".

EDIT:

Ronald, based on your comments to other answers, you might want to steer clear of edge-case behavior such as "what happens when I try to make Feb 30" or "what happens when I try to make 2009/13/07 (yyyy/mm/dd)" (that last one might still be a problem even for my solution, so you should test it).

Instead, I would explicitly code for the possibilities. Since you don't care about the day of the month (you just want the year and month to be correct for next month), something like this should suffice:

var now = new Date();
if (now.getMonth() == 11) {
    var current = new Date(now.getFullYear() + 1, 0, 1);
} else {
    var current = new Date(now.getFullYear(), now.getMonth() + 1, 1);
}

That gives you Jan 1 the following year for any day in December and the first day of the following month for any other day. More code, I know, but I've long since grown tired of coding tricks for efficiency, preferring readability unless there's a clear requirement to do otherwise.

Replace all elements of Python NumPy Array that are greater than some value

Since you actually want a different array which is arr where arr < 255, and 255 otherwise, this can be done simply:

result = np.minimum(arr, 255)

More generally, for a lower and/or upper bound:

result = np.clip(arr, 0, 255)

If you just want to access the values over 255, or something more complicated, @mtitan8's answer is more general, but np.clip and np.minimum (or np.maximum) are nicer and much faster for your case:

In [292]: timeit np.minimum(a, 255)
100000 loops, best of 3: 19.6 µs per loop

In [293]: %%timeit
   .....: c = np.copy(a)
   .....: c[a>255] = 255
   .....: 
10000 loops, best of 3: 86.6 µs per loop

If you want to do it in-place (i.e., modify arr instead of creating result) you can use the out parameter of np.minimum:

np.minimum(arr, 255, out=arr)

or

np.clip(arr, 0, 255, arr)

(the out= name is optional since the arguments in the same order as the function's definition.)

For in-place modification, the boolean indexing speeds up a lot (without having to make and then modify the copy separately), but is still not as fast as minimum:

In [328]: %%timeit
   .....: a = np.random.randint(0, 300, (100,100))
   .....: np.minimum(a, 255, a)
   .....: 
100000 loops, best of 3: 303 µs per loop

In [329]: %%timeit
   .....: a = np.random.randint(0, 300, (100,100))
   .....: a[a>255] = 255
   .....: 
100000 loops, best of 3: 356 µs per loop

For comparison, if you wanted to restrict your values with a minimum as well as a maximum, without clip you would have to do this twice, with something like

np.minimum(a, 255, a)
np.maximum(a, 0, a)

or,

a[a>255] = 255
a[a<0] = 0

Tensorflow image reading & display

According to the documentation you can decode JPEG/PNG images.

It should be something like this:

import tensorflow as tf

filenames = ['/image_dir/img.jpg']
filename_queue = tf.train.string_input_producer(filenames)

reader = tf.WholeFileReader()
key, value = reader.read(filename_queue)

images = tf.image.decode_jpeg(value, channels=3)

You can find a bit more info here

Random numbers with Math.random() in Java

int i = (int) (10 +Math.random()*11);

this will give you random number between 10 to 20.

the key here is:

a + Math.random()*b

a starting num (10) and ending num is max number (20) - a (10) + 1 (11)

Enjoy!

Align <div> elements side by side

Apply float:left; to both of your divs should make them stand side by side.

Create, read, and erase cookies with jQuery

As I know, there is no direct support, but you can use plain-ol' javascript for that:

// Cookies
function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";               

    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

How to bind Events on Ajax loaded Content?

If your ajax response are containing html form inputs for instance, than this would be great:

$(document).on("change", 'input[type=radio][name=fieldLoadedFromAjax]', function(event) { 
if (this.value == 'Yes') {
  // do something here
} else if (this.value == 'No') {
  // do something else here.
} else {
   console.log('The new input field from an ajax response has this value: '+ this.value);
}

});

Finding median of list in Python

fuction median:

def median(d):
    d=np.sort(d)
    n2=int(len(d)/2)
    r=n2%2
    if (r==0):
        med=d[n2] 
    else:
        med=(d[n2] + data[m+1]) / 2
    return med

Parsing JSON giving "unexpected token o" error

cur_ques_details is already a JS object, you don't need to parse it

Formatting struct timespec

The following will return an ISO8601 and RFC3339-compliant UTC timestamp, including nanoseconds.

It uses strftime(), which works with struct timespec just as well as with struct timeval because all it cares about is the number of seconds, which both provide. Nanoseconds are then appended (careful to pad with zeros!) as well as the UTC suffix 'Z'.

Example output: 2021-01-19T04:50:01.435561072Z

#include <stdio.h>
#include <time.h>
#include <sys/time.h>

int utc_system_timestamp(char[]);

int main(void) {
    char buf[31];
    utc_system_timestamp(buf);
    printf("%s\n", buf);
}

// Allocate exactly 31 bytes for buf
int utc_system_timestamp(char buf[]) {
        const int bufsize = 31;
        struct timespec now;
        struct tm tm;
        int retval = clock_gettime(CLOCK_REALTIME, &now);
        gmtime_r(&now.tv_sec, &tm);
        strftime(buf, bufsize, "%Y-%m-%dT%H:%M:%S.", &tm);
        sprintf(buf, "%s%09luZ", buf, now.tv_nsec);
        return retval;
}

C++ Matrix Class

You could do it that way. The only difference is you'd need to cast the result from malloc.

Rather, you would use a vector, either as a 1D array with computed indexing or an embedded vector. (The former matches your code better.)

For example:

template <typename T> // often, they are templates
struct matrix
{
    // should probably be hidden away, and the class would
    // provide `at` and `operator()` for access
    int col, row;
    std::vector<T> data;

    matrix(int columns, int rows) :
    col(columns), row(rows), 
    data(col * row)
    {}

}

matrix m(4, 4);
m.data[1 + 1 * 4] = /* ... */;

Or:

template <typename T>
struct matrix
{
    int col, row;
    std::vector<std::vector<T> > data;

    matrix(int columns, int rows) :
    col(columns), row(rows), 
    data(col, std::vector(row))
    {}
}

matrix m(4, 4);
m.data[1][1] = /* ... */;

But these are only examples. You'd want to make a full-fledged class; if you want more advice on that, edit your question and clarify you'd like to know the canonical way of implementing matrix classes.

There are pre-existing matrix classes. My favorite is that from boost, UBLAS.

Artificially create a connection timeout error

The following URL always gives a timeout, and combines the best of @Alexander and @Emu's answers above:

http://example.com:81

Using example.com:81 is an improvement on Alexander's answer because example.com is reserved by the DNS standard, so it will always be unreachable, unlike google.com:81, which may change if Google feels like it. Also, because example.com is defined to be unreachable, you won't be flooding Google's servers.

I'd say it's an improvement over @emu's answer because it's a lot easier to remember.

HTML button to NOT submit form

It's recommended not to use the <Button> tag. Use the <Input type='Button' onclick='return false;'> tag instead. (Using the "return false" should indeed not send the form.)

Some reference material

Execute specified function every X seconds

Use System.Windows.Forms.Timer.

private Timer timer1; 
public void InitTimer()
{
    timer1 = new Timer();
    timer1.Tick += new EventHandler(timer1_Tick);
    timer1.Interval = 2000; // in miliseconds
    timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    isonline();
}

You can call InitTimer() in Form1_Load().

Word count from a txt file program

you can do this:

file= open(r'D:\\zzzz\\names2.txt')
file_split=set(file.read().split())
print(len(file_split))

How to correct indentation in IntelliJ

Code ? Reformat Code... (default Ctrl + Alt + L) for the whole file or Code ? Auto-Indent Lines (default Ctrl + Alt + I) for the current line or selection.

You can customise the settings for how code is auto-formatted under File ? Settings ? Editor ? Code Style.


To ensure comments are also indented to the same level as the code, you can simply do as follows:

UI screenshot (example for JavaScript)

RedirectToAction with parameter

The following succeeded with asp.net core 2.1. It may apply elsewhere. The dictionary ControllerBase.ControllerContext.RouteData.Values is directly accessible and writable from within the action method. Perhaps this is the ultimate destination of the data in the other solutions. It also shows where the default routing data comes from.

[Route("/to/{email?}")]
public IActionResult ToAction(string email)
{
    return View("To", email);
}
[Route("/from")]
public IActionResult FromAction()
{
    ControllerContext.RouteData.Values.Add("email", "[email protected]");
    return RedirectToAction(nameof(ToAction));
         // will redirect to /to/[email protected]
}
[Route("/FromAnother/{email?}")]`
public IActionResult FromAnotherAction(string email)
{
    return RedirectToAction(nameof(ToAction));
         // will redirect to /to/<whatever the email param says>
         // no need to specify the route part explicitly
}

Get the number of rows in a HTML table

The following code assumes that your table has the ID 'MyTable'

<script language="JavaScript">
<!--
var oRows = document.getElementById('MyTable').getElementsByTagName('tr');
var iRowCount = oRows.length;

alert('Your table has ' + iRowCount + ' rows.');
//-->
</script>

Answer taken from : http://www.delphifaq.com/faq/f771.shtml, which is the first result on google for the query : "Get the number of rows in a HTML table" ;)

How to filter by object property in angularJS

You could also do this to make it more dynamic.

<input name="filterByPolarity" data-ng-model="text.polarity"/>

Then you ng-repeat will look like this

<div class="tweet" data-ng-repeat="tweet in tweets | filter:text"></div>

This filter will of course only be used to filter by polarity

Difference between object and class in Scala

A class is a definition, a description. It defines a type in terms of methods and composition of other types.

An object is a singleton -- an instance of a class which is guaranteed to be unique. For every object in the code, an anonymous class is created, which inherits from whatever classes you declared object to implement. This class cannot be seen from Scala source code -- though you can get at it through reflection.

There is a relationship between object and class. An object is said to be the companion-object of a class if they share the same name. When this happens, each has access to methods of private visibility in the other. These methods are not automatically imported, though. You either have to import them explicitly, or prefix them with the class/object name.

For example:

class X {
  // class X can see private members of object X
  // Prefix to call
  def m(x: Int) = X.f(x)

  // Import and use
  import X._
  def n(x: Int) = f(x)

  private def o = 2
}

object X {
  private def f(x: Int) = x * x

  // object X can see private members of class X
  def g(x: X) = {
    import x._
    x.o * o // fully specified and imported
   }
}

Spring Resttemplate exception handling

I fixed it by overriding the hasError method from DefaultResponseErrorHandler class:

public class BadRequestSafeRestTemplateErrorHandler extends DefaultResponseErrorHandler
{
    @Override
    protected boolean hasError(HttpStatus statusCode)
    {
        if(statusCode == HttpStatus.BAD_REQUEST)
        {
            return false;
        }
        return statusCode.isError();
    }
}

And you need to set this handler for restemplate bean:

@Bean
    protected RestTemplate restTemplate(RestTemplateBuilder builder)
    {
        return builder.errorHandler(new BadRequestSafeRestTemplateErrorHandler()).build();
    }

Get local IP address

This returns addresses from any interfaces that have gateway addresses and unicast addresses in two separate lists, IPV4 and IPV6.

public static (List<IPAddress> V4, List<IPAddress> V6) GetLocal()
{
    List<IPAddress> foundV4 = new List<IPAddress>();
    List<IPAddress> foundV6 = new List<IPAddress>();

    NetworkInterface.GetAllNetworkInterfaces().ToList().ForEach(ni =>
    {
        if (ni.GetIPProperties().GatewayAddresses.FirstOrDefault() != null)
        {
            ni.GetIPProperties().UnicastAddresses.ToList().ForEach(ua =>
            {
                if (ua.Address.AddressFamily == AddressFamily.InterNetwork) foundV4.Add(ua.Address);
                if (ua.Address.AddressFamily == AddressFamily.InterNetworkV6) foundV6.Add(ua.Address);
            });
        }
    });

    return (foundV4.Distinct().ToList(), foundV6.Distinct().ToList());
}

How to format number of decimal places in wpf using style/template?

You should use the StringFormat on the Binding. You can use either standard string formats, or custom string formats:

<TextBox Text="{Binding Value, StringFormat=N2}" />
<TextBox Text="{Binding Value, StringFormat={}{0:#,#.00}}" />

Note that the StringFormat only works when the target property is of type string. If you are trying to set something like a Content property (typeof(object)), you will need to use a custom StringFormatConverter (like here), and pass your format string as the ConverterParameter.

Edit for updated question

So, if your ViewModel defines the precision, I'd recommend doing this as a MultiBinding, and creating your own IMultiValueConverter. This is pretty annoying in practice, to go from a simple binding to one that needs to be expanded out to a MultiBinding, but if the precision isn't known at compile time, this is pretty much all you can do. Your IMultiValueConverter would need to take the value, and the precision, and output the formatted string. You'd be able to do this using String.Format.

However, for things like a ContentControl, you can much more easily do this with a Style:

<Style TargetType="{x:Type ContentControl}">
    <Setter Property="ContentStringFormat" 
            Value="{Binding Resolution, StringFormat=N{0}}" />
</Style>

Any control that exposes a ContentStringFormat can be used like this. Unfortunately, TextBox doesn't have anything like that.

Is there a good JSP editor for Eclipse?

I followed the advice of Simon Gibbs in this answer and found it worked out fine - if you're in a hurry, the "Web Page Editor (optional)" package from the Eclipse update site does the trick.

For the Eclipse-challenged (me) Help > Install New Software > Work with > Expand Web, XML, and Java EE Development > Select "Web Page Editor (optional)" and "next-through" to completion.

Linux c++ error: undefined reference to 'dlopen'

The topic is quite old, yet I struggled with the same issue today while compiling cegui 0.7.1 (openVibe prerequisite).

What worked for me was to set: LDFLAGS="-Wl,--no-as-needed" in the Makefile.

I've also tried -ldl for LDFLAGS but to no avail.

How to read a file from jar in Java?

Check first your class loader.

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

if (classLoader == null) {
    classLoader = Class.class.getClassLoader();
}

classLoader.getResourceAsStream("xmlFileNameInJarFile.xml");

// xml file location at xxx.jar
// + folder
// + folder
// xmlFileNameInJarFile.xml

mysql after insert trigger which updates another table's column

With your requirements you don't need BEGIN END and IF with unnecessary SELECT in your trigger. So you can simplify it to this

CREATE TRIGGER occupy_trig AFTER INSERT ON occupiedroom 
FOR EACH ROW
  UPDATE BookingRequest
     SET status = 1
   WHERE idRequest = NEW.idRequest;

Angular JS: What is the need of the directive’s link function when we already had directive’s controller with scope?

Why controllers are needed

The difference between link and controller comes into play when you want to nest directives in your DOM and expose API functions from the parent directive to the nested ones.

From the docs:

Best Practice: use controller when you want to expose an API to other directives. Otherwise use link.

Say you want to have two directives my-form and my-text-input and you want my-text-input directive to appear only inside my-form and nowhere else.

In that case, you will say while defining the directive my-text-input that it requires a controller from the parent DOM element using the require argument, like this: require: '^myForm'. Now the controller from the parent element will be injected into the link function as the fourth argument, following $scope, element, attributes. You can call functions on that controller and communicate with the parent directive.

Moreover, if such a controller is not found, an error will be raised.

Why use link at all

There is no real need to use the link function if one is defining the controller since the $scope is available on the controller. Moreover, while defining both link and controller, one does need to be careful about the order of invocation of the two (controller is executed before).

However, in keeping with the Angular way, most DOM manipulation and 2-way binding using $watchers is usually done in the link function while the API for children and $scope manipulation is done in the controller. This is not a hard and fast rule, but doing so will make the code more modular and help in separation of concerns (controller will maintain the directive state and link function will maintain the DOM + outside bindings).

Disable browser cache for entire ASP.NET website

Create a class that inherits from IActionFilter.

public class NoCacheAttribute : ActionFilterAttribute
{  
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
        filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();

        base.OnResultExecuting(filterContext);
    }
}

Then put attributes where needed...

[NoCache]
[HandleError]
public class AccountController : Controller
{
    [NoCache]
    [Authorize]
    public ActionResult ChangePassword()
    {
        return View();
    }
}

SQLAlchemy: What's the difference between flush() and commit()?

commit () records these changes in the database. flush () is always called as part of the commit () (1) call. When you use a Session object to query a database, the query returns results from both the database and the reddened parts of the unrecorded transaction it is performing.

Python - How to concatenate to a string in a for loop?

If you must, this is how you can do it in a for loop:

mylist = ['first', 'second', 'other']
endstring = ''
for s in mylist:
  endstring += s

but you should consider using join():

''.join(mylist)

How to convert a timezone aware string to datetime in Python without dateutil?

There are two issues with the code in the original question: there should not be a : in the timezone and the format string for "timezone as an offset" is lower case %z not upper %Z.

This works for me in Python v3.6

>>> from datetime import datetime
>>> t = datetime.strptime("2012-11-01T04:16:13-0400", "%Y-%m-%dT%H:%M:%S%z")
>>> print(t)
2012-11-01 04:16:13-04:00

Break string into list of characters in Python

a='hello world'
map(lambda x:x, a)

['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

An easy way is using function “map()”.

How do I fix a Git detached head?

git pull origin master

worked for me. It was just about giving remote and branch name explicitly.

Rails has_many with alias name

Give this a shot:

has_many :jobs, foreign_key: "user_id", class_name: "Task"

Note, that :as is used for polymorphic associations.

Removing empty lines in Notepad++

A few of the above expressions and extended expressions did not work for me, but the regular expression "$\n$" did.

Android Transparent TextView?

<TextView android:alpha="0.3" ..., for example.

How to find path of active app.config file?

Depending on the location of your config file System.Reflection.Assembly.GetExecutingAssembly().Location might do what you need.

How to obtain image size using standard Python class (without using external library)?

Found a nice solution in another Stackoverflow post (using only standard libraries + dealing with jpg as well): JohnTESlade answer

And another solution (the quick way) for those who can afford running 'file' command within python, run:

import os
info = os.popen("file foo.jpg").read()
print info

Output:

foo.jpg: JPEG image data...density 28x28, segment length 16, baseline, precision 8, 352x198, frames 3

All you gotta do now is to format the output to capture the dimensions. 352x198 in my case.

make UITableViewCell selectable only while editing

Have you tried setting the selection properties of your tableView like this:

tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES; 

If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath in your UITableView delegate. The documentation states:

Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected. 

You can have this method return nil in cases where you don't want the selection to happen.

Storing integer values as constants in Enum manner in java

You can use ordinal. So PAGE.SIGN_CREATE.ordinal() returns 1.

EDIT:

The only problem with doing this is that if you add, remove or reorder the enum values you will break the system. For many this is not an issue as they will not remove enums and will only add additional values to the end. It is also no worse than integer constants which also require you not to renumber them. However it is best to use a system like:

public enum PAGE{
  SIGN_CREATE0(0), SIGN_CREATE(1) ,HOME_SCREEN(2), REGISTER_SCREEN(3)

  private int id;

  PAGE(int id){
    this.id = id;
  }

  public int getID(){
    return id;
  }

}

You can then use getID. So PAGE.SIGN_CREATE.getID() returns 1.

jQuery serialize does not register checkboxes

I had a similar problem and the following allowed me to collect all form input values and checked/unchecked checkboxes.

var serialized = this.$('#myform input').map(function() {
return { name: this.name, id: this.id, value: this.checked ? "checked" : "false" };
});

adding directory to sys.path /PYTHONPATH

When running a Python script from Powershell under Windows, this should work:

$pathToSourceRoot = "C:/Users/Steve/YourCode"
$env:PYTHONPATH = "$($pathToSourceRoot);$($pathToSourceRoot)/subdirs_if_required"

# Now run the actual script
python your_script.py

Margin between items in recycler view Android

I faced similar issue, with RelativeLayout as the root element for each row in the recyclerview.

To solve the issue, find the xml file that holds each row and make sure that the root element's height is wrap_content NOT match_parent.

Python 3.6 install win32api?

Take a look at this answer: ImportError: no module named win32api

You can use

pip install pypiwin32

Override back button to act like home button

if it helps someone else, I had an activity with 2 layouts that I toggled on and off for visibilty, trying to emulate a kind of page1 > page2 structure. if they were on page 2 and pressed the back button I wanted them to go back to page 1, if they pressed the back button on page 1 it should still work as normal. Its pretty basic but it works

@Override
public void onBackPressed() {
// check if page 2 is open
    RelativeLayout page2layout = (RelativeLayout)findViewById(R.id.page2layout);
    if(page2layout.getVisibility() == View.VISIBLE){
        togglePageLayout(); // my method to toggle the views
        return;
    }else{
        super.onBackPressed(); // allows standard use of backbutton for page 1
    }

}

hope it helps someone, cheers

How to calculate distance between two locations using their longitude and latitude value

Why are you writing the code for calculating the distance by yourself?

Check the api's in Location class

node.js - how to write an array to file

A simple solution is to use writeFile :

require("fs").writeFile(
     somepath,
     arr.map(function(v){ return v.join(', ') }).join('\n'),
     function (err) { console.log(err ? 'Error :'+err : 'ok') }
);

video as site background? HTML 5

I might have a solution for the video as background, stretched to the browser-width or height, (but the video will still preserve the aspect ratio, couldnt find a solution for that yet.):

Put the video right after the body-tag with style="width:100%;". Right afterwords, put a "bodydummy"-tag:

<body>
<video id="bgVideo" autoplay poster="videos/poster.png">
    <source src="videos/test-h264-640x368-highqual-winff.mp4" type="video/mp4"/>
    <source src="videos/test-640x368-webmvp8-miro.webm" type="video/webm"/>
    <source src="videos/test-640x368-theora-miro.ogv" type="video/ogg"/>    
</video>

<img id="bgImg" src="videos/poster.png" />

<!-- This image stretches exactly to the browser width/height and lies behind the video-->

<div id="bodyDummy">

Put all your content inside the bodydummy-div and put the z-indexes correctly in CSS like this:

#bgImg{ 
    position: absolute;
    top: 0;
    left: 0;
    border: 0;
    z-index: 1;
    width: 100%;
    height: 100%;
}

#bgVideo{ 
    position: absolute;
    top: 0;
    left: 0;
    border: 0;
    z-index: 2;
    width: 100%;
    height: 100%;
}

#bodyDummy{ 
    position: absolute;
    top: 0;
    left: 0;
    z-index: 3;
    overflow: auto;
    width: 100%;
    height: 100%;
}

Hope I could help. Let me know when you could find a solution that the video does not maintain the aspect ratio, so it could fill the whole browser window so we do not have to put a bgimage.

Select option padding not working in chrome

Very, VERY simple idea, but you can modify it accordingly. This isn't set up to look good, only to provide the idea. Hope it helps.

CSS:

ul {
    width: 50px;
    height: 20px;
    border: 1px solid black;
    display: block;

}

li {
    padding: 5px 0px;
    width: 50px;
    display: none;

}

HTML:

<ul id="customComboBox">
&nbsp
    <li>Test</li>
    <li>Test 2</li>
    <li>Test 3</li>
</ul>

Script:

$(document).ready(function(){
    $("#customComboBox").click(function(){
        $("li").toggle("slow");
    });
});

DEMO

How to setup virtual environment for Python in VS Code?

I fixed the issue without changing the python path as that did not seem like the right solution for me. The following solution worked for me, hopefully it works for you as well :))

  1. Open cmd in windows / shell in Linux/Mac.
  2. Activate your virtualenv (using source activate / activate.bat / activate.ps1 if using power shell)

    C:\Users\<myUserName>\Videos\myFolder>django-project\Scripts\activate.bat (django-project) C:\Users\<myUserName>\Videos\myFolder>

  3. Navigate to your project directory and open vscode there.

    (django-project) C:\Users\prash\Videos\myFolder\projects>code .

  4. in VS Code, goto File --> Preferences --> Settings (dont worry you dont need to open the json file)

  5. In the setting search bar search for virtual / venv and hit enter. You should find the below in the search bar:

Python: Venv Folders Folders in your home directory to look into for virtual environments (supports pyenv, direnv and virtualenvwrapper by default).

  1. Add item, and then enter the path of the scripts of your virtuanenv which has the activate file in it. For example in my system, it is:

    C:\Users\<myUserName>\Videos\myFolder\django-project\Scripts\

  2. Save it and restart VS Code.

  3. To restart, open cmd again, navigate to your project path and open vs code. (Note that your venv should be activated in cmd before you open vs code from cmd)

Command to open vs code from cmd:

code .

How to setup virtualenv in VS code

Generate full SQL script from EF 5 Code First Migrations

To add to Matt wilson's answer I had a bunch of code-first entity classes but no database as I hadn't taken a backup. So I did the following on my Entity Framework project:

Open Package Manager console in Visual Studio and type the following:

Enable-Migrations

Add-Migration

Give your migration a name such as 'Initial' and then create the migration. Finally type the following:

Update-Database

Update-Database -Script -SourceMigration:0

The final command will create your database tables from your entity classes (provided your entity classes are well formed).

#1071 - Specified key was too long; max key length is 767 bytes

Index Lengths & MySQL / MariaDB


Laravel uses the utf8mb4 character set by default, which includes support for storing "emojis" in the database. If you are running a version of MySQL older than the 5.7.7 release or MariaDB older than the 10.2.2 release, you may need to manually configure the default string length generated by migrations in order for MySQL to create indexes for them. You may configure this by calling the Schema::defaultStringLength method within your AppServiceProvider:

use Illuminate\Support\Facades\Schema;

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    Schema::defaultStringLength(191);
}

Alternatively, you may enable the innodb_large_prefix option for your database. Refer to your database's documentation for instructions on how to properly enable this option.

Reference from blog : https://www.scratchcode.io/specified-key-too-long-error-in-laravel/

Reference from Official laravel documentation : https://laravel.com/docs/5.7/migrations

JavaScript unit test tools for TDD

MochiKit has a testing framework called SimpleTest that seems to have caught on. Here's a blog post from the original author.

function to remove duplicate characters in a string

This is my solution

public static String removeDup(String inputString){
    if (inputString.length()<2) return inputString;
    if (inputString==null) return null;
    char[] inputBuffer=inputString.toCharArray();
    for (int i=0;i<inputBuffer.length;i++){
        for (int j=i+1;j<inputBuffer.length;j++){
            if (inputBuffer[i]==inputBuffer[j]){
                inputBuffer[j]=0;
            }
        }
    }
    String result=new String(inputBuffer);
    return result;
}

Stop mouse event propagation

Adding to the answer from @AndroidUniversity. In a single line you can write it like so:

<component (click)="$event.stopPropagation()"></component>

Can I send a ctrl-C (SIGINT) to an application on Windows?

Based on process id, we can send the signal to process to terminate forcefully or gracefully or any other signal.

List all process :

C:\>tasklist

To kill the process:

C:\>Taskkill /IM firefox.exe /F
or
C:\>Taskkill /PID 26356 /F

Details:

http://tweaks.com/windows/39559/kill-processes-from-command-prompt/

AngularJS + JQuery : How to get dynamic content working in angularjs

You need to call $compile on the HTML string before inserting it into the DOM so that angular gets a chance to perform the binding.

In your fiddle, it would look something like this.

$("#dynamicContent").html(
  $compile(
    "<button ng-click='count = count + 1' ng-init='count=0'>Increment</button><span>count: {{count}} </span>"
  )(scope)
);

Obviously, $compile must be injected into your controller for this to work.

Read more in the $compile documentation.

CSS hover vs. JavaScript mouseover

In Internet Explorer, there must be declared a <!DOCTYPE> for the :hover selector to work on other elements than the <a> element.

fs: how do I locate a parent folder?

i'm running electron app and i can get the parent folder by path.resolve()

parent 1 level:path.resolve(__dirname, '..') + '/'

parent 2 levels:path.resolve(__dirname, '..', '..') + '/'

Image vs Bitmap class

This is a clarification because I have seen things done in code which are honestly confusing - I think the following example might assist others.

As others have said before - Bitmap inherits from the Abstract Image class

Abstract effectively means you cannot create a New() instance of it.

    Image imgBad1 = new Image();        // Bad - won't compile
    Image imgBad2 = new Image(200,200); // Bad - won't compile

But you can do the following:

    Image imgGood;  // Not instantiated object!
    // Now you can do this
    imgGood = new Bitmap(200, 200);

You can now use imgGood as you would the same bitmap object if you had done the following:

    Bitmap bmpGood = new Bitmap(200,200);

The nice thing here is you can draw the imgGood object using a Graphics object

    Graphics gr = default(Graphics);
    gr = Graphics.FromImage(new Bitmap(1000, 1000));
    Rectangle rect = new Rectangle(50, 50, imgGood.Width, imgGood.Height); // where to draw
    gr.DrawImage(imgGood, rect);

Here imgGood can be any Image object - Bitmap, Metafile, or anything else that inherits from Image!

Casting interfaces for deserialization in JSON.NET

Nicholas Westby provided a great solution in a awesome article.

If you want Deserializing JSON to one of many possible classes that implement an interface like that:

public class Person
{
    public IProfession Profession { get; set; }
}

public interface IProfession
{
    string JobTitle { get; }
}

public class Programming : IProfession
{
    public string JobTitle => "Software Developer";
    public string FavoriteLanguage { get; set; }
}

public class Writing : IProfession
{
    public string JobTitle => "Copywriter";
    public string FavoriteWord { get; set; }
}

public class Samples
{
    public static Person GetProgrammer()
    {
        return new Person()
        {
            Profession = new Programming()
            {
                FavoriteLanguage = "C#"
            }
        };
    }
}

You can use a custom JSON converter:

public class ProfessionConverter : JsonConverter
{
    public override bool CanWrite => false;
    public override bool CanRead => true;
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(IProfession);
    }
    public override void WriteJson(JsonWriter writer,
        object value, JsonSerializer serializer)
    {
        throw new InvalidOperationException("Use default serialization.");
    }

    public override object ReadJson(JsonReader reader,
        Type objectType, object existingValue,
        JsonSerializer serializer)
    {
        var jsonObject = JObject.Load(reader);
        var profession = default(IProfession);
        switch (jsonObject["JobTitle"].Value())
        {
            case "Software Developer":
                profession = new Programming();
                break;
            case "Copywriter":
                profession = new Writing();
                break;
        }
        serializer.Populate(jsonObject.CreateReader(), profession);
        return profession;
    }
}

And you will need to decorate the "Profession" property with a JsonConverter attribute to let it know to use your custom converter:

    public class Person
    {
        [JsonConverter(typeof(ProfessionConverter))]
        public IProfession Profession { get; set; }
    }

And then, you can cast your class with an Interface:

Person person = JsonConvert.DeserializeObject<Person>(jsonString);

Best way to "push" into C# array

The is no array.push(newValue) in C#. You don't push to an Array in C#. What we use for this is a List<T>. What you may want to consider (for teaching purpose only) is the ArrayList (no generic and it is a IList, so ...).

static void Main()
{
    // Create an ArrayList and add 3 elements.
    ArrayList list = new ArrayList();
    list.Add("One"); // Add is your push
    list.Add("Two");
    list.Add("Three");
}

self.tableView.reloadData() not working in Swift

All the calls to UI should be asynchronous, anything you change on the UI like updating table or changing text label should be done from main thread. using DispatchQueue.main will add your operation to the queue on the main thread.

Swift 4

DispatchQueue.main.async{
    self.tableView.reloadData()
}

How to dynamically remove items from ListView on a button click?

You can remove item from list view like this: or you can choose on your Button event which item have to be removed

public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_third);
     String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
                "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
                "Linux", "OS/2" };
     liste = new ArrayList<String>();
     Collections.addAll(liste, values);
     adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, liste);
     setListAdapter(adapter);
}
 @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
     liste.remove(position);
     adapter.notifyDataSetChanged();
  }
}

How do I format date and time on ssrs report?

The following is how I do it using Visual Studio 2017 for an RDL targetted for SSRS 2017:

Right-click on the field in the textbox on the design surface and choose Placeholder Properties. Choose the Number panel and click on Date in the Category listbox, then select the formatting you are looking for in the Type listbox.

Check whether a value is a number in JavaScript or jQuery

You've an number of options, depending on how you want to play it:

isNaN(val)

Returns true if val is not a number, false if it is. In your case, this is probably what you need.

isFinite(val)

Returns true if val, when cast to a String, is a number and it is not equal to +/- Infinity

/^\d+$/.test(val)

Returns true if val, when cast to a String, has only digits (probably not what you need).

How can I scale an image in a CSS sprite

transform: scale(); will make original element preserve its size.

I found the best option is to use vw. It's working like a charm:

https://jsfiddle.net/tomekmularczyk/6ebv9Lxw/1/

_x000D_
_x000D_
#div1,_x000D_
#div2,_x000D_
#div3 {_x000D_
  background:url('//www.google.pl/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png') no-repeat;_x000D_
  background-size: 50vw;   _x000D_
  border: 1px solid black;_x000D_
  margin-bottom: 40px;_x000D_
}_x000D_
_x000D_
#div1 {_x000D_
  background-position: 0 0;_x000D_
  width: 12.5vw;_x000D_
  height: 13vw;_x000D_
}_x000D_
#div2 {_x000D_
  background-position: -13vw -4vw;_x000D_
  width: 17.5vw;_x000D_
  height: 9vw;_x000D_
  transform: scale(1.8);_x000D_
}_x000D_
#div3 {_x000D_
  background-position: -30.5vw 0;_x000D_
  width: 19.5vw;_x000D_
  height: 17vw;_x000D_
}
_x000D_
<div id="div1">_x000D_
  </div>_x000D_
  <div id="div2">_x000D_
  </div>_x000D_
  <div id="div3">_x000D_
  </div>
_x000D_
_x000D_
_x000D_

How to use not contains() in xpath?

I need to select every production with a category that doesn't contain "Business"

Although I upvoted @Arran's answer as correct, I would also add this... Strictly interpreted, the OP's specification would be implemented as

//production[category[not(contains(., 'Business'))]]

rather than

//production[not(contains(category, 'Business'))]

The latter selects every production whose first category child doesn't contain "Business". The two XPath expressions will behave differently when a production has no category children, or more than one.

It doesn't make any difference in practice as long as every <production> has exactly one <category> child, as in your short example XML. Whether you can always count on that being true or not, depends on various factors, such as whether you have a schema that enforces that constraint. Personally, I would go for the more robust option, since it doesn't "cost" much... assuming your requirement as stated in the question is really correct (as opposed to e.g. 'select every production that doesn't have a category that contains "Business"').

Android - default value in editText

You can use text property in your xml file for particular Edittext fields. For example :

<EditText
    android:id="@+id/ET_User"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="yourusername"/>

like this all Edittext fields contains text whatever u want,if user wants to change particular Edittext field he remove older text and enter his new text.

In Another way just you get the particular Edittext field id in activity class and set text to that one.

Another way = programmatically

Example:

EditText username=(EditText)findViewById(R.id.ET_User);

username.setText("jack");

Notice: Array to string conversion in

One of reasons why you will get this Notice: Array to string conversion in… is that you are combining group of arrays. Example, sorting out several first and last names.

To echo elements of array properly, you can use the function, implode(separator, array) Example:

implode(' ', $var)

result:

first name[1], last name[1]
first name[2], last name[2]

More examples from W3C.

How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#

A slightly more concise example that builds on top of the other answers here. I leveraged the code generation that is shipped with Visual Studio to remove most of the extra invocation code and replaced it with typed objects instead.

    using System;
    using System.Management;

    namespace Utils
    {
        class NetworkManagement
        {
            /// <summary>
            /// Returns a list of all the network interface class names that are currently enabled in the system
            /// </summary>
            /// <returns>list of nic names</returns>
            public static string[] GetAllNicDescriptions()
            {
                List<string> nics = new List<string>();

                using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
                {
                    using (var networkConfigs = networkConfigMng.GetInstances())
                    {
                        foreach (var config in networkConfigs.Cast<ManagementObject>()
                                                                           .Where(mo => (bool)mo["IPEnabled"])
                                                                           .Select(x=> new NetworkAdapterConfiguration(x)))
                        {
                            nics.Add(config.Description);
                        }
                    }
                }

                return nics.ToArray();
            }

            /// <summary>
            /// Set's the DNS Server of the local machine
            /// </summary>
            /// <param name="nicDescription">The full description of the network interface class</param>
            /// <param name="dnsServers">Comma seperated list of DNS server addresses</param>
            /// <remarks>Requires a reference to the System.Management namespace</remarks>
            public static bool SetNameservers(string nicDescription, string[] dnsServers, bool restart = false)
            {
                using (ManagementClass networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
                {
                    using (ManagementObjectCollection networkConfigs = networkConfigMng.GetInstances())
                    {
                        foreach (ManagementObject mboDNS in networkConfigs.Cast<ManagementObject>().Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription))
                        {
                            // NAC class was generated by opening a developer console and entering:
                            // mgmtclassgen Win32_NetworkAdapterConfiguration -p NetworkAdapterConfiguration.cs
                            // See: http://blog.opennetcf.com/2008/06/24/disableenable-network-connections-under-vista/

                            using (NetworkAdapterConfiguration config = new NetworkAdapterConfiguration(mboDNS))
                            {
                                if (config.SetDNSServerSearchOrder(dnsServers) == 0)
                                {
                                    RestartNetworkAdapter(nicDescription);
                                }
                            }
                        }
                    }
                }

                return false;
            }

            /// <summary>
            /// Restarts a given Network adapter
            /// </summary>
            /// <param name="nicDescription">The full description of the network interface class</param>
            public static void RestartNetworkAdapter(string nicDescription)
            {
                using (ManagementClass networkConfigMng = new ManagementClass("Win32_NetworkAdapter"))
                {
                    using (ManagementObjectCollection networkConfigs = networkConfigMng.GetInstances())
                    {
                        foreach (ManagementObject mboDNS in networkConfigs.Cast<ManagementObject>().Where(mo=> (string)mo["Description"] == nicDescription))
                        {
                            // NA class was generated by opening dev console and entering
                            // mgmtclassgen Win32_NetworkAdapter -p NetworkAdapter.cs
                            using (NetworkAdapter adapter = new NetworkAdapter(mboDNS))
                            {
                                adapter.Disable();
                                adapter.Enable();
                                Thread.Sleep(4000); // Wait a few secs until exiting, this will give the NIC enough time to re-connect
                                return;
                            }
                        }
                    }
                }
            }

            /// <summary>
            /// Get's the DNS Server of the local machine
            /// </summary>
            /// <param name="nicDescription">The full description of the network interface class</param>
            public static string[] GetNameservers(string nicDescription)
            {
                using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
                {
                    using (var networkConfigs = networkConfigMng.GetInstances())
                    {
                        foreach (var config  in networkConfigs.Cast<ManagementObject>()
                                                              .Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription)
                                                              .Select( x => new NetworkAdapterConfiguration(x)))
                        {
                            return config.DNSServerSearchOrder;
                        }
                    }
                }

                return null;
            }

            /// <summary>
            /// Set's a new IP Address and it's Submask of the local machine
            /// </summary>
            /// <param name="nicDescription">The full description of the network interface class</param>
            /// <param name="ipAddresses">The IP Address</param>
            /// <param name="subnetMask">The Submask IP Address</param>
            /// <param name="gateway">The gateway.</param>
            /// <remarks>Requires a reference to the System.Management namespace</remarks>
            public static void SetIP(string nicDescription, string[] ipAddresses, string subnetMask, string gateway)
            {
                using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
                {
                    using (var networkConfigs = networkConfigMng.GetInstances())
                    {
                        foreach (var config in networkConfigs.Cast<ManagementObject>()
                                                                       .Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription)
                                                                       .Select( x=> new NetworkAdapterConfiguration(x)))
                        {
                            // Set the new IP and subnet masks if needed
                            config.EnableStatic(ipAddresses, Array.ConvertAll(ipAddresses, _ => subnetMask));

                            // Set mew gateway if needed
                            if (!String.IsNullOrEmpty(gateway))
                            {
                                config.SetGateways(new[] {gateway}, new ushort[] {1});
                            }
                        }
                    }
                }
            }

        }
    }

Full source: https://github.com/sverrirs/DnsHelper/blob/master/src/DnsHelperUI/NetworkManagement.cs

how to do file upload using jquery serialization

Use FormData object.It works for any type of form

$(document).on("submit", "form", function(event)
{
    event.preventDefault();
    $.ajax({
        url: $(this).attr("action"),
        type: $(this).attr("method"),
        dataType: "JSON",
        data: new FormData(this),
        processData: false,
        contentType: false,
        success: function (data, status)
        {

        },
        error: function (xhr, desc, err)
        {
            

        }
    });        

});

The imported project "C:\Microsoft.CSharp.targets" was not found

For me the issue was that the path of the project contained %20 characters, because git added those instead of spaces when the repository was cloned. Another problem might be if the path to a package is too long.

powerpoint loop a series of animation

Unfortunately you're probably done with the animation and presentation already. In the hopes this answer can help future questioners, however, this blog post has a walkthrough of steps that can loop a single slide as a sort of sub-presentation.

First, click Slide Show > Set Up Show.

Put a checkmark to Loop continuously until 'Esc'.

Click Ok. Now, Click Slide Show > Custom Shows. Click New.

Select the slide you are looping, click Add. Click Ok and Close.

Click on the slide you are looping. Click Slide Show > Slide Transition. Under Advance slide, put a checkmark to Automatically After. This will allow the slide to loop automatically. Do NOT Apply to all slides.

Right click on the thumbnail of the current slide, select Hide Slide.

Now, you will need to insert a new slide just before the slide you are looping. On the new slide, insert an action button. Set the hyperlink to the custom show you have created. Put a checkmark on "Show and Return"

This has worked for me.

List of foreign keys and the tables they reference in Oracle DB

Try this:

select * from all_constraints where r_constraint_name in (select constraint_name 
from all_constraints where table_name='YOUR_TABLE_NAME');

Using AES encryption in C#

Using AES or implementing AES? To use AES, there is the System.Security.Cryptography.RijndaelManaged class.

'Incorrect SET Options' Error When Building Database Project

For me, just setting the compatibility level to higher level works fine. To see C.Level :

select compatibility_level from sys.databases where name = [your_database]

Python Variable Declaration

There's no need to declare new variables in Python. If we're talking about variables in functions or modules, no declaration is needed. Just assign a value to a name where you need it: mymagic = "Magic". Variables in Python can hold values of any type, and you can't restrict that.

Your question specifically asks about classes, objects and instance variables though. The idiomatic way to create instance variables is in the __init__ method and nowhere else — while you could create new instance variables in other methods, or even in unrelated code, it's just a bad idea. It'll make your code hard to reason about or to maintain.

So for example:

class Thing(object):

    def __init__(self, magic):
        self.magic = magic

Easy. Now instances of this class have a magic attribute:

thingo = Thing("More magic")
# thingo.magic is now "More magic"

Creating variables in the namespace of the class itself leads to different behaviour altogether. It is functionally different, and you should only do it if you have a specific reason to. For example:

class Thing(object):

    magic = "Magic"

    def __init__(self):
        pass

Now try:

thingo = Thing()
Thing.magic = 1
# thingo.magic is now 1

Or:

class Thing(object):

    magic = ["More", "magic"]

    def __init__(self):
        pass

thing1 = Thing()
thing2 = Thing()
thing1.magic.append("here")
# thing1.magic AND thing2.magic is now ["More", "magic", "here"]

This is because the namespace of the class itself is different to the namespace of the objects created from it. I'll leave it to you to research that a bit more.

The take-home message is that idiomatic Python is to (a) initialise object attributes in your __init__ method, and (b) document the behaviour of your class as needed. You don't need to go to the trouble of full-blown Sphinx-level documentation for everything you ever write, but at least some comments about whatever details you or someone else might need to pick it up.

error::make_unique is not a member of ‘std’

If you are stuck with c++11, you can get make_unique from abseil-cpp, an open source collection of C++ libraries drawn from Google’s internal codebase.

React Native - Image Require Module using Dynamic Names

I know this is old but I'm going to add this here as I've found this question, whilst searching for a solution. The docs allow for a uri: 'Network Image'

https://facebook.github.io/react-native/docs/images#network-images

For me I got images working dynamically with this

<Image source={{uri: image}} />

MySQL error - #1062 - Duplicate entry ' ' for key 2

Seems like the second column is set as a unique index. If you dont need that remove it and your errors will go away. Possibly you added the index by mistake and thats why you are seeing the errors today and werent seeing them yesterday

Remove empty array elements

The most popular answer on this topic is absolutely INCORRECT.

Consider the following PHP script:

<?php
$arr = array('1', '', '2', '3', '0');
// Incorrect:
print_r(array_filter($arr));
// Correct:
print_r(array_filter($arr, 'strlen'));

Why is this? Because a string containing a single '0' character also evaluates to boolean false, so even though it's not an empty string, it will still get filtered. That would be a bug.

Passing the built-in strlen function as the filtering function will work, because it returns a non-zero integer for a non-empty string, and a zero integer for an empty string. Non-zero integers always evaluate to true when converted to boolean, while zero integers always evaluate to false when converted to boolean.

So, the absolute, definitive, correct answer is:

$arr = array_filter($arr, 'strlen');