Programs & Examples On #Texturing

Forcing to download a file using PHP

Nice clean solution:

<?php
    header('Content-Type: application/download');
    header('Content-Disposition: attachment; filename="example.csv"');
    header("Content-Length: " . filesize("example.csv"));

    $fp = fopen("example.csv", "r");
    fpassthru($fp);
    fclose($fp);
?>

how can I enable PHP Extension intl?

Simply copy all icu****.dll files from

C:\xampp\php

to

C:\xampp\apache\bin

[or]

C:\wamp\bin\php\php5.5.12

to

C:\wamp\bin\apache\apache2.4.9

intl extension will start working!!!

Jquery submit form

Use the following jquery to submit a selectbox with out a submit button. Use "change" instead of click as shown above.

$("selectbox").change(function() { 
   document.forms["form"].submit();
});

Cheers!

How can I run a function from a script in command line?

The following command first registers the function in the context, then calls it:

. ./myScript.sh && function_name

Month name as a string

I would recommend to use Calendar object and Locale since month names are different for different languages:

// index can be 0 - 11
private String getMonthName(final int index, final Locale locale, final boolean shortName)
{
    String format = "%tB";

    if (shortName)
        format = "%tb";

    Calendar calendar = Calendar.getInstance(locale);
    calendar.set(Calendar.MONTH, index);
    calendar.set(Calendar.DAY_OF_MONTH, 1);

    return String.format(locale, format, calendar);
}

Example for full month name:

System.out.println(getMonthName(0, Locale.US, false));

Result: January

Example for short month name:

System.out.println(getMonthName(0, Locale.US, true));

Result: Jan

How to set my phpmyadmin user session to not time out so quickly?

Once you're logged into phpmyadmin look on the top navigation for "Settings" and click that then:

"Features" >

...and you'll find "Login cookie validity" which is typically set to 1440.

Unfortunately changing it through the UI means that the changes don't persist between logins.

Redirecting new tab on button click.(Response.Redirect) in asp.net C#

You can use Rout redirecting.

protected void btnNewEntry_Click(object sender, EventArgs e)
{
    Response.RedirectToRoute("CMS_1"); 
}

which requires to define your routing logic in Global.asax file that could be like that:

routes.MapPageRoute("CMS_1", "CMS_1", "~/CMS_1.aspx");

where any request by CMS_1 pattern in application scope will be redirecting to CMS_1.aspx, but in URL shows like www.yoursite.com/CMS_1

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

Do not use authorization instead of authentication. I should get whole access to service all clients with header. The working code is :

public class TokenAuthenticationHandler : AuthenticationHandler<TokenAuthenticationOptions> 
{
    public IServiceProvider ServiceProvider { get; set; }

    public TokenAuthenticationHandler (IOptionsMonitor<TokenAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IServiceProvider serviceProvider) 
        : base (options, logger, encoder, clock) 
    {
        ServiceProvider = serviceProvider;
    }

    protected override Task<AuthenticateResult> HandleAuthenticateAsync () 
    {
        var headers = Request.Headers;
        var token = "X-Auth-Token".GetHeaderOrCookieValue (Request);

        if (string.IsNullOrEmpty (token)) {
            return Task.FromResult (AuthenticateResult.Fail ("Token is null"));
        }           

        bool isValidToken = false; // check token here

        if (!isValidToken) {
            return Task.FromResult (AuthenticateResult.Fail ($"Balancer not authorize token : for token={token}"));
        }

        var claims = new [] { new Claim ("token", token) };
        var identity = new ClaimsIdentity (claims, nameof (TokenAuthenticationHandler));
        var ticket = new AuthenticationTicket (new ClaimsPrincipal (identity), this.Scheme.Name);
        return Task.FromResult (AuthenticateResult.Success (ticket));
    }
}

Startup.cs :

#region Authentication
services.AddAuthentication (o => {
    o.DefaultScheme = SchemesNamesConst.TokenAuthenticationDefaultScheme;
})
.AddScheme<TokenAuthenticationOptions, TokenAuthenticationHandler> (SchemesNamesConst.TokenAuthenticationDefaultScheme, o => { });
#endregion

And mycontroller.cs

[Authorize(AuthenticationSchemes = SchemesNamesConst.TokenAuthenticationDefaultScheme)]
public class MainController : BaseController
{ ... }

I can't find TokenAuthenticationOptions now, but it was empty. I found the same class PhoneNumberAuthenticationOptions :

public class PhoneNumberAuthenticationOptions : AuthenticationSchemeOptions
{
    public Regex PhoneMask { get; set; }// = new Regex("7\\d{10}");
}

You should define static class SchemesNamesConst. Something like:

public static class SchemesNamesConst
{
    public const string TokenAuthenticationDefaultScheme = "TokenAuthenticationScheme";
}

How to set default value to all keys of a dict object in python?

Not after creating it, no. But you could use a defaultdict in the first place, which sets default values when you initialize it.

How to use linux command line ftp with a @ sign in my username?

I've never seen the -u parameter. But if you want to use an "@", how about stating it as "\@"?

That way it should be interpreted as you intend. You know something like

ftp -u user\@[email protected]

How to remove last n characters from a string in Bash?

In this case you could use basename assuming you have the same suffix on the files you want to remove.

Example:

basename -s .rtf "some string.rtf"

This will return "some string"

If you don't know the suffix, and want it to remove everything after and including the last dot:

f=file.whateverthisis
basename "${f%.*}"

outputs "file"

% means chop, . is what you are chopping, * is wildcard

How to View Oracle Stored Procedure using SQLPlus?

check your casing, the name is typically stored in upper case

SELECT * FROM all_source WHERE name = 'DAILY_UPDATE' ORDER BY TYPE, LINE;

How do you overcome the HTML form nesting limitation?

Alternatively you could assign the form actiob on the fly...might not be the best solution, but sure does relieve the server-side logic...

<form name="frm" method="post">  
    <input type="submit" value="One" onclick="javascript:this.form.action='1.htm'" />  
    <input type="submit" value="Two" onclick="javascript:this.form.action='2.htm'" />  
</form>

Correlation heatmap

The code below will produce this plot:

enter image description here

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

# A list with your data slightly edited
l = [1.0,0.00279981,0.95173379,0.02486161,-0.00324926,-0.00432099,
0.00279981,1.0,0.17728303,0.64425774,0.30735071,0.37379443,
0.95173379,0.17728303,1.0,0.27072266,0.02549031,0.03324756,
0.02486161,0.64425774,0.27072266,1.0,0.18336236,0.18913512,
-0.00324926,0.30735071,0.02549031,0.18336236,1.0,0.77678274,
-0.00432099,0.37379443,0.03324756,0.18913512,0.77678274,1.00]

# Split list
n = 6
data = [l[i:i + n] for i in range(0, len(l), n)]

# A dataframe
df = pd.DataFrame(data)

def CorrMtx(df, dropDuplicates = True):

    # Your dataset is already a correlation matrix.
    # If you have a dateset where you need to include the calculation
    # of a correlation matrix, just uncomment the line below:
    # df = df.corr()

    # Exclude duplicate correlations by masking uper right values
    if dropDuplicates:    
        mask = np.zeros_like(df, dtype=np.bool)
        mask[np.triu_indices_from(mask)] = True

    # Set background color / chart style
    sns.set_style(style = 'white')

    # Set up  matplotlib figure
    f, ax = plt.subplots(figsize=(11, 9))

    # Add diverging colormap from red to blue
    cmap = sns.diverging_palette(250, 10, as_cmap=True)

    # Draw correlation plot with or without duplicates
    if dropDuplicates:
        sns.heatmap(df, mask=mask, cmap=cmap, 
                square=True,
                linewidth=.5, cbar_kws={"shrink": .5}, ax=ax)
    else:
        sns.heatmap(df, cmap=cmap, 
                square=True,
                linewidth=.5, cbar_kws={"shrink": .5}, ax=ax)


CorrMtx(df, dropDuplicates = False)

I put this together after it was announced that the outstanding seaborn corrplot was to be deprecated. The snippet above makes a resembling correlation plot based on seaborn heatmap. You can also specify the color range and select whether or not to drop duplicate correlations. Notice that I've used the same numbers as you, but that I've put them in a pandas dataframe. Regarding the choice of colors you can have a look at the documents for sns.diverging_palette. You asked for blue, but that falls out of this particular range of the color scale with your sample data. For both observations of 0.95173379, try changing to -0.95173379 and you'll get this:

enter image description here

Get table column names in MySQL?

mysqli fetch_field() worked for me:

if ($result = $mysqli -> query($sql)) {
  // Get field information for all fields
  while ($fieldinfo = $result -> fetch_field()) {
    printf("Name: %s\n", $fieldinfo -> name);
    printf("Table: %s\n", $fieldinfo -> table);
    printf("Max. Len: %d\n", $fieldinfo -> max_length);
  }
  $result -> free_result();
}

Source: https://www.w3schools.com/pHP/func_mysqli_fetch_field.asp

Showing Thumbnail for link in WhatsApp || og:image meta-tag doesn't work

Clear your whatsapp data and cache (or use another whatsapp) !

Android Phone : Go to SETTINGS > APPS > Application List > WhatsApp > Storage and Clear Data.

Be careful ! Backup your messages before this action.

clear whatsapp data and cache

Then the result : before and after clearing data and cache WhatsApp before and after sharing

Programmatically close aspx page from code behind

if you are opening page on JavaScript popup then

 Response.Write("<script>javascript:window.close();</script>");

will do the job

How to add a new project to Github using VS Code

I think I ran into the similar problem. If you started a local git repository but have not set up a remote git project and want to push your local project to to git project.

1) create a remote git project and note the URL of project

2) open/edit your local git project

3) in the VS terminal type: git push --set-upstream [URL of project]

TypeError: object of type 'int' has no len() error assistance needed

Well, maybe an int does not posses the len attribute in Python like your error suggests?

Try:

len(str(numbers))

Screenshot sizes for publishing android app on Google Play

  • We require 2 screenshots.
  • Use: Displayed on the details page for your application in Google Play.
  • You may upload up to 8 screenshots each for phone, 7” tablet and 10” tablet.
  • Specs: Minimum dimension: 320 pixels. Maximum dimension: 3840 pixels. The maximum dimension of your screenshot cannot be more than twice as long as the minimum dimension. You may use 24 bit PNG or JPEG image (no alpha). Full bleed, no border in art.
  • We recommend adding screenshots of your app running on a 7" and 10" tablet. Go to ‘Store listing’ page in your Developer Console to add tablet apps screenshots.

https://support.google.com/googleplay/android-developer/answer/1078870?hl=en&ref_topic=2897459

.war vs .ear file

war - web archive. It is used to deploy web applications according to the servlet standard. It is a jar file containing a special directory called WEB-INF and several files and directories inside it (web.xml, lib, classes) as well as all the HTML, JSP, images, CSS, JavaScript and other resources of the web application

ear - enterprise archive. It is used to deploy enterprise application containing EJBs, web applications, and 3rd party libraries. It is also a jar file, it has a special directory called APP-INF that contains the application.xml file, and it contains jar and war files.

Android Button Onclick

Here is some sample code of how to add a button named Add. You should declare the variable as a member variable, and the naming convention for member variables is to start with the letter "m".

Hit Alt+Enter on the classes to add the missing references.

Add this to your activity_main.xml:

 <Button
        android:id="@+id/buttonAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ADD"
     />

Add this to your MainActivity.java:

public class MainActivity extends AppCompatActivity {

    Button mButtonAdd; 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mButtonAdd = findViewById(R.id.buttonAdd);

        mButtonAdd.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // do something here
            }
        });
    }
}

How to set JAVA_HOME for multiple Tomcat instances?

I had the same problem my OS is windows 8 and I am using Tomcat 8, I just edited the setclasspath.bat file in bin folder and set JAVA_HOME and JRE_HOME like this...

@echo off
...
...
set "JRE_HOME=%ProgramFiles%\Java\jre8"
set "JAVA_HOME=%ProgramFiles%\Java\jdk1.7.0_03"
...
...

and it works fine for me now......

How do you add input from user into list in Python

code below allows user to input items until they press enter key to stop:

In [1]: items=[]
   ...: i=0
   ...: while 1:
   ...:     i+=1
   ...:     item=input('Enter item %d: '%i)
   ...:     if item=='':
   ...:         break
   ...:     items.append(item)
   ...: print(items)
   ...: 

Enter item 1: apple

Enter item 2: pear

Enter item 3: #press enter here
['apple', 'pear']

In [2]: 

Return multiple fields as a record in PostgreSQL with PL/pgSQL

If you have a table with this exact record layout, use its name as a type, otherwise you will have to declare the type explicitly:

CREATE OR REPLACE FUNCTION get_object_fields
        (
        name text
        )
RETURNS mytable
AS
$$
        DECLARE f1 INT;
        DECLARE f2 INT;
        …
        DECLARE f8 INT;
        DECLARE retval mytable;
        BEGIN
        -- fetch fields f1, f2 and f3 from table t1
        -- fetch fields f4, f5 from table t2
        -- fetch fields f6, f7 and f8 from table t3
                retval := (f1, f2, …, f8);
                RETURN retval;
        END
$$ language plpgsql; 

What should be the sizeof(int) on a 64-bit machine?

In C++, the size of int isn't specified explicitly. It just tells you that it must be at least the size of short int, which must be at least as large as signed char. The size of char in bits isn't specified explicitly either, although sizeof(char) is defined to be 1. If you want a 64 bit int, C++11 specifies long long to be at least 64 bits.

Use images instead of radio buttons

Here is a simple jQuery UI solution based on the example here:

http://jqueryui.com/button/#radio

Modified code:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery UI Button - Radios</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script>
  $(function() {
    $( "#radio" ).buttonset();
  });
  </script>
</head>
<body>

<form>
  <div id="radio">
    <input type="radio" id="radio1" name="radio"><label for="radio1"><img src="image1.gif" /></label>
    <input type="radio" id="radio2" name="radio" checked="checked"><label for="radio2"><img src="image2.gif" /></label>
    <input type="radio" id="radio3" name="radio"><label for="radio3"><img src="image3.gif" /></label>
  </div>
</form>

</body>
</html>

jQueryUI takes care of the image background so you know which button is checked.

Beware: If you want to set a button to checked or unchecked via Javascript, you must call the refresh function:

        $('#radio3').prop('checked', true).button("refresh");

Android DialogFragment vs Dialog

I would recommend using DialogFragment.

Sure, creating a "Yes/No" dialog with it is pretty complex considering that it should be rather simple task, but creating a similar dialog box with Dialog is surprisingly complicated as well.

(Activity lifecycle makes it complicated - you must let Activity manage the lifecycle of the dialog box - and there is no way to pass custom parameters e.g. the custom message to Activity.showDialog if using API levels under 8)

The nice thing is that you can usually build your own abstraction on top of DialogFragment pretty easily.

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

you do not need to clean all files in dir C:\Users\ ~User Name~ \.gradle\wrapper\dists. and download all of them again

instead you can just delete the folder of gradle version you failed to download. In my case it was gradle-4.4-all so i just deleted that folder and android studio re downloaded gradle-4.4-all for me

In case you don't know version you was downloading:

Just go to help menu > show logs in explorer

their you will find idea.log open it and search for

Could not install Gradle distribution from 'https://services.gradle.org/distribution`

once you find it you will find gradle version you failed to download

Android: ScrollView vs NestedScrollView

Other than the advantages listed in the answers given, one more advantage of NestedScrollView over ScrollView is its compatibility with CoordinatorLayout. The ScrollView does not cooperate with the CoordinatorLayout. You have to use NestedScrollView to get "scroll off-screen" behaviour for the toolbar.

Toolbar will not collapse with Scrollview as child of CoordinatorLayout

Entity Framework is Too Slow. What are my options?

The fact of the matter is that products such as Entity Framework will ALWAYS be slow and inefficient, because they are executing lot more code.

I also find it silly that people are suggesting that one should optimize LINQ queries, look at the SQL generated, use debuggers, pre-compile, take many extra steps, etc. i.e. waste a lot of time. No one says - Simplify! Everyone wants to comlicate things further by taking even more steps (wasting time).

A common sense approach would be not to use EF or LINQ at all. Use plain SQL. There is nothing wrong with it. Just because there is herd mentality among programmers and they feel the urge to use every single new product out there, does not mean that it is good or it will work. Most programmers think if they incorporate every new piece of code released by a large company, it is making them a smarter programmer; not true at all. Smart programming is mostly about how to do more with less headaches, uncertainties, and in the least amount of time. Remember - Time! That is the most important element, so try to find ways not to waste it on solving problems in bad/bloated code written simply to conform with some strange so called 'patterns'

Relax, enjoy life, take a break from coding and stop using extra features, code, products, 'patterns'. Life is short and the life of your code is even shorter, and it is certainly not rocket science. Remove layers such as LINQ, EF and others, and your code will run efficiently, will scale, and yes, it will still be easy to maintain. Too much abstraction is a bad 'pattern'.

And that is the solution to your problem.

NSDictionary - Need to check whether dictionary contains key-value pair or not

With literal syntax you can check as follows

static const NSString* kKeyToCheck = @"yourKey"
if (xyz[kKeyToCheck])
  NSLog(@"Key: %@, has Value: %@", kKeyToCheck, xyz[kKeyToCheck]);
else
 NSLog(@"Key pair do not exits for key: %@", kKeyToCheck); 

MongoDB: Server has startup warnings ''Access control is not enabled for the database''

Mongodb v3.4

You need to do the following to create a secure database:

Make sure the user starting the process has permissions and that the directories exist (/data/db in this case).

1) Start MongoDB without access control.

mongod --port 27017 --dbpath /data/db

2) Connect to the instance.

mongo --port 27017

3) Create the user administrator (in the admin authentication database).

use admin
db.createUser(
  {
    user: "myUserAdmin",
    pwd: "abc123",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)

4) Re-start the MongoDB instance with access control.

mongod --auth --port 27017 --dbpath /data/db

5) Connect and authenticate as the user administrator.

mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"

6) Create additional users as needed for your deployment (e.g. in the test authentication database).

use test
db.createUser(
  {
    user: "myTester",
    pwd: "xyz123",
    roles: [ { role: "readWrite", db: "test" },
             { role: "read", db: "reporting" } ]
  }
)

7) Connect and authenticate as myTester.

mongo --port 27017 -u "myTester" -p "xyz123" --authenticationDatabase "test"

I basically just explained the short version of the official docs here: https://docs.mongodb.com/master/tutorial/enable-authentication/

Should I always use a parallel stream when possible?

Never parallelize an infinite stream with a limit. Here is what happens:

    public static void main(String[] args) {
        // let's count to 1 in parallel
        System.out.println(
            IntStream.iterate(0, i -> i + 1)
                .parallel()
                .skip(1)
                .findFirst()
                .getAsInt());
    }

Result

    Exception in thread "main" java.lang.OutOfMemoryError
        at ...
        at java.base/java.util.stream.IntPipeline.findFirst(IntPipeline.java:528)
        at InfiniteTest.main(InfiniteTest.java:24)
    Caused by: java.lang.OutOfMemoryError: Java heap space
        at java.base/java.util.stream.SpinedBuffer$OfInt.newArray(SpinedBuffer.java:750)
        at ...

Same if you use .limit(...)

Explanation here: Java 8, using .parallel in a stream causes OOM error

Similarly, don't use parallel if the stream is ordered and has much more elements than you want to process, e.g.

public static void main(String[] args) {
    // let's count to 1 in parallel
    System.out.println(
            IntStream.range(1, 1000_000_000)
                    .parallel()
                    .skip(100)
                    .findFirst()
                    .getAsInt());
}

This may run much longer because the parallel threads may work on plenty of number ranges instead of the crucial one 0-100, causing this to take very long time.

Better way to Format Currency Input editText?

If your json currency field is of number type (and not String) it may come as 3.1 , 3.15 or just 3. Because json automatically round number fields.

In this case you may need to round it for proper display (and to be able to use a mask on a input field later):

    NumberFormat nf = NumberFormat.getCurrencyInstance();

    float value = 200 // it can be 200, 200.3 or 200.37, BigDecimal will take care
    BigDecimal valueAsBD = BigDecimal.valueOf(value);
    valueAsBD.setScale(2, BigDecimal.ROUND_HALF_UP);

    String formated = nf.format(valueAsBD);

Why this is needed?

All answers point to removing currency simbols when typing judcing you are receiving the cents and so formating dolar + cents / 100 = dolar,cents. But if your json currency field is an number type (and not an String) it will round your cents, it may be 3 , 3.1 or 3.15.

Oracle PL Sql Developer cannot find my tnsnames.ora file

Which Oracle client are you using?

Oracle 64bit 11g client isn't support in PLSQL Developer. Try to install 32bits client.

How to use sessions in an ASP.NET MVC 4 application?

U can store any value in session like Session["FirstName"] = FirstNameTextBox.Text; but i will suggest u to take as static field in model assign value to it and u can access that field value any where in application. U don't need session. session should be avoided.

public class Employee
{
   public int UserId { get; set; }
   public string EmailAddress { get; set; }
   public static string FullName { get; set; }
}

on controller - Employee.FullName = "ABC"; Now u can access this full Name anywhere in application.

How to get the first day of the current week and month?

java.time

The java.time framework in Java 8 and later supplants the old java.util.Date/.Calendar classes. The old classes have proven to be troublesome, confusing, and flawed. Avoid them.

The java.time framework is inspired by the highly-successful Joda-Time library, defined by JSR 310, extended by the ThreeTen-Extra project, and explained in the Tutorial.

Instant

The Instant class represents a moment on the timeline in UTC.

The java.time framework has a resolution of nanoseconds, or 9 digits of a fractional second. Milliseconds is only 3 digits of a fractional second. Because millisecond resolution is common, java.time includes a handy factory method.

long millisecondsSinceEpoch = 1446959825213L;
Instant instant = Instant.ofEpochMilli ( millisecondsSinceEpoch );

millisecondsSinceEpoch: 1446959825213 is instant: 2015-11-08T05:17:05.213Z

ZonedDateTime

To consider current week and current month, we need to apply a particular time zone.

ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId );

In zoneId: America/Montreal that is: 2015-11-08T00:17:05.213-05:00[America/Montreal]

Half-Open

In date-time work, we commonly use the Half-Open approach to defining a span of time. The beginning is inclusive while the ending in exclusive. Rather than try to determine the last split-second of the end of the week (or month), we get the first moment of the following week (or month). So a week runs from the first moment of Monday and goes up to but not including the first moment of the following Monday.

Let's the first day of the week, and last. The java.time framework includes a tool for that, the with method and the ChronoField enum.

By default, java.time uses the ISO 8601 standard. So Monday is the first day of the week (1) and Sunday is last (7).

ZonedDateTime firstOfWeek = zdt.with ( ChronoField.DAY_OF_WEEK , 1 ); // ISO 8601, Monday is first day of week.
ZonedDateTime firstOfNextWeek = firstOfWeek.plusWeeks ( 1 );

That week runs from: 2015-11-02T00:17:05.213-05:00[America/Montreal] to 2015-11-09T00:17:05.213-05:00[America/Montreal]

Oops! Look at the time-of-day on those values. We want the first moment of the day. The first moment of the day is not always 00:00:00.000 because of Daylight Saving Time (DST) or other anomalies. So we should let java.time make the adjustment on our behalf. To do that, we must go through the LocalDate class.

ZonedDateTime firstOfWeek = zdt.with ( ChronoField.DAY_OF_WEEK , 1 ); // ISO 8601, Monday is first day of week.
firstOfWeek = firstOfWeek.toLocalDate ().atStartOfDay ( zoneId );
ZonedDateTime firstOfNextWeek = firstOfWeek.plusWeeks ( 1 );

That week runs from: 2015-11-02T00:00-05:00[America/Montreal] to 2015-11-09T00:00-05:00[America/Montreal]

And same for the month.

ZonedDateTime firstOfMonth = zdt.with ( ChronoField.DAY_OF_MONTH , 1 );
firstOfMonth = firstOfMonth.toLocalDate ().atStartOfDay ( zoneId );
ZonedDateTime firstOfNextMonth = firstOfMonth.plusMonths ( 1 );

That month runs from: 2015-11-01T00:00-04:00[America/Montreal] to 2015-12-01T00:00-05:00[America/Montreal]

YearMonth

Another way to see if a pair of moments are in the same month is to check for the same YearMonth value.

For example, assuming thisZdt and thatZdt are both ZonedDateTime objects:

boolean inSameMonth = YearMonth.from( thisZdt ).equals( YearMonth.from( thatZdt ) ) ;

Milliseconds

I strongly recommend against doing your date-time work in milliseconds-from-epoch. That is indeed the way date-time classes tend to work internally, but we have the classes for a reason. Handling a count-from-epoch is clumsy as the values are not intelligible by humans so debugging and logging is difficult and error-prone. And, as we've already seen, different resolutions may be in play; old Java classes and Joda-Time library use milliseconds, while databases like Postgres use microseconds, and now java.time uses nanoseconds.

Would you handle text as bits, or do you let classes such as String, StringBuffer, and StringBuilder handle such details?

But if you insist, from a ZonedDateTime get an Instant, and from that get a milliseconds-count-from-epoch. But keep in mind this call can mean loss of data. Any microseconds or nanoseconds that you might have in your ZonedDateTime/Instant will be truncated (lost).

long millis = firstOfWeek.toInstant().toEpochMilli();  // Possible data loss.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

How to find out which package version is loaded in R?

Use the following code to obtain the version of R packages installed in the system:

installed.packages(fields = c ("Package", "Version"))

There are no primary or candidate keys in the referenced table that match the referencing column list in the foreign key

Foreign keys work by joining a column to a unique key in another table, and that unique key must be defined as some form of unique index, be it the primary key, or some other unique index.

At the moment, the only unique index you have is a compound one on ISBN, Title which is your primary key.

There are a number of options open to you, depending on exactly what BookTitle holds and the relationship of the data within it.

I would hazard a guess that the ISBN is unique for each row in BookTitle. ON the assumption this is the case, then change your primary key to be only on ISBN, and change BookCopy so that instead of Title you have ISBN and join on that.

If you need to keep your primary key as ISBN, Title then you either need to store the ISBN in BookCopy as well as the Title, and foreign key on both columns, OR you need to create a unique index on BookTitle(Title) as a distinct index.

More generally, you need to make sure that the column or columns you have in your REFERENCES clause match exactly a unique index in the parent table: in your case it fails because you do not have a single unique index on Title alone.

How to send json data in the Http request using NSURLRequest

I would suggest to use ASIHTTPRequest

ASIHTTPRequest is an easy to use wrapper around the CFNetwork API that makes some of the more tedious aspects of communicating with web servers easier. It is written in Objective-C and works in both Mac OS X and iPhone applications.

It is suitable performing basic HTTP requests and interacting with REST-based services (GET / POST / PUT / DELETE). The included ASIFormDataRequest subclass makes it easy to submit POST data and files using multipart/form-data.


Please note, that the original author discontinued with this project. See the followring post for reasons and alternatives: http://allseeing-i.com/%5Brequest_release%5D;

Personally I am a big fan of AFNetworking

expand/collapse table rows with JQuery

You can try this way:-

Give a class say header to the header rows, use nextUntil to get all rows beneath the clicked header until the next header.

JS

$('.header').click(function(){
    $(this).nextUntil('tr.header').slideToggle(1000);
});

Html

<table border="0">
  <tr  class="header">
    <td colspan="2">Header</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>

Demo

Another Example:

$('.header').click(function(){
   $(this).find('span').text(function(_, value){return value=='-'?'+':'-'});
    $(this).nextUntil('tr.header').slideToggle(100); // or just use "toggle()"
});

Demo

You can also use promise to toggle the span icon/text after the toggle is complete in-case of animated toggle.

$('.header').click(function () {
    var $this = $(this);
    $(this).nextUntil('tr.header').slideToggle(100).promise().done(function () {
        $this.find('span').text(function (_, value) {
            return value == '-' ? '+' : '-'
        });
    });
});

.promise()

.slideToggle()

Or just with a css pseudo element to represent the sign of expansion/collapse, and just toggle a class on the header.

CSS:-

.header .sign:after{
  content:"+";
  display:inline-block;      
}
.header.expand .sign:after{
  content:"-";
}

JS:-

$(this).toggleClass('expand').nextUntil('tr.header').slideToggle(100);

Demo

Android Studio - Gradle sync project failed

I had a "Install build tools and sync" link in the lower right hand corner of my screen. I clicked on that and it fixed the issue.

Dump all documents of Elasticsearch

You can also dump elasticsearch data in JSON format by http request: https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html
CURL -XPOST 'https://ES/INDEX/_search?scroll=10m'
CURL -XPOST 'https://ES/_search/scroll' -d '{"scroll": "10m", "scroll_id": "ID"}'

Validate phone number with JavaScript

realy simple

"9001234567".match(/^\d{10}$/g)

Purpose of #!/usr/bin/python3 shebang

Actually the determination of what type of file a file is very complicated, so now the operating system can't just know. It can make lots of guesses based on -

  • extension
  • UTI
  • MIME

But the command line doesn't bother with all that, because it runs on a limited backwards compatible layer, from when that fancy nonsense didn't mean anything. If you double click it sure, a modern OS can figure that out- but if you run it from a terminal then no, because the terminal doesn't care about your fancy OS specific file typing APIs.

Regarding the other points. It's a convenience, it's similarly possible to run

python3 path/to/your/script

If your python isn't in the path specified, then it won't work, but we tend to install things to make stuff like this work, not the other way around. It doesn't actually matter if you're under *nix, it's up to your shell whether to consider this line because it's a shellcode. So for example you can run bash under Windows.

You can actually ommit this line entirely, it just mean the caller will have to specify an interpreter. Also don't put your interpreters in nonstandard locations and then try to call scripts without providing an interpreter.

How to use the pass statement?

You can say that pass means NOP (No Operation) operation. You will get a clear picture after this example :-

C Program

#include<stdio.h>

void main()
{
    int age = 12;

    if( age < 18 )
    {
         printf("You are not adult, so you can't do that task ");
    }
    else if( age >= 18 && age < 60)
    {
        // I will add more code later inside it 
    }
    else
    {
         printf("You are too old to do anything , sorry ");
    }
}

Now how you will write that in Python :-

age = 12

if age < 18:

    print "You are not adult, so you can't do that task"

elif age >= 18 and age < 60:

else:

    print "You are too old to do anything , sorry "

But your code will give error because it required an indented block after elif . Here is the role of pass keyword.

age = 12

if age < 18:

    print "You are not adult, so you can't do that task"

elif age >= 18 and age < 60:

    pass

else:

    print "You are too old to do anything , sorry "

Now I think its clear to you.

Change Default branch in gitlab

For GitLab 11.5.0-ee, go to https://gitlab.com/<username>/<project name>/settings/repository.

You should see:

Default Branch

Select the branch you want to set as the default for this project. All merge requests and commits will automatically be made against this branch unless you specify a different one.

Click Expand, select a branch, and click Save Changes.

Overlapping elements in CSS

You can try using the transform: translate property by passing the appropriate values inside the parenthesis using the inspect element in Google chrome.

You have to set translate property in such way that both the <div> overlap each other then You can use JavaScript to show and hide both the <div> according to your requirements

How to get the URL of the current page in C#

If you want to get

localhost:2806 

from

http://localhost:2806/Pages/ 

then use:

HttpContext.Current.Request.Url.Authority

No module named 'pymysql'

if you are using SPYDER IDE , just try to restart the console or restart the IDE, it works

How to connect access database in c#

Try this code,

public void ConnectToAccess()
{
    System.Data.OleDb.OleDbConnection conn = new 
        System.Data.OleDb.OleDbConnection();
    // TODO: Modify the connection string and include any
    // additional required properties for your database.
    conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
        @"Data source= C:\Documents and Settings\username\" +
        @"My Documents\AccessFile.mdb";
    try
    {
        conn.Open();
        // Insert code to process data.
    }
        catch (Exception ex)
    {
        MessageBox.Show("Failed to connect to data source");
    }
    finally
    {
        conn.Close();
    }
}

http://msdn.microsoft.com/en-us/library/5ybdbtte(v=vs.71).aspx

Replacing &nbsp; from javascript dom text node

for me replace doesn't work... try this code:

str = str.split("&quot;").join('"');

How do I copy to the clipboard in JavaScript?

In browsers other than Internet Explorer you need to use a small Flash object to manipulate the clipboard, e.g.

Initializing ArrayList with some predefined values

public static final List<String> permissions = new ArrayList<String>() {{
    add("public_profile");
    add("email");
    add("user_birthday");
    add("user_about_me");
    add("user_location");
    add("user_likes");
    add("user_posts");
}};

How to catch an Exception from a thread

If you implement Thread.UncaughtExceptionHandler in class that starts the Threads, you can set and then rethrow the exception:

public final class ThreadStarter implements Thread.UncaughtExceptionHandler{

private volatile Throwable initException;

    public void doSomeInit(){
        Thread t = new Thread(){
            @Override
            public void run() {
              throw new RuntimeException("UNCAUGHT");
            }
        };
        t.setUncaughtExceptionHandler(this);

        t.start();
        t.join();

        if (initException != null){
            throw new RuntimeException(initException);
        }

    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        initException =  e;
    }    

}

Which causes the following output:

Exception in thread "main" java.lang.RuntimeException: java.lang.RuntimeException: UNCAUGHT
    at com.gs.gss.ccsp.enrichments.ThreadStarter.doSomeInit(ThreadStarter.java:24)
    at com.gs.gss.ccsp.enrichments.ThreadStarter.main(ThreadStarter.java:38)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: java.lang.RuntimeException: UNCAUGHT
    at com.gs.gss.ccsp.enrichments.ThreadStarter$1.run(ThreadStarter.java:15)

SyntaxError: expected expression, got '<'

I had same error. And in my case

REASON: There was restriction to that resources on server and server was sending login page instead of javascript pages.

SOLUTION: give access to user for resourses or remove restriction at all.

how can I Update top 100 records in sql server

You can also update from select using alias and join:

UPDATE  TOP (500) T
SET     T.SomeColumn = 'Value'
FROM    SomeTable T
        INNER JOIN OtherTable O ON O.OtherTableFK = T.SomeTablePK
WHERE   T.SomeOtherColumn = 1

ADB server version (36) doesn't match this client (39) {Not using Genymotion}

This works for me...

  • go to GenyMotion settings -> ADB tab
  • instead of Use Genymotion Android tools, choose custom Android SDK Tools and then browse your installed SDK.

Selecting Multiple Values from a Dropdown List in Google Spreadsheet

To Add to AlexG's answer, a better and enhanced version of multi-select is found in this following link (which I tried and worked as expected):

https://gist.github.com/coinsandsteeldev/4c67dfa5411e8add913273fc5a30f5e7

For general guidance on setting up a script in Google Sheets, see this quickstart guide.

To use this script:

  1. In your Google Sheet, set up data validation for a cell (or cells), using data from a range. In cell validation, do not select 'Reject input'.
  2. Go to Tools > Script editor...
  3. In the script editor, go to File > New > Script file
  4. Name the file multi-select.gs and paste in the contents of multi-select.gs. File > Save.
  5. In the script editor, go to File > New > Html file Name the file dialog.html and paste in the contents of dialog.html. File > Save.
  6. Back in your spreadsheet, you should now have a new menu called 'Scripts'. Refresh the page if necessary.
  7. Select the cell you want to fill with multiple items from your validation range.
  8. Go to Scripts > Multi-select for this cell... and the sidebar should open, showing a checklist of valid items.
  9. Tick the items you want and click the 'Set' button to fill your cell with those selected items, comma separated.

You can leave the script sidebar open. When you select any cell that has validation, click 'Refresh validation' in the script sidebar to bring up that cell's checklist.

The above mentioned steps are taken from this link

Best way to store passwords in MYSQL database

Hashing algorithms such as sha1 and md5 are not suitable for password storing. They are designed to be very efficient. This means that brute forcing is very fast. Even if a hacker obtains a copy of your hashed passwords, it is pretty fast to brute force it. If you use a salt, it makes rainbow tables less effective, but does nothing against brute force. Using a slower algorithm makes brute force ineffective. For instance, the bcrypt algorithm can be made as slow as you wish (just change the work factor), and it uses salts internally to protect against rainbow tables. I would go with such an approach or similar (e.g. scrypt or PBKDF2) if I were you.

How can I generate an MD5 hash?

Take a look at the following link, the Example gets an MD5 Hash of a supplied image: MD5 Hash of an Image

Possible reason for NGINX 499 error codes

For my part I had enabled ufw but I forgot to expose my upstreams ports ._.

How to calculate difference between two dates in oracle 11g SQL

Oracle DateDiff is from a different product, probably mysql (which is now owned by Oracle).

The difference between two dates (in oracle's usual database product) is in days (which can have fractional parts). Factor by 24 to get hours, 24*60 to get minutes, 24*60*60 to get seconds (that's as small as dates go). The math is 100% accurate for dates within a couple of hundred years or so. E.g. to get the date one second before midnight of today, you could say

select trunc(sysdate) - 1/24/60/60 from dual;

That means "the time right now", truncated to be just the date (i.e. the midnight that occurred this morning). Then it subtracts a number which is the fraction of 1 day that measures one second. That gives you the date from the previous day with the time component of 23:59:59.

A network-related or instance-specific error occurred while establishing a connection to SQL Server

Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.

  1. Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .

  2. if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .

  3. if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .

  4. after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).

  5. if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.

  6. If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.

  7. If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.

  8. If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property. enter image description here

    1. Restart your sql server instance after making any changes in property as some changes will require restart.

if you further face any difficulty then you need to provide more information about your web site and sql server .

Passing an array as parameter in JavaScript

Just remove the .value, like this:

function(arrayP){    
   for(var i = 0; i < arrayP.length; i++){
      alert(arrayP[i]);    //no .value here
   }
}

Sure you can pass an array, but to get the element at that position, use only arrayName[index], the .value would be getting the value property off an object at that position in the array - which for things like strings, numbers, etc doesn't exist. For example, "myString".value would also be undefined.

How to convert List to Json in Java

Look at the google gson library. It provides a rich api for dealing with this and is very straightforward to use.

Node.js: printing to console without a trailing newline?

In Windows console (Linux, too), you should replace '\r' with its equivalent code \033[0G:

process.stdout.write('ok\033[0G');

This uses a VT220 terminal escape sequence to send the cursor to the first column.

React onClick function fires on render

The value for your onClick attribute should be a function, not a function call.

<button type="submit" onClick={function(){removeTaskFunction(todo)}}>Submit</button>

SQL Order By Count

...none of the other answers seem to do what the asker asked.

For table named 'things' with column 'group':

SELECT
  things.*, counter.count
FROM
  things
LEFT JOIN (
  SELECT
    things.group, count(things.group) as count
  FROM
    things
  GROUP BY
    things.group
) counter ON counter.group = things.group
ORDER BY
  counter.count ASC;

which gives:

id | name  | group | count 
---------------------------
3  | Cat   | B     | 1
1  | Apple | A     | 2
2  | Boy   | A     | 2
4  | Dog   | C     | 3
5  | Elep  | C     | 3
6  | Fish  | C     | 3

How can I delete derived data in Xcode 8?

Steps For Delete DerivedData:

  1. Open Finder
  2. From menu click on Go > Go to Folder
  3. Enter ~/Library/Developer/Xcode/DerivedData in textfield
  4. Click on Go button
  5. You will see the folders of your Xcode projects
  6. Delete the folders of projects, which you don't need.

no such file to load -- rubygems (LoadError)

OK, I am a Ruby noob, but I did get this fixed slightly differently than the answers here, so hopefully this helps someone else (tl;dr: I used RVM to switch the system Ruby version to the same one expected by rubygems).

First off, listing all Rubies as mentioned by Eimantas was a great starting point:

> which -a ruby
/opt/local/bin/ruby
/Users/Brian/.rvm/rubies/ruby-1.9.2-p290/bin/ruby
/Users/Brian/.rvm/bin/ruby
/usr/bin/ruby
/opt/local/bin/ruby

The default Ruby instance in use by the system appeared to be 1.8.7:

> ruby -v
ruby 1.8.7 (2010-06-23 patchlevel 299) [i686-darwin10]

while the version in use by Rubygems was the 1.9.2 version managed by RVM:

> gem env | grep 'RUBY EXECUTABLE'
  - RUBY EXECUTABLE: /Users/Brian/.rvm/rubies/ruby-1.9.2-p290/bin/ruby

So that was definitely the issue. I don't actively use Ruby myself (this is simply a dependency of a build system script I'm trying to run) so I didn't care which version was active for other purposes. Since rubygems expected the 1.9.2 that was already managed by RVM, I simply used RVM to switch the system to use the 1.9.2 version as the default:

> rvm use 1.9.2
Using /Users/Brian/.rvm/gems/ruby-1.9.2-p290

> ruby -v
ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-darwin11.3.0]

After doing that my "no such file" issue went away and my script started working.

mysql error 2005 - Unknown MySQL server host 'localhost'(11001)

ERROR 2005 (HY000): Unknown MySQL server host 'localhost' (0)

modify list of host names for your system:

C:\Windows\System32\drivers\etc\hosts

Make sure that you have the following entry:

127.0.0.1 localhost
In my case that entry was 0.0.0.0 localhost which caussed all problem

(you may need to change modify permission to modify this file)

This performs DNS resolution of host “localhost” to the IP address 127.0.0.1.

How do I get rid of the "cannot empty the clipboard" error?

I got rid of the problem by unchecking the option for "Alert before overwriting cells" in Excel options. I'm using Excel 2007

Efficient way to apply multiple filters to pandas DataFrame or Series

Why not do this?

def filt_spec(df, col, val, op):
    import operator
    ops = {'eq': operator.eq, 'neq': operator.ne, 'gt': operator.gt, 'ge': operator.ge, 'lt': operator.lt, 'le': operator.le}
    return df[ops[op](df[col], val)]
pandas.DataFrame.filt_spec = filt_spec

Demo:

df = pd.DataFrame({'a': [1,2,3,4,5], 'b':[5,4,3,2,1]})
df.filt_spec('a', 2, 'ge')

Result:

   a  b
 1  2  4
 2  3  3
 3  4  2
 4  5  1

You can see that column 'a' has been filtered where a >=2.

This is slightly faster (typing time, not performance) than operator chaining. You could of course put the import at the top of the file.

CSS selector for text input fields?

The attribute selectors are often used for inputs. This is the list of attribute selectors:

[title] All elements with the title attribute are selected.

[title=banana] All elements which have the 'banana' value of the title attribute.

[title~=banana] All elements which contain 'banana' in the value of the title attribute.

[title|=banana] All elements which value of the title attribute starts with 'banana'.

[title^=banana] All elements which value of the title attribute begins with 'banana'.

[title$=banana] All elements which value of the title attribute ends with 'banana'.

[title*=banana] All elements which value of the title attribute contains the substring 'banana'.

Reference: https://kolosek.com/css-selectors/

What are the most common naming conventions in C?

You should also think about the order of the words to make the auto name completion easier.

A good practice: library name + module name + action + subject

If a part is not relevant just skip it, but at least a module name and an action always should be presented.

Examples:

  • function name: os_task_set_prio, list_get_size, avg_get
  • define (here usually no action part): OS_TASK_PRIO_MAX

How to call a MySQL stored procedure from within PHP code?

<?php
    $res = mysql_query('SELECT getTreeNodeName(1) AS result');
    if ($res === false) {
        echo mysql_errno().': '.mysql_error();
    }
    while ($obj = mysql_fetch_object($res)) {
        echo $obj->result;
    }

Android get Current UTC time

see my answer here:

How can I get the current date and time in UTC or GMT in Java?

I've fully tested it by changing the timezones on the emulator

How can I get the current page name in WordPress?

You can get the current page, post, or custom post type with the global variable $post:

echo $post->post_title

Note: In a function or class you'll need to specify global $post; prior to trying to use $post.

If you have loops on your page, make sure you end each loop with wp_reset_postdata(); to set $post back to the default item being displayed (the page).

Note, the 'post_title' variable is also available for any custom loop / query... including menu items and media attachments... everything in WordPress is a 'post'.

OpenJDK8 for windows

Go to this link

Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download

Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.

JDK vs OpenJDK

How exactly to use Notification.Builder

Notification.Builder API 11 or NotificationCompat.Builder API 1

This is a usage example.

Intent notificationIntent = new Intent(ctx, YourClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(ctx,
        YOUR_PI_REQ_CODE, notificationIntent,
        PendingIntent.FLAG_CANCEL_CURRENT);

NotificationManager nm = (NotificationManager) ctx
        .getSystemService(Context.NOTIFICATION_SERVICE);

Resources res = ctx.getResources();
Notification.Builder builder = new Notification.Builder(ctx);

builder.setContentIntent(contentIntent)
            .setSmallIcon(R.drawable.some_img)
            .setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.some_big_img))
            .setTicker(res.getString(R.string.your_ticker))
            .setWhen(System.currentTimeMillis())
            .setAutoCancel(true)
            .setContentTitle(res.getString(R.string.your_notif_title))
            .setContentText(res.getString(R.string.your_notif_text));
Notification n = builder.build();

nm.notify(YOUR_NOTIF_ID, n);

NULL value for int in Update statement

If this is nullable int field then yes.

update TableName
set FiledName = null
where Id = SomeId

Service will not start: error 1067: the process terminated unexpectedly

I had this error, I looked into a log file C:\...\mysql\data\VM-IIS-Server.err and found this

2016-06-07 17:56:07 160c  InnoDB: Error: unable to create temporary file; errno: 2
2016-06-07 17:56:07 3392 [ERROR] Plugin 'InnoDB' init function returned error.
2016-06-07 17:56:07 3392 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2016-06-07 17:56:07 3392 [ERROR] Unknown/unsupported storage engine: InnoDB
2016-06-07 17:56:07 3392 [ERROR] Aborting

The first line says "unable to create temporary file", it sounds like "insufficient privileges", first I tried to give access to mysql folder for my current user - no effect, then after some wandering around I came up to control panel->Administration->Services->Right Clicked MysqlService->Properties->Log On, switched to "This account", entered my username/password, clicked OK, and it woked!

How to draw a circle with text in the middle?

Of course, you have to use to tags to do that. One to create the circle and other for the text.

Here some code may help you

#circle {
    background: #f00;
    width: 200px;
    height: 200px;
    border-radius: 50%;
    color:black;

}
.innerTEXT{
    position:absolute;
    top:80px;
    left:60px;
}

<div id="circle">
    <span class="innerTEXT"> Here a text</span>
</div>

Live example here http://jsbin.com/apumik/1/edit

Update

Here less smaller with a few changes

http://jsbin.com/apumik/3/edit

how to implement Pagination in reactJs

Give you a pagination component, which is maybe a little difficult to understand for newbie to react:

https://www.npmjs.com/package/pagination

QtCreator: No valid kits found

For QT 5.* if you face error at Kits, like No Valid Kits Found, go to Options->Build&Run-> (Kits tab) then you see a Manual category which should list Desktop as the default.

Just go to your OS Terminal and write sudo apt-get install qt5-default, go back to QT Creator and Start your New Project, and there you see the kit option Desktop included in the list.

EXCEL Multiple Ranges - need different answers for each range

Nested if's in Excel Are ugly:

=If(G2 < 1, .1, IF(G2 < 5,.15,if(G2 < 15,.2,if(G2 < 30,.5,if(G2 < 100,.1,1.3)))))

That should cover it.

Avoid synchronized(this) in Java?

No, you shouldn't always. However, I tend to avoid it when there are multiple concerns on a particular object that only need to be threadsafe in respect to themselves. For example, you might have a mutable data object that has "label" and "parent" fields; these need to be threadsafe, but changing one need not block the other from being written/read. (In practice I would avoid this by declaring the fields volatile and/or using java.util.concurrent's AtomicFoo wrappers).

Synchronization in general is a bit clumsy, as it slaps a big lock down rather than thinking exactly how threads might be allowed to work around each other. Using synchronized(this) is even clumsier and anti-social, as it's saying "no-one may change anything on this class while I hold the lock". How often do you actually need to do that?

I would much rather have more granular locks; even if you do want to stop everything from changing (perhaps you're serialising the object), you can just acquire all of the locks to achieve the same thing, plus it's more explicit that way. When you use synchronized(this), it's not clear exactly why you're synchronizing, or what the side effects might be. If you use synchronized(labelMonitor), or even better labelLock.getWriteLock().lock(), it's clear what you are doing and what the effects of your critical section are limited to.

How to linebreak an svg text within javascript?

I think this does what you want:

function ShowTooltip(evt, mouseovertext){
    // Make tooltip text        
    var tooltip_text = tt.childNodes.item(1);
    var words = mouseovertext.split("\\\n");
    var max_length = 0;

    for (var i=0; i<3; i++){
        tooltip_text.childNodes.item(i).firstChild.data = i<words.length ?  words[i] : " ";
        length = tooltip_text.childNodes.item(i).getComputedTextLength();
        if (length > max_length) {max_length = length;}
    }

    var x = evt.clientX + 14 + max_length/2;
    var y = evt.clientY + 29;
    tt.setAttributeNS(null,"transform", "translate(" + x + " " + y + ")")

    // Make tooltip background
    bg.setAttributeNS(null,"width", max_length+15);
    bg.setAttributeNS(null,"height", words.length*15+6);
    bg.setAttributeNS(null,"x",evt.clientX+8);
    bg.setAttributeNS(null,"y",evt.clientY+14);

    // Show everything
    tt.setAttributeNS(null,"visibility","visible");
    bg.setAttributeNS(null,"visibility","visible");
}

It splits the text on \\\n and for each puts each fragment in a tspan. Then it calculates the size of the box required based on the longest length of text and the number of lines. You will also need to change the tooltip text element to contain three tspans:

<g id="tooltip" visibility="hidden">
    <text><tspan>x</tspan><tspan x="0" dy="15">x</tspan><tspan x="0" dy="15">x</tspan></text>
</g>

This assumes that you never have more than three lines. If you want more than three lines you can add more tspans and increase the length of the for loop.

document.getElementById('btnid').disabled is not working in firefox and chrome

There are always weird issues with browser support of getElementById, try using the following instead:

// document.getElementsBySelector are part of the prototype.js library available at http://api.prototypejs.org/dom/Element/prototype/getElementsBySelector/

function disbtn(e) { 
    if ( someCondition == true ) {
        document.getElementsBySelector("#btn1")[0].setAttribute("disabled", "disabled");
    } else {
        document.getElementsBySelector("#btn1")[0].removeAttribute("disabled");
    }    
}

Alternatively, embrace jQuery where you could simply do this:

function disbtn(e) { 
    if ( someCondition == true ) {
        $("#btn1").attr("disabled", "disabled");
    } else {
        $("#btn1").removeAttr("disabled");
    }    
}

What is the difference between #include <filename> and #include "filename"?

#include <abc.h>

is used to include standard library files. So the compiler will check in the locations where standard library headers are residing.

#include "xyz.h"

will tell the compiler to include user-defined header files. So the compiler will check for these header files in the current folder or -I defined folders.

Loop through JSON in EJS

JSON.stringify returns a String. So, for example:

var data = [
    { id: 1, name: "bob" },
    { id: 2, name: "john" },
    { id: 3, name: "jake" },
];

JSON.stringify(data)

will return the equivalent of:

"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]"

as a String value.

So when you have

<% for(var i=0; i<JSON.stringify(data).length; i++) {%>

what that ends up looking like is:

<% for(var i=0; i<"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]".length; i++) {%>

which is probably not what you want. What you probably do want is something like this:

<table>
<% for(var i=0; i < data.length; i++) { %>
   <tr>
     <td><%= data[i].id %></td>
     <td><%= data[i].name %></td>
   </tr>
<% } %>
</table>

This will output the following table (using the example data from above):

<table>
  <tr>
    <td>1</td>
    <td>bob</td>
  </tr>
  <tr>
    <td>2</td>
    <td>john</td>
  </tr>
  <tr>
    <td>3</td>
    <td>jake</td>
  </tr>
</table>

Include PHP inside JavaScript (.js) files

This is somewhat tricky since PHP gets evaluated server-side and javascript gets evaluated client side.

I would call your PHP file using an AJAX call from inside javascript and then use JS to insert the returned HTML somewhere on your page.

How to modify PATH for Homebrew?

Just run the following line in your favorite terminal application:

echo export PATH="/usr/local/bin:$PATH" >> ~/.bash_profile

Restart your terminal and run

brew doctor

the issue should be resolved

How do I filter an array with AngularJS and use a property of the filtered object as the ng-model attribute?

You can use the "filter" filter in your controller to get all the "C" grades. Getting the first element of the result array will give you the title of the subject that has grade "C".

$scope.gradeC = $filter('filter')($scope.results.subjects, {grade: 'C'})[0];

http://jsbin.com/ewitun/1/edit

The same with plain ES6:

$scope.gradeC = $scope.results.subjects.filter((subject) => subject.grade === 'C')[0]

XPath contains(text(),'some string') doesn't work when used with node with more than one Text subnode

It took me a little while but finally figured out. Custom xpath that contains some text below worked perfectly for me.

//a[contains(text(),'JB-')]

Assembly - JG/JNLE/JL/JNGE after CMP

When you do a cmp a,b, the flags are set as if you had calculated a - b.

Then the jmp-type instructions check those flags to see if the jump should be made.

In other words, the first block of code you have (with my comments added):

cmp al,dl     ; set flags based on the comparison
jg label1     ; then jump based on the flags

would jump to label1 if and only if al was greater than dl.

You're probably better off thinking of it as al > dl but the two choices you have there are mathematically equivalent:

al > dl
al - dl > dl - dl (subtract dl from both sides)
al - dl > 0       (cancel the terms on the right hand side)

You need to be careful when using jg inasmuch as it assumes your values were signed. So, if you compare the bytes 101 (101 in two's complement) with 200 (-56 in two's complement), the former will actually be greater. If that's not what was desired, you should use the equivalent unsigned comparison.

See here for more detail on jump selection, reproduced below for completeness. First the ones where signed-ness is not appropriate:

+--------+------------------------------+-------------+--------------------+
|Instr   | Description                  | signed-ness | Flags              |
+--------+------------------------------+-------------+--------------------+
| JO     | Jump if overflow             |             | OF = 1             |
+--------+------------------------------+-------------+--------------------+
| JNO    | Jump if not overflow         |             | OF = 0             |
+--------+------------------------------+-------------+--------------------+
| JS     | Jump if sign                 |             | SF = 1             |
+--------+------------------------------+-------------+--------------------+
| JNS    | Jump if not sign             |             | SF = 0             |
+--------+------------------------------+-------------+--------------------+
| JE/    | Jump if equal                |             | ZF = 1             |
| JZ     | Jump if zero                 |             |                    |
+--------+------------------------------+-------------+--------------------+
| JNE/   | Jump if not equal            |             | ZF = 0             |
| JNZ    | Jump if not zero             |             |                    |
+--------+------------------------------+-------------+--------------------+
| JP/    | Jump if parity               |             | PF = 1             |
| JPE    | Jump if parity even          |             |                    |
+--------+------------------------------+-------------+--------------------+
| JNP/   | Jump if no parity            |             | PF = 0             |
| JPO    | Jump if parity odd           |             |                    |
+--------+------------------------------+-------------+--------------------+
| JCXZ/  | Jump if CX is zero           |             | CX = 0             |
| JECXZ  | Jump if ECX is zero          |             | ECX = 0            |
+--------+------------------------------+-------------+--------------------+

Then the unsigned ones:

+--------+------------------------------+-------------+--------------------+
|Instr   | Description                  | signed-ness | Flags              |
+--------+------------------------------+-------------+--------------------+
| JB/    | Jump if below                | unsigned    | CF = 1             |
| JNAE/  | Jump if not above or equal   |             |                    |
| JC     | Jump if carry                |             |                    |
+--------+------------------------------+-------------+--------------------+
| JNB/   | Jump if not below            | unsigned    | CF = 0             |
| JAE/   | Jump if above or equal       |             |                    |
| JNC    | Jump if not carry            |             |                    |
+--------+------------------------------+-------------+--------------------+
| JBE/   | Jump if below or equal       | unsigned    | CF = 1 or ZF = 1   |
| JNA    | Jump if not above            |             |                    |
+--------+------------------------------+-------------+--------------------+
| JA/    | Jump if above                | unsigned    | CF = 0 and ZF = 0  |
| JNBE   | Jump if not below or equal   |             |                    |
+--------+------------------------------+-------------+--------------------+

And, finally, the signed ones:

+--------+------------------------------+-------------+--------------------+
|Instr   | Description                  | signed-ness | Flags              |
+--------+------------------------------+-------------+--------------------+
| JL/    | Jump if less                 | signed      | SF <> OF           |
| JNGE   | Jump if not greater or equal |             |                    |
+--------+------------------------------+-------------+--------------------+
| JGE/   | Jump if greater or equal     | signed      | SF = OF            |
| JNL    | Jump if not less             |             |                    |
+--------+------------------------------+-------------+--------------------+
| JLE/   | Jump if less or equal        | signed      | ZF = 1 or SF <> OF |
| JNG    | Jump if not greater          |             |                    |
+--------+------------------------------+-------------+--------------------+
| JG/    | Jump if greater              | signed      | ZF = 0 and SF = OF |
| JNLE   | Jump if not less or equal    |             |                    |
+--------+------------------------------+-------------+--------------------+

Asp.net Validation of viewstate MAC failed

If you're using a web farm and running the same application on multiple computers, you need to define the machine key explicitly in the machine.config file:

<machineKey validationKey="JFDSGOIEURTJKTREKOIRUWTKLRJTKUROIUFLKSIOSUGOIFDS..." decryptionKey="KAJDFOIAUOILKER534095U43098435H43OI5098479854" validation="SHA1" />

Put it under the <system.web> tag.

The AutoGenerate for the machine code can not be used. To generate your own machineKey see this powershell script: https://support.microsoft.com/en-us/kb/2915218#bookmark-appendixa

SQL multiple column ordering

SELECT  *
FROM    mytable
ORDER BY
        column1 DESC, column2 ASC

Creating Unicode character from its number

This one worked fine for me.

  String cc2 = "2202";
  String text2 = String.valueOf(Character.toChars(Integer.parseInt(cc2, 16)));

Now text2 will have ?.

npm install won't install devDependencies

Check if npm config production value is set to true. If this value is true, it will skip over the dev dependencies.

Run npm config get production

To set it: npm config set -g production false

Creating a pandas DataFrame from columns of other DataFrames with similar indexes

You can use concat:

In [11]: pd.concat([df1['c'], df2['c']], axis=1, keys=['df1', 'df2'])
Out[11]: 
                 df1       df2
2014-01-01       NaN -0.978535
2014-01-02 -0.106510 -0.519239
2014-01-03 -0.846100 -0.313153
2014-01-04 -0.014253 -1.040702
2014-01-05  0.315156 -0.329967
2014-01-06 -0.510577 -0.940901
2014-01-07       NaN -0.024608
2014-01-08       NaN -1.791899

[8 rows x 2 columns]

The axis argument determines the way the DataFrames are stacked:

df1 = pd.DataFrame([1, 2, 3])
df2 = pd.DataFrame(['a', 'b', 'c'])

pd.concat([df1, df2], axis=0)
   0
0  1
1  2
2  3
0  a
1  b
2  c

pd.concat([df1, df2], axis=1)

   0  0
0  1  a
1  2  b
2  3  c

Is if(document.getElementById('something')!=null) identical to if(document.getElementById('something'))?

Just do it like this:

if(!document.getElementById("someId") { /Some code. Note the NOT (!) in the expresion/ };

If element with id "someId" does not exist expresion will return TRUE (NOT FALSE === TRUE) or !false === true;

try this code:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="format-detection" content="telephone-no">
        <meta name="viewport" content="user-scalable=no, initial-scale=1, minimum-scale=1, maximum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi">
        <title>Test</title>
    </head>
    <body>
      <script>
var createPerson = function (name) {
    var person;
    if (!document.getElementById(name)) {
        alert("Element does not exist. Let's create it.");
      person = document.createElement("div");
//add argument name as the ID of the element
      person.id = name;
//append element to the body of the document
      document.body.appendChild(person);
    } else {
        alert("Element exists. Lets get it by ID!");
      person = document.getElementById(name);
    }
    person.innerHTML = "HI THERE!";

};
//run the function.
createPerson("someid");
          </script>
       </body>
</html>

Try this in your browser and it should alert "Element does not exist. Let's create it."

Now add

<div id="someid"></div>

to the body of the page and try again. Voila! :)

Node.js - Maximum call stack size exceeded

You can use loop for.

var items = {1, 2, 3}
for(var i = 0; i < items.length; i++) {
  if(i == items.length - 1) {
    res.ok(i);
  }
}

Difference between matches() and find() in Java Regex

find() will consider the sub-string against the regular expression where as matches() will consider complete expression.

find() will returns true only if the sub-string of the expression matches the pattern.

public static void main(String[] args) {
        Pattern p = Pattern.compile("\\d");
        String candidate = "Java123";
        Matcher m = p.matcher(candidate);

        if (m != null){
            System.out.println(m.find());//true
            System.out.println(m.matches());//false
        }
    }

Difference between object and class in Scala

The formal difference -

  1. you can not provide constructor parameters for Objects
  2. Object is not a type - you may not create an instance with new operator. But it can have fields, methods, extend a superclass and mix in traits.

The difference in usage:

  • Scala doesn't have static methods or fields. Instead you should use object. You can use it with or without related class. In 1st case it's called a companion object. You have to:
    1. use the same name for both class and object
    2. put them in the same source file.
  • To create a program you should use main method in object, not in class.

    object Hello {
      def main(args: Array[String]) {
        println("Hello, World!")
      }
    }
    
  • You also may use it as you use singleton object in java.

      
        
      

How to clear Route Caching on server: Laravel 5.2.37

If you want to remove the routes cache on your server, remove this file:

bootstrap/cache/routes.php

And if you want to update it just run php artisan route:cache and upload the bootstrap/cache/routes.php to your server.

How to equalize the scales of x-axis and y-axis in Python matplotlib?

You need to dig a bit deeper into the api to do this:

from matplotlib import pyplot as plt
plt.plot(range(5))
plt.xlim(-3, 3)
plt.ylim(-3, 3)
plt.gca().set_aspect('equal', adjustable='box')
plt.draw()

doc for set_aspect

hide/show a image in jquery

Use the .css() jQuery manipulators, or better yet just call .show()/.hide() on the image once you've obtained a handle to it (e.g. $('#img' + id)).

BTW, you should not write javascript handlers with the "javascript:" prefix.

Is there a C# String.Format() equivalent in JavaScript?

Try sprintf() for javascript.

Or

// First, checks if it isn't implemented yet.
if (!String.prototype.format) {
  String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] != 'undefined'
        ? args[number]
        : match
      ;
    });
  };
}

"{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET")

Both answers pulled from JavaScript equivalent to printf/string.format

Message "Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout"

For those who are looking for an explanation about jest --runInBand, you can go to the documentation.

Running Puppeteer in CI environments

GitHub - smooth-code/jest-puppeteer: Run your tests using Jest & Puppeteer

Show Youtube video source into HTML5 video tag?

I have created a realtively small (4.89 KB) javascript library for this exact functionality.

Found on my GitHub here: https://github.com/thelevicole/youtube-to-html5-loader/

It's as simple as:

<video data-yt2html5="https://www.youtube.com/watch?v=ScMzIvxBSi4"></video>

<script src="https://cdn.jsdelivr.net/gh/thelevicole/[email protected]/dist/YouTubeToHtml5.js"></script>
<script>new YouTubeToHtml5();</script>

Working example here: https://jsfiddle.net/thelevicole/5g6dbpx3/1/

What the library does is extract the video ID from the data attribute and makes a request to the https://www.youtube.com/get_video_info?video_id=. It decodes the response which includes streaming information we can use to add a source to the <video> tag.

How to remove text before | character in notepad++

Please use regex to remove anything before |

example

dsfdf | fdfsfsf
dsdss|gfghhghg
dsdsds |dfdsfsds

Use find and replace in notepad++

find: .+(\|) replace: \1

output

| fdfsfsf
|gfghhghg
|dfdsfsds

Rails has_many with alias name

To complete @SamSaffron's answer :

You can use class_name with either foreign_key or inverse_of. I personally prefer the more abstract declarative, but it's really just a matter of taste :

class BlogPost
  has_many :images, class_name: "BlogPostImage", inverse_of: :blog_post  
end

and you need to make sure you have the belongs_to attribute on the child model:

class BlogPostImage
  belongs_to :blog_post
end

How does the "this" keyword work?

this in JavaScript always refers to the 'owner' of the function that is being executed.

If no explicit owner is defined, then the top most owner, the window object, is referenced.

So if I did

function someKindOfFunction() {
   this.style = 'foo';
}

element.onclick = someKindOfFunction;

this would refer to the element object. But be careful, a lot of people make this mistake.

<element onclick="someKindOfFunction()">

In the latter case, you merely reference the function, not hand it over to the element. Therefore, this will refer to the window object.

How to change cursor from pointer to finger using jQuery?

How do you change your cursor to the finger (like for clicking on links) instead of the regular pointer?

This is very simple to achieve using the CSS property cursor, no jQuery needed.

You can read more about in: CSS cursor property and cursor - CSS | MDN

_x000D_
_x000D_
.default {_x000D_
  cursor: default;_x000D_
}_x000D_
.pointer {_x000D_
  cursor: pointer;_x000D_
}
_x000D_
<a class="default" href="#">default</a>_x000D_
_x000D_
<a class="pointer" href="#">pointer</a>
_x000D_
_x000D_
_x000D_

"Items collection must be empty before using ItemsSource."

I just ran into a VERY insidious example of this problem. My original fragment was much more complex, which made it difficult to see the error.

   <ItemsControl           
      Foreground="Black"  Background="White" Grid.IsSharedSizingScope="True"
      x:Name="MyGrid" ItemsSource="{Binding}">
      >
      <ItemsControl.ItemsPanel>
           <!-- All is fine here -->
      </ItemsControl.ItemsPanel>
      <ItemsControl.ItemTemplate>
           <!-- All is fine here -->
      </ItemsControl.ItemTemplate>
      <!-- Have you caught the error yet? -->
    </ItemsControl>

The bug? The extra > after the initial opening <ItemsControl> tag! The < got applied to the built-in Items collection. When the DataContext was later set, instant crashola. So look out for more than just errors surround your ItemsControl specific data children when debugging this problem.

Ansible: filter a list by its attributes

To filter a list of dicts you can use the selectattr filter together with the equalto test:

network.addresses.private_man | selectattr("type", "equalto", "fixed")

The above requires Jinja2 v2.8 or later (regardless of Ansible version).


Ansible also has the tests match and search, which take regular expressions:

match will require a complete match in the string, while search will require a match inside of the string.

network.addresses.private_man | selectattr("type", "match", "^fixed$")

To reduce the list of dicts to a list of strings, so you only get a list of the addr fields, you can use the map filter:

... | map(attribute='addr') | list

Or if you want a comma separated string:

... | map(attribute='addr') | join(',')

Combined, it would look like this.

- debug: msg={{ network.addresses.private_man | selectattr("type", "equalto", "fixed") | map(attribute='addr') | join(',') }}

How can I convert a .py to .exe for Python?

There is an open source project called auto-py-to-exe on GitHub. Actually it also just uses PyInstaller internally but since it is has a simple GUI that controls PyInstaller it may be a comfortable alternative. It can also output a standalone file in contrast to other solutions. They also provide a video showing how to set it up.

GUI:

Auto Py to Exe

Output:

Output

Alarm Manager Example

MainActivity.java

package com.example.alarmexample;  

import android.app.Activity;  
import android.app.AlarmManager;  
import android.app.PendingIntent;  
import android.content.Intent;  
import android.os.Bundle;  
import android.view.View;  
import android.view.View.OnClickListener;  
import android.widget.Button;  
import android.widget.EditText;  
import android.widget.Toast;  

public class MainActivity extends Activity {  
Button b1;  

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

        startAlert();  

}   public void startAlert() { 
        int timeInSec = 2;

        Intent intent = new Intent(this, MyBroadcastReceiver.class);  
        PendingIntent pendingIntent = PendingIntent.getBroadcast(  
                                      this.getApplicationContext(), 234, intent, 0);  
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);  
        alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (timeInSec * 1000), pendingIntent);  
        Toast.makeText(this, "Alarm set to after " + i + " seconds",Toast.LENGTH_LONG).show();  
    }  

}

MyBroadcastReceiver.java

package com.example.alarmexample;  

import android.content.BroadcastReceiver;  
import android.content.Context;  
import android.content.Intent;  
import android.media.MediaPlayer;  
import android.widget.Toast;  

public class MyBroadcastReceiver extends BroadcastReceiver {  
    MediaPlayer mp;  
    @Override  
    public void onReceive(Context context, Intent intent) {  
        mp=MediaPlayer.create(context, R.raw.alarm);  
        mp.start();  
        Toast.makeText(context, "Alarm", Toast.LENGTH_LONG).show();  
    }  
}  

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>  
<manifest xmlns:android="http://schemas.android.com/apk/res/android"  
    package="com.example.alarmexample" >  

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


    <application  
        android:allowBackup="true"  
        android:icon="@drawable/ic_launcher"  
        android:label="@string/app_name"  
        android:theme="@style/AppTheme" >  

        <activity  
            android:name="com.example.alarmexample.MainActivity"  
            android:label="@string/app_name" >  
            <intent-filter>  
                <action android:name="android.intent.action.MAIN" />  

                <category android:name="android.intent.category.LAUNCHER" />  
            </intent-filter>  
        </activity>  

        <receiver android:name="MyBroadcastReceiver" >  
        </receiver>  
    </application>  

</manifest>  

How to select <td> of the <table> with javascript?

There are a lot of ways to accomplish this, and this is but one of them.

$("table").find("tbody td").eq(0).children().first()

Excel VBA Password via Hex Editor

  1. Open xls file with a hex editor.
  2. Search for DPB
  3. Replace DPB to DPx
  4. Save file.
  5. Open file in Excel.
  6. Click "Yes" if you get any message box.
  7. Set new password from VBA Project Properties.
  8. Close and open again file, then type your new password to unprotect.

Check http://blog.getspool.com/396/best-vba-password-recovery-cracker-tool-remove/

NumPy ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

The error message explains it pretty well:

ValueError: The truth value of an array with more than one element is ambiguous. 
Use a.any() or a.all()

What should bool(np.array([False, False, True])) return? You can make several plausible arguments:

(1) True, because bool(np.array(x)) should return the same as bool(list(x)), and non-empty lists are truelike;

(2) True, because at least one element is True;

(3) False, because not all elements are True;

and that's not even considering the complexity of the N-d case.

So, since "the truth value of an array with more than one element is ambiguous", you should use .any() or .all(), for example:

>>> v = np.array([1,2,3]) == np.array([1,2,4])
>>> v
array([ True,  True, False], dtype=bool)
>>> v.any()
True
>>> v.all()
False

and you might want to consider np.allclose if you're comparing arrays of floats:

>>> np.allclose(np.array([1,2,3+1e-8]), np.array([1,2,3]))
True

Visual Studio 2017: Display method references

For anyone who looks at this today after 2 years, Visual Studio 2019 (Community edition as well) shows the references

Change directory in PowerShell

Multiple posted answer here, but probably this can help who is newly using PowerShell

enter image description here

SO if any space is there in your directory path do not forgot to add double inverted commas "".

Not Able To Debug App In Android Studio

    <application android:debuggable="true">
</application>

This no longer works! No need to use debuggable="true" in manifest.

Instead, you should set the Build Variants to "debug"

Debug Mode

In Android Studio, go to BUILD -> Select Build Variant

Now try debugging. Thanks

python: order a list of numbers without built-in sort, min, max function

try sorting list , char have the ascii code, the same can be used for sorting the list of char.

aw=[1,2,2,1,1,3,5,342,345,56,2,35,436,6,576,54,76,47,658,8758,87,878]
for i in range(aw.__len__()):
    for j in range(aw.__len__()):
        if aw[i] < aw[j] :aw[i],aw[j]=aw[j],aw[i]

In-place edits with sed on OS X

The -i flag probably doesn't work for you, because you followed an example for GNU sed while macOS uses BSD sed and they have a slightly different syntax.

All the other answers tell you how to correct the syntax to work with BSD sed. The alternative is to install GNU sed on your macOS with:

brew install gsed

and then use it instead of the sed version shipped with macOS (note the g prefix), e.g:

gsed -i 's/oldword/newword/' file1.txt

If you want GNU sed commands to be always portable to your macOS, you could prepend "gnubin" directory to your path, by adding something like this to your .bashrc/.zshrc file (run brew info gsed to see what exactly you need to do):

export PATH="/usr/local/opt/gnu-sed/libexec/gnubin:$PATH"

and from then on the GNU sed becomes your default sed and you can simply run:

sed -i 's/oldword/newword/' file1.txt

How can I determine whether a specific file is open in Windows?

One equivalent of lsof could be combined output from Sysinternals' handle and listdlls, i.e.:

c:\SysInternals>handle
[...]
------------------------------------------------------------------------------
gvim.exe pid: 5380 FOO\alois.mahdal
   10: File  (RW-)   C:\Windows
   1C: File  (RW-)   D:\some\locked\path\OpenFile.txt
[...]

c:\SysInternals>listdlls
[...]
------------------------------------------------------------------------------
Listdlls.exe pid: 6840
Command line: listdlls

  Base        Size      Version         Path
  0x00400000  0x29000   2.25.0000.0000  D:\opt\SysinternalsSuite\Listdlls.exe
  0x76ed0000  0x180000  6.01.7601.17725  C:\Windows\SysWOW64\ntdll.dll
[...]

c:\SysInternals>listdlls

Unfortunately, you have to "run as Administrator" to be able to use them.

Also listdlls and handle do not produce continuous table-like form so filtering filename would hide PID. findstr /c:pid: /c:<filename> should get you very close with both utilities, though

c:\SysinternalsSuite>handle | findstr /c:pid: /c:Driver.pm
System pid: 4 \<unable to open process>
smss.exe pid: 308 NT AUTHORITY\SYSTEM
avgrsa.exe pid: 384 NT AUTHORITY\SYSTEM
[...]
cmd.exe pid: 7140 FOO\alois.mahdal
conhost.exe pid: 1212 FOO\alois.mahdal
gvim.exe pid: 3408 FOO\alois.mahdal
  188: File  (RW-)   D:\some\locked\path\OpenFile.txt
taskmgr.exe pid: 6016 FOO\alois.mahdal
[...]

Here we can see that gvim.exe is the one having this file open.

Form submit with AJAX passing form data to PHP without page refresh

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" >
  $(function () {
    $(".submit").click(function (event) {
      var time = $("#time").val();
      var date = $("#date").val();
      var dataString = 'time=' + time + '&date=' + date;
      console.log(dataString);
      if (time == '' || date == '')
      {
        $('.success').fadeOut(200).hide();
        $('.error').fadeOut(200).show();
      } else
      {
        $.ajax({
          type: "POST",
          url: "post.php",
          data: dataString,
          success: function (data) {
            $('.success').fadeIn(200).show();
            $('.error').fadeOut(200).hide();
            $("#data").html(data);
          }
        });
      }
      event.preventDefault();
    });
  });
</script>
<form action="post.php" method="POST">
  <input id="time" value=""><br>
  <input id="date" value=""><br>
  <input name="submit" type="button" value="Submit" class="submit">
</form>
<div id="data"></div>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Form Submitted Success</span>

<?php

print_r($_POST);
if ($_POST['date']) {
  $date = $_POST['date'];
  $time = $_POST['time'];
  echo '<h1>' . $date . '---' . $time . '</h1>';
}
else {

}
?>

check if directory exists and delete in one command unix

Assuming $WORKING_DIR is set to the directory... this one-liner should do it:

if [ -d "$WORKING_DIR" ]; then rm -Rf $WORKING_DIR; fi

(otherwise just replace with your directory)

Get the IP Address of local computer

Also, note that "the local IP" might not be a particularly unique thing. If you are on several physical networks (wired+wireless+bluetooth, for example, or a server with lots of Ethernet cards, etc.), or have TAP/TUN interfaces setup, your machine can easily have a whole host of interfaces.

Count lines in large files

Let us assume:

  • Your file system is distributed
  • Your file system can easily fill the network connection to a single node
  • You access your files like normal files

then you really want to chop the files into parts, count parts in parallel on multiple nodes and sum up the results from there (this is basically @Chris White's idea).

Here is how you do that with GNU Parallel (version > 20161222). You need to list the nodes in ~/.parallel/my_cluster_hosts and you must have ssh access to all of them:

parwc() {
    # Usage:
    #   parwc -l file                                                                

    # Give one chunck per host                                                     
    chunks=$(cat ~/.parallel/my_cluster_hosts|wc -l)
    # Build commands that take a chunk each and do 'wc' on that                    
    # ("map")                                                                      
    parallel -j $chunks --block -1 --pipepart -a "$2" -vv --dryrun wc "$1" |
        # For each command                                                         
        #   log into a cluster host                                                
        #   cd to current working dir                                              
        #   execute the command                                                    
        parallel -j0 --slf my_cluster_hosts --wd . |
        # Sum up the number of lines                                               
        # ("reduce")                                                               
        perl -ne '$sum += $_; END { print $sum,"\n" }'
}

Use as:

parwc -l myfile
parwc -w myfile
parwc -c myfile

How can I scale the content of an iframe?

This was my solution on a page with 890px width

#frame { 
overflow: hidden;
position: relative;
width:1044px;
height:1600px;
-ms-zoom: 0.85;
-moz-transform: scale(0.85);
-moz-transform-origin: 0px 0;
-o-transform: scale(0.85);
-o-transform-origin: 0 0;
-webkit-transform: scale(0.85);
-webkit-transform-origin: 0 0; 

}

Float vs Decimal in ActiveRecord

I remember my CompSci professor saying never to use floats for currency.

The reason for that is how the IEEE specification defines floats in binary format. Basically, it stores sign, fraction and exponent to represent a Float. It's like a scientific notation for binary (something like +1.43*10^2). Because of that, it is impossible to store fractions and decimals in Float exactly.

That's why there is a Decimal format. If you do this:

irb:001:0> "%.47f" % (1.0/10)
=> "0.10000000000000000555111512312578270211815834045" # not "0.1"!

whereas if you just do

irb:002:0> (1.0/10).to_s
=> "0.1" # the interprer rounds the number for you

So if you are dealing with small fractions, like compounding interests, or maybe even geolocation, I would highly recommend Decimal format, since in decimal format 1.0/10 is exactly 0.1.

However, it should be noted that despite being less accurate, floats are processed faster. Here's a benchmark:

require "benchmark" 
require "bigdecimal" 

d = BigDecimal.new(3) 
f = Float(3)

time_decimal = Benchmark.measure{ (1..10000000).each { |i| d * d } } 
time_float = Benchmark.measure{ (1..10000000).each { |i| f * f } }

puts time_decimal 
#=> 6.770960 seconds 
puts time_float 
#=> 0.988070 seconds

Answer

Use float when you don't care about precision too much. For example, some scientific simulations and calculations only need up to 3 or 4 significant digits. This is useful in trading off accuracy for speed. Since they don't need precision as much as speed, they would use float.

Use decimal if you are dealing with numbers that need to be precise and sum up to correct number (like compounding interests and money-related things). Remember: if you need precision, then you should always use decimal.

How to check Elasticsearch cluster health?

The _cluster/health API can do far more than the typical output that most see with it:

 $ curl -XGET 'localhost:9200/_cluster/health?pretty'

Most APIs within Elasticsearch can take a variety of arguments to augment their output. This applies to Cluster Health API as well.

Examples

all the indices health
$ curl -XGET 'localhost:9200/_cluster/health?level=indices&pretty' | head -50
{
  "cluster_name" : "rdu-es-01",
  "status" : "green",
  "timed_out" : false,
  "number_of_nodes" : 9,
  "number_of_data_nodes" : 6,
  "active_primary_shards" : 1106,
  "active_shards" : 2213,
  "relocating_shards" : 0,
  "initializing_shards" : 0,
  "unassigned_shards" : 0,
  "delayed_unassigned_shards" : 0,
  "number_of_pending_tasks" : 0,
  "number_of_in_flight_fetch" : 0,
  "task_max_waiting_in_queue_millis" : 0,
  "active_shards_percent_as_number" : 100.0,
  "indices" : {
    "filebeat-6.5.1-2019.06.10" : {
      "status" : "green",
      "number_of_shards" : 3,
      "number_of_replicas" : 1,
      "active_primary_shards" : 3,
      "active_shards" : 6,
      "relocating_shards" : 0,
      "initializing_shards" : 0,
      "unassigned_shards" : 0
    },
    "filebeat-6.5.1-2019.06.11" : {
      "status" : "green",
      "number_of_shards" : 3,
      "number_of_replicas" : 1,
      "active_primary_shards" : 3,
      "active_shards" : 6,
      "relocating_shards" : 0,
      "initializing_shards" : 0,
      "unassigned_shards" : 0
    },
    "filebeat-6.5.1-2019.06.12" : {
      "status" : "green",
      "number_of_shards" : 3,
      "number_of_replicas" : 1,
      "active_primary_shards" : 3,
      "active_shards" : 6,
      "relocating_shards" : 0,
      "initializing_shards" : 0,
      "unassigned_shards" : 0
    },
    "filebeat-6.5.1-2019.06.13" : {
      "status" : "green",
      "number_of_shards" : 3,
all shards health
$ curl -XGET 'localhost:9200/_cluster/health?level=shards&pretty' | head -50
{
  "cluster_name" : "rdu-es-01",
  "status" : "green",
  "timed_out" : false,
  "number_of_nodes" : 9,
  "number_of_data_nodes" : 6,
  "active_primary_shards" : 1106,
  "active_shards" : 2213,
  "relocating_shards" : 0,
  "initializing_shards" : 0,
  "unassigned_shards" : 0,
  "delayed_unassigned_shards" : 0,
  "number_of_pending_tasks" : 0,
  "number_of_in_flight_fetch" : 0,
  "task_max_waiting_in_queue_millis" : 0,
  "active_shards_percent_as_number" : 100.0,
  "indices" : {
    "filebeat-6.5.1-2019.06.10" : {
      "status" : "green",
      "number_of_shards" : 3,
      "number_of_replicas" : 1,
      "active_primary_shards" : 3,
      "active_shards" : 6,
      "relocating_shards" : 0,
      "initializing_shards" : 0,
      "unassigned_shards" : 0,
      "shards" : {
        "0" : {
          "status" : "green",
          "primary_active" : true,
          "active_shards" : 2,
          "relocating_shards" : 0,
          "initializing_shards" : 0,
          "unassigned_shards" : 0
        },
        "1" : {
          "status" : "green",
          "primary_active" : true,
          "active_shards" : 2,
          "relocating_shards" : 0,
          "initializing_shards" : 0,
          "unassigned_shards" : 0
        },
        "2" : {
          "status" : "green",
          "primary_active" : true,
          "active_shards" : 2,
          "relocating_shards" : 0,
          "initializing_shards" : 0,
          "unassigned_shards" : 0

The API also has a variety of wait_* options where it'll wait for various state changes before returning immediately or after some specified timeout.

Named regular expression group "(?P<group_name>regexp)": what does "P" stand for?

Since we're all guessing, I might as well give mine: I've always thought it stood for Python. That may sound pretty stupid -- what, P for Python?! -- but in my defense, I vaguely remembered this thread [emphasis mine]:

Subject: Claiming (?P...) regex syntax extensions

From: Guido van Rossum ([email protected])

Date: Dec 10, 1997 3:36:19 pm

I have an unusual request for the Perl developers (those that develop the Perl language). I hope this (perl5-porters) is the right list. I am cc'ing the Python string-sig because it is the origin of most of the work I'm discussing here.

You are probably aware of Python. I am Python's creator; I am planning to release a next "major" version, Python 1.5, by the end of this year. I hope that Python and Perl can co-exist in years to come; cross-pollination can be good for both languages. (I believe Larry had a good look at Python when he added objects to Perl 5; O'Reilly publishes books about both languages.)

As you may know, Python 1.5 adds a new regular expression module that more closely matches Perl's syntax. We've tried to be as close to the Perl syntax as possible within Python's syntax. However, the regex syntax has some Python-specific extensions, which all begin with (?P . Currently there are two of them:

(?P<foo>...) Similar to regular grouping parentheses, but the text
matched by the group is accessible after the match has been performed, via the symbolic group name "foo".

(?P=foo) Matches the same string as that matched by the group named "foo". Equivalent to \1, \2, etc. except that the group is referred
to by name, not number.

I hope that this Python-specific extension won't conflict with any future Perl extensions to the Perl regex syntax. If you have plans to use (?P, please let us know as soon as possible so we can resolve the conflict. Otherwise, it would be nice if the (?P syntax could be permanently reserved for Python-specific syntax extensions. (Is there some kind of registry of extensions?)

to which Larry Wall replied:

[...] There's no registry as of now--yours is the first request from outside perl5-porters, so it's a pretty low-bandwidth activity. (Sorry it was even lower last week--I was off in New York at Internet World.)

Anyway, as far as I'm concerned, you may certainly have 'P' with my blessing. (Obviously Perl doesn't need the 'P' at this point. :-) [...]

So I don't know what the original choice of P was motivated by -- pattern? placeholder? penguins? -- but you can understand why I've always associated it with Python. Which considering that (1) I don't like regular expressions and avoid them wherever possible, and (2) this thread happened fifteen years ago, is kind of odd.

How to configure "Shorten command line" method for whole project in IntelliJ

Inside your .idea folder, change workspace.xml file

Add

<property name="dynamic.classpath" value="true" />

to

  <component name="PropertiesComponent">
.
.
.
  </component>

Example

 <component name="PropertiesComponent">
    <property name="project.structure.last.edited" value="Project" />
    <property name="project.structure.proportion" value="0.0" />
    <property name="project.structure.side.proportion" value="0.0" />
    <property name="settings.editor.selected.configurable" value="preferences.pluginManager" />
    <property name="dynamic.classpath" value="true" />
  </component>

If you don't see one, feel free to add it yourself

 <component name="PropertiesComponent">
    <property name="dynamic.classpath" value="true" />
  </component>

Does GPS require Internet?

There are two issues:

  1. Getting the current coordinates (longitude, latitude, perhaps altitude) based on some external signals received by your device, and
  2. Deriving a human-readable position (address) from the coordinates.

To get the coordinates you don't need the Internet. GPS is satellite-based. But to derive street/city information from the coordinates, you'd need either to implement the map and the corresponding algorithms yourself on the device (a lot of work!) or to rely on proven services, e.g. by Google, in which case you'd need an Internet connection.

As of recently, Google allows for caching the maps, which would at least allow you to show your current position on the map even without a data connection, provided, you had cached the map in advance, when you could access the Internet.

How to return a file (FileContentResult) in ASP.NET WebAPI

I am not exactly sure which part to blame, but here's why MemoryStream doesn't work for you:

As you write to MemoryStream, it increments it's Position property. The constructor of StreamContent takes into account the stream's current Position. So if you write to the stream, then pass it to StreamContent, the response will start from the nothingness at the end of the stream.

There's two ways to properly fix this:

1) construct content, write to stream

[HttpGet]
public HttpResponseMessage Test()
{
    var stream = new MemoryStream();
    var response = Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new StreamContent(stream);
    // ...
    // stream.Write(...);
    // ...
    return response;
}

2) write to stream, reset position, construct content

[HttpGet]
public HttpResponseMessage Test()
{
    var stream = new MemoryStream();
    // ...
    // stream.Write(...);
    // ...
    stream.Position = 0;

    var response = Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new StreamContent(stream);
    return response;
}

2) looks a little better if you have a fresh Stream, 1) is simpler if your stream does not start at 0

What does print(... sep='', '\t' ) mean?

sep='\t' is often used for Tab-delimited file.

Apache error: _default_ virtualhost overlap on port 443

I ran into this problem because I had multiple wildcard entries for the same ports. You can easily check this by executing apache2ctl -S:

# apache2ctl -S
[Wed Oct 22 18:02:18 2014] [warn] _default_ VirtualHost overlap on port 30000, the first has precedence
[Wed Oct 22 18:02:18 2014] [warn] _default_ VirtualHost overlap on port 20001, the first has precedence
VirtualHost configuration:
11.22.33.44:80       is a NameVirtualHost
         default server xxx.com (/etc/apache2/sites-enabled/xxx.com.conf:1)
         port 80 namevhost xxx.com (/etc/apache2/sites-enabled/xxx.com.conf:1)
         [...]
11.22.33.44:443      is a NameVirtualHost
         default server yyy.com (/etc/apache2/sites-enabled/yyy.com.conf:37)
         port 443 namevhost yyy.com (/etc/apache2/sites-enabled/yyy.com.conf:37)
wildcard NameVirtualHosts and _default_ servers:
*:80                   hostname.com (/etc/apache2/sites-enabled/000-default:1)
*:20001                hostname.com (/etc/apache2/sites-enabled/000-default:33)
*:30000                hostname.com (/etc/apache2/sites-enabled/000-default:57)
_default_:443          hostname.com (/etc/apache2/sites-enabled/default-ssl:2)
*:20001                hostname.com (/etc/apache2/sites-enabled/default-ssl:163)
*:30000                hostname.com (/etc/apache2/sites-enabled/default-ssl:178)
Syntax OK

Notice how at the beginning of the output are a couple of warning lines. These will indicate which ports are creating the problems (however you probably already knew that).

Next, look at the end of the output and you can see exactly which files and lines the virtualhosts are defined that are creating the problem. In the above example, port 20001 is assigned both in /etc/apache2/sites-enabled/000-default on line 33 and /etc/apache2/sites-enabled/default-ssl on line 163. Likewise *:30000 is listed in 2 places. The solution (in my case) was simply to delete one of the entries.

How to handle Pop-up in Selenium WebDriver using Java

To switch to a popup window, you need to use getWindowHandles() and iterate through them.

In your code you are using getWindowHandle() which will give you the parent window itself.

String parentWindowHandler = driver.getWindowHandle(); // Store your parent window
String subWindowHandler = null;

Set<String> handles = driver.getWindowHandles(); // get all window handles
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()){
    subWindowHandler = iterator.next();
}
driver.switchTo().window(subWindowHandler); // switch to popup window

// Now you are in the popup window, perform necessary actions here

driver.switchTo().window(parentWindowHandler);  // switch back to parent window

Removing elements from array Ruby

For speed, I would do the following, which requires only one pass through each of the two arrays. This method preserves order. I will first present code that does not mutate the original array, then show how it can be easily modified to mutate.

arr = [1,1,1,2,2,3,1]
removals = [1,3,1]

h = removals.group_by(&:itself).transform_values(&:size)
  #=> {1=>2, 3=>1} 
arr.each_with_object([]) { |n,a|
  h.key?(n) && h[n] > 0 ? (h[n] -= 1) : a << n }
  #=> [1, 2, 2, 1]

arr
  #=> [1, 1, 1, 2, 2, 3, 1] 

To mutate arr write:

h = removals.group_by(&:itself).transform_values(&:count)
arr.replace(arr.each_with_object([]) { |n,a|
  h.key?(n) && h[n] > 0 ? (h[n] -= 1) : a << n })
  #=> [1, 2, 2, 1]

arr
  #=> [1, 2, 2, 1]

This uses the 21st century method Hash#transform_values (new in MRI v2.4), but one could instead write:

h = Hash[removals.group_by(&:itself).map { |k,v| [k,v.size] }]

or

h = removals.each_with_object(Hash.new(0)) { | n,h| h[n] += 1 }

GCC: array type has incomplete element type

The compiler needs to know the size of the second dimension in your two dimensional array. For example:

void print_graph(g_node graph_node[], double weight[][5], int nodes);

Cannot read property 'push' of undefined when combining arrays

In most cases you have to initialize the array,

let list: number[] = [];

How to embed a SWF file in an HTML page?

How about simple HTML5 tag embed?

<!DOCTYPE html>
<html>
<body>

<embed src="anim.swf">

</body>
</html>

How can I parse a YAML file from a Linux shell script?

I know my answer is specific, but if one already has PHP and Symfony installed, it can be very handy to use Symfony's YAML parser.

For instance:

php -r "require '$SYMFONY_ROOT_PATH/vendor/autoload.php'; \
    var_dump(\Symfony\Component\Yaml\Yaml::parse(file_get_contents('$YAML_FILE_PATH')));"

Here I simply used var_dump to output the parsed array but of course you can do much more... :)

How to checkout in Git by date?

To those who prefer a pipe to command substitution

git rev-list -n1 --before=2013-7-4 master | xargs git checkout

How can I interrupt a running code in R with a keyboard command?

I know this is old, but I ran into the same issue. I'm on a Mac/Ubuntu and switch back and forth. What I have found is that just sending a simple interrupt signal to the main R process does exactly what you're looking for. I've ran scripts that went on for as long as 24 hours and the signal interrupt works very well. You should be able to run kill in terminal:

$ kill -2 pid

You can find the pid by running

$ps aux | grep exec/R

Not sure about Windows since I'm not ever on there, but I can't imagine there's not an option to do this as well in Command Prompt/Task Manager

Hope this helps!

wamp server mysql user id and password

Go to http://localhost/phpmyadmin and click on the Privileges tab. There is a "Add a new user" link. alt text

How can I import Swift code to Objective-C?

Be careful with dashes and underscores, they can be mixed up and your Project Name and Target name won't be the same as SWIFT_MODULE_NAME.

Dashes and underscores

Hibernate Criteria for Dates

If the column is a timestamp you can do the following:

        if(fromDate!=null){
            criteria.add(Restrictions.sqlRestriction("TRUNC(COLUMN) >= TO_DATE('" + dataFrom + "','dd/mm/yyyy')"));
        }
        if(toDate!=null){               
            criteria.add(Restrictions.sqlRestriction("TRUNC(COLUMN) <= TO_DATE('" + dataTo + "','dd/mm/yyyy')"));
        }

        resultDB = criteria.list();

Count the Number of Tables in a SQL Server Database

You can use INFORMATION_SCHEMA.TABLES to retrieve information about your database tables.

As mentioned in the Microsoft Tables Documentation:

INFORMATION_SCHEMA.TABLES returns one row for each table in the current database for which the current user has permissions.

The following query, therefore, will return the number of tables in the specified database:

USE MyDatabase
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'

As of SQL Server 2008, you can also use sys.tables to count the the number of tables.

From the Microsoft sys.tables Documentation:

sys.tables returns a row for each user table in SQL Server.

The following query will also return the number of table in your database:

SELECT COUNT(*)
FROM sys.tables

CSS Resize/Zoom-In effect on Image while keeping Dimensions

You could achieve that simply by wrapping the image by a <div> and adding overflow: hidden to that element:

<div class="img-wrapper">
    <img src="..." />
</div>
.img-wrapper {
    display: inline-block; /* change the default display type to inline-block */
    overflow: hidden;      /* hide the overflow */
}

WORKING DEMO.


Also it's worth noting that <img> element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px gap at the bottom of the image.

That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align property to the image with a value other than baseline.

Additionally for a better user experience, you could add transition to the images.

Thus we'll end up with the following:

.img-wrapper img {
    transition: all .2s ease;
    vertical-align: middle;
}

UPDATED DEMO.

Valid characters in a Java class name

Identifiers are used for class names, method names, and variable names. An identifiermay be any descriptive sequence of uppercase and lowercase letters, numbers, or theunderscore and dollar-sign characters. They must not begin with a number, lest they beconfused with a numeric literal. Again, Java is case-sensitive, so VALUE is a differentidentifier than Value. Some examples of valid identifiers are:

AvgTemp ,count a4 ,$test ,this_is_ok

Invalid variable names include:

2count, high-temp, Not/ok

"UnboundLocalError: local variable referenced before assignment" after an if statement

I was facing same issue in my exercise. Although not related, yet might give some reference. I didn't get any error once I placed addition_result = 0 inside function. Hope it helps! Apologize if this answer is not in context.

user_input = input("Enter multiple values separated by comma > ")

def add_numbers(num_list):
    addition_result = 0
    for i in num_list:
        addition_result = addition_result + i
    print(addition_result)

add_numbers(user_input)

what's the easiest way to put space between 2 side-by-side buttons in asp.net

If you want the style to apply globally you could use the adjacent sibling combinator from css.

.my-button-style + .my-button-style {
  margin-left: 40px;
}

/* general button style */
.my-button-style {
  height: 100px;
  width: 150px;
}

Here is a fiddle: https://jsfiddle.net/caeLosby/10/

It is similar to some of the existing answers but it does not set the margin on the first button. For example in the case

<button id="btn1" class="my-button-style"/>
<button id="btn2" class="my-button-style"/>

only btn2 will get the margin.

For further information see https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_combinator

Installing tkinter on ubuntu 14.04

In Ubuntu 14.04.2 LTS:

  1. Go to Software Center and remove "IDLE(using Python-2.7)".

  2. Install "IDLE(using Python-3.4)".

Try again. This step worked for me.

How to check if smtp is working from commandline (Linux)

Not sure if this help or not but this is a command line tool which let you simply send test mails from a SMTP server priodically. http://code.google.com/p/woodpecker-tester/

What is the best way to remove the first element from an array?

Keep an index of the first "live" element of the array. Removing (pretending to remove) the first element then becomes an O(1) time complexity operation.

Change User Agent in UIWebView

Try this in the AppDelegate.m

+ (void)initialize 

{

    // Set user agent (the only problem is that we can’t modify the User-Agent later in the program)

    // iOS 5.1

    NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:@”Mozilla/5.0 (iPad; CPU OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B176 Safari/7534.48.3”, @”UserAgent”, nil];


    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];

}

Import Excel Data into PostgreSQL 9.3

You can handle loading the excel file content by writing Java code using Apache POI library (https://poi.apache.org/). The library is developed for working with MS office application data including Excel.

I have recently created the application based on the technology that will help you to load Excel files to the Postgres database. The application is available under http://www.abespalov.com/. The application is tested only for Windows, but should work for Linux as well.

The application automatically creates necessary tables with the same columns as in the Excel files and populate the tables with content. You can export several files in parallel. You can skip the step to convert the files into the CSV format. The application handles the xls and xlsx formats.

Overall application stages are :

  1. Load the excel file content. Here is the code depending on file extension:

{

fileExtension = FilenameUtils.getExtension(inputSheetFile.getName());
    if (fileExtension.equalsIgnoreCase("xlsx")) {
        workbook = createWorkbook(openOPCPackage(inputSheetFile));
    } else {
        workbook =     
        createWorkbook(openNPOIFSFileSystemPackage(inputSheetFile));
    }

sheet = workbook.getSheetAt(0);

}

  1. Establish Postgres JDBC connection
  2. Create a Postgres table
  3. Iterate over the sheet and inset rows into the table. Here is a piece of Java code :

{

Iterator<Row> rowIterator = InitInputFilesImpl.sheet.rowIterator();

//skip a header
if (rowIterator.hasNext()) {
    rowIterator.next();
}
while (rowIterator.hasNext()) {
    Row row = (Row) rowIterator.next();
    // inserting rows
}  

}

Here you can find all Java code for the application created for exporting excel to Postgres (https://github.com/palych-piter/Excel2DB).

Convert .cer certificate to .jks

keytool comes with the JDK installation (in the bin folder):

keytool -importcert -file "your.cer" -keystore your.jks -alias "<anything>"

This will create a new keystore and add just your certificate to it.

So, you can't convert a certificate to a keystore: you add a certificate to a keystore.

Rolling back local and remote git repository by 1 commit

You can also do this:

git reset --hard <commit-hash>
git push -f origin master

and have everyone else who got the latest bad commits reset:

git reset --hard origin/master

Configure nginx with multiple locations with different root folders on subdomain

server {

    index index.html index.htm;
    server_name test.example.com;

    location / {
        root /web/test.example.com/www;
    }

    location /static {
        root /web/test.example.com;
    }
}

http://nginx.org/r/root

Inline style to act as :hover in CSS

I put together a quick solution for anyone wanting to create hover popups without CSS using the onmouseover and onmouseout behaviors.

http://jsfiddle.net/Lk9w1mkv/

<div style="position:relative;width:100px;background:#ddffdd;overflow:hidden;" onmouseover="this.style.overflow='';" onmouseout="this.style.overflow='hidden';">first hover<div style="width:100px;position:absolute;top:5px;left:110px;background:white;border:1px solid gray;">stuff inside</div></div>

Adding a column to a data.frame

Approach based on identifying number of groups (x in mapply) and its length (y in mapply)

mytb<-read.table(text="h_no  h_freq  h_freqsq group
1     0.09091 0.008264628 1
2     0.00000 0.000000000 1
3     0.04545 0.002065702 1
4     0.00000 0.000000000 1  
1     0.13636 0.018594050 2
2     0.00000 0.000000000 2
3     0.00000 0.000000000 2
4     0.04545 0.002065702 2
5     0.31818 0.101238512 2
6     0.00000 0.000000000 2
7     0.50000 0.250000000 2 
1     0.13636 0.018594050 3 
2     0.09091 0.008264628 3
3     0.40909 0.167354628 3
4     0.04545 0.002065702 3", header=T, stringsAsFactors=F)
mytb$group<-NULL

positionsof1s<-grep(1,mytb$h_no)

mytb$newgroup<-unlist(mapply(function(x,y) 
  rep(x,y),                      # repeat x number y times
  x= 1:length(positionsof1s),    # x is 1 to number of nth group = g1:g3
  y= c( diff(positionsof1s),     # y is number of repeats of groups g1 to penultimate (g2) = 4, 7
        nrow(mytb)-              # this line and the following gives number of repeat for last group (g3)
          (positionsof1s[length(positionsof1s )]-1 )  # number of rows - position of penultimate group (g2) 
      ) ) )
mytb

Why can't DateTime.Parse parse UTC date

Assuming you use the format "o" for your datetime so you have "2016-07-24T18:47:36Z", there is a very simple way to handle this.

Call DateTime.Parse("2016-07-24T18:47:36Z").ToUniversalTime().

What happens when you call DateTime.Parse("2016-07-24T18:47:36Z") is you get a DateTime set to the local timezone. So it converts it to the local time.

The ToUniversalTime() changes it to a UTC DateTime and converts it back to UTC time.

How to go back last page

To go back without refreshing the page, We can do in html like below javascript:history.back()

<a class="btn btn-danger" href="javascript:history.back()">Go Back</a>

Why use def main()?

Everyone else has already answered it, but I think I still have something else to add.

Reasons to have that if statement calling main() (in no particular order):

  • Other languages (like C and Java) have a main() function that is called when the program is executed. Using this if, we can make Python behave like them, which feels more familiar for many people.

  • Code will be cleaner, easier to read, and better organized. (yeah, I know this is subjective)

  • It will be possible to import that python code as a module without nasty side-effects.

  • This means it will be possible to run tests against that code.

  • This means we can import that code into an interactive python shell and test/debug/run it.

  • Variables inside def main are local, while those outside it are global. This may introduce a few bugs and unexpected behaviors.

But, you are not required to write a main() function and call it inside an if statement.

I myself usually start writing small throwaway scripts without any kind of function. If the script grows big enough, or if I feel putting all that code inside a function will benefit me, then I refactor the code and do it. This also happens when I write bash scripts.

Even if you put code inside the main function, you are not required to write it exactly like that. A neat variation could be:

import sys

def main(argv):
    # My code here
    pass

if __name__ == "__main__":
    main(sys.argv)

This means you can call main() from other scripts (or interactive shell) passing custom parameters. This might be useful in unit tests, or when batch-processing. But remember that the code above will require parsing of argv, thus maybe it would be better to use a different call that pass parameters already parsed.

In an object-oriented application I've written, the code looked like this:

class MyApplication(something):
    # My code here

if __name__ == "__main__":
    app = MyApplication()
    app.run()

So, feel free to write the code that better suits you. :)

How do I Merge two Arrays in VBA?

My preferred way is a bit long, but has some advantages over the other answers:

  • It can combine an indefinite number of arrays at once
  • It can combine arrays with non-arrays (objects, strings, integers, etc.)
  • It accounts for the possibility that one or more of the arrays may contain objects
  • It allows the user to choose the base of the new array (0, 1, etc.)

Here it is:

Function combineArrays(ByVal toCombine As Variant, Optional ByVal newBase As Long = 1)
'Combines an array of one or more 1d arrays, objects, or values into a single 1d array
'newBase parameter indicates start position of new array (0, 1, etc.)
'Example usage:
    'combineArrays(Array(Array(1,2,3),Array(4,5,6),Array(7,8))) -> Array(1,2,3,4,5,6,7,8)
    'combineArrays(Array("Cat",Array(2,3,4))) -> Array("Cat",2,3,4)
    'combineArrays(Array("Cat",ActiveSheet)) -> Array("Cat",ActiveSheet)
    'combineArrays(Array(ThisWorkbook)) -> Array(ThisWorkbook)
    'combineArrays("Cat") -> Array("Cat")

    Dim tempObj As Object
    Dim tempVal As Variant

    If Not IsArray(toCombine) Then
        If IsObject(toCombine) Then
            Set tempObj = toCombine
            ReDim toCombine(newBase To newBase)
            Set toCombine(newBase) = tempObj
        Else
            tempVal = toCombine
            ReDim toCombine(newBase To newBase)
            toCombine(newBase) = tempVal
        End If
        combineArrays = toCombine
        Exit Function
    End If

    Dim i As Long
    Dim tempArr As Variant
    Dim newMax As Long
    newMax = 0

    For i = LBound(toCombine) To UBound(toCombine)
        If Not IsArray(toCombine(i)) Then
            If IsObject(toCombine(i)) Then
                Set tempObj = toCombine(i)
                ReDim tempArr(1 To 1)
                Set tempArr(1) = tempObj
                toCombine(i) = tempArr
            Else
                tempVal = toCombine(i)
                ReDim tempArr(1 To 1)
                tempArr(1) = tempVal
                toCombine(i) = tempArr
            End If
            newMax = newMax + 1
        Else
            newMax = newMax + (UBound(toCombine(i)) + LBound(toCombine(i)) - 1)
        End If
    Next
    newMax = newMax + (newBase - 1)

    ReDim newArr(newBase To newMax)
    i = newBase
    Dim j As Long
    Dim k As Long
    For j = LBound(toCombine) To UBound(toCombine)
        For k = LBound(toCombine(j)) To UBound(toCombine(j))
            If IsObject(toCombine(j)(k)) Then
                Set newArr(i) = toCombine(j)(k)
            Else
                newArr(i) = toCombine(j)(k)
            End If
            i = i + 1
        Next
    Next

    combineArrays = newArr

End Function

How to read a text file directly from Internet using Java?

Alternatively, you can use Guava's Resources object:

URL url = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
List<String> lines = Resources.readLines(url, Charsets.UTF_8);
lines.forEach(System.out::println);

Intent from Fragment to Activity

use getContext() instead of MainActivity.this

Intent intent = new Intent(getContext(), SecondActivity.class);
startActivity(start);

SQL: How do I SELECT only the rows with a unique value on certain column?

Modified!

SELECT distinct contract, activity from @t a
WHERE (SELECT COUNT(DISTINCT activity) FROM @t b WHERE b.contract = a.contract) = 1

And here's another one -- shorter/cleaner without subquery

select contract, max(activity) from @t
group by contract
having count(distinct activity) = 1

Using grep to help subset a data frame in R

It's pretty straightforward using [ to extract:

grep will give you the position in which it matched your search pattern (unless you use value = TRUE).

grep("^G45", My.Data$x)
# [1] 2

Since you're searching within the values of a single column, that actually corresponds to the row index. So, use that with [ (where you would use My.Data[rows, cols] to get specific rows and columns).

My.Data[grep("^G45", My.Data$x), ]
#      x y
# 2 G459 2

The help-page for subset shows how you can use grep and grepl with subset if you prefer using this function over [. Here's an example.

subset(My.Data, grepl("^G45", My.Data$x))
#      x y
# 2 G459 2

As of R 3.3, there's now also the startsWith function, which you can again use with subset (or with any of the other approaches above). According to the help page for the function, it's considerably faster than using substring or grepl.

subset(My.Data, startsWith(as.character(x), "G45"))
#      x y
# 2 G459 2

'LIKE ('%this%' OR '%that%') and something=else' not working

Break out the LIKE clauses into 2 separate statements, i.e.:

(fieldname1 LIKE '%this%' or fieldname1 LIKE '%that%' ) and something=else

How to create a md5 hash of a string in C?

As other answers have mentioned, the following calls will compute the hash:

MD5Context md5;
MD5Init(&md5);
MD5Update(&md5, data, datalen);
MD5Final(digest, &md5);

The purpose of splitting it up into that many functions is to let you stream large datasets.

For example, if you're hashing a 10GB file and it doesn't fit into ram, here's how you would go about doing it. You would read the file in smaller chunks and call MD5Update on them.

MD5Context md5;
MD5Init(&md5);

fread(/* Read a block into data. */)
MD5Update(&md5, data, datalen);

fread(/* Read the next block into data. */)
MD5Update(&md5, data, datalen);

fread(/* Read the next block into data. */)
MD5Update(&md5, data, datalen);

...

//  Now finish to get the final hash value.
MD5Final(digest, &md5);

What does auto do in margin:0 auto?

margin:0 auto;

0 is for top-bottom and auto for left-right. It means that left and right margin will take auto margin according to the width of the element and the width of the container.

Generally if you want to put any element at center position then margin:auto works perfectly. But it only works in block elements.

Print very long string completely in pandas dataframe

If you're using jupyter notebook, you can also print pandas dataframe as HTML table, which will print full strings.

from IPython.display import display, HTML
display(HTML(df.to_html()))

Output

    one
0   one
1   two
2   This is very long string very long string very long string veryvery long string

How do I change the default library path for R packages

Facing the very same problem (avoiding the default path in a network) I came up to this solution with the hints given in other answers.

The solution is editing the Rprofile file to overwrite the variable R_LIBS_USER which by default points to the home directory.

Here the steps:

  1. Create the target destination folder for the libraries, e.g., ~\target.
  2. Find the Rprofile file. In my case it was at C:\Program Files\R\R-3.3.3\library\base\R\Rprofile.
  3. Edit the file and change the definition the variable R_LIBS_USER. In my case, I replaced the this line file.path(Sys.getenv("R_USER"), "R", with file.path("~\target", "R",.

The documentation that support this solution is here

Original file with:

 if(!nzchar(Sys.getenv("R_LIBS_USER")))
     Sys.setenv(R_LIBS_USER=
                file.path(Sys.getenv("R_USER"), "R",
                          "win-library",
                          paste(R.version$major,
                                sub("\\..*$", "", R.version$minor),
                                sep=".")
                          )) 

Modified file:

if(!nzchar(Sys.getenv("R_LIBS_USER")))
     Sys.setenv(R_LIBS_USER=
                file.path("~\target", "R",
                          "win-library",
                          paste(R.version$major,
                                sub("\\..*$", "", R.version$minor),
                                sep=".")
                          ))

http://localhost:8080/ Access Error: 404 -- Not Found Cannot locate document: /

For CentOS users (at least), one will also get a 404 error trying to access the server on port 8080 on a fresh install if the tomcat-webapps package is not installed.

matplotlib does not show my drawings although I call pyplot.show()

What solved my problem was just using the below two lines in ipython notebook at the top

%matplotib inline
%pylab inline

And it worked. I'm using Ubuntu16.04 and ipython-5.1

EXC_BAD_ACCESS signal received

The 2010 WWDC videos are available to any participants in the apple developer program. There's a great video: "Session 311 - Advanced Memory Analysis with Instruments" that shows some examples of using zombies in instruments and debugging other memory problems.

For a link to the login page click HERE.

Why SQL Server throws Arithmetic overflow error converting int to data type numeric?

NUMERIC(3,2) means: 3 digits in total, 2 after the decimal point. So you only have a single decimal before the decimal point.

Try NUMERIC(5,2) - three before, two after the decimal point.

Call a stored procedure with another in Oracle

@Michael Lockwood - you don't need to use the keyword "CALL" anywhere. You just need to mention the procedure call directly.

That is

Begin
   proc1(input1, input2);
end;
/

instead of

Begin
   call proc1(input1, input2);
end;
/

Java Enum Methods - return opposite direction enum

Yes we do it all the time. You return a static instance rather than a new Object

 static Direction getOppositeDirection(Direction d){
       Direction result = null;
       if (d != null){
           int newCode = -d.getCode();
           for (Direction direction : Direction.values()){
               if (d.getCode() == newCode){
                   result = direction;
               }
           }
       }
       return result;
 }

ImportError: Couldn't import Django

windows :

  1. (virtualenv dir)\Scripts\activate # this step to activate virtualenv

  2. you should be in the dir of (project name)

  3. python manage.py runserver

Get url without querystring

var canonicallink = Request.Url.Scheme + "://" + Request.Url.Authority + Request.Url.AbsolutePath.ToString();

How to display list items as columns?

This can be done using CSS3 columns quite easily. Here's an example, HTML:

_x000D_
_x000D_
#limheight {_x000D_
    height: 300px; /*your fixed height*/_x000D_
    -webkit-column-count: 3;_x000D_
       -moz-column-count: 3;_x000D_
            column-count: 3; /*3 in those rules is just placeholder -- can be anything*/_x000D_
}_x000D_
_x000D_
#limheight li {_x000D_
    display: inline-block; /*necessary*/_x000D_
}
_x000D_
<ul id = "limheight">_x000D_
 <li><a href="">Glee is awesome 1</a></li>_x000D_
 <li><a href="">Glee is awesome 2</a></li>_x000D_
 <li><a href="">Glee is awesome 3</a></li>_x000D_
 <li><a href="">Glee is awesome 4</a></li>    _x000D_
 <li><a href="">Glee is awesome 5</a></li>_x000D_
 <li><a href="">Glee is awesome 6</a></li>_x000D_
 <li><a href="">Glee is awesome 7</a></li>_x000D_
 <li><a href="">Glee is awesome 8</a></li>_x000D_
 <li><a href="">Glee is awesome 9</a></li>_x000D_
 <li><a href="">Glee is awesome 10</a></li>_x000D_
 <li><a href="">Glee is awesome 11</a></li>_x000D_
 <li><a href="">Glee is awesome 12</a></li>    _x000D_
 <li><a href="">Glee is awesome 13</a></li>_x000D_
 <li><a href="">Glee is awesome 14</a></li>_x000D_
 <li><a href="">Glee is awesome 15</a></li>_x000D_
 <li><a href="">Glee is awesome 16</a></li>_x000D_
 <li><a href="">Glee is awesome 17</a></li>    _x000D_
 <li><a href="">Glee is awesome 18</a></li>_x000D_
 <li><a href="">Glee is awesome 19</a></li>_x000D_
 <li><a href="">Glee is awesome 20</a></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Running a command as Administrator using PowerShell?

On top of Shay Levy's answer, follow the below setup (just once)

  1. Start a PowerShell with Administrator rights.
  2. Follow Stack Overflow question PowerShell says “execution of scripts is disabled on this system.”.
  3. Put your .ps1 file in any of the PATH folders, for example. Windows\System32 folder

After the setup:

  1. Press Win + R
  2. Invoke powershell Start-Process powershell -Verb runAs <ps1_file>

You can now run everything in just one command line. The above works on Windows 8 Basic 64-bit.

XAMPP keeps showing Dashboard/Welcome Page instead of the Configuration Page

I had the same problem. I uninstalled the 6.8.14 and installed back older version 5.6.8, and it worked.

How to suppress scientific notation when printing float values?

Since this is the top result on Google, I will post here after failing to find a solution for my problem. If you are looking to format the display value of a float object and have it remain a float - not a string, you can use this solution:

Create a new class that modifies the way that float values are displayed.

from builtins import float
class FormattedFloat(float):

    def __str__(self):
        return "{:.10f}".format(self).rstrip('0')

You can modify the precision yourself by changing the integer values in {:f}

AngularJS ng-click to go to another page (with Ionic framework)

Use <a> with href instead of a <button> solves my problem.

<ion-nav-buttons side="secondary">
  <a class="button icon-right ion-plus-round" href="#/app/gosomewhere"></a>
</ion-nav-buttons>