What do column flags mean in MySQL Workbench?
PK - Primary Key
NN - Not Null
BIN - Binary (stores data as binary strings. There is no character set so sorting and comparison is based on the numeric values of the bytes in the values.)
UN - Unsigned (non-negative numbers only. so if the range is -500 to 500, instead its 0 - 1000, the range is the same but it starts at 0)
UQ - Create/remove Unique Key
ZF - Zero-Filled (if the length is 5 like INT(5) then every field is filled with 0’s to the 5th digit. 12 = 00012, 400 = 00400, etc. )
AI - Auto Increment
G - Generated column. i.e. value generated by a formula based on the other columns
Kotlin unresolved reference in IntelliJ
A possible solution for standalone Kotlin projects is to include Kotlin standard libs explicitliy inside the root project.
To do that in IntelliJ IDEA:
- press Ctrl+Shift+A (Search actions or options)
- type in "Configure kotlin in project" and let it include standard libs for you
Actionbar notification count icon (badge) like Google has
Ok, for @AndrewS solution to work with v7 appCompat library:
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:someNamespace="http://schemas.android.com/apk/res-auto" >
<item
android:id="@+id/saved_badge"
someNamespace:showAsAction="always"
android:icon="@drawable/shape_notification" />
</menu>
.
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.main, menu);
MenuItem item = menu.findItem(R.id.saved_badge);
MenuItemCompat.setActionView(item, R.layout.feed_update_count);
View view = MenuItemCompat.getActionView(item);
notifCount = (Button)view.findViewById(R.id.notif_count);
notifCount.setText(String.valueOf(mNotifCount));
}
private void setNotifCount(int count){
mNotifCount = count;
supportInvalidateOptionsMenu();
}
The rest of the code is the same.
Filtering Pandas DataFrames on dates
How about using pyjanitor
It has cool features.
After pip install pyjanitor
import janitor
df_filtered = df.filter_date(your_date_column_name, start_date, end_date)
bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js
On moving a .html template to a wordpress one, I found this "popper required" popping up regularly :)
Two reasons it happened for me: and the console error can be deceptive:
The error in the console can send you down the wrong path. It MIGHT not be the real issue. First reason for me was the order in which you have set your .js files to load. In html easy, put them in the same order as the theme template. In Wordpress, you need to enqueue them in the right order, but also set a priority if they don't appear in the right order,
Second thing is are the .js files in the header or the footer. Moving them to the footer can solve the issue - it did for me, after a day of trying to debug the issue. Usually doesn't matter, but for a complex page with lots of js libraries, it might!
Shorten string without cutting words in JavaScript
I came late for this but I think this function makes exactly what OP requests. You can easily change the SENTENCE and the LIMIT values for different results.
_x000D_
_x000D_
function breakSentence(word, limit) {_x000D_
const queue = word.split(' ');_x000D_
const list = [];_x000D_
_x000D_
while (queue.length) {_x000D_
const word = queue.shift();_x000D_
_x000D_
if (word.length >= limit) {_x000D_
list.push(word)_x000D_
}_x000D_
else {_x000D_
let words = word;_x000D_
_x000D_
while (true) {_x000D_
if (!queue.length ||_x000D_
words.length > limit ||_x000D_
words.length + queue[0].length + 1 > limit) {_x000D_
break;_x000D_
}_x000D_
_x000D_
words += ' ' + queue.shift();_x000D_
}_x000D_
_x000D_
list.push(words);_x000D_
}_x000D_
}_x000D_
_x000D_
return list;_x000D_
}_x000D_
_x000D_
const SENTENCE = 'the quick brown fox jumped over the lazy dog';_x000D_
const LIMIT = 11;_x000D_
_x000D_
// get result_x000D_
const words = breakSentence(SENTENCE, LIMIT);_x000D_
_x000D_
// transform the string so the result is easier to understand_x000D_
const wordsWithLengths = words.map((item) => {_x000D_
return `[${item}] has a length of - ${item.length}`;_x000D_
});_x000D_
_x000D_
console.log(wordsWithLengths);
_x000D_
_x000D_
_x000D_
The output of this snippet is where the LIMIT is 11 is:
[ '[the quick] has a length of - 9',
'[brown fox] has a length of - 9',
'[jumped over] has a length of - 11',
'[the lazy] has a length of - 8',
'[dog] has a length of - 3' ]
Apache2: 'AH01630: client denied by server configuration'
If you are using Apache 2.4 in WampServer on windows OS.
You need to open https-vhosts.conf file in notepad.
C:\wamp64\bin\apache\apache2.4.37\conf\extra\https-vhosts.conf
If you unable to find above file. check screenshot below
<VirtualHost *:80>
ServerName localhost
DocumentRoot c:/wamp64/www
<Directory "c:/wamp64/www/">
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Require local
</Directory>
</VirtualHost>
In above code Replace
Require local
with
Require all granted
And save it. Restart Apache service and try again.
What's the difference between ViewData and ViewBag?
ViewData
- ViewData is used to pass data from controller to view
- It is derived from ViewDataDictionary class
- It is available for the current request only
- Requires typecasting for complex data type and checks for null values to avoid error
- If redirection occurs, then its value becomes null
ViewBag
- ViewBag is also used to pass data from the controller to the respective view
- ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0
- It is also available for the current request only
- If redirection occurs, then its value becomes null
- Doesn’t require typecasting for complex data type
How to alter a column and change the default value?
Accepted Answer works good.
In case of Invalid use of NULL value error, on NULL values, update all null values to default value in that column and then try to do the alter.
UPDATE foobar_data SET col = '{}' WHERE col IS NULL;
ALTER TABLE foobar_data MODIFY COLUMN col VARCHAR(255) NOT NULL DEFAULT '{}';
Why isn't sizeof for a struct equal to the sum of sizeof of each member?
This can be due to byte alignment and padding so that the structure comes out to an even number of bytes (or words) on your platform. For example in C on Linux, the following 3 structures:
#include "stdio.h"
struct oneInt {
int x;
};
struct twoInts {
int x;
int y;
};
struct someBits {
int x:2;
int y:6;
};
int main (int argc, char** argv) {
printf("oneInt=%zu\n",sizeof(struct oneInt));
printf("twoInts=%zu\n",sizeof(struct twoInts));
printf("someBits=%zu\n",sizeof(struct someBits));
return 0;
}
Have members who's sizes (in bytes) are 4 bytes (32 bits), 8 bytes (2x 32 bits) and 1 byte (2+6 bits) respectively. The above program (on Linux using gcc) prints the sizes as 4, 8, and 4 - where the last structure is padded so that it is a single word (4 x 8 bit bytes on my 32bit platform).
oneInt=4
twoInts=8
someBits=4
Install psycopg2 on Ubuntu
This works for me in Ubuntu 12.04 and 15.10
if pip not installed:
sudo apt-get install python-pip
and then:
sudo apt-get update
sudo apt-get install libpq-dev python-dev
sudo pip install psycopg2
angularjs: allows only numbers to be typed into a text box
I arraged the jQuery in this
.directive('numbersCommaOnly', function(){
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
element.on('keydown', function(event) {
// Allow: backspace, delete, tab, escape, enter and .
var array2 = [46, 8, 9, 27, 13, 110, 190]
if (array2.indexOf(event.which) !== -1 ||
// Allow: Ctrl+A
(event.which == 65 && event.ctrlKey === true) ||
// Allow: Ctrl+C
(event.which == 67 && event.ctrlKey === true) ||
// Allow: Ctrl+X
(event.which == 88 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.which >= 35 && event.which <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((event.shiftKey || (event.which < 48 || event.which > 57)) && (event.which < 96 || event.which > 105)) {
event.preventDefault();
}
});
}
};
})
Find the 2nd largest element in an array with minimum number of comparisons
I have gone through all the posts above but I am convinced that the implementation of the Tournament algorithm is the best approach. Let us consider the following algorithm posted by @Gumbo
largest := numbers[0];
secondLargest := null
for i=1 to numbers.length-1 do
number := numbers[i];
if number > largest then
secondLargest := largest;
largest := number;
else
if number > secondLargest then
secondLargest := number;
end;
end;
end;
It is very good in case we are going to find the second largest number in an array. It has (2n-1) number of comparisons. But what if you want to calculate the third largest number or some kth largest number. The above algorithm doesn't work. You got to another procedure.
So, I believe tournament algorithm approach is the best and here is the link for that.
Mockito. Verify method arguments
I have used Mockito.verify in this way
@UnitTest
public class JUnitServiceTest
{
@Mock
private MyCustomService myCustomService;
@Test
public void testVerifyMethod()
{
Mockito.verify(myCustomService, Mockito.never()).mymethod(parameters); // method will never call (an alternative can be pick to use times(0))
Mockito.verify(myCustomService, Mockito.times(2)).mymethod(parameters); // method will call for 2 times
Mockito.verify(myCustomService, Mockito.atLeastOnce()).mymethod(parameters); // method will call atleast 1 time
Mockito.verify(myCustomService, Mockito.atLeast(2)).mymethod(parameters); // method will call atleast 2 times
Mockito.verify(myCustomService, Mockito.atMost(3)).mymethod(parameters); // method will call at most 3 times
Mockito.verify(myCustomService, Mockito.only()).mymethod(parameters); // no other method called except this
}
}
If...Then...Else with multiple statements after Then
This works with multiple statements:
if condition1 Then stmt1:stmt2 Else if condition2 Then stmt3:stmt4 Else stmt5:stmt6
Or you can split it over multiple lines:
if condition1 Then stmt1:stmt2
Else if condition2 Then stmt3:stmt4
Else stmt5:stmt6
Replace string in text file using PHP
Does this work:
$msgid = $_GET['msgid'];
$oldMessage = '';
$deletedFormat = '';
//read the entire string
$str=file_get_contents('msghistory.txt');
//replace something in the file string - this is a VERY simple example
$str=str_replace($oldMessage, $deletedFormat,$str);
//write the entire string
file_put_contents('msghistory.txt', $str);
Conditionally hide CommandField or ButtonField in Gridview
Hide the Entire GridView Column
If you want to remove the column completely (i.e. not just the button) from the table then use a suitable event handler, e.g. for the OnDataBound
event, and then hide the appropriate column on the target GridView
. Pick an event that will only fire once for this control, i.e. not OnRowDataBound
.
aspx:
<asp:GridView ID="grdUsers" runat="server" DataSourceID="dsProjectUsers" OnDataBound="grdUsers_DataBound">
<Columns>
<asp:TemplateField HeaderText="Admin Actions">
<ItemTemplate><asp:Button ID="btnEdit" runat="server" text="Edit" /></ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:BoundField DataField="Telephone" HeaderText="Telephone" />
</Columns>
</asp:GridView>
aspx.cs:
protected void grdUsers_DataBound(object sender, EventArgs e)
{
try
{
// in this case hiding the first col if not admin
if (!User.IsInRole(Constants.Role_Name_Admin))
grdUsers.Columns[0].Visible = false;
}
catch (Exception ex)
{
// deal with ex
}
}
How to pass Multiple Parameters from ajax call to MVC Controller
In addition to posts by @xdumain, I prefer creating data object before ajax call so you can debug it.
var dataObject = JSON.stringify({
'input': $('#myInput').val(),
'name': $('#myName').val(),
});
Now use it in ajax call
$.ajax({
url: "/Home/SaveChart",
type: 'POST',
async: false,
dataType: 'json',
contentType: 'application/json',
data: dataObject,
success: function (data) { },
error: function (xhr) { } )};
How do I use disk caching in Picasso?
1) answer of first question :
according to Picasso Doc for With() method
The global default Picasso instance returned from with() is automatically initialized with defaults that are suitable to most implementations.
- LRU memory cache of 15% the available application RAM
- Disk cache of 2% storage space up to 50MB but no less than 5MB.
But Disk Cache
operation for global Default Picasso is only available on API 14+
2) answer of second Question : Picasso
use the HTTP
client request to Disk Cache
operation So you can make your own http request header
has property Cache-Control
with max-age
And create your own Static Picasso Instance instead of default Picasso By using
1] HttpResponseCache (Note: Works only for API 13+ )
2] OkHttpClient (Works for all APIs)
Example for using OkHttpClient
to create your own Static Picasso class:
First create a new class to get your own singleton picasso
object
import android.content.Context;
import com.squareup.picasso.Downloader;
import com.squareup.picasso.OkHttpDownloader;
import com.squareup.picasso.Picasso;
public class PicassoCache {
/**
* Static Picasso Instance
*/
private static Picasso picassoInstance = null;
/**
* PicassoCache Constructor
*
* @param context application Context
*/
private PicassoCache (Context context) {
Downloader downloader = new OkHttpDownloader(context, Integer.MAX_VALUE);
Picasso.Builder builder = new Picasso.Builder(context);
builder.downloader(downloader);
picassoInstance = builder.build();
}
/**
* Get Singleton Picasso Instance
*
* @param context application Context
* @return Picasso instance
*/
public static Picasso getPicassoInstance (Context context) {
if (picassoInstance == null) {
new PicassoCache(context);
return picassoInstance;
}
return picassoInstance;
}
}
use your own singleton picasso
object Instead of Picasso.With()
PicassoCache.getPicassoInstance(getContext()).load(imagePath).into(imageView)
3) answer for third question : you do not need any disk permissions for disk Cache operations
References: Github issue about disk cache, two Questions has been answered by @jake-wharton -> Question1 and Question2
MySQL show status - active or total connections?
According to the docs, it means the total number throughout history:
Connections
The number of connection attempts (successful or not) to the MySQL server.
You can see the number of active connections either through the Threads_connected
status variable:
Threads_connected
The number of currently open connections.
mysql> show status where `variable_name` = 'Threads_connected';
+-------------------+-------+
| Variable_name | Value |
+-------------------+-------+
| Threads_connected | 4 |
+-------------------+-------+
1 row in set (0.00 sec)
... or through the show processlist
command:
mysql> show processlist;
+----+------+-----------------+--------+---------+------+-------+------------------+
| Id | User | Host | db | Command | Time | State | Info |
+----+------+-----------------+--------+---------+------+-------+------------------+
| 3 | root | localhost | webapp | Query | 0 | NULL | show processlist |
| 5 | root | localhost:61704 | webapp | Sleep | 208 | | NULL |
| 6 | root | localhost:61705 | webapp | Sleep | 208 | | NULL |
| 7 | root | localhost:61706 | webapp | Sleep | 208 | | NULL |
+----+------+-----------------+--------+---------+------+-------+------------------+
4 rows in set (0.00 sec)
Count words in a string method?
public static int countWords(String s){
int wordCount = 0;
boolean word = false;
int endOfLine = s.length() - 1;
for (int i = 0; i < s.length(); i++) {
// if the char is a letter, word = true.
if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
word = true;
// if char isn't a letter and there have been letters before,
// counter goes up.
} else if (!Character.isLetter(s.charAt(i)) && word) {
wordCount++;
word = false;
// last word of String; if it doesn't end with a non letter, it
// wouldn't count without this.
} else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
wordCount++;
}
}
return wordCount;
}
Trigger Change event when the Input value changed programmatically?
If someone is using react, following will be useful:
https://stackoverflow.com/a/62111884/1015678
const valueSetter = Object.getOwnPropertyDescriptor(this.textInputRef, 'value').set;
const prototype = Object.getPrototypeOf(this.textInputRef);
const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
if (valueSetter && valueSetter !== prototypeValueSetter) {
prototypeValueSetter.call(this.textInputRef, 'new value');
} else {
valueSetter.call(this.textInputRef, 'new value');
}
this.textInputRef.dispatchEvent(new Event('input', { bubbles: true }));
Deleting a file in VBA
The following can be used to test for the existence of a file, and then to delete it.
Dim aFile As String
aFile = "c:\file_to_delete.txt"
If Len(Dir$(aFile)) > 0 Then
Kill aFile
End If
Delayed function calls
Well, I'd have to agree with the "design" point... but you can probably use a Monitor to let one know when the other is past the critical section...
public void foo() {
// Do stuff!
object syncLock = new object();
lock (syncLock) {
// Delayed call to bar() after x number of ms
ThreadPool.QueueUserWorkItem(delegate {
lock(syncLock) {
bar();
}
});
// Do more Stuff
}
// lock now released, bar can begin
}
How to display an error message in an ASP.NET Web Application
All you need is a control that you can set the text of, and an UpdatePanel if the exception occurs during a postback.
If occurs during a postback:
markup:
<ajax:UpdatePanel id="ErrorUpdatePanel" runat="server" UpdateMode="Coditional">
<ContentTemplate>
<asp:TextBox id="ErrorTextBox" runat="server" />
</ContentTemplate>
</ajax:UpdatePanel>
code:
try
{
do something
}
catch(YourException ex)
{
this.ErrorTextBox.Text = ex.Message;
this.ErrorUpdatePanel.Update();
}
Scroll to a specific Element Using html
The above answers are good and correct. However, the code may not give the expected results. Allow me to add something to explain why this is very important.
It is true that adding the scroll-behavior: smooth to the html element allows smooth scrolling for the whole page. However not all web browsers support smooth scrolling using HTML.
So if you want to create a website accessible to all user, regardless of their web browsers, it is highly recommended to use JavaScript or a JavaScript library such as jQuery, to create a solution that will work for all browsers.
Otherwise, some users may not enjoy the smooth scrolling of your website / platform.
I can give a simpler example on how it can be applicable.
_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script>_x000D_
$(document).ready(function(){_x000D_
// Add smooth scrolling to all links_x000D_
$("a").on('click', function(event) {_x000D_
// Make sure this.hash has a value before overriding default behavior_x000D_
if (this.hash !== "") {_x000D_
// Prevent default anchor click behavior_x000D_
event.preventDefault();_x000D_
// Store hash_x000D_
var hash = this.hash;_x000D_
// Using jQuery's animate() method to add smooth page scroll_x000D_
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area_x000D_
$('html, body').animate({_x000D_
scrollTop: $(hash).offset().top_x000D_
}, 800, function(){_x000D_
// Add hash (#) to URL when done scrolling (default click behavior)_x000D_
window.location.hash = hash;_x000D_
});_x000D_
} // End if_x000D_
});_x000D_
});_x000D_
</script>
_x000D_
<style>_x000D_
#section1 {_x000D_
height: 600px;_x000D_
background-color: pink;_x000D_
}_x000D_
#section2 {_x000D_
height: 600px;_x000D_
background-color: yellow;_x000D_
}_x000D_
</style>
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<h1>Smooth Scroll</h1>_x000D_
<div class="main" id="section1">_x000D_
<h2>Section 1</h2>_x000D_
<p>Click on the link to see the "smooth" scrolling effect.</p>_x000D_
<a href="#section2">Click Me to Smooth Scroll to Section 2 Below</a>_x000D_
<p>Note: Remove the scroll-behavior property to remove smooth scrolling.</p>_x000D_
</div>_x000D_
<div class="main" id="section2">_x000D_
<h2>Section 2</h2>_x000D_
<a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_
Equal sized table cells to fill the entire width of the containing table
Just use percentage widths and fixed table layout:
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</table>
with
table { table-layout: fixed; }
td { width: 33%; }
Fixed table layout is important as otherwise the browser will adjust the widths as it sees fit if the contents don't fit ie the widths are otherwise a suggestion not a rule without fixed table layout.
Obviously, adjust the CSS to fit your circumstances, which usually means applying the styling only to a tables with a given class or possibly with a given ID.
Split page vertically using CSS
you can use..
<div style="width: 100%;">
<div style="float:left; width: 80%">
</div>
<div style="float:right;">
</div>
</div>
<div style="clear:both"></div>
now element below this will not be affected.
Image, saved to sdcard, doesn't appear in Android's Gallery app
My answer to the original question and to anyone else that may have this problem:
I was having this same problem, images in my app that people saved to the SD card were not showing up in their Gallery immediately. After some searching I found this one line of code inserted after my 'save to sdcard' code that fixed the problem:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
How to Create Multiple Where Clause Query Using Laravel Eloquent?
You can use subqueries in anonymous function like this:
$results = User::where('this', '=', 1)
->where('that', '=', 1)
->where(function($query) {
/** @var $query Illuminate\Database\Query\Builder */
return $query->where('this_too', 'LIKE', '%fake%')
->orWhere('that_too', '=', 1);
})
->get();
android asynctask sending callbacks to ui
IN completion to above answers, you can also customize your fallbacks for each async call you do, so that each call to the generic ASYNC method will populate different data, depending on the onTaskDone stuff you put there.
Main.FragmentCallback FC= new Main.FragmentCallback(){
@Override
public void onTaskDone(String results) {
localText.setText(results); //example TextView
}
};
new API_CALL(this.getApplicationContext(), "GET",FC).execute("&Books=" + Main.Books + "&args=" + profile_id);
Remind: I used interface on the main activity thats where "Main" comes, like this:
public interface FragmentCallback {
public void onTaskDone(String results);
}
My API post execute looks like this:
@Override
protected void onPostExecute(String results) {
Log.i("TASK Result", results);
mFragmentCallback.onTaskDone(results);
}
The API constructor looks like this:
class API_CALL extends AsyncTask<String,Void,String> {
private Main.FragmentCallback mFragmentCallback;
private Context act;
private String method;
public API_CALL(Context ctx, String api_method,Main.FragmentCallback fragmentCallback) {
act=ctx;
method=api_method;
mFragmentCallback = fragmentCallback;
}
JavaScript associative array to JSON
I posted a fix for this here
You can use this function to modify JSON.stringify
to encode arrays
, just post it near the beginning of your script (check the link above for more detail):
// Upgrade for JSON.stringify, updated to allow arrays
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
Where does Git store files?
In a .git directory in the root of the project. Unlike some other version control systems, notably CVS, there are no additional directories in any of the subdirectories.
Chosen Jquery Plugin - getting selected values
If anyone wants to get only the selected value on click to an option, he can do the follow:
$('.chosen-select').on('change', function(evt, params) {
var selectedValue = params.selected;
console.log(selectedValue);
});
How can I apply a function to every row/column of a matrix in MATLAB?
Building on Alex's answer, here is a more generic function:
applyToGivenRow = @(func, matrix) @(row) func(matrix(row, :));
newApplyToRows = @(func, matrix) arrayfun(applyToGivenRow(func, matrix), 1:size(matrix,1), 'UniformOutput', false)';
takeAll = @(x) reshape([x{:}], size(x{1},2), size(x,1))';
genericApplyToRows = @(func, matrix) takeAll(newApplyToRows(func, matrix));
Here is a comparison between the two functions:
>> % Example
myMx = [1 2 3; 4 5 6; 7 8 9];
myFunc = @(x) [mean(x), std(x), sum(x), length(x)];
>> genericApplyToRows(myFunc, myMx)
ans =
2 1 6 3
5 1 15 3
8 1 24 3
>> applyToRows(myFunc, myMx)
??? Error using ==> arrayfun
Non-scalar in Uniform output, at index 1, output 1.
Set 'UniformOutput' to false.
Error in ==> @(func,matrix)arrayfun(applyToGivenRow(func,matrix),1:size(matrix,1))'
How can I enable CORS on Django REST Framework
pip install django-cors-headers
and then add it to your installed apps:
INSTALLED_APPS = (
...
'corsheaders',
...
)
You will also need to add a middleware class to listen in on responses:
MIDDLEWARE_CLASSES = (
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
)
CORS_ORIGIN_ALLOW_ALL = True # If this is used then `CORS_ORIGIN_WHITELIST` will not have any effect
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = [
'http://localhost:3030',
] # If this is used, then not need to use `CORS_ORIGIN_ALLOW_ALL = True`
CORS_ORIGIN_REGEX_WHITELIST = [
'http://localhost:3030',
]
more details: https://github.com/ottoyiu/django-cors-headers/#configuration
read the official documentation can resolve almost all problem
How do you use String.substringWithRange? (or, how do Ranges work in Swift?)
You can use this extensions to improve substringWithRange
Swift 2.3
extension String
{
func substringWithRange(start: Int, end: Int) -> String
{
if (start < 0 || start > self.characters.count)
{
print("start index \(start) out of bounds")
return ""
}
else if end < 0 || end > self.characters.count
{
print("end index \(end) out of bounds")
return ""
}
let range = Range(start: self.startIndex.advancedBy(start), end: self.startIndex.advancedBy(end))
return self.substringWithRange(range)
}
func substringWithRange(start: Int, location: Int) -> String
{
if (start < 0 || start > self.characters.count)
{
print("start index \(start) out of bounds")
return ""
}
else if location < 0 || start + location > self.characters.count
{
print("end index \(start + location) out of bounds")
return ""
}
let range = Range(start: self.startIndex.advancedBy(start), end: self.startIndex.advancedBy(start + location))
return self.substringWithRange(range)
}
}
Swift 3
extension String
{
func substring(start: Int, end: Int) -> String
{
if (start < 0 || start > self.characters.count)
{
print("start index \(start) out of bounds")
return ""
}
else if end < 0 || end > self.characters.count
{
print("end index \(end) out of bounds")
return ""
}
let startIndex = self.characters.index(self.startIndex, offsetBy: start)
let endIndex = self.characters.index(self.startIndex, offsetBy: end)
let range = startIndex..<endIndex
return self.substring(with: range)
}
func substring(start: Int, location: Int) -> String
{
if (start < 0 || start > self.characters.count)
{
print("start index \(start) out of bounds")
return ""
}
else if location < 0 || start + location > self.characters.count
{
print("end index \(start + location) out of bounds")
return ""
}
let startIndex = self.characters.index(self.startIndex, offsetBy: start)
let endIndex = self.characters.index(self.startIndex, offsetBy: start + location)
let range = startIndex..<endIndex
return self.substring(with: range)
}
}
Usage:
let str = "Hello, playground"
let substring1 = str.substringWithRange(0, end: 5) //Hello
let substring2 = str.substringWithRange(7, location: 10) //playground
Java keytool easy way to add server cert from url/port
Just expose dnozay's answer to a function so that we can import multiple certificates at the same time.
#!/usr/bin/env sh
KEYSTORE_FILE=/path/to/keystore.jks
KEYSTORE_PASS=changeit
import_cert() {
local HOST=$1
local PORT=$2
# get the SSL certificate
openssl s_client -connect ${HOST}:${PORT} </dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ${HOST}.cert
# delete the old alias and then import the new one
keytool -delete -keystore ${KEYSTORE_FILE} -storepass ${KEYSTORE_PASS} -alias ${HOST} &> /dev/null
# create a keystore and import certificate
keytool -import -noprompt -trustcacerts \
-alias ${HOST} -file ${HOST}.cert \
-keystore ${KEYSTORE_FILE} -storepass ${KEYSTORE_PASS}
rm ${HOST}.cert
}
import_cert stackoverflow.com 443
import_cert www.google.com 443
import_cert 172.217.194.104 443 # google
Where are SQL Server connection attempts logged?
You can enable connection logging. For SQL Server 2008, you can enable Login Auditing. In SQL Server Management Studio, open SQL Server Properties > Security > Login Auditing select "Both failed and successful logins".
Make sure to restart the SQL Server service.
Once you've done that, connection attempts should be logged into SQL's error log. The physical logs location can be determined here.
How to use JavaScript to change div backgroundColor
var div = document.getElementById( 'div_id' );
div.onmouseover = function() {
this.style.backgroundColor = 'green';
var h2s = this.getElementsByTagName( 'h2' );
h2s[0].style.backgroundColor = 'blue';
};
div.onmouseout = function() {
this.style.backgroundColor = 'transparent';
var h2s = this.getElementsByTagName( 'h2' );
h2s[0].style.backgroundColor = 'transparent';
};
MsgBox "" vs MsgBox() in VBScript
The difference between "" and () is:
With "" you are not calling anything.
With () you are calling a sub.
Example with sub:
Sub = MsgBox("Msg",vbYesNo,vbCritical,"Title")
Select Case Sub
Case = vbYes
MsgBox"You said yes"
Case = vbNo
MsgBox"You said no"
End Select
vs Normal:
MsgBox"This is normal"
What does this square bracket and parenthesis bracket notation mean [first1,last1)?
A bracket - [
or ]
- means that end of the range is inclusive -- it includes the element listed. A parenthesis - (
or )
- means that end is exclusive and doesn't contain the listed element. So for [first1, last1)
, the range starts with first1
(and includes it), but ends just before last1
.
Assuming integers:
- (0, 5) = 1, 2, 3, 4
- (0, 5] = 1, 2, 3, 4, 5
- [0, 5) = 0, 1, 2, 3, 4
- [0, 5] = 0, 1, 2, 3, 4, 5
How to change font-size of a tag using inline css?
You should analyze your style.css file, possibly using Developer Tools in your favorite browser, to see which rule sets font size on the element in a manner that overrides the one in a style
attribute. Apparently, it has to be one using the !important
specifier, which generally indicates poor logic and structure in styling.
Primarily, modify the style.css file so that it does not use !important
. Failing this, add !important
to the rule in style
attribute. But you should aim at reducing the use of !important
, not increasing it.
How to get a .csv file into R?
As Dirk said, the function you are after is 'read.csv' or one of the other read.table variants. Given your sample data above, I think you will want to do something like this:
setwd("c:/random/directory")
df <- read.csv("myRandomFile.csv", header=TRUE)
All we did in the above was set the directory to where your .csv file is and then read the .csv into a dataframe named df. You can check that the data loaded properly by checking the structure of the object with:
str(df)
Assuming the data loaded properly, you can think go on to perform any number of statistical methods with the data in your data frame. I think summary(df)
would be a good place to start. Learning how to use the help in R will be immensely useful, and a quick read through the help on CRAN will save you lots of time in the future: http://cran.r-project.org/
How to get a time zone from a location using latitude and longitude coordinates?
https://en.wikipedia.org/wiki/Great-circle_distance
And here is a good implementation using JSON data:
https://github.com/agap/llttz
public TimeZone nearestTimeZone(Location node) {
double bestDistance = Double.MAX_VALUE;
Location bestGuess = timeZones.get(0);
for (Location current : timeZones.subList(1, timeZones.size())) {
double newDistance = distanceInKilometers(node, current);
if (newDistance < bestDistance) {
bestDistance = newDistance;
bestGuess = current;
}
}
return java.util.TimeZone.getTimeZone(bestGuess.getZone());
}
protected double distanceInKilometers(final double latFrom, final double lonFrom, final double latTo, final double lonTo) {
final double meridianLength = 111.1;
return meridianLength * centralAngle(latFrom, lonFrom, latTo, lonTo);
}
protected double centralAngle(final Location from, final Location to) {
return centralAngle(from.getLatitude(), from.getLongitude(), to.getLatitude(), to.getLongitude());
}
protected double centralAngle(final double latFrom, final double lonFrom, final double latTo, final double lonTo) {
final double latFromRad = toRadians(latFrom),
lonFromRad = toRadians(lonFrom),
latToRad = toRadians(latTo),
lonToRad = toRadians(lonTo);
final double centralAngle = toDegrees(acos(sin(latFromRad) * sin(latToRad) + cos(latFromRad) * cos(latToRad) * cos(lonToRad - lonFromRad)));
return centralAngle <= 180.0 ? centralAngle : (360.0 - centralAngle);
}
protected double distanceInKilometers(final Location from, final Location to) {
return distanceInKilometers(from.getLatitude(), from.getLongitude(), to.getLatitude(), to.getLongitude());
}
}
Splitting a string into separate variables
It is important to note the following difference between the two techniques:
$Str="This is the<BR />source string<BR />ALL RIGHT"
$Str.Split("<BR />")
This
is
the
(multiple blank lines)
source
string
(multiple blank lines)
ALL
IGHT
$Str -Split("<BR />")
This is the
source string
ALL RIGHT
From this you can see that the string.split()
method:
- performs a case sensitive split (note that "ALL RIGHT" his split on the "R" but "broken" is not split on the "r")
- treats the string as a list of possible characters to split on
While the -split
operator:
- performs a case-insensitive comparison
- only splits on the whole string
Could not find default endpoint element
I faced this problem once. It was because i was still developing the interface that uses WCF service. I configured test application and continued development. Then in development, i changed some of the services' namespaces. So i double checked "system.serviceModel -> client -> endpoint -> contract" in web.config to match WCF class. Then problem is solved.
An array of List in c#
List<int>[] a = new List<int>[100];
You still would have to allocate each individual list in the array before you can use it though:
for (int i = 0; i < a.Length; i++)
a[i] = new List<int>();
How to set socket timeout in C when making multiple connections?
You can use the SO_RCVTIMEO and SO_SNDTIMEO socket options to set timeouts for any socket operations, like so:
struct timeval timeout;
timeout.tv_sec = 10;
timeout.tv_usec = 0;
if (setsockopt (sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,
sizeof(timeout)) < 0)
error("setsockopt failed\n");
if (setsockopt (sockfd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout,
sizeof(timeout)) < 0)
error("setsockopt failed\n");
Edit: from the setsockopt
man page:
SO_SNDTIMEO
is an option to set a timeout value for output operations. It accepts a struct timeval parameter with the number of seconds and microseconds used to limit waits for output operations to complete. If a send operation has blocked for this much time, it returns with a partial count or with the error EWOULDBLOCK if no data were sent. In the current implementation, this timer is restarted each time additional data are delivered to the protocol, implying that the limit applies to output portions ranging in size from the low-water mark to the high-water mark for output.
SO_RCVTIMEO
is an option to set a timeout value for input operations. It accepts a struct timeval parameter with the number of seconds and microseconds used to limit waits for input operations to complete. In the current implementation, this timer is restarted each time additional data are received by the protocol, and thus the limit is in effect an inactivity timer. If a receive operation has been blocked for this much time without receiving additional data, it returns with a short count or with the error EWOULDBLOCK if no data were received. The struct timeval parameter must represent a positive time interval; otherwise, setsockopt() returns with the error EDOM.
Checking for an empty field with MySQL
Yes, what you are doing is correct. You are checking to make sure the email field is not an empty string. NULL means the data is missing. An empty string ""
is a blank string with the length of 0.
You can add the null check also
AND (email != "" OR email IS NOT NULL)
Does Arduino use C or C++?
Both are supported. To quote the Arduino homepage,
The core libraries are written in C and C++ and compiled using avr-gcc
Note that C++ is a superset of C (well, almost), and thus can often look very similar. I am not an expert, but I guess that most of what you will program for the Arduino in your first year on that platform will not need anything but plain C.
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:
- Apply -XX:+UseParallelGC when you require parallel collection method over YOUNG generation ONLY, (but still) use serial-mark-sweep method as OLD generation collection
- Apply -XX:+UseParallelOldGC when you require parallel collection method over YOUNG generation (automatically sets -XX:+UseParallelGC) AND OLD generation collection
- 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
- 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
How to convert a HTMLElement to a string
Suppose your element is entire [object HTMLDocument]
. You can convert it to a String this way:
_x000D_
_x000D_
const htmlTemplate = `<!DOCTYPE html><html lang="en"><head></head><body></body></html>`;
const domparser = new DOMParser();
const doc = domparser.parseFromString(htmlTemplate, "text/html"); // [object HTMLDocument]
const doctype = '<!DOCTYPE html>';
const html = doc.documentElement.outerHTML;
console.log(doctype + html);
_x000D_
_x000D_
_x000D_
How to save a list to a file and read it as a list type?
If you want you can use numpy's save function to save the list as file.
Say you have two lists
sampleList1=['z','x','a','b']
sampleList2=[[1,2],[4,5]]
here's the function to save the list as file, remember you need to keep the extension .npy
def saveList(myList,filename):
# the filename should mention the extension 'npy'
np.save(filename,myList)
print("Saved successfully!")
and here's the function to load the file into a list
def loadList(filename):
# the filename should mention the extension 'npy'
tempNumpyArray=np.load(filename)
return tempNumpyArray.tolist()
a working example
>>> saveList(sampleList1,'sampleList1.npy')
>>> Saved successfully!
>>> saveList(sampleList2,'sampleList2.npy')
>>> Saved successfully!
# loading the list now
>>> loadedList1=loadList('sampleList1.npy')
>>> loadedList2=loadList('sampleList2.npy')
>>> loadedList1==sampleList1
>>> True
>>> print(loadedList1,sampleList1)
>>> ['z', 'x', 'a', 'b'] ['z', 'x', 'a', 'b']
Change input value onclick button - pure javascript or jQuery
Try This(Simple javascript):-
_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<script>_x000D_
function change(value){_x000D_
document.getElementById("count").value= 500*value;_x000D_
document.getElementById("totalValue").innerHTML= "Total price: $" + 500*value;_x000D_
}_x000D_
_x000D_
</script>_x000D_
<body>_x000D_
Product price: $500_x000D_
<br>_x000D_
<div id= "totalValue">Total price: $500 </div>_x000D_
<br>_x000D_
<input type="button" onclick="change(2)" value="2
Qty">_x000D_
<input type="button" onclick="change(4)" value="4
Qty">_x000D_
<br>_x000D_
Total <input type="text" id="count" value="1">_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_
Hope this will help you..
How to sanity check a date in Java
java.time
With the Date and Time API (java.time classes) built into Java 8 and later, you can use the LocalDate
class.
public static boolean isDateValid(int year, int month, int day) {
boolean dateIsValid = true;
try {
LocalDate.of(year, month, day);
} catch (DateTimeException e) {
dateIsValid = false;
}
return dateIsValid;
}
Execute a command in command prompt using excel VBA
The S parameter does not do anything on its own.
/S Modifies the treatment of string after /C or /K (see below)
/C Carries out the command specified by string and then terminates
/K Carries out the command specified by string but remains
Try something like this instead
Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)
You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.
Shell("perl a.pl c:\temp")
-Edit-
To wait for the command to finish you will have to do something like @Nate Hekman shows in his answer here
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn
How to convert JSON string to array
You can convert json Object into Array & String.
$data='{"resultList":[{"id":"1839","displayName":"Analytics","subLine":""},{"id":"1015","displayName":"Automation","subLine":""},{"id":"1084","displayName":"Aviation","subLine":""},{"id":"554","displayName":"Apparel","subLine":""},{"id":"875","displayName":"Aerospace","subLine":""},{"id":"1990","displayName":"Account Reconciliation","subLine":""},{"id":"3657","displayName":"Android","subLine":""},{"id":"1262","displayName":"Apache","subLine":""},{"id":"1440","displayName":"Acting","subLine":""},{"id":"710","displayName":"Aircraft","subLine":""},{"id":"12187","displayName":"AAC","subLine":""}, {"id":"20365","displayName":"AAT","subLine":""}, {"id":"7849","displayName":"AAP","subLine":""}, {"id":"20511","displayName":"AACR2","subLine":""}, {"id":"28585","displayName":"AASHTO","subLine":""}, {"id":"45191","displayName":"AAMS","subLine":""}]}';
$b=json_decode($data);
$i=0;
while($b->{'resultList'}[$i])
{
print_r($b->{'resultList'}[$i]->{'displayName'});
echo "<br />";
$i++;
}
Argument list too long error for rm, cp, mv commands
tl;dr
It's a kernel limitation on the size of the command line argument. Use a for
loop instead.
Origin of problem
This is a system issue, related to execve
and ARG_MAX
constant. There is plenty of documentation about that (see man execve, debian's wiki).
Basically, the expansion produce a command (with its parameters) that exceeds the ARG_MAX
limit.
On kernel 2.6.23
, the limit was set at 128 kB
. This constant has been increased and you can get its value by executing:
getconf ARG_MAX
# 2097152 # on 3.5.0-40-generic
Solution: Using for
Loop
Use a for
loop as it's recommended on BashFAQ/095 and there is no limit except for RAM/memory space:
Dry run to ascertain it will delete what you expect:
for f in *.pdf; do echo rm "$f"; done
And execute it:
for f in *.pdf; do rm "$f"; done
Also this is a portable approach as glob have strong and consistant behavior among shells (part of POSIX spec).
Note: As noted by several comments, this is indeed slower but more maintainable as it can adapt more complex scenarios, e.g. where one want to do more than just one action.
Solution: Using find
If you insist, you can use find
but really don't use xargs as it "is dangerous (broken, exploitable, etc.) when reading non-NUL-delimited input":
find . -maxdepth 1 -name '*.pdf' -delete
Using -maxdepth 1 ... -delete
instead of -exec rm {} +
allows find
to simply execute the required system calls itself without using an external process, hence faster (thanks to @chepner comment).
References
Why is synchronized block better than synchronized method?
In your case both are equivalent!
Synchronizing a static method is equivalent to a synchronized block on corresponding Class object.
In fact when you declare a synchronized static method lock is obtained on the monitor corresponding to the Class object.
public static synchronized int getCount() {
// ...
}
is same as
public int getCount() {
synchronized (ClassName.class) {
// ...
}
}
How to calculate the width of a text string of a specific font and font-size?
This simple extension in Swift works well.
extension String {
func size(OfFont font: UIFont) -> CGSize {
return (self as NSString).size(attributes: [NSFontAttributeName: font])
}
}
Usage:
let string = "hello world!"
let font = UIFont.systemFont(ofSize: 12)
let width = string.size(OfFont: font).width // size: {w: 98.912 h: 14.32}
batch file to copy files to another location?
@echo off
cls
echo press any key to continue backup !
pause
xcopy c:\users\file*.* e:\backup*.* /s /e
echo backup complete
pause
file = name of file your wanting to copy
backup = where u want the file to be moved to
Hope this helps
Pass array to MySQL stored routine
I'm not sure if this is fully answering the question (it isn't), but it's the solution I came up with for my similar problem. Here I try to just use LOCATE() just once per delimiter.
-- *****************************************************************************
-- test_PVreplace
DROP FUNCTION IF EXISTS test_PVreplace;
delimiter //
CREATE FUNCTION test_PVreplace (
str TEXT, -- String to do search'n'replace on
pv TEXT -- Parameter/value pairs 'p1=v1|p2=v2|p3=v3'
)
RETURNS TEXT
-- Replace specific tags with specific values.
sproc:BEGIN
DECLARE idx INT;
DECLARE idx0 INT DEFAULT 1; -- 1-origined, not 0-origined
DECLARE len INT;
DECLARE sPV TEXT;
DECLARE iPV INT;
DECLARE sP TEXT;
DECLARE sV TEXT;
-- P/V string *must* end with a delimiter.
IF (RIGHT (pv, 1) <> '|') THEN
SET pv = CONCAT (pv, '|');
END IF;
-- Find all the P/V pairs.
SELECT LOCATE ('|', pv, idx0) INTO idx;
WHILE (idx > 0) DO
SET len = idx - idx0;
SELECT SUBSTRING(pv, idx0, len) INTO sPV;
-- Found a P/V pair. Break it up.
SELECT LOCATE ('=', sPV) INTO iPV;
IF (iPV = 0) THEN
SET sP = sPV;
SET sV = '';
ELSE
SELECT SUBSTRING(sPV, 1, iPV-1) INTO sP;
SELECT SUBSTRING(sPV, iPV+1) INTO sV;
END IF;
-- Do the substitution(s).
SELECT REPLACE (str, sP, sV) INTO str;
-- Do next P/V pair.
SET idx0 = idx + 1;
SELECT LOCATE ('|', pv, idx0) INTO idx;
END WHILE;
RETURN (str);
END//
delimiter ;
SELECT test_PVreplace ('%one% %two% %three%', '%one%=1|%two%=2|%three%=3');
SELECT test_PVreplace ('%one% %two% %three%', '%one%=I|%two%=II|%three%=III');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', '%one%=I|%two%=II|%three%=III');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', '');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', NULL);
SELECT test_PVreplace ('%one% %two% %three%', '%one%=%two%|%two%=%three%|%three%=III');
How to delete and update a record in Hive
As of Hive version 0.14.0: INSERT...VALUES, UPDATE, and DELETE are now available with full ACID support.
INSERT ... VALUES Syntax:
INSERT INTO TABLE tablename [PARTITION (partcol1[=val1], partcol2[=val2] ...)] VALUES values_row [, values_row ...]
Where values_row is:
( value [, value ...] )
where a value is either null or any valid SQL literal
UPDATE Syntax:
UPDATE tablename SET column = value [, column = value ...] [WHERE expression]
DELETE Syntax:
DELETE FROM tablename [WHERE expression]
Additionally, from the Hive Transactions doc:
If a table is to be used in ACID writes (insert, update, delete) then the table property "transactional" must be set on that table, starting with Hive 0.14.0. Without this value, inserts will be done in the old style; updates and deletes will be prohibited.
Hive DML reference:
https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DML
Hive Transactions reference:
https://cwiki.apache.org/confluence/display/Hive/Hive+Transactions
Java - get the current class name?
Try using this
this.getClass().getCanonicalName()
or this.getClass().getSimpleName()
. If it's an anonymous class, use this.getClass().getSuperclass().getName()
How to find GCD, LCM on a set of numbers
Basically to find gcd and lcm on a set of numbers you can use below formula,
LCM(a, b) X HCF(a, b) = a * b
Meanwhile in java you can use euclid's algorithm to find gcd and lcm, like this
public static int GCF(int a, int b)
{
if (b == 0)
{
return a;
}
else
{
return (GCF(b, a % b));
}
}
You can refer this resource to find examples on euclid's algorithm.
How to re-create database for Entity Framework?
Follow below steps:
1) First go to Server Explorer in Visual Studio, check if the ".mdf" Data Connections for this project are connected, if so, right click and delete.
2 )Go to Solution Explorer, click show All Files icon.
3) Go to App_Data, right click and delete all ".mdf" files for this project.
4) Delete Migrations folder by right click and delete.
5) Go to SQL Server Management Studio, make sure the DB for this project is not there, otherwise delete it.
6) Go to Package Manager Console in Visual Studio and type:
Enable-Migrations -Force
Add-Migration init
Update-Database
7) Run your application
Note: In step 6 part 3, if you get an error "Cannot attach the file...", it is possibly because you didn't delete the database files completely in SQL Server.
JUnit assertEquals(double expected, double actual, double epsilon)
Epsilon is your "fuzz factor," since doubles may not be exactly equal. Epsilon lets you describe how close they have to be.
If you were expecting 3.14159 but would take anywhere from 3.14059 to 3.14259 (that is, within 0.001), then you should write something like
double myPi = 22.0d / 7.0d; //Don't use this in real life!
assertEquals(3.14159, myPi, 0.001);
(By the way, 22/7 comes out to 3.1428+, and would fail the assertion. This is a good thing.)
How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?
I modified from @PsychoCoder.
All controls could be found now (include nested).
public static IEnumerable<T> GetChildrens<T>(Control control)
{
var type = typeof (T);
var allControls = GetAllChildrens(control);
return allControls.Where(c => c.GetType() == type).Cast<T>();
}
private static IEnumerable<Control> GetAllChildrens(Control control)
{
var controls = control.Controls.Cast<Control>();
return controls.SelectMany(c => GetAllChildrens(c))
.Concat(controls);
}
How to upload a file from Windows machine to Linux machine using command lines via PuTTy?
Pscp.exe is painfully slow.
Uploading files using WinSCP is like 10 times faster.
So, to do that from command line, first you got to add the winscp.com
file to your %PATH%. It's not a top-level domain, but an executable .com
file, which is located in your WinSCP installation directory.
Then just issue a simple command and your file will be uploaded much faster putty ever could:
WinSCP.com /command "open sftp://username:[email protected]:22" "put your_large_file.zip /var/www/somedirectory/" "exit"
And make sure your check the synchronize folders feature, which is basically what rsync
does, so you won't ever want to use pscp.exe again.
WinSCP.com /command "help synchronize"
Is there a Subversion command to reset the working copy?
Delete everything inside your local copy using:
rm -r your_local_svn_dir_path/*
And the revert everything recursively using the below command.
svn revert -R your_local_svn_dir_path
This is way faster than deleting the entire directory and then taking a fresh checkout, because the files are being restored from you local SVN meta data. It doesn't even need a network connection.
Why does range(start, end) not include end?
Because it's more common to call range(0, 10)
which returns [0,1,2,3,4,5,6,7,8,9]
which contains 10 elements which equals len(range(0, 10))
. Remember that programmers prefer 0-based indexing.
Also, consider the following common code snippet:
for i in range(len(li)):
pass
Could you see that if range()
went up to exactly len(li)
that this would be problematic? The programmer would need to explicitly subtract 1. This also follows the common trend of programmers preferring for(int i = 0; i < 10; i++)
over for(int i = 0; i <= 9; i++)
.
If you are calling range with a start of 1 frequently, you might want to define your own function:
>>> def range1(start, end):
... return range(start, end+1)
...
>>> range1(1, 10)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
How to insert a blob into a database using sql server management studio
Ok... this took me way too long. The sql-management studio tool is just not up to simple things like this (which I've noticed before when looking for where to set the timeout on queries, and it was done in 4 different locations)
I downloaded some other sql editor package (sql maestro in my case). And behold it includes a blob editor where you can look at blobs, and load new blobs into these field.
thanks for the input!
Simple and clean way to convert JSON string to Object in Swift
Here are some tips how to begin with simple example.
Consider you have following JSON Array String (similar to yours) like:
var list:Array<Business> = []
// left only 2 fields for demo
struct Business {
var id : Int = 0
var name = ""
}
var jsonStringAsArray = "[\n" +
"{\n" +
"\"id\":72,\n" +
"\"name\":\"Batata Cremosa\",\n" +
"},\n" +
"{\n" +
"\"id\":183,\n" +
"\"name\":\"Caldeirada de Peixes\",\n" +
"},\n" +
"{\n" +
"\"id\":76,\n" +
"\"name\":\"Batata com Cebola e Ervas\",\n" +
"},\n" +
"{\n" +
"\"id\":56,\n" +
"\"name\":\"Arroz de forma\",\n" +
"}]"
// convert String to NSData
var data: NSData = jsonStringAsArray.dataUsingEncoding(NSUTF8StringEncoding)!
var error: NSError?
// convert NSData to 'AnyObject'
let anyObj: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0),
error: &error)
println("Error: \(error)")
// convert 'AnyObject' to Array<Business>
list = self.parseJson(anyObj!)
//===============
func parseJson(anyObj:AnyObject) -> Array<Business>{
var list:Array<Business> = []
if anyObj is Array<AnyObject> {
var b:Business = Business()
for json in anyObj as Array<AnyObject>{
b.name = (json["name"] as AnyObject? as? String) ?? "" // to get rid of null
b.id = (json["id"] as AnyObject? as? Int) ?? 0
list.append(b)
}// for
} // if
return list
}//func
[EDIT]
To get rid of null changed to:
b.name = (json["name"] as AnyObject? as? String) ?? ""
b.id = (json["id"] as AnyObject? as? Int) ?? 0
See also Reference of Coalescing Operator (aka ??
)
Hope it will help you to sort things out,
SSRS custom number format
am assuming that you want to know how to format numbers in SSRS
Just right click
the TextBox
on which you want to apply formatting, go to its expression
.
suppose its expression is something like below
=Fields!myField.Value
then do this
=Format(Fields!myField.Value,"##.##")
or
=Format(Fields!myFields.Value,"00.00")
difference between the two is that former one would make 4 as 4 and later one would make 4 as 04.00
this should give you an idea.
also: you might have to convert your field into a numerical one. i.e.
=Format(CDbl(Fields!myFields.Value),"00.00")
so: 0 in format expression means, when no number is present, place a 0 there and # means when no number is present, leave it. Both of them works same when numbers are present
ie. 45.6567 would be 45.65 for both of them:
UPDATE :
if you want to apply variable formatting on the same column based on row values i.e.
you want myField
to have no formatting when it has no decimal value but formatting with double precision when it has decimal then you can do it through logic. (though you should not be doing so)
Go to the appropriate textbox and go to its expression and do this:
=IIF((Fields!myField.Value - CInt(Fields!myField.Value)) > 0,
Format(Fields!myField.Value, "##.##"),Fields!myField.Value)
so basically you are using IIF(condition, true,false)
operator of SSRS,
ur condition is to check whether the number has decimal value, if it has, you apply the formatting and if no, you let it as it is.
this should give you an idea, how to handle variable formatting.
How do I install the babel-polyfill library?
Like Babel says in the docs, for Babel > 7.4.0 the module @babel/polyfill is deprecated, so it's recommended to use directly core-js and regenerator-runtime libraries that before were included in @babel/polyfill.
So this worked for me:
npm install --save [email protected]
npm install regenerator-runtime
then add to the very top of your initial js file:
import 'core-js/stable';
import 'regenerator-runtime/runtime';
cannot resolve symbol javafx.application in IntelliJ Idea IDE
Another way to resolve the problem :
Click the left mouse's button on the project folder in the project structure at the left, and click on "open module settings" in the list of actions
In the new windows, click on SDKs which is under the menu title "Platform settngs"
Then check on the "Classpath" list if you can find the jfxrt plugin path, if not, click on the + symbol on the right and select the repertory of the jfxrt plugin (C:\Program Files\Java\jdk1.8.0\jre\lib\ext\jfxrt.jar on my desktop)
What is the MySQL JDBC driver connection string?
update for mySQL 8 :
String jdbcUrl="jdbc:mysql://localhost:3306/youdatabase?useSSL=false&serverTimezone=UTC";
Check whether your Jdbc configurations and URL correct or wrong using the following code snippet.
import java.sql.Connection;
import java.sql.DriverManager;
public class TestJdbc {
public static void main(String[] args) {
//db name:testdb_version001
//useSSL=false (get rid of MySQL SSL warnings)
String jdbcUrl = "jdbc:mysql://localhost:3306/testdb_version001?useSSL=false";
String username="testdb";
String password ="testdb";
try{
System.out.println("Connecting to database :" +jdbcUrl);
Connection myConn =
DriverManager.getConnection(jdbcUrl,username,password);
System.out.println("Connection Successful...!");
}catch (Exception e){
e.printStackTrace();
//e.printStackTrace();
}
}
}
How to convert float value to integer in php?
Use round()
$float_val = 4.5;
echo round($float_val);
You can also set param for precision and rounding mode, for more info
Update (According to your updated question):
$float_val = 1.0000124668092E+14;
printf('%.0f', $float_val / 1E+14); //Output Rounds Of To 1000012466809201
Is there a float input type in HTML5?
Using React on my IPad, type="number"
does not work perfectly for me.
For my floating point numbers in the range between 99.99999 - .00000 I use the regular expression (^[0-9]{0,2}$)|(^[0-9]{0,2}\.[0-9]{0,5}$)
. The first group (...)
is true for all positive two digit numbers without the floating point (e.g. 23), |
or e.g. .12345 for the second group (...)
. You can adopt it for any positive floating point number by simply changing the range {0,2}
or {0,5}
respectively.
<input
className="center-align"
type="text"
pattern="(^[0-9]{0,2}$)|(^[0-9]{0,2}\.[0-9]{0,5}$)"
step="any"
maxlength="7"
validate="true"
/>
Unsupported method: BaseConfig.getApplicationIdSuffix()
I did the following to make this run on AS 3.5
app/ build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "25.0.0"
defaultConfig {
applicationId "com.example.android.mobileperf.render"
minSdkVersion 14
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:21.0.0'
implementation 'com.squareup.picasso:picasso:2.71828'
}
build.gradle
buildscript {
repositories {
jcenter()
mavenCentral()
maven {
url 'https://maven.google.com/'
name 'Google'
}
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
}
}
allprojects {
repositories {
jcenter()
google()
}
}
gradle-wrapper.properties
distributionUrl=https://services.gradle.org/distributions/gradle-4.1-all.zip
Read from a gzip file in python
Try gzipping some data through the gzip libary like this...
import gzip
content = "Lots of content here"
f = gzip.open('Onlyfinnaly.log.gz', 'wb')
f.write(content)
f.close()
... then run your code as posted ...
import gzip
f=gzip.open('Onlyfinnaly.log.gz','rb')
file_content=f.read()
print file_content
This method worked for me as for some reason the gzip library fails to read some files.
Prevent row names to be written to file when using write.csv
For completeness, write_csv()
from the readr
package is faster and never writes row names
# install.packages('readr', dependencies = TRUE)
library(readr)
write_csv(t, "t.csv")
If you need to write big data out, use fwrite()
from the data.table
package. It's much faster than both write.csv
and write_csv
# install.packages('data.table')
library(data.table)
fwrite(t, "t.csv")
Below is a benchmark that Edouard published on his site
microbenchmark(write.csv(data, "baseR_file.csv", row.names = F),
write_csv(data, "readr_file.csv"),
fwrite(data, "datatable_file.csv"),
times = 10, unit = "s")
## Unit: seconds
## expr min lq mean median uq max neval
## write.csv(data, "baseR_file.csv", row.names = F) 13.8066424 13.8248250 13.9118324 13.8776993 13.9269675 14.3241311 10
## write_csv(data, "readr_file.csv") 3.6742610 3.7999409 3.8572456 3.8690681 3.8991995 4.0637453 10
## fwrite(data, "datatable_file.csv") 0.3976728 0.4014872 0.4097876 0.4061506 0.4159007 0.4355469 10
How to verify a Text present in the loaded page through WebDriver
Below code is most suitable way to verify a text on page. You can use any one out of 8 locators as per your convenience.
String Verifytext= driver.findElement(By.tagName("body")).getText().trim();
Assert.assertEquals(Verifytext, "Paste the text here which needs to be verified");
How do you use MySQL's source command to import large files in windows
On windows:
Use explorer to navigate to the folder with the .sql file.
Type cmd in the top address bar. Cmd will open.
Type:
"C:\path\to\mysql.exe" -u "your_username" -p "your password" < "name_of_your_sql_file.sql"
Wait a bit and the sql file will have been executed on your database.
Confirmed to work with MariaDB in feb 2018.
Declaring variables inside loops, good practice or bad practice?
Once upon a time (pre C++98); the following would break:
{
for (int i=0; i<.; ++i) {std::string foo;}
for (int i=0; i<.; ++i) {std::string foo;}
}
with the warning that i was already declared (foo was fine as that's scoped within the {}). This is likely the WHY people would first argue it's bad. It stopped being true a long time ago though.
If you STILL have to support such an old compiler (some people are on Borland) then the answer is yes, a case could be made to put the i out the loop, because not doing so makes it makes it "harder" for people to put multiple loops in with the same variable, though honestly the compiler will still fail, which is all you want if there's going to be a problem.
If you no longer have to support such an old compiler, variables should be kept to the smallest scope you can get them so that you not only minimise the memory usage; but also make understanding the project easier. It's a bit like asking why don't you have all your variables global. Same argument applies, but the scopes just change a bit.
Changing Font Size For UITableView Section Headers
With this method you can set font size, font style and Header background also.
there are have 2 method for this
First Method
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
header.backgroundView.backgroundColor = [UIColor darkGrayColor];
header.textLabel.font=[UIFont fontWithName:@"Open Sans-Regular" size:12];
[header.textLabel setTextColor:[UIColor whiteColor]];
}
Second Method
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 30)];
// myLabel.frame = CGRectMake(20, 8, 320, 20);
myLabel.font = [UIFont fontWithName:@"Open Sans-Regular" size:12];
myLabel.text = [NSString stringWithFormat:@" %@",[self tableView:FilterSearchTable titleForHeaderInSection:section]];
myLabel.backgroundColor=[UIColor blueColor];
myLabel.textColor=[UIColor whiteColor];
UIView *headerView = [[UIView alloc] init];
[headerView addSubview:myLabel];
return headerView;
}
Get child node index
<body>
<section>
<section onclick="childIndex(this)">child a</section>
<section onclick="childIndex(this)">child b</section>
<section onclick="childIndex(this)">child c</section>
</section>
<script>
function childIndex(e){
let i = 0;
while (e.parentNode.children[i] != e) i++;
alert('child index '+i);
}
</script>
</body>
Spark : how to run spark file from spark shell
You can use either sbt or maven to compile spark programs. Simply add the spark as dependency to maven
<repository>
<id>Spark repository</id>
<url>http://www.sparkjava.com/nexus/content/repositories/spark/</url>
</repository>
And then the dependency:
<dependency>
<groupId>spark</groupId>
<artifactId>spark</artifactId>
<version>1.2.0</version>
</dependency>
In terms of running a file with spark commands: you can simply do this:
echo"
import org.apache.spark.sql.*
ssc = new SQLContext(sc)
ssc.sql("select * from mytable").collect
" > spark.input
Now run the commands script:
cat spark.input | spark-shell
onclick open window and specific size
These are the best practices from Mozilla Developer Network's window.open page :
<script type="text/javascript">
var windowObjectReference = null; // global variable
function openFFPromotionPopup() {
if(windowObjectReference == null || windowObjectReference.closed)
/* if the pointer to the window object in memory does not exist
or if such pointer exists but the window was closed */
{
windowObjectReference = window.open("http://www.spreadfirefox.com/",
"PromoteFirefoxWindowName", "resizable,scrollbars,status");
/* then create it. The new window will be created and
will be brought on top of any other window. */
}
else
{
windowObjectReference.focus();
/* else the window reference must exist and the window
is not closed; therefore, we can bring it back on top of any other
window with the focus() method. There would be no need to re-create
the window or to reload the referenced resource. */
};
}
</script>
<p><a
href="http://www.spreadfirefox.com/"
target="PromoteFirefoxWindowName"
onclick="openFFPromotionPopup(); return false;"
title="This link will create a new window or will re-use an already opened one"
>Promote Firefox adoption</a></p>
What's the difference between a temp table and table variable in SQL Server?
Just looking at the claim in the accepted answer that table variables don't participate in logging.
It seems generally untrue that there is any difference in quantity of logging (at least for insert
/update
/delete
operations to the table itself though I have since found that there is some small difference in this respect for cached temporary objects in stored procedures due to additional system table updates).
I looked at the logging behaviour against both a @table_variable
and a #temp
table for the following operations.
- Successful Insert
- Multi Row Insert where statement rolled back due to constraint violation.
- Update
- Delete
- Deallocate
The transaction log records were almost identical for all operations.
The table variable version actually has a few extra log entries because it gets an entry added to (and later removed from) the sys.syssingleobjrefs
base table but overall had a few less bytes logged purely as the internal name for table variables consumes 236 less bytes than for #temp
tables (118 fewer nvarchar
characters).
Full script to reproduce (best run on an instance started in single user mode and using sqlcmd
mode)
:setvar tablename "@T"
:setvar tablescript "DECLARE @T TABLE"
/*
--Uncomment this section to test a #temp table
:setvar tablename "#T"
:setvar tablescript "CREATE TABLE #T"
*/
USE tempdb
GO
CHECKPOINT
DECLARE @LSN NVARCHAR(25)
SELECT @LSN = MAX([Current LSN])
FROM fn_dblog(null, null)
EXEC(N'BEGIN TRAN StartBatch
SAVE TRAN StartBatch
COMMIT
$(tablescript)
(
[4CA996AC-C7E1-48B5-B48A-E721E7A435F0] INT PRIMARY KEY DEFAULT 0,
InRowFiller char(7000) DEFAULT ''A'',
OffRowFiller varchar(8000) DEFAULT REPLICATE(''B'',8000),
LOBFiller varchar(max) DEFAULT REPLICATE(cast(''C'' as varchar(max)),10000)
)
BEGIN TRAN InsertFirstRow
SAVE TRAN InsertFirstRow
COMMIT
INSERT INTO $(tablename)
DEFAULT VALUES
BEGIN TRAN Insert9Rows
SAVE TRAN Insert9Rows
COMMIT
INSERT INTO $(tablename) ([4CA996AC-C7E1-48B5-B48A-E721E7A435F0])
SELECT TOP 9 ROW_NUMBER() OVER (ORDER BY (SELECT 0))
FROM sys.all_columns
BEGIN TRAN InsertFailure
SAVE TRAN InsertFailure
COMMIT
/*Try and Insert 10 rows, the 10th one will cause a constraint violation*/
BEGIN TRY
INSERT INTO $(tablename) ([4CA996AC-C7E1-48B5-B48A-E721E7A435F0])
SELECT TOP (10) (10 + ROW_NUMBER() OVER (ORDER BY (SELECT 0))) % 20
FROM sys.all_columns
END TRY
BEGIN CATCH
PRINT ERROR_MESSAGE()
END CATCH
BEGIN TRAN Update10Rows
SAVE TRAN Update10Rows
COMMIT
UPDATE $(tablename)
SET InRowFiller = LOWER(InRowFiller),
OffRowFiller =LOWER(OffRowFiller),
LOBFiller =LOWER(LOBFiller)
BEGIN TRAN Delete10Rows
SAVE TRAN Delete10Rows
COMMIT
DELETE FROM $(tablename)
BEGIN TRAN AfterDelete
SAVE TRAN AfterDelete
COMMIT
BEGIN TRAN EndBatch
SAVE TRAN EndBatch
COMMIT')
DECLARE @LSN_HEX NVARCHAR(25) =
CAST(CAST(CONVERT(varbinary,SUBSTRING(@LSN, 1, 8),2) AS INT) AS VARCHAR) + ':' +
CAST(CAST(CONVERT(varbinary,SUBSTRING(@LSN, 10, 8),2) AS INT) AS VARCHAR) + ':' +
CAST(CAST(CONVERT(varbinary,SUBSTRING(@LSN, 19, 4),2) AS INT) AS VARCHAR)
SELECT
[Operation],
[Context],
[AllocUnitName],
[Transaction Name],
[Description]
FROM fn_dblog(@LSN_HEX, null) AS D
WHERE [Current LSN] > @LSN
SELECT CASE
WHEN GROUPING(Operation) = 1 THEN 'Total'
ELSE Operation
END AS Operation,
Context,
AllocUnitName,
COALESCE(SUM([Log Record Length]), 0) AS [Size in Bytes],
COUNT(*) AS Cnt
FROM fn_dblog(@LSN_HEX, null) AS D
WHERE [Current LSN] > @LSN
GROUP BY GROUPING SETS((Operation, Context, AllocUnitName),())
Results
+-----------------------+--------------------+---------------------------+---------------+------+---------------+------+------------------+
| | | | @TV | #TV | |
+-----------------------+--------------------+---------------------------+---------------+------+---------------+------+------------------+
| Operation | Context | AllocUnitName | Size in Bytes | Cnt | Size in Bytes | Cnt | Difference Bytes |
+-----------------------+--------------------+---------------------------+---------------+------+---------------+------+------------------+
| LOP_ABORT_XACT | LCX_NULL | | 52 | 1 | 52 | 1 | |
| LOP_BEGIN_XACT | LCX_NULL | | 6056 | 50 | 6056 | 50 | |
| LOP_COMMIT_XACT | LCX_NULL | | 2548 | 49 | 2548 | 49 | |
| LOP_COUNT_DELTA | LCX_CLUSTERED | sys.sysallocunits.clust | 624 | 3 | 624 | 3 | |
| LOP_COUNT_DELTA | LCX_CLUSTERED | sys.sysrowsets.clust | 208 | 1 | 208 | 1 | |
| LOP_COUNT_DELTA | LCX_CLUSTERED | sys.sysrscols.clst | 832 | 4 | 832 | 4 | |
| LOP_CREATE_ALLOCCHAIN | LCX_NULL | | 120 | 3 | 120 | 3 | |
| LOP_DELETE_ROWS | LCX_INDEX_INTERIOR | Unknown Alloc Unit | 720 | 9 | 720 | 9 | |
| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysallocunits.clust | 444 | 3 | 444 | 3 | |
| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysallocunits.nc | 276 | 3 | 276 | 3 | |
| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.syscolpars.clst | 628 | 4 | 628 | 4 | |
| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.syscolpars.nc | 484 | 4 | 484 | 4 | |
| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysidxstats.clst | 176 | 1 | 176 | 1 | |
| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysidxstats.nc | 144 | 1 | 144 | 1 | |
| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysiscols.clst | 100 | 1 | 100 | 1 | |
| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysiscols.nc1 | 88 | 1 | 88 | 1 | |
| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysobjvalues.clst | 596 | 5 | 596 | 5 | |
| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysrowsets.clust | 132 | 1 | 132 | 1 | |
| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysrscols.clst | 528 | 4 | 528 | 4 | |
| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysschobjs.clst | 1040 | 6 | 1276 | 6 | 236 |
| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysschobjs.nc1 | 820 | 6 | 1060 | 6 | 240 |
| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysschobjs.nc2 | 820 | 6 | 1060 | 6 | 240 |
| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysschobjs.nc3 | 480 | 6 | 480 | 6 | |
| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.syssingleobjrefs.clst | 96 | 1 | | | -96 |
| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.syssingleobjrefs.nc1 | 88 | 1 | | | -88 |
| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | Unknown Alloc Unit | 72092 | 19 | 72092 | 19 | |
| LOP_DELETE_ROWS | LCX_TEXT_MIX | Unknown Alloc Unit | 16348 | 37 | 16348 | 37 | |
| LOP_FORMAT_PAGE | LCX_HEAP | Unknown Alloc Unit | 1596 | 19 | 1596 | 19 | |
| LOP_FORMAT_PAGE | LCX_IAM | Unknown Alloc Unit | 252 | 3 | 252 | 3 | |
| LOP_FORMAT_PAGE | LCX_INDEX_INTERIOR | Unknown Alloc Unit | 84 | 1 | 84 | 1 | |
| LOP_FORMAT_PAGE | LCX_TEXT_MIX | Unknown Alloc Unit | 4788 | 57 | 4788 | 57 | |
| LOP_HOBT_DDL | LCX_NULL | | 108 | 3 | 108 | 3 | |
| LOP_HOBT_DELTA | LCX_NULL | | 9600 | 150 | 9600 | 150 | |
| LOP_INSERT_ROWS | LCX_CLUSTERED | sys.sysallocunits.clust | 456 | 3 | 456 | 3 | |
| LOP_INSERT_ROWS | LCX_CLUSTERED | sys.syscolpars.clst | 644 | 4 | 644 | 4 | |
| LOP_INSERT_ROWS | LCX_CLUSTERED | sys.sysidxstats.clst | 180 | 1 | 180 | 1 | |
| LOP_INSERT_ROWS | LCX_CLUSTERED | sys.sysiscols.clst | 104 | 1 | 104 | 1 | |
| LOP_INSERT_ROWS | LCX_CLUSTERED | sys.sysobjvalues.clst | 616 | 5 | 616 | 5 | |
| LOP_INSERT_ROWS | LCX_CLUSTERED | sys.sysrowsets.clust | 136 | 1 | 136 | 1 | |
| LOP_INSERT_ROWS | LCX_CLUSTERED | sys.sysrscols.clst | 544 | 4 | 544 | 4 | |
| LOP_INSERT_ROWS | LCX_CLUSTERED | sys.sysschobjs.clst | 1064 | 6 | 1300 | 6 | 236 |
| LOP_INSERT_ROWS | LCX_CLUSTERED | sys.syssingleobjrefs.clst | 100 | 1 | | | -100 |
| LOP_INSERT_ROWS | LCX_CLUSTERED | Unknown Alloc Unit | 135888 | 19 | 135888 | 19 | |
| LOP_INSERT_ROWS | LCX_INDEX_INTERIOR | Unknown Alloc Unit | 1596 | 19 | 1596 | 19 | |
| LOP_INSERT_ROWS | LCX_INDEX_LEAF | sys.sysallocunits.nc | 288 | 3 | 288 | 3 | |
| LOP_INSERT_ROWS | LCX_INDEX_LEAF | sys.syscolpars.nc | 500 | 4 | 500 | 4 | |
| LOP_INSERT_ROWS | LCX_INDEX_LEAF | sys.sysidxstats.nc | 148 | 1 | 148 | 1 | |
| LOP_INSERT_ROWS | LCX_INDEX_LEAF | sys.sysiscols.nc1 | 92 | 1 | 92 | 1 | |
| LOP_INSERT_ROWS | LCX_INDEX_LEAF | sys.sysschobjs.nc1 | 844 | 6 | 1084 | 6 | 240 |
| LOP_INSERT_ROWS | LCX_INDEX_LEAF | sys.sysschobjs.nc2 | 844 | 6 | 1084 | 6 | 240 |
| LOP_INSERT_ROWS | LCX_INDEX_LEAF | sys.sysschobjs.nc3 | 504 | 6 | 504 | 6 | |
| LOP_INSERT_ROWS | LCX_INDEX_LEAF | sys.syssingleobjrefs.nc1 | 92 | 1 | | | -92 |
| LOP_INSERT_ROWS | LCX_TEXT_MIX | Unknown Alloc Unit | 5112 | 71 | 5112 | 71 | |
| LOP_MARK_SAVEPOINT | LCX_NULL | | 508 | 8 | 508 | 8 | |
| LOP_MODIFY_COLUMNS | LCX_CLUSTERED | Unknown Alloc Unit | 1560 | 10 | 1560 | 10 | |
| LOP_MODIFY_HEADER | LCX_HEAP | Unknown Alloc Unit | 3780 | 45 | 3780 | 45 | |
| LOP_MODIFY_ROW | LCX_CLUSTERED | sys.syscolpars.clst | 384 | 4 | 384 | 4 | |
| LOP_MODIFY_ROW | LCX_CLUSTERED | sys.sysidxstats.clst | 100 | 1 | 100 | 1 | |
| LOP_MODIFY_ROW | LCX_CLUSTERED | sys.sysrowsets.clust | 92 | 1 | 92 | 1 | |
| LOP_MODIFY_ROW | LCX_CLUSTERED | sys.sysschobjs.clst | 1144 | 13 | 1144 | 13 | |
| LOP_MODIFY_ROW | LCX_IAM | Unknown Alloc Unit | 4224 | 48 | 4224 | 48 | |
| LOP_MODIFY_ROW | LCX_PFS | Unknown Alloc Unit | 13632 | 169 | 13632 | 169 | |
| LOP_MODIFY_ROW | LCX_TEXT_MIX | Unknown Alloc Unit | 108640 | 120 | 108640 | 120 | |
| LOP_ROOT_CHANGE | LCX_CLUSTERED | sys.sysallocunits.clust | 960 | 10 | 960 | 10 | |
| LOP_SET_BITS | LCX_GAM | Unknown Alloc Unit | 1200 | 20 | 1200 | 20 | |
| LOP_SET_BITS | LCX_IAM | Unknown Alloc Unit | 1080 | 18 | 1080 | 18 | |
| LOP_SET_BITS | LCX_SGAM | Unknown Alloc Unit | 120 | 2 | 120 | 2 | |
| LOP_SHRINK_NOOP | LCX_NULL | | | | 32 | 1 | 32 |
+-----------------------+--------------------+---------------------------+---------------+------+---------------+------+------------------+
| Total | | | 410144 | 1095 | 411232 | 1092 | 1088 |
+-----------------------+--------------------+---------------------------+---------------+------+---------------+------+------------------+
Firing a Keyboard Event in Safari, using JavaScript
I am working on DOM Keyboard Event Level 3 polyfill . In latest browsers or with this polyfill you can do something like this:
element.addEventListener("keydown", function(e){ console.log(e.key, e.char, e.keyCode) })
var e = new KeyboardEvent("keydown", {bubbles : true, cancelable : true, key : "Q", char : "Q", shiftKey : true});
element.dispatchEvent(e);
//If you need legacy property "keyCode"
// Note: In some browsers you can't overwrite "keyCode" property. (At least in Safari)
delete e.keyCode;
Object.defineProperty(e, "keyCode", {"value" : 666})
UPDATE:
Now my polyfill supports legacy properties "keyCode", "charCode" and "which"
var e = new KeyboardEvent("keydown", {
bubbles : true,
cancelable : true,
char : "Q",
key : "q",
shiftKey : true,
keyCode : 81
});
Examples here
Additionally here is cross-browser initKeyboardEvent separately from my polyfill: (gist)
Polyfill demo
Trouble using ROW_NUMBER() OVER (PARTITION BY ...)
A bit involved. Easiest would be to refer to this SQL Fiddle I created for you that produces the exact result. There are ways you can improve it for performance or other considerations, but this should hopefully at least be clearer than some alternatives.
The gist is, you get a canonical ranking of your data first, then use that to segment the data into groups, then find an end date for each group, then eliminate any intermediate rows. ROW_NUMBER() and CROSS APPLY help a lot in doing it readably.
EDIT 2019:
The SQL Fiddle does in fact seem to be broken, for some reason, but it appears to be a problem on the SQL Fiddle site. Here's a complete version, tested just now on SQL Server 2016:
CREATE TABLE Source
(
EmployeeID int,
DateStarted date,
DepartmentID int
)
INSERT INTO Source
VALUES
(10001,'2013-01-01',001),
(10001,'2013-09-09',001),
(10001,'2013-12-01',002),
(10001,'2014-05-01',002),
(10001,'2014-10-01',001),
(10001,'2014-12-01',001)
SELECT *,
ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS EntryRank,
newid() as GroupKey,
CAST(NULL AS date) AS EndDate
INTO #RankedData
FROM Source
;
UPDATE #RankedData
SET GroupKey = beginDate.GroupKey
FROM #RankedData sup
CROSS APPLY
(
SELECT TOP 1 GroupKey
FROM #RankedData sub
WHERE sub.EmployeeID = sup.EmployeeID AND
sub.DepartmentID = sup.DepartmentID AND
NOT EXISTS
(
SELECT *
FROM #RankedData bot
WHERE bot.EmployeeID = sup.EmployeeID AND
bot.EntryRank BETWEEN sub.EntryRank AND sup.EntryRank AND
bot.DepartmentID <> sup.DepartmentID
)
ORDER BY DateStarted ASC
) beginDate (GroupKey);
UPDATE #RankedData
SET EndDate = nextGroup.DateStarted
FROM #RankedData sup
CROSS APPLY
(
SELECT TOP 1 DateStarted
FROM #RankedData sub
WHERE sub.EmployeeID = sup.EmployeeID AND
sub.DepartmentID <> sup.DepartmentID AND
sub.EntryRank > sup.EntryRank
ORDER BY EntryRank ASC
) nextGroup (DateStarted);
SELECT * FROM
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY GroupKey ORDER BY EntryRank ASC) AS GroupRank FROM #RankedData
) FinalRanking
WHERE GroupRank = 1
ORDER BY EntryRank;
DROP TABLE #RankedData
DROP TABLE Source
How to sort with a lambda?
Can the problem be with the "a.mProperty > b.mProperty" line? I've gotten the following code to work:
#include <algorithm>
#include <vector>
#include <iterator>
#include <iostream>
#include <sstream>
struct Foo
{
Foo() : _i(0) {};
int _i;
friend std::ostream& operator<<(std::ostream& os, const Foo& f)
{
os << f._i;
return os;
};
};
typedef std::vector<Foo> VectorT;
std::string toString(const VectorT& v)
{
std::stringstream ss;
std::copy(v.begin(), v.end(), std::ostream_iterator<Foo>(ss, ", "));
return ss.str();
};
int main()
{
VectorT v(10);
std::for_each(v.begin(), v.end(),
[](Foo& f)
{
f._i = rand() % 100;
});
std::cout << "before sort: " << toString(v) << "\n";
sort(v.begin(), v.end(),
[](const Foo& a, const Foo& b)
{
return a._i > b._i;
});
std::cout << "after sort: " << toString(v) << "\n";
return 1;
};
The output is:
before sort: 83, 86, 77, 15, 93, 35, 86, 92, 49, 21,
after sort: 93, 92, 86, 86, 83, 77, 49, 35, 21, 15,
How to decode JWT Token?
new JwtSecurityTokenHandler().ReadToken("")
will return a SecurityToken
new JwtSecurityTokenHandler().ReadJwtToken("")
will return a JwtSecurityToken
If you just change the method you are using you can avoid the cast in the above answer
How can I import data into mysql database via mysql workbench?
- Under Server Administration on the Home window select the server instance you want to restore database to (Create New Server Instance if doing it first time).
- Click on Manage Import/Export
- Click on Data Import/Restore on the left side of the screen.
- Select Import from Self-Contained File radio button (right side of screen)
- Select the path of .sql
- Click Start Import button at the right bottom corner of window.
Hope it helps.
---Edited answer---
Regarding selection of the schema. MySQL Workbench (5.2.47 CE Rev1039) does not yet support exporting to the user defined schema. It will create only the schema for which you exported the .sql... In 5.2.47 we see "New" target schema. But it does not work. I use MySQL Administrator (the old pre-Oracle MySQL Admin beauty) for my work for backup/restore.
You can still download it from Googled trustable sources (search MySQL Administrator 1.2.17).
How can I solve Exception in thread "main" java.lang.NullPointerException error
This is the problem
double a[] = null;
Since a
is null
, NullPointerException
will arise every time you use it until you initialize it. So this:
a[i] = var;
will fail.
A possible solution would be initialize it when declaring it:
double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7
IMO more important than solving this exception, is the fact that you should learn to read the stacktrace and understand what it says, so you could detect the problems and solve it.
java.lang.NullPointerException
This exception means there's a variable with null
value being used. How to solve? Just make sure the variable is not null
before being used.
at twoten.TwoTenB.(TwoTenB.java:29)
This line has two parts:
- First, shows the class and method where the error was thrown. In this case, it was at
<init>
method in class TwoTenB
declared in package twoten
. When you encounter an error message with SomeClassName.<init>
, means the error was thrown while creating a new instance of the class e.g. executing the constructor (in this case that seems to be the problem).
- Secondly, shows the file and line number location where the error is thrown, which is between parenthesis. This way is easier to spot where the error arose. So you have to look into file TwoTenB.java, line number 29. This seems to be
a[i] = var;
.
From this line, other lines will be similar to tell you where the error arose. So when reading this:
at javapractice.JavaPractice.main(JavaPractice.java:32)
It means that you were trying to instantiate a TwoTenB
object reference inside the main
method of your class JavaPractice
declared in javapractice
package.
Importing Excel into a DataTable Quickly
Dim sSheetName As String
Dim sConnection As String
Dim dtTablesList As DataTable
Dim oleExcelCommand As OleDbCommand
Dim oleExcelReader As OleDbDataReader
Dim oleExcelConnection As OleDbConnection
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Test.xls;Extended Properties=""Excel 12.0;HDR=No;IMEX=1"""
oleExcelConnection = New OleDbConnection(sConnection)
oleExcelConnection.Open()
dtTablesList = oleExcelConnection.GetSchema("Tables")
If dtTablesList.Rows.Count > 0 Then
sSheetName = dtTablesList.Rows(0)("TABLE_NAME").ToString
End If
dtTablesList.Clear()
dtTablesList.Dispose()
If sSheetName <> "" Then
oleExcelCommand = oleExcelConnection.CreateCommand()
oleExcelCommand.CommandText = "Select * From [" & sSheetName & "]"
oleExcelCommand.CommandType = CommandType.Text
oleExcelReader = oleExcelCommand.ExecuteReader
nOutputRow = 0
While oleExcelReader.Read
End While
oleExcelReader.Close()
End If
oleExcelConnection.Close()
Is module __file__ attribute absolute or relative?
__file__
is absolute since Python 3.4, except when executing a script directly using a relative path:
Module __file__
attributes (and related values) should now always contain absolute paths by default, with the sole exception of __main__.__file__
when a script has been executed directly using a relative path. (Contributed by Brett Cannon in bpo-18416.)
Not sure if it resolves symlinks though.
Example of passing a relative path:
$ python script.py
How to fix corrupted git repository?
Here's a script (bash) to automate the first solution by @CodeGnome to restore from a backup (run from the top level of the corrupted repo). The backup doesn't need to be complete, it only needs to have the missing objects.
git fsck 2>&1 | grep -e missing -e invalid | awk '{print $NF}' | sort -u |
while read entry; do
mkdir -p .git/objects/${entry:0:2}
cp ${BACKUP}/objects/${entry:0:2}/${entry:2} .git/objects/${entry:0:2}/${entry:2}
done
How to enable and use HTTP PUT and DELETE with Apache2 and PHP?
AllowOverride AuthConfig
try this. Authentication may be the problem. I was working with a CGI script written in C++, and faced some authentication issues when passed DELETE. The above solution helped me. It may help in your case too.
Also even if you don't get the solution for your problem of PUT and DELETE, do not stop working rather use "CORS". It is a google chrome app, which will help you bypass the problem, but remember it is a temporary solution, so that your work or experiments doesn't remain freeze for long. Obviously, you cannot ask your client to have "CORS" enabled to run your solution, as it may compromise systems security.
printf format specifiers for uint32_t and size_t
If you don't want to use the PRI* macros, another approach for printing ANY integer type is to cast to intmax_t
or uintmax_t
and use "%jd"
or %ju
, respectively. This is especially useful for POSIX (or other OS) types that don't have PRI* macros defined, for instance off_t
.
H2 in-memory database. Table not found
Hard to tell. I created a program to test this:
package com.gigaspaces.compass;
import org.testng.annotations.Test;
import java.sql.*;
public class H2Test {
@Test
public void testDatabaseNoMem() throws SQLException {
testDatabase("jdbc:h2:test");
}
@Test
public void testDatabaseMem() throws SQLException {
testDatabase("jdbc:h2:mem:test");
}
private void testDatabase(String url) throws SQLException {
Connection connection= DriverManager.getConnection(url);
Statement s=connection.createStatement();
try {
s.execute("DROP TABLE PERSON");
} catch(SQLException sqle) {
System.out.println("Table not found, not dropping");
}
s.execute("CREATE TABLE PERSON (ID INT PRIMARY KEY, FIRSTNAME VARCHAR(64), LASTNAME VARCHAR(64))");
PreparedStatement ps=connection.prepareStatement("select * from PERSON");
ResultSet r=ps.executeQuery();
if(r.next()) {
System.out.println("data?");
}
r.close();
ps.close();
s.close();
connection.close();
}
}
The test ran to completion, with no failures and no unexpected output. Which version of h2 are you running?
Javascript decoding html entities
var text = '<p>name</p><p><span style="font-size:xx-small;">ajde</span></p><p><em>da</em></p>';
var decoded = $('<textarea/>').html(text).text();
alert(decoded);
This sets the innerHTML of a new element (not appended to the page), causing jQuery to decode it into HTML, which is then pulled back out with .text().
Live demo.
Dropping connected users in Oracle database
Users are all capitals in v$session
(and data dictionary views). If you match with capitals you should find your session to kill.
SELECT s.sid, s.serial#, s.status, p.spid
FROM v$session s, v$process p
WHERE s.username = 'TEST' --<<<--
AND p.addr(+) = s.paddr
/
Pass actual SID and SERIAL# values for user TEST then drop user...:
ALTER SYSTEM KILL SESSION '<SID>, <SERIAL>'
/
How to mark a build unstable in Jenkins when running shell scripts
It can be done without printing magic strings and using TextFinder. Here's some info on it.
Basically you need a .jar file from http://yourserver.com/cli available in shell scripts, then you can use the following command to mark a build unstable:
java -jar jenkins-cli.jar set-build-result unstable
To mark build unstable on error, you can use:
failing_cmd cmd_args || java -jar jenkins-cli.jar set-build-result unstable
The problem is that jenkins-cli.jar has to be available from shell script. You can either put it in easy-to-access path, or download in via job's shell script:
wget ${JENKINS_URL}jnlpJars/jenkins-cli.jar
Adding a regression line on a ggplot
As I just figured, in case you have a model fitted on multiple linear regression, the above mentioned solution won't work.
You have to create your line manually as a dataframe that contains predicted values for your original dataframe (in your case data
).
It would look like this:
# read dataset
df = mtcars
# create multiple linear model
lm_fit <- lm(mpg ~ cyl + hp, data=df)
summary(lm_fit)
# save predictions of the model in the new data frame
# together with variable you want to plot against
predicted_df <- data.frame(mpg_pred = predict(lm_fit, df), hp=df$hp)
# this is the predicted line of multiple linear regression
ggplot(data = df, aes(x = mpg, y = hp)) +
geom_point(color='blue') +
geom_line(color='red',data = predicted_df, aes(x=mpg_pred, y=hp))
# this is predicted line comparing only chosen variables
ggplot(data = df, aes(x = mpg, y = hp)) +
geom_point(color='blue') +
geom_smooth(method = "lm", se = FALSE)
Razor If/Else conditional operator syntax
You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:
@(deletedView ? "Deleted" : "Created by")
Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.
mysql - move rows from one table to another
The answer of Fabio is really good but it take a long execution time (as Trilarion already has written)
I have an other solution with faster execution.
START TRANSACTION;
set @N := (now());
INSERT INTO table2 select * from table1 where ts < date_sub(@N,INTERVAL 32 DAY);
DELETE FROM table1 WHERE ts < date_sub(@N,INTERVAL 32 DAY);
COMMIT;
@N gets the Timestamp at the begin and is used for both commands.
All is in a Transaction to be sure nobody is disturbing
How to convert a Java 8 Stream to an Array?
Using the toArray(IntFunction<A[]> generator)
method is indeed a very elegant and safe way to convert (or more correctly, collect) a Stream into an array of the same type of the Stream.
However, if the returned array's type is not important, simply using the toArray()
method is both easier and shorter.
For example:
Stream<Object> args = Stream.of(BigDecimal.ONE, "Two", 3);
System.out.printf("%s, %s, %s!", args.toArray());
How to make a query with group_concat in sql server
Query:
SELECT
m.maskid
, m.maskname
, m.schoolid
, s.schoolname
, maskdetail = STUFF((
SELECT ',' + md.maskdetail
FROM dbo.maskdetails md
WHERE m.maskid = md.maskid
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM dbo.tblmask m
JOIN dbo.school s ON s.ID = m.schoolid
ORDER BY m.maskname
Additional information:
String Aggregation in the World of SQL Server
how to remove untracked files in Git?
Well, I had the similar issue. I had taken latest but there were some changes in the local due to which the merge was not happening to a particular file. The file was untracked and I did not want them so
What I did was -
$ git checkout filepath/filename
filepath - The location from where I did the git bash.
then when I took the latest the changes were available
how to get yesterday's date in C#
DateTime dateTime = DateTime.Now ;
string today = dateTime.DayOfWeek.ToString();
string yesterday = dateTime.AddDays(-1).DayOfWeek.ToString(); //Fetch day i.e. Mon, Tues
string result = dateTime.AddDays(-1).ToString("yyyy-MM-dd");
The above snippet will work. It is also advisable to make single instance of DateTime.Now;
simple Jquery hover enlarge
Demo Link
Tutorial Link
This will show original dimensions of Image on Hover using jQuery custom code
HTML
<ul class="thumb">
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/1.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/2.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/3.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/4.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/5.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/6.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/7.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/8.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/9.jpg)"></div>
</a>
</li>
</ul>
CSS
ul.thumb {
float: left;
list-style: none;
padding: 10px;
width: 360px;
margin: 80px;
}
ul.thumb li {
margin: 0;
padding: 5px;
float: left;
position: relative;
/* Set the absolute positioning base coordinate */
width: 110px;
height: 110px;
}
ul.thumb li .thumbnail-wrap {
width: 100px;
height: 100px;
/* Set the small thumbnail size */
-ms-interpolation-mode: bicubic;
/* IE Fix for Bicubic Scaling */
border: 1px solid #ddd;
padding: 5px;
position: absolute;
left: 0;
top: 0;
background-size: cover;
background-repeat: no-repeat;
-webkit-box-shadow: inset -3px 0px 40px -15px rgba(0, 0, 0, 1);
-moz-box-shadow: inset -3px 0px 40px -15px rgba(0, 0, 0, 1);
box-shadow: inset -3px 0px 40px -15px rgba(0, 0, 0, 1);
}
ul.thumb li .thumbnail-wrap.hover {
-webkit-box-shadow: -2px 1px 22px -1px rgba(0, 0, 0, 0.75);
-moz-box-shadow: -2px 1px 22px -1px rgba(0, 0, 0, 0.75);
box-shadow: -2px 1px 22px -1px rgba(0, 0, 0, 0.75);
}
.thumnail-zoomed-wrapper {
display: none;
position: fixed;
top: 0px;
left: 0px;
height: 100vh;
width: 100%;
background: rgba(0, 0, 0, 0.2);
z-index: 99;
}
.thumbnail-zoomed-image {
margin: auto;
display: block;
text-align: center;
margin-top: 12%;
}
.thumbnail-zoomed-image img {
max-width: 100%;
}
.close-image-zoom {
z-index: 10;
float: right;
margin: 10px;
cursor: pointer;
}
jQuery
var perc = 40;
$("ul.thumb li").hover(function () {
$("ul.thumb li").find(".thumbnail-wrap").css({
"z-index": "0"
});
$(this).find(".thumbnail-wrap").css({
"z-index": "10"
});
var imageval = $(this).find(".thumbnail-wrap").css("background-image").slice(5);
var img;
var thisImage = this;
img = new Image();
img.src = imageval.substring(0, imageval.length - 2);
img.onload = function () {
var imgh = this.height * (perc / 100);
var imgw = this.width * (perc / 100);
$(thisImage).find(".thumbnail-wrap").addClass("hover").stop()
.animate({
marginTop: "-" + (imgh / 4) + "px",
marginLeft: "-" + (imgw / 4) + "px",
width: imgw + "px",
height: imgh + "px"
}, 200);
}
}, function () {
var thisImage = this;
$(this).find(".thumbnail-wrap").removeClass("hover").stop()
.animate({
marginTop: "0",
marginLeft: "0",
top: "0",
left: "0",
width: "100px",
height: "100px",
padding: "5px"
}, 400, function () {});
});
//Show thumbnail in fullscreen
$("ul.thumb li .thumbnail-wrap").click(function () {
var imageval = $(this).css("background-image").slice(5);
imageval = imageval.substring(0, imageval.length - 2);
$(".thumbnail-zoomed-image img").attr({
src: imageval
});
$(".thumnail-zoomed-wrapper").fadeIn();
return false;
});
//Close fullscreen preview
$(".thumnail-zoomed-wrapper .close-image-zoom").click(function () {
$(".thumnail-zoomed-wrapper").hide();
return false;
});
Permission denied on CopyFile in VBS
Another thing to check is if any applications still have a hold on the file.
Had some issues with MoveFile. Part of my permissions problem was that my script opens the file (in this case in Excel), makes a modification, closes it, then moves it to a "processed" folder.
In debugging a couple things, the script crashed a few times. Digging into the permission denied error I found that I had 4 instances of Excel running in the background because the script was never able to properly terminate the application due to said crashes. Apparently one of them still had a hold on the file and, thusly, "permission denied."
How can I run an external command asynchronously from Python?
If you want to run many processes in parallel and then handle them when they yield results, you can use polling like in the following:
from subprocess import Popen, PIPE
import time
running_procs = [
Popen(['/usr/bin/my_cmd', '-i %s' % path], stdout=PIPE, stderr=PIPE)
for path in '/tmp/file0 /tmp/file1 /tmp/file2'.split()]
while running_procs:
for proc in running_procs:
retcode = proc.poll()
if retcode is not None: # Process finished.
running_procs.remove(proc)
break
else: # No process is done, wait a bit and check again.
time.sleep(.1)
continue
# Here, `proc` has finished with return code `retcode`
if retcode != 0:
"""Error handling."""
handle_results(proc.stdout)
The control flow there is a little bit convoluted because I'm trying to make it small -- you can refactor to your taste. :-)
This has the advantage of servicing the early-finishing requests first. If you call communicate
on the first running process and that turns out to run the longest, the other running processes will have been sitting there idle when you could have been handling their results.
How does the @property decorator work in Python?
Here is another example:
##
## Python Properties Example
##
class GetterSetterExample( object ):
## Set the default value for x ( we reference it using self.x, set a value using self.x = value )
__x = None
##
## On Class Initialization - do something... if we want..
##
def __init__( self ):
## Set a value to __x through the getter / setter... Since __x is defined above, this doesn't need to be set...
self.x = 1234
return None
##
## Define x as a property, ie a getter - All getters should have a default value arg, so I added it - it will not be passed in when setting a value, so you need to set the default here so it will be used..
##
@property
def x( self, _default = None ):
## I added an optional default value argument as all getters should have this - set it to the default value you want to return...
_value = ( self.__x, _default )[ self.__x == None ]
## Debugging - so you can see the order the calls are made...
print( '[ Test Class ] Get x = ' + str( _value ) )
## Return the value - we are a getter afterall...
return _value
##
## Define the setter function for x...
##
@x.setter
def x( self, _value = None ):
## Debugging - so you can see the order the calls are made...
print( '[ Test Class ] Set x = ' + str( _value ) )
## This is to show the setter function works.... If the value is above 0, set it to a negative value... otherwise keep it as is ( 0 is the only non-negative number, it can't be negative or positive anyway )
if ( _value > 0 ):
self.__x = -_value
else:
self.__x = _value
##
## Define the deleter function for x...
##
@x.deleter
def x( self ):
## Unload the assignment / data for x
if ( self.__x != None ):
del self.__x
##
## To String / Output Function for the class - this will show the property value for each property we add...
##
def __str__( self ):
## Output the x property data...
print( '[ x ] ' + str( self.x ) )
## Return a new line - technically we should return a string so it can be printed where we want it, instead of printed early if _data = str( C( ) ) is used....
return '\n'
##
##
##
_test = GetterSetterExample( )
print( _test )
## For some reason the deleter isn't being called...
del _test.x
Basically, the same as the C( object ) example except I'm using x instead... I also don't initialize in __init - ... well.. I do, but it can be removed because __x is defined as part of the class....
The output is:
[ Test Class ] Set x = 1234
[ Test Class ] Get x = -1234
[ x ] -1234
and if I comment out the self.x = 1234 in init then the output is:
[ Test Class ] Get x = None
[ x ] None
and if I set the _default = None to _default = 0 in the getter function ( as all getters should have a default value but it isn't passed in by the property values from what I've seen so you can define it here, and it actually isn't bad because you can define the default once and use it everywhere ) ie: def x( self, _default = 0 ):
[ Test Class ] Get x = 0
[ x ] 0
Note: The getter logic is there just to have the value be manipulated by it to ensure it is manipulated by it - the same for the print statements...
Note: I'm used to Lua and being able to dynamically create 10+ helpers when I call a single function and I made something similar for Python without using properties and it works to a degree, but, even though the functions are being created before being used, there are still issues at times with them being called prior to being created which is strange as it isn't coded that way... I prefer the flexibility of Lua meta-tables and the fact I can use actual setters / getters instead of essentially directly accessing a variable... I do like how quickly some things can be built with Python though - for instance gui programs. although one I am designing may not be possible without a lot of additional libraries - if I code it in AutoHotkey I can directly access the dll calls I need, and the same can be done in Java, C#, C++, and more - maybe I haven't found the right thing yet but for that project I may switch from Python..
Note: The code output in this forum is broken - I had to add spaces to the first part of the code for it to work - when copy / pasting ensure you convert all spaces to tabs.... I use tabs for Python because in a file which is 10,000 lines the filesize can be 512KB to 1MB with spaces and 100 to 200KB with tabs which equates to a massive difference for file size, and reduction in processing time...
Tabs can also be adjusted per user - so if you prefer 2 spaces width, 4, 8 or whatever you can do it meaning it is thoughtful for developers with eye-sight deficits.
Note: All of the functions defined in the class aren't indented properly because of a bug in the forum software - ensure you indent it if you copy / paste
Intellij idea subversion checkout error: `Cannot run program "svn"`
Check my solution, It will work.
Solutions:
First Download Subversion 1.8.13 ( 1.8 )
Download link ( https://www.visualsvn.com/downloads/ )
Then unzipped in a folder. There will have one folder "bin".
Then
Go to settings - > Version control -> Subversion
Copy the url of your downloaded svn.exe that is in bin folder that you have downloaded.
follow the pic:
Don't forget to give the end name like svn.exe last as per image.
Apply -> Ok
Restart your android studio now.
Happy Coding!
Concatenating date with a string in Excel
This is the numerical representation of the date. The thing you get when referring to dates from formulas like that.
You'll have to do:
= A1 & TEXT(A2, "mm/dd/yyyy")
The biggest problem here is that the format specifier is locale-dependent. It will not work/produce not what expected if the file is opened with a differently localized Excel.
Now, you could have a user-defined function:
public function AsDisplayed(byval c as range) as string
AsDisplayed = c.Text
end function
and then
= A1 & AsDisplayed(A2)
But then there's a bug (feature?) in Excel because of which the .Text
property is suddenly not available during certain stages of the computation cycle, and your formulas display #VALUE
instead of what they should.
That is, it's bad either way.
Go to next item in ForEach-Object
You just have to replace the break
with a return
statement.
Think of the code inside the Foreach-Object
as an anonymous function. If you have loops inside the function, just use the control keywords applying to the construction (continue
, break
, ...).
How can we redirect a Java program console output to multiple files?
You could use a "variable" inside the output filename, for example:
/tmp/FetchBlock-${current_date}.txt
current_date:
Returns the current system time formatted as yyyyMMdd_HHmm. An optional argument can be used to provide alternative formatting. The argument must be valid pattern for java.util.SimpleDateFormat.
Or you can also use a system_property or an env_var to specify something dynamic (either one needs to be specified as arguments)
Mapping a JDBC ResultSet to an object
Let's assume you want to use core Java, w/o any strategic frameworks. If you can guarantee, that field name of an entity will be equal to the column in database, you can use Reflection API (otherwise create annotation and define mapping name there)
By FieldName
/**
Class<T> clazz - a list of object types you want to be fetched
ResultSet resultSet - pointer to your retrieved results
*/
List<Field> fields = Arrays.asList(clazz.getDeclaredFields());
for(Field field: fields) {
field.setAccessible(true);
}
List<T> list = new ArrayList<>();
while(resultSet.next()) {
T dto = clazz.getConstructor().newInstance();
for(Field field: fields) {
String name = field.getName();
try{
String value = resultSet.getString(name);
field.set(dto, field.getType().getConstructor(String.class).newInstance(value));
} catch (Exception e) {
e.printStackTrace();
}
}
list.add(dto);
}
By annotation
@Retention(RetentionPolicy.RUNTIME)
public @interface Col {
String name();
}
DTO:
class SomeClass {
@Col(name = "column_in_db_name")
private String columnInDbName;
public SomeClass() {}
// ..
}
Same, but
while(resultSet.next()) {
T dto = clazz.getConstructor().newInstance();
for(Field field: fields) {
Col col = field.getAnnotation(Col.class);
if(col!=null) {
String name = col.name();
try{
String value = resultSet.getString(name);
field.set(dto, field.getType().getConstructor(String.class).newInstance(value));
} catch (Exception e) {
e.printStackTrace();
}
}
}
list.add(dto);
}
Thoughts
In fact, iterating over all Fields might seem ineffective, so I would store mapping somewhere, rather than iterating each time. However, if our T
is a DTO with only purpose of transferring data and won't contain loads of unnecessary fields, that's ok. In the end it's much better than using boilerplate methods all the way.
Hope this helps someone.
How to map a composite key with JPA and Hibernate?
To map a composite key, you can use the EmbeddedId
or the IdClass
annotations. I know this question is not strictly about JPA but the rules defined by the specification also applies. So here they are:
2.1.4 Primary Keys and Entity Identity
...
A composite primary key must
correspond to either a single
persistent field or property or to a
set of such fields or properties as
described below. A primary key class
must be defined to represent a
composite primary key. Composite
primary keys typically arise when
mapping from legacy databases when the
database key is comprised of several
columns. The EmbeddedId
and
IdClass
annotations are used to
denote composite primary keys. See
sections 9.1.14 and 9.1.15.
...
The following rules apply for
composite primary keys:
- The primary key class must be public and must have a public no-arg
constructor.
- If property-based access is used, the properties of the primary key
class must be public or protected.
- The primary key class must be
serializable
.
- The primary key class
must define
equals
and hashCode
methods. The semantics of value
equality for these methods must be
consistent with the database equality
for the database types to which the
key is mapped.
- A composite primary key must either be represented and mapped as an
embeddable class (see Section 9.1.14,
“EmbeddedId Annotation”) or must be
represented and mapped to multiple
fields or properties of the entity
class (see Section 9.1.15, “IdClass
Annotation”).
- If the composite primary key class is mapped to multiple fields or
properties of the entity class, the
names of primary key fields or
properties in the primary key class
and those of the entity class must
correspond and their types must be the
same.
With an IdClass
The class for the composite primary key could look like (could be a static inner class):
public class TimePK implements Serializable {
protected Integer levelStation;
protected Integer confPathID;
public TimePK() {}
public TimePK(Integer levelStation, Integer confPathID) {
this.levelStation = levelStation;
this.confPathID = confPathID;
}
// equals, hashCode
}
And the entity:
@Entity
@IdClass(TimePK.class)
class Time implements Serializable {
@Id
private Integer levelStation;
@Id
private Integer confPathID;
private String src;
private String dst;
private Integer distance;
private Integer price;
// getters, setters
}
The IdClass
annotation maps multiple fields to the table PK.
With EmbeddedId
The class for the composite primary key could look like (could be a static inner class):
@Embeddable
public class TimePK implements Serializable {
protected Integer levelStation;
protected Integer confPathID;
public TimePK() {}
public TimePK(Integer levelStation, Integer confPathID) {
this.levelStation = levelStation;
this.confPathID = confPathID;
}
// equals, hashCode
}
And the entity:
@Entity
class Time implements Serializable {
@EmbeddedId
private TimePK timePK;
private String src;
private String dst;
private Integer distance;
private Integer price;
//...
}
The @EmbeddedId
annotation maps a PK class to table PK.
Differences:
- From the physical model point of view, there are no differences
@EmbeddedId
somehow communicates more clearly that the key is a composite key and IMO makes sense when the combined pk is either a meaningful entity itself or it reused in your code.
@IdClass
is useful to specify that some combination of fields is unique but these do not have a special meaning.
They also affect the way you write queries (making them more or less verbose):
References
- JPA 1.0 specification
- Section 2.1.4 "Primary Keys and Entity Identity"
- Section 9.1.14 "EmbeddedId Annotation"
- Section 9.1.15 "IdClass Annotation"
Writing data into CSV file in C#
public static class Extensions
{
public static void WriteCSVLine(this StreamWriter writer, IEnumerable<string> fields)
{
const string q = @"""";
writer.WriteLine(string.Join(",",
fields.Select(
v => (v.Contains(',') || v.Contains('"') || v.Contains('\n') || v.Contains('\r')) ? $"{q}{v.Replace(q, q + q)}{q}" : v
)));
}
public static void WriteFields(this StreamWriter writer, params string[] fields) => WriteFields(writer, (IEnumerable<string>)fields);
}
This should allow you to write a csv file quite simply. Usage:
StreamWriter writer = new StreamWriter("myfile.csv");
writer.WriteCSVLine(new[]{"A", "B"});
vertical align middle in <div>
Use the translateY CSS property to vertically center your text in it's container
<style>
.centertext{
position: relative;
top: 50%;
transform: translateY(40%);
}
</style>
And then apply it to your containing DIV
<div class="centertext">
<font style="color:white; font-size:20px;"> Your Text Here </font>
</div>
Adjust the translateY percentage to suit your needs. Hope this helps
How to select the last column of dataframe
Just to add to @Anshul Singh Suryan's answer:
When we split the dataframe to just get the last column:
If we split like:
y = df.iloc[:,-1:] - y
remains a dataframe
However, if we split like
y = df.iloc[:,-1] - y
becomes a Series
.
This is a notable difference that I've found in the two approaches. If you don't care about the resultant type, you can use either of the two. Otherwise you need to take care of the above findings.
This is applicable for any number of rows you want to extract and not just the last row.
For example, if you want last n
number of rows of a dataframe, where n is any integer less than or equal to the number of columns present in the dataframe, then you can easily do the following:
y = df.iloc[:,n:]
Replace n
by the number of columns you want. Same is true for rows as well.
Where does linux store my syslog?
Default log location (rhel) are
General messages:
/var/log/messages
Authentication messages:
/var/log/secure
Mail events:
/var/log/maillog
Check your /etc/syslog.conf
or /etc/syslog-ng.conf
(it depends on which of syslog facility you have installed)
Example:
$ cat /etc/syslog.conf
# Log anything (except mail) of level info or higher.
# Don't log private authentication messages!
*.info;mail.none;authpriv.none /var/log/messages
# The authpriv file has restricted access.
authpriv.* /var/log/secure
# Log all the mail messages in one place.
mail.* /var/log/maillog
#For a start, use this simplified approach.
*.* /var/log/messages
boundingRectWithSize for NSAttributedString returning wrong size
Looks like you weren't providing the correct options. For wrapping labels, provide at least:
CGRect paragraphRect =
[attributedText boundingRectWithSize:CGSizeMake(300.f, CGFLOAT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
context:nil];
Note: if the original text width is under 300.f there won't be line wrapping, so make sure the bound size is correct, otherwise you will still get wrong results.
jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
The servlet API .jar file must not be embedded inside the webapp since, obviously, the container already has these classes in its classpath: it implements the interfaces contained in this jar.
The dependency should be in the provided
scope, rather than the default compile
scope, in your Maven pom:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
Include another JSP file
For a reason I don't yet understand, after I used <%@include file="includes/footer.jsp" %>
in my index.jsp
then in the other jsp files like register.jsp
I had to use <%@ include file="footer.jsp"%>
. As you see there was no more need to use full path, STS had store my initial path.
Copy array by value
In my particular case I needed to ensure the array remained intact so this worked for me:
// Empty array
arr1.length = 0;
// Add items from source array to target array
for (var i = 0; i < arr2.length; i++) {
arr1.push(arr2[i]);
}
'this' is undefined in JavaScript class methods
In ES2015 a.k.a ES6, class
is a syntactic sugar for functions
.
If you want to force to set a context for this
you can use bind()
method. As @chetan pointed, on invocation you can set the context as well! Check the example below:
class Form extends React.Component {
constructor() {
super();
}
handleChange(e) {
switch (e.target.id) {
case 'owner':
this.setState({owner: e.target.value});
break;
default:
}
}
render() {
return (
<form onSubmit={this.handleNewCodeBlock}>
<p>Owner:</p> <input onChange={this.handleChange.bind(this)} />
</form>
);
}
}
Here we forced the context inside handleChange()
to Form
.
Why compile Python code?
Yep, performance is the main reason and, as far as I know, the only reason.
If some of your files aren't getting compiled, maybe Python isn't able to write to the .pyc file, perhaps because of the directory permissions or something. Or perhaps the uncompiled files just aren't ever getting loaded... (scripts/modules only get compiled when they first get loaded)
How do I align spans or divs horizontally?
What you might like to do is look up CSS grid based layouts. This layout method involves specifying some CSS classes to align the page contents to a grid structure. It's more closely related to print-bsed layout than web-based, but it's a technique used on a lot of websites to layout the content into a structure without having to resort to tables.
Try this for starters from Smashing Magazine.
PageSpeed Insights 99/100 because of Google Analytics - How can I cache GA?
I wouldn't worry about it. Don't put it on your own server, it sounds like this is an issue with Google, but as good as it gets. Putting the file on your own server will create many new problems.
They probably need the file to get called every time rather than getting it from the client's cache, since that way you wouldn't count the visits.
If you have a problem to feel fine with that, run the Google insights URL on Google insights itself, have a laugh, relax and get on with your work.
What's the easy way to auto create non existing dir in ansible
copy module creates the directory if it's not there. In this case it created the resolved.conf.d directory
- name: put fallback_dns.conf in place
copy:
src: fallback_dns.conf
dest: /etc/systemd/resolved.conf.d/
mode: '0644'
owner: root
group: root
become: true
tags: testing