Programs & Examples On #Fade

Fade refers to the UI technique of having page elements gradually gain or lose visibility, usually in response to a user action.

CSS3 Fade Effect

The scrolling effect is cause by specifying the generic 'background' property in your css instead of the more specific background-image. By setting the background property, the animation will transition between all properties.. Background-Color, Background-Image, Background-Position.. Etc Thus causing the scrolling effect..

E.g.

a {
-webkit-transition-property: background-image 300ms ease-in 200ms;
-moz-transition-property: background-image 300ms ease-in 200ms;
-o-transition-property: background-image 300ms ease-in 200ms;
transition: background-image 300ms ease-in 200ms;
}

Fade Effect on Link Hover?

Nowadays people are just using CSS3 transitions because it's a lot easier than messing with JS, browser support is reasonably good and it's merely cosmetic so it doesn't matter if it doesn't work.

Something like this gets the job done:

a {
  color:blue;
  /* First we need to help some browsers along for this to work.
     Just because a vendor prefix is there, doesn't mean it will
     work in a browser made by that vendor either, it's just for
     future-proofing purposes I guess. */
  -o-transition:.5s;
  -ms-transition:.5s;
  -moz-transition:.5s;
  -webkit-transition:.5s;
  /* ...and now for the proper property */
  transition:.5s;
}
a:hover { color:red; }

You can also transition specific CSS properties with different timings and easing functions by separating each declaration with a comma, like so:

a {
  color:blue; background:white;
  -o-transition:color .2s ease-out, background 1s ease-in;
  -ms-transition:color .2s ease-out, background 1s ease-in;
  -moz-transition:color .2s ease-out, background 1s ease-in;
  -webkit-transition:color .2s ease-out, background 1s ease-in;
  /* ...and now override with proper CSS property */
  transition:color .2s ease-out, background 1s ease-in;
}
a:hover { color:red; background:yellow; }

Demo here

Fade In on Scroll Down, Fade Out on Scroll Up - based on element position in window

I know it's late, but I take the original code and change some stuff to control easily the css. So I made a code with the addClass() and the removeClass()

Here the full code : http://jsfiddle.net/e5qaD/4837/

        if( bottom_of_window > bottom_of_object ){
            $(this).addClass('showme');
       }
        if( bottom_of_window < bottom_of_object ){
            $(this).removeClass('showme');

How do you fade in/out a background color using jquery?

Usually you can use the .animate() method to manipulate arbitrary CSS properties, but for background colors you need to use the color plugin. Once you include this plugin, you can use something like others have indicated $('div').animate({backgroundColor: '#f00'}) to change the color.

As others have written, some of this can be done using the jQuery UI library as well.

Can I change the Android startActivity() transition animation?

If you always want to the same transition animation for the activity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);

@Override
protected void onPause() {
    super.onPause();
    if (isFinishing()) {
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }
}

How to fade changing background image

This was the only reasonable thing I found to fade a background image.

<div id="foo">
  <!-- some content here -->
</div>

Your CSS; now enhanced with CSS3 transition.

#foo {
  background-image: url(a.jpg);
  transition: background 1s linear;
}

Now swap out the background

document.getElementById("foo").style.backgroundImage = "url(b.jpg)";

Voilà, it fades!


Obvious disclaimer: if your browser doesn't support the CSS3 transition property, this won't work. In which case, the image will change without a transition. Given <1% of your users' browser don't support CSS3, that's probably fine. Don't kid yourself, it's fine.

What is the difference between Nexus and Maven?

This has a good general description: https://gephi.wordpress.com/tag/maven/

Let me make a few statement that can put the difference in focus:

  1. We migrated our code base from Ant to Maven

  2. All 3rd party librairies have been uploaded to Nexus. Maven is using Nexus as a source for libraries.

  3. Basic functionalities of a repository manager like Sonatype are:

    • Managing project dependencies,
    • Artifacts & Metadata,
    • Proxying external repositories
    • and deployment of packaged binaries and JARs to share those artifacts with other developers and end-users.

php timeout - set_time_limit(0); - don't work

I usually use set_time_limit(30) within the main loop (so each loop iteration is limited to 30 seconds rather than the whole script).

I do this in multiple database update scripts, which routinely take several minutes to complete but less than a second for each iteration - keeping the 30 second limit means the script won't get stuck in an infinite loop if I am stupid enough to create one.

I must admit that my choice of 30 seconds for the limit is somewhat arbitrary - my scripts could actually get away with 2 seconds instead, but I feel more comfortable with 30 seconds given the actual application - of course you could use whatever value you feel is suitable.

Hope this helps!

Error "There is already an open DataReader associated with this Command which must be closed first" when using 2 distinct commands

Try to combine the query, it will run much faster than executing an additional query per row. Ik don't like the string[] you're using, i would create a class for holding the information.

    public List<string[]> get_dados_historico_verificacao_email_WEB(string email)
    {
        List<string[]> historicos = new List<string[]>();

        using (SqlConnection conexao = new SqlConnection("ConnectionString"))
        {
            string sql =
                @"SELECT    *, 
                            (   SELECT      COUNT(e.cd_historico_verificacao_email) 
                                FROM        emails_lidos e 
                                WHERE       e.cd_historico_verificacao_email = a.nm_email ) QT
                  FROM      historico_verificacao_email a
                  WHERE     nm_email = @email
                  ORDER BY  dt_verificacao_email DESC, 
                            hr_verificacao_email DESC";

            using (SqlCommand com = new SqlCommand(sql, conexao))
            {
                com.Parameters.Add("email", SqlDbType.VarChar).Value = email;

                SqlDataReader dr = com.ExecuteReader();

                while (dr.Read())
                {
                    string[] dados_historico = new string[6];
                    dados_historico[0] = dr["nm_email"].ToString();
                    dados_historico[1] = dr["dt_verificacao_email"].ToString();
                    dados_historico[1] = dados_historico[1].Substring(0, 10);
                    //System.Windows.Forms.MessageBox.Show(dados_historico[1]);
                    dados_historico[2] = dr["hr_verificacao_email"].ToString();
                    dados_historico[3] = dr["ds_tipo_verificacao"].ToString();
                    dados_historico[4] = dr["QT"].ToString();
                    dados_historico[5] = dr["cd_login_usuario"].ToString();

                    historicos.Add(dados_historico);
                }
            }
        }
        return historicos;
    }

Untested, but maybee gives some idea.

Is there a "between" function in C#?

Base @Dan J this version don't care max/min, more like sql :)

public static bool IsBetween(this decimal me, decimal a, decimal b, bool include = true)
{
    var left = Math.Min(a, b);
    var righ = Math.Max(a, b);

    return include
        ? (me >= left && me <= righ)
        : (me > left && me < righ)
    ;
}

Call method when home button pressed

The HOME button cannot be intercepted by applications. This is a by-design behavior in Android. The reason is to prevent malicious apps from gaining control over your phone (If the user cannot press back or home, he might never be able to exit the app). The Home button is considered the user's "safe zone" and will always launch the user's configured home app.

The only exception to the above is any app configured as home replacement. Which means it has the following declared in its AndroidManifest.xml for the relevant activity:

<intent-filter>
   <action android:name="android.intent.action.MAIN" />
   <category android:name="android.intent.category.HOME" />
   <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

When pressing the home button, the current home app's activity's onNewIntent will be called.

sql query with multiple where statements

This..

(
        (meta_key = 'lat' AND meta_value >= '60.23457047672217')
    OR
        (meta_key = 'lat' AND meta_value <= '60.23457047672217')
)

is the same as

(
        (meta_key = 'lat')
)

Adding it all together (the same applies to the long filter) you have this impossible WHERE clause which will give no rows because meta_key cannot be 2 values in one row

WHERE
    (meta_key = 'lat' AND meta_key = 'long' )

You need to review your operators to make sure you get the correct logic

HTML span align center not working?

A div is a block element, and will span the width of the container unless a width is set. A span is an inline element, and will have the width of the text inside it. Currently, you are trying to set align as a CSS property. Align is an attribute.

<span align="center" style="border:1px solid red;">
    This is some text in a div element!
</span>

However, the align attribute is deprecated. You should use the CSS text-align property on the container.

<div style="text-align: center;">
    <span style="border:1px solid red;">
        This is some text in a div element!
    </span>
</div>

Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object

In addition to import/export issues mentioned. I found using React.cloneElement() to add props to a child element and then rendering it gave me this same error.

I had to change:

render() {
  const ChildWithProps = React.cloneElement(
    this.props.children,
    { className: `${PREFIX}-anchor` }
  );

  return (
    <div>
      <ChildWithProps />
      ...
    </div>
  );
}

to:

render() {
  ...
  return (
    <div>
      <ChildWithProps.type {...ChildWithProps.props} />
    </div>
  );
}

See the React.cloneElement() docs for more info.

Python 3 sort a dict by its values

from collections import OrderedDict
from operator import itemgetter    

d = {"aa": 3, "bb": 4, "cc": 2, "dd": 1}
print(OrderedDict(sorted(d.items(), key = itemgetter(1), reverse = True)))

prints

OrderedDict([('bb', 4), ('aa', 3), ('cc', 2), ('dd', 1)])

Though from your last sentence, it appears that a list of tuples would work just fine, e.g.

from operator import itemgetter  

d = {"aa": 3, "bb": 4, "cc": 2, "dd": 1}
for key, value in sorted(d.items(), key = itemgetter(1), reverse = True):
    print(key, value)

which prints

bb 4
aa 3
cc 2
dd 1

How can I consume a WSDL (SOAP) web service in Python?

Zeep is a decent SOAP library for Python that matches what you're asking for: http://docs.python-zeep.org

How to replace text in a column of a Pandas dataframe?

In addition, for those looking to replace more than one character in a column, you can do it using regular expressions:

import re
chars_to_remove = ['.', '-', '(', ')', '']
regular_expression = '[' + re.escape (''. join (chars_to_remove)) + ']'

df['string_col'].str.replace(regular_expression, '', regex=True)

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

I don't want to have to enable a reference library as I need my scripts to be portable. The Dim foo As New VBScript_RegExp_55.RegExp line caused User Defined Type Not Defined errors, but I found a solution that worked for me.

Update RE comments w/ @chrisneilsen :

I was under the impression that enabling a reference library was tied to the local computers settings, but it is in fact, tied directly to the workbook. So, you can enable a reference library, share a macro enabled workbook and the end user wouldn't have to enable the library as well. Caveat: The advantage to Late Binding is that the developer does not have to worry about the wrong version of an object library being installed on the user's computer. This likely would not be an issue w/ the VBScript_RegExp_55.RegExp library, but I'm not sold that the "performance" benifit is worth it for me at this time, as we are talking imperceptible milliseconds in my code. I felt this deserved an update to help others understand. If you enable the reference library, you can use "early bind", but if you don't, as far as I can tell, the code will work fine, but you need to "late bind" and loose on some performance/debugging features.

Source: https://peltiertech.com/Excel/EarlyLateBinding.html

What you'll want to do is put an example string in cell A1, then test your strPattern. Once that's working adjust then rng as desired.

Public Sub RegExSearch()
'https://stackoverflow.com/questions/22542834/how-to-use-regular-expressions-regex-in-microsoft-excel-both-in-cell-and-loops
'https://wellsr.com/vba/2018/excel/vba-regex-regular-expressions-guide/
'https://www.vitoshacademy.com/vba-regex-in-excel/
    Dim regexp As Object
    'Dim regex As New VBScript_RegExp_55.regexp 'Caused "User Defined Type Not Defined" Error
    Dim rng As Range, rcell As Range
    Dim strInput As String, strPattern As String
    
    Set regexp = CreateObject("vbscript.regexp")
    Set rng = ActiveSheet.Range("A1:A1")
        
    strPattern = "([a-z]{2})([0-9]{8})"
    'Search for 2 Letters then 8 Digits Eg: XY12345678 = Matched

    With regexp
        .Global = False
        .MultiLine = False
        .ignoreCase = True
        .Pattern = strPattern
    End With

    For Each rcell In rng.Cells

        If strPattern <> "" Then
            strInput = rcell.Value

            If regexp.test(strInput) Then
                MsgBox rcell & " Matched in Cell " & rcell.Address
            Else
                MsgBox "No Matches!"
            End If
        End If
    Next
End Sub

LINUX: Link all files from one to another directory

ln -s /mnt/usr/lib/* /usr/lib/

I guess, this belongs to superuser, though.

how can I login anonymously with ftp (/usr/bin/ftp)?

As others point out, the user name is usually anonymous, and the password is usually your e-mail address, but this is not universally true, and has been found not to work for certain anonymous FTP sites. For example, at least some cPanel sites seem to deviate from the norm, and if given the traditional user name without domain, one of various errors may result:

If the server uses Pure-FTP as the FTP server:

421 Can't change directory to /var/ftp/ error message.

If the server uses ProFTP as the FTP server:

530 Login Authentication Failed error message.

When one of the aforementioned errors occurs when attempting anonymous access, try including a domain with the username. For example, where example.com is the domain used in your e-mail address:

User name: [email protected]

In the specific case of a cPanel site, the password value is unimportant, and may be left blank, but there is no harm in providing a "traditional" anonymous password formatted as an e-mail address.

For reference, this answer is based on content found on a documentation.cpanel.net Anonymous FTP page. At the time of this writing, it stated:

When users log in to FTP anonymously, they must format usernames as [email protected], where example.com represents the user's domain name. This requirement directs your server to the correct public_ftp directory.

how to Call super constructor in Lombok

for superclasses with many members I would suggest you to use @Delegate

@Data
public class A {
    @Delegate public class AInner{
        private final int x;
        private final int y;
    }
}

@Data
@EqualsAndHashCode(callSuper = true)
public class B extends A {
    private final int z;

    public B(A.AInner a, int z) {
        super(a);
        this.z = z;
    }
}

How do I make background-size work in IE?

A bit late, but this could also be useful. There is an IE filter, for IE 5.5+, which you can apply:

filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='images/logo.gif',
sizingMethod='scale');

-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='images/logo.gif',
sizingMethod='scale')";

However, this scales the entire image to fit in the allocated area, so if you're using a sprite, this may cause issues.

Specification: AlphaImageLoader Filter @microsoft

PHP - iterate on string characters

Most of the answers forgot about non English characters !!!

strlen counts BYTES, not characters, that is why it is and it's sibling functions works fine with English characters, because English characters are stored in 1 byte in both UTF-8 and ASCII encodings, you need to use the multibyte string functions mb_*

This will work with any character encoded in UTF-8

// 8 characters in 12 bytes
$string = "abcd????";

$charsCount = mb_strlen($string, 'UTF-8');
for($i = 0; $i < $charsCount; $i++){
    $char = mb_substr($string, $i, 1, 'UTF-8');
    var_dump($char);
}

This outputs

string(1) "a"
string(1) "b"
string(1) "c"
string(1) "d"
string(2) "?"
string(2) "?"
string(2) "?"
string(2) "?"

Oracle SQL escape character (for a '&')

the & is the default value for DEFINE, which allows you to use substitution variables. I like to turn it off using

SET DEFINE OFF

then you won't have to worry about escaping or CHR(38).

In DB2 Display a table's definition

DB2 Version 11.0

Columns:
--------
SELECT NAME,COLTYPE,NULLS,LENGTH,SCALE,DEFAULT,DEFAULTVALUE FROM SYSIBM.SYSCOLUMNS where TBcreator ='ME' and TBNAME ='MY_TABLE' ORDER BY COLNO;

Indexes:
--------
SELECT P.SPACE, K.IXNAME, I.UNIQUERULE, I.CLUSTERING, K.COLNAME, K.COLNO, K.ORDERING
FROM SYSIBM.SYSINDEXES I
    JOIN SYSIBM.SYSINDEXPART P
        ON I.NAME = P.IXNAME
        AND I.CREATOR = P.IXCREATOR
    JOIN SYSIBM.SYSKEYS K
        ON P.IXNAME = K.IXNAME
        AND P.IXCREATOR = K.IXCREATOR
WHERE I.TBcreator ='ME' and I.TBNAME ='MY_TABLE'
ORDER BY K.IXNAME, K.COLSEQ;

Prevent the keyboard from displaying on activity start

You can also write these lines of code in the direct parent layout of the .xml layout file in which you have the "problem":

android:focusable="true"
android:focusableInTouchMode="true"

For example:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    ...
    android:focusable="true"
    android:focusableInTouchMode="true" >

    <EditText
        android:id="@+id/myEditText"
        ...
        android:hint="@string/write_here" />

    <Button
        android:id="@+id/button_ok"
        ...
        android:text="@string/ok" />
</LinearLayout>


EDIT :

Example if the EditText is contained in another layout:

<?xml version="1.0" encoding="utf-8"?>
<ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    ... >                                            <!--not here-->

    ...    <!--other elements-->

    <LinearLayout
        android:id="@+id/theDirectParent"
        ...
        android:focusable="true"
        android:focusableInTouchMode="true" >        <!--here-->

        <EditText
            android:id="@+id/myEditText"
            ...
            android:hint="@string/write_here" />

        <Button
            android:id="@+id/button_ok"
            ...
            android:text="@string/ok" />
    </LinearLayout>

</ConstraintLayout>

The key is to make sure that the EditText is not directly focusable.
Bye! ;-)

How to convert a date String to a Date or Calendar object?

The DateFormat class has a parse method.

See DateFormat for more information.

Serializing PHP object to JSON

Just implement an Interface given by PHP JsonSerializable.

Conditionally Remove Dataframe Rows with R

Use the which function:

A <- c('a','a','b','b','b')
B <- c(1,0,1,1,0)
d <- data.frame(A, B)

r <- with(d, which(B==0, arr.ind=TRUE))
newd <- d[-r, ]

Multidimensional Array [][] vs [,]

double[][] is an array of arrays and double[,] is a matrix. If you want to initialize an array of array, you will need to do this:

double[][] ServicePoint = new double[10][]
for(var i=0;i<ServicePoint.Length;i++)
    ServicePoint[i] = new double[9];

Take in account that using arrays of arrays will let you have arrays of different lengths:

ServicePoint[0] = new double[10];
ServicePoint[1] = new double[3];
ServicePoint[2] = new double[5];
//and so on...

How to create a session using JavaScript?

I assume you are using ASP.NET MVC (C#), if not then this answer is not in your issue.

Is it impossible to assign session values directly through javascript? No, there is a way to do that.

Look again your code:

<script type="text/javascript" >
{
Session["controlID"] ="This is my session";
}
</script> 

A little bit change:

<script type="text/javascript" >
{
  <%Session["controlID"] = "This is my session";%>
}
</script>

The session "controlID" has created, but what about the value of session? is that persistent or can changeable via javascript?

Let change a little bit more:

<script type="text/javascript" >
{
  var strTest = "This is my session"; 
  <%Session["controlID"] = "'+ strTest +'";%>
}
</script>

The session is created, but the value inside of session will be "'+ strTest +'" but not "This is my session". If you try to write variable directly into server code like:

<%Session["controlID"] = strTest;%>

Then an error will occur in you page "There is no parameter strTest in current context...". Until now it is still seem impossible to assign session values directly through javascript.

Now I move to a new way. Using WebMethod at code behind to do that. Look again your code with a little bit change:

<script type="text/javascript" >
{
 var strTest = "This is my session"; 
 PageMethods.CreateSessionViaJavascript(strTest);
}
</script> 

In code-behind page. I create a WebMethod:

[System.Web.Services.WebMethod]
public static string CreateSessionViaJavascript(string strTest)
{
    Page objp = new Page();
    objp.Session["controlID"] = strTest; 
    return strTest;
}

After call the web method to create a session from javascript. The session "controlID" will has value "This is my session".

If you use the way I have explained, then please add this block of code inside form tag of your aspx page. The code help to enable page methods.

<asp:ScriptManager EnablePageMethods="true" ID="MainSM" runat="server" ScriptMode="Release" LoadScriptsBeforeUI="true"></asp:ScriptManager>

Source: JavaScript - How to Set values to Session in Javascript

Happy codding, Tri

Regular Expression to get a string between parentheses in Javascript

_x000D_
_x000D_
let str = "Before brackets (Inside brackets) After brackets".replace(/.*\(|\).*/g, '');_x000D_
console.log(str) // Inside brackets
_x000D_
_x000D_
_x000D_

How to get a list of all valid IP addresses in a local network?

Try following steps:

  1. Type ipconfig (or ifconfig on Linux) at command prompt. This will give you the IP address of your own machine. For example, your machine's IP address is 192.168.1.6. So your broadcast IP address is 192.168.1.255.
  2. Ping your broadcast IP address ping 192.168.1.255 (may require -b on Linux)
  3. Now type arp -a. You will get the list of all IP addresses on your segment.

Border in shape xml

We can add drawable .xml like below

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">


    <stroke
        android:width="1dp"
        android:color="@color/color_C4CDD5"/>

    <corners android:radius="8dp"/>

    <solid
        android:color="@color/color_white"/>

</shape>

Load properties file in JAR?

For the record, this is documented in How do I add resources to my JAR? (illustrated for unit tests but the same applies for a "regular" resource):

To add resources to the classpath for your unit tests, you follow the same pattern as you do for adding resources to the JAR except the directory you place resources in is ${basedir}/src/test/resources. At this point you would have a project directory structure that would look like the following:

my-app
|-- pom.xml
`-- src
    |-- main
    |   |-- java
    |   |   `-- com
    |   |       `-- mycompany
    |   |           `-- app
    |   |               `-- App.java
    |   `-- resources
    |       `-- META-INF
    |           |-- application.properties
    `-- test
        |-- java
        |   `-- com
        |       `-- mycompany
        |           `-- app
        |               `-- AppTest.java
        `-- resources
            `-- test.properties

In a unit test you could use a simple snippet of code like the following to access the resource required for testing:

...

// Retrieve resource
InputStream is = getClass().getResourceAsStream("/test.properties" );

// Do something with the resource

...

How do I combine the first character of a cell with another cell in Excel?

Not sure why no one is using semicolons. This is how it works for me:

=CONCATENATE(LEFT(A1;1); B1)

Solutions with comma produce an error in Excel.

Finding the average of an array using JS

For the second part of your question you can use reduce to good effect here:

_x000D_
_x000D_
const grades = [80, 77, 88, 95, 68];_x000D_
_x000D_
function getAvg(grades) {_x000D_
  const total = grades.reduce((acc, c) => acc + c, 0);_x000D_
  return total / grades.length;_x000D_
}_x000D_
_x000D_
const average = getAvg(grades);_x000D_
console.log(average);
_x000D_
_x000D_
_x000D_

The other answers have given good insight into why you got 68, so I won't repeat it here.

jQuery select option elements by value

You can use .val() to select the value, like the following:

function select_option(i) {
    $("#span_id select").val(i);
}

Here is a jsfiddle: https://jsfiddle.net/tweissin/uscq42xh/8/

How to fix libeay32.dll was not found error

Download libeay32.dll and ssleay32.dll binary package for 32Bit and 64Bit from http://indy.fulgan.com/SSL/ then put it into executable or System32 directory.

Asp.net 4.0 has not been registered

I had the same issue but solved it...... Microsoft has a fix for something close to this that actually worked to solve this issue. you can visit this page http://blogs.msdn.com/b/webdev/archive/2014/11/11/dialog-box-may-be-displayed-to-users-when-opening-projects-in-microsoft-visual-studio-after-installation-of-microsoft-net-framework-4-6.aspx

The issue occurs after you installed framework 4.5 and/or framework 4.6. The Visual Studio 2012 Update 5 doesn't fix the issue, I tried that first.

The msdn blog has this to say: "After the installation of the Microsoft .NET Framework 4.6, users may experience the following dialog box displayed in Microsoft Visual Studio when either creating new Web Site or Windows Azure project or when opening existing projects....."

According to the Blog the dialog is benign. just click OK, nothing is effected by the dialog... The comments in the blog suggests that VS 2015 has the same problem, maybe even worse.

Add resources, config files to your jar using gradle

I ran into the same problem. I had a PNG file in a Java package and it wasn't exported in the final JAR along with the sources, which caused the app to crash upon start (file not found).

None of the answers above solved my problem but I found the solution on the Gradle forums. I added the following to my build.gradle file :

sourceSets.main.resources.srcDirs = [ "src/" ]
sourceSets.main.resources.includes = [ "**/*.png" ]

It tells Gradle to look for resources in the src folder, and ask it to include only PNG files.

EDIT: Beware that if you're using Eclipse, this will break your run configurations and you'll get a main class not found error when trying to run your program. To fix that, the only solution I've found is to move the image(s) to another directory, res/ for example, and to set it as srcDirs instead of src/.

Magento - How to add/remove links on my account navigation?

Most of the above work, but for me, this was the easiest.

Install the plugin, log out, log in, system, advanced, front end links manager, check and uncheck the options you want to show. It also works on any of the front end navigation's on your site.

http://www.magentocommerce.com/magento-connect/frontend-links-manager.html

resize font to fit in a div (on one line)

I've make a very little jQuery stuff to adjust the font size of your div. It even works with multiple lines, but will only increase font's size (you can simply set a default font size of 1px if you want). I increases the font size until having a line break, set decreases it 1px. No other fancy stuff, hidden div or so. Simply add the quickfit class to your div.

$(".quickfit").each(function() {
    var jThis=$(this);
    var fontSize=parseInt(jThis.css("font-size"));
    var originalLines=jThis.height()/fontSize;

    for(var i=0;originalLines>=jThis.height()/fontSize && i<30;i++)
    { jThis.css("font-size",""+(++fontSize)+"px"); }
    jThis.css("font-size",""+(fontSize-1)+"px");
});

Reading a resource file from within jar

The problem is that certain third party libraries require file pathnames rather than input streams. Most of the answers don't address this issue.

In this case, one workaround is to copy the resource contents into a temporary file. The following example uses jUnit's TemporaryFolder.

    private List<String> decomposePath(String path){
        List<String> reversed = Lists.newArrayList();
        File currFile = new File(path);
        while(currFile != null){
            reversed.add(currFile.getName());
            currFile = currFile.getParentFile();
        }
        return Lists.reverse(reversed);
    }

    private String writeResourceToFile(String resourceName) throws IOException {
        ClassLoader loader = getClass().getClassLoader();
        InputStream configStream = loader.getResourceAsStream(resourceName);
        List<String> pathComponents = decomposePath(resourceName);
        folder.newFolder(pathComponents.subList(0, pathComponents.size() - 1).toArray(new String[0]));
        File tmpFile = folder.newFile(resourceName);
        Files.copy(configStream, tmpFile.toPath(), REPLACE_EXISTING);
        return tmpFile.getAbsolutePath();
    }

Is there a REAL performance difference between INT and VARCHAR primary keys?

The question is about MySQL so I say there is a significant difference. If it was about Oracle (which stores numbers as string - yes, I couldn't believe it at first) then not much difference.

Storage in the table is not the issue but updating and referring to the index is. Queries involving looking up a record based on its primary key are frequent - you want them to occur as fast as possible because they happen so often.

The thing is a CPU deals with 4 byte and 8 byte integers naturally, in silicon. It's REALLY fast for it to compare two integers - it happens in one or two clock cycles.

Now look at a string - it's made up of lots of characters (more than one byte per character these days). Comparing two strings for precedence can't be done in one or two cycles. Instead the strings' characters must be iterated until a difference is found. I'm sure there are tricks to make it faster in some databases but that's irrelevant here because an int comparison is done naturally and lightning fast in silicon by the CPU.

My general rule - every primary key should be an autoincrementing INT especially in OO apps using an ORM (Hibernate, Datanucleus, whatever) where there's lots of relationships between objects - they'll usually always be implemented as a simple FK and the ability for the DB to resolve those fast is important to your app' s responsiveness.

Controlling Spacing Between Table Cells

Check this fiddle. You are going to need to take a look at using border-collapse and border-spacing. There are some quirks for IE (as usual). This is based on an answer to this question.

_x000D_
_x000D_
table.test td {
  background-color: lime;
  margin: 12px 12px 12px 12px;
  padding: 12px 12px 12px 12px;
}

table.test {
  border-collapse: separate;
  border-spacing: 10px;
  *border-collapse: expression('separate', cellSpacing='10px');
}
_x000D_
<table class="test">
  <tr>
    <td>Cell</td>
    <td>Cell</td>
    <td>Cell</td>
  </tr>
  <tr>
    <td>Cell</td>
    <td>Cell</td>
    <td>Cell</td>
  </tr>
  <tr>
    <td>Cell</td>
    <td>Cell</td>
    <td>Cell</td>
  </tr>
</table>
_x000D_
_x000D_
_x000D_

What does the "@" symbol do in SQL?

You may be used to MySQL's syntax: Microsoft SQL @ is the same as the MySQL's ?

How to read request body in an asp.net core webapi controller?

A clearer solution, works in ASP.Net Core 2.1 / 3.1

Filter class

using Microsoft.AspNetCore.Authorization;
// For ASP.NET 2.1
using Microsoft.AspNetCore.Http.Internal;
// For ASP.NET 3.1
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;

public class ReadableBodyStreamAttribute : AuthorizeAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        // For ASP.NET 2.1
        // context.HttpContext.Request.EnableRewind();
        // For ASP.NET 3.1
        // context.HttpContext.Request.EnableBuffering();
    }
}

In an Controller

[HttpPost]
[ReadableBodyStream]
public string SomePostMethod()
{
    //Note: if you're late and body has already been read, you may need this next line
    //Note2: if "Note" is true and Body was read using StreamReader too, then it may be necessary to set "leaveOpen: true" for that stream.
    HttpContext.Request.Body.Seek(0, SeekOrigin.Begin);

    using (StreamReader stream = new StreamReader(HttpContext.Request.Body))
    {
        string body = stream.ReadToEnd();
        // body = "param=somevalue&param2=someothervalue"
    }
}

Open source PDF library for C/C++ application?

PDF Hummus. see for http://pdfhummus.com/ - contains all required features for manipulation with PDF files except rendering.

How to make Java work with SQL Server?

Have you tried the jtds driver for SQLServer?

Android Studio: Where is the Compiler Error Output Window?

I solved this error "Compilation failed to see the compiler error output for details"

The solution is very Simple: Add in a Gradle below a line of code

implementation 'com.google.android.gms:play-services-ads:15.0.0'

Tool to Unminify / Decompress JavaScript

If you have a Mac and TextMate - An easy alternative for formatting Javascript is:

  1. Open the file with Textmate.
  2. Click on > Bundles > JavaScript > Reformat Document
  3. Crack open a beer.

How to apply multiple transforms in CSS?

Transform Rotate and Translate in single line css:-How?

_x000D_
_x000D_
div.className{_x000D_
    transform : rotate(270deg) translate(-50%, 0);    _x000D_
    -webkit-transform: rotate(270deg) translate(-50%, -50%);    _x000D_
    -moz-transform: rotate(270deg) translate(-50%, -50%);    _x000D_
    -ms-transform: rotate(270deg) translate(-50%, -50%);    _x000D_
    -o-transform: rotate(270deg) translate(-50%, -50%); _x000D_
    float:left;_x000D_
    position:absolute;_x000D_
    top:50%;_x000D_
    left:50%;_x000D_
    }
_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<div class="className">_x000D_
  <span style="font-size:50px">A</span>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

MySQL's now() +1 day

Try doing: INSERT INTO table(data, date) VALUES ('$data', now() + interval 1 day)

How to debug in Android Studio using adb over WiFi

I used the following steps to successfully debug over wifi connection. I recommend this solution to everybody experiencing problems using integrated solutions like Android WiFi ADB plugin. In my case it failed to keep the Wifi connection to my device after unplugging USB. The following solution overcomes this problem.

1. Connecting device

a. Connecting device using local wlan

If you have a local wlan you can connect your android device and your pc to this wlan. Then identify the IP address of the android device by looking into its wlan settings.

b. Connecting device directly using a hotspot

I prefer to connect with a hotspot on the device. This is more private and does not open your debugging connection to the (public) wlan.

  1. Create a Wifi hotspot on the Android device
  2. Connect PC to hotspot
  3. On PC look into network connection status of this hotspot connection to find the IPADDRESS of your device.
    My system showed IPADDRESS 192.168.43.1

2. Create debugging connection

  1. Connect your device to USB.
  2. Issue command adb tcpip 5555 to open a port on the device for adb connection.
  3. Create wireless debugging connection adb connect IPADDRESS.
    In my case the command looked like adb connect 192.168.43.1

The command adb devices -l should now display two devices if everything is ok. For example:

List of devices attached
ZY2244N2ZZ             device product:athene model:Moto_G__4_ device:athene
192.168.43.1:5555      device product:athene model:Moto_G__4_ device:athene

3. Keeping debugging connection

The tricky part comes when unplugging the USB connection. In my case both connections are closed immediately! This may not be the case for all users. For me this was the reason that I could not use Android WiFi ADB plugin for android studio. I solved the problem by manually reconnecting the Wifi after unplugging usb by

adb connect 192.168.43.1

After that adb devices -lshows a single wifi connected device. This devices shows also up in android studio and can then be selected for debugging. When the connection is unstable you may need to repeat the above command from time to time to reactivate the connection.

What is the difference between a strongly typed language and a statically typed language?

This is often misunderstood so let me clear it up.

Static/Dynamic Typing

Static typing is where the type is bound to the variable. Types are checked at compile time.

Dynamic typing is where the type is bound to the value. Types are checked at run time.

So in Java for example:

String s = "abcd";

s will "forever" be a String. During its life it may point to different Strings (since s is a reference in Java). It may have a null value but it will never refer to an Integer or a List. That's static typing.

In PHP:

$s = "abcd";          // $s is a string
$s = 123;             // $s is now an integer
$s = array(1, 2, 3);  // $s is now an array
$s = new DOMDocument; // $s is an instance of the DOMDocument class

That's dynamic typing.

Strong/Weak Typing

(Edit alert!)

Strong typing is a phrase with no widely agreed upon meaning. Most programmers who use this term to mean something other than static typing use it to imply that there is a type discipline that is enforced by the compiler. For example, CLU has a strong type system that does not allow client code to create a value of abstract type except by using the constructors provided by the type. C has a somewhat strong type system, but it can be "subverted" to a degree because a program can always cast a value of one pointer type to a value of another pointer type. So for example, in C you can take a value returned by malloc() and cheerfully cast it to FILE*, and the compiler won't try to stop you—or even warn you that you are doing anything dodgy.

(The original answer said something about a value "not changing type at run time". I have known many language designers and compiler writers and have not known one that talked about values changing type at run time, except possibly some very advanced research in type systems, where this is known as the "strong update problem".)

Weak typing implies that the compiler does not enforce a typing discpline, or perhaps that enforcement can easily be subverted.

The original of this answer conflated weak typing with implicit conversion (sometimes also called "implicit promotion"). For example, in Java:

String s = "abc" + 123; // "abc123";

This is code is an example of implicit promotion: 123 is implicitly converted to a string before being concatenated with "abc". It can be argued the Java compiler rewrites that code as:

String s = "abc" + new Integer(123).toString();

Consider a classic PHP "starts with" problem:

if (strpos('abcdef', 'abc') == false) {
  // not found
}

The error here is that strpos() returns the index of the match, being 0. 0 is coerced into boolean false and thus the condition is actually true. The solution is to use === instead of == to avoid implicit conversion.

This example illustrates how a combination of implicit conversion and dynamic typing can lead programmers astray.

Compare that to Ruby:

val = "abc" + 123

which is a runtime error because in Ruby the object 123 is not implicitly converted just because it happens to be passed to a + method. In Ruby the programmer must make the conversion explicit:

val = "abc" + 123.to_s

Comparing PHP and Ruby is a good illustration here. Both are dynamically typed languages but PHP has lots of implicit conversions and Ruby (perhaps surprisingly if you're unfamiliar with it) doesn't.

Static/Dynamic vs Strong/Weak

The point here is that the static/dynamic axis is independent of the strong/weak axis. People confuse them probably in part because strong vs weak typing is not only less clearly defined, there is no real consensus on exactly what is meant by strong and weak. For this reason strong/weak typing is far more of a shade of grey rather than black or white.

So to answer your question: another way to look at this that's mostly correct is to say that static typing is compile-time type safety and strong typing is runtime type safety.

The reason for this is that variables in a statically typed language have a type that must be declared and can be checked at compile time. A strongly-typed language has values that have a type at run time, and it's difficult for the programmer to subvert the type system without a dynamic check.

But it's important to understand that a language can be Static/Strong, Static/Weak, Dynamic/Strong or Dynamic/Weak.

How do I find the length of an array?

I provide a tricky solution here:

You can always store length in the first element:

// malloc/new

arr[0] = length;
arr++;

// do anything. 
int len = *(arr-1);

free(--arr); 

The cost is you must --arr when invoke free

Cannot open backup device. Operating System error 5

Yeah I just scored this one.

Look in Windows Services. Start > Administration > Services

Find the Service in the list called: SQL Server (MSSQLSERVER) look for the "Log On As" column (need to add it if it doesn't exist in the list).

This is the account you need to give permissions to the directory, right click in explorer > properties > Shares (And Security)

NOTE: Remember to give permissions to the actual directory AND to the share if you are going across the network.

Apply and wait for the permissions to propogate, try the backup again.

NOTE 2: if you are backing up across the network and your SQL is running as "Local Service" then you are in trouble ... you can try assigning permissions or it may be easier to backup locally and xcopy across outside of SQL Server (an hour later).

NOTE 3: If you're running as network service then SOMETIMES the remote machine will not recognize the network serivce on your SQL Server. If this is the case you need to add permissions for the actual computer itself eg. MyServer$.

How to execute Table valued function

A TVF (table-valued function) is supposed to be SELECTed FROM. Try this:

select * from FN('myFunc')

How do I convert seconds to hours, minutes and seconds?

dateutil.relativedelta is convenient if you need to access hours, minutes and seconds as floats as well. datetime.timedelta does not provide a similar interface.

from dateutil.relativedelta import relativedelta
rt = relativedelta(seconds=5440)
print(rt.seconds)
print('{:02d}:{:02d}:{:02d}'.format(
    int(rt.hours), int(rt.minutes), int(rt.seconds)))

Prints

40.0
01:30:40

Equivalent of explode() to work with strings in MySQL

use substring_index, in the example below i have created a table with column score1 and score2, score1 has 3-7, score2 7-3 etc as shown in the image. The below query is able to split using "-" and reverse the order of score2 and compare to score1

SELECT CONCAT(
  SUBSTRING_INDEX(score1, '-', 1),
  SUBSTRING_INDEX(score1,'-',-1)
) AS my_score1,
CONCAT(
  SUBSTRING_INDEX(score2, '-', -1),
  SUBSTRING_INDEX(score2, '-', 1)
) AS my_score2
FROM test HAVING my_score1=my_score2

scores table

query results

Create a 3D matrix

Create a 3D matrix

A = zeros(20, 10, 3);   %# Creates a 20x10x3 matrix

Add a 3rd dimension to a matrix

B = zeros(4,4);  
C = zeros(size(B,1), size(B,2), 4);  %# New matrix with B's size, and 3rd dimension of size 4
C(:,:,1) = B;                        %# Copy the content of B into C's first set of values

zeros is just one way of making a new matrix. Another could be A(1:20,1:10,1:3) = 0 for a 3D matrix. To confirm the size of your matrices you can run: size(A) which gives 20 10 3.

There is no explicit bound on the number of dimensions a matrix may have.

What do raw.githubusercontent.com URLs represent?

raw.githubusercontent.com/username/repo-name/branch-name/path

Replace username with the username of the user that created the repo.

Replace repo-name with the name of the repo.

Replace branch-name with the name of the branch.

Replace path with the path to the file.

To reverse to go to GitHub.com:

GitHub.com/username/repo-name/directory-path/blob/branch-name/filename

Why can't I set text to an Android TextView?

I was having a similar problem, however my program would crash when I tried to set the text. I was attempting to set the text value from within a class that extends AsyncTask, and that was what was causing the problem.

To resolve it, I moved my setText to the onPostExecute method

protected void onPostExecute(Void result) {
    super.onPostExecute(result);

    TextView text = (TextView) findViewById(R.id.errorsToday);
    text.setText("new string value");
}

Find if current time falls in a time range

Try using the TimeRange object in C# to complete your goal.

TimeRange timeRange = new TimeRange();
timeRange = TimeRange.Parse("13:00-14:00");

bool IsNowInTheRange = timeRange.IsIn(DateTime.Now.TimeOfDay);
Console.Write(IsNowInTheRange);

Here is where I got that example of using TimeRange

Convert HttpPostedFileBase to byte[]

As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:

MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();

It's easy enough to write the equivalent of CopyTo in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream.

For efficient purposes you could check whether the stream returned is already a MemoryStream:

byte[] data;
using (Stream inputStream = model.File.InputStream)
{
    MemoryStream memoryStream = inputStream as MemoryStream;
    if (memoryStream == null)
    {
        memoryStream = new MemoryStream();
        inputStream.CopyTo(memoryStream);
    }
    data = memoryStream.ToArray();
}

Find p-value (significance) in scikit-learn LinearRegression

There could be a mistake in @JARH's answer in the case of a multivariable regression. (I do not have enough reputation to comment.)

In the following line:

p_values =[2*(1-stats.t.cdf(np.abs(i),(len(newX)-1))) for i in ts_b],

the t-values follows a chi-squared distribution of degree len(newX)-1 instead of following a chi-squared distribution of degree len(newX)-len(newX.columns)-1.

So this should be:

p_values =[2*(1-stats.t.cdf(np.abs(i),(len(newX)-len(newX.columns)-1))) for i in ts_b]

(See t-values for OLS regression for more details)

How do I make an Android EditView 'Done' button and hide the keyboard when clicked?

If you don't want any button at all (e.g. you are developing a GUI for blind people where tap cannot be positional and you rely on single/double/long taps):

text.setItemOptions(EditorInfo.IME_ACTION_NONE)

Or in Kotlin:

text.imeOptions = EditorInfo.IME_ACTION_NONE

Forbidden :You don't have permission to access /phpmyadmin on this server

Find your IP address and replace where ever you see 127.0.0.1 with your workstation IP address you get from the link above.

. . .
Require ip your_workstation_IP_address
. . .
Allow from your_workstation_IP_address
. . .
Require ip your_workstation_IP_address
. . .
Allow from your_workstation_IP_address
. . .

and in the end don't forget to restart the server

sudo systemctl restart httpd.service

Search code inside a Github project

Recent private repositories have a search field for searching through that repo.

enter image description here

Bafflingly, it looks like this functionality is not available to public repositories, though.

Vertical Tabs with JQuery?

//o_O\\  (Poker Face) i know its late

just add beloww css style

<style type="text/css">

   /* Vertical Tabs ----------------------------------*/
 .ui-tabs-vertical { width: 55em; }
 .ui-tabs-vertical .ui-tabs-nav { padding: .2em .1em .2em .2em; float: left; width: 12em; }
 .ui-tabs-vertical .ui-tabs-nav li { clear: left; width: 100%; border-bottom-width: 1px !important; border-right-width: 0 !important; margin: 0 -1px .2em 0; }
 .ui-tabs-vertical .ui-tabs-nav li a { display:block; }
 .ui-tabs-vertical .ui-tabs-nav li.ui-tabs-selected { padding-bottom: 0; padding-right: .1em; border-right-width: 1px; border-right-width: 1px; }
 .ui-tabs-vertical .ui-tabs-panel { padding: 1em; float: right; width: 40em;}

</style>

UPDATED ! http://jqueryui.com/tabs/#vertical

How to set an environment variable from a Gradle build?

You can also "prepend" the environment variable setting by using 'environment' command:

run.doFirst { environment 'SPARK_LOCAL_IP', 'localhost' }

What does appending "?v=1" to CSS and JavaScript URLs in link and script tags do?

In order to answer you questions;

"?v=1" this is written only beacuse to download a fresh copy of the css and js files instead of using from the cache of the browser.

If you mention this query string parameter at the end of your stylesheet or the js file then it forces the browser to download a new file, Due to which the recent changes in the .css and .js files are made effetive in your browser.

If you dont use this versioning then you may need to clear the cache of refresh the page in order to view the recent changes in those files.

Here is an article that explains this thing How and Why to make versioning of CSS and JS files

How to delete a cookie?

Try this:

function delete_cookie( name, path, domain ) {
  if( get_cookie( name ) ) {
    document.cookie = name + "=" +
      ((path) ? ";path="+path:"")+
      ((domain)?";domain="+domain:"") +
      ";expires=Thu, 01 Jan 1970 00:00:01 GMT";
  }
}

You can define get_cookie() like this:

function get_cookie(name){
    return document.cookie.split(';').some(c => {
        return c.trim().startsWith(name + '=');
    });
}

Get Selected value of a Combobox

You can use the below change event to which will trigger when the combobox value will change.

Private Sub ComboBox1_Change()
'your code here
End Sub

Also you can get the selected value using below

ComboBox1.Value

How to convert integer into date object python?

This question is already answered, but for the benefit of others looking at this question I'd like to add the following suggestion: Instead of doing the slicing yourself as suggested above you might also use strptime() which is (IMHO) easier to read and perhaps the preferred way to do this conversion.

import datetime
s = "20120213"
s_datetime = datetime.datetime.strptime(s, '%Y%m%d')

Mipmap drawables for icons

When building separate apks for different densities, drawable folders for other densities get stripped. This will make the icons appear blurry in devices that use launcher icons of higher density. Since, mipmap folders do not get stripped, it’s always best to use them for including the launcher icons.

jQuery UI 1.10: dialog and zIndex option

Add zIndex property to dialog object:

$(elm).dialog(
 zIndex: 10000
);

Is Xamarin free in Visual Studio 2015?

Seems like now it's free for small teams and students, according to Scott Hanselman post https://twitter.com/shanselman/status/715568774418595840

https://visualstudio.microsoft.com/vs/pricing/

Visual Studio Community
FREE

A free, full-featured and extensible IDE for Windows users to create Android and iOS apps with Xamarin, as well as Windows apps, web apps, and cloud services.

  • Students
  • OSS development
  • Small teams

and

Xamarin Studio Community FREE

A free, full-featured IDE for Mac users to create Android and iOS apps using Xamarin.

  • Students
  • OSS development
  • Small teams

ldap query for group members

Active Directory does not store the group membership on user objects. It only stores the Member list on the group. The tools show the group membership on user objects by doing queries for it.

How about:

(&(objectClass=group)(member=cn=my,ou=full,dc=domain))

(You forgot the (& ) bit in your example in the question as well).

minimize app to system tray

this.WindowState = FormWindowState.Minimized;

Python: Convert timedelta to int in a dataframe

Timedelta objects have read-only instance attributes .days, .seconds, and .microseconds.

How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar?

Try with this:

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/drawer_layout"
android:fitsSystemWindows="true">


<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!--Main layout and ads-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <FrameLayout
            android:id="@+id/ll_main_hero"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1">

        </FrameLayout>

        <FrameLayout
            android:id="@+id/ll_ads"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <View
                android:layout_width="320dp"
                android:layout_height="50dp"
                android:layout_gravity="center"
                android:background="#ff00ff" />
        </FrameLayout>


    </LinearLayout>

    <!--Toolbar-->
    <android.support.v7.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/toolbar"
        android:elevation="4dp" />
</FrameLayout>


<!--left-->
<ListView
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:choiceMode="singleChoice"
    android:divider="@null"
    android:background="@mipmap/layer_image"
    android:id="@+id/left_drawer"></ListView>

<!--right-->
<FrameLayout
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="right"
    android:background="@mipmap/layer_image">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@mipmap/ken2"
        android:scaleType="centerCrop" />
</FrameLayout>

style :

<style name="ts_theme_overlay" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/red_A700</item>
    <item name="colorPrimaryDark">@color/red1</item>
    <item name="android:windowBackground">@color/blue_A400</item>
</style>

Main Activity extends ActionBarActivity

toolBar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolBar);

Now you can onCreateOptionsMenu like as normal ActionBar with ToolBar.

This is my Layout

  • TOP: Left Drawer - Right Drawer
    • MID: ToolBar (ActionBar)
    • BOTTOM: ListFragment

Hope you understand !have fun !

Arrays in cookies PHP

You can also try to write different elements in different cookies. Cookies names can be set as array names and will be available to your PHP scripts as arrays but separate cookies are stored on the user's system. Consider explode() to set one cookie with multiple names and values. It is not recommended to use serialize() for this purpose, because it can result in security holes. Look at setcookie PHP function for more details

Can HTTP POST be limitless?

Different IIS web servers can process different amounts of data in the 'header', according to this (now deleted) article; http://classicasp.aspfaq.com/forms/what-is-the-limit-on-form/post-parameters.html;

Note that there is no limit on the number of FORM elements you can pass via POST, but only on the aggregate size of all name/value pairs. While GET is limited to as low as 1024 characters, POST data is limited to 2 MB on IIS 4.0, and 128 KB on IIS 5.0. Each name/value is limited to 1024 characters, as imposed by the SGML spec. Of course this does not apply to files uploaded using enctype='multipart/form-data' ... I have had no problems uploading files in the 90 - 100 MB range using IIS 5.0, aside from having to increase the server.scriptTimeout value as well as my patience!

How can I initialize C++ object member variables in the constructor?

You're trying to create a ThingOne by using operator= which isn't going to work (incorrect syntax). Also, you're using a class name as a variable name, that is, ThingOne* ThingOne. Firstly, let's fix the variable names:

private:
    ThingOne* t1;
    ThingTwo* t2;

Since these are pointers, they must point to something. If the object hasn't been constructed yet, you'll need to do so explicitly with new in your BigMommaClass constructor:

BigMommaClass::BigMommaClass(int n1, int n2)
{
    t1 = new ThingOne(100);
    t2 = new ThingTwo(n1, n2);
}

Generally initializer lists are preferred for construction however, so it will look like:

BigMommaClass::BigMommaClass(int n1, int n2)
    : t1(new ThingOne(100)), t2(new ThingTwo(n1, n2))
{ }

Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php

At last I found the answer:

Just add this line before the line where you get error in your php file

ini_set('memory_limit', '-1');

It will take unlimited memory usage of server, it's working fine.

Consider '44M' instead of '-1' for safe memory usage.

Reloading module giving NameError: name 'reload' is not defined

To expand on the previously written answers, if you want a single solution which will work across Python versions 2 and 3, you can use the following:

try:
    reload  # Python 2.7
except NameError:
    try:
        from importlib import reload  # Python 3.4+
    except ImportError:
        from imp import reload  # Python 3.0 - 3.3

How to create an empty file at the command line in Windows?

echo "" > filename

I believe this works on Windows/DOS, but my last hands-on experience with either is quite a while ago. I do know for a fact that it works on basically any POSIX compliant OS.

Replace specific text with a redacted version using Python

You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.

NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.

Example:

Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.

Returns:

NER with spacy

Just be aware that this is not 100%!

Here are a little snippet for you to try out:

import spacy

phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
   doc = nlp(phrase)
   replaced = ""
   for token in doc:
      if token in doc.ents:
         replaced+="XXXX "
      else:
         replaced+=token.text+" "

Read more here: https://spacy.io/usage/linguistic-features#named-entities

You could, instead of replacing with XXXX, replace based on the entity type, like:

if ent.label_ == "PERSON":
   replaced += "<PERSON> "

Then:

import re, random

personames = ["Jack", "Mike", "Bob", "Dylan"]

phrase = re.replace("<PERSON>", random.choice(personames), phrase)

How can I extract a number from a string in JavaScript?

var elValue     = "-12,erer3  4,-990.234sdsd";

var isNegetive = false;
if(elValue.indexOf("-")==0) isNegetive=true;

elValue     = elValue.replace( /[^\d\.]*/g, '');
elValue     = isNaN(Number(elValue)) ? 0 : Number(elValue);

if(isNegetive) elValue = 0 - elValue;

alert(elValue); //-1234990.234

How to set null value to int in c#?

In .Net, you cannot assign a null value to an int or any other struct. Instead, use a Nullable<int>, or int? for short:

int? value = 0;

if (value == 0)
{
    value = null;
}

Further Reading

How can I get the first two digits of a number?

You can use a regular expression to test for a match and capture the first two digits:

import re

for i in range(1000):
    match = re.match(r'(1[56])', str(i))

    if match:
        print(i, 'begins with', match.group(1))

The regular expression (1[56]) matches a 1 followed by either a 5 or a 6 and stores the result in the first capturing group.

Output:

15 begins with 15
16 begins with 16
150 begins with 15
151 begins with 15
152 begins with 15
153 begins with 15
154 begins with 15
155 begins with 15
156 begins with 15
157 begins with 15
158 begins with 15
159 begins with 15
160 begins with 16
161 begins with 16
162 begins with 16
163 begins with 16
164 begins with 16
165 begins with 16
166 begins with 16
167 begins with 16
168 begins with 16
169 begins with 16

X11/Xlib.h not found in Ubuntu

A quick search using...

apt search Xlib.h

Turns up the package libx11-dev but you shouldn't need this for pure OpenGL programming. What tutorial are you using?

You can add Xlib.h to your system by running the following...

sudo apt install libx11-dev

How to do the equivalent of pass by reference for primitives in Java

You cannot pass primitives by reference in Java. All variables of object type are actually pointers, of course, but we call them "references", and they are also always passed by value.

In a situation where you really need to pass a primitive by reference, what people will do sometimes is declare the parameter as an array of primitive type, and then pass a single-element array as the argument. So you pass a reference int[1], and in the method, you can change the contents of the array.

How to use custom font in a project written in Android Studio

First create assets folder then create fonts folder in it.

Then you can set font from assets or directory like bellow :

public class FontSampler extends Activity {
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        TextView tv = (TextView) findViewById(R.id.custom);
        Typeface face = Typeface.createFromAsset(getAssets(), "fonts/HandmadeTypewriter.ttf");

        tv.setTypeface(face);

        File font = new File(Environment.getExternalStorageDirectory(), "MgOpenCosmeticaBold.ttf");

        if (font.exists()) {
            tv = (TextView) findViewById(R.id.file);
            face = Typeface.createFromFile(font);

            tv.setTypeface(face);
        } else {
            findViewById(R.id.filerow).setVisibility(View.GONE);
        }
    }
} 

What is the difference between single and double quotes in SQL?

The difference lies in their usage. The single quotes are mostly used to refer a string in WHERE, HAVING and also in some built-in SQL functions like CONCAT, STRPOS, POSITION etc.

When you want to use an alias that has space in between then you can use double quotes to refer to that alias.

For example

(select account_id,count(*) "count of" from orders group by 1)sub 

Here is a subquery from an orders table having account_id as Foreign key that I am aggregating to know how many orders each account placed. Here I have given one column any random name as "count of" for sake of purpose.

Now let's write an outer query to display the rows where "count of" is greater than 20.

select "count of" from 
(select account_id,count(*) "count of" from orders group by 1)sub where "count of" >20;

You can apply the same case to Common Table expressions also.

Return row of Data Frame based on value in a column - R

You could use dplyr:

df %>% group_by("Amount") %>% slice(which.min(x))

How to randomize (shuffle) a JavaScript array?

One could (or should) use it as a protoype from Array:

From ChristopheD:

Array.prototype.shuffle = function() {
  var i = this.length, j, temp;
  if ( i == 0 ) return this;
  while ( --i ) {
     j = Math.floor( Math.random() * ( i + 1 ) );
     temp = this[i];
     this[i] = this[j];
     this[j] = temp;
  }
  return this;
}

How to set JAVA_HOME environment variable on Mac OS X 10.9?

Since I'm using openjdk managed with sdkman, I added

sudo ln -sfn /path/to/my/installed/jdk/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk.jdk

Adding this to your system lets java_home recognize your installed version of Java even when its not installed via standard packages

Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv

Try conda install -c conda-forge opencv if you are using anaconda, it works!

How to extract img src, title and alt from html using php?

I used preg_match to do it.

In my case, I had a string containing exactly one <img> tag (and no other markup) that I got from Wordpress and I was trying to get the src attribute so I could run it through timthumb.

// get the featured image
$image = get_the_post_thumbnail($photos[$i]->ID);

// get the src for that image
$pattern = '/src="([^"]*)"/';
preg_match($pattern, $image, $matches);
$src = $matches[1];
unset($matches);

In the pattern to grab the title or the alt, you could simply use $pattern = '/title="([^"]*)"/'; to grab the title or $pattern = '/title="([^"]*)"/'; to grab the alt. Sadly, my regex isn't good enough to grab all three (alt/title/src) with one pass though.

How to create Select List for Country and States/province in MVC

I too liked Jordan's answer and implemented it myself. I only needed to abbreviations so in case someone else needs the same:

    public static IEnumerable<SelectListItem> GetStatesList()
    {
        IList<SelectListItem> states = new List<SelectListItem>
        {
            new SelectListItem() {Text="AL", Value="AL"},
            new SelectListItem() { Text="AK", Value="AK"},
            new SelectListItem() { Text="AZ", Value="AZ"},
            new SelectListItem() { Text="AR", Value="AR"},
            new SelectListItem() { Text="CA", Value="CA"},
            new SelectListItem() { Text="CO", Value="CO"},
            new SelectListItem() { Text="CT", Value="CT"},
            new SelectListItem() { Text="DC", Value="DC"},
            new SelectListItem() { Text="DE", Value="DE"},
            new SelectListItem() { Text="FL", Value="FL"},
            new SelectListItem() { Text="GA", Value="GA"},
            new SelectListItem() { Text="HI", Value="HI"},
            new SelectListItem() { Text="ID", Value="ID"},
            new SelectListItem() { Text="IL", Value="IL"},
            new SelectListItem() { Text="IN", Value="IN"},
            new SelectListItem() { Text="IA", Value="IA"},
            new SelectListItem() { Text="KS", Value="KS"},
            new SelectListItem() { Text="KY", Value="KY"},
            new SelectListItem() { Text="LA", Value="LA"},
            new SelectListItem() { Text="ME", Value="ME"},
            new SelectListItem() { Text="MD", Value="MD"},
            new SelectListItem() { Text="MA", Value="MA"},
            new SelectListItem() { Text="MI", Value="MI"},
            new SelectListItem() { Text="MN", Value="MN"},
            new SelectListItem() { Text="MS", Value="MS"},
            new SelectListItem() { Text="MO", Value="MO"},
            new SelectListItem() { Text="MT", Value="MT"},
            new SelectListItem() { Text="NE", Value="NE"},
            new SelectListItem() { Text="NV", Value="NV"},
            new SelectListItem() { Text="NH", Value="NH"},
            new SelectListItem() { Text="NJ", Value="NJ"},
            new SelectListItem() { Text="NM", Value="NM"},
            new SelectListItem() { Text="NY", Value="NY"},
            new SelectListItem() { Text="NC", Value="NC"},
            new SelectListItem() { Text="ND", Value="ND"},
            new SelectListItem() { Text="OH", Value="OH"},
            new SelectListItem() { Text="OK", Value="OK"},
            new SelectListItem() { Text="OR", Value="OR"},
            new SelectListItem() { Text="PA", Value="PA"},
            new SelectListItem() { Text="PR", Value="PR"},
            new SelectListItem() { Text="RI", Value="RI"},
            new SelectListItem() { Text="SC", Value="SC"},
            new SelectListItem() { Text="SD", Value="SD"},
            new SelectListItem() { Text="TN", Value="TN"},
            new SelectListItem() { Text="TX", Value="TX"},
            new SelectListItem() { Text="UT", Value="UT"},
            new SelectListItem() { Text="VT", Value="VT"},
            new SelectListItem() { Text="VA", Value="VA"},
            new SelectListItem() { Text="WA", Value="WA"},
            new SelectListItem() { Text="WV", Value="WV"},
            new SelectListItem() { Text="WI", Value="WI"},
            new SelectListItem() { Text="WY", Value="WY"}
        };
        return states;
    }

Saving timestamp in mysql table using php

Hey there, use the FROM_UNIXTIME() function for this.

Like this:

INSERT INTO table_name
(id,d_id,l_id,connection,s_time,upload_items_count,download_items_count,t_time,status)
VALUES
(1,5,9,'2',FROM_UNIXTIME(1299762201428),5,10,20,'1'), 
(2,5,9,'2',FROM_UNIXTIME(1299762201428),5,10,20,'1')

Creating .pem file for APNS?

Launch the Terminal application and enter the following command after the prompt

  openssl pkcs12 -in CertificateName.p12 -out CertificateName.pem -nodes

How to specify preference of library path?

Specifying the absolute path to the library should work fine:

g++ /my/dir/libfoo.so.0  ...

Did you remember to remove the -lfoo once you added the absolute path?

What are alternatives to document.write?

You can combine insertAdjacentHTML method and document.currentScript property.

The insertAdjacentHTML() method of the Element interface parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position:

  • 'beforebegin': Before the element itself.
  • 'afterbegin': Just inside the element, before its first child.
  • 'beforeend': Just inside the element, after its last child.
  • 'afterend': After the element itself.

The document.currentScript property returns the <script> element whose script is currently being processed. Best position will be beforebegin — new HTML will be inserted before <script> itself. To match document.write's native behavior, one would position the text afterend, but then the nodes from consecutive calls to the function aren't placed in the same order as you called them (like document.write does), but in reverse. The order in which your HTML appears is probably more important than where they're place relative to the <script> tag, hence the use of beforebegin.

_x000D_
_x000D_
document.currentScript.insertAdjacentHTML(
  'beforebegin', 
  'This is a document.write alternative'
)
_x000D_
_x000D_
_x000D_

How to install ia32-libs in Ubuntu 14.04 LTS (Trusty Tahr)

I had the same problem as above and Eclipse suggested installing:

Hint: On 64-bit systems, make sure the 32-bit libraries are installed:   
   "sudo apt-get install ia32-libs"    
or on some systems,  
   "sudo apt-get install lib32z1"   

When I tried to install ia32-libs, Ubuntu prompted to install three other packages:

$ sudo apt-get install ia32-libs  
Reading package lists... Done  
Building dependency tree         
Reading state information... Done  
Package ia32-libs is not available, but is referred to by another package.  
This may mean that the package is missing, has been obsoleted, or  
is only available from another source  
However the following packages replace it:  
  lib32z1 lib32ncurses5 lib32bz2-1.0  

E: Package 'ia32-libs' has no installation candidate  
$   
$ sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0    

With Android Studio and intellij, I also had to install the 32bit version of libstdc++6:

sudo apt-get install lib32stdc++6

PHPExcel How to apply styles and set cell width and cell height to cell generated dynamically

You can use

$objWorksheet->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
$objWorksheet->getActiveSheet()->getColumnDimension('A')->setWidth(100);

or define auto-size:

$objWorksheet->getRowDimension('1')->setRowHeight(-1);

jQuery validation: change default error message

To remove all default error messages use

$.validator.messages.required = "";

select into in mysql

In MySQL, It should be like this

INSERT INTO this_table_archive (col1, col2, ..., coln)
SELECT col1, col2, ..., coln
FROM this_table
WHERE entry_date < '2011-01-01 00:00:00';

MySQL Documentation

Why use $_SERVER['PHP_SELF'] instead of ""

In addition to above answers, another way of doing it is $_SERVER['PHP_SELF'] or simply using an empty string is to use __DIR__.
OR
If you're on a lower PHP version (<5.3), a more common alternative is to use dirname(__FILE__)
Both returns the folder name of the file in context.

EDIT
As Boann pointed out that this returns the on-disk location of the file. WHich you would not ideally expose as a url. In that case dirname($_SERVER['PHP_SELF']) can return the folder name of the file in context.

Is there a way to word-wrap long words in a div?

As david mentions, DIVs do wrap words by default.

If you are referring to really long strings of text without spaces, what I do is process the string server-side and insert empty spans:

thisIsAreallyLongStringThatIWantTo<span></span>BreakToFitInsideAGivenSpace

It's not exact as there are issues with font-sizing and such. The span option works if the container is variable in size. If it's a fixed width container, you could just go ahead and insert line breaks.

Get resultset from oracle stored procedure

Hi I know this was asked a while ago but I've just figured this out and it might help someone else. Not sure if this is exactly what you're looking for but this is how I call a stored proc and view the output using SQL Developer.
In SQL Developer when viewing the proc, right click and choose 'Run' or select Ctrl+F11 to bring up the Run PL/SQL window. This creates a template with the input and output params which you need to modify. My proc returns a sys_refcursor. The tricky part for me was declaring a row type that is exactly equivalent to the select stmt / sys_refcursor being returned by the proc:

DECLARE
  P_CAE_SEC_ID_N NUMBER;
  P_FM_SEC_CODE_C VARCHAR2(200);
  P_PAGE_INDEX NUMBER;
  P_PAGE_SIZE NUMBER;
  v_Return sys_refcursor;
  type t_row is record (CAE_SEC_ID NUMBER,FM_SEC_CODE VARCHAR2(7),rownum number, v_total_count number);
  v_rec t_row;

BEGIN
  P_CAE_SEC_ID_N := NULL;
  P_FM_SEC_CODE_C := NULL;
  P_PAGE_INDEX := 0;
  P_PAGE_SIZE := 25;

  CAE_FOF_SECURITY_PKG.GET_LIST_FOF_SECURITY(
    P_CAE_SEC_ID_N => P_CAE_SEC_ID_N,
    P_FM_SEC_CODE_C => P_FM_SEC_CODE_C,
    P_PAGE_INDEX => P_PAGE_INDEX,
    P_PAGE_SIZE => P_PAGE_SIZE,
    P_FOF_SEC_REFCUR => v_Return
  );
  -- Modify the code to output the variable
  -- DBMS_OUTPUT.PUT_LINE('P_FOF_SEC_REFCUR = ');
  loop
    fetch v_Return into v_rec;
    exit when v_Return%notfound;
    DBMS_OUTPUT.PUT_LINE('sec_id = ' || v_rec.CAE_SEC_ID || 'sec code = ' ||v_rec.FM_SEC_CODE);
  end loop;

END;

Passing Arrays to Function in C++

The syntaxes

int[]

and

int[X] // Where X is a compile-time positive integer

are exactly the same as

int*

when in a function parameter list (I left out the optional names).

Additionally, an array name decays to a pointer to the first element when passed to a function (and not passed by reference) so both int firstarray[3] and int secondarray[5] decay to int*s.

It also happens that both an array dereference and a pointer dereference with subscript syntax (subscript syntax is x[y]) yield an lvalue to the same element when you use the same index.

These three rules combine to make the code legal and work how you expect; it just passes pointers to the function, along with the length of the arrays which you cannot know after the arrays decay to pointers.

UNC path to a folder on my local computer

On Windows, you can also use the Win32 File Namespace prefixed with \\?\ to refer to your local directories:

\\?\C:\my_dir

See this answer for description.

sqlplus error on select from external table: ORA-29913: error in executing ODCIEXTTABLEOPEN callout

We faced the same problem:

ORA-29913: error in executing ODCIEXTTABLEOPEN callout
ORA-29400: data cartridge error error opening file /fs01/app/rms01/external/logs/SH_EXT_TAB_VGAG_DELIV_SCHED.log

In our case we had a RAC with 2 nodes. After giving write permission on the log directory, on both sides, everything worked fine.

How to remove "disabled" attribute using jQuery?

Always use the prop() method to enable or disable elements when using jQuery (see below for why).

In your case, it would be:

$("#edit").click(function(event){
   event.preventDefault();
   $('.inputDisabled').prop("disabled", false); // Element(s) are now enabled.
});

jsFiddle example here.


Why use prop() when you could use attr()/removeAttr() to do this?

Basically, prop() should be used when getting or setting properties (such as autoplay, checked, disabled and required amongst others).

By using removeAttr(), you are completely removing the disabled attribute itself - while prop() is merely setting the property's underlying boolean value to false.

While what you want to do can be done using attr()/removeAttr(), it doesn't mean it should be done (and can cause strange/problematic behaviour, as in this case).

The following extracts (taken from the jQuery documentation for prop()) explain these points in greater detail:

"The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes."

"Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include the value property of input elements, the disabled property of inputs and buttons, or the checked property of a checkbox. The .prop() method should be used to set disabled and checked instead of the .attr() method. The .val() method should be used for getting and setting value."

How to get public directory?

The best way to retrieve your public folder path from your Laravel config is the function:

$myPublicFolder = public_path();
$savePath = $mypublicPath."enter_path_to_save";
$path = $savePath."filename.ext";
return File::put($path , $data);

There is no need to have all the variables, but this is just for a demonstrative purpose.

Hope this helps, GRnGC

java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader

Ensure you have included the different abiFilters, this enables Gradle know what ABI libraries to package into your apk.

defaultConfig {
 ndk { 
       abiFilters "armeabi-v7a", "x86", "armeabi", "mips" 
     } 
  }

If you storing your jni libs in a different directory, or also using externally linked jni libs, Include them on the different source sets of the app.

sourceSets { 
  main { 
    jni.srcDirs = ['src/main/jniLibs'] 
    jniLibs.srcDir 'src/main/jniLibs' 
    } 
}

Is there a way to create interfaces in ES6 / Node 4?

Given that ECMA is a 'class-free' language, implementing classical composition doesn't - in my eyes - make a lot of sense. The danger is that, in so doing, you are effectively attempting to re-engineer the language (and, if one feels strongly about that, there are excellent holistic solutions such as the aforementioned TypeScript that mitigate reinventing the wheel)

Now that isn't to say that composition is out of the question however in Plain Old JS. I researched this at length some time ago. The strongest candidate I have seen for handling composition within the object prototypal paradigm is stampit, which I now use across a wide range of projects. And, importantly, it adheres to a well articulated specification.

more information on stamps here

How to get last month/year in java?

The simplest & least error prone approach is... Use Calendar's roll() method. Like this:

    c.roll(Calendar.MONTH, false);

the roll method takes a boolean, which basically means roll the month up(true) or down(false)?

The order of keys in dictionaries

Just sort the list when you want to use it.

l = sorted(d.keys())

java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication Maven

Another option is to use the Apache Maven Shade Plugin: This plugin provides the capability to package the artifact in an uber-jar, including its dependencies and to shade - i.e. rename - the packages of some of the dependencies.

add this to your build plugins section

<plugin>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-shade-plugin</artifactId>
</plugin>

Exists Angularjs code/naming conventions?

Update : STYLE GUIDE is now on Angular docs.

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

If you are looking for an opinionated style guide for syntax, conventions, and structuring AngularJS applications, then step right in. The styles contained here are based on my experience with AngularJS, presentations, training courses and working in teams.

The purpose of this style guide is to provide guidance on building AngularJS applications by showing the conventions I use and, more importantly, why I choose them.

- John Papa

Here is the Awesome Link (Latest and Up-to-date) : AngularJS Style Guide

How do I fix a merge conflict due to removal of a file in a branch?

I normally just run git mergetool and it will prompt me if I want to keep the modified file or keep it deleted. This is the quickest way IMHO since it's one command instead of several per file.

If you have a bunch of deleted files in a specific subdirectory and you want all of them to be resolved by deleting the files, you can do this:

yes d | git mergetool -- the/subdirectory

The d is provided to choose deleting each file. You can also use m to keep the modified file. Taken from the prompt you see when you run mergetool:

Use (m)odified or (d)eleted file, or (a)bort?

Using Eloquent ORM in Laravel to perform search of database using LIKE

You're able to do database finds using LIKE with this syntax:

Model::where('column', 'LIKE', '%value%')->get();

How to do a join in linq to sql with method syntax?

Justin has correctly shown the expansion in the case where the join is just followed by a select. If you've got something else, it becomes more tricky due to transparent identifiers - the mechanism the C# compiler uses to propagate the scope of both halves of the join.

So to change Justin's example slightly:

var result = from sc in enumerableOfSomeClass
             join soc in enumerableOfSomeOtherClass
             on sc.Property1 equals soc.Property2
             where sc.X + sc.Y == 10
             select new { SomeClass = sc, SomeOtherClass = soc }

would be converted into something like this:

var result = enumerableOfSomeClass
    .Join(enumerableOfSomeOtherClass,
          sc => sc.Property1,
          soc => soc.Property2,
          (sc, soc) => new { sc, soc })
    .Where(z => z.sc.X + z.sc.Y == 10)
    .Select(z => new { SomeClass = z.sc, SomeOtherClass = z.soc });

The z here is the transparent identifier - but because it's transparent, you can't see it in the original query :)

PUT and POST getting 405 Method Not Allowed Error for Restful Web Services

Well, apparently I had to change my PUT calling function updateUser. I removed the @Consumes, the @RequestMapping and also added a @ResponseBody to the function. So my method looked like this:

@RequestMapping(value="/{id}",method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public void updateUser(@PathVariable int id, @RequestBody User temp){
    Set<User> set1= obj2.getUsers();
    for(User a:set1)
    {
        if(id==a.getId())
        {
            set1.remove(a);
            a.setId(temp.getId());
            a.setName(temp.getName());
            set1.add(a);
        }
    }
    Userlist obj3=new Userlist(set1);
    obj2=obj3;
}

And it worked!!! Thank you all for the response.

Bootstrap 3 hidden-xs makes row narrower

.row {
    margin-right: 15px;
}

throw this in your CSS

Create SQLite database in android

Better example is here

 try {
   myDB = this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);

   /* Create a Table in the Database. */
   myDB.execSQL("CREATE TABLE IF NOT EXISTS "
     + TableName
     + " (Field1 VARCHAR, Field2 INT(3));");

   /* Insert data to a Table*/
   myDB.execSQL("INSERT INTO "
     + TableName
     + " (Field1, Field2)"
     + " VALUES ('Saranga', 22);");

   /*retrieve data from database */
   Cursor c = myDB.rawQuery("SELECT * FROM " + TableName , null);

   int Column1 = c.getColumnIndex("Field1");
   int Column2 = c.getColumnIndex("Field2");

   // Check if our result was valid.
   c.moveToFirst();
   if (c != null) {
    // Loop through all Results
    do {
     String Name = c.getString(Column1);
     int Age = c.getInt(Column2);
     Data =Data +Name+"/"+Age+"\n";
    }while(c.moveToNext());
   }

Cannot connect to repo with TortoiseSVN

Look into this as well:

Issue: After invoking SVN on the command line on a firewalled server, nothing visible happens for 15 seconds, then the program quits with the following error:

svn: E170013: Unable to connect to a repository at URL 'SVN.REPOSITORY.REDACTED'

svn: E730054: Error running context: An existing connection was forcibly closed by the remote host.

Investigation: Internet research on the above errors did not uncover any pertinent information.

Process Tracing (procmon) showed a connection attempt to an Akamai (cloud services) server after the SSL/TLS handshake to the SVN Server. The hostname for the server was not shown in Process tracing. Reverse DNS lookup showed a184-51-112-88.deploy.static.akamaitechnologies.com or a184-51-112-80.deploy.static.akamaitechnologies.com as the hostname, and the IP was either 184.51.112.88 or 184.51.112.80 (2 entries in DNS cache).

Packet capture tool (MMA) showed a connection attempt to the hostname ctldl.windowsupdate.com after the SSL/TLS Handshake to the SVN server.

The windows Crypto API was attempting to connect to Windows Update to retrieve Certificate revocation information (CRL – certificate revocation list). The default timeout for CRL retrieval is 15 seconds. The timeout for authentication on the server is 10 seconds; as 15 is greater than 10, this fails.

Resolution: Internet research uncovered the following: (also see picture at bottom)

Solution 1: Decrease CRL timeout Group Policy -> Computer Config ->Windows Settings -> Security Settings -> Public Key Policies -> Certificate Path Validation Settings -> Network Retrieval – see picture below.

https://subversion.open.collab.net/ds/viewMessage.do?dsForumId=4&dsMessageId=470698

support.microsoft.com/en-us/kb/2625048

blogs.technet.com/b/exchange/archive/2010/05/14/3409948.aspx

Solution 2: Open firewall for CRL traffic

support.microsoft.com/en-us/kb/2677070

Solution 3: SVN command line flags (untested)

serverfault.com/questions/716845/tortoise-svn-initial-connect-timeout - alternate svn command line flag solution.

Additional Information: Debugging this issue was particularly difficult. SVN 1.8 disabled support for the Neon HTTP RA (repository access) library in favor of the Serf library which removed client debug logging. [1] In addition, the SVN error code returned did not match the string given in svn_error_codes.h [2] Also, SVN Error codes cannot be mapped back to their ENUM label easily, this case SVN error code E170013 maps to SVN_ERR_RA_CANNOT_CREATE_SESSION.

  1. stackoverflow.com/questions/8416989/is-it-possible-to-get-svn-client-debug-output
  2. people.apache.org/~brane/svndocs/capi/svn__error__codes_8h.html#ac8784565366c15a28d456c4997963660a044e5248bb3a652768e5eb3105d6f28f
  3. code.google.com/archive/p/serf/issues/172

Suggested SVN Changes:

  1. Enable Verbosity on the command like for all operations

  2. Add error ENUM name to stderr

  3. Add config flag for Serf Library debug logging.

What is the difference between a symbolic link and a hard link?

Underneath the file system, files are represented by inodes. (Or is it multiple inodes? Not sure.)

A file in the file system is basically a link to an inode.
A hard link, then, just creates another file with a link to the same underlying inode.

When you delete a file, it removes one link to the underlying inode. The inode is only deleted (or deletable/over-writable) when all links to the inode have been deleted.

A symbolic link is a link to another name in the file system.

Once a hard link has been made the link is to the inode. Deleting, renaming, or moving the original file will not affect the hard link as it links to the underlying inode. Any changes to the data on the inode is reflected in all files that refer to that inode.

Note: Hard links are only valid within the same File System. Symbolic links can span file systems as they are simply the name of another file.

Writing a dict to txt file and reading it back?

You can iterate through the key-value pair and write it into file

pair = {'name': name,'location': location}
with open('F:\\twitter.json', 'a') as f:
     f.writelines('{}:{}'.format(k,v) for k, v in pair.items())
     f.write('\n')

Return JSON response from Flask view

if its a dict, flask can return it directly (Version 1.0.2)

def summary():
    d = make_summary()
    return d, 200

"Post Image data using POSTMAN"

Now you can hover the key input and select "file", which will give you a file selector in the value column:

enter image description here

How to put comments in Django templates

Using the {# #} notation, like so:

{# Everything you see here is a comment. It won't show up in the HTML output. #}

REST API Authentication

You can use HTTP Basic or Digest Authentication. You can securely authenticate users using SSL on the top of it, however, it slows down the API a little bit.

  • Basic authentication - uses Base64 encoding on username and password
  • Digest authentication - hashes the username and password before sending them over the network.

OAuth is the best it can get. The advantages oAuth gives is a revokable or expirable token. Refer following on how to implement: Working Link from comments: https://www.ida.liu.se/~TDP024/labs/hmacarticle.pdf

Which terminal command to get just IP address and nothing else?

To get only the IP address on Mac OS X you can type the following command:

ipconfig getifaddr en0

Python loop for inside lambda

If you are like me just want to print a sequence within a lambda, without get the return value (list of None).

x = range(3)
from __future__ import print_function           # if not python 3
pra = lambda seq=x: map(print,seq) and None     # pra for 'print all'
pra()
pra('abc')

Using `window.location.hash.includes` throws “Object doesn't support property or method 'includes'” in IE11

This question and its answers led me to my own solution (with help from SO), though some say you shouldn't tamper with native prototypes:

  // IE does not support .includes() so I'm making my own:
  String.prototype.doesInclude=function(needle){
    return this.substring(needle) != -1;
  }

Then I just replaced all .includes() with .doesInclude() and my problem was solved.

Error: Cannot find module 'ejs'

kindly ensure that your dependencies in your package.json files are up to date. Try reinstalling them one at a time after also ensuring that your NPM is the latest version (up-to-date). It worked for me. I advise you to run npm install for the packages(thats what worked in my own case after it refused to work because I added the dependencies manually).

java.lang.NoClassDefFoundError: javax/mail/Authenticator, whats wrong?

When I had this problem, I had included the mail-api.jar in my maven pom file. That's the API specification only. The fix is to replace this:

<!-- DO NOT USE - it's just the API, not an implementation -->
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>

with the reference implementation of that api:

<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>

I know it has sun in the package name, but that's the latest version. I learned this from https://stackoverflow.com/a/28935760/1128668

Javascript objects: get parent

I have been working on a solution to finding the parent object of the current object for my own pet project. Adding a reference to the parent object within the current object creates a cyclic relationship between the two objects.

Consider -

var obj = {
    innerObj: {},
    setParent: function(){
        this.innerObj.parent = this;
    }
};
obj.setParent();

The variable obj will now look like this -

obj.innerObj.parent.innerObj.parent.innerObj...

This is not good. The only solution that I have found so far is to create a function which iterates over all the properties of the outermost Object until a match is found for the current Object and then that Object is returned.

Example -

var obj = {
    innerObj: {
        innerInnerObj: {}
    }
};

var o = obj.innerObj.innerInnerObj,
    found = false;

var getParent = function (currObj, parObj) {
    for(var x in parObj){
        if(parObj.hasOwnProperty(x)){
            if(parObj[x] === currObj){
                found = parObj;
            }else if(typeof parObj[x] === 'object'){
                getParent(currObj, parObj[x]);
            }
        }
    }
    return found;
};

var res = getParent(o, obj); // res = obj.innerObj

Of course, without knowing or having a reference to the outermost object, there is no way to do this. This is not a practical nor is it an efficient solution. I am going to continue to work on this and hopefully find a good answer for this problem.

Move textfield when keyboard appears swift

Swift 4.x answer, merging answers from @Joseph Lord and @Isuru. bottomConstraint represents the bottom constraint of the view you're interested in moving.

override func viewDidLoad() {
    // Call super
    super.viewDidLoad()

    // Subscribe to keyboard notifications
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(keyboardNotification(notification:)),
                                           name: UIResponder.keyboardWillChangeFrameNotification,
                                           object: nil)        
}


deinit {
    NotificationCenter.default.removeObserver(self)
}


@objc func keyboardNotification(notification: NSNotification) {
    if let userInfo = notification.userInfo {
        // Get keyboard frame
        let keyboardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue

        // Set new bottom constraint constant
        let bottomConstraintConstant = keyboardFrame.origin.y >= UIScreen.main.bounds.size.height ? 0.0 : keyboardFrame.size.height

        // Set animation properties
        let duration = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
        let animationCurveRawNSN = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber
        let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIView.AnimationOptions.curveEaseInOut.rawValue
        let animationCurve = UIView.AnimationOptions(rawValue: animationCurveRaw)

        // Animate the view you care about
        UIView.animate(withDuration: duration, delay: 0, options: animationCurve, animations: {
            self.bottomConstraint.constant = bottomConstraintConstant
            self.view.layoutIfNeeded()
        }, completion: nil)
    }
}

Which is a better way to check if an array has more than one element?

The first method if (isset($arr['1'])) will not work on an associative array.

For example, the following code displays "Nope, not more than one."

$arr = array(
    'a' => 'apple',
    'b' => 'banana',
);

if (isset($arr['1'])) {
    echo "Yup, more than one.";
} else {
    echo "Nope, not more than one.";
}

How to split a number into individual digits in c#?

Well, a string is an IEnumerable and also implements an indexer, so you can iterate through it or reference each character in the string by index.

The fastest way to get what you want is probably the ToCharArray() method of a String:

var myString = "12345";

var charArray = myString.ToCharArray(); //{'1','2','3','4','5'}

You can then convert each Char to a string, or parse them into bytes or integers. Here's a Linq-y way to do that:

byte[] byteArray = myString.ToCharArray().Select(c=>byte.Parse(c.ToString())).ToArray();

A little more performant if you're using ASCII/Unicode strings:

byte[] byteArray = myString.ToCharArray().Select(c=>(byte)c - 30).ToArray();

That code will only work if you're SURE that each element is a number; otherisw the parsing will throw an exception. A simple Regex that will verify this is true is "^\d+$" (matches a full string consisting of one or more digit characters), used in the Regex.IsMatch() static method.

Change Twitter Bootstrap Tooltip content on click

Just found this today whilst reading the source code. So $.tooltip(string) calls any function within the Tooltip class. And if you look at Tooltip.fixTitle, it fetches the data-original-title attribute and replaces the title value with it.

So we simply do:

$(element).tooltip('hide')
          .attr('data-original-title', newValue)
          .tooltip('fixTitle')
          .tooltip('show');

and sure enough, it updates the title, which is the value inside the tooltip.

A shorter way:

$(element).attr('title', 'NEW_TITLE')
          .tooltip('fixTitle')
          .tooltip('show');

Where are the Android icon drawables within the SDK?

Material icons provided by google can be found here: https://design.google.com/icons/

You can download them as PNG or SVG in light and dark theme.

How do I hide the bullets on my list for the sidebar?

its on you ul in the file http://ratest4.com/wp-content/themes/HarnettArts-BP-2010/style.css on line 252

add this to your css

ul{
     list-style:none;
}

How to adjust text font size to fit textview

This is speedplane's FontFitTextView, but it only decreases font size if needed to make the text fit, and keeps its font size otherwise. It does not increase the font size to fit height.

public class FontFitTextView extends TextView {

    // Attributes
    private Paint mTestPaint;
    private float defaultTextSize;

    public FontFitTextView(Context context) {
        super(context);
        initialize();
    }

    public FontFitTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialize();
    }

    private void initialize() {
        mTestPaint = new Paint();
        mTestPaint.set(this.getPaint());
        defaultTextSize = getTextSize();
    }

    /* Re size the font so the specified text fits in the text box
     * assuming the text box is the specified width.
     */
    private void refitText(String text, int textWidth) {

        if (textWidth <= 0 || text.isEmpty())
            return;

        int targetWidth = textWidth - this.getPaddingLeft() - this.getPaddingRight();

        // this is most likely a non-relevant call
        if( targetWidth<=2 )
            return;

        // text already fits with the xml-defined font size?
        mTestPaint.set(this.getPaint());
        mTestPaint.setTextSize(defaultTextSize);
        if(mTestPaint.measureText(text) <= targetWidth) {
            this.setTextSize(TypedValue.COMPLEX_UNIT_PX, defaultTextSize);
            return;
        }

        // adjust text size using binary search for efficiency
        float hi = defaultTextSize;
        float lo = 2;
        final float threshold = 0.5f; // How close we have to be
        while (hi - lo > threshold) {
            float size = (hi + lo) / 2;
            mTestPaint.setTextSize(size);
            if(mTestPaint.measureText(text) >= targetWidth ) 
                hi = size; // too big
            else 
                lo = size; // too small

        }

        // Use lo so that we undershoot rather than overshoot
        this.setTextSize(TypedValue.COMPLEX_UNIT_PX, lo);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
        int height = getMeasuredHeight();
        refitText(this.getText().toString(), parentWidth);
        this.setMeasuredDimension(parentWidth, height);
    }

    @Override
    protected void onTextChanged(final CharSequence text, final int start,
            final int before, final int after) {
        refitText(text.toString(), this.getWidth());
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        if (w != oldw || h != oldh) {
            refitText(this.getText().toString(), w);
        }
    }

}

Here is an example how it could be used in xml:

<com.your.package.activity.widget.FontFitTextView
    android:id="@+id/my_id"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="My Text"
    android:textSize="60sp" />

This would keep the font size to 60sp as long as the text fits in width. If the text is longer, it will decrease font size. In this case, the TextViews height will also change because of height=wrap_content.

If you find any bugs, feel free to edit.

Checking for empty queryset in Django

If you have a huge number of objects, this can (at times) be much faster:

try:
    orgs[0]
    # If you get here, it exists...
except IndexError:
    # Doesn't exist!

On a project I'm working on with a huge database, not orgs is 400+ ms and orgs.count() is 250ms. In my most common use cases (those where there are results), this technique often gets that down to under 20ms. (One case I found, it was 6.)

Could be much longer, of course, depending on how far the database has to look to find a result. Or even faster, if it finds one quickly; YMMV.

EDIT: This will often be slower than orgs.count() if the result isn't found, particularly if the condition you're filtering on is a rare one; as a result, it's particularly useful in view functions where you need to make sure the view exists or throw Http404. (Where, one would hope, people are asking for URLs that exist more often than not.)

How to get 'System.Web.Http, Version=5.2.3.0?

In Package Manager Console

Install-Package Microsoft.AspNet.WebApi.Core -version 5.2.3

Is unsigned integer subtraction defined behavior?

Well, the first interpretation is correct. However, your reasoning about the "signed semantics" in this context is wrong.

Again, your first interpretation is correct. Unsigned arithmetic follow the rules of modulo arithmetic, meaning that 0x0000 - 0x0001 evaluates to 0xFFFF for 32-bit unsigned types.

However, the second interpretation (the one based on "signed semantics") is also required to produce the same result. I.e. even if you evaluate 0 - 1 in the domain of signed type and obtain -1 as the intermediate result, this -1 is still required to produce 0xFFFF when later it gets converted to unsigned type. Even if some platform uses an exotic representation for signed integers (1's complement, signed magnitude), this platform is still required to apply rules of modulo arithmetic when converting signed integer values to unsigned ones.

For example, this evaluation

signed int a = 0, b = 1;
unsigned int c = a - b;

is still guaranteed to produce UINT_MAX in c, even if the platform is using an exotic representation for signed integers.

How can I get query parameters from a URL in Vue.js?

You can get By Using this function.

console.log(this.$route.query.test)

counting number of directories in a specific directory

Using zsh:

a=(*(/N)); echo ${#a}

The N is a nullglob, / makes it match directories, # counts. It will neatly cope with spaces in directory names as well as returning 0 if there are no directories.

Hibernate: ids for this class must be manually assigned before calling save()

Assign primary key in hibernate

Make sure that the attribute is primary key and Auto Incrementable in the database. Then map it into the data class with the annotation with @GeneratedValue annotation using IDENTITY.

@Entity
@Table(name = "client")
data class Client(
        @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private val id: Int? = null
)

GL

Source

Setting PHPMyAdmin Language

sounds like you downloaded the german xampp package instead of the english xampp package (yes, it's another download-link) where the language is set according to the package you loaded. to change the language afterwards, simply edit the config.inc.php and set:

$cfg['Lang'] = 'en-utf-8';

What is the best way to prevent session hijacking?

Have you considered reading a book on PHP security? Highly recommended.

I have had much success with the following method for non SSL certified sites.

  1. Dis-allow multiple sessions under the same account, making sure you aren't checking this solely by IP address. Rather check by token generated upon login which is stored with the users session in the database, as well as IP address, HTTP_USER_AGENT and so forth

  2. Using Relation based hyperlinks Generates a link ( eg. http://example.com/secure.php?token=2349df98sdf98a9asdf8fas98df8 ) The link is appended with a x-BYTE ( preferred size ) random salted MD5 string, upon page redirection the randomly generated token corresponds to a requested page.

    • Upon reload, several checks are done.
    • Originating IP Address
    • HTTP_USER_AGENT
    • Session Token
    • you get the point.
  3. Short Life-span session authentication cookie. as posted above, a cookie containing a secure string, which is one of the direct references to the sessions validity is a good idea. Make it expire every x Minutes, reissuing that token, and re-syncing the session with the new Data. If any mis-matches in the data, either log the user out, or having them re-authenticate their session.

I am in no means an expert on the subject, I'v had a bit of experience in this particular topic, hope some of this helps anyone out there.

Change image in HTML page every few seconds

As of current edited version of the post, you call setInterval at each change's end, adding a new "changer" with each new iterration. That means after first run, there's one of them ticking in memory, after 100 runs, 100 different changers change image 100 times every second, completely destroying performance and producing confusing results.

You only need to "prime" setInterval once. Remove it from function and place it inside onload instead of direct function call.

Open file by its full path in C++

For those who are getting the path dynamicly... e.g. drag&drop:

Some main constructions get drag&dropped file with double quotes like:

"C:\MyPath\MyFile.txt"

Quick and nice solution is to use this function to remove chars from string:

void removeCharsFromString( string &str, char* charsToRemove ) {
   for ( unsigned int i = 0; i < strlen(charsToRemove); ++i ) {
      str.erase( remove(str.begin(), str.end(), charsToRemove[i]), str.end() );
   }
} 

string myAbsolutepath; //fill with your absolute path
removeCharsFromString( myAbsolutepath, "\"" );

myAbsolutepath now contains just C:\MyPath\MyFile.txt

The function needs these libraries: <iostream> <algorithm> <cstring>.
The function was based on this answer.

Working Fiddle: http://ideone.com/XOROjq

Create a Bitmap/Drawable from file path

here is a solution:

Bitmap bitmap = BitmapFactory.decodeFile(filePath);

How to install JQ on Mac by command-line?

For CentOS, RHEL, Amazon Linux: sudo yum install jq

difference between width auto and width 100 percent

  • width: auto; will try as hard as possible to keep an element the same width as its parent container when additional space is added from margins, padding, or borders.

  • width: 100%; will make the element as wide as the parent container. Extra spacing will be added to the element's size without regards to the parent. This typically causes problems.

enter image description here enter image description here

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub

EDIT

I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

Java Date - Insert into database

PreparedStatement

You should definitely use a PreparedStatement. (Tutorial)

That way you can invoke:

pstmt.setDate( 1, aDate );

The JDBC driver will do date-time handling appropriate for your particular database.

Also, a PreparedStatement stops any SQL injection hacking attempts – very important! (humor)

It should look like this:

SimpleDateFormat format = new SimpleDateFormat( "MM/dd/yyyy" );  // United States style of format.
java.util.Date myDate = format.parse( "10/10/2009" );  // Notice the ".util." of package name.

PreparedStatement pstmt = connection.prepareStatement(
"INSERT INTO USERS ( USER_ID, FIRST_NAME, LAST_NAME, SEX, DATE ) " +
" values (?, ?, ?, ?, ? )");

pstmt.setString( 1, userId );
pstmt.setString( 3, myUser.getLastName() ); 
pstmt.setString( 2, myUser.getFirstName() ); // please use "getFir…" instead of "GetFir…", per Java conventions.
pstmt.setString( 4, myUser.getSex() );
java.sql.Date sqlDate = new java.sql.Date( myDate.getTime() ); // Notice the ".sql." (not "util") in package name.
pstmt.setDate( 5, sqlDate ); 

And that's it, the JDBC driver will create the right SQL syntax for you.

Retrieving

When retrieving a Date object, you can use a SimpleDateFormat to create a formatted string representation of the date-time value.

Here is one quick example line, but search StackOverflow for many more.

String s = new SimpleDateFormat("dd/MM/yyyy").format( aDate ); 

How to get current local date and time in Kotlin

checkout these easy to use Kotlin extensions for date format

fun String.getStringDate(initialFormat: String, requiredFormat: String, locale: Locale = Locale.getDefault()): String {
    return this.toDate(initialFormat, locale).toString(requiredFormat, locale)
}

fun String.toDate(format: String, locale: Locale = Locale.getDefault()): Date = SimpleDateFormat(format, locale).parse(this)

fun Date.toString(format: String, locale: Locale = Locale.getDefault()): String {
    val formatter = SimpleDateFormat(format, locale)
    return formatter.format(this)
}

Docker: "no matching manifest for windows/amd64 in the manifest list entries"

I solved this in Windows 10 by running in admin Powershell:

cd "C:\Program Files\Docker\Docker"

And then:

./DockerCli.exe -SwitchDaemon

How to copy a file from one directory to another using PHP?

You could use the rename() function :

rename('foo/test.php', 'bar/test.php');

This however will move the file not copy

Count rows with not empty value

Make another column that determines if the referenced cell is blank using the function "CountBlank". Then use count on the values created in the new "CountBlank" column.

Android update activity UI from service

My solution might not be the cleanest but it should work with no problems. The logic is simply to create a static variable to store your data on the Service and update your view each second on your Activity.

Let's say that you have a String on your Service that you want to send it to a TextView on your Activity. It should look like this

Your Service:

public class TestService extends Service {
    public static String myString = "";
    // Do some stuff with myString

Your Activty:

public class TestActivity extends Activity {
    TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tv = new TextView(this);
        setContentView(tv);
        update();
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    while (!isInterrupted()) {
                        Thread.sleep(1000);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                update();
                            }
                        });
                    }
                } catch (InterruptedException ignored) {}
            }
        };
        t.start();
        startService(new Intent(this, TestService.class));
    }
    private void update() {
        // update your interface here
        tv.setText(TestService.myString);
    }
}

List distinct values in a vector in R

Try using the duplicated function in combination with the negation operator "!".

Example:

wdups <- rep(1:5,5)
wodups <- wdups[which(!duplicated(wdups))]

Hope that helps.

How to get class object's name as a string in Javascript?

If you don't want to use a function constructor like in Brian's answer you can use Object.create() instead:-

var myVar = {
count: 0
}

myVar.init = function(n) {
    this.count = n
    this.newDiv()
}

myVar.newDiv = function() {
    var newDiv = document.createElement("div")
    var contents = document.createTextNode("Click me!")
    var func = myVar.func(this)
    newDiv.addEventListener ? 
        newDiv.addEventListener('click', func, false) : 
        newDiv.attachEvent('onclick', func)
    newDiv.appendChild(contents)
    document.getElementsByTagName("body")[0].appendChild(newDiv)
}

myVar.func = function (thys) {
   return function() {
      thys.clickme()
   }
} 

myVar.clickme = function () {
   this.count += 1
   alert(this.count)
}

myVar.init(2)

var myVar1 = Object.create(myVar)
myVar1.init(55) 

var myVar2 = Object.create(myVar)
myVar2.init(150) 

// etc

Strangely, I couldn't get the above to work using newDiv.onClick, but it works with newDiv.addEventListener / newDiv.attachEvent.

Since Object.create is newish, include the following code from Douglas Crockford for older browsers, including IE8.

if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o
        return new F()
    }
}

This declaration has no storage class or type specifier in C++

This is a mistake:

m.check(side);

That code has to go inside a function. Your class definition can only contain declarations and functions.

Classes don't "run", they provide a blueprint for how to make an object.

The line Message m; means that an Orderbook will contain Message called m, if you later create an Orderbook.

Get list of a class' instance methods

To get only own methods, and exclude inherited ones:

From within the instance:

self.methods - self.class.superclass.instance_methods

From outside:

TestClass.instance_methods - TestClass.superclass.instance_methods

Add it to the class:

class TestClass
  class << self
    def own_methods
      self.instance_methods - self.superclass.instance_methods
    end
  end
end

TestClass.own_methods
=> [:method1, :method2, :method3]

(with ruby 2.6.x)

Set Windows process (or user) memory limit

Use the Application Verifier (AppVerifier) tool from Microsoft.

In my case I need to simulate memory no longer being available so I did the following in the tool:

  1. Added my application
  2. Unchecked Basic
  3. Checked Low Resource Simulation
    • Changed TimeOut to 120000 - my application will run normally for 2 minutes before anything goes into effect.
    • Changed HeapAlloc to 100 - 100% chance of heap allocation error
    • Set Stacks to true - the stack will not be able to grow any larger
  4. Save
  5. Start my application

After 2 minutes my program could no longer allocate new memory and I was able to see how everything was handled.

How to clean project cache in Intellij idea like Eclipse's clean?

Delete the "target" folder under the offending module. Then Build | Rebuild Project. Also make sure your clear the web browsers cache.

Revert to Eclipse default settings

Open any java class -> Right clic -> Checkstyle -> Clear Checkstyle vilolations. It works for me.

Regex to replace everything except numbers and a decimal point

Use this:

document.getElementById(target).value = newVal.replace(/[^0-9.]/g, '');

Array initialization syntax when not in a declaration

For those of you, who doesn't like this monstrous new AClass[] { ... } syntax, here's some sugar:

public AClass[] c(AClass... arr) { return arr; }

Use this little function as you like:

AClass[] array;
...
array = c(object1, object2);

How to use mysql JOIN without ON condition?

See some example in http://www.sitepoint.com/understanding-sql-joins-mysql-database/

You can use 'USING' instead of 'ON' as in the query

SELECT * FROM table1 LEFT JOIN table2 USING (id);

What is an ORM, how does it work, and how should I use one?

Can anyone give me a brief explanation...

Sure.

ORM stands for "Object to Relational Mapping" where

  • The Object part is the one you use with your programming language ( python in this case )

  • The Relational part is a Relational Database Manager System ( A database that is ) there are other types of databases but the most popular is relational ( you know tables, columns, pk fk etc eg Oracle MySQL, MS-SQL )

  • And finally the Mapping part is where you do a bridge between your objects and your tables.

In applications where you don't use a ORM framework you do this by hand. Using an ORM framework would allow you do reduce the boilerplate needed to create the solution.

So let's say you have this object.

 class Employee:
      def __init__( self, name ): 
          self.__name = name

       def getName( self ):
           return self.__name

       #etc.

and the table

   create table employee(
          name varcar(10),
          -- etc  
    )

Using an ORM framework would allow you to map that object with a db record automagically and write something like:

   emp = Employee("Ryan")

   orm.save( emp )

And have the employee inserted into the DB.

Oops it was not that brief but I hope it is simple enough to catch other articles you read.

What is the difference between Integer and int in Java?

This is taken from Java: The Complete Reference, Ninth Edition

Java uses primitive types (also called simple types), such as int or double, to hold the basic data types supported by the language. Primitive types, rather than objects, are used for these quantities for the sake of performance. Using objects for these values would add an unacceptable overhead to even the simplest of calculations. Thus, the primitive types are not part of the object hierarchy, and they do not inherit Object.

Despite the performance benefit offered by the primitive types, there are times when you will need an object representation. For example, you can’t pass a primitive type by reference to a method. Also, many of the standard data structures implemented by Java operate on objects, which means that you can’t use these (object specific) data structures to store primitive types. To handle these (and other) situations, Java provides type wrappers, which are classes that encapsulate a primitive type within an object.

Wrapper classes relate directly to Java’s autoboxing feature. The type wrappers are Double, Float, Long, Integer, Short, Byte, Character, and Boolean. These classes offer a wide array of methods that allow you to fully integrate the primitive types into Java’s object hierarchy.

MS-access reports - The search key was not found in any record - on save

In Access 2007 this error occurs when importing an Excel file where there are two fields with the same column header.

Escape @ character in razor view engine

@Html.Raw("@") seems to me to be even more reliable than @@, since not in all cases @@ will escape.

Therefore:

<meta name="twitter:site" content="@twitterSite">

would be:

<meta name="twitter:site" content="@Html.Raw("@")twitterSite">

Alter and Assign Object Without Side Effects

You will have the same object two times in your array, because object values are passed by reference. You have to create a new object like this

myElement.id = 244;
myElement.value = 3556;
myArray[0] = $.extend({}, myElement); //for shallow copy or
myArray[0] = $.extend(true, {}, myElement); // for deep copy

or

myArray.push({ id: 24, value: 246 });

Disable color change of anchor tag when visited

Either delete the selector or set it to the same color as your text appears normally.

MySQL integer field is returned as string in PHP

If prepared statements are used, the type will be int where appropriate. This code returns an array of rows, where each row is an associative array. Like if fetch_assoc() was called for all rows, but with preserved type info.

function dbQuery($sql) {
    global $mysqli;

    $stmt = $mysqli->prepare($sql);
    $stmt->execute();
    $stmt->store_result();

    $meta = $stmt->result_metadata();
    $params = array();
    $row = array();

    while ($field = $meta->fetch_field()) {
      $params[] = &$row[$field->name];
    }

    call_user_func_array(array($stmt, 'bind_result'), $params);

    while ($stmt->fetch()) {
      $tmp = array();
      foreach ($row as $key => $val) {
        $tmp[$key] = $val;
      }
      $ret[] = $tmp;
    }

    $meta->free();
    $stmt->close();

    return $ret;
}

How to change color in markdown cells ipython/jupyter notebook?

Similarly to Jakob's answer, you can use HTML tags. Just a note that the color attribute of font (<font color=...>) is deprecated in HTML5. The following syntax would be HTML5-compliant:

This <span style="color:red">word</span> is not black.

Same caution that Jakob made probably still applies:

Be aware that this will not survive a conversion of the notebook to latex.

(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

This error occurs because you are using a normal string as a path. You can use one of the three following solutions to fix your problem:

1: Just put r before your normal string it converts normal string to raw string:

pandas.read_csv(r"C:\Users\DeePak\Desktop\myac.csv")

2:

pandas.read_csv("C:/Users/DeePak/Desktop/myac.csv")

3:

pandas.read_csv("C:\\Users\\DeePak\\Desktop\\myac.csv")

java.lang.NoClassDefFoundError in junit

  1. Right click your project in Package Explorer > click Properties
  2. go to Java Build Path > Libraries tab
  3. click on 'Add Library' button
  4. select JUnit
  5. click Next.
  6. select in dropdown button JUnit4 or other new versions.
  7. click finish.
  8. Then Ok.

SQL Server : GROUP BY clause to get comma-separated values

SELECT  [ReportId], 
        SUBSTRING(d.EmailList,1, LEN(d.EmailList) - 1) EmailList
FROM
        (
            SELECT DISTINCT [ReportId]
            FROM Table1
        ) a
        CROSS APPLY
        (
            SELECT [Email] + ', ' 
            FROM Table1 AS B 
            WHERE A.[ReportId] = B.[ReportId]
            FOR XML PATH('')
        ) D (EmailList) 

SQLFiddle Demo

When is del useful in Python?

One place I've found del useful is cleaning up extraneous variables in for loops:

for x in some_list:
  do(x)
del x

Now you can be sure that x will be undefined if you use it outside the for loop.

Disable Tensorflow debugging information

If you only need to get rid of warning outputs on the screen, you might want to clear the console screen right after importing the tensorflow by using this simple command (Its more effective than disabling all debugging logs in my experience):

In windows:

import os
os.system('cls')

In Linux or Mac:

import os
os.system('clear')

Test credit card numbers for use with PayPal sandbox

It turns out, after messing around with all of the settings in the test business account, that one (or more) of the fraud related settings in the payment receiving preferences / security settings screens were causing the test payments to fail (without any useful error).

grep a file, but show several surrounding lines?

Here is the @Ygor solution in awk

awk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=3 a=3 s="pattern" myfile

Note: Replace a and b variables with number of lines before and after.

It's especially useful for system which doesn't support grep's -A, -B and -C parameters.

add scroll bar to table body

This is because you are adding your <tbody> tag before <td> in table you cannot print any data without <td>.

So for that you have to make a <div> say #header with position: fixed;

 header
 {
      position: fixed;
 }

make another <div> which will act as <tbody>

tbody
{
    overflow:scroll;
}

Now your header is fixed and the body will scroll. And the header will remain there.

Calling C/C++ from Python?

Cython is definitely the way to go, unless you anticipate writing Java wrappers, in which case SWIG may be preferable.

I recommend using the runcython command line utility, it makes the process of using Cython extremely easy. If you need to pass structured data to C++, take a look at Google's protobuf library, it's very convenient.

Here is a minimal examples I made that uses both tools:

https://github.com/nicodjimenez/python2cpp

Hope it can be a useful starting point.

scrollTop jquery, scrolling to div with id?

instead of

$('html, body').animate({scrollTop:xxx}, 'slow');

use

$('html, body').animate({scrollTop:$('#div_id').position().top}, 'slow');

this will return the absolute top position of whatever element you select as #div_id

Is it possible to style a mouseover on an image map using CSS?

I don't think this is possible just using CSS (not cross browser at least) but the jQuery plugin ImageMapster will do what you're after. You can outline, colour in or use an alternative image for hover/active states on an image map.

http://www.outsharked.com/imagemapster/examples/usa.html

Combining paste() and expression() functions in plot labels

Very nice example using paste and substitute to typeset both symbols (mathplot) and variables at http://vis.supstat.com/2013/04/mathematical-annotation-in-r/

Here is a ggplot adaptation

library(ggplot2)
x_mean <- 1.5
x_sd <- 1.2
N <- 500

n <- ggplot(data.frame(x <- rnorm(N, x_mean, x_sd)),aes(x=x)) +
    geom_bar() + stat_bin() +
    labs(title=substitute(paste(
             "Histogram of random data with ",
             mu,"=",m,", ",
             sigma^2,"=",s2,", ",
             "draws = ", numdraws,", ",
             bar(x),"=",xbar,", ",
             s^2,"=",sde),
             list(m=x_mean,xbar=mean(x),s2=x_sd^2,sde=var(x),numdraws=N)))

print(n)

Merge / convert multiple PDF files into one PDF

Yet another option, useful is you want to select also the pages inside the documents to be merged:

pdfjoin image.jpg '-' doc_only_first_pages.pdf '1,2' doc_with_all_pages.pdf '-'

It comes with package texlive-extra-utils