Programs & Examples On #Jquery effects

For questions related to animating elements using jQuery effects.

JQuery show and hide div on mouse click (animate)

Try this:

<script type="text/javascript">
$.fn.toggleFuncs = function() {
    var functions = Array.prototype.slice.call(arguments),
    _this = this.click(function(){
        var i = _this.data('func_count') || 0;
        functions[i%functions.length]();
        _this.data('func_count', i+1);
    });
}
$('$showmenu').toggleFuncs(
        function() {
           $( ".menu" ).toggle( "drop" );
            },
            function() {
                $( ".menu" ).toggle( "drop" );
            }
); 

</script>

First fuction is an alternative to JQuery deprecated toggle :) . Works good with JQuery 2.0.3 and JQuery UI 1.10.3

Laravel 4: how to "order by" using Eloquent ORM

If you are using the Eloquent ORM you should consider using scopes. This would keep your logic in the model where it belongs.

So, in the model you would have:

public function scopeIdDescending($query)
{
        return $query->orderBy('id','DESC');
}   

And outside the model you would have:

$posts = Post::idDescending()->get();

More info: http://laravel.com/docs/eloquent#query-scopes

jquery find element by specific class when element has multiple classes

You can select elements with multiple classes like so:

$("element.firstClass.anotherClass");

Simply chain the next class onto the first one, without a space (spaces mean "children of").

iOS: Modal ViewController with transparent background

A complete method tested on iOS 7 and iOS 8.

@interface UIViewController (MBOverCurrentContextModalPresenting)

/// @warning Some method of viewControllerToPresent will called twice before iOS 8, e.g. viewWillAppear:.
- (void)MBOverCurrentContextPresentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^)(void))completion;

@end

@implementation UIViewController (MBOverCurrentContextModalPresenting)

- (void)MBOverCurrentContextPresentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^)(void))completion {
    UIViewController *presentingVC = self;

    // iOS 8 before
    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
        UIViewController *root = presentingVC;
        while (root.parentViewController) {
            root = root.parentViewController;
        }

        [presentingVC presentViewController:viewControllerToPresent animated:YES completion:^{
            [viewControllerToPresent dismissViewControllerAnimated:NO completion:^{
                UIModalPresentationStyle orginalStyle = root.modalPresentationStyle;
                if (orginalStyle != UIModalPresentationCurrentContext) {
                    root.modalPresentationStyle = UIModalPresentationCurrentContext;
                }
                [presentingVC presentViewController:viewControllerToPresent animated:NO completion:completion];
                if (orginalStyle != UIModalPresentationCurrentContext) {
                    root.modalPresentationStyle = orginalStyle;
                }
            }];
        }];
        return;
    }

    UIModalPresentationStyle orginalStyle = viewControllerToPresent.modalPresentationStyle;
    if (orginalStyle != UIModalPresentationOverCurrentContext) {
        viewControllerToPresent.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    }
    [presentingVC presentViewController:viewControllerToPresent animated:YES completion:completion];
    if (orginalStyle != UIModalPresentationOverCurrentContext) {
        viewControllerToPresent.modalPresentationStyle = orginalStyle;
    }
}

@end

In a bootstrap responsive page how to center a div

jsFiddle

HTML:

<div class="container" id="parent">
  <div class="row">
    <div class="col-lg-12">text
      <div class="row ">
        <div class="col-md-4 col-md-offset-4" id="child">TEXT</div>
      </div>
    </div>
  </div>
</div>

CSS:

#parent {    
    text-align: center;
}
#child {
    margin: 0 auto;
    display: inline-block;
    background: red;
    color: white;
}

Cannot implicitly convert type 'int' to 'short'

The plus operator converts operands to int first and then does the addition. So the result is the int. You need to cast it back to short explicitly because conversions from a "longer" type to "shorter" type a made explicit, so that you don't loose data accidentally with an implicit cast.

As to why int16 is cast to int, the answer is, because this is what is defined in C# spec. And C# is this way is because it was designed to closely match to the way how CLR works, and CLR has only 32/64 bit arithmetic and not 16 bit. Other languages on top of CLR may choose to expose this differently.

How to validate an email address using a regular expression?

While deciding which characters are allowed, please remember your apostrophed and hyphenated friends. I have no control over the fact that my company generates my email address using my name from the HR system. That includes the apostrophe in my last name. I can't tell you how many times I have been blocked from interacting with a website by the fact that my email address is "invalid".

Java count occurrence of each item in an array

You could use a MultiSet from Google Collections/Guava or a Bag from Apache Commons.

If you have a collection instead of an array, you can use addAll() to add the entire contents to the above data structure, and then apply the count() method to each value. A SortedMultiSet or SortedBag would give you the items in a defined order.

Google Collections actually has very convenient ways of going from arrays to a SortedMultiset.

Angular 6: saving data to local storage

First you should understand how localStorage works. you are doing wrong way to set/get values in local storage. Please read this for more information : How to Use Local Storage with JavaScript

How to read text files with ANSI encoding and non-English letters?

using (StreamWriter writer = new StreamWriter(File.Open(@"E:\Sample.txt", FileMode.Append), Encoding.GetEncoding(1250)))  ////File.Create(path)
        {
            writer.Write("Sample Text");
        }

Select multiple columns in data.table by their numeric indices

From v1.10.2 onwards, you can also use ..

dt <- data.table(a=1:2, b=2:3, c=3:4)

keep_cols = c("a", "c")

dt[, ..keep_cols]

Using IQueryable with Linq

It allows for further querying further down the line. If this was beyond a service boundary say, then the user of this IQueryable object would be allowed to do more with it.

For instance if you were using lazy loading with nhibernate this might result in graph being loaded when/if needed.

Remove the last character in a string in T-SQL?

Try It :

  DECLARE @String NVARCHAR(100)
    SET @String = '12354851'
    SELECT LEFT(@String, NULLIF(LEN(@String)-1,-1))

Kill process by name?

import os, signal

def check_kill_process(pstring):
    for line in os.popen("ps ax | grep " + pstring + " | grep -v grep"):
        fields = line.split()
        pid = fields[0]
        os.kill(int(pid), signal.SIGKILL)

How to check if a .txt file is in ASCII or UTF-8 format in Windows environment?

Open the file in Notepad. Click 'Save As...'. In the 'Encoding:' combo box you will see the current file format.

How to prevent Browser cache for php site

You can try this:

    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
    header("Connection: close");

Hopefully it will help prevent Cache, if any!

Create a tag in a GitHub repository

For creating git tag you can simply run git tag <tagname> command by replacing with the actual name of the tag. Here is a complete tutorial on the basics of managing git tags: https://www.drupixels.com/blog/git-tags-create-push-remote-checkout-and-much-more

Codeigniter displays a blank page instead of error messages

The error, In my case, was occurring because my Apache server was configured to run PHP as Fast CGI, I changed it to FPM and it worked.

How organize uploaded media in WP?

Currently, media organisation is possible.

The "problem" with the media library in wordpress is always interesting. Check the following plugin to solve this: WordPress Real Media Library. WP RML creates a virtual folder structure based on an own taxonomy.

Drag & Drop your files

It allows you to organize your wordpress media library in a nice way with folders. It is easy to use, just drag&drop your files and move it to a specific folder. Filter when inserting media or create a gallery from a folder.

Turn your WordPress media library to the next level with folders / categories. Get organized with thousands of images.

RML (Real Media Library) is one of the most wanted media wordpress plugins. It is easy to use and it allows you to organize your thousands of images in folders. It is similar to wordpress categories like in the posts.

Use your mouse (or touch) to drag and drop your files. Create, rename, delete or reorder your folders If you want to select a image from the “Select a image”-dialog (e. g. featured image) you can filter when inserting media. Just install this plugin and it works fine with all your image and media files. It also supports multisite.

If you buy, you get: Forever FREE updates and high quality and fast support.

From the product description i can quote. If you want to try the plugin, there is also a demo on the plugin page.

Update #1 (2017-01-27): Manage your uploads physically

A long time ago I started to open this thread and now there is a usable extension plugin for Real Media Library which allows you to physically manage your uploads folder.

enter image description here

Check out this plugin: https://wordpress.org/plugins/physical-custom-upload-folder/

Do you know the wp-content/uploads folder? There, the files are stored in year/month based folders. This can be a very complicated and mass process, especially when you are working with a FTP client like FileZilla.

Moving already uploaded files: This plugin does not allow to move the files physically when you move a file in the Real Media Library because WordPress uses the URL's in different places. It is very hard to maintain such a process. So this only works for new uploads.

Physical organisation on server?

(Please read on if you are developer) I as developer thought about a solution about this. Does it make sense to organize the uploads on server, too? Yes, i think. Many people ask to organize it physically. I think also that the process of moving files on server and updating the image references is very hard to develop. There are many plugins out now, which are saving the URLs in their own-created database-tables.

Please check this thread where i explained the problem: https://wordpress.stackexchange.com/questions/226675/physical-organization-of-wordpress-media-library-real-media-library-plugin

Should a function have only one return statement?

Having a single exit point reduces Cyclomatic Complexity and therefore, in theory, reduces the probability that you will introduce bugs into your code when you change it. Practice however, tends to suggest that a more pragmatic approach is needed. I therefore tend to aim to have a single exit point, but allow my code to have several if that is more readable.

How to to send mail using gmail in Laravel?

Working for me after trying various combinations.

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=passowrd
MAIL_ENCRYPTION=ssl

It is necessary to generate application password https://myaccount.google.com/security and us it as MAIL_PASSWORD environment variable.

I found about about this by checking error code from google server, which was use-full and lead me to this webpage.

What are Java command line options to set to allow JVM to be remotely debugged?

Here is the easiest solution.

There are a lot of environment special configurations needed if you are using Maven. So, if you start your program from maven, just run the mvnDebug command instead of mvn, it will take care of starting your app with remote debugging configurated. Now you can just attach a debugger on port 8000.

It'll take care of all the environment problems for you.

Converting Select results into Insert script - SQL Server

I had a similar problem, but I needed to be able to create an INSERT statement from a query (with filters etc.)

So I created following procedure:

CREATE PROCEDURE dbo.ConvertQueryToInsert (@input NVARCHAR(max), @target NVARCHAR(max)) AS BEGIN

    DECLARE @fields NVARCHAR(max);
    DECLARE @select NVARCHAR(max);

    -- Get the defintion from sys.columns and assemble a string with the fields/transformations for the dynamic query
    SELECT
        @fields = COALESCE(@fields + ', ', '') + '[' + name +']', 
        @select = COALESCE(@select + ', ', '') + ''''''' + ISNULL(CAST([' + name + '] AS NVARCHAR(max)), ''NULL'')+'''''''
    FROM tempdb.sys.columns 
    WHERE [object_id] = OBJECT_ID(N'tempdb..'+@input);

    -- Run the a dynamic query with the fields from @select into a new temp table
    CREATE TABLE #ConvertQueryToInsertTemp (strings nvarchar(max))
    DECLARE @stmt NVARCHAR(max) = 'INSERT INTO #ConvertQueryToInsertTemp SELECT '''+ @select + ''' AS [strings] FROM '+@input
    exec sp_executesql @stmt

    -- Output the final insert statement 
    SELECT 'INSERT INTO ' + @target + ' (' + @fields + ') VALUES (' + REPLACE(strings, '''NULL''', 'NULL') +')' FROM #ConvertQueryToInsertTemp

    -- Clean up temp tables
    DROP TABLE #ConvertQueryToInsertTemp
    SET @stmt = 'DROP TABLE ' + @input
    exec sp_executesql @stmt
END

You can then use it by writing the output of your query into a temp table and running the procedure:

-- Example table
CREATE TABLE Dummy (Id INT, Comment NVARCHAR(50), TimeStamp DATETIME)
INSERT INTO Dummy VALUES (1 , 'Foo', GetDate()), (2, 'Bar', GetDate()), (3, 'Foo Bar', GetDate())

-- Run query and procedure
SELECT * INTO #TempTableForConvert FROM Dummy WHERE Id < 3
EXEC dbo.ConvertQueryToInsert '#TempTableForConvert', 'dbo.Dummy'

Note: This procedure only casts the values to a string which can cause the data to look a bit different. With DATETIME for example the seconds will be lost.

How to find a value in an excel column by vba code Cells.Find

I'd prefer to use the .Find method directly on a range object containing the range of cells to be searched. For original poster's code it might look like:

Set cell = ActiveSheet.Columns("B:B").Find( _
    What:=celda, _
    After:=ActiveCell _
    LookIn:=xlFormulas, _
    LookAt:=xlWhole, _
    SearchOrder:=xlByRows, _
    SearchDirection:=xlNext, _
    MatchCase:=False, _
    SearchFormat:=False _
)

If cell Is Nothing Then
    'do something
Else
    'do something else
End If

I'd prefer to use more variables (and be sure to declare them) and let a lot of optional arguments use their default values:

Dim rng as Range
Dim cell as Range
Dim search as String

Set rng = ActiveSheet.Columns("B:B")
search = "String to Find"
Set cell = rng.Find(What:=search, LookIn:=xlFormulas, LookAt:=xlWhole, MatchCase:=False)

If cell Is Nothing Then
    'do something
Else
    'do something else
End If

I kept LookIn:=, LookAt::=, and MatchCase:= to be explicit about what is being matched. The other optional parameters control the order matches are returned in - I'd only specify those if the order is important to my application.

Including dependencies in a jar with Maven

You can do this using the maven-assembly plugin with the "jar-with-dependencies" descriptor. Here's the relevant chunk from one of our pom.xml's that does this:

  <build>
    <plugins>
      <!-- any other plugins -->
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
      </plugin>
    </plugins>
  </build>

VB.NET Switch Statement GoTo Case

Why don't you just refactor the default case as a method and call it from both places? This should be more readable and will allow you to change the code later in a more efficient manner.

How can I delete an item from an array in VB.NET?

This may be a lazy man's solution, but can't you just delete the contents of the index you want removed by reassigning their values to 0 or "" and then ignore/skip these empty array elements instead of recreating and copying arrays on and off?

Pinging servers in Python

This function works in any OS (Unix, Linux, macOS, and Windows)
Python 2 and Python 3

EDITS:
By @radato os.system was replaced by subprocess.call. This avoids shell injection vulnerability in cases where your hostname string might not be validated.

import platform    # For getting the operating system name
import subprocess  # For executing a shell command

def ping(host):
    """
    Returns True if host (str) responds to a ping request.
    Remember that a host may not respond to a ping (ICMP) request even if the host name is valid.
    """

    # Option for the number of packets as a function of
    param = '-n' if platform.system().lower()=='windows' else '-c'

    # Building the command. Ex: "ping -c 1 google.com"
    command = ['ping', param, '1', host]

    return subprocess.call(command) == 0

Note that, according to @ikrase on Windows this function will still return True if you get a Destination Host Unreachable error.

Explanation

The command is ping in both Windows and Unix-like systems.
The option -n (Windows) or -c (Unix) controls the number of packets which in this example was set to 1.

platform.system() returns the platform name. Ex. 'Darwin' on macOS.
subprocess.call() performs a system call. Ex. subprocess.call(['ls','-l']).

Android 8: Cleartext HTTP traffic not permitted

To apply these various answers to Xamarin.Android, you can use class and assembly level Attributes vs. manually editing the AndroidManifest.xml

Internet permission of course is needed (duh..):

[assembly: UsesPermission(Android.Manifest.Permission.Internet)]

Note: Typically assembly level attributes are added to your AssemblyInfo.cs file, but any file, below the using and above the namespace works.

Then on your Application subclass (create one if needed), you can add NetworkSecurityConfig with a reference to an Resources/xml/ZZZZ.xml file:

#if DEBUG
[Application(AllowBackup = false, Debuggable = true, NetworkSecurityConfig = "@xml/network_security_config")]
#else
[Application(AllowBackup = true, Debuggable = false, NetworkSecurityConfig = "@xml/network_security_config"))]
#endif
public class App : Application
{
    public App(IntPtr javaReference, Android.Runtime.JniHandleOwnership transfer) : base(javaReference, transfer) { }
    public App() { }

    public override void OnCreate()
    {
        base.OnCreate();
    }
}

Create a file in the Resources/xml folder (create the xml folder if needed).

Example xml/network_security_config file, adjust as needed (see other answers)

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
          <domain includeSubdomains="true">www.example.com</domain>
          <domain includeSubdomains="true">notsecure.com</domain>
          <domain includeSubdomains="false">xxx.xxx.xxx</domain>
    </domain-config>
</network-security-config>

You can also use the UsesCleartextTraffic parameter on the ApplicationAttribute:

#if DEBUG
[Application(AllowBackup = false, Debuggable = true, UsesCleartextTraffic = true)]
#else
[Application(AllowBackup = true, Debuggable = false, UsesCleartextTraffic = true))]
#endif

Session unset, or session_destroy?

Something to be aware of, the $_SESSION variables are still set in the same page after calling session_destroy() where as this is not the case when using unset($_SESSION) or $_SESSION = array(). Also, unset($_SESSION) blows away the $_SESSION superglobal so only do this when you're destroying a session.

With all that said, it's best to do like the PHP docs has it in the first example for session_destroy().

How do you configure an OpenFileDialog to select folders?

Better to use the FolderBrowserDialog for that.

using (FolderBrowserDialog dlg = new FolderBrowserDialog())
{
    dlg.Description = "Select a folder";
    if (dlg.ShowDialog() == DialogResult.OK)
    {
        MessageBox.Show("You selected: " + dlg.SelectedPath);
    }
}

How to hide a column (GridView) but still access its value?

You can make the column hidden on the server side and for some reason this is different to doing it the aspx code. It can still be referenced as if it was visible. Just add this code to your OnDataBound event.

protected void gvSearchResults_DataBound(object sender, EventArgs e)
{
    GridView gridView = (GridView)sender;

    if (gridView.HeaderRow != null && gridView.HeaderRow.Cells.Count > 0)
    {
        gridView.HeaderRow.Cells[UserIdColumnIndex].Visible = false;
    }

    foreach (GridViewRow row in gvSearchResults.Rows)
    {
        row.Cells[UserIdColumnIndex].Visible = false;
    }
}

read subprocess stdout line by line

Bit late to the party, but was surprised not to see what I think is the simplest solution here:

import io
import subprocess

proc = subprocess.Popen(["prog", "arg"], stdout=subprocess.PIPE)
for line in io.TextIOWrapper(proc.stdout, encoding="utf-8"):  # or another encoding
    # do something with line

(This requires Python 3.)

Spark SQL: apply aggregate functions to a list of columns

There are multiple ways of applying aggregate functions to multiple columns.

GroupedData class provides a number of methods for the most common functions, including count, max, min, mean and sum, which can be used directly as follows:

  • Python:

    df = sqlContext.createDataFrame(
        [(1.0, 0.3, 1.0), (1.0, 0.5, 0.0), (-1.0, 0.6, 0.5), (-1.0, 5.6, 0.2)],
        ("col1", "col2", "col3"))
    
    df.groupBy("col1").sum()
    
    ## +----+---------+-----------------+---------+
    ## |col1|sum(col1)|        sum(col2)|sum(col3)|
    ## +----+---------+-----------------+---------+
    ## | 1.0|      2.0|              0.8|      1.0|
    ## |-1.0|     -2.0|6.199999999999999|      0.7|
    ## +----+---------+-----------------+---------+
    
  • Scala

    val df = sc.parallelize(Seq(
      (1.0, 0.3, 1.0), (1.0, 0.5, 0.0),
      (-1.0, 0.6, 0.5), (-1.0, 5.6, 0.2))
    ).toDF("col1", "col2", "col3")
    
    df.groupBy($"col1").min().show
    
    // +----+---------+---------+---------+
    // |col1|min(col1)|min(col2)|min(col3)|
    // +----+---------+---------+---------+
    // | 1.0|      1.0|      0.3|      0.0|
    // |-1.0|     -1.0|      0.6|      0.2|
    // +----+---------+---------+---------+
    

Optionally you can pass a list of columns which should be aggregated

df.groupBy("col1").sum("col2", "col3")

You can also pass dictionary / map with columns a the keys and functions as the values:

  • Python

    exprs = {x: "sum" for x in df.columns}
    df.groupBy("col1").agg(exprs).show()
    
    ## +----+---------+
    ## |col1|avg(col3)|
    ## +----+---------+
    ## | 1.0|      0.5|
    ## |-1.0|     0.35|
    ## +----+---------+
    
  • Scala

    val exprs = df.columns.map((_ -> "mean")).toMap
    df.groupBy($"col1").agg(exprs).show()
    
    // +----+---------+------------------+---------+
    // |col1|avg(col1)|         avg(col2)|avg(col3)|
    // +----+---------+------------------+---------+
    // | 1.0|      1.0|               0.4|      0.5|
    // |-1.0|     -1.0|3.0999999999999996|     0.35|
    // +----+---------+------------------+---------+
    

Finally you can use varargs:

  • Python

    from pyspark.sql.functions import min
    
    exprs = [min(x) for x in df.columns]
    df.groupBy("col1").agg(*exprs).show()
    
  • Scala

    import org.apache.spark.sql.functions.sum
    
    val exprs = df.columns.map(sum(_))
    df.groupBy($"col1").agg(exprs.head, exprs.tail: _*)
    

There are some other way to achieve a similar effect but these should more than enough most of the time.

See also:

Difference between JOIN and INNER JOIN

Similarly with OUTER JOINs, the word "OUTER" is optional. It's the LEFT or RIGHT keyword that makes the JOIN an "OUTER" JOIN.

However for some reason I always use "OUTER" as in LEFT OUTER JOIN and never LEFT JOIN, but I never use INNER JOIN, but rather I just use "JOIN":

SELECT ColA, ColB, ...
FROM MyTable AS T1
     JOIN MyOtherTable AS T2
         ON T2.ID = T1.ID
     LEFT OUTER JOIN MyOptionalTable AS T3
         ON T3.ID = T1.ID

How do I shutdown, restart, or log off Windows via a bat file?

I would write this in Notepad or WordPad for a basic logoff command:

@echo off
shutdown -l

This is basically the same as clicking start and logoff manually, but it is just slightly faster if you have the batch file ready.

There was no endpoint listening at (url) that could accept the message

Another case I just had - when the request size is bigger than the request size set in IIS as a limit, then you can get that error too.

Check the IIS request limit and increase it if it's lower than you need. Here is how you can check and change the IIS request limit:

  1. Open the IIS
  2. Click your site and/or your mapped application
  3. Click on Feature view and click Request Filtering
  4. Click - Edit Feature Settings.

Edit Feature Settings

I just found also another thread in stack IIS 7.5 hosted WCF service throws EndpointNotFoundException with 404 only for large requests

How to unzip files programmatically in Android?

public class MainActivity extends Activity {

private String LOG_TAG = MainActivity.class.getSimpleName();

private File zipFile;
private File destination;

private TextView status;

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

    status = (TextView) findViewById(R.id.main_status);
    status.setGravity(Gravity.CENTER);

    if ( initialize() ) {
        zipFile = new File(destination, "BlueBoxnew.zip");
        try {
            Unzipper.unzip(zipFile, destination);
            status.setText("Extracted to \n"+destination.getAbsolutePath());
        } catch (ZipException e) {
            Log.e(LOG_TAG, e.getMessage());
        } catch (IOException e) {
            Log.e(LOG_TAG, e.getMessage());
        }
    } else {
        status.setText("Unable to initialize sd card.");
    }
}

public boolean initialize() {
    boolean result = false;
     File sdCard = new File(Environment.getExternalStorageDirectory()+"/zip/");
    //File sdCard = Environment.getExternalStorageDirectory();
    if ( sdCard != null ) {
        destination = sdCard;
        if ( !destination.exists() ) {
            if ( destination.mkdir() ) {
                result = true;
            }
        } else {
            result = true;
        }
    }

    return result;
}

 }

->Helper Class(Unzipper.java)

    import java.io.File;
    import java.io.FileInputStream;
   import java.io.FileOutputStream;
    import java.io.IOException;
       import java.util.zip.ZipEntry;
    import java.util.zip.ZipException;
    import java.util.zip.ZipInputStream;
     import android.util.Log;

   public class Unzipper {

private static String LOG_TAG = Unzipper.class.getSimpleName();

public static void unzip(final File file, final File destination) throws ZipException, IOException {
    new Thread() {
        public void run() {
            long START_TIME = System.currentTimeMillis();
            long FINISH_TIME = 0;
            long ELAPSED_TIME = 0;
            try {
                ZipInputStream zin = new ZipInputStream(new FileInputStream(file));
                String workingDir = destination.getAbsolutePath()+"/";

                byte buffer[] = new byte[4096];
                int bytesRead;
                ZipEntry entry = null;
                while ((entry = zin.getNextEntry()) != null) {
                    if (entry.isDirectory()) {
                        File dir = new File(workingDir, entry.getName());
                        if (!dir.exists()) {
                            dir.mkdir();
                        }
                        Log.i(LOG_TAG, "[DIR] "+entry.getName());
                    } else {
                        FileOutputStream fos = new FileOutputStream(workingDir + entry.getName());
                        while ((bytesRead = zin.read(buffer)) != -1) {
                            fos.write(buffer, 0, bytesRead);
                        }
                        fos.close();
                        Log.i(LOG_TAG, "[FILE] "+entry.getName());
                    }
                }
                zin.close();

                FINISH_TIME = System.currentTimeMillis();
                ELAPSED_TIME = FINISH_TIME - START_TIME;
                Log.i(LOG_TAG, "COMPLETED in "+(ELAPSED_TIME/1000)+" seconds.");
            } catch (Exception e) {
                Log.e(LOG_TAG, "FAILED");
            }
        };
    }.start();
}

   }

->xml layout(activity_main.xml):

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context=".MainActivity" >

<TextView
    android:id="@+id/main_status"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="@string/hello_world" />

</RelativeLayout>

->permission in Menifest file:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Invoking a static method using reflection

// String.class here is the parameter type, that might not be the case with you
Method method = clazz.getMethod("methodName", String.class);
Object o = method.invoke(null, "whatever");

In case the method is private use getDeclaredMethod() instead of getMethod(). And call setAccessible(true) on the method object.

Sharing a variable between multiple different threads

AtomicBoolean

The succinct Answer by NPE sums up your three options. I'll add some example code for the second item listed there: AtomicBoolean.

You can think of the AtomicBoolean class as providing some thread-safety wrapping around a boolean value.

If you instantiate the AtomicBoolean only once, then you need not worry about the visibility issue in the Java Memory Model that requires volatile as a solution (the first item in that other Answer). Also, you need not concern yourself with synchronization (the third item in that other Answer) because AtomicBoolean performs that function of protecting multi-threaded access to its internal boolean value.

Let's look at some example code.

Firstly, in modern Java we generally do not address the Thread class directly. We now have the Executors framework to simplify handling of threads.

This code below is using Project Loom technology, coming to a future version of Java. Preliminary builds available now, built on early-access Java 16. This makes for simpler coding, with ExecutorService being AutoCloseable for convenient use with try-with-resources syntax. But Project Loom is not related to the point of this Answer; it just makes for simpler code that is easier to understand as “structured concurrency”.

The idea here is that we have three threads: the original thread, plus a ExecutorService that will create two more threads. The two new threads both report the value of our AtomicBoolean. The first new thread does so immediately, while the other waits 10 seconds before reporting. Meanwhile, our main thread sleeps for 5 seconds, wakes, changes the AtomicBoolean object’s contained value, and then waits for that second thread to wake and complete its work the report on the now-altered AtomicBoolean contained value. While we are installing seconds between each event, this is merely for dramatic demonstration. The real point is that these threads could coincidently try to access the AtomicBoolean simultaneously, but that object will protect access to its internal boolean value in a thread-safe manner. Protecting against simultaneous access is the job of the Atomic… classes.

try (
        ExecutorService executorService = Executors.newVirtualThreadExecutor() ;
)
{
    AtomicBoolean flag = new AtomicBoolean( true );

    // This task, when run, will immediately report the flag.
    Runnable task1 = ( ) -> System.out.println( "First task reporting flag = " + flag.get() + ". " + Instant.now() );

    // This task, when run, will wait several seconds, then report the flag. Meanwhile, code below waits a shorter time before *changing* the flag.
    Runnable task2 = ( ) -> {
        try { Thread.sleep( Duration.ofSeconds( 10 ) ); } catch ( InterruptedException e ) { e.printStackTrace(); }
        System.out.println( "Second task reporting flag = " + flag.get() + ". " + Instant.now() );
    };

    executorService.submit( task1 );
    executorService.submit( task2 );

    // Wait for first task to complete, so sleep here briefly. But wake before the sleeping second task awakens.
    try { Thread.sleep( Duration.ofSeconds( 5 ) ); } catch ( InterruptedException e ) { e.printStackTrace(); }
    System.out.println( "INFO - Original thread waking up, and setting flag to false. " + Instant.now() );
    flag.set( false );
}
// At this point, with Project Loom technology, the flow-of-control blocks until the submitted tasks are done.
// Also, the `ExecutorService` is automatically closed/shutdown by this point, via try-with-resources syntax.
System.out.println( "INFO - Tasks on background threads are done. The `AtomicBoolean` and threads are gone." + Instant.now() );

Methods such as AtomicBoolean#get and AtomicBoolean#set are built to be thread-safe, to internally protect access to the boolean value nested within. Read up on the various other methods as well.

When run:

First task reporting flag = true. 2021-01-05T06:42:17.367337Z
INFO - Original thread waking up, and setting flag to false. 2021-01-05T06:42:22.367456Z
Second task reporting flag = false. 2021-01-05T06:42:27.369782Z
INFO - Tasks on background threads are done. The `AtomicBoolean` and threads are gone.2021-01-05T06:42:27.372597Z

Pro Tip: When engaging in threaded code in Java, always study the excellent book, Java Concurrency in Practice by Brian Goetz et al.

make script execution to unlimited

Your script could be stopping, not because of the PHP timeout but because of the timeout in the browser you're using to access the script (ie. Firefox, Chrome, etc). Unfortunately there's seldom an easy way to extend this timeout, and in most browsers you simply can't. An option you have here is to access the script over a terminal. For example, on Windows you would make sure the PHP executable is in your path variable and then I think you execute:

C:\path\to\script> php script.php

Or, if you're using the PHP CGI, I think it's:

C:\path\to\script> php-cgi script.php

Plus, you would also set ini_set('max_execution_time', 0); in your script as others have mentioned. When running a PHP script this way, I'm pretty sure you can use buffer flushing to echo out the script's progress to the terminal periodically if you wish. The biggest issue I think with this method is there's really no way of stopping the script once it's started, other than stopping the entire PHP process or service.

Dart/Flutter : Converting timestamp

I tested this one and it works

// Map from firestore
// Using flutterfire package hence the returned data()
Map<String, dynamic> data = documentSnapshot.data();
DateTime _timestamp = data['timestamp'].toDate();

Test details can be found here: https://www.youtube.com/watch?v=W_X8J7uBPNw&feature=youtu.be

How do I subtract minutes from a date in javascript?

This is what I did: see on Codepen

var somedate = 1473888180593;
var myStartDate;
//var myStartDate = somedate - durationInMuntes;

myStartDate = new Date(dateAfterSubtracted('minutes', 100));

alert("The event will start on " + myStartDate.toDateString() + " at " + myStartDate.toTimeString());

function dateAfterSubtracted(range, amount){
    var now = new Date();
    if(range === 'years'){
        return now.setDate(now.getYear() - amount);
    }
    if(range === 'months'){
        return now.setDate(now.getMonth() - amount);
    }
    if(range === 'days'){
        return now.setDate(now.getDate() - amount);
    }
    if(range === 'hours'){
        return now.setDate(now.getHours() - amount);
    }
    if(range === 'minutes'){
        return now.setDate(now.getMinutes() - amount);
    }
    else {
        return null;
    }
}

SQL Server stored procedure parameters

CREATE PROCEDURE GetTaskEvents
@TaskName varchar(50),
@Id INT
AS
BEGIN
-- SP Logic
END

Procedure Calling

DECLARE @return_value nvarchar(50)

EXEC  @return_value = GetTaskEvents
        @TaskName = 'TaskName',
        @Id =2  

SELECT  'Return Value' = @return_value

How to check if a radiobutton is checked in a radiogroup in Android?

My answer is according to the documentation, which works fine.

1) In xml file include android:onClick="onRadioButtonClicked" as shown below:

<RadioGroup
android:id="@+id/rg1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center">
<RadioButton
    android:id="@+id/b1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="onCreateOptionsMenu()"
    android:onClick="onRadioButtonClicked"
            />
<RadioButton
    android:id="@+id/b2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="onCreateMenu()"
    android:onClick="onRadioButtonClicked"
            />
</RadioGroup>

2) In Java file implement onRadioButtonClicked method outside onCreate() method as shown below:

public void onRadioButtonClicked(View view) {
    // Is the button now checked?
    boolean checked = ((RadioButton) view).isChecked();

    // Check which radio button was clicked
    switch(view.getId()) {
        case R.id.b1:
            if (checked)
            {
                Log.e("b1", "b1" );
                break;
            }
        case R.id.b2:
            if (checked)
                break;
    }
}

Jquery UI datepicker. Disable array of Dates

$('input').datepicker({
   beforeShowDay: function(date){
       var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
       return [ array.indexOf(string) == -1 ]
   }
});

Could not read JSON: Can not deserialize instance of hello.Country[] out of START_OBJECT token

You need to do the following:

public class CountryInfoResponse {

   @JsonProperty("geonames")
   private List<Country> countries; 

   //getter - setter
}

RestTemplate restTemplate = new RestTemplate();
List<Country> countries = restTemplate.getForObject("http://api.geonames.org/countryInfoJSON?username=volodiaL",CountryInfoResponse.class).getCountries();

It would be great if you could use some kind of annotation to allow you to skip levels, but it's not yet possible (see this and this)

calling parent class method from child class object in java

Use the keyword super within the overridden method in the child class to use the parent class method. You can only use the keyword within the overridden method though. The example below will help.

public class Parent {
    public int add(int m, int n){
        return m+n;
    }
}


public class Child extends Parent{
    public int add(int m,int n,int o){
        return super.add(super.add(m, n),0);
    }

}


public class SimpleInheritanceTest {
    public static void main(String[] a){
        Child child = new Child();
        child.add(10, 11);
    }
}

The add method in the Child class calls super.add to reuse the addition logic.

Is mongodb running?

I know this is for php, but I got here looking for a solution for node. Using mongoskin:

mongodb.admin().ping(function(err) {
    if(err === null)
        // true - you got a conntion, congratulations
    else if(err.message.indexOf('failed to connect') !== -1)
        // false - database isn't around
    else
        // actual error, do something about it
})

With other drivers, you can attempt to make a connection and if it fails, you know the mongo server's down. Mongoskin needs to actually make some call (like ping) because it connects lazily. For php, you can use the try-to-connect method. Make a script!

PHP:

$dbIsRunning = true
try {
  $m = new MongoClient('localhost:27017');
} catch($e) {
  $dbIsRunning = false
}

How to get a list of sub-folders and their files, ordered by folder-names

Command to put list of all files and folders into a text file is as below:

Eg: dir /b /s | sort > ListOfFilesFolders.txt

How do I select a random value from an enumeration?

Personally, I'm a fan of extension methods, so I would use something like this (while not really an extension, it looks similar):

public enum Options {
    Zero,
    One,
    Two,
    Three,
    Four,
    Five
}

public static class RandomEnum {
    private static Random _Random = new Random(Environment.TickCount);

    public static T Of<T>() {
        if (!typeof(T).IsEnum)
            throw new InvalidOperationException("Must use Enum type");

        Array enumValues = Enum.GetValues(typeof(T));
        return (T)enumValues.GetValue(_Random.Next(enumValues.Length));
    }
}

[TestClass]
public class RandomTests {
    [TestMethod]
    public void TestMethod1() {
        Options option;
        for (int i = 0; i < 10; ++i) {
            option = RandomEnum.Of<Options>();
            Console.WriteLine(option);
        }
    }

}

How to use HTML to print header and footer on every printed page of a document?

Is this something you want to print-only? You could add it to every page on your site and use CSS to define the tag as a print-only media.

As an example, this could be an example header:

<span class="printspan">UNCLASSIFIED</span>

And in your CSS, do something like this:

<style type="text/css" media="screen">
    .printspan
    {
        display: none;
    }
</style>
<style type="text/css" media="print">
    .printspan
    {
        display: inline;
        font-family: Arial, sans-serif;
        font-size: 16 pt;
        color: red;
    }
</style>

Finally, to include the header/footer on every page you might use server-side includes or if you have any pages being generated with PHP or ASP you could simply code it in to a common file.

Edit:

This answer is intended to provide a way to show something on the physical printed version of a document while not showing it otherwise. However just as comments suggest, it doesn't solve the issue of having a footer on multiple printed pages when content overflows.

I'm leaving it here in case it's helpful nevertheless.

How to download an entire directory and subdirectories using wget?

You can use this in a shell:

wget -r -nH --cut-dirs=7 --reject="index.html*" \
      http://abc.tamu.edu/projects/tzivi/repository/revisions/2/raw/tzivi/

The Parameters are:

-r recursively download

-nH (--no-host-directories) cuts out hostname 

--cut-dirs=X (cuts out X directories)

RegEx for matching UK Postcodes

^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$

Regular expression to match valid UK postcodes. In the UK postal system not all letters are used in all positions (the same with vehicle registration plates) and there are various rules to govern this. This regex takes into account those rules. Details of the rules: First half of postcode Valid formats [A-Z][A-Z][0-9][A-Z] [A-Z][A-Z][0-9][0-9] [A-Z][0-9][0-9] [A-Z][A-Z][0-9] [A-Z][A-Z][A-Z] [A-Z][0-9][A-Z] [A-Z][0-9] Exceptions Position - First. Contraint - QVX not used Position - Second. Contraint - IJZ not used except in GIR 0AA Position - Third. Constraint - AEHMNPRTVXY only used Position - Forth. Contraint - ABEHMNPRVWXY Second half of postcode Valid formats [0-9][A-Z][A-Z] Exceptions Position - Second and Third. Contraint - CIKMOV not used

http://regexlib.com/REDetails.aspx?regexp_id=260

Select subset of columns in data.table R

If it's not mandatory to specify column names:

> cor(dt[, !c(1:3, 5)])
             V4          V6          V7         V8          V9         V10
V4   1.00000000 -0.50472635 -0.07123705  0.9089868 -0.17232607 -0.77988709
V6  -0.50472635  1.00000000  0.05757776 -0.2374420  0.67334474  0.29476983
V7  -0.07123705  0.05757776  1.00000000 -0.1812176 -0.36093750  0.01102428
V8   0.90898683 -0.23744196 -0.18121755  1.0000000  0.21372140 -0.75798418
V9  -0.17232607  0.67334474 -0.36093750  0.2137214  1.00000000 -0.01179544
V10 -0.77988709  0.29476983  0.01102428 -0.7579842 -0.01179544  1.00000000

What's the most efficient way to check if a record exists in Oracle?

What is the underlying logic you want to implement? If, for instance, you want to test for the existence of a record to determine to insert or update then a better choice would be to use MERGE instead.

If you expect the record to exist most of the time, this is probably the most efficient way of doing things (although the CASE WHEN EXISTS solution is likely to be just as efficient):

begin
    select null into dummy
    from sales
    where sales_type = 'Accessories'
    and rownum = 1;

    --  do things here when record exists
    ....        

exception
    when no_data_found then
        -- do things here when record doesn't exists
        .....
end;

You only need the ROWNUM line if SALES_TYPE is not unique. There's no point in doing a count when all you want to know is whether at least one record exists.

How should I choose an authentication library for CodeIgniter?

Also take a look at BackendPro

Ultimately you will probably end up writing something custom, but there's nothing wrong with borrowing concepts from DX Auth, Freak Auth, BackendPro, etc.

My experiences with the packaged apps is they are specific to certain structures and I have had problems integrating them into my own applications without requiring hacks, then if the pre-package has an update, I have to migrate them in.

I also use Smarty and ADOdb in my CI code, so no matter what I would always end up making major code changes.

invalid target release: 1.7

In IntelliJ IDEA this happened to me when I imported a project that had been working fine and running with Java 1.7. I apparently hadn't notified IntelliJ that java 1.7 had been installed on my machine, and it wasn't finding my $JAVA_HOME.

On a Mac, this is resolved by:

Right clicking on the module | Module Settings | Project

and adding the 1.7 SDK by selecting "New" in the Project SDK.

Then go to the main IntelliJ IDEA menu | Preferences | Maven | Runner

and select the correct JRE. In my case it updated correctly Use Project SDK, which was now 1.7.

Customize list item bullets using CSS

Depending on the level of IE support needed, you could also use the :before selector with the bullet style set as the content property.

li {  
  list-style-type: none;
  font-size: small;
}

li:before {
  content: '\2022';
  font-size: x-large;
}

You may have to look up the HTML ASCII for the bullet style you want and use a converter for CSS Hex value.

Get error message if ModelState.IsValid fails?

publicIHttpActionResultPost(Productproduct) {  
    if (ModelState.IsValid) {  
        //Dosomethingwiththeproduct(notshown).  
        returnOk();  
    } else {  
        returnBadRequest();  
    }  
}

OR

public HttpResponseMessage Post(Product product)
        {
            if (ModelState.IsValid)
            {
                // Do something with the product (not shown).

                return new HttpResponseMessage(HttpStatusCode.OK);
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
        }

Run CRON job everyday at specific time

Cron utility is an effective way to schedule a routine background job at a specific time and/or day on an on-going basis.

Linux Crontab Format

MIN HOUR DOM MON DOW CMD

enter image description here

Example::Scheduling a Job For a Specific Time

The basic usage of cron is to execute a job in a specific time as shown below. This will execute the Full backup shell script (full-backup) on 10th June 08:30 AM.

Please note that the time field uses 24 hours format. So, for 8 AM use 8, and for 8 PM use 20.

30 08 10 06 * /home/yourname/full-backup
  • 30 – 30th Minute
  • 08 – 08 AM
  • 10 – 10th Day
  • 06 – 6th Month (June)
  • *– Every day of the week

In your case, for 2.30PM,

30 14 * * * YOURCMD
  1. 30 – 30th Minute
  2. 14 – 2PM
  3. *– Every day
  4. *– Every month
  5. *– Every day of the week

To know more about cron, visit this website.

How to edit HTML input value colour?

Add a style = color:black !important; in your input type.

Change button text from Xcode?

myapp.h

{
UIButton *myButton;
}
@property (nonatomic,retain)IBoutlet UIButton *myButton;

myapp.m

@synthesize myButton;

-(IBAction)buttonTitle{
[myButton setTitle:@"Play" forState:UIControlStateNormal];
}

How to encode a URL in Swift

Updated for Swift 3:

var escapedAddress = address.addingPercentEncoding(
    withAllowedCharacters: CharacterSet.urlQueryAllowed)

How do I load external fonts into an HTML document?

Regarding Jay Stevens answer: "The fonts available to use in an HTML file have to be present on the user's machine and accessible from the web browser, so unless you want to distribute the fonts to the user's machine via a separate external process, it can't be done." That's true.

But there is another way using javascript / canvas / flash - very good solution gives cufon: http://cufon.shoqolate.com/generate/ library that generates a very easy to use external fonts methods.

How do I update the GUI from another thread?

Basically the way to resolve this issue regardless of the framework version or the GUI underlying library type is to save the control creating the thread's Synchronization context for the worker thread that will marshal the control's related interaction from the worker thread to the GUI's thread messages queue.

Example:

SynchronizationContext ctx = SynchronizationContext.Current; // From control
ctx.Send\Post... // From worker thread

Android: How to handle right to left swipe gestures

If you also need to process click events here some modifications:

public class OnSwipeTouchListener implements OnTouchListener {

    private final GestureDetector gestureDetector = new GestureDetector(new GestureListener());

    public boolean onTouch(final View v, final MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }

    private final class GestureListener extends SimpleOnGestureListener {

        private static final int SWIPE_THRESHOLD = 100;
        private static final int SWIPE_VELOCITY_THRESHOLD = 100;


        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            boolean result = false;
            try {
                float diffY = e2.getY() - e1.getY();
                float diffX = e2.getX() - e1.getX();
                if (Math.abs(diffX) > Math.abs(diffY)) {
                    if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffX > 0) {
                            result = onSwipeRight();
                        } else {
                            result = onSwipeLeft();
                        }
                    }
                } else {
                    if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffY > 0) {
                            result = onSwipeBottom();
                        } else {
                            result = onSwipeTop();
                        }
                    }
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
            return result;
        }
    }

    public boolean onSwipeRight() {
        return false;
    }

    public boolean onSwipeLeft() {
        return false;
    }

    public boolean onSwipeTop() {
        return false;
    }

    public boolean onSwipeBottom() {
        return false;
    }
}

And sample usage:

    background.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            toggleSomething();
        }
    });
    background.setOnTouchListener(new OnSwipeTouchListener() {
        public boolean onSwipeTop() {
            Toast.makeText(MainActivity.this, "top", Toast.LENGTH_SHORT).show();
            return true;
        }
        public boolean onSwipeRight() {
            Toast.makeText(MainActivity.this, "right", Toast.LENGTH_SHORT).show();
            return true;
        }
        public boolean onSwipeLeft() {
            Toast.makeText(MainActivity.this, "left", Toast.LENGTH_SHORT).show();
            return true;
        }
        public boolean onSwipeBottom() {
            Toast.makeText(MainActivity.this, "bottom", Toast.LENGTH_SHORT).show();
            return true;
        }
    });

How to convert 2D float numpy array to 2D int numpy array?

Use the astype method.

>>> x = np.array([[1.0, 2.3], [1.3, 2.9]])
>>> x
array([[ 1. ,  2.3],
       [ 1.3,  2.9]])
>>> x.astype(int)
array([[1, 2],
       [1, 2]])

Unable to generate an explicit migration in entity framework

This error can also mean that the migrations are not recognized anymore. This happened to me after having changed the value of the ContextKey in Migrations.Configuration. The solution was simply to update the ContextKey in the database table "__MigrationHistory" (or revert the value in the Configuration class I guess). The ContextKey and the Namespace in your application should match.

Reading and displaying data from a .txt file

I love this piece of code, use it to load a file into one String:

File file = new File("/my/location");
String contents = new Scanner(file).useDelimiter("\\Z").next();

Default keystore file does not exist?

In macOS, open the Terminal and type below command

~/.android

It will navigate to the folder that containing Keystore file (You can confirm it with 'ls' command)

In my case, there is a file named 'debug.keystore'. Then type below command in the terminal from the ~/.android directory.

keytool -list -v -keystore debug.keystore

You will get the expected output.

PHP function to get the subdomain of a URL

if you are using drupal 7

this will help you:

global $base_path;
global $base_root;  
$fulldomain = parse_url($base_root);    
$splitdomain = explode(".", $fulldomain['host']);
$subdomain = $splitdomain[0];

How To Raise Property Changed events on a Dependency Property?

I ran into a similar problem where I have a dependency property that I wanted the class to listen to change events to grab related data from a service.

public static readonly DependencyProperty CustomerProperty = 
    DependencyProperty.Register("Customer", typeof(Customer),
        typeof(CustomerDetailView),
        new PropertyMetadata(OnCustomerChangedCallBack));

public Customer Customer {
    get { return (Customer)GetValue(CustomerProperty); }
    set { SetValue(CustomerProperty, value); }
}

private static void OnCustomerChangedCallBack(
        DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
    CustomerDetailView c = sender as CustomerDetailView;
    if (c != null) {
        c.OnCustomerChanged();
    }
}

protected virtual void OnCustomerChanged() {
    // Grab related data.
    // Raises INotifyPropertyChanged.PropertyChanged
    OnPropertyChanged("Customer");
}

how to use getSharedPreferences in android

//Set Preference
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor;  
prefsEditor = myPrefs.edit();  
//strVersionName->Any value to be stored  
prefsEditor.putString("STOREDVALUE", strVersionName);  
prefsEditor.commit();

//Get Preferenece  
SharedPreferences myPrefs;    
myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);  
String StoredValue=myPrefs.getString("STOREDVALUE", "");

Try this..

How do I compare two DateTime objects in PHP 5.2.8?

This may help you.

$today = date("m-d-Y H:i:s");
$thisMonth =date("m");
$thisYear = date("y");
$expectedDate = ($thisMonth+1)."-08-$thisYear 23:58:00";


if (strtotime($expectedDate) > strtotime($today)) {
    echo "Expected date is greater then current date";
    return ;
} else
{
 echo "Expected date is lesser then current date";
}

How to get last 7 days data from current datetime to last 7 days in sql server

DATEADD and GETDATE functions might not work in MySQL database. so if you are working with MySQL database, then the following command may help you.

select id, NewsHeadline as news_headline,    
NewsText as news_text,    
state, CreatedDate as created_on    
from News    
WHERE CreatedDate>= DATE_ADD(CURDATE(), INTERVAL -3 DAY);

I hope it will help you

Multi-key dictionary in c#?

Tuples will be (are) in .Net 4.0 Until then, you can also use a

 Dictionary<key1, Dictionary<key2, TypeObject>> 

or, creating a custom collection class to represent this...

 public class TwoKeyDictionary<K1, K2, T>: 
        Dictionary<K1, Dictionary<K2, T>> { }

or, with three keys...

public class ThreeKeyDictionary<K1, K2, K3, T> :
    Dictionary<K1, Dictionary<K2, Dictionary<K3, T>>> { }

The type arguments for method cannot be inferred from the usage

I wanted to make a simple and understandable example

if you call a method like this, your client will not know return type

var interestPoints = Mediator.Handle(new InterestPointTypeRequest
            {
                LanguageCode = request.LanguageCode,
                AgentId = request.AgentId,
                InterestPointId = request.InterestPointId,
            });

Then you should say to compiler i know the return type is List<InterestPointTypeMap>

var interestPoints  = Mediator.Handle<List<InterestPointTypeMap>>(new InterestPointTypeRequest
            {
                LanguageCode = request.LanguageCode,
                AgentId = request.AgentId,
                InterestPointId = request.InterestPointId,
                InterestPointTypeId = request.InterestPointTypeId
            });

the compiler will no longer be mad at you for knowing the return type

#1062 - Duplicate entry for key 'PRIMARY'

I solved it by changing the "lock" property from "shared" to "exclusive":

ALTER TABLE `table` 
CHANGE COLUMN `ID` `ID` INT(11) NOT NULL AUTO_INCREMENT COMMENT '' , LOCK = EXCLUSIVE;

How to create a fixed sidebar layout with Bootstrap 4?

My version:

div#dashmain { margin-left:150px; }
div#dashside {position:fixed; width:150px; height:100%; }
<div id="dashside"></div>
<div id="dashmain">                        
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">Content</div>
        </div>            
    </div>        
</div>

sorting a vector of structs

As others have mentioned, you could use a comparison function, but you can also overload the < operator and the default less<T> functor will work as well:

struct data {
    string word;
    int number;
    bool operator < (const data& rhs) const {
        return word.size() < rhs.word.size();
    }
};

Then it's just:

std::sort(info.begin(), info.end());

Edit

As James McNellis pointed out, sort does not actually use the less<T> functor by default. However, the rest of the statement that the less<T> functor will work as well is still correct, which means that if you wanted to put struct datas into a std::map or std::set this would still work, but the other answers which provide a comparison function would need additional code to work with either.

Selecting data from two different servers in SQL Server

Server 2008:

When in SSMS connected to server1.DB1 and try:

SELECT  * FROM
[server2].[DB2].[dbo].[table1]

as others noted, if it doesn't work it's because the server isn't linked.

I get the error:

Could not find server DB2 in sys.servers. Verify that the correct server name was specified. If necessary, execute stored procedure sp_addlinkedserver to add the server to sys.servers.

To add the server:

reference: To add server using sp_addlinkedserver Link: [1]: To add server using sp_addlinkedserver

To see what is in your sys.servers just query it:

SELECT * FROM [sys].[servers]

How to call base.base.method()?

As can be seen from previous posts, one can argue that if class functionality needs to be circumvented then something is wrong in the class architecture. That might be true, but one cannot always restructure or refactor the class structure on a large mature project. The various levels of change management might be one problem, but to keep existing functionality operating the same after refactoring is not always a trivial task, especially if time constraints apply. On a mature project it can be quite an undertaking to keep various regression tests from passing after a code restructure; there are often obscure "oddities" that show up. We had a similar problem in some cases inherited functionality should not execute (or should perform something else). The approach we followed below, was to put the base code that need to be excluded in a separate virtual function. This function can then be overridden in the derived class and the functionality excluded or altered. In this example "Text 2" can be prevented from output in the derived class.

public class Base
{
    public virtual void Foo()
    {
        Console.WriteLine("Hello from Base");
    }
}

public class Derived : Base
{
    public override void Foo()
    {
        base.Foo();
        Console.WriteLine("Text 1");
        WriteText2Func();
        Console.WriteLine("Text 3");
    }

    protected virtual void WriteText2Func()
    {  
        Console.WriteLine("Text 2");  
    }
}

public class Special : Derived
{
    public override void WriteText2Func()
    {
        //WriteText2Func will write nothing when 
        //method Foo is called from class Special.
        //Also it can be modified to do something else.
    }
}

WooCommerce return product object by id

global $woocommerce;
var_dump($woocommerce->customer->get_country());
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
    $product = new WC_product($cart_item['product_id']);
    var_dump($product);
}

How do I keep a label centered in WinForms?

Some minor additional content for setting programmatically:

Label textLabel = new Label() { 
        AutoSize = false, 
        TextAlign = ContentAlignment.MiddleCenter, 
        Dock = DockStyle.None, 
        Left = 10, 
        Width = myDialog.Width - 10
};            

Dockstyle and Content alignment may differ from your needs. For example, for a simple label on a wpf form I use DockStyle.None.

.NET console application as Windows service

You can use

reg add HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run /v ServiceName /d "c:\path\to\service\file\exe"

And it will appear int the service list. I do not know, whether that works correctly though. A service usually has to listen to several events.

There are several service wrapper though, that can run any application as a real service. For Example Microsofts SrvAny from the Win2003 Resource Kit

Powershell: Get FQDN Hostname

A cleaner format FQDN remotely

[System.Net.Dns]::GetHostByName('remotehost').HostName

Windows equivalent of OS X Keychain?

It is year 2018, and Windows 10 has a "Credential Manager" that can be found in "Control Panel"

Check if array is empty or null

You should check for '' (empty string) before pushing into your array. Your array has elements that are empty strings. Then your album_text.length === 0 will work just fine.

jquery - check length of input field?

That doesn't work because, judging by the rest of the code, the initial value of the text input is "Default text" - which is more than one character, and so your if condition is always true.

The simplest way to make it work, it seems to me, is to account for this case:

    var value = $(this).val();
    if ( value.length > 0 && value != "Default text" ) ...

Flexbox Not Centering Vertically in IE

Just in case someone gets here with the same issue I had, which is not specifically addressed in previous comments.

I had margin: auto on the inner element which caused it to stick to the bottom of it's parent (or the outer element). What fixed it for me was changing the margin to margin: 0 auto;.

Inserting image into IPython notebook markdown

You can find your current working directory by 'pwd' command in jupyter notebook without quotes.

Using jQuery to see if a div has a child with a certain class

Use the children funcion of jQuery.

$("#text-field").keydown(function(event) {
    if($('#popup').children('p.filled-text').length > 0) {
        console.log("Found");
     }
});

$.children('').length will return the count of child elements which match the selector.

Getting the last element of a list

To prevent IndexError: list index out of range, use this syntax:

mylist = [1, 2, 3, 4]

# With None as default value:
value = mylist and mylist[-1]

# With specified default value (option 1):
value = mylist and mylist[-1] or 'default'

# With specified default value (option 2):
value = mylist[-1] if mylist else 'default'

How to print a int64_t type in C

The C99 way is

#include <inttypes.h>
int64_t my_int = 999999999999999999;
printf("%" PRId64 "\n", my_int);

Or you could cast!

printf("%ld", (long)my_int);
printf("%lld", (long long)my_int); /* C89 didn't define `long long` */
printf("%f", (double)my_int);

If you're stuck with a C89 implementation (notably Visual Studio) you can perhaps use an open source <inttypes.h> (and <stdint.h>): http://code.google.com/p/msinttypes/

How can I write a heredoc to a file in Bash script?

Note:

The question (how to write a here document (aka heredoc) to a file in a bash script?) has (at least) 3 main independent dimensions or subquestions:

  1. Do you want to overwrite an existing file, append to an existing file, or write to a new file?
  2. Does your user or another user (e.g., root) own the file?
  3. Do you want to write the contents of your heredoc literally, or to have bash interpret variable references inside your heredoc?

(There are other dimensions/subquestions which I don't consider important. Consider editing this answer to add them!) Here are some of the more important combinations of the dimensions of the question listed above, with various different delimiting identifiers--there's nothing sacred about EOF, just make sure that the string you use as your delimiting identifier does not occur inside your heredoc:

  1. To overwrite an existing file (or write to a new file) that you own, substituting variable references inside the heredoc:

    cat << EOF > /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, with the variable contents substituted.
    EOF
    
  2. To append an existing file (or write to a new file) that you own, substituting variable references inside the heredoc:

    cat << FOE >> /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, with the variable contents substituted.
    FOE
    
  3. To overwrite an existing file (or write to a new file) that you own, with the literal contents of the heredoc:

    cat << 'END_OF_FILE' > /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, without the variable contents substituted.
    END_OF_FILE
    
  4. To append an existing file (or write to a new file) that you own, with the literal contents of the heredoc:

    cat << 'eof' >> /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, without the variable contents substituted.
    eof
    
  5. To overwrite an existing file (or write to a new file) owned by root, substituting variable references inside the heredoc:

    cat << until_it_ends | sudo tee /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, with the variable contents substituted.
    until_it_ends
    
  6. To append an existing file (or write to a new file) owned by user=foo, with the literal contents of the heredoc:

    cat << 'Screw_you_Foo' | sudo -u foo tee -a /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, without the variable contents substituted.
    Screw_you_Foo
    

Variables not showing while debugging in Eclipse

Window --> Show View --> Variables

Download files from SFTP with SSH.NET library

Without you providing any specific error message, it's hard to give specific suggestions.

However, I was using the same example and was getting a permissions exception on File.OpenWrite - using the localFileName variable, because using Path.GetFile was pointing to a location that obviously would not have permissions for opening a file > C:\ProgramFiles\IIS(Express)\filename.doc

I found that using System.IO.Path.GetFileName is not correct, use System.IO.Path.GetFullPath instead, point to your file starting with "C:\..."

Also open your solution in FileExplorer and grant permissions to asp.net for the file or any folders holding the file. I was able to download my file at that point.

PHP Excel Header

You are giving multiple Content-Type headers. application/vnd.ms-excel is enough.

And there are couple of syntax error too. To statement termination with ; on the echo statement and wrong filename extension.

header("Content-Type:   application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=abc.xls");  //File name extension was wrong
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
echo "Some Text"; //no ending ; here

Dropping Unique constraint from MySQL table

my table name is buyers which has a unique constraint column emp_id now iam going to drop the emp_id

step 1: exec sp_helpindex buyers, see the image file

step 2: copy the index address

enter image description here

step3: alter table buyers drop constraint [UQ__buyers__1299A860D9793F2E] alter table buyers drop column emp_id

note:

Blockquote

instead of buyers change it to your table name :)

Blockquote

thats all column name emp_id with constraints is dropped!

Can't run Curl command inside my Docker Container

This is happening because there is no package cache in the image, you need to run:

apt-get -qq update

before installing packages, and if your command is in a Dockerfile, you'll then need:

apt-get -qq -y install curl

After that install ZSH and GIT Core:

apt-get install zsh
apt-get install git-core

Getting zsh to work in ubuntu is weird since sh does not understand the source command. So, you do this to install zsh:

wget https://github.com/robbyrussell/oh-my-zsh/raw/master/tools/install.sh -O - | zsh

and then you change your shell to zsh:

chsh -s `which zsh`

and then restart:

sudo shutdown -r 0

This problem is explained in depth in this issue.

Visual Studio Code Automatic Imports

I am using 'ImportJS' plugin by Devin Abbott for auto import and you can install this using below code

npm install --global import-js

ImportError: No module named _ssl

Did you build the Python from source? If so, you need the --with-ssl option while building.

Printing Python version in output

Try

import sys
print(sys.version)

This prints the full version information string. If you only want the python version number, then Bastien Léonard's solution is the best. You might want to examine the full string and see if you need it or portions of it.

convert date string to mysql datetime field

If these strings are currently in the db, you can skip php by using mysql's STR_TO_DATE() function.

I assume the strings use a format like month/day/year where month and day are always 2 digits, and year is 4 digits.

UPDATE some_table
   SET new_column = STR_TO_DATE(old_column, '%m/%d/%Y')

You can support other date formats by using other format specifiers.

What is the best open XML parser for C++?

Do not use TinyXML if you're concerned about efficiency/memory management (it tends to allocate lots of tiny blocks). My personal favourite is RapidXML.

How to quickly edit values in table in SQL Server Management Studio?

Go to Tools > Options. In the tree on the left, select SQL Server Object Explorer. Set the option "Value for Edit Top Rows command" to 0. It'll now allow you to view and edit the entire table from the context menu.

How do I escape double quotes in attributes in an XML String in T-SQL?

tSql escapes a double quote with another double quote. So if you wanted it to be part of your sql string literal you would do this:

declare @xml xml 
set @xml = "<transaction><item value=""hi"" /></transaction>"

If you want to include a quote inside a value in the xml itself, you use an entity, which would look like this:

declare @xml xml
set @xml = "<transaction><item value=""hi &quot;mom&quot; lol"" /></transaction>"

Custom HTTP Authorization Header

The format defined in RFC2617 is credentials = auth-scheme #auth-param. So, in agreeing with fumanchu, I think the corrected authorization scheme would look like

Authorization: FIRE-TOKEN apikey="0PN5J17HBGZHT7JJ3X82", hash="frJIUN8DYpKDtOLCwo//yllqDzg="

Where FIRE-TOKEN is the scheme and the two key-value pairs are the auth parameters. Though I believe the quotes are optional (from Apendix B of p7-auth-19)...

auth-param = token BWS "=" BWS ( token / quoted-string )

I believe this fits the latest standards, is already in use (see below), and provides a key-value format for simple extension (if you need additional parameters).

Some examples of this auth-param syntax can be seen here...

http://tools.ietf.org/html/draft-ietf-httpbis-p7-auth-19#section-4.4

https://developers.google.com/youtube/2.0/developers_guide_protocol_clientlogin

https://developers.google.com/accounts/docs/AuthSub#WorkingAuthSub

Conversion failed when converting the varchar value to data type int in sql

Try this one -

CREATE PROC [dbo].[getVoucherNo]
AS BEGIN

     DECLARE 
            @Prefix VARCHAR(10) = 'J'
          , @startFrom INT = 1
          , @maxCode VARCHAR(100)
          , @sCode INT

     IF EXISTS(
          SELECT 1 
          FROM dbo.Journal_Entry
     ) BEGIN

          SELECT @maxCode = CAST(MAX(CAST(SUBSTRING(Voucher_No,LEN(@startFrom)+1,ABS(LEN(Voucher_No)- LEN(@Prefix))) AS INT)) AS varchar(100)) 
          FROM dbo.Journal_Entry;

          SELECT @Prefix + 
               CAST(LEN(LEFT(@maxCode, 10) + 1) AS VARCHAR(10)) + -- !!! possible problem here
               CAST(@maxCode AS VARCHAR(100))

     END
     ELSE BEGIN

          SELECT (@Prefix + CAST(@startFrom AS VARCHAR)) 

     END

END

Using partial views in ASP.net MVC 4

Change the code where you load the partial view to:

@Html.Partial("_CreateNote", new QuickNotes.Models.Note())

This is because the partial view is expecting a Note but is getting passed the model of the parent view which is the IEnumerable

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved

I had same issue while creating new spring project in eclipse using Maven.

The main reason for this issue is that the proxy settings was not there.

I used the following approach to reslove it:
1) create settings.xml with  the below content
    <settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                          https://maven.apache.org/xsd/settings-1.0.0.xsd">
      <localRepository/>
      <interactiveMode/>
      <usePluginRegistry/>
      <offline/>
      <pluginGroups/>
      <servers/>
      <mirrors/>
      <proxies>
        <proxy>
            <active>true</active>
            <protocol>http</protocol>
            <host>Your proxy</host>
            <port>Your port</port>
        </proxy>
      </proxies>
      <profiles/>
      <activeProfiles/>
    </settings>
2) Save the settings.xml file under local C:\Users\<<your user account>>\.m2
3) Then Right click project pom.XML in eclipse and select "Update Project". It always give precedence to settings.XML

Can I set max_retries for requests.request?

It is the underlying urllib3 library that does the retrying. To set a different maximum retry count, use alternative transport adapters:

from requests.adapters import HTTPAdapter

s = requests.Session()
s.mount('http://stackoverflow.com', HTTPAdapter(max_retries=5))

The max_retries argument takes an integer or a Retry() object; the latter gives you fine-grained control over what kinds of failures are retried (an integer value is turned into a Retry() instance which only handles connection failures; errors after a connection is made are by default not handled as these could lead to side-effects).


Old answer, predating the release of requests 1.2.1:

The requests library doesn't really make this configurable, nor does it intend to (see this pull request). Currently (requests 1.1), the retries count is set to 0. If you really want to set it to a higher value, you'll have to set this globally:

import requests

requests.adapters.DEFAULT_RETRIES = 5

This constant is not documented; use it at your own peril as future releases could change how this is handled.

Update: and this did change; in version 1.2.1 the option to set the max_retries parameter on the HTTPAdapter() class was added, so that now you have to use alternative transport adapters, see above. The monkey-patch approach no longer works, unless you also patch the HTTPAdapter.__init__() defaults (very much not recommended).

Using PI in python 2.7

Python 2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.pi
3.141592653589793

Check out the Python tutorial on modules and how to use them.

As for the second part of your question, Python comes with batteries included, of course:

>>> math.radians(90)
1.5707963267948966
>>> math.radians(180)
3.141592653589793

Check If array is null or not in php

I understand what you want. You want to check every data of the array if all of it is empty or at least 1 is not empty

Empty array

Array ( [Tags] => SimpleXMLElement Object ( [0] => ) )

Not an Empty array

Array ( [Tags] => SimpleXMLElement Object ( [0] =>,[1] => "s" ) )


I hope I am right. You can use this function to check every data of an array if at least 1 of them has a value.

/*
 return true if the array is not empty
 return false if it is empty
*/
function is_array_empty($arr){
  if(is_array($arr)){     
      foreach($arr $key => $value){
          if(!empty($value) || $value != NULL || $value != ""){
              return true;
              break;//stop the process we have seen that at least 1 of the array has value so its not empty
          }
      }
      return false;
  }
}

if(is_array_empty($result['Tags'])){
    //array is not empty
}else{
    //array is empty
}

Hope that helps.

Getting a File's MD5 Checksum in Java

If you're using ANT to build, this is dead-simple. Add the following to your build.xml:

<checksum file="${jarFile}" todir="${toDir}"/>

Where jarFile is the JAR you want to generate the MD5 against, and toDir is the directory you want to place the MD5 file.

More info here.

How to get text in QlineEdit when QpushButton is pressed in a string?

The object name is not very important. what you should be focusing at is the variable that stores the lineedit object (le) and your pushbutton object(pb)

QObject(self.pb, SIGNAL("clicked()"), self.button_clicked)

def button_clicked(self):
  self.le.setText("shost")

I think this is what you want. I hope i got your question correctly :)

Why is access to the path denied?

I also ran into this post as dealing with the same issue. Looks like the file is in use and hence not able to write to it. Though not able to figure it out, which process is using it. Signed out the other user who was logged in in that box, dont see any users who is holding it. Any quick tips regarding on how to find the same.

Thanks, Lakshay (developer)

How to check task status in Celery?

for simple tasks, we can use http://flower.readthedocs.io/en/latest/screenshots.html and http://policystat.github.io/jobtastic/ to do the monitoring.

and for complicated tasks, say a task which deals with a lot other modules. We recommend manually record the progress and message on the specific task unit.

Functional style of Java 8's Optional.ifPresent and if-not-Present?

Another solution could be following:

This is how you use it:

    final Opt<String> opt = Opt.of("I'm a cool text");
    opt.ifPresent()
        .apply(s -> System.out.printf("Text is: %s\n", s))
        .elseApply(() -> System.out.println("no text available"));

Or in case you in case of the opposite use case is true:

    final Opt<String> opt = Opt.of("This is the text");
    opt.ifNotPresent()
        .apply(() -> System.out.println("Not present"))
        .elseApply(t -> /*do something here*/);

This are the ingredients:

  1. Little modified Function interface, just for the "elseApply" method
  2. Optional enhancement
  3. A little bit of curring :-)

The "cosmetically" enhanced Function interface.

@FunctionalInterface
public interface Fkt<T, R> extends Function<T, R> {

    default R elseApply(final T t) {
        return this.apply(t);
    }

}

And the Optional wrapper class for enhancement:

public class Opt<T> {

    private final Optional<T> optional;

    private Opt(final Optional<T> theOptional) {
        this.optional = theOptional;
    }

    public static <T> Opt<T> of(final T value) {
        return new Opt<>(Optional.of(value));
    }

    public static <T> Opt<T> of(final Optional<T> optional) {
        return new Opt<>(optional);
    }

    public static <T> Opt<T> ofNullable(final T value) {
        return new Opt<>(Optional.ofNullable(value));
    }

    public static <T> Opt<T> empty() {
        return new Opt<>(Optional.empty());
    }

    private final BiFunction<Consumer<T>, Runnable, Void> ifPresent = (present, notPresent) -> {
        if (this.optional.isPresent()) {
            present.accept(this.optional.get());
        } else {
            notPresent.run();
        }
        return null;
    };

   private final BiFunction<Runnable, Consumer<T>, Void> ifNotPresent = (notPresent, present) -> {
        if (!this.optional.isPresent()) {
            notPresent.run();
        } else {
            present.accept(this.optional.get());
        }
        return null;
    };

    public Fkt<Consumer<T>, Fkt<Runnable, Void>> ifPresent() {
        return Opt.curry(this.ifPresent);
    }

    public Fkt<Runnable, Fkt<Consumer<T>, Void>> ifNotPresent() {
        return Opt.curry(this.ifNotPresent);
    }

    private static <X, Y, Z> Fkt<X, Fkt<Y, Z>> curry(final BiFunction<X, Y, Z> function) {
        return (final X x) -> (final Y y) -> function.apply(x, y);
    }
}

This should do the trick and could serve as a basic template how to deal with such requirements.

The basic idea here is following. In a non functional style programming world you would probably implement a method taking two parameter where the first is a kind of runnable code which should be executed in case the value is available and the other parameter is the runnable code which should be run in case the value is not available. For the sake of better readability, you can use curring to split the function of two parameter in two functions of one parameter each. This is what I basically did here.

Hint: Opt also provides the other use case where you want to execute a piece of code just in case the value is not available. This could be done also via Optional.filter.stuff but I found this much more readable.

Hope that helps!

Good programming :-)

Device not detected in Eclipse when connected with USB cable

Here is my checklist in windows (not the device itself) when my device is not shown:

  1. Make sure "USB debugging is turned in setting>Developer options.
  2. Check status bar on your device. It tells you if your phone is connected as Media Device (MTP) or Send images (PTP). My device is only listed when PTP is selected.
  3. Turn of windows firewall.
  4. Turn of any proxy programs ran on whole windows ports.
  5. And finally stop adb.exe from windows task manager and wait some seconds to restart automatically.

Could not find method compile() for arguments Gradle

Wrong gradle file. The right one is build.gradle in your 'app' folder.

Usage of unicode() and encode() functions in Python

Make sure you've set your locale settings right before running the script from the shell, e.g.

$ locale -a | grep "^en_.\+UTF-8"
en_GB.UTF-8
en_US.UTF-8
$ export LC_ALL=en_GB.UTF-8
$ export LANG=en_GB.UTF-8

Docs: man locale, man setlocale.

Strip out HTML and Special Characters

preg_replace('/[^a-zA-Z0-9\s]/', '',$string) this is using for removing special character only rather than space between the strings.

Read text file into string array (and write)

If you don't care about loading the file into memory, as of Go 1.16, you can use the os.ReadFile and bytes.Count functions.

package main

import (
    "log"
    "os"
    "bytes"
)

func main() {
    data, err := os.ReadFile("input.txt")
    if err != nil {
        log.Fatal(err)
    }

    n := bytes.Count(data, []byte{'\n'})

    fmt.Printf("input.txt has %d lines\n", n)
}

Add borders to cells in POI generated Excel File

a Helper function:

private void setRegionBorderWithMedium(CellRangeAddress region, Sheet sheet) {
        Workbook wb = sheet.getWorkbook();
        RegionUtil.setBorderBottom(CellStyle.BORDER_MEDIUM, region, sheet, wb);
        RegionUtil.setBorderLeft(CellStyle.BORDER_MEDIUM, region, sheet, wb);
        RegionUtil.setBorderRight(CellStyle.BORDER_MEDIUM, region, sheet, wb);
        RegionUtil.setBorderTop(CellStyle.BORDER_MEDIUM, region, sheet, wb);
    }

When you want to add Border in Excel, then

String cellAddr="$A$11:$A$17";

setRegionBorderWithMedium(CellRangeAddress.valueOf(cellAddr1), sheet);

Numpy: Get random set of rows from 2D array

An alternative way of doing it is by using the choice method of the Generator class, https://github.com/numpy/numpy/issues/10835

import numpy as np

# generate the random array
A = np.random.randint(5, size=(10,3))

# use the choice method of the Generator class
rng = np.random.default_rng()
A_sampled = rng.choice(A, 2)

leading to a sampled data,

array([[1, 3, 2],
       [1, 2, 1]])

The running time is also profiled compared as follows,

%timeit rng.choice(A, 2)
15.1 µs ± 115 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit np.random.permutation(A)[:2]
4.22 µs ± 83.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit A[np.random.randint(A.shape[0], size=2), :]
10.6 µs ± 418 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

But when the array goes big, A = np.random.randint(10, size=(1000,300)). working on the index is the best way.

%timeit A[np.random.randint(A.shape[0], size=50), :]
17.6 µs ± 657 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit rng.choice(A, 50)
22.3 µs ± 134 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit np.random.permutation(A)[:50]
143 µs ± 1.33 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

So the permutation method seems to be the most efficient one when your array is small while working on the index is the optimal solution when your array goes big.

How to select last child element in jQuery?

If you want to select the last child and need to be specific on the element type you can use the selector last-of-type

Here is an example:

$("div p:last-of-type").css("border", "3px solid red");
$("div span:last-of-type").css("border", "3px solid red");

<div id="example">
            <p>This is paragraph 1</p>
            <p>This is paragraph 2</p>
            <span>This is paragraph 3</span>
            <span>This is paragraph 4</span>
            <p>This is paragraph 5</p>
        </div>

In the example above both Paragraph 4 and Paragraph 5 will have a red border since Paragraph 5 is the last element of "p" type in the div and Paragraph 4 is the last "span" in the div.

Android: How to change CheckBox size?

Here was what I did, first set:

android:button="@null"

and also set

android:drawableLeft="@drawable/selector_you_defined_for_your_checkbox"

then in your Java code:

Drawable d = mCheckBox.getCompoundDrawables()[0];
d.setBounds(0, 0, width_you_prefer, height_you_prefer);
mCheckBox.setCompoundDrawables(d, null, null, null);

It works for me, and hopefully it will work for you!

How do I detect IE 8 with jQuery?

If you fiddle with browser versions it leads to no good very often. You don't want to implement it by yourself. But you can Modernizr made by Paul Irish and other smart folks. It will detect what the browser actually can do and put apropriate classes in <html> element. However with Modernizr, you can test IE version like this:

$('html.lt-ie9').each() {
    // this will execute if browser is IE 8 or less
}

Similary, you can use .lt-ie8, and .lt-ie7.

What is the difference between UTF-8 and ISO-8859-1?

One more important thing to realise: if you see iso-8859-1, it probably refers to Windows-1252 rather than ISO/IEC 8859-1. They differ in the range 0x80–0x9F, where ISO 8859-1 has the C1 control codes, and Windows-1252 has useful visible characters instead.

For example, ISO 8859-1 has 0x85 as a control character (in Unicode, U+0085, ``), while Windows-1252 has a horizontal ellipsis (in Unicode, U+2026 HORIZONTAL ELLIPSIS, ).

The WHATWG Encoding spec (as used by HTML) expressly declares iso-8859-1 to be a label for windows-1252, and web browsers do not support ISO 8859-1 in any way: the HTML spec says that all encodings in the Encoding spec must be supported, and no more.

Also of interest, HTML numeric character references essentially use Windows-1252 for 8-bit values rather than Unicode code points; per https://html.spec.whatwg.org/#numeric-character-reference-end-state, &#x85; will produce U+2026 rather than U+0085.

How do I send an HTML email?

As per the Javadoc, the MimeMessage#setText() sets a default mime type of text/plain, while you need text/html. Rather use MimeMessage#setContent() instead.

message.setContent(someHtmlMessage, "text/html; charset=utf-8");

For additional details, see:

Is there an equivalent for var_dump (PHP) in Javascript?

console.dir (toward the bottom of the linked page) in either firebug or the google-chrome web-inspector will output an interactive listing of an object's properties.

See also this Stack-O answer

How to build a query string for a URL in C#?

While not elegant, I opted for a simpler version that doesn't use NameValueCollecitons - just a builder pattern wrapped around StringBuilder.

public class UrlBuilder
{
    #region Variables / Properties

    private readonly StringBuilder _builder;

    #endregion Variables / Properties

    #region Constructor

    public UrlBuilder(string urlBase)
    {
        _builder = new StringBuilder(urlBase);
    }

    #endregion Constructor

    #region Methods

    public UrlBuilder AppendParameter(string paramName, string value)
    {
        if (_builder.ToString().Contains("?"))
            _builder.Append("&");
        else
            _builder.Append("?");

        _builder.Append(HttpUtility.UrlEncode(paramName));
        _builder.Append("=");
        _builder.Append(HttpUtility.UrlEncode(value));

        return this;
    }

    public override string ToString()
    {
        return _builder.ToString();
    }

    #endregion Methods
}

Per existing answers, I made sure to use HttpUtility.UrlEncode calls. It's used like so:

string url = new UrlBuilder("http://www.somedomain.com/")
             .AppendParameter("a", "true")
             .AppendParameter("b", "muffin")
             .AppendParameter("c", "muffin button")
             .ToString();
// Result: http://www.somedomain.com?a=true&b=muffin&c=muffin%20button

How can I convert a std::string to int?

To convert from string representation to integer value, we can use std::stringstream.

if the value converted is out of range for integer data type, it returns INT_MIN or INT_MAX.

Also if the string value can’t be represented as an valid int data type, then 0 is returned.

#include 
#include 
#include 

int main() {

    std::string x = "50";
    int y;
    std::istringstream(x) >> y;
    std::cout << y << '\n';
    return 0;
}

Output: 50

As per the above output, we can see it converted from string numbers to integer number.

Source and more at string to int c++

Maven: mvn command not found

I tried solutions from other threads. Adding M2 and M2_HOME at System variables, and even at User variables. Running cmd as admin. None of the methods worked.

But today I added entire path to maven bin to my System variables "PATH" (C:\Program Files (x86)\Apache Software Foundation\apache-maven-3.1.0\bin) besides other paths, and so far it's working good. Hopefully it'll stay that way.

Variable name as a string in Javascript

var x = 2;
for(o in window){ 
   if(window[o] === x){
      alert(o);
   }
}

However, I think you should do like "karim79"

Call a python function from jinja2

Never saw such simple way at official docs or at stack overflow, but i was amazed when found this:

# jinja2.__version__ == 2.8
from jinja2 import Template

def calcName(n, i):
    return ' '.join([n] * i)

template = Template("Hello {{ calcName('Gandalf', 2) }}")

template.render(calcName=calcName)
# or
template.render({'calcName': calcName})

How to generate a Makefile with source in sub-directories using just one makefile

Usually, you create a Makefile in each subdirectory, and write in the top-level Makefile to call make in the subdirectories.

This page may help: http://www.gnu.org/software/make/

In-memory size of a Python structure

When you use the dir([object]) built-in function, you can get the __sizeof__ of the built-in function.

>>> a = -1
>>> a.__sizeof__()
24

cd into directory without having permission

Unless you have sudo permissions to change it or its in your own usergroup/account you will not be able to get into it.

Check out man chmod in the terminal for more information about changing permissions of a directory.

How do I share variables between different .c files?

In 99.9% of all cases it is bad program design to share non-constant, global variables between files. There are very few cases when you actually need to do this: they are so rare that I cannot come up with any valid cases. Declarations of hardware registers perhaps.

In most of the cases, you should either use (possibly inlined) setter/getter functions ("public"), static variables at file scope ("private"), or incomplete type implementations ("private") instead.

In those few rare cases when you need to share a variable between files, do like this:

// file.h
extern int my_var;

// file.c
#include "file.h"
int my_var = something;

// main.c
#include "file.h"
use(my_var);

Never put any form of variable definition in a h-file.

How to stop IIS asking authentication for default website on localhost

It could be because of couple of Browser settings. Try with these options checked..

Tools > Internet Options > Advanced > Enable Integrated Windows Authentication (works with Integrated Windows Authentication set on IIS)

Tools > Internet Options> Security > Local Intranet > Custom Level > Automatic Logon

Worst case, try adding localhost to the Trusted sites.

If you are in a network, you can also try debugging by getting a network trace. Could be because of some proxy trying to authenticate.

Log4Net configuring log level

Within the definition of the appender, I believe you can do something like this:

<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
    <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="INFO"/>
        <param name="LevelMax" value="INFO"/>
    </filter>
    ...
</appender>

What is difference between MVC, MVP & MVVM design pattern in terms of coding c#

Great Explanation from the link : http://geekswithblogs.net/dlussier/archive/2009/11/21/136454.aspx

Let's First look at MVC

The input is directed at the Controller first, not the view. That input might be coming from a user interacting with a page, but it could also be from simply entering a specific url into a browser. In either case, its a Controller that is interfaced with to kick off some functionality.

There is a many-to-one relationship between the Controller and the View. That’s because a single controller may select different views to be rendered based on the operation being executed.

There is one way arrow from Controller to View. This is because the View doesn’t have any knowledge of or reference to the controller.

The Controller does pass back the Model, so there is knowledge between the View and the expected Model being passed into it, but not the Controller serving it up.

MVP – Model View Presenter

Now let’s look at the MVP pattern. It looks very similar to MVC, except for some key distinctions:

The input begins with the View, not the Presenter.

There is a one-to-one mapping between the View and the associated Presenter.

The View holds a reference to the Presenter. The Presenter is also reacting to events being triggered from the View, so its aware of the View its associated with.

The Presenter updates the View based on the requested actions it performs on the Model, but the View is not Model aware.

MVVM – Model View View Model

So with the MVC and MVP patterns in front of us, let’s look at the MVVM pattern and see what differences it holds:

The input begins with the View, not the View Model.

While the View holds a reference to the View Model, the View Model has no information about the View. This is why its possible to have a one-to-many mapping between various Views and one View Model…even across technologies. For example, a WPF View and a Silverlight View could share the same View Model.

Convert list into a pandas data frame

You need convert list to numpy array and then reshape:

df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

What's the difference between lists and tuples?

Lists are mutable. whereas tuples are immutable. Accessing an offset element with index makes more sense in tuples than lists, Because the elements and their index cannot be changed.

How to preventDefault on anchor tags?

You can disable url redirection inside $location's Html5Mode to achieve the objective. You can define it inside the specific controller used for the page. Something like this:

_x000D_
_x000D_
app.config(['$locationProvider', function ($locationProvider) {_x000D_
    $locationProvider.html5Mode({_x000D_
        enabled: true,_x000D_
        rewriteLinks: false,_x000D_
        requireBase: false_x000D_
    });_x000D_
}]);
_x000D_
_x000D_
_x000D_

Difference between logical addresses, and physical addresses?

To the best of my memory, a physical address is an explicit, set in stone address in memory, while a logical address consists of a base pointer and offset.

The reason is as you have basically specified. It allows for not only the segmentation of programs and processes into threads and data, but also for the dynamic loading of such programs, and the allowance for at least pseudo-parallelism, without any actual interlacing of instructions in memory needing to take place.

Delete from two tables in one query

DELETE message.*, usersmessage.* from users, usersmessage WHERE message.messageid=usersmessage.messageid AND message.messageid='1'

SET NAMES utf8 in MySQL?

Not only PDO. If sql answer like '????' symbols, preset of you charset (hope UTF-8) really recommended:

if (!$mysqli->set_charset("utf8")) 
 { printf("Can't set utf8: %s\n", $mysqli->error); }

or via procedure style mysqli_set_charset($db,"utf8")

How to rotate x-axis tick labels in Pandas barplot

For bar graphs, you can include the angle which you finally want the ticks to have.

Here I am using rot=0 to make them parallel to the x axis.

series.plot.bar(rot=0)
plt.show()
plt.close()

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

EDIT: added a new example for ggplot2 at the end

See ?plotmath for the different mathematical operations in R

You should be able to use expression without paste. If you use the tilda (~) symbol within the expression function it will assume there is a space between the characters, or you could use the * symbol and it won't put a space between the arguments

Sometimes you will need to change the margins in you're putting superscripts on the y-axis.

par(mar=c(5, 4.3, 4, 2) + 0.1)
plot(1:10, xlab = expression(xLab ~ x^2 ~ m^-2),
     ylab = expression(yLab ~ y^2 ~ m^-2),
     main="Plot 1")

enter image description here

plot(1:10, xlab = expression(xLab * x^2 * m^-2),
     ylab = expression(yLab * y^2 * m^-2),
     main="Plot 2")

enter image description here

plot(1:10, xlab = expression(xLab ~ x^2 * m^-2),
     ylab = expression(yLab ~ y^2 * m^-2),
     main="Plot 3")

enter image description here

Hopefully you can see the differences between plots 1, 2 and 3 with the different uses of the ~ and * symbols. An extra note, you can use other symbols such as plotting the degree symbol for temperatures for or mu, phi. If you want to add a subscript use the square brackets.

plot(1:10, xlab = expression('Your x label' ~ mu[3] * phi),
     ylab = expression("Temperature (" * degree * C *")"))

enter image description here

Here is a ggplot example using expression with a nonsense example

require(ggplot2)

Or if you have the pacman library installed you can use p_load to automatically download and load and attach add-on packages

# require(pacman)
# p_load(ggplot2)

data = data.frame(x = 1:10, y = 1:10)

ggplot(data, aes(x,y)) + geom_point() + 
  xlab(expression(bar(yourUnits) ~ g ~ m^-2 ~ OR ~ integral(f(x)*dx, a,b))) + 
  ylab(expression("Biomass (g per" ~ m^3 *")")) + theme_bw()

enter image description here

How is using OnClickListener interface different via XML and Java code?

Even though you define android:onClick = "DoIt" in XML, you need to make sure your activity (or view context) has public method defined with exact same name and View as parameter. Android wires your definitions with this implementation in activity. At the end, implementation will have same code which you wrote in anonymous inner class. So, in simple words instead of having inner class and listener attachement in activity, you will simply have a public method with implementation code.

Suppress InsecureRequestWarning: Unverified HTTPS request is being made in Python2.6

Per this github comment, one can disable urllib3 request warnings via requests in a 1-liner:

requests.packages.urllib3.disable_warnings()

This will suppress all warnings though, not just InsecureRequest (ie it will also suppress InsecurePlatform etc). In cases where we just want stuff to work, I find the conciseness handy.

PHP create key => value pairs within a foreach

Create key value pairs on the phpsh commandline like this:

php> $keyvalues = array();
php> $keyvalues['foo'] = "bar";
php> $keyvalues['pyramid'] = "power";
php> print_r($keyvalues);
Array
(
    [foo] => bar
    [pyramid] => power
)

Get the count of key value pairs:

php> echo count($offerarray);
2

Get the keys as an array:

php> echo implode(array_keys($offerarray));
foopyramid

How can I send JSON response in symfony2 controller

Symfony 2.1

$response = new Response(json_encode(array('name' => $name)));
$response->headers->set('Content-Type', 'application/json');

return $response;

Symfony 2.2 and higher

You have special JsonResponse class, which serialises array to JSON:

return new JsonResponse(array('name' => $name));

But if your problem is How to serialize entity then you should have a look at JMSSerializerBundle

Assuming that you have it installed, you'll have simply to do

$serializedEntity = $this->container->get('serializer')->serialize($entity, 'json');

return new Response($serializedEntity);

You should also check for similar problems on StackOverflow:

How do I set the selenium webdriver get timeout?

The solution of driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS) will work on the pages with synch loading. This does not solve, however, the problem on pages loading stuff in async, then the tests will fail all the time if we set the pageLoadTimeOut.

Display current date and time without punctuation

Here you go:

date +%Y%m%d%H%M%S

As man date says near the top, you can use the date command like this:

date [OPTION]... [+FORMAT]

That is, you can give it a format parameter, starting with a +. You can probably guess the meaning of the formatting symbols I used:

  • %Y is for year
  • %m is for month
  • %d is for day
  • ... and so on

You can find this, and other formatting symbols in man date.

comparing two strings in ruby

Here are some:

"Ali".eql? "Ali"
=> true

The spaceship (<=>) method can be used to compare two strings in relation to their alphabetical ranking. The <=> method returns 0 if the strings are identical, -1 if the left hand string is less than the right hand string, and 1 if it is greater:

"Apples" <=> "Apples"
=> 0

"Apples" <=> "Pears"
=> -1

"Pears" <=> "Apples"
=> 1

A case insensitive comparison may be performed using the casecmp method which returns the same values as the <=> method described above:

"Apples".casecmp "apples"
=> 0

MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"?

Basically, you get connections in the Sleep state when :

  • a PHP script connects to MySQL
  • some queries are executed
  • then, the PHP script does some stuff that takes time
    • without disconnecting from the DB
  • and, finally, the PHP script ends
    • which means it disconnects from the MySQL server

So, you generally end up with many processes in a Sleep state when you have a lot of PHP processes that stay connected, without actually doing anything on the database-side.

A basic idea, so : make sure you don't have PHP processes that run for too long -- or force them to disconnect as soon as they don't need to access the database anymore.


Another thing, that I often see when there is some load on the server :

  • There are more and more requests coming to Apache
    • which means many pages to generate
  • Each PHP script, in order to generate a page, connects to the DB and does some queries
  • These queries take more and more time, as the load on the DB server increases
  • Which means more processes keep stacking up

A solution that can help is to reduce the time your queries take -- optimizing the longest ones.

How to print last two columns using awk

@jim mcnamara: try using parentheses for around NF, i. e. $(NF-1) and $(NF) instead of $NF-1 and $NF (works on Mac OS X 10.6.8 for FreeBSD awkand gawk).

echo '
1 2
2 3
one
one two three
' | gawk '{if (NF >= 2) print $(NF-1), $(NF);}'

# output:
# 1 2
# 2 3
# two three

Difference between drop table and truncate table?

DELETE

The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it.

TRUNCATE

TRUNCATE removes all rows from a table. The operation cannot be rolled back ... As such, TRUCATE is faster and doesn't use as much undo space as a DELETE.

From: http://www.orafaq.com/faq/difference_between_truncate_delete_and_drop_commands

MySQL SELECT AS combine two columns into one

If both columns can contain NULL, but you still want to merge them to a single string, the easiest solution is to use CONCAT_WS():

SELECT FirstName AS First_Name
     , LastName AS Last_Name
     , CONCAT_WS('', ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone 
  FROM TABLE1

This way you won't have to check for NULL-ness of each column separately.

Alternatively, if both columns are actually defined as NOT NULL, CONCAT() will be quite enough:

SELECT FirstName AS First_Name
     , LastName AS Last_Name
     , CONCAT(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone 
  FROM TABLE1

As for COALESCE, it's a bit different beast: given the list of arguments, it returns the first that's not NULL.

Check if a list contains an item in Ansible

You do not need {{}} in when conditions. What you are searching for is:

- fail: msg="unsupported version"
  when: version not in acceptable_versions

Delete data with foreign key in SQL Server table

SET foreign_key_checks = 0; DELETE FROM yourtable; SET foreign_key_checks = 1;

How to set a primary key in MongoDB?

This is the syntax of creating primary key

db.< collection >.createIndex( < key and index type specification>, { unique: true } )

Let's take that our database have collection named student and it's document have key named student_id which we need to make a primary key. Then the command should be like below.

db.student.createIndex({student_id:1},{unique:true})

You can check whether this student_id set as primary key by trying to add duplicate value to the student collection.

prefer this document for further informations https://docs.mongodb.com/manual/core/index-unique/#create-a-unique-index

Using AES encryption in C#

I've recently had to bump up against this again in my own project - and wanted to share the somewhat simpler code that I've been using, as this question and series of answers kept coming up in my searches.

I'm not going to get into the security concerns around how often to update things like your Salt and Initialization Vector - that's a topic for a security forum, and there are some great resources out there to look at. This is simply a block of code to implement AesManaged in C#.

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

namespace Your.Namespace.Security {
    public static class Cryptography {
        #region Settings

        private static int _iterations = 2;
        private static int _keySize = 256;

        private static string _hash     = "SHA1";
        private static string _salt     = "aselrias38490a32"; // Random
        private static string _vector   = "8947az34awl34kjq"; // Random

        #endregion

        public static string Encrypt(string value, string password) {
            return Encrypt<AesManaged>(value, password);
        }
        public static string Encrypt<T>(string value, string password) 
                where T : SymmetricAlgorithm, new() {
            byte[] vectorBytes = GetBytes<ASCIIEncoding>(_vector);
            byte[] saltBytes = GetBytes<ASCIIEncoding>(_salt);
            byte[] valueBytes = GetBytes<UTF8Encoding>(value);

            byte[] encrypted;
            using (T cipher = new T()) {
                PasswordDeriveBytes _passwordBytes = 
                    new PasswordDeriveBytes(password, saltBytes, _hash, _iterations);
                byte[] keyBytes = _passwordBytes.GetBytes(_keySize / 8);

                cipher.Mode = CipherMode.CBC;

                using (ICryptoTransform encryptor = cipher.CreateEncryptor(keyBytes, vectorBytes)) {
                    using (MemoryStream to = new MemoryStream()) {
                        using (CryptoStream writer = new CryptoStream(to, encryptor, CryptoStreamMode.Write)) {
                            writer.Write(valueBytes, 0, valueBytes.Length);
                            writer.FlushFinalBlock();
                            encrypted = to.ToArray();
                        }
                    }
                }
                cipher.Clear();
            }
            return Convert.ToBase64String(encrypted);
        }

        public static string Decrypt(string value, string password) {
            return Decrypt<AesManaged>(value, password);
        }
        public static string Decrypt<T>(string value, string password) where T : SymmetricAlgorithm, new() {
            byte[] vectorBytes = GetBytes<ASCIIEncoding>(_vector);
            byte[] saltBytes = GetBytes<ASCIIEncoding>(_salt);
            byte[] valueBytes = Convert.FromBase64String(value);

            byte[] decrypted;
            int decryptedByteCount = 0;

            using (T cipher = new T()) {
                PasswordDeriveBytes _passwordBytes = new PasswordDeriveBytes(password, saltBytes, _hash, _iterations);
                byte[] keyBytes = _passwordBytes.GetBytes(_keySize / 8);

                cipher.Mode = CipherMode.CBC;

                try {
                    using (ICryptoTransform decryptor = cipher.CreateDecryptor(keyBytes, vectorBytes)) {
                        using (MemoryStream from = new MemoryStream(valueBytes)) {
                            using (CryptoStream reader = new CryptoStream(from, decryptor, CryptoStreamMode.Read)) {
                                decrypted = new byte[valueBytes.Length];
                                decryptedByteCount = reader.Read(decrypted, 0, decrypted.Length);
                            }
                        }
                    }
                } catch (Exception ex) {
                    return String.Empty;
                }

                cipher.Clear();
            }
            return Encoding.UTF8.GetString(decrypted, 0, decryptedByteCount);
        }

    }
}

The code is very simple to use. It literally just requires the following:

string encrypted = Cryptography.Encrypt(data, "testpass");
string decrypted = Cryptography.Decrypt(encrypted, "testpass");

By default, the implementation uses AesManaged - but you could actually also insert any other SymmetricAlgorithm. A list of the available SymmetricAlgorithm inheritors for .NET 4.5 can be found at:

http://msdn.microsoft.com/en-us/library/system.security.cryptography.symmetricalgorithm.aspx

As of the time of this post, the current list includes:

  • AesManaged
  • RijndaelManaged
  • DESCryptoServiceProvider
  • RC2CryptoServiceProvider
  • TripleDESCryptoServiceProvider

To use RijndaelManaged with the code above, as an example, you would use:

string encrypted = Cryptography.Encrypt<RijndaelManaged>(dataToEncrypt, password);
string decrypted = Cryptography.Decrypt<RijndaelManaged>(encrypted, password);

I hope this is helpful to someone out there.

Read environment variables in Node.js

You can use env package to manage your environment variables per project:

  • Create a .env file under the project directory and put all of your variables there.
  • Add this line in the top of your application entry file:
    require('dotenv').config();

Done. Now you can access your environment variables with process.env.ENV_NAME.

Reduce size of legend area in barplot

The cex parameter will do that for you.

a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
        col = 1:6, space = c(0, 2))
legend("topright", 
       legend = c("a", "b", "c", "d", "e", "f"), 
       fill = 1:6, ncol = 2,
       cex = 0.75)

The plot

.map() a Javascript ES6 Map?

You can map() arrays, but there is no such operation for Maps. The solution from Dr. Axel Rauschmayer:

  • Convert the map into an array of [key,value] pairs.
  • Map or filter the array.
  • Convert the result back to a map.

Example:

let map0 = new Map([
  [1, "a"],
  [2, "b"],
  [3, "c"]
]);

const map1 = new Map(
  [...map0]
  .map(([k, v]) => [k * 2, '_' + v])
);

resulted in

{2 => '_a', 4 => '_b', 6 => '_c'}

Undefined Reference to

I had this issue when I forgot to add the new .h/.c file I created to the meson recipe so this is just a friendly reminder.

PHP : send mail in localhost

It is possible to send Emails without using any heavy libraries I have included my example here.

lightweight SMTP Email sender for PHP

https://github.com/jerryurenaa/EZMAIL

Tested in both environments production and development.

and most importantly emails will not go to spam unless your IP is blacklisted by the server.

cheers.

Querying Windows Active Directory server using ldapsearch from command line

You could query an LDAP server from the command line with ldap-utils: ldapsearch, ldapadd, ldapmodify

Reading/parsing Excel (xls) files with Python

I think Pandas is the best way to go. There is already one answer here with Pandas using ExcelFile function, but it did not work properly for me. From here I found the read_excel function which works just fine:

import pandas as pd
dfs = pd.read_excel("your_file_name.xlsx", sheet_name="your_sheet_name")
print(dfs.head(10))

P.S. You need to have the xlrd installed for read_excel function to work

Update 21-03-2020: As you may see here, there are issues with the xlrd engine and it is going to be deprecated. The openpyxl is the best replacement. So as described here, the canonical syntax should be:

dfs = pd.read_excel("your_file_name.xlsx", sheet_name="your_sheet_name", engine="openpyxl")

Assigning strings to arrays of characters

You can use this:

yylval.sval=strdup("VHDL + Volcal trance...");

Where yylval is char*. strdup from does the job.

HTML <select> selected option background-color CSS style

I think the solution you may been looking for is:

option:checked {
  box-shadow: 0 0 10px 100px #FFFF00 inset; }

Conditional Binding: if let error – Initializer for conditional binding must have Optional type

Same applies for guard statements. The same error message lead me to this post and answer (thanks @nhgrif).

The code: Print the last name of the person only if the middle name is less than four characters.

func greetByMiddleName(name: (first: String, middle: String?, last: String?)) {
    guard let Name = name.last where name.middle?.characters.count < 4 else {
        print("Hi there)")
        return
    }
    print("Hey \(Name)!")
}

Until I declared last as an optional parameter I was seeing the same error.

How to convert file to base64 in JavaScript?

Building up on Dmitri Pavlutin and joshua.paling answers, here's an extended version that extracts the base64 content (removes the metadata at the beginning) and also ensures padding is done correctly.

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      let encoded = reader.result.toString().replace(/^data:(.*,)?/, '');
      if ((encoded.length % 4) > 0) {
        encoded += '='.repeat(4 - (encoded.length % 4));
      }
      resolve(encoded);
    };
    reader.onerror = error => reject(error);
  });
}

Is there a way to only install the mysql client (Linux)?

sudo apt-get install mysql-client-core-5.5

__init__ and arguments in Python

In Python:

  • Instance methods: require the self argument.
  • Class methods: take the class as a first argument.
  • Static methods: do not require either the instance (self) or the class (cls) argument.

__init__ is a special function and without overriding __new__ it will always be given the instance of the class as its first argument.

An example using the builtin classmethod and staticmethod decorators:

import sys

class Num:
    max = sys.maxint

    def __init__(self,num):
        self.n = num

    def getn(self):
        return self.n

    @staticmethod
    def getone():
        return 1

    @classmethod
    def getmax(cls):
        return cls.max

myObj = Num(3)
# with the appropriate decorator these should work fine
myObj.getone()
myObj.getmax()
myObj.getn()

That said, I would try to use @classmethod/@staticmethod sparingly. If you find yourself creating objects that consist of nothing but staticmethods the more pythonic thing to do would be to create a new module of related functions.

Find a value anywhere in a database

Suppose if you want to get all the table with name a column name contain logintime in the database MyDatabase below is the code sample

    use MyDatabase

    SELECT t.name AS table_name,
    SCHEMA_NAME(schema_id) AS schema_name,
    c.name AS column_name
    FROM sys.tables AS t
    INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
    WHERE c.name LIKE '%logintime%'
    ORDER BY schema_name, table_name;

Cannot find JavaScriptSerializer in .Net 4.0

Did you include a reference to System.Web.Extensions? If you click on your first link it says which assembly it's in.

Move SQL Server 2008 database files to a new folder location

This is a complete procedure to transfer database and logins from an istance to a new one, scripting logins and relocating datafile and log files on the destination. Everything using metascripts.

http://zaboilab.com/sql-server-toolbox/massive-database-migration-between-sql-server-instances-the-complete-procedure

Sorry for the off-site procedure but scripts are very long. You have to:
- Script logins with original SID and HASHED password
- Create script to backup database using metascripts
- Create script to restore database passing relocate parameters using again metascripts
- Run the generated scripts on source and destination instance.
See details and download scripts following the link above.

No generated R.java file in my project

I just had a problem where a previously working project stopped working with everything that referenced R being posted as errors because R.java was not being generated.

** * CHECK THE CONSOLE VIEW TOO **

I had (using finder) made a backup of the main icon (not even used) so one of the res folders (hdpi) had

icon.png copy of icon.png

Console indicated that "copy of icon.png" was not a valid file name. No errors were flagged anywhere else - no red X in the res folders....

but replacing the spaces with "_" and it is all back to normal....

How to get a complete list of ticker symbols from Yahoo Finance?

I may be able to help with a list of ticker symbols for (U.S. and non-U.S.) stocks and for ETFs.

Yahoo provides an Earnings Calendar that lists all the stocks that announce earnings for a given day. This includes non-US stocks.

For example, here is today's: http://biz.yahoo.com/research/earncal/20120710.html

the last part of the URL is the date (in YYYYMMDD format) for which you want the Earnings Calendar. You can loop through several days and scrape the Symbols of all stocks that reported earnings on those days.

There is no guarantee that yahoo has data for all stocks that report earnings, especially since some stocks no longer exist (bankruptcy, acquisition, etc.), but this is probably a decent starting point.

If you are familiar with R, you can use the qmao package to do this. (See this post) if you have trouble installing it.

ec <- getEarningsCalendar(from="2011-01-01", to="2012-07-01") #this may take a while
s <- unique(ec$Symbol)
length(s)
#[1] 12223
head(s, 20) #look at the first 20 Symbols
# [1] "CVGW"    "ANGO"    "CAMP"    "LNDC"    "MOS"     "NEOG"    "SONC"   
# [8] "TISI"    "SHLM"    "FDO"     "FC"      "JPST.PK" "RECN"    "RELL"   
#[15] "RT"      "UNF"     "WOR"     "WSCI"    "ZEP"     "AEHR"   

This will not include any ETFs, futures, options, bonds, forex or mutual funds.

You can get a list of ETFs from yahoo here: http://finance.yahoo.com/etf/browser/mkt That only shows the first 20. You need the URL of the "Show All" link at the bottom of that page. You can scrape the page to find out how many ETFs there are, then construct a URL.

L <- readLines("http://finance.yahoo.com/etf/browser/mkt")
# Sorry for the ugly regex
n <- gsub("^(\\w+)\\s?(.*)$", "\\1", 
          gsub("(.*)(Showing 1 - 20 of )(.*)", "\\3",  
               L[grep("Showing 1 - 20", L)]))
URL <- paste0("http://finance.yahoo.com/etf/browser/mkt?c=0&k=5&f=0&o=d&cs=1&ce=", n)
#http://finance.yahoo.com/etf/browser/mkt?c=0&k=5&f=0&o=d&cs=1&ce=1442

Now, you can extract the Tickers from the table on that page

library(XML)
tbl <- readHTMLTable(URL, stringsAsFactors=FALSE)
dat <- tbl[[tail(grep("Ticker", tbl), 1)]][-1, ]
colnames(dat) <- dat[1, ]
dat <- dat[-1, ]
etfs <- dat$Ticker # All ETF tickers from yahoo
length(etfs)
#[1] 1442
head(etfs)
#[1] "DGAZ" "TAGS" "GASX" "KOLD" "DWTI" "RTSA"

That's about all the help I can offer, but you could do something similar to get some of the futures they offer by scraping these pages (These are only U.S. futures)

http://finance.yahoo.com/indices?e=futures, http://finance.yahoo.com/futures?t=energy, http://finance.yahoo.com/futures?t=metals, http://finance.yahoo.com/futures?t=grains, http://finance.yahoo.com/futures?t=livestock, http://finance.yahoo.com/futures?t=softs, http://finance.yahoo.com/futures?t=indices,

And, for U.S. and non-U.S. indices, you could scrape these pages

http://finance.yahoo.com/intlindices?e=americas, http://finance.yahoo.com/intlindices?e=asia, http://finance.yahoo.com/intlindices?e=europe, http://finance.yahoo.com/intlindices?e=africa, http://finance.yahoo.com/indices?e=dow_jones, http://finance.yahoo.com/indices?e=new_york, http://finance.yahoo.com/indices?e=nasdaq, http://finance.yahoo.com/indices?e=sp, http://finance.yahoo.com/indices?e=other, http://finance.yahoo.com/indices?e=treasury, http://finance.yahoo.com/indices?e=commodities

How to convert current date to epoch timestamp?

Use strptime to parse the time, and call time() on it to get the Unix timestamp.

Regex pattern inside SQL Replace function?

In a general sense, SQL Server does not support regular expressions and you cannot use them in the native T-SQL code.

You could write a CLR function to do that. See here, for example.

Phone: numeric keyboard for text input

try this:

$(document).ready(function() {
    $(document).find('input[type=number]').attr('type', 'tel');
});

refer: https://answers.laserfiche.com/questions/88002/Use-number-field-input-type-with-Field-Mask

Format number to always show 2 decimal places

(num + "").replace(/^([0-9]*)(\.[0-9]{1,2})?.*$/,"$1$2")

Is null check needed before calling instanceof?

Using a null reference as the first operand to instanceof returns false.

NameError: name 'python' is not defined

When you run the Windows Command Prompt, and type in python, it starts the Python interpreter.

Typing it again tries to interpret python as a variable, which doesn't exist and thus won't work:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\USER>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>> print("interpreter has started")
interpreter has started
>>> quit() # leave the interpreter, and go back to the command line

C:\Users\USER>

If you're not doing this from the command line, and instead running the Python interpreter (python.exe or IDLE's shell) directly, you are not in the Windows Command Line, and python is interpreted as a variable, which you have not defined.

Communication between tabs or windows

Another method that people should consider using is Shared Workers. I know it's a cutting edge concept, but you can create a relay on a Shared Worker that is MUCH faster than localstorage, and doesn't require a relationship between the parent/child window, as long as you're on the same origin.

See my answer here for some discussion I made about this.

An error occurred while executing the command definition. See the inner exception for details

Look at the Inner Exception and find out what object might have caused the problem, you might have changed its name.

Best Regular Expression for Email Validation in C#

I would like to suggest new EmailAddressAttribute().IsValid(emailTxt) for additional validation before/after validating using RegEx

Remember EmailAddressAttribute is part of System.ComponentModel.DataAnnotations namespace.