Programs & Examples On #Msf

Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website

this issue was driving me insane until i found this post which said to do

brew upgrade python3 

(not using pycharm, using sublime)

Error when importing ssl in Python 3.7.4 on macOS 10.14.6

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

Even without looking at assembly, the most obvious reason is that /= 2 is probably optimized as >>=1 and many processors have a very quick shift operation. But even if a processor doesn't have a shift operation, the integer division is faster than floating point division.

Edit: your milage may vary on the "integer division is faster than floating point division" statement above. The comments below reveal that the modern processors have prioritized optimizing fp division over integer division. So if someone were looking for the most likely reason for the speedup which this thread's question asks about, then compiler optimizing /=2 as >>=1 would be the best 1st place to look.


On an unrelated note, if n is odd, the expression n*3+1 will always be even. So there is no need to check. You can change that branch to

{
   n = (n*3+1) >> 1;
   count += 2;
}

So the whole statement would then be

if (n & 1)
{
    n = (n*3 + 1) >> 1;
    count += 2;
}
else
{
    n >>= 1;
    ++count;
}

Extract Data from PDF and Add to Worksheet

You can open the PDF file and extract its contents using the Adobe library (which I believe you can download from Adobe as part of the SDK, but it comes with certain versions of Acrobat as well)

Make sure to add the Library to your references too (On my machine it is the Adobe Acrobat 10.0 Type Library, but not sure if that is the newest version)

Even with the Adobe library it is not trivial (you'll need to add your own error-trapping etc):

Function getTextFromPDF(ByVal strFilename As String) As String
   Dim objAVDoc As New AcroAVDoc
   Dim objPDDoc As New AcroPDDoc
   Dim objPage As AcroPDPage
   Dim objSelection As AcroPDTextSelect
   Dim objHighlight As AcroHiliteList
   Dim pageNum As Long
   Dim strText As String

   strText = ""
   If (objAvDoc.Open(strFilename, "") Then
      Set objPDDoc = objAVDoc.GetPDDoc
      For pageNum = 0 To objPDDoc.GetNumPages() - 1
         Set objPage = objPDDoc.AcquirePage(pageNum)
         Set objHighlight = New AcroHiliteList
         objHighlight.Add 0, 10000 ' Adjust this up if it's not getting all the text on the page
         Set objSelection = objPage.CreatePageHilite(objHighlight)

         If Not objSelection Is Nothing Then
            For tCount = 0 To objSelection.GetNumText - 1
               strText = strText & objSelection.GetText(tCount)
            Next tCount
         End If
      Next pageNum
      objAVDoc.Close 1
   End If

   getTextFromPDF = strText

End Function

What this does is essentially the same thing you are trying to do - only using Adobe's own library. It's going through the PDF one page at a time, highlighting all of the text on the page, then dropping it (one text element at a time) into a string.

Keep in mind what you get from this could be full of all kinds of non-printing characters (line feeds, newlines, etc) that could even end up in the middle of what look like contiguous blocks of text, so you may need additional code to clean it up before you can use it.

Hope that helps!

How to set "style=display:none;" using jQuery's attr method?

Based on the comment we are removing one property from style attribute.

Here this was not affect, but when more property are used within the style it helpful.

$('#msform').css('display', '')

After this we use

$("#msform").show();

Name [jdbc/mydb] is not bound in this Context

you put resource-ref in the description tag in web.xml

auto refresh for every 5 mins

Install an interval:

<script type="text/javascript">    
    setInterval(page_refresh, 5*60000); //NOTE: period is passed in milliseconds
</script>

Invalid character in identifier

The error SyntaxError: invalid character in identifier means you have some character in the middle of a variable name, function, etc. that's not a letter, number, or underscore. The actual error message will look something like this:

  File "invalchar.py", line 23
    values =  list(analysis.values ())
                ^
SyntaxError: invalid character in identifier

That tells you what the actual problem is, so you don't have to guess "where do I have an invalid character"? Well, if you look at that line, you've got a bunch of non-printing garbage characters in there. Take them out, and you'll get past this.

If you want to know what the actual garbage characters are, I copied the offending line from your code and pasted it into a string in a Python interpreter:

>>> s='    values ??=  list(analysis.values ??())'
>>> s
'    values \u200b\u200b=  list(analysis.values \u200b\u200b())'

So, that's \u200b, or ZERO WIDTH SPACE. That explains why you can't see it on the page. Most commonly, you get these because you've copied some formatted (not plain-text) code off a site like StackOverflow or a wiki, or out of a PDF file.

If your editor doesn't give you a way to find and fix those characters, just delete and retype the line.

Of course you've also got at least two IndentationErrors from not indenting things, at least one more SyntaxError from stay spaces (like = = instead of ==) or underscores turned into spaces (like analysis results instead of analysis_results).

The question is, how did you get your code into this state? If you're using something like Microsoft Word as a code editor, that's your problem. Use a text editor. If not… well, whatever the root problem is that caused you to end up with these garbage characters, broken indentation, and extra spaces, fix that, before you try to fix your code.

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

I got this problem after moving a project and deleting it's packages folder. Nuget was showning that MSTest.TestAdapter and MSTest.TestFramework v 1.3.2 was installed. The fix seemed to be to open VS as administrator and build After that I was able to re-open and build without having admin priviledge.

batch file to check 64bit or 32bit OS

*** Start ***

@echo off

Set RegQry=HKLM\Hardware\Description\System\CentralProcessor\0

REG.exe Query %RegQry% > checkOS.txt

Find /i "x86" < CheckOS.txt > StringCheck.txt

If %ERRORLEVEL% == 0 (
    Echo "This is 32 Bit Operating system"
) ELSE (
    Echo "This is 64 Bit Operating System"
)

*** End ***

reference http://support.microsoft.com/kb/556009

How to drop all tables in a SQL Server database?

You can also delete all tables from database using only MSSMS UI tools (without using SQL script). Sometimes this way can be more comfortable (especially if it is performed occasionally)

I do this step by step as follows:

  1. Select 'Tables' on the database tree (Object Explorer)
  2. Press F7 to open Object Explorer Details view
  3. In this view select tables which have to be deleted (in this case all of them)
  4. Keep pressing Delete until all tables have been deleted (you repeat it as many times as amount of errors due to key constraints/dependencies)

ViewPager and fragments — what's the right way to store fragment's state?

When the FragmentPagerAdapter adds a fragment to the FragmentManager, it uses a special tag based on the particular position that the fragment will be placed. FragmentPagerAdapter.getItem(int position) is only called when a fragment for that position does not exist. After rotating, Android will notice that it already created/saved a fragment for this particular position and so it simply tries to reconnect with it with FragmentManager.findFragmentByTag(), instead of creating a new one. All of this comes free when using the FragmentPagerAdapter and is why it is usual to have your fragment initialisation code inside the getItem(int) method.

Even if we were not using a FragmentPagerAdapter, it is not a good idea to create a new fragment every single time in Activity.onCreate(Bundle). As you have noticed, when a fragment is added to the FragmentManager, it will be recreated for you after rotating and there is no need to add it again. Doing so is a common cause of errors when working with fragments.

A usual approach when working with fragments is this:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ...

    CustomFragment fragment;
    if (savedInstanceState != null) {
        fragment = (CustomFragment) getSupportFragmentManager().findFragmentByTag("customtag");
    } else {
        fragment = new CustomFragment();
        getSupportFragmentManager().beginTransaction().add(R.id.container, fragment, "customtag").commit(); 
    }

    ...

}

When using a FragmentPagerAdapter, we relinquish fragment management to the adapter, and do not have to perform the above steps. By default, it will only preload one Fragment in front and behind the current position (although it does not destroy them unless you are using FragmentStatePagerAdapter). This is controlled by ViewPager.setOffscreenPageLimit(int). Because of this, directly calling methods on the fragments outside of the adapter is not guaranteed to be valid, because they may not even be alive.

To cut a long story short, your solution to use putFragment to be able to get a reference afterwards is not so crazy, and not so unlike the normal way to use fragments anyway (above). It is difficult to obtain a reference otherwise because the fragment is added by the adapter, and not you personally. Just make sure that the offscreenPageLimit is high enough to load your desired fragments at all times, since you rely on it being present. This bypasses lazy loading capabilities of the ViewPager, but seems to be what you desire for your application.

Another approach is to override FragmentPageAdapter.instantiateItem(View, int) and save a reference to the fragment returned from the super call before returning it (it has the logic to find the fragment, if already present).

For a fuller picture, have a look at some of the source of FragmentPagerAdapter (short) and ViewPager (long).

What is the most efficient way to loop through dataframes with pandas?

Like what has been mentioned before, pandas object is most efficient when process the whole array at once. However for those who really need to loop through a pandas DataFrame to perform something, like me, I found at least three ways to do it. I have done a short test to see which one of the three is the least time consuming.

t = pd.DataFrame({'a': range(0, 10000), 'b': range(10000, 20000)})
B = []
C = []
A = time.time()
for i,r in t.iterrows():
    C.append((r['a'], r['b']))
B.append(time.time()-A)

C = []
A = time.time()
for ir in t.itertuples():
    C.append((ir[1], ir[2]))    
B.append(time.time()-A)

C = []
A = time.time()
for r in zip(t['a'], t['b']):
    C.append((r[0], r[1]))
B.append(time.time()-A)

print B

Result:

[0.5639059543609619, 0.017839908599853516, 0.005645036697387695]

This is probably not the best way to measure the time consumption but it's quick for me.

Here are some pros and cons IMHO:

  • .iterrows(): return index and row items in separate variables, but significantly slower
  • .itertuples(): faster than .iterrows(), but return index together with row items, ir[0] is the index
  • zip: quickest, but no access to index of the row

EDIT 2020/11/10

For what it is worth, here is an updated benchmark with some other alternatives (perf with MacBookPro 2,4 GHz Intel Core i9 8 cores 32 Go 2667 MHz DDR4)

import sys
import tqdm
import time
import pandas as pd

B = []
t = pd.DataFrame({'a': range(0, 10000), 'b': range(10000, 20000)})
for _ in tqdm.tqdm(range(10)):
    C = []
    A = time.time()
    for i,r in t.iterrows():
        C.append((r['a'], r['b']))
    B.append({"method": "iterrows", "time": time.time()-A})

    C = []
    A = time.time()
    for ir in t.itertuples():
        C.append((ir[1], ir[2]))
    B.append({"method": "itertuples", "time": time.time()-A})

    C = []
    A = time.time()
    for r in zip(t['a'], t['b']):
        C.append((r[0], r[1]))
    B.append({"method": "zip", "time": time.time()-A})

    C = []
    A = time.time()
    for r in zip(*t.to_dict("list").values()):
        C.append((r[0], r[1]))
    B.append({"method": "zip + to_dict('list')", "time": time.time()-A})

    C = []
    A = time.time()
    for r in t.to_dict("records"):
        C.append((r["a"], r["b"]))
    B.append({"method": "to_dict('records')", "time": time.time()-A})

    A = time.time()
    t.agg(tuple, axis=1).tolist()
    B.append({"method": "agg", "time": time.time()-A})

    A = time.time()
    t.apply(tuple, axis=1).tolist()
    B.append({"method": "apply", "time": time.time()-A})

print(f'Python {sys.version} on {sys.platform}')
print(f"Pandas version {pd.__version__}")
print(
    pd.DataFrame(B).groupby("method").agg(["mean", "std"]).xs("time", axis=1).sort_values("mean")
)

## Output

Python 3.7.9 (default, Oct 13 2020, 10:58:24) 
[Clang 12.0.0 (clang-1200.0.32.2)] on darwin
Pandas version 1.1.4
                           mean       std
method                                   
zip + to_dict('list')  0.002353  0.000168
zip                    0.003381  0.000250
itertuples             0.007659  0.000728
to_dict('records')     0.025838  0.001458
agg                    0.066391  0.007044
apply                  0.067753  0.006997
iterrows               0.647215  0.019600

proper hibernate annotation for byte[]

I'm using the Hibernate 4.2.7.SP1 with Postgres 9.3 and following works for me:

@Entity
public class ConfigAttribute {
  @Lob
  public byte[] getValueBuffer() {
    return m_valueBuffer;
  }
}

as Oracle has no trouble with that, and for Postgres I'm using custom dialect:

public class PostgreSQLDialectCustom extends PostgreSQL82Dialect {

    @Override
    public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) {
    if (sqlTypeDescriptor.getSqlType() == java.sql.Types.BLOB) {
      return BinaryTypeDescriptor.INSTANCE;
    }
    return super.remapSqlTypeDescriptor(sqlTypeDescriptor);
  }
}

the advantage of this solution I consider, that I can keep hibernate jars untouched.

For more Postgres/Oracle compatibility issues with Hibernate, see my blog post.

Doctrine2: Best way to handle many-to-many with extra columns in reference table

The solution is in the documentation of Doctrine. In the FAQ you can see this :

http://docs.doctrine-project.org/en/2.1/reference/faq.html#how-can-i-add-columns-to-a-many-to-many-table

And the tutorial is here :

http://docs.doctrine-project.org/en/2.1/tutorials/composite-primary-keys.html

So you do not anymore do a manyToMany but you have to create an extra Entity and put manyToOne to your two entities.

ADD for @f00bar comment :

it's simple, you have just to to do something like this :

Article  1--N  ArticleTag  N--1  Tag

So you create an entity ArticleTag

ArticleTag:
  type: entity
  id:
    id:
      type: integer
      generator:
        strategy: AUTO
  manyToOne:
    article:
      targetEntity: Article
      inversedBy: articleTags
  fields: 
    # your extra fields here
  manyToOne:
    tag:
      targetEntity: Tag
      inversedBy: articleTags

I hope it helps

How can I use Oracle SQL developer to run stored procedures?

Not only is there a way to do this, there is more than one way to do this (which I concede is not very Pythonic, but then SQL*Developer is written in Java ).

I have a procedure with this signature: get_maxsal_by_dept( dno number, maxsal out number).

I highlight it in the SQL*Developer Object Navigator, invoke the right-click menu and chose Run. (I could use ctrl+F11.) This spawns a pop-up window with a test harness. (Note: If the stored procedure lives in a package, you'll need to right-click the package, not the icon below the package containing the procedure's name; you will then select the sproc from the package's "Target" list when the test harness appears.) In this example, the test harness will display the following:

DECLARE
  DNO NUMBER;
  MAXSAL NUMBER;
BEGIN
  DNO := NULL;

  GET_MAXSAL_BY_DEPT(
    DNO => DNO,
    MAXSAL => MAXSAL
  );
  DBMS_OUTPUT.PUT_LINE('MAXSAL = ' || MAXSAL);
END;

I set the variable DNO to 50 and press okay. In the Running - Log pane (bottom right-hand corner unless you've closed/moved/hidden it) I can see the following output:

Connecting to the database apc.
MAXSAL = 4500
Process exited.
Disconnecting from the database apc. 

To be fair the runner is less friendly for functions which return a Ref Cursor, like this one: get_emps_by_dept (dno number) return sys_refcursor.

DECLARE
  DNO NUMBER;
  v_Return sys_refcursor;
BEGIN
  DNO := 50;

  v_Return := GET_EMPS_BY_DEPT(
    DNO => DNO
  );
  -- Modify the code to output the variable
  -- DBMS_OUTPUT.PUT_LINE('v_Return = ' || v_Return);
END;

However, at least it offers the chance to save any changes to file, so we can retain our investment in tweaking the harness...

DECLARE
  DNO NUMBER;
  v_Return sys_refcursor;
  v_rec emp%rowtype;
BEGIN
  DNO := 50;

  v_Return := GET_EMPS_BY_DEPT(
    DNO => DNO
  );

  loop
    fetch v_Return into v_rec;
    exit when v_Return%notfound;
    DBMS_OUTPUT.PUT_LINE('name = ' || v_rec.ename);
  end loop;
END;

The output from the same location:

Connecting to the database apc.
name = TRICHLER
name = VERREYNNE
name = FEUERSTEIN
name = PODER
Process exited.
Disconnecting from the database apc. 

Alternatively we can use the old SQLPLus commands in the SQLDeveloper worksheet:

var rc refcursor 
exec :rc := get_emps_by_dept(30) 
print rc

In that case the output appears in Script Output pane (default location is the tab to the right of the Results tab).

The very earliest versions of the IDE did not support much in the way of SQL*Plus. However, all of the above commands have been supported since 1.2.1. Refer to the matrix in the online documentation for more info.


"When I type just var rc refcursor; and select it and run it, I get this error (GUI):"

There is a feature - or a bug - in the way the worksheet interprets SQLPlus commands. It presumes SQLPlus commands are part of a script. So, if we enter a line of SQL*Plus, say var rc refcursor and click Execute Statement (or F9 ) the worksheet hurls ORA-900 because that is not an executable statement i.e. it's not SQL . What we need to do is click Run Script (or F5 ), even for a single line of SQL*Plus.


"I am so close ... please help."

You program is a procedure with a signature of five mandatory parameters. You are getting an error because you are calling it as a function, and with just the one parameter:

exec :rc := get_account(1)

What you need is something like the following. I have used the named notation for clarity.

var ret1 number
var tran_cnt number
var msg_cnt number
var rc refcursor

exec :tran_cnt := 0
exec :msg_cnt := 123

exec get_account (Vret_val => :ret1, 
                  Vtran_count => :tran_cnt, 
                  Vmessage_count => :msg_cnt, 
                  Vaccount_id   => 1,
                  rc1 => :rc )

print tran_count 
print rc

That is, you need a variable for each OUT or IN OUT parameter. IN parameters can be passed as literals. The first two EXEC statements assign values to a couple of the IN OUT parameters. The third EXEC calls the procedure. Procedures don't return a value (unlike functions) so we don't use an assignment syntax. Lastly this script displays the value of a couple of the variables mapped to OUT parameters.

How do I list all tables in all databases in SQL Server in a single result set?

I think the common approach is to SELECT * FROM INFORMATION_SCHEMA.TABLES for each database using sp_MSforeachdb

I created a snippet in VS Code that I think it might be helpful.

Query

IF OBJECT_ID('tempdb..#alltables', 'U') IS NOT NULL DROP TABLE #alltables;
SELECT * INTO #alltables FROM INFORMATION_SCHEMA.TABLES;
TRUNCATE TABLE #alltables;
EXEC sp_MSforeachdb 'USE [?];INSERT INTO #alltables SELECT * from INFORMATION_SCHEMA.TABLES';
SELECT * FROM #alltables WHERE TABLE_NAME LIKE '%<TABLE_NAME_TO_SEARCH>%';
GO 

Snippet

{
    "List all tables": {
        "prefix": "sqlListTable",
        "body": [
            "IF OBJECT_ID('tempdb..#alltables', 'U') IS NOT NULL DROP TABLE #alltables;",
            "SELECT * INTO #alltables FROM INFORMATION_SCHEMA.TABLES;",
            "TRUNCATE TABLE #alltables;",
            "EXEC sp_MSforeachdb 'USE [?];INSERT INTO #alltables SELECT * from INFORMATION_SCHEMA.TABLES';",
            "SELECT * FROM #alltables WHERE TABLE_NAME LIKE '%$0%';",
            "GO"
        ]
    }
}

"Invalid JSON primitive" in Ajax processing

Just a guess what does the variable json contain after

var json = Sys.Serialization.JavaScriptSerializer.serialize(obj);?

If it is a valid json object like {'foo':'foovalue', 'bar':'barvalue'} then jQuery might not send it as json data but instead serialize it to foor=foovalue&bar=barvalue thus you get the error "Invalid JSON primitive: foo"

Try instead setting the data as string

$.ajax({
    ...
    data: "{'foo':'foovalue', 'bar':'barvalue'}", //note the additional quotation marks
    ...
})

This way jQuery should leave the data alone and send the string as is to the server which should allow ASP.NET to parse the json server side.

Add a property to a JavaScript object using a variable as the name?

With lodash, you can create new object like this _.set:

obj = _.set({}, key, val);

Or you can set to existing object like this:

var existingObj = { a: 1 };
_.set(existingObj, 'a', 5); // existingObj will be: { a: 5 }

You should take care if you want to use dot (".") in your path, because lodash can set hierarchy, for example:

_.set({}, "a.b.c", "d"); // { "a": { "b": { "c": "d" } } }

How can I get stock quotes using Google Finance API?

Here is an example that you can use. Havent got Google Finance yet, but Here is the Yahoo Example. You will need the HTMLAgilityPack , Which is awesome. Happy Symbol Hunting.

Call the procedure by using YahooStockRequest(string Symbols);

Where Symbols = a comma-delimited string of symbols, or just one symbol

public string YahooStockRequest(string Symbols,bool UseYahoo=true)
        {
            {
                string StockQuoteUrl = string.Empty;

                try
                {
                    // Use Yahoo finance service to download stock data from Yahoo
                    if (UseYahoo)
                    {
                        string YahooSymbolString = Symbols.Replace(",","+");
                        StockQuoteUrl = @"http://finance.yahoo.com/q?s=" + YahooSymbolString + "&ql=1";
                    }
                    else
                    {
                        //Going to Put Google Finance here when I Figure it out.
                    }

                    // Initialize a new WebRequest.
                    HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(StockQuoteUrl);
                    // Get the response from the Internet resource.
                    HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse();
                    // Read the body of the response from the server.

                    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                    string pageSource;
                    using (StreamReader sr = new StreamReader(webresp.GetResponseStream()))
                    {
                        pageSource = sr.ReadToEnd();
                    }
                    doc.LoadHtml(pageSource.ToString());
                    if (UseYahoo)
                    {
                        string Results=string.Empty;
                        //loop through each Symbol that you provided with a "," delimiter
                        foreach (string SplitSymbol in Symbols.Split(new char[] { ',' }))
                        {
                            Results+=SplitSymbol + " : " + doc.GetElementbyId("yfs_l10_" + SplitSymbol).InnerText + Environment.NewLine;
                        }
                        return (Results);
                    }
                    else
                    {
                        return (doc.GetElementbyId("ref_14135_l").InnerText);
                    }

                }
                catch (WebException Webex)
                {
                    return("SYSTEM ERROR DOWNLOADING SYMBOL: " + Webex.ToString());

                }

            }
        }

How does cookie based authentication work?

Cookie-Based Authentication

Cookies based Authentication works normally in these 4 steps-

  1. The user provides a username and password in the login form and clicks Log In.
  2. After the request is made, the server validate the user on the backend by querying in the database. If the request is valid, it will create a session by using the user information fetched from the database and store them, for each session a unique id called session Id is created ,by default session Id is will be given to client through the Browser.
  3. Browser will submit this session Id on each subsequent requests, the session ID is verified against the database, based on this session id website will identify the session belonging to which client and then give access the request.

  4. Once a user logs out of the app, the session is destroyed both client-side and server-side.

How to do date/time comparison

The following solved my problem of converting string into date

package main

import (
    "fmt"
    "time"
)

func main() {
    value  := "Thu, 05/19/11, 10:47PM"
    // Writing down the way the standard time would look like formatted our way
    layout := "Mon, 01/02/06, 03:04PM"
    t, _ := time.Parse(layout, value)
    fmt.Println(t)
}

// => "Thu May 19 22:47:00 +0000 2011"

Thanks to paul adam smith

What does the NS prefix mean?

NeXTSTEP or NeXTSTEP/Sun depending on who you are asking.

Sun had a fairly large investment in OpenStep for a while. Before Sun entered the picture most things in the foundation, even though it wasn't known as the foundation back then, was prefixed NX, for NeXT, and sometime just before Sun entered the picture everything was renamed to NS. The S most likely did not stand for Sun then but after Sun stepped in the general consensus was that it stood for Sun to honor their involvement.

I actually had a reference for this but I can't find it right now. I will update the post if/when I find it again.

Configuring Hibernate logging using Log4j XML config file?

You can configure your log4j file with the category tag like this (with a console appender for the example):

<appender name="console" class="org.apache.log4j.ConsoleAppender">
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d{yy-MM-dd HH:mm:ss} %p %c - %m%n" />
    </layout>
</appender>
<category name="org.hibernate">
    <priority value="WARN" />
</category>
<root>
    <priority value="INFO" />
    <appender-ref ref="console" />
</root>

So every warning, error or fatal message from hibernate will be displayed, nothing more. Also, your code and library code will be in info level (so info, warn, error and fatal)

To change log level of a library, just add a category, for example, to desactive spring info log:

<category name="org.springframework">
    <priority value="WARN" />
</category>

Or with another appender, break the additivity (additivity default value is true)

<category name="org.springframework" additivity="false">
    <priority value="WARN" />
    <appender-ref ref="anotherAppender" />
</category>

And if you don't want that hibernate log every query, set the hibernate property show_sql to false.

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

How to display items side-by-side without using tables?

Yes, divs and CSS are usually a better and easier way to place your HTML. There are many different ways to do this and it all depends on the context.

For instance, if you want to place an image to the right of your text, you could do it like so:

<p style="width: 500px;">
<img src="image.png" style="float: right;" />
This is some text
</p> 

And if you want to display multiple items side by side, float is also usually preferred.For example:

<div>
  <img src="image1.png" style="float: left;" />
  <img src="image2.png" style="float: left;" />
  <img src="image3.png" style="float: left;" />
</div>

Floating these images to the same side will have then laying next to each other for as long as you hava horizontal space.

Can a java file have more than one class?

In general, there should be one class per file. If you organise things that way, then when you search for a class, you know you only need to search for the file with that name.

The exception is when a class is best implemented using one or more small helper classes. Usually, the code is easiest to follow when those classes are present in the same file. For instance, you might need a small 'tuple' wrapper class to pass some data between method calls. Another example are 'task' classes implementing Runnable or Callable. They may be so small that they are best combined with the parent class creating and calling them.

HTML: How to make a submit button with text + image in it?

Here is an other example:

<button type="submit" name="submit" style="border: none; background-color: white">

How to use if statements in underscore.js templates?

To check for null values you could use _.isNull from official documentation

isNull_.isNull(object)

Returns true if the value of object is null.

_.isNull(null);
=> true
_.isNull(undefined);
=> false

Extracting .jar file with command line

In Ubuntu:

unzip file.jar -d dir_name_where_extracting

How to fire an event on class change using jQuery?

you can use something like this:

$(this).addClass('someClass');

$(Selector).trigger('ClassChanged')

$(otherSelector).bind('ClassChanged', data, function(){//stuff });

but otherwise, no, there's no predefined function to fire an event when a class changes.

Read more about triggers here

Read a zipped file as a pandas DataFrame

It seems you don't even have to specify the compression any more. The following snippet loads the data from filename.zip into df.

import pandas as pd
df = pd.read_csv('filename.zip')

(Of course you will need to specify separator, header, etc. if they are different from the defaults.)

Use of REPLACE in SQL Query for newline/ carriage return characters

There are probably embedded tabs (CHAR(9)) etc. as well. You can find out what other characters you need to replace (we have no idea what your goal is) with something like this:

DECLARE @var NVARCHAR(255), @i INT;

SET @i = 1;

SELECT @var = AccountType FROM dbo.Account
  WHERE AccountNumber = 200
  AND AccountType LIKE '%Daily%';

CREATE TABLE #x(i INT PRIMARY KEY, c NCHAR(1), a NCHAR(1));

WHILE @i <= LEN(@var)
BEGIN
  INSERT #x 
    SELECT SUBSTRING(@var, @i, 1), ASCII(SUBSTRING(@var, @i, 1));

  SET @i = @i + 1;
END

SELECT i,c,a FROM #x ORDER BY i;

You might also consider doing better cleansing of this data before it gets into your database. Cleaning it every time you need to search or display is not the best approach.

How to get coordinates of an svg element?

svg.selectAll("rect")
.attr('x',function(d,i){
    // get x coord
    console.log(this.getBBox().x, 'or', d3.select(this).attr('x'))
})
.attr('y',function(d,i){
    // get y coord
    console.log(this.getBBox().y)
})
.attr('dx',function(d,i){
    // get dx coord
    console.log(parseInt(d3.select(this).attr('dx')))
})

What is CMake equivalent of 'configure --prefix=DIR && make all install '?

Regarding Bruce Adams answer:

Your answer creates dangerous confusion. DESTDIR is intended for installs out of the root tree. It allows one to see what would be installed in the root tree if one did not specify DESTDIR. PREFIX is the base directory upon which the real installation is based.

For example, PREFIX=/usr/local indicates that the final destination of a package is /usr/local. Using DESTDIR=$HOME will install the files as if $HOME was the root (/). If, say DESTDIR, was /tmp/destdir, one could see what 'make install' would affect. In that spirit, DESTDIR should never affect the built objects.

A makefile segment to explain it:

install:
    cp program $DESTDIR$PREFIX/bin/program

Programs must assume that PREFIX is the base directory of the final (i.e. production) directory. The possibility of symlinking a program installed in DESTDIR=/something only means that the program does not access files based upon PREFIX as it would simply not work. cat(1) is a program that (in its simplest form) can run from anywhere. Here is an example that won't:

prog.pseudo.in:
    open("@prefix@/share/prog.db")
    ...

prog:
    sed -e "s/@prefix@/$PREFIX/" prog.pseudo.in > prog.pseudo
    compile prog.pseudo

install:
    cp prog $DESTDIR$PREFIX/bin/prog
    cp prog.db $DESTDIR$PREFIX/share/prog.db

If you tried to run prog from elsewhere than $PREFIX/bin/prog, prog.db would never be found as it is not in its expected location.

Finally, /etc/alternatives really does not work this way. There are symlinks to programs installed in the root tree (e.g. vi -> /usr/bin/nvi, vi -> /usr/bin/vim, etc.).

How do I generate a list with a specified increment step?

Executing seq(1, 10, 1) does what 1:10 does. You can change the last parameter of seq, i.e. by, to be the step of whatever size you like.

> #a vector of even numbers
> seq(0, 10, by=2) # Explicitly specifying "by" only to increase readability 
> [1]  0  2  4  6  8 10

Android Drawing Separator/Divider Line in Layout?

Adding this view; that draws a separator between your textviews

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="#000000" />

Detecting a long press with Android

When you mean user presses, do you mean a click? A click is when the user presses down and then immediately lifts up finger. Therefore it is encompassing two onTouch Events. You should save the use of onTouchEvent for stuff that happens on the initial touch or the after release.

Thus, you should be using onClickListener if it is a click.

Your answer is analogous: Use onLongClickListener.

Can't find out where does a node.js app running and can't kill it

You can kill all node processes using pkill node

or you can do a ps T to see all processes on this terminal
then you can kill a specific process ID doing a kill [processID] example: kill 24491

Additionally, you can do a ps -help to see all the available options

How do I load an HTML page in a <div> using JavaScript?

$("button").click(function() {
    $("#target_div").load("requesting_page_url.html");
});

or

document.getElementById("target_div").innerHTML='<object type="text/html" data="requesting_page_url.html"></object>';

Flutter: Trying to bottom-center an item in a Column, but it keeps left-aligning

Widget _bottom() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Expanded(
          child: Container(
            color: Colors.amberAccent,
            width: double.infinity,
            child: SingleChildScrollView(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: new List<int>.generate(50, (index) => index + 1)
                    .map((item) {
                  return Text(
                    item.toString(),
                    style: TextStyle(fontSize: 20),
                  );
                }).toList(),
              ),
            ),
          ),
        ),
        Container(
          color: Colors.blue,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                'BoTToM',
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 33),
              ),
            ],
          ),
        ),
      ],
    );
  }

how to download file in react js

React gives a security issue when using a tag with target="_blank".

I managed to get it working like that:

<a href={uploadedFileLink} target="_blank" rel="noopener noreferrer" download>
   <Button>
      <i className="fas fa-download"/>
      Download File
   </Button>
</a>

Django model "doesn't declare an explicit app_label"

I had this error today trying to run Django tests because I was using the shorthand from .models import * syntax in one of my files. The issue was that I had a file structure like so:

    apps/
      myapp/
        models/
          __init__.py
          foo.py
          bar.py

and in models/__init__.py I was importing my models using the shorthand syntax:

    from .foo import *
    from .bar import *

In my application I was importing models like so:

    from myapp.models import Foo, Bar

This caused the Django model doesn't declare an explicit app_label when running ./manage.py test.

To fix the problem, I had to explicitly import from the full path in models/__init__.py:

    from myapp.models.foo import *
    from myapp.models.bar import *

That took care of the error.

H/t https://medium.com/@michal.bock/fix-weird-exceptions-when-running-django-tests-f58def71b59a

Get protocol + host name from URL

Python3 using urlsplit:

from urllib.parse import urlsplit
url = "http://stackoverflow.com/questions/9626535/get-domain-name-from-url"
base_url = "{0.scheme}://{0.netloc}/".format(urlsplit(url))
print(base_url)
# http://stackoverflow.com/

Grep characters before and after match?

You can use regexp grep for finding + second grep for highlight

echo "some123_string_and_another" | grep -o -P '.{0,3}string.{0,4}' | grep string

23_string_and

enter image description here

define a List like List<int,string>?

With the new ValueTuple from C# 7 (VS 2017 and above), there is a new solution:

List<(int,string)> mylist= new List<(int,string)>();

Which creates a list of ValueTuple type. If you're targeting .Net Framework 4.7+ or .Net Core, it's native, otherwise you have to get the ValueTuple package from nuget.

It's a struct opposing to Tuple, which is a class. It also has the advantage over the Tuple class that you could create a named tuple, like this:

var mylist = new List<(int myInt, string myString)>();

That way you can access like mylist[0].myInt and mylist[0].myString

How to clear the canvas for redrawing

These are all great examples of how you clear a standard canvas, but if you are using paperjs, then this will work:

Define a global variable in JavaScript:

var clearCanvas = false;

From your PaperScript define:

function onFrame(event){
    if(clearCanvas && project.activeLayer.hasChildren()){
        project.activeLayer.removeChildren();
        clearCanvas = false;
    }
}

Now wherever you set clearCanvas to true, it will clear all the items from the screen.

How to get user agent in PHP

You can use the jQuery ajax method link if you want to pass data from client to server. In this case you can use $_SERVER['HTTP_USER_AGENT'] variable to found browser user agent.

Making PHP var_dump() values display one line per value

I really love var_export(). If you like copy/paste-able code, try:

echo '<pre>' . var_export($data, true) . '</pre>';

Or even something like this for color syntax highlighting:

highlight_string("<?php\n\$data =\n" . var_export($data, true) . ";\n?>");

How to create JNDI context in Spring Boot with Embedded Tomcat Container

Please note instead of

public TomcatEmbeddedServletContainerFactory tomcatFactory()

I had to use the following method signature

public EmbeddedServletContainerFactory embeddedServletContainerFactory() 

Bringing a subview to be in front of all other views

As far as i experienced zposition is a best way.

self.view.layer.zPosition = 1;

How can I make Bootstrap 4 columns all the same height?

Equal height columns is the default behaviour for Bootstrap 4 grids.

_x000D_
_x000D_
.col { background: red; }_x000D_
.col:nth-child(odd) { background: yellow; }
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col">_x000D_
      1 of 3_x000D_
    </div>_x000D_
    <div class="col">_x000D_
      1 of 3_x000D_
      <br>_x000D_
      Line 2_x000D_
      <br>_x000D_
      Line 3_x000D_
    </div>_x000D_
    <div class="col">_x000D_
      1 of 3_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Maven – Always download sources and javadocs

As @xecaps12 said, the simplest/efficient approach is to change your Maven settings file (~/.m2/settings.xml) but if it is a default settings for you, you can also set it like that

<profile>
  <id>downloadSources</id>
  <activation>
    <activeByDefault>true</activeByDefault>
  </activation>
  <properties>
      <downloadSources>true</downloadSources>
      <downloadJavadocs>true</downloadJavadocs>
  </properties>
</profile>

How to get the onclick calling object?

The thing with your method is that you clutter your HTML with javascript. If you put your javascript in an external file you can access your HTML unobtrusive and this is much neater.

Lateron you can expand your code with addEventListener/attackEvent(IE) to prevent memory leaks.

This is without jQuery

<a href="123.com" id="elementid">link</a>

window.onload = function () {
  var el = document.getElementById('elementid');
  el.onclick = function (e) {
    var ev = e || window.event;
    // here u can use this or el as the HTML node
  }
}

You say you want to manipulate it with jQuery. So you can use jQuery. Than it is even better to do it like this:

// this is the window.onload startup of your JS as in my previous example. The difference is 
// that you can add multiple onload functions
$(function () {
  $('a#elementid').bind('click', function (e) {
    // "this" points to the <a> element
    // "e" points to the event object
  });
});

Importing a function from a class in another file?

You can use the below syntax -

from FolderName.FileName import Classname

Invalid use side-effecting operator Insert within a function

There is an exception (I'm using SQL 2014) when you are only using Insert/Update/Delete on Declared-Tables. These Insert/Update/Delete statements cannot contain an OUTPUT statement. The other restriction is that you are not allowed to do a MERGE, even into a Declared-Table. I broke up my Merge statements, that didn't work, into Insert/Update/Delete statements that did work.

The reason I didn't convert it to a stored-procedure is that the table-function was faster (even without the MERGE) than the stored-procedure. This is despite the stored-procedure allowing me to use Temp-Tables that have statistics. I needed the table-function to be very fast, since it is called 20-K times/day. This table function never updates the database.

I also noticed that the NewId() and RAND() SQL functions are not allowed in a function.

How to fix: Error device not found with ADB.exe

On my G2 I had to select PTP instead of MTP mode to get the connection to work.

How to get current time and date in Android

There is a ISO8601Utils utils class in com.google.gson.internal.bind.util package so if you use GSON in your app you can use this.

It supports millis and timezones so it's a pretty good option right out of the box.

MySQL: Invalid use of group function

First, the error you're getting is due to where you're using the COUNT function -- you can't use an aggregate (or group) function in the WHERE clause.

Second, instead of using a subquery, simply join the table to itself:

SELECT a.pid 
FROM Catalog as a LEFT JOIN Catalog as b USING( pid )
WHERE a.sid != b.sid
GROUP BY a.pid

Which I believe should return only rows where at least two rows exist with the same pid but there is are at least 2 sids. To make sure you get back only one row per pid I've applied a grouping clause.

"Register" an .exe so you can run it from any command line in Windows

You have to put your .exe file's path into enviroment variable path. Go to "My computer -> properties -> advanced -> environment variables -> Path" and edit path by adding .exe's directory into path.

Another solution I personally prefer is using RapidEE for a smoother variable editing.

How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?

Can't you just change working directory within the python script using os.chdir(target)? I agree, I can't see any way of doing it from the jar command itself.

If you don't want to permanently change directory, then store the current directory (using os.getcwd())in a variable and change back afterwards.

window.open target _self v window.location.href?

Hopefully someone else is saved by reading this.

We encountered an issue with webkit based browsers doing:

window.open("webpage.htm", "_self");

The browser would lockup and die if we had too many DOM nodes. When we switched our code to following the accepted answer of:

location.href = "webpage.html";

all was good. It took us awhile to figure out what was causing the issue, since it wasn't obvious what made our page periodically fail to load.

Index (zero based) must be greater than or equal to zero

String.Format must start with zero index "{0}" like this:

Aboutme.Text = String.Format("{0}", reader.GetString(0));

What is the lifetime of a static variable in a C++ function?

FWIW, Codegear C++Builder doesn't destruct in the expected order according to the standard.

C:\> sample.exe 1 2
Created in foo
Created in if
Destroyed in foo
Destroyed in if

... which is another reason not to rely on the destruction order!

"Unable to launch the IIS Express Web server" error

I face this issue, All I did was go to the web project Properties -> Web -> In the ProjectUrl I clicked on the "Create Virtual Directory" and my issue was fixed.

How to load npm modules in AWS Lambda?

npm module has to be bundeled inside your nodejs package and upload to AWS Lambda Layers as zip, then you would need to refer to your module/js as below and use available methods from it. const mymodule = require('/opt/nodejs/MyLogger');

PostgreSQL: Drop PostgreSQL database through command line

Try this. Note there's no database specified - it just runs "on the server"

psql -U postgres -c "drop database databasename"

If that doesn't work, I have seen a problem with postgres holding onto orphaned prepared statements.
To clean them up, do this:

SELECT * FROM pg_prepared_xacts;

then for every id you see, run this:

ROLLBACK PREPARED '<id>';

Convert a file path to Uri in Android

Please try the following code

Uri.fromFile(new File("/sdcard/sample.jpg"))

Return Type for jdbcTemplate.queryForList(sql, object, classType)

In order to map a the result set of query to a particular Java class you'll probably be best (assuming you're interested in using the object elsewhere) off with a RowMapper to convert the columns in the result set into an object instance.

See Section 12.2.1.1 of Data access with JDBC on how to use a row mapper.

In short, you'll need something like:

List<Conversation> actors = jdbcTemplate.query(
    SELECT_ALL_CONVERSATIONS_SQL_FULL,
    new Object[] {userId, dateFrom, dateTo},
    new RowMapper<Conversation>() {
        public Conversation mapRow(ResultSet rs, int rowNum) throws SQLException {
            Conversation c = new Conversation();
            c.setId(rs.getLong(1));
            c.setRoom(rs.getString(2));
            [...]
            return c;
        }
    });

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

Use format with no parameters:

var date = moment();
date.format(); // "2014-09-08T08:02:17-05:00"

(http://jsfiddle.net/8gvhL1dz/)

Excel VBA to Export Selected Sheets to PDF

Once you have Selected a group of sheets, you can use Selection

Consider:

Sub luxation()
    ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Select
    Selection.ExportAsFixedFormat _
        Type:=xlTypePDF, _
        Filename:="C:\TestFolder\temp.pdf", _
        Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=True
End Sub

EDIT#1:

Further testing has reveled that this technique depends on the group of cells selected on each worksheet. To get a comprehensive output, use something like:

Sub Macro1()

   Sheets("Sheet1").Activate
   ActiveSheet.UsedRange.Select
   Sheets("Sheet2").Activate
   ActiveSheet.UsedRange.Select
   Sheets("Sheet3").Activate
   ActiveSheet.UsedRange.Select

   ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Select
   Selection.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
      "C:\Users\James\Desktop\pdfmaker.pdf", Quality:=xlQualityStandard, _
      IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
      True
End Sub

How can I use a for each loop on an array?

Element needs to be a variant, so you can't declare it as a string. Your function should accept a variant if it is a string though as long as you pass it ByVal.

Public Sub example()
    Dim sArray(4) As string
    Dim element As variant

    For Each element In sArray
        do_something (element)
    Next element
End Sub


Sub do_something(ByVal e As String)

End Sub

The other option is to convert the variant to a string before passing it.

  do_something CStr(element)

How to check if element has any children in Javascript?

Late but document fragment could be a node:

function hasChild(el){
    var child = el && el.firstChild;
    while (child) {
        if (child.nodeType === 1 || child.nodeType === 11) {
            return true;
        }
        child = child.nextSibling;
    }
    return false;
}
// or
function hasChild(el){
    for (var i = 0; el && el.childNodes[i]; i++) {
        if (el.childNodes[i].nodeType === 1 || el.childNodes[i].nodeType === 11) {
            return true;
        }
    }
    return false;
}

See:
https://github.com/k-gun/so/blob/master/so.dom.js#L42
https://github.com/k-gun/so/blob/master/so.dom.js#L741

How do I get the height and width of the Android Navigation Bar programmatically?

Combining the answer from @egis and others - this works well on a variety of devices, tested on Pixel EMU, Samsung S6, Sony Z3, Nexus 4. This code uses the display dimensions to test for availability of nav bar and then uses the actual system nav bar size if present.

_x000D_
_x000D_
/**_x000D_
 * Calculates the system navigation bar size._x000D_
 */_x000D_
_x000D_
public final class NavigationBarSize {_x000D_
_x000D_
 private final int systemNavBarHeight;_x000D_
 @NonNull_x000D_
 private final Point navBarSize;_x000D_
_x000D_
 public NavigationBarSize(@NonNull Context context) {_x000D_
  Resources resources = context.getResources();_x000D_
  int displayOrientation = resources.getConfiguration().orientation;_x000D_
  final String name;_x000D_
  switch (displayOrientation) {_x000D_
   case Configuration.ORIENTATION_PORTRAIT:_x000D_
    name = "navigation_bar_height";_x000D_
    break;_x000D_
   default:_x000D_
    name = "navigation_bar_height_landscape";_x000D_
  }_x000D_
  int id = resources.getIdentifier(name, "dimen", "android");_x000D_
  systemNavBarHeight = id > 0 ? resources.getDimensionPixelSize(id) : 0;_x000D_
  navBarSize = getNavigationBarSize(context);_x000D_
 }_x000D_
_x000D_
 public void adjustBottomPadding(@NonNull View view, @DimenRes int defaultHeight) {_x000D_
  int height = 0;_x000D_
  if (navBarSize.y > 0) {_x000D_
   // the device has a nav bar, get the correct size from the system_x000D_
   height = systemNavBarHeight;_x000D_
  }_x000D_
  if (height == 0) {_x000D_
   // fallback to default_x000D_
   height = view.getContext().getResources().getDimensionPixelSize(defaultHeight);_x000D_
  }_x000D_
  view.setPadding(0, 0, 0, height);_x000D_
 }_x000D_
_x000D_
 @NonNull_x000D_
 private static Point getNavigationBarSize(@NonNull Context context) {_x000D_
  Point appUsableSize = new Point();_x000D_
  Point realScreenSize = new Point();_x000D_
  WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);_x000D_
  if (windowManager != null) {_x000D_
   Display display = windowManager.getDefaultDisplay();_x000D_
   display.getSize(appUsableSize);_x000D_
   display.getRealSize(realScreenSize);_x000D_
  }_x000D_
  return new Point(realScreenSize.x - appUsableSize.x, realScreenSize.y - appUsableSize.y);_x000D_
 }_x000D_
_x000D_
}
_x000D_
_x000D_
_x000D_

how to execute a scp command with the user name and password in one line

Thanks for your feed back got it to work I used the sshpass tool.

sshpass -p 'password' scp [email protected]:sys_config /var/www/dev/

JavaScript code to stop form submission

Simply do it....

<form>
<!-- Your Input Elements -->
</form>

and here goes your JQuery

$(document).on('submit', 'form', function(e){
    e.preventDefault();
    //your code goes here
    //100% works
    return;
});

How to create a pivot query in sql server without aggregate function

SELECT *
FROM
(
SELECT [Period], [Account], [Value]
FROM TableName
) AS source
PIVOT
(
    MAX([Value])
    FOR [Period] IN ([2000], [2001], [2002])
) as pvt

Another way,

SELECT ACCOUNT,
      MAX(CASE WHEN Period = '2000' THEN Value ELSE NULL END) [2000],
      MAX(CASE WHEN Period = '2001' THEN Value ELSE NULL END) [2001],
      MAX(CASE WHEN Period = '2002' THEN Value ELSE NULL END) [2002]
FROM tableName
GROUP BY Account

Using ng-if as a switch inside ng-repeat?

I will suggest move all templates to separate files, and don't do spagetti inside repeat

take a look here:

html:

<div ng-repeat = "data in comments">
    <div ng-include src="buildUrl(data.type)"></div>
 </div>

js:

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {

  $scope.comments = [
    {"_id":"52fb84fac6b93c152d8b4569",
       "post_id":"52fb84fac6b93c152d8b4567",
       "user_id":"52df9ab5c6b93c8e2a8b4567",
       "type":"hoot"},  
    {"_id":"52fb798cc6b93c74298b4568",
       "post_id":"52fb798cc6b93c74298b4567",
       "user_id":"52df9ab5c6b93c8e2a8b4567",
       "type":"story"},        
    {"_id":"52fb7977c6b93c5c2c8b456b",
       "post_id":"52fb7977c6b93c5c2c8b456a",
       "user_id":"52df9ab5c6b93c8e2a8b4567",
       "type":"article"}
  ];

  $scope.buildUrl = function(type) {
    return type + '.html';
  }
});

http://plnkr.co/edit/HxnirSvMHNQ748M2WeRt?p=preview

Stop embedded youtube iframe?

How we Pause/stop YouTube iframe to when we use embed videos in modalpopup

 $('#close_one').click(function (e) {
         
         
         let link = document.querySelector('.divclass');// get iframe class 
         let link = document.querySelector('#divid');// get iframe id
         let video_src = link.getAttribute('src');

         $('.youtube-video').children('iframe').attr('src', ''); // set iframe parent div value null 
         $('.youtube-video').children('iframe').attr('src', video_src);// set iframe src again it works perfect

     });

How do I uniquely identify computers visiting my web site?

The suggestions to use cookies aside, the only comprehensive set of identifying attributes available to interrogate are contained in the HTTP request header. So it is possible to use some subset of these to create a pseudo-unique identifier for a user agent (i.e., browser). Further, most of this information is possibly already being logged in the so-called "access log" of your web server software by default and, if not, can be easily configured to do so. Then, a utlity could be developed that simply scans the content of this log, creating fingerprints of each request comprised of, say, the IP address and User Agent string, etc. The more data available, even including the contents of specific cookies, adds to the quality of the uniqueness of this fingerprint. Though, as many others have stated already, the HTTP protocol doesn't make this 100% foolproof - at best it can only be a fairly good indicator.

Get list of passed arguments in Windows batch script (.bat)

enter image description here

For to use looping to get all arguments and in pure batch:

Obs: For using without: ?*&<>


@echo off && setlocal EnableDelayedExpansion

for %%Z in (%*)do set "_arg_=%%Z" && set/a "_cnt+=1+0" && call set "_arg_[!_cnt!]=!_arg_!")

:: write/test these arguments/parameters ::
for /l %%l in (1 1 !_cnt!)do echo/ The argument n:%%l is: !_arg_[%%l]!

goto :eof 

Your code is ready to do something with the argument number where it needs, like...

@echo off && setlocal EnableDelayedExpansion

for %%Z in (%*)do set "_arg_=%%Z" && set/a "_cnt+=1+0" && call set "_arg_[!_cnt!]=!_arg_!"

echo= !_arg_[1]! !_arg_[2]! !_arg_[2]!> log.txt

How can I replace every occurrence of a String in a file with PowerShell?

This worked for me using the current working directory in PowerShell. You need to use the FullName property, or it won't work in PowerShell version 5. I needed to change the target .NET framework version in ALL my CSPROJ files.

gci -Recurse -Filter *.csproj |
% { (get-content "$($_.FullName)")
.Replace('<TargetFramework>net47</TargetFramework>', '<TargetFramework>net462</TargetFramework>') |
 Set-Content "$($_.FullName)"}

urllib and "SSL: CERTIFICATE_VERIFY_FAILED" Error

import requests
requests.packages.urllib3.disable_warnings()

import ssl

try:
    _create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
    # Legacy Python that doesn't verify HTTPS certificates by default
    pass
else:
    # Handle target environment that doesn't support HTTPS verification
    ssl._create_default_https_context = _create_unverified_https_context

Taken from here https://gist.github.com/michaelrice/a6794a017e349fc65d01

Back button and refreshing previous activity

One option would be to use the onResume of your first activity.

@Override
public void onResume()
    {  // After a pause OR at startup
    super.onResume();
    //Refresh your stuff here
     }

Or you can start Activity for Result:

Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);

In secondActivity if you want to send back data:

 Intent returnIntent = new Intent();
 returnIntent.putExtra("result",result);
 setResult(RESULT_OK,returnIntent);     
 finish();

if you don't want to return data:

Intent returnIntent = new Intent();
setResult(RESULT_CANCELED, returnIntent);        
finish();

Now in your FirstActivity class write following code for onActivityResult() method

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

  if (requestCode == 1) {

     if(resultCode == RESULT_OK){      
         //Update List         
     }
     if (resultCode == RESULT_CANCELED) {    
         //Do nothing?
     }
  }
}//onActivityResult

Rails 3.1 and Image Assets

http://railscasts.com/episodes/279-understanding-the-asset-pipeline

This railscast (Rails Tutorial video on asset pipeline) helps a lot to explain the paths in assets pipeline as well. I found it pretty useful, and actually watched it a few times.

The solution I chose is @Lee McAlilly's above, but this railscast helped me to understand why it works. Hope it helps!

adding comment in .properties files

The property file task is for editing properties files. It contains all sorts of nice features that allow you to modify entries. For example:

<propertyfile file="build.properties">
    <entry key="build_number"
        type="int"
        operation="+"
        value="1"/>
</propertyfile>

I've incremented my build_number by one. I have no idea what the value was, but it's now one greater than what it was before.

  • Use the <echo> task to build a property file instead of <propertyfile>. You can easily layout the content and then use <propertyfile> to edit that content later on.

Example:

<echo file="build.properties">
# Default Configuration
source.dir=1
dir.publish=1
# Source Configuration
dir.publish.html=1
</echo>
  • Create separate properties files for each section. You're allowed a comment header for each type. Then, use to batch them together into one single file:

Example:

<propertyfile file="default.properties"
    comment="Default Configuration">
    <entry key="source.dir" value="1"/>
    <entry key="dir.publish" value="1"/>
<propertyfile>

<propertyfile file="source.properties"
    comment="Source Configuration">
    <entry key="dir.publish.html" value="1"/>
<propertyfile>
<concat destfile="build.properties">
    <fileset dir="${basedir}">
        <include name="default.properties"/>
        <include name="source.properties"/>
    </fileset>
</concat>

<delete>
    <fileset dir="${basedir}">
         <include name="default.properties"/>
        <include name="source.properties"/>
    </fileset>
</delete>      

How do you sign a Certificate Signing Request with your Certification Authority?

In addition to answer of @jww, I would like to say that the configuration in openssl-ca.cnf,

default_days     = 1000         # How long to certify for

defines the default number of days the certificate signed by this root-ca will be valid. To set the validity of root-ca itself you should use '-days n' option in:

openssl req -x509 -days 3000 -config openssl-ca.cnf -newkey rsa:4096 -sha256 -nodes -out cacert.pem -outform PEM

Failing to do so, your root-ca will be valid for only the default one month and any certificate signed by this root CA will also have validity of one month.

Serializing class instance to JSON

An approach which I have been using in my Flask app to serialize Class instance to JSON response.

Github project for reference

from json import JSONEncoder
import json
from typing import List

class ResponseEncoder(JSONEncoder):
    def default(self, o):
        return o.__dict__

class ListResponse:
    def __init__(self, data: List):
        self.data = data
        self.count = len(data)

class A:
    def __init__(self, message: str):
        self.message = message

class B:
    def __init__(self, record: A):
        self.record = record

class C:
    def __init__(self, data: B):
        self.data = data

Now create an instance of A, B, C then encode.

data_a = A('Test Data')
data_b = B(data_a)
data_c = C(data_b)

response = ResponseEncoder().encode(data_c)
json_response = json.loads(response)

Output

{
    "data": {
        "record": {
            "message": "Test Data"
        }
    }
}

For list type response

records = ['One', 'Two', 'Three']
list_response = ListResponse(records)
response = ResponseEncoder().encode(list_response)
json_response = json.loads(response)

Output

{
    "data": [
        "One",
        "Two",
        "Three"
    ],
    "count": 3
}

How to read files and stdout from a running Docker container

A bit late but this is what I'm doing with journald. It's pretty powerful.

You need to be running your docker containers on an OS with systemd-journald.

docker run -d --log-driver=journald myapp

This pipes the whole lot into host's journald which takes care of stuff like log pruning, storage format etc and gives you some cool options for viewing them:

journalctl CONTAINER_NAME=myapp -f

which will feed it to your console as it is logged,

journalctl CONTAINER_NAME=myapp > output.log

which gives you the whole lot in a file to take away, or

journalctl CONTAINER_NAME=myapp --since=17:45

Plus you can still see the logs via docker logs .... if that's your preference.

No more > my.log or -v "/apps/myapp/logs:/logs" etc

Understanding INADDR_ANY for socket programming

To bind socket with localhost, before you invoke the bind function, sin_addr.s_addr field of the sockaddr_in structure should be set properly. The proper value can be obtained either by

my_sockaddress.sin_addr.s_addr = inet_addr("127.0.0.1")

or by

my_sockaddress.sin_addr.s_addr=htonl(INADDR_LOOPBACK);

Difference between readFile() and readFileSync()

fs.readFile takes a call back which calls response.send as you have shown - good. If you simply replace that with fs.readFileSync, you need to be aware it does not take a callback so your callback which calls response.send will never get called and therefore the response will never end and it will timeout.

You need to show your readFileSync code if you're not simply replacing readFile with readFileSync.

Also, just so you're aware, you should never call readFileSync in a node express/webserver since it will tie up the single thread loop while I/O is performed. You want the node loop to process other requests until the I/O completes and your callback handling code can run.

String to HtmlDocument

You could try with OpenNew and then with Write but that's a bit strange use of that class. More info on MSDN.

How to make UIButton's text alignment center? Using IB

This will make exactly what you were expecting:

Objective-C:

 [myButton.titleLabel setTextAlignment:UITextAlignmentCenter];

For iOS 6 or higher it's

 [myButton.titleLabel setTextAlignment: NSTextAlignmentCenter];

as explained in tyler53's answer

Swift:

myButton.titleLabel?.textAlignment = NSTextAlignment.Center

Swift 4.x and above

myButton.titleLabel?.textAlignment = .center

How do you overcome the HTML form nesting limitation?

One way I would do this without javascript would be to add a set of radio buttons that define the action to be taken:

  • Update
  • Delete
  • Whatever

Then the action script would take different actions depending on the value of the radio button set.

Another way would be to put two forms on the page as you suggested, just not nested. The layout may be difficult to control though:

<form name="editform" action="the_action_url"  method="post">
   <input type="hidden" name="task" value="update" />
   <input type="text" name="foo" />
   <input type="submit" name="save" value="Save" />
</form>

<form name="delform" action="the_action_url"  method="post">
   <input type="hidden" name="task" value="delete" />
   <input type="hidden" name="post_id" value="5" />
   <input type="submit" name="delete" value="Delete" />
</form>

Using the hidden "task" field in the handling script to branch appropriately.

How can I make the computer beep in C#?

In .Net 2.0, you can use Console.Beep().

// Default beep
Console.Beep();

You can also specify the frequency and length of the beep in milliseconds.

// Beep at 5000 Hz for 1 second
Console.Beep(5000, 1000);

For more information refer http://msdn.microsoft.com/en-us/library/8hftfeyw%28v=vs.110%29.aspx

Using Linq to get the last N elements of a collection?

coll.Reverse().Take(N).Reverse().ToList();


public static IEnumerable<T> TakeLast<T>(this IEnumerable<T> coll, int N)
{
    return coll.Reverse().Take(N).Reverse();
}

UPDATE: To address clintp's problem: a) Using the TakeLast() method I defined above solves the problem, but if you really want the do it without the extra method, then you just have to recognize that while Enumerable.Reverse() can be used as an extension method, you aren't required to use it that way:

List<string> mystring = new List<string>() { "one", "two", "three" }; 
mystring = Enumerable.Reverse(mystring).Take(2).Reverse().ToList();

DateTime vs DateTimeOffset

TLDR if you don't want to read all these great answers :-)

Explicit:

Using DateTimeOffset because the timezone is forced to UTC+0.

Implicit:

Using DateTime where you hope everyone sticks to the unwritten rule of the timezone always being UTC+0.


(Side note for devs: explicit is always better than implicit!)

(Side side note for Java devs, C# DateTimeOffset == Java OffsetDateTime, read this: https://www.baeldung.com/java-zoneddatetime-offsetdatetime)

@JsonProperty annotation on field as well as getter/setter

In addition to existing good answers, note that Jackson 1.9 improved handling by adding "property unification", meaning that ALL annotations from difference parts of a logical property are combined, using (hopefully) intuitive precedence.

In Jackson 1.8 and prior, only field and getter annotations were used when determining what and how to serialize (writing JSON); and only and setter annotations for deserialization (reading JSON). This sometimes required addition of "extra" annotations, like annotating both getter and setter.

With Jackson 1.9 and above these extra annotations are NOT needed. It is still possible to add those; and if different names are used, one can create "split" properties (serializing using one name, deserializing using other): this is occasionally useful for sort of renaming.

Reading file contents on the client-side in javascript in various browsers

Edited to add information about the File API

Since I originally wrote this answer, the File API has been proposed as a standard and implemented in most browsers (as of IE 10, which added support for FileReader API described here, though not yet the File API). The API is a bit more complicated than the older Mozilla API, as it is designed to support asynchronous reading of files, better support for binary files and decoding of different text encodings. There is some documentation available on the Mozilla Developer Network as well as various examples online. You would use it as follows:

var file = document.getElementById("fileForUpload").files[0];
if (file) {
    var reader = new FileReader();
    reader.readAsText(file, "UTF-8");
    reader.onload = function (evt) {
        document.getElementById("fileContents").innerHTML = evt.target.result;
    }
    reader.onerror = function (evt) {
        document.getElementById("fileContents").innerHTML = "error reading file";
    }
}

Original answer

There does not appear to be a way to do this in WebKit (thus, Safari and Chrome). The only keys that a File object has are fileName and fileSize. According to the commit message for the File and FileList support, these are inspired by Mozilla's File object, but they appear to support only a subset of the features.

If you would like to change this, you could always send a patch to the WebKit project. Another possibility would be to propose the Mozilla API for inclusion in HTML 5; the WHATWG mailing list is probably the best place to do that. If you do that, then it is much more likely that there will be a cross-browser way to do this, at least in a couple years time. Of course, submitting either a patch or a proposal for inclusion to HTML 5 does mean some work defending the idea, but the fact that Firefox already implements it gives you something to start with.

What is the purpose of meshgrid in Python / NumPy?

Basic Idea

Given possible x values, xs, (think of them as the tick-marks on the x-axis of a plot) and possible y values, ys, meshgrid generates the corresponding set of (x, y) grid points---analogous to set((x, y) for x in xs for y in yx). For example, if xs=[1,2,3] and ys=[4,5,6], we'd get the set of coordinates {(1,4), (2,4), (3,4), (1,5), (2,5), (3,5), (1,6), (2,6), (3,6)}.

Form of the Return Value

However, the representation that meshgrid returns is different from the above expression in two ways:

First, meshgrid lays out the grid points in a 2d array: rows correspond to different y-values, columns correspond to different x-values---as in list(list((x, y) for x in xs) for y in ys), which would give the following array:

   [[(1,4), (2,4), (3,4)],
    [(1,5), (2,5), (3,5)],
    [(1,6), (2,6), (3,6)]]

Second, meshgrid returns the x and y coordinates separately (i.e. in two different numpy 2d arrays):

   xcoords, ycoords = (
       array([[1, 2, 3],
              [1, 2, 3],
              [1, 2, 3]]),
       array([[4, 4, 4],
              [5, 5, 5],
              [6, 6, 6]]))
   # same thing using np.meshgrid:
   xcoords, ycoords = np.meshgrid([1,2,3], [4,5,6])
   # same thing without meshgrid:
   xcoords = np.array([xs] * len(ys)
   ycoords = np.array([ys] * len(xs)).T

Note, np.meshgrid can also generate grids for higher dimensions. Given xs, ys, and zs, you'd get back xcoords, ycoords, zcoords as 3d arrays. meshgrid also supports reverse ordering of the dimensions as well as sparse representation of the result.

Applications

Why would we want this form of output?

Apply a function at every point on a grid: One motivation is that binary operators like (+, -, *, /, **) are overloaded for numpy arrays as elementwise operations. This means that if I have a function def f(x, y): return (x - y) ** 2 that works on two scalars, I can also apply it on two numpy arrays to get an array of elementwise results: e.g. f(xcoords, ycoords) or f(*np.meshgrid(xs, ys)) gives the following on the above example:

array([[ 9,  4,  1],
       [16,  9,  4],
       [25, 16,  9]])

Higher dimensional outer product: I'm not sure how efficient this is, but you can get high-dimensional outer products this way: np.prod(np.meshgrid([1,2,3], [1,2], [1,2,3,4]), axis=0).

Contour plots in matplotlib: I came across meshgrid when investigating drawing contour plots with matplotlib for plotting decision boundaries. For this, you generate a grid with meshgrid, evaluate the function at each grid point (e.g. as shown above), and then pass the xcoords, ycoords, and computed f-values (i.e. zcoords) into the contourf function.

How to style CSS role

please use :

 #content[role=main]{
   your style here
}

Interfaces — What's the point?

I did a search for the word "composition" on this page and didn't see it once. This answer is very much in addition to the answers aforementioned.

One of the absolutely crucial reasons for using interfaces in an Object Oriented Project is that they allow you to favour composition over inheritance. By implementing interfaces you can decouple your implementations from the various algorithms you are applying to them.

This superb "Decorator Pattern" tutorial by Derek Banas (which - funnily enough - also uses pizza as an example) is a worthwhile illustration:

https://www.youtube.com/watch?v=j40kRwSm4VE

Select row with most recent date per user

 select result from (
     select vorsteuerid as result, count(*) as anzahl from kreditorenrechnung where kundeid = 7148
     group by vorsteuerid
 ) a order by anzahl desc limit 0,1

How to: Install Plugin in Android Studio

if you are on Linux (Ubuntu)... the go to File-> Settings-> Plugin and select plugin from respective location.

If you are on Mac OS... the go to File-> Preferences-> Plugin and select plugin from respective location.

Base64 encoding and decoding in client-side Javascript

Did someone say code golf? =)

The following is my attempt at improving my handicap while catching up with the times. Supplied for your convenience.

function decode_base64(s) {
  var b=l=0, r='',
  m='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  s.split('').forEach(function (v) {
    b=(b<<6)+m.indexOf(v); l+=6;
    if (l>=8) r+=String.fromCharCode((b>>>(l-=8))&0xff);
  });
  return r;
}

What I was actually after was an asynchronous implementation and to my surprise it turns out forEach as opposed to JQuery's $([]).each method implementation is very much synchronous.

If you also had such crazy notions in mind a 0 delay window.setTimeout will run the base64 decode asynchronously and execute the callback function with the result when done.

function decode_base64_async(s, cb) {
  setTimeout(function () { cb(decode_base64(s)); }, 0);
}

@Toothbrush suggested "index a string like an array", and get rid of the split. This routine seems really odd and not sure how compatible it will be, but it does hit another birdie so lets have it.

function decode_base64(s) {
  var b=l=0, r='',
  m='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  [].forEach.call(s, function (v) {
    b=(b<<6)+m.indexOf(v); l+=6;
    if (l>=8) r+=String.fromCharCode((b>>>(l-=8))&0xff);
  });
  return r;
}

While trying to find more information on JavaScript string as array I stumbled on this pro tip using a /./g regex to step through a string. This reduces the code size even more by replacing the string in place and eliminating the need of keeping a return variable.

function decode_base64(s) {
  var b=l=0,
  m='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  return s.replace(/./g, function (v) {
    b=(b<<6)+m.indexOf(v); l+=6;
    return l<8?'':String.fromCharCode((b>>>(l-=8))&0xff);
  });
}

If however you were looking for something a little more traditional perhaps the following is more to your taste.

function decode_base64(s) {
  var b=l=0, r='', s=s.split(''), i,
  m='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  for (i in s) {
    b=(b<<6)+m.indexOf(s[i]); l+=6;
    if (l>=8) r+=String.fromCharCode((b>>>(l-=8))&0xff);
  }
  return r;
}

I didn't have the trailing null issue so this was removed to remain under par but it should easily be resolved with a trim() or a trimRight() if you'd prefer, should this pose a problem for you.

ie.

return r.trimRight();

Note:

The result is an ascii byte string, if you need unicode the easiest is to escape the byte string which can then be decoded with decodeURIComponent to produce the unicode string.

function decode_base64_usc(s) {      
  return decodeURIComponent(escape(decode_base64(s)));
}

Since escape is being deprecated we could change our function to support unicode directly without the need for escape or String.fromCharCode we can produce a % escaped string ready for URI decoding.

function decode_base64(s) {
  var b=l=0,
  m='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  return decodeURIComponent(s.replace(/./g, function (v) {
    b=(b<<6)+m.indexOf(v); l+=6;
    return l<8?'':'%'+(0x100+((b>>>(l-=8))&0xff)).toString(16).slice(-2);
  }));
}

nJoy!

How to add item to the beginning of List<T>?

Use the Insert method:

ti.Insert(0, initialItem);

IIS Express Windows Authentication

Visual Studio 2010 SP1 and 2012 added support for IIS Express eliminating the need to edit angle brackets.

  1. If you haven't already, right-click a web-flavored project and select "Use IIS Express...".
  2. Once complete, select the web project and press F4 to focus the Properties panel.
  3. Set the "Windows Authentication" property to Enabled, and the "Anonymous Authentication" property to Disabled.

enter image description here

I believe this solution is superior to the vikomall's options.

  • Option #1 is a global change for all IIS Express sites.
  • Option #2 leaves development cruft in the web.config.
    • Further, it will probably lead to an error when deployed to IIS 7.5 unless you follow the "unlock" procedure on your IIS server's applicationHost.config.

The UI-based solution above uses site-specific location elements in IIS Express's applicationHost.config leaving the app untouched.

More information here: http://msdn.microsoft.com/en-us/magazine/hh288080.aspx

Vue v-on:click does not work on component

Native events of components aren't directly accessible from parent elements. Instead you should try v-on:click.native="testFunction", or you can emit an event from Test component as well. Like v-on:click="$emit('click')".

undefined reference to WinMain@16 (codeblocks)

You should create a new project in Code::Blocks, and make sure it's 'Console Application'.

Add your .cpp files into the project so they are all compiled and linked together.

Print second last column/field in awk

It's simplest:

 awk '{print $--NF}' 

The reason the original $NF-- didn't work is because the expression is evaluated before the decrement, whereas my prefix decrement is performed before evaluation.

How to change the date format from MM/DD/YYYY to YYYY-MM-DD in PL/SQL?

select to_date(to_char(ORDER_DATE,'YYYY/MM/DD')) 
from ORDERS;

This might help but, at the end you will get a string not the date. Apparently, your format problem will get solved for sure .

Reading and writing binary file

Here is a short example, the C++ way using rdbuf. I got this from the web. I can't find my original source on this:

#include <fstream>
#include <iostream>

int main () 
{
  std::ifstream f1 ("C:\\me.txt",std::fstream::binary);

  std::ofstream f2 ("C:\\me2.doc",std::fstream::trunc|std::fstream::binary);

  f2<<f1.rdbuf();

  return 0;
}

Android: ListView elements with multiple clickable buttons

I Know it's late but this may help, this is an example how I write custom adapter class for different click actions

 public class CustomAdapter extends BaseAdapter {

    TextView title;
  Button button1,button2;

    public long getItemId(int position) {
        return position;
    }

    public int getCount() {
        return mAlBasicItemsnav.size();  // size of your list array
    }

    public Object getItem(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = getLayoutInflater().inflate(R.layout.listnavsub_layout, null, false); // use sublayout which you want to inflate in your each list item
        }

        title = (TextView) convertView.findViewById(R.id.textViewnav); // see you have to find id by using convertView.findViewById 
        title.setText(mAlBasicItemsnav.get(position));
      button1=(Button) convertView.findViewById(R.id.button1);
      button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //your click action 

           // if you have different click action at different positions then
            if(position==0)
              {
                       //click action of 1st list item on button click
        }
           if(position==1)
              {
                       //click action of 2st list item on button click
        }
    });

 // similarly for button 2

   button2=(Button) convertView.findViewById(R.id.button2);
      button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //your click action 

    });



        return convertView;
    }
}

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

The proper way is to use Hibernate Transformers:

public class StudentDTO {
private String studentName;
private String courseDescription;

public StudentDTO() { }  
...
} 

.

List resultWithAliasedBean = s.createSQLQuery(
"SELECT st.name as studentName, co.description as courseDescription " +
"FROM Enrolment e " +
"INNER JOIN Student st on e.studentId=st.studentId " +
"INNER JOIN Course co on e.courseCode=co.courseCode")
.setResultTransformer( Transformers.aliasToBean(StudentDTO.class))
.list();

StudentDTO dto =(StudentDTO) resultWithAliasedBean.get(0);

Iterating througth Object[] is redundant and would have some performance penalty. Detailed information about transofrmers usage you will find here: Transformers for HQL and SQL

If you are looking for even more simple solution you can use out-of-the-box-map-transformer:

List iter = s.createQuery(
"select e.student.name as studentName," +
"       e.course.description as courseDescription" +
"from   Enrolment as e")
.setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP )
.iterate();

String name = (Map)(iter.next()).get("studentName");

How to get arguments with flags in Bash

This is the idiom I usually use:

while test $# -gt 0; do
  case "$1" in
    -h|--help)
      echo "$package - attempt to capture frames"
      echo " "
      echo "$package [options] application [arguments]"
      echo " "
      echo "options:"
      echo "-h, --help                show brief help"
      echo "-a, --action=ACTION       specify an action to use"
      echo "-o, --output-dir=DIR      specify a directory to store output in"
      exit 0
      ;;
    -a)
      shift
      if test $# -gt 0; then
        export PROCESS=$1
      else
        echo "no process specified"
        exit 1
      fi
      shift
      ;;
    --action*)
      export PROCESS=`echo $1 | sed -e 's/^[^=]*=//g'`
      shift
      ;;
    -o)
      shift
      if test $# -gt 0; then
        export OUTPUT=$1
      else
        echo "no output dir specified"
        exit 1
      fi
      shift
      ;;
    --output-dir*)
      export OUTPUT=`echo $1 | sed -e 's/^[^=]*=//g'`
      shift
      ;;
    *)
      break
      ;;
  esac
done

Key points are:

  • $# is the number of arguments
  • while loop looks at all the arguments supplied, matching on their values inside a case statement
  • shift takes the first one away. You can shift multiple times inside of a case statement to take multiple values.

load jquery after the page is fully loaded

You can also use:

$(window).bind("load", function() { 
    // Your code here.
});

How do I implement Cross Domain URL Access from an Iframe using Javascript?

You might want to take a look at these questions/answers ; they could give you some informations concerning your problem :

To make things short : accessing iframe from another domain is not possible, for security reasons -- which explains the error message you are getting.


The Same origin policy page on wikipedia brings some informations about that security measure :

In a nutshell, the policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions — but prevents access to most methods and properties across pages on different sites.

A strict separation between content provided by unrelated sites must be maintained on client side to prevent the loss of data confidentiality or integrity.

Getting rid of \n when using .readlines()

You can use .rstrip('\n') to only remove newlines from the end of the string:

for i in contents:
    alist.append(i.rstrip('\n'))

This leaves all other whitespace intact. If you don't care about whitespace at the start and end of your lines, then the big heavy hammer is called .strip().

However, since you are reading from a file and are pulling everything into memory anyway, better to use the str.splitlines() method; this splits one string on line separators and returns a list of lines without those separators; use this on the file.read() result and don't use file.readlines() at all:

alist = t.read().splitlines()

Shrinking navigation bar when scrolling down (bootstrap3)

You can combine "scroll" and "scrollstop" events in order to achieve desired result:

$(window).on("scroll",function(){
   $('nav').addClass('shrink');
}); 
$(window).on("scrollstop",function(){
   $('nav').removeClass('shrink');
}); 

Is it possible to run .APK/Android apps on iPad/iPhone devices?

Apple users can download your .apk file, however they cannot run it. It is a different file format than iPhone apps (.ipa)

Regular Expression usage with ls

You don't say what shell you are using, but they generally don't support regular expressions that way, although there are common *nix CLI tools (grep, sed, etc) that do.

What shells like bash do support is globbing, which uses some similiar characters (eg, *) but is not the same thing.

Newer versions of bash do have a regular expression operator, =~:

for x in `ls`; do 
    if [[ $x =~ .+\..* ]]; then 
        echo $x; 
    fi; 
done

What is the difference between active and passive FTP?

Redacted version of my article FTP Connection Modes (Active vs. Passive):

FTP connection mode (active or passive), determines how a data connection is established. In both cases, a client creates a TCP control connection to an FTP server command port 21. This is a standard outgoing connection, as with any other file transfer protocol (SFTP, SCP, WebDAV) or any other TCP client application (e.g. web browser). So, usually there are no problems when opening the control connection.

Where FTP protocol is more complicated comparing to the other file transfer protocols are file transfers. While the other protocols use the same connection for both session control and file (data) transfers, the FTP protocol uses a separate connection for the file transfers and directory listings.

In the active mode, the client starts listening on a random port for incoming data connections from the server (the client sends the FTP command PORT to inform the server on which port it is listening). Nowadays, it is typical that the client is behind a firewall (e.g. built-in Windows firewall) or NAT router (e.g. ADSL modem), unable to accept incoming TCP connections.

For this reason the passive mode was introduced and is mostly used nowadays. Using the passive mode is preferable because most of the complex configuration is done only once on the server side, by experienced administrator, rather than individually on a client side, by (possibly) inexperienced users.

In the passive mode, the client uses the control connection to send a PASV command to the server and then receives a server IP address and server port number from the server, which the client then uses to open a data connection to the server IP address and server port number received.

Network Configuration for Passive Mode

With the passive mode, most of the configuration burden is on the server side. The server administrator should setup the server as described below.

The firewall and NAT on the FTP server side have to be configured not only to allow/route the incoming connections on FTP port 21 but also a range of ports for the incoming data connections. Typically, the FTP server software has a configuration option to setup a range of the ports, the server will use. And the same range has to be opened/routed on the firewall/NAT.

When the FTP server is behind a NAT, it needs to know it's external IP address, so it can provide it to the client in a response to PASV command.

Network Configuration for Active Mode

With the active mode, most of the configuration burden is on the client side.

The firewall (e.g. Windows firewall) and NAT (e.g. ADSL modem routing rules) on the client side have to be configured to allow/route a range of ports for the incoming data connections. To open the ports in Windows, go to Control Panel > System and Security > Windows Firewall > Advanced Settings > Inbound Rules > New Rule. For routing the ports on the NAT (if any), refer to its documentation.

When there's NAT in your network, the FTP client needs to know its external IP address that the WinSCP needs to provide to the FTP server using PORT command. So that the server can correctly connect back to the client to open the data connection. Some FTP clients are capable of autodetecting the external IP address, some have to be manually configured.

Smart Firewalls/NATs

Some firewalls/NATs try to automatically open/close data ports by inspecting FTP control connection and/or translate the data connection IP addresses in control connection traffic.

With such a firewall/NAT, the above configuration is not necessary for a plain unencrypted FTP. But this cannot work with FTPS, as the control connection traffic is encrypted and the firewall/NAT cannot inspect nor modify it.

Ruby on Rails: Where to define global constants?

As of Rails 4.2, you can use the config.x property:

# config/application.rb (or config/custom.rb if you prefer)
config.x.colours.options = %w[white blue black red green]
config.x.colours.default = 'white'

Which will be available as:

Rails.configuration.x.colours.options
# => ["white", "blue", "black", "red", "green"]
Rails.configuration.x.colours.default
# => "white"

Another method of loading custom config:

# config/colours.yml
default: &default
  options:
    - white
    - blue
    - black
    - red
    - green
  default: white
development:
  *default
production:
  *default
# config/application.rb
config.colours = config_for(:colours)
Rails.configuration.colours
# => {"options"=>["white", "blue", "black", "red", "green"], "default"=>"white"}
Rails.configuration.colours['default']
# => "white"

In Rails 5 & 6, you can use the configuration object directly for custom configuration, in addition to config.x. However, it can only be used for non-nested configuration:

# config/application.rb
config.colours = %w[white blue black red green]

It will be available as:

Rails.configuration.colours
# => ["white", "blue", "black", "red", "green"]

initialize a const array in a class initializer in C++

interestingly, in C# you have the keyword const that translates to C++'s static const, as opposed to readonly which can be only set at constructors and initializations, even by non-constants, ex:

readonly DateTime a = DateTime.Now;

I agree, if you have a const pre-defined array you might as well make it static. At that point you can use this interesting syntax:

//in header file
class a{
    static const int SIZE;
    static const char array[][10];
};
//in cpp file:
const int a::SIZE = 5;
const char array[SIZE][10] = {"hello", "cruel","world","goodbye", "!"};

however, I did not find a way around the constant '10'. The reason is clear though, it needs it to know how to perform accessing to the array. A possible alternative is to use #define, but I dislike that method and I #undef at the end of the header, with a comment to edit there at CPP as well in case if a change.

Add quotation at the start and end of each line in Notepad++

  • Place your cursor at the end of the text.
  • Press SHIFT and ->. The cursor will move to the next line.
  • Press CTRL-F and type , in "Replace with:" and press ENTER.

You will need to put a quote at the beginning of your first text and the end of your last.

Concatenating strings in C, which method is more efficient?

The difference is unlikely to matter:

  • If your strings are small, the malloc will drown out the string concatenations.
  • If your strings are large, the time spent copying the data will drown out the differences between strcat / sprintf.

As other posters have mentioned, this is a premature optimization. Concentrate on algorithm design, and only come back to this if profiling shows it to be a performance problem.

That said... I suspect method 1 will be faster. There is some---admittedly small---overhead to parse the sprintf format-string. And strcat is more likely "inline-able".

How to set breakpoints in inline Javascript in Google Chrome?

I know the Q is not about Firefox but I did not want to add a copy of this question to just answer it myself.

For Firefox you need to add debugger; to be able to do what @matt-ball suggested for the script tag.

So on your code, you add debugger above the line you want to debug and then you can add breakpoints. If you just set the breakpoints on the browser it won't stop.

If this is not the place to add a Firefox answer given that the question is about Chrome. Don't :( minus the answer just let me know where I should post it and I'll happily move the post. :)

How to get rid of blank pages in PDF exported from SSRS

Another thing to try is to set the report property called ConsumeContainerWhitespace to True (the default is false). That's how it got resolved for me.

How to hide a mobile browser's address bar?

I know this is old, but I have to add this in here..

And while this is not a full answer, it is an 'IN ADDITION TO'

The address bar will not disappear if you're NOT using https.

ALSO

If you are using https and the address bar still won't hide, you might have some https errors in your webpage (such as certain images being served from a non-https location.)

Hope this helps..

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

The method you're looking for is extend(). From the Python documentation:

list.append(x)
    Add an item to the end of the list; equivalent to a[len(a):] = [x].

list.extend(L)
    Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

list.insert(i, x)
    Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

Refresh Page and Keep Scroll Position

Thanks Sanoj, that worked for me.
However iOS does not support "onbeforeunload" on iPhone. Workaround for me was to set localStorage with js:

<button onclick="myFunction()">Click me</button>

<script>
document.addEventListener("DOMContentLoaded", function(event) { 
            var scrollpos = localStorage.getItem('scrollpos');
            if (scrollpos) window.scrollTo(0, scrollpos);
        });
function myFunction() {
  localStorage.setItem('scrollpos', window.scrollY);
  location.reload(); 
}
</script>

Search and replace part of string in database

I was just faced with a similar problem. I exported the contents of the db into one sql file and used TextEdit to find and replace everything I needed. Simplicity ftw!

writing integer values to a file using out.write()

write() only takes a single string argument, so you could do this:

outf.write(str(num))

or

outf.write('{}'.format(num))  # more "modern"
outf.write('%d' % num)        # deprecated mostly

Also note that write will not append a newline to your output so if you need it you'll have to supply it yourself.

Aside:

Using string formatting would give you more control over your output, so for instance you could write (both of these are equivalent):

num = 7
outf.write('{:03d}\n'.format(num))

num = 12
outf.write('%03d\n' % num)          

to get three spaces, with leading zeros for your integer value followed by a newline:

007
012

format() will be around for a long while, so it's worth learning/knowing.

Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener

It happen if there are two more ContextLoaderListener exist in your project.

For ex: in my case 2 ContextLoaderListener was exist using

  1. java configuration
  2. web.xml

So, remove any one ContextLoaderListener from your project and run your application.

Difference between git checkout --track origin/branch and git checkout -b branch origin/branch

You can't create a new branch with this command

git checkout --track origin/branch

if you have changes that are not staged.

Here is example:

$ git status
On branch master
Your branch is up to date with 'origin/master'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   src/App.js

no changes added to commit (use "git add" and/or "git commit -a")

// TRY TO CREATE:

$ git checkout --track origin/new-branch
fatal: 'origin/new-branch' is not a commit and a branch 'new-branch' cannot be created from it

However you can easily create a new branch with un-staged changes with git checkout -b command:

$ git checkout -b new-branch
Switched to a new branch 'new-branch'
M       src/App.js

StringBuilder vs String concatenation in toString() in Java

I think we should go with StringBuilder append approach. Reason being :

  1. The String concatenate will create a new string object each time (As String is immutable object) , so it will create 3 objects.

  2. With String builder only one object will created[StringBuilder is mutable] and the further string gets appended to it.

Get epoch for a specific date using Javascript

Take a look at http://www.w3schools.com/jsref/jsref_obj_date.asp

There is a function UTC() that returns the milliseconds from the unix epoch.

foreach for JSON array , syntax

You can use the .forEach() method of JavaScript for looping through JSON.

_x000D_
_x000D_
var datesBooking = [_x000D_
    {"date": "04\/24\/2018"},_x000D_
      {"date": "04\/25\/2018"}_x000D_
    ];_x000D_
    _x000D_
    datesBooking.forEach(function(data, index) {_x000D_
      console.log(data);_x000D_
    });
_x000D_
_x000D_
_x000D_

Turn Pandas Multi-Index into column

This doesn't really apply to your case but could be helpful for others (like myself 5 minutes ago) to know. If one's multindex have the same name like this:

                         value
Trial        Trial
    1              0        13
                   1         3
                   2         4
    2              0       NaN
                   1        12
    3              0        34 

df.reset_index(inplace=True) will fail, cause the columns that are created cannot have the same names.

So then you need to rename the multindex with df.index = df.index.set_names(['Trial', 'measurement']) to get:

                           value
Trial    measurement       

    1              0        13
    1              1         3
    1              2         4
    2              0       NaN
    2              1        12
    3              0        34 

And then df.reset_index(inplace=True) will work like a charm.

I encountered this problem after grouping by year and month on a datetime-column(not index) called live_date, which meant that both year and month were named live_date.

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

The accepted answer is the correct command, I just want to add one additional thing, when extracting the key if you leave the PEM password("Enter PEM pass phrase:") blank then the complete key will not be extracted but only the localKeyID will be extracted. To get the complete key you must specify a PEM password whem running the following command.

Please note that when it comes to Import password, you can specify the actual password for "Enter Import Password:" or can leave this password blank:

openssl pkcs12 -in yourP12File.pfx -nocerts -out privateKey.pem

Android: No Activity found to handle Intent error? How it will resolve

in my case, i was sure that the action is correct, but i was passing wrong URL, i passed the website link without the http:// in it's beginning, so it caused the same issue, here is my manifest (part of it)

<activity
        android:name=".MyBrowser"
        android:label="MyBrowser Activity" >
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <action android:name="com.dsociety.activities.MyBrowser" />

            <category android:name="android.intent.category.DEFAULT" />

            <data android:scheme="http" />
        </intent-filter>
    </activity>

when i code the following, the same Exception is thrown at run time :

Intent intent = new Intent();
intent.setAction("com.dsociety.activities.MyBrowser");
intent.setData(Uri.parse("www.google.com"));    // should be http://www.google.com
startActivity(intent);

Fullscreen Activity in Android?

Inside styles.xml...

<!-- No action bar -->
<style name="NoActonBar" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Theme customization. -->
    <item name="colorPrimary">#000</item>
    <item name="colorPrimaryDark">#444</item>
    <item name="colorAccent">#999</item>
    <item name="android:windowFullscreen">true</item>
</style>

This worked for me. Hope it'll help you.

using CASE in the WHERE clause

This is working Oracle example but it should work in MySQL too.

You are missing smth - see IN after END Replace 'IN' with '=' sign for a single value.

SELECT empno, ename, job
  FROM scott.emp
 WHERE (CASE WHEN job = 'MANAGER' THEN '1'  
         WHEN job = 'CLERK'   THEN '2' 
         ELSE '0'  END) IN (1, 2)

How to change owner of PostgreSql database?

Frank Heikens answer will only update database ownership. Often, you also want to update ownership of contained objects (including tables). Starting with Postgres 8.2, REASSIGN OWNED is available to simplify this task.

IMPORTANT EDIT!

Never use REASSIGN OWNED when the original role is postgres, this could damage your entire DB instance. The command will update all objects with a new owner, including system resources (postgres0, postgres1, etc.)


First, connect to admin database and update DB ownership:

psql
postgres=# REASSIGN OWNED BY old_name TO new_name;

This is a global equivalent of ALTER DATABASE command provided in Frank's answer, but instead of updating a particular DB, it change ownership of all DBs owned by 'old_name'.

The next step is to update tables ownership for each database:

psql old_name_db
old_name_db=# REASSIGN OWNED BY old_name TO new_name;

This must be performed on each DB owned by 'old_name'. The command will update ownership of all tables in the DB.

Switch between two frames in tkinter

Note: According to JDN96, the answer below may cause a memory leak by repeatedly destroying and recreating frames. However, I have not tested to verify this myself.

One way to switch frames in tkinter is to destroy the old frame then replace it with your new frame.

I have modified Bryan Oakley's answer to destroy the old frame before replacing it. As an added bonus, this eliminates the need for a container object and allows you to use any generic Frame class.

# Multi-frame tkinter application v2.3
import tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self._frame = None
        self.switch_frame(StartPage)

    def switch_frame(self, frame_class):
        """Destroys current frame and replaces it with a new one."""
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self._frame = new_frame
        self._frame.pack()

class StartPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Label(self, text="This is the start page").pack(side="top", fill="x", pady=10)
        tk.Button(self, text="Open page one",
                  command=lambda: master.switch_frame(PageOne)).pack()
        tk.Button(self, text="Open page two",
                  command=lambda: master.switch_frame(PageTwo)).pack()

class PageOne(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Label(self, text="This is page one").pack(side="top", fill="x", pady=10)
        tk.Button(self, text="Return to start page",
                  command=lambda: master.switch_frame(StartPage)).pack()

class PageTwo(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Label(self, text="This is page two").pack(side="top", fill="x", pady=10)
        tk.Button(self, text="Return to start page",
                  command=lambda: master.switch_frame(StartPage)).pack()

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

Start page Page one Page two

Explanation

switch_frame() works by accepting any Class object that implements Frame. The function then creates a new frame to replace the old one.

  • Deletes old _frame if it exists, then replaces it with the new frame.
  • Other frames added with .pack(), such as menubars, will be unaffected.
  • Can be used with any class that implements tkinter.Frame.
  • Window automatically resizes to fit new content

Version History

v2.3

- Pack buttons and labels as they are initialized

v2.2

- Initialize `_frame` as `None`.
- Check if `_frame` is `None` before calling `.destroy()`.

v2.1.1

- Remove type-hinting for backwards compatibility with Python 3.4.

v2.1

- Add type-hinting for `frame_class`.

v2.0

- Remove extraneous `container` frame.
    - Application now works with any generic `tkinter.frame` instance.
- Remove `controller` argument from frame classes.
    - Frame switching is now done with `master.switch_frame()`.

v1.6

- Check if frame attribute exists before destroying it.
- Use `switch_frame()` to set first frame.

v1.5

  - Revert 'Initialize new `_frame` after old `_frame` is destroyed'.
      - Initializing the frame before calling `.destroy()` results
        in a smoother visual transition.

v1.4

- Pack frames in `switch_frame()`.
- Initialize new `_frame` after old `_frame` is destroyed.
    - Remove `new_frame` variable.

v1.3

- Rename `parent` to `master` for consistency with base `Frame` class.

v1.2

- Remove `main()` function.

v1.1

- Rename `frame` to `_frame`.
    - Naming implies variable should be private.
- Create new frame before destroying old frame.

v1.0

- Initial version.

Concatenating elements in an array to a string

Arrays.toString(arr);

output is [1,2,3] and you storing it to your string . and printing it so you get output [1,2,3].

If you want to get output 123 try this:

public static void main(String[] args) {
    String[] arr= {"1","2","3"};
    String output ="";
    for(String str: arr)
        output=output+str;
    System.out.println(output);


}

Output:

123

Checkbox angular material checked by default

this works for me in Angular 7

// in component.ts
checked: boolean = true;

changeValue(value) {
    this.checked = !value;
}

// in component.html
<mat-checkbox value="checked" (click)="changeValue(checked)" color="primary">
   some Label
</mat-checkbox>

I hope help someone ... greetings. let me know if someone have some easiest

What is the exact meaning of Git Bash?

git bash is a shell where:

See "Fix msysGit Portable $HOME location":

On a Windows 64:

C:\Windows\SysWOW64\cmd.exe /c ""C:\Prog\Git\1.7.1\bin\sh.exe" --login -i"

This differs from git-cmd.bat, which provides git commands in a plain DOS command prompt.

A tool like GitHub for Windows (G4W) provides different shell for git (including a PowerShell one)


Update April 2015:

Note: the git bash in msysgit/Git for windows 1.9.5 is an old one:

GNU bash, version 3.1.20(4)-release (i686-pc-msys)
Copyright (C) 2005 Free Software Foundation, Inc.

But with the phasing out of msysgit (Q4 2015) and the new Git For Windows (Q2 2015), you now have Git for Windows 2.3.5.
It has a much more recent bash, based on the 64bits msys2 project, an independent rewrite of MSYS, based on modern Cygwin (POSIX compatibility layer) and MinGW-w64 with the aim of better interoperability with native Windows software. msys2 comes with its own installer too.

The git bash is now (with the new Git For Windows):

GNU bash, version 4.3.33(3)-release (x86_64-pc-msys)
Copyright (C) 2013 Free Software Foundation, Inc.

Original answer (June 2013) More precisely, from msygit wiki:

Historically, Git on Windows was only officially supported using Cygwin.
To help make a native Windows version, this project was started, based on the mingw fork.

To make the milky 'soup' of project names more clear, we say like this:

  • msysGit - is the name of this project, a build environment for Git for Windows, which releases the official binaries
  • MinGW - is a minimalist development environment for native Microsoft Windows applications.
    It is really a very thin compile-time layer over the Microsoft Runtime; MinGW programs are therefore real Windows programs, with no concept of Unix-style paths or POSIX niceties such as a fork() call
  • MSYS - is a Bourne Shell command line interpreter system, is used by MinGW (and others), was forked in the past from Cygwin
  • Cygwin - a Linux like environment, which was used in the past to build Git for Windows, nowadays has no relation to msysGit

So, your two lines description about "git bash" are:

"Git bash" is a msys shell included in "Git for Windows", and is a slimmed-down version of Cygwin (an old version at that), whose only purpose is to provide enough of a POSIX layer to run a bash.


Reminder:

msysGit is the development environment to compile Git for Windows. It is complete, in the sense that you just need to install msysGit, and then you can build Git. Without installing any 3rd-party software.

msysGit is not Git for Windows; that is an installer which installs Git -- and only Git.

See more in "Difference between msysgit and Cygwin + git?".

Can I restore a single table from a full mysql mysqldump file?

This tool may be is what you want: tbdba-restore-mysqldump.pl

https://github.com/orczhou/dba-tool/blob/master/tbdba-restore-mysqldump.pl

e.g. Restore a table from database dump file:

tbdba-restore-mysqldump.pl -t yourtable -s yourdb -f backup.sql

How do you add input from user into list in Python

shopList = [] 
maxLengthList = 6
while len(shopList) < maxLengthList:
    item = input("Enter your Item to the List: ")
    shopList.append(item)
    print shopList
print "That's your Shopping List"
print shopList

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:*

or

Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*"

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*');

What is the fastest/most efficient way to find the highest set bit (msb) in an integer in C?

unsigned int
msb32(register unsigned int x)
{
        x |= (x >> 1);
        x |= (x >> 2);
        x |= (x >> 4);
        x |= (x >> 8);
        x |= (x >> 16);
        return(x & ~(x >> 1));
}

1 register, 13 instructions. Believe it or not, this is usually faster than the BSR instruction mentioned above, which operates in linear time. This is logarithmic time.

From http://aggregate.org/MAGIC/#Most%20Significant%201%20Bit

Why doesn't indexOf work on an array IE8?

The problem

IE<=8 simply doesn't have an indexOf() method for arrays.


The solution

If you need indexOf in IE<=8, you should consider using the following polyfill, which is recommended at the MDN :

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(searchElement, fromIndex) {
        var k;
        if (this == null) {
            throw new TypeError('"this" is null or not defined');
        }
        var o = Object(this);
        var len = o.length >>> 0;
        if (len === 0) {
            return -1;
        }
        var n = +fromIndex || 0;
        if (Math.abs(n) === Infinity) {
            n = 0;
        }
        if (n >= len) {
            return -1;
        }
        k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
        while (k < len) {
            if (k in o && o[k] === searchElement) {
                return k;
            }
            k++;
        }
        return -1;
    };
}

Minified :

Array.prototype.indexOf||(Array.prototype.indexOf=function(r,t){var n;if(null==this)throw new TypeError('"this" is null or not defined');var e=Object(this),i=e.length>>>0;if(0===i)return-1;var a=+t||0;if(Math.abs(a)===1/0&&(a=0),a>=i)return-1;for(n=Math.max(a>=0?a:i-Math.abs(a),0);i>n;){if(n in e&&e[n]===r)return n;n++}return-1});

Have nginx access_log and error_log log to STDOUT and STDERR of master process

In docker image of PHP-FPM, i've see such approach:

# cat /usr/local/etc/php-fpm.d/docker.conf
[global]
error_log = /proc/self/fd/2

[www]
; if we send this to /proc/self/fd/1, it never appears
access.log = /proc/self/fd/2

HTTP requests and JSON parsing in Python

Try this:

import requests
import json

# Goole Maps API.
link = 'http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false'

# Request data from link as 'str'
data = requests.get(link).text

# convert 'str' to Json
data = json.loads(data)

# Now you can access Json 
for i in data['routes'][0]['legs'][0]['steps']:
    lattitude = i['start_location']['lat']
    longitude = i['start_location']['lng']
    print('{}, {}'.format(lattitude, longitude))

Python circular importing?

When you import a module (or a member of it) for the first time, the code inside the module is executed sequentially like any other code; e.g., it is not treated any differently that the body of a function. An import is just a command like any other (assignment, a function call, def, class). Assuming your imports occur at the top of the script, then here's what's happening:

  • When you try to import World from world, the world script gets executed.
  • The world script imports Field, which causes the entities.field script to get executed.
  • This process continues until you reach the entities.post script because you tried to import Post
  • The entities.post script causes physics module to be executed because it tries to import PostBody
  • Finally, physics tries to import Post from entities.post
  • I'm not sure whether the entities.post module exists in memory yet, but it really doesn't matter. Either the module is not in memory, or the module doesn't yet have a Post member because it hasn't finished executing to define Post
  • Either way, an error occurs because Post is not there to be imported

So no, it's not "working further up in the call stack". This is a stack trace of where the error occurred, which means it errored out trying to import Post in that class. You shouldn't use circular imports. At best, it has negligible benefit (typically, no benefit), and it causes problems like this. It burdens any developer maintaining it, forcing them to walk on egg shells to avoid breaking it. Refactor your module organization.

Map vs Object in JavaScript

I came across this post by Minko Gechev which clearly explains the major differences.

enter image description here

Postgresql Select rows where column = array

In my case, I needed to work with a column that has the data, so using IN() didn't work. Thanks to @Quassnoi for his examples. Here is my solution:

SELECT column(s) FROM table WHERE expr|column = ANY(STRING_TO_ARRAY(column,',')::INT[])

I spent almost 6 hours before I stumble on the post.

In Chart.js set chart title, name of x axis and y axis?

just use this:

<script>
  var ctx = document.getElementById("myChart").getContext('2d');
  var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ["1","2","3","4","5","6","7","8","9","10","11",],
      datasets: [{
        label: 'YOUR LABEL',
        backgroundColor: [
          "#566573",
          "#99a3a4",
          "#dc7633",
          "#f5b041",
          "#f7dc6f",
          "#82e0aa",
          "#73c6b6",
          "#5dade2",
          "#a569bd",
          "#ec7063",
          "#a5754a"
        ],
        data: [12, 19, 3, 17, 28, 24, 7, 2,4,14,6],            
      },]
    },
    //HERE COMES THE AXIS Y LABEL
    options : {
      scales: {
        yAxes: [{
          scaleLabel: {
            display: true,
            labelString: 'probability'
          }
        }]
      }
    }
  });
</script>

Programmatically set image to UIImageView with Xcode 6.1/Swift

You just need to drag and drop an ImageView, create the outlet action, link it, and provide an image (Xcode is going to look in your assets folder for the name you provided (here: "toronto"))

In yourProject/ViewController.swift

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var imgView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        imgView.image = UIImage(named: "toronto")
    }
}

How do I get an element to scroll into view, using jQuery?

Simplest solution I have seen

var offset = $("#target-element").offset();
$('html, body').animate({
    scrollTop: offset.top,
    scrollLeft: offset.left
}, 1000);

Tutorial Here

How to play only the audio of a Youtube video using HTML 5?

_x000D_
_x000D_
// YouTube video ID
var videoID = "CMNry4PE93Y";

// Fetch video info (using a proxy to avoid CORS errors)
fetch('https://cors-anywhere.herokuapp.com/' + "https://www.youtube.com/get_video_info?video_id=" + videoID).then(response => {
  if (response.ok) {
    response.text().then(ytData => {
      
      // parse response to find audio info
      var ytData = parse_str(ytData);
      var getAdaptiveFormats = JSON.parse(ytData.player_response).streamingData.adaptiveFormats;
      var findAudioInfo = getAdaptiveFormats.findIndex(obj => obj.audioQuality);
      
      // get the URL for the audio file
      var audioURL = getAdaptiveFormats[findAudioInfo].url;
      
      // update the <audio> element src
      var youtubeAudio = document.getElementById('youtube');
      youtubeAudio.src = audioURL;
      
    });
  }
});

function parse_str(str) {
  return str.split('&').reduce(function(params, param) {
    var paramSplit = param.split('=').map(function(value) {
      return decodeURIComponent(value.replace('+', ' '));
    });
    params[paramSplit[0]] = paramSplit[1];
    return params;
  }, {});
}
_x000D_
<audio id="youtube" controls></audio>
_x000D_
_x000D_
_x000D_

ByRef argument type mismatch in Excel VBA

I don't know why, but it is very important to declare the variables separately if you want to pass variables (as variables) into other procedure or function.

For example there is a procedure which make some manipulation with data: based on ID returns Part Number and Quantity information. ID as constant value, other two arguments are variables.

Public Sub GetPNQty(ByVal ID As String, PartNumber As String, Quantity As Long)

the next main code gives me a "ByRef argument mismatch":

Sub KittingScan()  
Dim BoxPN As String
Dim BoxQty, BoxKitQty As Long

  Call GetPNQty(InputBox("Enter ID:"), BoxPN, BoxQty) 

End sub

and the next one is working as well:

Sub KittingScan()
Dim BoxPN As String
Dim BoxQty As Long
Dim BoxKitQty As Long

  Call GetPNQty(InputBox("Enter ID:"), BoxPN, BoxQty)

End sub

MIPS: Integer Multiplication and Division

To multiply, use mult for signed multiplication and multu for unsigned multiplication. Note that the result of the multiplication of two 32-bit numbers yields a 64-number. If you want the result back in $v0 that means that you assume the result will fit in 32 bits.

The 32 most significant bits will be held in the HI special register (accessible by mfhi instruction) and the 32 least significant bits will be held in the LO special register (accessible by the mflo instruction):

E.g.:

li $a0, 5
li $a1, 3
mult $a0, $a1
mfhi $a2 # 32 most significant bits of multiplication to $a2
mflo $v0 # 32 least significant bits of multiplication to $v0

To divide, use div for signed division and divu for unsigned division. In this case, the HI special register will hold the remainder and the LO special register will hold the quotient of the division.

E.g.:

div $a0, $a1
mfhi $a2 # remainder to $a2
mflo $v0 # quotient to $v0

Join two sql queries

I would just use a Union

In your second query add the extra column name and add a '' in all the corresponding locations in the other queries

Example

//reverse order to get the column names
select top 10 personId, '' from Telephone//No Column name assigned 
Union 
select top 10 personId, loanId from loan

How to turn off Wifi via ADB?

  1. go to location android/android-sdk/platform-tools
  2. shift+right click
  3. open cmd here and type the following commands

    1. adb shell
    2. su
    3. svc wifi enable/disable
  4. done!!!!!

Setting the selected attribute on a select list using jQuery

<select id="cars">
<option value='volvo'>volvo</option>
<option value='bmw'>bmw</option>
<option value='fiat'>fiat</option>
</select>

var make = "fiat";

$("#cars option[value='" + make + "']").attr("selected","selected");

Check if enum exists in Java

Just use valueOf() method. If the value doesn't exist, it throws IllegalArgumentException and you can catch it like that:

      boolean isSettingCodeValid = true;

       try {
            SettingCode.valueOf(settingCode.toUpperCase());
        } catch (IllegalArgumentException e) {
            // throw custom exception or change the isSettingCodeValid value
            isSettingCodeValid = false;
        }

What is the difference between required and ng-required?

I would like to make a addon for tiago's answer:

Suppose you're hiding element using ng-show and adding a required attribute on the same:

<div ng-show="false">
    <input required name="something" ng-model="name"/>
</div>

will throw an error something like :

An invalid form control with name='' is not focusable

This is because you just cannot impose required validation on hidden elements. Using ng-required makes it easier to conditionally apply required validation which is just awesome!!

Very Simple Image Slider/Slideshow with left and right button. No autoplay

Why try to reinvent the wheel? There are more lightweight jQuery slideshow solutions out there then you could poke a stick at, and someone has already done the hard work for you and thought about issues that you might run into (cross-browser compatability etc).

jQuery Cycle is one of my favourite light weight libraries.

What you want to achieve could be done in just

    jQuery("#slideshow").cycle({
    timeout:0, // no autoplay
    fx: 'fade', //fade effect, although there are heaps
    next: '#next',
    prev: '#prev'
    });

JSFIDDLE TO SEE HOW EASY IT IS

The infamous java.sql.SQLException: No suitable driver found

I found the followig tip helpful, to eliminate this issue in Tomcat -

be sure to load the driver first doing a Class.forName(" org.postgresql.Driver"); in your code.

This is from the post - https://www.postgresql.org/message-id/[email protected]

The jdbc code worked fine as a standalone program but, in TOMCAT it gave the error -'No suitable driver found'

How to read/process command line arguments?

I like getopt from stdlib, eg:

try:
    opts, args = getopt.getopt(sys.argv[1:], 'h', ['help'])
except getopt.GetoptError, err: 
    usage(err)

for opt, arg in opts:
    if opt in ('-h', '--help'): 
        usage()

if len(args) != 1:
    usage("specify thing...")

Lately I have been wrapping something similiar to this to make things less verbose (eg; making "-h" implicit).

How to access site through IP address when website is on a shared host?

Include the port number with the IP address.

For example:

http://19.18.20.101:5566

where 5566 is the port number.

How to get index of object by its property in JavaScript?

Just go through your array and find the position:

var i = 0;
for(var item in Data) {
    if(Data[item].name == 'John')
        break;
    i++;
}
alert(i);

C# Clear all items in ListView

Don't bother with Clear(). Just do this: ListView.DataSource = null; ListView.DataBind();

The key is the databind(); Works everytime for me.

How do I create/edit a Manifest file?

Go to obj folder in you app folder, then Debug. In there delete the manifest file and build again. It worked for me.

Android studio - Failed to find target android-18

Thank you RobertoAV96.

You're my hero. But it's not enough. In my case, I changed both compileSdkVersion, and buildToolsVersion. Now it work. Hope this help

buildscript {
       repositories {
           mavenCentral()
       }
       dependencies {
          classpath 'com.android.tools.build:gradle:0.6.+'
       }
   }
   apply plugin: 'android'

   dependencies {
       compile fileTree(dir: 'libs', include: '*.jar')
   }

   android {
       compileSdkVersion 19
       buildToolsVersion "19"

       sourceSets {
           main {
               manifest.srcFile 'AndroidManifest.xml'
               java.srcDirs = ['src']
               resources.srcDirs = ['src']
               aidl.srcDirs = ['src']
               renderscript.srcDirs = ['src']
               res.srcDirs = ['res']
               assets.srcDirs = ['assets']
           }

           // Move the tests to tests/java, tests/res, etc...
           instrumentTest.setRoot('tests')
           // Move the build types to build-types/<type>
           // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ..
           // This moves them out of them default location under src/<type>/... which would
           // conflict with src/ being used by the main source set.
           // Adding new build types or product flavors should be accompanied
           // by a similar customization.
           debug.setRoot('build-types/debug')
           release.setRoot('build-types/release')
       }
   }

HTML table with horizontal scrolling (first column fixed)

Take a look at this JQuery plugin:

http://fixedheadertable.com

It adds vertical (fixed header row) or horizontal (fixed first column) scrolling to an existing HTML table. There is a demo you can check for both cases of scrolling.

How to make the webpack dev server run on port 80 and on 0.0.0.0 to make it publicly accessible?

I tried the solutions above, but had no luck. I noticed this line in my project's package.json:

 "bin": {
"webpack-dev-server": "bin/webpack-dev-server.js"

},

I looked at bin/webpack-dev-server.js and found this line:

.describe("port", "The port").default("port", 8080)

I changed the port to 3000. A bit of a brute force approach, but it worked for me.

Opening new window in HTML for target="_blank"

You don't have that kind of control with a bare a tag. But you can hook up the tag's onclick handler to call window.open(...) with the right parameters. See here for examples: https://developer.mozilla.org/En/DOM/Window.open

I still don't think you can force window over tab directly though-- that depends on the browser and the user's settings.

How do I order my SQLITE database in descending order, for an android app?

We have one more option to do order by

public Cursor getlistbyrank(String rank) {
        try {
//This can be used
return db.`query("tablename", null, null, null, null, null, rank +"DESC",null );
OR
return db.rawQuery("SELECT * FROM table order by rank", null);
        } catch (SQLException sqle) {
            Log.e("Exception on query:-", "" + sqle.getMessage());
            return null;
        }
    }

You can use this two method for order

rebase in progress. Cannot commit. How to proceed or stop (abort)?

If git rebase --abort doesnt work and you still get

error: could not read '.git/rebase-apply/head-name': No such file or directory

Type:

git rebase --quit

How to save and load numpy.array() data properly?

np.save('data.npy', num_arr) # save
new_num_arr = np.load('data.npy') # load

Maven: Command to update repository after adding dependency to POM

mvn install (or mvn package) will always work.

You can use mvn compile to download compile time dependencies or mvn test for compile time and test dependencies but I prefer something that always works.

How to style a select tag's option element?

I have a workaround using jquery... although we cannot style a particular option, we can style the select itself - and use javascript to change the class of the select based on what is selected. It works sufficiently for simple cases.

_x000D_
_x000D_
$('select.potentially_red').on('change', function() {_x000D_
 if ($(this).val()=='red') {_x000D_
  $(this).addClass('option_red');_x000D_
 } else {_x000D_
  $(this).removeClass('option_red');_x000D_
 }_x000D_
});_x000D_
$('select.potentially_red').each( function() {_x000D_
 if ($(this).val()=='red') {_x000D_
  $(this).addClass('option_red');_x000D_
 } else {_x000D_
  $(this).removeClass('option_red');_x000D_
 }_x000D_
});
_x000D_
.option_red {_x000D_
    background-color: #cc0000; _x000D_
    font-weight: bold; _x000D_
    font-size: 12px; _x000D_
    color: white;_x000D_
}
_x000D_
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
<!-- The js will affect all selects which have the class 'potentially_red' -->_x000D_
<select name="color" class="potentially_red">_x000D_
    <option value="red">Red</option>_x000D_
    <option value="white">White</option>_x000D_
    <option value="blue">Blue</option>_x000D_
    <option value="green">Green</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Note that the js is in two parts, the each part for initializing everything on the page correctly, the .on('change', ... part for responding to change. I was unable to mangle the js into a function to DRY it up, it breaks it for some reason

Resource files not found from JUnit test cases

Make 'maven.test.skip' as false in pom file, while building project test reource will come under test-classes.

<maven.test.skip>false</maven.test.skip>

How to convert a char array to a string?

The string class has a constructor that takes a NULL-terminated C-string:

char arr[ ] = "This is a test";

string str(arr);


//  You can also assign directly to a string.
str = "This is another string";

// or
str = arr;

How to display pandas DataFrame of floats using a format string for columns?

Similar to unutbu above, you could also use applymap as follows:

import pandas as pd
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
                  index=['foo','bar','baz','quux'],
                  columns=['cost'])

df = df.applymap("${0:.2f}".format)

How to calculate number of days between two given dates?

If you have two date objects, you can just subtract them, which computes a timedelta object.

from datetime import date

d0 = date(2008, 8, 18)
d1 = date(2008, 9, 26)
delta = d1 - d0
print(delta.days)

The relevant section of the docs: https://docs.python.org/library/datetime.html.

See this answer for another example.

equivalent of vbCrLf in c#

"FirstLine" + "<br/>" "SecondLine"

How do I read image data from a URL in Python?

In Python3 the StringIO and cStringIO modules are gone.

In Python3 you should use:

from PIL import Image
import requests
from io import BytesIO

response = requests.get(url)
img = Image.open(BytesIO(response.content))

What is Turing Complete?

Its complete if it can test and branch (has an 'if')

Open directory using C

You should really post your code(a), but here goes. Start with something like:

    #include <stdio.h>
    #include <dirent.h>

    int main (int argc, char *argv[]) {
        struct dirent *pDirent;
        DIR *pDir;

        // Ensure correct argument count.

        if (argc != 2) {
            printf ("Usage: testprog <dirname>\n");
            return 1;
        }

        // Ensure we can open directory.

        pDir = opendir (argv[1]);
        if (pDir == NULL) {
            printf ("Cannot open directory '%s'\n", argv[1]);
            return 1;
        }

        // Process each entry.

        while ((pDirent = readdir(pDir)) != NULL) {
            printf ("[%s]\n", pDirent->d_name);
        }

        // Close directory and exit.

        closedir (pDir);
        return 0;
    }

You need to check in your case that args[1] is both set and refers to an actual directory. A sample run, with tmp is a subdirectory off my current directory but you can use any valid directory, gives me: testprog tmp

[.]
[..]
[file1.txt]
[file1_file1.txt]
[file2.avi]
[file2_file2.avi]
[file3.b.txt]
[file3_file3.b.txt]

Note also that you have to pass a directory in, not a file. When I execute:

testprog tmp/file1.txt

I get:

Cannot open directory 'tmp/file1.txt'

That's because it's a file rather than a directory (though, if you're sneaky, you can attempt to use diropen(dirname(argv[1])) if the initial diropen fails).


(a) This has now been rectified but, since this answer has been accepted, I'm going to assume it was the issue of whatever you were passing in.

Convert a Unix timestamp to time in JavaScript

See Date/Epoch Converter.

You need to ParseInt, otherwise it wouldn't work:


if (!window.a)
    window.a = new Date();

var mEpoch = parseInt(UNIX_timestamp);

if (mEpoch < 10000000000)
    mEpoch *= 1000;

------
a.setTime(mEpoch);
var year = a.getFullYear();
...
return time;

Get a list of dates between two dates using a function

All you have to do is just change the hard coded value in the code provided below

DECLARE @firstDate datetime
    DECLARE @secondDate datetime
    DECLARE @totalDays  INT
    SELECT @firstDate = getDate() - 30
    SELECT @secondDate = getDate()

    DECLARE @index INT
    SELECT @index = 0
    SELECT @totalDays = datediff(day, @firstDate, @secondDate)

    CREATE TABLE #temp
    (
         ID INT NOT NULL IDENTITY(1,1)
        ,CommonDate DATETIME NULL
    )

    WHILE @index < @totalDays
        BEGIN

            INSERT INTO #temp (CommonDate) VALUES  (DATEADD(Day, @index, @firstDate))   
            SELECT @index = @index + 1
        END

    SELECT CONVERT(VARCHAR(10), CommonDate, 102) as [Date Between] FROM #temp

    DROP TABLE #temp

How to put the legend out of the plot

It's worth refreshing this question, as newer versions of Matplotlib have made it much easier to position the legend outside the plot. I produced this example with Matplotlib version 3.1.1.

Users can pass a 2-tuple of coordinates to the loc parameter to position the legend anywhere in the bounding box. The only gotcha is you need to run plt.tight_layout() to get matplotlib to recompute the plot dimensions so the legend is visible:

import matplotlib.pyplot as plt

plt.plot([0, 1], [0, 1], label="Label 1")
plt.plot([0, 1], [0, 2], label='Label 2')

plt.legend(loc=(1.05, 0.5))
plt.tight_layout()

This leads to the following plot:

plot with legend outside

References:

git: fatal: Could not read from remote repository

Actually I tried a lot of things to make it work on Win7, since changing the SSH exectun fron native to build-it and backwards and the same error. By chance, i change it to HTTPS in the ".git/config" file as:

[remote "origin"]
        url = https://github.com/user_name/repository_name.git
        fetch = +refs/heads/*:refs/remotes/origin/*

and it finally worked. So maybe it could work for you as well.

Calling a php function by onclick event

Use this html code it will surely help you

<input type="button" value="NEXT"  onclick="document.write('<?php //call a function here ex- 'fun();' ?>');" />

one limitation is that it is taking more time to run so wait for few seconds it will work

How to center cards in bootstrap 4?

i basically suggest equal gap on right and left, and setting width to auto. Here like:

.bmi {         /*my additional class name -for card*/
    margin-left: 18%;      
    margin-right: 18%;
    width: auto;
}

How to write a file with C in Linux?

You need to write() the read() data into the new file:

ssize_t nrd;
int fd;
int fd1;

fd = open(aa[1], O_RDONLY);
fd1 = open(aa[2], O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
while (nrd = read(fd,buffer,50)) {
    write(fd1,buffer,nrd);
}

close(fd);
close(fd1);

Update: added the proper opens...

Btw, the O_CREAT can be OR'd (O_CREAT | O_WRONLY). You are actually opening too many file handles. Just do the open once.

Angular cookies

Update: angular2-cookie is now deprecated. Please use my ngx-cookie instead.

Old answer:

Here is angular2-cookie which is the exact implementation of Angular 1 $cookies service (plus a removeAll() method) that I created. It is using the same methods, only implemented in typescript with Angular 2 logic.

You can inject it as a service in the components providers array:

import {CookieService} from 'angular2-cookie/core';

@Component({
    selector: 'my-very-cool-app',
    template: '<h1>My Angular2 App with Cookies</h1>',
    providers: [CookieService]
})

After that, define it in the consturctur as usual and start using:

export class AppComponent { 
  constructor(private _cookieService:CookieService){}

  getCookie(key: string){
    return this._cookieService.get(key);
  }
}

You can get it via npm:

npm install angular2-cookie --save

The specified child already has a parent. You must call removeView() on the child's parent first (Android)

frameLayout.addView(bannerAdView); <----- if you get error on this line the do like below..

if (bannerAdView.getParent() != null)

  ((ViewGroup) bannerAdView.getParent()).removeView(bannerAdView);

   frameLayout.addView(bannerAdView);     <------ now added view

How to debug ORA-01775: looping chain of synonyms?

ORA-01775: looping chain of synonyms I faced the above error while I was trying to compile a Package which was using an object for which synonym was created however underlying object was not available.

HTML5 Canvas background image

Why don't you style it out:

<canvas id="canvas" width="800" height="600" style="background: url('./images/image.jpg')">
  Your browser does not support the canvas element.
</canvas>

Referencing a string in a string array resource with xml

Maybe this would help:

String[] some_array = getResources().getStringArray(R.array.your_string_array)

So you get the array-list as a String[] and then choose any i, some_array[i].

How to compile a c++ program in Linux?

You have to use g++ (as mentioned in other answers). On top of that you can think of providing some good options available at command line (which helps you avoid making ill formed code):

g++   -O4    -Wall hi.cpp -o hi.out
     ^^^^^   ^^^^^^
  optimize  related to coding mistakes

For more detail you can refer to man g++ | less.

Session unset, or session_destroy?

Something to be aware of, the $_SESSION variables are still set in the same page after calling session_destroy() where as this is not the case when using unset($_SESSION) or $_SESSION = array(). Also, unset($_SESSION) blows away the $_SESSION superglobal so only do this when you're destroying a session.

With all that said, it's best to do like the PHP docs has it in the first example for session_destroy().

How to return a resolved promise from an AngularJS Service using $q?

How to simply return a pre-resolved promise in AngularJS

Resolved promise:

return $q.when( someValue );    // angularjs 1.2+
return $q.resolve( someValue ); // angularjs 1.4+, alias to `when` to match ES6

Rejected promise:

return $q.reject( someValue );

Is it possible to run .php files on my local computer?

Sure you just need to setup a local web server. Check out XAMPP: http://www.apachefriends.org/en/xampp.html

That will get you up and running in about 10 minutes.

There is now a way to run php locally without installing a server: https://stackoverflow.com/a/21872484/672229


Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.

Basically you need apache / php running.

Convert International String to \u Codes in java

There's a command-line tool that ships with java called native2ascii. This converts unicode files to ASCII-escaped files. I've found that this is a necessary step for generating .properties files for localization.

PermissionError: [WinError 5] Access is denied python using moviepy to write gif

Sometimes it occurs when some installations are not completed correctly, the process is stuck, or a file is still opened. So, when you try to run the installation again and the installation requires deleting, you can see the aforementioned error. In my case, shutting down the python processes and command prompt utilization helped.

Troubleshooting "program does not contain a static 'Main' method" when it clearly does...?

In my case (where none of the proposed solutions fit), the problem was I used async/await where the signature for main method looked this way:

static async void Main(string[] args)

I simply removed async so the main method looked this way:

static void Main(string[] args)

I also removed all instances of await and used .Result for async calls, so my console application could compile happily.

add an onclick event to a div

Is it possible to add onclick to a div and have it occur if any area of the div is clicked.

Yes … although it should be done with caution. Make sure there is some mechanism that allows keyboard access. Build on things that work

If yes then why is the onclick method not going through to my div.

You are assigning a string where a function is expected.

divTag.onclick = printWorking;

There are nicer ways to assign event handlers though, although older versions of Internet Explorer are sufficiently different that you should use a library to abstract it. There are plenty of very small event libraries and every major library jQuery) has event handling functionality.

That said, now it is 2019, older versions of Internet Explorer no longer exist in practice so you can go direct to addEventListener

Creating a directory in /sdcard fails

The correct path to the sdcard is

/mnt/sdcard/

but, as answered before, you shouldn't hardcode it. If you are on Android 2.1 or after, use

getExternalFilesDir(String type) 

Otherwise:

Environment.getExternalStorageDirectory()

Read carefully https://developer.android.com/guide/topics/data/data-storage.html#filesExternal

Also, you'll need to use this method or something similar

boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {
    // We can read and write the media
    mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    // We can only read the media
    mExternalStorageAvailable = true;
    mExternalStorageWriteable = false;
} else {
    // Something else is wrong. It may be one of many other states, but all we need
    //  to know is we can neither read nor write
    mExternalStorageAvailable = mExternalStorageWriteable = false;
}

then check if you can access the sdcard. As said, read the official documentation.

Another option, maybe you need to use mkdirs instead of mkdir

file.mkdirs()

Creates the directory named by the trailing filename of this file, including the complete directory path required to create this directory.