Come late, but after searching everywhere, I've created a solution that seems to be "the one".
Being known that there is a column iterator on last API versions, but not knowing how to atuoadjust the column object it self, basically I've created a loop to go from real first used column to real last used one.
Here it goes:
//Just before saving de Excel document, you do this:
PHPExcel_Shared_Font::setAutoSizeMethod(PHPExcel_Shared_Font::AUTOSIZE_METHOD_EXACT);
//We get the util used space on worksheet. Change getActiveSheet to setActiveSheetIndex(0) to choose the sheet you want to autosize. Iterate thorugh'em if needed.
//We remove all digits from this string, which cames in a form of "A1:G24".
//Exploding via ":" to get a 2 position array being 0 fisrt used column and 1, the last used column.
$cols = explode(":", trim(preg_replace('/\d+/u', '', $objPHPExcel->getActiveSheet()->calculateWorksheetDimension())));
$col = $cols[0]; //first util column with data
$end = ++$cols[1]; //last util column with data +1, to use it inside the WHILE loop. Else, is not going to use last util range column.
while($col != $end){
$objPHPExcel->getActiveSheet()->getColumnDimension($col)->setAutoSize(true);
$col++;
}
//Saving.
$objWriter->save('php://output');
I get it resolved appending datetime as an random number:
$http.get("/your_url?rnd="+new Date().getTime()).success(function(data, status, headers, config) {
console.log('your get response is new!!!');
});
Gives totals and percentages for process using swap
smem -t -p
Source : https://www.cyberciti.biz/faq/linux-which-process-is-using-swap/
if you have any version problems (javac -version=15.0.1, java -version=1.8.0)
windows search : edit environment variables for your account
then delete these in your windows Environment variable: system variable: Path
C:\Program Files (x86)\Common Files\Oracle\Java\javapath
C:\Program Files\Common Files\Oracle\Java\javapath
then if you're using java 15
environment variable: system variable : Path
add path C:\Program Files\Java\jdk-15.0.1\bin
is enough
if you're using java 8
Since any solution given so far will open the command prompt on the project folder, you would still have to navigate to the project's folder. If you are interested in getting the command prompt directly into the project's folder, here is my 2 steps:
Et voila! Hope that helps
try with following code. make elements with class name page-scroll and keep id name to href
of corresponding links
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: ($($anchor.attr('href')).offset().top - 50)
}, 1250, 'easeInOutExpo');
event.preventDefault();
});
I had the same issue.
Only after I changed in php.ini variable
display_errors = Off
to
display_errors = On
Phpadmin started working.. crazy....
/sys/sim/source/gm/kg/jl/ls/owow/lsal
/sys/sim/source/gm/kg/jl/ls/owow/lsal
/sys/sim/source/gm/kg/jl/ls/owow/lsal
/sys/sim/source/gm/kg/jl/ls/owow/lsal
/sys/sim/source/gm/kg/jl/ls/owow/lsal
/sys/sim/source/gm/kg/jl/ls/owow/lsal
/sys/sim/source/gm/kg/jl/ls/owow/lsal
/sys/sim/source/gm/kg/jl/ls/owow/lsal
Suppose if you want to replace the above with some other info.
COMMAND(:%s/\/sys\/sim\/source\/gm\/kg\/jl\/ls\/owow\/lsal/sys.pkg.mpu.umc.kdk./g)
In this the above will be get replaced with (sys.pkg.mpu.umc.kdk.
) .
With the devel version of tidyr
‘0.8.3.9000’
, there is pivot_wider
and pivot_longer
which is generalized to do the reshaping (long -> wide, wide -> long, respectively) from 1 to multiple columns. Using the OP's data
-single column long -> wide
library(dplyr)
library(tidyr)
dat1 %>%
pivot_wider(names_from = numbers, values_from = value)
# A tibble: 2 x 5
# name `1` `2` `3` `4`
# <fct> <dbl> <dbl> <dbl> <dbl>
#1 firstName 0.341 -0.703 -0.380 -0.746
#2 secondName -0.898 -0.335 -0.501 -0.175
-> created another column for showing the functionality
dat1 %>%
mutate(value2 = value * 2) %>%
pivot_wider(names_from = numbers, values_from = c("value", "value2"))
# A tibble: 2 x 9
# name value_1 value_2 value_3 value_4 value2_1 value2_2 value2_3 value2_4
# <fct> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1 firstName 0.341 -0.703 -0.380 -0.746 0.682 -1.41 -0.759 -1.49
#2 secondName -0.898 -0.335 -0.501 -0.175 -1.80 -0.670 -1.00 -0.349
search = browser.find_element_by_xpath("//*[@type='text']")
search.send_keys(u'\ue007')
#ENTER = u'\ue007'
Refer to Selenium's documentation 'Special Keys'.
ln(n!) = n*ln(n) - n + O(ln(n))
where the last 2 terms are less significant than the first one.
Element
objects have no .getroot()
method. Drop that call, and the .tostring()
call works:
xmlstr = ElementTree.tostring(et, encoding='utf8', method='xml')
You only need to use .getroot()
if you have an ElementTree
instance.
Other notes:
This produces a bytestring, which in Python 3 is the bytes
type.
If you must have a str
object, you have two options:
Decode the resulting bytes value, from UTF-8: xmlstr.decode("utf8")
Use encoding='unicode'
; this avoids an encode / decode cycle:
xmlstr = ElementTree.tostring(et, encoding='unicode', method='xml')
If you wanted the UTF-8 encoded bytestring value or are using Python 2, take into account that ElementTree doesn't properly detect utf8
as the standard XML encoding, so it'll add a <?xml version='1.0' encoding='utf8'?>
declaration. Use utf-8
or UTF-8
(with a dash) if you want to prevent this. When using encoding="unicode"
no declaration header is added.
This issue can happen not only in eclipse but also in any of the text-editor.
On windows systems, windows-10 in my case, this issue arose when the shift and insert key was pressed in tandem unintentionally which takes the user to the overwrite mode.
To get back to insert mode you need to press shift and insert in tandem again.
This is for Nikola.
public static JSONObject setProperty(JSONObject js1, String keys, String valueNew) throws JSONException {
String[] keyMain = keys.split("\\.");
for (String keym : keyMain) {
Iterator iterator = js1.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
if ((js1.optJSONArray(key) == null) && (js1.optJSONObject(key) == null)) {
if ((key.equals(keym)) && (js1.get(key).toString().equals(valueMain))) {
js1.put(key, valueNew);
return js1;
}
}
if (js1.optJSONObject(key) != null) {
if ((key.equals(keym))) {
js1 = js1.getJSONObject(key);
break;
}
}
if (js1.optJSONArray(key) != null) {
JSONArray jArray = js1.getJSONArray(key);
JSONObject j;
for (int i = 0; i < jArray.length(); i++) {
js1 = jArray.getJSONObject(i);
break;
}
}
}
}
return js1;
}
public static void main(String[] args) throws IOException, JSONException {
String text = "{ "key1":{ "key2":{ "key3":{ "key4":[ { "fieldValue":"Empty", "fieldName":"Enter Field Name 1" }, { "fieldValue":"Empty", "fieldName":"Enter Field Name 2" } ] } } } }";
JSONObject json = new JSONObject(text);
setProperty(json, "ke1.key2.key3.key4.fieldValue", "nikola");
System.out.println(json.toString(4));
}
If it's help bro,Do not forget to up for my reputation)))
Use DATEDIFF
Select I.Fee
From Item I
WHERE DATEDIFF(day, GETDATE(), I.DateCreated) < 365
After you granted the permissions to the specified user you have to do this at filtering:
First step:
Second step:
Now you will be able to display the tables after you changed the default load Alter session to the desire schema (using a Trigger after LOG ON).
If you want to allow 1
and 1.2
:
(?<=^| )\d+(\.\d+)?(?=$| )
If you want to allow 1
, 1.2
and .1
:
(?<=^| )\d+(\.\d+)?(?=$| )|(?<=^| )\.\d+(?=$| )
If you want to only allow 1.2
(only floats):
(?<=^| )\d+\.\d+(?=$| )
\d
allows digits (while \D
allows anything but digits).
(?<=^| )
checks that the number is preceded by either a space or the beginning of the string. (?=$| )
makes sure the string is followed by a space or the end of the string. This makes sure the number isn't part of another number or in the middle of words or anything.
Edit: added more options, improved the regexes by adding lookahead- and behinds for making sure the numbers are standalone (i.e. aren't in the middle of words or other numbers.
For those running JPA in Spring, from version 3.1 onwards, you can set packagesToScan
property under LocalContainerEntityManagerFactoryBean
and get rid of persistence.xml altogether.
Character set conversion is done implicitly on the database connection level. You can force automatic conversion off in the ODBC or ADODB connection string with the parameter "Auto Translate=False". This is NOT recommended. See: https://msdn.microsoft.com/en-us/library/ms130822.aspx
There has been a codepage incompatibility in SQL Server 2005 when Database and Client codepage did not match. https://support.microsoft.com/kb/KbView/904803
SQL-Management Console 2008 and upwards is a UNICODE application. All values entered or requested are interpreted as such on the application level. Conversation to and from the column collation is done implicitly. You can verify this with:
SELECT CAST(N'±' as varbinary(10)) AS Result
This will return 0xB100
which is the Unicode character U+00B1 (as entered in the Management Console window). You cannot turn off "Auto Translate" for Management Studio.
If you specify a different collation in the select, you eventually end up in a double conversion (with possible data loss) as long as "Auto Translate" is still active. The original character is first transformed to the new collation during the select, which in turn gets "Auto Translated" to the "proper" application codepage. That's why your various COLLATION tests still show all the same result.
You can verify that specifying the collation DOES have an effect in the select, if you cast the result as VARBINARY
instead of VARCHAR
so the SQL Server transformation is not invalidated by the client before it is presented:
SELECT cast(columnName COLLATE SQL_Latin1_General_CP850_BIN2 as varbinary(10)) from tableName
SELECT cast(columnName COLLATE SQL_Latin1_General_CP1_CI_AS as varbinary(10)) from tableName
This will get you 0xF1
or 0xB1
respectively if columnName
contains just the character '±'
You still might get the correct result and yet a wrong character, if the font you are using does not provide the proper glyph.
Please double check the actual internal representation of your character by casting the query to VARBINARY
on a proper sample and verify whether this code indeed corresponds to the defined database collation SQL_Latin1_General_CP850_BIN2
SELECT CAST(columnName as varbinary(10)) from tableName
Differences in application collation and database collation might go unnoticed as long as the conversion is always done the same way in and out. Troubles emerge as soon as you add a client with a different collation. Then you might find that the internal conversion is unable to match the characters correctly.
All that said, you should keep in mind that Management Studio usually is not the final reference when interpreting result sets. Even if it looks gibberish in MS, it still might be the correct output. The question is whether the records show up correctly in your applications.
Yes, simply set it to another value:
$_POST['text'] = 'another value';
This will override the previous value corresponding to text
key of the array. The $_POST
is superglobal associative array and you can change the values like a normal PHP array.
Caution: This change is only visible within the same PHP execution scope. Once the execution is complete and the page has loaded, the $_POST
array is cleared. A new form submission will generate a new $_POST
array.
If you want to persist the value across form submissions, you will need to put it in the form as an input
tag's value
attribute or retrieve it from a data store.
Use moment-timezone
moment(date).tz('Europe/Berlin').format(format)
Before being able to access a particular timezone, you will need to load it like so (or using alternative methods described here)
moment.tz.add('Europe/Berlin|CET CEST CEMT|-10 -20 -30')
What if your application does logging some other way – not using the
logging
module?
Now, traceback
could be used here.
import traceback
def log_traceback(ex, ex_traceback=None):
if ex_traceback is None:
ex_traceback = ex.__traceback__
tb_lines = [ line.rstrip('\n') for line in
traceback.format_exception(ex.__class__, ex, ex_traceback)]
exception_logger.log(tb_lines)
Use it in Python 2:
try:
# your function call is here
except Exception as ex:
_, _, ex_traceback = sys.exc_info()
log_traceback(ex, ex_traceback)
Use it in Python 3:
try:
x = get_number()
except Exception as ex:
log_traceback(ex)
An ioctl
, which means "input-output control" is a kind of device-specific system call. There are only a few system calls in Linux (300-400), which are not enough to express all the unique functions devices may have. So a driver can define an ioctl which allows a userspace application to send it orders. However, ioctls are not very flexible and tend to get a bit cluttered (dozens of "magic numbers" which just work... or not), and can also be insecure, as you pass a buffer into the kernel - bad handling can break things easily.
An alternative is the sysfs
interface, where you set up a file under /sys/
and read/write that to get information from and to the driver. An example of how to set this up:
static ssize_t mydrvr_version_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%s\n", DRIVER_RELEASE);
}
static DEVICE_ATTR(version, S_IRUGO, mydrvr_version_show, NULL);
And during driver setup:
device_create_file(dev, &dev_attr_version);
You would then have a file for your device in /sys/
, for example, /sys/block/myblk/version
for a block driver.
Another method for heavier use is netlink, which is an IPC (inter-process communication) method to talk to your driver over a BSD socket interface. This is used, for example, by the WiFi drivers. You then communicate with it from userspace using the libnl
or libnl3
libraries.
When I had this problem, I installed 'Remote Tools for Visual Studio 2015' from MSDN. I attached my local VS to the server to debug.
I appreciate that some folks may not have the ability to either install on or access other servers, but I thought I'd throw it out there as an option.
ALTER SCHEMA NewSchema TRANSFER [OldSchema].[TableName]
I always have to use the brackets when I use the ALTER SCHEMA
query in SQL, or I get an error message.
I prefer a popup.
$shell = new-object -comobject "WScript.Shell"
$choice = $shell.popup("Insert question here",0,"Popup window title",4+32)
If $choice equals 6, the answer was Yes If $choice equals 7, the answer was No
I would just use a value in the querystring to pass the required information to the next page.
There is a "Enable Version Control Integration..." option from the VCS popup (control V). Until you do this and select a VCS the VCS system context menus do not show up and the VCS features are not fully integrated. Not sure why this is so hidden?
function getKeys(obj){
var keys = [];
for (key in obj) {
if (obj.hasOwnProperty(key)) { keys[keys.length] = key; }
}
return keys;
}
Try this lets say your form id is formID
$(".nextbutton").click(function() { $("form#formID").submit(); });
The most common causes are:
1. An incorrectly configured GOROOT
OR
2. GOPATH is not set
With gitk
you can view the two branches graphically:
gitk branch1 branch2
And then it's easy to find the common ancestor in the history of the two branches.
You will either need LESS or SASS for the same..
But here is another alternative which I believe will work out in CSS3..
http://css3.bradshawenterprises.com/blog/css-variables/
Example :
:root {
-webkit-var-beautifulColor: rgba(255,40,100, 0.8);
-moz-var-beautifulColor: rgba(255,40,100, 0.8);
-ms-var-beautifulColor: rgba(255,40,100, 0.8);
-o-var-beautifulColor: rgba(255,40,100, 0.8);
var-beautifulColor: rgba(255,40,100, 0.8);
}
.example1 h1 {
color: -webkit-var(beautifulColor);
color: -moz-var(beautifulColor);
color: -ms-var(beautifulColor);
color: -o-var(beautifulColor);
color: var(beautifulColor);
}
You could use Trigger.io's UI module to use the native Android date / time picker with a regular HTML5 input. Doing that does require using the overall framework though (so won't work as a regular mobile web page).
You can see before and after screenshots in this blog post: date time picker
This is answered here: a few suggestions on implementation
The bottom line is Objective-C
is using a regular, old C
enum
, which is just a glorified set of integers.
Given an enum
like this:
typedef enum { a, b, c } FirstThreeAlpha;
Your method would look like this:
- (NSString*) convertToString:(FirstThreeAlpha) whichAlpha {
NSString *result = nil;
switch(whichAlpha) {
case a:
result = @"a";
break;
case b:
result = @"b";
break;
case c:
result = @"c";
break;
default:
result = @"unknown";
}
return result;
}
Another neat option is to use the Directive
as an element and not as an attribute.
@Directive({
selector: 'app-directive'
})
export class InformativeDirective implements AfterViewInit {
@Input()
public first: string;
@Input()
public second: string;
ngAfterViewInit(): void {
console.log(`Values: ${this.first}, ${this.second}`);
}
}
And this directive can be used like that:
<app-someKindOfComponent>
<app-directive [first]="'first 1'" [second]="'second 1'">A</app-directive>
<app-directive [first]="'First 2'" [second]="'second 2'">B</app-directive>
<app-directive [first]="'First 3'" [second]="'second 3'">C</app-directive>
</app-someKindOfComponent>`
Simple, neat and powerful.
Many answers to the question already. For me the problem was two fold:
when I expand my routes:
devise_for :users do
get '/users/sign_out' => 'devise/sessions#destroy'
end
I was getting warning that this is depreciated so I have replaced it with:
devise_scope :users do
get '/users/sign_out' => 'devise/sessions#destroy'
end
I thought I will remove my jQuery. Bad choice. Devise is using jQuery to "fake" DELETE request and send it as GET. Therefore you need to:
//= require jquery
//= require jquery_ujs
and of course same link as many mentioned before:
<%= link_to "Sign out", destroy_user_session_path, :method => :delete %>
Try this:
CREATE TABLE SCHEMA.NEW_TB LIKE SCHEMA.OLD_TB;
INSERT INTO SCHEMA.NEW_TB (SELECT * FROM SCHEMA.OLD_TB);
Options that are not copied include:
An excellent answer given by msigman. I just want to add that in windows 10 you can find IIS Express System Tray (32 bit)
process under Visual Studio
process:
If you mean, you want to scroll through multiple items in your stackpanel, try putting a grid around it. By definition, a stackpanel has infinite length.
So try something like this:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<StackPanel Width="311">
<TextBlock Text="{Binding A}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" FontStretch="Condensed" FontSize="28" />
<TextBlock Text="{Binding B}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
</StackPanel>
</Grid>
You could even make this work with a ScrollViewer
Sounds like you're trying to execute the PHP code directly in your shell. Your shell doesn't speak PHP, so it interprets your PHP code as though it's in your shell's native language, as though you had literally run <?php
at the command line.
Shell scripts usually start with a "shebang" line that tells the shell what program to use to interpret the file. Begin your file like this:
#!/usr/bin/env php
<?php
//Connection
function connection () {
Besides that, the string you're passing to exec
doesn't make any sense. It starts with a slash all by itself, it uses too many periods in the path, and it has a stray right parenthesis.
Copy the contents of the command string and paste them at your command line. If it doesn't run there, then exec
probably won't be able to run it, either.
Another option is to change the command you execute. Instead of running the script directly, run php
and pass your script as an argument. Then you shouldn't need the shebang line.
exec('php name.php');
Easiest way to do this in VBA is to create a function that takes in an array, your new amount of rows, and new amount of columns.
Run the below function to copy in all of the old data back to the array after it has been resized.
function dynamic_preserve(array1, num_rows, num_cols)
dim array2 as variant
array2 = array1
reDim array1(1 to num_rows, 1 to num_cols)
for i = lbound(array2, 1) to ubound(array2, 2)
for j = lbound(array2,2) to ubound(array2,2)
array1(i,j) = array2(i,j)
next j
next i
dynamic_preserve = array1
end function
To get the current directory full path:
os.path.realpath('.')
public static String saveImage(String folderName, String imageName, RelativeLayout layoutCollage) {
String selectedOutputPath = "";
if (isSDCARDMounted()) {
File mediaStorageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), folderName);
// Create a storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("PhotoEditorSDK", "Failed to create directory");
}
}
// Create a media file name
selectedOutputPath = mediaStorageDir.getPath() + File.separator + imageName;
Log.d("PhotoEditorSDK", "selected camera path " + selectedOutputPath);
File file = new File(selectedOutputPath);
try {
FileOutputStream out = new FileOutputStream(file);
if (layoutCollage != null) {
layoutCollage.setDrawingCacheEnabled(true);
layoutCollage.getDrawingCache().compress(Bitmap.CompressFormat.JPEG, 80, out);
}
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return selectedOutputPath;
}
private static boolean isSDCARDMounted() {
String status = Environment.getExternalStorageState();
return status.equals(Environment.MEDIA_MOUNTED);
}
Unfortunately, there is no fool-proof way of achieving this. A block will only expand to the height of its container if it is not floated. Floated blocks are considered outside of the document flow.
One way to do the following without using JavaScript is via a technique called Faux-Columns.
It basically involves applying a background-image
to the parent elements of the floated elements which makes you believe that the two elements are the same height.
More information available at:
The current directory is a system-level feature; it returns the directory that the server was launched from. It has nothing to do with the website.
You want HttpRuntime.AppDomainAppPath
.
If you're in an HTTP request, you can also call Server.MapPath("~/Whatever")
.
You need to set the path to the headers in the project properties so the compiler looks there when trying to find the header file(s). I can't remember the exact location, but look though the Project properties and you should see it.
this is my full solution which would read any base64 image format and save it in the proper format in the database:
// Save base64 image to disk
try
{
// Decoding base-64 image
// Source: http://stackoverflow.com/questions/20267939/nodejs-write-base64-image-file
function decodeBase64Image(dataString)
{
var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
var response = {};
if (matches.length !== 3)
{
return new Error('Invalid input string');
}
response.type = matches[1];
response.data = new Buffer(matches[2], 'base64');
return response;
}
// Regular expression for image type:
// This regular image extracts the "jpeg" from "image/jpeg"
var imageTypeRegularExpression = /\/(.*?)$/;
// Generate random string
var crypto = require('crypto');
var seed = crypto.randomBytes(20);
var uniqueSHA1String = crypto
.createHash('sha1')
.update(seed)
.digest('hex');
var base64Data = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAZABkAAD/4Q3zaHR0cDovL25zLmFkb2JlLmN...';
var imageBuffer = decodeBase64Image(base64Data);
var userUploadedFeedMessagesLocation = '../img/upload/feed/';
var uniqueRandomImageName = 'image-' + uniqueSHA1String;
// This variable is actually an array which has 5 values,
// The [1] value is the real image extension
var imageTypeDetected = imageBuffer
.type
.match(imageTypeRegularExpression);
var userUploadedImagePath = userUploadedFeedMessagesLocation +
uniqueRandomImageName +
'.' +
imageTypeDetected[1];
// Save decoded binary image to disk
try
{
require('fs').writeFile(userUploadedImagePath, imageBuffer.data,
function()
{
console.log('DEBUG - feed:message: Saved to disk image attached by user:', userUploadedImagePath);
});
}
catch(error)
{
console.log('ERROR:', error);
}
}
catch(error)
{
console.log('ERROR:', error);
}
import java.util.Scanner;
public class LoginMain {
public static void main(String[] args) {
String Username;
String Password;
Password = "123";
Username = "wisdom";
Scanner input1 = new Scanner(System.in);
System.out.println("Enter Username : ");
String username = input1.next();
Scanner input2 = new Scanner(System.in);
System.out.println("Enter Password : ");
String password = input2.next();
if (username.equals(Username) && password.equals(Password)) {
System.out.println("Access Granted! Welcome!");
}
else if (username.equals(Username)) {
System.out.println("Invalid Password!");
} else if (password.equals(Password)) {
System.out.println("Invalid Username!");
} else {
System.out.println("Invalid Username & Password!");
}
This is the simple example to use both of them:
import {
Directive, HostListener, HostBinding
}
from '@angular/core';
@Directive({
selector: '[Highlight]'
})
export class HighlightDirective {
@HostListener('mouseenter') mouseover() {
this.backgroundColor = 'green';
};
@HostListener('mouseleave') mouseleave() {
this.backgroundColor = 'white';
}
@HostBinding('style.backgroundColor') get setColor() {
return this.backgroundColor;
};
private backgroundColor = 'white';
constructor() {}
}
Introduction:
HostListener can bind an event to the element.
HostBinding can bind a style to the element.
this is directive, so we can use it for
Some TextSo according to the debug, we can find that this div has been binded style = "background-color:white"
Some Textwe also can find that EventListener of this div has two event: mouseenter
and mouseleave
. So when we move the mouse into the div, the colour will become green, mouse leave, the colour will become white.
After you edited your question it's cler you're using ASP.NET. Things are pretty different there (because in that case a roundtrip to server is pretty discouraged). You can do same things with JavaScript (but to handle globalization with toUpperCase()
may be a pain) or you can use CSS classes (relying on browsers implementation). Simply declare this CSS rule:
.upper-case
{
text-transform: uppercase
}
And add upper-case class to your text-box:
<asp:TextBox ID="TextBox1" CssClass="upper-case" runat="server"/>
but it capitalize characters after pressing Enter key.
It depends where you put that code. If you put it in, for example, TextChanged
event it'll make upper case as you type.
You have a property that do exactly what you need: CharacterCasing
:
TextBox1.CharacterCasing = CharacterCasing.Upper;
It works more or less but it doesn't handle locales very well. For example in German language ß is SS when converted in upper case (Institut für Deutsche Sprache) and this property doesn't handle that.
You may mimic CharacterCasing
property adding this code in KeyPress
event handler:
e.KeyChar = Char.ToUpper(e.KeyChar);
Unfortunately .NET framework doesn't handle this properly and upper case of sharp s character is returned unchanged. An upper case version of ß exists and it's ? and it may create some confusion, for example a word containing "ss" and another word containing "ß" can't be distinguished if you convert in upper case using "SS"). Don't forget that:
However, in 2010 the use of the capital sharp s became mandatory in official documentation when writing geographical names in all-caps.
There isn't much you can do unless you add proper code for support this (and others) subtle bugs in .NET localization. Best advice I can give you is to use a custom dictionary per each culture you need to support.
Finally don't forget that this transformation may be confusing for your users: in Turkey, for example, there are two different versions of i upper case letter.
If text processing is important in your application you can solve many issues using specialized DLLs for each locale you support like Word Processors do.
What I usually do is to do not use standard .NET functions for strings when I have to deal with culture specific issues (I keep them only for text in invariant culture). I create a Unicode class with static methods for everything I need (character counting, conversions, comparison) and many specialized derived classes for each supported language. At run-time that static methods will user current thread culture name to pick proper implementation from a dictionary and to delegate work to that. A skeleton may be something like this:
abstract class Unicode
{
public static string ToUpper(string text)
{
return GetConcreteClass().ToUpperCore(text);
}
protected virtual string ToUpperCore(string text)
{
// Default implementation, overridden in derived classes if needed
return text.ToUpper();
}
private Dictionary<string, Unicode> _implementations;
private Unicode GetConcreteClass()
{
string cultureName = Thread.Current.CurrentCulture.Name;
// Check if concrete class has been loaded and put in dictionary
...
return _implementations[cultureName];
}
}
I'll then have an implementation specific for German language:
sealed class German : Unicode
{
protected override string ToUpperCore(string text)
{
// Very naive implementation, just to provide an example
return text.ToUpper().Replace("ß", "?");
}
}
True implementation may be pretty more complicate (not all OSes supports upper case ?) but take as a proof of concept. See also this post for other details about Unicode issues on .NET.
Both <ins>text</ins>
and <span style="text-decoration:underline">text</span>
work perfectly in Joplin, although I agree with @nfm that underlined text looks like a link and can be misleading in Markdown.
Here's what I ended up with. This works for me if I import my script in the interpreter, and also if I execute it as a script:
import os
import sys
# Returns the directory the current script (or interpreter) is running in
def get_script_directory():
path = os.path.realpath(sys.argv[0])
if os.path.isdir(path):
return path
else:
return os.path.dirname(path)
ES6 supports unicode-aware regular expressions.
RegExp(/^\p{L}/,'u').test(str)
This works for all alphabets.
Unfortunately, there is a bug in Firefox (will be fixed in version 78) that prevents this from being used universally. But if you can control your runtime environment and it supports it (e.g. Node.js), this is a straightforward, comprehensive solution.
Atlernatively, XRegExp provides a polyfill of modern regular expression to all browsers.
//A custom toast class where you can show custom or default toast as desired)
public class ToastMessage {
private Context context;
private static ToastMessage instance;
/**
* @param context
*/
private ToastMessage(Context context) {
this.context = context;
}
/**
* @param context
* @return
*/
public synchronized static ToastMessage getInstance(Context context) {
if (instance == null) {
instance = new ToastMessage(context);
}
return instance;
}
/**
* @param message
*/
public void showLongMessage(String message) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
/**
* @param message
*/
public void showSmallMessage(String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
/**
* The Toast displayed via this method will display it for short period of time
*
* @param message
*/
public void showLongCustomToast(String message) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
View layout = inflater.inflate(R.layout.layout_custom_toast, (ViewGroup) ((Activity) context).findViewById(R.id.ll_toast));
TextView msgTv = (TextView) layout.findViewById(R.id.tv_msg);
msgTv.setText(message);
Toast toast = new Toast(context);
toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
/**
* The toast displayed by this class will display it for long period of time
*
* @param message
*/
public void showSmallCustomToast(String message) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
View layout = inflater.inflate(R.layout.layout_custom_toast, (ViewGroup) ((Activity) context).findViewById(R.id.ll_toast));
TextView msgTv = (TextView) layout.findViewById(R.id.tv_msg);
msgTv.setText(message);
Toast toast = new Toast(context);
toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
}
}
Look into using grunt to automate this, there are numerous tutorials around, but here's a quick start.
For a folder structure like:
blah/
blah/one.ts
blah/two.ts
blah/example/
blah/example/example.ts
blah/example/package.json
blah/example/Gruntfile.js
blah/example/index.html
You can watch and work with typescript easily from the example folder with:
npm install
grunt
With package.json:
{
"name": "PROJECT",
"version": "0.0.1",
"author": "",
"description": "",
"homepage": "",
"private": true,
"devDependencies": {
"typescript": "~0.9.5",
"connect": "~2.12.0",
"grunt-ts": "~1.6.4",
"grunt-contrib-watch": "~0.5.3",
"grunt-contrib-connect": "~0.6.0",
"grunt-open": "~0.2.3"
}
}
And a grunt file:
module.exports = function (grunt) {
// Import dependencies
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-open');
grunt.loadNpmTasks('grunt-ts');
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
connect: {
server: { // <--- Run a local server on :8089
options: {
port: 8089,
base: './'
}
}
},
ts: {
lib: { // <-- compile all the files in ../ to PROJECT.js
src: ['../*.ts'],
out: 'PROJECT.js',
options: {
target: 'es3',
sourceMaps: false,
declaration: true,
removeComments: false
}
},
example: { // <--- compile all the files in . to example.js
src: ['*.ts'],
out: 'example.js',
options: {
target: 'es3',
sourceMaps: false,
declaration: false,
removeComments: false
}
}
},
watch: {
lib: { // <-- Watch for changes on the library and rebuild both
files: '../*.ts',
tasks: ['ts:lib', 'ts:example']
},
example: { // <--- Watch for change on example and rebuild
files: ['*.ts', '!*.d.ts'],
tasks: ['ts:example']
}
},
open: { // <--- Launch index.html in browser when you run grunt
dev: {
path: 'http://localhost:8089/index.html'
}
}
});
// Register the default tasks to run when you run grunt
grunt.registerTask('default', ['ts', 'connect', 'open', 'watch']);
}
SELECT COUNT(1) FROM FB
WHERE Dte > DATE_SUB(now(), INTERVAL 2 MONTH)
Make sure you die()
after your redirection, and make sure you do your redirect AS SOON AS POSSIBLE while your script executes. It makes sure that no more database queries (if some) are not wasted for nothing. That's the one tip I can give you
For search engines, 301 is the best response code
I'm solved this problem more simple way using regex
fun parseTime(time: String?): Long {
val longRegex = "\\d{4}+-\\d{2}+-\\d{2}+\\w\\d{2}:\\d{2}:\\d{2}.\\d{3}[Z]\$"
val shortRegex = "\\d{4}+-\\d{2}+-\\d{2}+\\w\\d{2}:\\d{2}:\\d{2}Z\$"
val longDateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sssXXX")
val shortDateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX")
return when {
Pattern.matches(longRegex, time) -> longDateFormat.parse(time).time
Pattern.matches(shortRegex, time) -> shortDateFormat.parse(time).time
else -> throw InvalidParamsException(INVALID_TIME_MESSAGE, null)
}
}
I just ran into this problem. I was running my source from the command line and kept getting the same error. It turns out that I needed to remove the package name from my source code and then the command line compiler was happy.
The solutions above didn't work for me so maybe this will work for someone else with a similar problem.
The solution is to simply not declare width: 100%
.
The default is width: auto
, which for block-level elements (such as div
), will take the "full space" available anyway (different to how width: 100%
does it).
See: http://jsfiddle.net/U7PhY/2/
Just in case it's not already clear from my answer: just don't set a width
on the child div
.
You might instead be interested in box-sizing: border-box
.
I personally really hate the alternate syntax. One nice thing about the braces is that most IDEs, vim, etc all have bracket highlighting. In my text editor I can double click a brace and it will highlight the whole chunk so I can see where it ends and begins very easily.
I don't know of a single editor that can highlight endif, endforeach, etc.
JQuery's :empty selector selects all elements on the page that are empty in the sense that they have no child elements, including text nodes, not all inputs that have no text in them.
Jquery: How to check if an input element has not been filled in.
Here's the code stolen from the above thread:
$('#apply-form input').blur(function() //whenever you click off an input element
{
if( !$(this).val() ) { //if it is blank.
alert('empty');
}
});
This works because an empty string in JavaScript is a 'falsy value', which basically means if you try to use it as a boolean value it will always evaluate to false
. If you want, you can change the conditional to $(this).val() === ''
for added clarity. :D
As specified in the documentation, use undefined
:
export interface INotificationService {
error(message: string, title?: string, autoHideAfter? : number);
}
class X {
error(message: string, title?: string, autoHideAfter?: number) {
console.log(message, title, autoHideAfter);
}
}
new X().error("hi there", undefined, 1000);
Some frameworks are using this header to detect xhr requests e.g. grails spring security is using this header to identify xhr request and give either a json response or html response as response.
Most Ajax libraries (Prototype, JQuery, and Dojo as of v2.1) include an X-Requested-With header that indicates that the request was made by XMLHttpRequest instead of being triggered by clicking a regular hyperlink or form submit button.
Source: http://grails-plugins.github.io/grails-spring-security-core/guide/helperClasses.html
I'd use modulus and a loop.
int[] GetIntArray(int num)
{
List<int> listOfInts = new List<int>();
while(num > 0)
{
listOfInts.Add(num % 10);
num = num / 10;
}
listOfInts.Reverse();
return listOfInts.ToArray();
}
In the "root" __init__.py
you can also do a
import sys
sys.path.insert(1, '.')
which should make both modules importable.
If it's a background image, use background-size:contain.
Example css:
#your-div {
background: url('image.jpg') no-repeat;
background-size:contain;
}
Therefore, I would like to separate the string by the furthest delimiter.
I know this is an old question, but this is a simple requirement for which SUBSTR and INSTR would suffice. REGEXP are still slower and CPU intensive operations than the old subtsr and instr functions.
SQL> WITH DATA AS
2 ( SELECT 'F/P/O' str FROM dual
3 )
4 SELECT SUBSTR(str, 1, Instr(str, '/', -1, 1) -1) part1,
5 SUBSTR(str, Instr(str, '/', -1, 1) +1) part2
6 FROM DATA
7 /
PART1 PART2
----- -----
F/P O
As you said you want the furthest delimiter, it would mean the first delimiter from the reverse.
You approach was fine, but you were missing the start_position in INSTR. If the start_position is negative, the INSTR
function counts back start_position number of characters from the end of string and then searches towards the beginning of string.
I believe the async library will provide you a very elegant way to do this. While promises and callbacks can get a little hard to juggle with, async can give neat patterns to streamline your thought process. To run functions in serial, you would need to put them in an async waterfall. In async lingo, every function is called a task
that takes some arguments and a callback
; which is the next function in the sequence. The basic structure would look something like:
async.waterfall([
// A list of functions
function(callback){
// Function no. 1 in sequence
callback(null, arg);
},
function(arg, callback){
// Function no. 2 in sequence
callback(null);
}
],
function(err, results){
// Optional final callback will get results for all prior functions
});
I've just tried to briefly explain the structure here. Read through the waterfall guide for more information, it's pretty well written.
Launch4j perhaps? Can't say I've used it myself, but it sounds like what you're after.
If you are generating Notification from a Service that is started in the foreground using
startForeground(NOTIFICATION_ID, notificationBuilder.build());
Then issuing
notificationManager.cancel(NOTIFICATION_ID);
does't work canceling the Notification & notification still appears in the status bar. In this particular case, you will solve these by 2 ways:
1> Using stopForeground( false ) inside service:
stopForeground( false );
notificationManager.cancel(NOTIFICATION_ID);
2> Destroy that service class with calling activity:
Intent i = new Intent(context, Service.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
if(ServiceCallingActivity.activity != null) {
ServiceCallingActivity.activity.finish();
}
context.stopService(i);
Second way prefer in music player notification more because thay way not only notification remove but remove player also...!!
You can add your attribute on callback function ({key} , speed.callback, like is
$('.usercontent').animate( {
backgroundColor:'#ddd',
},1000,function () {
$(this).css("backgroundColor","red")
});
Depending on the type of your variable, one of abs(int)
, labs(long)
, llabs(long long)
, imaxabs(intmax_t)
, fabsf(float)
, fabs(double)
, or fabsl(long double)
.
Those functions are all part of the C standard library, and so are present both in Objective-C and plain C (and are generally available in C++ programs too.)
(Alas, there is no habs(short)
function. Or scabs(signed char)
for that matter...)
Apple's and GNU's Objective-C headers also include an ABS()
macro which is type-agnostic. I don't recommend using ABS()
however as it is not guaranteed to be side-effect-safe. For instance, ABS(a++)
will have an undefined result.
If you're using C++ or Objective-C++, you can bring in the <cmath>
header and use std::abs()
, which is templated for all the standard integer and floating-point types.
every javascript object is a simple hashmap which accepts a string or a Symbol as its key, so you could write your code as:
var map = {};
// add a item
map[key1] = value1;
// or remove it
delete map[key1];
// or determine whether a key exists
key1 in map;
javascript object is a real hashmap on its implementation, so the complexity on search is O(1), but there is no dedicated hashcode()
function for javascript strings, it is implemented internally by javascript engine (V8, SpiderMonkey, JScript.dll, etc...)
2020 Update:
javascript today supports other datatypes as well: Map
and WeakMap
. They behave more closely as hash maps than traditional objects.
The modern way to do this is with flexbox, adding align-items: flex-end;
on the container.
With this content:
<div class="Container">
<div>one</div>
<div>two</div>
</div>
Use this style:
.Container {
display: flex;
align-items: flex-end;
}
Working code, I have used Java Mail 1.4.7 jar
import java.util.Properties;
import javax.activation.*;
import javax.mail.*;
public class MailProjectClass {
public static void main(String[] args) {
final String username = "[email protected]";
final String password = "your.password";
Properties props = new Properties();
props.put("mail.smtp.auth", true);
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("[email protected]"));
message.setSubject("Testing Subject");
message.setText("PFA");
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
String file = "path of file to be attached";
String fileName = "attachmentName";
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
System.out.println("Sending");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
It is most efficient to do your aggregation by integer and then convert back to datetime for presentation.
select
cast(daybucket - 1 as datetime) as count_date,
counted_leads
from
(select
cast(created_date as int) as DayBucket,
count(*) as counted_leads
from mytable
group by cast(created_date as int) ) as countByDay
in my case I have to update the records which are more than 1000, for this instead of hitting the update query each time I preferred this,
UPDATE mst_users
SET base_id = CASE user_id
WHEN 78 THEN 999
WHEN 77 THEN 88
ELSE base_id END WHERE user_id IN(78, 77)
78,77 are the user Ids and for those user id I need to update the base_id 999 and 88 respectively.This works for me.
Note that you can also use the InOrder class to verify that various methods are called in order on a single mock, not just on two or more mocks.
Suppose I have two classes Foo
and Bar
:
public class Foo {
public void first() {}
public void second() {}
}
public class Bar {
public void firstThenSecond(Foo foo) {
foo.first();
foo.second();
}
}
I can then add a test class to test that Bar
's firstThenSecond()
method actually calls first()
, then second()
, and not second()
, then first()
. See the following test code:
public class BarTest {
@Test
public void testFirstThenSecond() {
Bar bar = new Bar();
Foo mockFoo = Mockito.mock(Foo.class);
bar.firstThenSecond(mockFoo);
InOrder orderVerifier = Mockito.inOrder(mockFoo);
// These lines will PASS
orderVerifier.verify(mockFoo).first();
orderVerifier.verify(mockFoo).second();
// These lines will FAIL
// orderVerifier.verify(mockFoo).second();
// orderVerifier.verify(mockFoo).first();
}
}
I found an article under the above topic.There by I could take the full code .I will mention it.
Here are steps mentioned in the article:
Add embedded/result/ at the end of the JSFiddle URL you wanna grab.
Show the frame or the frame’s source code: right-click anywhere in the page and view the frame in a new tab or the source right-away (requires Firefox).
Finally, save the page in your preferred format (MHT, HTML, TXT, etc.) and voilà!
also you can find it : https://sirusdark.wordpress.com/2014/04/10/how-to-save-and-download-jsfiddle-code/
A SELECT
in SQL Server will place a shared lock on a table row - and a second SELECT
would also require a shared lock, and those are compatible with one another.
So no - one SELECT
cannot block another SELECT
.
What the WITH (NOLOCK)
query hint is used for is to be able to read data that's in the process of being inserted (by another connection) and that hasn't been committed yet.
Without that query hint, a SELECT
might be blocked reading a table by an ongoing INSERT
(or UPDATE
) statement that places an exclusive lock on rows (or possibly a whole table), until that operation's transaction has been committed (or rolled back).
Problem of the WITH (NOLOCK)
hint is: you might be reading data rows that aren't going to be inserted at all, in the end (if the INSERT
transaction is rolled back) - so your e.g. report might show data that's never really been committed to the database.
There's another query hint that might be useful - WITH (READPAST)
. This instructs the SELECT
command to just skip any rows that it attempts to read and that are locked exclusively. The SELECT
will not block, and it will not read any "dirty" un-committed data - but it might skip some rows, e.g. not show all your rows in the table.
Rookie, if you want to write a file to server by socket, how about using fileoutputstream instead of dataoutputstream? dataoutputstream is more fit for protocol-level read-write. it is not very reasonable for your code in bytes reading and writing. loop to read and write is necessary in java io. and also, you use a buffer way. flush is necessary. here is a code sample: http://www.rgagnon.com/javadetails/java-0542.html
I think it's most convenient way to inject properties into bean is setter method.
Example:
package org.some.beans;
public class MyBean {
Long id;
String name;
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Bean xml definition:
<bean id="Bean1" class="org.some.beans.MyBean">
<property name="id" value="1"/>
<property name="name" value="MyBean"/>
</bean>
For every named property
method setProperty(value)
will be invoked.
This way is especially helpful if you need more than one bean based on one implementation.
For example, if we define one more bean in xml:
<bean id="Bean2" class="org.some.beans.MyBean">
<property name="id" value="2"/>
<property name="name" value="EnotherBean"/>
</bean>
Then code like this:
MyBean b1 = appContext.getBean("Bean1");
System.out.println("Bean id = " + b1.getId() + " name = " + b1.getName());
MyBean b2 = appContext.getBean("Bean2");
System.out.println("Bean id = " + b2.getId() + " name = " + b2.getName());
Will print
Bean id = 1 name = MyBean
Bean id = 2 name = AnotherBean
So, in your case it should look like this:
@Repository("personDao")
public class PersonDaoImpl extends AbstractDaoImpl implements PersonDao {
Long maxResults;
public void setMaxResults(Long maxResults) {
this.maxResults = maxResults;
}
// Now use maxResults value in your code, it will be injected on Bean creation
public void someMethod(Long results) {
if (results < maxResults) {
...
}
}
}
You typically restore purchases with this code:
[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
It will reinvoke -paymentQueue:updatedTransactions
on the observer(s) for the purchased items. This is useful for users who reinstall the app after deletion or install it on a different device.
Not all types of In-App purchases can be restored.
You can also use this syntax (L[start:stop:step]
):
mylist = [1,2,3,4,5,6,7,8,9,10]
for i in mylist[::2]:
print i,
# prints 1 3 5 7 9
for i in mylist[1::2]:
print i,
# prints 2 4 6 8 10
Where the first digit is the starting index (defaults to beginning of list or 0), 2nd is ending slice index (defaults to end of list), and the third digit is the offset or step.
In node.js we can use node-geocoder npm module to get address from lat, lng.,
geo.js
var NodeGeocoder = require('node-geocoder');
var options = {
provider: 'google',
httpAdapter: 'https', // Default
apiKey: ' ', // for Mapquest, OpenCage, Google Premier
formatter: 'json' // 'gpx', 'string', ...
};
var geocoder = NodeGeocoder(options);
geocoder.reverse({lat:28.5967439, lon:77.3285038}, function(err, res) {
console.log(res);
});
output:
node geo.js
[ { formattedAddress: 'C-85B, C Block, Sector 8, Noida, Uttar Pradesh 201301, India',
latitude: 28.5967439,
longitude: 77.3285038,
extra:
{ googlePlaceId: 'ChIJkTdx9vzkDDkRx6LVvtz1Rhk',
confidence: 1,
premise: 'C-85B',
subpremise: null,
neighborhood: 'C Block',
establishment: null },
administrativeLevels:
{ level2long: 'Gautam Buddh Nagar',
level2short: 'Gautam Buddh Nagar',
level1long: 'Uttar Pradesh',
level1short: 'UP' },
city: 'Noida',
country: 'India',
countryCode: 'IN',
zipcode: '201301',
provider: 'google' } ]
My class was annotated with JsonSerialize, and the include parameter was set to JsonSerialize.Inclusion.NON_DEFAULT
. This caused Jackson to determine the default values for each bean property. I had a bean property that returned an int. The problem in my case was that the bean getter made a call to a method which has an inferred return type (i.e.: a generic method). For some odd reason this code compiled; it shouldn't have compiled because you cannot use an int for an inferred return type. I changed the 'int' to an 'Integer' for that bean property and I no longer got a 406. The odd thing is, the code now fails to compile if I change the Integer back to an int.
This problem is about SSL connection. When you try to connect to some resource https protocol requires to create secured connection. That means only your browser and website server know what data is being sent in requests bodies. This security is achieved by ssl certificates that stored on website and are being downloaded by your browser (or any other client, Spring RestTemplate with Apache Http Client behind in our case) with first connection to host. There are RSA256 encryption and many other cool things around. But in the end of a day: In case certificate is not registered or is invalid you will see certificate error (HTTPS connection is not secure). To fix certificate error website provider need to buy it for particular website or fix somehow e.g. https://www.register.com/ssl-certificates
Right way how problem can be solved
Not a right way how problem can be solved
import SSL certificate to Java cacerts (certificate storage)
keytool -importcert -trustcacerts -noprompt -storepass changeit -alias citrix -keystore "C:\Program Files\Java\jdk-11.0.2\lib\security\cacerts" -file citrix.cer
Dirty (Insecure) way how problem can be solved
make RestTemplate to ignore SSL verification
@Bean
public RestTemplateBuilder restTemplateBuilder(@Autowired SSLContext sslContext) {
return new RestTemplateBuilder() {
@Override
public ClientHttpRequestFactory buildRequestFactory() {
return new HttpComponentsClientHttpRequestFactory(
HttpClients.custom().setSSLSocketFactory(
new SSLConnectionSocketFactory(sslContext
, NoopHostnameVerifier.INSTANCE)).build());
}
};
}
@Bean
public SSLContext insecureSslContext() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
return SSLContexts.custom()
.loadTrustMaterial(null, (x509Certificates, s) -> true)
.build();
}
Unfortunately what you'd like to do is not possible. GraphQL requires you to be explicit about specifying which fields you would like returned from your query.
Note that this approach is more biased and less efficient than a nextInt
approach, https://stackoverflow.com/a/738651/360211
One standard pattern for accomplishing this is:
Min + (int)(Math.random() * ((Max - Min) + 1))
The Java Math library function Math.random() generates a double value in the range [0,1)
. Notice this range does not include the 1.
In order to get a specific range of values first, you need to multiply by the magnitude of the range of values you want covered.
Math.random() * ( Max - Min )
This returns a value in the range [0,Max-Min)
, where 'Max-Min' is not included.
For example, if you want [5,10)
, you need to cover five integer values so you use
Math.random() * 5
This would return a value in the range [0,5)
, where 5 is not included.
Now you need to shift this range up to the range that you are targeting. You do this by adding the Min value.
Min + (Math.random() * (Max - Min))
You now will get a value in the range [Min,Max)
. Following our example, that means [5,10)
:
5 + (Math.random() * (10 - 5))
But, this still doesn't include Max
and you are getting a double value. In order to get the Max
value included, you need to add 1 to your range parameter (Max - Min)
and then truncate the decimal part by casting to an int. This is accomplished via:
Min + (int)(Math.random() * ((Max - Min) + 1))
And there you have it. A random integer value in the range [Min,Max]
, or per the example [5,10]
:
5 + (int)(Math.random() * ((10 - 5) + 1))
For gcc you want to omit any -O1 -O2 or -O3 options passed to the compiler or if you already have them you can append the -O0 option to turn it off again. It might also help you to add -g for debug so that you can see the c source and disassembled machine code in your debugger.
See also: http://sourceware.org/gdb/onlinedocs/gdb/Optimized-Code.html
Here is the angularJs source code for parsing url query parameters into an Object :
function tryDecodeURIComponent(value) {_x000D_
try {_x000D_
return decodeURIComponent(value);_x000D_
} catch (e) {_x000D_
// Ignore any invalid uri component_x000D_
}_x000D_
}_x000D_
_x000D_
function isDefined(value) {return typeof value !== 'undefined';}_x000D_
_x000D_
function parseKeyValue(keyValue) {_x000D_
keyValue = keyValue.replace(/^\?/, '');_x000D_
var obj = {}, key_value, key;_x000D_
var iter = (keyValue || "").split('&');_x000D_
for (var i=0; i<iter.length; i++) {_x000D_
var kValue = iter[i];_x000D_
if (kValue) {_x000D_
key_value = kValue.replace(/\+/g,'%20').split('=');_x000D_
key = tryDecodeURIComponent(key_value[0]);_x000D_
if (isDefined(key)) {_x000D_
var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;_x000D_
if (!hasOwnProperty.call(obj, key)) {_x000D_
obj[key] = val;_x000D_
} else if (isArray(obj[key])) {_x000D_
obj[key].push(val);_x000D_
} else {_x000D_
obj[key] = [obj[key],val];_x000D_
}_x000D_
}_x000D_
}_x000D_
};_x000D_
return obj;_x000D_
}_x000D_
_x000D_
alert(JSON.stringify(parseKeyValue('?a=1&b=3&c=m2-m3-m4-m5')));
_x000D_
You can add this function to window.location
:
window.location.query = function query(arg){
q = parseKeyValue(this.search);
if (!isDefined(arg)) {
return q;
}
if (q.hasOwnProperty(arg)) {
return q[arg];
} else {
return "";
}
}
// assuming you have this url :
// http://www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5
console.log(window.location.query())
// Object {a: "1", b: "3", c: "m2-m3-m4-m5"}
console.log(window.location.query('c'))
// "m2-m3-m4-m5"
I stumbled on this question while trying to do the same thing (I think). Here is how I did it:
df['index_col'] = df.index
You can then sort on the new index column, if you like.
B is not statistically significant. The data is not capable of drawing inferences from it. C does influence B probabilities
df = pd.DataFrame({"A": [10,20,30,40,50], "B": [20, 30, 10, 40, 50], "C": [32, 234, 23, 23, 42523]})
avg_c=df['C'].mean()
sumC=df['C'].apply(lambda x: x if x<avg_c else 0).sum()
countC=df['C'].apply(lambda x: 1 if x<avg_c else None).count()
avg_c2=sumC/countC
df['C']=df['C'].apply(lambda x: avg_c2 if x >avg_c else x)
print(df)
model_ols = smf.ols("A ~ B+C",data=df).fit()
print(model_ols.summary())
df[['B','C']].plot()
plt.show()
df2=pd.DataFrame()
df2['B']=np.linspace(10,50,10)
df2['C']=30
df3=pd.DataFrame()
df3['B']=np.linspace(10,50,10)
df3['C']=100
predB=model_ols.predict(df2)
predC=model_ols.predict(df3)
plt.plot(df2['B'],predB,label='predict B C=30')
plt.plot(df3['B'],predC,label='predict B C=100')
plt.legend()
plt.show()
print("A change in the probability of C affects the probability of B")
intercept=model_ols.params.loc['Intercept']
B_slope=model_ols.params.loc['B']
C_slope=model_ols.params.loc['C']
#Intercept 11.874252
#B 0.760859
#C -0.060257
print("Intercept {}\n B slope{}\n C slope{}\n".format(intercept,B_slope,C_slope))
#lower_conf,upper_conf=np.exp(model_ols.conf_int())
#print(lower_conf,upper_conf)
#print((1-(lower_conf/upper_conf))*100)
model_cov=model_ols.cov_params()
std_errorB = np.sqrt(model_cov.loc['B', 'B'])
std_errorC = np.sqrt(model_cov.loc['C', 'C'])
print('SE: ', round(std_errorB, 4),round(std_errorC, 4))
#check for statistically significant
print("B z value {} C z value {}".format((B_slope/std_errorB),(C_slope/std_errorC)))
print("B feature is more statistically significant than C")
Output:
A change in the probability of C affects the probability of B
Intercept 11.874251554067563
B slope0.7608594144571961
C slope-0.060256845997223814
Standard Error: 0.4519 0.0793
B z value 1.683510336937001 C z value -0.7601036314930376
B feature is more statistically significant than C
z>2 is statistically significant
// Once finished with the bitmap objects, we deallocate them.
originalBMP.Dispose();
bannerBMP.Dispose();
oGraphics.Dispose();
This is a programming style that you'll regret sooner or later. Sooner is knocking on the door, you forgot one. You are not disposing newBitmap. Which keeps a lock on the file until the garbage collector runs. If it doesn't run then the second time you try to save to the same file you'll get the klaboom. GDI+ exceptions are too miserable to give a good diagnostic so serious head-scratching ensues. Beyond the thousands of googlable posts that mention this mistake.
Always favor using the using statement. Which never forgets to dispose an object, even if the code throws an exception.
using (var newBitmap = new Bitmap(thumbBMP)) {
newBitmap.Save("~/image/thumbs/" + "t" + objPropBannerImage.ImageId, ImageFormat.Jpeg);
}
Albeit that it is very unclear why you even create a new bitmap, saving thumbBMP should already be good enough. Anyhoo, give the rest of your disposable objects the same using love.
On Postgres @Lob is breaking for byte[] as it tries to save it as oid, and for String also same problem occurs. Below code is breaking on postgres which is working fine on oracle.
@Lob
private String stringField;
and
@Lob
private byte[] someByteStream;
In order to fix above on postgres have written below custom hibernate.dialect
public class PostgreSQLDialectCustom extends PostgreSQL82Dialect{
public PostgreSQLDialectCustom()
{
super();
registerColumnType(Types.BLOB, "bytea");
}
@Override
public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) {
if (Types.CLOB == sqlTypeDescriptor.getSqlType()) {
return LongVarcharTypeDescriptor.INSTANCE;
}
return super.remapSqlTypeDescriptor(sqlTypeDescriptor);
}
}
Now configure custom dialect in hibernate
hibernate.dialect=X.Y.Z.PostgreSQLDialectCustom
X.Y.Z is package name.
Now it working fine. NOTE- My Hibernate version - 5.2.8.Final Postgres version- 9.6.3
I've encountered such issue recently. Though code was correct, I didn't turn on permissions in app settings. So, all permissions hasn't been set by default on emulators, so you should do it yourself.
n your code, for the modal-dialog div, add another class, modal-lg:
use modal-xl
If you are only interested in the direct parent, and not other ancestors, you can just use parent()
, and give it the selector, as in target.parent('div#hello')
.
Example: http://jsfiddle.net/6BX9n/
function fun(evt) {
var target = $(evt.target);
if (target.parent('div#hello').length) {
alert('Your clicked element is having div#hello as parent');
}
}
Or if you want to check to see if there are any ancestors that match, then use .parents()
.
Example: http://jsfiddle.net/6BX9n/1/
function fun(evt) {
var target = $(evt.target);
if (target.parents('div#hello').length) {
alert('Your clicked element is having div#hello as parent');
}
}
For windows open git bash and try
NODE_ENV=production node app.js
For Chrome via Chrome Fullscreen API
Note that for (Chrome) security reasons it cannot be called or executed automatically, there must be an interaction from the user first. (Such as button click, keydown/keypress etc.)
addEventListener("click", function() {
var
el = document.documentElement
, rfs =
el.requestFullScreen
|| el.webkitRequestFullScreen
|| el.mozRequestFullScreen
;
rfs.call(el);
});
Javascript Fullscreen API as demo'd by David Walsh that seems to be a cross browser solution
// Find the right method, call on correct element
function launchFullScreen(element) {
if(element.requestFullScreen) {
element.requestFullScreen();
} else if(element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if(element.webkitRequestFullScreen) {
element.webkitRequestFullScreen();
}
}
// Launch fullscreen for browsers that support it!
launchFullScreen(document.documentElement); // the whole page
launchFullScreen(document.getElementById("videoElement")); // any individual element
Right click project -> Properties -> Build Events
Remove the text in Post-build event command line text block
First off I should point out that css animations would probably work best if you are doing this a lot but I ended getting the desired effect by wrapping .scrollLeft inside .animate
$('.swipeRight').click(function()
{
$('.swipeBox').animate( { scrollLeft: '+=460' }, 1000);
});
$('.swipeLeft').click(function()
{
$('.swipeBox').animate( { scrollLeft: '-=460' }, 1000);
});
The second parameter is speed, and you can also add a third parameter if you are using smooth scrolling of some sort.
It looks like you are trying to read an object from JSON that actually describes an array. Java objects are mapped to JSON objects with curly braces {}
but your JSON actually starts with square brackets []
designating an array.
What you actually have is a List<product>
To describe generic types, due to Java's type erasure, you must use a TypeReference
. Your deserialization could read: myProduct = objectMapper.readValue(productJson, new TypeReference<List<product>>() {});
A couple of other notes: your classes should always be PascalCased. Your main method can just be public static void main(String[] args) throws Exception
which saves you all the useless catch
blocks.
It's generally recommended to use a version manager like rbenv
or rvm
. Otherwise, installed Gems will be available as root
for other users.
If you know what you're doing, you can use sudo gem install
.
Style the td
and th
instead
td, th {
border: 1px solid black;
}
And also to make it so there is no spacing between cells use:
table {
border-collapse: collapse;
}
(also note, you have border-style: none;
which should be border-style: solid;
)
See an example here: http://jsfiddle.net/KbjNr/
Try this:
export CURLNAME="john:@31&3*J"
curl -d -u "${CURLNAME}" https://www.example.com
You must not use StreamReader
for binary files (like gifs or jpgs). StreamReader
is for text data. You will almost certainly lose data if you use it for arbitrary binary data. (If you use Encoding.GetEncoding(28591) you will probably be okay, but what's the point?)
Why do you need to use a StreamReader
at all? Why not just keep the binary data as binary data and write it back to disk (or SQL) as binary data?
EDIT: As this seems to be something people want to see... if you do just want to copy one stream to another (e.g. to a file) use something like this:
/// <summary>
/// Copies the contents of input to output. Doesn't close either stream.
/// </summary>
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[8 * 1024];
int len;
while ( (len = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, len);
}
}
To use it to dump a stream to a file, for example:
using (Stream file = File.Create(filename))
{
CopyStream(input, file);
}
Note that Stream.CopyTo
was introduced in .NET 4, serving basically the same purpose.
You can switch to manual build so can control when this is done. Just make sure that Project > Build Automatically
from the main menu is unchecked.
Pelo Hyper-V:
private PerformanceCounter theMemCounter = new PerformanceCounter(
"Hyper-v Dynamic Memory VM",
"Physical Memory",
Process.GetCurrentProcess().ProcessName);
You can try the below function to get value from JSON string,
public static String GetJSONValue(String JSONString, String Field)
{
return JSONString.substring(JSONString.indexOf(Field), JSONString.indexOf("\n", JSONString.indexOf(Field))).replace(Field+"\": \"", "").replace("\"", "").replace(",","");
}
For speed, I would do the following, which requires only one pass through each of the two arrays. This method preserves order. I will first present code that does not mutate the original array, then show how it can be easily modified to mutate.
arr = [1,1,1,2,2,3,1]
removals = [1,3,1]
h = removals.group_by(&:itself).transform_values(&:size)
#=> {1=>2, 3=>1}
arr.each_with_object([]) { |n,a|
h.key?(n) && h[n] > 0 ? (h[n] -= 1) : a << n }
#=> [1, 2, 2, 1]
arr
#=> [1, 1, 1, 2, 2, 3, 1]
To mutate arr
write:
h = removals.group_by(&:itself).transform_values(&:count)
arr.replace(arr.each_with_object([]) { |n,a|
h.key?(n) && h[n] > 0 ? (h[n] -= 1) : a << n })
#=> [1, 2, 2, 1]
arr
#=> [1, 2, 2, 1]
This uses the 21st century method Hash#transform_values (new in MRI v2.4), but one could instead write:
h = Hash[removals.group_by(&:itself).map { |k,v| [k,v.size] }]
or
h = removals.each_with_object(Hash.new(0)) { | n,h| h[n] += 1 }
The Problem
When an element is floated, its parent no longer contains it because the float is removed from the flow. The floated element is out of the natural flow, so all block elements will render as if the floated element is not even there, so a parent container will not fully expand to hold the floated child element.
Take a look at the following article to get a better idea of how the CSS Float property works:
The Mystery Of The CSS Float Property
A Potential Solution
Now, I think the following article resembles what you're trying to do. Take a look at it and see if you can solve your problem.
Equal Height Columns with Cross-Browser CSS
I hope this helps.
As @markus said use the "Cookie Manager" and delete the cookie.
If you want to learn how to set destroy cookies in postman, You should check the Postman Echo service https://docs.postman-echo.com/
There you will find complete explanation on how to Set, Get and Delete those cookies.
Check it on : https://docs.postman-echo.com/#3de3b135-b3cc-3a68-ba27-b6d373e03c8c
Give it a Try.
CHARINDEX()
searches for a substring within a larger string, and returns the position of the match, or 0 if no match is found
if CHARINDEX('ME',@mainString) > 0
begin
--do something
end
Edit or from daniels answer, if you're wanting to find a word (and not subcomponents of words), your CHARINDEX
call would look like:
CHARINDEX(' ME ',' ' + REPLACE(REPLACE(@mainString,',',' '),'.',' ') + ' ')
(Add more recursive REPLACE() calls for any other punctuation that may occur)
The .NET framework provides a ToolTip class. Add one of those to your form and then on the MouseHover event for each item you would like a tooltip for, do something like the following:
private void checkBox1_MouseHover(object sender, EventArgs e)
{
toolTip1.Show("text", checkBox1);
}
Interesting I just ran a test using LinqPad with SQL Server which should be just running Linq to SQL underneath and it generates the following SQL statement.
Records .Where(r => r.Name.Contains("lkjwer--_~[]"))
-- Region Parameters
DECLARE @p0 VarChar(1000) = '%lkjwer--~_~~~[]%'
-- EndRegion
SELECT [t0].[ID], [t0].[Name]
FROM [RECORDS] AS [t0]
WHERE [t0].[Name] LIKE @p0 ESCAPE '~'
So I haven't tested it yet but it looks like potentially the ESCAPE '~'
keyword may allow for automatic escaping of a string for use within a like expression.
You should take a look at Java date formatting, in particular SimpleDateFormat. There's some examples here: http://download.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html - but you can also find a lot more with a quick google.
If you use native sql, you can refer to my code, otherwise just ignore my answer.
SELECT * FROM table WHERE tags LIKE "%banana%";
from sqlalchemy import text
bar_tags = "banana"
# '%' attention to spaces
query_sql = """SELECT * FROM table WHERE tags LIKE '%' :bar_tags '%'"""
# db is sqlalchemy session object
tags_res_list = db.execute(text(query_sql), {"bar_tags": bar_tags}).fetchall()
As it may happens that the default branch of your submodules is not master
, this is how I automate the full Git submodules upgrades:
git submodule init
git submodule update
git submodule foreach 'git fetch origin; git checkout $(git rev-parse --abbrev-ref HEAD); git reset --hard origin/$(git rev-parse --abbrev-ref HEAD); git submodule update --recursive; git clean -dfx'
It has nothing to do with your form or the values in it. It gets fired by the browser to prevent the user from repeating the same request with the cached data. If you really need to enable the refreshing of the result page, you should redirect the user, either via PHP (header('Location:result.php');
) or other server-side language you're using. Meta tag solution should work also to disable the resending on refresh.
As already pointed out in comments by Abhijeet you can just add line like:
/target/**
to exclude file in \.git\info\
folder.
Then if you want to get rid of that target
folder in your remote repo you will need to first manually delete this folder from your local repository, commit and then push it. Thats because git will show you content of a target folder as modified at first.
Imagine you end up with double dashes, and want to replace them with a single character and not doubles of the replace character. You can just use array split and array filter and array join.
var str = "This-is---a--news-----item----";
Then to replace all dashes with single spaces, you could do this:
var newStr = str.split('-').filter(function(item) {
item = item ? item.replace(/-/g, ''): item
return item;
}).join(' ');
Now if the string contains double dashes, like '----' then array split will produce an element with 3 dashes in it (because it split on the first dash). So by using this line:
item = item ? item.replace(/-/g, ''): item
The filter method removes those extra dashes so the element will be ignored on the filter iteration. The above line also accounts for if item is already an empty element so it doesn't crash on item.replace.
Then when your string join runs on the filtered elements, you end up with this output:
"This is a news item"
Now if you were using something like knockout.js where you can have computer observables. You could create a computed observable to always calculate "newStr" when "str" changes so you'd always have a version of the string with no dashes even if you change the value of the original input string. Basically they are bound together. I'm sure other JS frameworks can do similar things.
SELECT to_char(sysdate + (1/24/60) * 30, 'dd/mm/yy HH24:MI am') from dual;
simply you can use this with various date format....
To answer the question more generally, the answer is:
select: function( event , ui ) {
alert( "You selected: " + ui.item.label );
}
Complete example :
$('#test').each(function(i, el) {_x000D_
var that = $(el);_x000D_
that.autocomplete({_x000D_
source: ['apple','banana','orange'],_x000D_
select: function( event , ui ) {_x000D_
alert( "You selected: " + ui.item.label );_x000D_
}_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>_x000D_
_x000D_
Type a fruit here: <input type="text" id="test" />
_x000D_
in fact, you can, but not that way.
Sub MySub( Optional Byval Counter as Long=1 , Optional Byval Events as Boolean= True)
'code...
End Sub
And you can set the variables differently when calling the sub, or let them at their default values.
No. But it's relatively trivial to achieve using sscanf
in a loop.
The better and correct solution is to have a directive. The scope is the same, whether in the controller of the directive or the main controller. Use $element
to do DOM operations. The method defined in the directive controller is accessible in the main controller.
Example, finding a child element:
var app = angular.module('myapp', []);
app.directive("testDir", function () {
function link(scope, element) {
}
return {
restrict: "AE",
link: link,
controller:function($scope,$element){
$scope.name2 = 'this is second name';
var barGridSection = $element.find('#barGridSection'); //helps to find the child element.
}
};
})
app.controller('mainController', function ($scope) {
$scope.name='this is first name'
});
I modified @Abhishek Chaubey answer to change the whole file name:
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
applicationVariants.all { variant ->
variant.outputs.each { output ->
project.ext { appName = 'MyAppName' }
def formattedDate = new Date().format('yyyyMMddHHmmss')
def newName = output.outputFile.name
newName = newName.replace("app-", "$project.ext.appName-") //"MyAppName" -> I set my app variables in the root project
newName = newName.replace("-release", "-release" + formattedDate)
//noinspection GroovyAssignabilityCheck
output.outputFile = new File(output.outputFile.parent, newName)
}
}
}
debug {
}
}
This produces a file name like: MyAppName-release20150519121617.apk
When the browser sends p
in the querystring, it is received as a string, not an int. is_int()
will therefore always return false.
Instead try is_numeric()
or ctype_digit()
You can use the strip() to remove trailing and leading spaces.
>>> s = ' abd cde '
>>> s.strip()
'abd cde'
Note: the internal spaces are preserved
The better practice is to use for-each
. Besides violating the Keep It Simple, Stupid principle, the new-fangled forEach()
has at least the following deficiencies:
Object prev = null; for(Object curr : list) { if( prev != null ) foo(prev, curr); prev = curr; }
Can't handle checked exceptions. Lambdas aren't actually forbidden from throwing checked exceptions, but common functional interfaces like Consumer
don't declare any. Therefore, any code that throws checked exceptions must wrap them in try-catch
or Throwables.propagate()
. But even if you do that, it's not always clear what happens to the thrown exception. It could get swallowed somewhere in the guts of forEach()
Limited flow-control. A return
in a lambda equals a continue
in a for-each, but there is no equivalent to a break
. It's also difficult to do things like return values, short circuit, or set flags (which would have alleviated things a bit, if it wasn't a violation of the no non-final variables rule). "This is not just an optimization, but critical when you consider that some sequences (like reading the lines in a file) may have side-effects, or you may have an infinite sequence."
Might execute in parallel, which is a horrible, horrible thing for all but the 0.1% of your code that needs to be optimized. Any parallel code has to be thought through (even if it doesn't use locks, volatiles, and other particularly nasty aspects of traditional multi-threaded execution). Any bug will be tough to find.
Might hurt performance, because the JIT can't optimize forEach()+lambda to the same extent as plain loops, especially now that lambdas are new. By "optimization" I do not mean the overhead of calling lambdas (which is small), but to the sophisticated analysis and transformation that the modern JIT compiler performs on running code.
If you do need parallelism, it is probably much faster and not much more difficult to use an ExecutorService. Streams are both automagical (read: don't know much about your problem) and use a specialized (read: inefficient for the general case) parallelization strategy (fork-join recursive decomposition).
Makes debugging more confusing, because of the nested call hierarchy and, god forbid, parallel execution. The debugger may have issues displaying variables from the surrounding code, and things like step-through may not work as expected.
Streams in general are more difficult to code, read, and debug. Actually, this is true of complex "fluent" APIs in general. The combination of complex single statements, heavy use of generics, and lack of intermediate variables conspire to produce confusing error messages and frustrate debugging. Instead of "this method doesn't have an overload for type X" you get an error message closer to "somewhere you messed up the types, but we don't know where or how." Similarly, you can't step through and examine things in a debugger as easily as when the code is broken into multiple statements, and intermediate values are saved to variables. Finally, reading the code and understanding the types and behavior at each stage of execution may be non-trivial.
Sticks out like a sore thumb. The Java language already has the for-each statement. Why replace it with a function call? Why encourage hiding side-effects somewhere in expressions? Why encourage unwieldy one-liners? Mixing regular for-each and new forEach willy-nilly is bad style. Code should speak in idioms (patterns that are quick to comprehend due to their repetition), and the fewer idioms are used the clearer the code is and less time is spent deciding which idiom to use (a big time-drain for perfectionists like myself!).
As you can see, I'm not a big fan of the forEach() except in cases when it makes sense.
Particularly offensive to me is the fact that Stream
does not implement Iterable
(despite actually having method iterator
) and cannot be used in a for-each, only with a forEach(). I recommend casting Streams into Iterables with (Iterable<T>)stream::iterator
. A better alternative is to use StreamEx which fixes a number of Stream API problems, including implementing Iterable
.
That said, forEach()
is useful for the following:
Atomically iterating over a synchronized list. Prior to this, a list generated with Collections.synchronizedList()
was atomic with respect to things like get or set, but was not thread-safe when iterating.
Parallel execution (using an appropriate parallel stream). This saves you a few lines of code vs using an ExecutorService, if your problem matches the performance assumptions built into Streams and Spliterators.
Specific containers which, like the synchronized list, benefit from being in control of iteration (although this is largely theoretical unless people can bring up more examples)
Calling a single function more cleanly by using forEach()
and a method reference argument (ie, list.forEach (obj::someMethod)
). However, keep in mind the points on checked exceptions, more difficult debugging, and reducing the number of idioms you use when writing code.
Articles I used for reference:
EDIT: Looks like some of the original proposals for lambdas (such as http://www.javac.info/closures-v06a.html Google Cache) solved some of the issues I mentioned (while adding their own complications, of course).
Alternatively you could use:
if ($('#navigation a').is(".active")) {
$(this).parent().addClass("active");
}
I found the above answer giving an error with Oracle SQL, you also must use square brackets, below;
SQL> SELECT Q'[Paddy O'Reilly]' FROM DUAL;
Result: Paddy O'Reilly
Either specify the type of T, or if you want to make it generic, you'll need to make the parent class generic.
public class MyClass<T>
{
etc
There is no need for custom helper functions if all we need is to print the string of the form [D day[s], ][H]H:MM:SS[.UUUUUU]
. timedelta object supports str()
operation that will do this. It works even in Python 2.6.
>>> from datetime import timedelta
>>> timedelta(seconds=90136)
datetime.timedelta(1, 3736)
>>> str(timedelta(seconds=90136))
'1 day, 1:02:16'
Encountered the same issue with a ASP.Net Web App and two library class projects which needed to be referenced within the Web App. I had no information provided on why the build failed and the references were invalid.
Solution was to ensure all projects had the same Target Framework:
In Visual Studio 2015- Right Click project > Properties > Application > Target Framework
Save, Clean and Rebuild solution. The project references should no longer appear as yellow warnings and the solution will compile.
My Web App was targeting .Net 4.5 whereas the other two dependent library class projects targeted .Net v4.5.2
With jQuery library-
Use .width()
and .height()
.
More in jQuery width and jQuery heigth.
$(document).ready(function(){_x000D_
$("button").click(function()_x000D_
{_x000D_
alert("Width of image: " + $("#img_exmpl").width());_x000D_
alert("Height of image: " + $("#img_exmpl").height());_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>_x000D_
_x000D_
<img id="img_exmpl" src="http://images.all-free-download.com/images/graphicthumb/beauty_of_nature_9_210287.jpg">_x000D_
<button>Display dimensions of img</button>
_x000D_
I needed a slightly different result.
I wanted the first word, and what ever came after it - even if it was blank.
str.substr(0, text.indexOf(' ') == -1 ? text.length : text.indexOf(' '));
str.substr(text.indexOf(' ') == -1 ? text.length : text.indexOf(' ') + 1);
so if the input is oneword
you get oneword
and ''
.
If the input is one word and some more
you get one
and word and some more
.
You will need to use reflection to get the type "TestRunner". Use the Assembly.GetType method.
class Program
{
static void Main(string[] args)
{
Assembly assembly = Assembly.LoadFile(@"C:\dyn.dll");
Type type = assembly.GetType("TestRunner");
var obj = (TestRunner)Activator.CreateInstance(type);
obj.Run();
}
}
static void PrintSmallestLargest(int[] arr)
{
if (arr.Length > 0)
{
int small = arr[0];
int large = arr[0];
for (int i = 0; i < arr.Length; i++)
{
if (large < arr[i])
{
int tmp = large;
large = arr[i];
arr[i] = large;
}
if (small > arr[i])
{
int tmp = small;
small = arr[i];
arr[i] = small;
}
}
Console.WriteLine("Smallest is {0}", small);
Console.WriteLine("Largest is {0}", large);
}
}
This way you can have smallest and largest number in a single loop.
Yes, define log4j.configuration
property
java -Dlog4j.configuration=file:/path/to/log4j.properties myApp
Note, that property value must be a URL.
For more read section 'Default Initialization Procedure' in Log4j manual.
In Windows 7, the command is
fsutil hardlink create new-file existing-file
PowerShell finds it without the full path (c:\Windows\system32) or extension (.exe).
Yup, and sun.misc.BASE64Decoder is way slower: 9x slower than java.xml.bind.DatatypeConverter.parseBase64Binary() and 4x slower than org.apache.commons.codec.binary.Base64.decodeBase64(), at least for a small string on Java 6 OSX.
Below is the test program I used. With Java 1.6.0_43 on OSX:
john:password = am9objpwYXNzd29yZA==
javax.xml took 373: john:password
apache took 612: john:password
sun took 2215: john:password
Btw that's with commons-codec 1.4. With 1.7 it seems to get slower:
javax.xml took 377: john:password
apache took 1681: john:password
sun took 2197: john:password
Didn't test Java 7 or other OS.
import javax.xml.bind.DatatypeConverter;
import org.apache.commons.codec.binary.Base64;
import java.io.IOException;
public class TestBase64 {
private static volatile String save = null;
public static void main(String argv[]) {
String teststr = "john:password";
String b64 = DatatypeConverter.printBase64Binary(teststr.getBytes());
System.out.println(teststr + " = " + b64);
try {
final int COUNT = 1000000;
long start;
start = System.currentTimeMillis();
for (int i=0; i<COUNT; ++i) {
save = new String(DatatypeConverter.parseBase64Binary(b64));
}
System.out.println("javax.xml took "+(System.currentTimeMillis()-start)+": "+save);
start = System.currentTimeMillis();
for (int i=0; i<COUNT; ++i) {
save = new String(Base64.decodeBase64(b64));
}
System.out.println("apache took "+(System.currentTimeMillis()-start)+": "+save);
sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
start = System.currentTimeMillis();
for (int i=0; i<COUNT; ++i) {
save = new String(dec.decodeBuffer(b64));
}
System.out.println("sun took "+(System.currentTimeMillis()-start)+": "+save);
} catch (Exception e) {
System.out.println(e);
}
}
}
new AsyncRoute({path: '/demo/:demoKey1/:demoKey2', loader: () => {
return System.import('app/modules/demo/demo').then(m =>m.demoComponent);
}, name: 'demoPage'}),
export class demoComponent {
onClick(){
this._router.navigate( ['/demoPage', {demoKey1: "123", demoKey2: "234"}]);
}
}
Create a table with column as type json
CREATE TABLE friends ( id serial primary key, data jsonb);
Now let's insert json data
INSERT INTO friends(data) VALUES ('{"name": "Arya", "work": ["Improvements", "Office"], "available": true}');
INSERT INTO friends(data) VALUES ('{"name": "Tim Cook", "work": ["Cook", "ceo", "Play"], "uses": ["baseball", "laptop"], "available": false}');
Now let's make some queries to fetch data
select data->'name' from friends;
select data->'name' as name, data->'work' as work from friends;
You might have noticed that the results comes with inverted comma( " ) and brackets ([ ])
name | work
------------+----------------------------
"Arya" | ["Improvements", "Office"]
"Tim Cook" | ["Cook", "ceo", "Play"]
(2 rows)
Now to retrieve only the values just use ->>
select data->>'name' as name, data->'work'->>0 as work from friends;
select data->>'name' as name, data->'work'->>0 as work from friends where data->>'name'='Arya';
This error happened to me, generally it'll be a problem due to not including the mysql-connector.jar in your eclipse project (or your IDE).
In my case, it was because of a problem on the OS.
I was editing a table in phpmyadmin, and mysql hung, I restarted Ubuntu. I cleaned the project without being successful. This morning, when I've tried the web server, it work perfectly the first time.
At the first reboot, the OS recognized that there was a problem, and after the second one, it was fixed. I hope this will save some time to somebody that "could" have this problem!
You could use OrderedDict (requires Python 2.7) or higher.
Also, note that OrderedDict({'a': 1, 'b':2, 'c':3})
won't work since the dict
you create with {...}
has already forgotten the order of the elements. Instead, you want to use OrderedDict([('a', 1), ('b', 2), ('c', 3)])
.
As mentioned in the documentation, for versions lower than Python 2.7, you can use this recipe.
The solution I found is very simple. Use Window's WMIC & Java's Runtime to locate & kill the process.
Part 1: You need to put some sort of identifier into your app's startup command line. E.g. something like:
String id = "com.domain.app";
Part 2: When you run your app, make sure to include the string. Let's say you start it from within Java, do the following:
Runtime.getRuntime().exec(
"C:\...\javaw.exe -cp ... -Dwhatever=" + id + " com.domain.app.Main"
);
Part 3: To kill the process, use Window's WMIC. Just make sure you app was started containing your id from above:
Runtime.getRuntime().exec(
"wmic process Where \"CommandLine Like '%" + id + "%'\" Call Terminate"
);
You should have 64-bit OS on hardware that supports 64-bit OS, 64-bit Apache version and the same for PHP. But this does not guarantee that functions that are work with PDF can use such big sizes of memory. You'd better not load the whole file into memory, split it into chunks or use file functions to seek on it without loading to RAM.
Overwrite the brand class, either in the bootstrap.css or a new CSS file, as below -
.brand
{
background: url(images/logo.png) no-repeat left center;
height: 20px;
width: 100px;
}
and your html should look like -
<div class="container-fluid">
<a class="brand" href="index.html"></a>
</div>
struct emp {
int id;
char *name;
};
struct emp get() {
char *name = "John";
struct emp e1 = {100, name};
return (e1);
}
int main() {
struct emp e2 = get();
printf("%s\n", e2.name);
}
works fine with newer versions of compilers. Just like id, content of the name gets copied to the assigned structure variable.
There are two ways you can update the record in sequelize.
First, if you have a unique identifier then you can use where clause or else if you want to update multiple records with the same identifier.
You can either create the whole object to update or a specific column
const objectToUpdate = {
title: 'Hello World',
description: 'Hello World'
}
models.Locale.update(objectToUpdate, { where: { id: 2}})
Only Update a specific column
models.Locale.update({ title: 'Hello World'}, { where: { id: 2}})
Second, you can use find a query to find it and use set and save function to update the DB.
const objectToUpdate = {
title: 'Hello World',
description: 'Hello World'
}
models.Locale.findAll({ where: { title: 'Hello World'}}).then((result) => {
if(result){
// Result is array because we have used findAll. We can use findOne as well if you want one row and update that.
result[0].set(objectToUpdate);
result[0].save(); // This is a promise
}
})
Always use transaction while updating or creating a new row. that way it will roll back any updates if there is any error or if you doing any multiple updates:
models.sequelize.transaction((tx) => {
models.Locale.update(objectToUpdate, { transaction: t, where: {id: 2}});
})
Check to see if the FORM has been submitted first, then the field. You should also sanitize the field to prevent hackers.
form name="new user" method="post" action="step2_check.php">
<input type="text" name="mail"/> <br />
<input type="password" name="password"/><br />
<input type="submit" id="SubmitForm" name= "SubmitForm" value="continue"/>
</form>
step2_check:
if (isset($_POST["SubmitForm"]))
{
$Email = sanitize_text_field(stripslashes($_POST["SubmitForm"]));
if(!empty($Email))
echo "Yes, mail is set";
else
echo "N0, mail is not set";
}
}
While respond_to?
will return true only for public methods, checking for "method definition" on a class may also pertain to private methods.
On Ruby v2.0+ checking both public and private sets can be achieved with
Foo.private_instance_methods.include?(:bar) || Foo.instance_methods.include?(:bar)
you can try to replace -->
with a different string say, #END#
and do search and replace with your editor when you wish to return the closing tags.
For what its worth you are also only generating numbers between 0 and 99 (inclusive). If you wanted to generate values between 0 and 100 you would need.
rand() % 101
in addition to calling srand() as mentioned by others.
I had a similar problem when updated my android studio. Somehow it changed my SDK path. I just changed it to my updated SDK path and it worked.
Android Studio -> File -> Settings -> Appearance & Behaviour -> System Settings -> Android SDK
Here you will find Android SDK location just click on edit link in front of that and browse and select the Android SDK from the file browser. Select and click on Apply.
Select AVD manager and start Emulator. This solution worked for me.
Two years later (Found this on Google, so for anyone else)... As has been mentioned above, you don't need to select anything. These three lines:
Workbooks(File).Worksheets(SheetData).Range("A1").Select
Workbooks(File).Worksheets(SheetData).Range(Selection, Selection.End(xlToRight)).Select
Workbooks(File).Worksheets(SheetData).Selection.Copy ActiveWorkbook.Sheets(sheetName).Cells(1, 1)
Can be replaced with
Workbooks(File).Worksheets(SheetData).Range(Workbooks(File).Worksheets(SheetData). _
Range("A1"), Workbooks(File).Worksheets(SheetData).Range("A1").End(xlToRight)).Copy _
Destination:=ActiveWorkbook.Sheets(sheetName).Cells(1, 1)
This should get around the select error.
Well, actually I'll have to say David is right with his solution, but there are some topics disturbing me:
ViewModel
, and include the Model as member in the ViewModel
, then you effectively sent your model to the View => this is BADSo how can you create a better coupling?
I would use a tool like AutoMapper
or ValueInjecter to map between ViewModel
and Model.
AutoMapper
does seem to have the better syntax and feel to it, but the current version lacks a
very severe topic: It is not able to perform the mapping from ViewModel
to Model (under certain circumstances like flattening, etc., but this is off topic)
So at present I prefer to use ValueInjecter
.
So you create a ViewModel
with the fields you need in the view.
You add the SelectList items you need as lookups.
And you add them as SelectLists already. So you can query from a LINQ enabled sourc, select the ID and text field and store it as a selectlist:
You gain that you do not have to create a new type (dictionary) as lookup and you just move the new SelectList
from the view to the controller.
// StaffTypes is an IEnumerable<StaffType> from dbContext
// viewModel is the viewModel initialized to copy content of Model Employee
// viewModel.StaffTypes is of type SelectList
viewModel.StaffTypes =
new SelectList(
StaffTypes.OrderBy( item => item.Name )
"StaffTypeID",
"Type",
viewModel.StaffTypeID
);
In the view you just have to call
@Html.DropDownListFor( model => mode.StaffTypeID, model.StaffTypes )
Back in the post element of your method in the controller you have to take a parameter of the type of your ViewModel
. You then check for validation.
If the validation fails, you have to remember to re-populate the viewModel.StaffTypes
SelectList, because this item will be null on entering the post function.
So I tend to have those population things separated into a function.
You just call back return new View(viewModel)
if anything is wrong.
Validation errors found by MVC3 will automatically be shown in the view.
If you have your own validation code you can add validation errors by specifying which field they belong to. Check documentation on ModelState
to get info on that.
If the viewModel
is valid you have to perform the next step:
If it is a create of a new item, you have to populate a model from the viewModel
(best suited is ValueInjecter
). Then you can add it to the EF collection of that type and commit changes.
If you have an update, you get the current db item first into a model. Then you can copy the values from the viewModel
back to the model (again using ValueInjecter
gets you do that very quick).
After that you can SaveChanges
and are done.
Feel free to ask if anything is unclear.
$("#masterdiv div").text("");
FOR SQL SERVER
EXEC sp_addlinkedserver @server='servername'
No need to specify other parameters. You can go through this article.
Check local_listener definition in your spfile or pfile. In my case, the problem was with pfile, I had moved the pfile from a similar environment and it had LISTENER_sid as LISTENER and not just LISTENER.
You should give the new monkeyrunner a go. Maybe this can solve your problems. You put keycodes in it for testing, maybe touch events are also possible.
Gender :<br>
<input type="radio" name="g" value="male" <?php echo ($g=='Male')?'checked':'' ?>>male <br>
<input type="radio" name="g" value="female"<?php echo ($g=='female')?'checked':'' ?>>female
<?php echo $errors['g'];?>
The Action Bar Style Generator, suggested by Sunny, is very useful, but it generates a lot of files, most of which are irrelevant if you only want to change the background colour.
So, I dug deeper into the zip it generates, and tried to narrow down what are the parts that matter, so I can make the minimum amount of changes to my app. Below is what I found out.
In the style generator, the relevant setting is Popup color, which affects "Overflow menu, submenu and spinner panel background".
Go on and generate the zip, but out of all the files generated, you only really need one image, menu_dropdown_panel_example.9.png
, which looks something like this:
So, add the different resolution versions of it to res/drawable-*
. (And perhaps rename them to menu_dropdown_panel.9.png
.)
Then, as an example, in res/values/themes.xml
you would have the following, with android:popupMenuStyle
and android:popupBackground
being the key settings.
<resources>
<style name="MyAppActionBarTheme" parent="android:Theme.Holo.Light">
<item name="android:popupMenuStyle">@style/MyApp.PopupMenu</item>
<item name="android:actionBarStyle">@style/MyApp.ActionBar</item>
</style>
<!-- The beef: background color for Action Bar overflow menu -->
<style name="MyApp.PopupMenu" parent="android:Widget.Holo.Light.ListPopupWindow">
<item name="android:popupBackground">@drawable/menu_dropdown_panel</item>
</style>
<!-- Bonus: if you want to style whole Action Bar, not just the menu -->
<style name="MyApp.ActionBar" parent="android:Widget.Holo.Light.ActionBar.Solid">
<!-- Blue background color & black bottom border -->
<item name="android:background">@drawable/blue_action_bar_background</item>
</style>
</resources>
And, of course, in AndroidManifest.xml
:
<application
android:theme="@style/MyAppActionBarTheme"
... >
What you get with this setup:
Note that I'm using Theme.Holo.Light
as the base theme. If you use Theme.Holo
(Holo Dark), there's an additional step needed as this answer describes!
Also, if you (like me) wanted to style the whole Action Bar, not just the menu, put something like this in res/drawable/blue_action_bar_background.xml
:
<!-- Bonus: if you want to style whole Action Bar, not just the menu -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle">
<stroke android:width="2dp" android:color="#FF000000" />
<solid android:color="#FF2070B0" />
</shape>
</item>
<item android:bottom="2dp">
<shape android:shape="rectangle">
<stroke android:width="2dp" android:color="#FF2070B0" />
<solid android:color="#00000000" />
<padding android:bottom="2dp" />
</shape>
</item>
</layer-list>
Works great at least on Android 4.0+ (API level 14+).
Add this to the stylesheet:
table {
border-collapse: collapse;
}
The reason why it behaves this way is actually described pretty well in the specification:
There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.
... and later, for collapse
setting:
In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.
Dont have high enough rep to comment on existing answer.
But for https://stackoverflow.com/a/11825864/3920439 answer
This works for integers, but does not work for array of floats (at least in python 3.6)
It will raise TypeError: list indices must be integers or slices, not float
How we get right real dimensions without a blink real image:
(function( $ ){
$.fn.getDimensions=function(){
alert("First example:This works only for HTML code without CSS width/height definition.");
w=$(this, 'img')[0].width;
h=$(this, 'img')[0].height;
alert("This is a width/height on your monitor: " + $(this, 'img')[0].width+"/"+$(this, 'img')[0].height);
//This is bad practice - it shows on your monitor
$(this, 'img')[0].removeAttribute( "width" );
$(this, 'img')[0].removeAttribute( "height" );
alert("This is a bad effect of view after attributes removing, but we get right dimensions: "+ $(this, 'img')[0].width+"/"+$(this, 'img')[0].height);
//I'am going to repare it
$(this, 'img')[0].width=w;
$(this, 'img')[0].height=h;
//This is a good practice - it doesn't show on your monitor
ku=$(this, 'img').clone(); //We will work with a clone
ku.attr( "id","mnbv1lk87jhy0utrd" );//Markup clone for a final removing
ku[0].removeAttribute( "width" );
ku[0].removeAttribute( "height" );
//Now we still get 0
alert("There are still 0 before a clone appending to document: "+ $(ku)[0].width+"/"+$(ku)[0].height);
//Hide a clone
ku.css({"visibility" : "hidden",'position':'absolute','left':'-9999px'});
//A clone appending
$(document.body).append (ku[0]);
alert("We get right dimensions: "+ $(ku)[0].width+"/"+$(ku)[0].height);
//Remove a clone
$("#mnbv1lk87jhy0utrd").remove();
//But a next resolution is the best of all. It works in case of CSS definition of dimensions as well.
alert("But if you want to read real dimensions for image with CSS class definition outside of img element, you can't do it with a clone of image. Clone method is working with CSS dimensions, a clone has dimensions as well as in CSS class. That's why you have to work with a new img element.");
imgcopy=$('<img src="'+ $(this, 'img').attr('src') +'" />');//new object
imgcopy.attr( "id","mnbv1lk87jhy0aaa" );//Markup for a final removing
imgcopy.css({"visibility" : "hidden",'position':'absolute','left':'-9999px'});//hide copy
$(document.body).append (imgcopy);//append to document
alert("We get right dimensions: "+ imgcopy.width()+"/"+imgcopy.height());
$("#mnbv1lk87jhy0aaa").remove();
}
})( jQuery );
$(document).ready(function(){
$("img.toreaddimensions").click(function(){$(this).getDimensions();});
});
It works with <img class="toreaddimensions"...
Try below structure for applying two color border,
<div class="white">
<div class="grey">
</div>
</div>
.white
{
border: 2px solid white;
}
.grey
{
border: 1px solid grey;
}
This is a clever little trick (that I think I've seen on SO before):
var str = "" + 1
var pad = "0000"
var ans = pad.substring(0, pad.length - str.length) + str
JavaScript is more forgiving than some languages if the second argument to substring is negative so it will "overflow correctly" (or incorrectly depending on how it's viewed):
That is, with the above:
Supporting negative numbers is left as an exercise ;-)
Happy coding.
I had it when I did so :
function foo() (...) export default foo
correctly:
export default () =>(...);
or
const foo = ...
export default foo
If you can give up the scales/axis labels, you can rescale the data to (0, 1) interval. This works for example for different 'wiggle' trakcs on chromosomes, when you're generally interested in local correlations between the tracks and they have different scales (coverage in thousands, Fst 0-1).
# rescale numeric vector into (0, 1) interval
# clip everything outside the range
rescale <- function(vec, lims=range(vec), clip=c(0, 1)) {
# find the coeficients of transforming linear equation
# that maps the lims range to (0, 1)
slope <- (1 - 0) / (lims[2] - lims[1])
intercept <- - slope * lims[1]
xformed <- slope * vec + intercept
# do the clipping
xformed[xformed < 0] <- clip[1]
xformed[xformed > 1] <- clip[2]
xformed
}
Then, having a data frame with chrom
, position
, coverage
and fst
columns, you can do something like:
ggplot(d, aes(position)) +
geom_line(aes(y = rescale(fst))) +
geom_line(aes(y = rescale(coverage))) +
facet_wrap(~chrom)
The advantage of this is that you're not limited to two trakcs.
git push origin +7f6d03:master
This will revert your repo to mentioned commit number
The build-in raw_input should help.
for i in range(3):
print ("So much work to do!")
k = raw_input("Press any key to continue...")
print ("Ok, back to work.")
Another tree implementation loosely based off of Bruno's answer:
class Node:
def __init__(self):
self.name: str = ''
self.children: List[Node] = []
self.parent: Node = self
def __getitem__(self, i: int) -> 'Node':
return self.children[i]
def add_child(self):
child = Node()
self.children.append(child)
child.parent = self
return child
def __str__(self) -> str:
def _get_character(x, left, right) -> str:
if x < left:
return '/'
elif x >= right:
return '\\'
else:
return '|'
if len(self.children):
children_lines: Sequence[List[str]] = list(map(lambda child: str(child).split('\n'), self.children))
widths: Sequence[int] = list(map(lambda child_lines: len(child_lines[0]), children_lines))
max_height: int = max(map(len, children_lines))
total_width: int = sum(widths) + len(widths) - 1
left: int = (total_width - len(self.name) + 1) // 2
right: int = left + len(self.name)
return '\n'.join((
self.name.center(total_width),
' '.join(map(lambda width, position: _get_character(position - width // 2, left, right).center(width),
widths, accumulate(widths, add))),
*map(
lambda row: ' '.join(map(
lambda child_lines: child_lines[row] if row < len(child_lines) else ' ' * len(child_lines[0]),
children_lines)),
range(max_height))))
else:
return self.name
And an example of how to use it:
tree = Node()
tree.name = 'Root node'
tree.add_child()
tree[0].name = 'Child node 0'
tree.add_child()
tree[1].name = 'Child node 1'
tree.add_child()
tree[2].name = 'Child node 2'
tree[1].add_child()
tree[1][0].name = 'Grandchild 1.0'
tree[2].add_child()
tree[2][0].name = 'Grandchild 2.0'
tree[2].add_child()
tree[2][1].name = 'Grandchild 2.1'
print(tree)
Which should output:
Root node / / \ Child node 0 Child node 1 Child node 2 | / \ Grandchild 1.0 Grandchild 2.0 Grandchild 2.1
def exit(self):
self.frame.destroy()
exit_btn=Button(self.frame,text='Exit',command=self.exit,activebackground='grey',activeforeground='#AB78F1',bg='#58F0AB',highlightcolor='red',padx='10px',pady='3px')
exit_btn.place(relx=0.45,rely=0.35)
This worked for me to destroy my Tkinter frame on clicking the exit button.
this in your callback function refers to the clicked element.
$(".addressClick").click(function () {
var addressValue = $(this).attr("href");
alert(addressValue );
});
Use this
Sub calc()
Range("C1:C10").FormulaR1C1 = "=(R10C1+R10C2)"
End Sub
Converting to a DATE
or using an open-ended date range in any case will yield the best performance. FYI, convert to date using an index are the best performers. More testing a different techniques in article: What is the most efficient way to trim time from datetime? Posted by Aaron Bertrand
From that article:
DECLARE @dateVar datetime = '19700204';
-- Quickest when there is an index on t.[DateColumn],
-- because CONVERT can still use the index.
SELECT t.[DateColumn]
FROM MyTable t
WHERE = CONVERT(DATE, t.[DateColumn]) = CONVERT(DATE, @dateVar);
-- Quicker when there is no index on t.[DateColumn]
DECLARE @dateEnd datetime = DATEADD(DAY, 1, @dateVar);
SELECT t.[DateColumn]
FROM MyTable t
WHERE t.[DateColumn] >= @dateVar AND
t.[DateColumn] < @dateEnd;
Also from that article: using BETWEEN
, DATEDIFF
or CONVERT(CHAR(8)...
are all slower.
Essentially javascript and C++ work on two different principles. Javascript creates an "associative array" or hash table, which matches a string key, which is the field name, to a value. C++ lays out structures in memory, so the first 4 bytes are an integer, which is an age, then maybe we have a fixed-wth 32 byte string which represents the "profession".
So javascript will handle things like "age" being 18 in one record and "nineteen" in another. C++ can't. (However C++ is much faster).
So if we want to handle JSON in C++, we have to build the associative array from the ground up. Then we have to tag the values with their types. Is it an integer, a real value (probably return as "double"), boolean, a string? It follows that a JSON C++ class is quite a large chunk of code. Effectively what we are doing is implementing a bit of the javascript engine in C++. We then pass our JSON parser the JSON as a string, and it tokenises it, and gives us functions to query the JSON from C++.
I had the same issue and none of the above answers solved the problem, so I tried something very straight-forward: I just putted in my strings.xml
\n\t
The complete String looks like this <string name="premium_features_listing_3">- Automatische Aktualisierung der\n\tDatenbank</string>
Results in:
Automatische Aktualisierung der
Datenbank
(with no extra line in between)
Maybe it will help others. Regards
If you want to follow all the "best practices," there's a few things I'd recommend, some of which are touched on in other answers and comments to this question.
First, while it doesn't have too much of an affect on the specific question you asked, you did mention efficiency, and the best way to handle shared data in your application is to factor it out into a service.
I would personally recommend embracing AngularJS's promise system, which will make your asynchronous services more composable compared to raw callbacks. Luckily, Angular's $http
service already uses them under the hood. Here's a service that will return a promise that resolves to the data from the JSON file; calling the service more than once will not cause a second HTTP request.
app.factory('locations', function($http) {
var promise = null;
return function() {
if (promise) {
// If we've already asked for this data once,
// return the promise that already exists.
return promise;
} else {
promise = $http.get('locations/locations.json');
return promise;
}
};
});
As far as getting the data into your directive, it's important to remember that directives are designed to abstract generic DOM manipulation; you should not inject them with application-specific services. In this case, it would be tempting to simply inject the locations
service into the directive, but this couples the directive to that service.
A brief aside on code modularity: a directive’s functions should almost never be responsible for getting or formatting their own data. There’s nothing to stop you from using the $http service from within a directive, but this is almost always the wrong thing to do. Writing a controller to use $http is the right way to do it. A directive already touches a DOM element, which is a very complex object and is difficult to stub out for testing. Adding network I/O to the mix makes your code that much more difficult to understand and that much more difficult to test. In addition, network I/O locks in the way that your directive will get its data – maybe in some other place you’ll want to have this directive receive data from a socket or take in preloaded data. Your directive should either take data in as an attribute through scope.$eval and/or have a controller to handle acquiring and storing the data.
In this specific case, you should place the appropriate data on your controller's scope and share it with the directive via an attribute.
app.controller('SomeController', function($scope, locations) {
locations().success(function(data) {
$scope.locations = data;
});
});
<ul class="list">
<li ng-repeat="location in locations">
<a href="#">{{location.id}}. {{location.name}}</a>
</li>
</ul>
<map locations='locations'></map>
app.directive('map', function() {
return {
restrict: 'E',
replace: true,
template: '<div></div>',
scope: {
// creates a scope variable in your directive
// called `locations` bound to whatever was passed
// in via the `locations` attribute in the DOM
locations: '=locations'
},
link: function(scope, element, attrs) {
scope.$watch('locations', function(locations) {
angular.forEach(locations, function(location, key) {
// do something
});
});
}
};
});
In this way, the map
directive can be used with any set of location data--the directive is not hard-coded to use a specific set of data, and simply linking the directive by including it in the DOM will not fire off random HTTP requests.
For completing the answers, Spring MVC uses viewResolver(for example, as axtavt metionned, InternalResourceViewResolver) to get the specific view. Therefore the first step is making sure that a viewResolver is configured.
Secondly, you should pay attention to the url of redirection(redirect or forward). A url starting with "/" means that it's a url absolute in the application. As Jigar says,
return "redirect:/index.html";
should work. If your view locates in the root of the application, Spring can find it. If a url without a "/", such as that in your question, it means a url relative. It explains why it worked before and don't work now. If your page calling "redirect" locates in the root by chance, it works. If not, Spring can't find the view and it doesn't work.
Here is the source code of the method of RedirectView of Spring
protected void renderMergedOutputModel(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
throws IOException {
// Prepare target URL.
StringBuilder targetUrl = new StringBuilder();
if (this.contextRelative && getUrl().startsWith("/")) {
// Do not apply context path to relative URLs.
targetUrl.append(request.getContextPath());
}
targetUrl.append(getUrl());
// ...
sendRedirect(request, response, targetUrl.toString(), this.http10Compatible);
}
What if you compile it using another machine? A fresh installed one would be lovely. I hope your machine is not jealous.
Check out this awesome converter. http://labs.rampinteractive.co.uk/android_dp_px_calculator/
To link means not to work properly. Digging into stdio.h of VS2012 and VS2015 the following worked for me. Alas, you have to decide if it should work for one of { stdin, stdout, stderr }, never more than one.
extern "C" FILE* __cdecl __iob_func()
{
struct _iobuf_VS2012 { // ...\Microsoft Visual Studio 11.0\VC\include\stdio.h #56
char *_ptr;
int _cnt;
char *_base;
int _flag;
int _file;
int _charbuf;
int _bufsiz;
char *_tmpfname; };
// VS2015 has only FILE = struct {void*}
int const count = sizeof(_iobuf_VS2012) / sizeof(FILE);
//// stdout
//return (FILE*)(&(__acrt_iob_func(1)->_Placeholder) - count);
// stderr
return (FILE*)(&(__acrt_iob_func(2)->_Placeholder) - 2 * count);
}
according to http://docs.angularjs.org/api/ng.filter:orderBy , orderBy sorts an array. In your case you're passing an object, so You'll have to implement Your own sorting function.
or pass an array -
$scope.testData = {
C: {name:"CData", order: 1},
B: {name:"BData", order: 2},
A: {name:"AData", order: 3},
}
take a look at http://jsfiddle.net/qaK56/
You may also need to enable the World Wide Web Service inbound firewall rule.
On Windows 7: Start -> Control Panel -> Windows Firewall -> Advanced Settings -> Inbound Rules
Find World Wide Web Services (HTTP Traffic-In)
in the list and select to enable the rule. Change is pretty much immediate.
I recently set up a script that does this.
As David Brabant pointed out, you can use the System.Net.WebRequest
class to do an HTTP request.
To check whether it is operational, you should use the following example code:
# First we create the request.
$HTTP_Request = [System.Net.WebRequest]::Create('http://google.com')
# We then get a response from the site.
$HTTP_Response = $HTTP_Request.GetResponse()
# We then get the HTTP code as an integer.
$HTTP_Status = [int]$HTTP_Response.StatusCode
If ($HTTP_Status -eq 200) {
Write-Host "Site is OK!"
}
Else {
Write-Host "The Site may be down, please check!"
}
# Finally, we clean up the http request by closing it.
If ($HTTP_Response -eq $null) { }
Else { $HTTP_Response.Close() }
For your specific example, you don't actually need to nest them. If the expression in the try
block succeeds, the function will return, so any code after the whole try/except block will only be run if the first attempt fails. So you can just do:
def __getattribute__(self, item):
try:
return object.__getattribute__(item)
except AttributeError:
pass
# execution only reaches here when try block raised AttributeError
try:
return self.dict[item]
except KeyError:
print "The object doesn't have such attribute"
Nesting them isn't bad, but I feel like leaving it flat makes the structure more clear: you're sequentially trying a series of things and returning the first one that works.
Incidentally, you might want to think about whether you really want to use __getattribute__
instead of __getattr__
here. Using __getattr__
will simplify things because you'll know that the normal attribute lookup process has already failed.
If you just want to remove "username1" you can use a simple replace.
name.replace("username1,", "")
or you could use split like you mentioned.
var name = "username1, username2 and username3 like this post.".split(",")[1];
$("h1").text(name);
jsfiddle example
Card seems to be "discarded" LOL, I found the "well" not working with bootstrap 4.3.1 and jQuery v3.4.1, just working fine with bootstrap 4.3.1 and jQuery v3.3.1. Hope it helps.
Why not both? Use jQuery for animated effects and CSS as the fallback. This gives you the benefits of jQuery with graceful degradation.
CSS:
a {color: blue;}
a:hover {color: red;}
jQuery (uses jQueryUI to animate color):
$('a').hover(
function() {
$(this)
.css('color','blue')
.animate({'color': 'red'}, 400);
},
function() {
$(this)
.animate({'color': 'blue'}, 400);
}
);
I'm on Mac, in my case I just had to specify the separator with "sep=;\n"
and encode the file in UTF-16LE like this:
$data = "sep=;\n" .mb_convert_encoding($data, 'UTF-16LE', 'UTF-8');