It does not seem like this one was mentioned yet.
http://thecommandline.net/ -- "Exploring the rough edges where technology, society and public policy meet."
He does a weekly News show and a weekly topics show.
From the website, Endorsement: "Thoughtful, informative, and deep, a real plunge into the geeky end of the news-pool. There's great analysis and rumination, as well as detailed explanations of important security issues with common OSes and so on." -- Cory Doctorow
In a for..of
loop we can achieve this via array.entries()
. array.entries
returns a new Array iterator object. An iterator object knows how to access items from an iterable one at the time, while keeping track of its current position within that sequence.
When the next()
method is called on the iterator key value pairs are generated. In these key value pairs the array index is the key and the array item is the value.
let arr = ['a', 'b', 'c'];_x000D_
let iterator = arr.entries();_x000D_
console.log(iterator.next().value); // [0, 'a']_x000D_
console.log(iterator.next().value); // [1, 'b']
_x000D_
A for..of
loop is basically a construct which consumes an iterable and loops through all elements (using an iterator under the hood). We can combine this with array.entries()
in the following manner:
array = ['a', 'b', 'c'];_x000D_
_x000D_
for (let indexValue of array.entries()) {_x000D_
console.log(indexValue);_x000D_
}_x000D_
_x000D_
_x000D_
// we can use array destructuring to conveniently_x000D_
// store the index and value in variables_x000D_
for (let [index, value] of array.entries()) {_x000D_
console.log(index, value);_x000D_
}
_x000D_
git log --grep=<pattern>
Limit the commits output to ones with log message that matches the
specified pattern (regular expression).
For those that have tried every answer to this question and are still scratching their heads as to why none of them work for you, you might have ran into a form of the issue I ran into.
My TextBlock.Text
property was inside of a ToolTipService.ToolTip
element and it was databound to a property of an object whose data was being pulled from a SQL stored procedure. Now the data from this particular property within the stored procedure was being pulled from a SQL function.
Since nothing had worked for me, I gave up my search and created the converter class below:
public class NewLineConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var s = string.Empty;
if (value.IsNotNull())
{
s = value.ToString();
if (s.Contains("\\r\\n"))
s = s.Replace("\\r\\n", Environment.NewLine);
if (s.Contains("\\n"))
s = s.Replace("\\n", Environment.NewLine);
if (s.Contains("

"))
s = s.Replace("

", Environment.NewLine);
if (s.Contains("
"))
s = s.Replace("
", Environment.NewLine);
if (s.Contains("
"))
s = s.Replace("
", Environment.NewLine);
if (s.Contains(" "))
s = s.Replace(" ", Environment.NewLine);
if (s.Contains(" "))
s = s.Replace(" ", Environment.NewLine);
if (s.Contains(" "))
s = s.Replace(" ", Environment.NewLine);
if (s.Contains("<br />"))
s = s.Replace("<br />", Environment.NewLine);
if (s.Contains("<LineBreak />"))
s = s.Replace("<LineBreak />", Environment.NewLine);
}
return s;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
I ended up having to use the Enivornment.NewLine
method from @dparker's answer. I instructed the converter to look for any possible textual representation of a newline and replace it with Environment.NewLine
.
This worked!
However, I was still perplexed as to why none of the other methods worked with databound properties.
I left a comment on @BobKing's accepted answer:
@BobKing - This doesn't seem to work in the ToolTipService.ToolTip when binding to a field that has the line feeds embedded from a SQL sproc.
He replied with:
@CodeMaverick If you're binding to text with the new lines embedded, they should probably be real char 10 values (or 13's) and not the XML sentinels. This is only if you want to write literal new lines in XAML files.
A light bulb went off!
I went into my SQL function, replaced my textual representations of newlines with ...
CHAR( 13 ) + CHAR( 10 )
... removed the converter from my TextBlock.Text
binding, and just like that ... it worked!
Don't forget also that the path for the file is on the actual oracle server machine and not any local development machine that might be calling your stored procedure. This is probably very obvious but something that should be remembered.
Excerpted from Josh Stodola's Setting keyboard caret Position in a Textbox or TextArea with Javascript
A generic function that will allow you to insert the caret at any position of a textbox or textarea that you wish:
function setCaretPosition(elemId, caretPos) {
var elem = document.getElementById(elemId);
if(elem != null) {
if(elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
}
else {
if(elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
}
else
elem.focus();
}
}
}
The first expected parameter is the ID of the element you wish to insert the keyboard caret on. If the element is unable to be found, nothing will happen (obviously). The second parameter is the caret positon index. Zero will put the keyboard caret at the beginning. If you pass a number larger than the number of characters in the elements value, it will put the keyboard caret at the end.
Tested on IE6 and up, Firefox 2, Opera 8, Netscape 9, SeaMonkey, and Safari. Unfortunately on Safari it does not work in combination with the onfocus event).
An example of using the above function to force the keyboard caret to jump to the end of all textareas on the page when they receive focus:
function addLoadEvent(func) {
if(typeof window.onload != 'function') {
window.onload = func;
}
else {
if(func) {
var oldLoad = window.onload;
window.onload = function() {
if(oldLoad)
oldLoad();
func();
}
}
}
}
// The setCaretPosition function belongs right here!
function setTextAreasOnFocus() {
/***
* This function will force the keyboard caret to be positioned
* at the end of all textareas when they receive focus.
*/
var textAreas = document.getElementsByTagName('textarea');
for(var i = 0; i < textAreas.length; i++) {
textAreas[i].onfocus = function() {
setCaretPosition(this.id, this.value.length);
}
}
textAreas = null;
}
addLoadEvent(setTextAreasOnFocus);
I also wouldn't call two many (is_a?
and kind_of?
are aliases of the same method), but if you want to see more possibilities, turn your attention to #class
method:
A = Class.new
B = Class.new A
a, b = A.new, B.new
b.class < A # true - means that b.class is a subclass of A
a.class < B # false - means that a.class is not a subclass of A
# Another possibility: Use #ancestors
b.class.ancestors.include? A # true - means that b.class has A among its ancestors
a.class.ancestors.include? B # false - means that B is not an ancestor of a.class
The top rated solutions didn't seem to work for me. My solution is below:
brew uninstall nvm
brew install nvm
In Terminal, follow the steps below(these are also listed when installing nvm via homebrew):
mkdir ~/.nvm cp $(brew --prefix nvm)/nvm-exec ~/.nvm/ export NVM_DIR=~/.nvm source $(brew --prefix nvm)/nvm.sh
The steps outlined above will add NVM's working directory to your $HOME path, copy nvm-exec to NVM's working directory and add to $HOME/.bashrc, $HOME/.zshrc, or your shell's equivalent configuration file.(again taken from whats listed on an NVM install using homebrew)
Use the constructor that takes a File
and a boolean
FileOutputStream(File file, boolean append)
and set the boolean to true
. That way, the data you write will be appended to the end of the file, rather than overwriting what was already there.
The amount of "neurons", or "cells", or whatever the layer has inside it.
It's a property of each layer, and yes, it's related to the output shape (as we will see later). In your picture, except for the input layer, which is conceptually different from other layers, you have:
Shapes are consequences of the model's configuration. Shapes are tuples representing how many elements an array or tensor has in each dimension.
Ex: a shape (30,4,10)
means an array or tensor with 3 dimensions, containing 30 elements in the first dimension, 4 in the second and 10 in the third, totaling 30*4*10 = 1200 elements or numbers.
What flows between layers are tensors. Tensors can be seen as matrices, with shapes.
In Keras, the input layer itself is not a layer, but a tensor. It's the starting tensor you send to the first hidden layer. This tensor must have the same shape as your training data.
Example: if you have 30 images of 50x50 pixels in RGB (3 channels), the shape of your input data is (30,50,50,3)
. Then your input layer tensor, must have this shape (see details in the "shapes in keras" section).
Each type of layer requires the input with a certain number of dimensions:
Dense
layers require inputs as (batch_size, input_size)
(batch_size, optional,...,optional, input_size)
channels_last
: (batch_size, imageside1, imageside2, channels)
channels_first
: (batch_size, channels, imageside1, imageside2)
(batch_size, sequence_length, features)
Now, the input shape is the only one you must define, because your model cannot know it. Only you know that, based on your training data.
All the other shapes are calculated automatically based on the units and particularities of each layer.
Given the input shape, all other shapes are results of layers calculations.
The "units" of each layer will define the output shape (the shape of the tensor that is produced by the layer and that will be the input of the next layer).
Each type of layer works in a particular way. Dense layers have output shape based on "units", convolutional layers have output shape based on "filters". But it's always based on some layer property. (See the documentation for what each layer outputs)
Let's show what happens with "Dense" layers, which is the type shown in your graph.
A dense layer has an output shape of (batch_size,units)
. So, yes, units, the property of the layer, also defines the output shape.
(batch_size,4)
. (batch_size,4)
. (batch_size,1)
. Weights will be entirely automatically calculated based on the input and the output shapes. Again, each type of layer works in a certain way. But the weights will be a matrix capable of transforming the input shape into the output shape by some mathematical operation.
In a dense layer, weights multiply all inputs. It's a matrix with one column per input and one row per unit, but this is often not important for basic works.
In the image, if each arrow had a multiplication number on it, all numbers together would form the weight matrix.
Earlier, I gave an example of 30 images, 50x50 pixels and 3 channels, having an input shape of (30,50,50,3)
.
Since the input shape is the only one you need to define, Keras will demand it in the first layer.
But in this definition, Keras ignores the first dimension, which is the batch size. Your model should be able to deal with any batch size, so you define only the other dimensions:
input_shape = (50,50,3)
#regardless of how many images I have, each image has this shape
Optionally, or when it's required by certain kinds of models, you can pass the shape containing the batch size via batch_input_shape=(30,50,50,3)
or batch_shape=(30,50,50,3)
. This limits your training possibilities to this unique batch size, so it should be used only when really required.
Either way you choose, tensors in the model will have the batch dimension.
So, even if you used input_shape=(50,50,3)
, when keras sends you messages, or when you print the model summary, it will show (None,50,50,3)
.
The first dimension is the batch size, it's None
because it can vary depending on how many examples you give for training. (If you defined the batch size explicitly, then the number you defined will appear instead of None
)
Also, in advanced works, when you actually operate directly on the tensors (inside Lambda layers or in the loss function, for instance), the batch size dimension will be there.
input_shape=(50,50,3)
(30,50,50,3)
(None,50,50,3)
or (30,50,50,3)
, depending on what type of message it sends you. And in the end, what is dim
?
If your input shape has only one dimension, you don't need to give it as a tuple, you give input_dim
as a scalar number.
So, in your model, where your input layer has 3 elements, you can use any of these two:
input_shape=(3,)
-- The comma is necessary when you have only one dimension input_dim = 3
But when dealing directly with the tensors, often dim
will refer to how many dimensions a tensor has. For instance a tensor with shape (25,10909) has 2 dimensions.
Keras has two ways of doing it, Sequential
models, or the functional API Model
. I don't like using the sequential model, later you will have to forget it anyway because you will want models with branches.
PS: here I ignored other aspects, such as activation functions.
With the Sequential model:
from keras.models import Sequential
from keras.layers import *
model = Sequential()
#start from the first hidden layer, since the input is not actually a layer
#but inform the shape of the input, with 3 elements.
model.add(Dense(units=4,input_shape=(3,))) #hidden layer 1 with input
#further layers:
model.add(Dense(units=4)) #hidden layer 2
model.add(Dense(units=1)) #output layer
With the functional API Model:
from keras.models import Model
from keras.layers import *
#Start defining the input tensor:
inpTensor = Input((3,))
#create the layers and pass them the input tensor to get the output tensor:
hidden1Out = Dense(units=4)(inpTensor)
hidden2Out = Dense(units=4)(hidden1Out)
finalOut = Dense(units=1)(hidden2Out)
#define the model's start and end points
model = Model(inpTensor,finalOut)
Shapes of the tensors
Remember you ignore batch sizes when defining layers:
(None,3)
(None,4)
(None,4)
(None,1)
Example with preloader Dotnet 3.0 Core
ProgressMessageHandler processMessageHander = new ProgressMessageHandler();
processMessageHander.HttpSendProgress += (s, e) =>
{
if (e.ProgressPercentage > 0)
{
ProgressPercentage = e.ProgressPercentage;
TotalBytes = e.TotalBytes;
progressAction?.Invoke(progressFile);
}
};
using (var client = HttpClientFactory.Create(processMessageHander))
{
var uri = new Uri(transfer.BackEndUrl);
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", AccessToken);
using (MultipartFormDataContent multiForm = new MultipartFormDataContent())
{
multiForm.Add(new StringContent(FileId), "FileId");
multiForm.Add(new StringContent(FileName), "FileName");
string hash = "";
using (MD5 md5Hash = MD5.Create())
{
var sb = new StringBuilder();
foreach (var data in md5Hash.ComputeHash(File.ReadAllBytes(FullName)))
{
sb.Append(data.ToString("x2"));
}
hash = result.ToString();
}
multiForm.Add(new StringContent(hash), "Hash");
using (FileStream fs = File.OpenRead(FullName))
{
multiForm.Add(new StreamContent(fs), "file", Path.GetFileName(FullName));
var response = await client.PostAsync(uri, multiForm);
progressFile.Message = response.ToString();
if (response.IsSuccessStatusCode) {
progressAction?.Invoke(progressFile);
} else {
progressErrorAction?.Invoke(progressFile);
}
response.EnsureSuccessStatusCode();
}
}
}
Instead of converting each date, you can use the following code:
long difference = (sDt4.getTime() - sDt3.getTime()) / 1000;
System.out.println(difference);
And then see that the result is:
1
Try this:
CGFloat statusBarHeight = [[UIApplication sharedApplication] statusBarFrame].size.height;
Simple sorting algorithm Bubble sort:
public static void main(String[] args) {
int[] arr = new int[] { 6, 8, 7, 4, 312, 78, 54, 9, 12, 100, 89, 74 };
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
int tmp = 0;
if (arr[i] > arr[j]) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
}
The easiest one,
$('#location').find('option:selected').attr('myTag');
OK, finally got it working: see https://github.com/angular/angular/pull/10314#issuecomment-242218563
In brief, you can no longer use name
attribute within a formGroup
, and must use formControlName
instead
s.strip() you can use from java 11 onwards.
s.trim() you can use.
To print your context ,you can write code like this :
FILE *fp;
char *of;
sprintf(of,"%s%s",text1,text2);
fp=fopen(of,'w');
fprintf(fp,"your print line");
Do as below using String#tr
:
"((String1))".tr('()', '')
# => "String1"
This will get ALL parameters from the request. For Debugging purposes only:
@RequestMapping (value = "/promote", method = {RequestMethod.POST, RequestMethod.GET})
public ModelAndView renderPromotePage (HttpServletRequest request) {
Map<String, String[]> parameters = request.getParameterMap();
for(String key : parameters.keySet()) {
System.out.println(key);
String[] vals = parameters.get(key);
for(String val : vals)
System.out.println(" -> " + val);
}
ModelAndView mv = new ModelAndView();
mv.setViewName("test");
return mv;
}
HashMap
implements Serializable
so you can use normal serialization to write hashmap to file
Here is the link for Java - Serialization example
I had this problem, it is for foreign-key
Click on the Relation View
(like the image below) then find name of the field you are going to remove it, and under the Foreign key constraint (INNODB)
column, just put the select to nothing! Means no foreign-key
Hope that works!
Java does not have pointers like C has, but it does allow you to create new objects on the heap which are "referenced" by variables. The lack of pointers is to stop Java programs from referencing memory locations illegally, and also enables Garbage Collection to be automatically carried out by the Java Virtual Machine.
I had a similar issue with Intellij. The issue was that someone added the file that I am trying to compare in Intellij to .gitignore, without actually deleting the file from Git.
I didnt know about css3pie.com, a very useful site after seeing this post:
But what after testing it out it didnt work for me either. However I found that wrapping it in the .PHP file worked fine. So instead of:
behavior: url(PIE.htc);
use this:
behavior: url(PIE.php);
I put mine in a folder called jquery, so mine was:
behavior: url(jquery/PIE.php);
So goto their downloads or get it here:
http://css3pie.com/download-latest
And use their PHP file. Inside the PHP file it explains that some servers are not configured for proper .HTC usage. And that was the problem I had.
Try it! I did, it works. Hope this helps others out too.
If you are simply looking for the occurrence of "Miami" or "Florida" inside a string (since you put * at both ends), it's probably better to use the InStr function instead of Like. Not only are the results more predictable, but I believe you'll get better performance.
Also, VBA is not short-circuited so when you use the AND keyword, it will test both sides of the AND, regardless if the first test failed or not. In VBA, it is more optimal to use 2 if-statements in these cases, that way you aren't checking for "Florida" if you don't find "Miami".
The other advice I have is that a for-each loop is faster than a for-loop. Using .offset, you can achieve the same thing, but with better effeciency. Of course there are even better ways (like variant arrays), but those will add a layer of complexity not needed in this example.
Here is some sample code:
Sub test()
Application.ScreenUpdating = False
Dim lastRow As Long
Dim cell As Range
lastRow = Range("A" & Rows.Count).End(xlUp).Row
For Each cell In Range("A1:A" & lastRow)
If InStr(1, cell.Value, "Miami") <> 0 Then
If InStr(1, cell.Offset(, 3).Value, "Florida") <> 0 Then
cell.Offset(, 2).Value = "BA"
End If
End If
Next
Application.ScreenUpdating = True
End Sub
I hope you find some of this helpful, and keep at it with VBA! ^^
If I understand you correctly, you need to use -SearchBase:
Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *
Note that Get-ADUser defaults to using
-SearchScope Subtree
so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).
If you want to reset bootstrap page with button click using jQuery :
function resetForm(){
var validator = $( "#form_ID" ).validate();
validator.resetForm();
}
Using above code you also have change the field colour as red to normal.
If you want to reset only fielded value then :
$("#form_ID")[0].reset();
KEY
is normally a synonym for INDEX
. The key attribute PRIMARY KEY
can also be specified as just KEY
when given in a column definition. This was implemented for compatibility with other database systems.
column_definition:
data_type [NOT NULL | NULL] [DEFAULT default_value]
[AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY]
...
Ref: http://dev.mysql.com/doc/refman/5.1/en/create-table.html
The limitations of a 32-bit JVM on a 64-bit OS will be exactly the same as the limitations of a 32-bit JVM on a 32-bit OS. After all, the 32-bit JVM will be running In a 32-bit virtual machine (in the virtualization sense) so it won't know that it's running on a 64-bit OS/machine.
The one advantage to running a 32-bit JVM on a 64-bit OS versus a 32-bit OS is that you can have more physical memory, and therefore will encounter swapping/paging less frequently. This advantage is only really fully realized when you have multiple processes, however.
You will have to use cookie to store the value across page refresh. You can use any one of the many javascript based cookie libraries to simplify the cookie access, like this one
If you want to support only html5 then you can think of Storage api like localStorage/sessionStorage
Ex: using localStorage and cookies library
var mode = getStoredValue('myPageMode');
function buttonClick(mode) {
mode = mode;
storeValue('myPageMode', mode);
}
function storeValue(key, value) {
if (localStorage) {
localStorage.setItem(key, value);
} else {
$.cookies.set(key, value);
}
}
function getStoredValue(key) {
if (localStorage) {
return localStorage.getItem(key);
} else {
return $.cookies.get(key);
}
}
This is probably due to CORS (or not quoting paths) and is expected behaviour. I know it sounds confusing, but the reason is due to the source of your fonts and not the web page itself.
A good explanation and numerous solutions for Apache, NGINX, IIS or PHP available in multiple languages can be found here:
https://www.hirehop.com/blog/cross-domain-fonts-cors-font-face-issue/
Per this link:
the symptom could occur if the replication service tries to use the ports that occupied by others, or by a malfunction NIC. Please try the following steps:
Reduce() is..
It was ..
let array=[1,2,3];
function sum(acc,val){ return acc+val;} // => can change to (acc,val)=>acc+val
let answer= array.reduce(sum); // answer is 6
Change to
let array=[1,2,3];
let answer=arrays.reduce((acc,val)=>acc+val);
Also you can use in
let array=[5,4,19,2,7];
function findMax(acc,val)
{
if(val>acc){
acc=val;
}
}
let biggest=arrays.reduce(findMax); // 19
arr = [1, 2, 5, 4, 6, 8, 9, 2, 1, 4, 5, 8, 9]
v = 0
for i in range(len(arr)):
v = v ^ arr[i]
print(value) //6
boolean turnedOn;
if(turnedOn)
{
//do stuff when the condition is true - i.e, turnedOn is true
}
else
{
//do stuff when the condition is false - i.e, turnedOn is false
}
Install virtualenv locally (source of instructions):
Important: Insert the current release (like 16.1.0) for X.X.X.
Check the name of the extracted file and insert it for YYYYY.
$ curl -L -o virtualenv.tar.gz https://github.com/pypa/virtualenv/tarball/X.X.X
$ tar xfz virtualenv.tar.gz
$ python pypa-virtualenv-YYYYY/src/virtualenv.py env
Before you can use or install any package you need to source
your virtual Python environment env
:
$ source env/bin/activate
To install new python packages (like numpy), use:
(env)$ pip install <package>
The way you have used the HTML syntax is problematic.
This is how the syntax should be
style="property1:value1;property2:value2"
In your case, this will be the way to do
<h2 style="text-align :center; font-family :tahoma" >TITLE</h2>
A further example would be as follows
<div class ="row">
<button type="button" style= "margin-top : 20px; border-radius: 15px"
class="btn btn-primary">View Full Profile</button>
</div>
I was receiving this notice for doing this:
$var = reset($myClass->my_magic_property);
This fixed it:
$tmp = $myClass->my_magic_property;
$var = reset($tmp);
It looks like you're using python 3.x. In python3, filter
, map
, zip
, etc return an object which is iterable, but not a list. In other words,
filter(func,data) #python 2.x
is equivalent to:
list(filter(func,data)) #python 3.x
I think it was changed because you (often) want to do the filtering in a lazy sense -- You don't need to consume all of the memory to create a list up front, as long as the iterator returns the same thing a list would during iteration.
If you're familiar with list comprehensions and generator expressions, the above filter is now (almost) equivalent to the following in python3.x:
( x for x in data if func(x) )
As opposed to:
[ x for x in data if func(x) ]
in python 2.x
You need to be at MySQL version 5.6.4 or later to declare columns with fractional-second time datatypes. Not sure you have the right version? Try SELECT NOW(3)
. If you get an error, you don't have the right version.
For example, DATETIME(3)
will give you millisecond resolution in your timestamps, and TIMESTAMP(6)
will give you microsecond resolution on a *nix-style timestamp.
Read this: https://dev.mysql.com/doc/refman/8.0/en/fractional-seconds.html
NOW(3)
will give you the present time from your MySQL server's operating system with millisecond precision.
If you have a number of milliseconds since the Unix epoch, try this to get a DATETIME(3) value
FROM_UNIXTIME(ms * 0.001)
Javascript timestamps, for example, are represented in milliseconds since the Unix epoch.
(Notice that MySQL internal fractional arithmetic, like * 0.001
, is always handled as IEEE754 double precision floating point, so it's unlikely you'll lose precision before the Sun becomes a white dwarf star.)
If you're using an older version of MySQL and you need subsecond time precision, your best path is to upgrade. Anything else will force you into doing messy workarounds.
If, for some reason you can't upgrade, you could consider using BIGINT
or DOUBLE
columns to store Javascript timestamps as if they were numbers. FROM_UNIXTIME(col * 0.001)
will still work OK. If you need the current time to store in such a column, you could use UNIX_TIMESTAMP() * 1000
If you add height in .wrapper
class then your scroll is working, without height
scroll is not working.
Try this http://jsfiddle.net/ZcrFr/3/
CSS:
.wrapper {
position: relative;
overflow: scroll;
width: 1000px;
height: 800px;
}
//C# class
public class DashBoardViewModel
{
public int Id { get; set;}
public decimal TotalSales { get; set;}
public string Url { get; set;}
public string MyDate{ get; set;}
}
//JavaScript file
//Create dashboard.js file
$(document).ready(function () {
// See the html on the View below
$('.dashboardUrl').on('click', function(){
var url = $(this).attr("href");
});
$("#inpDateCompleted").change(function () {
// Construct your view model to send to the controller
// Pass viewModel to ajax function
// Date
var myDate = $('.myDate').val();
// IF YOU USE @Html.EditorFor(), the myDate is as below
var myDate = $('#MyDate').val();
var viewModel = { Id : 1, TotalSales: 50, Url: url, MyDate: myDate };
$.ajax({
type: 'GET',
dataType: 'json',
cache: false,
url: '/Dashboard/IndexPartial',
data: viewModel ,
success: function (data, textStatus, jqXHR) {
//Do Stuff
$("#DailyInvoiceItems").html(data.Id);
},
error: function (jqXHR, textStatus, errorThrown) {
//Do Stuff or Nothing
}
});
});
});
//ASP.NET 5 MVC 6 Controller
public class DashboardController {
[HttpGet]
public IActionResult IndexPartial(DashBoardViewModel viewModel )
{
// Do stuff with my model
var model = new DashBoardViewModel { Id = 23 /* Some more results here*/ };
return Json(model);
}
}
// MVC View
// Include jQuerylibrary
// Include dashboard.js
<script src="~/Scripts/jquery-2.1.3.js"></script>
<script src="~/Scripts/dashboard.js"></script>
// If you want to capture your URL dynamically
<div>
<a class="dashboardUrl" href ="@Url.Action("IndexPartial","Dashboard")"> LinkText </a>
</div>
<div>
<input class="myDate" type="text"/>
//OR
@Html.EditorFor(model => model.MyDate)
</div>
I have solved it with Dov Benjamin's help like that:
<ul>
<li v-for="(n,index) in 2">{{ object.price }}</li>
</ul>
And another method, for both V1.x and 2.x of vue.js
Vue 1:
<p v-for="item in items | limitBy 10">{{ item }}</p>
Vue2:
// Via slice method in computed prop
<p v-for="item in filteredItems">{{ item }}</p>
computed: {
filteredItems: function () {
return this.items.slice(0, 10)
}
}
Try this...
SELECT
AlarmEventTransactionTableTable.TxnID,
CASE
WHEN DeviceID IN('7', '10', '62', '58', '60',
'46', '48', '50', '137', '139',
'142', '143', '164') THEN '01'
WHEN DeviceID IN('8', '9', '63', '59', '61',
'47', '49', '51', '138', '140',
'141', '144', '165') THEN '02'
ELSE 'NA' END AS clocking,
AlarmEventTransactionTable.DateTimeOfTxn
FROM
multiMAXTxn.dbo.AlarmEventTransactionTable
Just remove highlighted string
SELECT AlarmEventTransactionTableTable.TxnID, CASE AlarmEventTransactions.DeviceID WHEN DeviceID IN('7', '10', '62', '58', '60', ...)
Here's another way that might be faster, in terms of compute time, than iterating. Not sure. The idea is to convert the array to a string, truncate it, and get the size of the new array.
For example, to find the index of 'd':
arr=(a b c d)
temp=`echo ${arr[@]}`
temp=( ${temp%%d*} )
index=${#temp[@]}
You could turn this into a function like:
get-index() {
Item=$1
Array="$2[@]"
ArgArray=( ${!Array} )
NewArray=( ${!Array%%${Item}*} )
Index=${#NewArray[@]}
[[ ${#ArgArray[@]} == ${#NewArray[@]} ]] && echo -1 || echo $Index
}
You could then call:
get-index d arr
and it would echo back 3, which would be assignable with:
index=`get-index d arr`
Even better than Ran's suggestion of using GetProcAddress
, simply make the call to LoadLibrary
before any calls to the DllImport
functions (with only a filename without a path) and they'll use the loaded module automatically.
I've used this method to choose at runtime whether to load a 32-bit or 64-bit native DLL without having to modify a bunch of P/Invoke-d functions. Stick the loading code in a static constructor for the type that has the imported functions and it'll all work fine.
I checked the git checkout documentation, it revealed one interesting thing:
git checkout -b <new_branch_name> <start_point> , where the <start_point> is the name of a commit at which to start the new branch; Defaults to HEAD
So we can mention the tag name( as tag is nothing but a name of a commit) as, say:
>> git checkout -b 1.0.2_branch 1.0.2
later, modify some files
>> git push --tags
P.S: In Git, you can't update a tag directly(since tag is just a label to a commit), you need to checkout the same tag as a branch and then commit to it and then create a separate tag.
You forgot the namespace you're referring to. Add
using namespace std;
to avoid std::string all the time.
In Expression Language you can just use the ==
or eq
operator to compare object values. Behind the scenes they will actually use the Object#equals()
. This way is done so, because until with the current EL 2.1 version you cannot invoke methods with other signatures than standard getter (and setter) methods (in the upcoming EL 2.2 it would be possible).
So the particular line
<c:when test="${lang}.equals(${pageLang})">
should be written as (note that the whole expression is inside the {
and }
)
<c:when test="${lang == pageLang}">
or, equivalently
<c:when test="${lang eq pageLang}">
Both are behind the scenes roughly interpreted as
jspContext.findAttribute("lang").equals(jspContext.findAttribute("pageLang"))
If you want to compare constant String
values, then you need to quote it
<c:when test="${lang == 'en'}">
or, equivalently
<c:when test="${lang eq 'en'}">
which is behind the scenes roughly interpreted as
jspContext.findAttribute("lang").equals("en")
You mean JavaScript? Just output it like anything else in the page:
<script type="text/javascript">
<?php echo "alert('message');"; ?>
</script>
If want PHP to generate a custom message for the alert dialog, then basically you want to write your JavaScript as usual in the HTML, but insert PHP echo statements in the middle of your JavaScript where you want the messages, like:
<script type="text/javascript">
alert('<?php echo $custom_message; ?>');
</script>
Or you could even do something like this:
<script type="text/javascript">
var alertMsg = '<?php echo $custom_message; ?>';
alert(alertMsg);
</script>
Basically, think about where in your JavaScript you want PHP to generate dynamic output and just put an echo statement there.
I do not recall my original use case for this mechanism. Nowadays, I cannot think of any valid use case.
Your client should be able to detect when the connection is lost and allow you to re-create the connection. If it important that part of program logic is executed using the same connection, then use transactions.
tl;dr; Do not use this method.
A pragmatic solution is to force MySQL to keep the connection alive:
setInterval(function () {
db.query('SELECT 1');
}, 5000);
I prefer this solution to connection pool and handling disconnect because it does not require to structure your code in a way thats aware of connection presence. Making a query every 5 seconds ensures that the connection will remain alive and PROTOCOL_CONNECTION_LOST
does not occur.
Furthermore, this method ensures that you are keeping the same connection alive, as opposed to re-connecting. This is important. Consider what would happen if your script relied on LAST_INSERT_ID()
and mysql connection have been reset without you being aware about it?
However, this only ensures that connection time out (wait_timeout
and interactive_timeout
) does not occur. It will fail, as expected, in all others scenarios. Therefore, make sure to handle other errors.
It may not be the most common git server setup, but having played with different layouts, tools, mirroring and permission schemes, I'd say one pretty solid alternative for enterprise repositories is Gerrit, which may seem surprising as it is more known as a code review tool. We started using it as code review and it slowly became our main repository, deprecating g3/gitolite
In addition, it's used by large projects (e.g. android, chrome) so it does scales and is now fairly solid. Just give your users the PUSH permission if you want to allow bypassing the code review part.
It looks like Google actively frowns on using IP-to-location mapping:
https://developers.google.com/maps/articles/geolocation?hl=en
That article encourages using the W3C geolocation API. I was a little skeptical, but it looks like almost every major browser already supports the geolocation API:
I'm not sure if there is but if there was such a property it wouldn't be considered reliable. A WebException
can be fired for reasons other than HTTP error codes including simple networking errors. Those have no such matching http error code.
Can you give us a bit more info on what you're trying to accomplish with that code. There may be a better way to get the information you need.
I wrote a helper function to enumerate an enum:
static getEnumValues<T extends number>(enumType: {}): T[] {
const values: T[] = [];
const keys = Object.keys(enumType);
for (const key of keys.slice(0, keys.length / 2)) {
values.push(<T>+key);
}
return values;
}
Usage:
for (const enumValue of getEnumValues<myEnum>(myEnum)) {
// do the thing
}
The function returns something that can be easily enumerated, and also casts to the enum type.
Yes it is, none of the Visual Stdio editions have C mentioned, but it is included with the C++ compiler (you therefore need to look under C++). The main difference between using C and C++ is the naming system (i.e. using .c and not .cpp).
You do have to be careful not to create a C++ project and rename it to C though, that does not work.
Much like you can use gcc
on Linux (or if you have MinGW installed) Visual Studio has a command to be used from command prompt (it must be the Visual Studio Developer Command Prompt though). As mentioned in the other answer you can use cl
to compile your c file (make sure it is named .c)
Example:
cl myfile.c
Or to check all the accepted commands:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Community>cl
Microsoft (R) C/C++ Optimizing Compiler Version 19.16.27030.1 for x86
Copyright (C) Microsoft Corporation. All rights reserved.
usage: cl [ option... ] filename... [ /link linkoption... ]
C:\Program Files (x86)\Microsoft Visual Studio\2017\Community>
Without doubt one of the best features of Visual Studio is the convenient IDE.
Although it takes more configuring, you get bonuses such as basic debugging before compiling (for example if you forget a ;
)
To create a C project do the following:
Start a new project, go under C++ and select Empty Project
, enter the Name
of your project and the Location
you want it to install to, then click Ok
. Now wait for the project to be created.
Next under Solutions Explorer
right click Source Files
, select Add
then New Item
. You should see something like this:
Rename Source.cpp
to include a .c
extension (Source.c
for example). Select the location you want to keep it in, I would recommend always keeping it within the project folder itself (in this case C:\Users\Simon\Desktop\Learn\My First C Code
)
It should open up the .c
file, ready to be modified. Visual Studio can now be used as normal, happy coding!
you can use ssl for your host there is free project for ssl like letsencrypt https://letsencrypt.org/
Your script could be stopping, not because of the PHP timeout but because of the timeout in the browser you're using to access the script (ie. Firefox, Chrome, etc). Unfortunately there's seldom an easy way to extend this timeout, and in most browsers you simply can't. An option you have here is to access the script over a terminal. For example, on Windows you would make sure the PHP executable is in your path variable and then I think you execute:
C:\path\to\script> php script.php
Or, if you're using the PHP CGI, I think it's:
C:\path\to\script> php-cgi script.php
Plus, you would also set ini_set('max_execution_time', 0);
in your script as others have mentioned. When running a PHP script this way, I'm pretty sure you can use buffer flushing to echo out the script's progress to the terminal periodically if you wish. The biggest issue I think with this method is there's really no way of stopping the script once it's started, other than stopping the entire PHP process or service.
moment(timestamp).format('''any format''')
Do not use authorization instead of authentication. I should get whole access to service all clients with header. The working code is :
public class TokenAuthenticationHandler : AuthenticationHandler<TokenAuthenticationOptions>
{
public IServiceProvider ServiceProvider { get; set; }
public TokenAuthenticationHandler (IOptionsMonitor<TokenAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IServiceProvider serviceProvider)
: base (options, logger, encoder, clock)
{
ServiceProvider = serviceProvider;
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync ()
{
var headers = Request.Headers;
var token = "X-Auth-Token".GetHeaderOrCookieValue (Request);
if (string.IsNullOrEmpty (token)) {
return Task.FromResult (AuthenticateResult.Fail ("Token is null"));
}
bool isValidToken = false; // check token here
if (!isValidToken) {
return Task.FromResult (AuthenticateResult.Fail ($"Balancer not authorize token : for token={token}"));
}
var claims = new [] { new Claim ("token", token) };
var identity = new ClaimsIdentity (claims, nameof (TokenAuthenticationHandler));
var ticket = new AuthenticationTicket (new ClaimsPrincipal (identity), this.Scheme.Name);
return Task.FromResult (AuthenticateResult.Success (ticket));
}
}
Startup.cs :
#region Authentication
services.AddAuthentication (o => {
o.DefaultScheme = SchemesNamesConst.TokenAuthenticationDefaultScheme;
})
.AddScheme<TokenAuthenticationOptions, TokenAuthenticationHandler> (SchemesNamesConst.TokenAuthenticationDefaultScheme, o => { });
#endregion
And mycontroller.cs
[Authorize(AuthenticationSchemes = SchemesNamesConst.TokenAuthenticationDefaultScheme)]
public class MainController : BaseController
{ ... }
I can't find TokenAuthenticationOptions now, but it was empty. I found the same class PhoneNumberAuthenticationOptions :
public class PhoneNumberAuthenticationOptions : AuthenticationSchemeOptions
{
public Regex PhoneMask { get; set; }// = new Regex("7\\d{10}");
}
You should define static class SchemesNamesConst
. Something like:
public static class SchemesNamesConst
{
public const string TokenAuthenticationDefaultScheme = "TokenAuthenticationScheme";
}
The following signature will do:
List<Email> findByEmailIdInAndPincodeIn(List<String> emails, List<String> pinCodes);
Spring Data JPA supports a large number of keywords to build a query. IN
and AND
are among them.
It can be cleaner to add an extension to FileManager for this kind of awkward call, for tidiness if nothing else. Something like:
extension FileManager {
static var documentDir : URL {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
}
}
Those are just version designations (just like windows xp, vista or windows 7) which they are using to name their major releases, instead of using version numbers. so you'll want to use the newest eclipse version available, which is helios (or 3.6 which is the corresponding version number).
Oh. I think you're writing the workbook out 944,000 times. Your wb.write(bos) call is in the inner loop. I'm not sure this is quite consistent with the semantics of the Workbook class? From what I can tell in the Javadocs of that class, that method writes out the entire workbook to the output stream specified. And it's gonna write out every row you've added so far once for every row as the thing grows.
This explains why you're seeing exactly 1 row, too. The first workbook (with one row) to be written out to the file is all that is being displayed - and then 7GB of junk thereafter.
This will help....
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return
c.substring(nameEQ.length,c.length);
}
return null;
}
You can use select2 plugin for creating such a filter. With this lot's of coding work can be avoided. You can grab the plugin from https://select2.github.io/
This plugin is much simple to apply and even advanced work can be easily done with it. :)
There are many misleading answers answers here, including the highly upvoted one (although I don't believe their ops meant harm). The short answer is: These are the same.
There are many keywords in the (T-)SQL language, but in the end, the only thing that really happens on the hardware is the operations as seen in the execution query plan.
The relational (maths theory) operation we do when we invoke [NOT] IN
and [NOT] EXISTS
is the semi join (anti-join when using NOT
). It is not a coincidence that the corresponding sql-server operations have the same name. There is no operation that mentions IN
or EXISTS
anywhere - only (anti-)semi joins. Thus, there is no way that a logically-equivalent IN
vs EXISTS
choice could affect performance because there is one and only way, the (anti)semi join execution operation, to get their results.
An example:
Query 1 ( plan )
select * from dt where dt.customer in (select c.code from customer c where c.active=0)
Query 2 ( plan )
select * from dt where exists (select 1 from customer c where c.code=dt.customer and c.active=0)
require.paths
is deprecated.
Go to your project folder and type
npm install socket.io
that should install it in the local ./node_modules folder where node will look for it.
I keep my things like this:
cd ~/Sites/
mkdir sweetnodeproject
cd sweetnodeproject
npm install socket.io
Create an app.js file
// app.js
var socket = require('socket.io')
now run my app
node app.js
Make sure you're using npm >= 1.0
and node >= 4.0
.
I use this code (I use Python 3):
import csv
import io
import requests
url = "http://samplecsvs.s3.amazonaws.com/Sacramentorealestatetransactions.csv"
r = requests.get(url)
r.encoding = 'utf-8' # useful if encoding is not sent (or not sent properly) by the server
csvio = io.StringIO(r.text, newline="")
data = []
for row in csv.DictReader(csvio):
data.append(row)
For me everything was working fine until Bitbucket automatically changed their policy today (April 21, 2020). This happens to align with a new feature recently introduced today called Workspaces, so I suspect it has something to do with that.
Workaround: I (as an Admin) followed the instructions to add the email address to Users in the UI (the email you are using can be found git config --list
use count instead of sum in your original formula u will get your result
Original One
=SUM(IF(MONTH('2013'!$A$2:$A$19)=4,'2013'!$D$2:$D$19,0))
Modified One
=COUNT(IF(MONTH('2013'!$A$2:$A$19)=4,'2013'!$D$2:$D$19,0))
AND USE ctrl+shift+enter
TO EXECUTE
CEF offers lot of flexibility and options for customisation. But if the intent is to develop quickly node-webkit is also a good option. Node-web kit also offers ability to call node modules directly from DOM.
If there aren't any native modules to integrate Node-Webkit can offer better mileage. With native modules C/C++ or even C# it is better with CEF.
Try ZZ
to save and close.
Here is a bit more info on using vim with Git
I think the following would work well with lesser line of codes.
session()->flash('toast', [
'status' => 'success',
'body' => 'Body',
'topic' => 'Success']
);
I'm using a toaster package, but you can have something like this in your view.
toastr.{{session('toast.status')}}(
'{{session('toast.body')}}',
'{{session('toast.topic')}}'
);
All answers were just a suggested solutions or workarounds. But still don't get answer to the question: why margin:auto works with position:relative but does not with position:absolute.
Following explanation was helpful for me:
"Margins make little sense on absolutely positioned elements since such elements are removed from the normal flow, thus they cannot push away any other elements on the page. Using margins like this can only affect the placement of the element to which the margin is applied, not any other element." http://www.justskins.com/forums/css-margins-and-absolute-82168.html
You might want to use Scanner to parse through and find the specific sections you want to modify. There's also Split and StringTokenizer that may work, but at the level you're working at Scanner might be what's needed.
Here's some additional info on what the difference is between them: Scanner vs. StringTokenizer vs. String.Split
On .Net Core (or Mono), most of the answers won't apply when the binary defining the process is the runtime binary of Mono or .Net Core (dotnet) and not your actual application you're interested in. In that case, use this:
var myName = Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location);
No way to do this that I know of, although I'm very curious to read if anyone has a good answer. I have been thinking about adding something like this to one of the apps my company builds, but have found no good way to do it.
The one thing I can think of (although not directly on point) is that I believe you can limit the total memory usage for a COM+ application in Windows. It would require the app to be written to run in COM+, of course, but it's the closest way I know of.
The working set stuff is good (Job Objects also control working sets), but that's not total memory usage, only real memory usage (paged in) at any one time. It may work for what you want, but afaik it doesn't limit total allocated memory.
d = <dict>
values = d.values()
For performance purpose, here's a little code to benchmark these two alternatives:
#!/bin/python
def hexxorA(a, b):
if len(a) > len(b):
return "".join(["%x" % (int(x,16) ^ int(y,16)) for (x, y) in zip(a[:len(b)], b)])
else:
return "".join(["%x" % (int(x,16) ^ int(y,16)) for (x, y) in zip(a, b[:len(a)])])
def hexxorB(a, b):
if len(a) > len(b):
return '%x' % (int(a[:len(b)],16)^int(b,16))
else:
return '%x' % (int(a,16)^int(b[:len(a)],16))
def testA():
strstr = hexxorA("b4affa21cbb744fa9d6e055a09b562b87205fe73cd502ee5b8677fcd17ad19fce0e0bba05b1315e03575fe2a783556063f07dcd0b9d15188cee8dd99660ee751", "5450ce618aae4547cadc4e42e7ed99438b2628ff15d47b20c5e968f086087d49ec04d6a1b175701a5e3f80c8831e6c627077f290c723f585af02e4c16122b7e2")
if not int(strstr, 16) == int("e0ff3440411901bd57b24b18ee58fbfbf923d68cd88455c57d8e173d91a564b50ce46d01ea6665fa6b4a7ee2fb2b3a644f702e407ef2a40d61ea3958072c50b3", 16):
raise KeyError
return strstr
def testB():
strstr = hexxorB("b4affa21cbb744fa9d6e055a09b562b87205fe73cd502ee5b8677fcd17ad19fce0e0bba05b1315e03575fe2a783556063f07dcd0b9d15188cee8dd99660ee751", "5450ce618aae4547cadc4e42e7ed99438b2628ff15d47b20c5e968f086087d49ec04d6a1b175701a5e3f80c8831e6c627077f290c723f585af02e4c16122b7e2")
if not int(strstr, 16) == int("e0ff3440411901bd57b24b18ee58fbfbf923d68cd88455c57d8e173d91a564b50ce46d01ea6665fa6b4a7ee2fb2b3a644f702e407ef2a40d61ea3958072c50b3", 16):
raise KeyError
return strstr
if __name__ == '__main__':
import timeit
print("Time-it 100k iterations :")
print("\thexxorA: ", end='')
print(timeit.timeit("testA()", setup="from __main__ import testA", number=100000), end='s\n')
print("\thexxorB: ", end='')
print(timeit.timeit("testB()", setup="from __main__ import testB", number=100000), end='s\n')
Here are the results :
Time-it 100k iterations :
hexxorA: 8.139988073991844s
hexxorB: 0.240523161992314s
Seems like '%x' % (int(a,16)^int(b,16))
is faster then the zip version.
You can convert the URL
to a String
and use it to create a new File
. e.g.
URL url = new URL("http://google.com/pathtoaimage.jpg");
File f = new File(url.getFile());
i think its helpfull to you
JSONArray jre = objJson.getJSONArray("Result");
for (int j = 0; j < jre.length(); j++) {
JSONObject jobject = jre.getJSONObject(j);
String date = jobject.getString("Date");
String keywords=jobject.getString("keywords");
String needed=jobject.getString("NeededString");
}
I am using Windows 7. To disable that all I did is to Right click on the Windows desktop and select "Graphics Properties" ->Options. Then selected "Off" at the left side on the resulting screen. This disabled all hotkey combination. I think there is no way to disable only some them, its all or none. Anyway I didn't need them. So now crtl+Alt+Up and Crtl+Alt+down works for me in Eclipse and my screen stays same :) I think similar option also exist in other versions of Windows. Have fun :)
just use a reference:
Vec3b & color = image.at<Vec3b>(y,x);
color[2] = 13;
Generally, a parameter is a string value that is most commonly known for being sent from the client to the server (e.g. a form post) and retrieved from the servlet request. The frustrating exception to this is ServletContext initial parameters which are string parameters that are configured in web.xml and exist on the server.
An attribute is a server variable that exists within a specified scope i.e.:
application
, available for the life of the entire applicationsession
, available for the life of the sessionrequest
, only available for the life of the requestpage
(JSP only), available for the current JSP page only The union
statement cause a deal time in huge data. It is good to perform the select in 2 steps:
For Windows user, please note to use "
instead of '
Also added -f
to force the command if another backup is already there.
git filter-branch -f --tree-filter "rm -rf FOLDERNAME" --prune-empty HEAD
git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d
echo FOLDERNAME/ >> .gitignore
git add .gitignore
git commit -m "Removing FOLDERNAME from git history"
git gc
git push origin master --force
class LL(object):
def __init__(self,val):
self.val = val
self.next = None
def pushNodeEnd(self,top,val):
if top is None:
top.val=val
top.next=None
else:
tmp=top
while (tmp.next != None):
tmp=tmp.next
newNode=LL(val)
newNode.next=None
tmp.next=newNode
def pushNodeFront(self,top,val):
if top is None:
top.val=val
top.next=None
else:
newNode=LL(val)
newNode.next=top
top=newNode
def popNodeFront(self,top):
if top is None:
return
else:
sav=top
top=top.next
return sav
def popNodeEnd(self,top):
if top is None:
return
else:
tmp=top
while (tmp.next != None):
prev=tmp
tmp=tmp.next
prev.next=None
return tmp
top=LL(10)
top.pushNodeEnd(top, 20)
top.pushNodeEnd(top, 30)
pop=top.popNodeEnd(top)
print (pop.val)
My simple solution. IMHO it's the cleanest.
First create a application.yml
spring.main.allow-bean-definition-overriding: true
security:
oauth2:
client:
clientId: XXX
clientSecret: XXX
accessTokenUri: XXX
tokenName: access_token
grant-type: client_credentials
Create the main class: Main
@SpringBootApplication
@EnableOAuth2Client
public class Main extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll();
}
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
@Bean
public OAuth2RestTemplate oauth2RestTemplate(ClientCredentialsResourceDetails details) {
return new OAuth2RestTemplate(details);
}
}
Then Create the controller class: Controller
@RestController
class OfferController {
@Autowired
private OAuth2RestOperations restOperations;
@RequestMapping(value = "/<your url>"
, method = RequestMethod.GET
, produces = "application/json")
public String foo() {
ResponseEntity<String> responseEntity = restOperations.getForEntity(<the url you want to call on the server>, String.class);
return responseEntity.getBody();
}
}
Maven dependencies
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>
</dependencies>
Just had the same problem here. In my case, the bat files had space " " After getting rid of spaces from filename and change into underscore, bat file worked
sample before it wont start
"x:\Update & pull.bat"
after rename
"x:\Update_and_pull.bat"
http://maps.google.com/maps?q=58%2041.881N%20152%2031.324W
Just use the coordinates as q
-parameter. Strip the z
and t
prameters. While z
should actually just be the zoom level, it seems that it won't work if you set any.
t
is the map type. Having that said, it's not obvious how those parameters would affect the result in the shown way. But they do.
Maybe you should try the ll
-parameter, but only decimal format will be accepted.
You can find a quick overview of all the parameters here.
Setting Up the database
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "database_name";
// Table Names
private static final String DB_TABLE = "table_image";
// column names
private static final String KEY_NAME = "image_name";
private static final String KEY_IMAGE = "image_data";
// Table create statement
private static final String CREATE_TABLE_IMAGE = "CREATE TABLE " + DB_TABLE + "("+
KEY_NAME + " TEXT," +
KEY_IMAGE + " BLOB);";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// creating table
db.execSQL(CREATE_TABLE_IMAGE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
// create new table
onCreate(db);
}
}
Insert in the Database:
public void addEntry( String name, byte[] image) throws SQLiteException{
SQLiteDatabase database = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_IMAGE, image);
database.insert( DB_TABLE, null, cv );
}
Retrieving data:
byte[] image = cursor.getBlob(1);
Note:
Below is an Utility class which I hope could help you:
public class DbBitmapUtility {
// convert from bitmap to byte array
public static byte[] getBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, stream);
return stream.toByteArray();
}
// convert from byte array to bitmap
public static Bitmap getImage(byte[] image) {
return BitmapFactory.decodeByteArray(image, 0, image.length);
}
}
Further reading
If you are not familiar how to insert and retrieve into a database, go through this tutorial.
wordlists is not a function, it is a list. You need the bracket subscript
print wordlists[len(words)]
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(text(), 'YourTextHere')]")));
assertNotNull(driver.findElement(By.xpath("//*[contains(text(), 'YourTextHere')]")));
String yourButtonName = driver.findElement(By.xpath("//*[contains(text(), 'YourTextHere')]")).getAttribute("innerText");
assertTrue(yourButtonName.equalsIgnoreCase("YourTextHere"));
Using Linux Instead of regexp take the first line and take out the current resolution values.
Current resolution of display :0
>>> screen = os.popen("xrandr -q -d :0").readlines()[0]
>>> print screen
Screen 0: minimum 320 x 200, current 1920 x 1080, maximum 1920 x 1920
>>> width = screen.split()[7]
>>> print width
1920
>>> height = screen.split()[9][:-1]
>>> print height
1080
>>> print "Current resolution is %s x %s" % (width,height)
Current resolution is 1920 x 1080
This was done on xrandr 1.3.5, I don't know if the output is different on other versions, but this should make it easy to figure out.
You can use JPQL as well as JPA Criteria API for any kind of DTO projection(Mapping only selected columns to a DTO class) . Look at below code snippets showing how to selectively select various columns instead of selecting all columns . These example also show how to select various columns from joining multiple columns . I hope this helps .
JPQL code :
String dtoProjection = "new com.katariasoft.technologies.jpaHibernate.college.data.dto.InstructorDto"
+ "(i.id, i.name, i.fatherName, i.address, id.proofNo, "
+ " v.vehicleNumber, v.vechicleType, s.name, s.fatherName, "
+ " si.name, sv.vehicleNumber , svd.name) ";
List<InstructorDto> instructors = queryExecutor.fetchListForJpqlQuery(
"select " + dtoProjection + " from Instructor i " + " join i.idProof id " + " join i.vehicles v "
+ " join i.students s " + " join s.instructors si " + " join s.vehicles sv "
+ " join sv.documents svd " + " where i.id > :id and svd.name in (:names) "
+ " order by i.id , id.proofNo , v.vehicleNumber , si.name , sv.vehicleNumber , svd.name ",
CollectionUtils.mapOf("id", 2, "names", Arrays.asList("1", "2")), InstructorDto.class);
if (Objects.nonNull(instructors))
instructors.forEach(i -> i.setName("Latest Update"));
DataPrinters.listDataPrinter.accept(instructors);
JPA Criteria API code :
@Test
public void fetchFullDataWithCriteria() {
CriteriaBuilder cb = criteriaUtils.criteriaBuilder();
CriteriaQuery<InstructorDto> cq = cb.createQuery(InstructorDto.class);
// prepare from expressions
Root<Instructor> root = cq.from(Instructor.class);
Join<Instructor, IdProof> insIdProofJoin = root.join(Instructor_.idProof);
Join<Instructor, Vehicle> insVehicleJoin = root.join(Instructor_.vehicles);
Join<Instructor, Student> insStudentJoin = root.join(Instructor_.students);
Join<Student, Instructor> studentInsJoin = insStudentJoin.join(Student_.instructors);
Join<Student, Vehicle> studentVehicleJoin = insStudentJoin.join(Student_.vehicles);
Join<Vehicle, Document> vehicleDocumentJoin = studentVehicleJoin.join(Vehicle_.documents);
// prepare select expressions.
CompoundSelection<InstructorDto> selection = cb.construct(InstructorDto.class, root.get(Instructor_.id),
root.get(Instructor_.name), root.get(Instructor_.fatherName), root.get(Instructor_.address),
insIdProofJoin.get(IdProof_.proofNo), insVehicleJoin.get(Vehicle_.vehicleNumber),
insVehicleJoin.get(Vehicle_.vechicleType), insStudentJoin.get(Student_.name),
insStudentJoin.get(Student_.fatherName), studentInsJoin.get(Instructor_.name),
studentVehicleJoin.get(Vehicle_.vehicleNumber), vehicleDocumentJoin.get(Document_.name));
// prepare where expressions.
Predicate instructorIdGreaterThan = cb.greaterThan(root.get(Instructor_.id), 2);
Predicate documentNameIn = cb.in(vehicleDocumentJoin.get(Document_.name)).value("1").value("2");
Predicate where = cb.and(instructorIdGreaterThan, documentNameIn);
// prepare orderBy expressions.
List<Order> orderBy = Arrays.asList(cb.asc(root.get(Instructor_.id)),
cb.asc(insIdProofJoin.get(IdProof_.proofNo)), cb.asc(insVehicleJoin.get(Vehicle_.vehicleNumber)),
cb.asc(studentInsJoin.get(Instructor_.name)), cb.asc(studentVehicleJoin.get(Vehicle_.vehicleNumber)),
cb.asc(vehicleDocumentJoin.get(Document_.name)));
// prepare query
cq.select(selection).where(where).orderBy(orderBy);
DataPrinters.listDataPrinter.accept(queryExecutor.fetchListForCriteriaQuery(cq));
}
var json = {"ListID" : "1", "ItemName":"test"};
$.ajax({
url: url,
type: 'POST',
data: username,
cache:false,
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success:function(response){
console.log("Success")
},
error : function(xhr, status, error) {
console.log("error")
}
);
Note the following is functionally different to Gordon Linoff's answer. His answer assumes that you want to use email2
if email
is NULL. Mine assumes you want to use email2
if email
is an empty-string. The correct answer will depend on your database (or you could perform a NULL check and an empty-string check - it all depends on what is appropriate for your database design).
SELECT `id` , `naam`
FROM `klanten`
WHERE `email` LIKE '%[email protected]%'
OR (LENGTH(email) = 0 AND `email2` LIKE '%[email protected]%')
Most people have said it - Plain Old CLR Object (as opposed to the earlier POJO - Plain Old Java Object)
The POJO one came out of EJB, which required you to inherit from a specific parent class for things like value objects (what you get back from a query in an ORM or similar), so if you ever wanted to move from EJB (eg to Spring), you were stuffed.
POJO's are just classes which dont force inheritance or any attribute markup to make them "work" in whatever framework you are using.
POCO's are the same, except in .NET.
Generally it'll be used around ORM's - older (and some current ones) require you to inherit from a specific base class, which ties you to that product. Newer ones dont (nhibernate being the variant I know) - you just make a class, register it with the ORM, and you are off. Much easier.
In my case I needed to pass arguments to a targetFragment. But I got exception "Fragment already active". So I declared an Interface in my DialogFragment which parentFragment implemented. When parentFragment started a DialogFragment , it set itself as TargetFragment. Then in DialogFragment I called
((Interface)getTargetFragment()).onSomething(selectedListPosition);
It appears this issue is fixed in npm v5.4.2
https://github.com/npm/npm/issues/17979
(Scroll down to the last comment in the thread)
Update
Actually fixed in 5.6.0. There was a cross platform bug in 5.4.2 that was causing the issue to still occur.
https://github.com/npm/npm/issues/18712
Update 2
See my answer here: https://stackoverflow.com/a/53680257/1611058
npm ci
is the command you should be using when installing existing projects now.
In my case, I had configure environment variables using the following option and it worked-
Manage Jenkins -> Configure System -> Global Properties -> Environment Variables -> Add
$( this ).attr( 'checked', 'checked' )
just attr( 'checked' )
will return the value of $( this )'s checked attribute. To set it, you need that second argument. Based on <input type="checkbox" checked="checked" />
Edit:
Based on comments, a more appropriate manipulation would be:
$( this ).attr( 'checked', true )
And a straight javascript method, more appropriate and efficient:
this.checked = true;
Thanks @Andy E for that.
Hope this helps
/* Hide scrollbar for Chrome, Safari and Opera */
::-webkit-scrollbar {
display: none;
}
/* Hide scrollbar for IE, Edge and Firefox */
html {
-ms-overflow-style: none; /* IE and Edge */
scrollbar-width: none; /* Firefox */
}
The simplest way is to use the following pattern:
http://[server]/[site]/[ListName]/[Folder]/[SubFolder]
To place a shortcut to a document library:
If you haven't pushed your changes yet use git reset --soft [Hash for one commit]
to rollback to a specific commit. --soft
tells git to keep the changes being rolled back (i.e., mark the files as modified). --hard
tells git to delete the changes being rolled back.
You can use embed player with opacity over on a cover photo with a right positioned play icon. After this you can check the activeElement of your document.
Of course I know this is not an optimal solution, but works on mobile devices too.
<div style="position: relative;">
<img src="http://s3.amazonaws.com/content.newsok.com/newsok/images/mobile/play_button.png" style="position:absolute;top:0;left:0;opacity:1;" id="cover">
<iframe width="560" height="315" src="https://www.youtube.com/embed/2qhCjgMKoN4?controls=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in- picture" allowfullscreen style="position: absolute;top:0;left:0;opacity:0;" id="player"></iframe>
</div>
<script>
setInterval(function(){
if(document.activeElement instanceof HTMLIFrameElement){
document.getElementById('cover').style.opacity=0;
document.getElementById('player').style.opacity=1;
}
} , 50);
</script>
Try it on codepen: https://codepen.io/sarkiroka/pen/OryxGP
I'm not fine with solutions that iterates over a collection and inside the loop manipulating the content of even that collection. This can result in unexpected behaviour.
See also here: https://stackoverflow.com/a/2304578/655224 and in a comment the given link http://php.net/manual/en/control-structures.foreach.php#88578
So, when using foreach
if seems to be OK but IMHO the much more readable and simple solution is to filter your collection to a new one.
/**
* Filter all `selected` items
*
* @link https://laravel.com/docs/7.x/collections#method-filter
*/
$selected = $collection->filter(function($value, $key) {
return $value->selected;
})->toArray();
In normal winForms, value of Label object is changed by,
myLabel.Text= "Your desired string";
But in WPF Label control, you have to use .content property of Label control for example,
myLabel.Content= "Your desired string";
I am on shared hosting, so I can't do a lot of queries otherwise I get a blank page.
That sounds very peculiar. I've got the cheapest PHP hosting package I could find for my last project - and it does not behave like this. I would not pay for a service which did. Indeed, I'm stumped to even know how I could configure a server to replicate this behaviour.
Regardless of why it behaves this way, adding a sleep in the middle of the script cannot resolve the problem.
Since, presumably, you control your product catalog, new products should be relatively infrequent (or are you trying to get stock reports?). If you control when you change the data, why run the scripts automatically? Or do you mean that you already have these URLs and you get the expected files when you run them one at a time?
This should help. How can I upload files asynchronously?
As the post suggest I recommend a plugin located here http://malsup.com/jquery/form/#code-samples
If you don't mind picking the same item again at some other time:
$items[rand(0, count($items) - 1)];
template<int> void DoMyOperationHelper();
template<> void DoMyOperationHelper<4>()
{
// do 32-bits operations
}
template<> void DoMyOperationHelper<8>()
{
// do 64-bits operations
}
// helper function just to hide clumsy syntax
inline void DoMyOperation() { DoMyOperationHelper<sizeof(size_t)>(); }
int main()
{
// appropriate function will be selected at compile time
DoMyOperation();
return 0;
}
If you only want the shortened commit hash:
git log --pretty=format:'%h' -n 1
Furthermore, using %H
is another way to get the long commit hash, and simply -1
can be used in place of -n 1
.
Not sure what you are asking, but... Class.forname, maybe?
@($output).Count
does not always produce correct results.
I used the ($output | Measure).Count
method.
I found this with VMware Get-VmQuestion cmdlet:
$output = Get-VmQuestion -VM vm1
@($output).Count
The answer it gave is one, whereas
$output
produced no output (the correct answer was 0 as produced with the Measure
method).
This only seemed to be the case with 0 and 1. Anything above 1 was correct with limited testing.
this bellow solution worked for me
$result_encr="##Sƒ";
iconv("cp1252", "utf-8//IGNORE", $result_encr);
If you want a destructive backspace, you'll need something like
"\b \b"
i.e. a backspace, a space, and another backspace.
Case :1 > We have two main method but with "Main" AND "main2" so jvm only a=calling "main" method .
2> Same method but diff params, still jvm calling "main(String[] args) " meyhod.
3> Exactly same method but it gives copile time error as you can not have two same name method in a single class !!!
Hope it will give you clear pic
This scope https://www.googleapis.com/auth/userinfo.profile has been deprecated now. Please look at https://developers.google.com/+/api/auth-migration#timetable.
New scope you will be using to get profile info is: profile or https://www.googleapis.com/auth/plus.login
and the endpoint is - https://www.googleapis.com/plus/v1/people/{userId} - userId can be just 'me' for currently logged in user.
If your function returns a value via reference, the compiler cannot store it in a register when calling other functions because, theoretically, the first function can save the address of the variable passed to it in a globally accessible variable, and any subsecuently called functions may change it, so the compiler will have (1) save the value from registers back to memory before calling other functions and (2) re-read it when it is needed from the memory again after any of such calls.
If you return by reference, optimization of your program will suffer
Call
setSupportActionBar(toolbar)
inside
onViewCreated(...)
of Fragment
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
((MainActivity)getActivity()).setSupportActionBar(toolbar);
setHasOptionsMenu(true);
}
You are using the wrong format tokens when parsing your input. You should use ddd
for an abbreviation of the name of day of the week, DD
for day of the month, MMM
for an abbreviation of the month's name, YYYY
for the year, hh
for the 1-12
hour, mm
for minutes and A
for AM/PM
. See moment(String, String)
docs.
Here is a working live sample:
console.log( moment('Mon 03-Jul-2017, 11:00 AM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );_x000D_
console.log( moment('Mon 03-Jul-2017, 11:00 PM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
Aside from @see
, a more general way of refering to another class and possibly method of that class is {@link somepackage.SomeClass#someMethod(paramTypes)}
. This has the benefit of being usable in the middle of a javadoc description.
From the javadoc documentation (description of the @link tag):
This tag is very simliar to @see – both require the same references and accept exactly the same syntax for package.class#member and label. The main difference is that {@link} generates an in-line link rather than placing the link in the "See Also" section. Also, the {@link} tag begins and ends with curly braces to separate it from the rest of the in-line text.
I don't think you're fully grasping modulo. a % b
and a mod b
are just two different ways to express modulo. In this case, python uses %
. No, 15 mod 4
is not 1
, 15 % 4 == 15 mod 4 == 3
.
This answer is based upon Matifou's answer.
First I modified it to ensure that I don't get the freq column returned as a scientific notation column by using the scipen option.
Then I multiple the answer by 100 to get a percent rather than decimal to make the freq column easier to read as a percentage.
getOption("scipen")
options("scipen"=10)
mtcars %>%
count(am, gear) %>%
mutate(freq = (n / sum(n)) * 100)
If you have integers in your file fscanf returns 1 until integer occurs. For example:
FILE *in = fopen("./task.in", "r");
int length = 0;
int counter;
int sequence;
for ( int i = 0; i < 10; i++ ) {
counter = fscanf(in, "%d", &sequence);
if ( counter == 1 ) {
length += 1;
}
}
To find out the end of the file with symbols you can use EOF. For example:
char symbol;
FILE *in = fopen("./task.in", "r");
for ( ; fscanf(in, "%c", &symbol) != EOF; ) {
printf("%c", symbol);
}
Use Firefox with Firebug. Open the 'Console' tab while firing the ajax request. With DEBUG=True
you get the nice django error page as response and you can even see the rendered html of the ajax response in the console tab.
Then you will know what the error is.
If you have more than the last leaf directory to be created, you can either run a separate ssh ... mkdir -p
first, or use the --rsync-path
trick as explained here :
rsync -a --rsync-path="mkdir -p /tmp/x/y/z/ && rsync" $source user@remote:/tmp/x/y/z/
Or use the --relative
option as suggested by Tony. In that case, you only specify the root of the destination, which must exist, and not the directory structure of the source, which will be created:
rsync -a --relative /new/x/y/z/ user@remote:/pre_existing/dir/
This way, you will end up with /pre_existing/dir/new/x/y/z/
And if you want to have "y/z/" created, but not inside "new/x/", you can add ./
where you want --relative
to begin:
rsync -a --relative /new/x/./y/z/ user@remote:/pre_existing/dir/
would create /pre_existing/dir/y/z/.
If you want change bottom line without using app colors, use these lines in your theme:
<item name="android:editTextStyle">@android:style/Widget.EditText</item>
<item name="editTextStyle">@android:style/Widget.EditText</item>
I don't know another solution.
I think it should be "there can only be one NON-STATIC top level public class per .java file". Isn't it?
It really depends on what you're storing. If you're talking about structured data, then either XML or a very lightweight SQL RDBMS like SQLite or SQL Server Compact Edition will work well for you. The SQL solution becomes especially compelling if the data moves beyond a trivial size.
If you're storing large pieces of relatively unstructured data (binary objects like images, for example) then obviously neither a database nor XML solution are appropriate, but given your question I'm guessing it's more of the former than the latter.
function Do-SendKeys {
param (
$SENDKEYS,
$WINDOWTITLE
)
$wshell = New-Object -ComObject wscript.shell;
IF ($WINDOWTITLE) {$wshell.AppActivate($WINDOWTITLE)}
Sleep 1
IF ($SENDKEYS) {$wshell.SendKeys($SENDKEYS)}
}
Do-SendKeys -WINDOWTITLE Print -SENDKEYS '{TAB}{TAB}'
Do-SendKeys -WINDOWTITLE Print
Do-SendKeys -SENDKEYS '%{f4}'
This should work:
select * from mytable where 'Journal'=ANY(pub_types);
i.e. the syntax is <value> = ANY ( <array> )
. Also notice that string literals in postresql are written with single quotes.
I try to understand the famous sentence in my way: "Python dose not care an object is a real duck or not. All it cares is whether the object, first 'quack', second 'like a duck'."
There is a good website. http://www.voidspace.org.uk/python/articles/duck_typing.shtml#id14
The author pointed that duck typing let you create your own classes that have their own internal data structure - but are accessed using normal Python syntax.
There is no JavaScript function to achieve this. However, you could set a boolean value to true
when you add the listener, and false
when you remove it. Then check against this boolean before potentially adding a duplicate event listener.
Possible duplicate: How to check whether dynamically attached event listener exists or not?
Why don't you create service and put logic in onCreate()
. In this case even if you press back button service will keep on executing. and once you enter into application it will not call
onCreate()
again. Rather it will call onStart()
For string comparisons in Perl, use eq
or ne
:
if ($str eq "")
{
// ...
}
The ==
and !=
operators are numeric comparison operators. They will attempt to convert both operands to integers before comparing them.
See the perlop man page for more information.
You can use this one it's for YYYY-MM-DD. It checks if it's a valid date and that the value is not NULL. It returns TRUE
if everythings check out to be correct or FALSE
if anything is invalid. It doesn't get easier then this!
function validateDate(date) {
var matches = /^(\d{4})[-\/](\d{2})[-\/](\d{2})$/.exec(date);
if (matches == null) return false;
var d = matches[3];
var m = matches[2] - 1;
var y = matches[1] ;
var composedDate = new Date(y, m, d);
return composedDate.getDate() == d &&
composedDate.getMonth() == m &&
composedDate.getFullYear() == y;
}
Be aware that months need to be subtracted like this: var m = matches[2] - 1;
else the new Date()
instance won't be properly made.
If you are in a network of users, then the username will be different:
Environment.UserName
Will Display format : 'Username', rather than
System.Security.Principal.WindowsIdentity.GetCurrent().Name
Will Display format : 'NetworkName\Username'
Choose the format you want.
There are two ways in which abstract base classes are used.
You are specializing your abstract object, but all clients will use the derived class through its base interface.
You are using an abstract base class to factor out duplication within objects in your design, and clients use the concrete implementations through their own interfaces.!
Solution For 1 - Strategy Pattern
If you have the first situation, then you actually have an interface defined by the virtual methods in the abstract class that your derived classes are implementing.
You should consider making this a real interface, changing your abstract class to be concrete, and take an instance of this interface in its constructor. Your derived classes then become implementations of this new interface.
This means you can now test your previously abstract class using a mock instance of the new interface, and each new implementation through the now public interface. Everything is simple and testable.
Solution For 2
If you have the second situation, then your abstract class is working as a helper class.
Take a look at the functionality it contains. See if any of it can be pushed onto the objects that are being manipulated to minimize this duplication. If you still have anything left, look at making it a helper class that your concrete implementation take in their constructor and remove their base class.
This again leads to concrete classes that are simple and easily testable.
As a Rule
Favor complex network of simple objects over a simple network of complex objects.
The key to extensible testable code is small building blocks and independent wiring.
Updated : How to handle mixtures of both?
It is possible to have a base class performing both of these roles... ie: it has a public interface, and has protected helper methods. If this is the case, then you can factor out the helper methods into one class (scenario2) and convert the inheritance tree into a strategy pattern.
If you find you have some methods your base class implements directly and other are virtual, then you can still convert the inheritance tree into a strategy pattern, but I would also take it as a good indicator that the responsibilities are not correctly aligned, and may need refactoring.
Update 2 : Abstract Classes as a stepping stone (2014/06/12)
I had a situation the other day where I used abstract, so I'd like to explore why.
We have a standard format for our configuration files. This particular tool has 3 configuration files all in that format. I wanted a strongly typed class for each setting file so, through dependency injection, a class could ask for the settings it cared about.
I implemented this by having an abstract base class that knows how to parse the settings files formats and derived classes that exposed those same methods, but encapsulated the location of the settings file.
I could have written a "SettingsFileParser" that the 3 classes wrapped, and then delegated through to the base class to expose the data access methods. I chose not to do this yet as it would lead to 3 derived classes with more delegation code in them than anything else.
However... as this code evolves and the consumers of each of these settings classes become clearer. Each settings users will ask for some settings and transform them in some way (as settings are text they may wrap them in objects of convert them to numbers etc.). As this happens I will start to extract this logic into data manipulation methods and push them back onto the strongly typed settings classes. This will lead to a higher level interface for each set of settings, that is eventually no longer aware it's dealing with 'settings'.
At this point the strongly typed settings classes will no longer need the "getter" methods that expose the underlying 'settings' implementation.
At that point I would no longer want their public interface to include the settings accessor methods; so I will change this class to encapsulate a settings parser class instead of derive from it.
The Abstract class is therefore: a way for me to avoid delegation code at the moment, and a marker in the code to remind me to change the design later. I may never get to it, so it may live a good while... only the code can tell.
I find this to be true with any rule... like "no static methods" or "no private methods". They indicate a smell in the code... and that's good. It keeps you looking for the abstraction that you have missed... and lets you carry on providing value to your customer in the mean time.
I imagine rules like this one defining a landscape, where maintainable code lives in the valleys. As you add new behaviour, it's like rain landing on your code. Initially you put it wherever it lands.. then you refactor to allow the forces of good design to push the behaviour around until it all ends up in the valleys.
Definitely the second one. In the first one, you use a constant empty List<?>
and then convert it to a File[]
, which requires to create an empty File[0]
array. And that is what you do in the second one in one single step.
if you want to try without 'array_count_values'
you can do with a smart way here
<?php
$input= array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
$count_values = array();
foreach ($input as $a) {
@$count_values[$a]++;
}
echo 'Duplicates count: '.count($count_values);
print_r($count_values);
?>
A few principles:
you have a std::exception base class, you should have your exceptions derive from it. That way general exception handler still have some information.
Don't throw pointers but object, that way memory is handled for you.
Example:
struct MyException : public std::exception
{
std::string s;
MyException(std::string ss) : s(ss) {}
~MyException() throw () {} // Updated
const char* what() const throw() { return s.c_str(); }
};
And then use it in your code:
void Foo::Bar(){
if(!QueryPerformanceTimer(&m_baz)){
throw MyException("it's the end of the world!");
}
}
void Foo::Caller(){
try{
this->Bar();// should throw
}catch(MyException& caught){
std::cout<<"Got "<<caught.what()<<std::endl;
}
}
Something like this should do it :
UPDATE table1
SET table1.Price = table2.price
FROM table1 INNER JOIN table2 ON table1.id = table2.id
You can also try this:
UPDATE table1
SET price=(SELECT price FROM table2 WHERE table1.id=table2.id);
The substitute of fcntl
on windows are win32api
calls. The usage is completely different. It is not some switch you can just flip.
In other words, porting a fcntl
-heavy-user module to windows is not trivial. It requires you to analyze what exactly each fcntl
call does and then find the equivalent win32api
code, if any.
There's also the possibility that some code using fcntl
has no windows equivalent, which would require you to change the module api and maybe the structure/paradigm of the program using the module you're porting.
If you provide more details about the fcntl
calls people can find windows equivalents.
In javascript there are trues and truthys. When something is true it is obviously true or false. When something is truthy it may or may not be a boolean, but the "cast" value of is a boolean.
Examples.
true == true; // (true) true
1 == true; // (true) truthy
"hello" == true; // (true) truthy
[1, 2, 3] == true; // (true) truthy
[] == false; // (true) truthy
false == false; // (true) true
0 == false; // (true) truthy
"" == false; // (true) truthy
undefined == false; // (true) truthy
null == false; // (true) truthy
This can make things simpler if you want to check if a string is set or an array has any values.
var users = [];
if(users) {
// this array is populated. do something with the array
}
var name = "";
if(!name) {
// you forgot to enter your name!
}
And as stated. expect(something).toBe(true)
and expect(something).toBeTrue()
is the same. But expect(something).toBeTruthy()
is not the same as either of those.
my problem was with the accents (á É ñ ) and the plus sign (+) when i to try to save javascript "code examples" to mysql:
my solution (not the better way, but it works):
javascript:
function replaceAll( text, busca, reemplaza ){
while (text.toString().indexOf(busca) != -1)
text = text.toString().replace(busca,reemplaza);return text;
}
function cleanCode(cod){
code = replaceAll(cod , "|", "{1}" ); // error | palos de explode en java
code = replaceAll(code, "+", "{0}" ); // error con los signos mas
return code;
}
function to save:
function save(pid,code){
code = cleanCode(code); // fix sign + and |
code = escape(code); // fix accents
var url = 'editor.php';
var variables = 'op=save';
var myData = variables +'&code='+ code +'&pid='+ pid +'&newdate=' +(new Date()).getTime();
var result = null;
$.ajax({
datatype : "html",
data: myData,
url: url,
success : function(result) {
alert(result); // result ok
},
});
} // end function
function in php:
<?php
function save($pid,$code){
$code= preg_replace("[\{1\}]","|",$code);
$code= preg_replace("[\{0\}]","+",$code);
mysql_query("update table set code= '" . mysql_real_escape_string($code) . "' where pid='$pid'");
}
?>
If you want the field to always be hidden, use the following:
class MyForm(forms.Form):
hidden_input = forms.CharField(widget=forms.HiddenInput(), initial="value")
If you want the field to be conditionally hidden, you can do the following:
form = MyForm()
if condition:
form.fields["field_name"].widget = forms.HiddenInput()
form.fields["field_name"].initial = "value"
Use "$@"
to represent all the arguments:
for var in "$@"
do
echo "$var"
done
This will iterate over each argument and print it out on a separate line. $@ behaves like $* except that when quoted the arguments are broken up properly if there are spaces in them:
sh test.sh 1 2 '3 4'
1
2
3 4
I got the same error, This is what i did to solve the issue.
Before Indentation:
Indentation Error: expected an indented block.
After Indentation:
Working fine. After TAB space.
Set
dgv.CurrentCell = null;
when user clicks on a blank part of the dgv.
This is actually really easy:
Another way to do this is to use the Ruby on Rails debugger. There's a Ruby on Rails guide about debugging at http://guides.rubyonrails.org/debugging_rails_applications.html
Basically, start the server with the -u option:
./script/server -u
And then insert a breakpoint into your script where you would like to have access to the controllers, helpers, etc.
class EventsController < ApplicationController
def index
debugger
end
end
And when you make a request and hit that part in the code, the server console will return a prompt where you can then make requests, view objects, etc. from a command prompt. When finished, just type 'cont' to continue execution. There are also options for extended debugging, but this should at least get you started.
Try running
lsof | grep /mnt/data
That should list any process that is accessing /mnt/data that would prevent it from being unmounted.
This is quite a misleading status. It should be called "reading and filtering data".
This means that MySQL
has some data stored on the disk (or in memory) which is yet to be read and sent over. It may be the table itself, an index, a temporary table, a sorted output etc.
If you have a 1M records table (without an index) of which you need only one record, MySQL
will still output the status as "sending data" while scanning the table, despite the fact it has not sent anything yet.
Yes, the OS keeps some things in the 'background.' For example, if you run
int* num = new int[5];
the OS can allocate 4 extra bytes, store the size of the allocation in the first 4 bytes of the allocated memory and return an offset pointer (ie, it allocates memory spaces 1000 to 1024 but the pointer returned points to 1004, with locations 1000-1003 storing the size of the allocation). Then, when delete is called, it can look at 4 bytes before the pointer passed to it to find the size of the allocation.
I am sure that there are other ways of tracking the size of an allocation, but that's one option.
I don't know why the other solutions go through the whole list of stylesheets for the document. Doing so creates a new entry in each stylesheet, which is inefficient. Instead, we can simply append a new stylesheet and simply add our desired CSS rules there.
style=document.createElement('style');
document.head.appendChild(style);
stylesheet=style.sheet;
function css(selector,property,value)
{
try{ stylesheet.insertRule(selector+' {'+property+':'+value+'}',stylesheet.cssRules.length); }
catch(err){}
}
Note that we can override even inline styles set directly on elements by adding " !important" to the value of the property, unless there already exist more specific "!important" style declarations for that property.
session in rails is a hash object. Hence any function available for clearing hash will work with sessions.
session.clear
or if specific keys have to be destroyed:
session.delete(key)
Tested in rails 3.2
added
People have mentioned by session={}
is a bad idea. Regarding session.clear
, Lobati comments- It looks like you're probably better off using reset_session [than session.clear], as it does some other cleaning up beyond what session.clear does. Internally, reset_session calls session.destroy, which itself calls clear as well some other stuff.
If anyone's looking to detect a given key and needs to know the status of the "modifiers" (as they are called in Java), i.e. Shift, Alt and Control keys, you can do something like this, which responds to keydown
on key F9, but only if none of the Shift, Alt or Control keys is currently pressed.
jqMyDiv.on( 'keydown', function( e ){
if( ! e.shiftKey && ! e.altKey && ! e.ctrlKey ){
console.log( e );
if( e.originalEvent.code === 'F9' ){
// do something
}
}
});
For anyone that is still stuck on this issue after trying the above. If you are right-clicking on the database and going to tasks->import, then here is the issue. Go to your start menu and under sql server, find the x64 bit import export wizard and try that. Worked like a charm for me, but it took me FAR too long to find it Microsoft!
Sort each element then look for duplicates. There's a built-in function for sorting so you do not need to import anything
Before increasing the max_connections variable, you have to check how many non-interactive connection you have by running show processlist command.
If you have many sleep connection, you have to decrease the value of the "wait_timeout" variable to close non-interactive connection after waiting some times.
SHOW SESSION VARIABLES LIKE 'wait_timeout';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| wait_timeout | 28800 |
+---------------+-------+
the value is in second, it means that non-interactive connection still up to 8 hours.
SET session wait_timeout=600; Query OK, 0 rows affected (0.00 sec)
After 10 minutes if the sleep connection still sleeping the mysql or MariaDB drop that connection.
Here's a quick example on how to use the Selector
class on Swift:
override func viewDidLoad() {
super.viewDidLoad()
var rightButton = UIBarButtonItem(title: "Title", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("method"))
self.navigationItem.rightBarButtonItem = rightButton
}
func method() {
// Something cool here
}
Note that if the method passed as a string doesn't work, it will fail at runtime, not compile time, and crash your app. Be careful
If we are use chosen dropdown list, then we can use below css(No JS/JQuery require)
<select chosen="{width: '100%'}" ng-
model="modelName" class="form-control input-
sm"
ng-
options="persons.persons as
persons.persons for persons in
jsonData"
ng-
change="anyFunction(anyParam)"
required>
<option value=""> </option>
</select>
<style>
.chosen-container .chosen-drop {
border-bottom: 0;
border-top: 1px solid #aaa;
top: auto;
bottom: 40px;
}
.chosen-container.chosen-with-drop .chosen-single {
border-top-left-radius: 0px;
border-top-right-radius: 0px;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
background-image: none;
}
.chosen-container.chosen-with-drop .chosen-drop {
border-bottom-left-radius: 0px;
border-bottom-right-radius: 0px;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
box-shadow: none;
margin-bottom: -16px;
}
</style>
With jQuery, you use $(document).ready()
to execute something when the DOM is loaded and $(window).on("load", handler)
to execute something when all other things are loaded as well, such as the images.
The difference can be seen in the following complete HTML file, provided you have a lot of jollyrogerNN
JPEG files (or other suitable ones):
<html>
<head>
<script src="jquery-1.7.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
alert ("done");
});
</script>
</head><body>
Hello
<img src="jollyroger00.jpg">
<img src="jollyroger01.jpg">
// : 100 copies of this in total
<img src="jollyroger99.jpg">
</body>
</html>
With that, the alert box appears before the images are loaded, because the DOM is ready at that point. If you then change:
$(document).ready(function() {
into:
$(window).on("load", function() {
then the alert box doesn't appear until after the images are loaded.
Hence, to wait until the entire page is ready, you could use something like:
$(window).on("load", function() {
// weave your magic here.
});
In case you want to cast to a class and not just a string:
YourClass model = await request.Content.ReadAsAsync<YourClass>();
If you wanted to accomplish this with pure HTML alone, this solution will work across all major browsers:
Description Lists
Simply using the following HTML:
<dl>
<dt>List Item 1</dt>
<dd>Sub-Item 1.1</dd>
<dt>List Item 2</dt>
<dd>Sub-Item 2.1</dd>
<dd>Sub-Item 2.2</dd>
<dd>Sub-Item 2.3</dd>
<dt>List Item 3</dt>
<dd>Sub-Item 3.1</dd>
</dl>
_x000D_
Example here: https://jsfiddle.net/zumcmvma/2/
Reference here: https://www.w3schools.com/tags/tag_dl.asp
Offering an interactive sort handling multiple columns is nothing trivial.
Unless you want to write a good amount of code handling logic for multiple row clicks, editing and refreshing page content, managing sort algorithms for large tables… then you really are better off adopting a plug-in.
tablesorter, (with updates by Mottie) is my favorite. It’s easy to get going and very customizable. Just add the class tablesorter
to the table you want to sort, then invoke the tablesorter plugin in a document load event:
$(function(){
$("#myTable").tablesorter();
});
You can browse the documentation to learn about advanced features.
If you have many factor variables, you can use select_if
funtion.
install the dplyr packages. There are many function that separates data by satisfying a condition. you can set the conditions.
Use like this.
categorical<-select_if(df,is.factor)
str(categorical)
As a more elementary situation it would be nice IF this
had a property that could reference it's referring variable (heads
or tails
) but unfortunately it only references the instantiation of the new coinSide
object.
javascript: /* it would be nice but ... a solution NOT! */
function coinSide(){this.ref=this};
/* can .ref be set so as to identify it's referring variable? (heads or tails) */
heads = new coinSide();
tails = new coinSide();
toss = Math.random()<0.5 ? heads : tails;
alert(toss.ref);
alert(["FF's Gecko engine shows:\n\ntoss.toSource() is ", toss.toSource()])
which always displays
[object Object]
and Firefox's Gecko engine shows:
toss.toSource() is ,#1={ref:#1#}
Of course, in this example, to resolve #1
, and hence toss
, it's simple enough to test toss==heads
and toss==tails
. This question, which is really asking if javascript has a call-by-name
mechanism, motivates consideration of the counterpart, is there a call-by-value
mechanism to determine the ACTUAL value of a variable? The example demonstrates that the "values" of both heads
and tails
are identical, yet alert(heads==tails)
is false
.
The self-reference can be coerced as follows:
(avoiding the object space hunt and possible ambiguities as noted in the How to get class object's name as a string in Javascript? solution)
javascript:
function assign(n,v){ eval( n +"="+ v ); eval( n +".ref='"+ n +"'" ) }
function coinSide(){};
assign("heads", "new coinSide()");
assign("tails", "new coinSide()");
toss = Math.random()<0.5 ? heads : tails;
alert(toss.ref);
to display heads
or tails
.
It is perhaps an anathema to the essence of Javascript's language design, as an interpreted prototyping functional language, to have such capabilities as primitives.
A final consideration:
javascript:
item=new Object(); refName="item"; deferAgain="refName";
alert([deferAgain,eval(deferAgain),eval(eval(deferAgain))].join('\n'));
so, as stipulated ...
javascript:
function bindDIV(objName){
return eval( objName +'=new someObject("'+objName+'")' )
};
function someObject(objName){
this.div="\n<DIV onclick='window.opener."+ /* window.opener - hiccup!! */
objName+
".someFunction()'>clickable DIV</DIV>\n";
this.someFunction=function(){alert(['my variable object name is ',objName])}
};
with(window.open('','test').document){ /* see above hiccup */
write('<html>'+
bindDIV('DIVobj1').div+
bindDIV('DIV2').div+
(alias=bindDIV('multiply')).div+
'an aliased DIV clone'+multiply.div+
'</html>');
close();
};
void (0);
Is there a better way ... ?
"better" as in easier? Easier to program? Easier to understand? Easier as in faster execution? Or is it as in "... and now for something completely different"?
First, here's some sample data:
set.seed(1)
dat <- data.frame(one = rnorm(15),
two = sample(LETTERS, 15),
three = rnorm(15),
four = runif(15))
dat <- data.frame(lapply(dat, function(x) { x[sample(15, 5)] <- NA; x }))
head(dat)
# one two three four
# 1 NA M 0.80418951 0.8921983
# 2 0.1836433 O -0.05710677 NA
# 3 -0.8356286 L 0.50360797 0.3899895
# 4 NA E NA NA
# 5 0.3295078 S NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595
Here's our replacement:
dat[["four"]][is.na(dat[["four"]])] <- 0
head(dat)
# one two three four
# 1 NA M 0.80418951 0.8921983
# 2 0.1836433 O -0.05710677 0.0000000
# 3 -0.8356286 L 0.50360797 0.3899895
# 4 NA E NA 0.0000000
# 5 0.3295078 S NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595
Alternatively, you can, of course, write dat$four[is.na(dat$four)] <- 0
this worked for me:
ssh-keygen -R <server_IP>
to delete the old keys stored on the workstation also works with instead of
then doing the same ssh again it worked:
ssh -v -i <your_pem_file> ubuntu@<server_IP>
on ubuntu instances the username is: ubuntu on Amazon Linux AMI the username is: ec2-user
I didn't have to re-create the instance from an image.
The @japf answer above is working fine and in my case I wanted to change the mouse cursor from a Spinning Wheel back to the normal Arrow once the CEF Browser finished loading the page. In case it can help someone, here is the code:
private void Browser_LoadingStateChanged(object sender, CefSharp.LoadingStateChangedEventArgs e) {
if (!e.IsLoading) {
// set the cursor back to arrow
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background,
new Action(() => Mouse.OverrideCursor = Cursors.Arrow));
}
}
Well, my solution uses residue technique. We can place the values under sorting in the upper 2 bytes and the indices of the elements - in the lower 2 bytes:
int myints[] = {32,71,12,45,26,80,53,33};
for (int i = 0; i < 8; i++)
myints[i] = myints[i]*(1 << 16) + i;
Then sort the array myints
as usual:
std::vector<int> myvector(myints, myints+8);
sort(myvector.begin(), myvector.begin()+8, std::less<int>());
After that you can access the elements' indices via residuum. The following code prints the indices of the values sorted in the ascending order:
for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
std::cout << ' ' << (*it)%(1 << 16);
Of course, this technique works only for the relatively small values in the original array myints
(i.e. those which can fit into upper 2 bytes of int
). But it has additional benefit of distinguishing identical values of myints
: their indices will be printed in the right order.
<input type="text" id="text" name="search">
<table id="table_data">
<tr class="listR"><td>PHP</td></tr>
<tr class="listR"><td>MySql</td></tr>
<tr class="listR"><td>AJAX</td></tr>
<tr class="listR"><td>jQuery</td></tr>
<tr class="listR"><td>JavaScript</td></tr>
<tr class="listR"><td>HTML</td></tr>
<tr class="listR"><td>CSS</td></tr>
<tr class="listR"><td>CSS3</td></tr>
</table>
$("#textbox").on('keyup',function(){
var f = $(this).val();
$("#table_data tr.listR").each(function(){
if ($(this).text().search(new RegExp(f, "i")) < 0) {
$(this).fadeOut();
} else {
$(this).show();
}
});
});
Demo You can perform by search() method with use RegExp matching text
The changed it from change
to selectionChange
.
<mat-select (change)="doSomething($event)">
is now
<mat-select (selectionChange)="doSomething($event)">
var x = parseInt(455/10);
The parseInt() function parses a string and returns an integer.
The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.
If the radix parameter is omitted, JavaScript assumes the following:
If the string begins with "0x", the radix is 16 (hexadecimal) If the string begins with "0", the radix is 8 (octal). This feature is deprecated If the string begins with any other value, the radix is 10 (decimal)
Use boost::filesystem. It will be incorporated into the next standard anyway so you may as well get used to it.
Use Numpy direct array indexing, as in MATLAB, Julia, ...
a = [10, 11, 12, 13, 14, 15];
s = [1, 2, 5] ;
import numpy as np
list(np.array(a)[s])
# [11, 12, 15]
Better yet, just stay with Numpy arrays
a = np.array([10, 11, 12, 13, 14, 15])
a[s]
#array([11, 12, 15])
var e = $('<div style="display:block; id="myid" float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
$("#box").html(e);
What you need is a date template filter.
e.g:
<td>Joined {{user.date_created|date:"F Y" }}<td>
This returns Joined December 2018
A pivot is used to convert one of the columns in your data set from rows into columns (this is typically referred to as the spreading column). In the example you have given, this means converting the PhaseID
rows into a set of columns, where there is one column for each distinct value that PhaseID
can contain - 1, 5 and 6 in this case.
These pivoted values are grouped via the ElementID
column in the example that you have given.
Typically you also then need to provide some form of aggregation that gives you the values referenced by the intersection of the spreading value (PhaseID
) and the grouping value (ElementID
). Although in the example given the aggregation that will be used is unclear, but involves the Effort
column.
Once this pivoting is done, the grouping and spreading columns are used to find an aggregation value. Or in your case, ElementID
and PhaseIDX
lookup Effort
.
Using the grouping, spreading, aggregation terminology you will typically see example syntax for a pivot as:
WITH PivotData AS
(
SELECT <grouping column>
, <spreading column>
, <aggregation column>
FROM <source table>
)
SELECT <grouping column>, <distinct spreading values>
FROM PivotData
PIVOT (<aggregation function>(<aggregation column>)
FOR <spreading column> IN <distinct spreading values>));
This gives a graphical explanation of how the grouping, spreading and aggregation columns convert from the source to pivoted tables if that helps further.
A couple of methods that, if the char does not exists, return the original string.
This one cuts the string after the first occurrence of the pivot:
public static string truncateStringAfterChar(string input, char pivot){
int index = input.IndexOf(pivot);
if(index >= 0) {
return input.Substring(index + 1);
}
return input;
}
This one instead cuts the string after the last occurrence of the pivot:
public static string truncateStringAfterLastChar(string input, char pivot){
return input.Split(pivot).Last();
}
Maybe you don't have a language file:
Language files are here: https://github.com/jquery/jquery-ui/tree/master/ui/i18n
A new localization should be created in a separate JavaScript file named ui.datepicker-.js. Within a document.ready event it should add a new entry into the $.datepicker.regional array, indexed by the language code, with the following attributes:
For Python 3+
for i in range(5):
print(str(i) + '\r', sep='', end ='', file = sys.stdout , flush = False)
The JSON sample you provided is not valid. Check it online with this JSON Validator http://jsonlint.com/. You need to remove the extra comma on line 59.
One you have valid json you can use this code to convert it to an array.
json_decode($json, true);
Array
(
[bpath] => http://www.sampledomain.com/
[clist] => Array
(
[0] => Array
(
[cid] => 11
[display_type] => grid
[ctitle] => abc
[acount] => 71
[alist] => Array
(
[0] => Array
(
[aid] => 6865
[adate] => 2 Hours ago
[atitle] => test
[adesc] => test desc
[aimg] =>
[aurl] => ?nid=6865
[weburl] => news.php?nid=6865
[cmtcount] => 0
)
[1] => Array
(
[aid] => 6857
[adate] => 20 Hours ago
[atitle] => test1
[adesc] => test desc1
[aimg] =>
[aurl] => ?nid=6857
[weburl] => news.php?nid=6857
[cmtcount] => 0
)
)
)
[1] => Array
(
[cid] => 1
[display_type] => grid
[ctitle] => test1
[acount] => 2354
[alist] => Array
(
[0] => Array
(
[aid] => 6851
[adate] => 1 Days ago
[atitle] => test123
[adesc] => test123 desc
[aimg] =>
[aurl] => ?nid=6851
[weburl] => news.php?nid=6851
[cmtcount] => 7
)
[1] => Array
(
[aid] => 6847
[adate] => 2 Days ago
[atitle] => test12345
[adesc] => test12345 desc
[aimg] =>
[aurl] => ?nid=6847
[weburl] => news.php?nid=6847
[cmtcount] => 7
)
)
)
)
)
Could use Tortoise:
http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-branchtag.html
You can try:
jar tvf jarfile.jar
This will be helpful only if your jar is executable i.e. in manifest you have defined some class as main class
This is a full solution (found in the Hackbook example from the Facebook SDK). It has the advantage of not needing access to the file itself. This is extremely useful if you are loading an image from the content resolver thingy (e.g. if your app is responding to a share-photo intent).
public static int getOrientation(Context context, Uri photoUri) {
/* it's on the external media. */
Cursor cursor = context.getContentResolver().query(photoUri,
new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);
if (cursor.getCount() != 1) {
return -1;
}
cursor.moveToFirst();
return cursor.getInt(0);
}
And then you can get a rotated Bitmap as follows. This code also scales down the image (badly unfortunately) to MAX_IMAGE_DIMENSION. Otherwise you may run out of memory.
public static Bitmap getCorrectlyOrientedImage(Context context, Uri photoUri) throws IOException {
InputStream is = context.getContentResolver().openInputStream(photoUri);
BitmapFactory.Options dbo = new BitmapFactory.Options();
dbo.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, dbo);
is.close();
int rotatedWidth, rotatedHeight;
int orientation = getOrientation(context, photoUri);
if (orientation == 90 || orientation == 270) {
rotatedWidth = dbo.outHeight;
rotatedHeight = dbo.outWidth;
} else {
rotatedWidth = dbo.outWidth;
rotatedHeight = dbo.outHeight;
}
Bitmap srcBitmap;
is = context.getContentResolver().openInputStream(photoUri);
if (rotatedWidth > MAX_IMAGE_DIMENSION || rotatedHeight > MAX_IMAGE_DIMENSION) {
float widthRatio = ((float) rotatedWidth) / ((float) MAX_IMAGE_DIMENSION);
float heightRatio = ((float) rotatedHeight) / ((float) MAX_IMAGE_DIMENSION);
float maxRatio = Math.max(widthRatio, heightRatio);
// Create the bitmap from file
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = (int) maxRatio;
srcBitmap = BitmapFactory.decodeStream(is, null, options);
} else {
srcBitmap = BitmapFactory.decodeStream(is);
}
is.close();
/*
* if the orientation is not 0 (or -1, which means we don't know), we
* have to do a rotation.
*/
if (orientation > 0) {
Matrix matrix = new Matrix();
matrix.postRotate(orientation);
srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(),
srcBitmap.getHeight(), matrix, true);
}
return srcBitmap;
}
Use the CSS pointer-events:none on fields you want to "disable" (possibly together with a greyed background) which allows the POST action, like:
<input type="text" class="disable">
.disable{
pointer-events:none;
background:grey;
}
Ref: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.
You have two options:
Grant write permissions to the folder to the user or group you log in with (myuser
), or change the ownership of the folder to the user, or
Disable a transfer to temporary file.
In Preferences, go to Transfer > Endurance page and in Enable transfer resume/transfer to temporary file name for select Disable:
If double-clicking on it brings up WinRAR, you need to change the program you are running it with. You can right-click on it and click "Open with". Java should be listed in there.
However, you must first upgrade your Java version to be compatible with that JAR.
this is one good answer to figure out how sorting works from another user and I will add my notes to know how it is not fully correct and what is correct:
The effect on the formula after a sort is the same as copying. A sort does not move the row contents, it copies them. The formula may (or may not depending on the abs/relative references) use new data, just as a copied formula does.
My point is that if the formula can be copied from 1 row to another and the effects don't change, the sorting will not affect the formula results. If the formulas are so complex and so dependent on position that copying them changes the relative contents, then don't sort them.
And my note that I experienced in practice:
The above user is saying right but in fact It has some exception: parts of a columns formula containing sheet name (like sheet1!A1) are treated as absolute references (in spite of copying that changes the references if they are relative ) so that part of formula will be copied without changing references relative to changing the place of formula This includes current sheet cells addressed fully like : sheet1!A2 and will be treated as absolute references(for sorting only) I tested this of excel 2010 and I do not think this issue be solved in other versions. The solution is to copy and past special as value in another place and then use sorting.
After SqlCommand cmd=new SqlCommand ("insert into time(project,iteration)values('....
Add
cmd.Connection = conn;
Hope this help
The Static variables are come into play once the program execution starts and it remain available till the program execution ends.
The Static variables are created in the Data Segment of the Memory.
To make an Image fill its parent, simply wrap it into a FittedBox
:
FittedBox(
child: Image.asset('foo.png'),
fit: BoxFit.fill,
)
FittedBox
here will stretch the image to fill the space.
(Note that this functionality used to be provided by BoxFit.fill
, but the API has meanwhile changed such that BoxFit
no longer provides this functionality. FittedBox
should work as a drop-in replacement, no changes need to be made to the constructor arguments.)
Alternatively, for complex decorations you can use a Container
instead of an Image
– and use decoration
/foregroundDecoration
fields.
To make the Container
will its parent, it should either:
alignment
property not null
Here's an example that combines two images and a Text
in a single Container
, while taking 100% width/height of its parent:
Container(
foregroundDecoration: const BoxDecoration(
image: DecorationImage(
image: NetworkImage(
'https://p6.storage.canalblog.com/69/50/922142/85510911_o.png'),
fit: BoxFit.fill),
),
decoration: const BoxDecoration(
image: DecorationImage(
alignment: Alignment(-.2, 0),
image: NetworkImage(
'http://www.naturerights.com/blog/wp-content/uploads/2017/12/Taranaki-NR-post-1170x550.png'),
fit: BoxFit.cover),
),
alignment: Alignment.bottomCenter,
padding: EdgeInsets.only(bottom: 20),
child: Text(
"Hello World",
style: Theme.of(context)
.textTheme
.display1
.copyWith(color: Colors.white),
),
),
For builtin JS types you can use:
function getTypeName(val) {
return {}.toString.call(val).slice(8, -1);
}
Here we use 'toString' method from 'Object' class which works different than the same method of another types.
Examples:
// Primitives
getTypeName(42); // "Number"
getTypeName("hi"); // "String"
getTypeName(true); // "Boolean"
getTypeName(Symbol('s'))// "Symbol"
getTypeName(null); // "Null"
getTypeName(undefined); // "Undefined"
// Non-primitives
getTypeName({}); // "Object"
getTypeName([]); // "Array"
getTypeName(new Date); // "Date"
getTypeName(function() {}); // "Function"
getTypeName(/a/); // "RegExp"
getTypeName(new Error); // "Error"
If you need a class name you can use:
instance.constructor.name
Examples:
({}).constructor.name // "Object"
[].constructor.name // "Array"
(new Date).constructor.name // "Date"
function MyClass() {}
let my = new MyClass();
my.constructor.name // "MyClass"
But this feature was added in ES2015.
Both IanSR and bchhun suggested overriding TEMPLATE_CONTEXT_PROCESSORS in the settings. Be aware that this setting has a default that can cause some screwy things if you override it without re-setting the defaults. The defaults have also changed in recent versions of Django.
https://docs.djangoproject.com/en/1.3/ref/settings/#template-context-processors
The default TEMPLATE_CONTEXT_PROCESSORS :
TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages")
That should fit your needs:
var yourComponent = React.createClass({
render: function () {
return (
<View style={{flex:1, flexDirection:'column', justifyContent:'center'}}>
<View style={{flexDirection:'row'}}>
<TextInput style={{flex:0.8, borderWidth:1, height:20}}></TextInput>
<View style={{flex:0.2}}></View> // spacer
</View>
</View>
);
}
});