Can you try doing something like (to get the last entry):
linkedHashMap.entrySet().toArray()[linkedHashMap.size() -1];
An Iterator
moves forward only, if it read it once, it's done. Your
m.get(itr2.next());
is reading the next value of itr2.next();
, that is why you are missing a few (actually not a few, every other) keys.
I had similar Issue where we have GenericResponse object containing list of values
ResponseEntity<ResponseDTO> responseEntity = restTemplate.exchange(
redisMatchedDriverUrl,
HttpMethod.POST,
requestEntity,
ResponseDTO.class
);
Usage of objectMapper helped in converting LinkedHashMap into respective DTO objects
ObjectMapper mapper = new ObjectMapper();
List<DriverLocationDTO> driverlocationsList = mapper.convertValue(responseDTO.getData(), new TypeReference<List<DriverLocationDTO>>() { });
// iterate over the map
for(Entry<String, ArrayList<String>> entry : test1.entrySet()){
// iterate over each entry
for(String item : entry.getValue()){
// print the map's key with each value in the ArrayList
System.out.println(entry.getKey() + ": " + item);
}
}
Using anytime package:
library(anytime)
anydate("2009-01")
# [1] "2009-01-01"
This question has been answered, but maybe this might someone else coming here.
I also had an issue where this
is undefined, when I was foolishly trying to destructure the methods of a class when initialising it:
import MyClass from "./myClass"
// 'this' is not defined here:
const { aMethod } = new MyClass()
aMethod() // error: 'this' is not defined
// So instead, init as you would normally:
const myClass = new MyClass()
myClass.aMethod() // OK
Use attributed string:
// Define attributes
let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 18)
let attributes :Dictionary = [NSFontAttributeName : labelFont]
// Create attributed string
var attrString = NSAttributedString(string: "Foo", attributes:attributes)
label.attributedText = attrString
You need to define attributes.
Using attributed string you can mix colors, sizes, fonts etc within one text
In addition to previous answers there is one important for me note:
shelve
is JetBrains products feature (such as WebStorm
, PhpStorm
, PyCharm
, etc.). It puts shelved files into .idea/shelf
directory.
stash
is one of git
options. It puts stashed files under the .git
directory.
EDITED: with the new release of the official Facebook app for Android (July 14 2011) IT WORKS!!!
OLD: The examples above do not work if the user chooses the Facebook app for sharing, but they do work if the user chooses the Seesmic app to post to Facebook. I guess Seesmic have a better implementation of the Facebook API than Facebook!
You simply need to remove v-bind (:) from selected and required attributes. Like this :-
<template>_x000D_
<select class="form-control" v-model="selected" required @change="changeLocation">_x000D_
<option selected>Choose Province</option>_x000D_
<option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>_x000D_
</select>_x000D_
</template>
_x000D_
You are not binding anything to the vue instance through these attributes thats why it is giving error.
I like the fact that after you have just edited the file, all you need to do is type:
. !$
This sources the file you had just edited in history. See What is bang dollar in bash.
Here is a Android variant, but same principle can be used in plain Java too.
private static final String TAG = YourClass.class.getSimpleName();
private static final String TAG = YourClass.class.getName();
Disabled is a Boolean Attribute of the select element as stated by WHATWG, that means the RIGHT WAY TO DISABLE with jQuery would be
jQuery("#selectId").attr('disabled',true);
This would make this HTML
<select id="selectId" name="gender" disabled="disabled">
<option value="-1">--Select a Gender--</option>
<option value="0">Male</option>
<option value="1">Female</option>
</select>
This works for both XHTML and HTML (W3School reference)
Yet it also can be done using it as property
jQuery("#selectId").prop('disabled', 'disabled');
getting
<select id="selectId" name="gender" disabled>
Which only works for HTML and not XTML
NOTE: A disabled element will not be submitted with the form as answered in this question: The disabled form element is not submitted
NOTE2: A disabled element may be greyed out.
NOTE3:
A form control that is disabled must prevent any click events that are queued on the user interaction task source from being dispatched on the element.
<script>
var update_pizza = function () {
if ($("#pizza").is(":checked")) {
$('#pizza_kind').attr('disabled', false);
} else {
$('#pizza_kind').attr('disabled', true);
}
};
$(update_pizza);
$("#pizza").change(update_pizza);
</script>
You might also find this useful (non-Windows only):
mysql> pager less -SFX
mysql> SELECT * FROM sometable;
This will pipe the outut through the less
command line tool which - with these parameters - will give you a tabular output that can be scrolled horizontally and vertically with the cursor keys.
Leave this view by hitting the q
key, which will quit the less
tool.
You can also use the ternary conditional-operator:
var a = "hallo world";_x000D_
var a = !a ? document.write("i dont know 'a'") : document.write("a = " + a);
_x000D_
//var a = "hallo world";_x000D_
var a = !a ? document.write("i dont know 'a'") : document.write("a = " + a);
_x000D_
We can use replace
to change the values in 'mpg' to NA
that corresponds to cyl==4
.
mtcars %>%
mutate(mpg=replace(mpg, cyl==4, NA)) %>%
as.data.frame()
You can combine both these actions and do Esc:wqEnter to save the commit and quit vim.
As an alternate to the above, you can also press ZZ while in the normal mode, which will save the file and exit vim. This is also easier for some people as it's the same key pressed twice.
I have this code snippet run from the ENTRYPOINT
in my docker file:
while true
do
echo "Press [CTRL+C] to stop.."
sleep 1
done
Run the built docker image as:
docker run -td <image name>
Log in to the container shell:
docker exec -it <container id> /bin/bash
You can use myDict.has_key(keyname)
as well to validate if the key exists.
This would work only on versions lower than 3.1. has_key
has been removed from Python 3.1. You should use the in
operator if you are using Python 3.1
What is gone is gone. The only protection I know of is regular backup.
The show()
method only affects the display
CSS setting. If you want to set the visibility you need to do it directly. Also, the .load_button
element is a button and does not raise a submit
event. You would need to change your selector to the form
for that to work:
$('#login_form').submit(function() {
$('#gif').css('visibility', 'visible');
});
Also note that return true;
is redundant in your logic, so it can be removed.
I usually put these lines at the beginning of my stored procedure, and then at the end.
It is an "exists" check for #temp tables.
IF OBJECT_ID('tempdb..#MyCoolTempTable') IS NOT NULL
begin
drop table #MyCoolTempTable
end
Full Example:
CREATE PROCEDURE [dbo].[uspTempTableSuperSafeExample]
AS
BEGIN
SET NOCOUNT ON;
IF OBJECT_ID('tempdb..#MyCoolTempTable') IS NOT NULL
BEGIN
DROP TABLE #MyCoolTempTable
END
CREATE TABLE #MyCoolTempTable (
MyCoolTempTableKey INT IDENTITY(1,1),
MyValue VARCHAR(128)
)
INSERT INTO #MyCoolTempTable (MyValue)
SELECT LEFT(@@VERSION, 128)
UNION ALL SELECT TOP 10 LEFT(name, 128) from sysobjects
SELECT MyCoolTempTableKey, MyValue FROM #MyCoolTempTable
IF OBJECT_ID('tempdb..#MyCoolTempTable') IS NOT NULL
BEGIN
DROP TABLE #MyCoolTempTable
END
SET NOCOUNT OFF;
END
GO
Files.exists()
Files.createDirectory()
Files.copy()
Overwriting Existing Files: Files.move()
Files.delete()
Files.walkFileTree() enter link description here
More concise than others:
def parseString(string):
try:
return int(string)
except ValueError:
return string
b = [[parseString(s) for s in clause.split(', ')] for clause in a]
Alternatively if your format is fixed as <string>, <int>, <int>
, you can be even more concise:
def parseClause(a,b,c):
return [a, int(b), int(c)]
b = [parseClause(*clause) for clause in a]
Why don't you just save/serve the CSS file as UTF-8?
nav a:hover:after {
content: "?";
}
If that's not good enough, and you want to keep it all-ASCII:
nav a:hover:after {
content: "\2193";
}
The general format for a Unicode character inside a string is \000000
to \FFFFFF
– a backslash followed by six hexadecimal digits. You can leave out leading 0
digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.
Relevant part of the CSS2 spec:
Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:
- with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
- by providing exactly 6 hexadecimal digits: "\000026B" ("&B")
In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.
If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).
- Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
The identifier "te\st" is exactly the same identifier as "test".
Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).
For python version >= 3.6 (see PEP 498)
s1='albha'
s2='beta'
f'{s1}{s2:>10}'
#output
'albha beta'
I'm using Ember.js which generates a file named .eslintrc.js
. Adding "no-console": 0
to the rules object did the job for me. The updated file looks like this:
module.exports = {
root: true,
parserOptions: {
ecmaVersion: 6,
sourceType: 'module'
},
extends: 'eslint:recommended',
env: {
browser: true
},
rules: {
"no-console": 0
}
};
You can create a RegExp
object to make it a bit more readable
str.replace(new RegExp('/'), 'foobar');
If you want to replace all of them add the "g"
flag
str.replace(new RegExp('/', 'g'), 'foobar');
This statement works for me
ALTER TABLE table_name DROP UNIQUE (column_name);
Use the after
method on the Tk
object:
from tkinter import *
root = Tk()
def task():
print("hello")
root.after(2000, task) # reschedule event in 2 seconds
root.after(2000, task)
root.mainloop()
Here's the declaration and documentation for the after
method:
def after(self, ms, func=None, *args):
"""Call function once after given time.
MS specifies the time in milliseconds. FUNC gives the
function which shall be called. Additional parameters
are given as parameters to the function call. Return
identifier to cancel scheduling with after_cancel."""
Filestash is the perfect tool for that:
Also Filestash is open source. (Disclaimer: I am the author)
you may also want to remove the 0 at the beginning of the input... I simply add an if block to Mordred answer above because I cannot make a comment yet...
app.directive('numericOnly', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
var transformedInput = inputValue ? inputValue.replace(/[^\d.-]/g,'') : null;
if (transformedInput!=inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
//clear beginning 0
if(transformedInput == 0){
modelCtrl.$setViewValue(null);
modelCtrl.$render();
}
return transformedInput;
});
}
};
})
You can do this way:
scp hostname@serverNameOrServerIp:/path/to/files/\\{file1,file2,file3\\}.fileExtension ./
This will download all the listed filenames to whatever local directory you're on.
Make sure not to put spaces between each filename only use a comma ,
.
foreach($test_package_data as $key=>$data ) {
$category_detail_arr = $test_package_data[$key]['category_detail'];
foreach( $category_detail_arr as $i=>$value ) {
$test_package_data[$key]['category_detail'][$i]['count'] = $some_value;////<----Here
}
}
If you are using Spring Security, you can do the following to ensure that CORS requests are handled first:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// by default uses a Bean by the name of corsConfigurationSource
.cors().and()
...
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
configuration.setAllowedMethods(Arrays.asList("GET","POST"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
See Spring 4.2.x CORS for more information.
Without Spring Security this will work:
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "PUT", "POST", "PATCH", "DELETE", "OPTIONS");
}
};
}
Use the throw statement.
JavaScript doesn't care what the exception type is (as Java does). JavaScript just notices, there's an exception and when you catch it, you can "look" what the exception "says".
If you have different exception types you have to throw, I'd suggest to use variables which contain the string/object of the exception i.e. message. Where you need it use "throw myException" and in the catch, compare the caught exception to myException.
What about this:
out_string = filter(lambda c: not c.isdigit(), in_string)
This is what I do for those situations:
I don't start the html element with class 'hide', but I put style="display: none".
This is because bootstrap jquery modifies the style attribute and not the classes to hide/unhide.
Example:
<button type="button" id="btn_cancel" class="btn default" style="display: none">Cancel</button>
or
<button type="button" id="btn_cancel" class="btn default display-hide">Cancel</button>
Later on, you can run all the following that will work:
$('#btn_cancel').toggle() // toggle between hide/unhide
$('#btn_cancel').hide()
$('#btn_cancel').show()
You can also uso the class of Twitter Bootstrap 'display-hide', which also works with the jQuery IU .toggle() method.
I was having the exact same problem in Windows.
I noticed that in OP's gist, he uses string("open ")
in line 21, however, by using it one comes across this error:
'open' is not recognized as an internal or external command
After researching, I have found that open
is MacOS the default command to open things. It is different on Windows or Linux.
Linux: xdg-open <URL>
Windows: start <URL>
For those of you that are using Windows, as I am, you can use the following:
std::string op = std::string("start ").append(url);
system(op.c_str());
If you "want to return a fixed value when the input parameter has a particular value", maybe you don't even need a mock and could use a dict
along with its get
method:
foo = {'input1': 'value1', 'input2': 'value2'}.get
foo('input1') # value1
foo('input2') # value2
This works well when your fake's output is a mapping of input. When it's a function of input I'd suggest using side_effect
as per Amber's answer.
You can also use a combination of both if you want to preserve Mock
's capabilities (assert_called_once
, call_count
etc):
self.mock.side_effect = {'input1': 'value1', 'input2': 'value2'}.get
Here is my simple and working function to generate a Bitmap! I Use ZXing1.3.jar only! I've also set Correction Level to High!
PS: x and y are reversed, it's normal, because bitMatrix reverse x and y. This code works perfectly with a square image.
public static Bitmap generateQrCode(String myCodeText) throws WriterException {
Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // H = 30% damage
QRCodeWriter qrCodeWriter = new QRCodeWriter();
int size = 256;
ByteMatrix bitMatrix = qrCodeWriter.encode(myCodeText,BarcodeFormat.QR_CODE, size, size, hintMap);
int width = bitMatrix.width();
Bitmap bmp = Bitmap.createBitmap(width, width, Bitmap.Config.RGB_565);
for (int x = 0; x < width; x++) {
for (int y = 0; y < width; y++) {
bmp.setPixel(y, x, bitMatrix.get(x, y)==0 ? Color.BLACK : Color.WHITE);
}
}
return bmp;
}
EDIT
It's faster to use bitmap.setPixels(...) with a pixel int array instead of bitmap.setPixel one by one:
BitMatrix bitMatrix = writer.encode(inputValue, BarcodeFormat.QR_CODE, size, size);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = bitMatrix.get(x, y) ? BLACK : WHITE;
}
}
bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
For my scenario, I had to import both [CommonModule] and [FormsModule] to my module
import { NgModule } from '@angular/core'
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { MyComponent } from './mycomponent'
@NgModule({
imports: [
CommonModule,
FormsModule
],
declarations: [
MyComponent
]
})
export class MyModule { }
Like that:
$ command >>output 2>>error
I found a solution that doesn't need to access directly the pixel data and loop through it to perform the downsampling. Depending on the size of the image this can be very resource intensive, and it would be better to use the browser's internal algorithms.
The drawImage() function is using a linear-interpolation, nearest-neighbor resampling method. That works well when you are not resizing down more than half the original size.
If you loop to only resize max one half at a time, the results would be quite good, and much faster than accessing pixel data.
This function downsample to half at a time until reaching the desired size:
function resize_image( src, dst, type, quality ) {
var tmp = new Image(),
canvas, context, cW, cH;
type = type || 'image/jpeg';
quality = quality || 0.92;
cW = src.naturalWidth;
cH = src.naturalHeight;
tmp.src = src.src;
tmp.onload = function() {
canvas = document.createElement( 'canvas' );
cW /= 2;
cH /= 2;
if ( cW < src.width ) cW = src.width;
if ( cH < src.height ) cH = src.height;
canvas.width = cW;
canvas.height = cH;
context = canvas.getContext( '2d' );
context.drawImage( tmp, 0, 0, cW, cH );
dst.src = canvas.toDataURL( type, quality );
if ( cW <= src.width || cH <= src.height )
return;
tmp.src = dst.src;
}
}
// The images sent as parameters can be in the DOM or be image objects
resize_image( $( '#original' )[0], $( '#smaller' )[0] );
to get the smart break (break-word) work well on different browsers, what worked for me was the following set of rules:
#elm {
word-break:break-word; /* webkit/blink browsers */
word-wrap:break-word; /* ie */
}
-moz-document url-prefix() {/* catch ff */
#elm {
word-break: break-all; /* in ff- with no break-word we'll settle for break-all */
}
}
C:\>FORFILES /C "cmd /c echo @fname @fsize"
C:\>FORFILES /?
FORFILES [/P pathname] [/M searchmask] [/S]
[/C command] [/D [+ | -] {MM/dd/yyyy | dd}]
Description:
Selects a file (or set of files) and executes a
command on that file. This is helpful for batch jobs.
Parameter List:
/P pathname Indicates the path to start searching.
The default folder is the current working
directory (.).
My guess is that you are trying to replace a standard class which ships with Java 5 with one in a library you have.
This is not allowed under the terms of the license agreement, however AFAIK it wasn't enforced until Java 5.
I have seen this with QName before and I "fixed" it by removing the class from the jar I had.
EDIT http://www.manpagez.com/man/1/java/ notes for the option "-Xbootclasspath:"
"Applications that use this option for the purpose of overriding a class in rt.jar should not be deployed as doing so would contravene the Java 2 Runtime Environment binary code license."
The http://www.idt.mdh.se/rc/sumo/aJile/Uppackat/jre/LICENSE
"Java Technology Restrictions. You may not modify the Java Platform Interface ("JPI", identified as classes contained within the "java" package or any subpackages of the "java" package), by creating additional classes within the JPI or otherwise causing the addition to or modification of the classes in the JPI. In the event that you create an additional class and associated API(s) which (i) extends the functionality of the Java platform, and (ii) is exposed to third party software developers for the purpose of developing additional software which invokes such additional API, you must promptly publish broadly an accurate specification for such API for free use by all developers. You may not create, or authorize your licensees to create, additional classes, interfaces, or subpackages that are in any way identified as "java", "javax", "sun" or similar convention as specified by Sun in any naming convention designation."
Foreign key means a non prime attribute of a table referes the prime attribute of another *in phpMyAdmin* first set the column you want to set foreign key as an index
then click on RELATION VIEW
there u can find the options to set foreign key
In general, if you don't know how something works, look for an example which you can learn from.
For this problem, consider this DEMO
You can see loading content with AJAX is very easily accomplished with jQuery:
$(function(){
// don't cache ajax or content won't be fresh
$.ajaxSetup ({
cache: false
});
var ajax_load = "<img src='http://automobiles.honda.com/images/current-offers/small-loading.gif' alt='loading...' />";
// load() functions
var loadUrl = "http://fiddle.jshell.net/deborah/pkmvD/show/";
$("#loadbasic").click(function(){
$("#result").html(ajax_load).load(loadUrl);
});
// end
});
Try to understand how this works and then try replicating it. Good luck.
You can find the corresponding tutorial HERE
Right now the following event starts the ajax load
function:
$("#loadbasic").click(function(){
$("#result").html(ajax_load).load(loadUrl);
});
You can also do this periodically: How to fire AJAX request Periodically?
(function worker() {
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 5000);
}
});
})();
I made a demo of this implementation for you HERE. In this demo, every 2 seconds (setTimeout(worker, 2000);
) the content is updated.
You can also just load the data immediately:
$("#result").html(ajax_load).load(loadUrl);
Which has THIS corresponding demo.
Please note on iPad Safari, NoviceCoding's solution won't work if you have -webkit-overflow-scrolling: touch;
somewhere in your CSS.
The solution is either removing all the occurrences of -webkit-overflow-scrolling: touch;
or putting -webkit-overflow-scrolling: auto;
with
NoviceCoding's solution.
Another variation: Define two functions in the trait, a protected one that performs the actual task, and a public one which in turn calls the protected one.
This just saves classes from having to mess with the 'use' statement if they want to override the function, since they can still call the protected function internally.
trait A {
protected function traitcalc($v) {
return $v+1;
}
function calc($v) {
return $this->traitcalc($v);
}
}
class MyClass {
use A;
function calc($v) {
$v++;
return $this->traitcalc($v);
}
}
class MyOtherClass {
use A;
}
print (new MyClass())->calc(2); // will print 4
print (new MyOtherClass())->calc(2); // will print 3
I've found that whenever I need to check if a value exists in an enum, I don't really need an enum and that a type is a better solution. So my enum in my original answer becomes:
export type ValidColors =
| "red"
| "orange"
| "yellow"
| "green"
| "blue"
| "purple";
For clarity, I like to break the values
and includes
calls onto separate lines. Here's an example:
export enum ValidColors {
Red = "red",
Orange = "orange",
Yellow = "yellow",
Green = "green",
Blue = "blue",
Purple = "purple",
}
function isValidColor(color: string): boolean {
const options: string[] = Object.values(ButtonColors);
return options.includes(color);
}
document.getElementById('mybox').style.display = "block";
you can always create new admin template , and do what you need in your admin_view (override the admin add url to your admin_view):
url(r'^admin/mymodel/mymodel/add/$' , 'admin_views.add_my_special_model')
var lst = new List<int>() { 1, 2, 3 };
var ans = lst.Where( i => i > 3 );
(ans == null).Dump(); // False
(ans.Count() == 0 ).Dump(); // True
(Dump is from LinqPad)
I would definitely use html markers to achieve this. Just surround your text with <p></p>
or <font></font>
and add the desired attributes. See the following example:
<p style="font-family: times, serif; font-size:11pt; font-style:italic">
Why did we use these specific parameters during the calculation of the fingerprints?
</p>
This will produce the following output
compared to
This would work with Jupyter Notebook as well as Typora, but I'm not sure if it is universal.
Lastly, be aware that the html marker overrides the font styling used by Markdown.
I see this has been answered; however, I feel this link provides appropriate information for what formatting is supported in various email clients.
http://www.campaignmonitor.com/css/
It's worth noting that GMail and Outlook are two of the pickiest to format HTML email for.
Using eq()
you can target the third cell in the table:
$('#table_header td').eq(2).html('new content');
If you wanted to target every third cell in each row, use the nth-child-selector
:
$('#table_header td:nth-child(3)').html('new content');
Linux supports capabilities to support more fine-grained permissions than just "this application is run as root". One of those capabilities is CAP_NET_BIND_SERVICE
which is about binding to a privileged port (<1024).
Unfortunately I don't know how to exploit that to run an application as non-root while still giving it CAP_NET_BIND_SERVICE
(probably using setcap
, but there's bound to be an existing solution for this).
Number(new Date(2010, 6, 26))
Works the same way as things above. If you need seconds don't forget to / 1000
I am not getting your question properly but as per your heading, you can convert any type of object to string by using toString()
function on a String
Object.
- What is the difference between connection and read timeout for sockets?
The connection timeout is the timeout in making the initial connection; i.e. completing the TCP connection handshake. The read timeout is the timeout on waiting to read data1. If the server (or network) fails to deliver any data <timeout> seconds after the client makes a socket read
call, a read timeout error will be raised.
- What does connection timeout set to "infinity" mean? In what situation can it remain in an infinitive loop? and what can trigger that the infinity-loop dies?
It means that the connection attempt can potentially block for ever. There is no infinite loop, but the attempt to connect can be unblocked by another thread closing the socket. (A Thread.interrupt()
call may also do the trick ... not sure.)
- What does read timeout set to "infinity" mean? In what situation can it remain in an infinite loop? What can trigger that the infinite loop to end?
It means that a call to read
on the socket stream may block for ever. Once again there is no infinite loop, but the read
can be unblocked by a Thread.interrupt()
call, closing the socket, and (of course) the other end sending data or closing the connection.
1 - It is not ... as one commenter thought ... the timeout on how long a socket can be open, or idle.
Edit: Coming back to this answer after a year of security research, I realize it makes the rather unfortunate implication that you would ever actually compare plaintext passwords. Please don't. Use a secure one-way hash with a salt and a reasonable number of iterations. Consider using a library: this stuff is hard to get right!
Original answer: What about the fact that String.equals() uses short-circuit evaluation, and is therefore vulnerable to a timing attack? It may be unlikely, but you could theoretically time the password comparison in order to determine the correct sequence of characters.
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
// Quits here if Strings are different lengths.
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
// Quits here at first different character.
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
Some more resources on timing attacks:
using System.Reflection;
using System.Collections.Generic;
//...
static List<string> GetClasses(string nameSpace)
{
Assembly asm = Assembly.GetExecutingAssembly();
List<string> namespacelist = new List<string>();
List<string> classlist = new List<string>();
foreach (Type type in asm.GetTypes())
{
if (type.Namespace == nameSpace)
namespacelist.Add(type.Name);
}
foreach (string classname in namespacelist)
classlist.Add(classname);
return classlist;
}
NB: The above code illustrates what's going on. Were you to implement it, a simplified version can be used:
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
//...
static IEnumerable<string> GetClasses(string nameSpace)
{
Assembly asm = Assembly.GetExecutingAssembly();
return asm.GetTypes()
.Where(type => type.Namespace == nameSpace)
.Select(type => type.Name);
}
There are a couple of other applications that i've seen recommended, you'll find them here:
function isObject(o) {
return null != o &&
typeof o === 'object' &&
Object.prototype.toString.call(o) === '[object Object]';
}
function isDerivedObject(o) {
return !isObject(o) &&
null != o &&
(typeof o === 'object' || typeof o === 'function') &&
/^\[object /.test(Object.prototype.toString.call(o));
}
// Loose equality operator (==) is intentionally used to check
// for undefined too
// Also note that, even null is an object, within isDerivedObject
// function we skip that and always return false for null
In Javascript, null
, Object
, Array
, Date
and function
s are all objects. Although, null
is bit contrived. So, it's better to check for the null
first, to detect it's not null.
Checking for typeof o === 'object'
guarantees that o
is an object. Without this check, Object.prototype.toString
would be meaningless, since it would return object for everthing, even for undefined
and null
! For example: toString(undefined)
returns [object Undefined]
!
After typeof o === 'object'
check, toString.call(o) is a great method to check whether o
is an object, a derived object like Array
, Date
or a function
.
In isDerivedObject
function, it checks for the o
is a function. Because, function also an object, that's why it's there. If it didn't do that, function will return as false. Example: isDerivedObject(function() {})
would return false
, however now it returns true
.
One can always change the definition of what is an object. So, one can change these functions accordingly.
function isObject(o) {_x000D_
return null != o && _x000D_
typeof o === 'object' && _x000D_
Object.prototype.toString.call(o) === '[object Object]';_x000D_
}_x000D_
_x000D_
function isDerivedObject(o) {_x000D_
return !isObject(o) && _x000D_
null != o && _x000D_
(typeof o === 'object' || typeof o === 'function') &&_x000D_
/^\[object /.test(Object.prototype.toString.call(o));_x000D_
}_x000D_
_x000D_
// TESTS_x000D_
_x000D_
// is null an object?_x000D_
_x000D_
console.log(_x000D_
'is null an object?', isObject(null)_x000D_
);_x000D_
_x000D_
console.log(_x000D_
'is null a derived object?', isDerivedObject(null)_x000D_
);_x000D_
_x000D_
// is 1234 an object?_x000D_
_x000D_
console.log(_x000D_
'is 1234 an object?', isObject(1234)_x000D_
);_x000D_
_x000D_
console.log(_x000D_
'is 1234 a derived object?', isDerivedObject(1234)_x000D_
);_x000D_
_x000D_
// is new Number(1234) an object?_x000D_
_x000D_
console.log(_x000D_
'is new Number(1234) an object?', isObject(new Number(1234))_x000D_
);_x000D_
_x000D_
console.log(_x000D_
'is new Number(1234) a derived object?', isDerivedObject(1234)_x000D_
);_x000D_
_x000D_
// is function object an object?_x000D_
_x000D_
console.log(_x000D_
'is (new (function (){})) an object?', _x000D_
isObject((new (function (){})))_x000D_
);_x000D_
_x000D_
console.log(_x000D_
'is (new (function (){})) a derived object?', _x000D_
isObject((new (function (){})))_x000D_
);_x000D_
_x000D_
// is {} an object?_x000D_
_x000D_
console.log(_x000D_
'is {} an object?', isObject({})_x000D_
);_x000D_
_x000D_
console.log(_x000D_
'is {} a derived object?', isDerivedObject({})_x000D_
);_x000D_
_x000D_
// is Array an object?_x000D_
_x000D_
console.log(_x000D_
'is Array an object?',_x000D_
isObject([])_x000D_
)_x000D_
_x000D_
console.log(_x000D_
'is Array a derived object?',_x000D_
isDerivedObject([])_x000D_
)_x000D_
_x000D_
// is Date an object?_x000D_
_x000D_
console.log(_x000D_
'is Date an object?', isObject(new Date())_x000D_
);_x000D_
_x000D_
console.log(_x000D_
'is Date a derived object?', isDerivedObject(new Date())_x000D_
);_x000D_
_x000D_
// is function an object?_x000D_
_x000D_
console.log(_x000D_
'is function an object?', isObject(function(){})_x000D_
);_x000D_
_x000D_
console.log(_x000D_
'is function a derived object?', isDerivedObject(function(){})_x000D_
);
_x000D_
My solution was not to rely on the class name. object.constructor.name works in theory. But if you're using TypeScript in something like Ionic, as soon as you go to production it's going to go up in flames because Ionic's production mode minifies the Javascript code. So the classes get named things like "a" and "e."
What I ended up doing was having a typeName class in all my objects that the constructor assigns the class name to. So:
export class Person {
id: number;
name: string;
typeName: string;
constructor() {
typeName = "Person";
}
Yes that wasn't what was asked, really. But using the constructor.name on something that might potentially get minified down the road is just begging for a headache.
Your syntax isn't quite right: you need to list the fields in order before the INTO, and the corresponding target variables after:
SELECT Id, dateCreated
INTO iId, dCreate
FROM products
WHERE pName = iName
You don't need the count, just whether or not the item was seen before. Adapted that answer to this problem:
def list_duplicates(seq):
seen = set()
seen_add = seen.add
# adds all elements it doesn't know yet to seen and all other to seen_twice
seen_twice = set( x for x in seq if x in seen or seen_add(x) )
# turn the set into a list (as requested)
return list( seen_twice )
a = [1,2,3,2,1,5,6,5,5,5]
list_duplicates(a) # yields [1, 2, 5]
Just in case speed matters, here are some timings:
# file: test.py
import collections
def thg435(l):
return [x for x, y in collections.Counter(l).items() if y > 1]
def moooeeeep(l):
seen = set()
seen_add = seen.add
# adds all elements it doesn't know yet to seen and all other to seen_twice
seen_twice = set( x for x in l if x in seen or seen_add(x) )
# turn the set into a list (as requested)
return list( seen_twice )
def RiteshKumar(l):
return list(set([x for x in l if l.count(x) > 1]))
def JohnLaRooy(L):
seen = set()
seen2 = set()
seen_add = seen.add
seen2_add = seen2.add
for item in L:
if item in seen:
seen2_add(item)
else:
seen_add(item)
return list(seen2)
l = [1,2,3,2,1,5,6,5,5,5]*100
Here are the results: (well done @JohnLaRooy!)
$ python -mtimeit -s 'import test' 'test.JohnLaRooy(test.l)'
10000 loops, best of 3: 74.6 usec per loop
$ python -mtimeit -s 'import test' 'test.moooeeeep(test.l)'
10000 loops, best of 3: 91.3 usec per loop
$ python -mtimeit -s 'import test' 'test.thg435(test.l)'
1000 loops, best of 3: 266 usec per loop
$ python -mtimeit -s 'import test' 'test.RiteshKumar(test.l)'
100 loops, best of 3: 8.35 msec per loop
Interestingly, besides the timings itself, also the ranking slightly changes when pypy is used. Most interestingly, the Counter-based approach benefits hugely from pypy's optimizations, whereas the method caching approach I have suggested seems to have almost no effect.
$ pypy -mtimeit -s 'import test' 'test.JohnLaRooy(test.l)'
100000 loops, best of 3: 17.8 usec per loop
$ pypy -mtimeit -s 'import test' 'test.thg435(test.l)'
10000 loops, best of 3: 23 usec per loop
$ pypy -mtimeit -s 'import test' 'test.moooeeeep(test.l)'
10000 loops, best of 3: 39.3 usec per loop
Apparantly this effect is related to the "duplicatedness" of the input data. I have set l = [random.randrange(1000000) for i in xrange(10000)]
and got these results:
$ pypy -mtimeit -s 'import test' 'test.moooeeeep(test.l)'
1000 loops, best of 3: 495 usec per loop
$ pypy -mtimeit -s 'import test' 'test.JohnLaRooy(test.l)'
1000 loops, best of 3: 499 usec per loop
$ pypy -mtimeit -s 'import test' 'test.thg435(test.l)'
1000 loops, best of 3: 1.68 msec per loop
Considering user also want to edit their previous input,
<select name="title">
@foreach ($titles as $key => $value)
<option value="{{$value->id}}" {{(old('title', $user->title_id) == $value->id ? 'selected' : '')}} > {{$value->name}} </option>
@endforeach
</select>
old('title', $user->title_id) returns user saved title_id first time, if validation fails it returns user-selected title_id. Then if it is match with current option id, it is being selected.
Unfortunately:
It seems you can not reference a single item from an array in values/arrays.xml with XML. Of course you can in Java, but not XML. There's no information on doing so in the Android developer reference, and I could not find any anywhere else.
It seems you can't use an array as a key in the preferences layout. Each key has to be a single value with it's own key name.
What I want to accomplish: I want to be able to loop through the 17 preferences, check if the item is checked, and if it is, load the string from the string array for that preference name.
Here's the code I was hoping would complete this task:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
ArrayAdapter<String> itemsArrayList = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1);
String[] itemNames = getResources().getStringArray(R.array.itemNames_array);
for (int i = 0; i < 16; i++) {
if (prefs.getBoolean("itemKey[i]", true)) {
itemsArrayList.add(itemNames[i]);
}
}
What I did:
I set a single string for each of the items, and referenced the single strings in the . I use the single string reference for the preferences layout checkbox titles, and the array for my loop.
To loop through the preferences, I just named the keys like key1, key2, key3, etc. Since you reference a key with a string, you have the option to "build" the key name at runtime.
Here's the new code:
for (int i = 0; i < 16; i++) {
if (prefs.getBoolean("itemKey" + String.valueOf(i), true)) {
itemsArrayList.add(itemNames[i]);
}
}
You need access to the object.... you can't simply ask the form class....
eg...
you would of done some thing like
Form1.txtLog.Text = "blah"
instead of
Form1 blah = new Form1();
blah.txtLog.Text = "hello"
in gradle.properties, you can even delete
org.gradle.jvmargs=-Xmx1536m
such lines or comment them out. Let android studio decide for it. When I ran into this same problem, none of above solutions worked for me. Commenting out this line in gradle.properties helped in solving that error.
This exact question is answered on mySql workbench-faq:
Hover over an acronym to view a description, and see the Section 8.1.11.2, “The Columns Tab” and MySQL CREATE TABLE documentation for additional details.
That means hover over an acronym in the mySql Workbench table editor.
select cast(your_float_column as decimal(10,2))
from your_table
decimal(10,2)
means you can have a decimal number with a maximal total precision of 10 digits. 2 of them after the decimal point and 8 before.
The biggest possible number would be 99999999.99
Code below does not print boolean, but allows for dataframe subsetting by index... I understand this is likely not the most efficient way to solve the problem, but I (1) like the way this reads and (2) you can easily subset where df1 index exists in df2:
df3 = df1[df1.index.isin(df2.index)]
or where df1 index does not exist in df2...
df3 = df1[~df1.index.isin(df2.index)]
Try the following code:
public static byte[] decode(String hex){
String[] list=hex.split("(?<=\\G.{2})");
ByteBuffer buffer= ByteBuffer.allocate(list.length);
System.out.println(list.length);
for(String str: list)
buffer.put(Byte.parseByte(str,16));
return buffer.array();
}
To convert to String just create a new String with the byte[] returned by the decode method.
I used the code from the most upvoted answer:
startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
It opens the device settings in the same window, thus got the users of my android application (finnmglas/Launcher) for android stuck in there.
The answer for 2020 and beyond (in Kotlin):
startActivity(Intent(Settings.ACTION_SETTINGS))
It works in my app, should also be working in yours without any unwanted consequences.
CURL request by default is GET, you don't have to set any options to make a GET CURL request.
I don't think the accepted solution handles the case where the error text is reported on stderr. From my testing the exception's output attribute did not contain the results from stderr and the docs warn against using stderr=PIPE in check_output(). Instead, I would suggest one small improvement to J.F Sebastian's solution by adding stderr support. We are, after all, trying to handle errors and stderr is where they are often reported.
from subprocess import Popen, PIPE
p = Popen(['bitcoin', 'sendtoaddress', ..], stdout=PIPE, stderr=PIPE)
output, error = p.communicate()
if p.returncode != 0:
print("bitcoin failed %d %s %s" % (p.returncode, output, error))
I will add that if your need is just to override a property used by your bean, the id approach works too like skaffman explained :
In your first called XML configuration file :
<bean id="myBeanId" class="com.blabla">
<property name="myList" ref="myList"/>
</bean>
<util:list id="myList">
<value>3</value>
<value>4</value>
</util:list>
In your second called XML configuration file :
<util:list id="myList">
<value>6</value>
</util:list>
Then your bean "myBeanId" will be instantiated with a "myList" property of one element which is 6.
If start
can't find what it's looking for, it does what you describe.
Since what you're doing should work, it's very likely you're leaving out some quotes (or putting extras in).
It is interesting to note that the map with default 0 value, intentionally designed for this case demonstrates the worst performance (and not as concise as groupBy
)
type Word = String
type Sentence = Seq[Word]
type Occurrences = scala.collection.Map[Char, Int]
def woGrouped(w: Word): Occurrences = {
w.groupBy(c => c).map({case (c, list) => (c -> list.length)})
} //> woGrouped: (w: forcomp.threadBug.Word)forcomp.threadBug.Occurrences
def woGetElse0Map(w: Word): Occurrences = {
val map = Map[Char, Int]()
w.foldLeft(map)((m, c) => m + (c -> (m.getOrElse(c, 0) + 1)) )
} //> woGetElse0Map: (w: forcomp.threadBug.Word)forcomp.threadBug.Occurrences
def woDeflt0Map(w: Word): Occurrences = {
val map = Map[Char, Int]().withDefaultValue(0)
w.foldLeft(map)((m, c) => m + (c -> (m(c) + 1)) )
} //> woDeflt0Map: (w: forcomp.threadBug.Word)forcomp.threadBug.Occurrences
def dfltHashMap(w: Word): Occurrences = {
val map = scala.collection.immutable.HashMap[Char, Int]().withDefaultValue(0)
w.foldLeft(map)((m, c) => m + (c -> (m(c) + 1)) )
} //> dfltHashMap: (w: forcomp.threadBug.Word)forcomp.threadBug.Occurrences
def mmDef(w: Word): Occurrences = {
val map = scala.collection.mutable.Map[Char, Int]().withDefaultValue(0)
w.foldLeft(map)((m, c) => m += (c -> (m(c) + 1)) )
} //> mmDef: (w: forcomp.threadBug.Word)forcomp.threadBug.Occurrences
val functions = List("grp" -> woGrouped _, "mtbl" -> mmDef _, "else" -> woGetElse0Map _
, "dfl0" -> woDeflt0Map _, "hash" -> dfltHashMap _
) //> functions : List[(String, String => scala.collection.Map[Char,Int])] = Lis
//| t((grp,<function1>), (mtbl,<function1>), (else,<function1>), (dfl0,<functio
//| n1>), (hash,<function1>))
val len = 100 * 1000 //> len : Int = 100000
def test(len: Int) {
val data: String = scala.util.Random.alphanumeric.take(len).toList.mkString
val firstResult = functions.head._2(data)
def run(f: Word => Occurrences): Int = {
val time1 = System.currentTimeMillis()
val result= f(data)
val time2 = (System.currentTimeMillis() - time1)
assert(result.toSet == firstResult.toSet)
time2.toInt
}
def log(results: Seq[Int]) = {
((functions zip results) map {case ((title, _), r) => title + " " + r} mkString " , ")
}
var groupResults = List.fill(functions.length)(1)
val integrals = for (i <- (1 to 10)) yield {
val results = functions map (f => (1 to 33).foldLeft(0) ((acc,_) => run(f._2)))
println (log (results))
groupResults = (results zip groupResults) map {case (r, gr) => r + gr}
log(groupResults).toUpperCase
}
integrals foreach println
} //> test: (len: Int)Unit
test(len)
test(len * 2)
// GRP 14 , mtbl 11 , else 31 , dfl0 36 , hash 34
// GRP 91 , MTBL 111
println("Done")
def main(args: Array[String]) {
}
produces
grp 5 , mtbl 5 , else 13 , dfl0 17 , hash 17
grp 3 , mtbl 6 , else 14 , dfl0 16 , hash 16
grp 3 , mtbl 6 , else 13 , dfl0 17 , hash 15
grp 4 , mtbl 5 , else 13 , dfl0 15 , hash 16
grp 23 , mtbl 6 , else 14 , dfl0 15 , hash 16
grp 5 , mtbl 5 , else 13 , dfl0 16 , hash 17
grp 4 , mtbl 6 , else 13 , dfl0 16 , hash 16
grp 4 , mtbl 6 , else 13 , dfl0 17 , hash 15
grp 3 , mtbl 5 , else 14 , dfl0 16 , hash 16
grp 3 , mtbl 6 , else 14 , dfl0 16 , hash 16
GRP 5 , MTBL 5 , ELSE 13 , DFL0 17 , HASH 17
GRP 8 , MTBL 11 , ELSE 27 , DFL0 33 , HASH 33
GRP 11 , MTBL 17 , ELSE 40 , DFL0 50 , HASH 48
GRP 15 , MTBL 22 , ELSE 53 , DFL0 65 , HASH 64
GRP 38 , MTBL 28 , ELSE 67 , DFL0 80 , HASH 80
GRP 43 , MTBL 33 , ELSE 80 , DFL0 96 , HASH 97
GRP 47 , MTBL 39 , ELSE 93 , DFL0 112 , HASH 113
GRP 51 , MTBL 45 , ELSE 106 , DFL0 129 , HASH 128
GRP 54 , MTBL 50 , ELSE 120 , DFL0 145 , HASH 144
GRP 57 , MTBL 56 , ELSE 134 , DFL0 161 , HASH 160
grp 7 , mtbl 11 , else 28 , dfl0 31 , hash 31
grp 7 , mtbl 10 , else 28 , dfl0 32 , hash 31
grp 7 , mtbl 11 , else 28 , dfl0 31 , hash 32
grp 7 , mtbl 11 , else 28 , dfl0 31 , hash 33
grp 7 , mtbl 11 , else 28 , dfl0 32 , hash 31
grp 8 , mtbl 11 , else 28 , dfl0 31 , hash 33
grp 8 , mtbl 11 , else 29 , dfl0 38 , hash 35
grp 7 , mtbl 11 , else 28 , dfl0 32 , hash 33
grp 8 , mtbl 11 , else 32 , dfl0 35 , hash 41
grp 7 , mtbl 13 , else 28 , dfl0 33 , hash 35
GRP 7 , MTBL 11 , ELSE 28 , DFL0 31 , HASH 31
GRP 14 , MTBL 21 , ELSE 56 , DFL0 63 , HASH 62
GRP 21 , MTBL 32 , ELSE 84 , DFL0 94 , HASH 94
GRP 28 , MTBL 43 , ELSE 112 , DFL0 125 , HASH 127
GRP 35 , MTBL 54 , ELSE 140 , DFL0 157 , HASH 158
GRP 43 , MTBL 65 , ELSE 168 , DFL0 188 , HASH 191
GRP 51 , MTBL 76 , ELSE 197 , DFL0 226 , HASH 226
GRP 58 , MTBL 87 , ELSE 225 , DFL0 258 , HASH 259
GRP 66 , MTBL 98 , ELSE 257 , DFL0 293 , HASH 300
GRP 73 , MTBL 111 , ELSE 285 , DFL0 326 , HASH 335
Done
It is curious that most concise groupBy
is faster than even mutable map!
Ok...so first you need to import in your project the image
1)Select the picturebox in Form Design
2)Open PictureBox Tasks (it's the little arrow pinted to right on the edge on the picturebox)
3)Click on "Choose image..."
4)Select the second option "Project resource file:" (this option will create a folder called "Resources" which you can acces with Properties.Resources)
5)Click on import and select your image from your computer (now a copy of the image with the same name as the image will be sent in Resources folder created at step 4)
6)Click on ok
Now the image is in your project and you can use it with Properties command.Just type this code when you want to change the picture from picturebox:
pictureBox1.Image = Properties.Resources.myimage;
Note: myimage represent the name of the image...after typing the dot after Resources,in your options it will be your imported image file
Generic classes are a type of class that takes in a data type as a parameter when it's created. This type parameter is specified using angle brackets and the type can change each time a new instance of the class is instantiated. For instance, let's create an ArrayList for Employee objects and another for Company objects
ArrayList<Employee> employees = new ArrayList<Employee>();
ArrayList<Company> companies = new ArrayList<Company>();
You'll notice that we're using the same ArrayList class to create both lists and we pass in the Employee or Company type using angle brackets. Having one generic class be able to handle multiple types of data cuts down on having a lot of classes that perform similar tasks. Generics also help to cut down on bugs by giving everything a strong type which helps the compiler point out errors. By specifying a type for ArrayList, the compiler will throw an error if you try to add an Employee to the Company list or vice versa.
I was able to get a combination of some of the other suggestions here working for me, but only while toggling the plt.interactive(False)
to True
and back again.
plt.interactive(True)
plt.pyplot.show()
This will flash up the my plots. Then setting to False
allowed for viewing.
plt.interactive(False)
plt.pyplot.show()
As noted also my program would not exit until all the windows were closed. Here are some details on my current run environment:
Python version 2.7.6
Anaconda 1.9.2 (x86_64)
(default, Jan 10 2014, 11:23:15)
[GCC 4.0.1 (Apple Inc. build 5493)]
Pandas version: 0.13.1
Edited:
The vertical-align CSS property specifies the vertical alignment of an inline, inline-block or table-cell element.
Read this article for Understanding vertical-align
if you are using jQuery 1.6 and up, you want to use .prop() rather than .attr():
$('#abc_frame').prop('src', url)
See this question for an explanation of the differences.
If you made a virtual env, then deleted that python installation, you'll get the same error. Just rm -r
your venv folder, then recreate it with a valid python location and do pip install -r requirements.txt
and you'll be all set (assuming you got your requirements.txt right).
Well I did not think this was possible until I went and checked. In some previous version of Excel I could not do this. I am currently using Excel 2013.
This is what you want to do in a scatter plot:
right click on your data point
select "Format Data Labels" (note you may have to add data labels first)
In order to colour the labels individually use the following steps:
If you have the entire series selected instead of the individual label, text formatting changes should apply to all labels instead of just one.
Assuming that c++ code (c++11) is okay as well and the interface is known.
#include <cstdint>
#include <fstream>
#include <streambuf>
#include <regex>
using namespace std;
uint64_t getIFMAC(const string &ifname) {
ifstream iface("/sys/class/net/" + ifname + "/address");
string str((istreambuf_iterator<char>(iface)), istreambuf_iterator<char>());
if (str.length() > 0) {
string hex = regex_replace(str, std::regex(":"), "");
return stoull(hex, 0, 16);
} else {
return 0;
}
}
int main()
{
string iface = "eth0";
printf("%s: mac=%016llX\n", iface.c_str(), getIFMAC(iface));
}
In addition to existing good answers, note that Jackson 1.9 improved handling by adding "property unification", meaning that ALL annotations from difference parts of a logical property are combined, using (hopefully) intuitive precedence.
In Jackson 1.8 and prior, only field and getter annotations were used when determining what and how to serialize (writing JSON); and only and setter annotations for deserialization (reading JSON). This sometimes required addition of "extra" annotations, like annotating both getter and setter.
With Jackson 1.9 and above these extra annotations are NOT needed. It is still possible to add those; and if different names are used, one can create "split" properties (serializing using one name, deserializing using other): this is occasionally useful for sort of renaming.
Define "First"? If the table has a PK then it will be ordered by that, and you can delete by that:
DECLARE @TABLE TABLE
(
ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
Data NVARCHAR(50) NOT NULL
)
INSERT INTO @TABLE(Data)
SELECT 'Hello' UNION
SELECT 'World'
SET ROWCOUNT 1
DELETE FROM @TABLE
SET ROWCOUNT 0
SELECT * FROM @TABLE
If the table has no PK, then ordering won't be guaranteed...
An interface is like a set of genes that are publicly documented to have some kind of effect: A DNA test will tell me whether I've got them - and if I do, I can publicly make it known that I'm a "carrier" and part of my behavior or state will conform to them. (But of course, I may have many other genes that provide traits outside this scope.)
An abstract class is like the dead ancestor of a single-sex species(*): She can't be brought to life but a living (i.e. non-abstract) descendant inherits all her genes.
(*) To stretch this metaphor, let's say all members of the species live to the same age. This means all ancestors of a dead ancestor must also be dead - and likewise, all descendants of a living ancestor must be alive.
You can use simple jQuery jPut plugin
http://plugins.jquery.com/jput/
<script>
$(document).ready(function(){
var json = [{"name": "name1","email":"[email protected]"},{"name": "name2","link":"[email protected]"}];
//while running this code the template will be appended in your div with json data
$("#tbody").jPut({
jsonData:json,
//ajax_url:"youfile.json", if you want to call from a json file
name:"tbody_template",
});
});
</script>
<table jput="t_template">
<tbody jput="tbody_template">
<tr>
<td>{{name}}</td>
<td>{{email}}</td>
</tr>
</tbody>
</table>
<table>
<tbody id="tbody">
</tbody>
</table>
The commands your are looking for are editor.action.copyLinesDownAction
and editor.action.copyLinesUpAction
.
You can see the associated keybindings by picking: File > Preferences > Keyboard Shortcuts
Windows:
Shift+Alt+Down and Shift+Alt+Up
Mac:
Shift+Option+Down and Shift+OptionUp
Linux:
Ctrl+Shift+Alt+Down and Ctrl+Shift+Alt+Up
(Might need to use numpad Down and Up for Linux)
Furthermore, commands editor.action.moveLinesUpAction
and editor.action.moveLinesDownAction
are the ones to move lines and they are bound to Alt+Down and Alt+Up on Windows and Mac and Ctrl+Down and Ctrl+Up on Linux.
Go to redis-cli and use below command
info keyspace
It may help someone
Try this:
Dim colHeader(12)
colHeader = ("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")
Unfortunately the code found online was VB.NET not VBA.
Stuart's answer provides a great explanation, but I'd like to provide another example.
I ran into this issue when attempting to perform a reduce
on a Stream containing null values (actually it was LongStream.average()
, which is a type of reduction). Since average() returns OptionalDouble
, I assumed the Stream could contain nulls but instead a NullPointerException was thrown. This is due to Stuart's explanation of null v. empty.
So, as the OP suggests, I added a filter like so:
list.stream()
.filter(o -> o != null)
.reduce(..);
Or as tangens pointed out below, use the predicate provided by the Java API:
list.stream()
.filter(Objects::nonNull)
.reduce(..);
From the mailing list discussion Stuart linked: Brian Goetz on nulls in Streams
java.io.FileInputStream is what you're looking for :-)
We have a large .SLN files with many project files. I started the policy of having a "ViewLocal" directory where all non-sourcecontrolled files are located. Inside that directory is an 'Inter' and an 'Out' directory. For the intermediate files, and the output files, respectively.
This obviously makes it easy to just go to your 'viewlocal' directory and do a simple delete, to get rid of everything.
Before you spent time figuring out a way to work around this with scripts, you might think about setting up something similar.
I won't lie though, maintaining such a setup in a large organization has proved....interesting. Especially when you use technologies such as QT that like to process files and create non-sourcecontrolled source files. But that is a whole OTHER story!
I think the best is to check if fragment is added before calling method in fragment. Do something like this to avoid null exception.
ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
if(fragment.isAdded()){
fragment.<specific_function_name>();
}
These are command line instructions where the above Graphical version is not available or you can not open the Lombok jar file by double clicks, like in Ubuntu.
At the time of writing using Lombok is not straightforward as just adding a dependency in your POM xml file and adding the annotation. These are the next steps:
1) Locate where your Lombok jar file is downloaded by maven; Usually it is in .m2 folder inside your home directory. Then execute the following command.
java -jar lombok-1.16.18.jar install <path of where your IDE is installed>
example usage:
java -jar lombok-x.xx.xx.jar install ~/Downloads/spring-tool-suite-3.9.1.RELEASE-e4.7.1a-linux-gtk-x86_64/sts-bundle/sts-3.9.1.RELEASE/
the above command basically makes a configuration update in your IDE .ini
or configuration
file something like below:
-javaagent:/home/neshant/Downloads/spring-tool-suite-3.9.1.RELEASE-e4.7.1a-linux-gtk-x86_64/sts-bundle/sts-3.9.1.RELEASE/lombok.jar
this ensures that the @Data
or @Getter
or @Setter
annotations are understood by the IDE. It is weird that it had to be so complex.
Another method that has not been mentioned yet is std::vector
.
std::vector<std::string> line;
while(file >> mystr)
{
line.push_back(mystr);
}
Then you can simply iterate over the vector and modify/extract what you need/
TL;DR:
Using slicing:
>>> import numpy as np
>>>
>>> arr = np.array([[1,2,3,4,5],[6,7,8,9,10]])
>>>
>>> arr[0,0]
1
>>> arr[1,1]
7
>>> arr[1,0]
6
>>> arr[1,-1]
10
>>> arr[1,-2]
9
In Long:
Hopefully this helps in your understanding:
>>> import numpy as np
>>> np.array([ [1,2,3], [4,5,6] ])
array([[1, 2, 3],
[4, 5, 6]])
>>> x = np.array([ [1,2,3], [4,5,6] ])
>>> x[1][2] # 2nd row, 3rd column
6
>>> x[1,2] # Similarly
6
But to appreciate why slicing is useful, in more dimensions:
>>> np.array([ [[1,2,3], [4,5,6]], [[7,8,9],[10,11,12]] ])
array([[[ 1, 2, 3],
[ 4, 5, 6]],
[[ 7, 8, 9],
[10, 11, 12]]])
>>> x = np.array([ [[1,2,3], [4,5,6]], [[7,8,9],[10,11,12]] ])
>>> x[1][0][2] # 2nd matrix, 1st row, 3rd column
9
>>> x[1,0,2] # Similarly
9
>>> x[1][0:2][2] # 2nd matrix, 1st row, 3rd column
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: index 2 is out of bounds for axis 0 with size 2
>>> x[1, 0:2, 2] # 2nd matrix, 1st and 2nd row, 3rd column
array([ 9, 12])
>>> x[1, 0:2, 1:3] # 2nd matrix, 1st and 2nd row, 2nd and 3rd column
array([[ 8, 9],
[11, 12]])
In Swift 4.2 and Xcode 10
//This is your str
let str = "This is my String" //Here replace with your string
Option 1
let items = str.components(separatedBy: " ")//Here replase space with your value and the result is Array.
//Direct single line of code
//let items = "This is my String".components(separatedBy: " ")
let str1 = items[0]
let str2 = items[1]
let str3 = items[2]
let str4 = items[3]
//OutPut
print(items.count)
print(str1)
print(str2)
print(str3)
print(str4)
print(items.first!)
print(items.last!)
Option 2
let items = str.split(separator: " ")
let str1 = String(items.first!)
let str2 = String(items.last!)
//Output
print(items.count)
print(items)
print(str1)
print(str2)
Option 3
let arr = str.split {$0 == " "}
print(arr)
Option 4
let line = "BLANCHE: I don't want realism. I want magic!"
print(line.split(separator: " "))
// Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
let line = "BLANCHE: I don't want realism. I want magic!"
print(line.split(separator: " "))
// Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
print(line.split(separator: " ", maxSplits: 1))//This can split your string into 2 parts
// Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
print(line.split(separator: " ", maxSplits: 2))//This can split your string into 3 parts
print(line.split(separator: " ", omittingEmptySubsequences: false))//array contains empty strings where spaces were repeated.
// Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
print(line.split(separator: " ", omittingEmptySubsequences: true))//array not contains empty strings where spaces were repeated.
print(line.split(separator: " ", maxSplits: 4, omittingEmptySubsequences: false))
print(line.split(separator: " ", maxSplits: 3, omittingEmptySubsequences: true))
If you want to find a specific user's home directory, I don't believe you can do it directly.
When I've needed to do this before from Java I had to write some JNI native code that wrapped the UNIX getpwXXX()
family of calls.
Here is the simple logic to find Biggest/Largest Number
Input : 11, 33, 1111, 4, 0 Output : 1111
namespace PurushLogics
{
class Purush_BiggestNumber
{
static void Main()
{
int count = 0;
Console.WriteLine("Enter Total Number of Integers\n");
count = int.Parse(Console.ReadLine());
int[] numbers = new int[count];
Console.WriteLine("Enter the numbers"); // Input 44, 55, 111, 2 Output = "111"
for (int temp = 0; temp < count; temp++)
{
numbers[temp] = int.Parse(Console.ReadLine());
}
int largest = numbers[0];
for (int big = 1; big < numbers.Length; big++)
{
if (largest < numbers[big])
{
largest = numbers[big];
}
}
Console.WriteLine(largest);
Console.ReadKey();
}
}
}
Call clear()
method from your custom adapter .
I used a small hack to use the RecyclerView on older devices. I just went into my local m2 repository and picked up the RecyclerView source files and put them into my project.
You can find the sourcecode here:
<Android-SDK>\extras\android\m2repository\com\android\support\recyclerview-v7\21.0.0-rc1\recyclerview-v7-21.0.0-rc1-sources.jar
Cellspacing is all around the cell and cannot be changed (i.e. if it's set to one, there will be 1 pixel of space on all sides). Padding can be specified discreetly (e.g. padding-top
, padding-bottom
, padding-left
, and padding-right;
or padding: [top] [right] [bottom] [left];
).
You can use the Y-combinator: (Wikipedia)
// ES5 syntax
var Y = function Y(a) {
return (function (a) {
return a(a);
})(function (b) {
return a(function (a) {
return b(b)(a);
});
});
};
// ES6 syntax
const Y = a=>(a=>a(a))(b=>a(a=>b(b)(a)));
// If the function accepts more than one parameter:
const Y = a=>(a=>a(a))(b=>a((...a)=>b(b)(...a)));
And you can use it as this:
// ES5
var fn = Y(function(fn) {
return function(counter) {
console.log(counter);
if (counter > 0) {
fn(counter - 1);
}
}
});
// ES6
const fn = Y(fn => counter => {
console.log(counter);
if (counter > 0) {
fn(counter - 1);
}
});
SELECT LTRIM(RTRIM(Replace(Replace(Replace(name,' ',' '),CHAR(13), ' '),char(10), ' ')))
from author
How about..
var result = (from s in context.Shift join es in employeeshift on s.shiftid equals es.shiftid where es.empid == 57 select s)
Edit: This will give you shifts where there is an associated employeeshift (because of the join). For the "not exists" I'd do what @ArsenMkrt or @hyp suggest
Try to make the bounds
's size integer.
#include <math.h>
....
if (ratio > 1) {
bounds.size.width = resolution;
bounds.size.height = round(bounds.size.width / ratio);
} else {
bounds.size.height = resolution;
bounds.size.width = round(bounds.size.height * ratio);
}
I was in SLES12 and for me it worked after upgrading to wget 1.14, using --secure-protocol=TLSv1.2 and using --auth-no-challenge.
wget --no-check-certificate --secure-protocol=TLSv1.2 --user=satul --password=xxx --auth-no-challenge -v --debug https://jenkins-server/artifact/build.x86_64.tgz
This isn't quite what you're looking for, but I've found it useful in similar circumstances.
I recently added the following to my $HOME/.bashrc
(something similar should be possible with shells other than bash):
if [ -f $HOME/.add-screen-to-history ] ; then
history -s 'screen -dr'
fi
I keep a screen
session running on one particular machine, and I've had problems with ssh
connections to that machine being dropped, requiring me to re-run screen -dr
every time I reconnect.
With that addition, and after creating that (empty) file in my home directory, I automatically have the screen -dr
command in my history when my shell starts. After reconnecting, I can just type Control-P Enter and I'm back in my screen session -- or I can ignore it. It's flexible, but not quite automatic, and in your case it's easier than typing tmux list-sessions
.
You might want to make the history -s
command unconditional.
This does require updating your $HOME/.bashrc
on each of the target systems, which might or might not make it unsuitable for your purposes.
If your config file is in a different path than classpath, you can add the configuration file path as a system property:
java -Dapp.config.path=path_to_config_file -jar your.jar
On Ubuntu; using mkvirtualenv -p python3 env_name
loads the virtualenv with python3.
Inside the env, use python --version
to verify.
Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.
In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:
CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
one int;
two int;
BEGIN
one := 1;
two := 2;
RETURN one + two;
END
$$;
SELECT somefuncname();
The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.
Yes. you can't remember all the shortcuts. You will forget many of them for sure. In this way, you can recall it and get the work done quickly.
Press Ctrl+3
And type whatever the hell you want :) It's a shortcut for shortcuts
May be it´s a little late. But you can do this.
txtFoo.Multiline = true;
txtFoo.MinimumSize = new Size(someWith,someHeight);
I solved it that way.
If you don't care what groups the users were in, and just want a big ol' list of users - this does the job:
$Groups = Get-ADGroup -Filter {Name -like "AB*"}
$rtn = @(); ForEach ($Group in $Groups) {
$rtn += (Get-ADGroupMember -Identity "$($Group.Name)" -Recursive)
}
Then the results:
$rtn | ft -autosize
If you want to filter the models by applicationname
and the remaining models by surname
:
List<Model> newList = list.Where(m => m.application == "applicationname")
.Select(m => new Model {
application = m.application,
users = m.users.Where(u => u.surname == "surname").ToList()
}).ToList();
As you can see, it needs to create new models and user-lists, hence it is not the most efficient way.
If you instead don't want to filter the list of users but filter the models by users with at least one user with a given username, use Any
:
List<Model> newList = list
.Where(m => m.application == "applicationname"
&& m.users.Any(u => u.surname == "surname"))
.ToList();
The concern is we should not use ALLOW_ALL_HOSTNAME_VERIFIER.
How about I implement my own hostname verifier?
class MyHostnameVerifier implements org.apache.http.conn.ssl.X509HostnameVerifier
{
@Override
public boolean verify(String host, SSLSession session) {
String sslHost = session.getPeerHost();
System.out.println("Host=" + host);
System.out.println("SSL Host=" + sslHost);
if (host.equals(sslHost)) {
return true;
} else {
return false;
}
}
@Override
public void verify(String host, SSLSocket ssl) throws IOException {
String sslHost = ssl.getInetAddress().getHostName();
System.out.println("Host=" + host);
System.out.println("SSL Host=" + sslHost);
if (host.equals(sslHost)) {
return;
} else {
throw new IOException("hostname in certificate didn't match: " + host + " != " + sslHost);
}
}
@Override
public void verify(String host, X509Certificate cert) throws SSLException {
throw new SSLException("Hostname verification 1 not implemented");
}
@Override
public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
throw new SSLException("Hostname verification 2 not implemented");
}
}
Let's test against https://www.rideforrainbows.org/ which is hosted on a shared server.
public static void main (String[] args) throws Exception {
//org.apache.http.conn.ssl.SSLSocketFactory sf = org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory();
//sf.setHostnameVerifier(new MyHostnameVerifier());
//org.apache.http.conn.scheme.Scheme sch = new Scheme("https", 443, sf);
org.apache.http.client.HttpClient client = new DefaultHttpClient();
//client.getConnectionManager().getSchemeRegistry().register(sch);
org.apache.http.client.methods.HttpPost post = new HttpPost("https://www.rideforrainbows.org/");
org.apache.http.HttpResponse response = client.execute(post);
java.io.InputStream is = response.getEntity().getContent();
java.io.BufferedReader rd = new java.io.BufferedReader(new java.io.InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
}
SSLException:
Exception in thread "main" javax.net.ssl.SSLException: hostname in certificate didn't match: www.rideforrainbows.org != stac.rt.sg OR stac.rt.sg OR www.stac.rt.sg
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:231)
...
Do with MyHostnameVerifier:
public static void main (String[] args) throws Exception {
org.apache.http.conn.ssl.SSLSocketFactory sf = org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory();
sf.setHostnameVerifier(new MyHostnameVerifier());
org.apache.http.conn.scheme.Scheme sch = new Scheme("https", 443, sf);
org.apache.http.client.HttpClient client = new DefaultHttpClient();
client.getConnectionManager().getSchemeRegistry().register(sch);
org.apache.http.client.methods.HttpPost post = new HttpPost("https://www.rideforrainbows.org/");
org.apache.http.HttpResponse response = client.execute(post);
java.io.InputStream is = response.getEntity().getContent();
java.io.BufferedReader rd = new java.io.BufferedReader(new java.io.InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
}
Shows:
Host=www.rideforrainbows.org
SSL Host=www.rideforrainbows.org
At least I have the logic to compare (Host == SSL Host) and return true.
The above source code is working for httpclient-4.2.3.jar and httpclient-4.3.3.jar.
I created the following utility to set the console size and scroll buffers.
I compiled it using DEV C++ (http://www.bloodshed.net/devcpp.html).
An executable is included in https://sourceforge.net/projects/wa2l-wintools/.
#include <iostream>
#include <windows.h>
using namespace std;
// SetWindow(Width,Height,WidthBuffer,HeightBuffer) -- set console size and buffer dimensions
//
void SetWindow(int Width, int Height, int WidthBuffer, int HeightBuffer) {
_COORD coord;
coord.X = WidthBuffer;
coord.Y = HeightBuffer;
_SMALL_RECT Rect;
Rect.Top = 0;
Rect.Left = 0;
Rect.Bottom = Height - 1;
Rect.Right = Width - 1;
HANDLE Handle = GetStdHandle(STD_OUTPUT_HANDLE); // Get Handle
SetConsoleScreenBufferSize(Handle, coord); // Set Buffer Size
SetConsoleWindowInfo(Handle, TRUE, &Rect); // Set Window Size
} // SetWindow
// main(Width,Height,WidthBuffer,HeightBuffer) -- main
//
int main(int argc, char *argv[]) {
int width = 80;
int height = 25;
int wbuffer = width + 200;
int hbuffer = height + 1000;
if ( argc == 5 ){
width = atoi(argv[1]);
height = atoi(argv[2]);
wbuffer = atoi(argv[3]);
hbuffer = atoi(argv[4]);
} else if ( argc > 1 ) {
cout << "Usage: " << argv[0] << " [ width height bufferwidth bufferheight ]" << endl << endl;
cout << " Where" << endl;
cout << " width console width" << endl;
cout << " height console height" << endl;
cout << " bufferwidth scroll buffer width" << endl;
cout << " bufferheight scroll buffer height" << endl;
return 4;
}
SetWindow(width,height,wbuffer,hbuffer);
return 0;
}
if you are using Bootstrap.just use this code in your custom css file. Bootstrap removes all your colors in print preview.
@media print{
.box-text {
font-size: 27px !important;
color: blue !important;
-webkit-print-color-adjust: exact !important;
}
}
If you are using VS 2010 and it is a ASP.NET project make sure you have the Visual Developer installed from the VS 2010 CD. This is not the free one, but part of what is required to work on ASP.NET projects in Visual Studio.
$('#select_id option:eq(0)').prop('selected', 'selected');
its good
Once you have cloned the repo, you have everything: you can then hg up branchname
or hg up tagname
to update your working copy.
UP: hg up
is a shortcut of hg update
, which also has hg checkout
alias for people with git
habits.
You can also get the body of triggers as following:
SELECT o.[name],
c.[text]
FROM sys.objects AS o
INNER JOIN sys.syscomments AS c
ON o.object_id = c.id
WHERE o.[type] = 'TR'
From C++11 onwards, all the standard containers (std::vector
, std::map
, etc) support move semantics, meaning that you can now pass rvalues to standard containers and avoid a copy:
// Example object class.
class object
{
private:
int m_val1;
std::string m_val2;
public:
// Constructor for object class.
object(int val1, std::string &&val2) :
m_val1(val1),
m_val2(std::move(val2))
{
}
};
std::vector<object> myList;
// #1 Copy into the vector.
object foo1(1, "foo");
myList.push_back(foo1);
// #2 Move into the vector (no copy).
object foo2(1024, "bar");
myList.push_back(std::move(foo2));
// #3 Move temporary into vector (no copy).
myList.push_back(object(453, "baz"));
// #4 Create instance of object directly inside the vector (no copy, no move).
myList.emplace_back(453, "qux");
Alternatively you can use various smart pointers to get mostly the same effect:
std::unique_ptr
example
std::vector<std::unique_ptr<object>> myPtrList;
// #5a unique_ptr can only ever be moved.
auto pFoo = std::make_unique<object>(1, "foo");
myPtrList.push_back(std::move(pFoo));
// #5b unique_ptr can only ever be moved.
myPtrList.push_back(std::make_unique<object>(1, "foo"));
std::shared_ptr
example
std::vector<std::shared_ptr<object>> objectPtrList2;
// #6 shared_ptr can be used to retain a copy of the pointer and update both the vector
// value and the local copy simultaneously.
auto pFooShared = std::make_shared<object>(1, "foo");
objectPtrList2.push_back(pFooShared);
// Pointer to object stored in the vector, but pFooShared is still valid.
savez() save data in a zip file, It may take some time to zip & unzip the file. You can use save() & load() function:
f = file("tmp.bin","wb")
np.save(f,a)
np.save(f,b)
np.save(f,c)
f.close()
f = file("tmp.bin","rb")
aa = np.load(f)
bb = np.load(f)
cc = np.load(f)
f.close()
To save multiple arrays in one file, you just need to open the file first, and then save or load the arrays in sequence.
Demo here
Try this one
$('html').on('click', 'a.Link', function(event){
event.preventDefault();
});
The issue here is that input()
returns a string in Python 3.x, so when you do your comparison, you are comparing a string and an integer, which isn't well defined (what if the string is a word, how does one compare a string and a number?) - in this case Python doesn't guess, it throws an error.
To fix this, simply call int()
to convert your string to an integer:
int(input(...))
As a note, if you want to deal with decimal numbers, you will want to use one of float()
or decimal.Decimal()
(depending on your accuracy and speed needs).
Note that the more pythonic way of looping over a series of numbers (as opposed to a while
loop and counting) is to use range()
. For example:
def main():
print("Let me Retire Financial Calculator")
deposit = float(input("Please input annual deposit in dollars: $"))
rate = int(input ("Please input annual rate in percentage: %")) / 100
time = int(input("How many years until retirement?"))
value = 0
for x in range(1, time+1):
value = (value * rate) + deposit
print("The value of your account after" + str(x) + "years will be $" + str(value))
This is how the if
behaves.
if(turnedOn) // This turnedOn should be a boolean or you could have a condition here which would give a boolean result.
{
// It will come here if turnedOn is true (i.e) the condition in the "if" evaluates to true
}
else
{
// It will come here if turnedOn is false (i.e) the condition in the "if" evaluates to false
}
String to Date conversion:
private Date StringtoDate(String date) throws Exception {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
java.sql.Date sqlDate = null;
if( !date.isEmpty()) {
try {
java.util.Date normalDate = sdf1.parse(date);
sqlDate = new java.sql.Date(normalDate.getTime());
} catch (ParseException e) {
throw new Exception("Not able to Parse the date", e);
}
}
return sqlDate;
}
SQLAlchemy is very, very powerful. However it is not thread safe make sure you keep that in mind when working with cherrypy in thread-pool mode.
The other answers will work for most strings, but you can end up unescaping an already escaped double quote, which is probably not what you want.
To work correctly, you are going to need to escape all backslashes and then escape all double quotes, like this:
var test_str = '"first \\" middle \\" last "';
var result = test_str.replace(/\\/g, '\\\\').replace(/\"/g, '\\"');
depending on how you need to use the string, and the other escaped charaters involved, this may still have some issues, but I think it will probably work in most cases.
Always use nibName file otherwise your preloaded content of Xib will not show .
vc : ViewController = ViewController(nibName: "ViewController", bundle: nil) //change this to your class name
self.presentViewController(vc, animated: true, completion: nil)
I think you should refactor your packages in more convenient hierarchy, so they are out of the base package.
But if you can't do this, try:
<context:component-scan base-package="com.example">
...
<context:exclude-filter type="regex" expression="com\.example\.ignore.*"/>
</context:component-scan>
Here you could find more examples: Using filters to customize scanning
Use a scripts section in the view and master layout.
Put all your scripts defined in your view inside a Scripts section of the view. This way you can have the master layout load this after all other scripts have been loaded. This is the default setup when starting a new MVC5 web project. Not sure about earlier versions.
Views/Foo/MyView.cshtml:
// The rest of your view code above here.
@section Scripts
{
// Either render the bundle defined with same name in BundleConfig.cs...
@Scripts.Render("~/bundles/myCustomBundle")
// ...or hard code the HTML.
<script src="URL-TO-CUSTOM-JS-FILE"></script>
<script type="text/javascript">
$(document).ready(function () {
// Do your custom javascript for this view here. Will be run after
// loading all the other scripts.
});
</script>
}
Views/Shared/_Layout.cshtml
<html>
<body>
<!-- ... Rest of your layout file here ... -->
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
Note how the scripts section is rendered last in the master layout file.
As mentioned in Yoshua Wuyts' answer, using git branch
:
git branch --unset-upstream
You don't have to delete your local branch.
Simply delete the local branch that is tracking the remote branch:
git branch -d -r origin/<remote branch name>
-r, --remotes
tells git to delete the remote-tracking branch (i.e., delete the branch set to track the remote branch). This will not delete the branch on the remote repo!
See "Having a hard time understanding git-fetch"
there's no such concept of local tracking branches, only remote tracking branches.
Soorigin/master
is a remote tracking branch formaster
in theorigin
repo
As mentioned in Dobes Vandermeer's answer, you also need to reset the configuration associated to the local branch:
git config --unset branch.<branch>.remote
git config --unset branch.<branch>.merge
Remove the upstream information for
<branchname>
.
If no branch is specified it defaults to the current branch.
(git 1.8+, Oct. 2012, commit b84869e by Carlos Martín Nieto (carlosmn
))
That will make any push/pull completely unaware of origin/<remote branch name>
.
One more option if your id isn't autoincrement and you know which one to insert/update:
$object = MyModel::findOrNew($id);
//assign attributes to update...
$object->save();
Multiply everything by 100 and store it in a long as cents.
//Off the cuff, Prototype style.
//Note, this is not optimal; there should be some basic partitioning and caching going on.
(function () {
var elements = [];
Element.register = function (element) {
for (var i=0; i<elements.length; i++) {
if (elements[i]==element) break;
}
elements.push(element);
if (arguments.length>1)
for (var i=0; i<arguments.length; i++)
Element.register(arguments[i]);
};
Element.collide = function () {
for (var outer=0; outer < elements.length; outer++) {
var e1 = Object.extend(
$(elements[outer]).positionedOffset(),
$(elements[outer]).getDimensions()
);
for (var inner=outer; inner<elements.length; innter++) {
var e2 = Object.extend(
$(elements[inner]).positionedOffset(),
$(elements[inner]).getDimensions()
);
if (
(e1.left+e1.width)>=e2.left && e1.left<=(e2.left+e2.width) &&
(e1.top+e1.height)>=e2.top && e1.top<=(e2.top+e2.height)
) {
$(elements[inner]).fire(':collision', {element: $(elements[outer])});
$(elements[outer]).fire(':collision', {element: $(elements[inner])});
}
}
}
};
})();
//Usage:
Element.register(myElementA);
Element.register(myElementB);
$(myElementA).observe(':collision', function (ev) {
console.log('Damn, '+ev.memo.element+', that hurt!');
});
//detect collisions every 100ms
setInterval(Element.collide, 100);
C++11 gives you a lot of new options with random
. The canonical paper on this topic would be N3551, Random Number Generation in C++11
To see why using rand()
can be problematic see the rand() Considered Harmful presentation material by Stephan T. Lavavej given during the GoingNative 2013 event. The slides are in the comments but here is a direct link.
I also cover boost
as well as using rand
since legacy code may still require its support.
The example below is distilled from the cppreference site and uses the std::mersenne_twister_engine engine and the std::uniform_real_distribution which generates numbers in the [0,10)
interval, with other engines and distributions commented out (see it live):
#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <random>
int main()
{
std::random_device rd;
//
// Engines
//
std::mt19937 e2(rd());
//std::knuth_b e2(rd());
//std::default_random_engine e2(rd()) ;
//
// Distribtuions
//
std::uniform_real_distribution<> dist(0, 10);
//std::normal_distribution<> dist(2, 2);
//std::student_t_distribution<> dist(5);
//std::poisson_distribution<> dist(2);
//std::extreme_value_distribution<> dist(0,2);
std::map<int, int> hist;
for (int n = 0; n < 10000; ++n) {
++hist[std::floor(dist(e2))];
}
for (auto p : hist) {
std::cout << std::fixed << std::setprecision(1) << std::setw(2)
<< p.first << ' ' << std::string(p.second/200, '*') << '\n';
}
}
output will be similar to the following:
0 ****
1 ****
2 ****
3 ****
4 *****
5 ****
6 *****
7 ****
8 *****
9 ****
The output will vary depending on which distribution you choose, so if we decided to go with std::normal_distribution with a value of 2
for both mean and stddev e.g. dist(2, 2)
instead the output would be similar to this (see it live):
-6
-5
-4
-3
-2 **
-1 ****
0 *******
1 *********
2 *********
3 *******
4 ****
5 **
6
7
8
9
The following is a modified version of some of the code presented in N3551
(see it live) :
#include <algorithm>
#include <array>
#include <iostream>
#include <random>
std::default_random_engine & global_urng( )
{
static std::default_random_engine u{};
return u ;
}
void randomize( )
{
static std::random_device rd{};
global_urng().seed( rd() );
}
int main( )
{
// Manufacture a deck of cards:
using card = int;
std::array<card,52> deck{};
std::iota(deck.begin(), deck.end(), 0);
randomize( ) ;
std::shuffle(deck.begin(), deck.end(), global_urng());
// Display each card in the shuffled deck:
auto suit = []( card c ) { return "SHDC"[c / 13]; };
auto rank = []( card c ) { return "AKQJT98765432"[c % 13]; };
for( card c : deck )
std::cout << ' ' << rank(c) << suit(c);
std::cout << std::endl;
}
Results will look similar to:
5H 5S AS 9S 4D 6H TH 6D KH 2S QS 9H 8H 3D KC TD 7H 2D KS 3C TC 7D 4C QH QC QD JD AH JC AC KD 9D 5C 2H 4H 9C 8C JH 5D 4S 7C AD 3S 8S TS 2C 8D 3H 6C JS 7S 6S
Boost
Of course Boost.Random is always an option as well, here I am using boost::random::uniform_real_distribution:
#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_real_distribution.hpp>
int main()
{
boost::random::mt19937 gen;
boost::random::uniform_real_distribution<> dist(0, 10);
std::map<int, int> hist;
for (int n = 0; n < 10000; ++n) {
++hist[std::floor(dist(gen))];
}
for (auto p : hist) {
std::cout << std::fixed << std::setprecision(1) << std::setw(2)
<< p.first << ' ' << std::string(p.second/200, '*') << '\n';
}
}
rand()
If you must use rand()
then we can go to the C FAQ for a guides on How can I generate floating-point random numbers? , which basically gives an example similar to this for generating an on the interval [0,1)
:
#include <stdlib.h>
double randZeroToOne()
{
return rand() / (RAND_MAX + 1.);
}
and to generate a random number in the range from [M,N)
:
double randMToN(double M, double N)
{
return M + (rand() / ( RAND_MAX / (N-M) ) ) ;
}
When you push a new branch the first time use: >git push -u origin
After that, you can just type a shorter command: >git push
The first-time -u option created a persistent upstream tracking branch with your local branch.
To clarify which command to use based on the situation
exec()
- Execute an external program
system()
- Execute an external program and display the output
passthru()
- Execute an external program and display raw output
You use return false to prevent something from happening. So if you have a script running on submit then return false will prevent the submit from working.
Let me try to make it simple, suppose URL of the site is www.example.com and you need to sign up by filling username and password, so we go to the login page say http://www.example.com/login.php now and view it's source code and search for the action URL it will be in form tag something like
<form name="loginform" method="post" action="userinfo.php">
now take userinfo.php to make absolute URL which will be 'http://example.com/userinfo.php', now run a simple python script
import requests
url = 'http://example.com/userinfo.php'
values = {'username': 'user',
'password': 'pass'}
r = requests.post(url, data=values)
print r.content
I Hope that this helps someone somewhere someday.
Using dplyr you can:
df <- df %>% dplyr:: select(grep("ABC", names(df)), grep("XYZ", names(df)))
There is a CSS unit called viewport height / viewport width.
Example
.mainbody{height: 100vh;}
similarly html,body{width: 100vw;}
or 90vh = 90% of the viewport height.
**IE9+ and most modern browsers.
std::sort(object.begin(), object.end(), pred());
where, pred()
is a function object defining the order on objects of myclass
. Alternatively, you can define myclass::operator<
.
For example, you can pass a lambda:
std::sort(object.begin(), object.end(),
[] (myclass const& a, myclass const& b) { return a.v < b.v; });
Or if you're stuck with C++03, the function object approach (v
is the member on which you want to sort):
struct pred {
bool operator()(myclass const & a, myclass const & b) const {
return a.v < b.v;
}
};
I had an issue where I had to replace the text of link, but I couldn't use JavaScript nor could I directly change the text of a hyperlink as it was compiled down from XML. Also, I couldn't use pseudo elements, or they didn't seem to work when I had tried them.
Basically, I put the text I wanted into a span and put the anchor tag underneath it and wrapped both in a div. I basically moved the anchor tag up via CSS and then made the font transparent. Now when you hover over the span, it "acts" like a link. A really hacky way of doing this, but this is how you can have a link with different text...
This is a fiddle of how I got around this issue
My HTML
<div class="field">
<span>This is your link text</span><br/>
<a href="//www.google.com" target="_blank">This is your actual link</a>
</div>
My CSS
div.field a {
color: transparent;
position: absolute;
top:1%;
}
div.field span {
display: inline-block;
}
The CSS will need to change based off your requirements, but this is a general way of doing what you are asking.
If I remember correctly, window.location.reload()
reloads the current page with POST data, while window.location.href=window.location.href
does not include the POST data.
As noted by @W3Max in the comments below, window.location.href=window.location.href
will not reload the page if there's an anchor (#) in the URL - You must use window.location.reload()
in this case.
Also, as noted by @Mic below, window.location.reload()
takes an additional argument skipCache
so that with using window.location.reload(true)
the browser will skip the cache and reload the page from the server. window.location.reload(false)
will do the opposite, and load the page from cache if possible.
A bare repository is pretty much something you only push to and fetch from. You cannot do much directly "in it": you cannot check stuff out, create references (branches, tags), run git status
, etc.
If you want to create a new branch in a bare Git repository, you can push a branch from a clone to your bare repo:
# initialize your bare repo
$ git init --bare test-repo.git
# clone it and cd to the clone's root directory
$ git clone test-repo.git/ test-clone
Cloning into 'test-clone'...
warning: You appear to have cloned an empty repository.
done.
$ cd test-clone
# make an initial commit in the clone
$ touch README.md
$ git add .
$ git commit -m "add README"
[master (root-commit) 65aab0e] add README
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 README.md
# push to origin (i.e. your bare repo)
$ git push origin master
Counting objects: 3, done.
Writing objects: 100% (3/3), 219 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To /Users/jubobs/test-repo.git/
* [new branch] master -> master
Why choose between a traditional database and a NoSQL data store? Use both! The problem with NoSQL solutions (beyond the initial learning curve) is the lack of transactions -- you do all updates to MySQL and have MySQL populate a NoSQL data store for reads -- you then benefit from each technology's strengths. This does add more complexity, but you already have the MySQL side -- just add MongoDB, Cassandra, etc to the mix.
NoSQL datastores generally scale way better than a traditional DB for the same otherwise specs -- there is a reason why Facebook, Twitter, Google, and most start-ups are using NoSQL solutions. It's not just geeks getting high on new tech.
For purely html @isherwood has a great solution. For jQuery, give your select drop down an ID then select it with jQuery:
<form>
<select id="myDropDown">
<option value="0">aaaa</option>
<option value="1">bbbb</option>
</select>
</form>
Then use this jQuery to clear the drop down on page load:
$(document).ready(function() {
$('#myDropDown').val('');
});
Or put it inside a function by itself:
$('#myDropDown').val('');
accomplishes what you're looking for and it is easy to put this in functions that may get called on your page if you need to blank out the drop down without reloading the page.
Yes - absolutely. Looking up a class via reflection is, by magnitude, more expensive.
Quoting Java's documentation on reflection:
Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.
Here's a simple test I hacked up in 5 minutes on my machine, running Sun JRE 6u10:
public class Main {
public static void main(String[] args) throws Exception
{
doRegular();
doReflection();
}
public static void doRegular() throws Exception
{
long start = System.currentTimeMillis();
for (int i=0; i<1000000; i++)
{
A a = new A();
a.doSomeThing();
}
System.out.println(System.currentTimeMillis() - start);
}
public static void doReflection() throws Exception
{
long start = System.currentTimeMillis();
for (int i=0; i<1000000; i++)
{
A a = (A) Class.forName("misc.A").newInstance();
a.doSomeThing();
}
System.out.println(System.currentTimeMillis() - start);
}
}
With these results:
35 // no reflection
465 // using reflection
Bear in mind the lookup and the instantiation are done together, and in some cases the lookup can be refactored away, but this is just a basic example.
Even if you just instantiate, you still get a performance hit:
30 // no reflection
47 // reflection using one lookup, only instantiating
Again, YMMV.
The two functions you need are documented here:
In short:
// Load images in the C++ format
cv::Mat img = cv::imread("something.jpg");
cv::Mat src = cv::imread("src.jpg");
// Resize src so that is has the same size as img
cv::resize(src, src, img.size());
And please, please, stop using the old and completely deprecated IplImage* classes
In the App Delegate, you can write
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.window endEditing:YES];
}
use this way, you can don`t write too much code.
You could create a view that has the columns you wish to select, then you can just select *
from the view...
I found this problem while trying to install a new clang compiler. Turns out that both the Debian and the LLVM maintainers agree that the alternatives system should be used for alternatives, NOT for versioning.
The solution they propose is something like this:
PATH=/usr/lib/llvm-3.7/bin:$PATH
where /usr/lib/llvm-3.7/bin is a directory that got created by the llvm-3.7 package, and which contains all the tools with their non-suffixed names. With that, llvm-config (version 3.7) appears with its plain name in your PATH. No need to muck around with symlinks, nor to call the llvm-config-3.7 that got installed in /usr/bin.
Also, check for a package named llvm-defaults (or gcc-defaults), which might offer other way to do this (I didn't use it).
This will only work in C++. Functions in structs are not a feature of C.
Same goes for your client.AddClient(); call ... this is a call for a member function, which is object oriented programming, i.e. C++.
Convert your source to a .cpp file and make sure you are compiling accordingly.
If you need to stick to C, the code below is (sort of) the equivalent:
typedef struct client_t client_t, *pno;
struct client_t
{
pid_t pid;
char password[TAM_MAX]; // -> 50 chars
pno next;
};
pno AddClient(pno *pclient)
{
/* code */
}
int main()
{
client_t client;
//code ..
AddClient(client);
}
Restarting the emulator works in some scenario.
You could do this using an IF
statement:
IF NOT EXISTS
( SELECT 1
FROM tblSoftwareTitles
WHERE Softwarename = @SoftwareName
AND SoftwareSystemType = @Softwaretype
)
BEGIN
INSERT tblSoftwareTitles (SoftwareName, SoftwareSystemType)
VALUES (@SoftwareName, @SoftwareType)
END;
You could do it without IF
using SELECT
INSERT tblSoftwareTitles (SoftwareName, SoftwareSystemType)
SELECT @SoftwareName,@SoftwareType
WHERE NOT EXISTS
( SELECT 1
FROM tblSoftwareTitles
WHERE Softwarename = @SoftwareName
AND SoftwareSystemType = @Softwaretype
);
Both methods are susceptible to a race condition, so while I would still use one of the above to insert, but you can safeguard duplicate inserts with a unique constraint:
CREATE UNIQUE NONCLUSTERED INDEX UQ_tblSoftwareTitles_Softwarename_SoftwareSystemType
ON tblSoftwareTitles (SoftwareName, SoftwareSystemType);
ADDENDUM
In SQL Server 2008 or later you can use MERGE
with HOLDLOCK
to remove the chance of a race condition (which is still not a substitute for a unique constraint).
MERGE tblSoftwareTitles WITH (HOLDLOCK) AS t
USING (VALUES (@SoftwareName, @SoftwareType)) AS s (SoftwareName, SoftwareSystemType)
ON s.Softwarename = t.SoftwareName
AND s.SoftwareSystemType = t.SoftwareSystemType
WHEN NOT MATCHED BY TARGET THEN
INSERT (SoftwareName, SoftwareSystemType)
VALUES (s.SoftwareName, s.SoftwareSystemType);
Very easy to use select option submit
<select name="sortby" onchange="this.form.submit()">
<option value="">Featured</option>
<option value="asc" >Price: Low to High</option>
<option value="desc">Price: High to Low</option>
</select>
This code use and enjoy now:
Read More: Go Link
new_dict = {x: v for x, v in mydict.items() if x in mykeys}
I am using red hat linux on a VPS server (and via SSH - putty), for me the following worked:
First, you list all the running processes:
ps -ef
Then in the first column you find your user name; I found it the following three times:
Then in the second column you can find the PID of the nohup process and you only type:
kill PID
(replacing the PID with the nohup process's PID of course)
And that is it!
I hope this answer will be useful for someone I'm also very new to bash and SSH, but found 95% of the knowledge I need here :)
I would just query for the for
attribute instead of repetitively recursing the DOM tree.
$("input:checkbox").on("change", function() {
$("label[for='"+this.id+"']").text("TESTTTT");
});
I created a project like you did. The structure looks like this
The Classes are just copy pasted from yours.
I changed the application.properties to this:
spring.datasource.url=jdbc:mysql://localhost/testproject
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
But I think your problem is in your pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
</parent>
<artifactId>spring-boot-sample-jpa</artifactId>
<name>Spring Boot JPA Sample</name>
<description>Spring Boot JPA Sample</description>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Check these files for differences. Hope this helps
Update 1: I changed my username. The link to the example is now https://github.com/Yannic92/stackOverflowExamples/tree/master/SpringBoot/MySQL
Don't do things like [A-Z] or [0-9]. Do \p{Lu} and \d instead. Of course, this is valid for perl based regex flavours. This includes java.
I would suggest that you don't make some huge regex. First split the text in sentences. then tokenize it (split into words). Use a regex to check each token/word. Skip the first token from sentence. Check if all tokens are uppercase beforehand and skip the whole sentence if so, or alter the regex in this case.
This work-around worked for me: http://connect.microsoft.com/PowerShell/feedback/details/419466/new-webserviceproxy-needs-force-parameter-to-ignore-ssl-errors
Basically, in your PowerShell script:
add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
$result = Invoke-WebRequest -Uri "https://IpAddress/resource"
Regarding the issue with 'size', size is not a function on a dataframe, it is rather a property. So instead of using size(), plain size should work
Apart from that, a method like this should work
def doCalculation(df):
groupCount = df.size
groupSum = df['my_labels'].notnull().sum()
return groupCount / groupSum
dataFrame.groupby('my_labels').apply(doCalculation)
git reflog
and back to the last HEAD
6a56624 (HEAD -> master) HEAD@{0}: reset: moving to HEAD~3
1a9bf73 HEAD@{1}: commit: add changes in model generate binary
Here are the all keycodes.
Here is a table with some keycodes for the three platforms. It is based on a US Extended keyboard layout.
http://web.archive.org/web/20100501161453/http://www.classicteck.com/rbarticles/mackeyboard.php
Or, there is an app in the Mac App Store named "Key Codes". Download it to see the keycodes of the keys you press.
Key Codes:
https://itunes.apple.com/tr/app/key-codes/id414568915?l=tr&mt=12
For those who want to easily rename their panes, this is what I have in my .tmux.conf
set -g default-command ' \
function renamePane () { \
read -p "Enter Pane Name: " pane_name; \
printf "\033]2;%s\033\\r:r" "${pane_name}"; \
}; \
export -f renamePane; \
bash -i'
set -g pane-border-status top
set -g pane-border-format "#{pane_index} #T #{pane_current_command}"
bind-key -T prefix R send-keys "renamePane" C-m
Panes are automatically named with their index, machine name and current command.
To change the machine name you can run <C-b>R
which will prompt you to enter a new name.
*Pane renaming only works when you are in a shell.
private void TurnOnAutocomplete()
{
textBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
textBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
AutoCompleteStringCollection collection = new AutoCompleteStringCollection();
string[] arrayOfWowrds = new string[];
try
{
//Read in data Autocomplete list to a string[]
string[] arrayOfWowrds = new string[];
}
catch (Exception err)
{
MessageBox.Show(err.Message, "File Missing", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
collection.AddRange(arrayOFWords);
textBox.AutoCompleteCustomSource = collection;
}
You only need to call this once after you have your data needed for the autocomplete list. Once bound it stays with the textBox. You do not need to or want to call it every time the text is changed in the textBox, that will kill your program.
You could use SET ANSI_NULLS
in order to specify the behavior of the Equals (=) and Not Equal To (<>) comparison operators when they are used with null values.
This Code May be Help you : [ Both maximizing and preventing resizing on a JFrame ]
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
frame.setResizable(false);
I used GENEGC's script, but I found it quite slow.
It is slow because it scans whole sheet on every edit.
So I wrote way faster and cleaner method for myself and I wanted to share it.
function onEdit(e) {
if (e) {
var ss = e.source.getActiveSheet();
var r = e.source.getActiveRange();
// If you want to be specific
// do not work in first row
// do not work in other sheets except "MySheet"
if (r.getRow() != 1 && ss.getName() == "MySheet") {
// E.g. status column is 2nd (B)
status = ss.getRange(r.getRow(), 2).getValue();
// Specify the range with which You want to highlight
// with some reading of API you can easily modify the range selection properties
// (e.g. to automatically select all columns)
rowRange = ss.getRange(r.getRow(),1,1,19);
// This changes font color
if (status == 'YES') {
rowRange.setFontColor("#999999");
} else if (status == 'N/A') {
rowRange.setFontColor("#999999");
// DEFAULT
} else if (status == '') {
rowRange.setFontColor("#000000");
}
}
}
}
\path-to-your-android-sdk-folder\platforms\android-xx\data\res
ng-show and ng-hide work in opposite way. But the difference between ng-hide or ng-show with ng-if is,if we use ng-if then element will created in the dom but with ng-hide/ng-show element will be hidden completely.
ng-show=true/ng-hide=false:
Element will be displayed
ng-show=false/ng-hide=true:
element will be hidden
ng-if =true
element will be created
ng-if= false
element will be created in the dom.
Scale can be used for both full data frame and specific columns. For specific columns, following code can be used:
trainingSet[, 3:7] = scale(trainingSet[, 3:7]) # For column 3 to 7
trainingSet[, 8] = scale(trainingSet[, 8]) # For column 8
Full data frame
trainingSet <- scale(trainingSet)
Try this command:
ALTER TABLE your_table ADD COLUMN key_column BIGSERIAL PRIMARY KEY;
Try it with the same DB-user as the one you have created the table.
It is purely a string:
startInfo.Arguments = "-sk server -sky exchange -pe -n CN=localhost -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyAdHocTestCert.cer"
Of course, when arguments contain whitespaces you'll have to escape them using \" \", like:
"... -ss \"My MyAdHocTestCert.cer\""
See MSDN for this.
I would like to explain the concepts from the perspective of JavaScript prototype inheritance. Hopefully help to understand.
There are three options to define the scope of a directive:
scope: false
: Angular default. The directive's scope is exactly the one of its parent scope (parentScope
).scope: true
: Angular creates a scope for this directive. The scope prototypically inherits from parentScope
.scope: {...}
: isolated scope is explained below. Specifying scope: {...}
defines an isolatedScope
. An isolatedScope
does not inherit properties from parentScope
, although isolatedScope.$parent === parentScope
. It is defined through:
app.directive("myDirective", function() {
return {
scope: {
... // defining scope means that 'no inheritance from parent'.
},
}
})
isolatedScope
does not have direct access to parentScope
. But sometimes the directive needs to communicate with the parentScope
. They communicate through @
, =
and &
. The topic about using symbols @
, =
and &
are talking about scenarios using isolatedScope
.
It is usually used for some common components shared by different pages, like Modals. An isolated scope prevents polluting the global scope and is easy to share among pages.
Here is a basic directive: http://jsfiddle.net/7t984sf9/5/. An image to illustrate is:
@
: one-way binding@
simply passes the property from parentScope
to isolatedScope
. It is called one-way binding
, which means you cannot modify the value of parentScope
properties. If you are familiar with JavaScript inheritance, you can understand these two scenarios easily:
If the binding property is a primitive type, like interpolatedProp
in the example: you can modify interpolatedProp
, but parentProp1
would not be changed. However, if you change the value of parentProp1
, interpolatedProp
will be overwritten with the new value (when angular $digest).
If the binding property is some object, like parentObj
: since the one passed to isolatedScope
is a reference, modifying the value will trigger this error:
TypeError: Cannot assign to read only property 'x' of {"x":1,"y":2}
=
: two-way binding=
is called two-way binding
, which means any modification in childScope
will also update the value in parentScope
, and vice versa. This rule works for both primitives and objects. If you change the binding type of parentObj
to be =
, you will find that you can modify the value of parentObj.x
. A typical example is ngModel
.
&
: function binding&
allows the directive to call some parentScope
function and pass in some value from the directive. For example, check JSFiddle: & in directive scope.
Define a clickable template in the directive like:
<div ng-click="vm.onCheck({valueFromDirective: vm.value + ' is from the directive'})">
And use the directive like:
<div my-checkbox value="vm.myValue" on-check="vm.myFunction(valueFromDirective)"></div>
The variable valueFromDirective
is passed from the directive to the parent controller through {valueFromDirective: ...
.
Reference: Understanding Scopes
There are a couple of things to consider.
If your growth is 0 for that month, it'd be 0 in change from 0. So it is meaningful in that sense. You could adjust by adding a small number, so it'd be change from 0.1 to 0.1. Then change and percentage change would be 0 and 0%.
Then to think about case where you change from 0 to 20. Such practice would result in massive reporting issues. Depending on what small number you choose to add, eg if you use 0.1 or 0.001, your percentage change would be 100 fold difference. So there is a problem with such practice.
It is possible however if you have a change from 1 to 20, then the %change would be 19/1=1900%. Here the % change doesn't make too much sense when you start off so low, it becomes very sensitive to any change and may skew your results if other data points are on different scale.
So it is important to understand your data, and in this case, how frequent you encounter 0s and extreme numbers in your data.
The values are determined by the bit of the image. 8 bit 0 to 255
16 bit...some ridiculous number..0 to 65,000 approx.
32 bit are 0 to 1
I use .004 with 32 bit images...this gives 1.02 as a result when multiplied by 255
Even though this is pretty old, just chiming in to say that what is useful in @Sidupac's answer is the FOREIGN_KEY_CHECKS=0
.
This answer is not an option when you are using something that manages the database schema for you (JPA in my case) but the problem may be that there are "orphaned" entries in your table (referencing a foreign key that might not exist).
This can often happen when you convert a MySQL table from MyISAM to InnoDB since referential integrity isn't really a thing with the former.
Try This
ImagePath = "http://localhost/profilepics/abc.png";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ImagePath);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
Rather than use Ajax / XMLHttpRequest / $http to invoke your WebApi method, use an html form. That way the browser saves the file using the filename and content type information in the response headers, and you don't need to work around javascript's limitations on file handling. You might also use a GET method rather than a POST as the method returns data. Here's an example form:
<form name="export" action="/MyController/Export" method="get" novalidate>
<input name="id" type="id" ng-model="id" placeholder="ID" />
<input name="fileName" type="text" ng-model="filename" placeholder="file name" required />
<span class="error" ng-show="export.fileName.$error.required">Filename is required!</span>
<button type="submit" ng-disabled="export.$invalid">Export</button>
</form>
After gone throug the various post, this worked fine for me doing on IntelliJ Idea
:
java -cp "./lib/*;Path to your test.class" org.testng.TestNG testng.xml
Here is my directory structure:
/lib
-- all jar including testng.jar
/out
--/production/Example1/test.class
/src
-- test.java
testing.xml
So execute by this command:
java -cp "./lib/*;C:\Users\xyz\IdeaProjects\Example1\out\production\Example1" org.testng.TestNG testng.xml
My project directory Example1
is in the path:
C:\Users\xyz\IdeaProjects\
HTML:
<div class="control-group">
<input class="btn" type="submit" value="Log in" ng-click="login.onSubmit($event)">
</div>
In your controller:
$scope.login = {
onSubmit: function(event) {
if (dataIsntValid) {
displayErrors();
event.preventDefault();
}
else {
submitData();
}
}
}
I was frustrated trying to connect my Android App to my RESTful service using https. Also I was a bit annoyed about all the answers that suggested to disable certificate checking altogether. If you do so, whats the point of https?
After googled about the topic for a while, I finally found this solution where external jars are not needed, just Android APIs. Thanks to Andrew Smith, who posted it on July, 2014
/**
* Set up a connection to myservice.domain using HTTPS. An entire function
* is needed to do this because myservice.domain has a self-signed certificate.
*
* The caller of the function would do something like:
* HttpsURLConnection urlConnection = setUpHttpsConnection("https://littlesvr.ca");
* InputStream in = urlConnection.getInputStream();
* And read from that "in" as usual in Java
*
* Based on code from:
* https://developer.android.com/training/articles/security-ssl.html#SelfSigned
*/
public static HttpsURLConnection setUpHttpsConnection(String urlString)
{
try
{
// Load CAs from an InputStream
// (could be from a resource or ByteArrayInputStream or ...)
CertificateFactory cf = CertificateFactory.getInstance("X.509");
// My CRT file that I put in the assets folder
// I got this file by following these steps:
// * Go to https://littlesvr.ca using Firefox
// * Click the padlock/More/Security/View Certificate/Details/Export
// * Saved the file as littlesvr.crt (type X.509 Certificate (PEM))
// The MainActivity.context is declared as:
// public static Context context;
// And initialized in MainActivity.onCreate() as:
// MainActivity.context = getApplicationContext();
InputStream caInput = new BufferedInputStream(MainActivity.context.getAssets().open("littlesvr.crt"));
Certificate ca = cf.generateCertificate(caInput);
System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
// Tell the URLConnection to use a SocketFactory from our SSLContext
URL url = new URL(urlString);
HttpsURLConnection urlConnection = (HttpsURLConnection)url.openConnection();
urlConnection.setSSLSocketFactory(context.getSocketFactory());
return urlConnection;
}
catch (Exception ex)
{
Log.e(TAG, "Failed to establish SSL connection to server: " + ex.toString());
return null;
}
}
It worked nice for my mockup App.
To undo: C-_
To redo after a undo: C-g C-_
Type multiple times on C-_ to redo what have been undone by C-_ To redo an emacs command multiple times, execute your command then type C-xz and then type many times on z key to repeat the command (interesting when you want to execute multiple times a macro)
Open xCode can be exhausting if you do it everytime, so you need to add this flag :
OR if you have build.json file at the root of your project, you must add this lines:
{
"ios": {
"debug": {
"buildFlag": [
"-UseModernBuildSystem=0"
]
},
"release": {
"buildFlag": [
"-UseModernBuildSystem=0"
]
}
}
}
Hope this will help in the future
As here str(u'\u2013')
is causing error so use isinstance(foo,basestring)
to check for unicode/string, if not of type base string convert it into Unicode and then apply encode
if isinstance(foo,basestring):
foo.encode('utf8')
else:
unicode(foo).encode('utf8')
If you want an alternative to pickle
or json
, you can use klepto
.
>>> init = {'y': 2, 'x': 1, 'z': 3}
>>> import klepto
>>> cache = klepto.archives.file_archive('memo', init, serialized=False)
>>> cache
{'y': 2, 'x': 1, 'z': 3}
>>>
>>> # dump dictionary to the file 'memo.py'
>>> cache.dump()
>>>
>>> # import from 'memo.py'
>>> from memo import memo
>>> print memo
{'y': 2, 'x': 1, 'z': 3}
With klepto
, if you had used serialized=True
, the dictionary would have been written to memo.pkl
as a pickled dictionary instead of with clear text.
You can get klepto
here: https://github.com/uqfoundation/klepto
dill
is probably a better choice for pickling then pickle
itself, as dill
can serialize almost anything in python. klepto
also can use dill
.
You can get dill
here: https://github.com/uqfoundation/dill
The additional mumbo-jumbo on the first few lines are because klepto
can be configured to store dictionaries to a file, to a directory context, or to a SQL database. The API is the same for whatever you choose as the backend archive. It gives you an "archivable" dictionary with which you can use load
and dump
to interact with the archive.