Programs & Examples On #Zend rest

Multiple INSERT statements vs. single INSERT with multiple VALUES

Addition: SQL Server 2012 shows some improved performance in this area but doesn't seem to tackle the specific issues noted below. This should apparently be fixed in the next major version after SQL Server 2012!

Your plan shows the single inserts are using parameterised procedures (possibly auto parameterised) so parse/compile time for these should be minimal.

I thought I'd look into this a bit more though so set up a loop (script) and tried adjusting the number of VALUES clauses and recording the compile time.

I then divided the compile time by the number of rows to get the average compile time per clause. The results are below

Graph

Up until 250 VALUES clauses present the compile time / number of clauses has a slight upward trend but nothing too dramatic.

Graph

But then there is a sudden change.

That section of the data is shown below.

+------+----------------+-------------+---------------+---------------+
| Rows | CachedPlanSize | CompileTime | CompileMemory | Duration/Rows |
+------+----------------+-------------+---------------+---------------+
|  245 |            528 |          41 |          2400 | 0.167346939   |
|  246 |            528 |          40 |          2416 | 0.162601626   |
|  247 |            528 |          38 |          2416 | 0.153846154   |
|  248 |            528 |          39 |          2432 | 0.157258065   |
|  249 |            528 |          39 |          2432 | 0.156626506   |
|  250 |            528 |          40 |          2448 | 0.16          |
|  251 |            400 |         273 |          3488 | 1.087649402   |
|  252 |            400 |         274 |          3496 | 1.087301587   |
|  253 |            400 |         282 |          3520 | 1.114624506   |
|  254 |            408 |         279 |          3544 | 1.098425197   |
|  255 |            408 |         290 |          3552 | 1.137254902   |
+------+----------------+-------------+---------------+---------------+

The cached plan size which had been growing linearly suddenly drops but CompileTime increases 7 fold and CompileMemory shoots up. This is the cut off point between the plan being an auto parametrized one (with 1,000 parameters) to a non parametrized one. Thereafter it seems to get linearly less efficient (in terms of number of value clauses processed in a given time).

Not sure why this should be. Presumably when it is compiling a plan for specific literal values it must perform some activity that does not scale linearly (such as sorting).

It doesn't seem to affect the size of the cached query plan when I tried a query consisting entirely of duplicate rows and neither affects the order of the output of the table of the constants (and as you are inserting into a heap time spent sorting would be pointless anyway even if it did).

Moreover if a clustered index is added to the table the plan still shows an explicit sort step so it doesn't seem to be sorting at compile time to avoid a sort at run time.

Plan

I tried to look at this in a debugger but the public symbols for my version of SQL Server 2008 don't seem to be available so instead I had to look at the equivalent UNION ALL construction in SQL Server 2005.

A typical stack trace is below

sqlservr.exe!FastDBCSToUnicode()  + 0xac bytes  
sqlservr.exe!nls_sqlhilo()  + 0x35 bytes    
sqlservr.exe!CXVariant::CmpCompareStr()  + 0x2b bytes   
sqlservr.exe!CXVariantPerformCompare<167,167>::Compare()  + 0x18 bytes  
sqlservr.exe!CXVariant::CmpCompare()  + 0x11f67d bytes  
sqlservr.exe!CConstraintItvl::PcnstrItvlUnion()  + 0xe2 bytes   
sqlservr.exe!CConstraintProp::PcnstrUnion()  + 0x35e bytes  
sqlservr.exe!CLogOp_BaseSetOp::PcnstrDerive()  + 0x11a bytes    
sqlservr.exe!CLogOpArg::PcnstrDeriveHandler()  + 0x18f bytes    
sqlservr.exe!CLogOpArg::DeriveGroupProperties()  + 0xa9 bytes   
sqlservr.exe!COpArg::DeriveNormalizedGroupProperties()  + 0x40 bytes    
sqlservr.exe!COptExpr::DeriveGroupProperties()  + 0x18a bytes   
sqlservr.exe!COptExpr::DeriveGroupProperties()  + 0x146 bytes   
sqlservr.exe!COptExpr::DeriveGroupProperties()  + 0x146 bytes   
sqlservr.exe!COptExpr::DeriveGroupProperties()  + 0x146 bytes   
sqlservr.exe!CQuery::PqoBuild()  + 0x3cb bytes  
sqlservr.exe!CStmtQuery::InitQuery()  + 0x167 bytes 
sqlservr.exe!CStmtDML::InitNormal()  + 0xf0 bytes   
sqlservr.exe!CStmtDML::Init()  + 0x1b bytes 
sqlservr.exe!CCompPlan::FCompileStep()  + 0x176 bytes   
sqlservr.exe!CSQLSource::FCompile()  + 0x741 bytes  
sqlservr.exe!CSQLSource::FCompWrapper()  + 0x922be bytes    
sqlservr.exe!CSQLSource::Transform()  + 0x120431 bytes  
sqlservr.exe!CSQLSource::Compile()  + 0x2ff bytes   

So going off the names in the stack trace it appears to spend a lot of time comparing strings.

This KB article indicates that DeriveNormalizedGroupProperties is associated with what used to be called the normalization stage of query processing

This stage is now called binding or algebrizing and it takes the expression parse tree output from the previous parse stage and outputs an algebrized expression tree (query processor tree) to go forward to optimization (trivial plan optimization in this case) [ref].

I tried one more experiment (Script) which was to re-run the original test but looking at three different cases.

  1. First Name and Last Name Strings of length 10 characters with no duplicates.
  2. First Name and Last Name Strings of length 50 characters with no duplicates.
  3. First Name and Last Name Strings of length 10 characters with all duplicates.

Graph

It can clearly be seen that the longer the strings the worse things get and that conversely the more duplicates the better things get. As previously mentioned duplicates don't affect the cached plan size so I presume that there must be a process of duplicate identification when constructing the algebrized expression tree itself.

Edit

One place where this information is leveraged is shown by @Lieven here

SELECT * 
FROM (VALUES ('Lieven1', 1),
             ('Lieven2', 2),
             ('Lieven3', 3))Test (name, ID)
ORDER BY name, 1/ (ID - ID) 

Because at compile time it can determine that the Name column has no duplicates it skips ordering by the secondary 1/ (ID - ID) expression at run time (the sort in the plan only has one ORDER BY column) and no divide by zero error is raised. If duplicates are added to the table then the sort operator shows two order by columns and the expected error is raised.

Equivalent of SQL ISNULL in LINQ?

Since aa is the set/object that might be null, can you check aa == null ?

(aa / xx might be interchangeable (a typo in the question); the original question talks about xx but only defines aa)

i.e.

select new {
    AssetID = x.AssetID,
    Status = aa == null ? (bool?)null : aa.Online; // a Nullable<bool>
}

or if you want the default to be false (not null):

select new {
    AssetID = x.AssetID,
    Status = aa == null ? false : aa.Online;
}

Update; in response to the downvote, I've investigated more... the fact is, this is the right approach! Here's an example on Northwind:

        using(var ctx = new DataClasses1DataContext())
        {
            ctx.Log = Console.Out;
            var qry = from boss in ctx.Employees
                      join grunt in ctx.Employees
                          on boss.EmployeeID equals grunt.ReportsTo into tree
                      from tmp in tree.DefaultIfEmpty()
                      select new
                             {
                                 ID = boss.EmployeeID,
                                 Name = tmp == null ? "" : tmp.FirstName
                        };
            foreach(var row in qry)
            {
                Console.WriteLine("{0}: {1}", row.ID, row.Name);
            }
        }

And here's the TSQL - pretty much what we want (it isn't ISNULL, but it is close enough):

SELECT [t0].[EmployeeID] AS [ID],
    (CASE
        WHEN [t2].[test] IS NULL THEN CONVERT(NVarChar(10),@p0)
        ELSE [t2].[FirstName]
     END) AS [Name]
FROM [dbo].[Employees] AS [t0]
LEFT OUTER JOIN (
    SELECT 1 AS [test], [t1].[FirstName], [t1].[ReportsTo]
    FROM [dbo].[Employees] AS [t1]
    ) AS [t2] ON ([t0].[EmployeeID]) = [t2].[ReportsTo]
-- @p0: Input NVarChar (Size = 0; Prec = 0; Scale = 0) []
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1

QED?

Could not connect to React Native development server on Android

For me all done as mentioned above still it was not working then I followed below steps and working like charm

Go Window security => Select Firewall and network protection => Turn off private networkenter image description here

Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?'

Installing mysqlclient using anaconda is pretty simple and straight forward.

conda install -c bioconda mysqlclient

and then, install pymysql using pip.

pip install pymysql

happy learning..

how to place last div into right top corner of parent div? (css)

You can simply add a right float to .block2 element and place it in the first position (this is very important).

Here is the code:

<html>
<head>
    <style type="text/css">
        .block1 {
            color: red;
            width: 100px;
            border: 1px solid green;
        }
        .block2 {
            color: blue;
            width: 70px;
            border: 2px solid black;
            position: relative;
            float: right;
        }
    </style>
</head>
<body>
    <div class='block1'>
        <div class='block2'>block2</div>
        <p>text</p>
        <p>text2</p>
    </div>
</body>

Regards...

C# equivalent of the IsNull() function in SQL Server

    public static T IsNull<T>(this T DefaultValue, T InsteadValue)
    {

        object obj="kk";

        if((object) DefaultValue == DBNull.Value)
        {
            obj = null;
        }

        if (obj==null || DefaultValue==null || DefaultValue.ToString()=="")
        {
            return InsteadValue;
        }
        else
        {
            return DefaultValue;
        }

    }

//This method can work with DBNull and null value. This method is question's answer

Adding backslashes without escaping [Python]

Python treats \ in literal string in a special way.
This is so you can type '\n' to mean newline or '\t' to mean tab
Since '\&' doesn't mean anything special to Python, instead of causing an error, the Python lexical analyser implicitly adds the extra \ for you.

Really it is better to use \\& or r'\&' instead of '\&'

The r here means raw string and means that \ isn't treated specially unless it is right before the quote character at the start of the string.

In the interactive console, Python uses repr to display the result, so that is why you see the double '\'. If you print your string or use len(string) you will see that it is really only the 2 characters

Some examples

>>> 'Here\'s a backslash: \\'
"Here's a backslash: \\"
>>> print 'Here\'s a backslash: \\'
Here's a backslash: \
>>> 'Here\'s a backslash: \\. Here\'s a double quote: ".'
'Here\'s a backslash: \\. Here\'s a double quote: ".'
>>> print 'Here\'s a backslash: \\. Here\'s a double quote: ".'
Here's a backslash: \. Here's a double quote ".

To Clarify the point Peter makes in his comment see this link

Unlike Standard C, all unrecognized escape sequences are left in the string unchanged, i.e., the backslash is left in the string. (This behavior is useful when debugging: if an escape sequence is mistyped, the resulting output is more easily recognized as broken.) It is also important to note that the escape sequences marked as “(Unicode only)” in the table above fall into the category of unrecognized escapes for non-Unicode string literals.

How to set selected item of Spinner by value, not by position?

I had the same issue when trying to select the correct item in a spinner populated using a cursorLoader. I retrieved the id of the item I wanted to select first from table 1 and then used a CursorLoader to populate the spinner. In the onLoadFinished I cycled through the cursor populating the spinner's adapter until I found the item that matched the id I already had. Then assigned the row number of the cursor to the spinner's selected position. It would be nice to have a similar function to pass in the id of the value you wish to select in the spinner when populating details on a form containing saved spinner results.

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {  
  adapter.swapCursor(cursor);

  cursor.moveToFirst();

 int row_count = 0;

 int spinner_row = 0;

  while (spinner_row < 0 || row_count < cursor.getCount()){ // loop until end of cursor or the 
                                                             // ID is found 

    int cursorItemID = bCursor.getInt(cursor.getColumnIndexOrThrow(someTable.COLUMN_ID));

    if (knownID==cursorItemID){
    spinner_row  = row_count;  //set the spinner row value to the same value as the cursor row 

    }
cursor.moveToNext();

row_count++;

  }

}

spinner.setSelection(spinner_row ); //set the selected item in the spinner

}

Stylesheet not loaded because of MIME-type

My problem is that I was using webpack and in my HTML CSS link I had a relative path, and anytime I would navigate to a nested page, that would resolve to the wrong path:

<link rel="stylesheet" href='./index.css'>

so the simple solution was to remove the . since mine is a single-page application.

Like this:

<link rel="stylesheet" href='/index.css'>

so it always resolves to /index.css

BULK INSERT with identity (auto-increment) column

I had a similar issue, but I needed to be sure that the order of the ID is aligning to the order in the source file. My solution is using a VIEW for the BULK INSERT:

Keep your table as it is and create this VIEW (select everything except the ID column)

CREATE VIEW [dbo].[VW_Employee]
AS
SELECT [Name], [Address]
FROM [dbo].[Employee];

Your BULK INSERT should then look like:

BULK INSERT [dbo].[VW_Employee] FROM 'path\tempFile.csv ' 
WITH (FIRSTROW = 2,FIELDTERMINATOR = ',' , ROWTERMINATOR = '\n');

How to find SQL Server running port?

In our enterprise I don't have access to MSSQL Server, so I can'r access the system tables.

What works for me is:

  1. capture the network traffic Wireshark (run as Administrator, select Network Interface),while opening connection to server.
  2. Find the ip address with ping
  3. filter with ip.dst == x.x.x.x

The port is shown in the column info in the format src.port -> dst.port

ORA-00907: missing right parenthesis

ORA-00907: missing right parenthesis

This is one of several generic error messages which indicate our code contains one or more syntax errors. Sometimes it may mean we literally have omitted a right bracket; that's easy enough to verify if we're using an editor which has a match bracket capability (most text editors aimed at coders do). But often it means the compiler has come across a keyword out of context. Or perhaps it's a misspelled word, a space instead of an underscore or a missing comma.

Unfortunately the possible reasons why our code won't compile is virtually infinite and the compiler just isn't clever enough to distinguish them. So it hurls a generic, slightly cryptic, message like ORA-00907: missing right parenthesis and leaves it to us to spot the actual bloomer.

The posted script has several syntax errors. First I will discuss the error which triggers that ORA-0097 but you'll need to fix them all.

Foreign key constraints can be declared in line with the referencing column or at the table level after all the columns have been declared. These have different syntaxes; your scripts mix the two and that's why you get the ORA-00907.

In-line declaration doesn't have a comma and doesn't include the referencing column name.

CREATE TABLE historys_T    (
    history_record    VARCHAR2 (8),
    customer_id       VARCHAR2 (8) 
          CONSTRAINT historys_T_FK FOREIGN KEY REFERENCES T_customers ON DELETE CASCADE,
    order_id           VARCHAR2 (10) NOT NULL,
          CONSTRAINT fk_order_id_orders REFERENCES orders ON DELETE CASCADE)

Table level constraints are a separate component, and so do have a comma and do mention the referencing column.

CREATE TABLE historys_T    (
    history_record    VARCHAR2 (8),
    customer_id       VARCHAR2 (8),    
    order_id           VARCHAR2 (10) NOT NULL,
    CONSTRAINT historys_T_FK FOREIGN KEY (customer_id) REFERENCES T_customers ON DELETE CASCADE,   
   CONSTRAINT fk_order_id_orders FOREIGN KEY (order_id) REFERENCES orders ON DELETE CASCADE)

Here is a list of other syntax errors:

  1. The referenced table (and the referenced primary key or unique constraint) must already exist before we can create a foreign key against them. So you cannot create a foreign key for HISTORYS_T before you have created the referenced ORDERS table.
  2. You have misspelled the names of the referenced tables in some of the foreign key clauses (LIBRARY_T and FORMAT_T).
  3. You need to provide an expression in the DEFAULT clause. For DATE columns that is usually the current date, DATE DEFAULT sysdate.

Looking at our own code with a cool eye is a skill we all need to gain to be successful as developers. It really helps to be familiar with Oracle's documentation. A side-by-side comparison of your code and the examples in the SQL Reference would have helped you resolved these syntax errors in considerably less than two days. Find it here (11g) and here (12c).

As well as syntax errors, your scripts contain design mistakes. These are not failures, but bad practice which should not become habits.

  1. You have not named most of your constraints. Oracle will give them a default name but it will be a horrible one, and makes the data dictionary harder to understand. Explicitly naming every constraint helps us navigate the physical database. It also leads to more comprehensible error messages when our SQL trips a constraint violation.
  2. Name your constraints consistently. HISTORY_T has constraints called historys_T_FK and fk_order_id_orders, neither of which is helpful. A useful convention is <child_table>_<parent_table>_fk. So history_customer_fk and history_order_fk respectively.
  3. It can be useful to create the constraints with separate statements. Creating tables then primary keys then foreign keys will avoid the problems with dependency ordering identified above.
  4. You are trying to create cyclic foreign keys between LIBRARY_T and FORMATS. You could do this by creating the constraints in separate statement but don't: you will have problems when inserting rows and even worse problems with deletions. You should reconsider your data model and find a way to model the relationship between the two tables so that one is the parent and the other the child. Or perhaps you need a different kind of relationship, such as an intersection table.
  5. Avoid blank lines in your scripts. Some tools will handle them but some will not. We can configure SQL*Plus to handle them but it's better to avoid the need.
  6. The naming convention of LIBRARY_T is ugly. Try to find a more expressive name which doesn't require a needless suffix to avoid a keyword clash.
  7. T_CUSTOMERS is even uglier, being both inconsistent with your other tables and completely unnecessary, as customers is not a keyword.

Naming things is hard. You wouldn't believe the wrangles I've had about table names over the years. The most important thing is consistency. If I look at a data dictionary and see tables called T_CUSTOMERS and LIBRARY_T my first response would be confusion. Why are these tables named with different conventions? What conceptual difference does this express? So, please, decide on a naming convention and stick to. Make your table names either all singular or all plural. Avoid prefixes and suffixes as much as possible; we already know it's a table, we don't need a T_ or a _TAB.

Calling a function of a module by using its name (a string)

locals()["myfunction"]()

or

globals()["myfunction"]()

locals returns a dictionary with a current local symbol table. globals returns a dictionary with global symbol table.

What is the main difference between Collection and Collections in Java?

Collection is an root interface of Java collection framework. Collections is a utility class which contains static methods. example Collections.sort()

How to get on scroll events?

for angular 4, the working solution was to do inside the component

@HostListener('window:scroll', ['$event']) onScrollEvent($event){
  console.log($event);
  console.log("scrolling");
} 

Dead simple example of using Multiprocessing Queue, Pool and Locking

The best solution for your problem is to utilize a Pool. Using Queues and having a separate "queue feeding" functionality is probably overkill.

Here's a slightly rearranged version of your program, this time with only 2 processes coralled in a Pool. I believe it's the easiest way to go, with minimal changes to original code:

import multiprocessing
import time

data = (
    ['a', '2'], ['b', '4'], ['c', '6'], ['d', '8'],
    ['e', '1'], ['f', '3'], ['g', '5'], ['h', '7']
)

def mp_worker((inputs, the_time)):
    print " Processs %s\tWaiting %s seconds" % (inputs, the_time)
    time.sleep(int(the_time))
    print " Process %s\tDONE" % inputs

def mp_handler():
    p = multiprocessing.Pool(2)
    p.map(mp_worker, data)

if __name__ == '__main__':
    mp_handler()

Note that mp_worker() function now accepts a single argument (a tuple of the two previous arguments) because the map() function chunks up your input data into sublists, each sublist given as a single argument to your worker function.

Output:

Processs a  Waiting 2 seconds
Processs b  Waiting 4 seconds
Process a   DONE
Processs c  Waiting 6 seconds
Process b   DONE
Processs d  Waiting 8 seconds
Process c   DONE
Processs e  Waiting 1 seconds
Process e   DONE
Processs f  Waiting 3 seconds
Process d   DONE
Processs g  Waiting 5 seconds
Process f   DONE
Processs h  Waiting 7 seconds
Process g   DONE
Process h   DONE

Edit as per @Thales comment below:

If you want "a lock for each pool limit" so that your processes run in tandem pairs, ala:

A waiting B waiting | A done , B done | C waiting , D waiting | C done, D done | ...

then change the handler function to launch pools (of 2 processes) for each pair of data:

def mp_handler():
    subdata = zip(data[0::2], data[1::2])
    for task1, task2 in subdata:
        p = multiprocessing.Pool(2)
        p.map(mp_worker, (task1, task2))

Now your output is:

 Processs a Waiting 2 seconds
 Processs b Waiting 4 seconds
 Process a  DONE
 Process b  DONE
 Processs c Waiting 6 seconds
 Processs d Waiting 8 seconds
 Process c  DONE
 Process d  DONE
 Processs e Waiting 1 seconds
 Processs f Waiting 3 seconds
 Process e  DONE
 Process f  DONE
 Processs g Waiting 5 seconds
 Processs h Waiting 7 seconds
 Process g  DONE
 Process h  DONE

How to check if current thread is not main thread

Summarizing the solutions, I think that's the best one:

boolean isUiThread = VERSION.SDK_INT >= VERSION_CODES.M 
    ? Looper.getMainLooper().isCurrentThread()
    : Thread.currentThread() == Looper.getMainLooper().getThread();

And, if you wish to run something on the UI thread, you can use this:

new Handler(Looper.getMainLooper()).post(new Runnable() {
    @Override
    public void run() {
       //this runs on the UI thread
    }
});

Make a link use POST instead of GET

As mentioned in many posts, this is not directly possible, but an easy and successful way is as follows: First, we put a form in the body of our html page, which does not have any buttons for the submit, and also its inputs are hidden. Then we use a javascript function to get the data and ,send the form. One of the advantages of this method is to redirect to other pages, which depends on the server-side code. The code is as follows: and now in anywhere you need an to be in "POST" method:

<script type="text/javascript" language="javascript">
function post_link(data){

    $('#post_form').find('#form_input').val(data);
    $('#post_form').submit();
};
</script>

   <form id="post_form" action="anywhere/you/want/" method="POST">
 {% csrf_token %}
    <input id="form_input" type="hidden" value="" name="form_input">
</form>

<a href="javascript:{}" onclick="javascript:post_link('data');">post link is ready</a>

Why does background-color have no effect on this DIV?

This being a very old question but worth adding that I have just had a similar issue where a background colour on a footer element in my case didn't show. I added a position: relative which worked.

UICollectionView spacing margins

To put space between CollectionItems use this

write this two Line in viewdidload

UICollectionViewFlowLayout *collectionViewLayout = (UICollectionViewFlowLayout*)self.collectionView.collectionViewLayout;
collectionViewLayout.sectionInset = UIEdgeInsetsMake(<CGFloat top>, <CGFloat left>, <CGFloat bottom>, <CGFloat right>)

Html.RenderPartial() syntax with Razor

Html.RenderPartial() is a void method - you can check whether a method is a void method by placing your mouse over the call to RenderPartial in your code and you will see the text (extension) void HtmlHelper.RenderPartial...

Void methods require a semicolon at the end of the calling code.

In the Webforms view engine you would have encased your Html.RenderPartial() call within the bee stings <% %>

like so

<% Html.RenderPartial("Path/to/my/partial/view"); %>

when you are using the Razor view engine the equivalent is

@{Html.RenderPartial("Path/to/my/partial/view");}

Undo a Git merge that hasn't been pushed yet

You can use only two commands to revert a merge or restart by a specific commit:

  1. git reset --hard commitHash (you should use the commit that you want to restart, eg. 44a587491e32eafa1638aca7738)
  2. git push origin HEAD --force (Sending the new local master branch to origin/master)

Good luck and go ahead!

Show popup after page load

Use this below code to display pop-up box on page load:

$(document).ready(function() { 
  var id = '#dialog';
  var maskHeight = $(document).height();
  var maskWidth = $(window).width();
  $('#mask').css({'width':maskWidth,'height':maskHeight}); 
  $('#mask').fadeIn(500); 
  $('#mask').fadeTo("slow",0.9); 
        var winH = $(window).height();
  var winW = $(window).width();
        $(id).css('top',  winH/2-$(id).height()/2);
  $(id).css('left', winW/2-$(id).width()/2);
     $(id).fadeIn(2000);  
     $('.window .close').click(function (e) {
  e.preventDefault();
  $('#mask').hide();
  $('.window').hide();
     });  
     $('#mask').click(function () {
  $(this).hide();
  $('.window').hide();
 });  

});

<div class="maintext">
<h2> Main text goes here...</h2>
</div>
<div id="boxes">
<div style="top: 50%; left: 50%; display: none;" id="dialog" class="window"> 
<div id="san">
<a href="#" class="close agree"><img src="close-icon.png" width="25" style="float:right; margin-right: -25px; margin-top: -20px;"></a>
<img src="san-web-corner.png" width="450">
</div>
</div>
<div style="width: 2478px; font-size: 32pt; color:white; height: 1202px; display: none; opacity: 0.4;" id="mask"></div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js"></script> 

I refereed this code from here Demo

Don't understand why UnboundLocalError occurs (closure)

To modify a global variable inside a function, you must use the global keyword.

When you try to do this without the line

global counter

inside of the definition of increment, a local variable named counter is created so as to keep you from mucking up the counter variable that the whole program may depend on.

Note that you only need to use global when you are modifying the variable; you could read counter from within increment without the need for the global statement.

How to convert JTextField to String and String to JTextField?

how to convert JTextField to string and string to JTextField in java

If you mean how to get and set String from jTextField then you can use following methods:

String str = jTextField.getText() // get string from jtextfield

and

jTextField.setText(str)  // set string to jtextfield
//or
new JTextField(str)     // set string to jtextfield

You should check JavaDoc for JTextField

Filter output in logcat by tagname

Do not depend on ADB shell, just treat it (the adb logcat) a normal linux output and then pip it:

$ adb shell logcat | grep YouTag
# just like: 
$ ps -ef | grep your_proc 

How do I delete NuGet packages that are not referenced by any project in my solution?

I've found a workaround for this.

  1. Enable package restore and automatic checking (Options / Package Manager / General)
  2. Delete entire contents of the packages folder (to Recycle Bin if you're nervous!)
  3. Manage Nuget Packages For Solution
  4. Click the restore button.

NuGet will restore only the packages used in your solution. You end up with a nice, streamlined set of packages.

How can I generate random alphanumeric strings?

Just some performance comparisons of the various answers in this thread:

Methods & Setup

// what's available
public static string possibleChars = "abcdefghijklmnopqrstuvwxyz";
// optimized (?) what's available
public static char[] possibleCharsArray = possibleChars.ToCharArray();
// optimized (precalculated) count
public static int possibleCharsAvailable = possibleChars.Length;
// shared randomization thingy
public static Random random = new Random();


// http://stackoverflow.com/a/1344242/1037948
public string LinqIsTheNewBlack(int num) {
    return new string(
    Enumerable.Repeat(possibleCharsArray, num)
              .Select(s => s[random.Next(s.Length)])
              .ToArray());
}

// http://stackoverflow.com/a/1344258/1037948
public string ForLoop(int num) {
    var result = new char[num];
    while(num-- > 0) {
        result[num] = possibleCharsArray[random.Next(possibleCharsAvailable)];
    }
    return new string(result);
}

public string ForLoopNonOptimized(int num) {
    var result = new char[num];
    while(num-- > 0) {
        result[num] = possibleChars[random.Next(possibleChars.Length)];
    }
    return new string(result);
}

public string Repeat(int num) {
    return new string(new char[num].Select(o => possibleCharsArray[random.Next(possibleCharsAvailable)]).ToArray());
}

// http://stackoverflow.com/a/1518495/1037948
public string GenerateRandomString(int num) {
  var rBytes = new byte[num];
  random.NextBytes(rBytes);
  var rName = new char[num];
  while(num-- > 0)
    rName[num] = possibleCharsArray[rBytes[num] % possibleCharsAvailable];
  return new string(rName);
}

//SecureFastRandom - or SolidSwiftRandom
static string GenerateRandomString(int Length) //Configurable output string length
{
    byte[] rBytes = new byte[Length]; 
    char[] rName = new char[Length];
    SolidSwiftRandom.GetNextBytesWithMax(rBytes, biasZone);
    for (var i = 0; i < Length; i++)
    {
        rName[i] = charSet[rBytes[i] % charSet.Length];
    }
    return new string(rName);
}

Results

Tested in LinqPad. For string size of 10, generates:

  • from Linq = chdgmevhcy [10]
  • from Loop = gtnoaryhxr [10]
  • from Select = rsndbztyby [10]
  • from GenerateRandomString = owyefjjakj [10]
  • from SecureFastRandom = VzougLYHYP [10]
  • from SecureFastRandom-NoCache = oVQXNGmO1S [10]

And the performance numbers tend to vary slightly, very occasionally NonOptimized is actually faster, and sometimes ForLoop and GenerateRandomString switch who's in the lead.

  • LinqIsTheNewBlack (10000x) = 96762 ticks elapsed (9.6762 ms)
  • ForLoop (10000x) = 28970 ticks elapsed (2.897 ms)
  • ForLoopNonOptimized (10000x) = 33336 ticks elapsed (3.3336 ms)
  • Repeat (10000x) = 78547 ticks elapsed (7.8547 ms)
  • GenerateRandomString (10000x) = 27416 ticks elapsed (2.7416 ms)
  • SecureFastRandom (10000x) = 13176 ticks elapsed (5ms) lowest [Different machine]
  • SecureFastRandom-NoCache (10000x) = 39541 ticks elapsed (17ms) lowest [Different machine]

Evaluating a mathematical expression in a string

[I know this is an old question, but it is worth pointing out new useful solutions as they pop up]

Since python3.6, this capability is now built into the language, coined "f-strings".

See: PEP 498 -- Literal String Interpolation

For example (note the f prefix):

f'{2**4}'
=> '16'

XML string to XML document

Depending on what document type you want you can use XmlDocument.LoadXml or XDocument.Load.

Bash ignoring error for a particular command

Just add || true after the command where you want to ignore the error.

How to resize html canvas element?

Here's my effort to give a more complete answer (building on @john's answer).

The initial issue I encountered was changing the width and height of a canvas node (using styles), resulted in the contents just being "zoomed" or "shrunk." This was not the desired effect.

So, say you want to draw two rectangles of arbitrary size in a canvas that is 100px by 100px.

<canvas width="100" height="100"></canvas>

To ensure that the rectangles will not exceed the size of the canvas and therefore not be visible, you need to ensure that the canvas is big enough.

var $canvas = $('canvas'),
    oldCanvas,
    context = $canvas[0].getContext('2d');

function drawRects(x, y, width, height)
{
  if (($canvas.width() < x+width) || $canvas.height() < y+height)
  {
    oldCanvas = $canvas[0].toDataURL("image/png")
    $canvas[0].width = x+width;
    $canvas[0].height = y+height;

    var img = new Image();
    img.src = oldCanvas;
    img.onload = function (){
      context.drawImage(img, 0, 0);
    };
  }
  context.strokeRect(x, y, width, height);
}


drawRects(5,5, 10, 10);
drawRects(15,15, 20, 20);
drawRects(35,35, 40, 40);
drawRects(75, 75, 80, 80);

Finally, here's the jsfiddle for this: http://jsfiddle.net/Rka6D/4/ .

Is there any quick way to get the last two characters in a string?

String value = "somestring";
String lastTwo = null;
if (value != null && value.length() >= 2) {  
    lastTwo = value.substring(value.length() - 2);
}

Python reshape list to ndim array

You can specify the interpretation order of the axes using the order parameter:

np.reshape(arr, (2, -1), order='F')

Bulk Insert into Oracle database: Which is better: FOR Cursor loop or a simple Select?

I would recommend the Select option because cursors take longer.
Also using the Select is much easier to understand for anyone who has to modify your query

Cross origin requests are only supported for HTTP but it's not cross-domain

For all python users:

Simply go to your destination folder in the terminal.

cd projectFoder

then start HTTP server For Python3+:

python -m http.server 8000

Serving HTTP on :: port 8000 (http://[::]:8000/) ...

go to your link: http://0.0.0.0:8000/

Enjoy :)

How to drop rows of Pandas DataFrame whose value in a certain column is NaN

Don't drop, just take the rows where EPS is not NA:

df = df[df['EPS'].notna()]

Delete item from array and shrink array

You can always expand an array just by increment the size of it while creating an array or you can also change the size after creating, but to shrink or delete elements. The alternate solution without creating a new array, possibly is:

package sample;

public class Delete {
    int i;
    int h=0;
    int n=10;
    int[] a;
    public Delete()
    {
    a = new int[10];
    a[0]=-1; 
    a[1]=-1; 
    a[2]=-1;
    a[3]=10;
    a[4]=20;
    a[5]=30;
    a[6]=40;
    a[7]=50;
    a[8]=60;
    a[9]=70;
    }
    public void shrinkArray()
    {
    for(i=0;i<n;i++)
            {
                if(a[i]==-1)
                    h++;
                else 
                    break;
            }
            while(h>0)
                {
                    for(i=h;i<n;i++)
                    {
                        a[i-1]=a[i];
                    }
                    h--;
                    n--;
                }
            System.out.println(n);
    }
    public void display()
    {
        for(i=0;i<n;i++)
        {
            System.out.println(a[i]);
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Delete obj = new Delete();
        obj.shrinkArray();
        obj.display();

    }

}

Please comment for any mistakes!!

what is the difference between json and xml

The fundamental difference, which no other answer seems to have mentioned, is that XML is a markup language (as it actually says in its name), whereas JSON is a way of representing objects (as also noted in its name).

A markup language is a way of adding extra information to free-flowing plain text, e.g

Here is some text.

With XML (using a certain element vocabulary) you can put:

<Document>
    <Paragraph Align="Center">
        Here <Bold>is</Bold> some text.
    </Paragraph>
</Document>

This is what makes markup languages so useful for representing documents.

An object notation like JSON is not as flexible. But this is usually a good thing. When you're representing objects, you simply don't need the extra flexibility. To represent the above example in JSON, you'd actually have to solve some problems manually that XML solves for you.

{
    "Paragraphs": [
        {
            "align": "center",
            "content": [
                "Here ", {
                    "style" : "bold",
                    "content": [ "is" ]
                },
                " some text."
            ]
        }
    ]
}

It's not as nice as the XML, and the reason is that we're trying to do markup with an object notation. So we have to invent a way to scatter snippets of plain text around our objects, using "content" arrays that can hold a mixture of strings and nested objects.

On the other hand, if you have typical a hierarchy of objects and you want to represent them in a stream, JSON is better suited to this task than HTML.

{
    "firstName": "Homer",
    "lastName": "Simpson",
    "relatives": [ "Grandpa", "Marge", "The Boy", "Lisa", "I think that's all of them" ]
} 

Here's the logically equivalent XML:

<Person>
    <FirstName>Homer</FirstName>
    <LastName>Simpsons</LastName>
    <Relatives>
        <Relative>Grandpa</Relative>
        <Relative>Marge</Relative>
        <Relative>The Boy</Relative>
        <Relative>Lisa</Relative>
        <Relative>I think that's all of them</Relative>
    </Relatives>
</Person>

JSON looks more like the data structures we declare in programming languages. Also it has less redundant repetition of names.

But most importantly of all, it has a defined way of distinguishing between a "record" (items unordered, identified by names) and a "list" (items ordered, identified by position). An object notation is practically useless without such a distinction. And XML has no such distinction! In my XML example <Person> is a record and <Relatives> is a list, but they are not identified as such by the syntax.

Instead, XML has "elements" versus "attributes". This looks like the same kind of distinction, but it's not, because attributes can only have string values. They cannot be nested objects. So I couldn't have applied this idea to <Person>, because I shouldn't have to turn <Relatives> into a single string.

By using an external schema, or extra user-defined attributes, you can formalise a distinction between lists and records in XML. The advantage of JSON is that the low-level syntax has that distinction built into it, so it's very succinct and universal. This means that JSON is more "self describing" by default, which is an important goal of both formats.

So JSON should be the first choice for object notation, where XML's sweet spot is document markup.

Unfortunately for XML, we already have HTML as the world's number one rich text markup language. An attempt was made to reformulate HTML in terms of XML, but there isn't much advantage in this.

So XML should (in my opinion) have been a pretty limited niche technology, best suited only for inventing your own rich text markup languages if you don't want to use HTML for some reason. The problem was that in 1998 there was still a lot of hype about the Web, and XML became popular due to its superficial resemblance to HTML. It was a strange design choice to try to apply to hierarchical data a syntax actually designed for convenient markup.

Right Align button in horizontal LinearLayout

Single LinearLayout solution. Only adding a simple spacing view:
(No-one seemed to have mentioned this one, only more complicated multi-layout solutions.)

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_marginTop="35dp">

    <TextView
        android:id="@+id/lblExpenseCancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/cancel"
        android:textColor="#404040"
        android:layout_marginLeft="10dp"
        android:textSize="20sp"
        android:layout_marginTop="9dp" />

    <!-------------------------  ADDED SPACER VIEW -------------------->
    <View
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="1"
        />
    <!------------------------- /ADDED SPACER VIEW -------------------->

    <Button
        android:id="@+id/btnAddExpense"
        android:layout_width="wrap_content"
        android:layout_height="45dp"
        android:background="@drawable/stitch_button"
        android:layout_marginLeft="10dp"
        android:text="@string/add"
        android:layout_gravity="right"
        android:layout_marginRight="15dp" />

</LinearLayout>

Note the "highlighted" View, I didn't modify anything else. Height=0 makes sure it's not visible. Width=0 is because the width is determined by the LinearLayout based on weight=1. This means that the spacer view will stretch as much as possible in the direction (orientation) of the LinearLayout.

Note that you should use android.widget.Space or android.support.v4.widget.Space instead of View if your API level and/or dependencies allow it. Space achieves the job in a cheaper way, because it only measures and doesn't try to draw anything like View does; it's also more expressive conveying the intention.

How to edit my Excel dropdown list?

The answers above will work for changing the values.

If you want to change the number of cells in your list (e.g. I have a list called 'revisions' which has 4 items, I now need 7 items) you will find that you can't simply select your list and amend it on the sheet, So:

go to your 'Formulas' tab

choose "Name Manager"

a pop up box will show what is available for editing. Your list should be in it. Select your list and edit the range.

CSS image overlay with color and transparency

something like this? http://codepen.io/Nunotmp/pen/wKjvB

You can add an empty div and use absolute positioning.

How do I make a simple crawler in PHP?

Its worth remembering that when crawling external links (I do appreciate the OP relates to a users own page) you should be aware of robots.txt. I have found the following which will hopefully help http://www.the-art-of-web.com/php/parse-robots/.

Easy way to convert a unicode list to a list containing python strings?

how about:

def fix_unicode(data):
    if isinstance(data, unicode):
        return data.encode('utf-8')
    elif isinstance(data, dict):
        data = dict((fix_unicode(k), fix_unicode(data[k])) for k in data)
    elif isinstance(data, list):
        for i in xrange(0, len(data)):
            data[i] = fix_unicode(data[i])
    return data

Floating point vs integer calculations on modern hardware

Alas, I can only give you an "it depends" answer...

From my experience, there are many, many variables to performance...especially between integer & floating point math. It varies strongly from processor to processor (even within the same family such as x86) because different processors have different "pipeline" lengths. Also, some operations are generally very simple (such as addition) and have an accelerated route through the processor, and others (such as division) take much, much longer.

The other big variable is where the data reside. If you only have a few values to add, then all of the data can reside in cache, where they can be quickly sent to the CPU. A very, very slow floating point operation that already has the data in cache will be many times faster than an integer operation where an integer needs to be copied from system memory.

I assume that you are asking this question because you are working on a performance critical application. If you are developing for the x86 architecture, and you need extra performance, you might want to look into using the SSE extensions. This can greatly speed up single-precision floating point arithmetic, as the same operation can be performed on multiple data at once, plus there is a separate* bank of registers for the SSE operations. (I noticed in your second example you used "float" instead of "double", making me think you are using single-precision math).

*Note: Using the old MMX instructions would actually slow down programs, because those old instructions actually used the same registers as the FPU does, making it impossible to use both the FPU and MMX at the same time.

How to install a PHP IDE plugin for Eclipse directly from the Eclipse environment?

Easiest Way To install PDT

  1. Run eclipse
  2. Click on "Help", "Install New Software"
  3. “Choose all available sites”, in search box type "php"(takes a while to load)
  4. => “programming languages” => "PHP Development Tools", => PhP Development Tools (PDT) SDK Feature.
  5. Restart eclipse
  6. File new => other => php .
  7. Should be able to follow from their

npm throws error without sudo

I set my user account as the owner of the /usr/local directory, so that can just issue normal commands in there.

sudo chown -R $USER /usr/local

Reference: http://howtonode.org/introduction-to-npm

Tomcat - maxThreads vs maxConnections

From Tomcat documentation, For blocking I/O (BIO), the default value of maxConnections is the value of maxThreads unless Executor (thread pool) is used in which case, the value of 'maxThreads' from Executor will be used instead. For Non-blocking IO, it doesn't seem to be dependent on maxThreads.

Comparing arrays in C#

"Why do i get that error?" - probably, you don't have "using System.Collections;" at the top of the file - only "using System.Collections.Generic;" - however, generics are probably safer - see below:

static bool ArraysEqual<T>(T[] a1, T[] a2)
{
    if (ReferenceEquals(a1,a2))
        return true;

    if (a1 == null || a2 == null)
        return false;

    if (a1.Length != a2.Length)
        return false;

    EqualityComparer<T> comparer = EqualityComparer<T>.Default;
    for (int i = 0; i < a1.Length; i++)
    {
        if (!comparer.Equals(a1[i], a2[i])) return false;
    }
    return true;
}

Dynamically Dimensioning A VBA Array?

You need to use a constant.

CONST NumberOfZombies = 20000
Dim Zombies(NumberOfZombies) As Zombies

or if you want to use a variable you have to do it this way:

Dim NumberOfZombies As Integer
NumberOfZombies = 20000

Dim Zombies() As Zombies

ReDim Zombies(NumberOfZombies)

How do I specify row heights in CSS Grid layout?

One of the Related posts gave me the (simple) answer.

Apparently the auto value on the grid-template-rows property does exactly what I was looking for.

.grid {
    display:grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
    grid-gap:10px;
    height: calc(100vh - 10px);
}

Get unique values from a list in python

I am surprised that nobody so far has given a direct order-preserving answer:

def unique(sequence):
    """Generate unique items from sequence in the order of first occurrence."""
    seen = set()
    for value in sequence:
        if value in seen:
            continue

        seen.add(value)

        yield value

It will generate the values so it works with more than just lists, e.g. unique(range(10)). To get a list, just call list(unique(sequence)), like this:

>>> list(unique([u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']))
[u'nowplaying', u'PBS', u'job', u'debate', u'thenandnow']

It has the requirement that each item is hashable and not just comparable, but most stuff in Python is and it is O(n) and not O(n^2), so will work just fine with a long list.

How can I zoom an HTML element in Firefox and Opera?

For me this works to counter the difference between zoom and scale transform, adjust for the intended origin desired:

zoom: 0.5;
-ms-zoom: 0.5;
-webkit-zoom: 0.5;
-moz-transform:  scale(0.5,0.5);
-moz-transform-origin: left center;

How can I change eclipse's Internal Browser from IE to Firefox on Windows XP?

I like the Aptana Browser Preview windo for this.

You can get it from their update site: http://download.aptana.org/tools/studio/plugin/update/studio/

After you install the Aptana plugin, open an Aptana project and there should be an option under help to install aptana features. under other you will find a Firefox/XUL browser. There may be a more direct way to install the XUL plugin, but the above procedure works.

Updating and committing only a file's permissions using git version control

By default, git will update execute file permissions if you change them. It will not change or track any other permissions.

If you don't see any changes when modifying execute permission, you probably have a configuration in git which ignore file mode.

Look into your project, in the .git folder for the config file and you should see something like this:

[core]
    filemode = false

You can either change it to true in your favorite text editor, or run:

git config core.filemode true

Then, you should be able to commit normally your files. It will only commit the permission changes.

jQuery on window resize

Give your anonymous function a name, then:

$(window).on("resize", doResize);

http://api.jquery.com/category/events/

What is output buffering?

As name suggest here memory buffer used to manage how the output of script appears.

Here is one very good tutorial for the topic

Styling JQuery UI Autocomplete

Bootstrap styling for jQuery UI Autocomplete

    .ui-autocomplete {
    position: absolute;
    top: 100%;
    left: 0;
    z-index: 1000;
    float: left;
    display: none;
    min-width: 160px;   
    padding: 4px 0;
    margin: 0 0 10px 25px;
    list-style: none;
    background-color: #ffffff;
    border-color: #ccc;
    border-color: rgba(0, 0, 0, 0.2);
    border-style: solid;
    border-width: 1px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    -webkit-background-clip: padding-box;
    -moz-background-clip: padding;
    background-clip: padding-box;
    *border-right-width: 2px;
    *border-bottom-width: 2px;
}

.ui-menu-item > a.ui-corner-all {
    display: block;
    padding: 3px 15px;
    clear: both;
    font-weight: normal;
    line-height: 18px;
    color: #555555;
    white-space: nowrap;
    text-decoration: none;
}

.ui-state-hover, .ui-state-active {
    color: #ffffff;
    text-decoration: none;
    background-color: #0088cc;
    border-radius: 0px;
    -webkit-border-radius: 0px;
    -moz-border-radius: 0px;
    background-image: none;
}

Flexbox and Internet Explorer 11 (display:flex in <html>?)

Sometimes it's as simple as adding: '-ms-' in front of the style Like -ms-flex-flow: row wrap; to get it to work also.

No ConcurrentList<T> in .Net 4.0?

System.Collections.Generic.List<t> is already thread safe for multiple readers. Trying to make it thread safe for multiple writers wouldn't make sense. (For reasons Henk and Stephen already mentioned)

How can I get the day of a specific date with PHP

$date = strtotime('2016-2-3');
$date = date('l', $date);
var_dump($date)

(i added format 'l' so it will return full name of day)

How to remove all .svn directories from my application directories

Try this:

find . -name .svn -exec rm -v {} \;

Read more about the find command at developerWorks.

multiple conditions for filter in spark data frames

You can try, (filtering with 1 object like a list or a set of values)

ds = ds.filter(functions.col(COL_NAME).isin(myList));

or as @Tony Fraser suggested, you can try, (with a Seq of objects)

ds = ds.filter(functions.col(COL_NAME).isin(mySeq));

All the answers are correct but most of them do not represent a good coding style. Also, you should always consider the variable length of arguments for the future, even though they are static at a certain point in time.

How do I iterate through table rows and cells in JavaScript?

Better solution: use Javascript's native Array.from() and to convert HTMLCollection object to an array, after which you can use standard array functions.

var t = document.getElementById('mytab1');
if(t) {
    Array.from(t.rows).forEach((tr, row_ind) => {
        Array.from(tr.cells).forEach((cell, col_ind) => {
            console.log('Value at row/col [' + row_ind + ',' + col_ind + '] = ' + cell.textContent);
        });
    });
}

You could also reference tr.rowIndex and cell.colIndex instead of using row_ind and col_ind.

I much prefer this approach over the top 2 highest-voted answers because it does not clutter your code with global variables i, j, row and col, and therefore it delivers clean, modular code that will not have any side effects (or raise lint / compiler warnings)... without other libraries (e.g. jquery).

If you require this to run in an old version (pre-ES2015) of Javascript, Array.from can be polyfilled.

Determine the size of an InputStream

you can get the size of InputStream using getBytes(inputStream) of Utils.java check this following link

Get Bytes from Inputstream

Comparing two strings in C?

You are currently comparing the addresses of the two strings.

Use strcmp to compare the values of two char arrays

 if (strcmp(namet2, nameIt2) != 0)

What is {this.props.children} and when you should use it?

What even is ‘children’?

The React docs say that you can use props.children on components that represent ‘generic boxes’ and that don’t know their children ahead of time. For me, that didn’t really clear things up. I’m sure for some, that definition makes perfect sense but it didn’t for me.

My simple explanation of what this.props.children does is that it is used to display whatever you include between the opening and closing tags when invoking a component.

A simple example:

Here’s an example of a stateless function that is used to create a component. Again, since this is a function, there is no this keyword so just use props.children

const Picture = (props) => {
  return (
    <div>
      <img src={props.src}/>
      {props.children}
    </div>
  )
}

This component contains an <img> that is receiving some props and then it is displaying {props.children}.

Whenever this component is invoked {props.children} will also be displayed and this is just a reference to what is between the opening and closing tags of the component.

//App.js
render () {
  return (
    <div className='container'>
      <Picture key={picture.id} src={picture.src}>
          //what is placed here is passed as props.children  
      </Picture>
    </div>
  )
}

Instead of invoking the component with a self-closing tag <Picture /> if you invoke it will full opening and closing tags <Picture> </Picture> you can then place more code between it.

This de-couples the <Picture> component from its content and makes it more reusable.

Reference: A quick intro to React’s props.children

<Django object > is not JSON serializable

The easiest way is to use a JsonResponse.

For a queryset, you should pass a list of the the values for that queryset, like so:

from django.http import JsonResponse

queryset = YourModel.objects.filter(some__filter="some value").values()
return JsonResponse({"models_to_return": list(queryset)})

Generate random numbers using C++11 random library

I red all the stuff above, about 40 other pages with c++ in it like this and watched the video from Stephan T. Lavavej "STL" and still wasn't sure how random numbers works in praxis so I took a full Sunday to figure out what its all about and how it works and can be used.

In my opinion STL is right about "not using srand anymore" and he explained it well in the video 2. He also recommend to use:

a) void random_device_uniform() -- for encrypted generation but slower (from my example)

b) the examples with mt19937 -- faster, ability to create seeds, not encrypted


I pulled out all claimed c++11 books I have access to and found f.e. that german Authors like Breymann (2015) still use a clone of

srand( time( 0 ) );
srand( static_cast<unsigned int>(time(nullptr))); or
srand( static_cast<unsigned int>(time(NULL))); or

just with <random> instead of <time> and <cstdlib> #includings - so be careful to learn just from one book :).

Meaning - that shouldn't be used since c++11 because:

Programs often need a source of random numbers. Prior to the new standard, both C and C++ relied on a simple C library function named rand. That function produces pseudorandom integers that are uniformly distributed in the range from 0 to a system- dependent maximum value that is at least 32767. The rand function has several problems: Many, if not most, programs need random numbers in a different range from the one produced by rand. Some applications require random floating-point numbers. Some programs need numbers that reflect a nonuniform distribution. Programmers often introduce nonrandomness when they try to transform the range, type, or distribution of the numbers generated by rand. (quote from Lippmans C++ primer fifth edition 2012)


I finally found a the best explaination out of 20 books in Bjarne Stroustrups newer ones - and he should know his stuff - in "A tour of C++ 2019", "Programming Principles and Practice Using C++ 2016" and "The C++ Programming Language 4th edition 2014" and also some examples in "Lippmans C++ primer fifth edition 2012":

And it is really simple because a random number generator consists of two parts: (1) an engine that produces a sequence of random or pseudo-random values. (2) a distribution that maps those values into a mathematical distribution in a range.


Despite the opinion of Microsofts STL guy, Bjarne Stroustrups writes:

In , the standard library provides random number engines and distributions (§24.7). By default use the default_random_engine , which is chosen for wide applicability and low cost.

The void die_roll() Example is from Bjarne Stroustrups - good idea generating engine and distribution with using (more bout that here).


To be able to make practical use of the random number generators provided by the standard library in <random> here some executable code with different examples reduced to the least necessary that hopefully safe time and money for you guys:

    #include <random>     //random engine, random distribution
    #include <iostream>   //cout
    #include <functional> //to use bind

    using namespace std;


    void space() //for visibility reasons if you execute the stuff
    {
       cout << "\n" << endl;
       for (int i = 0; i < 20; ++i)
       cout << "###";
       cout << "\n" << endl;
    }

    void uniform_default()
    {
    // uniformly distributed from 0 to 6 inclusive
        uniform_int_distribution<size_t> u (0, 6);
        default_random_engine e;  // generates unsigned random integers

    for (size_t i = 0; i < 10; ++i)
        // u uses e as a source of numbers
        // each call returns a uniformly distributed value in the specified range
        cout << u(e) << " ";
    }

    void random_device_uniform()
    {
         space();
         cout << "random device & uniform_int_distribution" << endl;

         random_device engn;
         uniform_int_distribution<size_t> dist(1, 6);

         for (int i=0; i<10; ++i)
         cout << dist(engn) << ' ';
    }

    void die_roll()
    {
        space();
        cout << "default_random_engine and Uniform_int_distribution" << endl;

    using my_engine = default_random_engine;
    using my_distribution = uniform_int_distribution<size_t>;

        my_engine rd {};
        my_distribution one_to_six {1, 6};

        auto die = bind(one_to_six,rd); // the default engine    for (int i = 0; i<10; ++i)

        for (int i = 0; i <10; ++i)
        cout << die() << ' ';

    }


    void uniform_default_int()
    {
       space();
       cout << "uniform default int" << endl;

       default_random_engine engn;
       uniform_int_distribution<size_t> dist(1, 6);

        for (int i = 0; i<10; ++i)
        cout << dist(engn) << ' ';
    }

    void mersenne_twister_engine_seed()
    {
        space();
        cout << "mersenne twister engine with seed 1234" << endl;

        //mt19937 dist (1234);  //for 32 bit systems
        mt19937_64 dist (1234); //for 64 bit systems

        for (int i = 0; i<10; ++i)
        cout << dist() << ' ';
    }


    void random_seed_mt19937_2()
    {
        space();
        cout << "mersenne twister split up in two with seed 1234" << endl;

        mt19937 dist(1234);
        mt19937 engn(dist);

        for (int i = 0; i < 10; ++i)
        cout << dist() << ' ';

        cout << endl;

        for (int j = 0; j < 10; ++j)
        cout << engn() << ' ';
    }



    int main()
    {
            uniform_default(); 
            random_device_uniform();
            die_roll();
            random_device_uniform();
            mersenne_twister_engine_seed();
            random_seed_mt19937_2();
        return 0;
    }

I think that adds it all up and like I said, it took me a bunch of reading and time to destill it to that examples - if you have further stuff about number generation I am happy to hear about that via pm or in the comment section and will add it if necessary or edit this post. Bool

How to return values in javascript

I would prefer a callback solution: Working fiddle here: http://jsfiddle.net/canCu/

function myFunction(value1,value2,value3, callback) {

    value2 = 'somevalue2'; //to return
    value3 = 'somevalue3'; //to return

    callback( value2, value3 );

}

var value1 = 1;
var value2 = 2;
var value3 = 3;

myFunction(value1,value2,value3, function(value2, value3){
    if (value2 && value3) {
        //Do some stuff
        alert( value2 + '-' + value3 );
    }    
});

Opening the Settings app from another app

Seems like you can use the prefs:<area> URL to open the settings and go to specific areas. Apple could change these and break your app so always check if you can open them first.

From this article they have listed some of them for iOS 13.1:

Settings URLs

iCloud

  • iCloud: prefs:root=CASTLE
  • iCloud Backup: prefs:root=CASTLE&path=BACKUP

Wireless Radios

  • Wi-Fi: prefs:root=WIFI
  • Bluetooth: prefs:root=Bluetooth
  • Cellular: prefs:root=MOBILE_DATA_SETTINGS_ID

Personal Hotspot

  • Personal Hotspot: prefs:root=INTERNET_TETHERING
  • Personal Hotspot ? Family Sharing: prefs:root=INTERNET_TETHERING&path=Family%20Sharing
  • Personal Hotspot ? Wi-Fi Password: prefs:root=INTERNET_TETHERING&path=Wi-Fi%20Password

VPN

  • VPN: prefs:root=General&path=VPN

Notifications

  • Notifications: prefs:root=NOTIFICATIONS_ID
  • Notifications ? Siri Suggestions: prefs:root=NOTIFICATIONS_ID&path=Siri%20Suggestions

Sounds

  • Sounds: prefs:root=Sounds
  • Ringtone: prefs:root=Sounds&path=Ringtone

Do Not Disturb

  • Do Not Disturb: prefs:root=DO_NOT_DISTURB
  • Do Not Disturb ? Allow Calls From: prefs:root=DO_NOT_DISTURB&path=Allow%20Calls%20From

Screen Time

  • Screen Time: prefs:root=SCREEN_TIME
  • Screen Time ? Downtime: prefs:root=SCREEN_TIME&path=DOWNTIME
  • Screen Time ? App Limits: prefs:root=SCREEN_TIME&path=APP_LIMITS
  • Screen Time ? Always Allowed: prefs:root=SCREEN_TIME&path=ALWAYS_ALLOWED

General

  • General: prefs:root=General
  • General ? About: prefs:root=General&path=About
  • General ? Software Update: prefs:root=General&path=SOFTWARE_UPDATE_LINK
  • General ? CarPlay: prefs:root=General&path=CARPLAY
  • General ? Background App Refresh: prefs:root=General&path=AUTO_CONTENT_DOWNLOAD
  • General ? Multitasking (iPad-only): prefs:root=General&path=MULTITASKING
  • General ? Date & Time: prefs:root=General&path=DATE_AND_TIME
  • General ? Keyboard: prefs:root=General&path=Keyboard
  • General ? Keyboard ? Keyboards: prefs:root=General&path=Keyboard/KEYBOARDS
  • General ? Keyboard ? Hardware Keyboard: prefs:root=General&path=Keyboard/Hardware%20Keyboard
  • General ? Keyboard ? Text Replacement: prefs:root=General&path=Keyboard/USER_DICTIONARY
  • General ? Keyboard ? One Handed Keyboard: prefs:root=General&path=Keyboard/ReachableKeyboard
  • General ? Language & Region: prefs:root=General&path=INTERNATIONAL
  • General ? Dictionary: prefs:root=General&path=DICTIONARY
  • General ? Profiles: prefs:root=General&path=ManagedConfigurationList
  • General ? Reset: prefs:root=General&path=Reset

Control Center

  • Control Center: prefs:root=ControlCenter
  • Control Center ? Customize Controls: prefs:root=ControlCenter&path=CUSTOMIZE_CONTROLS

Display

  • Display: prefs:root=DISPLAY
  • Display ? Auto Lock: prefs:root=DISPLAY&path=AUTOLOCK
  • Display ? Text Size: prefs:root=DISPLAY&path=TEXT_SIZE

Accessibility

  • Accessibility: prefs:root=ACCESSIBILITY

Wallpaper

  • Wallpaper: prefs:root=Wallpaper

Siri

  • Siri: prefs:root=SIRI

Apple Pencil

  • Apple Pencil (iPad-only): prefs:root=Pencil

Face ID

  • Face ID: prefs:root=PASSCODE

Emergency SOS

  • Emergency SOS: prefs:root=EMERGENCY_SOS

Battery

  • Battery: prefs:root=BATTERY_USAGE
  • Battery ? Battery Health (iPhone-only): prefs:root=BATTERY_USAGE&path=BATTERY_HEALTH

Privacy

  • Privacy: prefs:root=Privacy
  • Privacy ? Location Services: prefs:root=Privacy&path=LOCATION
  • Privacy ? Contacts: prefs:root=Privacy&path=CONTACTS
  • Privacy ? Calendars: prefs:root=Privacy&path=CALENDARS
  • Privacy ? Reminders: prefs:root=Privacy&path=REMINDERS
  • Privacy ? Photos: prefs:root=Privacy&path=PHOTOS
  • Privacy ? Microphone: prefs:root=Privacy&path=MICROPHONE
  • Privacy ? Speech Recognition: prefs:root=Privacy&path=SPEECH_RECOGNITION
  • Privacy ? Camera: prefs:root=Privacy&path=CAMERA
  • Privacy ? Motion: prefs:root=Privacy&path=MOTION\

App Store

  • App Store: prefs:root=STORE
  • App Store ? App Downloads: prefs:root=STORE&path=App%20Downloads
  • App Store ? Video Autoplay: prefs:root=STORE&path=Video%20Autoplay

Wallet

  • Wallet: prefs:root=PASSBOOK

Passwords & Accounts

  • Passwords & Accounts: prefs:root=ACCOUNTS_AND_PASSWORDS
  • Passwords & Accounts ? Fetch New Data: prefs:root=ACCOUNTS_AND_PASSWORDS&path=FETCH_NEW_DATA
  • Passwords & Accounts ? Add Account: prefs:root=ACCOUNTS_AND_PASSWORDS&path=ADD_ACCOUNT

Mail

  • Mail: prefs:root=MAIL
  • Mail ? Preview: prefs:root=MAIL&path=Preview
  • Mail ? Swipe Options: prefs:root=MAIL&path=Swipe%20Options
  • Mail ? Notifications: prefs:root=MAIL&path=NOTIFICATIONS
  • Mail ? Blocked: prefs:root=MAIL&path=Blocked
  • Mail ? Muted Thread Action: prefs:root=MAIL&path=Muted%20Thread%20Action
  • Mail ? Blocked Sender Options: prefs:root=MAIL&path=Blocked%20Sender%20Options
  • Mail ? Mark Addresses: prefs:root=MAIL&path=Mark%20Addresses
  • Mail ? Increase Quote Level: prefs:root=MAIL&path=Increase%20Quote%20Level
  • Mail ? Include Attachments with Replies: prefs:root=MAIL&path=Include%20Attachments%20with%20Replies
  • Mail ? Signature: prefs:root=MAIL&path=Signature
  • Mail ? Default Account: prefs:root=MAIL&path=Default%20Account

Contacts

  • Contacts: prefs:root=CONTACTS

Calendar

  • Calendar: prefs:root=CALENDAR
  • Calendar ? Alternate Calendars: prefs:root=CALENDAR&path=Alternate%20Calendars
  • Calendar ? Sync: prefs:root=CALENDAR&path=Sync
  • Calendar ? Default Alert Times: prefs:root=CALENDAR&path=Default%20Alert%20Times
  • Calendar ? Default Calendar: prefs:root=CALENDAR&path=Default%20Calendar

Notes

  • Notes: prefs:root=NOTES
  • Notes ? Default Account: prefs:root=NOTES&path=Default%20Account
  • Notes ? Password: prefs:root=NOTES&path=Password
  • Notes ? Sort Notes By: prefs:root=NOTES&path=Sort%20Notes%20By
  • Notes ? New Notes Start With: prefs:root=NOTES&path=New%20Notes%20Start%20With
  • Notes ? Sort Checked Items: prefs:root=NOTES&path=Sort%20Checked%20Items
  • Notes ? Lines & Grids: prefs:root=NOTES&path=Lines%20%26%20Grids
  • Notes ? Access Notes from Lock Screen: prefs:root=NOTES&path=Access%20Notes%20from%20Lock%20Screen

Reminders

  • Reminders: prefs:root=REMINDERS
  • Reminders ? Default List: prefs:root=REMINDERS&path=DEFAULT_LIST

Voice Memos

  • Voice Memos: prefs:root=VOICE_MEMOS

Phone

  • Phone: prefs:root=Phone

Messages

  • Messages: prefs:root=MESSAGES

FaceTime

  • FaceTime: prefs:root=FACETIME

Maps

  • Maps: prefs:root=MAPS
  • Maps ? Driving & Navigation: prefs:root=MAPS&path=Driving%20%26%20Navigation
  • Maps ? Transit: prefs:root=MAPS&path=Transit

Compass

  • Compass: prefs:root=COMPASS

Measure

  • Measure: prefs:root=MEASURE

Safari

  • Safari: prefs:root=SAFARI
  • Safari ? Content Blockers: prefs:root=SAFARI&path=Content%20Blockers
  • Safari ? Downloads: prefs:root=SAFARI&path=DOWNLOADS
  • Safari ? Close Tabs: prefs:root=SAFARI&path=Close%20Tabs
  • Safari ? Clear History and Data: prefs:root=SAFARI&path=CLEAR_HISTORY_AND_DATA
  • Safari ? Page Zoom: prefs:root=SAFARI&path=Page%20Zoom
  • Safari ? Request Desktop Website: prefs:root=SAFARI&path=Request%20Desktop%20Website
  • Safari ? Reader: prefs:root=SAFARI&path=Reader
  • Safari ? Camera: prefs:root=SAFARI&path=Camera
  • Safari ? Microphone: prefs:root=SAFARI&path=Microphone
  • Safari ? Location: prefs:root=SAFARI&path=Location
  • Safari ? Advanced: prefs:root=SAFARI&path=ADVANCED

News

  • News: prefs:root=NEWS

Health

  • Health: prefs:root=HEALTH

Shortcuts

  • Shortcuts: prefs:root=SHORTCUTS

Music

  • Music: prefs:root=MUSIC
  • Music ? Cellular Data: prefs:root=MUSIC&path=com.apple.Music:CellularData
  • Music ? Optimize Storage: prefs:root=MUSIC&path=com.apple.Music:OptimizeStorage
  • Music ? EQ: prefs:root=MUSIC&path=com.apple.Music:EQ
  • Music ? Volume Limit: prefs:root=MUSIC&path=com.apple.Music:VolumeLimit

TV

  • Settings ? TV: prefs:root=TVAPP

Photos

  • Photos: prefs:root=Photos

Camera

  • Camera: prefs:root=CAMERA
  • Camera ? Record Video: prefs:root=CAMERA&path=Record%20Video
  • Camera ? Record Slo-mo: prefs:root=CAMERA&path=Record%20Slo-mo

Books

  • Books: prefs:root=IBOOKS

Game Center

  • Game Center: prefs:root=GAMECENTER

What is the "proper" way to cast Hibernate Query.list() to List<Type>?

You use a ResultTransformer like that:

public List<Foo> activeObjects() {
    Session s = acquireSession();
    Query   q = s.createQuery("from foo where active");
    q.setResultTransformer(Transformers.aliasToBean(Foo.class));
    return (List<Foo>) q.list();
}

PHPExcel - creating multiple sheets by iteration

In case you haven't come to a conclusion... I took Henrique's answer and gave a better logic solution. This is completely compatible with PHPSpreadSheet in case someone is using PHPSpreadSheet or PHPExcel.

$spreadOrPhpExcel = new SpreadSheet(); // or new PHPExcel();
print_in_sheet($spreadOrPhpExcel);

function print_in_sheet($spread)
{
    $sheet = 0;

    foreach( getData() as $report => $value ){
        # If number of sheet is 0 then no new worksheets are created
        if( $sheet > 0 ){
            $spread->createSheet();
        }

        # Index for the worksheet is setted and a title is assigned
        $wSheet = $spread->setActiveSheetIndex($sheet)->setTitle($report);

        # Printing data
        $wSheet->setCellValue("A1", "Hello World!");

        # Index number is incremented for the next worksheet
        $sheet++;
    }

    return $spread;
}

How can I shuffle an array?

Use the modern version of the Fisher–Yates shuffle algorithm:

/**
 * Shuffles array in place.
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    var j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}

ES2015 (ES6) version

/**
 * Shuffles array in place. ES6 version
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}

Note however, that swapping variables with destructuring assignment causes significant performance loss, as of October 2017.

Use

var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);

Implementing prototype

Using Object.defineProperty (method taken from this SO answer) we can also implement this function as a prototype method for arrays, without having it show up in loops such as for (i in arr). The following will allow you to call arr.shuffle() to shuffle the array arr:

Object.defineProperty(Array.prototype, 'shuffle', {
    value: function() {
        for (let i = this.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [this[i], this[j]] = [this[j], this[i]];
        }
        return this;
    }
});

How to update Ruby to 1.9.x on Mac?

Dan Benjamin's Hivelogic article Installing Ruby, RubyGems, and Rails on Snow Leopard is the recommended place to go although the article is for 1.8, so here's a Ruby 1.9-specific install on Snow Leopard. Watch out for the 64-bit thing... either go all 64-bit 'fat' (as is - for example - Apache on OS X, which can cause problems with 32-bit libraries) or check any gems you're likely to use to make sure they're okay for 64-bit.

Javascript change font color

You can use the HTML tag in order to apply font size, font color in one line on JavaScript, as well as you can use .fontcolor() method to define color, .fontsize() method to define the font size, .bold() method to define bold, etc. These are called JavaScript Built-in Functions.

  • Here is a list of some JavaScript built-in functions:

    .big()
    .small()
    .italics()
    .fixed()
    .strike()
    .sup()

  • The below built-in functions require parameters:

    .fontsize() //e.g.: the size to be applied in number .fontsize(4)

    .fontcolor("") //e.g.: the color to be applied in string .fontcolor("red")

    .txt.link("") //e.g.: the url to be linkable as string .link("www.test.com")

    .toUpperCase() //e.g.: the converted to uppercase to be applied in string .toUpperCase()

  • Remember the syntax is: string.functionName() e.g.:

    var txt = "Hello World!"; txt.bold();

  • This also can be done in one line:

    var txt = "Hello World!".bold();

    The result will be: Hello World!

  • You can use multiple built-in functions in one line, adding one next to the other. e.g.:

    "10/22/2018".fontcolor("red").fontsize(4).bold()

  • The following is an example how I used it on my JavaScript code to change font (color, size, bold) using both HTML tags and JavaScript functions:

vForm.message = "<HTML><font size = 4 color = 'red'><b> Application Deadline was </b></font></HTML> " + "10/22/2018".fontcolor("red").fontsize(4).bold(); /* setting HTML font color, size, bold and combined them with JavaScript functions to change font color, size, bold in JavaScript code */

  • Here is the result:

Application Deadline was  10/22/2018

Nodejs cannot find installed module on Windows

All of the above answers did not work for me. The only thing that worked eventually was to add the %AppData%\npm to the environment Path variable, AND to delete the two ng files in C:\Program Files\nodejs.

The ng packages were not installed in C:\Program Files\nodejs\node_modules, so it was apparent that using the ng binary from the nodejs directory would not work.

I am not sure why it searched in this directory, because I already configured - PATH environment variable - .npmrc in the C:\Users\MyUser - Tried to add system variables and/or NODE_PATH

How do you remove the title text from the Android ActionBar?

I am new to Android so maybe I am wrong...but to solve this problem cant we just go to the manifest and remove the activity label

<activity
        android:name=".Bcft"
        android:screenOrientation="portrait"

        **android:label="" >**

Worked for me....

What is lexical scope?

Lexical scope means that in a nested group of functions, the inner functions have access to the variables and other resources of their parent scope. This means that the child functions are lexically bound to the execution context of their parents. Lexical scope is sometimes also referred to as static scope.

function grandfather() {
    var name = 'Hammad';
    // 'likes' is not accessible here
    function parent() {
        // 'name' is accessible here
        // 'likes' is not accessible here
        function child() {
            // Innermost level of the scope chain
            // 'name' is also accessible here
            var likes = 'Coding';
        }
    }
}

The thing you will notice about lexical scope is that it works forward, meaning name can be accessed by its children's execution contexts. But it doesn't work backward to its parents, meaning that the variable likes cannot be accessed by its parents.

This also tells us that variables having the same name in different execution contexts gain precedence from top to bottom of the execution stack. A variable, having a name similar to another variable, in the innermost function (topmost context of the execution stack) will have higher precedence.

Source.

Angular 2 declaring an array of objects

type NumberArray = Array<{id: number, text: string}>;

const arr: NumberArray = [
    {id: 0, text: 'Number 0'},
    {id: 1, text: 'Number 1'},
    {id: 2, text: 'Number 2'},
    {id: 3, text: 'Number 3 '},
    {id: 4, text: 'Number 4 '},
    {id: 5, text: 'Number 5 '},
];

C error: Expected expression before int

By C89, variable can only be defined at the top of a block.

if (a == 1)
    int b = 10;   // it's just a statement, syntacitially error 

if (a == 1)
{                  // refer to the beginning of a local block 
    int b = 10;    // at the top of the local block, syntacitially correct
}                  // refer to the end of a local block

if (a == 1)
{
    func();
    int b = 10;    // not at the top of the local block, syntacitially error, I guess
}

Internal Error 500 Apache, but nothing in the logs?

Check your php error log which might be a separate file from your apache error log.

Find it by going to phpinfo() and check for error_log attribute. If it is not set. Set it: https://stackoverflow.com/a/12835262/445131

Maybe your post_max_size is too small for what you're trying to post, or one of the other max memory settings is too low.

How to resolve "gpg: command not found" error during RVM installation?

As the instruction said "might need gpg2"

In mac, you can try install it with homebrew

$ brew install gpg2 

Difference between string and StringBuilder in C#

A string instance is immutable. You cannot change it after it was created. Any operation that appears to change the string instead returns a new instance:

string foo = "Foo";
// returns a new string instance instead of changing the old one
string bar = foo.Replace('o', 'a');
string baz = foo + "bar"; // ditto here

Immutable objects have some nice properties, such as they can be used across threads without fearing synchronization problems or that you can simply hand out your private backing fields directly without fearing that someone changes objects they shouldn't be changing (see arrays or mutable lists, which often need to be copied before returning them if that's not desired). But when used carelessly they may create severe performance problems (as nearly anything – if you need an example from a language that prides itself on speed of execution then look at C's string manipulation functions).

When you need a mutable string, such as one you're contructing piece-wise or where you change lots of things, then you'll need a StringBuilder which is a buffer of characters that can be changed. This has, for the most part, performance implications. If you want a mutable string and instead do it with a normal string instance, then you'll end up with creating and destroying lots of objects unnecessarily, whereas a StringBuilder instance itself will change, negating the need for many new objects.

Simple example: The following will make many programmers cringe with pain:

string s = string.Empty;
for (i = 0; i < 1000; i++) {
  s += i.ToString() + " ";
}

You'll end up creating 2001 strings here, 2000 of which are thrown away. The same example using StringBuilder:

StringBuilder sb = new StringBuilder();
for (i = 0; i < 1000; i++) {
  sb.Append(i);
  sb.Append(' ');
}

This should place much less stress on the memory allocator :-)

It should be noted however, that the C# compiler is reasonably smart when it comes to strings. For example, the following line

string foo = "abc" + "def" + "efg" + "hij";

will be joined by the compiler, leaving only a single string at runtime. Similarly, lines such as

string foo = a + b + c + d + e + f;

will be rewritten to

string foo = string.Concat(a, b, c, d, e, f);

so you don't have to pay for five nonsensical concatenations which would be the naïve way of handling that. This won't save you in loops as above (unless the compiler unrolls the loop but I think only the JIT may actually do so and better don't bet on that).

Wrapping long text without white space inside of a div

white-space: pre-wrap

is what worked for me for <span> and <div>.

JPanel vs JFrame in Java

JFrame is the window; it can have one or more JPanel instances inside it. JPanel is not the window.

You need a Swing tutorial:

http://docs.oracle.com/javase/tutorial/uiswing/

CSS align one item right with flexbox

To align one flex child to the right set it withmargin-left: auto;

From the flex spec:

One use of auto margins in the main axis is to separate flex items into distinct "groups". The following example shows how to use this to reproduce a common UI pattern - a single bar of actions with some aligned on the left and others aligned on the right.

.wrap div:last-child {
  margin-left: auto;
}

Updated fiddle

_x000D_
_x000D_
.wrap {_x000D_
  display: flex;_x000D_
  background: #ccc;_x000D_
  width: 100%;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.wrap div:last-child {_x000D_
  margin-left: auto;_x000D_
}_x000D_
.result {_x000D_
  background: #ccc;_x000D_
  margin-top: 20px;_x000D_
}_x000D_
.result:after {_x000D_
  content: '';_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
.result div {_x000D_
  float: left;_x000D_
}_x000D_
.result div:last-child {_x000D_
  float: right;_x000D_
}
_x000D_
<div class="wrap">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<!-- DESIRED RESULT -->_x000D_
<div class="result">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note:

You could achieve a similar effect by setting flex-grow:1 on the middle flex item (or shorthand flex:1) which would push the last item all the way to the right. (Demo)

The obvious difference however is that the middle item becomes bigger than it may need to be. Add a border to the flex items to see the difference.

Demo

_x000D_
_x000D_
.wrap {_x000D_
  display: flex;_x000D_
  background: #ccc;_x000D_
  width: 100%;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.wrap div {_x000D_
  border: 3px solid tomato;_x000D_
}_x000D_
.margin div:last-child {_x000D_
  margin-left: auto;_x000D_
}_x000D_
.grow div:nth-child(2) {_x000D_
  flex: 1;_x000D_
}_x000D_
.result {_x000D_
  background: #ccc;_x000D_
  margin-top: 20px;_x000D_
}_x000D_
.result:after {_x000D_
  content: '';_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
.result div {_x000D_
  float: left;_x000D_
}_x000D_
.result div:last-child {_x000D_
  float: right;_x000D_
}
_x000D_
<div class="wrap margin">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<div class="wrap grow">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<!-- DESIRED RESULT -->_x000D_
<div class="result">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I put an icon inside a TextInput in React Native?

This is working for me in ReactNative 0.60.4

View

<View style={styles.SectionStyle}>
    <Image
        source={require('../assets/images/ico-email.png')} //Change your icon image here
        style={styles.ImageStyle}
    />

    <TextInput
        style={{ flex: 1 }}
        placeholder="Enter Your Name Here"
        underlineColorAndroid="transparent"
    />
</View>

Styles

SectionStyle: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
    borderWidth: 0.5,
    borderColor: '#000',
    height: 40,
    borderRadius: 5,
    margin: 10,
},
ImageStyle: {
    padding: 10,
    margin: 5,
    height: 25,
    width: 25,
    resizeMode: 'stretch',
    alignItems: 'center',
}

Java swing application, close one window and open another when button is clicked

Here is an example:

enter image description here

enter image description here

StartupWindow.java

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;


public class StartupWindow extends JFrame implements ActionListener
{
    private JButton btn;

    public StartupWindow()
    {
        super("Simple GUI");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        btn = new JButton("Open the other JFrame!");
        btn.addActionListener(this);
        btn.setActionCommand("Open");
        add(btn);
        pack();

    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        String cmd = e.getActionCommand();

        if(cmd.equals("Open"))
        {
            dispose();
            new AnotherJFrame();
        }
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable(){

            @Override
            public void run()
            {
                new StartupWindow().setVisible(true);
            }

        });
    }
}

AnotherJFrame.java

import javax.swing.JFrame;
import javax.swing.JLabel;

public class AnotherJFrame extends JFrame
{
    public AnotherJFrame()
    {
        super("Another GUI");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        add(new JLabel("Empty JFrame"));
        pack();
        setVisible(true);
    }
}

How to sort a HashMap in Java

A proper answer.

HashMap<Integer, Object> map = new HashMap<Integer, Object>();

ArrayList<Integer> sortedKeys = new ArrayList<Integer>(map.keySet());
Collections.sort(sortedKeys, new Comparator<Integer>() {
  @Override
  public int compare(Integer a, Integer b) {
    return a.compareTo(b);
  }
});

for (Integer key: sortedKeys) {
  //map.get(key);
}

Note that HashMap itself cannot maintain sorting, as other answers have pointed out. It's a hash map, and hashed values are unsorted. You can thus either sort the keys when you need to and then access the values in order, as I demonstrated above, or you can find a different collection to store your data, like an ArrayList of Pairs/Tuples, such as the Pair found in Apache Commons:

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/Pair.html

Getting the ID of the element that fired an event

In case of Angular 7.x you can get the native element and its id or properties.

myClickHandler($event) {
    this.selectedElement = <Element>$event.target;
    console.log(this.selectedElement.id)
    this.selectedElement.classList.remove('some-class');
}

html:

<div class="list-item" (click)="myClickHandler($event)">...</div>

Background color in input and text fields

The best solution is the attribute selector in CSS (input[type="text"]) as the others suggested.

But if you have to support Internet Explorer 6, you cannot use it (QuirksMode). Well, only if you have to and also are willing to support it.

In this case your only option seems to be to define classes on input elements.

<input type="text" class="input-box" ... />
<input type="submit" class="button" ... />
...

and target them with a class selector:

input.input-box, textarea { background: cyan; }

mongodb: insert if not exists

In general, using update is better in MongoDB as it will just create the document if it doesn't exist yet, though I'm not sure how to work that with your python adapter.

Second, if you only need to know whether or not that document exists, count() which returns only a number will be a better option than find_one which supposedly transfer the whole document from your MongoDB causing unnecessary traffic.

Set the text in a span

Give an ID to your span and then change the text of target span.

$("#StatusTitle").text("Info");
$("#StatusTitleIcon").removeClass("fa-exclamation").addClass("fa-info-circle"); 

<i id="StatusTitleIcon" class="fa fa-exclamation fa-fw"></i>
<span id="StatusTitle">Error</span>

Here "Error" text will become "Info" and their fontawesome icons will be changed as well.

How can I make a TextBox be a "password box" and display stars when using MVVM?

As Tasnim Fabiha mentioned, it is possible to change font for TextBox in order to show only dots/asterisks. But I wasn't able to find his font...so I give you my working example:

<TextBox Text="{Binding Password}" 
     FontFamily="pack://application:,,,/Resources/#password" />

Just copy-paste won't work. Firstly you have to download mentioned font "password.ttf" link: https://github.com/davidagraf/passwd/blob/master/public/ttf/password.ttf Then copy that to your project Resources folder (Project->Properties->Resources->Add resource->Add existing file). Then set it's Build Action to: Resource.

After this you will see just dots, but you can still copy text from that, so it is needed to disable CTRL+C shortcut like this:

<TextBox Text="{Binding Password}" 
     FontFamily="pack://application:,,,/Resources/#password" > 
    <TextBox.InputBindings>
        <!--Disable CTRL+C -->
        <KeyBinding Command="ApplicationCommands.NotACommand"
            Key="C"
            Modifiers="Control" />
    </TextBox.InputBindings>
</TextBox>

Open JQuery Datepicker by clicking on an image w/ no input field

The jQuery documentation says that the datePicker needs to be attached to a SPAN or a DIV when it is not associated with an input box. You could do something like this:

<img src='someimage.gif' id="datepickerImage" />
<div id="datepicker"></div>

<script type="text/javascript">
 $(document).ready(function() {
    $("#datepicker").datepicker({
            changeMonth: true,
            changeYear: true,
    })
    .hide()
    .click(function() {
      $(this).hide();
    });

    $("#datepickerImage").click(function() {
       $("#datepicker").show(); 
    });
 });
</script>

How do I run a node.js app as a background service?

I use tmux for a multiple window/pane development environment on remote hosts. It's really simple to detach and keep the process running in the background. Have a look at tmux

scale Image in an UIButton to AspectFit?

I had the same problem. Just set the ContentMode of the ImageView that is inside the UIButton.

[[self.itemImageButton imageView] setContentMode: UIViewContentModeScaleAspectFit];
[self.itemImageButton setImage:[UIImage imageNamed:stretchImage] forState:UIControlStateNormal];

Hope this helps.

Can you split/explode a field in a MySQL query?

Seeing that it's a fairly popular question - the answer is YES.

For a column column in table table containing all of your coma separated values:

CREATE TEMPORARY TABLE temp (val CHAR(255));
SET @S1 = CONCAT("INSERT INTO temp (val) VALUES ('",REPLACE((SELECT GROUP_CONCAT( DISTINCT  `column`) AS data FROM `table`), ",", "'),('"),"');");
PREPARE stmt1 FROM @s1;
EXECUTE stmt1;
SELECT DISTINCT(val) FROM temp;

Please remember however to not store CSV in your DB


Per @Mark Amery - as this translates coma separated values into an INSERT statement, be careful when running it on unsanitised data


Just to reiterate, please don't store CSV in your DB; this function is meant to translate CSV into sensible DB structure and not to be used anywhere in your code. If you have to use it in production, please rethink your DB structure

How to export table as CSV with headings on Postgresql?

copy (anysql query datawanttoexport) to 'fileablsoutepathwihname' delimiter ',' csv header;

Using this u can export data also.

Allow anonymous authentication for a single folder in web.config?

<location path="ForAll/Demo.aspx">
 <system.web>
  <authorization>
    <allow users="*" />
  </authorization>
 </system.web>
</location>

In Addition: If you want to write something on that folder through website , you have to give IIS_User permission to the folder

Splitting a Java String by the pipe symbol using split("|")

You could also use the apache library and do this:

StringUtils.split(test, "|");

Creating a recursive method for Palindrome

Here is my go at it:

public class Test {

    public static boolean isPalindrome(String s) {
        return s.length() <= 1 ||
            (s.charAt(0) == s.charAt(s.length() - 1) &&
             isPalindrome(s.substring(1, s.length() - 1)));
    }


    public static boolean isPalindromeForgiving(String s) {
        return isPalindrome(s.toLowerCase().replaceAll("[\\s\\pP]", ""));
    }


    public static void main(String[] args) {

        // True (odd length)
        System.out.println(isPalindrome("asdfghgfdsa"));

        // True (even length)
        System.out.println(isPalindrome("asdfggfdsa"));

        // False
        System.out.println(isPalindrome("not palindrome"));

        // True (but very forgiving :)
        System.out.println(isPalindromeForgiving("madam I'm Adam"));
    }
}

Elegant solution for line-breaks (PHP)

Not very "elegant" and kinda a waste, but if you really care what the code looks like you could make your own fancy flag and then do a str_replace.

Example:<br />
$myoutput =  "After this sentence there is a line break.<b>.|..</b> Here is a new line.";<br />
$myoutput =  str_replace(".|..","&lt;br />",$myoutput);<br />

or

how about:<br />
$myoutput =  "After this sentence there is a line break.<b>E(*)3</b> Here is a new line.";<br />
$myoutput =  str_replace("E(*)3","&lt;br />",$myoutput);<br />

I call the first method "middle finger style" and the second "goatse style".

How do you decrease navbar height in Bootstrap 3?

Instead of <nav class="navbar ... use <nav class="navbar navbar-xs...

and add these 3 line of css

.navbar-xs { min-height:28px; height: 28px; }
.navbar-xs .navbar-brand{ padding: 0px 12px;font-size: 16px;line-height: 28px; }
.navbar-xs .navbar-nav > li > a {  padding-top: 0px; padding-bottom: 0px; line-height: 28px; }

Output :

enter image description here

How to reposition Chrome Developer Tools

In addition, if you want to see Sources and Console on one window, go to:

"Customize and control DevTools -> "Show console drawer"

You can also see it here at the right corner:

"Show console drawer"

Unresponsive KeyListener for JFrame

This should help

    yourJFrame.setFocusable(true);
    yourJFrame.addKeyListener(new java.awt.event.KeyAdapter() {


        @Override
        public void keyTyped(KeyEvent e) {
            System.out.println("you typed a key");
        }

        @Override
        public void keyPressed(KeyEvent e) {
            System.out.println("you pressed a key");
        }

        @Override
        public void keyReleased(KeyEvent e) {
            System.out.println("you released a key");
        }
    });

List of remotes for a Git repository?

If you only need the names of the remote repositories (and not any of the other data), a simple git remote is enough.

$ git remote
iqandreas
octopress
origin

How to extract a substring using regex

add apache.commons dependency on your pom.xml

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-io</artifactId>
    <version>1.3.2</version>
</dependency>

And below code works.

StringUtils.substringBetween(String mydata, String "'", String "'")

Get UserDetails object from Security Context in Spring MVC controller

if you are using spring security then you can get the current logged in user by

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
     String name = auth.getName(); //get logged in username

DropDownList in MVC 4 with Razor

This can also be done like

@model IEnumerable<ItemList>

_x000D_
_x000D_
<select id="dropdowntipo">_x000D_
    <option value="0">Select Item</option>_x000D_
    _x000D_
    @{_x000D_
      foreach(var item in Model)_x000D_
      {_x000D_
        <option value= "@item.Value">@item.DisplayText</option>_x000D_
      }_x000D_
    }_x000D_
_x000D_
</select>
_x000D_
_x000D_
_x000D_

Pandas read_csv low_memory and dtype options

I had a similar issue with a ~400MB file. Setting low_memory=False did the trick for me. Do the simple things first,I would check that your dataframe isn't bigger than your system memory, reboot, clear the RAM before proceeding. If you're still running into errors, its worth making sure your .csv file is ok, take a quick look in Excel and make sure there's no obvious corruption. Broken original data can wreak havoc...

How to put two divs side by side

<div style="display: inline">
    <div style="width:80%; display: inline-block; float:left; margin-right: 10px;"></div>
    <div style="width: 19%; display: inline-block; border: 1px solid red"></div>
</div>

How to delay the .keyup() handler until the user stops typing?

Another slight enhancement on CMS's answer. To easily allow for separate delays, you can use the following:

function makeDelay(ms) {
    var timer = 0;
    return function(callback){
        clearTimeout (timer);
        timer = setTimeout(callback, ms);
    };
};

If you want to reuse the same delay, just do

var delay = makeDelay(250);
$(selector1).on('keyup', function() {delay(someCallback);});
$(selector2).on('keyup', function() {delay(someCallback);});

If you want separate delays, you can do

$(selector1).on('keyup', function() {makeDelay(250)(someCallback);});
$(selector2).on('keyup', function() {makeDelay(250)(someCallback);});

How do I get the last character of a string?

String aString = "This will return the letter t";
System.out.println(aString.charAt(aString.length() - 1));

Output should be:

t

Happy coding!

How to change the height of a div dynamically based on another div using css?

The simplest way to get equal height columns, without the ugly side effects that come along with absolute positioning, is to use the display: table properties:

.div1 {
  width:300px;
  height: auto;
  background-color: grey;  
  border:1px solid;
  display: table;
}

.div2, .div3 {
  display: table-cell;
}
.div2 {
  width:150px;
  height:auto;
  background-color: #F4A460;  

}
.div3 {
  width:150px;
  height:auto;
  background-color: #FFFFE0;  
}

http://jsfiddle.net/E4Zgj/21/


Now, if your goal is to have .div2 so that it is only as tall as it needs to be to contain its content while .div3 is at least as tall as .div2 but still able to expand if its content makes it taller than .div2, then you need to use flexbox. Flexbox support isn't quite there yet (IE10, Opera, Chrome. Firefox follows an old spec, but is following the current spec soon).

.div1 {
  width:300px;
  height: auto;
  background-color: grey;  
  border:1px solid;
  display: flex;
  align-items: flex-start;
}

.div2 {
  width:150px;
  background-color: #F4A460;
}

.div3 {
  width:150px;
  background-color: #FFFFE0;
  align-self: stretch;
}

http://jsfiddle.net/E4Zgj/22/

C++ cast to derived class

dynamic_cast should be what you are looking for.

EDIT:

DerivedType m_derivedType = m_baseType; // gives same error

The above appears to be trying to invoke the assignment operator, which is probably not defined on type DerivedType and accepting a type of BaseType.

DerivedType * m_derivedType = (DerivedType*) & m_baseType; // gives same error

You are on the right path here but the usage of the dynamic_cast will attempt to safely cast to the supplied type and if it fails, a NULL will be returned.

Going on memory here, try this (but note the cast will return NULL as you are casting from a base type to a derived type):

DerivedType * m_derivedType = dynamic_cast<DerivedType*>(&m_baseType);

If m_baseType was a pointer and actually pointed to a type of DerivedType, then the dynamic_cast should work.

Hope this helps!

jquery select option click handler

You want the 'change' event handler, instead of 'click'.

$('#mySelect').change(function(){ 
    var value = $(this).val();
});

Catch multiple exceptions in one line (except block)

One of the way to do this is..

try:
   You do your operations here;
   ......................
except(Exception1[, Exception2[,...ExceptionN]]]):
   If there is any exception from the given exception list, 
   then execute this block.
   ......................
else:
   If there is no exception then execute this block. 

and another way is to create method which performs task executed by except block and call it through all of the except block that you write..

try:
   You do your operations here;
   ......................
except Exception1:
    functionname(parameterList)
except Exception2:
    functionname(parameterList)
except Exception3:
    functionname(parameterList)
else:
   If there is no exception then execute this block. 

def functionname( parameters ):
   //your task..
   return [expression]

I know that second one is not the best way to do this, but i'm just showing number of ways to do this thing.

How to break out of jQuery each Loop

I created a Fiddle for the answer to this question because the accepted answer is incorrect plus this is the first StackOverflow thread returned from Google regarding this question.

To break out of a $.each you must use return false;

Here is a Fiddle proving it:

http://jsfiddle.net/9XqRy/

Oracle SQL Developer: Unable to find a JVM

This is known to happen even if there are some syntactical errors in your heap space setting in the sqldeveloper.conf. If you have defined the heap space in any of the wrong ways mentioned here, it still will show the same error when you launch it.

EDIT : The correct way to set your heap size parameters would be something like this:

AddVMOption -XX:MaxPermSize=256M
AddVMOption -Xms256M
AddVMOption -Xmx768M

How to count down in for loop?

The range function in python has the syntax:

range(start, end, step)

It has the same syntax as python lists where the start is inclusive but the end is exclusive.

So if you want to count from 5 to 1, you would use range(5,0,-1) and if you wanted to count from last to posn you would use range(last, posn - 1, -1).

PyCharm shows unresolved references error for valid code

Geeze what a nightmare, my amalgamation of different StackOVerflow answers:

  1. Switch to local interpreter /usr/bin/pythonX.X and apply
  2. View paths like above answer
  3. Find skeletons path. Mine was (/home/tim/Desktop/pycharm-community-2016.2.3/helpers/python-skeletons)
  4. Switch back to virt interpreter and add the skeletons path manually if it didn't automatically show up.

Making a PowerShell POST request if a body param starts with '@'

You should be able to do the following:

$params = @{"@type"="login";
 "username"="[email protected]";
 "password"="yyy";
}

Invoke-WebRequest -Uri http://foobar.com/endpoint -Method POST -Body $params

This will send the post as the body. However - if you want to post this as a Json you might want to be explicit. To post this as a JSON you can specify the ContentType and convert the body to Json by using

Invoke-WebRequest -Uri http://foobar.com/endpoint -Method POST -Body ($params|ConvertTo-Json) -ContentType "application/json"

Extra: You can also use the Invoke-RestMethod for dealing with JSON and REST apis (which will save you some extra lines for de-serializing)

How to check if variable is array?... or something array-like

PHP 7.1.0 has introduced the iterable pseudo-type and the is_iterable() function, which is specially designed for such a purpose:

This […] proposes a new iterable pseudo-type. This type is analogous to callable, accepting multiple types instead of one single type.

iterable accepts any array or object implementing Traversable. Both of these types are iterable using foreach and can be used with yield from within a generator.

function foo(iterable $iterable) {
    foreach ($iterable as $value) {
        // ...
    }
}

This […] also adds a function is_iterable() that returns a boolean: true if a value is iterable and will be accepted by the iterable pseudo-type, false for other values.

var_dump(is_iterable([1, 2, 3])); // bool(true)
var_dump(is_iterable(new ArrayIterator([1, 2, 3]))); // bool(true)
var_dump(is_iterable((function () { yield 1; })())); // bool(true)
var_dump(is_iterable(1)); // bool(false)
var_dump(is_iterable(new stdClass())); // bool(false)

You can also use the function is_array($var) to check if the passed variable is an array:

<?php
    var_dump( is_array(array()) ); // true
    var_dump( is_array(array(1, 2, 3)) ); // true
    var_dump( is_array($_SERVER) ); // true
?>

Read more in How to check if a variable is an array in PHP?

Set Radiobuttonlist Selected from Codebehind

You could do:

radio1.SelectedIndex = 1;

But this is the most simple form and would most likely become problematic as your UI grows. Say, for instance, if a team member inserts an item in the RadioButtonList above option2 but doesn't know we use magic numbers in code-behind to select - now the app selects the wrong index!

Maybe you want to look into using FindControl in order to determine the ListItem actually required, by name, and selecting appropriately. For instance:

//omitting possible null reference checks...
var wantedOption = radio1.FindControl("option2").Selected = true;

How do you read a CSV file and display the results in a grid in Visual Basic 2010?

This is how you can read data from .csv file using OLEDB provider.

  If OpenFileDialog1.ShowDialog(Me) = DialogResult.OK Then
        Try
            Dim fi As New FileInfo(OpenFileDialog1.FileName)
            Dim sConnectionStringz As String = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Text;Data Source=" & fi.DirectoryName
            Dim objConn As New OleDbConnection(sConnectionStringz)
            objConn.Open()
            'DataGridView1.TabIndex = 1
            Dim objCmdSelect As New OleDbCommand("SELECT * FROM " & fi.Name, objConn)
            Dim objAdapter1 As New OleDbDataAdapter
            objAdapter1.SelectCommand = objCmdSelect
            Dim objDataset1 As New DataSet
            objAdapter1.Fill(objDataset1)

            '--objAdapter1.Update(objDataset1) '--updating
            DataGridView1.DataSource = objDataset1.Tables(0).DefaultView
        Catch ex as Exception
           MsgBox("Error: " + ex.Message)
        Finally
            objConn.Close()
        End Try
    End If

How to split a file into equal parts, without breaking individual lines?

The script isn't even necessary, split(1) supports the wanted feature out of the box:
split -l 75 auth.log auth.log. The above command splits the file in chunks of 75 lines a piece, and outputs file on the form: auth.log.aa, auth.log.ab, ...

wc -l on the original file and output gives:

  321 auth.log
   75 auth.log.aa
   75 auth.log.ab
   75 auth.log.ac
   75 auth.log.ad
   21 auth.log.ae
  642 total

how to concatenate two dictionaries to create a new one in Python?

Use the dict constructor

d1={1:2,3:4}
d2={5:6,7:9}
d3={10:8,13:22}

d4 = reduce(lambda x,y: dict(x, **y), (d1, d2, d3))

As a function

from functools import partial
dict_merge = partial(reduce, lambda a,b: dict(a, **b))

The overhead of creating intermediate dictionaries can be eliminated by using thedict.update() method:

from functools import reduce
def update(d, other): d.update(other); return d
d4 = reduce(update, (d1, d2, d3), {})

Android: java.lang.SecurityException: Permission Denial: start Intent

I had this problem with this exact activity.

You can't start com.fsck.k9.activity.MessageList from an external activity.

I solved it with:

Intent LaunchK9 = getPackageManager().getLaunchIntentForPackage("com.fsck.k9"); this.startActivity(LaunchK9);

Using http://developer.android.com/reference/android/content/pm/PackageManager.html

HTML: can I display button text in multiple lines?

Yes it is, and you can also use it like this

<button>Click here to<br/> start playing</button>

if you want to make the break yourself.

Ruby on Rails form_for select field with class

Try this way:

<%= f.select(:object_field, ['Item 1', ...], {}, { :class => 'my_style_class' }) %>

select helper takes two options hashes, one for select, and the second for html options. So all you need is to give default empty options as first param after list of items and then add your class to html_options.

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select

How can I print variable and string on same line in Python?

I copied and pasted your script into a .py file. I ran it as-is with Python 2.7.10 and received the same syntax error. I also tried the script in Python 3.5 and received the following output:

File "print_strings_on_same_line.py", line 16
print fiveYears
              ^
SyntaxError: Missing parentheses in call to 'print'

Then, I modified the last line where it prints the number of births as follows:

currentPop = 312032486
oneYear = 365
hours = 24
minutes = 60
seconds = 60

# seconds in a single day
secondsInDay = hours * minutes * seconds

# seconds in a year
secondsInYear = secondsInDay * oneYear

fiveYears = secondsInYear * 5

#Seconds in 5 years
print fiveYears

# fiveYears in seconds, divided by 7 seconds
births = fiveYears // 7

print "If there was a birth every 7 seconds, there would be: " + str(births) + " births"

The output was (Python 2.7.10):

157680000
If there was a birth every 7 seconds, there would be: 22525714 births

I hope this helps.

Get the value for a listbox item by index

I'm using a BindingSource with a SqlDataReader behind it and none of the above works for me.

Question for Microsoft: Why does this work:

  ? lst.SelectedValue

But this doesn't?

   ? lst.Items[80].Value

I find I have to go back to to the BindingSource object, cast it as a System.Data.Common.DbDataRecord, and then refer to its column name:

   ? ((System.Data.Common.DbDataRecord)_bsBlocks[80])["BlockKey"]

Now that's just ridiculous.

An App ID with Identifier '' is not available. Please enter a different string

This is for those who bump into the odd case I did, you CANNOT use the keyword test in the bundle id.

We were needing to test sharing data through the app group feature and the companion app wasn't developed yet so we simply changed the bundle identifier to test.APP_NAME instead of company.APP_NAME. We set up everything in iTunes Connect and nothing worked right. We then swapped the name to beta.APP_NAME and Xcode was able to manage the app id correctly again.

Normally to fix this issue, verify your provisioning profiles and App Id's have the correct settings, and if your still having trouble to to Xcode -> Preferences -> Accounts -> View Details -> Download All and you should be good.

Hope that helps.

Safely turning a JSON string into an object

Older question, I know, however nobody notice this solution by using new Function(), an anonymous function that returns the data.


Just an example:

 var oData = 'test1:"This is my object",test2:"This is my object"';

 if( typeof oData !== 'object' )
  try {
   oData = (new Function('return {'+oData+'};'))();
  }
  catch(e) { oData=false; }

 if( typeof oData !== 'object' )
  { alert( 'Error in code' ); }
 else {
        alert( oData.test1 );
        alert( oData.test2 );
      }

This is a little more safe because it executes inside a function and do not compile in your code directly. So if there is a function declaration inside it, it will not be bound to the default window object.

I use this to 'compile' configuration settings of DOM elements (for example the data attribute) simple and fast.

How can I create an object and add attributes to it?

The built-in object can be instantiated but can't have any attributes set on it. (I wish it could, for this exact purpose.) It doesn't have a __dict__ to hold the attributes.

I generally just do this:

class Object(object):
    pass

a = Object()
a.somefield = somevalue

When I can, I give the Object class a more meaningful name, depending on what kind of data I'm putting in it.

Some people do a different thing, where they use a sub-class of dict that allows attribute access to get at the keys. (d.key instead of d['key'])

Edit: For the addition to your question, using setattr is fine. You just can't use setattr on object() instances.

params = ['attr1', 'attr2', 'attr3']
for p in params:
    setattr(obj.a, p, value)

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

javaw.exe cannot find path

Just update your eclipse.ini file (you can find it in the root-directory of eclipse) by this:

-vm
path/javaw.exe

for example:

-vm 
C:/Program Files/Java/jdk1.7.0_09/jre/bin/javaw.exe

Select dropdown with fixed width cutting off content in IE

I found a pretty straightforward fix for this. In the <select> html element add these properties:

onmouseover="autoWidth(this)" 
onblur="resetWidth(this)" 

So whenever user clicks on that the width will automatically expand, and user moves out of the select box, the width will be reset to original.

How To change the column order of An Existing Table in SQL Server 2008

Relying on column order is generally a bad idea in SQL. SQL is based on Relational theory where order is never guaranteed - by design. You should treat all your columns and rows as having no order and then change your queries to provide the correct results:

For Columns:

  • Try not to use SELECT *, but instead specify the order of columns in the select list as in: SELECT Member_ID, MemberName, MemberAddress from TableName. This will guarantee order and will ease maintenance if columns get added.

For Rows:

  • Row order in your result set is only guaranteed if you specify the ORDER BY clause.
  • If no ORDER BY clause is specified the result set may differ as the Query Plan might differ or the database pages might have changed.

Hope this helps...

node.js Error: connect ECONNREFUSED; response from server

use a proxy property in your code it should work just fine

const https = require('https');
const request = require('request');

request({
    'url':'https://teamtreehouse.com/chalkers.json',
    'proxy':'http://xx.xxx.xxx.xx'
    },
    function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var data = body;
            console.log(data);
        }
    }
);

Play an audio file using jQuery when a button is clicked

JSFiddle Demonstration

This is what I use with JQuery:

$('.button').on('click', function () { 
    var obj = document.createElement("audio");
        obj.src = "linktoyourfile.wav"; 
        obj.play(); 
});

How to use Elasticsearch with MongoDB?

Here how to do this on mongodb 3.0. I used this nice blog

  1. Install mongodb.
  2. Create data directories:
$ mkdir RANDOM_PATH/node1
$ mkdir RANDOM_PATH/node2> 
$ mkdir RANDOM_PATH/node3
  1. Start Mongod instances
$ mongod --replSet test --port 27021 --dbpath node1
$ mongod --replSet test --port 27022 --dbpath node2
$ mongod --replSet test --port 27023 --dbpath node3
  1. Configure the Replica Set:
$ mongo
config = {_id: 'test', members: [ {_id: 0, host: 'localhost:27021'}, {_id: 1, host: 'localhost:27022'}]};    
rs.initiate(config);
  1. Installing Elasticsearch:
a. Download and unzip the [latest Elasticsearch][2] distribution

b. Run bin/elasticsearch to start the es server.

c. Run curl -XGET http://localhost:9200/ to confirm it is working.
  1. Installing and configuring the MongoDB River:

$ bin/plugin --install com.github.richardwilly98.elasticsearch/elasticsearch-river-mongodb

$ bin/plugin --install elasticsearch/elasticsearch-mapper-attachments

  1. Create the “River” and the Index:

curl -XPUT 'http://localhost:8080/_river/mongodb/_meta' -d '{ "type": "mongodb", "mongodb": { "db": "mydb", "collection": "foo" }, "index": { "name": "name", "type": "random" } }'

  1. Test on browser:

    http://localhost:9200/_search?q=home

Android - Handle "Enter" in an EditText

editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId != 0 || event.getAction() == KeyEvent.ACTION_DOWN) {
                // Action
                return true;
            } else {
                return false;
            }
        }
    });

Xml

<EditText
        android:id="@+id/editText2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/password"
        android:imeOptions="actionGo|flagNoFullscreen"
        android:inputType="textPassword"
        android:maxLines="1" />

Volley - POST/GET parameters

In your Request class (that extends Request), override the getParams() method. You would do the same for headers, just override getHeaders().

If you look at PostWithBody class in TestRequest.java in Volley tests, you'll find an example. It goes something like this

public class LoginRequest extends Request<String> {

    // ... other methods go here

    private Map<String, String> mParams;

    public LoginRequest(String param1, String param2, Listener<String> listener, ErrorListener errorListener) {
        super(Method.POST, "http://test.url", errorListener);
        mListener = listener;
        mParams = new HashMap<String, String>();
        mParams.put("paramOne", param1);
        mParams.put("paramTwo", param2);

    }

    @Override
    public Map<String, String> getParams() {
        return mParams;
    }
}

Evan Charlton was kind enough to make a quick example project to show us how to use volley. https://github.com/evancharlton/folly/

Find a string by searching all tables in SQL Server Management Studio 2008

A bit late but hopefully useful.

Why not try some of the third party tools that can be integrated into SSMS.

I’ve worked with ApexSQL Search (100% free) with good success for both schema and data search and there is also SSMS tools pack that has this feature (not free for SQL 2012 but quite affordable).

Stored procedure above is really great; it’s just that this is way more convenient in my opinion. Also, it would require some slight modifications if you want to search for datetime columns or GUID columns and such…

Having a UITextField in a UITableViewCell

This should not be difficult. When creating a cell for your table, add a UITextField object to the cell's content view

UITextField *txtField = [[UITextField alloc] initWithFrame....]
...
[cell.contentView addSubview:txtField]

Set the delegate of the UITextField as self (ie your viewcontroller) Give a tag to the text field so you can identify which textfield was edited in your delegate methods. The keyboard should pop up when the user taps the text field. I got it working like this. Hope it helps.

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

Enter the command to start up the server in that directory: py -3.7 -m http.server

Python vs Bash - In which kind of tasks each one outruns the other performance-wise?

Generally, bash works better than python only in those environments where python is not available. :)

Seriously, I have to deal with both languages daily, and will take python instantly over bash if given the choice. Alas, I am forced to use bash on certain "small" platforms because someone has (mistakenly, IMHO) decided that python is "too large" to fit.

While it is true that bash might be faster than python for some select tasks, it can never be as quick to develop with, or as easy to maintain (at least after you get past 10 lines of code or so). Bash's sole strong point wrt python or ruby or lua, etc., is its ubiquity.

How to override trait function and call it from the overridden function?

If the class implements the method directly, it will not use the traits version. Perhaps what you are thinking of is:

trait A {
    function calc($v) {
        return $v+1;
    }
}

class MyClass {
    function calc($v) {
        return $v+2;
    }
}

class MyChildClass extends MyClass{
}

class MyTraitChildClass extends MyClass{
    use A;
}

print (new MyChildClass())->calc(2); // will print 4

print (new MyTraitChildClass())->calc(2); // will print 3

Because the child classes do not implement the method directly, they will first use that of the trait if there otherwise use that of the parent class.

If you want, the trait can use method in the parent class (assuming you know the method would be there) e.g.

trait A {
    function calc($v) {
        return parent::calc($v*3);
    }
}
// .... other code from above
print (new MyTraitChildClass())->calc(2); // will print 8 (2*3 + 2)

You can also provide for ways to override, but still access the trait method as follows:

trait A {
    function trait_calc($v) {
        return $v*3;
    }
}

class MyClass {
    function calc($v) {
        return $v+2;
    }
}


class MyTraitChildClass extends MyClass{
    use A {
      A::trait_calc as calc;
    }
}


class MySecondTraitChildClass extends MyClass{
    use A {
      A::trait_calc as calc;
    }

    public function calc($v) {
      return $this->trait_calc($v)+.5;
    }
}


print (new MyTraitChildClass())->calc(2); // will print 6
echo "\n";
print (new MySecondTraitChildClass())->calc(2); // will print 6.5

You can see it work at http://sandbox.onlinephpfunctions.com/code/e53f6e8f9834aea5e038aec4766ac7e1c19cc2b5

How can I calculate the number of years between two dates?

getYears(date1, date2) {
let years = new Date(date1).getFullYear() - new Date(date2).getFullYear();
let month = new Date(date1).getMonth() - new Date(date2).getMonth();
let dateDiff = new Date(date1).getDay() - new Date(date2).getDay();
if (dateDiff < 0) {
    month -= 1;
}
if (month < 0) {
    years -= 1;
}
return years;
}

How can I clear or empty a StringBuilder?

If you look at the source code for a StringBuilder or StringBuffer the setLength() call just resets an index value for the character array. IMHO using the setLength method will always be faster than a new allocation. They should have named the method 'clear' or 'reset' so it would be clearer.

How do I convert array of Objects into one Object in JavaScript?

Use lodash!

const obj = _.keyBy(arrayOfObjects, 'keyName')

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

Do this :

<script type="text/javascript">
function showDetails(username)
{
   window.location = '/player_detail?username='+username;
}
</script>

<input type="button" name="theButton" value="Detail" onclick="showDetails('username');">

Android: How do bluetooth UUIDs work?

To sum up: UUid is used to uniquely identify applications. Each application has a unique UUid

So, use the same UUid for each device

Can't resolve module (not found) in React.js

There is a better way you can handle the import of modules in your React App. Consider doing this:

Add a jsconfig.json file to your base folder. That is the same folder containing your package.json. Next define your base URL imports in it:

//jsconfig.json
{
  "compilerOptions": {
    "baseUrl": "./src"
  }
}

Now rather than calling ../../ you can easily do this instead:

import navBar from 'components/header/navBar'
import 'css/header.css'

Notice that 'components/' is different from '../components/'

It's neater this way.

But if you want to import files in the same directory you can do this also:

import logo from './logo.svg'

How to input a regex in string.replace?

I would go like this (regex explained in comments):

import re

# If you need to use the regex more than once it is suggested to compile it.
pattern = re.compile(r"</{0,}\[\d+>")

# <\/{0,}\[\d+>
# 
# Match the character “<” literally «<»
# Match the character “/” literally «\/{0,}»
#    Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «{0,}»
# Match the character “[” literally «\[»
# Match a single digit 0..9 «\d+»
#    Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
# Match the character “>” literally «>»

subject = """this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>. 
and there are many other lines in the txt files
with<[3> such tags </[3>"""

result = pattern.sub("", subject)

print(result)

If you want to learn more about regex I recomend to read Regular Expressions Cookbook by Jan Goyvaerts and Steven Levithan.

When correctly use Task.Run and when just async-await

One issue with your ContentLoader is that internally it operates sequentially. A better pattern is to parallelize the work and then sychronize at the end, so we get

public class PageViewModel : IHandle<SomeMessage>
{
   ...

   public async void Handle(SomeMessage message)
   {
      ShowLoadingAnimation();

      // makes UI very laggy, but still not dead
      await this.contentLoader.LoadContentAsync(); 

      HideLoadingAnimation();   
   }
}

public class ContentLoader 
{
    public async Task LoadContentAsync()
    {
        var tasks = new List<Task>();
        tasks.Add(DoCpuBoundWorkAsync());
        tasks.Add(DoIoBoundWorkAsync());
        tasks.Add(DoCpuBoundWorkAsync());
        tasks.Add(DoSomeOtherWorkAsync());

        await Task.WhenAll(tasks).ConfigureAwait(false);
    }
}

Obviously, this doesn't work if any of the tasks require data from other earlier tasks, but should give you better overall throughput for most scenarios.

XML Error: Extra content at the end of the document

You need a root node

<?xml version="1.0" encoding="ISO-8859-1"?>    
<documents>
    <document>
        <name>Sample Document</name>
        <type>document</type>
        <url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&amp;titletype=Title&amp;fontsize=9&amp;fontface=Arial&amp;spacing=1.0&amp;text=&amp;wordcount3=0</url>
    </document>

    <document>
        <name>Sample</name>
        <type>document</type>
        <url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&amp;titletype=Title&amp;fontsize=9&amp;fontface=Arial&amp;spacing=1.0&amp;text=&amp;</url>
    </document>
</documents>

How do I add one month to current date in Java?

public class StringSplit {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        date(5, 3);
        date(5, 4);
    }

    public static String date(int month, int week) {
        LocalDate futureDate = LocalDate.now().plusMonths(month).plusWeeks(week);
        String Fudate = futureDate.toString();
        String[] arr = Fudate.split("-", 3);
        String a1 = arr[0];
        String a2 = arr[1];
        String a3 = arr[2];
        String date = a3 + "/" + a2 + "/" + a1;
        System.out.println(date);
        return date;
    }
}

Output:

10/03/2020
17/03/2020

Basic example for sharing text or image with UIActivityViewController in Swift

UIActivityViewController Example Project

Set up your storyboard with two buttons and hook them up to your view controller (see code below).

enter image description here

Add an image to your Assets.xcassets. I called mine "lion".

enter image description here

Code

import UIKit
class ViewController: UIViewController {

    // share text
    @IBAction func shareTextButton(_ sender: UIButton) {

        // text to share
        let text = "This is some text that I want to share."

        // set up activity view controller
        let textToShare = [ text ]
        let activityViewController = UIActivityViewController(activityItems: textToShare, applicationActivities: nil)
        activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash

        // exclude some activity types from the list (optional)
        activityViewController.excludedActivityTypes = [ UIActivityType.airDrop, UIActivityType.postToFacebook ]

        // present the view controller
        self.present(activityViewController, animated: true, completion: nil)

    }

    // share image
    @IBAction func shareImageButton(_ sender: UIButton) {

        // image to share
        let image = UIImage(named: "Image")

        // set up activity view controller
        let imageToShare = [ image! ]
        let activityViewController = UIActivityViewController(activityItems: imageToShare, applicationActivities: nil)
        activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash

        // exclude some activity types from the list (optional)
        activityViewController.excludedActivityTypes = [ UIActivityType.airDrop, UIActivityType.postToFacebook ]

        // present the view controller
        self.present(activityViewController, animated: true, completion: nil)
    }

}

Result

Clicking "Share some text" gives result on the left and clicking "Share an image" gives the result on the right.

enter image description here

Notes

  • I retested this with iOS 11 and Swift 4. I had to run it a couple times in the simulator before it worked because it was timing out. This may be because my computer is slow.
  • If you wish to hide some of these choices, you can do that with excludedActivityTypes as shown in the code above.
  • Not including the popoverPresentationController?.sourceView line will cause your app to crash when run on an iPad.
  • This does not allow you to share text or images to other apps. You probably want UIDocumentInteractionController for that.

See also

How do you overcome the HTML form nesting limitation?

can you have the forms side by side on the page, but not nested. then use CSS to make all the buttons line up pretty?

<form method="post" action="delete_processing_page">
   <input type="hidden" name="id" value="foo" />
   <input type="submit" value="delete" class="css_makes_me_pretty" />
</form>

<form method="post" action="add_edit_processing_page">
   <input type="text" name="foo1"  />
   <input type="text" name="foo2"  />
   <input type="text" name="foo3"  />
   ...
   <input type="submit" value="post/edit" class="css_makes_me_pretty" />
</form>

.jar error - could not find or load main class

Had this problem couldn't find the answer so i went looking on other threads, I found that i was making my app with 1.8 but for some reason my jre was out dated even though i remember updating it. I downloaded the lastes jre 8 and the jar file runs perfectly. Hope this helps.

How do I check if the Java JDK is installed on Mac?

Type in a terminal:

which javac

It should show you something like

/usr/bin/javac

403 Forbidden error when making an ajax Post request in Django framework

With SSL/https and with CSRF_COOKIE_HTTPONLY = False, I still don't have csrftoken in the cookie, either using the getCookie(name) function proposed in django Doc or the jquery.cookie.js proposed by fivef.

Wtower summary is perfect and I thought it would work after removing CSRF_COOKIE_HTTPONLY from settings.py but it does'nt in https!

Why csrftoken is not visible in document.cookie???

Instead of getting

"django_language=fr; csrftoken=rDrGI5cp98MnooPIsygWIF76vuYTkDIt"

I get only

"django_language=fr"

WHY? Like SSL/https removes X-CSRFToken from headers I thought it was due to the proxy header params of Nginx but apparently not... Any idea?

Unlike django doc Notes, it seems impossible to work with csrf_token in cookies with https. The only way to pass csrftoken is through the DOM by using {% csrf_token %} in html and get it in jQuery by using

var csrftoken = $('input[name="csrfmiddlewaretoken"]').val();

It is then possible to pass it to ajax either by header (xhr.setRequestHeader), either by params.

Shell Script: Execute a python program from within a shell script

Since the other posts say everything (and I stumbled upon this post while looking for the following).
Here is a way how to execute a python script from another python script:

Python 2:

execfile("somefile.py", global_vars, local_vars)

Python 3:

with open("somefile.py") as f:
    code = compile(f.read(), "somefile.py", 'exec')
    exec(code, global_vars, local_vars)

and you can supply args by providing some other sys.argv

How to check if an environment variable exists and get its value?

If you don't care about the difference between an unset variable or a variable with an empty value, you can use the default-value parameter expansion:

foo=${DEPLOY_ENV:-default}

If you do care about the difference, drop the colon

foo=${DEPLOY_ENV-default}

You can also use the -v operator to explicitly test if a parameter is set.

if [[ ! -v DEPLOY_ENV ]]; then
    echo "DEPLOY_ENV is not set"
elif [[ -z "$DEPLOY_ENV" ]]; then
    echo "DEPLOY_ENV is set to the empty string"
else
    echo "DEPLOY_ENV has the value: $DEPLOY_ENV"
fi

Squaring all elements in a list

Use numpy.

import numpy as np
b = list(np.array(a)**2)

How to design RESTful search/filtering?

As I'm using a laravel/php backend I tend to go with something like this:

/resource?filters[status_id]=1&filters[city]=Sydney&page=2&include=relatedResource

PHP automatically turns [] params into an array, so in this example I'll end up with a $filter variable that holds an array/object of filters, along with a page and any related resources I want eager loaded.

If you use another language, this might still be a good convention and you can create a parser to convert [] to an array.

Setting attribute disabled on a SPAN element does not prevent click events

Try unbinding the event.

$("span").click(function(){
alert($(this).text());
    $("span").not($(this)).unbind('click');
});

Here is the fiddle

"An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP

I had a same issue. It was working fine on the local machine but it had issues on the server. I have changed the SMTP setting. It works fine for me.

If you're using GoDaddy Plesk Hosting, use the following SMTP details.

Host = relay-hosting.secureserver.net
Port = 25 

How to join a slice of strings into a single string?

This is still relevant in 2018.

To String

import strings
stringFiles := strings.Join(fileSlice[:], ",")

Back to Slice again

import strings
fileSlice := strings.Split(stringFiles, ",")

Enable UTF-8 encoding for JavaScript

just add your script like this:

<script src="/js/intlTelInput.min.js" charset="utf-8"></script>

How to add 10 minutes to my (String) time?

Something like this

 String myTime = "14:10";
 SimpleDateFormat df = new SimpleDateFormat("HH:mm");
 Date d = df.parse(myTime); 
 Calendar cal = Calendar.getInstance();
 cal.setTime(d);
 cal.add(Calendar.MINUTE, 10);
 String newTime = df.format(cal.getTime());

As a fair warning there might be some problems if daylight savings time is involved in this 10 minute period.

How to get the current TimeStamp?

Since Qt 5.8, we now have QDateTime::currentSecsSinceEpoch() to deliver the seconds directly, a.k.a. as real Unix timestamp. So, no need to divide the result by 1000 to get seconds anymore.

Credits: also posted as comment to this answer. However, I think it is easier to find if it is a separate answer.

Get path from open file in Python

You can get it like this also.

filepath = os.path.abspath(f.name)

manage.py runserver

I was struggling with the same problem and found one solution. I guess it can help you. when you run python manage.py runserver, it will take 127.0.0.1 as default ip address and 8000. 127.0.0.0 is the same as localhost which can be accessed locally. to access it from cross origin you need to run it on your system ip or 0.0.0.0. 0.0.0.0 can be accessed from any origin in the network. for port number, you need to set inbound and outbound policy of your system if you want to use your own port number not the default one.

To do this you need to run server with command python manage.py runserver 0.0.0.0:<your port> as mentioned above

or, set a default ip and port in your python environment. For this see my answer on django change default runserver port

Enjoy coding .....

How can I use Helvetica Neue Condensed Bold in CSS?

I had the same problem and trouble getting it to work on all browsers.

So this is the best font stack for Helvetica Neue Condensed Bold I could find:

font-family: "HelveticaNeue-CondensedBold", "HelveticaNeueBoldCondensed", "HelveticaNeue-Bold-Condensed", "Helvetica Neue Bold Condensed", "HelveticaNeueBold", "HelveticaNeue-Bold", "Helvetica Neue Bold", "HelveticaNeue", "Helvetica Neue", 'TeXGyreHerosCnBold', "Helvetica", "Tahoma", "Geneva", "Arial Narrow", "Arial", sans-serif; font-weight:600; font-stretch:condensed;

Even more stacks to find at:

http://rachaelmoore.name/posts/design/css/web-safe-helvetica-font-stack/

fcntl substitute on Windows

The substitute of fcntl on windows are win32api calls. The usage is completely different. It is not some switch you can just flip.

In other words, porting a fcntl-heavy-user module to windows is not trivial. It requires you to analyze what exactly each fcntl call does and then find the equivalent win32api code, if any.

There's also the possibility that some code using fcntl has no windows equivalent, which would require you to change the module api and maybe the structure/paradigm of the program using the module you're porting.

If you provide more details about the fcntl calls people can find windows equivalents.

How to convert a JSON string to a Map<String, String> with Jackson JSON

just wanted to give a Kotlin answer

val propertyMap = objectMapper.readValue<Map<String,String>>(properties, object : TypeReference<Map<String, String>>() {})

What does double question mark (??) operator mean in PHP

It's the "null coalescing operator", added in php 7.0. The definition of how it works is:

It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

So it's actually just isset() in a handy operator.

Those two are equivalent1:

$foo = $bar ?? 'something';
$foo = isset($bar) ? $bar : 'something';

Documentation: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce

In the list of new PHP7 features: http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op

And original RFC https://wiki.php.net/rfc/isset_ternary


EDIT: As this answer gets a lot of views, little clarification:

1There is a difference: In case of ??, the first expression is evaluated only once, as opposed to ? :, where the expression is first evaluated in the condition section, then the second time in the "answer" section.

Limiting the number of characters per line with CSS

Another approach to this would put a span element with a display:block style inside the p element each time you need the content to break. It would only be useful when your p content is static.

<p>this is a not-dynamic text and I want to put<span style="display:block">the following words in the next line</span>and these other words in a third one</p>

It would output:

This is a not-dynamic text and I want to put

the following words in the next line

and these others in a third one

This allows you to change your text line-breaks in different viewports without JS.

Tar a directory, but don't store full absolute paths in the archive

The following command will create a root directory "." and put all the files from the specified directory into it.

tar -cjf site1.tar.bz2 -C /var/www/site1 .

If you want to put all files in root of the tar file, @chinthaka is right. Just cd in to the directory and do:

tar -cjf target_path/file.tar.gz *

This will put all the files in the cwd to the tar file as root files.

How to convert a DataFrame back to normal RDD in pyspark?

Use the method .rdd like this:

rdd = df.rdd

How do I get the SelectedItem or SelectedIndex of ListView in vb.net?

Private Sub ListView1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListView1.Click
        Dim tt As String
        tt = ListView1.SelectedItems.Item(0).SubItems(1).Text
        TextBox1.Text = tt.ToString
End Sub

Why I am getting Cannot pass parameter 2 by reference error when I am using bindParam with a constant value?

Try This.

$stmt->bindValue(':v1', null, PDO::PARAM_NULL); // --> insert null

How to remove the default arrow icon from a dropdown list (select element)?

there's a library called DropKick.js that replaces the normal select dropdowns with HTML/CSS so you can fully style and control them with javascript. http://dropkickjs.com/

'module' object has no attribute 'DataFrame'

The most likely explanation is that either a file called 'pandas.py' is in the same directory as your script, or that another variable called 'pd' is used in your program.

How to save all console output to file in R?

You have to sink "output" and "message" separately (the sink function only looks at the first element of type)

Now if you want the input to be logged too, then put it in a script:

script.R

1:5 + 1:3   # prints and gives a warning
stop("foo") # an error

And at the prompt:

con <- file("test.log")
sink(con, append=TRUE)
sink(con, append=TRUE, type="message")

# This will echo all input and not truncate 150+ character lines...
source("script.R", echo=TRUE, max.deparse.length=10000)

# Restore output to console
sink() 
sink(type="message")

# And look at the log...
cat(readLines("test.log"), sep="\n")

Inserting data to table (mysqli insert)

Warning: Never ever refer to w3schools for learning purposes. They have so many mistakes in their tutorials.

According to the mysqli_query documentation, the first parameter must be a connection string:

$link = mysqli_connect("localhost","root","","web_table");

mysqli_query($link,"INSERT INTO web_formitem (`ID`, `formID`, `caption`, `key`, `sortorder`, `type`, `enabled`, `mandatory`, `data`)
VALUES (105, 7, 'Tip izdelka (6)', 'producttype_6', 42, 5, 1, 0, 0)") 
or die(mysqli_error($link));

Note: Add backticks ` for column names in your insert query as some of your column names are reserved words.

How can I undo a `git commit` locally and on a remote after `git push`

git reset HEAD~1 if you don't want your changes to be gone(unstaged changes). Change, commit and push again git push -f [origin] [branch]

Running multiple async tasks and waiting for them all to complete

There should be a more succinct solution than the accepted answer. It shouldn't take three steps to run multiple tasks simultaneously and get their results.

  1. Create tasks
  2. await Task.WhenAll(tasks)
  3. Get task results (e.g., task1.Result)

Here's a method that cuts this down to two steps:

    public async Task<Tuple<T1, T2>> WhenAllGeneric<T1, T2>(Task<T1> task1, Task<T2> task2)
    {
        await Task.WhenAll(task1, task2);
        return Tuple.Create(task1.Result, task2.Result);
    }

You can use it like this:

var taskResults = await Task.WhenAll(DoWorkAsync(), DoMoreWorkAsync());
var DoWorkResult = taskResults.Result.Item1;
var DoMoreWorkResult = taskResults.Result.Item2;

This removes the need for the temporary task variables. The problem with using this is that while it works for two tasks, you'd need to update it for three tasks, or any other number of tasks. Also it doesn't work well if one of the tasks doesn't return anything. Really, the .Net library should provide something that can do this

How to set the DefaultRoute to another Route in React Router

UPDATE : 2020

Instead of using Redirect, Simply add multiple route in the path

Example:

<Route exact path={["/","/defaultPath"]} component={searchDashboard} />

How to delete a folder in C++?

If you are using the Poco library, here is a portable way to delete a directory.

#include "Poco/File.h"
...
...
Poco::File fooDir("/path/to/your/dir");
fooDir.remove(true);

The remove function when called with "true" means recursively delete all files and sub directories in a directory.

PHP 5 disable strict standards error

All above solutions are correct. But, when we are talking about a normal PHP application, they have to included in every page, that it requires. A way to solve this, is through .htaccess at root folder. Just to hide the errors. [Put one of the followling lines in the file]

php_flag display_errors off

Or

php_value display_errors 0

Next, to set the error reporting

php_value error_reporting 30719

If you are wondering how the value 30719 came, E_ALL (32767), E_STRICT (2048) are actually constant that hold numeric value and (32767 - 2048 = 30719)

How do I make XAML DataGridColumns fill the entire DataGrid?

My 2 Cent ->

Very late to party

DataGrid -> Column -> Width="*" only work if DataGrid parent container has fix width.

example : i put the DataGrid in Grid -> Column whose width="Auto" then Width="*" in DataGrid does not work but if you set Grid -> Column Width="450" mean fixed then it work fine

Replace only text inside a div using jquery

If you actually know the text you are going to replace you could use

$('#one').contents(':contains("Hi I am text")')[0].nodeValue = '"Hi I am replace"';

http://jsfiddle.net/5rWwh/

Or

$('#one').contents(':not(*)')[1].nodeValue = '"Hi I am replace"';

$('#one').contents(':not(*)') selects non-element child nodes in this case text nodes and the second node is the one we want to replace.

http://jsfiddle.net/5rWwh/1/

iPhone Safari Web App opens links in new window

I prefer to open all links inside the standalone web app mode except ones that have target="_blank". Using jQuery, of course.

$(document).on('click', 'a', function(e) {
    if ($(this).attr('target') !== '_blank') {
        e.preventDefault();
        window.location = $(this).attr('href');
    }
});