Programs & Examples On #Disconnection

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

I upgraded my IntelliJ Version from 2018.1 to 2018.3.6. It works !

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

I found the solution as Its problem with Android Studio 3.1 Canary 6

My backup of Android Studio 3.1 Canary 5 is useful to me and saved my half day.

Now My build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.2'
    defaultConfig {
        applicationId "com.example.demo"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    dataBinding {
        enabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.android.support:design:${rootProject.ext.supportLibVersion}"
    implementation "com.android.support:support-v4:${rootProject.ext.supportLibVersion}"
    implementation "com.android.support:recyclerview-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.android.support:cardview-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.squareup.retrofit2:retrofit:2.3.0"
    implementation "com.google.code.gson:gson:2.8.2"
    implementation "com.android.support.constraint:constraint-layout:1.0.2"
    implementation "com.squareup.retrofit2:converter-gson:2.3.0"
    implementation "com.squareup.okhttp3:logging-interceptor:3.6.0"
    implementation "com.squareup.picasso:picasso:2.5.2"
    implementation "com.dlazaro66.qrcodereaderview:qrcodereaderview:2.0.3"
    compile 'com.github.elevenetc:badgeview:v1.0.0'
    annotationProcessor 'com.github.elevenetc:badgeview:v1.0.0'
    testImplementation "junit:junit:4.12"
    androidTestImplementation("com.android.support.test.espresso:espresso-core:3.0.1", {
        exclude group: "com.android.support", module: "support-annotations"
    })
}

and My gradle is:

classpath 'com.android.tools.build:gradle:3.1.0-alpha06'

and its working finally.

I think there problem in Android Studio 3.1 Canary 6

Thank you all for your time.

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

Another possible recent solution is changing gradle version to:

classpath 'com.android.tools.build:gradle:3.0.0-rc2'

and updating build tool

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

For me, the problem was solved after I removed jar file from my project. it seems that one of the jar files inside my project was using an older version of google play services.

configuring project ':app' failed to find Build Tools revision

also try to increase gradle version in your project's build.gradle. It helped me

How to customize the configuration file of the official PostgreSQL Docker image?

Inject custom postgresql.conf into postgres Docker container

The default postgresql.conf file lives within the PGDATA dir (/var/lib/postgresql/data), which makes things more complicated especially when running postgres container for the first time, since the docker-entrypoint.sh wrapper invokes the initdb step for PGDATA dir initialization.

To customize PostgreSQL configuration in Docker consistently, I suggest using config_file postgres option together with Docker volumes like this:

Production database (PGDATA dir as Persistent Volume)

docker run -d \
-v $CUSTOM_CONFIG:/etc/postgresql.conf \
-v $CUSTOM_DATADIR:/var/lib/postgresql/data \
-e POSTGRES_USER=postgres \
-p 5432:5432 \
--name postgres \
postgres:9.6 postgres -c config_file=/etc/postgresql.conf

Testing database (PGDATA dir will be discarded after docker rm)

docker run -d \
-v $CUSTOM_CONFIG:/etc/postgresql.conf \
-e POSTGRES_USER=postgres \
--name postgres \
postgres:9.6 postgres -c config_file=/etc/postgresql.conf

Debugging

  1. Remove the -d (detach option) from docker run command to see the server logs directly.
  2. Connect to the postgres server with psql client and query the configuration:

    docker run -it --rm --link postgres:postgres postgres:9.6 sh -c 'exec psql -h $POSTGRES_PORT_5432_TCP_ADDR -p $POSTGRES_PORT_5432_TCP_PORT -U postgres'
    
    psql (9.6.0)
    Type "help" for help.
    
    postgres=# SHOW all;
    

No tests found for given includes Error, when running Parameterized Unit test in Android Studio

In my case I was getting this message due to a runtime error with Junit which wasn't at all visible from the output of the gradle test task execution. I've run into this for a couple reasons:

  1. Including the org.junit.platform:junit-platform-launcher dependency with a version that didn't match the junit version I was using
  2. Having an entry in META-INF/services for a Junit test listener which I had commented out

You can try re-running with --debug and search for FAILED or org.gradle.api.internal.tasks.testing.TestSuiteExecutionException. In my second case, the exception was:

2020-10-20T11:34:26.517-0700 [DEBUG] [TestEventLogger]
2020-10-20T11:34:26.517-0700 [DEBUG] [TestEventLogger] Gradle Test Executor 1 STARTED
2020-10-20T11:34:26.661-0700 [DEBUG] [TestEventLogger]
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger] Gradle Test Executor 1 FAILED
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]     org.gradle.api.internal.tasks.testing.TestSuiteExecutionException: Could not complete execution for Gradle Test Executor 1.
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:63)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at java.lang.reflect.Method.invoke(Method.java:498)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at com.sun.proxy.$Proxy2.stop(Unknown Source)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:132)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at java.lang.reflect.Method.invoke(Method.java:498)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:413)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at java.lang.Thread.run(Thread.java:748)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]         Caused by:
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]         java.util.ServiceConfigurationError: org.junit.platform.launcher.TestExecutionListener: Provider com.example.myproject.MyCommentedOutClass not found
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at java.util.ServiceLoader.fail(ServiceLoader.java:239)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at java.util.ServiceLoader.access$300(ServiceLoader.java:185)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at java.util.ServiceLoader$LazyIterator.nextService(ServiceLoader.java:372)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:404)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at java.util.ServiceLoader$1.next(ServiceLoader.java:480)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at java.lang.Iterable.forEach(Iterable.java:74)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at org.junit.platform.launcher.core.LauncherFactory.create(LauncherFactory.java:94)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at org.junit.platform.launcher.core.LauncherFactory.create(LauncherFactory.java:67)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:97)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             ... 25 more

Notice that these are DEBUG logs. I didn't see anything helpful with just --info

Instantly detect client disconnection from server socket

I've found quite useful, another workaround for that!

If you use asynchronous methods for reading data from the network socket (I mean, use BeginReceive - EndReceive methods), whenever a connection is terminated; one of these situations appear: Either a message is sent with no data (you can see it with Socket.Available - even though BeginReceive is triggered, its value will be zero) or Socket.Connected value becomes false in this call (don't try to use EndReceive then).

I'm posting the function I used, I think you can see what I meant from it better:


private void OnRecieve(IAsyncResult parameter) 
{
    Socket sock = (Socket)parameter.AsyncState;
    if(!sock.Connected || sock.Available == 0)
    {
        // Connection is terminated, either by force or willingly
        return;
    }

    sock.EndReceive(parameter);
    sock.BeginReceive(..., ... , ... , ..., new AsyncCallback(OnRecieve), sock);

    // To handle further commands sent by client.
    // "..." zones might change in your code.
}

cast class into another class or convert class to another

Use JSON serialization and deserialization:

using Newtonsoft.Json;

Class1 obj1 = new Class1();
Class2 obj2 = JsonConvert.DeserializeObject<Class2>(JsonConvert.SerializeObject(obj1));

Or:

public class Class1
{
    public static explicit operator Class2(Class1 obj)
    {
        return JsonConvert.DeserializeObject<Class2>(JsonConvert.SerializeObject(obj));
    }
}

Which then allows you to do something like

Class1 obj1 = new Class1();
Class2 obj2 = (Class2)obj1;

How to compare two dates in Objective-C

Get Today's Date:

NSDate* date = [NSDate date];

Create a Date From Scratch:    
NSDateComponents* comps = [[NSDateComponents alloc]init];
comps.year = 2015;
comps.month = 12;
comps.day = 31;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* date = [calendar dateFromComponents:comps];


Add a day to a Date:  
NSDate* date = [NSDate date];
NSDateComponents* comps = [[NSDateComponents alloc]init];
comps.day = 1;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* tomorrow = [calendar dateByAddingComponents:comps toDate:date options:nil];


Subtract a day from a Date:    
NSDate* date = [NSDate date];
NSDateComponents* comps = [[NSDateComponents alloc]init];
comps.day = -1;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* yesterday = [calendar dateByAddingComponents:comps toDate:date options:nil];



Convert a Date to a String:  

NSDate* date = [NSDate date];
NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = @"MMMM dd, yyyy";
NSString* dateString = [formatter stringFromDate:date];


Convert a String to a Date:

NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = @"MMMM dd, yyyy";
NSDate* date = [formatter dateFromString:@"August 02, 2014"];


Find how many days are in a month:    
NSDate* date = [NSDate date];
NSCalendar* cal = [NSCalendar currentCalendar];
NSRange currentRange = [cal rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:date];
NSInteger numberOfDays = currentRange.length;


Calculate how much time something took:   

NSDate* start = [NSDate date];
for(int i = 0; i < 1000000000; i++);
NSDate* end = [NSDate date];
NSTimeInterval duration = [end timeIntervalSinceDate:start];


Find the Day Of Week for a specific Date:

NSDate* date = [NSDate date];
NSCalendar* cal = [NSCalendar currentCalendar];
NSInteger dow = [cal ordinalityOfUnit:NSWeekdayCalendarUnit inUnit:NSWeekCalendarUnit forDate:date];

Then use NSComparisonResult to compare date.

How can I tell what edition of SQL Server runs on the machine?

select @@version

Sample Output

Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64) Mar 29 2009 10:11:52 Copyright (c) 1988-2008 Microsoft Corporation Developer Edition (64-bit) on Windows NT 6.1 (Build 7600: )

If you just want to get the edition, you can use:

select serverproperty('Edition')

To use in an automated script, you can get the edition ID, which is an integer:

select serverproperty('EditionID')
  • -1253826760 = Desktop
  • -1592396055 = Express
  • -1534726760 = Standard
  • 1333529388 = Workgroup
  • 1804890536 = Enterprise
  • -323382091 = Personal
  • -2117995310 = Developer
  • 610778273 = Enterprise Evaluation
  • 1044790755 = Windows Embedded SQL
  • 4161255391 = Express with Advanced Services

How to get the current date/time in Java

Create object of date and simply print it down.

Date d = new Date(System.currentTimeMillis());
System.out.print(d);

Writing your own square root function

Well there are already quite a few answers, but here goes mine It's the most simplest piece of code ( for me ), here is the algorithm for it.

And code in python 2.7:

from __future__ import division 
val = 81
x = 10
def sqr(data,x):
    temp = x - ( (x**2 - data)/(2*x))
    if temp == x:
        print temp
        return
    else:
        x = temp
        return sqr(data,x)
    #x =temp 
    #sqr(data,x)
sqr(val,x)

Spark : how to run spark file from spark shell

You can use either sbt or maven to compile spark programs. Simply add the spark as dependency to maven

<repository>
      <id>Spark repository</id>
      <url>http://www.sparkjava.com/nexus/content/repositories/spark/</url>
</repository>

And then the dependency:

<dependency>
      <groupId>spark</groupId>
      <artifactId>spark</artifactId>
      <version>1.2.0</version>
</dependency>

In terms of running a file with spark commands: you can simply do this:

echo"
   import org.apache.spark.sql.*
   ssc = new SQLContext(sc)
   ssc.sql("select * from mytable").collect
" > spark.input

Now run the commands script:

cat spark.input | spark-shell

System.Data.SqlClient.SqlException: Login failed for user

I faced the same situation. Create your connection string as follows.

Replace

"connectionString": "Data Source=server name;Initial Catalog=DB name;User id=user id;Password=password;Integrated Security=True;MultipleActiveResultSets=True"

by

"connectionString": "Server=server name; Database=Treat; User Id=user id; Password=password; Trusted_Connection=False; MultipleActiveResultSets=true"

Python; urllib error: AttributeError: 'bytes' object has no attribute 'read'

Try this:

jsonResponse = json.loads(response.decode('utf-8'))

Plot different DataFrames in the same figure

Although Chang's answer explains how to plot multiple times on the same figure, in this case you might be better off in this case using a groupby and unstacking:

(Assuming you have this in dataframe, with datetime index already)

In [1]: df
Out[1]:
            value  
datetime                         
2010-01-01      1  
2010-02-01      1  
2009-01-01      1  

# create additional month and year columns for convenience
df['Month'] = map(lambda x: x.month, df.index)
df['Year'] = map(lambda x: x.year, df.index)    

In [5]: df.groupby(['Month','Year']).mean().unstack()
Out[5]:
       value      
Year    2009  2010
Month             
1          1     1
2        NaN     1

Now it's easy to plot (each year as a separate line):

df.groupby(['Month','Year']).mean().unstack().plot()

Insert a row to pandas dataframe

Below would be the best way to insert a row into pandas dataframe without sorting and reseting an index:

import pandas as pd

df = pd.DataFrame(columns=['a','b','c'])

def insert(df, row):
    insert_loc = df.index.max()

    if pd.isna(insert_loc):
        df.loc[0] = row
    else:
        df.loc[insert_loc + 1] = row

insert(df,[2,3,4])
insert(df,[8,9,0])
print(df)

jQuery Clone table row

Your problem is that your insertAfter:

.insertAfter(".tr_clone")

inserts after every .tr_clone:

the matched set of elements will be inserted after the element(s) specified by this parameter.

You probably just want to use after on the row you're duplicating. And a little .find(':text').val('') will clear the cloned text inputs; something like this:

var $tr    = $(this).closest('.tr_clone');
var $clone = $tr.clone();
$clone.find(':text').val('');
$tr.after($clone);

Demo: http://jsfiddle.net/ambiguous/LAECx/ or for a modern jQuery: http://jsfiddle.net/ambiguous/LAECx/3274/

I'm not sure which input should end up with the focus so I've left that alone.

How to get the name of the current Windows user in JavaScript

If the script is running on Microsoft Windows in an HTA or similar, you can do this:

var wshshell=new ActiveXObject("wscript.shell");
var username=wshshell.ExpandEnvironmentStrings("%username%");

Otherwise, as others have pointed out, you're out of luck. This is considered to be private information and is not provided by the browser to the javascript engine.

Android ImageButton with a selected state?

This works for me:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- NOTE: order is important (the first matching state(s) is what is rendered) -->
    <item 
        android:state_selected="true" 
        android:drawable="@drawable/info_icon_solid_with_shadow" />
    <item 
        android:drawable="@drawable/info_icon_outline_with_shadow" />
 </selector>

And then in java:

//assign the image in code (or you can do this in your layout xml with the src attribute)
imageButton.setImageDrawable(getBaseContext().getResources().getDrawable(R.drawable....));

//set the click listener
imageButton.setOnClickListener(new OnClickListener() {

    public void onClick(View button) {
        //Set the button's appearance
        button.setSelected(!button.isSelected());

        if (button.isSelected()) {
            //Handle selected state change
        } else {
            //Handle de-select state change
        }

    }

});

For smooth transition you can also mention animation time:

<selector xmlns:android="http://schemas.android.com/apk/res/android" android:exitFadeDuration="@android:integer/config_mediumAnimTime">

Insert all data of a datagridview to database at once

If you move your for loop, you won't have to make multiple connections. Just a quick edit to your code block (by no means completely correct):

string StrQuery;
try
{
    using (SqlConnection conn = new SqlConnection(ConnString))
    {
        using (SqlCommand comm = new SqlCommand())
        {
            comm.Connection = conn;
            conn.Open();
            for(int i=0; i< dataGridView1.Rows.Count;i++)
            {
                StrQuery= @"INSERT INTO tableName VALUES (" 
                    + dataGridView1.Rows[i].Cells["ColumnName"].Text+", " 
                    + dataGridView1.Rows[i].Cells["ColumnName"].Text+");";
                comm.CommandText = StrQuery;
                comm.ExecuteNonQuery();
            }
        }
    }
}

As to executing multiple SQL commands at once, please look at this link: Multiple statements in single SqlCommand

how to create virtual host on XAMPP

Add this Code in C:\xampp\apache\conf\extra\httpd-vhosts.conf

<VirtualHost *:80>
DocumentRoot "C:/xampp/htdocs"
ServerName qa-staging.com
ServerAlias www.qa-staging.com
<Directory "c:/xampp/htdocs">
Order allow,deny
Allow from all
</Directory>
</VirtualHost>

Now Add your virtual host name in bellow file.

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

127.0.0.1 qa-staging.com

If you are not able to save this code in host file then right click on notpad select Run as administrator and then you can able to save your custom code now restart your XAMP

How to save MySQL query output to excel or .txt file?

From Save MySQL query results into a text or CSV file:

MySQL provides an easy mechanism for writing the results of a select statement into a text file on the server. Using extended options of the INTO OUTFILE nomenclature, it is possible to create a comma separated value (CSV) which can be imported into a spreadsheet application such as OpenOffice or Excel or any other application which accepts data in CSV format.

Given a query such as

SELECT order_id,product_name,qty FROM orders

which returns three columns of data, the results can be placed into the file /tmp/orders.txt using the query:

SELECT order_id,product_name,qty FROM orders
INTO OUTFILE '/tmp/orders.txt'

This will create a tab-separated file, each row on its own line. To alter this behavior, it is possible to add modifiers to the query:

SELECT order_id,product_name,qty FROM orders
INTO OUTFILE '/tmp/orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'

In this example, each field will be enclosed in double quotes, the fields will be separated by commas, and each row will be output on a new line separated by a newline (\n). Sample output of this command would look like:

"1","Tech-Recipes sock puppet","14.95" "2","Tech-Recipes chef's hat","18.95"

Keep in mind that the output file must not already exist and that the user MySQL is running as has write permissions to the directory MySQL is attempting to write the file to.

Syntax

   SELECT Your_Column_Name
    FROM Your_Table_Name
    INTO OUTFILE 'Filename.csv'
    FIELDS TERMINATED BY ','
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n'

Or you could try to grab the output via the client:

You could try executing the query from the your local client and redirect the output to a local file destination:

mysql -user -pass -e "select cols from table where cols not null" > /tmp/output

Hint: If you don't specify an absoulte path but use something like INTO OUTFILE 'output.csv' or INTO OUTFILE './output.csv', it will store the output file to the directory specified by show variables like 'datadir';.

How can I get the file name from request.FILES?

request.FILES['filename'].name

From the request documentation.

If you don't know the key, you can iterate over the files:

for filename, file in request.FILES.iteritems():
    name = request.FILES[filename].name

Checking if a variable is an integer in PHP

All $_GET parameters have a string datatype, therefore, is_int will always return false.

You can see this by calling var_dump:

var_dump($_GET['p']); // string(2) "54"

Using is_numeric will provide the desired result (mind you, that allows values such as: 0x24).

Hibernate JPA Sequence (non-Id)

"I don't want to use a trigger or any other thing other than Hibernate itself to generate the value for my property"

In that case, how about creating an implementation of UserType which generates the required value, and configuring the metadata to use that UserType for persistence of the mySequenceVal property?

Excel - Shading entire row based on change of value

Use Conditional Formatting.

In it's simplest form, you are saying "for this cell, if it's value is X, then apply format foo". However, if you use the "formula" method, you can select the whole row, enter the formula and associated format, then use copy and paste (formats only) for the rest of the table.

You're limited to only 3 rules in Excel 2003 or older so you might want to define a pattern for the colours rather than using raw values. Something like this should work though:

alt text

range() for floats

As kichik wrote, this shouldn't be too complicated. However this code:

def frange(x, y, jump):
  while x < y:
    yield x
    x += jump

Is inappropriate because of the cumulative effect of errors when working with floats. That is why you receive something like:

>>>list(frange(0, 100, 0.1))[-1]
99.9999999999986

While the expected behavior would be:

>>>list(frange(0, 100, 0.1))[-1]
99.9

Solution 1

The cumulative error can simply be reduced by using an index variable. Here's the example:

from math import ceil

    def frange2(start, stop, step):
        n_items = int(ceil((stop - start) / step))
        return (start + i*step for i in range(n_items))

This example works as expected.

Solution 2

No nested functions. Only a while and a counter variable:

def frange3(start, stop, step):
    res, n = start, 1

    while res < stop:
        yield res
        res = start + n * step
        n += 1

This function will work well too, except for the cases when you want the reversed range. E.g:

>>>list(frange3(1, 0, -.1))
[]

Solution 1 in this case will work as expected. To make this function work in such situations, you must apply a hack, similar to the following:

from operator import gt, lt

def frange3(start, stop, step):
    res, n = start, 0.
    predicate = lt if start < stop else gt
    while predicate(res, stop):
        yield res
        res = start + n * step
        n += 1

With this hack you can use these functions with negative steps:

>>>list(frange3(1, 0, -.1))
[1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.3999999999999999, 0.29999999999999993, 0.19999999999999996, 0.09999999999999998]

Solution 3

You can go even further with plain standard library and compose a range function for the most of numeric types:

from itertools import count
from itertools import takewhile

def any_range(start, stop, step):
    start = type(start + step)(start)
    return takewhile(lambda n: n < stop, count(start, step))

This generator is adapted from the Fluent Python book (Chapter 14. Iterables, Iterators and generators). It will not work with decreasing ranges. You must apply a hack, like in the previous solution.

You can use this generator as follows, for example:

>>>list(any_range(Fraction(2, 1), Fraction(100, 1), Fraction(1, 3)))[-1]
299/3
>>>list(any_range(Decimal('2.'), Decimal('4.'), Decimal('.3')))
[Decimal('2'), Decimal('2.3'), Decimal('2.6'), Decimal('2.9'), Decimal('3.2'), Decimal('3.5'), Decimal('3.8')]

And of course you can use it with float and int as well.

Be careful

If you want to use these functions with negative steps, you should add a check for the step sign, e.g.:

no_proceed = (start < stop and step < 0) or (start > stop and step > 0)
if no_proceed: raise StopIteration

The best option here is to raise StopIteration, if you want to mimic the range function itself.

Mimic range

If you would like to mimic the range function interface, you can provide some argument checks:

def any_range2(*args):
    if len(args) == 1:
        start, stop, step = 0, args[0], 1.
    elif len(args) == 2:
        start, stop, step = args[0], args[1], 1.
    elif len(args) == 3:
        start, stop, step = args
    else:
        raise TypeError('any_range2() requires 1-3 numeric arguments')

    # here you can check for isinstance numbers.Real or use more specific ABC or whatever ...

    start = type(start + step)(start)
    return takewhile(lambda n: n < stop, count(start, step))

I think, you've got the point. You can go with any of these functions (except the very first one) and all you need for them is python standard library.

Get selected option from select element

Using the selectedOptions property (HTML5) you can get the selected option(s)

document.getElementbyId("id").selectedOptions; 

With JQuery can be achieved by doing this

$("#id")[0].selectedOptions; 

or

$("#id").prop("selectedOptions");

The property contains an HTMLCollection array similitar to this one selected option

[<option value=?"1">?ABC</option>]

or multiple selections

[<option value=?"1">?ABC</option>, <option value=?"2">?DEF</option> ...]

How do I access ViewBag from JS

ViewBag is server side code.
Javascript is client side code.

You can't really connect them.

You can do something like this:

var x = $('#' + '@(ViewBag.CC)').val();

But it will get parsed on the server, so you didn't really connect them.

Get pandas.read_csv to read empty values as empty string instead of nan

I was still confused after reading the other answers and comments. But the answer now seems simpler, so here you go.

Since Pandas version 0.9 (from 2012), you can read your csv with empty cells interpreted as empty strings by simply setting keep_default_na=False:

pd.read_csv('test.csv', keep_default_na=False)

This issue is more clearly explained in

That was fixed on on Aug 19, 2012 for Pandas version 0.9 in

Installing specific laravel version with composer create-project

composer create-project laravel/laravel=4.1.27 your-project-name --prefer-dist

And then you probably need to install all of vendor packages, so

composer install

Gradle does not find tools.jar

In CentOS7 the development package will install tools.jar. The file is not present in java-1.8.0-openjdk

sudo yum install java-1.8.0-openjdk-devel

Parse string to date with moment.js

I always seem to find myself landing here only to realize that the title and question are not quite aligned.

If you want a moment date from a string:

const myMomentObject = moment(str, 'YYYY-MM-DD')

From moment documentation:

Instead of modifying the native Date.prototype, Moment.js creates a wrapper for the Date object.

If you instead want a javascript Date object from a string:

const myDate = moment(str, 'YYYY-MM-DD').toDate();

Fastest way to ping a network range and return responsive hosts?

The following (evil) code runs more than TWICE as fast as the nmap method

for i in {1..254} ;do (ping 192.168.1.$i -c 1 -w 5  >/dev/null && echo "192.168.1.$i" &) ;done

takes around 10 seconds, where the standard nmap

nmap -sP 192.168.1.1-254

takes 25 seconds...

Regex: Check if string contains at least one digit

In perl:

if($testString =~ /\d/) 
{
    print "This string contains at least one digit"
}

where \d matches to a digit.

How to make a <svg> element expand or contract to its parent container?

For your iphone You could use in your head balise :

"width=device-width"

Run JavaScript when an element loses focus

From w3schools.com: Made compatible with Firefox Sept, 2016

<input type="text" onfocusout="myFunction()">

Is there a way to avoid null check before the for-each loop iteration starts?

If possible, you should design your code such that the collections aren't null in the first place.

null collections are bad practice (for this reason); you should use empty collections instead. (eg, Collections.emptyList())

Alternatively, you could make a wrapper class that implements Iterable and takes a collections, and handles a null collection.
You could then write foreach(T obj : new Nullable<T>(list1))

Prevent double curly brace notation from displaying momentarily before angular.js compiles/interpolates document

Just add the cloaking CSS to the head of the page or to one of your CSS files:

[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak, .ng-hide {
    display: none !important;
}

Then you can use the ngCloak directive according to normal Angular practice, and it will work even before Angular itself is loaded.

This is exactly what Angular does: the code at the end of angular.js adds the above CSS rules to the head of the page.

How to set an button align-right with Bootstrap?

This worked for me:

<div class="text-right">
    <button type="button">Button 1</button>
    <button type="button">Button 2</button>
</div>

How to automatically close cmd window after batch file execution?

You could try the somewhat dangerous: taskkill /IM cmd.exe ..dangerous bcz that will kill the cmd that is open and any cmd's opened before it.

Or add a verification to confirm that you had the right cmd.exe and then kill it via PID, such as this:

set loc=%time%%random%
title=%loc%
for /f "tokens=2 delims= " %%A in ('tasklist /v ^| findstr /i "%loc%"') do (taskkill /PID %%A) 

Substitute (pslist &&A) or (tasklist /FI "PID eq %%A") for the (taskkill /PID %%A) if you want to check it first (and maybe have pstools installed).

Print out the values of a (Mat) matrix in OpenCV C++

I think using the matrix.at<type>(x,y) is not the best way to iterate trough a Mat object! If I recall correctly matrix.at<type>(x,y) will iterate from the beginning of the matrix each time you call it(I might be wrong though). I would suggest using cv::MatIterator_

cv::Mat someMat(1, 4, CV_64F, &someData);;
cv::MatIterator_<double> _it = someMat.begin<double>();
for(;_it!=someMat.end<double>(); _it++){
    std::cout << *_it << std::endl;
}

print memory address of Python variable

There is no way to get the memory address of a value in Python 2.7 in general. In Jython or PyPy, the implementation doesn't even know your value's address (and there's not even a guarantee that it will stay in the same place—e.g., the garbage collector is allowed to move it around if it wants).

However, if you only care about CPython, id is already returning the address. If the only issue is how to format that integer in a certain way… it's the same as formatting any integer:

>>> hex(33)
0x21
>>> '{:#010x}'.format(33) # 32-bit
0x00000021
>>> '{:#018x}'.format(33) # 64-bit
0x0000000000000021

… and so on.

However, there's almost never a good reason for this. If you actually need the address of an object, it's presumably to pass it to ctypes or similar, in which case you should use ctypes.addressof or similar.

Backporting Python 3 open(encoding="utf-8") to Python 2

I think

from io import open

should do.

Counting number of lines, words, and characters in a text file

in.next(); is consuming all the lines in the first while(). After the end of your first while loop, there are no more characters to be read at the input stream.

You should nest your character and word-counting within a while loop counting lines.

How to run functions in parallel?

This can be done elegantly with Ray, a system that allows you to easily parallelize and distribute your Python code.

To parallelize your example, you'd need to define your functions with the @ray.remote decorator, and then invoke them with .remote.

import ray

ray.init()

dir1 = 'C:\\folder1'
dir2 = 'C:\\folder2'
filename = 'test.txt'
addFiles = [25, 5, 15, 35, 45, 25, 5, 15, 35, 45]

# Define the functions. 
# You need to pass every global variable used by the function as an argument.
# This is needed because each remote function runs in a different process,
# and thus it does not have access to the global variables defined in 
# the current process.
@ray.remote
def func1(filename, addFiles, dir):
    # func1() code here...

@ray.remote
def func2(filename, addFiles, dir):
    # func2() code here...

# Start two tasks in the background and wait for them to finish.
ray.get([func1.remote(filename, addFiles, dir1), func2.remote(filename, addFiles, dir2)]) 

If you pass the same argument to both functions and the argument is large, a more efficient way to do this is using ray.put(). This avoids the large argument to be serialized twice and to create two memory copies of it:

largeData_id = ray.put(largeData)

ray.get([func1(largeData_id), func2(largeData_id)])

Important - If func1() and func2() return results, you need to rewrite the code as follows:

ret_id1 = func1.remote(filename, addFiles, dir1)
ret_id2 = func2.remote(filename, addFiles, dir2)
ret1, ret2 = ray.get([ret_id1, ret_id2])

There are a number of advantages of using Ray over the multiprocessing module. In particular, the same code will run on a single machine as well as on a cluster of machines. For more advantages of Ray see this related post.

how to make a div to wrap two float divs inside?

Aside from the clear: both hack, you can skip the extra element and use overflow: hidden on the wrapping div:

<div style="overflow: hidden;">
    <div style="float: left;"></div>
    <div style="float: left;"></div>
</div>

Detect if the device is iPhone X

To detect any of the devices by using simple methods. like below,

func isPhoneDevice() -> Bool {
    return UIDevice.current.userInterfaceIdiom == .phone
}

func isDeviceIPad() -> Bool {
    return UIDevice.current.userInterfaceIdiom == .pad
}

func isPadProDevice() -> Bool {
    let SCREEN_WIDTH: CGFloat = UIScreen.main.bounds.size.width
    let SCREEN_HEIGHT: CGFloat = UIScreen.main.bounds.size.height
    let SCREEN_MAX_LENGTH: CGFloat = fmax(SCREEN_WIDTH, SCREEN_HEIGHT)

    return UIDevice.current.userInterfaceIdiom == .pad && SCREEN_MAX_LENGTH == 1366.0
}

func isPhoneXandXSDevice() -> Bool {
    let SCREEN_WIDTH = CGFloat(UIScreen.main.bounds.size.width)
    let SCREEN_HEIGHT = CGFloat(UIScreen.main.bounds.size.height)
    let SCREEN_MAX_LENGTH: CGFloat = fmax(SCREEN_WIDTH, SCREEN_HEIGHT)

    return UIDevice.current.userInterfaceIdiom == .phone && SCREEN_MAX_LENGTH == 812.0
}

func isPhoneXSMaxandXRDevice() -> Bool {
    let SCREEN_WIDTH = CGFloat(UIScreen.main.bounds.size.width)
    let SCREEN_HEIGHT = CGFloat(UIScreen.main.bounds.size.height)
    let SCREEN_MAX_LENGTH: CGFloat = fmax(SCREEN_WIDTH, SCREEN_HEIGHT)

    return UIDevice.current.userInterfaceIdiom == .phone && SCREEN_MAX_LENGTH == 896.0
}

and call like this,

if isPhoneDevice() {
     // Your code
}

How to list all AWS S3 objects in a bucket using Java

Gray your solution was strange but you seem like a nice guy.

AmazonS3Client s3Client = new AmazonS3Client(new BasicAWSCredentials( ....

ObjectListing images = s3Client.listObjects(bucketName); 

List<S3ObjectSummary> list = images.getObjectSummaries();
for(S3ObjectSummary image: list) {
    S3Object obj = s3Client.getObject(bucketName, image.getKey());
    writeToFile(obj.getObjectContent());
}

How to execute a command prompt command from python

It's very simple. You need just two lines of code with just using the built-in function and also it takes the input and runs forever until you stop it. Also that 'cmd' in quotes, leave it and don't change it. Here is the code:

import os
os.system('cmd')

Now just run this code and see the whole windows command prompt in your python project!

Showing an image from an array of images - Javascript

This is a simple example and try to combine it with yours using some modifications. I prefer you set all the images in one array in order to make your code easier to read and shorter:

var myImage = document.getElementById("mainImage");

var imageArray = ["_images/image1.jpg","_images/image2.jpg","_images/image3.jpg",
  "_images/image4.jpg","_images/image5.jpg","_images/image6.jpg"];

var imageIndex = 0; 

function changeImage() {
  myImage.setAttribute("src",imageArray[imageIndex]);
  imageIndex = (imageIndex + 1) % imageArray.length;
}

setInterval(changeImage, 5000);

How can I get the intersection, union, and subset of arrays in Ruby?

If Multiset extends from the Array class

x = [1, 1, 2, 4, 7]
y = [1, 2, 2, 2]
z = [1, 1, 3, 7]

UNION

x.union(y)           # => [1, 2, 4, 7]      (ONLY IN RUBY 2.6)
x.union(y, z)        # => [1, 2, 4, 7, 3]   (ONLY IN RUBY 2.6)
x | y                # => [1, 2, 4, 7]

DIFFERENCE

x.difference(y)      # => [4, 7] (ONLY IN RUBY 2.6)
x.difference(y, z)   # => [4] (ONLY IN RUBY 2.6)
x - y                # => [4, 7]

INTERSECTION

x & y                # => [1, 2]

For more info about the new methods in Ruby 2.6, you can check this blog post about its new features

How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?

You can. Transparent canvas can be quickly faded by using destination-out global composite operation. It's not 100% perfect, sometimes it leaves some traces but it could be tweaked, depending what's needed (i.e. use 'source-over' and fill it with white color with alpha at 0.13, then fade to prepare the canvas).

// Fill canvas using 'destination-out' and alpha at 0.05
ctx.globalCompositeOperation = 'destination-out';
ctx.fillStyle = "rgba(255, 255, 255, 0.05)";
ctx.beginPath();
ctx.fillRect(0, 0, width, height);
ctx.fill();
// Set the default mode.
ctx.globalCompositeOperation = 'source-over';

How to use enums as flags in C++?

What type is the seahawk.flags variable?

In standard C++, enumerations are not type-safe. They are effectively integers.

AnimalFlags should NOT be the type of your variable. Your variable should be int and the error will go away.

Putting hexadecimal values like some other people suggested is not needed. It makes no difference.

The enum values ARE of type int by default. So you can surely bitwise OR combine them and put them together and store the result in an int.

The enum type is a restricted subset of int whose value is one of its enumerated values. Hence, when you make some new value outside of that range, you can't assign it without casting to a variable of your enum type.

You can also change the enum value types if you'd like, but there is no point for this question.

EDIT: The poster said they were concerned with type safety and they don't want a value that should not exist inside the int type.

But it would be type unsafe to put a value outside of AnimalFlags's range inside a variable of type AnimalFlags.

There is a safe way to check for out of range values though inside the int type...

int iFlags = HasClaws | CanFly;
//InvalidAnimalFlagMaxValue-1 gives you a value of all the bits 
// smaller than itself set to 1
//This check makes sure that no other bits are set.
assert(iFlags & ~(InvalidAnimalFlagMaxValue-1) == 0);

enum AnimalFlags {
    HasClaws = 1,
    CanFly =2,
    EatsFish = 4,
    Endangered = 8,

    // put new enum values above here
    InvalidAnimalFlagMaxValue = 16
};

The above doesn't stop you from putting an invalid flag from a different enum that has the value 1,2,4, or 8 though.

If you want absolute type safety then you could simply create a std::set and store each flag inside there. It is not space efficient, but it is type safe and gives you the same ability as a bitflag int does.

C++0x note: Strongly typed enums

In C++0x you can finally have type safe enum values....

enum class AnimalFlags {
    CanFly = 2,
    HasClaws = 4
};

if(CanFly == 2) { }//Compiling error

How to include route handlers in multiple files in Express?

I wrote a small plugin for doing this! got sick of writing the same code over and over.

https://www.npmjs.com/package/js-file-req

Hope it helps.

Simple prime number generator in Python

Here's a simple (Python 2.6.2) solution... which is in-line with the OP's original request (now six-months old); and should be a perfectly acceptable solution in any "programming 101" course... Hence this post.

import math

def isPrime(n):
    for i in range(2, int(math.sqrt(n)+1)):
        if n % i == 0: 
            return False;
    return n>1;

print 2
for n in range(3, 50):
    if isPrime(n):
        print n

This simple "brute force" method is "fast enough" for numbers upto about about 16,000 on modern PC's (took about 8 seconds on my 2GHz box).

Obviously, this could be done much more efficiently, by not recalculating the primeness of every even number, or every multiple of 3, 5, 7, etc for every single number... See the Sieve of Eratosthenes (see eliben's implementation above), or even the Sieve of Atkin if you're feeling particularly brave and/or crazy.

Caveat Emptor: I'm a python noob. Please don't take anything I say as gospel.

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

link file is not good for me.

ln -s aarch64-linux-android-4.9 mips64el-linux-android
ln -s arm-linux-androideabi-4.9 mipsel-linux-android

Because there is another error.

* What went wrong:
A problem occurred configuring project ':Test'.
> Expected caller to ensure valid ABI: MIPS

Add this in defaultConfig if you build with gralde

ndk {
    abiFilters 'armeabi-v7a','arm64-v8a','x86','x86_64'
}

If you use ndk-build command, add this in Application.mk.

APP_ABI := armeabi-v7a arm64-v8a x86 x86_64

Python: Passing variables between functions

This is what is actually happening:

global_list = []

def defineAList():
    local_list = ['1','2','3']
    print "For checking purposes: in defineAList, list is", local_list 
    return local_list 

def useTheList(passed_list):
    print "For checking purposes: in useTheList, list is", passed_list

def main():
    # returned list is ignored
    returned_list = defineAList()   

    # passed_list inside useTheList is set to global_list
    useTheList(global_list) 

main()

This is what you want:

def defineAList():
    local_list = ['1','2','3']
    print "For checking purposes: in defineAList, list is", local_list 
    return local_list 

def useTheList(passed_list):
    print "For checking purposes: in useTheList, list is", passed_list

def main():
    # returned list is ignored
    returned_list = defineAList()   

    # passed_list inside useTheList is set to what is returned from defineAList
    useTheList(returned_list) 

main()

You can even skip the temporary returned_list and pass the returned value directly to useTheList:

def main():
    # passed_list inside useTheList is set to what is returned from defineAList
    useTheList(defineAList()) 

Add a fragment to the URL without causing a redirect?

For straight HTML, with no JavaScript required:

<a href="#something">Add '#something' to URL</a>

Or, to take your question more literally, to just add '#' to the URL:

<a href="#">Add '#' to URL</a>

how to insert date and time in oracle?

Try this:

...(to_date('2011/04/22 08:30:00', 'yyyy/mm/dd hh24:mi:ss'));

Learning Ruby on Rails

My first suggestion would be to learn a little about symbols first. Rails isn't the smallest framework ever, and while there's definitely lots to learn, most of it will start to make sense if you have at least a little bit of understanding what makes it different ("special") from other languages. As pointed out, there's no exact analog in any of the major languages, but they're heavily used by Rails, in order to make things read straightforwardly and perform well, which is the reason I brought it up. My very first exposure to Rails was also my first time looking at Ruby (well before 2.0), and the first thing that caught my eye was the goofy :things they were passing around, and I asked, "WTF is that?"

Also, check out RubyQuiz, and read other peoples' answers on that site.

How to enable LogCat/Console in Eclipse for Android?

In Eclipse, Goto Window-> Show View -> Other -> Android-> Logcat.

Logcat is nothing but a console of your Emulator or Device.

System.out.println does not work in Android. So you have to handle every thing in Logcat. More Info Look out this Documentation.

Edit 1: System.out.println is working on Logcat. If you use that the Tag will be like System.out and Message will be your message.

Oracle SQL Developer: Unable to find a JVM

If you have a 64-bit version of SQL Developer, but for some reason your default JDK is a 32-bit JDK (e.g. if you develop an Eclipse RCP application which requires a 32-bit JDK), then you have to set the value of the SetJavaHome property in the product.conf file to a 64-bit version of JDK in order to run the SQL Developer. For example:

SetJavaHome C:\Program Files\Java\jdk1.7.0_80

The product.conf file is in my case located in the following directory:

C:\Users\username\AppData\Roaming\sqldeveloper\1.0.0.0.0

The solution described above worked in my case. The solutions of @evgenyl and @FGreg did not work in my case.

How do I install pip on macOS or OS X?

Install python3 first, then use pip3 to install packages.

brew install python

python3 will be installed, and pip is shipped with it. To use pip to install some package, run the following

pip3 install package

Notice it's pip3 because you want to use python3.

How to use forEach in vueJs?

In VueJS you can loop through an array like this : const array1 = ['a', 'b', 'c'];

Array.from(array1).forEach(element => 
 console.log(element)
      );

in my case I want to loop through files and add their types to another array:

 Array.from(files).forEach((file) => {
       if(this.mediaTypes.image.includes(file.type)) {
            this.media.images.push(file)
             console.log(this.media.images)
       }
   }

Collections sort(List<T>,Comparator<? super T>) method example

This might be simplest way -

Collections.sort(listOfStudent,new Comparator<Student>(){
                     public int compare(Student s1,Student s2){
                           // Write your logic here.
                     }});

Using Java 8(lambda expression) -

listOfStudent.sort((s1, s2) -> s1.age - s2.age); 

String or binary data would be truncated. The statement has been terminated

Specify a size for the item and warehouse like in the [dbo].[testing1] FUNCTION

@trackingItems1 TABLE (
item       nvarchar(25)  NULL, -- 25 OR equal size of your item column
warehouse   nvarchar(25) NULL, -- same as above
price int   NULL

) 

Since in MSSQL only saying only nvarchar is equal to nvarchar(1) hence the values of the column from the stock table are truncated

Error renaming a column in MySQL

There is a syntax problem, because the right syntax to alter command is ALTER TABLE tablename CHANGE OldColumnName NewColunmName DATATYPE;

Remote Connections Mysql Ubuntu

I was facing the same problem when I was trying to connect Mysql to a Remote Server. I had found out that I had to change the bind-address to the current private IP address of the DB server. But when I was trying to add the bind-address =0.0.0.0 line in my.cnf file, it was not understanding the line when I tried to create a DB.

Upon searching, I found out the original place where bind-address was declared.

The actual declaration is in : /etc/mysql/mariadb.conf.d/50-server.cnf

Therefore I changed the bind-address directly there and then all seems working.

how to check if the input is a number or not in C?

Using fairly simple code:

int i;
int value;
int n;
char ch;

/* Skip i==0 because that will be the program name */
for (i=1; i<argc; i++) {
    n = sscanf(argv[i], "%d%c", &value, &ch);

    if (n != 1) {
        /* sscanf didn't find a number to convert, so it wasn't a number */
    }
    else {
        /* It was */
    }
}

ImportError: No module named pandas

I fixed the same problem with the below commands... Type python on your terminal. If you see python version 2.x then run these two commands to install pandas:

sudo python -m pip install wheel

and

sudo python -m pip install pandas

Else if you see python version 3.x then run these two commands to install pandas:

sudo python3 -m pip install wheel

and

sudo python3 -m pip install pandas

Good Luck!

Difference between View and Request scope in managed beans

A @ViewScoped bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null or void (and thus navigates back to the same view). Once you refresh the page, or return a non-null string (even an empty string!) navigation outcome, then the view scope will end.

A @RequestScoped bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.

A @ViewScoped bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped bean. Every view has its own unique @ViewScoped bean.

See also:

$_POST not working. "Notice: Undefined index: username..."

undefined index means that somewhere in the $_POST array, there isn't an index (key) for the key username.

You should be setting your posted values into variables for a more clean solution, and it's a good habit to get into.

If I was having a similar error, I'd do something like this:

$username = $_POST['username']; // you should really do some more logic to see if it's set first
echo $username;

If username didn't turn up, that'd mean I was screwing up somewhere. You can also,

var_dump($_POST);

To see what you're posting. var_dump is really useful as far as debugging. Check it out: var_dump

How to get a list of properties with a given attribute?

The solution I end up using most is based off of Tomas Petricek's answer. I usually want to do something with both the attribute and property.

var props = from p in this.GetType().GetProperties()
            let attr = p.GetCustomAttributes(typeof(MyAttribute), true)
            where attr.Length == 1
            select new { Property = p, Attribute = attr.First() as MyAttribute};

Python module os.chmod(file, 664) does not change the permission to rw-rw-r-- but -w--wx----

leading 0 means this is octal constant, not the decimal one. and you need an octal to change file mode.

permissions are a bit mask, for example, rwxrwx--- is 111111000 in binary, and it's very easy to group bits by 3 to convert to the octal, than calculate the decimal representation.

0644 (octal) is 0.110.100.100 in binary (i've added dots for readability), or, as you may calculate, 420 in decimal.

Find the most common element in a list

What you want is known in statistics as mode, and Python of course has a built-in function to do exactly that for you:

>>> from statistics import mode
>>> mode([1, 2, 2, 3, 3, 3, 3, 3, 4, 5, 6, 6, 6])
3

Note that if there is no "most common element" such as cases where the top two are tied, this will raise StatisticsError, because statistically speaking, there is no mode in this case.

How to limit the number of dropzone.js files uploaded?

I thought that the most intuitive single file upload process was to replace the previous file upon a new entry.

  $(".drop-image").dropzone({
    url: '/cart?upload-engraving=true',
    maxFiles: 1,
    maxfilesexceeded: function(file) {
        this.removeAllFiles();
        this.addFile(file);
    }
})

Notepad++ Multi editing

Yes: simply press and hold the Alt key, click and drag to select the lines whose columns you wish to edit, and begin typing.

You can also go to Settings > Preferences..., and in the Editing tab, turn on multi-editing, to enable selection of multiple separate regions or columns of text to edit at once.

It's much more intuitive, as you can see your edits live as you type.

Difference between @Before, @BeforeClass, @BeforeEach and @BeforeAll

The code marked @Before is executed before each test, while @BeforeClass runs once before the entire test fixture. If your test class has ten tests, @Before code will be executed ten times, but @BeforeClass will be executed only once.

In general, you use @BeforeClass when multiple tests need to share the same computationally expensive setup code. Establishing a database connection falls into this category. You can move code from @BeforeClass into @Before, but your test run may take longer. Note that the code marked @BeforeClass is run as static initializer, therefore it will run before the class instance of your test fixture is created.

In JUnit 5, the tags @BeforeEach and @BeforeAll are the equivalents of @Before and @BeforeClass in JUnit 4. Their names are a bit more indicative of when they run, loosely interpreted: 'before each tests' and 'once before all tests'.

How can I write maven build to add resources to classpath?

A cleaner alternative of putting your config file into a subfolder of src/main/resources would be to enhance your classpath locations. This is extremely easy to do with Maven.

For instance, place your property file in a new folder src/main/config, and add the following to your pom:

 <build>
    <resources>
        <resource>
            <directory>src/main/config</directory>
        </resource>
    </resources>
 </build>

From now, every files files under src/main/config is considered as part of your classpath (note that you can exclude some of them from the final jar if needed: just add in the build section:

    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <excludes>
                    <exclude>my-config.properties</exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>

so that my-config.properties can be found in your classpath when you run your app from your IDE, but will remain external from your jar in your final distribution).

jQuery UI: Datepicker set year range dropdown to 100 years

I wanted to implement the datepicker to select the birthdate and I had troubles changing the yearRange as it doesn't seemed to work with my version (1.5). I updated to the newest jquery-ui datepicker version here: https://github.com/uxsolutions/bootstrap-datepicker.

Then I found out they provide this very helpful on-the-fly tool, so you can config your whole datepicker and see what settings you have to use.

That's how I found out that the option

defaultViewDate

is the option I was looking for and I didn't find any results searching the web.

So for other users: If you also want to provide the datepicker to change the birthdate, I suggest to use this code options:

$('#birthdate').datepicker({
    startView: 2,
    maxViewMode: 2,
    daysOfWeekHighlighted: "1,2",
    defaultViewDate: { year: new Date().getFullYear()-20, month: 01, day: 01 }
});

When opening the datepicker you will start with the view to select the years, 20 years ago relative to the current year.

Laravel Eloquent where field is X or null

It sounds like you need to make use of advanced where clauses.

Given that search in field1 and field2 is constant we will leave them as is, but we are going to adjust your search in datefield a little.

Try this:

$query = Model::where('field1', 1)
    ->whereNull('field2')
    ->where(function ($query) {
        $query->where('datefield', '<', $date)
            ->orWhereNull('datefield');
    }
);

If you ever need to debug a query and see why it isn't working, it can help to see what SQL it is actually executing. You can chain ->toSql() to the end of your eloquent query to generate the SQL.

How to change package name of Android Project in Eclipse?

Goto the Src folder of your Android project, and open the Java file.

Change the package OldName.android.widget to newName.android.widget.

It gives you an error like this

The declared package "newName.android.widget" does not match the expected package "OLDName.android.widget.

To fix this problem, select Move filename.Java to Newname.android.widget and delete the old package folder.

Next step: Go to AndroidManifest.xml and change package="OldName.android.widget" to package="newName.android.widget".

Use String.split() with multiple delimiters

Try this code:

var string = 'AA.BB-CC-DD.zip';
array = string.split(/[,.]/);

@RequestBody and @ResponseBody annotations in Spring

@RequestBody : Annotation indicating a method parameter should be bound to the body of the HTTP request.

For example:

@RequestMapping(path = "/something", method = RequestMethod.PUT)
public void handle(@RequestBody String body, Writer writer) throws IOException {
    writer.write(body);
}

@ResponseBody annotation can be put on a method and indicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpreted as a view name).

For example:

@RequestMapping(path = "/something", method = RequestMethod.PUT)
public  @ResponseBody String helloWorld() {
    return "Hello World";
}  

Alternatively, we can use @RestController annotation in place of @Controller annotation. This will remove the need to using @ResponseBody.

for more details

How To Make Circle Custom Progress Bar in Android

I've encountered same problem and not found any appropriate solution for my case, so I decided to go another way. I've created custom drawable class. Within this class I've created 2 Paints for progress line and background line (with some bigger stroke). First of all set startAngle and sweepAngle in constructor:

    mSweepAngle = 0;
    mStartAngle = 270;

Here is onDraw method of this class:

@Override
public void draw(Canvas canvas) {
    // draw background line
    canvas.drawArc(mRectF, 0, 360, false, mPaintBackground);
    // draw progress line
    canvas.drawArc(mRectF, mStartAngle, mSweepAngle, false, mPaintProgress);
}

So now all you need to do is set this drawable as a backgorund of the view, in background thread change sweepAngle:

mSweepAngle += 360 / totalTimerTime // this is mStep

and directly call InvalidateSelf() with some interval (e.g every 1 second or more often if you want smooth progress changes) on the view that have this drawable as a background. Thats it!

P.S. I know, I know...of course you want some more code. So here it is all flow:

  1. Create XML view :

     <View
     android:id="@+id/timer"
     android:layout_width="match_parent"
     android:layout_height="match_parent"/>
    
  2. Create and configure Custom Drawable class (as I described above). Don't forget to setup Paints for lines. Here paint for progress line:

    mPaintProgress = new Paint();
    mPaintProgress.setAntiAlias(true);
    mPaintProgress.setStyle(Paint.Style.STROKE);
    mPaintProgress.setStrokeWidth(widthProgress);
    mPaintProgress.setStrokeCap(Paint.Cap.ROUND);
    mPaintProgress.setColor(colorThatYouWant);
    

Same for backgroung paint (set width little more if you want)

  1. In drawable class create method for updating (Step calculation described above)

    public void update() {
        mSweepAngle += mStep;
        invalidateSelf();
    }
    
  2. Set this drawable class to YourTimerView (I did it in runtime) - view with @+id/timer from xml above:

    OurSuperDrawableClass superDrawable = new OurSuperDrawableClass(); YourTimerView.setBackgroundDrawable(superDrawable);

  3. Create background thread with runnable and update view:

    YourTimerView.post(new Runnable() {
        @Override
        public void run() {
            // update progress view
            superDrawable.update();
        }
    });
    

Thats it ! Enjoy your cool progress bar. Here screenshot of result if you're too bored of this amount of text.enter image description here

How do I force "git pull" to overwrite local files?

You might find this command helpful to throw away local changes:

git checkout <your-branch> -f

And then do a cleanup (removes untracked files from the working tree):

git clean -f

If you want to remove untracked directories in addition to untracked files:

git clean -fd

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

You can try and check for the referer, which should be the parent site if you're an iframe

you can do that like this:

var href = document.referrer;

Create a mocked list by mockito

When dealing with mocking lists and iterating them, I always use something like:

@Spy
private List<Object> parts = new ArrayList<>();

Powershell: Get FQDN Hostname

Local Computer FQDN via dotNet class

[System.Net.Dns]::GetHostEntry([string]$env:computername).HostName

or

[System.Net.Dns]::GetHostEntry([string]"localhost").HostName

Reference:

Dns Methods (System.Net)

note: GetHostByName method is obsolete


Local computer FQDN via WMI query

$myFQDN=(Get-WmiObject win32_computersystem).DNSHostName+"."+(Get-WmiObject win32_computersystem).Domain
Write-Host $myFQDN

Reference:

Win32_ComputerSystem class

SQL Error with Order By in Subquery

I Use This Code To Get Top Second Salary

I am Also Get Error Like

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.

TOP 100 I Used To Avoid The Error

select * from ( select tbl.Coloumn1 ,CONVERT(varchar, ROW_NUMBER() OVER (ORDER BY (SELECT 1))) AS Rowno from ( select top 100 * from Table1 order by Coloumn1 desc) as tbl) as tbl where tbl.Rowno=2

sklearn: Found arrays with inconsistent numbers of samples when calling LinearRegression.fit()

I faced a similar problem. The problem in my case was, Number of rows in X was not equal to number of rows in y.

i.e. number of entries in feature columns was not equal to number of entires in target variable since I had dropped some rows from freature columns.

Can not connect to local PostgreSQL

gem uninstall pg

On OS X with Homebrew:

gem install pg -- --with-pg-config=/usr/local/bin/pg_config

set background color: Android

By the way, a good tip on quickly selecting color on the newer versions of AS is simply to type #fff and then using the color picker on the side of the code to choose the one you want. Quick and easier than remembering all the color hexadecimals. For example:

android:background="#fff"

DataTrigger where value is NOT null?

This is a bit of a cheat but I just set a default style and then overrode it using a DataTrigger if the value is null...

  <Style> 
      <!-- Highlight for Reviewed (Default) -->
      <Setter Property="Control.Background" Value="PaleGreen" /> 
      <Style.Triggers>
        <!-- Highlight for Not Reviewed -->
        <DataTrigger Binding="{Binding Path=REVIEWEDBY}" Value="{x:Null}">
          <Setter Property="Control.Background" Value="LightIndianRed" />
        </DataTrigger>
      </Style.Triggers>
  </Style>

Write a file in UTF-8 using FileWriter (Java)?

OK it's 2019 now, and from Java 11 you have a constructor with Charset:

FileWriter?(String fileName, Charset charset)

Unfortunately, we still cannot modify the byte buffer size, and it's set to 8192. (https://www.baeldung.com/java-filewriter)

Big-oh vs big-theta

One reason why big O gets used so much is kind of because it gets used so much. A lot of people see the notation and think they know what it means, then use it (wrongly) themselves. This happens a lot with programmers whose formal education only went so far - I was once guilty myself.

Another is because it's easier to type a big O on most non-Greek keyboards than a big theta.

But I think a lot is because of a kind of paranoia. I worked in defence-related programming for a bit (and knew very little about algorithm analysis at the time). In that scenario, the worst case performance is always what people are interested in, because that worst case might just happen at the wrong time. It doesn't matter if the actually probability of that happening is e.g. far less than the probability of all members of a ships crew suffering a sudden fluke heart attack at the same moment - it could still happen.

Though of course a lot of algorithms have their worst case in very common circumstances - the classic example being inserting in-order into a binary tree to get what's effectively a singly-linked list. A "real" assessment of average performance needs to take into account the relative frequency of different kinds of input.

Combine :after with :hover

Just append :after to your #alertlist li:hover selector the same way you do with your #alertlist li.selected selector:

#alertlist li.selected:after, #alertlist li:hover:after
{
    position:absolute;
    top: 0;
    right:-10px;
    bottom:0;

    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-left: 10px solid #303030;
    content: "";
}

c++ array assignment of multiple values

const static int newvals[] = {34,2,4,5,6};

std::copy(newvals, newvals+sizeof(newvals)/sizeof(newvals[0]), array);

Proper indentation for Python multiline strings

Use inspect.cleandoc like so:

def method():
    string = inspect.cleandoc("""
        line one
        line two
        line three""")

Relative indentation will be maintained as expected. As commented below, if you want to keep preceding empty lines, use textwrap.dedent. However that also keeps the first line break.

Note: It's good practice to indent logical blocks of code under its related context to clarify the structure. E.g. the multi-line string belonging to the variable string.

How to request Google to re-crawl my website?

There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:

  1. Go to: https://www.google.com/webmasters/tools/ and log in
  2. If you haven't already, add and verify the site with the "Add a Site" button
  3. Click on the site name for the one you want to manage
  4. Click Crawl -> Fetch as Google
  5. Optional: if you want to do a specific page only, type in the URL
  6. Click Fetch
  7. Click Submit to Index
  8. Select either "URL" or "URL and its direct links"
  9. Click OK and you're done.

With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.

Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/

Update 2019:

  1. Login to - Google Search Console
  2. Add a site and verify it with the available methods.
  3. After verification from the console, click on URL Inspection.
  4. In the Search bar on top, enter your website URL or custom URLs for inspection and enter.
  5. After Inspection, it'll show an option to Request Indexing
  6. Click on it and GoogleBot will add your website in a Queue for crawling.

"relocation R_X86_64_32S against " linking Error

Relocation R_X86_64_PC32 against undefined symbol , usually happens when LDFLAGS are set with hardening and CFLAGS not .
Maybe just user error:
If you are using -specs=/usr/lib/rpm/redhat/redhat-hardened-ld at link time, you also need to use -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 at compile time, and as you are compiling and linking at the same time, you need either both, or drop the -specs=/usr/lib/rpm/redhat/redhat-hardened-ld . Common fixes :
https://bugzilla.redhat.com/show_bug.cgi?id=1304277#c3
https://github.com/rpmfusion/lxdream/blob/master/lxdream-0.9.1-implicit.patch

Verify host key with pysftp

Cook book to use different ways of pysftp.CnOpts() and hostkeys options.

Source : https://pysftp.readthedocs.io/en/release_0.2.9/cookbook.html

Host Key checking is enabled by default. It will use ~/.ssh/known_hosts by default. If you wish to disable host key checking (NOT ADVISED) you will need to modify the default CnOpts and set the .hostkeys to None.

import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
with pysftp.Connection('host', username='me', password='pass', cnopts=cnopts):
    # do stuff here

To use a completely different known_hosts file, you can override CnOpts looking for ~/.ssh/known_hosts by specifying the file when instantiating.

import pysftp
cnopts = pysftp.CnOpts(knownhosts='path/to/your/knownhostsfile')

with pysftp.Connection('host', username='me', password='pass', cnopts=cnopts):
    # do stuff here

If you wish to use ~/.ssh/known_hosts but add additional known host keys you can merge with update additional known_host format files by using .load method.

import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys.load('path/to/your/extra_knownhosts')
with pysftp.Connection('host', username='me', password='pass', cnopts=cnopts):
    # do stuff here

how to display data values on Chart.js

If you are using the plugin chartjs-plugin-datalabels then the following code options object will help

Make sure you import import 'chartjs-plugin-datalabels'; in your typescript file or add reference to <script src="chartjs-plugin-datalabels.js"></script> in your javascript file.

options: {
    maintainAspectRatio: false,
    responsive: true,
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true,
        }
      }]
    },
    plugins: {
      datalabels: {
        anchor: 'end',
        align: 'top',
        formatter: Math.round,
        font: {
          weight: 'bold'
        }
      }
    }
  }

matplotlib set yaxis label size

If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40).

If you use pyplot programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40) or afterwards with ax.yaxis.label.set_size(40).

How do I uninstall nodejs installed from pkg (Mac OS X)?

Following previous posts, here is the full list I used

sudo npm uninstall npm -g
sudo rm -rf /usr/local/lib/node /usr/local/lib/node_modules /var/db/receipts/org.nodejs.*
sudo rm -rf /usr/local/include/node /Users/$USER/.npm
sudo rm /usr/local/bin/node
sudo rm /usr/local/share/man/man1/node.1
sudo rm /usr/local/lib/dtrace/node.d
brew install node

How can I get the current date and time in the terminal and set a custom command in the terminal for it?

You can use date to get time and date of a day:

[pengyu@GLaDOS ~]$date
Tue Aug 27 15:01:27 CST 2013

Also hwclock would do:

[pengyu@GLaDOS ~]$hwclock
Tue 27 Aug 2013 03:01:29 PM CST  -0.516080 seconds

For customized output, you can either redirect the output of date to something like awk, or write your own program to do that.

Remember to put your own executable scripts/binary into your PATH (e.g. /usr/bin) to make it invokable anywhere.

How to add element in Python to the end of list using list.insert?

list.insert with any index >= len(of_the_list) places the value at the end of list. It behaves like append

Python 3.7.4
>>>lst=[10,20,30]
>>>lst.insert(len(lst), 101)
>>>lst
[10, 20, 30, 101]
>>>lst.insert(len(lst)+50, 202)
>>>lst
[10, 20, 30, 101, 202]

Time complexity, append O(1), insert O(n)

How to check whether a str(variable) is empty or not?

if the variable contains text then:

len(variable) != 0

of it does not

len(variable) == 0

Is it possible to set transparency in CSS3 box-shadow?

I suppose rgba() would work here. After all, browser support for both box-shadow and rgba() is roughly the same.

/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);

_x000D_
_x000D_
div {_x000D_
    width: 200px;_x000D_
    height: 50px;_x000D_
    line-height: 50px;_x000D_
    text-align: center;_x000D_
    color: white;_x000D_
    background-color: red;_x000D_
    margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
  box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
  box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
_x000D_
_x000D_

How to declare variable and use it in the same Oracle SQL script?

Try using double quotes if it's a char variable:

DEFINE stupidvar = "'stupidvarcontent'";

or

DEFINE stupidvar = 'stupidvarcontent';

SELECT stupiddata  
FROM stupidtable  
WHERE stupidcolumn = '&stupidvar'

upd:

SQL*Plus: Release 10.2.0.1.0 - Production on Wed Aug 25 17:13:26 2010

Copyright (c) 1982, 2005, Oracle.  All rights reserved.

SQL> conn od/od@etalon
Connected.
SQL> define var = "'FL-208'";
SQL> select code from product where code = &var;
old   1: select code from product where code = &var
new   1: select code from product where code = 'FL-208'

CODE
---------------
FL-208

SQL> define var = 'FL-208';
SQL> select code from product where code = &var;
old   1: select code from product where code = &var
new   1: select code from product where code = FL-208
select code from product where code = FL-208
                                      *
ERROR at line 1:
ORA-06553: PLS-221: 'FL' is not a procedure or is undefined

mysql-python install error: Cannot open include file 'config-win.h'

well this worked for me:

pip install mysqlclient

this is for python 3.x in window 7 i am not sure about other windows os versions

Help needed with Median If in Excel

Assuming your categories are in cells A1:A6 and the corresponding values are in B1:B6, you might try typing the formula =MEDIAN(IF($A$1:$A$6="Airline",$B$1:$B$6,"")) in another cell and then pressing CTRL+SHIFT+ENTER.

Using CTRL+SHIFT+ENTER tells Excel to treat the formula as an "array formula". In this example, that means that the IF statement returns an array of 6 values (one of each of the cells in the range $A$1:$A$6) instead of a single value. The MEDIAN function then returns the median of these values. See http://www.cpearson.com/excel/arrayformulas.aspx for a similar example using AVERAGE instead of MEDIAN.

Boolean.parseBoolean("1") = false...?

How about this?

boolean uses_votes =
  ( "|1|yes|on|true|"
      .indexOf("|"+o.get("uses_votes").toLowerCase()+"|")
      > -1
  );

How to Maximize window in chrome using webDriver (python)

try this, tested on windows platform and it works fine :

from selenium import webdriver
browser = webdriver.Chrome('C:\\Users\\yeivic\\Downloads\\chromedriver')
browser.fullscreen_window()
browser.get('http://google.com/')

LINQ query on a DataTable

You can get it work elegant via linq like this:

from prod in TenMostExpensiveProducts().Tables[0].AsEnumerable()
where prod.Field<decimal>("UnitPrice") > 62.500M
select prod

Or like dynamic linq this (AsDynamic is called directly on DataSet):

TenMostExpensiveProducts().AsDynamic().Where (x => x.UnitPrice > 62.500M)

I prefer the last approach while is is the most flexible. P.S.: Don't forget to connect System.Data.DataSetExtensions.dll reference

When do I need a fb:app_id or fb:admins?

I think the documentation is reasonably helpful!

If you read it again, it says that adding open graph elements on your website will make your website act as a facebook page and you'll get the ability to publish updates to them etc.

So I think it's up to you - you can either just have a page with no OG elements, which is less work but also less 'rewarding' for you.

If you do use og, then set type to: blog

Finally: fb:admins or fb:app_id - A comma-separated list of either the Facebook IDs of page administrators or a Facebook Platform application ID. At a minimum, include only your own Facebook ID.

So just put your own fbid in there. As a tip, you can easily get this by looking at the url of your profile photo on facebook.

Address in mailbox given [] does not comply with RFC 2822, 3.6.2. when email is in a variable

Make sure your email address variable is not blank. Check using

print_r($variable_passed);

'int' object has no attribute '__getitem__'

The error:

'int' object has no attribute '__getitem__'

means that you're attempting to apply the index operator [] on an int, not a list. So is col not a list, even when it should be? Let's start from that.

Look here:

col = [[0 for col in range(5)] for row in range(6)]

Use a different variable name inside, looks like the list comprehension overwrites the col variable during iteration. (Not during the iteration when you set col, but during the following ones.)

How do you do a deep copy of an object in .NET?

    public static object CopyObject(object input)
    {
        if (input != null)
        {
            object result = Activator.CreateInstance(input.GetType());
            foreach (FieldInfo field in input.GetType().GetFields(Consts.AppConsts.FullBindingList))
            {
                if (field.FieldType.GetInterface("IList", false) == null)
                {
                    field.SetValue(result, field.GetValue(input));
                }
                else
                {
                    IList listObject = (IList)field.GetValue(result);
                    if (listObject != null)
                    {
                        foreach (object item in ((IList)field.GetValue(input)))
                        {
                            listObject.Add(CopyObject(item));
                        }
                    }
                }
            }
            return result;
        }
        else
        {
            return null;
        }
    }

This way is a few times faster than BinarySerialization AND this does not require the [Serializable] attribute.

Free space in a CMD shell

The following script will give you free bytes on the drive:

@setlocal enableextensions enabledelayedexpansion
@echo off
for /f "tokens=3" %%a in ('dir c:\') do (
    set bytesfree=%%a
)
set bytesfree=%bytesfree:,=%
echo %bytesfree%
endlocal && set bytesfree=%bytesfree%

Note that this depends on the output of your dir command, which needs the last line containing the free space of the format 24 Dir(s) 34,071,691,264 bytes free. Specifically:

  • it must be the last line (or you can modify the for loop to detect the line explicitly rather than relying on setting bytesfree for every line).
  • the free space must be the third "word" (or you can change the tokens= bit to get a different word).
  • thousands separators are the , character (or you can change the substitution from comma to something else).

It doesn't pollute your environment namespace, setting only the bytesfree variable on exit. If your dir output is different (eg, different locale or language settings), you will need to adjust the script.

Comparing two input values in a form validation with AngularJS

You should be able to use ng-pattern/regex for comparing 2 input values

Email:<input type="email" name="email1" ng-model="emailReg">
Repeat Email:<input type="email" name="email2" ng-model="emailReg2" ng-pattern="emailReg">

and validation with:

<span ng-show="registerForm.email2.$error.pattern">Repeat Email should have the same value with email!</span>

Print string and variable contents on the same line in R

As other users said, cat() is probably the best option.

@krlmlr suggested using sprintf() and it's currently the third ranked answer. sprintf() is not a good idea. From R documentation:

The format string is passed down the OS's sprintf function, and incorrect formats can cause the latter to crash the R process.

There is no good reason to use sprintf() over cat or other options.

Using Address Instead Of Longitude And Latitude With Google Maps API

Thought I'd share this code snippet that I've used before, this adds multiple addresses via Geocode and adds these addresses as Markers...

_x000D_
_x000D_
var addressesArray = [_x000D_
  'Address Str.No, Postal Area/city',_x000D_
  //follow this structure_x000D_
]_x000D_
var map = new google.maps.Map(document.getElementById('map'), {_x000D_
  center: {_x000D_
    lat: 12.7826,_x000D_
    lng: 105.0282_x000D_
  },_x000D_
  zoom: 6,_x000D_
  gestureHandling: 'cooperative'_x000D_
});_x000D_
var geocoder = new google.maps.Geocoder();_x000D_
for (i = 0; i < addressArray.length; i++) {_x000D_
  var address = addressArray[i];_x000D_
  geocoder.geocode({_x000D_
    'address': address_x000D_
  }, function(results, status) {_x000D_
    if (status === 'OK') {_x000D_
      var marker = new google.maps.Marker({_x000D_
        map: map,_x000D_
        position: results[0].geometry.location,_x000D_
        center: {_x000D_
          lat: 12.7826,_x000D_
          lng: 105.0282_x000D_
        },_x000D_
      });_x000D_
    } else {_x000D_
      alert('Geocode was not successful for the following reason: ' + status);_x000D_
    }_x000D_
  });_x000D_
}
_x000D_
_x000D_
_x000D_

Java List.add() UnsupportedOperationException

You must initialize your List seeAlso :

List<String> seeAlso = new Vector<String>();

or

List<String> seeAlso = new ArrayList<String>();

Typing Greek letters etc. in Python plots

Python 3.x: small greek letters are coded from 945 to 969 so,alpha is chr(945), omega is chr(969) so just type

print(chr(945))

the list of small greek letters in a list:

greek_letterz=[chr(code) for code in range(945,970)]

print(greek_letterz)

And now, alpha is greek_letterz[0], beta is greek_letterz[1], a.s.o

How to delete all files and folders in a directory?

In Windows 7, if you have just created it manually with Windows Explorer, the directory structure is similar to this one:

C:
  \AAA
    \BBB
      \CCC
        \DDD

And running the code suggested in the original question to clean the directory C:\AAA, the line di.Delete(true) always fails with IOException "The directory is not empty" when trying to delete BBB. It is probably because of some kind of delays/caching in Windows Explorer.

The following code works reliably for me:

static void Main(string[] args)
{
    DirectoryInfo di = new DirectoryInfo(@"c:\aaa");
    CleanDirectory(di);
}

private static void CleanDirectory(DirectoryInfo di)
{
    if (di == null)
        return;

    foreach (FileSystemInfo fsEntry in di.GetFileSystemInfos())
    {
        CleanDirectory(fsEntry as DirectoryInfo);
        fsEntry.Delete();
    }
    WaitForDirectoryToBecomeEmpty(di);
}

private static void WaitForDirectoryToBecomeEmpty(DirectoryInfo di)
{
    for (int i = 0; i < 5; i++)
    {
        if (di.GetFileSystemInfos().Length == 0)
            return;
        Console.WriteLine(di.FullName + i);
        Thread.Sleep(50 * i);
    }
}

Copying and pasting data using VBA code

Use the PasteSpecial method:

sht.Columns("A:G").Copy
Range("A1").PasteSpecial Paste:=xlPasteValues

BUT your big problem is that you're changing your ActiveSheet to "Data" and not changing it back. You don't need to do the Activate and Select, as per my code (this assumes your button is on the sheet you want to copy to).

How to find keys of a hash?

There is function in modern JavaScript (ECMAScript 5) called Object.keys performing this operation:

var obj = { "a" : 1, "b" : 2, "c" : 3};
alert(Object.keys(obj)); // will output ["a", "b", "c"]

Compatibility details can be found here.

On the Mozilla site there is also a snippet for backward compatibility:

if(!Object.keys) Object.keys = function(o){
   if (o !== Object(o))
      throw new TypeError('Object.keys called on non-object');
   var ret=[],p;
   for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)) ret.push(p);
   return ret;
}

How to remove whitespace from a string in typescript?

Trim just removes the trailing and leading whitespace. Use .replace(/ /g, "") if there are just spaces to be replaced.

this.maintabinfo = this.inner_view_data.replace(/ /g, "").toLowerCase();

Returning a stream from File.OpenRead()

You need

    str.CopyTo(data);
    data.Position = 0; // reset to beginning
    byte[] buf = new byte[data.Length];
    data.Read(buf, 0, buf.Length);  

And since your Test() method is imitating the client it ought to Close() or Dispose() the str Stream. And the memoryStream too, just out of principal.

What does API level mean?

API level is basically the Android version. Instead of using the Android version name (eg 2.0, 2.3, 3.0, etc) an integer number is used. This number is increased with each version. Android 1.6 is API Level 4, Android 2.0 is API Level 5, Android 2.0.1 is API Level 6, and so on.

Regular expression to validate US phone numbers?

The easiest way to match both

^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$

and

^[0-9]{3}-[0-9]{3}-[0-9]{4}$

is to use alternation ((...|...)): specify them as two mostly-separate options:

^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$

By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234, not (123)123-1234. So you might want to write:

^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$

(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)

Convert Int to String in Swift

In swift 3.0, you may change integer to string as given below

let a:String = String(stringInterpolationSegment: 15)

Another way is

let number: Int = 15
let _numberInStringFormate: String = String(number)

//or any integer number in place of 15

Android dependency has different version for the compile and runtime

Just add these lines in your build.gradle file

resolutionStrategy.force "com.android.support:support-media-compat:26.0.0-beta2"

resolutionStrategy.force "com.android.support:support-v4:26.0.0-beta2"

Relative paths in Python

From what suggest others and from pathlib documentation, a simple and clear solution is the following (suppose the file we need to refer to: Test/data/users.csv:

# This file location: Tests/src/long/module/subdir/some_script.py
from pathlib import Path

# back to Tests/
PROJECT_ROOT = Path(__file__).parents[4]
# then down to Test/data/users.csv
CSV_USERS_PATH = PROJECT_ROOT / 'data' / 'users.csv'  

with CSV_USERS_PATH.open() as users:
    print(users.read())

Now this looks a bit odd to me, because if you move some_script.py around, the path to the root of our project may change (we would need to modify parents[4]). On the other hand I found a solution that I prefer based on the same idea.

Suppose we have the following directory structure:

Tests
+-- data
¦  +-- users.csv
+-- src
   +-- long
   ¦  +-- module
   ¦     +-- subdir
   ¦        +-- some_script.py
   +-- main.py
   +-- paths.py

The paths.py file will be responsible for storing the root location of our projet:

from pathlib import Path

PROJECT_ROOT = Path(__file__).parents[1]

All scripts can now use paths.PROJECT_ROOT to express absolute paths from the root of the project. For example in src/long/module/subdir/some_script.py we could have:

from paths import PROJECT_ROOT

CSV_USERS_PATH = PROJECT_ROOT / 'data' / 'users.csv'

def hello():
    with CSV_USERS_PATH.open() as f:
        print(f.read())

And everything goes as expected:

~/Tests/src/$ python main.py

/Users/cglacet/Tests/data/users.csv
hello, user

~/Tests/$ python src/main.py

/Users/cglacet/Tests/data/users.csv
hello, user

The main.py script simply is:

from long.module.subdir import some_script

some_script.hello()

An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll

Read the message:

Only one <configSections> element allowed per config file and if present must be the first child of the root <configuration> element.

Move the configSections element to the top - just above where system.data is currently.

Permission denied (publickey,gssapi-keyex,gssapi-with-mic)

I had the same problem and for some reason The sshKeys was not syncing up with my user on the instance.

I created another user by adding --ssh_user=anotheruser to gcutil command.

The gcutil looked like this

gcutil --service_version="v1" --project="project"  --ssh_user=anotheruser ssh  --zone="us-central1-a" "inst1"

Capture iframe load complete event

You can also capture jquery ready event this way:

$('#iframeid').ready(function () {
//Everything you need.
});

Here is a working example:

http://jsfiddle.net/ZrFzF/

Correct way to work with vector of arrays

There is no error in the following piece of code:

float arr[4];
arr[0] = 6.28;
arr[1] = 2.50;
arr[2] = 9.73;
arr[3] = 4.364;
std::vector<float*> vec = std::vector<float*>();
vec.push_back(arr);
float* ptr = vec.front();
for (int i = 0; i < 3; i++)
    printf("%g\n", ptr[i]);

OUTPUT IS:

6.28

2.5

9.73

4.364

IN CONCLUSION:

std::vector<double*>

is another possibility apart from

std::vector<std::array<double, 4>>

that James McNellis suggested.

scrollIntoView Scrolls just too far

Position Anchor By Absolute Method

Another way do do this is to position your anchors exactly where you want on the page rather than relying on scrolling by offset. I find it allows better control for each element (eg. if you want a different offset for certain elements), and may also be more resistant to browser API changes/differences.

<div id="title-element" style="position: relative;">
  <div id="anchor-name" style="position: absolute; top: -100px; left: 0"></div>
</div>

Now the offset is specified as -100px relative to the element. Create a function to create this anchor for code reuse, or if you are using a modern JS framework such as React do this by creating a component that renders your anchor, and pass in the anchor name and alignment for each element, which may or may not be the same.

Then just use :

const element = document.getElementById('anchor-name')
element.scrollIntoView({ behavior: 'smooth', block: 'start' });

For smooth scrolling with an offset of 100px.

Java - sending HTTP parameters via POST method easily

GET and POST method set like this... Two types for api calling 1)get() and 2) post() . get() method to get value from api json array to get value & post() method use in our data post in url and get response.

 public class HttpClientForExample {

    private final String USER_AGENT = "Mozilla/5.0";

    public static void main(String[] args) throws Exception {

        HttpClientExample http = new HttpClientExample();

        System.out.println("Testing 1 - Send Http GET request");
        http.sendGet();

        System.out.println("\nTesting 2 - Send Http POST request");
        http.sendPost();

    }

    // HTTP GET request
    private void sendGet() throws Exception {

        String url = "http://www.google.com/search?q=developer";

        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);

        // add request header
        request.addHeader("User-Agent", USER_AGENT);

        HttpResponse response = client.execute(request);

        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + 
                       response.getStatusLine().getStatusCode());

        BufferedReader rd = new BufferedReader(
                       new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        System.out.println(result.toString());

    }

    // HTTP POST request
    private void sendPost() throws Exception {

        String url = "https://selfsolve.apple.com/wcResults.do";

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);

        // add header
        post.setHeader("User-Agent", USER_AGENT);

        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("sn", "C02G8416DRJM"));
        urlParameters.add(new BasicNameValuePair("cn", ""));
        urlParameters.add(new BasicNameValuePair("locale", ""));
        urlParameters.add(new BasicNameValuePair("caller", ""));
        urlParameters.add(new BasicNameValuePair("num", "12345"));

        post.setEntity(new UrlEncodedFormEntity(urlParameters));

        HttpResponse response = client.execute(post);
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + post.getEntity());
        System.out.println("Response Code : " + 
                                    response.getStatusLine().getStatusCode());

        BufferedReader rd = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        System.out.println(result.toString());

    }

}

Image comparison - fast algorithm

My company has about 24million images come in from manufacturers every month. I was looking for a fast solution to ensure that the images we upload to our catalog are new images.

I want to say that I have searched the internet far and wide to attempt to find an ideal solution. I even developed my own edge detection algorithm.
I have evaluated speed and accuracy of multiple models. My images, which have white backgrounds, work extremely well with phashing. Like redcalx said, I recommend phash or ahash. DO NOT use MD5 Hashing or anyother cryptographic hashes. Unless, you want only EXACT image matches. Any resizing or manipulation that occurs between images will yield a different hash.

For phash/ahash, Check this out: imagehash

I wanted to extend *redcalx'*s post by posting my code and my accuracy.

What I do:

from PIL import Image
from PIL import ImageFilter
import imagehash

img1=Image.open(r"C:\yourlocation")
img2=Image.open(r"C:\yourlocation")
if img1.width<img2.width:
    img2=img2.resize((img1.width,img1.height))
else:
    img1=img1.resize((img2.width,img2.height))
img1=img1.filter(ImageFilter.BoxBlur(radius=3))
img2=img2.filter(ImageFilter.BoxBlur(radius=3))
phashvalue=imagehash.phash(img1)-imagehash.phash(img2)
ahashvalue=imagehash.average_hash(img1)-imagehash.average_hash(img2)
totalaccuracy=phashvalue+ahashvalue

Here are some of my results:

item1  item2  totalsimilarity
desk1  desk1       3
desk1  phone1     22
chair1 desk1      17
phone1 chair1     34

Hope this helps!

Checking that a List is not empty in Hamcrest

Well there's always

assertThat(list.isEmpty(), is(false));

... but I'm guessing that's not quite what you meant :)

Alternatively:

assertThat((Collection)list, is(not(empty())));

empty() is a static in the Matchers class. Note the need to cast the list to Collection, thanks to Hamcrest 1.2's wonky generics.

The following imports can be used with hamcrest 1.3

import static org.hamcrest.Matchers.empty;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.*;

INNER JOIN vs INNER JOIN (SELECT . FROM)

You are correct. You did exactly the right thing, checking the query plan rather than trying to second-guess the optimiser. :-)

With CSS, use "..." for overflowed block of multi-lines

Here is the closest solution I could get using just css.

HTML

<div class="ellipsis"> <span>...</span>
Hello this is Mr_Green from Stackoverflow. I love CSS. I live in CSS and I will never leave working on CSS even my work is on other technologies.</div>

CSS

div {
    height: 3em;
    line-height: 1.5em;
    width: 80%;
    border: 1px solid green;
    overflow: hidden;
    position: relative;
}
div:after {
    content:". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  . . . . . . . . . . . . . . . . . . . . . . . . . . . .";
    background-color: white;
    color: white;
    display: inline;
    position: relative;
    box-shadow: 8px 1px 1px white;
    z-index: 1;
}
span {
    position: absolute;
    bottom: 0px;
    right: 0px;
    background-color: white;
}

Working Fiddle (resize the window to check)

Link to my blog for explanation

Updated Fiddle

I hope now some css expert would have got idea on how to make it perfect. :)

Setting a backgroundImage With React Inline Styles

Sometimes your SVG will be inlined by React so you need quotes around it:

     backgroundImage: `url("${Background}")`

otherwise it's invalid CSS and the browser dev tools will not show that you've set background-image at all.

How does "FOR" work in cmd batch file?

Couldn't resist throwing this out there, old as this thread is... Usually when the need arises to iterate through each of the files in PATH, all you really want to do is find a particular file... If that's the case, this one-liner will spit out the first directory it finds your file in:

(ex: looking for java.exe)

for %%x in (java.exe) do echo %%~dp$PATH:x

How to import Maven dependency in Android Studio/IntelliJ?

Android Studio 3

The answers that talk about Maven Central are dated since Android Studio uses JCenter as the default repository center now. Your project's build.gradle file should have something like this:

repositories {
    google()
    jcenter()
}

So as long as the developer has their Maven repository there (which Picasso does), then all you would have to do is add a single line to the dependencies section of your app's build.gradle file.

dependencies {
    // ...
    implementation 'com.squareup.picasso:picasso:2.5.2'
}

'readline/readline.h' file not found

You reference a Linux distribution, so you need to install the readline development libraries

On Debian based platforms, like Ubuntu, you can run:

sudo apt-get install libreadline-dev 

and that should install the correct headers in the correct places,.

If you use a platform with yum, like SUSE, then the command should be:

yum install readline-devel

How to cherry pick a range of commits and merge into another branch?

I wrapped VonC's code into a short bash script, git-multi-cherry-pick, for easy running:

#!/bin/bash

if [ -z $1 ]; then
    echo "Equivalent to running git-cherry-pick on each of the commits in the range specified.";
    echo "";
    echo "Usage:  $0 start^..end";
    echo "";
    exit 1;
fi

git rev-list --reverse --topo-order $1 | while read rev 
do 
  git cherry-pick $rev || break 
done 

I'm currently using this as I rebuild the history of a project that had both 3rd-party code and customizations mixed together in the same svn trunk. I'm now splitting apart core 3rd party code, 3rd party modules, and customizations onto their own git branches for better understanding of customizations going forward. git-cherry-pick is helpful in this situation since I have two trees in the same repository, but without a shared ancestor.

How to make `setInterval` behave more in sync, or how to use `setTimeout` instead?

According to your requirement

just show me a basic example of using setTimeout to loop something

we have following example which can help you

_x000D_
_x000D_
var itr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];_x000D_
var  interval = 1000; //one second_x000D_
itr.forEach((itr, index) => {_x000D_
_x000D_
  setTimeout(() => {_x000D_
    console.log(itr)_x000D_
  }, index * interval)_x000D_
})
_x000D_
_x000D_
_x000D_

Call a VBA Function into a Sub Procedure

To Add a Function To a new Button on your Form: (and avoid using macro to call function)

After you created your Function (Function MyFunctionName()) and you are in form design view:

  1. Add a new button (I don't think you can reassign an old button - not sure though).

  2. When the button Wizard window opens up click Cancel.

  3. Go to the Button properties Event Tab - On Click - field.

  4. At that fields drop down menu select: Event Procedure.

  5. Now click on button beside drop down menu that has ... in it and you will be taken to a new Private Sub in the forms Visual Basic window.

  6. In that Private Sub type: Call MyFunctionName
    It should look something like this:

    Private Sub Command23_Click()
    
        Call MyFunctionName
    
    End Sub
    
  7. Then just save it.

nodejs - first argument must be a string or Buffer - when using response.write with http.request

The first argument must be one of type string or Buffer. Received type object

 at write_

I was getting like the above error while I passing body data to the request module.

I have passed another parameter that is JSON: true and its working.

var option={
url:"https://myfirstwebsite/v1/appdata",
json:true,
body:{name:'xyz',age:30},
headers://my credential
}
rp(option)
.then((res)=>{
res.send({response:res});})
.catch((error)=>{
res.send({response:error});})

What is JavaScript garbage collection?

garbage collection (GC) is a form of automatic memory management by removing the objects that no needed anymore.

any process deal with memory follow these steps:

1 - allocate your memory space you need

2 - do some processing

3 - free this memory space

there are two main algorithm used to detect which objects no needed anymore.

Reference-counting garbage collection: this algorithm reduces the definition of "an object is not needed anymore" to "an object has no other object referencing to it", the object will removed if no reference point to it

Mark-and-sweep algorithm: connect each objects to root source. any object doesn't connect to root or other object. this object will be removed.

currently most modern browsers using the second algorithm.

Laravel 5 Clear Views Cache

use Below command in terminal

php artisan cache:clear
php artisan route:cache 
php artisan config:cache 
php artisan view:clear

How to switch to new window in Selenium for Python?

for eg. you may take

driver.get('https://www.naukri.com/')

since, it is a current window ,we can name it

main_page = driver.current_window_handle

if there are atleast 1 window popup except the current window,you may try this method and put if condition in break statement by hit n trial for the index

for handle in driver.window_handles:
    if handle != main_page:
        print(handle)
        login_page = handle
        break

driver.switch_to.window(login_page)

Now ,whatever the credentials you have to apply,provide after it is loggen in. Window will disappear, but you have to come to main page window and you are done

driver.switch_to.window(main_page)
sleep(10)

includes() not working in all browsers

Here is solution ( ref : https://www.cluemediator.com/object-doesnt-support-property-or-method-includes-in-ie )

if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, 'includes', {
    value: function (searchElement, fromIndex) {

      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      // 1. Let O be ? ToObject(this value).
      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If len is 0, return false.
      if (len === 0) {
        return false;
      }

      // 4. Let n be ? ToInteger(fromIndex).
      //    (If fromIndex is undefined, this step produces the value 0.)
      var n = fromIndex | 0;

      // 5. If n = 0, then
      //  a. Let k be n.
      // 6. Else n < 0,
      //  a. Let k be len + n.
      //  b. If k < 0, let k be 0.
      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

      function sameValueZero(x, y) {
        return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
      }

      // 7. Repeat, while k < len
      while (k < len) {
        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
        // b. If SameValueZero(searchElement, elementK) is true, return true.
        if (sameValueZero(o[k], searchElement)) {
          return true;
        }
        // c. Increase k by 1. 
        k++;
      }

      // 8. Return false
      return false;
    }
  });
}

SQL join on multiple columns in same tables

Join like this:

ON a.userid = b.sourceid AND a.listid = b.destinationid;

How to extract custom header value in Web API message handler?

request.Headers.FirstOrDefault( x => x.Key == "MyCustomID" ).Value.FirstOrDefault()

modern variant :)

How do I get column names to print in this C# program?

You can access column name specifically like this too if you don't want to loop through all columns:

table.Columns[1].ColumnName

Prevent Caching in ASP.NET MVC for specific actions using an attribute

ASP.NET MVC 5 solutions:

  1. Caching prevention code at a central location: the App_Start/FilterConfig.cs's RegisterGlobalFilters method:
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            // ...
            filters.Add(new OutputCacheAttribute
            {
                NoStore = true,
                Duration = 0,
                VaryByParam = "*",
                Location = System.Web.UI.OutputCacheLocation.None
            });
        }
    }
  1. Once you have that in place my understanding is that you can override the global filter by applying a different OutputCache directive at Controller or View level. For regular Controller it's
[OutputCache(NoStore = true, Duration = 0, Location=System.Web.UI.ResponseCacheLocation.None, VaryByParam = "*")]

or if it's an ApiController it'd be

[System.Web.Mvc.OutputCache(NoStore = true, Duration = 0, Location = System.Web.UI.OutputCacheLocation.None, VaryByParam = "*")]

How to access parameters in a RESTful POST method

Your @POST method should be accepting a JSON object instead of a string. Jersey uses JAXB to support marshaling and unmarshaling JSON objects (see the jersey docs for details). Create a class like:

@XmlRootElement
public class MyJaxBean {
    @XmlElement public String param1;
    @XmlElement public String param2;
}

Then your @POST method would look like the following:

@POST @Consumes("application/json")
@Path("/create")
public void create(final MyJaxBean input) {
    System.out.println("param1 = " + input.param1);
    System.out.println("param2 = " + input.param2);
}

This method expects to receive JSON object as the body of the HTTP POST. JAX-RS passes the content body of the HTTP message as an unannotated parameter -- input in this case. The actual message would look something like:

POST /create HTTP/1.1
Content-Type: application/json
Content-Length: 35
Host: www.example.com

{"param1":"hello","param2":"world"}

Using JSON in this way is quite common for obvious reasons. However, if you are generating or consuming it in something other than JavaScript, then you do have to be careful to properly escape the data. In JAX-RS, you would use a MessageBodyReader and MessageBodyWriter to implement this. I believe that Jersey already has implementations for the required types (e.g., Java primitives and JAXB wrapped classes) as well as for JSON. JAX-RS supports a number of other methods for passing data. These don't require the creation of a new class since the data is passed using simple argument passing.


HTML <FORM>

The parameters would be annotated using @FormParam:

@POST
@Path("/create")
public void create(@FormParam("param1") String param1,
                   @FormParam("param2") String param2) {
    ...
}

The browser will encode the form using "application/x-www-form-urlencoded". The JAX-RS runtime will take care of decoding the body and passing it to the method. Here's what you should see on the wire:

POST /create HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 25

param1=hello&param2=world

The content is URL encoded in this case.

If you do not know the names of the FormParam's you can do the following:

@POST @Consumes("application/x-www-form-urlencoded")
@Path("/create")
public void create(final MultivaluedMap<String, String> formParams) {
    ...
}

HTTP Headers

You can using the @HeaderParam annotation if you want to pass parameters via HTTP headers:

@POST
@Path("/create")
public void create(@HeaderParam("param1") String param1,
                   @HeaderParam("param2") String param2) {
    ...
}

Here's what the HTTP message would look like. Note that this POST does not have a body.

POST /create HTTP/1.1
Content-Length: 0
Host: www.example.com
param1: hello
param2: world

I wouldn't use this method for generalized parameter passing. It is really handy if you need to access the value of a particular HTTP header though.


HTTP Query Parameters

This method is primarily used with HTTP GETs but it is equally applicable to POSTs. It uses the @QueryParam annotation.

@POST
@Path("/create")
public void create(@QueryParam("param1") String param1,
                   @QueryParam("param2") String param2) {
    ...
}

Like the previous technique, passing parameters via the query string does not require a message body. Here's the HTTP message:

POST /create?param1=hello&param2=world HTTP/1.1
Content-Length: 0
Host: www.example.com

You do have to be particularly careful to properly encode query parameters on the client side. Using query parameters can be problematic due to URL length restrictions enforced by some proxies as well as problems associated with encoding them.


HTTP Path Parameters

Path parameters are similar to query parameters except that they are embedded in the HTTP resource path. This method seems to be in favor today. There are impacts with respect to HTTP caching since the path is what really defines the HTTP resource. The code looks a little different than the others since the @Path annotation is modified and it uses @PathParam:

@POST
@Path("/create/{param1}/{param2}")
public void create(@PathParam("param1") String param1,
                   @PathParam("param2") String param2) {
    ...
}

The message is similar to the query parameter version except that the names of the parameters are not included anywhere in the message.

POST /create/hello/world HTTP/1.1
Content-Length: 0
Host: www.example.com

This method shares the same encoding woes that the query parameter version. Path segments are encoded differently so you do have to be careful there as well.


As you can see, there are pros and cons to each method. The choice is usually decided by your clients. If you are serving FORM-based HTML pages, then use @FormParam. If your clients are JavaScript+HTML5-based, then you will probably want to use JAXB-based serialization and JSON objects. The MessageBodyReader/Writer implementations should take care of the necessary escaping for you so that is one fewer thing that can go wrong. If your client is Java based but does not have a good XML processor (e.g., Android), then I would probably use FORM encoding since a content body is easier to generate and encode properly than URLs are. Hopefully this mini-wiki entry sheds some light on the various methods that JAX-RS supports.

Note: in the interest of full disclosure, I haven't actually used this feature of Jersey yet. We were tinkering with it since we have a number of JAXB+JAX-RS applications deployed and are moving into the mobile client space. JSON is a much better fit that XML on HTML5 or jQuery-based solutions.

Test for array of string type in TypeScript

I know this has been answered, but TypeScript introduced type guards: https://www.typescriptlang.org/docs/handbook/advanced-types.html#typeof-type-guards

If you have a type like: Object[] | string[] and what to do something conditionally based on what type it is - you can use this type guarding:

function isStringArray(value: any): value is string[] {
  if (value instanceof Array) {
    value.forEach(function(item) { // maybe only check first value?
      if (typeof item !== 'string') {
        return false
      }
    })
    return true
  }
  return false
}

function join<T>(value: string[] | T[]) {
  if (isStringArray(value)) {
    return value.join(',') // value is string[] here
  } else {
    return value.map((x) => x.toString()).join(',') // value is T[] here
  }
}

There is an issue with an empty array being typed as string[], but that might be okay

Excel date to Unix timestamp

To make up for the daylight saving time (starting on March's last sunday until October's last sunday) I had to use the following formula:

=IF(
  AND(
    A2>=EOMONTH(DATE(YEAR(A2);3;1);0)-MOD(WEEKDAY(EOMONTH(DATE(YEAR(A2);3;1);0);11);7);
    A2<=EOMONTH(DATE(YEAR(A2);10;1);0)-MOD(WEEKDAY(EOMONTH(DATE(YEAR(A2);10;1);0);11);7)
  );
  (A2-DATE(1970;1;1)-TIME(1;0;0))*24*60*60*1000;
  (A2-DATE(1970;1;1))*24*60*60*1000
)

Quick explanation:

If the date ["A2"] is between March's last sunday and October's last sunday [third and fourth code lines], then I'll be subtracting one hour [-TIME(1;0;0)] to the date.

Module AppRegistry is not registered callable module (calling runApplication)

I tried killall -9 node command in terminal

then again i run my project using npm start and it's working fine

How can I upload files asynchronously?

A solution I found was to have the <form> target a hidden iFrame. The iFrame can then run JS to display to the user that it's complete (on page load).

Jquery bind double click and single click separately

Sure, bind two handlers, one to click and the other to dblclick. Create a variable that increments on every click. then resets after a set delay. Inside the setTimeout function you can do something...

var DELAY = 2000,
    clicks = 0,
    timer = null;

$('a').bind({
    click: function(e) {
        clearTimeout(timer);

        timer = setTimeout(function() {
            clicks = 0;
        }, DELAY);

        if(clicks === 1) {
            alert(clicks);
             //do something here

            clicks = 0;
        }

        //Increment clicks
        clicks++;
    },
    dblclick: function(e) {
        e.preventDefault(); //don't do anything
    }
});

How to convert a 3D point into 2D perspective projection?

I see this question is a bit old, but I decided to give an answer anyway for those who find this question by searching.
The standard way to represent 2D/3D transformations nowadays is by using homogeneous coordinates. [x,y,w] for 2D, and [x,y,z,w] for 3D. Since you have three axes in 3D as well as translation, that information fits perfectly in a 4x4 transformation matrix. I will use column-major matrix notation in this explanation. All matrices are 4x4 unless noted otherwise.
The stages from 3D points and to a rasterized point, line or polygon looks like this:

  1. Transform your 3D points with the inverse camera matrix, followed with whatever transformations they need. If you have surface normals, transform them as well but with w set to zero, as you don't want to translate normals. The matrix you transform normals with must be isotropic; scaling and shearing makes the normals malformed.
  2. Transform the point with a clip space matrix. This matrix scales x and y with the field-of-view and aspect ratio, scales z by the near and far clipping planes, and plugs the 'old' z into w. After the transformation, you should divide x, y and z by w. This is called the perspective divide.
  3. Now your vertices are in clip space, and you want to perform clipping so you don't render any pixels outside the viewport bounds. Sutherland-Hodgeman clipping is the most widespread clipping algorithm in use.
  4. Transform x and y with respect to w and the half-width and half-height. Your x and y coordinates are now in viewport coordinates. w is discarded, but 1/w and z is usually saved because 1/w is required to do perspective-correct interpolation across the polygon surface, and z is stored in the z-buffer and used for depth testing.

This stage is the actual projection, because z isn't used as a component in the position any more.

The algorithms:

Calculation of field-of-view

This calculates the field-of view. Whether tan takes radians or degrees is irrelevant, but angle must match. Notice that the result reaches infinity as angle nears 180 degrees. This is a singularity, as it is impossible to have a focal point that wide. If you want numerical stability, keep angle less or equal to 179 degrees.

fov = 1.0 / tan(angle/2.0)

Also notice that 1.0 / tan(45) = 1. Someone else here suggested to just divide by z. The result here is clear. You would get a 90 degree FOV and an aspect ratio of 1:1. Using homogeneous coordinates like this has several other advantages as well; we can for example perform clipping against the near and far planes without treating it as a special case.

Calculation of the clip matrix

This is the layout of the clip matrix. aspectRatio is Width/Height. So the FOV for the x component is scaled based on FOV for y. Far and near are coefficients which are the distances for the near and far clipping planes.

[fov * aspectRatio][        0        ][        0              ][        0       ]
[        0        ][       fov       ][        0              ][        0       ]
[        0        ][        0        ][(far+near)/(far-near)  ][        1       ]
[        0        ][        0        ][(2*near*far)/(near-far)][        0       ]

Screen Projection

After clipping, this is the final transformation to get our screen coordinates.

new_x = (x * Width ) / (2.0 * w) + halfWidth;
new_y = (y * Height) / (2.0 * w) + halfHeight;

Trivial example implementation in C++

#include <vector>
#include <cmath>
#include <stdexcept>
#include <algorithm>

struct Vector
{
    Vector() : x(0),y(0),z(0),w(1){}
    Vector(float a, float b, float c) : x(a),y(b),z(c),w(1){}

    /* Assume proper operator overloads here, with vectors and scalars */
    float Length() const
    {
        return std::sqrt(x*x + y*y + z*z);
    }
    
    Vector Unit() const
    {
        const float epsilon = 1e-6;
        float mag = Length();
        if(mag < epsilon){
            std::out_of_range e("");
            throw e;
        }
        return *this / mag;
    }
};

inline float Dot(const Vector& v1, const Vector& v2)
{
    return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;
}

class Matrix
{
    public:
    Matrix() : data(16)
    {
        Identity();
    }
    void Identity()
    {
        std::fill(data.begin(), data.end(), float(0));
        data[0] = data[5] = data[10] = data[15] = 1.0f;
    }
    float& operator[](size_t index)
    {
        if(index >= 16){
            std::out_of_range e("");
            throw e;
        }
        return data[index];
    }
    Matrix operator*(const Matrix& m) const
    {
        Matrix dst;
        int col;
        for(int y=0; y<4; ++y){
            col = y*4;
            for(int x=0; x<4; ++x){
                for(int i=0; i<4; ++i){
                    dst[x+col] += m[i+col]*data[x+i*4];
                }
            }
        }
        return dst;
    }
    Matrix& operator*=(const Matrix& m)
    {
        *this = (*this) * m;
        return *this;
    }

    /* The interesting stuff */
    void SetupClipMatrix(float fov, float aspectRatio, float near, float far)
    {
        Identity();
        float f = 1.0f / std::tan(fov * 0.5f);
        data[0] = f*aspectRatio;
        data[5] = f;
        data[10] = (far+near) / (far-near);
        data[11] = 1.0f; /* this 'plugs' the old z into w */
        data[14] = (2.0f*near*far) / (near-far);
        data[15] = 0.0f;
    }

    std::vector<float> data;
};

inline Vector operator*(const Vector& v, const Matrix& m)
{
    Vector dst;
    dst.x = v.x*m[0] + v.y*m[4] + v.z*m[8 ] + v.w*m[12];
    dst.y = v.x*m[1] + v.y*m[5] + v.z*m[9 ] + v.w*m[13];
    dst.z = v.x*m[2] + v.y*m[6] + v.z*m[10] + v.w*m[14];
    dst.w = v.x*m[3] + v.y*m[7] + v.z*m[11] + v.w*m[15];
    return dst;
}

typedef std::vector<Vector> VecArr;
VecArr ProjectAndClip(int width, int height, float near, float far, const VecArr& vertex)
{
    float halfWidth = (float)width * 0.5f;
    float halfHeight = (float)height * 0.5f;
    float aspect = (float)width / (float)height;
    Vector v;
    Matrix clipMatrix;
    VecArr dst;
    clipMatrix.SetupClipMatrix(60.0f * (M_PI / 180.0f), aspect, near, far);
    /*  Here, after the perspective divide, you perform Sutherland-Hodgeman clipping 
        by checking if the x, y and z components are inside the range of [-w, w].
        One checks each vector component seperately against each plane. Per-vertex
        data like colours, normals and texture coordinates need to be linearly
        interpolated for clipped edges to reflect the change. If the edge (v0,v1)
        is tested against the positive x plane, and v1 is outside, the interpolant
        becomes: (v1.x - w) / (v1.x - v0.x)
        I skip this stage all together to be brief.
    */
    for(VecArr::iterator i=vertex.begin(); i!=vertex.end(); ++i){
        v = (*i) * clipMatrix;
        v /= v.w; /* Don't get confused here. I assume the divide leaves v.w alone.*/
        dst.push_back(v);
    }

    /* TODO: Clipping here */

    for(VecArr::iterator i=dst.begin(); i!=dst.end(); ++i){
        i->x = (i->x * (float)width) / (2.0f * i->w) + halfWidth;
        i->y = (i->y * (float)height) / (2.0f * i->w) + halfHeight;
    }
    return dst;
}

If you still ponder about this, the OpenGL specification is a really nice reference for the maths involved. The DevMaster forums at http://www.devmaster.net/ have a lot of nice articles related to software rasterizers as well.

Format Date time in AngularJS

Simplly if you want to output like "Jan 30, 2017 4:31:20 PM" then follow to simple step

step1- Declare following variable in js controller

$scope.current_time = new Date();

step2- display in html page like

{{current_time | date:'medium'}}

How to delete a file via PHP?

AIO solution, handles everything, It's not my work but I just improved myself. Enjoy!

/**
 * Unlink a file, which handles symlinks.
 * @see https://github.com/luyadev/luya/blob/master/core/helpers/FileHelper.php
 * @param string $filename The file path to the file to delete.
 * @return boolean Whether the file has been removed or not.
 */
function unlinkFile ( $filename ) {
    // try to force symlinks
    if ( is_link ($filename) ) {
        $sym = @readlink ($filename);
        if ( $sym ) {
            return is_writable ($filename) && @unlink ($filename);
        }
    }

    // try to use real path
    if ( realpath ($filename) && realpath ($filename) !== $filename ) {
        return is_writable ($filename) && @unlink (realpath ($filename));
    }

    // default unlink
    return is_writable ($filename) && @unlink ($filename);
}

How to close TCP and UDP ports via windows command line

If you're runnning on Windows 8,`Windows Server 2012 or above with PowerShell v4 of above installed, you can use the below script. This finds the processes associated with the port & terminates them.

Code

#which port do you want to kill
[int]$portOfInterest = 80

#fetch the process ids related to this port
[int[]]$processId = Get-NetTCPConnection -LocalPort $portOfInterest | 
    Select-Object -ExpandProperty OwningProcess -Unique | 
    Where-Object {$_ -gt 0} 

#kill those processes
Stop-Process -Id $processId 

Documentation:

Converting camel case to underscore case in ruby

Check out snakecase from Ruby Facets

The following cases are handled, as seen below:

"SnakeCase".snakecase         #=> "snake_case"
"Snake-Case".snakecase        #=> "snake_case"
"Snake Case".snakecase        #=> "snake_case"
"Snake  -  Case".snakecase    #=> "snake_case"

From: https://github.com/rubyworks/facets/blob/master/lib/core/facets/string/snakecase.rb

class String

  # Underscore a string such that camelcase, dashes and spaces are
  # replaced by underscores. This is the reverse of {#camelcase},
  # albeit not an exact inverse.
  #
  #   "SnakeCase".snakecase         #=> "snake_case"
  #   "Snake-Case".snakecase        #=> "snake_case"
  #   "Snake Case".snakecase        #=> "snake_case"
  #   "Snake  -  Case".snakecase    #=> "snake_case"
  #
  # Note, this method no longer converts `::` to `/`, in that case
  # use the {#pathize} method instead.

  def snakecase
    #gsub(/::/, '/').
    gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
    gsub(/([a-z\d])([A-Z])/,'\1_\2').
    tr('-', '_').
    gsub(/\s/, '_').
    gsub(/__+/, '_').
    downcase
  end

  #
  alias_method :underscore, :snakecase

  # TODO: Add *separators to #snakecase, like camelcase.

end

Alter a MySQL column to be AUTO_INCREMENT

Use the following queries:

ALTER TABLE YourTable DROP COLUMN IDCol

ALTER TABLE YourTable ADD IDCol INT IDENTITY(1,1)

Why do we have to specify FromBody and FromUri?

The default behavior is:

  1. If the parameter is a primitive type (int, bool, double, ...), Web API tries to get the value from the URI of the HTTP request.

  2. For complex types (your own object, for example: Person), Web API tries to read the value from the body of the HTTP request.

So, if you have:

  • a primitive type in the URI, or
  • a complex type in the body

...then you don't have to add any attributes (neither [FromBody] nor [FromUri]).

But, if you have a primitive type in the body, then you have to add [FromBody] in front of your primitive type parameter in your WebAPI controller method. (Because, by default, WebAPI is looking for primitive types in the URI of the HTTP request.)

Or, if you have a complex type in your URI, then you must add [FromUri]. (Because, by default, WebAPI is looking for complex types in the body of the HTTP request by default.)

Primitive types:

public class UsersController : ApiController
{
    // api/users
    public HttpResponseMessage Post([FromBody]int id)
    {

    }
    // api/users/id
    public HttpResponseMessage Post(int id)
    {

    }       
}

Complex types:

public class UsersController : ApiController
{       
    // api/users
    public HttpResponseMessage Post(User user)
    {

    }

    // api/users/user
    public HttpResponseMessage Post([FromUri]User user)
    {

    }       
}

This works as long as you send only one parameter in your HTTP request. When sending multiple, you need to create a custom model which has all your parameters like this:

public class MyModel
{
    public string MyProperty { get; set; }
    public string MyProperty2 { get; set; }
}

[Route("search")]
[HttpPost]
public async Task<dynamic> Search([FromBody] MyModel model)
{
    // model.MyProperty;
    // model.MyProperty2;
}

From Microsoft's documentation for parameter binding in ASP.NET Web API:

When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object). At most one parameter is allowed to read from the message body.

This should work:

public HttpResponseMessage Post([FromBody] string name) { ... }

This will not work:

// Caution: This won't work!    
public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }

The reason for this rule is that the request body might be stored in a non-buffered stream that can only be read once.

How can I run dos2unix on an entire directory?

find . -type f -print0 | xargs -0 dos2unix

Will recursively find all files inside current directory and call for these files dos2unix command

WPF C# button style

   <Button x:Name="mybtnSave" FlowDirection="LeftToRight"  HorizontalAlignment="Left" Margin="813,614,0,0" VerticalAlignment="Top"  Width="223" Height="53" BorderBrush="#FF2B3830" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontFamily="B Titr" FontSize="15" FontWeight="Bold" BorderThickness="2" TabIndex="107" Click="mybtnSave_Click" >
        <Button.Background>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="Black" Offset="0"/>
                <GradientStop Color="#FF080505" Offset="1"/>
                <GradientStop Color="White" Offset="0.536"/>
            </LinearGradientBrush>
        </Button.Background>
        <Button.Effect>
            <DropShadowEffect/>
        </Button.Effect>
        <StackPanel HorizontalAlignment="Stretch" Cursor="Hand" >
            <StackPanel.Background>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="#FF3ED82E" Offset="0"/>
                    <GradientStop Color="#FF3BF728" Offset="1"/>
                    <GradientStop Color="#FF212720" Offset="0.52"/>
                </LinearGradientBrush>
            </StackPanel.Background>
            <Image HorizontalAlignment="Left"  Source="image/Append Or Save 3.png" Height="36" Width="203" />
            <TextBlock HorizontalAlignment="Center" Width="145" Height="22" VerticalAlignment="Top" Margin="0,-31,-35,0" Text="Save Com F12" FontFamily="Tahoma" FontSize="14" Padding="0,4,0,0" Foreground="White" />
        </StackPanel>
    </Button>ente[![enter image description here][1]][1]r image description here

Is there a numpy builtin to reject outliers from a list

Consider that all the above methods fail when your standard deviation gets very large due to huge outliers.

(Simalar as the average caluclation fails and should rather caluclate the median. Though, the average is "more prone to such an error as the stdDv".)

You could try to iteratively apply your algorithm or you filter using the interquartile range: (here "factor" relates to a n*sigma range, yet only when your data follows a Gaussian distribution)

import numpy as np

def sortoutOutliers(dataIn,factor):
    quant3, quant1 = np.percentile(dataIn, [75 ,25])
    iqr = quant3 - quant1
    iqrSigma = iqr/1.34896
    medData = np.median(dataIn)
    dataOut = [ x for x in dataIn if ( (x > medData - factor* iqrSigma) and (x < medData + factor* iqrSigma) ) ] 
    return(dataOut)

How to add class active on specific li on user click with jQuery

Slightly off topic but having arrived here while developing an Angular2 app I would like to share that Angular2 automatically adds the class "router-link-active" to active router links such as this one:

<li><a [routerLink]="['Dashboard']">Dashboard</a></li>

You can therefore easily style such links using CSS:

.router-link-active {
    color: red;
}

New line in Sql Query

You could do Char(13) and Char(10). Cr and Lf.

Char() works in SQL Server, I don't know about other databases.

Get text from pressed button

In Kotlin:

myButton.setOnClickListener { doSomething((it as Button).text) }

Note: This gets the button text as a CharSequence, which more places in code can likely use. If you really want a String from there, then you can use .toString().

Disable nginx cache for JavaScript files

The expires and add_header directives have no impact on NGINX caching the files, those are purely about what the browser sees.

What you likely want instead is:

location stuffyoudontwanttocache {
    # don't cache it
    proxy_no_cache 1;
    # even if cached, don't try to use it
    proxy_cache_bypass 1; 
}

Though usually .js etc is the thing you would cache, so perhaps you should just disable caching entirely?

How to open a new form from another form

Try this..

//button1 will be clicked to open a new form
private void button1_Click(object sender, EventArgs e)
{
    this.Visible = false;     // this = is the current form
    SignUp s = new SignUp();  //SignUp is the name of  my other form
    s.Visible = true;
}

Use of the MANIFEST.MF file in Java

Manifest.MF contains information about the files contained in the JAR file.

Whenever a JAR file is created a default manifest.mf file is created inside META-INF folder and it contains the default entries like this:

Manifest-Version: 1.0
Created-By: 1.7.0_06 (Oracle Corporation)

These are entries as “header:value” pairs. The first one specifies the manifest version and second one specifies the JDK version with which the JAR file is created.

Main-Class header: When a JAR file is used to bundle an application in a package, we need to specify the class serving an entry point of the application. We provide this information using ‘Main-Class’ header of the manifest file,

Main-Class: {fully qualified classname}

The ‘Main-Class’ value here is the class having main method. After specifying this entry we can execute the JAR file to run the application.

Class-Path header: Most of the times we need to access the other JAR files from the classes packaged inside application’s JAR file. This can be done by providing their fully qualified paths in the manifest file using ‘Class-Path’ header,

Class-Path: {jar1-name jar2-name directory-name/jar3-name}

This header can be used to specify the external JAR files on the same local network and not inside the current JAR.

Package version related headers: When the JAR file is used for package versioning the following headers are used as specified by the Java language specification:

Headers in a manifest
Header                  | Definition
-------------------------------------------------------------------
Name                    | The name of the specification.
Specification-Title     | The title of the specification.
Specification-Version   | The version of the specification.
Specification-Vendor    | The vendor of the specification.
Implementation-Title    | The title of the implementation.
Implementation-Version  | The build number of the implementation.
Implementation-Vendor   | The vendor of the implementation.

Package sealing related headers:

We can also specify if any particular packages inside a JAR file should be sealed meaning all the classes defined in that package must be archived in the same JAR file. This can be specified with the help of ‘Sealed’ header,

Name: {package/some-package/} Sealed:true

Here, the package name must end with ‘/’.

Enhancing security with manifest files:

We can use manifest files entries to ensure the security of the web application or applet it packages with the different attributes as ‘Permissions’, ‘Codebae’, ‘Application-Name’, ‘Trusted-Only’ and many more.

META-INF folder:

This folder is where the manifest file resides. Also, it can contain more files containing meta data about the application. For example, in an EJB module JAR file, this folder contains the EJB deployment descriptor for the EJB module along with the manifest file for the JAR. Also, it contains the xml file containing mapping of an abstract EJB references to concrete container resources of the application server on which it will be run.

Reference:
https://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html

how to get current datetime in SQL?

  1. GETDATE() or GETUTCDATE() are now superseded by the richer SYSDATETIME, SYSUTCDATETIME, and SYSDATETIMEOFFSET (in SQL 2008)
  2. Yes, I don't think ANSI has ever declared anything, and so each manufacturer has their own.
  3. That would be NOW()

Hope this helps...

Rob

How to read a file from jar in Java?

Check first your class loader.

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

if (classLoader == null) {
    classLoader = Class.class.getClassLoader();
}

classLoader.getResourceAsStream("xmlFileNameInJarFile.xml");

// xml file location at xxx.jar
// + folder
// + folder
// xmlFileNameInJarFile.xml

Convert bytes to a string

You need to decode the byte string and turn it in to a character (Unicode) string.

On Python 2

encoding = 'utf-8'
'hello'.decode(encoding)

or

unicode('hello', encoding)

On Python 3

encoding = 'utf-8'
b'hello'.decode(encoding)

or

str(b'hello', encoding)

Populate one dropdown based on selection in another

_x000D_
_x000D_
function configureDropDownLists(ddl1, ddl2) {_x000D_
  var colours = ['Black', 'White', 'Blue'];_x000D_
  var shapes = ['Square', 'Circle', 'Triangle'];_x000D_
  var names = ['John', 'David', 'Sarah'];_x000D_
_x000D_
  switch (ddl1.value) {_x000D_
    case 'Colours':_x000D_
      ddl2.options.length = 0;_x000D_
      for (i = 0; i < colours.length; i++) {_x000D_
        createOption(ddl2, colours[i], colours[i]);_x000D_
      }_x000D_
      break;_x000D_
    case 'Shapes':_x000D_
      ddl2.options.length = 0;_x000D_
      for (i = 0; i < shapes.length; i++) {_x000D_
        createOption(ddl2, shapes[i], shapes[i]);_x000D_
      }_x000D_
      break;_x000D_
    case 'Names':_x000D_
      ddl2.options.length = 0;_x000D_
      for (i = 0; i < names.length; i++) {_x000D_
        createOption(ddl2, names[i], names[i]);_x000D_
      }_x000D_
      break;_x000D_
    default:_x000D_
      ddl2.options.length = 0;_x000D_
      break;_x000D_
  }_x000D_
_x000D_
}_x000D_
_x000D_
function createOption(ddl, text, value) {_x000D_
  var opt = document.createElement('option');_x000D_
  opt.value = value;_x000D_
  opt.text = text;_x000D_
  ddl.options.add(opt);_x000D_
}
_x000D_
<select id="ddl" onchange="configureDropDownLists(this,document.getElementById('ddl2'))">_x000D_
  <option value=""></option>_x000D_
  <option value="Colours">Colours</option>_x000D_
  <option value="Shapes">Shapes</option>_x000D_
  <option value="Names">Names</option>_x000D_
</select>_x000D_
_x000D_
<select id="ddl2">_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to import set of icons into Android Studio project


Edit : After Android Studios 1.5 android support Vector Asset Studio.


Follow this, which says:

To start Vector Asset Studio:

  1. In Android Studio, open an Android app project.
  2. In the Project window, select the Android view.
  3. Right-click the res folder and select New > Vector Asset.

enter image description here


Old Answer

Go to Settings > Plugin > Browse Repository > Search Android Drawable Import

This plugin consists of 4 main features.

  1. AndroidIcons Drawable Import
  2. Material Icons Drawable Import
  3. Scaled Drawable
  4. Multisource-Drawable

How to Use Material Icons Drawable Import : (Android Studio 1.2)

  • Go to File > Setting > Other Settings > Android Drawable Import

enter image description here

  • Download Material Icon and select your downloaded path.

enter image description here

  • Now right click on project , New > Material Icon Import

enter image description here

  • Use your favorite drawable in your project.

enter image description here

Rotating a point about another point (2D)

I struggled while working MS OCR Read API which returns back angle of rotation in range (-180, 180]. So I have to do an extra step of converting negative angles to positive. I hope someone struggling with point rotation with negative or positive angles can use the following.

def rotate(origin, point, angle):
    """
    Rotate a point counter-clockwise by a given angle around a given origin.
    """
    # Convert negative angles to positive
    angle = normalise_angle(angle)

    # Convert to radians
    angle = math.radians(angle)

    # Convert to radians
    ox, oy = origin
    px, py = point
    
    # Move point 'p' to origin (0,0)
    _px = px - ox
    _py = py - oy
    
    # Rotate the point 'p' 
    qx = (math.cos(angle) * _px) - (math.sin(angle) * _py)
    qy = (math.sin(angle) * _px) + (math.cos(angle) * _py)
    
    # Move point 'p' back to origin (ox, oy)
    qx = ox + qx
    qy = oy + qy
    
    return [qx, qy]


def normalise_angle(angle):
    """ If angle is negative then convert it to positive. """
    if (angle != 0) & (abs(angle) == (angle * -1)):
        angle = 360 + angle
    return angle

Why Does OAuth v2 Have Both Access and Refresh Tokens?

Despite all the great answers above, I as a security master student and programmer who previously worked at eBay when I took a look into buyer protection and fraud, can say to separate access token and refresh token has its best balance between harassing user of frequent username/password input and keeping the authority in hand to revoke access to potential abuse of your service.

Think of a scenario like this. You issue user of an access token of 3600 seconds and refresh token much longer as one day.

  1. The user is a good user, he is at home and gets on/off your website shopping and searching on his iPhone. His IP address doesn't change and have a very low load on your server. Like 3-5 page requests every minute. When his 3600 seconds on the access token is over, he requires a new one with the refresh token. We, on the server side, check his activity history and IP address, think he is a human and behaves himself. We grant him a new access token to continue using our service. The user won't need to enter again the username/password until he has reached one day life-span of refresh token itself.

  2. The user is a careless user. He lives in New York, USA and got his virus program shutdown and was hacked by a hacker in Poland. When the hacker got the access token and refresh token, he tries to impersonate the user and use our service. But after the short-live access token expires, when the hacker tries to refresh the access token, we, on the server, has noticed a dramatic IP change in user behavior history (hey, this guy logins in USA and now refresh access in Poland after just 3600s ???). We terminate the refresh process, invalidate the refresh token itself and prompt to enter username/password again.

  3. The user is a malicious user. He is intended to abuse our service by calling 1000 times our API each minute using a robot. He can well doing so until 3600 seconds later, when he tries to refresh the access token, we noticed his behavior and think he might not be a human. We reject and terminate the refresh process and ask him to enter username/password again. This might potentially break his robot's automatic flow. At least makes him uncomfortable.

You can see the refresh token has acted perfectly when we try to balance our work, user experience and potential risk of a stolen token. Your watch dog on the server side can check more than IP change, frequency of api calls to determine whether the user shall be a good user or not.

Another word is you can also try to limit the damage control of stolen token/abuse of service by implementing on each api call the basic IP watch dog or any other measures. But this is expensive as you have to read and write record about the user and will slow down your server response.

How do I convert a String to a BigInteger?

According to the documentation:

BigInteger(String val)

Translates the decimal String representation of a BigInteger into a BigInteger.

It means that you can use a String to initialize a BigInteger object, as shown in the following snippet:

sum = sum.add(new BigInteger(newNumber));

How to remove package using Angular CLI?

npm uninstal @angular/material

and also clear file custom-theme.scss

Angular 2: Passing Data to Routes?

You can do this:

app-routing-modules.ts:

import { NgModule                  }    from '@angular/core';
import { RouterModule, Routes      }    from '@angular/router';
import { PowerBoosterComponent     }    from './component/power-booster.component';


export const routes: Routes = [
  { path:  'pipeexamples',component: PowerBoosterComponent, 
data:{  name:'shubham' } },
    ];
    @NgModule({
      imports: [ RouterModule.forRoot(routes) ],
      exports: [ RouterModule ]
    })
    export class AppRoutingModule {}

In this above route, I want to send data via a pipeexamples path to PowerBoosterComponent.So now I can receive this data in PowerBoosterComponent like this:

power-booster-component.ts

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params, Data } from '@angular/router';

@Component({
  selector: 'power-booster',
  template: `
    <h2>Power Booster</h2>`
})

export class PowerBoosterComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private router: Router

  ) { }
  ngOnInit() {
    //this.route.snapshot.data['name']
    console.log("Data via params: ",this.route.snapshot.data['name']);
  }
}

So you can get the data by this.route.snapshot.data['name'].

Scraping data from website using vba

I modified some thing that were poping up error for me and end up with this which worked great to extract the data as I needed:

Sub get_data_web()

Dim appIE As Object
Set appIE = CreateObject("internetexplorer.application")

With appIE
    .navigate "https://finance.yahoo.com/quote/NQ%3DF/futures?p=NQ%3DF"
    .Visible = True
End With

Do While appIE.Busy
    DoEvents
Loop

Set allRowofData = appIE.document.getElementsByClassName("Ta(end) BdT Bdc($c-fuji-grey-c) H(36px)")

Dim i As Long
Dim myValue As String

Count = 1

    For Each itm In allRowofData

        For i = 0 To 4

        myValue = itm.Cells(i).innerText
        ActiveSheet.Cells(Count, i + 1).Value = myValue

        Next

        Count = Count + 1

    Next

appIE.Quit
Set appIE = Nothing


End Sub

Date validation with ASP.NET validator

I think the following is the easiest way to do it.

<asp:TextBox ID="DateControl" runat="server" Visible="False"></asp:TextBox>
<asp:RangeValidator ID ="rvDate" runat ="server" ControlToValidate="DateControl" ErrorMessage="Invalid Date" Type="Date" MinimumValue="01/01/1900" MaximumValue="01/01/2100" Display="Dynamic"></asp:RangeValidator>

Hide Show content-list with only CSS, no javascript used

Just wanted to illustrate, in the context of nested lists, the usefulness of the hidden checkbox <input> approach @jeffmcneill recommends — a context where each shown/hidden element should hold its state independently of focus and the show/hide state of other elements on the page.

Giving values with a common set of beginning characters to the id attributes of all the checkboxes used for the shown/hidden elements on the page lets you use an economical [id^=""] selector scheme for the stylesheet rules that toggle your clickable element’s appearance and the related shown/hidden element’s display state back and forth. Here, my ids are ‘expanded-1,’ ‘expanded-2,’ ‘expanded-3.’

Note that I’ve also used @Diepen’s :after selector idea in order to keep the <label> element free of content in the html.

Note also that the <input> <label> <div class="collapsible"> sequence matters, and the corresponding CSS with + selector instead of ~.

jsfiddle here

_x000D_
_x000D_
.collapse-below {_x000D_
    display: inline;_x000D_
}_x000D_
_x000D_
p.collapse-below::after {_x000D_
    content: '\000A0\000A0';_x000D_
}_x000D_
_x000D_
p.collapse-below ~ label {_x000D_
    display: inline;_x000D_
}_x000D_
_x000D_
p.collapse-below ~ label:hover {_x000D_
    color: #ccc;_x000D_
}_x000D_
_x000D_
input.collapse-below,_x000D_
ul.collapsible {_x000D_
    display: none;_x000D_
}_x000D_
_x000D_
input[id^="expanded"]:checked + label::after {_x000D_
    content: '\025BE';_x000D_
}_x000D_
_x000D_
input[id^="expanded"]:not(:checked) + label::after {_x000D_
    content: '\025B8';_x000D_
}_x000D_
_x000D_
input[id^="expanded"]:checked + label + ul.collapsible {_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
input[id^="expanded"]:not(:checked) + label + ul.collapsible {_x000D_
    display: none;_x000D_
}
_x000D_
<ul>_x000D_
  <li>single item a</li>_x000D_
  <li>single item b</li>_x000D_
  <li>_x000D_
    <p class="collapse-below" title="this expands">multiple item a</p>_x000D_
    <input type="checkbox" id="expanded-1" class="collapse-below" name="toggle">_x000D_
    <label for="expanded-1" title="click to expand"></label>_x000D_
    <ul class="collapsible">_x000D_
      <li>sub item a.1</li>_x000D_
      <li>sub item a.2</li>_x000D_
    </ul>_x000D_
  </li>_x000D_
  <li>single item c</li>_x000D_
  <li>_x000D_
    <p class="collapse-below" title="this expands">multiple item b</p>_x000D_
    <input type="checkbox" id="expanded-2" class="collapse-below" name="toggle">_x000D_
    <label for="expanded-2" title="click to expand"></label>_x000D_
    <ul class="collapsible">_x000D_
      <li>sub item b.1</li>_x000D_
      <li>sub item b.2</li>_x000D_
    </ul>_x000D_
  </li>_x000D_
  <li>single item d</li>_x000D_
  <li>single item e</li>_x000D_
  <li>_x000D_
    <p class="collapse-below" title="this expands">multiple item c</p>_x000D_
    <input type="checkbox" id="expanded-3" class="collapse-below" name="toggle">_x000D_
    <label for="expanded-3" title="click to expand"></label>_x000D_
    <ul class="collapsible">_x000D_
      <li>sub item c.1</li>_x000D_
      <li>sub item c.2</li>_x000D_
    </ul>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Error HRESULT E_FAIL has been returned from a call to a COM component VS2012 when debugging

I've gone through all the different steps on how to fix this issue with VS2019 16.2.4 and the issue still remains. I certainly hope that MS fixes this issue since this has been going on for a long time.

Just above adding to Object Browser, I couldn't work out how to Add Reference dialog in this version, since I couldn't find the GAC for 2019.

Capturing count from an SQL query

int count = 0;    
using (new SqlConnection connection = new SqlConnection("connectionString"))
{
    sqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM table_name", connection);
    connection.Open();
    count = (int32)cmd.ExecuteScalar();
}

How to install plugins to Sublime Text 2 editor?

Installation code chunks for vanilla Sublime may change in the future.

This link would be the safest place to install plugin support to Sublime Text 2.

For Sublime Text 3 this link works has the code.

enter image description here

How can I access localhost from another computer in the same network?

You need to find what your local network's IP of that computer is. Then other people can access to your site by that IP.

You can find your local network's IP by go to Command Prompt or press Windows + R then type in ipconfig. It will give out some information and your local IP should look like 192.168.1.x.

How to print a debug log?

If you are on Linux:

file_put_contents('your_log_file', 'your_content');

or

error_log ('your_content', 3, 'your_log_file');

and then in console

tail -f your_log_file

This will show continuously the last line put in the file.

How to sort a dataframe by multiple column(s)

Dirk's answer is great. It also highlights a key difference in the syntax used for indexing data.frames and data.tables:

## The data.frame way
dd[with(dd, order(-z, b)), ]

## The data.table way: (7 fewer characters, but that's not the important bit)
dd[order(-z, b)]

The difference between the two calls is small, but it can have important consequences. Especially if you write production code and/or are concerned with correctness in your research, it's best to avoid unnecessary repetition of variable names. data.table helps you do this.

Here's an example of how repetition of variable names might get you into trouble:

Let's change the context from Dirk's answer, and say this is part of a bigger project where there are a lot of object names and they are long and meaningful; instead of dd it's called quarterlyreport. It becomes :

quarterlyreport[with(quarterlyreport,order(-z,b)),]

Ok, fine. Nothing wrong with that. Next your boss asks you to include last quarter's report in the report. You go through your code, adding an object lastquarterlyreport in various places and somehow (how on earth?) you end up with this :

quarterlyreport[with(lastquarterlyreport,order(-z,b)),]

That isn't what you meant but you didn't spot it because you did it fast and it's nestled on a page of similar code. The code doesn't fall over (no warning and no error) because R thinks it is what you meant. You'd hope whoever reads your report spots it, but maybe they don't. If you work with programming languages a lot then this situation may be all to familiar. It was a "typo" you'll say. I'll fix the "typo" you'll say to your boss.

In data.table we're concerned about tiny details like this. So we've done something simple to avoid typing variable names twice. Something very simple. i is evaluated within the frame of dd already, automatically. You don't need with() at all.

Instead of

dd[with(dd, order(-z, b)), ]

it's just

dd[order(-z, b)]

And instead of

quarterlyreport[with(lastquarterlyreport,order(-z,b)),]

it's just

quarterlyreport[order(-z,b)]

It's a very small difference, but it might just save your neck one day. When weighing up the different answers to this question, consider counting the repetitions of variable names as one of your criteria in deciding. Some answers have quite a few repeats, others have none.

How do I schedule a task to run at periodic intervals?

public void schedule(TimerTask task,long delay)

Schedules the specified task for execution after the specified delay.

you want:

public void schedule(TimerTask task, long delay, long period)

Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals separated by the specified period.