Programs & Examples On #Dynamic data exchange

Change EditText hint color when using TextInputLayout

android:textColorHint="#FFFFFF" sometime works and sometime doesnt. For me below solution works perfectly

Try The Below Code It Works In your XML file and TextLabel theme is defined in style.xml

 <android.support.design.widget.TextInputLayout
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:theme="@style/MyTextLabel">

     <EditText
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:hint="Floating Label"
         android:id="@+id/edtText"/>

 </android.support.design.widget.TextInputLayout>

In Styles Folder TextLabel Code

 <style name="MyTextLabel" parent="TextAppearance.AppCompat">
    <!-- Hint color and label color in FALSE state -->
    <item name="android:textColorHint">@color/Color Name</item> 
<!--The size of the text appear on label in false state -->
    <item name="android:textSize">20sp</item>
    <!-- Label color in TRUE state and bar color FALSE and TRUE State -->
    <item name="colorAccent">@color/Color Name</item>
    <item name="colorControlNormal">@color/Color Name</item>
    <item name="colorControlActivated">@color/Color Name</item>
 </style>

If you just want to change the color of label in false state then colorAccent , colorControlNormal and colorControlActivated are not required

Unable to load DLL (Module could not be found HRESULT: 0x8007007E)

Setup: 32-bit Windows 7

Context: Installed a PCI-GPIB driver that I was unable to communicate through due to the aforementioned issue.

Short Answer: Reinstall the driver.

Long Answer: I also used Dependency Walker, which identified several missing dependency modules. Immediately, I thought that it must have been a botched driver installation. I didn't want to check and restore each missing file.

The fact that I was unable to find the uninstaller under Programs and Features of the Control Panel is another indicator of bad installation. I had to manually delete a couple of *.dll in \system32 and registry keys to allow for driver re-installation.

Issue fixed.

The unexpected part was that not all dependency modules were resolved. Nevertheless, the *.dll of interest can now be referenced.

Using Mockito to stub and execute methods for testing

You are confusing a Mock with a Spy.

In a mock all methods are stubbed and return "smart return types". This means that calling any method on a mocked class will do nothing unless you specify behaviour.

In a spy the original functionality of the class is still there but you can validate method invocations in a spy and also override method behaviour.

What you want is

MyProcessingAgent mockMyAgent = Mockito.spy(MyProcessingAgent.class);

A quick example:

static class TestClass {

    public String getThing() {
        return "Thing";
    }

    public String getOtherThing() {
        return getThing();
    }
}

public static void main(String[] args) {
    final TestClass testClass = Mockito.spy(new TestClass());
    Mockito.when(testClass.getThing()).thenReturn("Some Other thing");
    System.out.println(testClass.getOtherThing());
}

Output is:

Some Other thing

NB: You should really try to mock the dependencies for the class being tested not the class itself.

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

The only way I could get this to work is to pass the JSON as a string and then deserialise it using JavaScriptSerializer.Deserialize<T>(string input), which is pretty strange if that's the default deserializer for MVC 4.

My model has nested lists of objects and the best I could get using JSON data is the uppermost list to have the correct number of items in it, but all the fields in the items were null.

This kind of thing should not be so hard.

    $.ajax({
        type: 'POST',
        url: '/Agri/Map/SaveSelfValuation',
        data: { json: JSON.stringify(model) },
        dataType: 'text',
        success: function (data) {

    [HttpPost]
    public JsonResult DoSomething(string json)
    {
        var model = new JavaScriptSerializer().Deserialize<Valuation>(json);

How to find files recursively by file type and copy them to a directory while in ssh?

Try this:

find . -name "*.pdf" -type f -exec cp {} ./pdfsfolder \;

docker unauthorized: authentication required - upon push with successful login

if you are using heroku, be sure you did not forget to "heroku container:login" before pushing.

Displaying standard DataTables in MVC

Here is the answer in Razor syntax

 <table border="1" cellpadding="5">
    <thead>
       <tr>
          @foreach (System.Data.DataColumn col in Model.Columns)
          {
             <th>@col.Caption</th>
          }
       </tr>
    </thead>
    <tbody>
    @foreach(System.Data.DataRow row in Model.Rows)
    {
       <tr>
          @foreach (var cell in row.ItemArray)
          {
             <td>@cell.ToString()</td>
          }
       </tr>
    }      
    </tbody>
</table>

Parse query string in JavaScript

You can also use the excellent URI.js library by Rodney Rehm. Here's how:-

var qs = URI('www.mysite.com/default.aspx?dest=aboutus.aspx').query(true); // == { dest : 'aboutus.aspx' }
    alert(qs.dest); // == aboutus.aspx

And to parse the query string of current page:-

var $_GET = URI(document.URL).query(true); // ala PHP
    alert($_GET['dest']); // == aboutus.aspx 

Get an object's class name at runtime

If you already know what types to expect (for example, when a method returns a union type), then you can use type guards.

For example, for primitive types you can use a typeof guard:

if (typeof thing === "number") {
  // Do stuff
}

For complex types you can use an instanceof guard:

if (thing instanceof Array) {
  // Do stuff
}

Number format in excel: Showing % value without multiplying with 100

In Excel workbook - Select the Cell-goto Format Cells - Number - Custom - in the Type box type as shows (0.00%)

Online PHP syntax checker / validator

To expand on my comment.

You can validate on the command line using php -l [filename], which does a syntax check only (lint). This will depend on your php.ini error settings, so you can edit you php.ini or set the error_reporting in the script.

Here's an example of the output when run on a file containing:

<?php
echo no quotes or semicolon

Results in:

PHP Parse error:  syntax error, unexpected T_STRING, expecting ',' or ';' in badfile.php on line 2

Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in badfile.php on line 2

Errors parsing badfile.php

I suggested you build your own validator.

A simple page that allows you to upload a php file. It takes the uploaded file runs it through php -l and echos the output.

Note: this is not a security risk it does not execute the file, just checks for syntax errors.

Here's a really basic example of creating your own:

<?php
if (isset($_FILES['file'])) {
    echo '<pre>';
    passthru('php -l '.$_FILES['file']['tmp_name']);
    echo '</pre>';
}
?>
<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file"/>
    <input type="submit"/>
</form>

Difference between null and empty ("") Java String

String s = "";
s.length();

String s = null;
s.length();

A reference to an empty string "" points to an object in the heap - so you can call methods on it.

But a reference pointing to null has no object to point in the heap and thus you'll get a NullPointerException.

How can I convert a comma-separated string to an array?

For an array of strings to a comma-separated string:

let months = ["January","Feb"];
let monthsString = months.join(", ");

What's a simple way to get a text input popup dialog box on an iPhone

UIAlertview *alt = [[UIAlertView alloc]initWithTitle:@"\n\n\n" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];

UILabel *lbl1 = [[UILabel alloc]initWithFrame:CGRectMake(25,17, 100, 30)];
lbl1.text=@"User Name";

UILabel *lbl2 = [[UILabel alloc]initWithFrame:CGRectMake(25, 60, 80, 30)];
lbl2.text = @"Password";

UITextField *username=[[UITextField alloc]initWithFrame:CGRectMake(130, 17, 130, 30)];
UITextField *password=[[UITextField alloc]initWithFrame:CGRectMake(130, 60, 130, 30)];

lbl1.textColor = [UIColor whiteColor];
lbl2.textColor = [UIColor whiteColor];

[lbl1 setBackgroundColor:[UIColor clearColor]];
[lbl2 setBackgroundColor:[UIColor clearColor]];

username.borderStyle = UITextBorderStyleRoundedRect;
password.borderStyle = UITextBorderStyleRoundedRect;

[alt addSubview:lbl1];
[alt addSubview:lbl2];
[alt addSubview:username];
[alt addSubview:password];

[alt show];

How to get values from IGrouping

Assume that you have MyPayments class like

 public class Mypayment
{
    public int year { get; set; }
    public string month { get; set; }
    public string price { get; set; }
    public bool ispaid { get; set; }
}

and you have a list of MyPayments

public List<Mypayment> mypayments { get; set; }

and you want group the list by year. You can use linq like this:

List<List<Mypayment>> mypayments = (from IGrouping<int, Mypayment> item in yearGroup
                                                let mypayments1 = (from _payment in UserProjects.mypayments
                                                                   where _payment.year == item.Key
                                                                   select _payment).ToList()
                                                select mypayments1).ToList();

Can I set background image and opacity in the same property?

Two methods:

  1. Convert to PNG and make the original image 0.2 opacity
  2. (Better method) have a <div> that is position: absolute; before #main and the same height as #main, then apply the background-image and opacity: 0.2; filter: alpha(opacity=20);.

KnockoutJs v2.3.0 : Error You cannot apply bindings multiple times to the same element

There are a lot of great answers for this issue but I have a noobie answer.

I found that I accidentally added the same Script in two places and it was trying to bind twice. So before you pull your hair out on a simple mistake, make sure you check for this issue.

How to compare types

You can compare for exactly the same type using:

class A {
}
var a = new A();
var typeOfa = a.GetType();
if (typeOfa == typeof(A)) {
}

typeof returns the Type object from a given class.

But if you have a type B, that inherits from A, then this comparison is false. And you are looking for IsAssignableFrom.

class B : A {
}
var b = new B();
var typeOfb = b.GetType();

if (typeOfb == typeof(A)) { // false
}

if (typeof(A).IsAssignableFrom(typeOfb)) { // true
}

How to delete files older than X hours

-mmin is for minutes.

Try looking at the man page.

man find

for more types.

SOAP or REST for Web Services?

An old question but still relevant today....due to so many developers in the enterprise space still using it.

My work involves designing and developing IoT (Internet of Things) solutions. Which includes developing code for small embedded devices that communicate with the Cloud.

It is clear REST is now widely accepted and useful, and pretty much the defacto standard for the web, even Microsoft has REST support included throughout Azure. If I needed to rely on SOAP I could not do what I need to do, as is just too big, bulky and annoying for small embedded devices.

REST is simple and clean and small. Making it ideal for small embedded devices. I always scream when I am working with a web developer who sends me a WSDLs. As I will have to begin an education campaign about why this just isn't going to work and why they are going to have to learn REST.

Java 8 Iterable.forEach() vs foreach loop

The advantage of Java 1.8 forEach method over 1.7 Enhanced for loop is that while writing code you can focus on business logic only.

forEach method takes java.util.function.Consumer object as an argument, so It helps in having our business logic at a separate location that you can reuse it anytime.

Have look at below snippet,

  • Here I have created new Class that will override accept class method from Consumer Class, where you can add additional functionility, More than Iteration..!!!!!!

    class MyConsumer implements Consumer<Integer>{
    
        @Override
        public void accept(Integer o) {
            System.out.println("Here you can also add your business logic that will work with Iteration and you can reuse it."+o);
        }
    }
    
    public class ForEachConsumer {
    
        public static void main(String[] args) {
    
            // Creating simple ArrayList.
            ArrayList<Integer> aList = new ArrayList<>();
            for(int i=1;i<=10;i++) aList.add(i);
    
            //Calling forEach with customized Iterator.
            MyConsumer consumer = new MyConsumer();
            aList.forEach(consumer);
    
    
            // Using Lambda Expression for Consumer. (Functional Interface) 
            Consumer<Integer> lambda = (Integer o) ->{
                System.out.println("Using Lambda Expression to iterate and do something else(BI).. "+o);
            };
            aList.forEach(lambda);
    
            // Using Anonymous Inner Class.
            aList.forEach(new Consumer<Integer>(){
                @Override
                public void accept(Integer o) {
                    System.out.println("Calling with Anonymous Inner Class "+o);
                }
            });
        }
    }
    

Is there a PowerShell "string does not contain" cmdlet or syntax?

If $arrayofStringsNotInterestedIn is an [array] you should use -notcontains:

Get-Content $FileName | foreach-object { `
   if ($arrayofStringsNotInterestedIn -notcontains $_) { $) }

or better (IMO)

Get-Content $FileName | where { $arrayofStringsNotInterestedIn -notcontains $_}

Renaming the current file in Vim

How about this (improved by Jake's suggestion):

:exe "!mv % newfilename" | e newfilename

How to prevent going back to the previous activity?

paulsm4's answer is the correct one. If in onBackPressed() you just return, it will disable the back button. However, I think a better approach given your use case is to flip the activity logic, i.e. make your home activity the main one, check if the user is signed in there, if not, start the sign in activity. The reason is that if you override the back button in your main activity, most users will be confused when they press back and your app does nothing.

Android: long click on a button -> perform actions

To get both functions working for a clickable image that will respond to both short and long clicks, I tried the following that seems to work perfectly:

    image = (ImageView) findViewById(R.id.imageViewCompass);
    image.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            shortclick();
        }
     });

    image.setOnLongClickListener(new View.OnLongClickListener() {
    public boolean onLongClick(View v) {
        longclick();
        return true;
    }
});

//Then the functions that are called:

 public void shortclick()
{
 Toast.makeText(this, "Why did you do that? That hurts!!!", Toast.LENGTH_LONG).show();

}

 public void longclick()
{
 Toast.makeText(this, "Why did you do that? That REALLY hurts!!!", Toast.LENGTH_LONG).show();

}

It seems that the easy way of declaring the item in XML as clickable and then defining a function to call on the click only applies to short clicks - you must have a listener to differentiate between short and long clicks.

How to alert using jQuery

Don't do this, but this is how you would do it:

$(".overdue").each(function() { 
    alert("Your book is overdue"); 
});

The reason I say "don't do it" is because nothing is more annoying to users, in my opinion, than repeated pop-ups that cannot be stopped. Instead, just use the length property and let them know that "You have X books overdue".

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

Try this using HTML like here:

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

Target WSGI script cannot be loaded as Python module

I was getting this error. I'm using python 3 in a virtual environment found this in my apache logs

[Fri Dec 21 08:01:43.471561 2018] [mpm_prefork:notice] [pid 21786] AH00163: Apache/2.4.6 (Red Hat Enterprise Linux) mod_wsgi/3.4 Python/2.7.5 configured -- resuming normal operations

I had installed wsgi using yum -y install mod_wsgi. This had installed mod_wsgi compiled for python 2. So I uninstalled it

yum remove mod_wsgi

and installed mod_wsgi compiled for python 3 using

yum install python35u-mod_wsgi

It worked after that

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

If above solutions not work just one time comment the getter and setter methods of entity class and do not set the value of id.(Primary key) Then this will work.

SQLite UPSERT / UPDATE OR INSERT

Q&A Style

Well, after researching and fighting with the problem for hours, I found out that there are two ways to accomplish this, depending on the structure of your table and if you have foreign keys restrictions activated to maintain integrity. I'd like to share this in a clean format to save some time to the people that may be in my situation.


Option 1: You can afford deleting the row

In other words, you don't have foreign key, or if you have them, your SQLite engine is configured so that there no are integrity exceptions. The way to go is INSERT OR REPLACE. If you are trying to insert/update a player whose ID already exists, the SQLite engine will delete that row and insert the data you are providing. Now the question comes: what to do to keep the old ID associated?

Let's say we want to UPSERT with the data user_name='steven' and age=32.

Look at this code:

INSERT INTO players (id, name, age)

VALUES (
    coalesce((select id from players where user_name='steven'),
             (select max(id) from drawings) + 1),
    32)

The trick is in coalesce. It returns the id of the user 'steven' if any, and otherwise, it returns a new fresh id.


Option 2: You cannot afford deleting the row

After monkeying around with the previous solution, I realized that in my case that could end up destroying data, since this ID works as a foreign key for other table. Besides, I created the table with the clause ON DELETE CASCADE, which would mean that it'd delete data silently. Dangerous.

So, I first thought of a IF clause, but SQLite only has CASE. And this CASE can't be used (or at least I did not manage it) to perform one UPDATE query if EXISTS(select id from players where user_name='steven'), and INSERT if it didn't. No go.

And then, finally I used the brute force, with success. The logic is, for each UPSERT that you want to perform, first execute a INSERT OR IGNORE to make sure there is a row with our user, and then execute an UPDATE query with exactly the same data you tried to insert.

Same data as before: user_name='steven' and age=32.

-- make sure it exists
INSERT OR IGNORE INTO players (user_name, age) VALUES ('steven', 32); 

-- make sure it has the right data
UPDATE players SET user_name='steven', age=32 WHERE user_name='steven'; 

And that's all!

EDIT

As Andy has commented, trying to insert first and then update may lead to firing triggers more often than expected. This is not in my opinion a data safety issue, but it is true that firing unnecessary events makes little sense. Therefore, a improved solution would be:

-- Try to update any existing row
UPDATE players SET age=32 WHERE user_name='steven';

-- Make sure it exists
INSERT OR IGNORE INTO players (user_name, age) VALUES ('steven', 32); 

reactjs giving error Uncaught TypeError: Super expression must either be null or a function, not undefined

There might be a third party package causing this. In our case it was react-dazzle. We have similar settings to that of @steine (see this answer above).

In order to find the problematic package I ran the webpack build locally with production mode and thus was able to find the problematic package in the stack trace. So for us this provided the solution and I was able to keep the uglification.

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

Enable Multidex through build.gradle of your app module

multiDexEnabled true

Same as below -

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

Then follow below steps -

  1. From the Build menu -> press the Clean Project button.
  2. When task completed, press the Rebuild Project button from the Build menu.
  3. From menu File -> Invalidate cashes / Restart

compile is now deprecated so it's better to use implementation or api

Create an enum with string values

UPDATE: TypeScript 3.4

You can simply use as const:

const AwesomeType = {
   Foo: "foo",
   Bar: "bar"
} as const;

TypeScript 2.1

This can also be done this way. Hope it help somebody.

const AwesomeType = {
    Foo: "foo" as "foo",
    Bar: "bar" as "bar"
};

type AwesomeType = (typeof AwesomeType)[keyof typeof AwesomeType];

console.log(AwesomeType.Bar); // returns bar
console.log(AwesomeType.Foo); // returns foo

function doSth(awesometype: AwesomeType) {
    console.log(awesometype);
}

doSth("foo") // return foo
doSth("bar") // returns bar
doSth(AwesomeType.Bar) // returns bar
doSth(AwesomeType.Foo) // returns foo
doSth('error') // does not compile

How to delete an item in a list if it exists?

try:
    s.remove("")
except ValueError:
    print "new_tag_list has no empty string"

Note that this will only remove one instance of the empty string from your list (as your code would have, too). Can your list contain more than one?

How to store images in mysql database using php

I found the answer, For those who are looking for the same thing here is how I did it. You should not consider uploading images to the database instead you can store the name of the uploaded file in your database and then retrieve the file name and use it where ever you want to display the image.

HTML CODE

<input type="file" name="imageUpload" id="imageUpload">

PHP CODE

if(isset($_POST['submit'])) {

    //Process the image that is uploaded by the user

    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

    if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["imageUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }

    $image=basename( $_FILES["imageUpload"]["name"],".jpg"); // used to store the filename in a variable

    //storind the data in your database
    $query= "INSERT INTO items VALUES ('$id','$title','$description','$price','$value','$contact','$image')";
    mysql_query($query);

    require('heading.php');
    echo "Your add has been submited, you will be redirected to your account page in 3 seconds....";
    header( "Refresh:3; url=account.php", true, 303);
}

CODE TO DISPLAY THE IMAGE

while($row = mysql_fetch_row($result)) {
    echo "<tr>";
    echo "<td><img src='uploads/$row[6].jpg' height='150px' width='300px'></td>";
    echo "</tr>\n";
}

Check if int is between two numbers

Because that syntax simply isn't defined? Besides, x < y evaluates as a bool, so what does bool < int mean? It isn't really an overhead; besides, you could write a utility method if you really want - isBetween(10,x,20) - I wouldn't myself, but hey...

Android Reading from an Input stream efficiently

The problem in your code is that it's creating lots of heavy String objects, copying their contents and performing operations on them. Instead, you should use StringBuilder to avoid creating new String objects on each append and to avoid copying the char arrays. The implementation for your case would be something like this:

BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
for (String line; (line = r.readLine()) != null; ) {
    total.append(line).append('\n');
}

You can now use total without converting it to String, but if you need the result as a String, simply add:

String result = total.toString();

I'll try to explain it better...

  • a += b (or a = a + b), where a and b are Strings, copies the contents of both a and b to a new object (note that you are also copying a, which contains the accumulated String), and you are doing those copies on each iteration.
  • a.append(b), where a is a StringBuilder, directly appends b contents to a, so you don't copy the accumulated string at each iteration.

DOM element to corresponding vue.js component

The proper way to do with would be to use the v-el directive to give it a reference. Then you can do this.$$[reference].

Update for vue 2

In Vue 2 refs are used for both elements and components: http://vuejs.org/guide/migration.html#v-el-and-v-ref-replaced

MySQL Stored procedure variables from SELECT statements

You simply need to enclose your SELECT statements in parentheses to indicate that they are subqueries:

SET cityLat = (SELECT cities.lat FROM cities WHERE cities.id = cityID);

Alternatively, you can use MySQL's SELECT ... INTO syntax. One advantage of this approach is that both cityLat and cityLng can be assigned from a single table-access:

SELECT lat, lng INTO cityLat, cityLng FROM cities WHERE id = cityID;

However, the entire procedure can be replaced with a single self-joined SELECT statement:

SELECT   b.*, HAVERSINE(a.lat, a.lng, b.lat, b.lng) AS dist
FROM     cities AS a, cities AS b
WHERE    a.id = cityID
ORDER BY dist
LIMIT    10;

Remove an entire column from a data.frame in R

There are several options for removing one or more columns with dplyr::select() and some helper functions. The helper functions can be useful because some do not require naming all the specific columns to be dropped. Note that to drop columns using select() you need to use a leading - to negate the column names.

Using the dplyr::starwars sample data for some variety in column names:

library(dplyr)

starwars %>% 
  select(-height) %>%                  # a specific column name
  select(-one_of('mass', 'films')) %>% # any columns named in one_of()
  select(-(name:hair_color)) %>%       # the range of columns from 'name' to 'hair_color'
  select(-contains('color')) %>%       # any column name that contains 'color'
  select(-starts_with('bi')) %>%       # any column name that starts with 'bi'
  select(-ends_with('er')) %>%         # any column name that ends with 'er'
  select(-matches('^v.+s$')) %>%       # any column name matching the regex pattern
  select_if(~!is.list(.)) %>%          # not by column name but by data type
  head(2)

# A tibble: 2 x 2
homeworld species
  <chr>     <chr>  
1 Tatooine  Human  
2 Tatooine  Droid 

You can also drop by column number:

starwars %>% 
  select(-2, -(4:10)) # column 2 and columns 4 through 10

How can I check if a view is visible or not in Android?

If the image is part of the layout it might be "View.VISIBLE" but that doesn't mean it's within the confines of the visible screen. If that's what you're after; this will work:

Rect scrollBounds = new Rect();
scrollView.getHitRect(scrollBounds);
if (imageView.getLocalVisibleRect(scrollBounds)) {
    // imageView is within the visible window
} else {
    // imageView is not within the visible window
}

What exactly does the Access-Control-Allow-Credentials header do?

By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.

In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.

The client code must set the withCredentials property on the XMLHttpRequest to true in order to give permission.

However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials header. Responding with this header to true means that the server allows cookies (or other user credentials) to be included on cross-origin requests.

You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.

Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).

Changing background color of selected cell?

- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    cell.contentView.backgroundColor = [UIColor yellowColor];
}

- (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    cell.contentView.backgroundColor = nil;
}

Merge DLL into EXE?

Download

ILMerge

Call

ilmerge /target:winexe /out:c:\output.exe c:\input.exe C:\input.dll

open_basedir restriction in effect. File(/) is not within the allowed path(s):

I uploaded my codeigniter project on Directadmin panel. I was getting same error. error

Then I change in php settings.

open_basedir = session.save_path = ./temp/

Then it worked for me.

Android toolbar center title and custom font

You can insert this code in your xml file

 <androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimaryDark"
    android:elevation="4dp"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Toolbar Title"
        android:textColor="#000000"
        android:textSize="20dp"
        android:id="@+id/toolbar_title" />

</androidx.appcompat.widget.Toolbar>

What does void mean in C, C++, and C#?

Void is the equivalent of Visual Basic's Sub.

How to insert blank lines in PDF?

document.add(new Paragraph("")) 

It is ineffective above,must add a blank string, like this:

document.add(new Paragraph(" "));

Is either GET or POST more secure than the other?

My usual methodology for choosing is something like:

  • GET for items that will be retrieved later by URL
    • E.g. Search should be GET so you can do search.php?s=XXX later on
  • POST for items that will be sent
    • This is relatively invisible comapred to GET and harder to send, but data can still be sent via cURL.

How to check if an object is an array?

Here's my lazy approach:

if (Array.prototype.array_ === undefined) {
  Array.prototype.array_ = true;
}

// ...

var test = [],
    wat = {};

console.log(test.array_ === true); // true
console.log(wat.array_ === true);  // false

I know it's sacrilege to "mess with" the prototype, but it appears to perform significantly better than the recommended toString method.

Note: A pitfall of this approach is that it wont work across iframe boundaries, but for my use case this is not an issue.

Remove array element based on object property

Using lodash library it is simple as this

_.remove(myArray , { field: 'money' });

Python: access class property from string

Extending Alex's answer slightly:

class User:
    def __init__(self):
        self.data = [1,2,3]
        self.other_data = [4,5,6]
    def doSomething(self, source):
        dataSource = getattr(self,source)
        return dataSource

A = User()
print A.doSomething("data")
print A.doSomething("other_data")

will yield:

[1, 2, 3]
[4, 5, 6]

However, personally I don't think that's great style - getattr will let you access any attribute of the instance, including things like the doSomething method itself, or even the __dict__ of the instance. I would suggest that instead you implement a dictionary of data sources, like so:

class User:
    def __init__(self):

        self.data_sources = {
            "data": [1,2,3],
            "other_data":[4,5,6],
        }

    def doSomething(self, source):
        dataSource = self.data_sources[source]
        return dataSource

A = User()

print A.doSomething("data")
print A.doSomething("other_data")

again yielding:

[1, 2, 3]
[4, 5, 6]

How to check if the given string is palindrome?

C#: LINQ

var str = "a b a";
var test = Enumerable.SequenceEqual(str.ToCharArray(), 
           str.ToCharArray().Reverse());

case-insensitive matching in xpath?

for selenium xpath lower-case will not work ... Translate will help Case 1 :

  1. using Attribute //*[translate(@id,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='login_field']
  2. Using any attribute //[translate(@,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='login_field']

Case 2 : (with contains) //[contains(translate(@id,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz'),'login_field')]

case 3 : for Text property //*[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'),'username')]


QA Automator is automation management tool on cloud platform , where you can create, execute and maintenance the automation test scripts https://www.youtube.com/watch?v=iFk1Na_627U&t=53s

Converting between strings and ArrayBuffers

In case you have binary data in a string (obtained from nodejs + readFile(..., 'binary'), or cypress + cy.fixture(..., 'binary'), etc), you can't use TextEncoder. It supports only utf8. Bytes with values >= 128 are each turned into 2 bytes.

ES2015:

a = Uint8Array.from(s, x => x.charCodeAt(0))

Uint8Array(33) [2, 134, 140, 186, 82, 70, 108, 182, 233, 40, 143, 247, 29, 76, 245, 206, 29, 87, 48, 160, 78, 225, 242, 56, 236, 201, 80, 80, 152, 118, 92, 144, 48

s = String.fromCharCode.apply(null, a)

"ºRFl¶é(÷LõÎW0 Náò8ìÉPPv\0"

Can I change the Android startActivity() transition animation?

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

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

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

Order discrete x scale by frequency/value

The best way for me was using vector with categories in order I need as limits parameter to scale_x_discrete. I think it is pretty simple and straightforward solution.

ggplot(mtcars, aes(factor(cyl))) + 
  geom_bar() + 
  scale_x_discrete(limits=c(8,4,6))

enter image description here

WCF Service Client: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding

Hy, In my case this error appeared because the Application pool of the webservice had the wrong 32/64 bit setting. So this error needed the following fix: you go to the IIS, select the site of the webservice , go to Advanced setting and get the application pool. Then go to Application pools, select it, go to "Advanced settings..." , select the "Enable 32 bit applications" and make it Enable or Disable, according to the 32/64 bit type of your webservice. If the setting is True, it means that it only allows 32 bit applications, so for 64 bit apps you have to make it "Disable" (default).

Python logging not outputting anything

Maybe try this? It seems the problem is solved after remove all the handlers in my case.

for handler in logging.root.handlers[:]:
    logging.root.removeHandler(handler)

logging.basicConfig(filename='output.log', level=logging.INFO)

How to get the process ID to kill a nohup process?

Suppose you are executing a java program with nohup you can get java process id by

`ps aux | grep java`

output

xxxxx     9643  0.0  0.0  14232   968 pts/2   

then you can kill the process by typing

sudo kill 9643

or lets say that you need to kill all the java processes then just use

sudo killall java

this command kills all the java processes. you can use this with process. just give the process name at the end of the command

sudo killall {processName}

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

Go back from classpath 'com.android.tools.build:gradle:3.3.0-alpha13' to classpath 'com.android.tools.build:gradle:3.2.0'

this worked for me

Android Studio - Device is connected but 'offline'

  • Restart adb by issuing these commands in cmd

    adb kill-server to kill existing adb session

    followed by adb start-server to start a new adb session
  • Disable and re-enable USB debugging on the phone and accept RSA fingerprints if asked by phone
  • Rebooting the phone if it still doesn't work.

If all above don't solve your problem, you may try delete environment variable named "ANDROID_SDK_HOME". It really solved my problem. Hope it Help you!

Access non-numeric Object properties by index?

The only way I can think of doing this is by creating a method that gives you the property using Object.keys();.

var obj = {
    dog: "woof",
    cat: "meow",
    key: function(n) {
        return this[Object.keys(this)[n]];
    }
};
obj.key(1); // "meow"

Demo: http://jsfiddle.net/UmkVn/

It would be possible to extend this to all objects using Object.prototype; but that isn't usually recommended.

Instead, use a function helper:

var object = {
  key: function(n) {
    return this[ Object.keys(this)[n] ];
  }
};

function key(obj, idx) {
  return object.key.call(obj, idx);
}

key({ a: 6 }, 0); // 6

How do you get the path to the Laravel Storage folder?

In Laravel 3, call path('storage').

In Laravel 4, use the storage_path() helper function.

Most Useful Attributes

Being a middle tier developer I like

System.ComponentModel.EditorBrowsableAttribute Allows me to hide properties so that the UI developer is not overwhelmed with properties that they don't need to see.

System.ComponentModel.BindableAttribute Some things don't need to be databound. Again, lessens the work the UI developers need to do.

I also like the DefaultValue that Lawrence Johnston mentioned.

System.ComponentModel.BrowsableAttribute and the Flags are used regularly.

I use System.STAThreadAttribute System.ThreadStaticAttribute when needed.

By the way. I these are just as valuable for all the .Net framework developers.

Update multiple columns in SQL

Your query is nearly correct. The T-SQL for this is:

UPDATE  Table1
SET     Field1 = Table2.Field1,
        Field2 = Table2.Field2,
        other columns...
FROM    Table2
WHERE   Table1.ID = Table2.ID

ssh: Could not resolve hostname github.com: Name or service not known; fatal: The remote end hung up unexpectedly

Recently, I have seen this problem too. Below, you have my solution:

  1. ping github.com, if ping failed. it is DNS error.
  2. sudo vim /etc/resolv.conf, the add: nameserver 8.8.8.8 nameserver 8.8.4.4

Or it can be a genuine network issue. Restart your network-manager using sudo service network-manager restart or fix it up


I have just received this error after switching from HTTPS to SSH (for my origin remote). To fix, I simply ran the following command (for each repo):

ssh -T [email protected]

Upon receiving a successful response, I could fetch/push to the repo with ssh.

I took that command from Git's Testing your SSH connection guide, which is part of the greater Connecting to GitHub with with SSH guide.

How to check if a variable is null or empty string or all whitespace in JavaScript?

You can try this:

do {
   var op = prompt("please input operatot \n you most select one of * - / *  ")
} while (typeof op == "object" || op == ""); 
// execute block of code when click on cancle or ok whthout input

How do I base64 encode (decode) in C?

GNU coreutils has it in lib/base64. It's a little bloated but deals with stuff like EBCDIC. You can also play around on your own, e.g.,

char base64_digit (n) unsigned n; {
  if (n < 10) return n - '0';
  else if (n < 10 + 26) return n - 'a';
  else if (n < 10 + 26 + 26) return n - 'A';
  else assert(0);
  return 0;
}

unsigned char base64_decode_digit(char c) {
  switch (c) {
    case '=' : return 62;
    case '.' : return 63;
    default  :
      if (isdigit(c)) return c - '0';
      else if (islower(c)) return c - 'a' + 10;
      else if (isupper(c)) return c - 'A' + 10 + 26;
      else assert(0);
  }
  return 0xff;
}

unsigned base64_decode(char *s) {
  char *p;
  unsigned n = 0;

  for (p = s; *p; p++)
    n = 64 * n + base64_decode_digit(*p);

  return n;
}

Know ye all persons by these presents that you should not confuse "playing around on your own" with "implementing a standard." Yeesh.

How to print out more than 20 items (documents) in MongoDB's shell?

From the shell if you want to show all results you could do db.collection.find().toArray() to get all results without it.

Formatting code snippets for blogging on Blogger

This can be done fairly easily with SyntaxHighlighter. I have step-by-step instructions for setting up SyntaxHighlighter in Blogger on my blog. SyntaxHighlighter is very easy to use. It lets you post snippets in raw form and then wrap them in pre blocks like:

<pre name="code" class="brush: erlang"><![CDATA[
-module(trim).

-export([string_strip_right/1, reverse_tl_reverse/1, bench/0]).

bench() -> [nbench(N) || N <- [1,1000,1000000]].

nbench(N) -> {N, bench(["a" || _ <- lists:seq(1,N)])}.

bench(String) ->
    {{string_strip_right,
    lists:sum([
        element(1, timer:tc(trim, string_strip_right, [String]))
        || _ <- lists:seq(1,1000)])},
    {reverse_tl_reverse,
    lists:sum([
        element(1, timer:tc(trim, reverse_tl_reverse, [String]))
        || _ <- lists:seq(1,1000)])}}.

string_strip_right(String) -> string:strip(String, right, $\n).

reverse_tl_reverse(String) ->
    lists:reverse(tl(lists:reverse(String))).
]]></pre>

Just change the brush name to "python" or "java" or "javascript" and paste in the code of your choice. The CDATA tagging let's you put pretty much any code in there without worrying about entity escaping or other typical annoyances of code blogging.

UTF-8 encoded html pages show ? (questions marks) instead of characters

Tell PDO your charset initially.... something like

PDO("mysql:host=$host;dbname=$DB_name;charset=utf8;", $username, $password);

Notice the: charset=utf8; part.

hope it helps!

Is it safe to clean docker/overlay2/

DON'T DO THIS IN PRODUCTION

The answer given by @ravi-luthra technically works but it has some issues!

In my case, I was just trying to recover disk space. The lib/docker/overlay folder was taking 30GB of space and I only run a few containers regularly. Looks like docker has some issue with data leakage and some of the temporary data are not cleared when the container stops.

So I went ahead and deleted all the contents of lib/docker/overlay folder. After that, My docker instance became un-useable. When I tried to run or build any container, It gave me this error:

failed to create rwlayer: symlink ../04578d9f8e428b693174c6eb9a80111c907724cc22129761ce14a4c8cb4f1d7c/diff /var/lib/docker/overlay2/l/C3F33OLORAASNIYB3ZDATH2HJ7: no such file or directory

Then with some trial and error, I solved this issue by running

(WARNING: This will delete all your data inside docker volumes)

docker system prune --volumes -a

So It is not recommended to do such dirty clean ups unless you completely understand how the system works.

Error:Unable to locate adb within SDK in Android Studio

In my case I had no SDK selected for my project(not sure why). Simply went to Project Structure dialog (alt+ctrl+shift+s or button 1 on the screen) and then to project-> Project SDK's was selected <no SDK>. Just changed it to the latest

Project Structure dialog

How do I automatically play a Youtube video (IFrame API) muted?

You can select the video player and then set its volume:

var mp = iframe.getElementById('movie_player');
mp.setVolume(0);

Source: http://userscripts.org/scripts/review/49366

Does an HTTP Status code of 0 have any meaning?

from documentation http://www.w3.org/TR/XMLHttpRequest/#the-status-attribute means a request was cancelled before going anywhere

Install IPA with iTunes 12

For iTunes 12.9.5.5 and above you can install the apps by Copying the IPA file and Paste it (Cmd+V or Edit -> Paste in iTunes) in any categories as Music/Films/TV Programmes etc. The app will be installed automatically on your iPhone screen.

Tested on 29 Nov 2019.

Demo: enter image description here

iOS application: how to clear notifications?

When you logout from your app, at that time you have to use a below line of code on your logout button click method.

[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];

[[UIApplication sharedApplication] cancelAllLocalNotifications];

and this works perfectly in my app.

Match all elements having class name starting with a specific string

You can easily add multiple classes to divs... So:

<div class="myclass myclass-one"></div>
<div class="myclass myclass-two"></div>
<div class="myclass myclass-three"></div>

Then in the CSS call to the share class to apply the same styles:

.myclass {...}

And you can still use your other classes like this:

.myclass-three {...}

Or if you want to be more specific in the CSS like this:

.myclass.myclass-three {...}

Convert a Unicode string to a string in Python (containing extra symbols)

file contain unicode-esaped string

\"message\": \"\\u0410\\u0432\\u0442\\u043e\\u0437\\u0430\\u0446\\u0438\\u044f .....\",

for me

 f = open("56ad62-json.log", encoding="utf-8")
 qq=f.readline() 

 print(qq)                          
 {"log":\"message\": \"\\u0410\\u0432\\u0442\\u043e\\u0440\\u0438\\u0437\\u0430\\u0446\\u0438\\u044f \\u043f\\u043e\\u043b\\u044c\\u0437\\u043e\\u0432\\u0430\\u0442\\u0435\\u043b\\u044f\"}

(qq.encode().decode("unicode-escape").encode().decode("unicode-escape")) 
# '{"log":"message": "??????????? ????????????"}\n'

Reading and writing binary file

Here is implementation of standard C++ 14 using vectors and tuples to Read and Write Text,Binary and Hex files.

Snippet code :

try {
if (file_type == BINARY_FILE) {

    /*Open the stream in binary mode.*/
    std::ifstream bin_file(file_name, std::ios::binary);

    if (bin_file.good()) {
        /*Read Binary data using streambuffer iterators.*/
        std::vector<uint8_t> v_buf((std::istreambuf_iterator<char>(bin_file)), (std::istreambuf_iterator<char>()));
        vec_buf = v_buf;
        bin_file.close();
    }

    else {
        throw std::exception();
    }

}

else if (file_type == ASCII_FILE) {

    /*Open the stream in default mode.*/
    std::ifstream ascii_file(file_name);
    string ascii_data;

    if (ascii_file.good()) {
        /*Read ASCII data using getline*/
        while (getline(ascii_file, ascii_data))
            str_buf += ascii_data + "\n";

        ascii_file.close();
    }
    else {
        throw std::exception();
    }
}

else if (file_type == HEX_FILE) {

    /*Open the stream in default mode.*/
    std::ifstream hex_file(file_name);

    if (hex_file.good()) {
        /*Read Hex data using streambuffer iterators.*/
        std::vector<char> h_buf((std::istreambuf_iterator<char>(hex_file)), (std::istreambuf_iterator<char>()));
        string hex_str_buf(h_buf.begin(), h_buf.end());
        hex_buf = hex_str_buf;

        hex_file.close();
    }
    else {
        throw std::exception();
    }
}

}

Full Source code can be found here

Making HTTP Requests using Chrome Developer tools

If you want to do a POST from the same domain, you can always insert a form into the DOM using Developer tools and submit that:

Inserted form into document

Float a div in top right corner without overlapping sibling header

Get rid from your <Button> wrap div using display:block and float:left in both <Button> and <h1> and specifying their width with a position:relative to your Section. This approach has the advantage of not needing another div only to position your <Button>

html

<section>  
    <h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>     
    <button>button</button>
</section>

? css

section {
    position: relative;
    width: 50%;
    border: 1px solid;
    float:left;
}
h1 {
    display: block;
    width:70%;
    float:left;
}
button
{
    position:relative;
    top:0;
    left:0;
    float:left;
}

?

How to find count of Null and Nan values for each column in a PySpark dataframe efficiently?

Here is my one liner. Here 'c' is the name of the column

df.select('c').withColumn('isNull_c',F.col('c').isNull()).where('isNull_c = True').count()

Generate random 5 characters string

function CaracteresAleatorios( $Tamanno, $Opciones) {
    $Opciones = empty($Opciones) ? array(0, 1, 2) : $Opciones;
    $Tamanno = empty($Tamanno) ? 16 : $Tamanno;
    $Caracteres=array("0123456789","abcdefghijklmnopqrstuvwxyz","ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    $Caracteres= implode("",array_intersect_key($Caracteres, array_flip($Opciones)));
    $CantidadCaracteres=strlen($Caracteres)-1;
    $CaracteresAleatorios='';
    for ($k = 0; $k < $Tamanno; $k++) {
        $CaracteresAleatorios.=$Caracteres[rand(0, $CantidadCaracteres)];
    }
    return $CaracteresAleatorios;
}

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

 $(document).ready(function () {
    $('.dates li a').click(function (e) {

        $('.dates li a').removeClass('active');

        var $parent = $(this);
        if (!$parent.hasClass('active')) {
            $parent.addClass('active');
        }
        e.preventDefault();
    });
});

How can I check if a key exists in a dictionary?

If you want to retrieve the key's value if it exists, you can also use

try:
    value = a[key]
except KeyError:
    # Key is not present
    pass

If you want to retrieve a default value when the key does not exist, use value = a.get(key, default_value). If you want to set the default value at the same time in case the key does not exist, use value = a.setdefault(key, default_value).

Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type

If you need a quick fix, simply add this before the line of your import:

// @ts-ignore

windows batch file rename

Use REN Command

Ren is for rename

ren ( where the file is located ) ( the new name )

example

ren C:\Users\&username%\Desktop\aaa.txt bbb.txt

it will change aaa.txt to bbb.txt

Your code will be :

ren (file located)AAA_a001.jpg a001.AAA.jpg

ren (file located)BBB_a002.jpg a002.BBB.jpg

ren (file located)CCC_a003.jpg a003.CCC.jpg

and so on

IT WILL NOT WORK IF THERE IS SPACES!

Hope it helps :D

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

I just solved this error happening in my tests.

Just make sure your test class has all dependencies in the attributes of the class being tested annotated with @MockBean so SpringBoot test context can wire your classes correctly.

Only if you are testing controller: you need also class annotations to load the Controller context propertly.

Check it out:

@DisplayName("UserController Adapter Test")
@WebMvcTest(UserController.class)
@AutoConfigureMockMvc(addFilters = false)
@Import(TestConfig.class)
public class UserControllerTest {

@Autowired
private MockMvc mockMvc;

@Autowired
private ObjectMapper objectMapper;

@MockBean
private CreateUserCommand createUserCommand;

@MockBean
private GetUserListQuery getUserListQuery;

@MockBean
private GetUserQuery getUserQuery;

Variable declaration in a header file

You should declare the variable in a header file:

extern int x;

and then define it in one C file:

int x;

In C, the difference between a definition and a declaration is that the definition reserves space for the variable, whereas the declaration merely introduces the variable into the symbol table (and will cause the linker to go looking for it when it comes to link time).

Get first row of dataframe in Python Pandas based on criteria

you can take care of the first 3 items with slicing and head:

  1. df[df.A>=4].head(1)
  2. df[(df.A>=4)&(df.B>=3)].head(1)
  3. df[(df.A>=4)&((df.B>=3) * (df.C>=2))].head(1)

The condition in case nothing comes back you can handle with a try or an if...

try:
    output = df[df.A>=6].head(1)
    assert len(output) == 1
except: 
    output = df.sort_values('A',ascending=False).head(1)

what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean?

In my case it happened when calling a function by passing a parameter of a Core Data managed object's property. At the time of calling the object was no longer existed, and that caused this error.

I have solved the issue by checking if the managed object exists or not before calling the function.

What is the difference between int, Int16, Int32 and Int64?

A very important note on the 16, 32 and 64 types:

if you run this query... Array.IndexOf(new Int16[]{1,2,3}, 1)

you are suppose to get zero(0) because you are asking... is 1 within the array of 1, 2 or 3. if you get -1 as answer, it means 1 is not within the array of 1, 2 or 3.

Well check out what I found: All the following should give you 0 and not -1 (I've tested this in all framework versions 2.0, 3.0, 3.5, 4.0)

C#:

Array.IndexOf(new Int16[]{1,2,3}, 1) = -1 (not correct)
Array.IndexOf(new Int32[]{1,2,3}, 1) = 0 (correct)
Array.IndexOf(new Int64[]{1,2,3}, 1) = 0 (correct)

VB.NET:

Array.IndexOf(new Int16(){1,2,3}, 1) = -1 (not correct)
Array.IndexOf(new Int32(){1,2,3}, 1) = 0 (correct)
Array.IndexOf(new Int64(){1,2,3}, 1) = -1 (not correct)

So my point is, for Array.IndexOf comparisons, only trust Int32!

What's the best way to do a backwards loop in C/C#/C++?

// this is how I always do it
for (i = n; --i >= 0;){
   ...
}

Connecting to TCP Socket from browser using javascript

The solution you are really looking for is web sockets. However, the chromium project has developed some new technologies that are direct TCP connections TCP chromium

Finding the layers and layer sizes for each Docker image

I've solved this problem by using the search function on Docker's website where '*' is a valid search that returns 200k repositories and then I crawled each invididual page. HTML parsing allows me to extract all the image names on each page.

How to get the current user in ASP.NET MVC

In the IIS Manager, under Authentication, disable: 1) Anonymous Authentication 2) Forms Authentication

Then add the following to your controller, to handle testing versus server deployment:

string sUserName = null;
string url = Request.Url.ToString();

if (url.Contains("localhost"))
  sUserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
else
  sUserName = User.Identity.Name;

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

Returns true if comes 'y', '1', 'true', 'on'or whatever you add in similar way

boolean getValue(String value) {
  return ("Y".equals(value.toUpperCase()) 
      || "1".equals(value.toUpperCase())
      || "TRUE".equals(value.toUpperCase())
      || "ON".equals(value.toUpperCase()) 
     );
}

Difference between variable declaration syntaxes in Javascript (including global variables)?

In global scope there is no semantic difference.

But you really should avoid a=0 since your setting a value to an undeclared variable.

Also use closures to avoid editing global scope at all

(function() {
   // do stuff locally

   // Hoist something to global scope
   window.someGlobal = someLocal
}());

Always use closures and always hoist to global scope when its absolutely neccesary. You should be using asynchronous event handling for most of your communication anyway.

As @AvianMoncellor mentioned there is an IE bug with var a = foo only declaring a global for file scope. This is an issue with IE's notorious broken interpreter. This bug does sound familiar so it's probably true.

So stick to window.globalName = someLocalpointer

How do I use variables in Oracle SQL Developer?

You can read up elsewhere on substitution variables; they're quite handy in SQL Developer. But I have fits trying to use bind variables in SQL Developer. This is what I do:

SET SERVEROUTPUT ON
declare
  v_testnum number;
  v_teststring varchar2(1000);

begin
   v_testnum := 2;
   DBMS_OUTPUT.put_line('v_testnum is now ' || v_testnum);

   SELECT 36,'hello world'
   INTO v_testnum, v_teststring
   from dual;

   DBMS_OUTPUT.put_line('v_testnum is now ' || v_testnum);
   DBMS_OUTPUT.put_line('v_teststring is ' || v_teststring);
end;

SET SERVEROUTPUT ON makes it so text can be printed to the script output console.

I believe what we're doing here is officially called PL/SQL. We have left the pure SQL land and are using a different engine in Oracle. You see the SELECT above? In PL/SQL you always have to SELECT ... INTO either variable or a refcursor. You can't just SELECT and return a result set in PL/SQL.

Task<> does not contain a definition for 'GetAwaiter'

Make sure your .NET version 4.5 or greater

Reflection: How to Invoke Method with parameters

I would use it like this, its way shorter and it won't give any problems

        dynamic result = null;
        if (methodInfo != null)
        {
            ParameterInfo[] parameters = methodInfo.GetParameters();
            object classInstance = Activator.CreateInstance(type, null);
            result = methodInfo.Invoke(classInstance, parameters.Length == 0 ? null : parametersArray);
        }

Unable to compile simple Java 10 / Java 11 project with Maven

As of 30Jul, 2018 to fix the above issue, one can configure the java version used within maven to any up to JDK/11 and make use of the maven-compiler-plugin:3.8.0 to specify a release of either 9,10,11 without any explicit dependencies.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.0</version>
    <configuration>
        <release>11</release>  <!--or <release>10</release>-->
    </configuration>
</plugin>

Note:- The default value for source/target has been lifted from 1.5 to 1.6 with this version. -- release notes.


Edit [30.12.2018]

In fact, you can make use of the same version of maven-compiler-plugin while compiling the code against JDK/12 as well.

More details and a sample configuration in how to Compile and execute a JDK preview feature with Maven.

Difference between -XX:+UseParallelGC and -XX:+UseParNewGC

Parallel GC

  • XX:+UseParallelGC Use parallel garbage collection for scavenges. (Introduced in 1.4.1)
  • XX:+UseParallelOldGC Use parallel garbage collection for the full collections. Enabling this option automatically sets -XX:+UseParallelGC. (Introduced in 5.0 update 6.)

UseParNewGC

UseParNewGC A parallel version of the young generation copying collector is used with the concurrent collector (i.e. if -XX:+ UseConcMarkSweepGC is used on the command line then the flag UseParNewGC is also set to true if it is not otherwise explicitly set on the command line).

Perhaps the easiest way to understand was combinations of garbage collection algorithms made by Alexey Ragozin

_x000D_
_x000D_
<table border="1" style="width:100%">_x000D_
  <tr>_x000D_
    <td align="center">Young collector</td>_x000D_
    <td align="center">Old collector</td>_x000D_
    <td align="center">JVM option</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Serial (DefNew)</td>_x000D_
    <td>Serial Mark-Sweep-Compact</td>_x000D_
    <td>-XX:+UseSerialGC</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Parallel scavenge (PSYoungGen)</td>_x000D_
    <td>Serial Mark-Sweep-Compact (PSOldGen)</td>_x000D_
    <td>-XX:+UseParallelGC</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Parallel scavenge (PSYoungGen)</td>_x000D_
    <td>Parallel Mark-Sweep-Compact (ParOldGen)</td>_x000D_
    <td>-XX:+UseParallelOldGC</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Serial (DefNew)</td>_x000D_
    <td>Concurrent Mark Sweep</td>_x000D_
    <td>_x000D_
      <p>-XX:+UseConcMarkSweepGC</p>_x000D_
      <p>-XX:-UseParNewGC</p>_x000D_
    </td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Parallel (ParNew)</td>_x000D_
    <td>Concurrent Mark Sweep</td>_x000D_
    <td>_x000D_
      <p>-XX:+UseConcMarkSweepGC</p>_x000D_
      <p>-XX:+UseParNewGC</p>_x000D_
    </td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td colspan="2">G1</td>_x000D_
    <td>-XX:+UseG1GC</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Conclusion:

  1. Apply -XX:+UseParallelGC when you require parallel collection method over YOUNG generation ONLY, (but still) use serial-mark-sweep method as OLD generation collection
  2. Apply -XX:+UseParallelOldGC when you require parallel collection method over YOUNG generation (automatically sets -XX:+UseParallelGC) AND OLD generation collection
  3. Apply -XX:+UseParNewGC & -XX:+UseConcMarkSweepGC when you require parallel collection method over YOUNG generation AND require CMS method as your collection over OLD generation memory
  4. You can't apply -XX:+UseParallelGC or -XX:+UseParallelOldGC with -XX:+UseConcMarkSweepGC simultaneously, that's why your require -XX:+UseParNewGC to be paired with CMS otherwise use -XX:+UseSerialGC explicitly OR -XX:-UseParNewGC if you wish to use serial method against young generation

OAuth2 and Google API: access token expiration time?

The default expiry_date for google oauth2 access token is 1 hour. The expiry_date is in the Unix epoch time in milliseconds. If you want to read this in human readable format then you can simply check it here..Unix timestamp to human readable time

Can I create links with 'target="_blank"' in Markdown?

In my project I'm doing this and it works fine:

[Link](https://example.org/ "title" target="_blank")

Link

But not all parsers let you do that.

What is C# analog of C++ std::pair?

C# has tuples as of version 4.0.

ORA-00932: inconsistent datatypes: expected - got CLOB

The same error occurs also when doing SELECT DISTINCT ..., <CLOB_column>, ....

If this CLOB column contains values shorter than limit for VARCHAR2 in all the applicable rows you may use to_char(<CLOB_column>) or concatenate results of multiple calls to DBMS_LOB.SUBSTR(<CLOB_column>, ...).

Disable submit button ONLY after submit

  $(function(){

    $("input[type='submit']").click(function () {
        $(this).attr("disabled", true);   
     });
  });

thant's it.

How to remove word wrap from textarea?

The following CSS based solution works for me:

<html>
 <head>
  <style type='text/css'>
   textarea {
    white-space: nowrap;
    overflow:    scroll;
    overflow-y:  hidden;
    overflow-x:  scroll;
    overflow:    -moz-scrollbars-horizontal;
   }
  </style>
 </head>
 <body>
  <form>
   <textarea>This is a long line of text for testing purposes...</textarea>
  </form>
 </body>
</html>

How to add a string to a string[] array? There's no .Add function

Why don't you use a for loop instead of using foreach. In this scenario, there is no way you can get the index of the current iteration of the foreach loop.

The name of the file can be added to the string[] in this way,

private string[] ColeccionDeCortes(string Path)
{
  DirectoryInfo X = new DirectoryInfo(Path);
  FileInfo[] listaDeArchivos = X.GetFiles();
  string[] Coleccion=new string[listaDeArchivos.Length];

  for (int i = 0; i < listaDeArchivos.Length; i++)
  {
     Coleccion[i] = listaDeArchivos[i].Name;
  }

  return Coleccion;
}

What is the best open-source java charting library? (other than jfreechart)

Good question, I was just looking for alternatives to JFreeChart myself the other day. JFreeChart is excellent and very comprehensive, I've used it on several projects. My recent problem was that it meant adding 1.6mb of libraries to a 50kb applet, so I was looking for something smaller.

The JFreeChart FAQ itself lists alternatives. Compared to JFreeChart, most of them are pretty basic, and some pretty ugly. The most promising seem to be the Java Chart Construction Kit and OpenChart2.

I also found EasyCharts, which is a commercial product but seemingly free to use in some circumstances.

In the end, I went back to the tried and trusted JFreeChart and used Proguard to butcher it into a more manageable size.

I suggest that you take another look at JFreeChart. The user guide is only available to buy, but the demo shows what is possible and it's pretty easy to work out how from the API documentation. Basically you start with the ChartFactory static methods and plug the resultant JFreeChart object into a ChartPanel to display it. If you get stuck, I'm sure you'll get some quick answers to your problems on StackOverflow.

How to set adaptive learning rate for GradientDescentOptimizer?

Gradient descent algorithm uses the constant learning rate which you can provide in during the initialization. You can pass various learning rates in a way showed by Mrry.

But instead of it you can also use more advanced optimizers which have faster convergence rate and adapts to the situation.

Here is a brief explanation based on my understanding:

  • momentum helps SGD to navigate along the relevant directions and softens the oscillations in the irrelevant. It simply adds a fraction of the direction of the previous step to a current step. This achieves amplification of speed in the correct dirrection and softens oscillation in wrong directions. This fraction is usually in the (0, 1) range. It also makes sense to use adaptive momentum. In the beginning of learning a big momentum will only hinder your progress, so it makse sense to use something like 0.01 and once all the high gradients disappeared you can use a bigger momentom. There is one problem with momentum: when we are very close to the goal, our momentum in most of the cases is very high and it does not know that it should slow down. This can cause it to miss or oscillate around the minima
  • nesterov accelerated gradient overcomes this problem by starting to slow down early. In momentum we first compute gradient and then make a jump in that direction amplified by whatever momentum we had previously. NAG does the same thing but in another order: at first we make a big jump based on our stored information, and then we calculate the gradient and make a small correction. This seemingly irrelevant change gives significant practical speedups.
  • AdaGrad or adaptive gradient allows the learning rate to adapt based on parameters. It performs larger updates for infrequent parameters and smaller updates for frequent one. Because of this it is well suited for sparse data (NLP or image recognition). Another advantage is that it basically illiminates the need to tune the learning rate. Each parameter has its own learning rate and due to the peculiarities of the algorithm the learning rate is monotonically decreasing. This causes the biggest problem: at some point of time the learning rate is so small that the system stops learning
  • AdaDelta resolves the problem of monotonically decreasing learning rate in AdaGrad. In AdaGrad the learning rate was calculated approximately as one divided by the sum of square roots. At each stage you add another square root to the sum, which causes denominator to constantly decrease. In AdaDelta instead of summing all past square roots it uses sliding window which allows the sum to decrease. RMSprop is very similar to AdaDelta
  • Adam or adaptive momentum is an algorithm similar to AdaDelta. But in addition to storing learning rates for each of the parameters it also stores momentum changes for each of them separately

    A few visualizations: enter image description here enter image description here

how to return a char array from a function in C

Daniel is right: http://ideone.com/kgbo1C#view_edit_box

Change

test=substring(i,j,*s);

to

test=substring(i,j,s);  

Also, you need to forward declare substring:

char *substring(int i,int j,char *ch);

int main // ...

Closing WebSocket correctly (HTML5, Javascript)

As mentioned by theoobe, some browsers do not close the websockets automatically. Don't try to handle any "close browser window" events client-side. There is currently no reliable way to do it, if you consider support of major desktop AND mobile browsers (e.g. onbeforeunload will not work in Mobile Safari). I had good experience with handling this problem server-side. E.g. if you use Java EE, take a look at javax.websocket.Endpoint, depending on the browser either the OnClose method or the OnError method will be called if you close/reload the browser window.

SQL: how to use UNION and order by a specific select?

SELECT id FROM a -- returns 1,4,2,3
UNION
SELECT id FROM b -- returns 2,1
order by 2,1

How do I add a simple onClick event handler to a canvas element?

As another cheap alternative on somewhat static canvas, using an overlaying img element with a usemap definition is quick and dirty. Works especially well on polygon based canvas elements like a pie chart.

What exactly is Apache Camel?

Apache Camel is a Java framework for Enterprise integration. Eg:- if you are building a web application which interacts with many vendor API's we can use the camel as the External integration tool. We can do more with it based on the use case. Camel in Action from Manning publications is a great book for learning Camel. The integrations can be defined as below.

Java DSL

from("jetty://0.0.0.0:8080/searchProduct").routeId("searchProduct.products").threads()
    .log(LoggingLevel.INFO, "searchProducts request Received with body: ${body}")
    .bean(Processor.class, "createSearchProductsRequest").removeHeaders("CamelHttp*")
    .setHeader(Exchange.HTTP_METHOD, constant(org.apache.camel.component.http4.HttpMethods.POST))
    .to("http4://" + preLiveBaseAPI + searchProductsUrl + "?apiKey=" + ApiKey
                    + "&bridgeEndpoint=true")
    .bean(Processor.class, "buildResponse").log(LoggingLevel.INFO, "Search products finished");

This is to just create a REST API endpoint which in turn calls an external API and sends the request back

Spring DSL

<route id="GROUPS-SHOW">
    <from uri="jetty://0.0.0.0:8080/showGroups" />
    <log loggingLevel="INFO" message="Reqeust receviced service to fetch groups -> ${body}" />
    <to uri="direct:auditLog" />
    <process ref="TestProcessor" />
</route>

Coming to your questions

  1. What exactly is it? Ans:- It is a framework which implements Enterprise integration patterns
  2. How does it interact with an application written in Java? Ans:- it can interact with any available protocols like http, ftp, amqp etc
  3. Is it something that goes together with the server? Ans:- It can be deployed in a container like tomcat or can be deployed independently as a java process
  4. Is it an independent program? Ans:- It can be.

Hope it helps

What is this spring.jpa.open-in-view=true property in Spring Boot?

The OSIV Anti-Pattern

Instead of letting the business layer decide how it’s best to fetch all the associations that are needed by the View layer, OSIV (Open Session in View) forces the Persistence Context to stay open so that the View layer can trigger the Proxy initialization, as illustrated by the following diagram.

enter image description here

  • The OpenSessionInViewFilter calls the openSession method of the underlying SessionFactory and obtains a new Session.
  • The Session is bound to the TransactionSynchronizationManager.
  • The OpenSessionInViewFilter calls the doFilter of the javax.servlet.FilterChain object reference and the request is further processed
  • The DispatcherServlet is called, and it routes the HTTP request to the underlying PostController.
  • The PostController calls the PostService to get a list of Post entities.
  • The PostService opens a new transaction, and the HibernateTransactionManager reuses the same Session that was opened by the OpenSessionInViewFilter.
  • The PostDAO fetches the list of Post entities without initializing any lazy association.
  • The PostService commits the underlying transaction, but the Session is not closed because it was opened externally.
  • The DispatcherServlet starts rendering the UI, which, in turn, navigates the lazy associations and triggers their initialization.
  • The OpenSessionInViewFilter can close the Session, and the underlying database connection is released as well.

At first glance, this might not look like a terrible thing to do, but, once you view it from a database perspective, a series of flaws start to become more obvious.

The service layer opens and closes a database transaction, but afterward, there is no explicit transaction going on. For this reason, every additional statement issued from the UI rendering phase is executed in auto-commit mode. Auto-commit puts pressure on the database server because each transaction issues a commit at end, which can trigger a transaction log flush to disk. One optimization would be to mark the Connection as read-only which would allow the database server to avoid writing to the transaction log.

There is no separation of concerns anymore because statements are generated both by the service layer and by the UI rendering process. Writing integration tests that assert the number of statements being generated requires going through all layers (web, service, DAO) while having the application deployed on a web container. Even when using an in-memory database (e.g. HSQLDB) and a lightweight webserver (e.g. Jetty), these integration tests are going to be slower to execute than if layers were separated and the back-end integration tests used the database, while the front-end integration tests were mocking the service layer altogether.

The UI layer is limited to navigating associations which can, in turn, trigger N+1 query problems. Although Hibernate offers @BatchSize for fetching associations in batches, and FetchMode.SUBSELECT to cope with this scenario, the annotations are affecting the default fetch plan, so they get applied to every business use case. For this reason, a data access layer query is much more suitable because it can be tailored to the current use case data fetch requirements.

Last but not least, the database connection is held throughout the UI rendering phase which increases connection lease time and limits the overall transaction throughput due to congestion on the database connection pool. The more the connection is held, the more other concurrent requests are going to wait to get a connection from the pool.

Spring Boot and OSIV

Unfortunately, OSIV (Open Session in View) is enabled by default in Spring Boot, and OSIV is really a bad idea from a performance and scalability perspective.

So, make sure that in the application.properties configuration file, you have the following entry:

spring.jpa.open-in-view=false

This will disable OSIV so that you can handle the LazyInitializationException the right way.

Starting with version 2.0, Spring Boot issues a warning when OSIV is enabled by default, so you can discover this problem long before it affects a production system.

SqlException: DB2 SQL error: SQLCODE: -302, SQLSTATE: 22001, SQLERRMC: null

As a general point when using a search engine to search for SQL codes make sure you put the sqlcode e.g. -302 in quote marks - like "-302" otherwise the search engine will exclude all search results including the text 302, since the - sign is used to exclude results.

Change default date time format on a single database in SQL Server

If this really is a QA issue and you can't change the code. Setup a new server instance on the machine and setup the language as "British English"

Word wrapping in phpstorm

For all files (default setting for opened file): Settings/Preferences | Editor | General | Use soft wraps in editor

For currently opened file in editor: Menu | View | Active Editor | Use Soft Wraps


In latest IDE versions you can also access this option via context menu for the editor gutter area (the area with line numbers on the left side of the editor).

Search Everywhere (Shift 2x times) or Help | Find Action... ( Ctrl + Shift+ A on Windows using Default keymap) can also be used to quickly change this option (instead of going into Settings/Preferences).

How to access List elements

Tried list[:][0] to show all first member of each list inside list is not working. Result is unknowingly will same as list[0][:]

So i use list comprehension like this:

[i[0] for i in list] which return first element value for each list inside list.

How to automatically crop and center an image

Try this: Set your image crop dimensions and use this line in your CSS:

object-fit: cover;

How to delete all files and folders in a folder by cmd call

No, I don't know one.

If you want to retain the original directory for some reason (ACLs, &c.), and instead really want to empty it, then you can do the following:

del /q destination\*
for /d %x in (destination\*) do @rd /s /q "%x"

This first removes all files from the directory, and then recursively removes all nested directories, but overall keeping the top-level directory as it is (except for its contents).

Note that within a batch file you need to double the % within the for loop:

del /q destination\*
for /d %%x in (destination\*) do @rd /s /q "%%x"

How do you count the elements of an array in java

If you assume that 0 is not a valid item in the array then the following code should work:

   public static void main( String[] args )
   {
      int[] theArray = new int[20];
      theArray[0] = 1;
      theArray[1] = 2;

      System.out.println(count(theArray));
   }

   private static int count(int[] array) 
   {
      int count = 0;
      for(int i : array)
      {
         if(i > 0)
         {
            count++;
         }
      }
      return count;
   }

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

In my case if you are using UITableView do not forget to add UITableViewDelegate and UITableViewDataSource next to viewcontroller like this. class MenuController: UIViewController, UITableViewDelegate, UITableViewDataSource

When converting old projects (written in Swift 2.3) to Swift 3 it needs adding these keywords.

Passing command line arguments to R CMD BATCH

Here's another way to process command line args, using R CMD BATCH. My approach, which builds on an earlier answer here, lets you specify arguments at the command line and, in your R script, give some or all of them default values.

Here's an R file, which I name test.R:

defaults <- list(a=1, b=c(1,1,1)) ## default values of any arguments we might pass

## parse each command arg, loading it into global environment
for (arg in commandArgs(TRUE))
  eval(parse(text=arg))

## if any variable named in defaults doesn't exist, then create it
## with value from defaults
for (nm in names(defaults))
  assign(nm, mget(nm, ifnotfound=list(defaults[[nm]]))[[1]])

print(a)
print(b)

At the command line, if I type

R CMD BATCH --no-save --no-restore '--args a=2 b=c(2,5,6)' test.R

then within R we'll have a = 2 and b = c(2,5,6). But I could, say, omit b, and add in another argument c:

R CMD BATCH --no-save --no-restore '--args a=2 c="hello"' test.R

Then in R we'll have a = 2, b = c(1,1,1) (the default), and c = "hello".

Finally, for convenience we can wrap the R code in a function, as long as we're careful about the environment:

## defaults should be either NULL or a named list
parseCommandArgs <- function(defaults=NULL, envir=globalenv()) {
  for (arg in commandArgs(TRUE))
    eval(parse(text=arg), envir=envir)

  for (nm in names(defaults))
    assign(nm, mget(nm, ifnotfound=list(defaults[[nm]]), envir=envir)[[1]], pos=envir)
}

## example usage:
parseCommandArgs(list(a=1, b=c(1,1,1)))

Add CSS3 transition expand/collapse

this should work, had to try a while too.. :D

_x000D_
_x000D_
function showHide(shID) {_x000D_
  if (document.getElementById(shID)) {_x000D_
    if (document.getElementById(shID + '-show').style.display != 'none') {_x000D_
      document.getElementById(shID + '-show').style.display = 'none';_x000D_
      document.getElementById(shID + '-hide').style.display = 'inline';_x000D_
      document.getElementById(shID).style.height = '100px';_x000D_
    } else {_x000D_
      document.getElementById(shID + '-show').style.display = 'inline';_x000D_
      document.getElementById(shID + '-hide').style.display = 'none';_x000D_
      document.getElementById(shID).style.height = '0px';_x000D_
    }_x000D_
  }_x000D_
}
_x000D_
#example {_x000D_
  background: red;_x000D_
  height: 0px;_x000D_
  overflow: hidden;_x000D_
  transition: height 2s;_x000D_
  -moz-transition: height 2s;_x000D_
  /* Firefox 4 */_x000D_
  -webkit-transition: height 2s;_x000D_
  /* Safari and Chrome */_x000D_
  -o-transition: height 2s;_x000D_
  /* Opera */_x000D_
}_x000D_
_x000D_
a.showLink,_x000D_
a.hideLink {_x000D_
  text-decoration: none;_x000D_
  background: transparent url('down.gif') no-repeat left;_x000D_
}_x000D_
_x000D_
a.hideLink {_x000D_
  background: transparent url('up.gif') no-repeat left;_x000D_
}
_x000D_
Here is some text._x000D_
<div class="readmore">_x000D_
  <a href="#" id="example-show" class="showLink" onclick="showHide('example');return false;">Read more</a>_x000D_
  <div id="example" class="more">_x000D_
    <div class="text">_x000D_
      Here is some more text: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum vitae urna nulla. Vivamus a purus mi. In hac habitasse platea dictumst. In ac tempor quam. Vestibulum eleifend vehicula ligula, et cursus nisl gravida sit amet._x000D_
      Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas._x000D_
    </div>_x000D_
    <p>_x000D_
      <a href="#" id="example-hide" class="hideLink" onclick="showHide('example');return false;">Hide</a>_x000D_
    </p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Redirect from asp.net web api post action

You can check this

[Route("Report/MyReport")]
public IHttpActionResult GetReport()
{

   string url = "https://localhost:44305/Templates/ReportPage.html";

   System.Uri uri = new System.Uri(url);

   return Redirect(uri);
}

Callback when DOM is loaded in react.js

In modern browsers, it should be like

try() {
     if (!$("#element").size()) {
       window.requestAnimationFrame(try);
     } else {
       // do your stuff
     }
};

componentDidMount(){
     this.try();
}

Textfield with only bottom border

See this JSFiddle

_x000D_
_x000D_
 input[type="text"]_x000D_
    {_x000D_
        border: 0;_x000D_
        border-bottom: 1px solid red;_x000D_
        outline: 0;_x000D_
    }
_x000D_
<form>_x000D_
        <input type="text" value="See! ONLY BOTTOM BORDER!" />_x000D_
    </form>
_x000D_
_x000D_
_x000D_

How to change the default collation of a table?

may need to change the SCHEMA not only table

ALTER SCHEMA `<database name>`  DEFAULT CHARACTER SET utf8mb4  DEFAULT COLLATE utf8mb4_unicode_ci (as Rich said - utf8mb4);

(mariaDB 10)

Opening port 80 EC2 Amazon web services

This is actually really easy:

  • Go to the "Network & Security" -> Security Group settings in the left hand navigation
  • Find the Security Group that your instance is apart of
  • Click on Inbound Rules
  • Use the drop down and add HTTP (port 80)
  • Click Apply and enjoy

How to click on hidden element in Selenium WebDriver?

overflow:hidden 

does not always mean that the element is hidden or non existent in the DOM, it means that the overflowing chars that do not fit in the element are being trimmed. Basically it means that do not show scrollbar even if it should be showed, so in your case the link with text

Plastic Spiral Bind

could possibly be shown as "Plastic Spir..." or similar. So it is possible, that this linkText indeed is non existent.

So you can probably try:

driver.findElement(By.partialLinkText("Plastic ")).click();

or xpath:

//a[contains(@title, \"Plastic Spiral Bind\")]

Redirect stderr to stdout in C shell

   xxx >& filename

Or do this to see everything on the screen and have it go to your file:

  xxx | & tee ./logfile

How to check permissions of a specific directory?

In addition to the above posts, i'd like to point out that "man ls" will give you a nice manual about the "ls" ( List " command.

Also, using ls -la myFile will list & show all the facts about that file.

jQuery see if any or no checkboxes are selected

You can do this:

  if ($('#form_id :checkbox:checked').length > 0){
    // one or more checkboxes are checked
  }
  else{
   // no checkboxes are checked
  }

Where:

  • :checkbox filter selector selects all checkbox.
  • :checked will select checked checkboxes
  • length will give the number of checked ones there

An item with the same key has already been added

I faced similar exception. Check if all columns has header names( from select query in database) with exactly matching property names in model class.

How to make a programme continue to run after log out from ssh?

You should try using nohup and running it in the background:

nohup sleep 3600 &

Get name of property as a string

You can use the StackTrace class to get the name of the current function, (or if you put the code in a function, then step down a level and get the calling function).

See http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace(VS.71).aspx

How do I import global modules in Node? I get "Error: Cannot find module <module>"?

Node.js uses the environmental variable NODE_PATH to allow for specifying additional directories to include in the module search path. You can use npm itself to tell you where global modules are stored with the npm root -g command. So putting those two together, you can make sure global modules are included in your search path with the following command (on Linux-ish)

export NODE_PATH=$(npm root --quiet -g)

Use of contains in Java ArrayList<String>

You're correct. As others said according to your comments, you probably did not initialize your ArrayList.

My point is different: you claimed that you're checking for duplicates and this is why you call the contains method. Try using HashSet. It should be more efficient - unless you need to keep the order of URLs for any reason.

scp via java

Here is an example to upload a file using JSch:

ScpUploader.java:

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

import java.io.ByteArrayInputStream;
import java.util.Properties;

public final class ScpUploader
{
    public static ScpUploader newInstance()
    {
        return new ScpUploader();
    }

    private volatile Session session;
    private volatile ChannelSftp channel;

    private ScpUploader(){}

    public synchronized void connect(String host, int port, String username, String password) throws JSchException
    {
        JSch jsch = new JSch();

        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");

        session = jsch.getSession(username, host, port);
        session.setPassword(password);
        session.setConfig(config);
        session.setInputStream(System.in);
        session.connect();

        channel = (ChannelSftp) session.openChannel("sftp");
        channel.connect();
    }

    public synchronized void uploadFile(String directoryPath, String fileName, byte[] fileBytes, boolean overwrite) throws SftpException
    {
        if(session == null || channel == null)
        {
            System.err.println("No open session!");
            return;
        }

        // a workaround to check if the directory exists. Otherwise, create it
        channel.cd("/");
        String[] directories = directoryPath.split("/");
        for(String directory : directories)
        {
            if(directory.length() > 0)
            {
                try
                {
                    channel.cd(directory);
                }
                catch(SftpException e)
                {
                    // swallowed exception

                    System.out.println("The directory (" + directory + ") seems to be not exist. We will try to create it.");

                    try
                    {
                        channel.mkdir(directory);
                        channel.cd(directory);
                        System.out.println("The directory (" + directory + ") is created successfully!");
                    }
                    catch(SftpException e1)
                    {
                        System.err.println("The directory (" + directory + ") is failed to be created!");
                        e1.printStackTrace();
                        return;
                    }

                }
            }
        }

        channel.put(new ByteArrayInputStream(fileBytes), directoryPath + "/" + fileName, overwrite ? ChannelSftp.OVERWRITE : ChannelSftp.RESUME);
    }

    public synchronized void disconnect()
    {
        if(session == null || channel == null)
        {
            System.err.println("No open session!");
            return;
        }

        channel.exit();
        channel.disconnect();
        session.disconnect();

        channel = null;
        session = null;
    }
}

AppEntryPoint.java:

import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public final class AppEntryPoint
{
    private static final String HOST = "192.168.1.1";
    private static final int PORT = 22;
    private static final String USERNAME = "root";
    private static final String PASSWORD = "root";

    public static void main(String[] args) throws IOException
    {
        ScpUploader scpUploader = ScpUploader.newInstance();

        try
        {
            scpUploader.connect(HOST, PORT, USERNAME, PASSWORD);
        }
        catch(JSchException e)
        {
            System.err.println("Failed to connect the server!");
            e.printStackTrace();
            return;
        }

        System.out.println("Successfully connected to the server!");

        byte[] fileBytes = Files.readAllBytes(Paths.get("C:/file.zip"));

        try
        {
            scpUploader.uploadFile("/test/files", "file.zip", fileBytes, true); // if overwrite == false, it won't throw exception if the file exists
            System.out.println("Successfully uploaded the file!");
        }
        catch(SftpException e)
        {
            System.err.println("Failed to upload the file!");
            e.printStackTrace();
        }

        scpUploader.disconnect();
    }
}

How to Export Private / Secret ASC Key to Decrypt GPG Files

1.Export a Secret Key (this is what your boss should have done for you)

gpg --export-secret-keys yourKeyName > privateKey.asc

2.Import Secret Key (import your privateKey)

gpg --import privateKey.asc

3.Not done yet, you still need to ultimately trust a key. You will need to make sure that you also ultimately trust a key.

gpg --edit-key yourKeyName

Enter trust, 5, y, and then quit

Source: https://medium.com/@GalarnykMichael/public-key-asymmetric-cryptography-using-gpg-5a8d914c9bca

Generate a range of dates using SQL

This query generates a list of dates 4000 days in the future and 5000 in the past as of today (inspired on http://blogs.x2line.com/al/articles/207.aspx):

SELECT * FROM (SELECT
    (CONVERT(SMALLDATETIME, CONVERT(CHAR,GETDATE() ,103)) + 4000 -
                n4.num * 1000 -
                n3.num * 100 -
                n2.num * 10 -
                n1.num) AS Date, 
    year(CONVERT(SMALLDATETIME, CONVERT(CHAR,GETDATE() ,103)) + 4000 -
                n4.num * 1000 -
                n3.num * 100 -
                n2.num * 10 -
                n1.num) as Year,
    month(CONVERT(SMALLDATETIME, CONVERT(CHAR,GETDATE() ,103)) + 4000 -
                n4.num * 1000 -
                n3.num * 100 -
                n2.num * 10 -
                n1.num) as Month,
    day(CONVERT(SMALLDATETIME, CONVERT(CHAR,GETDATE() ,103)) + 4000 -
                n4.num * 1000 -
                n3.num * 100 -
                n2.num * 10 -
                n1.num) as Day
           FROM (SELECT 0 AS num union ALL
                 SELECT 1 UNION ALL
                 SELECT 2 UNION ALL
                 SELECT 3 UNION ALL
                 SELECT 4 UNION ALL
                 SELECT 5 UNION ALL
                 SELECT 6 UNION ALL
                 SELECT 7 UNION ALL
                 SELECT 8 UNION ALL
                 SELECT 9) n1
               ,(SELECT 0 AS num UNION ALL
                 SELECT 1 UNION ALL
                 SELECT 2 UNION ALL
                 SELECT 3 UNION ALL
                 SELECT 4 UNION ALL
                 SELECT 5 UNION ALL
                 SELECT 6 UNION ALL
                 SELECT 7 UNION ALL
                 SELECT 8 UNION ALL
                 SELECT 9) n2
               ,(SELECT 0 AS num union ALL
                 SELECT 1 UNION ALL
                 SELECT 2 UNION ALL
                 SELECT 3 UNION ALL
                 SELECT 4 UNION ALL
                 SELECT 5 UNION ALL
                 SELECT 6 UNION ALL
                 SELECT 7 UNION ALL
                 SELECT 8 UNION ALL
                 SELECT 9) n3  
               ,(SELECT 0 AS num UNION ALL
                 SELECT 1 UNION ALL
                 SELECT 2 UNION ALL
                 SELECT 3 UNION ALL
                 SELECT 4 UNION ALL
                 SELECT 5 UNION ALL
                 SELECT 6 UNION ALL
                 SELECT 7 UNION ALL
                 SELECT 8) n4
        ) GenCalendar  ORDER BY 1

How can I set the maximum length of 6 and minimum length of 6 in a textbox?

Addition to Alex' answer:

JavaScript

$(function() {
    $('input[type="submit"]').prop('disabled', true);
    $('#check').on('input', function(e) {
        if(this.value.length === 6) {
            $('input[type="submit"]').prop('disabled', false);
        } else {
            $('input[type="submit"]').prop('disabled', true);
        }
    });
});

HTML

<input type="text" maxlength="6" id="check" data-minlength="6" /><br />
<input type="submit" value="send" />

JsFiddle

But: You should always remember to validate the user input on the server side again. The user could modify the local HTML or disable JavaScript.

AngularJS ng-style with a conditional expression

simple example:

<div ng-style="isTrue && {'background-color':'green'} || {'background-color': 'blue'}" style="width:200px;height:100px;border:1px solid gray;"></div>

{'background-color':'green'} RETURN true

OR the same result:

<div ng-style="isTrue && {'background-color':'green'}" style="width:200px;height:100px;border:1px solid gray;background-color: blue"></div>

other conditional possibility:

<div ng-style="count === 0 && {'background-color':'green'}  || count === 1 && {'background-color':'yellow'}" style="width:200px;height:100px;border:1px solid gray;background-color: blue"></div>

refresh div with jquery

I want to just refresh the div, without refreshing the page ... Is this possible?

Yes, though it isn't going to be obvious that it does anything unless you change the contents of the div.

If you just want the graphical fade-in effect, simply remove the .html(data) call:

$("#panel").hide().fadeIn('fast');

Here is a demo you can mess around with: http://jsfiddle.net/ZPYUS/

It changes the contents of the div without making an ajax call to the server, and without refreshing the page. The content is hard coded, though. You can't do anything about that fact without contacting the server somehow: ajax, some sort of sub-page request, or some sort of page refresh.

html:

<div id="panel">test data</div>
<input id="changePanel" value="Change Panel" type="button">?

javascript:

$("#changePanel").click(function() {
    var data = "foobar";
    $("#panel").hide().html(data).fadeIn('fast');
});?

css:

div {
    padding: 1em;
    background-color: #00c000;
}

input {
    padding: .25em 1em;
}?

How to set a Javascript object values dynamically?

simple as this myObj.name = value;

How do I call an Angular 2 pipe with multiple arguments?

You're missing the actual pipe.

{{ myData | date:'fullDate' }}

Multiple parameters can be separated by a colon (:).

{{ myData | myPipe:'arg1':'arg2':'arg3' }}

Also you can chain pipes, like so:

{{ myData | date:'fullDate' | myPipe:'arg1':'arg2':'arg3' }}

Convert string to decimal number with 2 decimal places in Java

I just want to be sure that the float number will also have 2 decimal places after converting that string.

You can't, because floating point numbers don't have decimal places. They have binary places, which aren't commensurate with decimal places.

If you want decimal places, use a decimal radix.

Where are logs located?

  • Ensure debug mode is on - either add APP_DEBUG=true to .env file or set an environment variable

  • Log files are in storage/logs folder. laravel.log is the default filename. If there is a permission issue with the log folder, Laravel just halts. So if your endpoint generally works - permissions are not an issue.

  • In case your calls don't even reach Laravel or aren't caused by code issues - check web server's log files (check your Apache/nginx config files to see the paths).

  • If you use PHP-FPM, check its log files as well (you can see the path to log file in PHP-FPM pool config).

Conditionally change img src based on model data

Another way ..

<img ng-src="{{!video.playing ? 'img/icons/play-rounded-button-outline.svg' : 'img/icons/pause-thin-rounded-button.svg'}}" />

How to convert a string of numbers to an array of numbers?

You can use JSON.parse, adding brakets to format Array

_x000D_
_x000D_
const a = "1,2,3,4";
const myArray = JSON.parse(`[${a}]`)
console.log(myArray)
console.info('pos 2 = ',  myArray[2])
_x000D_
_x000D_
_x000D_

Not able to change TextField Border Color

The best and most effective solution is just adding theme in your main class and add input decoration like these.

theme: ThemeData(
    inputDecorationTheme: InputDecorationTheme(
        border: OutlineInputBorder(
           borderSide: BorderSide(color: Colors.pink)
        )
    ),
)

HTML table needs spacing between columns, not rows

<table cellpadding="pixels"cellspacing="pixels"></table>
<td align="position"valign="position"></td>

cellpadding="length in pixels" ~ The cellpadding attribute, used in the <table> tag, specifies how much blank space to display in between the content of each table cell and its respective border. The value is defined as a length in pixels. Hence, a cellpadding="10" attribute-value pair will display 10 pixels of blank space on all four sides of the content of each cell in that table.

cellspacing="length in pixels" ~ The cellspacing attribute, also used in the <table> tag, defines how much blank space to display in between adjacent table cells and in between table cells and the table border. The value is defined as a length in pixels. Hence, a cellspacing="10" attribute-value pair will horizontally and vertically separate all adjacent cells in the respective table by a length of 10 pixels. It will also offset all cells from the table's frame on all four sides by a length of 10 pixels.

Updating a dataframe column in spark

While you cannot modify a column as such, you may operate on a column and return a new DataFrame reflecting that change. For that you'd first create a UserDefinedFunction implementing the operation to apply and then selectively apply that function to the targeted column only. In Python:

from pyspark.sql.functions import UserDefinedFunction
from pyspark.sql.types import StringType

name = 'target_column'
udf = UserDefinedFunction(lambda x: 'new_value', StringType())
new_df = old_df.select(*[udf(column).alias(name) if column == name else column for column in old_df.columns])

new_df now has the same schema as old_df (assuming that old_df.target_column was of type StringType as well) but all values in column target_column will be new_value.

How to know which is running in Jupyter notebook?

from platform import python_version

print(python_version())

This will give you the exact version of python running your script. eg output:

3.6.5

How to expand textarea width to 100% of parent (or how to expand any HTML element to 100% of parent width)?

HTML:

<div id="left"></div>
<div id="content">
        <textarea cols="2" rows="10" id="rules"></textarea>
</div>

CSS:

body{
    width:100%;
    border:1px solid black;
    border-radius:5px;

}
#left{
    width:20%;
height:400px;
    float:left;
    border: 1px solid black;
    display:block;
}
#content{
    width:78%;
    height:400px;
    float:left;
    border:1px solid black;
    text-align:center;
}
textarea
{
   margin-top:100px;
    width:98%;
}

DEMO: HERE

References with text in LaTeX

I think you can do this with the hyperref package, although I've not tried it myself. From the relevant LaTeX Wikibook section:

The hyperref package introduces another useful command; \autoref{}. This command creates a reference with additional text corresponding to the targets type, all of which will be a hyperlink. For example, the command \autoref{sec:intro} would create a hyperlink to the \label{sec:intro} command, wherever it is. Assuming that this label is pointing to a section, the hyperlink would contain the text "section 3.4", or similar (capitalization rules will be followed, which makes this very convenient). You can customize the prefixed text by redefining \typeautorefname to the prefix you want, as in:

\def\subsectionautorefname{section}

MySQL "Group By" and "Order By"

A simple solution is to wrap the query into a subselect with the ORDER statement first and applying the GROUP BY later:

SELECT * FROM ( 
    SELECT `timestamp`, `fromEmail`, `subject`
    FROM `incomingEmails` 
    ORDER BY `timestamp` DESC
) AS tmp_table GROUP BY LOWER(`fromEmail`)

This is similar to using the join but looks much nicer.

Using non-aggregate columns in a SELECT with a GROUP BY clause is non-standard. MySQL will generally return the values of the first row it finds and discard the rest. Any ORDER BY clauses will only apply to the returned column value, not to the discarded ones.

IMPORTANT UPDATE Selecting non-aggregate columns used to work in practice but should not be relied upon. Per the MySQL documentation "this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate."

As of 5.7.5 ONLY_FULL_GROUP_BY is enabled by default so non-aggregate columns cause query errors (ER_WRONG_FIELD_WITH_GROUP)

As @mikep points out below the solution is to use ANY_VALUE() from 5.7 and above

See http://www.cafewebmaster.com/mysql-order-sort-group https://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_any-value

Regular Expression: Any character that is NOT a letter or number

You are looking for:

var yourVar = '1324567890abc§$)%';
yourVar = yourVar.replace(/[^a-zA-Z0-9]/g, ' ');

This replaces all non-alphanumeric characters with a space.

The "g" on the end replaces all occurrences.

Instead of specifying a-z (lowercase) and A-Z (uppercase) you can also use the in-case-sensitive option: /[^a-z0-9]/gi.

List distinct values in a vector in R

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

Example:

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

Hope that helps.

How to break nested loops in JavaScript?

The another trick is by setting the parent loop to reach the end and then break the current loop

function foo()
{
    for(var k = 0; k < 4; k++){
        for(var m = 0; m < 4; m++){
            if(m == 2){
                k = 5; // Set this then break
                break;
            }
          console.log(m);
        }
    }
}

How to solve "Could not establish trust relationship for the SSL/TLS secure channel with authority"

If you are using .net core, then during development you can bypass certificate validation by using compiler directives. This way will only validate certificate for release and not for debug:

#if (DEBUG)
        client.ClientCredentials.ServiceCertificate.SslCertificateAuthentication =
                new X509ServiceCertificateAuthentication()
                {
                    CertificateValidationMode = X509CertificateValidationMode.None,
                    RevocationMode = System.Security.Cryptography.X509Certificates.X509RevocationMode.NoCheck
                };   #endif

Random Number Between 2 Double Numbers

Use a static Random or the numbers tend to repeat in tight/fast loops due to the system clock seeding them.

public static class RandomNumbers
{
    private static Random random = new Random();
    //=-------------------------------------------------------------------
    // double between min and the max number
    public static double RandomDouble(int min, int max) 
    {
        return (random.NextDouble() * (max - min)) + min;
    }
    //=----------------------------------
    // double between 0 and the max number
    public static double RandomDouble(int max) 
    {
        return (random.NextDouble() * max);
    }
    //=-------------------------------------------------------------------
    // int between the min and the max number
    public static int RandomInt(int min, int max) 
    {   
        return random.Next(min, max + 1);
    }
    //=----------------------------------
    // int between 0 and the max number
    public static int RandomInt(int max) 
    {
        return random.Next(max + 1);
    }
    //=-------------------------------------------------------------------
 }

See also : https://docs.microsoft.com/en-us/dotnet/api/system.random?view=netframework-4.8

CSS @font-face not working in ie

I read a lot of tutorials that suggested hacks, so I came up with this solution I think is better... It seems to work fine.

@font-face { 
    font-family: MyFont; src: url('myfont.ttf'); 
}
@font-face{ 
    font-family: MyFont_IE; src: url('myfont.eot'); 
}
.my_font{ 
    font-family: MyFont, MyFont_IE, Arial, Helvetica, sans-serif; 
}

How do I disable TextBox using JavaScript?

You can use disabled attribute to disable the textbox.

document.getElementById('color').disabled = true;

Return empty cell from formula in Excel

This is how I did it for the dataset I was using. It seems convoluted and stupid, but it was the only alternative to learning how to use the VB solution mentioned above.

  1. I did a "copy" of all the data, and pasted the data as "values".
  2. Then I highlighted the pasted data and did a "replace" (Ctrl-H) the empty cells with some letter, I chose q since it wasn't anywhere on my data sheet.
  3. Finally, I did another "replace", and replaced q with nothing.

This three step process turned all of the "empty" cells into "blank" cells". I tried merging steps 2 & 3 by simply replacing the blank cell with a blank cell, but that didn't work--I had to replace the blank cell with some kind of actual text, then replace that text with a blank cell.

Applying function with multiple arguments to create a new pandas column

You can go with @greenAfrican example, if it's possible for you to rewrite your function. But if you don't want to rewrite your function, you can wrap it into anonymous function inside apply, like this:

>>> def fxy(x, y):
...     return x * y

>>> df['newcolumn'] = df.apply(lambda x: fxy(x['A'], x['B']), axis=1)
>>> df
    A   B  newcolumn
0  10  20        200
1  20  30        600
2  30  10        300

ITextSharp insert text to an existing pdf

Here is a method that uses stamper and absolute coordinates showed in the different PDF clients (Adobe, FoxIt and etc. )

public static void AddTextToPdf(string inputPdfPath, string outputPdfPath, string textToAdd, System.Drawing.Point point)
    {
        //variables
        string pathin = inputPdfPath;
        string pathout = outputPdfPath;

        //create PdfReader object to read from the existing document
        using (PdfReader reader = new PdfReader(pathin))
        //create PdfStamper object to write to get the pages from reader 
        using (PdfStamper stamper = new PdfStamper(reader, new FileStream(pathout, FileMode.Create)))
        {
            //select two pages from the original document
            reader.SelectPages("1-2");

            //gettins the page size in order to substract from the iTextSharp coordinates
            var pageSize = reader.GetPageSize(1);

            // PdfContentByte from stamper to add content to the pages over the original content
            PdfContentByte pbover = stamper.GetOverContent(1);

            //add content to the page using ColumnText
            Font font = new Font();
            font.Size = 45;

            //setting up the X and Y coordinates of the document
            int x = point.X;
            int y = point.Y;

            y = (int) (pageSize.Height - y);

            ColumnText.ShowTextAligned(pbover, Element.ALIGN_CENTER, new Phrase(textToAdd, font), x, y, 0);
        }
    }

List of Stored Procedures/Functions Mysql Command Line

Shows all the stored procedures:

SHOW PROCEDURE STATUS;

Shows all the functions:

SHOW FUNCTION STATUS;

Shows the definition of the specified procedure:

SHOW CREATE PROCEDURE [PROC_NAME];

Shows you all the procedures of the given database:

SHOW PROCEDURE STATUS WHERE Db = '[db_name]';

Detecting iOS orientation change instantly

For my case handling UIDeviceOrientationDidChangeNotification was not good solution as it is called more frequent and UIDeviceOrientation is not always equal to UIInterfaceOrientation because of (FaceDown, FaceUp).

I handle it using UIApplicationDidChangeStatusBarOrientationNotification:

//To add the notification
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didChangeOrientation:)

//to remove the
[[NSNotificationCenter defaultCenter]removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];

 ...

- (void)didChangeOrientation:(NSNotification *)notification
{
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;

    if (UIInterfaceOrientationIsLandscape(orientation)) {
        NSLog(@"Landscape");
    }
    else {
        NSLog(@"Portrait");
    }
}

remove first element from array and return the array minus the first element

Why not use ES6?

_x000D_
_x000D_
 var myarray = ["item 1", "item 2", "item 3", "item 4"];_x000D_
 const [, ...rest] = myarray;_x000D_
 console.log(rest)
_x000D_
_x000D_
_x000D_

RegEx to exclude a specific string constant

In .NET you can use grouping to your advantage like this:

http://regexhero.net/tester/?id=65b32601-2326-4ece-912b-6dcefd883f31

You'll notice that:

(ABC)|(.)

Will grab everything except ABC in the 2nd group. Parenthesis surround each group. So (ABC) is group 1 and (.) is group 2.

So you just grab the 2nd group like this in a replace:

$2

Or in .NET look at the Groups collection inside the Regex class for a little more control.

You should be able to do something similar in most other regex implementations as well.

UPDATE: I found a much faster way to do this here: http://regexhero.net/tester/?id=997ce4a2-878c-41f2-9d28-34e0c5080e03

It still uses grouping (I can't find a way that doesn't use grouping). But this method is over 10X faster than the first.

How can I get a vertical scrollbar in my ListBox?

I was having the same problem, I had a ComboBox followed by a ListBox in a StackPanel and the scroll bar for the ListBox was not showing up. I solved this by putting the two in a DockPanel instead. I set the ComboBox DockPanel.Dock="Top" and let the ListBox fill the remaining space.

Media Queries: How to target desktop, tablet, and mobile?

It's not a matter of pixels count, it's a matter of actual size (in mm or inches) of characters on the screen, which depends on pixels density. Hence "min-width:" and "max-width:" are useless. A full explanation of this issue is here: what exactly is device pixel ratio?

"@media" queries take into account the pixels count and the device pixel ratio, resulting in a "virtual resolution" which is what you have to actually take into account while designing your page: if your font is 10px fixed-width and the "virtual horizontal resolution" is 300 px, 30 characters will be needed to fill a line.

Converting to upper and lower case in Java

WordUtils.capitalizeFully(str) from apache commons-lang has the exact semantics as required.

Parse json string using JSON.NET

If your keys are dynamic I would suggest deserializing directly into a DataTable:

    class SampleData
    {
        [JsonProperty(PropertyName = "items")]
        public System.Data.DataTable Items { get; set; }
    }

    public void DerializeTable()
    {
        const string json = @"{items:["
            + @"{""Name"":""AAA"",""Age"":""22"",""Job"":""PPP""},"
            + @"{""Name"":""BBB"",""Age"":""25"",""Job"":""QQQ""},"
            + @"{""Name"":""CCC"",""Age"":""38"",""Job"":""RRR""}]}";
        var sampleData = JsonConvert.DeserializeObject<SampleData>(json);
        var table = sampleData.Items;

        // write tab delimited table without knowing column names
        var line = string.Empty;
        foreach (DataColumn column in table.Columns)            
            line += column.ColumnName + "\t";                       
        Console.WriteLine(line);

        foreach (DataRow row in table.Rows)
        {
            line = string.Empty;
            foreach (DataColumn column in table.Columns)                
                line += row[column] + "\t";                                   
            Console.WriteLine(line);
        }

        // Name   Age   Job    
        // AAA    22    PPP    
        // BBB    25    QQQ    
        // CCC    38    RRR    
    }

You can determine the DataTable column names and types dynamically once deserialized.

dispatch_after - GCD in Swift?

In Swift 5, use in the below:

 DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: closure) 

// time gap, specify unit is second
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) {
            Singleton.shared().printDate()
        }
// default time gap is second, you can reduce it
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
          // just do it!
    }

Hive insert query like SQL

There are few properties to set to make a Hive table support ACID properties and to insert the values into tables as like in SQL .

Conditions to create a ACID table in Hive.

  1. The table should be stored as ORC file. Only ORC format can support ACID prpoperties for now.
  2. The table must be bucketed

Properties to set to create ACID table:

set hive.support.concurrency =true;
set hive.enforce.bucketing =true;
set hive.exec.dynamic.partition.mode =nonstrict
set hive.compactor.initiator.on = true;
set hive.compactor.worker.threads= 1;
set hive.txn.manager = org.apache.hadoop.hive.ql.lockmgr.DbTxnManager;

set the property hive.in.test to true in hive.site.xml

After setting all these properties , the table should be created with tblproperty 'transactional' ='true'. The table should be bucketed and saved as orc

CREATE TABLE table_name (col1 int,col2 string, col3 int) CLUSTERED BY col1 INTO 4 

BUCKETS STORED AS orc tblproperties('transactional' ='true');

Now its possible to inserte values into the table like SQL query.

INSERT INTO TABLE table_name VALUES (1,'a',100),(2,'b',200),(3,'c',300);

How to use an output parameter in Java?

Wrap the value passed in different classes that might be helpful doing the trick, check below for more real example:

  class Ref<T>{

    T s;

    public void set(T value){
        s =  value;
    }

    public T get(){
        return s;
    }

    public Ref(T value) {
        s = value;
    }
}


class Out<T>{

    T s;

    public void set(T value){
        s =  value;
    }
    public T get(){
        return s;
    }

    public Out() {
    }
}

public static void doAndChangeRefs (Ref<String> str, Ref<Integer> i, Out<String> str2){
    //refs passed .. set value
    str.set("def");
    i.set(10);

    //out param passed as null .. instantiate and set 
    str2 = new Out<String>();
    str2.set("hello world");
}
public static void main(String args[]) {
        Ref<Integer>  iRef = new Ref<Integer>(11);
        Out<String> strOut = null; 
        doAndChangeRefs(new Ref<String>("test"), iRef, strOut);
        System.out.println(iRef.get());
        System.out.println(strOut.get());

    }

Bootstrap 4 card-deck with number of columns based on viewport

Using Bootstrap 4.4.1, I was able to set the number of cards per deck using simple classes by adding some scss into the mix.

HTML

<div class="card-deck deck-1 deck-md-2 deck-lg-3">
   <div class="card">
      <h2 class="card-header">Card 1</h3>
      <div class="card-body">
          Card body
      </div>
      <div class="card-footer">
          Card footer
      </div>
   </div>
   <div class="card">
      <h2 class="card-header">Card 2</h3>
      <div class="card-body">
          Card body
      </div>
      <div class="card-footer">
          Card footer
      </div>
   </div>
   <div class="card">
      <h2 class="card-header">Card 3</h3>
      <div class="card-body">
          Card body
      </div>
      <div class="card-footer">
          Card footer
      </div>
   </div>
</div>

SCSS

// _card_deck_columns.scss
// add deck-X and deck-BP-X classes to select the number of cards per line
@for $i from 1 through $grid-columns {
  .deck-#{$i} > .card {
    $percentage: percentage(1 / $i);
    @if $i == 1 {
      $width: $percentage;
      flex-basis: $width;
      max-width: $width;
      margin-left: 0;
      margin-right: 0;
    } @else {
      $width: unquote("calc(#{$percentage} - #{$grid-gutter-width})");
      flex-basis: $width;
      max-width: $width;
    }
  }
}
@each $breakpoint in map-keys($grid-breakpoints) {
  $infix: breakpoint-infix($breakpoint, $grid-breakpoints);
  @include media-breakpoint-up($breakpoint) {
    @for $i from 1 through $grid-columns {
      .deck#{$infix}-#{$i} > .card {
        $percentage: percentage(1 / $i);
        @if $i == 1 {
          $width: $percentage;
          flex-basis: $width;
          max-width: $width;
          margin-left: 0;
          margin-right: 0;
        } @else {
          $width: unquote("calc(#{$percentage} - #{$grid-gutter-width})");
          flex-basis: $width;
          max-width: $width;
          margin-left: $grid-gutter-width / 2;
          margin-right: $grid-gutter-width / 2;
        }
      }
    }
  }
}

CSS

.deck-1 > .card {
  flex-basis: 100%;
  max-width: 100%;
  margin-left: 0;
  margin-right: 0; }

.deck-2 > .card {
  flex-basis: calc(50% - 30px);
  max-width: calc(50% - 30px); }

.deck-3 > .card {
  flex-basis: calc(33.3333333333% - 30px);
  max-width: calc(33.3333333333% - 30px); }

.deck-4 > .card {
  flex-basis: calc(25% - 30px);
  max-width: calc(25% - 30px); }

.deck-5 > .card {
  flex-basis: calc(20% - 30px);
  max-width: calc(20% - 30px); }

.deck-6 > .card {
  flex-basis: calc(16.6666666667% - 30px);
  max-width: calc(16.6666666667% - 30px); }

.deck-7 > .card {
  flex-basis: calc(14.2857142857% - 30px);
  max-width: calc(14.2857142857% - 30px); }

.deck-8 > .card {
  flex-basis: calc(12.5% - 30px);
  max-width: calc(12.5% - 30px); }

.deck-9 > .card {
  flex-basis: calc(11.1111111111% - 30px);
  max-width: calc(11.1111111111% - 30px); }

.deck-10 > .card {
  flex-basis: calc(10% - 30px);
  max-width: calc(10% - 30px); }

.deck-11 > .card {
  flex-basis: calc(9.0909090909% - 30px);
  max-width: calc(9.0909090909% - 30px); }

.deck-12 > .card {
  flex-basis: calc(8.3333333333% - 30px);
  max-width: calc(8.3333333333% - 30px); }

.deck-1 > .card {
  flex-basis: 100%;
  max-width: 100%;
  margin-left: 0;
  margin-right: 0; }

.deck-2 > .card {
  flex-basis: calc(50% - 30px);
  max-width: calc(50% - 30px);
  margin-left: 15px;
  margin-right: 15px; }

.deck-3 > .card {
  flex-basis: calc(33.3333333333% - 30px);
  max-width: calc(33.3333333333% - 30px);
  margin-left: 15px;
  margin-right: 15px; }

.deck-4 > .card {
  flex-basis: calc(25% - 30px);
  max-width: calc(25% - 30px);
  margin-left: 15px;
  margin-right: 15px; }

.deck-5 > .card {
  flex-basis: calc(20% - 30px);
  max-width: calc(20% - 30px);
  margin-left: 15px;
  margin-right: 15px; }

.deck-6 > .card {
  flex-basis: calc(16.6666666667% - 30px);
  max-width: calc(16.6666666667% - 30px);
  margin-left: 15px;
  margin-right: 15px; }

.deck-7 > .card {
  flex-basis: calc(14.2857142857% - 30px);
  max-width: calc(14.2857142857% - 30px);
  margin-left: 15px;
  margin-right: 15px; }

.deck-8 > .card {
  flex-basis: calc(12.5% - 30px);
  max-width: calc(12.5% - 30px);
  margin-left: 15px;
  margin-right: 15px; }

.deck-9 > .card {
  flex-basis: calc(11.1111111111% - 30px);
  max-width: calc(11.1111111111% - 30px);
  margin-left: 15px;
  margin-right: 15px; }

.deck-10 > .card {
  flex-basis: calc(10% - 30px);
  max-width: calc(10% - 30px);
  margin-left: 15px;
  margin-right: 15px; }

.deck-11 > .card {
  flex-basis: calc(9.0909090909% - 30px);
  max-width: calc(9.0909090909% - 30px);
  margin-left: 15px;
  margin-right: 15px; }

.deck-12 > .card {
  flex-basis: calc(8.3333333333% - 30px);
  max-width: calc(8.3333333333% - 30px);
  margin-left: 15px;
  margin-right: 15px; }

@media (min-width: 576px) {
  .deck-sm-1 > .card {
    flex-basis: 100%;
    max-width: 100%;
    margin-left: 0;
    margin-right: 0; }

  .deck-sm-2 > .card {
    flex-basis: calc(50% - 30px);
    max-width: calc(50% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-sm-3 > .card {
    flex-basis: calc(33.3333333333% - 30px);
    max-width: calc(33.3333333333% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-sm-4 > .card {
    flex-basis: calc(25% - 30px);
    max-width: calc(25% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-sm-5 > .card {
    flex-basis: calc(20% - 30px);
    max-width: calc(20% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-sm-6 > .card {
    flex-basis: calc(16.6666666667% - 30px);
    max-width: calc(16.6666666667% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-sm-7 > .card {
    flex-basis: calc(14.2857142857% - 30px);
    max-width: calc(14.2857142857% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-sm-8 > .card {
    flex-basis: calc(12.5% - 30px);
    max-width: calc(12.5% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-sm-9 > .card {
    flex-basis: calc(11.1111111111% - 30px);
    max-width: calc(11.1111111111% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-sm-10 > .card {
    flex-basis: calc(10% - 30px);
    max-width: calc(10% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-sm-11 > .card {
    flex-basis: calc(9.0909090909% - 30px);
    max-width: calc(9.0909090909% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-sm-12 > .card {
    flex-basis: calc(8.3333333333% - 30px);
    max-width: calc(8.3333333333% - 30px);
    margin-left: 15px;
    margin-right: 15px; } }
@media (min-width: 768px) {
  .deck-md-1 > .card {
    flex-basis: 100%;
    max-width: 100%;
    margin-left: 0;
    margin-right: 0; }

  .deck-md-2 > .card {
    flex-basis: calc(50% - 30px);
    max-width: calc(50% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-md-3 > .card {
    flex-basis: calc(33.3333333333% - 30px);
    max-width: calc(33.3333333333% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-md-4 > .card {
    flex-basis: calc(25% - 30px);
    max-width: calc(25% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-md-5 > .card {
    flex-basis: calc(20% - 30px);
    max-width: calc(20% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-md-6 > .card {
    flex-basis: calc(16.6666666667% - 30px);
    max-width: calc(16.6666666667% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-md-7 > .card {
    flex-basis: calc(14.2857142857% - 30px);
    max-width: calc(14.2857142857% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-md-8 > .card {
    flex-basis: calc(12.5% - 30px);
    max-width: calc(12.5% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-md-9 > .card {
    flex-basis: calc(11.1111111111% - 30px);
    max-width: calc(11.1111111111% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-md-10 > .card {
    flex-basis: calc(10% - 30px);
    max-width: calc(10% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-md-11 > .card {
    flex-basis: calc(9.0909090909% - 30px);
    max-width: calc(9.0909090909% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-md-12 > .card {
    flex-basis: calc(8.3333333333% - 30px);
    max-width: calc(8.3333333333% - 30px);
    margin-left: 15px;
    margin-right: 15px; } }
@media (min-width: 992px) {
  .deck-lg-1 > .card {
    flex-basis: 100%;
    max-width: 100%;
    margin-left: 0;
    margin-right: 0; }

  .deck-lg-2 > .card {
    flex-basis: calc(50% - 30px);
    max-width: calc(50% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-lg-3 > .card {
    flex-basis: calc(33.3333333333% - 30px);
    max-width: calc(33.3333333333% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-lg-4 > .card {
    flex-basis: calc(25% - 30px);
    max-width: calc(25% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-lg-5 > .card {
    flex-basis: calc(20% - 30px);
    max-width: calc(20% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-lg-6 > .card {
    flex-basis: calc(16.6666666667% - 30px);
    max-width: calc(16.6666666667% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-lg-7 > .card {
    flex-basis: calc(14.2857142857% - 30px);
    max-width: calc(14.2857142857% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-lg-8 > .card {
    flex-basis: calc(12.5% - 30px);
    max-width: calc(12.5% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-lg-9 > .card {
    flex-basis: calc(11.1111111111% - 30px);
    max-width: calc(11.1111111111% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-lg-10 > .card {
    flex-basis: calc(10% - 30px);
    max-width: calc(10% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-lg-11 > .card {
    flex-basis: calc(9.0909090909% - 30px);
    max-width: calc(9.0909090909% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-lg-12 > .card {
    flex-basis: calc(8.3333333333% - 30px);
    max-width: calc(8.3333333333% - 30px);
    margin-left: 15px;
    margin-right: 15px; } }
@media (min-width: 1200px) {
  .deck-xl-1 > .card {
    flex-basis: 100%;
    max-width: 100%;
    margin-left: 0;
    margin-right: 0; }

  .deck-xl-2 > .card {
    flex-basis: calc(50% - 30px);
    max-width: calc(50% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-xl-3 > .card {
    flex-basis: calc(33.3333333333% - 30px);
    max-width: calc(33.3333333333% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-xl-4 > .card {
    flex-basis: calc(25% - 30px);
    max-width: calc(25% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-xl-5 > .card {
    flex-basis: calc(20% - 30px);
    max-width: calc(20% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-xl-6 > .card {
    flex-basis: calc(16.6666666667% - 30px);
    max-width: calc(16.6666666667% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-xl-7 > .card {
    flex-basis: calc(14.2857142857% - 30px);
    max-width: calc(14.2857142857% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-xl-8 > .card {
    flex-basis: calc(12.5% - 30px);
    max-width: calc(12.5% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-xl-9 > .card {
    flex-basis: calc(11.1111111111% - 30px);
    max-width: calc(11.1111111111% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-xl-10 > .card {
    flex-basis: calc(10% - 30px);
    max-width: calc(10% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-xl-11 > .card {
    flex-basis: calc(9.0909090909% - 30px);
    max-width: calc(9.0909090909% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-xl-12 > .card {
    flex-basis: calc(8.3333333333% - 30px);
    max-width: calc(8.3333333333% - 30px);
    margin-left: 15px;
    margin-right: 15px; } }

How to convert a JSON string to a Map<String, String> with Jackson JSON

ObjectReader reader = new ObjectMapper().readerFor(Map.class);

Map<String, String> map = reader.readValue("{\"foo\":\"val\"}");

Note that reader instance is Thread Safe.

How do I concatenate two strings in C?

C does not have the support for strings that some other languages have. A string in C is just a pointer to an array of char that is terminated by the first null character. There is no string concatenation operator in C.

Use strcat to concatenate two strings. You could use the following function to do it:

#include <stdlib.h>
#include <string.h>

char* concat(const char *s1, const char *s2)
{
    char *result = malloc(strlen(s1) + strlen(s2) + 1); // +1 for the null-terminator
    // in real code you would check for errors in malloc here
    strcpy(result, s1);
    strcat(result, s2);
    return result;
}

This is not the fastest way to do this, but you shouldn't be worrying about that now. Note that the function returns a block of heap allocated memory to the caller and passes on ownership of that memory. It is the responsibility of the caller to free the memory when it is no longer needed.

Call the function like this:

char* s = concat("derp", "herp");
// do things with s
free(s); // deallocate the string

If you did happen to be bothered by performance then you would want to avoid repeatedly scanning the input buffers looking for the null-terminator.

char* concat(const char *s1, const char *s2)
{
    const size_t len1 = strlen(s1);
    const size_t len2 = strlen(s2);
    char *result = malloc(len1 + len2 + 1); // +1 for the null-terminator
    // in real code you would check for errors in malloc here
    memcpy(result, s1, len1);
    memcpy(result + len1, s2, len2 + 1); // +1 to copy the null-terminator
    return result;
}

If you are planning to do a lot of work with strings then you may be better off using a different language that has first class support for strings.

Fork() function in C

int a = fork(); 

Creates a duplicate process "clone?", which shares the execution stack. The difference between the parent and the child is the return value of the function.

The child getting 0 returned, and the parent getting the new pid.

Each time the addresses and the values of the stack variables are copied. The execution continues at the point it already got to in the code.

At each fork, only one value is modified - the return value from fork.

Change the name of a key in dictionary

Be aware of the position of pop:
Put the key you want to delete after pop()
orig_dict['AAAAA'] = orig_dict.pop('A')

orig_dict = {'A': 1, 'B' : 5,  'C' : 10, 'D' : 15}   
# printing initial 
print ("original: ", orig_dict) 

# changing keys of dictionary 
orig_dict['AAAAA'] = orig_dict.pop('A')
  
# printing final result 
print ("Changed: ", str(orig_dict)) 

VBA: Conditional - Is Nothing

Based on your comment to Issun:

Thanks for the explanation. In my case, The object is declared and created prior to the If condition. So, How do I use If condition to check for < No Variables> ? In other words, I do not want to execute My_Object.Compute if My_Object has < No Variables>

You need to check one of the properties of the object. Without telling us what the object is, we cannot help you.

I did test several common objects and found that an instantiated Collection with no items added shows <No Variables> in the watch window. If your object is indeed a collection, you can check for the <No Variables> condition using the .Count property:

Sub TestObj()
Dim Obj As Object
    Set Obj = New Collection
    If Obj Is Nothing Then
        Debug.Print "Object not instantiated"
    Else
        If Obj.Count = 0 Then
            Debug.Print "<No Variables> (ie, no items added to the collection)"
        Else
            Debug.Print "Object instantiated and at least one item added"
        End If
    End If
End Sub

It is also worth noting that if you declare any object As New then the Is Nothing check becomes useless. The reason is that when you declare an object As New then it gets created automatically when it is first called, even if the first time you call it is to see if it exists!

Dim MyObject As New Collection
If MyObject Is Nothing Then  ' <--- This check always returns False

This does not seem to be the cause of your specific problem. But, since others may find this question through a Google search, I wanted to include it because it is a common beginner mistake.

How to remove item from array by value?

Simply

var ary = ['three', 'seven', 'eleven'];
var index = ary.indexOf('seven'); // get index if value found otherwise -1

if (index > -1) { //if found
  ary.splice(index, 1);
}

How to Get XML Node from XDocument

The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:

XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
                    where xml2.Element("ID").Value == variable
                    select xml2).FirstOrDefault();

This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.

Marc

How to make a phone call using intent in Android?

For making a call activity using intents, you should request the proper permissions.

For that you include uses permissions in AndroidManifest.xml file.

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

Then include the following code in your activity

if (ActivityCompat.checkSelfPermission(mActivity,
        Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
    //Creating intents for making a call
    Intent callIntent = new Intent(Intent.ACTION_CALL);
    callIntent.setData(Uri.parse("tel:123456789"));
    mActivity.startActivity(callIntent);

}else{
    Toast.makeText(mActivity, "You don't assign permission.", Toast.LENGTH_SHORT).show();
}

Laravel 5.2 - Use a String as a Custom Primary Key for Eloquent Table becomes 0

On the model set $incrementing to false

public $incrementing = false;

This will stop it from thinking it is an auto increment field.

Laravel Docs - Eloquent - Defining Models

How store a range from excel into a Range variable?

Define what GetData is. At the moment it is not defined.

Function getData(currentWorksheet as Worksheet, dataStartRow as Integer, dataEndRow as Integer, DataStartCol as Integer, dataEndCol as Integer) as variant

ASP.NET - How to write some html in the page? With Response.Write?

You can also use pageMethods in asp.net. So that you can call javascript functions from asp.net functions. E.g.

_x000D_
_x000D_
 [WebMethod]_x000D_
    public static string showTxtbox(string name)_x000D_
    {_x000D_
         return showResult(name);_x000D_
    }_x000D_
      _x000D_
    public static string showResult(string name)_x000D_
    {_x000D_
        Database databaseObj = new Database();_x000D_
        DataTable dtObj = databaseObj.getMatches(name);_x000D_
_x000D_
        string result = "<table  border='1' cellspacing='2' cellpadding='2' >" +_x000D_
                                            "<tr>" +_x000D_
                                                "<td><b>Name</b></td>" +_x000D_
                                                "<td><b>Company Name</b></td>" +_x000D_
                                                "<td><b>Phone</b></td>"+_x000D_
                                             "</tr>";_x000D_
_x000D_
        for (int i = 0; i < dtObj.Rows.Count; i++)_x000D_
        {_x000D_
            result += "<tr> <td><a href=\"javascript:link('" + dtObj.Rows[i][0].ToString().Trim() + "','" +_x000D_
             dtObj.Rows[i][1].ToString().Trim() +"','"+dtObj.Rows[i][2]+ "');\">" + Convert.ToString(dtObj.Rows[i]["name"]) + "</td>" +_x000D_
                "<td>" + Convert.ToString(dtObj.Rows[i]["customerCompany"]) + "</td>" +_x000D_
                "<td>"+Convert.ToString(dtObj.Rows[i]["Phone"])+"</td>"+_x000D_
             "</tr>";_x000D_
        }_x000D_
_x000D_
        result += "</table>";_x000D_
        return result;_x000D_
    }
_x000D_
_x000D_
_x000D_

Here above code is written in .aspx.cs page. Database is another class. In showResult() function I've called javascript's link() function. Result is displayed in the form of table.