Programs & Examples On #Sessionfactory

A main interface used by the application to obtain a Hibernate session.

Hibernate SessionFactory vs. JPA EntityManagerFactory

Using EntityManagerFactory approach allows us to use callback method annotations like @PrePersist, @PostPersist,@PreUpdate with no extra configuration.

Using similar callbacks while using SessionFactory will require extra efforts.

Related Hibernate docs can be found here and here.

Related SOF Question and Spring Forum discussion

How to rebuild docker container in docker-compose.yml?

This should fix your problem:

docker-compose ps # lists all services (id, name)
docker-compose stop <id/name> #this will stop only the selected container
docker-compose rm <id/name> # this will remove the docker container permanently 
docker-compose up # builds/rebuilds all not already built container 

Jenkins Pipeline Wipe Out Workspace

In fact the deleteDir function recursively deletes the current directory and its contents. Symbolic links and junctions will not be followed but will be removed.

To delete a specific directory of a workspace wrap the deleteDir step in a dir step.

dir('directoryToDelete') {
    deleteDir()
}

INFO: No Spring WebApplicationInitializer types detected on classpath

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>          
    <configuration>
        <source>1.8</source>
        <target>1.8</target>
    </configuration>
 </plugin>

This is the important plugin that should be in pom.xml. I spent my two days debugging and researching. This was the solution. This is Apache plugin to tell maven to use the the given Compiler.

Formatting Decimal places in R

You can format a number, say x, up to decimal places as you wish. Here x is a number with many decimal places. Suppose we wish to show up to 8 decimal places of this number:

x = 1111111234.6547389758965789345
y = formatC(x, digits = 8, format = "f")
# [1] "1111111234.65473890"

Here format="f" gives floating numbers in the usual decimal places say, xxx.xxx, and digits specifies the number of digits. By contrast, if you wanted to get an integer to display you would use format="d" (much like sprintf).

Run MySQLDump without Locking Tables

If you use the Percona XtraDB Cluster - I found that adding --skip-add-locks
to the mysqldump command Allows the Percona XtraDB Cluster to run the dump file without an issue about LOCK TABLES commands in the dump file.

How to find the foreach index?

I solved this way, when I had to use the foreach index and value in the same context:

$array = array('a', 'b', 'c');
foreach ($array as $letter=>$index) {

  echo $letter; //Here $letter content is the actual index
  echo $array[$letter]; // echoes the array value

}//foreach

Get first n characters of a string

$width = 10;

$a = preg_replace ("~^(.{{$width}})(.+)~", '\\1…', $a);

or with wordwrap

$a = preg_replace ("~^(.{1,${width}}\b)(.+)~", '\\1…', $a);

Saving excel worksheet to CSV files with filename+worksheet name using VB

The code above works perfectly with one minor flaw; the resulting file is not saved with a .csv extension. – Tensigh 2 days ago

I added the following to code and it saved my file as a csv. Thanks for this bit of code.It all worked as expected.

ActiveWorkbook.SaveAs Filename:=SaveToDirectory & ThisWorkbook.Name & "-" & WS.Name & ".csv", FileFormat:=xlCSV

What does "Content-type: application/json; charset=utf-8" really mean?

I was using HttpClient and getting back response header with content-type of application/json, I lost characters such as foreign languages or symbol that used unicode since HttpClient is default to ISO-8859-1. So, be explicit as possible as mentioned by @WesternGun to avoid any possible problem.

There is no way handle that due to server doesn't handle requested-header charset (method.setRequestHeader("accept-charset", "UTF-8");) for me and I had to retrieve response data as draw bytes and convert it into String using UTF-8. So, it is recommended to be explicit and avoid assumption of default value.

How do I use disk caching in Picasso?

1) answer of first question : according to Picasso Doc for With() method

The global default Picasso instance returned from with() is automatically initialized with defaults that are suitable to most implementations.

  • LRU memory cache of 15% the available application RAM
  • Disk cache of 2% storage space up to 50MB but no less than 5MB.

But Disk Cache operation for global Default Picasso is only available on API 14+

2) answer of second Question : Picasso use the HTTP client request to Disk Cache operation So you can make your own http request header has property Cache-Control with max-age And create your own Static Picasso Instance instead of default Picasso By using

1] HttpResponseCache (Note: Works only for API 13+ )
2] OkHttpClient (Works for all APIs)

Example for using OkHttpClient to create your own Static Picasso class:

  • First create a new class to get your own singleton picasso object

    import android.content.Context;
    import com.squareup.picasso.Downloader;
    import com.squareup.picasso.OkHttpDownloader;
    import com.squareup.picasso.Picasso;
    
    public class PicassoCache {
    
        /**
         * Static Picasso Instance
         */
        private static Picasso picassoInstance = null;
    
        /**
         * PicassoCache Constructor
         *
         * @param context application Context
         */
        private PicassoCache (Context context) {
    
            Downloader downloader   = new OkHttpDownloader(context, Integer.MAX_VALUE);
            Picasso.Builder builder = new Picasso.Builder(context);
                builder.downloader(downloader);
    
            picassoInstance = builder.build();
        }
    
        /**
         * Get Singleton Picasso Instance
         *
         * @param context application Context
         * @return Picasso instance
         */
        public static Picasso getPicassoInstance (Context context) {
    
            if (picassoInstance == null) {
    
                new PicassoCache(context);
                return picassoInstance;
            }
    
            return picassoInstance;
        }
    
    } 
    
  • use your own singleton picasso object Instead of Picasso.With()

PicassoCache.getPicassoInstance(getContext()).load(imagePath).into(imageView)

3) answer for third question : you do not need any disk permissions for disk Cache operations

References: Github issue about disk cache, two Questions has been answered by @jake-wharton -> Question1 and Question2

IE throws JavaScript Error: The value of the property 'googleMapsQuery' is null or undefined, not a Function object (works in other browsers)

I found the answer, and in spite of what I reported, it was NOT browser specific. The bug was in my function code, and would have occurred in any browser. It boils down to this. I had two lines in my code that were FireFox/FireBug specific. They used console.log. In IE, they threw an error, so I commented them out (or so I thought). I did a crappy job commenting them out, and broke the bracketing in my function.

Original Code (with console.log in it):

if (sxti.length <= 50) console.log('sxti=' + sxti);
if (sxph.length <= 50) console.log('sxph=' + sxph);

Broken Code (misplaced brackets inside comments):

if (sxti.length <= 50) { //console.log('sxti=' + sxti); }
if (sxph.length <= 50) { //console.log('sxph=' + sxph); }

Fixed Code (fixed brackets outside comments):

if (sxti.length <= 50) { }//console.log('sxti=' + sxti);
if (sxph.length <= 50) { }//console.log('sxph=' + sxph);

So, it was my own sloppy coding. The function really wasn't defined, because a syntax error kept it from being closed.

Oh well, live and learn. ;)

Easily measure elapsed time

Internally the function will access the system's clock, which is why it returns different values each time you call it. In general with non-functional languages there can be many side effects and hidden state in functions which you can't see just by looking at the function's name and arguments.

javascript check for not null

It is possibly because the value of val is actually the string "null" rather than the value null.

Why is sed not recognizing \t as a tab?

sed doesn't support \t, nor other escape sequences like \n for that matter. The only way I've found to do it was to actually insert the tab character in the script using sed.

That said, you may want to consider using Perl or Python. Here's a short Python script I wrote that I use for all stream regex'ing:

#!/usr/bin/env python
import sys
import re

def main(args):
  if len(args) < 2:
    print >> sys.stderr, 'Usage: <search-pattern> <replace-expr>'
    raise SystemExit

  p = re.compile(args[0], re.MULTILINE | re.DOTALL)
  s = sys.stdin.read()
  print p.sub(args[1], s),

if __name__ == '__main__':
  main(sys.argv[1:])

Google maps Places API V3 autocomplete - select first option on enter

I just want to write an small enhancement for the answer of amirnissim
The script posted doesn't support IE8, because "event.which" seems to be always empty in IE8.
To solve this problem you just need to additionally check for "event.keyCode":

listener = function (event) {
  if (event.which == 13 || event.keyCode == 13) {
    var suggestion_selected = $(".pac-item.pac-selected").length > 0;
    if(!suggestion_selected){
      var simulated_downarrow = $.Event("keydown", {keyCode:40, which:40})
      orig_listener.apply(input, [simulated_downarrow]);
    }
  }
  orig_listener.apply(input, [event]);
};

JS-Fiddle: http://jsfiddle.net/QW59W/107/

App installation failed due to application-identifier entitlement

Even though I followed some few logical steps: uninstall app, rebuild project, the only solution that worked for me was: restart XCode. (XCode 8.1)

Spring Maven clean error - The requested profile "pom.xml" could not be activated because it does not exist

Bumped into same warning. If you specified goals and built project using "Run as -> Maven build..." option check and remove pom.xml from Profiles: just below Goals:

scikit-learn random state in splitting dataset

random_state is None by default which means every time when you run your program you will get different output because of splitting between train and test varies within.

random_state = any int value means every time when you run your program you will get tehe same output because of splitting between train and test does not varies within.

facet label font size

This should get you started:

R> qplot(hwy, cty, data = mpg) + 
       facet_grid(. ~ manufacturer) + 
       theme(strip.text.x = element_text(size = 8, colour = "orange", angle = 90))

See also this question: How can I manipulate the strip text of facet plots in ggplot2?

Saving lists to txt file

@Jon's answer is great and will get you where you need to go. So why is your code printing out what it is. The answer: You're not writing out the contents of your list, but the String representation of your list itself, by an implicit call to Lists.verbList.ToString(). Object.ToString() defines the default behavior you're seeing here.

How to change the font on the TextView?

Typeface tf = Typeface.createFromAsset(getAssets(),
        "fonts/DroidSansFallback.ttf");
TextView tv = (TextView) findViewById(R.id.CustomFontText);
tv.setTypeface(tf);

Check last modified date of file in C#

You simply want the File.GetLastWriteTime static method.

Example:

var lastModified = System.IO.File.GetLastWriteTime("C:\foo.bar");

Console.WriteLine(lastModified.ToString("dd/MM/yy HH:mm:ss"));

Note however that in the rare case the last-modified time is not updated by the system when writing to the file (this can happen intentionally as an optimisation for high-frequency writing, e.g. logging, or as a bug), then this approach will fail, and you will instead need to subscribe to file write notifications from the system, constantly listening.

How to run wget inside Ubuntu Docker image?

If you're running ubuntu container directly without a local Dockerfile you can ssh into the container and enable root control by entering su then apt-get install -y wget

How to flush output after each `echo` call?

This is my code: (work for PHP7)

private function closeConnection()
{
    @apache_setenv('no-gzip', 1);
    @ini_set('zlib.output_compression', 0);
    @ini_set('implicit_flush', 1);

    ignore_user_abort(true);
    set_time_limit(0);

    ob_start();
    // do initial processing here
    echo json_encode(['ans' => true]);

    header('Connection: close');
    header('Content-Length: ' . ob_get_length());
    ob_end_flush();
    ob_flush();
    flush();
}

What does question mark and dot operator ?. mean in C# 6.0?

It can be very useful when flattening a hierarchy and/or mapping objects. Instead of:

if (Model.Model2 == null
  || Model.Model2.Model3 == null
  || Model.Model2.Model3.Model4 == null
  || Model.Model2.Model3.Model4.Name == null)
{
  mapped.Name = "N/A"
}
else
{
  mapped.Name = Model.Model2.Model3.Model4.Name;
}

It can be written like (same logic as above)

mapped.Name = Model.Model2?.Model3?.Model4?.Name ?? "N/A";

DotNetFiddle.Net Working Example.

(the ?? or null-coalescing operator is different than the ? or null conditional operator).

It can also be used out side of assignment operators with Action. Instead of

Action<TValue> myAction = null;

if (myAction != null)
{
  myAction(TValue);
}

It can be simplified to:

myAction?.Invoke(TValue);

DotNetFiddle Example:

using System;

public class Program
{
  public static void Main()
  {
    Action<string> consoleWrite = null;

    consoleWrite?.Invoke("Test 1");

    consoleWrite = (s) => Console.WriteLine(s);

    consoleWrite?.Invoke("Test 2");
  }
}

Result:

Test 2

iOS: How to store username/password within an app?

try this one:

 KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:@"YourAppLogin" accessGroup:nil];
[keychainItem setObject:@"password you are saving" forKey:kSecValueData]; 
[keychainItem setObject:@"username you are saving" forKey:kSecAttrAccount];

may it will help.

The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via

My solution, having encountered the same error message, was even simpler than the ones above, I just updated the to basicHttpsBinding>

  <bindings>
    <basicHttpsBinding>
    <binding name="ShipServiceSoap" maxBufferPoolSize="512000" maxReceivedMessageSize="512000" />
    </basicHttpsBinding>
    </bindings>

And the same in the section below:

  <client>
    <endpoint address="https://s.asmx" binding="basicHttpsBinding" bindingConfiguration="ShipServiceSoap" contract="..ServiceSoap" name="ShipServiceSoap" />
    </client>

Passing ArrayList through Intent

if you using Generic Array List with Class instead of specific type like

EX:

private ArrayList<Model> aListModel = new ArrayList<Model>();

Here, Model = Class

Receiving Intent Like :

aListModel = (ArrayList<Model>) getIntent().getSerializableExtra(KEY);

MUST REMEMBER:

Here Model-class must be implemented like: ModelClass implements Serializable

presenting ViewController with NavigationViewController swift

The accepted answer is great. This is not answer, but just an illustration of the issue.

I present a viewController like this:

inside vc1:

func showVC2() {
    if let navController = self.navigationController{
        navController.present(vc2, animated: true)
    }
}

inside vc2:

func returnFromVC2() {
    if let navController = self.navigationController {
        navController.popViewController(animated: true)
    }else{
        print("navigationController is nil") <-- I was reaching here!
    }
}

As 'stefandouganhyde' has said: "it is not contained by your UINavigationController or any other"

new solution:

func returnFromVC2() {
    dismiss(animated: true, completion: nil)
}

Remove a cookie

To remove all cookies you could write:

foreach ($_COOKIE as $key => $value) {
    unset($value);
    setcookie($key, '', time() - 3600);
}

npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY

Had the same error. Looks like it is related to SSL certificates. If you are using NPM for public packages (don't need the security of HTTPS) you can turn off strict SSL key validation with the following command.

This might be the simplest fix if you're just looking to install a few publicly available packages one time.

npm config set strict-ssl=false

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

This worked for me!!

SELECT * FROM `users` where `created_at` BETWEEN CURDATE()-7 AND CURDATE()

Gson and deserializing an array of objects with arrays in it

Use your bean class like this, if your JSON data starts with an an array object. it helps you.

Users[] bean = gson.fromJson(response,Users[].class);

Users is my bean class.

Response is my JSON data.

Regular expression containing one word or another

You just missed an extra pair of brackets for the "OR" symbol. The following should do the trick:

([0-9]+)\s+((\bseconds\b)|(\bminutes\b))

Without those you were either matching a number followed by seconds OR just the word minutes

File path for project files?

You would do something like this to get the path "Data\ich_will.mp3" inside your application environments folder.

string fileName = "ich_will.mp3";
string path = Path.Combine(Environment.CurrentDirectory, @"Data\", fileName);

In my case it would return the following:

C:\MyProjects\Music\MusicApp\bin\Debug\Data\ich_will.mp3

I use Path.Combine and Environment.CurrentDirectory in my example. These are very useful and allows you to build a path based on the current location of your application. Path.Combine combines two or more strings to create a location, and Environment.CurrentDirectory provides you with the working directory of your application.

The working directory is not necessarily the same path as where your executable is located, but in most cases it should be, unless specified otherwise.

Saving a select count(*) value to an integer (SQL Server)

If @myInt is zero it means no rows in the table: it would be NULL if never set at all.

COUNT will always return a row, even for no rows in a table.

Edit, Apr 2012: the rules for this are described in my answer here:Does COUNT(*) always return a result?

Your count/assign is correct but could be either way:

select @myInt = COUNT(*) from myTable
set @myInt = (select COUNT(*) from myTable)

However, if you are just looking for the existence of rows, (NOT) EXISTS is more efficient:

IF NOT EXISTS (SELECT * FROM myTable)

Case insensitive 'Contains(string)'

One issue with the answer is that it will throw an exception if a string is null. You can add that as a check so it won't:

public static bool Contains(this string source, string toCheck, StringComparison comp)
{
    if (string.IsNullOrEmpty(toCheck) || string.IsNullOrEmpty(source))
        return true;

    return source.IndexOf(toCheck, comp) >= 0;
} 

java.lang.NoClassDefFoundError in junit

  1. Eclipse -> Top menu -> Run -> Run Configurations
  2. Delete all the occurrences of your test. Your test may appear as YourTest.Method_1(). Delete that as well.
  3. Re-run. Let Eclipse build a fresh configuration.

Addendum: Locally I have created a "User Library" and added to my projects which has

hamcrest-core-1.3.jar

junit-4.12.jar

Add space between <li> elements

#access a {
    border-bottom: 2px solid #fff;
    color: #eee;
    display: block;
    line-height: 3.333em;
    padding: 0 10px 0 20px;
    text-decoration: none;
}

I see that you had used line-height but you gave it to <a> tag instead of <ul> Try this:

#access ul {line-height:3.333em;}

You wouldn't need to play with margins then.

TypeError: $(...).autocomplete is not a function

Simple solution: The sequence is really matter while including the auto complete libraries:

<link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="Stylesheet"></link>
<script src='https://cdn.rawgit.com/pguso/jquery-plugin-circliful/master/js/jquery.circliful.min.js'></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js" ></script>

Drop columns whose name contains a specific string from pandas DataFrame

Here is one way to do this:

df = df[df.columns.drop(list(df.filter(regex='Test')))]

Rmi connection refused with localhost

One difference we can note in Windows is:

If you use Runtime.getRuntime().exec("rmiregistry 1024");

you can see rmiregistry.exe process will run in your Task Manager

whereas if you use Registry registry = LocateRegistry.createRegistry(1024);

you can not see the process running in Task Manager,

I think Java handles it in a different way.

and this is my server.policy file

Before running the the application, make sure that you killed all your existing javaw.exe and rmiregistry.exe corresponds to your rmi programs which are already running.

The following code works for me by using Registry.LocateRegistry() or

Runtime.getRuntime.exec("");


// Standard extensions get all permissions by default

grant {
    permission java.security.AllPermission;
};

VM argument

-Djava.rmi.server.codebase=file:\C:\Users\Durai\workspace\RMI2\src\

Code:

package server;    

import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.rmi.Remote;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class HelloServer 
{
  public static void main (String[] argv) 
  {
    try {

        if(System.getSecurityManager()==null){
            System.setProperty("java.security.policy","C:\\Users\\Durai\\workspace\\RMI\\src\\server\\server.policy");
            System.setSecurityManager(new RMISecurityManager());
        }

 Runtime.getRuntime().exec("rmiregistry 1024");

 //     Registry registry = LocateRegistry.createRegistry(1024);
   //   registry.rebind ("Hello", new Hello ("Hello,From Roseindia.net pvt ltd!"));
   //Process process = Runtime.getRuntime().exec("C:\\Users\\Durai\\workspace\\RMI\\src\\server\\rmi_registry_start.bat");

        Naming.rebind ("//localhost:1024/Hello",new Hello ("Hello,From Roseindia.net pvt ltd!")); 
      System.out.println ("Server is connected and ready for operation.");
    } 
    catch (Exception e) {
      System.out.println ("Server not connected: " + e);
      e.printStackTrace();
    }
  }
}

How to use jQuery to show/hide divs based on radio button selection?

The simple jquery source for the same -

$("input:radio[name='group1']").click(function() {      
    $('.desc').hide();
    $('#' + $("input:radio[name='group1']:checked").val()).show();
});

In order to make it little more appropriate just add checked to first option --

<div><label><input type="radio" name="group1" value="opt1" checked>opt1</label></div>  

remove .desc class from styling and modify divs like --

<div id="opt1" class="desc">lorem ipsum dolor</div>
<div id="opt2" class="desc" style="display: none;">consectetur adipisicing</div>
<div id="opt3" class="desc" style="display: none;">sed do eiusmod tempor</div>

it will really look good any-ways.

how to set width for PdfPCell in ItextSharp

Try something like this

PdfPCell cell;
PdfPTable tableHeader;
PdfPTable tmpTable;
PdfPTable table = new PdfPTable(10) { WidthPercentage = 100, RunDirection = PdfWriter.RUN_DIRECTION_LTR, ExtendLastRow = false };

// row 1 / cell 1 (merge)
PdfPCell _c = new PdfPCell(new Phrase("SER. No")) { Rotation = -90, VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER, BorderWidth = 1 };
_c.Rowspan = 2;

table.AddCell(_c);

// row 1 / cell 2
_c = new PdfPCell(new Phrase("TYPE OF SHIPPING")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);

// row 1 / cell 3
_c = new PdfPCell(new Phrase("ORDER NO.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);

// row 1 / cell 4
_c = new PdfPCell(new Phrase("QTY.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);

// row 1 / cell 5
_c = new PdfPCell(new Phrase("DISCHARGE PPORT")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);

// row 1 / cell 6 (merge)
_c = new PdfPCell(new Phrase("DESCRIPTION OF GOODS")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);

// row 1 / cell 7
_c = new PdfPCell(new Phrase("LINE DOC. RECI. DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);

// row 1 / cell 8 (merge)
_c = new PdfPCell(new Phrase("OWNER DOC. RECI. DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);

// row 1 / cell 9 (merge)
_c = new PdfPCell(new Phrase("CLEARANCE DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);

// row 1 / cell 10 (merge)
_c = new PdfPCell(new Phrase("CUSTOM PERMIT NO.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);


// row 2 / cell 2
_c = new PdfPCell(new Phrase("AWB / BL NO.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);

// row 2 / cell 3
_c = new PdfPCell(new Phrase("COMPLEX NAME")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);

// row 2 / cell 4
_c = new PdfPCell(new Phrase("G.W Kgs.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);

// row 2 / cell 5
_c = new PdfPCell(new Phrase("DESTINATON")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);

// row 2 / cell 7
_c = new PdfPCell(new Phrase("OWNER DOC. RECI. DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);

_doc.Add(table);
///////////////////////////////////////////////////////////
_doc.Close();

You might need to re-adjust slightly on the widths and borders but that is a one shot to do.

rewrite a folder name using .htaccess

mod_rewrite can only rewrite/redirect requested URIs. So you would need to request /apple/… to get it rewritten to a corresponding /folder1/….

Try this:

RewriteEngine on
RewriteRule ^apple/(.*) folder1/$1

This rule will rewrite every request that starts with the URI path /apple/… internally to /folder1/….


Edit    As you are actually looking for the other way round:

RewriteCond %{THE_REQUEST} ^GET\ /folder1/
RewriteRule ^folder1/(.*) /apple/$1 [L,R=301]

This rule is designed to work together with the other rule above. Requests of /folder1/… will be redirected externally to /apple/… and requests of /apple/… will then be rewritten internally back to /folder1/….

Select all 'tr' except the first one

Though the question has a decent answer already, I just want to stress that the :first-child tag goes on the item type that represents the children.

For example, in the code:

<div id"someDiv">
     <input id="someInput1" /> 
     <input id="someInput2" />
     <input id="someInput2" />
</div

If you want to affect only the second two elements with a margin, but not the first, you would do:

#someDiv > input {
     margin-top: 20px;
}
#someDiv > input:first-child{
     margin-top: 0px;
}

that is, since the inputs are the children, you would place first-child on the input portion of the selector.

SQL query to find record with ID not in another table

There are basically 3 approaches to that: not exists, not in and left join / is null.

LEFT JOIN with IS NULL

SELECT  l.*
FROM    t_left l
LEFT JOIN
        t_right r
ON      r.value = l.value
WHERE   r.value IS NULL

NOT IN

SELECT  l.*
FROM    t_left l
WHERE   l.value NOT IN
        (
        SELECT  value
        FROM    t_right r
        )

NOT EXISTS

SELECT  l.*
FROM    t_left l
WHERE   NOT EXISTS
        (
        SELECT  NULL
        FROM    t_right r
        WHERE   r.value = l.value
        )

Which one is better? The answer to this question might be better to be broken down to major specific RDBMS vendors. Generally speaking, one should avoid using select ... where ... in (select...) when the magnitude of number of records in the sub-query is unknown. Some vendors might limit the size. Oracle, for example, has a limit of 1,000. Best thing to do is to try all three and show the execution plan.

Specifically form PostgreSQL, execution plan of NOT EXISTS and LEFT JOIN / IS NULL are the same. I personally prefer the NOT EXISTS option because it shows better the intent. After all the semantic is that you want to find records in A that its pk do not exist in B.

Old but still gold, specific to PostgreSQL though: https://explainextended.com/2009/09/16/not-in-vs-not-exists-vs-left-join-is-null-postgresql/

Eclipse IDE for Java - Full Dark Theme

Install a newer version of Eclipse, (Luna Release (4.4.0) or more recent), it include a great Dark theme by default.

Here is a screenshot :

Eclipse Luna 4.4.0 Dark Theme

What are the benefits of using C# vs F# or F# vs C#?

You're asking for a comparison between a procedural language and a functional language so I feel your question can be answered here: What is the difference between procedural programming and functional programming?

As to why MS created F# the answer is simply: Creating a functional language with access to the .Net library simply expanded their market base. And seeing how the syntax is nearly identical to OCaml, it really didn't require much effort on their part.

How do I detect IE 8 with jQuery?

I think the best way would be this:

From HTML5 boilerplate:

<!--[if lt IE 7]> <html lang="en-us" class="no-js ie6 oldie"> <![endif]-->
<!--[if IE 7]>    <html lang="en-us" class="no-js ie7 oldie"> <![endif]-->
<!--[if IE 8]>    <html lang="en-us" class="no-js ie8 oldie"> <![endif]-->
<!--[if gt IE 8]><!--> <html lang="en-us" class="no-js"> <!--<![endif]-->

in JS:

if( $("html").hasClass("ie8") ) { /* do your things */ };

especially since $.browser has been removed from jQuery 1.9+.

AttributeError: Can only use .dt accessor with datetimelike values

When you write

df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
df['Date'] = df['Date'].dt.strftime('%m/%d')

It can fixed

How to convert a data frame column to numeric type?

If you don't care about preserving the factors, and want to apply it to any column that can get converted to numeric, I used the script below. if df is your original dataframe, you can use the script below.

df[] <- lapply(df, as.character)
df <- data.frame(lapply(df, function(x) ifelse(!is.na(as.numeric(x)), as.numeric(x),  x)))

I referenced Shane's and Joran's solution btw

Best practice for REST token-based authentication with JAX-RS and Jersey

How token-based authentication works

In token-based authentication, the client exchanges hard credentials (such as username and password) for a piece of data called token. For each request, instead of sending the hard credentials, the client will send the token to the server to perform authentication and then authorization.

In a few words, an authentication scheme based on tokens follow these steps:

  1. The client sends their credentials (username and password) to the server.
  2. The server authenticates the credentials and, if they are valid, generate a token for the user.
  3. The server stores the previously generated token in some storage along with the user identifier and an expiration date.
  4. The server sends the generated token to the client.
  5. The client sends the token to the server in each request.
  6. The server, in each request, extracts the token from the incoming request. With the token, the server looks up the user details to perform authentication.
    • If the token is valid, the server accepts the request.
    • If the token is invalid, the server refuses the request.
  7. Once the authentication has been performed, the server performs authorization.
  8. The server can provide an endpoint to refresh tokens.

Note: The step 3 is not required if the server has issued a signed token (such as JWT, which allows you to perform stateless authentication).

What you can do with JAX-RS 2.0 (Jersey, RESTEasy and Apache CXF)

This solution uses only the JAX-RS 2.0 API, avoiding any vendor specific solution. So, it should work with JAX-RS 2.0 implementations, such as Jersey, RESTEasy and Apache CXF.

It is worthwhile to mention that if you are using token-based authentication, you are not relying on the standard Java EE web application security mechanisms offered by the servlet container and configurable via application's web.xml descriptor. It's a custom authentication.

Authenticating a user with their username and password and issuing a token

Create a JAX-RS resource method which receives and validates the credentials (username and password) and issue a token for the user:

@Path("/authentication")
public class AuthenticationEndpoint {

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response authenticateUser(@FormParam("username") String username, 
                                     @FormParam("password") String password) {

        try {

            // Authenticate the user using the credentials provided
            authenticate(username, password);

            // Issue a token for the user
            String token = issueToken(username);

            // Return the token on the response
            return Response.ok(token).build();

        } catch (Exception e) {
            return Response.status(Response.Status.FORBIDDEN).build();
        }      
    }

    private void authenticate(String username, String password) throws Exception {
        // Authenticate against a database, LDAP, file or whatever
        // Throw an Exception if the credentials are invalid
    }

    private String issueToken(String username) {
        // Issue a token (can be a random String persisted to a database or a JWT token)
        // The issued token must be associated to a user
        // Return the issued token
    }
}

If any exceptions are thrown when validating the credentials, a response with the status 403 (Forbidden) will be returned.

If the credentials are successfully validated, a response with the status 200 (OK) will be returned and the issued token will be sent to the client in the response payload. The client must send the token to the server in every request.

When consuming application/x-www-form-urlencoded, the client must to send the credentials in the following format in the request payload:

username=admin&password=123456

Instead of form params, it's possible to wrap the username and the password into a class:

public class Credentials implements Serializable {

    private String username;
    private String password;

    // Getters and setters omitted
}

And then consume it as JSON:

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response authenticateUser(Credentials credentials) {

    String username = credentials.getUsername();
    String password = credentials.getPassword();

    // Authenticate the user, issue a token and return a response
}

Using this approach, the client must to send the credentials in the following format in the payload of the request:

{
  "username": "admin",
  "password": "123456"
}

Extracting the token from the request and validating it

The client should send the token in the standard HTTP Authorization header of the request. For example:

Authorization: Bearer <token-goes-here>

The name of the standard HTTP header is unfortunate because it carries authentication information, not authorization. However, it's the standard HTTP header for sending credentials to the server.

JAX-RS provides @NameBinding, a meta-annotation used to create other annotations to bind filters and interceptors to resource classes and methods. Define a @Secured annotation as following:

@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secured { }

The above defined name-binding annotation will be used to decorate a filter class, which implements ContainerRequestFilter, allowing you to intercept the request before it be handled by a resource method. The ContainerRequestContext can be used to access the HTTP request headers and then extract the token:

@Secured
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {

    private static final String REALM = "example";
    private static final String AUTHENTICATION_SCHEME = "Bearer";

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        // Get the Authorization header from the request
        String authorizationHeader =
                requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

        // Validate the Authorization header
        if (!isTokenBasedAuthentication(authorizationHeader)) {
            abortWithUnauthorized(requestContext);
            return;
        }

        // Extract the token from the Authorization header
        String token = authorizationHeader
                            .substring(AUTHENTICATION_SCHEME.length()).trim();

        try {

            // Validate the token
            validateToken(token);

        } catch (Exception e) {
            abortWithUnauthorized(requestContext);
        }
    }

    private boolean isTokenBasedAuthentication(String authorizationHeader) {

        // Check if the Authorization header is valid
        // It must not be null and must be prefixed with "Bearer" plus a whitespace
        // The authentication scheme comparison must be case-insensitive
        return authorizationHeader != null && authorizationHeader.toLowerCase()
                    .startsWith(AUTHENTICATION_SCHEME.toLowerCase() + " ");
    }

    private void abortWithUnauthorized(ContainerRequestContext requestContext) {

        // Abort the filter chain with a 401 status code response
        // The WWW-Authenticate header is sent along with the response
        requestContext.abortWith(
                Response.status(Response.Status.UNAUTHORIZED)
                        .header(HttpHeaders.WWW_AUTHENTICATE, 
                                AUTHENTICATION_SCHEME + " realm=\"" + REALM + "\"")
                        .build());
    }

    private void validateToken(String token) throws Exception {
        // Check if the token was issued by the server and if it's not expired
        // Throw an Exception if the token is invalid
    }
}

If any problems happen during the token validation, a response with the status 401 (Unauthorized) will be returned. Otherwise the request will proceed to a resource method.

Securing your REST endpoints

To bind the authentication filter to resource methods or resource classes, annotate them with the @Secured annotation created above. For the methods and/or classes that are annotated, the filter will be executed. It means that such endpoints will only be reached if the request is performed with a valid token.

If some methods or classes do not need authentication, simply do not annotate them:

@Path("/example")
public class ExampleResource {

    @GET
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response myUnsecuredMethod(@PathParam("id") Long id) {
        // This method is not annotated with @Secured
        // The authentication filter won't be executed before invoking this method
        ...
    }

    @DELETE
    @Secured
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response mySecuredMethod(@PathParam("id") Long id) {
        // This method is annotated with @Secured
        // The authentication filter will be executed before invoking this method
        // The HTTP request must be performed with a valid token
        ...
    }
}

In the example shown above, the filter will be executed only for the mySecuredMethod(Long) method because it's annotated with @Secured.

Identifying the current user

It's very likely that you will need to know the user who is performing the request agains your REST API. The following approaches can be used to achieve it:

Overriding the security context of the current request

Within your ContainerRequestFilter.filter(ContainerRequestContext) method, a new SecurityContext instance can be set for the current request. Then override the SecurityContext.getUserPrincipal(), returning a Principal instance:

final SecurityContext currentSecurityContext = requestContext.getSecurityContext();
requestContext.setSecurityContext(new SecurityContext() {

        @Override
        public Principal getUserPrincipal() {
            return () -> username;
        }

    @Override
    public boolean isUserInRole(String role) {
        return true;
    }

    @Override
    public boolean isSecure() {
        return currentSecurityContext.isSecure();
    }

    @Override
    public String getAuthenticationScheme() {
        return AUTHENTICATION_SCHEME;
    }
});

Use the token to look up the user identifier (username), which will be the Principal's name.

Inject the SecurityContext in any JAX-RS resource class:

@Context
SecurityContext securityContext;

The same can be done in a JAX-RS resource method:

@GET
@Secured
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response myMethod(@PathParam("id") Long id, 
                         @Context SecurityContext securityContext) {
    ...
}

And then get the Principal:

Principal principal = securityContext.getUserPrincipal();
String username = principal.getName();

Using CDI (Context and Dependency Injection)

If, for some reason, you don't want to override the SecurityContext, you can use CDI (Context and Dependency Injection), which provides useful features such as events and producers.

Create a CDI qualifier:

@Qualifier
@Retention(RUNTIME)
@Target({ METHOD, FIELD, PARAMETER })
public @interface AuthenticatedUser { }

In your AuthenticationFilter created above, inject an Event annotated with @AuthenticatedUser:

@Inject
@AuthenticatedUser
Event<String> userAuthenticatedEvent;

If the authentication succeeds, fire the event passing the username as parameter (remember, the token is issued for a user and the token will be used to look up the user identifier):

userAuthenticatedEvent.fire(username);

It's very likely that there's a class that represents a user in your application. Let's call this class User.

Create a CDI bean to handle the authentication event, find a User instance with the correspondent username and assign it to the authenticatedUser producer field:

@RequestScoped
public class AuthenticatedUserProducer {

    @Produces
    @RequestScoped
    @AuthenticatedUser
    private User authenticatedUser;

    public void handleAuthenticationEvent(@Observes @AuthenticatedUser String username) {
        this.authenticatedUser = findUser(username);
    }

    private User findUser(String username) {
        // Hit the the database or a service to find a user by its username and return it
        // Return the User instance
    }
}

The authenticatedUser field produces a User instance that can be injected into container managed beans, such as JAX-RS services, CDI beans, servlets and EJBs. Use the following piece of code to inject a User instance (in fact, it's a CDI proxy):

@Inject
@AuthenticatedUser
User authenticatedUser;

Note that the CDI @Produces annotation is different from the JAX-RS @Produces annotation:

Be sure you use the CDI @Produces annotation in your AuthenticatedUserProducer bean.

The key here is the bean annotated with @RequestScoped, allowing you to share data between filters and your beans. If you don't wan't to use events, you can modify the filter to store the authenticated user in a request scoped bean and then read it from your JAX-RS resource classes.

Compared to the approach that overrides the SecurityContext, the CDI approach allows you to get the authenticated user from beans other than JAX-RS resources and providers.

Supporting role-based authorization

Please refer to my other answer for details on how to support role-based authorization.

Issuing tokens

A token can be:

  • Opaque: Reveals no details other than the value itself (like a random string)
  • Self-contained: Contains details about the token itself (like JWT).

See details below:

Random string as token

A token can be issued by generating a random string and persisting it to a database along with the user identifier and an expiration date. A good example of how to generate a random string in Java can be seen here. You also could use:

Random random = new SecureRandom();
String token = new BigInteger(130, random).toString(32);

JWT (JSON Web Token)

JWT (JSON Web Token) is a standard method for representing claims securely between two parties and is defined by the RFC 7519.

It's a self-contained token and it enables you to store details in claims. These claims are stored in the token payload which is a JSON encoded as Base64. Here are some claims registered in the RFC 7519 and what they mean (read the full RFC for further details):

  • iss: Principal that issued the token.
  • sub: Principal that is the subject of the JWT.
  • exp: Expiration date for the token.
  • nbf: Time on which the token will start to be accepted for processing.
  • iat: Time on which the token was issued.
  • jti: Unique identifier for the token.

Be aware that you must not store sensitive data, such as passwords, in the token.

The payload can be read by the client and the integrity of the token can be easily checked by verifying its signature on the server. The signature is what prevents the token from being tampered with.

You won't need to persist JWT tokens if you don't need to track them. Althought, by persisting the tokens, you will have the possibility of invalidating and revoking the access of them. To keep the track of JWT tokens, instead of persisting the whole token on the server, you could persist the token identifier (jti claim) along with some other details such as the user you issued the token for, the expiration date, etc.

When persisting tokens, always consider removing the old ones in order to prevent your database from growing indefinitely.

Using JWT

There are a few Java libraries to issue and validate JWT tokens such as:

To find some other great resources to work with JWT, have a look at http://jwt.io.

Handling token revocation with JWT

If you want to revoke tokens, you must keep the track of them. You don't need to store the whole token on server side, store only the token identifier (that must be unique) and some metadata if you need. For the token identifier you could use UUID.

The jti claim should be used to store the token identifier on the token. When validating the token, ensure that it has not been revoked by checking the value of the jti claim against the token identifiers you have on server side.

For security purposes, revoke all the tokens for a user when they change their password.

Additional information

  • It doesn't matter which type of authentication you decide to use. Always do it on the top of a HTTPS connection to prevent the man-in-the-middle attack.
  • Take a look at this question from Information Security for more information about tokens.
  • In this article you will find some useful information about token-based authentication.

What is the difference between 'my' and 'our' in Perl?

#!/usr/bin/perl -l

use strict;

# if string below commented out, prints 'lol' , if the string enabled, prints 'eeeeeeeee'
#my $lol = 'eeeeeeeeeee' ;
# no errors or warnings at any case, despite of 'strict'

our $lol = eval {$lol} || 'lol' ;

print $lol;

Why shouldn't `&apos;` be used to escape single quotes?

If you really need single quotes, apostrophes, you can use

html    | numeric | hex
&lsquo; | &#145;  | &#x91; // for the left/beginning single-quote and
&rsquo; | &#146;  | &#x92; // for the right/ending single-quote

How to get a user's client IP address in ASP.NET?

What you can do is store the router IP of your user and also the forwarded IP and try to make it reliable using both the IPs [External Public and Internal Private]. But again after some days client may be assigned new internal IP from router but it will be more reliable.

What does 'x packages are looking for funding' mean when running `npm install`?

npm decided to add a new command: npm fund that will provide more visibility to npm users on what dependencies are actively looking for ways to fund their work.

npm install will also show a single message at the end in order to let user aware that dependencies are looking for funding, it looks like this:

$ npm install
packages are looking for funding.
run `npm fund` for details.

Running npm fund <package> will open the url listed for that given package right in your browser.

For more details look here

How to add border around linear layout except at the bottom?

Save this xml and add as a background for the linear layout....

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <stroke android:width="4dp" android:color="#FF00FF00" /> 
    <solid android:color="#ffffff" /> 
    <padding android:left="7dp" android:top="7dp" 
            android:right="7dp" android:bottom="0dp" /> 
    <corners android:radius="4dp" /> 
</shape>

Hope this helps! :)

How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

If you want to know if the user is accessing your app from facebook page tab or canvas check for the Signed Request. If you don't get it, probably the user is not accessing from facebook. To make sure confirm the signed_request fields structure and fields content.

With the php-sdk you can get the Signed Request like this:

$signed_request = $facebook->getSignedRequest();

You can read more about Signed Request here:

https://developers.facebook.com/docs/reference/php/facebook-getSignedRequest/

and here:

https://developers.facebook.com/docs/reference/login/signed-request/

WCF error - There was no endpoint listening at

You do not define a binding in your service's config, so you are getting the default values for wsHttpBinding, and the default value for securityMode\transport for that binding is Message.

Try copying your binding configuration from the client's config to your service config and assign that binding to the endpoint via the bindingConfiguration attribute:

<bindings>
  <wsHttpBinding>
    <binding name="ota2010AEndpoint" 
             .......>
      <readerQuotas maxDepth="32" ... />
        <reliableSession ordered="true" .... />
          <security mode="Transport">
            <transport clientCredentialType="None" proxyCredentialType="None"
                       realm="" />
            <message clientCredentialType="Windows" negotiateServiceCredential="true"
                     establishSecurityContext="true" />
          </security>
    </binding>
  </wsHttpBinding>
</bindings>    

(Snipped parts of the config to save space in the answer).

<service name="Synxis" behaviorConfiguration="SynxisWCF">
    <endpoint address="" name="wsHttpEndpoint" 
              binding="wsHttpBinding" 
              bindingConfiguration="ota2010AEndpoint"
              contract="Synxis" />

This will then assign your defined binding (with Transport security) to the endpoint.

How to make a movie out of images in python

Here is a minimal example using moviepy. For me this was the easiest solution.

import os
import moviepy.video.io.ImageSequenceClip
image_folder='folder_with_images'
fps=1

image_files = [image_folder+'/'+img for img in os.listdir(image_folder) if img.endswith(".png")]
clip = moviepy.video.io.ImageSequenceClip.ImageSequenceClip(image_files, fps=fps)
clip.write_videofile('my_video.mp4')

Clear ComboBox selected text

The following code will work:

ComboBox1.SelectedIndex.Equals(String.Empty);

float:left; vs display:inline; vs display:inline-block; vs display:table-cell;

I usually use float: left; and add overflow: auto; to solve the collapsing parent problem (as to why this works, overflow: auto will expand the parent instead of adding scrollbars if you do not give it explicit height, overflow: hidden works as well). Most of the vertical alignment needs I had are for one-line of text in menu bars, which can be solved using line-height property. If I really need to vertical align a block element, I'd set an explicit height on the parent and the vertically aligned item, position absolute, top 50%, and negative margin.

The reason I don't use display: table-cell is the way it overflows when you have more items than the site's width can handle. table-cell will force the user to scroll horizontally, while floats will wrap the overflow menu, making it still usable without the need for horizontal scrolling.

The best thing about float: left and overflow: auto is that it works all the way back to IE6 without hacks, probably even further.

enter image description here

Getting input values from text box

Remove the id="pass" off the td element. Right now the js will get the td element instead of the input hence the value is undefined.

change values in array when doing foreach

Array: [1, 2, 3, 4]
Result: ["foo1", "foo2", "foo3", "foo4"]

Array.prototype.map() Keep original array

_x000D_
_x000D_
const originalArr = ["Iron", "Super", "Ant", "Aqua"];
const modifiedArr = originalArr.map(name => `${name}man`);

console.log( "Original: %s", originalArr );
console.log( "Modified: %s", modifiedArr );
_x000D_
_x000D_
_x000D_

Array.prototype.forEach() Override original array

_x000D_
_x000D_
const originalArr = ["Iron", "Super", "Ant", "Aqua"];
originalArr.forEach((name, index) => originalArr[index] = `${name}man`);

console.log( "Overridden: %s", originalArr );
_x000D_
_x000D_
_x000D_

HEAD and ORIG_HEAD in Git

From git reset

"pull" or "merge" always leaves the original tip of the current branch in ORIG_HEAD.

git reset --hard ORIG_HEAD

Resetting hard to it brings your index file and the working tree back to that state, and resets the tip of the branch to that commit.

git reset --merge ORIG_HEAD

After inspecting the result of the merge, you may find that the change in the other branch is unsatisfactory. Running "git reset --hard ORIG_HEAD" will let you go back to where you were, but it will discard your local changes, which you do not want. "git reset --merge" keeps your local changes.


Before any patches are applied, ORIG_HEAD is set to the tip of the current branch.
This is useful if you have problems with multiple commits, like running 'git am' on the wrong branch or an error in the commits that is more easily fixed by changing the mailbox (e.g. +errors in the "From:" lines).

In addition, merge always sets '.git/ORIG_HEAD' to the original state of HEAD so a problematic merge can be removed by using 'git reset ORIG_HEAD'.


Note: from here

HEAD is a moving pointer. Sometimes it means the current branch, sometimes it doesn't.

So HEAD is NOT a synonym for "current branch" everywhere already.

HEAD means "current" everywhere in git, but it does not necessarily mean "current branch" (i.e. detached HEAD).

But it almost always means the "current commit".
It is the commit "git commit" builds on top of, and "git diff --cached" and "git status" compare against.
It means the current branch only in very limited contexts (exactly when we want a branch name to operate on --- resetting and growing the branch tip via commit/rebase/etc.).

Reflog is a vehicle to go back in time and time machines have interesting interaction with the notion of "current".

HEAD@{5.minutes.ago} could mean "dereference HEAD symref to find out what branch we are on RIGHT NOW, and then find out where the tip of that branch was 5 minutes ago".
Alternatively it could mean "what is the commit I would have referred to as HEAD 5 minutes ago, e.g. if I did "git show HEAD" back then".


git1.8.4 (July 2013) introduces introduced a new notation!
(Actually, it will be for 1.8.5, Q4 2013: reintroduced with commit 9ba89f4), by Felipe Contreras.

Instead of typing four capital letters "HEAD", you can say "@" now,
e.g. "git log @".

See commit cdfd948

Typing 'HEAD' is tedious, especially when we can use '@' instead.

The reason for choosing '@' is that it follows naturally from the ref@op syntax (e.g. HEAD@{u}), except we have no ref, and no operation, and when we don't have those, it makes sens to assume 'HEAD'.

So now we can use 'git show @~1', and all that goody goodness.

Until now '@' was a valid name, but it conflicts with this idea, so let's make it invalid. Probably very few people, if any, used this name.

How to get the current location latitude and longitude in android

Use Location Listener Method

@Override
public void onLocationChanged(Location loc) {
Double lat = loc.getLatitude();
Double lng = loc.getLongitude();
}

What's the difference between Unicode and UTF-8?

It's weird. Unicode is a standard, not an encoding. As it is possible to specify the endianness I guess it's effectively UTF-16 or maybe 32.

Where does this menu provide from?

ORA-06508: PL/SQL: could not find program unit being called

Based on previous answers. I resolved my issue by removing global variable at package level to procedure, since there was no impact in my case.

Original script was

create or replace PACKAGE BODY APPLICATION_VALIDATION AS 

V_ERROR_NAME varchar2(200) := '';

PROCEDURE  APP_ERROR_X47_VALIDATION (   PROCESS_ID IN VARCHAR2 ) AS BEGIN
     ------ rules for validation... END APP_ERROR_X47_VALIDATION ;

/* Some more code
*/

END APPLICATION_VALIDATION; /

Rewritten the same without global variable V_ERROR_NAME and moved to procedure under package level as

Modified Code

create or replace PACKAGE BODY APPLICATION_VALIDATION AS

PROCEDURE  APP_ERROR_X47_VALIDATION (   PROCESS_ID IN VARCHAR2 ) AS

**V_ERROR_NAME varchar2(200) := '';** 

BEGIN
     ------ rules for validation... END APP_ERROR_X47_VALIDATION ;

/* Some more code
*/

END APPLICATION_VALIDATION; /

Android: Scale a Drawable or background image?

Use image as background sized to layout:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <ImageView
        android:id="@+id/imgPlaylistItemBg"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:adjustViewBounds="true"
        android:maxHeight="0dp"
        android:scaleType="fitXY"
        android:src="@drawable/img_dsh" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >


    </LinearLayout>

</FrameLayout>

How to get DataGridView cell value in messagebox?

Sum all cells

        double X=0;
        if (datagrid.Rows.Count-1 > 0)
        {
           for(int i = 0; i < datagrid.Rows.Count-1; i++)
            {
               for(int j = 0; j < datagrid.Rows.Count-1; j++)
               {
                  X+=Convert.ToDouble(datagrid.Rows[i].Cells[j].Value.ToString());
               }
            } 
        }

HTTP Range header

For folks who are stumbling across Victor Stoddard's answer above in 2019, and become hopeful and doe eyed, note that:

a) Support for X-Content-Duration was removed in Firefox 41: https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Releases/41#HTTP

b) I think it was only supported in Firefox for .ogg audio and .ogv video, not for any other types.

c) I can't see that it was ever supported at all in Chrome, but that may just be a lack of research on my part. But its presence or absence seems to have no effect one way or another for webm or ogv videos as of today in Chrome 71.

d) I can't find anywhere where 'Content-Duration' replaced 'X-Content-Duration' for anything, I don't think 'X-Content-Duration' lived long enough for there to be a successor header name.

I think this means that, as of today if you want to serve webm or ogv containers that contain streams that don't know their duration (e.g. the output of an ffpeg pipe) to Chrome or FF, and you want them to be scrubbable in an HTML 5 video element, you are probably out of luck. Firefox 64.0 makes a half hearted attempt to make these scrubbable whether or not you serve via range requests, but it gets confused and throws up a spinning wheel until the stream is completely downloaded if you seek a few times more than it thinks is appropriate. Chrome doesn't even try, it just nopes out and won't let you scrub at all until the entire stream is finished playing.

Simple prime number generator in Python

Here is what I have:

def is_prime(num):
    if num < 2:         return False
    elif num < 4:       return True
    elif not num % 2:   return False
    elif num < 9:       return True
    elif not num % 3:   return False
    else:
        for n in range(5, int(math.sqrt(num) + 1), 6):
            if not num % n:
                return False
            elif not num % (n + 2):
                return False

    return True

It's pretty fast for large numbers, as it only checks against already prime numbers for divisors of a number.

Now if you want to generate a list of primes, you can do:

# primes up to 'max'
def primes_max(max):
    yield 2
    for n in range(3, max, 2):
        if is_prime(n):
            yield n

# the first 'count' primes
def primes_count(count):
    counter = 0
    num = 3

    yield 2

    while counter < count:
        if is_prime(num):
            yield num
            counter += 1
        num += 2

using generators here might be desired for efficiency.

And just for reference, instead of saying:

one = 1
while one == 1:
    # do stuff

you can simply say:

while 1:
    #do stuff

Call a React component method from outside

If you are in ES6 just use the "static" keyword on your method from your example would be the following: static alertMessage: function() { ...
},

Hope can help anyone out there :)

Keep a line of text as a single line - wrap the whole line or none at all

You could also put non-breaking spaces (&nbsp;) in lieu of the spaces so that they're forced to stay together.

How do I wrap this line of text
-&nbsp;asked&nbsp;by&nbsp;Peter&nbsp;2&nbsp;days&nbsp;ago

Is it possible to reference one CSS rule within another?

Just add the classes to your html

<div class="someDiv radius opacity"></div>

Deserializing a JSON file with JavaScriptSerializer()

  1. You need to create a class that holds the user values, just like the response class User.
  2. Add a property to the Response class 'user' with the type of the new class for the user values User.

    public class Response {
    
        public string id { get; set; }
        public string text { get; set; }
        public string url { get; set; }
        public string width { get; set; }
        public string height { get; set; }
        public string size { get; set; }
        public string type { get; set; }
        public string timestamp { get; set; }
        public User user { get; set; }
    
    }
    
    public class User {
    
        public int id { get; set; }
        public string screen_name { get; set; }
    
    }
    

In general you should make sure the property types of the json and your CLR classes match up. It seems that the structure that you're trying to deserialize contains multiple number values (most likely int). I'm not sure if the JavaScriptSerializer is able to deserialize numbers into string fields automatically, but you should try to match your CLR type as close to the actual data as possible anyway.

Retrieve column names from java.sql.ResultSet

If you want to use spring jdbctemplate and don't want to deal with connection staff, you can use following:

jdbcTemplate.query("select * from books", new RowCallbackHandler() {
        public void processRow(ResultSet resultSet) throws SQLException {
            ResultSetMetaData rsmd = resultSet.getMetaData();
            for (int i = 1; i <= rsmd.getColumnCount(); i++ ) {
                String name = rsmd.getColumnName(i);
                // Do stuff with name
            }
        }
    });

Django: List field in model?

If you are using PostgreSQL, you can use ArrayField with a nested ArrayField: https://docs.djangoproject.com/en/2.2/ref/contrib/postgres/fields/

This way, the data structure will be known to the underlying database. Also, the ORM brings special functionality for it.

Note that you will have to create a GIN index by yourself, though (see the above link, further down: https://docs.djangoproject.com/en/2.2/ref/contrib/postgres/fields/#indexing-arrayfield).

(Edit: updated links to newest Django LTS, this feature exists at least since 1.8.)

Parse a URI String into Name-Value Collection

If you are using Spring, add an argument of type @RequestParam Map<String,String> to your controller method, and Spring will construct the map for you!

How to load all modules in a folder?

Using importlib the only thing you've got to add is

from importlib import import_module
from pathlib import Path

__all__ = [
    import_module(f".{f.stem}", __package__)
    for f in Path(__file__).parent.glob("*.py")
    if "__" not in f.stem
]
del import_module, Path

Reduce left and right margins in matplotlib plot

You can adjust the spacing around matplotlib figures using the subplots_adjust() function:

import matplotlib.pyplot as plt
plt.plot(whatever)
plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1)

This will work for both the figure on screen and saved to a file, and it is the right function to call even if you don't have multiple plots on the one figure.

The numbers are fractions of the figure dimensions, and will need to be adjusted to allow for the figure labels.

Java: How to set Precision for double value?

This is an easy way to do it:

String formato = String.format("%.2f");

It sets the precision to 2 digits.

If you only want to print, use it this way:

System.out.printf("%.2f",123.234);

How to get the selected date value while using Bootstrap Datepicker?

Try this using HTML like here:

var myDate = window.document.getElementById("startdate").value;

Check for special characters in string

Remove the characters ^ (start of string) and $ (end of string) from the regular expression.

var format = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/;

Difference between .on('click') vs .click()

Here you will get list of diffrent ways of applying the click event. You can select accordingly as suaitable or if your click is not working just try an alternative out of these.

$('.clickHere').click(function(){ 
     // this is flat click. this event will be attatched 
     //to element if element is available in 
     //dom at the time when JS loaded. 

  // do your stuff
});

$('.clickHere').on('click', function(){ 
    // same as first one

    // do your stuff
})

$(document).on('click', '.clickHere', function(){
          // this is diffrent type 
          //  of click. The click will be registered on document when JS 
          //  loaded and will delegate to the '.clickHere ' element. This is 
          //  called event delegation 
   // do your stuff
});

$('body').on('click', '.clickHere', function(){
   // This is same as 3rd 
   // point. Here we used body instead of document/

   // do your stuff
});

$('.clickHere').off().on('click', function(){ // 
    // deregister event listener if any and register the event again. This 
    // prevents the duplicate event resistration on same element. 
    // do your stuff
})

"configuration file /etc/nginx/nginx.conf test failed": How do I know why this happened?

If you want to check syntax error for any nginx files, you can use the -c option.

[root@server ~]# sudo nginx -t -c /etc/nginx/my-server.conf
nginx: the configuration file /etc/nginx/my-server.conf syntax is ok
nginx: configuration file /etc/nginx/my-server.conf test is successful
[root@server ~]# 

An unhandled exception was generated during the execution of the current web request

You have more than one form tags with runat="server" on your template, most probably you have one in your master page, remove one on your aspx page, it is not needed if already have form in master page file which is surrounding your content place holders.

Try to remove that tag:

<form id="formID" runat="server">

and of course closing tag:

</form>

AngularJS - Trigger when radio button is selected

There are at least 2 different methods of invoking functions on radio button selection:

1) Using ng-change directive:

<input type="radio" ng-model="value" value="foo" ng-change='newValue(value)'>

and then, in a controller:

$scope.newValue = function(value) {
     console.log(value);
}

Here is the jsFiddle: http://jsfiddle.net/ZPcSe/5/

2) Watching the model for changes. This doesn't require anything special on the input level:

<input type="radio" ng-model="value" value="foo">

but in a controller one would have:

$scope.$watch('value', function(value) {
       console.log(value);
 });

And the jsFiddle: http://jsfiddle.net/vDTRp/2/

Knowing more about your the use case would help to propose an adequate solution.

Java: how do I initialize an array size if it's unknown?

**input of list of number for array from single line.

   String input = sc.nextLine();
    String arr[] = input.split(" ");
    int new_arr[] = new int[arr.length];
    for(int i=0; i<arr.length; i++)
    {
         new_arr[i] = Integer.parseInt(arr[i]);
    }

Bootstrap carousel multiple frames at once

_x000D_
_x000D_
    $('#carousel-example-generic').on('slid.bs.carousel', function () {_x000D_
        $(".item.active:nth-child(" + ($(".carousel-inner .item").length -1) + ") + .item").insertBefore($(".item:first-child"));_x000D_
        $(".item.active:last-child").insertBefore($(".item:first-child"));_x000D_
    });    
_x000D_
        .item.active,_x000D_
        .item.active + .item,_x000D_
        .item.active + .item  + .item {_x000D_
           width: 33.3%;_x000D_
           display: block;_x000D_
           float:left;_x000D_
        }          
_x000D_
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">_x000D_
_x000D_
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel" style="max-width:800px;">_x000D_
  <!-- Indicators -->_x000D_
  <ol class="carousel-indicators">_x000D_
    <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>_x000D_
    <li data-target="#carousel-example-generic" data-slide-to="1"></li>_x000D_
    <li data-target="#carousel-example-generic" data-slide-to="2"></li>_x000D_
  </ol>_x000D_
_x000D_
  <!-- Wrapper for slides -->_x000D_
  <div class="carousel-inner" role="listbox">_x000D_
    <div class="item active">_x000D_
        <img data-src="holder.js/300x200?text=1">_x000D_
    </div>_x000D_
    <div class="item">_x000D_
        <img data-src="holder.js/300x200?text=2">_x000D_
    </div>_x000D_
    <div class="item">_x000D_
        <img data-src="holder.js/300x200?text=3">_x000D_
    </div>_x000D_
    <div class="item">_x000D_
        <img data-src="holder.js/300x200?text=4">_x000D_
    </div>_x000D_
    <div class="item">_x000D_
        <img data-src="holder.js/300x200?text=5">_x000D_
    </div>_x000D_
    <div class="item">_x000D_
        <img data-src="holder.js/300x200?text=6">_x000D_
    </div>_x000D_
    <div class="item">_x000D_
        <img data-src="holder.js/300x200?text=7">_x000D_
    </div>    _x000D_
  </div>_x000D_
_x000D_
  <!-- Controls -->_x000D_
  <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">_x000D_
    <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>_x000D_
    <span class="sr-only">Previous</span>_x000D_
  </a>_x000D_
  <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">_x000D_
    <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>_x000D_
    <span class="sr-only">Next</span>_x000D_
  </a>_x000D_
</div>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>_x000D_
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>_x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/holder/2.9.1/holder.min.js"></script>_x000D_
    
_x000D_
_x000D_
_x000D_

redirect to current page in ASP.Net

Why Server.Transfer? Response.Redirect(Request.RawUrl) would get you what you need.

How to programmatically set SelectedValue of Dropdownlist when it is bound to XmlDataSource

Have you tried, after calling DataBind on your DropDownList, to do something like ddl.SelectedIndex = 0 ?

jQuery Mobile how to check if button is disabled?

Faced with the same issue when trying to check if a button is disabled. I've tried a variety of approaches, such as btn.disabled, .is(':disabled'), .attr('disabled'), .prop('disabled'). But no one works for me.

Some, for example .disabled or .is(':disabled') returned undefined and other like .attr('disabled') returned the wrong result - false when the button was actually disabled.

But only one technique works for me: .is('[disabled]') (with square brackets).

So to determine if a button is disabled try this:

$("#myButton").is('[disabled]');

C++ vector of char array

You can directly define a char type vector as below.

vector<char> c = {'a', 'b', 'c'};
vector < vector<char> > t = {{'a','a'}, 'b','b'};

How to run a .jar in mac?

You don't need JDK to run Java based programs. JDK is for development which stands for Java Development Kit.

You need JRE which should be there in Mac.

Try: java -jar Myjar_file.jar

EDIT: According to this article, for Mac OS 10

The Java runtime is no longer installed automatically as part of the OS installation.

Then, you need to install JRE to your machine.

How to extract text from a PDF file?

I am adding code to accomplish this: It is working fine for me:

# This works in python 3
# required python packages
# tabula-py==1.0.0
# PyPDF2==1.26.0
# Pillow==4.0.0
# pdfminer.six==20170720

import os
import shutil
import warnings
from io import StringIO

import requests
import tabula
from PIL import Image
from PyPDF2 import PdfFileWriter, PdfFileReader
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage

warnings.filterwarnings("ignore")


def download_file(url):
    local_filename = url.split('/')[-1]
    local_filename = local_filename.replace("%20", "_")
    r = requests.get(url, stream=True)
    print(r)
    with open(local_filename, 'wb') as f:
        shutil.copyfileobj(r.raw, f)

    return local_filename


class PDFExtractor():
    def __init__(self, url):
        self.url = url

    # Downloading File in local
    def break_pdf(self, filename, start_page=-1, end_page=-1):
        pdf_reader = PdfFileReader(open(filename, "rb"))
        # Reading each pdf one by one
        total_pages = pdf_reader.numPages
        if start_page == -1:
            start_page = 0
        elif start_page < 1 or start_page > total_pages:
            return "Start Page Selection Is Wrong"
        else:
            start_page = start_page - 1

        if end_page == -1:
            end_page = total_pages
        elif end_page < 1 or end_page > total_pages - 1:
            return "End Page Selection Is Wrong"
        else:
            end_page = end_page

        for i in range(start_page, end_page):
            output = PdfFileWriter()
            output.addPage(pdf_reader.getPage(i))
            with open(str(i + 1) + "_" + filename, "wb") as outputStream:
                output.write(outputStream)

    def extract_text_algo_1(self, file):
        pdf_reader = PdfFileReader(open(file, 'rb'))
        # creating a page object
        pageObj = pdf_reader.getPage(0)

        # extracting extract_text from page
        text = pageObj.extractText()
        text = text.replace("\n", "").replace("\t", "")
        return text

    def extract_text_algo_2(self, file):
        pdfResourceManager = PDFResourceManager()
        retstr = StringIO()
        la_params = LAParams()
        device = TextConverter(pdfResourceManager, retstr, codec='utf-8', laparams=la_params)
        fp = open(file, 'rb')
        interpreter = PDFPageInterpreter(pdfResourceManager, device)
        password = ""
        max_pages = 0
        caching = True
        page_num = set()

        for page in PDFPage.get_pages(fp, page_num, maxpages=max_pages, password=password, caching=caching,
                                      check_extractable=True):
            interpreter.process_page(page)

        text = retstr.getvalue()
        text = text.replace("\t", "").replace("\n", "")

        fp.close()
        device.close()
        retstr.close()
        return text

    def extract_text(self, file):
        text1 = self.extract_text_algo_1(file)
        text2 = self.extract_text_algo_2(file)

        if len(text2) > len(str(text1)):
            return text2
        else:
            return text1

    def extarct_table(self, file):

        # Read pdf into DataFrame
        try:
            df = tabula.read_pdf(file, output_format="csv")
        except:
            print("Error Reading Table")
            return

        print("\nPrinting Table Content: \n", df)
        print("\nDone Printing Table Content\n")

    def tiff_header_for_CCITT(self, width, height, img_size, CCITT_group=4):
        tiff_header_struct = '<' + '2s' + 'h' + 'l' + 'h' + 'hhll' * 8 + 'h'
        return struct.pack(tiff_header_struct,
                           b'II',  # Byte order indication: Little indian
                           42,  # Version number (always 42)
                           8,  # Offset to first IFD
                           8,  # Number of tags in IFD
                           256, 4, 1, width,  # ImageWidth, LONG, 1, width
                           257, 4, 1, height,  # ImageLength, LONG, 1, lenght
                           258, 3, 1, 1,  # BitsPerSample, SHORT, 1, 1
                           259, 3, 1, CCITT_group,  # Compression, SHORT, 1, 4 = CCITT Group 4 fax encoding
                           262, 3, 1, 0,  # Threshholding, SHORT, 1, 0 = WhiteIsZero
                           273, 4, 1, struct.calcsize(tiff_header_struct),  # StripOffsets, LONG, 1, len of header
                           278, 4, 1, height,  # RowsPerStrip, LONG, 1, lenght
                           279, 4, 1, img_size,  # StripByteCounts, LONG, 1, size of extract_image
                           0  # last IFD
                           )

    def extract_image(self, filename):
        number = 1
        pdf_reader = PdfFileReader(open(filename, 'rb'))

        for i in range(0, pdf_reader.numPages):

            page = pdf_reader.getPage(i)

            try:
                xObject = page['/Resources']['/XObject'].getObject()
            except:
                print("No XObject Found")
                return

            for obj in xObject:

                try:

                    if xObject[obj]['/Subtype'] == '/Image':
                        size = (xObject[obj]['/Width'], xObject[obj]['/Height'])
                        data = xObject[obj]._data
                        if xObject[obj]['/ColorSpace'] == '/DeviceRGB':
                            mode = "RGB"
                        else:
                            mode = "P"

                        image_name = filename.split(".")[0] + str(number)

                        print(xObject[obj]['/Filter'])

                        if xObject[obj]['/Filter'] == '/FlateDecode':
                            data = xObject[obj].getData()
                            img = Image.frombytes(mode, size, data)
                            img.save(image_name + "_Flate.png")
                            # save_to_s3(imagename + "_Flate.png")
                            print("Image_Saved")

                            number += 1
                        elif xObject[obj]['/Filter'] == '/DCTDecode':
                            img = open(image_name + "_DCT.jpg", "wb")
                            img.write(data)
                            # save_to_s3(imagename + "_DCT.jpg")
                            img.close()
                            number += 1
                        elif xObject[obj]['/Filter'] == '/JPXDecode':
                            img = open(image_name + "_JPX.jp2", "wb")
                            img.write(data)
                            # save_to_s3(imagename + "_JPX.jp2")
                            img.close()
                            number += 1
                        elif xObject[obj]['/Filter'] == '/CCITTFaxDecode':
                            if xObject[obj]['/DecodeParms']['/K'] == -1:
                                CCITT_group = 4
                            else:
                                CCITT_group = 3
                            width = xObject[obj]['/Width']
                            height = xObject[obj]['/Height']
                            data = xObject[obj]._data  # sorry, getData() does not work for CCITTFaxDecode
                            img_size = len(data)
                            tiff_header = self.tiff_header_for_CCITT(width, height, img_size, CCITT_group)
                            img_name = image_name + '_CCITT.tiff'
                            with open(img_name, 'wb') as img_file:
                                img_file.write(tiff_header + data)

                            # save_to_s3(img_name)
                            number += 1
                except:
                    continue

        return number

    def read_pages(self, start_page=-1, end_page=-1):

        # Downloading file locally
        downloaded_file = download_file(self.url)
        print(downloaded_file)

        # breaking PDF into number of pages in diff pdf files
        self.break_pdf(downloaded_file, start_page, end_page)

        # creating a pdf reader object
        pdf_reader = PdfFileReader(open(downloaded_file, 'rb'))

        # Reading each pdf one by one
        total_pages = pdf_reader.numPages

        if start_page == -1:
            start_page = 0
        elif start_page < 1 or start_page > total_pages:
            return "Start Page Selection Is Wrong"
        else:
            start_page = start_page - 1

        if end_page == -1:
            end_page = total_pages
        elif end_page < 1 or end_page > total_pages - 1:
            return "End Page Selection Is Wrong"
        else:
            end_page = end_page

        for i in range(start_page, end_page):
            # creating a page based filename
            file = str(i + 1) + "_" + downloaded_file

            print("\nStarting to Read Page: ", i + 1, "\n -----------===-------------")

            file_text = self.extract_text(file)
            print(file_text)
            self.extract_image(file)

            self.extarct_table(file)
            os.remove(file)
            print("Stopped Reading Page: ", i + 1, "\n -----------===-------------")

        os.remove(downloaded_file)


# I have tested on these 3 pdf files
# url = "http://s3.amazonaws.com/NLP_Project/Original_Documents/Healthcare-January-2017.pdf"
url = "http://s3.amazonaws.com/NLP_Project/Original_Documents/Sample_Test.pdf"
# url = "http://s3.amazonaws.com/NLP_Project/Original_Documents/Sazerac_FS_2017_06_30%20Annual.pdf"
# creating the instance of class
pdf_extractor = PDFExtractor(url)

# Getting desired data out
pdf_extractor.read_pages(15, 23)

Errors: Data path ".builders['app-shell']" should have required property 'class'

I changed @angular-devkit/build-angular": "0.9.0.1" to @angular-devkit/build-angular": "0.13.4" and it worked.

SQL Query for Student mark functionality

I would have said:

select s.stname, s2.subname, highmarks.mark
from students s
join marks m on s.stid = m.stid
join Subject s2 on m.subid = s2.subid
join (select subid, max(mark) as mark
  from marks group by subid) as highmarks
    on highmarks.subid = m.subid and highmarks.mark = m.mark
order by subname, stname;

SQLFiddle here: http://sqlfiddle.com/#!2/5ef84/3

This is a:

  • select on the students table to get the possible students
  • a join to the marks table to match up students to marks,
  • a join to the subjects table to resolve subject ids into names.
  • a join to a derived table of the maximum marks in each subject.

Only the students that get maximum marks will meet all three join conditions. This lists all students who got that maximum mark, so if there are ties, both get listed.

How to send Basic Auth with axios

An example (axios_example.js) using Axios in Node.js:

const axios = require('axios');
const express = require('express');
const app = express();
const port = process.env.PORT || 5000;

app.get('/search', function(req, res) {
    let query = req.query.queryStr;
    let url = `https://your.service.org?query=${query}`;

    axios({
        method:'get',
        url,
        auth: {
            username: 'xxxxxxxxxxxxx',
            password: 'xxxxxxxxxxxxx'
        }
    })
    .then(function (response) {
        res.send(JSON.stringify(response.data));
    })
    .catch(function (error) {
        console.log(error);
    });
});

var server = app.listen(port);

Be sure in your project directory you do:

npm init
npm install express
npm install axios
node axios_example.js

You can then test the Node.js REST API using your browser at: http://localhost:5000/search?queryStr=xxxxxxxxx

Ref: https://github.com/axios/axios

Line Break in XML formatting?

If you are refering to res strings, use CDATA with \n.

<string name="about">
    <![CDATA[
 Author: Sergio Abreu\n
 http://sites.sitesbr.net
  ]]>        
</string>

Naming returned columns in Pandas aggregate function?

such as this kind of dataframe, there are two levels of thecolumn name:

 shop_id  item_id   date_block_num item_cnt_day       
                                  target              
0   0       30          1            31               

we can use this code:

df.columns = [col[0] if col[-1]=='' else col[-1] for col in df.columns.values]

result is:

 shop_id  item_id   date_block_num target              
0   0       30          1            31 

How to remove an iOS app from the App Store

For permanently delete your app follow below steps.

Step 1 :- GO to My Apps App in iTunes Connect

enter image description here

Here you can see your all app which are currently on Appstore.

Step 2 :- Select your app which you want to delete.(click on app-name)

enter image description here

Step 3 :- Select Pricing and Availability Tab.

enter image description here

Step 4 :- Select Remove from sale option.

enter image description here

Step 5 :- Click on save Button.

Now you will see below your app like , Developer Removed it from sale in Red Symbol in place of Green.

enter image description here

Step 6 :- Now again Select your app and Go to App information Tab. you will see Delete App option. (need to scroll bit bottom)

enter image description here

Step 7 :- After clicking on Delete button you will get warning like this ,

enter image description here

Step 8 :- Click on Delete button.

Congratulation , You have Permanently deleted your app successfully from appstore. Now , you cant able to see app on appstore aswellas in your developer account.

Note :-

When you have selected only Remove from sale option you have not deleted app permanently. You can able to make your app live again by clicking on Available in all territories option Again.

enter image description here

Change DataGrid cell colour based on values

If you need to do it with a set number of columns, H.B.'s way is best. But if you don't know how many columns you are dealing with until runtime, then the below code [read: hack] will work. I am not sure if there is a better solution with an unknown number of columns. It took me two days working at it off and on to get it, so I'm sticking with it regardless.

C#

public class ValueToBrushConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        int input;
        try
        {
            DataGridCell dgc = (DataGridCell)value;
            System.Data.DataRowView rowView = (System.Data.DataRowView)dgc.DataContext;
            input = (int)rowView.Row.ItemArray[dgc.Column.DisplayIndex];
        }
        catch (InvalidCastException e)
        {
            return DependencyProperty.UnsetValue;
        }
        switch (input)
        {
            case 1: return Brushes.Red;
            case 2: return Brushes.White;
            case 3: return Brushes.Blue;
            default: return DependencyProperty.UnsetValue;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

XAML

<UserControl.Resources>
    <conv:ValueToBrushConverter x:Key="ValueToBrushConverter"/>
    <Style x:Key="CellStyle" TargetType="DataGridCell">
        <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ValueToBrushConverter}}" />
    </Style>
</UserControl.Resources>
<DataGrid x:Name="dataGrid" CellStyle="{StaticResource CellStyle}">
</DataGrid>

Could not find a part of the path ... bin\roslyn\csc.exe

I experienced this error on a Jenkins build server running MSBuild, which outputs the build files to a separate folder location (_PublishedWebsites). Exactly the same - the roslyn folder was not in the bin directory, and all the roslyn files were lumped in with the bin files.

@igor-semin 's answer was the only thing that worked for me (as I am using the C# 6 language features, I cannot simply uninstall the nuget packages as per other answers), but as I am also running CodeAnalysis, I was getting another error on my deployment target server:

An attempt to override an existing mapping was detected for type Microsoft.CodeAnalysis.ICompilationUnitSyntax with name "", currently mapped to type Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax, to type Microsoft.CodeAnalysis.VisualBasic.Syntax.CompilationUnitSyntax.

The reason for this is that as the roslyn files are getting dumped into the main bin directory, when you run the xcopy to recreate them in the nested roslyn folder, you now have 2 copies of these files being compiled and there is a clash between them. After much frustration I decided on a 'hack' fix - an additional post-build task to delete these files from the bin directory, removing the conflict.

The .csproj of my offending projects now looks like:

................... more here ......................

 <PropertyGroup>
   <PostBuildEvent>
   if not exist "$(WebProjectOutputDir)\bin\Roslyn" md "$(WebProjectOutputDir)\bin\Roslyn"
   start /MIN xcopy /s /y /R "$(OutDir)roslyn\*.*" "$(WebProjectOutputDir)\bin\Roslyn"
 </PostBuildEvent>
</PropertyGroup>
<Target Name="DeleteDuplicateAnalysisFiles" AfterTargets="AfterBuild">
   <!-- Jenkins now has copies of the following files in both the bin directory and the 'bin\rosyln' directory. Delete from bin. -->
   <ItemGroup>
     <FilesToDelete Include="$(WebProjectOutputDir)\bin\Microsoft.CodeAnalysis*.dll" />
   </ItemGroup>
   <Delete Files="@(FilesToDelete)" />
</Target>

................... more here ......................

How to define static constant in a class in swift

If I understand your question correctly, you are asking how you can create class level constants (static - in C++ parlance) such that you don't a) replicate the overhead in every instance, and b have to recompute what is otherwise constant.

The language has evolved - as every reader knows, but as I test this in Xcode 6.3.1, the solution is:

import Swift

class MyClass {
    static let testStr = "test"
    static let testStrLen = count(testStr)

    init() {
        println("There are \(MyClass.testStrLen) characters in \(MyClass.testStr)")
    }
}

let a = MyClass()

// -> There are 4 characters in test

I don't know if the static is strictly necessary as the compiler surely only adds only one entry per const variable into the static section of the binary, but it does affect syntax and access. By using static, you can refer to it even when you don't have an instance: MyClass.testStrLen.

How to embed fonts in CSS?

I used Ataturk's font like this. I didn't use "TTF" version. I translated orginal font version ("otf" version) to "eot" and "woof" version. Then It works in local but not working when I uploaded the files to server. So I added "TTF" version too like this. Now, It's working on Chrome and Firefox but Internet Explorer still defence. When you installed on your computer "Ataturk" font, then working IE too. But I wanted to use this font without installing.

@font-face {
    font-family: 'Ataturk';
    font-style: normal;
    font-weight: normal;
    src: url('font/ataturk.eot');
    src: local('Ataturk Regular'), url('font/ataturk.ttf') format('truetype'), 
    url('font/ataturk.woff') format('woff');
}

You can see it on my website here: http://www.canotur.com

Insert Unicode character into JavaScript

One option is to put the character literally in your script, e.g.:

const omega = 'O';

This requires that you let the browser know the correct source encoding, see Unicode in JavaScript

However, if you can't or don't want to do this (e.g. because the character is too exotic and can't be expected to be available in the code editor font), the safest option may be to use new-style string escape or String.fromCodePoint:

const omega = '\u{3a9}';

// or:

const omega = String.fromCodePoint(0x3a9);

This is not restricted to UTF-16 but works for all unicode code points. In comparison, the other approaches mentioned here have the following downsides:

  • HTML escapes (const omega = '&#937';): only work when rendered unescaped in an HTML element
  • old style string escapes (const omega = '\u03A9';): restricted to UTF-16
  • String.fromCharCode: restricted to UTF-16

Grant Select on a view not base table when base table is in a different database

The way I have done this is to give the user permission to the tables that I didn't want them to have access to. Then fine tune the select permission in SSMS by only allowing select permission to the columns that are in my view. This way, the select clause on the table is only limited to the columns that they see in the view anyways.

enter image description here

Shaji

How do I extract value from Json

    JSONArray ja = new JSONArray(json);
    JSONObject ob = ja.getJSONObject(0);
    String nh = ob.getString("status");

[ { "status" : "true" } ]

where 'json' is a String and status is the key from which i will get value

find if an integer exists in a list of integers

As long as your list is initialized with values and that value actually exists in the list, then Contains should return true.

I tried the following:

var list = new List<int> {1,2,3,4,5};
var intVar = 4;
var exists = list.Contains(intVar);

And exists is indeed set to true.

How can I make an svg scale with its parent container?

Adjusting the currentScale attribute works in IE ( I tested with IE 11), but not in Chrome.

Can we cast a generic object to a custom object type in javascript?

The answer of @PeterOlson may be worked back in the day but it looks like Object.create is changed. I would go for the copy-constructor way like @user166390 said in the comments.
The reason I necromanced this post is because I needed such implementation.

Nowadays we can use Object.assign (credits to @SayanPal solution) & ES6 syntax:

class Person {
  constructor(obj) {
    obj && Object.assign(this, obj);
  }

  getFullName() {
    return `${this.lastName} ${this.firstName}`;
  }
}

Usage:

const newPerson = new Person(person1)
newPerson.getFullName() // -> Freeman Gordon

ES5 answer below

function Person(obj) {
    for(var prop in obj){
        // for safety you can use the hasOwnProperty function
        this[prop] = obj[prop];
    }
}

Usage:

var newPerson = new Person(person1);
console.log(newPerson.getFullName()); // -> Freeman Gordon

Using a shorter version, 1.5 liner:

function Person(){
    if(arguments[0]) for(var prop in arguments[0]) this[prop] = arguments[0][prop];
}

jsfiddle

What is the difference between compare() and compareTo()?

Important Answar
String name;
int roll;

public int compare(Object obj1,Object obj2) { // For Comparator interface
    return obj1.compareTo(obj1);
}

public int compareTo(Object obj1) { // For Comparable Interface
    return obj1.compareTo(obj);
}

Here in return obj1.compareTo(obj1) or return obj1.compareTo(obj) statement only take Object; primitive is not allowed. For Example

name.compareTo(obj1.getName()) // Correct Statement.

But

roll.compareTo(obj1.getRoll()) 
// Wrong Statement Compile Time Error Because roll 
// is not an Object Type, it is primitive type.

name is String Object so it worked. If you want to sort roll number of student than use below code.

public int compareTo(Object obj1) { // For Comparable Interface
    Student s = (Student) obj1;
    return rollno - s.getRollno();
}  

or

public int compare(Object obj1,Object obj2) { // For Comparator interface
    Student s1 = (Student) obj1;
    Student s2 = (Student) obj2;
    return s1.getRollno() - s2.getRollno();
}  

What does the [Flags] Enum Attribute mean in C#?

Combining answers https://stackoverflow.com/a/8462/1037948 (declaration via bit-shifting) and https://stackoverflow.com/a/9117/1037948 (using combinations in declaration) you can bit-shift previous values rather than using numbers. Not necessarily recommending it, but just pointing out you can.

Rather than:

[Flags]
public enum Options : byte
{
    None    = 0,
    One     = 1 << 0,   // 1
    Two     = 1 << 1,   // 2
    Three   = 1 << 2,   // 4
    Four    = 1 << 3,   // 8

    // combinations
    OneAndTwo = One | Two,
    OneTwoAndThree = One | Two | Three,
}

You can declare

[Flags]
public enum Options : byte
{
    None    = 0,
    One     = 1 << 0,       // 1
    // now that value 1 is available, start shifting from there
    Two     = One << 1,     // 2
    Three   = Two << 1,     // 4
    Four    = Three << 1,   // 8

    // same combinations
    OneAndTwo = One | Two,
    OneTwoAndThree = One | Two | Three,
}

Confirming with LinqPad:

foreach(var e in Enum.GetValues(typeof(Options))) {
    string.Format("{0} = {1}", e.ToString(), (byte)e).Dump();
}

Results in:

None = 0
One = 1
Two = 2
OneAndTwo = 3
Three = 4
OneTwoAndThree = 7
Four = 8

Get file size before uploading

You can use PHP filesize function. During upload using ajax, please check the filesize first by making a request an ajax request to php script that checks the filesize and return the value.

How do we count rows using older versions of Hibernate (~2009)?

You could try count(*)

Integer count = (Integer) session.createQuery("select count(*) from Books").uniqueResult();

Where Books is the name off the class - not the table in the database.

Why do we have to normalize the input for an artificial neural network?

Looking at the neural network from the outside, it is just a function that takes some arguments and produces a result. As with all functions, it has a domain (i.e. a set of legal arguments). You have to normalize the values that you want to pass to the neural net in order to make sure it is in the domain. As with all functions, if the arguments are not in the domain, the result is not guaranteed to be appropriate.

The exact behavior of the neural net on arguments outside of the domain depends on the implementation of the neural net. But overall, the result is useless if the arguments are not within the domain.

How to put a delay on AngularJS instant search?

Angular 1.3 will have ng-model-options debounce, but until then, you have to use a timer like Josue Ibarra said. However, in his code he launches a timer on every key press. Also, he is using setTimeout, when in Angular one has to use $timeout or use $apply at the end of setTimeout.

Encoding URL query parameters in Java

String param="2019-07-18 19:29:37";
param="%27"+param.trim().replace(" ", "%20")+"%27";

I observed in case of Datetime (Timestamp) URLEncoder.encode(param,"UTF-8") does not work.

How to initialise memory with new operator in C++?

It's a surprisingly little-known feature of C++ (as evidenced by the fact that no-one has given this as an answer yet), but it actually has special syntax for value-initializing an array:

new int[10]();

Note that you must use the empty parentheses — you cannot, for example, use (0) or anything else (which is why this is only useful for value initialization).

This is explicitly permitted by ISO C++03 5.3.4[expr.new]/15, which says:

A new-expression that creates an object of type T initializes that object as follows:

...

  • If the new-initializer is of the form (), the item is value-initialized (8.5);

and does not restrict the types for which this is allowed, whereas the (expression-list) form is explicitly restricted by further rules in the same section such that it does not allow array types.

How to create an empty DataFrame with a specified schema?

Here is a solution that creates an empty dataframe in pyspark 2.0.0 or more.

from pyspark.sql import SQLContext
sc = spark.sparkContext
schema = StructType([StructField('col1', StringType(),False),StructField('col2', IntegerType(), True)])
sqlContext.createDataFrame(sc.emptyRDD(), schema)

Configuring Log4j Loggers Programmatically

If someone comes looking for configuring log4j2 programmatically in Java, then this link could help: (https://www.studytonight.com/post/log4j2-programmatic-configuration-in-java-class)

Here is the basic code for configuring a Console Appender:

ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();

builder.setStatusLevel(Level.DEBUG);
// naming the logger configuration
builder.setConfigurationName("DefaultLogger");

// create a console appender
AppenderComponentBuilder appenderBuilder = builder.newAppender("Console", "CONSOLE")
                .addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
// add a layout like pattern, json etc
appenderBuilder.add(builder.newLayout("PatternLayout")
                .addAttribute("pattern", "%d %p %c [%t] %m%n"));
RootLoggerComponentBuilder rootLogger = builder.newRootLogger(Level.DEBUG);
rootLogger.add(builder.newAppenderRef("Console"));

builder.add(appenderBuilder);
builder.add(rootLogger);
Configurator.reconfigure(builder.build());

This will reconfigure the default rootLogger and will also create a new appender.

import sun.misc.BASE64Encoder results in error compiled in Eclipse

Sure - just don't use the Sun base64 encoder/decoder. There are plenty of other options available, including Apache Codec or this public domain implementation.

Then read why you shouldn't use sun.* packages.

Error in launching AVD with AMD processor

While creating a Virtual Device select the ARM system Image. Others have suggested to install HAXM, but the truth is haxm wont work on amd platform or even if it does as android studio does not supports amd-vt on windows the end result will still be a very very slow emulator to run and operate. My recommendation would be to either use alternative emulator like Genymotion (works like a charm with Gapps installed) or switch to linux as then you will get the benefit of amd-vt and emulator will run a lot faster.

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

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

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

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

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

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

Using JQuery hover with HTML image map

You should check out this plugin:

https://github.com/kemayo/maphilight

and the demo:

http://davidlynch.org/js/maphilight/docs/demo_usa.html

if anything, you might be able to borrow some code from it to fix yours.

"elseif" syntax in JavaScript

You could use this syntax which is functionally equivalent:

switch (true) {
  case condition1:
     //e.g. if (condition1 === true)
     break;
  case condition2:
     //e.g. elseif (condition2 === true)
     break;
  default:
     //e.g. else
}

This works because each condition is fully evaluated before comparison with the switch value, so the first one that evaluates to true will match and its branch will execute. Subsequent branches will not execute, provided you remember to use break.

Note that strict comparison is used, so a branch whose condition is merely "truthy" will not be executed. You can cast a truthy value to true with double negation: !!condition.

How to amend a commit without changing commit message (reusing the previous one)?

just to add some clarity, you need to stage changes with git add, then amend last commit:

git add /path/to/modified/files
git commit --amend --no-edit

This is especially useful for if you forgot to add some changes in last commit or when you want to add more changes without creating new commits by reusing the last commit.

SQL Server remove milliseconds from datetime

Use 'Smalldatetime' data type

select convert(smalldatetime, getdate())

will fetch

2015-01-08 15:27:00

Is it possible to deserialize XML into List<T>?

If you decorate the User class with the XmlType to match the required capitalization:

[XmlType("user")]
public class User
{
   ...
}

Then the XmlRootAttribute on the XmlSerializer ctor can provide the desired root and allow direct reading into List<>:

    // e.g. my test to create a file
    using (var writer = new FileStream("users.xml", FileMode.Create))
    {
        XmlSerializer ser = new XmlSerializer(typeof(List<User>),  
            new XmlRootAttribute("user_list"));
        List<User> list = new List<User>();
        list.Add(new User { Id = 1, Name = "Joe" });
        list.Add(new User { Id = 2, Name = "John" });
        list.Add(new User { Id = 3, Name = "June" });
        ser.Serialize(writer, list);
    }

...

    // read file
    List<User> users;
    using (var reader = new StreamReader("users.xml"))
    {
        XmlSerializer deserializer = new XmlSerializer(typeof(List<User>),  
            new XmlRootAttribute("user_list"));
        users = (List<User>)deserializer.Deserialize(reader);
    }

Credit: based on answer from YK1.

How to set dropdown arrow in spinner?

Set the Dropdown arrow image to spinner like this :

<Spinner
    android:id="@+id/Exam_Course"
    android:layout_width="320dp"
    android:background="@drawable/spinner_bg"
    android:layout_height="wrap_content"/>

Here android:background="@drawable/spinner_bg" the spinner_bg is the Dropdown arrow image.

Loop through files in a folder using VBA?

Dir seems to be very fast.

Sub LoopThroughFiles()
    Dim MyObj As Object, MySource As Object, file As Variant
   file = Dir("c:\testfolder\")
   While (file <> "")
      If InStr(file, "test") > 0 Then
         MsgBox "found " & file
         Exit Sub
      End If
     file = Dir
  Wend
End Sub

What is the Python equivalent for a case/switch statement?

While the official docs are happy not to provide switch, I have seen a solution using dictionaries.

For example:

# define the function blocks
def zero():
    print "You typed zero.\n"

def sqr():
    print "n is a perfect square\n"

def even():
    print "n is an even number\n"

def prime():
    print "n is a prime number\n"

# map the inputs to the function blocks
options = {0 : zero,
           1 : sqr,
           4 : sqr,
           9 : sqr,
           2 : even,
           3 : prime,
           5 : prime,
           7 : prime,
}

Then the equivalent switch block is invoked:

options[num]()

This begins to fall apart if you heavily depend on fall through.

SyntaxError: Non-ASCII character '\xa3' in file when function returns '£'

Adding the following two lines in the script solved the issue for me.

# !/usr/bin/python
# coding=utf-8

Hope it helps !

JavaScript file not updating no matter what I do

1.Clear browser cache in browser developer tools 2.Under Network tab – select Disable cache option 3.Restarted browser 4.Force reload Js file command+shift+R in mac   Make sure the fresh war is deployed properly on the Server side

Decoding a Base64 string in Java

Commonly base64 it is used for images. if you like to decode an image (jpg in this example with org.apache.commons.codec.binary.Base64 package):

byte[] decoded = Base64.decodeBase64(imageJpgInBase64);
FileOutputStream fos = null;
fos = new FileOutputStream("C:\\output\\image.jpg");
fos.write(decoded);
fos.close();

Force Java timezone as GMT/UTC

I had to set the JVM timezone for Windows 2003 Server because it always returned GMT for new Date();

-Duser.timezone=America/Los_Angeles

Or your appropriate time zone. Finding a list of time zones proved to be a bit challenging also...

Here are two list;

http://wrapper.tanukisoftware.com/doc/english/prop-timezone.html

http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=%2Frzatz%2F51%2Fadmin%2Freftz.htm

C# find highest array value and index

A succinct one-liner:

var max = anArray.Select((n, i) => (Number: n, Index: i)).Max();

Test case:

var anArray = new int[] { 1, 5, 7, 4, 2 };
var max = anArray.Select((n, i) => (Number: n, Index: i)).Max();
Console.WriteLine($"Maximum number = {max.Number}, on index {max.Index}.");
// Maximum number = 7, on index 2.

Features:

  • Uses Linq (not as optimized as vanilla, but the trade-off is less code).
  • Does not need to sort.
  • Computational complexity: O(n).
  • Space complexity: O(n).

Remarks:

  • Make sure the number (and not the index) is the first element in the tuple because tuple sorting is done by comparing tuple items from left to right.

Get the data received in a Flask request

If you post JSON with content type application/json, use request.get_json() to get it in Flask. If the content type is not correct, None is returned. If the data is not JSON, an error is raised.

@app.route("/something", methods=["POST"])
def do_something():
    data = request.get_json()

window.location.href not working

The browser is still submitting the form after your code runs.

Add return false; to the handler to prevent that.

Which are more performant, CTE or temporary tables?

One use where I found CTE's excelled performance wise was where I needed to join a relatively complex Query on to a few tables which had a few million rows each.

I used the CTE to first select the subset based of the indexed columns to first cut these tables down to a few thousand relevant rows each and then joined the CTE to my main query. This exponentially reduced the runtime of my query.

Whilst results for the CTE are not cached and table variables might have been a better choice I really just wanted to try them out and found the fit the above scenario.

Cannot execute RUN mkdir in a Dockerfile

When creating subdirectories hanging off from a non-existing parent directory(s) you must pass the -p flag to mkdir ... Please update your Dockerfile with

RUN mkdir -p ... 

I tested this and it's correct.

Method to Add new or update existing item in Dictionary

The only problem could be if one day

map[key] = value

will transform to -

map[key]++;

and that will cause a KeyNotFoundException.

Which Android phones out there do have a gyroscope?

Since I have recently developed an Android application using gyroscope data (steady compass), I tried to collect a list with such devices. This is not an exhaustive list at all, but it is what I have so far:

*** Phones:

  • HTC Sensation
  • HTC Sensation XL
  • HTC Evo 3D
  • HTC One S
  • HTC One X
  • Huawei Ascend P1
  • Huawei Ascend X (U9000)
  • Huawei Honor (U8860)
  • LG Nitro HD (P930)
  • LG Optimus 2x (P990)
  • LG Optimus Black (P970)
  • LG Optimus 3D (P920)
  • Samsung Galaxy S II (i9100)
  • Samsung Galaxy S III (i9300)
  • Samsung Galaxy R (i9103)
  • Samsung Google Nexus S (i9020)
  • Samsung Galaxy Nexus (i9250)
  • Samsung Galaxy J3 (2017) model
  • Samsung Galaxy Note (n7000)
  • Sony Xperia P (LT22i)
  • Sony Xperia S (LT26i)

*** Tablets:

  • Acer Iconia Tab A100 (7")
  • Acer Iconia Tab A500 (10.1")
  • Asus Eee Pad Transformer (TF101)
  • Asus Eee Pad Transformer Prime (TF201)
  • Motorola Xoom (mz604)
  • Samsung Galaxy Tab (p1000)
  • Samsung Galaxy Tab 7 plus (p6200)
  • Samsung Galaxy Tab 10.1 (p7100)
  • Sony Tablet P
  • Sony Tablet S
  • Toshiba Thrive 7"
  • Toshiba Trhive 10"

Hope the list keeps growing and hope that gyros will be soon available on mid and low price smartphones.

How can I rotate an HTML <div> 90 degrees?

Use transform: rotate(90deg):

_x000D_
_x000D_
#container_2 {_x000D_
    border: 1px solid;_x000D_
    padding: .5em;_x000D_
    width: 5em;_x000D_
    height: 5em;_x000D_
    transition: .3s all;  /* rotate gradually instead of instantly */_x000D_
}_x000D_
_x000D_
#container_2:hover {_x000D_
    -webkit-transform: rotate(90deg);  /* to support Safari and Android browser */_x000D_
    -ms-transform: rotate(90deg);      /* to support IE 9 */_x000D_
    transform: rotate(90deg);_x000D_
}
_x000D_
<div id="container_2">This box should be rotated 90&deg; on hover.</div>
_x000D_
_x000D_
_x000D_

Click "Run code snippet", then hover over the box to see the effect of the transform.

Realistically, no other prefixed entries are needed. See Can I use CSS3 Transforms?

Proper way to catch exception from JSON.parse

This promise will not resolve if the argument of JSON.parse() can not be parsed into a JSON object.

Promise.resolve(JSON.parse('{"key":"value"}')).then(json => {
    console.log(json);
}).catch(err => {
    console.log(err);
});

Eclipse won't compile/run java file

right click somewhere on the file or in project explorer and choose 'run as'->'java application'

The container 'Maven Dependencies' references non existing library - STS

I have solved it using "force update", pressing Alt+F5 as it is mentioned in the following link.

Running SSH Agent when starting Git Bash on Windows

I found the smoothest way to achieve this was using Pageant as the SSH agent and plink.

You need to have a putty session configured for the hostname that is used in your remote.

You will also need plink.exe which can be downloaded from the same site as putty.

And you need Pageant running with your key loaded. I have a shortcut to pageant in my startup folder that loads my SSH key when I log in.

When you install git-scm you can then specify it to use tortoise/plink rather than OpenSSH.

The net effect is you can open git-bash whenever you like and push/pull without being challenged for passphrases.

Same applies with putty and WinSCP sessions when pageant has your key loaded. It makes life a hell of a lot easier (and secure).

HTTP Status 404 - The requested resource (/) is not available

Following steps helped me solve the issue.

  1. In the eclipse right click on server and click on properties.
  2. If Location is set workspace/metadata click on switch location and so that it refers to /servers/tomcatv7server at localhost.server
  3. Save and close
  4. Next double click on server
  5. Under server locations mostly it would be selected as use workspace metadata Instead, select use tomcat installation
  6. Save changes
  7. Restart server and verify localhost:8080 works.

Get img thumbnails from Vimeo?

If you would like to use thumbnail through pure js/jquery no api, you can use this tool to capture a frame from the video and voila! Insert url thumb in which ever source you like.

Here is a code pen :

http://codepen.io/alphalink/pen/epwZpJ

<img src="https://i.vimeocdn.com/video/531141496_640.jpg"` alt="" />

Here is the site to get thumbnail:

http://video.depone.eu/

Python: How to ignore an exception and proceed?

Try this:

try:
    blah()
except:
    pass

What is Parse/parsing?

Parsing can be considered as a synonym of "Breaking down into small pieces" and then analysing what is there or using it in a modified way. In Java, Strings are parsed into Decimal, Octal, Binary, Hexadecimal, etc. It is done if your application is taking input from the user in the form of string but somewhere in your application you want to use that input in the form of an integer or of double type. It is not same as type casting. For type casting the types used should be compatible in order to caste but nothing such in parsing.

Create a file from a ByteArrayOutputStream

You can do it with using a FileOutputStream and the writeTo method.

ByteArrayOutputStream byteArrayOutputStream = getByteStreamMethod();
try(OutputStream outputStream = new FileOutputStream("thefilename")) {
    byteArrayOutputStream.writeTo(outputStream);
}

Source: "Creating a file from ByteArrayOutputStream in Java." on Code Inventions

What is the difference between a mutable and immutable string in C#?

Immutable :

When you do some operation on a object, it creates a new object hence state is not modifiable as in case of string.

Mutable

When you perform some operation on a object, object itself modified no new obect created as in case of StringBuilder

CSS image resize percentage of itself?

This actually is possible, and I discovered how quite by accident while designing my first large-scale responsive design site.

<div class="wrapper">
  <div class="box">
    <img src="/logo.png" alt="">
  </div>
</div>

.wrapper { position:relative; overflow:hidden; }

.box { float:left; } //Note: 'float:right' would work too

.box > img { width:50%; }

The overflow:hidden gives the wrapper height and width, despite the floating contents, without using the clearfix hack. You can then position your content using margins. You can even make the wrapper div an inline-block.

convert from Color to brush

SolidColorBrush brush = new SolidColorBrush( Color.FromArgb(255,255,139,0) )

PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

From the XAMPP panel, click on the ADMIN button on the Apache site. Then choose to edit php.ini And add the missing post_max_size to a value you are comfortable with.

post_max_size = 100M

Using Gradle to build a jar with dependencies

I use task shadowJar by plugin . com.github.jengelman.gradle.plugins:shadow:5.2.0

Usage just run ./gradlew app::shadowJar result file will be at MyProject/app/build/libs/shadow.jar

top level build.gradle file :

 apply plugin: 'kotlin'

buildscript {
    ext.kotlin_version = '1.3.61'

    repositories {
        mavenLocal()
        mavenCentral()
        jcenter()
    }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.github.jengelman.gradle.plugins:shadow:5.2.0'
    }
}

app module level build.gradle file

apply plugin: 'java'
apply plugin: 'kotlin'
apply plugin: 'kotlin-kapt'
apply plugin: 'application'
apply plugin: 'com.github.johnrengelman.shadow'

sourceCompatibility = 1.8

kapt {
    generateStubs = true
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation "org.seleniumhq.selenium:selenium-java:4.0.0-alpha-4"
    shadow "org.seleniumhq.selenium:selenium-java:4.0.0-alpha-4"

    implementation project(":module_remote")
    shadow project(":module_remote")
}

jar {
    exclude 'META-INF/*.SF', 'META-INF/*.DSA', 'META-INF/*.RSA', 'META-INF/*.MF'
    manifest {
        attributes(
                'Main-Class': 'com.github.kolyall.TheApplication',
                'Class-Path': configurations.compile.files.collect { "lib/$it.name" }.join(' ')
        )
    }
}

shadowJar {
    baseName = 'shadow'
    classifier = ''
    archiveVersion = ''
    mainClassName = 'com.github.kolyall.TheApplication'

    mergeServiceFiles()
}

Asynchronous file upload (AJAX file upload) using jsp and javascript

The latest dwr (http://directwebremoting.org/dwr/index.html) has ajax file uploads, complete with examples and nice stuff for users (like progress indicators and such).

It looks pretty nifty and dwr is fairly easy to use in general so this will be pretty good as well.

How to call a SOAP web service on Android

Follow these steps by the method SOAP

From the WSDL file,

  • create SOAP Request templates for each Request.

  • Then substitute the values to be passed in code.

  • POST this data to the service end point using DefaultHttpClient instance.

  • Get the response stream and finally

  • Parse the Response Stream using an XML Pull parser.

Javascript onclick hide div

just add onclick handler for anchor tag

onclick="this.parentNode.style.display = 'none'"

or change onclick handler for img tag

onclick="this.parentNode.parentNode.style.display = 'none'"

Disabling user input for UITextfield in swift

Another solution, declare your controller as UITextFieldDelegate, implement this call-back:

@IBOutlet weak var myTextField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    myTextField.delegate = self
}

func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
    if textField == myTextField {
        return false; //do not show keyboard nor cursor
    }
    return true
}

Asynchronous Requests with Python requests

Unfortunately, as far as I know, the requests library is not equipped for performing asynchronous requests. You can wrap async/await syntax around requests, but that will make the underlying requests no less synchronous. If you want true async requests, you must use other tooling that provides it. One such solution is aiohttp (Python 3.5.3+). It works well in my experience using it with the Python 3.7 async/await syntax. Below I write three implementations of performing n web requests using

  1. Purely synchronous requests (sync_requests_get_all) using the Python requests library
  2. Synchronous requests (async_requests_get_all) using the Python requests library wrapped in Python 3.7 async/await syntax and asyncio
  3. A truly asynchronous implementation (async_aiohttp_get_all) with the Python aiohttp library wrapped in Python 3.7 async/await syntax and asyncio
import time
import asyncio
import requests
import aiohttp

from types import SimpleNamespace

durations = []


def timed(func):
    """
    records approximate durations of function calls
    """
    def wrapper(*args, **kwargs):
        start = time.time()
        print(f'{func.__name__:<30} started')
        result = func(*args, **kwargs)
        duration = f'{func.__name__:<30} finished in {time.time() - start:.2f} seconds'
        print(duration)
        durations.append(duration)
        return result
    return wrapper


async def fetch(url, session):
    """
    asynchronous get request
    """
    async with session.get(url) as response:
        response_json = await response.json()
        return SimpleNamespace(**response_json)


async def fetch_many(loop, urls):
    """
    many asynchronous get requests, gathered
    """
    async with aiohttp.ClientSession() as session:
        tasks = [loop.create_task(fetch(url, session)) for url in urls]
        return await asyncio.gather(*tasks)

@timed
def sync_requests_get_all(urls):
    """
    performs synchronous get requests
    """
    # use session to reduce network overhead
    session = requests.Session()
    return [SimpleNamespace(**session.get(url).json()) for url in urls]


@timed
def async_requests_get_all(urls):
    """
    asynchronous wrapper around synchronous requests
    """
    loop = asyncio.get_event_loop()
    # use session to reduce network overhead
    session = requests.Session()

    async def async_get(url):
        return session.get(url)

    async_tasks = [loop.create_task(async_get(url)) for url in urls]
    return loop.run_until_complete(asyncio.gather(*async_tasks))


@timed
def asnyc_aiohttp_get_all(urls):
    """
    performs asynchronous get requests
    """
    loop = asyncio.get_event_loop()
    return loop.run_until_complete(fetch_many(loop, urls))


if __name__ == '__main__':
    # this endpoint takes ~3 seconds to respond,
    # so a purely synchronous implementation should take
    # little more than 30 seconds and a purely asynchronous
    # implementation should take little more than 3 seconds.
    urls = ['https://postman-echo.com/delay/3']*10

    sync_requests_get_all(urls)
    async_requests_get_all(urls)
    asnyc_aiohttp_get_all(urls)
    print('----------------------')
    [print(duration) for duration in durations]

On my machine, this is the output:

sync_requests_get_all          started
sync_requests_get_all          finished in 30.92 seconds
async_requests_get_all         started
async_requests_get_all         finished in 30.87 seconds
asnyc_aiohttp_get_all          started
asnyc_aiohttp_get_all          finished in 3.22 seconds
----------------------
sync_requests_get_all          finished in 30.92 seconds
async_requests_get_all         finished in 30.87 seconds
asnyc_aiohttp_get_all          finished in 3.22 seconds

How do I import from Excel to a DataSet using Microsoft.Office.Interop.Excel?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;
using Microsoft.Office.Interop.Excel;

namespace trg.satmap.portal.ParseAgentSkillMapping
{
    class ConvertXLStoDT
    {
        private StringBuilder errorMessages;

        public StringBuilder ErrorMessages
        {
            get { return errorMessages; }
            set { errorMessages = value; }
        }

        public ConvertXLStoDT()
        {
            ErrorMessages = new StringBuilder();
        }

        public System.Data.DataTable XLStoDTusingInterOp(string FilePath)
        {
            #region Excel important Note.
            /*
             * Excel creates XLS and XLSX files. These files are hard to read in C# programs. 
             * They are handled with the Microsoft.Office.Interop.Excel assembly. 
             * This assembly sometimes creates performance issues. Step-by-step instructions are helpful.
             * 
             * Add the Microsoft.Office.Interop.Excel assembly by going to Project -> Add Reference.
             */
            #endregion

            Microsoft.Office.Interop.Excel.Application excelApp = null;
            Microsoft.Office.Interop.Excel.Workbook workbook = null;


            System.Data.DataTable dt = new System.Data.DataTable(); //Creating datatable to read the content of the Sheet in File.

            try
            {

                excelApp = new Microsoft.Office.Interop.Excel.Application(); // Initialize a new Excel reader. Must be integrated with an Excel interface object.

                //Opening Excel file(myData.xlsx)
                workbook = excelApp.Workbooks.Open(FilePath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

                Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets.get_Item(1);

                Microsoft.Office.Interop.Excel.Range excelRange = ws.UsedRange; //gives the used cells in sheet

                ws = null; // now No need of this so should expire.

                //Reading Excel file.               
                object[,] valueArray = (object[,])excelRange.get_Value(Microsoft.Office.Interop.Excel.XlRangeValueDataType.xlRangeValueDefault);

                excelRange = null; // you don't need to do any more Interop. Now No need of this so should expire.

                dt = ProcessObjects(valueArray);                

            }
            catch (Exception ex)
            {
                ErrorMessages.Append(ex.Message);
            }
            finally
            {
                #region Clean Up                
                if (workbook != null)
                {
                    #region Clean Up Close the workbook and release all the memory.
                    workbook.Close(false, FilePath, Missing.Value);                    
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
                    #endregion
                }
                workbook = null;

                if (excelApp != null)
                {
                    excelApp.Quit();
                }
                excelApp = null;                

                #endregion
            }
            return (dt);
        }

        /// <summary>
        /// Scan the selected Excel workbook and store the information in the cells
        /// for this workbook in an object[,] array. Then, call another method
        /// to process the data.
        /// </summary>
        private void ExcelScanIntenal(Microsoft.Office.Interop.Excel.Workbook workBookIn)
        {
            //
            // Get sheet Count and store the number of sheets.
            //
            int numSheets = workBookIn.Sheets.Count;

            //
            // Iterate through the sheets. They are indexed starting at 1.
            //
            for (int sheetNum = 1; sheetNum < numSheets + 1; sheetNum++)
            {
                Worksheet sheet = (Worksheet)workBookIn.Sheets[sheetNum];

                //
                // Take the used range of the sheet. Finally, get an object array of all
                // of the cells in the sheet (their values). You can do things with those
                // values. See notes about compatibility.
                //
                Range excelRange = sheet.UsedRange;
                object[,] valueArray = (object[,])excelRange.get_Value(XlRangeValueDataType.xlRangeValueDefault);

                //
                // Do something with the data in the array with a custom method.
                //
                ProcessObjects(valueArray);
            }
        }
        private System.Data.DataTable ProcessObjects(object[,] valueArray)
        {
            System.Data.DataTable dt = new System.Data.DataTable();

            #region Get the COLUMN names

            for (int k = 1; k <= valueArray.GetLength(1); k++)
            {
                dt.Columns.Add((string)valueArray[1, k]);  //add columns to the data table.
            }
            #endregion

            #region Load Excel SHEET DATA into data table

            object[] singleDValue = new object[valueArray.GetLength(1)];
            //value array first row contains column names. so loop starts from 2 instead of 1
            for (int i = 2; i <= valueArray.GetLength(0); i++)
            {
                for (int j = 0; j < valueArray.GetLength(1); j++)
                {
                    if (valueArray[i, j + 1] != null)
                    {
                        singleDValue[j] = valueArray[i, j + 1].ToString();
                    }
                    else
                    {
                        singleDValue[j] = valueArray[i, j + 1];
                    }
                }
                dt.LoadDataRow(singleDValue, System.Data.LoadOption.PreserveChanges);
            }
            #endregion


            return (dt);
        }
    }
}

Calculating percentile of dataset column

The quantile() function will do much of what you probably want, but since the question was ambiguous, I will provide an alternate answer that does something slightly different from quantile().

ecdf(infert$age)(infert$age)

will generate a vector of the same length as infert$age giving the proportion of infert$age that is below each observation. You can read the ecdf documentation, but the basic idea is that ecdf() will give you a function that returns the empirical cumulative distribution. Thus ecdf(X)(Y) is the value of the cumulative distribution of X at the points in Y. If you wanted to know just the probability of being below 30 (thus what percentile 30 is in the sample), you could say

ecdf(infert$age)(30)

The main difference between this approach and using the quantile() function is that quantile() requires that you put in the probabilities to get out the levels, and this requires that you put in the levels to get out the probabilities.

Where can I find the assembly System.Web.Extensions dll?

Your project is mostly likely targetting .NET Framework 4 Client Profile. Check the application tab in your project properties.

This question has a good answer on the different versions: Target framework, what does ".NET Framework ... Client Profile" mean?

Java - Check if JTextField is empty or not

if(name.getText().hashCode() != 0){
    JOptionPane.showMessageDialog(null, "not empty");
}
else{
    JOptionPane.showMessageDialog(null, "empty");
}

How can I generate a tsconfig.json file?

If you don't want to install Typescript globally (which makes sense to me, so you don't need to update it constantly), you can use npx:

npx -p typescript tsc --init

The key point is using the -p flag to inform npx that the tsc binary belongs to the typescript package

Visual Studio 2008 Product Key in Registry?

I found the product key for Visual Studio 2008 Professional under a slightly different key:

HKLM\SOFTWARE\Wow6432Node\Microsoft\MSDN\8.0\Registration\PIDKEY

it was listed without the dashes as stated above.

Shall we always use [unowned self] inside closure in Swift

There are some great answers here. But recent changes to how Swift implements weak references should change everyone's weak self vs. unowned self usage decisions. Previously, if you needed the best performance using unowned self was superior to weak self, as long as you could be certain that self would never be nil, because accessing unowned self is much faster than accessing weak self.

But Mike Ash has documented how Swift has updated the implementation of weak vars to use side-tables and how this substantially improves weak self performance.

https://mikeash.com/pyblog/friday-qa-2017-09-22-swift-4-weak-references.html

Now that there isn't a significant performance penalty to weak self, I believe we should default to using it going forward. The benefit of weak self is that it's an optional, which makes it far easier to write more correct code, it's basically the reason Swift is such a great language. You may think you know which situations are safe for the use of unowned self, but my experience reviewing lots of other developers code is, most don't. I've fixed lots of crashes where unowned self was deallocated, usually in situations where a background thread completes after a controller is deallocated.

Bugs and crashes are the most time-consuming, painful and expensive parts of programming. Do your best to write correct code and avoid them. I recommend making it a rule to never force unwrap optionals and never use unowned self instead of weak self. You won't lose anything missing the times force unwrapping and unowned self actually are safe. But you'll gain a lot from eliminating hard to find and debug crashes and bugs.

fastest way to export blobs from table into individual files

I tried using a CLR function and it was more than twice as fast as BCP. Here's my code.

Original Method:

SET @bcpCommand = 'bcp "SELECT blobcolumn FROM blobtable WHERE ID = ' + CAST(@FileID AS VARCHAR(20)) + '" queryout "' + @FileName + '" -T -c'
EXEC master..xp_cmdshell @bcpCommand

CLR Method:

declare @file varbinary(max) = (select blobcolumn from blobtable WHERE ID = @fileid)
declare @filepath nvarchar(4000) = N'c:\temp\' + @FileName
SELECT Master.dbo.WriteToFile(@file, @filepath, 0)

C# Code for the CLR function

using System;
using System.Data;
using System.Data.SqlTypes;
using System.IO;
using Microsoft.SqlServer.Server;

namespace BlobExport
{
    public class Functions
    {
      [SqlFunction]
      public static SqlString WriteToFile(SqlBytes binary, SqlString path, SqlBoolean append)
      {        
        try
        {
          if (!binary.IsNull && !path.IsNull && !append.IsNull)
          {         
            var dir = Path.GetDirectoryName(path.Value);           
            if (!Directory.Exists(dir))              
              Directory.CreateDirectory(dir);            
              using (var fs = new FileStream(path.Value, append ? FileMode.Append : FileMode.OpenOrCreate))
            {
                byte[] byteArr = binary.Value;
                for (int i = 0; i < byteArr.Length; i++)
                {
                    fs.WriteByte(byteArr[i]);
                };
            }
            return "SUCCESS";
          }
          else
             "NULL INPUT";
        }
        catch (Exception ex)
        {          
          return ex.Message;
        }
      }
    }
}

Radio buttons not checked in jQuery

if ( ! $("input").is(':checked') )

Doesn't work?

You might also try iterating over the elements like so:

var iz_checked = true;
$('input').each(function(){
   iz_checked = iz_checked && $(this).is(':checked');
});
if ( ! iz_checked )

Check if application is on its first run

There's no reliable way to detect first run, as the shared preferences way is not always safe, the user can delete the shared preferences data from the settings! a better way is to use the answers here Is there a unique Android device ID? to get the device's unique ID and store it somewhere in your server, so whenever the user launches the app you request the server and check if it's there in your database or it is new.

How to check if a variable is NULL, then set it with a MySQL stored procedure?

@last_run_time is a 9.4. User-Defined Variables and last_run_time datetime one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.

Try: SELECT last_run_time;

UPDATE

Example:

/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$

CREATE PROCEDURE `sp_test`()
BEGIN
    DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
    DECLARE last_run_time DATETIME DEFAULT NULL;
    DECLARE current_run_time DATETIME DEFAULT NOW();

    -- Define the last run time
    SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);

    -- if there is no last run time found then use yesterday as starting point
    IF(last_run_time IS NULL) THEN
        SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
    END IF;

    SELECT last_run_time;

    -- Insert variables in table2
    INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$

DELIMITER ;

c# Image resizing to different size while preserving aspect ratio

public static void resizeImage_n_save(Stream sourcePath, string targetPath, int requiredSize)
    {
        using (var image = System.Drawing.Image.FromStream(sourcePath))
        {
            double ratio = 0;

            var newWidth = 0;
            var newHeight = 0;
            double w = Convert.ToInt32(image.Width);
            double h = Convert.ToInt32(image.Height);
            if (w > h)
            {
                ratio = h / w * 100;
                newWidth = requiredSize;
                newHeight = Convert.ToInt32(requiredSize * ratio / 100);
            }
            else
            {
                ratio = w / h * 100;
                newHeight = requiredSize;
                newWidth = Convert.ToInt32(requiredSize * ratio / 100);
            }

            //   var newWidth = (int)(image.Width * scaleFactor);
            // var newHeight = (int)(image.Height * scaleFactor);
            var thumbnailImg = new Bitmap(newWidth, newHeight);
            var thumbGraph = Graphics.FromImage(thumbnailImg);
            thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
            thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
            thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
            var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);

            thumbGraph.DrawImage(image, imageRectangle);
            thumbnailImg.Save(targetPath, image.RawFormat);

            //var img = FixedSize(image, requiredSize, requiredSize);
            //img.Save(targetPath, image.RawFormat);

        }
    }

Override standard close (X) button in a Windows Form

protected override bool ProcessCmdKey(ref Message msg, Keys dataKey)
    {
        if (dataKey == Keys.Escape)
        {
            this.Close();
            //this.Visible = false;
            //Plus clear values from form, if Visible false.
        }
        return base.ProcessCmdKey(ref msg, dataKey);
    }

Is ASCII code 7-bit or 8-bit?

ASCII encoding is 7-bit, but in practice, characters encoded in ASCII are not stored in groups of 7 bits. Instead, one ASCII is stored in a byte, with the MSB usually set to 0 (yes, it's wasted in ASCII).

You can verify this by inputting a string in the ASCII character set in a text editor, setting the encoding to ASCII, and viewing the binary/hex:
enter image description here

Aside: the use of (strictly) ASCII encoding is now uncommon, in favor of UTF-8 (which does not waste the MSB mentioned above - in fact, an MSB of 1 indicates the code point is encoded with more than 1 byte).

How to run Linux commands in Java?

if the opening in windows

try {
        //chm file address
        String chmFile = System.getProperty("user.dir") + "/chm/sample.chm";
        Desktop.getDesktop().open(new File(chmFile));
    } catch (IOException ex) {
        Logger.getLogger(Frame.class.getName()).log(Level.SEVERE, null, ex);
        {
            JOptionPane.showMessageDialog(null, "Terjadi Kesalahan", "Error", JOptionPane.WARNING_MESSAGE);
        }
    }

Peak signal detection in realtime timeseries data

Thought I would provide my Julia implementation of the algorithm for others. The gist can be found here

using Statistics
using Plots
function SmoothedZscoreAlgo(y, lag, threshold, influence)
    # Julia implimentation of http://stackoverflow.com/a/22640362/6029703
    n = length(y)
    signals = zeros(n) # init signal results
    filteredY = copy(y) # init filtered series
    avgFilter = zeros(n) # init average filter
    stdFilter = zeros(n) # init std filter
    avgFilter[lag - 1] = mean(y[1:lag]) # init first value
    stdFilter[lag - 1] = std(y[1:lag]) # init first value

    for i in range(lag, stop=n-1)
        if abs(y[i] - avgFilter[i-1]) > threshold*stdFilter[i-1]
            if y[i] > avgFilter[i-1]
                signals[i] += 1 # postive signal
            else
                signals[i] += -1 # negative signal
            end
            # Make influence lower
            filteredY[i] = influence*y[i] + (1-influence)*filteredY[i-1]
        else
            signals[i] = 0
            filteredY[i] = y[i]
        end
        avgFilter[i] = mean(filteredY[i-lag+1:i])
        stdFilter[i] = std(filteredY[i-lag+1:i])
    end
    return (signals = signals, avgFilter = avgFilter, stdFilter = stdFilter)
end


# Data
y = [1,1,1.1,1,0.9,1,1,1.1,1,0.9,1,1.1,1,1,0.9,1,1,1.1,1,1,1,1,1.1,0.9,1,1.1,1,1,0.9,
       1,1.1,1,1,1.1,1,0.8,0.9,1,1.2,0.9,1,1,1.1,1.2,1,1.5,1,3,2,5,3,2,1,1,1,0.9,1,1,3,
       2.6,4,3,3.2,2,1,1,0.8,4,4,2,2.5,1,1,1]

# Settings: lag = 30, threshold = 5, influence = 0
lag = 30
threshold = 5
influence = 0

results = SmoothedZscoreAlgo(y, lag, threshold, influence)
upper_bound = results[:avgFilter] + threshold * results[:stdFilter]
lower_bound = results[:avgFilter] - threshold * results[:stdFilter]
x = 1:length(y)

yplot = plot(x,y,color="blue", label="Y",legend=:topleft)
yplot = plot!(x,upper_bound, color="green", label="Upper Bound",legend=:topleft)
yplot = plot!(x,results[:avgFilter], color="cyan", label="Average Filter",legend=:topleft)
yplot = plot!(x,lower_bound, color="green", label="Lower Bound",legend=:topleft)
signalplot = plot(x,results[:signals],color="red",label="Signals",legend=:topleft)
plot(yplot,signalplot,layout=(2,1),legend=:topleft)

Results

SQL JOIN, GROUP BY on three tables to get totals

I know this is late, but it does answer your original question.

/*Read the comments the same way that SQL runs the query
    1) FROM 
    2) GROUP 
    3) SELECT 
    4) My final notes at the bottom 
*/
SELECT 
        list.invoiceid
    ,   cust.customernumber 
    ,   MAX(list.inv_amount) AS invoice_amount/* we select the max because it will be the same for each payment to that invoice (presumably invoice amounts do not vary based on payment) */
    ,   MAX(list.inv_amount) - SUM(list.pay_amount)  AS [amount_due]
FROM 
Customers AS cust 
    INNER JOIN 
Payments  AS pay 
    ON 
        pay.customerid = cust.customerid
INNER JOIN  (   /* generate a list of payment_ids, their amounts, and the totals of the invoices they billed to*/
    SELECT 
            inpay.paymentid AS paymentid
        ,   inv.invoiceid AS invoiceid 
        ,   inv.amount  AS inv_amount 
        ,   pay.amount AS pay_amount 
    FROM 
    InvoicePayments AS inpay
        INNER JOIN 
    Invoices AS inv 
        ON  inv.invoiceid = inpay.invoiceid 
        INNER JOIN 
    Payments AS pay 
        ON pay.paymentid = inpay.paymentid
    )  AS list
ON 
    list.paymentid = pay.paymentid
    /* so at this point my result set would look like: 
    -- All my customers (crossed by) every paymentid they are associated to (I'll call this A)
    -- Every invoice payment and its association to: its own ammount, the total invoice ammount, its own paymentid (what I call list) 
    -- Filter out all records in A that do not have a paymentid matching in (list)
     -- we filter the result because there may be payments that did not go towards invoices!
 */
GROUP BY
    /* we want a record line for each customer and invoice ( or basically each invoice but i believe this makes more sense logically */ 
        cust.customernumber 
    ,   list.invoiceid 
/*
    -- we can improve this query by only hitting the Payments table once by moving it inside of our list subquery, 
    -- but this is what made sense to me when I was planning. 
    -- Hopefully it makes it clearer how the thought process works to leave it in there
    -- as several people have already pointed out, the data structure of the DB prevents us from looking at customers with invoices that have no payments towards them.
*/

Can I make 'git diff' only the line numbers AND changed file names?

Shows the file names and amount/nubmer of lines that changed in each file between now and the specified commit:

git diff --stat <commit-hash>

Convert JS date time to MySQL datetime

Solution built on the basis of other answers, while maintaining the timezone and leading zeros:

var d = new Date;

var date = [
    d.getFullYear(),
    ('00' + d.getMonth() + 1).slice(-2),
    ('00' + d.getDate() + 1).slice(-2)
].join('-');

var time = [
    ('00' + d.getHours()).slice(-2),
    ('00' + d.getMinutes()).slice(-2),
    ('00' + d.getSeconds()).slice(-2)
].join(':');

var dateTime = date + ' ' + time;
console.log(dateTime) // 2021-01-41 13:06:01

UIScrollView Scrollable Content Size Ambiguity

As mentioned in previous answers, you should add a custom view inside the scroll view:

The custom view is the ContentView marked in the image

Add all your subviews to the content view. At some point you will see a scroll content view has ambiguous content size warning, you should select the content view and click the "Resolve auto layout issues" button (at the bottom right corner of the IB layout), and select the "Add missing constraints" option.

enter image description here

From now on when you run the project, the scroll view will automatically update it's content size, no additional code needed.

JavaScript string newline character?

A practical observation... In my NodeJS script I have the following function:

function writeToLogFile (message) {
    fs.appendFile('myserverlog.txt', Date() + " " + message + "\r\n", function (err) {
        if (err) throw err;
    });
}

First I had only "\n" but I noticed that when I open the log file in Notepad, it shows all entries on the same line. Notepad++ on the other hand shows the entries each on their own line. After changing the code to "\r\n", even Notepad shows every entry on its own line.

dropzone.js - how to do something after ALL files are uploaded

In addition to @enyo's answer in checking for files that are still uploading or in the queue, I also created a new function in dropzone.js to check for any files in an ERROR state (ie bad file type, size, etc).

Dropzone.prototype.getErroredFiles = function () {
    var file, _i, _len, _ref, _results;
    _ref = this.files;
    _results = [];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        file = _ref[_i];
        if (file.status === Dropzone.ERROR) {
            _results.push(file);
        }
    }
    return _results;
};

And thus, the check would become:

  if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0 && this.getErroredFiles().length === 0) {
    doSomething();
  }

PHPmailer sending HTML CODE

or if you have still problems you can use this

$mail->Body =  html_entity_decode($Body);

Python: Remove division decimal

if val % 1 == 0:
    val = int(val)

else:
    val = float(val)

This worked for me.

How it works: if the remainder of the quotient of val and 1 is 0, val has to be an integer and can, therefore, be declared to be int without having to worry about losing decimal numbers.

Compare these two situations:

A:

val = 12.00

if val % 1 == 0:
    val = int(val)
else:
    val = float(val)

print(val)

In this scenario, the output is 12, because 12.00 divided by 1 has the remainder of 0. With this information we know, that val doesn't have any decimals and we can declare val to be int.

B:

val = 13.58

if val % 1 == 0:
    val = int(val)
else:
    val = float(val)

print(val)

This time the output is 13.58, because when val is divided by 1 there is a remainder (0.58) and therefore val is declared to be a float.

By just declaring the number to be an int (without testing the remainder) decimal numbers will be cut off.

This way there are no zeros in the end and no other than the zeros will be ignored.

How do you implement a re-try-catch?

Below snippet execute some code snippet. If you got any error while executing the code snippet, sleep for M milliseconds and retry. Reference link.

public void retryAndExecuteErrorProneCode(int noOfTimesToRetry, CodeSnippet codeSnippet, int sleepTimeInMillis)
  throws InterruptedException {

 int currentExecutionCount = 0;
 boolean codeExecuted = false;

 while (currentExecutionCount < noOfTimesToRetry) {
  try {
   codeSnippet.errorProneCode();
   System.out.println("Code executed successfully!!!!");
   codeExecuted = true;
   break;
  } catch (Exception e) {
   // Retry after 100 milliseconds
   TimeUnit.MILLISECONDS.sleep(sleepTimeInMillis);
   System.out.println(e.getMessage());
  } finally {
   currentExecutionCount++;
  }
 }

 if (!codeExecuted)
  throw new RuntimeException("Can't execute the code within given retries : " + noOfTimesToRetry);
}

Angular 2 Checkbox Two Way Data Binding

I know it may be repeated answer but for any one want to load list of checkboxes with selectall checkbox into angular form i follow this example: Select all/deselect all checkbox using angular 2+

it work fine but just need to add

[ngModelOptions]="{standalone: true}" 

the final HTML should be like this:

<ul>
    <li><input type="checkbox" [(ngModel)]="selectedAll" (change)="selectAll();"/></li>
    <li *ngFor="let n of names">
    <input type="checkbox" [(ngModel)]="n.selected" (change)="checkIfAllSelected();">{{n.name}}
    </li>
  </ul>

TypeScript

  selectAll() {
    for (var i = 0; i < this.names.length; i++) {
      this.names[i].selected = this.selectedAll;
    }
  }
  checkIfAllSelected() {
    this.selectedAll = this.names.every(function(item:any) {
        return item.selected == true;
      })
  }

hope this help thnx

Display a jpg image on a JPanel

You could also use

ImageIcon background = new ImageIcon("Background/background.png");
JLabel label = new JLabel();
label.setBounds(0, 0, x, y);
label.setIcon(background);

JPanel panel = new JPanel();
panel.setLayout(null);
panel.add(label);

if your working with a absolut value as layout.

Typescript react - Could not find a declaration file for module ''react-materialize'. 'path/to/module-name.js' implicitly has an any type

I got it after lots of trouble In react app there will be a react-app-env.d.ts file in src folder just declare module there

/// <reference types="react-scripts" />
declare module 'react-color/lib/components/alpha/AlphaPointer'

If a folder does not exist, create it

Use the below code. I use this code for file copy and creating a new folder.

string fileToCopy = "filelocation\\file_name.txt";
String server = Environment.UserName;
string newLocation = "C:\\Users\\" + server + "\\Pictures\\Tenders\\file_name.txt";
string folderLocation = "C:\\Users\\" + server + "\\Pictures\\Tenders\\";
bool exists = System.IO.Directory.Exists(folderLocation);

if (!exists)
{
   System.IO.Directory.CreateDirectory(folderLocation);
   if (System.IO.File.Exists(fileToCopy))
   {
     MessageBox.Show("file copied");
     System.IO.File.Copy(fileToCopy, newLocation, true);
   }
   else
   {
      MessageBox.Show("no such files");
   }
}

check if array is empty (vba excel)

this worked for me:

Private Function arrIsEmpty(arr as variant)
    On Error Resume Next
    arrIsEmpty = False
    arrIsEmpty = IsNumeric(UBound(arr))
End Function

Hibernate: failed to lazily initialize a collection of role, no session or session was closed

I've had this issue especially when entities are mashalled by Jaxb + Jax-rs. I've used the pre-fetch strategy, but I have also found it effective to provide two entities:

  1. Full-blown entity with all collections mapped as EAGER
  2. Simplified entity with most or all collections trimmed out

Common fields and be mapped in @MappedSuperclass and extended by both entity implementations.

Certainly if you always need the collections loaded, then there is no reason to not to EAGER load them. In my case I wanted a stripped down version of the entity to display in a grid.