I agree with bizl
[XmlInclude(typeof(ParentOfTheItem))]
[Serializable]
public abstract class WarningsType{ }
also if you need to apply this included class to an object item you can do like that
[System.Xml.Serialization.XmlElementAttribute("Warnings", typeof(WarningsType))]
public object[] Items
{
get
{
return this.itemsField;
}
set
{
this.itemsField = value;
}
}
In case of a very large stream length there is the hazard of memory leak due to Large Object Heap. i.e. The byte buffer created by stream.ToArray creates a copy of memory stream in Heap memory leading to duplication of reserved memory. I would suggest to use a StreamReader
, a TextWriter
and read the stream in chunks of char
buffers.
In netstandard2.0 System.IO.StreamReader
has a method ReadBlock
you can use this method in order to read the instance of a Stream (a MemoryStream instance as well since Stream is the super of MemoryStream):
private static string ReadStreamInChunks(Stream stream, int chunkLength)
{
stream.Seek(0, SeekOrigin.Begin);
string result;
using(var textWriter = new StringWriter())
using (var reader = new StreamReader(stream))
{
var readChunk = new char[chunkLength];
int readChunkLength;
//do while: is useful for the last iteration in case readChunkLength < chunkLength
do
{
readChunkLength = reader.ReadBlock(readChunk, 0, chunkLength);
textWriter.Write(readChunk,0,readChunkLength);
} while (readChunkLength > 0);
result = textWriter.ToString();
}
return result;
}
NB. The hazard of memory leak is not fully eradicated, due to the usage of MemoryStream, that can lead to memory leak for large memory stream instance (memoryStreamInstance.Size >85000 bytes). You can use Recyclable Memory stream, in order to avoid LOH. This is the relevant library
.NET 4.5 is not a side-by-side version, it replaces the assemblies for 4.0. Much like .NET 3.0, 3.5 and 3.5SP1 replaced the assemblies for 2.0. And added some new ones. The CLR version is still 4.0.30319. You only care about the reference assemblies, they are in c:\program files\reference assemblies.
This means that somewhere else in your code, you have something like:
sum = 0
Which shadows the builtin sum (which is callable) with an int (which isn't).
You can have multiple identical hash keys; but only if you have a range key that varies. Think of it like file formats; you can have 2 files with the same name in the same folder as long as their format is different. If their format is the same, their name must be different. The same concept applies to DynamoDB's hash/range keys; just think of the hash as the name and the range as the format.
Also, I don't recall if they had these at the time of the OP (I don't believe they did), but they now offer Local Secondary Indexes.
My understanding of these is that it should now allow you to perform the desired queries without having to do a full scan. The downside is that these indexes have to be specified at table creation, and also (I believe) cannot be blank when creating an item. In addition, they require additional throughput (though typically not as much as a scan) and storage, so it's not a perfect solution, but a viable alternative, for some.
I do still recommend Mike Brant's answer as the preferred method of using DynamoDB, though; and use that method myself. In my case, I just have a central table with only a hash key as my ID, then secondary tables that have a hash and range that can be queried, then the item points the code to the central table's "item of interest", directly.
Additional data regarding the secondary indexes can be found in Amazon's DynamoDB documentation here for those interested.
Anyway, hopefully this will help anyone else that happens upon this thread.
Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.
git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67
Then, abort the rebase again.
You can pass array or dictionary. Here, I am taking NSMutableDictionary.
NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
[contentDictionary setValue:@"a" forKey:@"b"];
[contentDictionary setValue:@"c" forKey:@"d"];
To generate a JSON string from a NSDictionary or NSArray, You don't need to import any third party framework. Just use following code:-
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:contentDictionary // Here you can pass array or dictionary
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
NSString *jsonString;
if (jsonData) {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//This is your JSON String
//NSUTF8StringEncoding encodes special characters using an escaping scheme
} else {
NSLog(@"Got an error: %@", error);
jsonString = @"";
}
NSLog(@"Your JSON String is %@", jsonString);
C:\>FORFILES /C "cmd /c echo @fname @fsize"
C:\>FORFILES /?
FORFILES [/P pathname] [/M searchmask] [/S]
[/C command] [/D [+ | -] {MM/dd/yyyy | dd}]
Description:
Selects a file (or set of files) and executes a
command on that file. This is helpful for batch jobs.
Parameter List:
/P pathname Indicates the path to start searching.
The default folder is the current working
directory (.).
The simplest solution is to select the second cell, and press =
. This will begin the fomula creation process. Now either type in the 1st cell reference (eg, A1
) or click on the first cell and press enter. This should make the second cell reference the value of the first cell.
To read up more on different options for referencing see - This Article.
Basically the Kernel is the interface between hardware (devices which are available in Computer) and Application software is like MS Office, Visual Studio, etc.
If I answer "what is an OS?" then the answer could be the same. Hence the kernel is the part & core of the OS.
The very sensitive tasks of an OS like memory management, I/O management, process management are taken care of by the kernel only.
So the ultimate difference is:
CentOS 7: I had the libcurl and gnutls development packages installed already, but still got the "cannot load git2r.so" error when installing devtools in R. I had to "reinstall" them for it to work:
sudo yum reinstall gnutls-devel.x86_64
natural left
or natural right
) that assumes the join criteria to be where same-named columns in both table matchI would avoid using natural joins like the plague, because natural joins are:
How big is your sample? Here is another option to test your data against any distribution using OpenTURNS library. In the example below, I generate a sample x of 1.000.000 numbers from a Uniform distribution and test it against a Normal distribution.
You can replace x by your data if you reshape it as x= [[x1], [x2], .., [xn]]
import openturns as ot
x = ot.Uniform().getSample(1000000)
g = ot.VisualTest.DrawQQplot(x, ot.Normal())
g
In my Jupyter Notebook, I see:
If you are writing a script, you can do it more properly
from openturns.viewer import View`
import matplotlib.pyplot as plt
View(g)
plt.show()
I just used :first
as CSS selector successfully.
.red:first
ALTER TABLE [TableName] ADD CONSTRAINT [constraintName] UNIQUE ([columns])
It is the version key.It gets updated whenever a new update is made. I personally don't like to disable it .
Read this solution if you want to know more [1]: Mongoose versioning: when is it safe to disable it?
Except when it is the operand of the sizeof
or unary &
operator, or is a string literal being used to initialize another array in a declaration, an expression of type "N-element array of T
" is converted ("decays") to an expression of type "pointer to T
", and the value of the expression is the address of the first element of the array.
If the declaration of the array being passed is
int S[4][4] = {...};
then when you write
rotateArr( S );
the expression S
has type "4-element array of 4-element array of int
"; since S
is not the operand of the sizeof
or unary &
operators, it will be converted to an expression of type "pointer to 4-element array of int
", or int (*)[4]
, and this pointer value is what actually gets passed to rotateArr
. So your function prototype needs to be one of the following:
T rotateArr( int (*arr)[4] )
or
T rotateArr( int arr[][4] )
or even
T rotateArr( int arr[4][4] )
In the context of a function parameter list, declarations of the form T a[N]
and T a[]
are interpreted as T *a
; all three declare a
as a pointer to T
.
You're probably wondering why I changed the return type from int
to T
. As written, you're trying to return a value of type "4-element array of 4-element array of int
"; unfortunately, you can't do that. C functions cannot return array types, nor can you assign array types. IOW, you can't write something like:
int a[N], b[N];
...
b = a; // not allowed
a = f(); // not allowed either
Functions can return pointers to arrays, but that's not what you want here. D
will cease to exist once the function returns, so any pointer you return will be invalid.
If you want to assign the results of the rotated array to a different array, then you'll have to pass the target array as a parameter to the function:
void rotateArr( int (*dst)[4], int (*src)[4] )
{
...
dst[i][n] = src[n][M - i + 1];
...
}
And call it as
int S[4][4] = {...};
int D[4][4];
rotateArr( D, S );
After looking around on Google for a long time, trying out several solutions, both CSS, JavaScript and JQuery, i found that most of them were using an Image as the button. Some of them were hard to use, but i did manage to piece together something that ended out working out for me.
The important parts for me was:
This is the solution i came up with. And hope it can be of use to others as well.
Change the width of .file_input_textbox to change the width of the textbox.
Change the width of both .file_input_div, .file_input_button and .file_input_button_hover to change the width of the button. You might need to tweak a bit on the positions also. I never figured out why...
To test this solution, make a new html file and paste the content into it.
<html>
<head>
<style type="text/css">
.file_input_textbox {height:25px;width:200px;float:left; }
.file_input_div {position: relative;width:80px;height:26px;overflow: hidden; }
.file_input_button {width: 80px;position:absolute;top:0px;
border:1px solid #F0F0EE;padding:2px 8px 2px 8px; font-weight:bold; height:25px; margin:0px; margin-right:5px; }
.file_input_button_hover{width:80px;position:absolute;top:0px;
border:1px solid #0A246A; background-color:#B2BBD0;padding:2px 8px 2px 8px; height:25px; margin:0px; font-weight:bold; margin-right:5px; }
.file_input_hidden {font-size:45px;position:absolute;right:0px;top:0px;cursor:pointer;
opacity:0;filter:alpha(opacity=0);-ms-filter:"alpha(opacity=0)";-khtml-opacity:0;-moz-opacity:0; }
</style>
</head>
<body>
<input type="text" id="fileName" class="file_input_textbox" readonly="readonly">
<div class="file_input_div">
<input id="fileInputButton" type="button" value="Browse" class="file_input_button" />
<input type="file" class="file_input_hidden"
onchange="javascript: document.getElementById('fileName').value = this.value"
onmouseover="document.getElementById('fileInputButton').className='file_input_button_hover';"
onmouseout="document.getElementById('fileInputButton').className='file_input_button';" />
</div>
</body>
</html>
Try this:
header('location: xyz.php'); //thats all for redirecting to another php file
You can't use memcmp to compare structs for equality due to potential random padding characters between field in structs.
// bad
memcmp(&struct1, &struct2, sizeof(struct1));
The above would fail for a struct like this:
typedef struct Foo {
char a;
/* padding */
double d;
/* padding */
char e;
/* padding */
int f;
} Foo ;
You have to use member-wise comparison to be safe.
This is a direct conversion from your PHP code:
//Loading the variable
var mystr = '0000000020C90037:TEMP:data';
//Splitting it with : as the separator
var myarr = mystr.split(":");
//Then read the values from the array where 0 is the first
//Since we skipped the first element in the array, we start at 1
var myvar = myarr[1] + ":" + myarr[2];
// Show the resulting value
console.log(myvar);
// 'TEMP:data'
$x = '1234567'; echo substr ($x, 0, 3); // outputs 123 echo substr ($x, 1, 1); // outputs 2 echo substr ($x, -2); // outputs 67 echo substr ($x, 1); // outputs 234567 echo substr ($x, -2, 1); // outputs 6
This page helped me fix the issue.
Fix for Unity disconnected from Visual Studio
In the Unity Editor, select the Edit > Preferences menu..
Select the External Tools tab on the left.
Select unity version from drop down list on the right
Click regenerate Files
You Done
This should work:
s=json.dumps(variables)
variables2=json.loads(s)
assert(variables==variables2)
In eclipse Galileo :
From there you can Add External Jars
The following will display all 3 buttons on the same line provided there is enough horizontal space to display them:
<button type="submit" class="msgBtn" onClick="return false;" >Save</button>
<button type="submit" class="msgBtn2" onClick="return false;">Publish</button>
<button class="msgBtnBack">Back</button>
// Note the lack of unnecessary divs, floats, etc.
The only reason the buttons wouldn't display inline is if they have had display:block applied to them within your css.
If none of the previous solution are working for you, why not add some validation on combobox something like,
var orginalindex = 0;
private void comboBox1_SelectedItemChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == 0)
{
comboBox1.Text = "Select one of the answers";
comboBox1.SelectedIndex = comboBox1.SelectedIndex;
}
else
{
orginalindex = comboBox1.SelectedIndex;
}
}
Take a look at Numeral.js. It can format numbers, currency, percentages and has support for localization.
Using SQL Server Management Studio
To configure the default language option
English
.Using Transact-SQL
To configure the default language option
This example shows how to use sp_configure to configure the default language option to French
USE AdventureWorks2012 ;
GO
EXEC sp_configure 'default language', 2 ;
GO
RECONFIGURE ;
GO
The 33 languages of SQL Server
| LANGID | ALIAS |
|--------|---------------------|
| 0 | English |
| 1 | German |
| 2 | French |
| 3 | Japanese |
| 4 | Danish |
| 5 | Spanish |
| 6 | Italian |
| 7 | Dutch |
| 8 | Norwegian |
| 9 | Portuguese |
| 10 | Finnish |
| 11 | Swedish |
| 12 | Czech |
| 13 | Hungarian |
| 14 | Polish |
| 15 | Romanian |
| 16 | Croatian |
| 17 | Slovak |
| 18 | Slovenian |
| 19 | Greek |
| 20 | Bulgarian |
| 21 | Russian |
| 22 | Turkish |
| 23 | British English |
| 24 | Estonian |
| 25 | Latvian |
| 26 | Lithuanian |
| 27 | Brazilian |
| 28 | Traditional Chinese |
| 29 | Korean |
| 30 | Simplified Chinese |
| 31 | Arabic |
| 32 | Thai |
| 33 | Bokmål |
I had a similar issue when onMouseEnter was called but sometimes the corresponding onMouseLeave event wasn't fired, here is a workaround that works well for me (it partially relies on jQuery):
var Hover = React.createClass({
getInitialState: function() {
return {
hover: false
};
},
onMouseEnterHandler: function(e) {
this.setState({
hover: true
});
console.log('enter');
$(e.currentTarget).one("mouseleave", function (e) {
this.onMouseLeaveHandler();
}.bind(this));
},
onMouseLeaveHandler: function() {
this.setState({
hover: false
});
console.log('leave');
},
render: function() {
var inner = normal;
if(this.state.hover) {
inner = hover;
}
return (
<div style={outer}>
<div style={inner}
onMouseEnter={this.onMouseEnterHandler} >
{this.props.children}
</div>
</div>
);
}
});
See on jsfiddle: http://jsfiddle.net/qtbr5cg6/1/
Why was it happening (in my case): I am running a jQuery scrolling animation (through $('#item').animate({ scrollTop: 0 })
) when clicking on the item. So the cursor doesn't leave the item "naturally", but during a the JavaScript-driven animation ... and in this case the onMouseLeave was not fired properly by React (React 15.3.0, Chrome 51, Desktop)
This seems to be already asked before:
This might help:
Twitter Bootstrap Use collapse.js on table cells [Almost Done]
UPDATE:
Your fiddle wasn't loading jQuery, so anything worked.
<table class="table table-hover">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr data-toggle="collapse" data-target="#accordion" class="clickable">
<td>Some Stuff</td>
<td>Some more stuff</td>
<td>And some more</td>
</tr>
<tr>
<td colspan="3">
<div id="accordion" class="collapse">Hidden by default</div>
</td>
</tr>
</tbody>
</table>
Try this one: http://jsfiddle.net/Nb7wy/2/
I also added colspan='2'
to the details row. But it's essentially your fiddle with jQuery loaded (in frameworks in the left column)
use request.getContextPath()
instead of ${pageContext.request.contextPath}
in JSP expression language.
<%
String contextPath = request.getContextPath();
%>
out.println(contextPath);
output: willPrintMyProjectcontextPath
Hibernate also is picky about the capitalization. By default it's going to be the class name with the First letter Capitalized. So if your class is called FooBar
, don't pass "foobar"
. You have to pass "FooBar"
with that exact capitalization for it to work.
This is working for me-:
public static bool IsPropertyExist(dynamic dynamicObj, string property)
{
try
{
var value=dynamicObj[property].Value;
return true;
}
catch (RuntimeBinderException)
{
return false;
}
}
Let me provide complete code for execution protected methods via reflection. It supports any types of params including generics, autoboxed params and null values
@SuppressWarnings("unchecked")
public static <T> T executeSuperMethod(Object instance, String methodName, Object... params) throws Exception {
return executeMethod(instance.getClass().getSuperclass(), instance, methodName, params);
}
public static <T> T executeMethod(Object instance, String methodName, Object... params) throws Exception {
return executeMethod(instance.getClass(), instance, methodName, params);
}
@SuppressWarnings("unchecked")
public static <T> T executeMethod(Class clazz, Object instance, String methodName, Object... params) throws Exception {
Method[] allMethods = clazz.getDeclaredMethods();
if (allMethods != null && allMethods.length > 0) {
Class[] paramClasses = Arrays.stream(params).map(p -> p != null ? p.getClass() : null).toArray(Class[]::new);
for (Method method : allMethods) {
String currentMethodName = method.getName();
if (!currentMethodName.equals(methodName)) {
continue;
}
Type[] pTypes = method.getParameterTypes();
if (pTypes.length == paramClasses.length) {
boolean goodMethod = true;
int i = 0;
for (Type pType : pTypes) {
if (!ClassUtils.isAssignable(paramClasses[i++], (Class<?>) pType)) {
goodMethod = false;
break;
}
}
if (goodMethod) {
method.setAccessible(true);
return (T) method.invoke(instance, params);
}
}
}
throw new MethodNotFoundException("There are no methods found with name " + methodName + " and params " +
Arrays.toString(paramClasses));
}
throw new MethodNotFoundException("There are no methods found with name " + methodName);
}
Method uses apache ClassUtils for checking compatibility of autoboxed params
I am not sure how to see the actual rows/records that come back.
Stored procedures do not return records. They may have a cursor as an output parameter, which is a pointer to a select statement. But it requires additional action to actually bring back rows from that cursor.
In SQL Developer, you can execute a procedure that returns a ref cursor as follows
var rc refcursor
exec proc_name(:rc)
After that, if you execute the following, it will show the results from the cursor:
print rc
Here's a good place to use the FormArray
https://angular.io/docs/ts/latest/api/forms/index/FormArray-class.html
To start we'll build up our array of controls either with a FormBuilder
or newing up a FormArray
FormBuilder
this.checkboxGroup = _fb.group({
myValues: _fb.array([true, false, true])
});
new FormArray
let checkboxArray = new FormArray([
new FormControl(true),
new FormControl(false),
new FormControl(true)]);
this.checkboxGroup = _fb.group({
myValues: checkboxArray
});
Easy enough to do, but then we're going to change our template and let the templating engine handle how we bind to our controls:
template.html
<form [formGroup]="checkboxGroup">
<input *ngFor="let control of checkboxGroup.controls['myValues'].controls"
type="checkbox" id="checkbox-1" value="value-1" [formControl]="control" />
</form>
Here we're iterating over our set of FormControls
in our myValues
FormArray
and for each control we're binding [formControl]
to that control instead of to the FormArray
control and <div>{{checkboxGroup.controls['myValues'].value}}</div>
produces true,false,true
while also making your template syntax a little less manual.
You can use this example: http://plnkr.co/edit/a9OdMAq2YIwQFo7gixbj?p=preview to poke around
Finally, I found a solution to know if the current item is visible, from the onBindViewHolder event in the adapter.
The key is the method isViewPartiallyVisible from LayoutManager.
In your adapter, you can get the LayoutManager from the RecyclerView, which you get as parameter from the onAttachedToRecyclerView event.
Since the value of $var
is the empty string, this:
if [ $var == $var1 ]; then
expands to this:
if [ == abcd ]; then
which is a syntax error.
You need to quote the arguments:
if [ "$var" == "$var1" ]; then
You can also use =
rather than ==
; that's the original syntax, and it's a bit more portable.
If you're using bash, you can use the [[
syntax, which doesn't require the quotes:
if [[ $var = $var1 ]]; then
Even then, it doesn't hurt to quote the variable reference, and adding quotes:
if [[ "$var" = "$var1" ]]; then
might save a future reader a moment trying to remember whether [[
... ]]
requires them.
I will provide a simple and general answer that works with any number of audios and srt subtitles and respects the metadata that may include the mkv container. So it will even add the images the matroska may include as attachments (though not another types AFAIK) and convert them to tracks; you will not be able to watch but they will be there (you can demux them). Ah, and if the mkv has chapters the mp4 too.
ffmpeg -i <mkv-input> -c copy -map 0 -c:s mov_text <mp4-output>
As you can see, it's all about the -map 0
, that tells FFmpeg to add all the tracks, which includes metadata, chapters, attachments, etc. If there is an unrecognized "track" (mkv allows to attach any type of file), it will end with an error.
You can create a simple batch mkv2mp4.bat
, if you usually do this, to create an mp4 with the same name as the mkv. It would be better with error control, a different output name, etc., but you get the point.
@ffmpeg -i %1 -c copy -map 0 -c:s mov_text "%~n1.mp4"
Now you can simply run
mkv2mp4 "Video with subtitles etc.mkv"
And it will create "Video with subtitles etc.mp4" with the maximum of information included.
You can also implement the like queries using Spring Data JPA supported keyword "Containing".
List<Registration> findByPlaceContaining(String place);
Save the state of nocasematch (in case some other function is depending on it being disabled):
local orig_nocasematch=$(shopt -p nocasematch)
shopt -s nocasematch
[[ "foo" == "Foo" ]] && echo "match" || echo "notmatch"
$orig_nocasematch
Note: only use local
if it's inside a function.
Shove it in the ViewBag
:
Controller:
ViewBag.ProductId = 1;
View:
@Html.TextBoxFor(c => c.Propertyname, new {@Value = ViewBag.ProductId})
Oddly enough, the issue for me was I was trying to open 2012 SQL Server Integration Services on SSMS 2008 R2. When I opened the same in SSMS 2012, it connected right away.
One issue with your ContentLoader is that internally it operates sequentially. A better pattern is to parallelize the work and then sychronize at the end, so we get
public class PageViewModel : IHandle<SomeMessage>
{
...
public async void Handle(SomeMessage message)
{
ShowLoadingAnimation();
// makes UI very laggy, but still not dead
await this.contentLoader.LoadContentAsync();
HideLoadingAnimation();
}
}
public class ContentLoader
{
public async Task LoadContentAsync()
{
var tasks = new List<Task>();
tasks.Add(DoCpuBoundWorkAsync());
tasks.Add(DoIoBoundWorkAsync());
tasks.Add(DoCpuBoundWorkAsync());
tasks.Add(DoSomeOtherWorkAsync());
await Task.WhenAll(tasks).ConfigureAwait(false);
}
}
Obviously, this doesn't work if any of the tasks require data from other earlier tasks, but should give you better overall throughput for most scenarios.
I've created that effect on my blog Landman Code.
What I did was
#Header {
position: relative;
}
#Header H1 {
font-size: 3em;
color: #00FF00;
margin:0;
padding:0;
}
#Header H2 {
font-size: 1.5em;
color: #FFFF00;
margin:0;
padding:0;
}
#Header .Background {
background: #557700;
filter: alpha(opacity=30);
filter: progid: DXImageTransform.Microsoft.Alpha(opacity=30);
-moz-opacity: 0.30;
opacity: 0.3;
zoom: 1;
}
#Header .Background * {
visibility: hidden; // hide the faded text
}
#Header .Foreground {
position: absolute; // position on top of the background div
left: 0;
top: 0;
}
_x000D_
<div id="Header">
<div class="Background">
<h1>Title</h1>
<h2>Subtitle</h2>
</div>
<div class="Foreground">
<h1>Title</h1>
<h2>Subtitle</h2>
</div>
</div>
_x000D_
The important thing that every padding/margin and content must be the same in both the .Background as .Foreground.
For fine control, consider an InputVerifier using the SimpleDateFormat("YYYY-MM-dd")
suggested by Steve B.
The values you provided are UTF-8 values. When set, the array of:
declare -a ARR=(0xA7 0x9B 0x46 0x8D 0x1E 0x52 0xA7 0x9B 0x7B 0x31 0xD2)
Will be parsed to print the plaintext characters of each value.
for ((n=0; n < ${#ARR[*]}; n++)); do echo -e "\u${ARR[$n]//0x/}"; done
And the output will yield a few printable characters and some non-printable characters as shown here:
For converting hex values to plaintext using the echo
command:
echo -e "\x<hex value here>"
And for converting UTF-8 values to plaintext using the echo
command:
echo -e "\u<UTF-8 value here>"
And then for converting octal to plaintext using the echo
command:
echo -e "\0<octal value here>"
When you have encoding values you aren't familiar with, take the time to check out the ranges in the common encoding schemes to determine what encoding a value belongs to. Then conversion from there is a snap.
There are many answers and all are correct as well. But unfortunately none of them have a clear explanation.
The following works for a non-primary key mapping as well.
Let's say we have parent table A with column 1 and another table, B, with column 2 which references column 1:
@ManyToOne
@JoinColumn(name = "TableBColumn", referencedColumnName = "TableAColumn")
private TableA session_UserName;
@ManyToOne
@JoinColumn(name = "bok_aut_id", referencedColumnName = "aut_id")
private Author bok_aut_id;
I recently worked on a project to read the RFID tags. The project used the Devices from manufacturers like Zebra (we were using RFD8500 ) & TSL.
More devices are from Motorola & other vendors as well!
We have to use the native SDK api's provided by the manufacturer, how it works is by pairing the device by the Bluetooth of the phones and so the data transfer between both devices take place! The programming is based on subscribe pattern where the scan should be read by the device trigger(hardware trigger) or soft trigger (from the application).
The Tag read gives us the tagId & the RSSI which is the distance factor from the RFID tags!
This is the sample app:
We get all the device paired to our Android/iOS phones :
This what I came up with, since I need to run several operations in a chain.
<button onclick="tprom('Hello Niclas')">test promise</button>
<script>
function tprom(mess) {
console.clear();
var promise = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve(mess);
}, 2000);
});
var promise2 = new Promise(async function (resolve, reject) {
await promise;
setTimeout(function () {
resolve(mess + ' ' + mess);
}, 2000);
});
var promise3 = new Promise(async function (resolve, reject) {
await promise2;
setTimeout(function () {
resolve(mess + ' ' + mess+ ' ' + mess);
}, 2000);
});
promise.then(function (data) {
console.log(data);
});
promise2.then(function (data) {
console.log(data);
});
promise3.then(function (data) {
console.log(data);
});
}
</script>
Just create a Pair<TFirst, TSecond>
type and use that as your value.
I have an example of one in my C# in Depth source code. Reproduced here for simplicity:
using System;
using System.Collections.Generic;
public sealed class Pair<TFirst, TSecond>
: IEquatable<Pair<TFirst, TSecond>>
{
private readonly TFirst first;
private readonly TSecond second;
public Pair(TFirst first, TSecond second)
{
this.first = first;
this.second = second;
}
public TFirst First
{
get { return first; }
}
public TSecond Second
{
get { return second; }
}
public bool Equals(Pair<TFirst, TSecond> other)
{
if (other == null)
{
return false;
}
return EqualityComparer<TFirst>.Default.Equals(this.First, other.First) &&
EqualityComparer<TSecond>.Default.Equals(this.Second, other.Second);
}
public override bool Equals(object o)
{
return Equals(o as Pair<TFirst, TSecond>);
}
public override int GetHashCode()
{
return EqualityComparer<TFirst>.Default.GetHashCode(first) * 37 +
EqualityComparer<TSecond>.Default.GetHashCode(second);
}
}
In addition to the above comments, I would like to add few points about Views.
It is possible and you don't need to code it on your own.
Just set the ringer volume to zero and vibration to none if incomingNumber equals an empty string. Thats it ...
Its just done for you with the application Nostalk from Android Market. Just give it a try ...
Differences in In python 2 and 3 version:
If you already have a default method in a class with same name and you re-declare as a same name it will appear as unbound-method call of that class instance when you wanted to instantiated it.
If you wanted class methods, but you declared them as instance methods instead.
An instance method is a method that is used when to create an instance of the class.
An example would be
def user_group(self): #This is an instance method
return "instance method returning group"
Class label method:
@classmethod
def user_group(groups): #This is an class-label method
return "class method returning group"
In python 2 and 3 version differ the class @classmethod to write in python 3 it automatically get that as a class-label method and don't need to write @classmethod I think this might help you.
When using regular expressions from RegexBuddy's library, make sure to use the same matching modes in your own code as the regex from the library. If you generate a source code snippet on the Use tab, RegexBuddy will automatically set the correct matching options in the source code snippet. If you copy/paste the regex, you have to do that yourself.
In this case, as others pointed out, you missed the case insensitivity option.
Use Split-Path
$filePath = "C:\PS\Test.Documents\myTestFile.txt";
$fileName = (Split-Path -Path $filePath -Leaf).Split(".")[0];
$extension = (Split-Path -Path $filePath -Leaf).Split(".")[1];
You should just pass the variable (or data) inside "mysql_real_escape_string(trim($val))"
where $val
is the data which is troubling you.
Is this code snippet work for you?
if (!count($_SESSION)>0) {
session_start();
}
If you want to perform any event on any specific keyboard button press, in that case, you can use @HostListener. For this, you have to import HostListener in your component ts file.
import { HostListener } from '@angular/core';
then use below function anywhere in your component ts file.
@HostListener('document:keyup', ['$event'])
handleDeleteKeyboardEvent(event: KeyboardEvent) {
if(event.key === 'Delete')
{
// remove something...
}
}
Add the log4j.properties file to the runtime class path of the project. Some people add this to the root of the source tree (so that it gets copied to the root of the compiled classes).
Edit: If your project is a maven project, you can put the log4j.properties in the src/main/resources folder (and the src/test/resources for your unit tests).
If you have multiple environments (for example development and production), want different logging for each environment, and want to deploy the same jar (or war, or ear) file to each environment (as in one build for all environments) then store the log4j.properties file outside of the jar file and put it in the class path for each environment (configurable by environment). Historically, I would include some known directory in each environment in the classpath and deploy environment specific stuff there. For example, ~tomcat_user/localclasspath where ~tomcat_user is the home directory of the user that will be running the tomcat instance to which my war file will be deployed.
There is no need to explicitly check $?
. Just do:
ps aux | grep some_proces[s] > /tmp/test.txt && echo 1 || echo 0
Note that this relies on echo not failing, which is certainly not guaranteed. A more reliable way to write this is:
if ps aux | grep some_proces[s] > /tmp/test.txt; then echo 1; else echo 0; fi
Use Not IsEmpty()
.
For example:
Sub DoStuffIfNotEmpty()
If Not IsEmpty(ActiveCell.Value) Then
MsgBox "I'm not empty!"
End If
End Sub
I'm coming from a SQL Server background also and spent the past 2 weeks figuring out how to run scripts like this in IBM Data Studio. Hope it helps.
CREATE VARIABLE v_lookupid INTEGER DEFAULT (4815162342); --where 4815162342 is your variable data
SELECT * FROM DB1.PERSON WHERE PERSON_ID = v_lookupid;
SELECT * FROM DB1.PERSON_DATA WHERE PERSON_ID = v_lookupid;
SELECT * FROM DB1.PERSON_HIST WHERE PERSON_ID = v_lookupid;
DROP VARIABLE v_lookupid;
One of the easiest ways to achiever what is mentioned in the question is by using CONTAINS with NEAR or '~'. For example the following queries would give us all the columns that specifically include word1, word2 and word3.
SELECT * FROM MyTable WHERE CONTAINS(Column1, 'word1 NEAR word2 NEAR word3')
SELECT * FROM MyTable WHERE CONTAINS(Column1, 'word1 ~ word2 ~ word3')
In addition, CONTAINSTABLE returns a rank for each document based on the proximity of "word1", "word2" and "word3". For example, if a document contains the sentence, "The word1 is word2 and word3," its ranking would be high because the terms are closer to one another than in other documents.
One other thing that I would like to add is that we can also use proximity_term to find columns where the words are inside a specific distance between them inside the column phrase.
Html file (/index.html)
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<link rel="stylesheet" media="screen" href="assets/css/style.css" />
</head>
<body>
<h1>Background Image</h1>
</body>
</html>
Css file (/assets/css/style.css)
body{
background:url(../img/bg.jpg);
}
You can use .filter()
method of the Array
object:
var filtered = workItems.filter(function(element) {
// Create an array using `.split()` method
var cats = element.category.split(' ');
// Filter the returned array based on specified filters
// If the length of the returned filtered array is equal to
// length of the filters array the element should be returned
return cats.filter(function(cat) {
return filtersArray.indexOf(cat) > -1;
}).length === filtersArray.length;
});
Some old browsers like IE8 doesn't support .filter()
method of the Array
object, if you are using jQuery you can use .filter()
method of jQuery object.
jQuery version:
var filtered = $(workItems).filter(function(i, element) {
var cats = element.category.split(' ');
return $(cats).filter(function(_, cat) {
return $.inArray(cat, filtersArray) > -1;
}).length === filtersArray.length;
});
You could try something like:
WebElement rxBtn = driver.findElement(By.className("icon-rx"));
WebElement otcBtn = driver.findElement(By.className("icon-otc"));
WebElement herbBtn = driver.findElement(By.className("icon-herb"));
Assert.assertEquals(true, rxBtn.isDisplayed());
Assert.assertEquals(true, otcBtn.isDisplayed());
Assert.assertEquals(true, herbBtn.isDisplayed());
This is just an example. Basically you declare and define the WebElement variables you wish to use and then Assert
whether or not they are displayed. This is using TestNG Assertions.
Below is the Patrick Desjardins (alias Daok) code with a bit of comments added and some minor changes:
/*
decimal_sep: character used as decimal separator, it defaults to '.' when omitted
thousands_sep: char used as thousands separator, it defaults to ',' when omitted
*/
Number.prototype.toMoney = function(decimals, decimal_sep, thousands_sep)
{
var n = this,
c = isNaN(decimals) ? 2 : Math.abs(decimals), //if decimal is zero we must take it, it means user does not want to show any decimal
d = decimal_sep || '.', //if no decimal separator is passed we use the dot as default decimal separator (we MUST use a decimal separator)
/*
according to [https://stackoverflow.com/questions/411352/how-best-to-determine-if-an-argument-is-not-sent-to-the-javascript-function]
the fastest way to check for not defined parameter is to use typeof value === 'undefined'
rather than doing value === undefined.
*/
t = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep, //if you don't want to use a thousands separator you can pass empty string as thousands_sep value
sign = (n < 0) ? '-' : '',
//extracting the absolute value of the integer part of the number and converting to string
i = parseInt(n = Math.abs(n).toFixed(c)) + '',
j = ((j = i.length) > 3) ? j % 3 : 0;
return sign + (j ? i.substr(0, j) + t : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : '');
}
and here some tests:
//some tests (do not forget parenthesis when using negative numbers and number with no decimals)
alert(123456789.67392.toMoney() + '\n' + 123456789.67392.toMoney(3) + '\n' + 123456789.67392.toMoney(0) + '\n' + (123456).toMoney() + '\n' + (123456).toMoney(0) + '\n' + 89.67392.toMoney() + '\n' + (89).toMoney());
//some tests (do not forget parenthesis when using negative numbers and number with no decimals)
alert((-123456789.67392).toMoney() + '\n' + (-123456789.67392).toMoney(-3));
The minor changes are:
moved a bit the Math.abs(decimals)
to be done only when is not NaN
.
decimal_sep
can not be empty string anymore (a some sort of decimal separator is a MUST)
we use typeof thousands_sep === 'undefined'
as suggested in How best to determine if an argument is not sent to the JavaScript function
(+n || 0)
is not needed because this
is a Number
object
1---Enable protected mode for all zones You need to enable protected mode for all zones from Internet Options -> Security tab. To enable protected mode for all zones
Open Internet Explorer browser.
Go to menu Tools -> Internet Options.
Click on Security tab.
Select Internet from "Select a zone to view or change security settings" and Select(check) check box "Enable Protected Mode" from In the "Security level for this zone" block .
Apply same thing for all other 3 zones -> Local Internet, Trusted Sites and Restricted Sites
This setting will resolve error related to "Protected Mode settings are not the same for all zones.
2-- Set IE browser's zoom level 100%
Open Internet Explorer browser.
Go to menu View -> Zoom -> Select 100%
PHP 5.3 (an I think older versions too) seems to have problem with same name in different cases. So I had this problem when a had the class Login and the interface it implements LogIn. After I renamed LogIn to Log_In the problem got solved.
If method 1 has to be executed after method 2, 3, 4. The following code snippet can be the solution for this using Deferred object in JavaScript.
function method1(){_x000D_
var dfd = new $.Deferred();_x000D_
setTimeout(function(){_x000D_
console.log("Inside Method - 1"); _x000D_
method2(dfd); _x000D_
}, 5000);_x000D_
return dfd.promise();_x000D_
}_x000D_
_x000D_
function method2(dfd){_x000D_
setTimeout(function(){_x000D_
console.log("Inside Method - 2"); _x000D_
method3(dfd); _x000D_
}, 3000);_x000D_
}_x000D_
_x000D_
function method3(dfd){_x000D_
setTimeout(function(){_x000D_
console.log("Inside Method - 3"); _x000D_
dfd.resolve();_x000D_
}, 3000);_x000D_
}_x000D_
_x000D_
function method4(){ _x000D_
console.log("Inside Method - 4"); _x000D_
}_x000D_
_x000D_
var call = method1();_x000D_
_x000D_
$.when(call).then(function(cb){_x000D_
method4();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
One more thing to consider is whether or not the class could be used in an array:
foo bar[400];
In this scenario, there is no advantage to using the default parameter.
This would certainly NOT work:
foo bar("david", 34)[400]; // NOPE
You'll need a PDF API for C#. iTextSharp is one possible API, though better ones might exist.
iTextSharp Example
You must install iTextSharp.dll as a reference. Download iTextsharp from SourceForge.net This is a complete working program using a console application.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;
namespace GetPages_PDF
{
class Program
{
static void Main(string[] args)
{
// Right side of equation is location of YOUR pdf file
string ppath = "C:\\aworking\\Hawkins.pdf";
PdfReader pdfReader = new PdfReader(ppath);
int numberOfPages = pdfReader.NumberOfPages;
Console.WriteLine(numberOfPages);
Console.ReadLine();
}
}
}
It sounds like you want to use join
, e.g.:
var text = list.join();
The problem that I had with the change
handler was that it triggered on every keypress that I scrolled up and down the <select>
.
I wanted to get the event for whenever an option was clicked or when enter
was pressed on the desired option. This is how I ended up doing it:
let blockChange = false;
$element.keydown(function (e) {
const keycode = (e.keyCode ? e.keyCode : e.which);
// prevents select opening when enter is pressed
if (keycode === 13) {
e.preventDefault();
}
// lets the change event know that these keypresses are to be ignored
if([38, 40].indexOf(keycode) > -1){
blockChange = true;
}
});
$element.keyup(function(e) {
const keycode = (e.keyCode ? e.keyCode : e.which);
// handle enter press
if(keycode === 13) {
doSomething();
}
});
$element.change(function(e) {
// this effective handles the click only as preventDefault was used on enter
if(!blockChange) {
doSomething();
}
blockChange = false;
});
It's difficult without specifying what decimal separator to look for, but if you do, this is what I'm using:
public static double Parse(string str, char decimalSep)
{
string s = GetInvariantParseString(str, decimalSep);
return double.Parse(s, System.Globalization.CultureInfo.InvariantCulture);
}
public static bool TryParse(string str, char decimalSep, out double result)
{
// NumberStyles.Float | NumberStyles.AllowThousands got from Reflector
return double.TryParse(GetInvariantParseString(str, decimalSep), NumberStyles.Float | NumberStyles.AllowThousands, System.Globalization.CultureInfo.InvariantCulture, out result);
}
private static string GetInvariantParseString(string str, char decimalSep)
{
str = str.Replace(" ", "");
if (decimalSep != '.')
str = SwapChar(str, decimalSep, '.');
return str;
}
public static string SwapChar(string value, char from, char to)
{
if (value == null)
throw new ArgumentNullException("value");
StringBuilder builder = new StringBuilder();
foreach (var item in value)
{
char c = item;
if (c == from)
c = to;
else if (c == to)
c = from;
builder.Append(c);
}
return builder.ToString();
}
private static void ParseTestErr(string p, char p_2)
{
double res;
bool b = TryParse(p, p_2, out res);
if (b)
throw new Exception();
}
private static void ParseTest(double p, string p_2, char p_3)
{
double d = Parse(p_2, p_3);
if (d != p)
throw new Exception();
}
static void Main(string[] args)
{
ParseTest(100100100.100, "100.100.100,100", ',');
ParseTest(100100100.100, "100,100,100.100", '.');
ParseTest(100100100100, "100.100.100.100", ',');
ParseTest(100100100100, "100,100,100,100", '.');
ParseTestErr("100,100,100,100", ',');
ParseTestErr("100.100.100.100", '.');
ParseTest(100100100100, "100 100 100 100.0", '.');
ParseTest(100100100.100, "100 100 100.100", '.');
ParseTest(100100100.100, "100 100 100,100", ',');
ParseTest(100100100100, "100 100 100,100", '.');
ParseTest(1234567.89, "1.234.567,89", ',');
ParseTest(1234567.89, "1 234 567,89", ',');
ParseTest(1234567.89, "1 234 567.89", '.');
ParseTest(1234567.89, "1,234,567.89", '.');
ParseTest(1234567.89, "1234567,89", ',');
ParseTest(1234567.89, "1234567.89", '.');
ParseTest(123456789, "123456789", '.');
ParseTest(123456789, "123456789", ',');
ParseTest(123456789, "123.456.789", ',');
ParseTest(1234567890, "1.234.567.890", ',');
}
This should work with any culture. It correctly fails to parse strings that has more than one decimal separator, unlike implementations that replace instead of swap.
This can also occur if you have table arguments for things like 'aoColumns':[..]
which don't match the correct number of columns. Problems like this can commonly occur when copy pasting code from other pages to quick start your datatables integration.
Example:
This won't work:
<table id="dtable">
<thead>
<tr>
<th>col 1</th>
<th>col 2</th>
</tr>
</thead>
<tbody>
<td>data 1</td>
<td>data 2</td>
</tbody>
</table>
<script>
var dTable = $('#dtable');
dTable.DataTable({
'order': [[ 1, 'desc' ]],
'aoColumns': [
null,
null,
null,
null,
null,
null,
{
'bSortable': false
}
]
});
</script>
But this will work:
<table id="dtable">
<thead>
<tr>
<th>col 1</th>
<th>col 2</th>
</tr>
</thead>
<tbody>
<td>data 1</td>
<td>data 2</td>
</tbody>
</table>
<script>
var dTable = $('#dtable');
dTable.DataTable({
'order': [[ 0, 'desc' ]],
'aoColumns': [
null,
{
'bSortable': false
}
]
});
</script>
Make sure, that all of your class methods (updateVelocity
, updatePosition
, ...) take at least one positional argument, which is canonically named self
and refers to the current instance of the class.
When you call particle.updateVelocity()
, the called method implicitly gets an argument: the instance, here particle
as first parameter.
If your using jQuery, it's parseJSON function can be used and is preferable to JavaScript's native eval()
function.
Try this code:
String str = "a12.334tyz.78x";
str = str.replaceAll("[^\\d.]", "");
Now str
will contain "12.334.78"
.
List<T>.Add
adds a single element. Instead, use List<T>.AddRange
to add multiple values.
Additionally, List<T>.AddRange
takes an IEnumerable<T>
, so you don't need to convert tripDetails
into a List<TripDetails>
, you can pass it directly, e.g.:
tripDetailsCollection.AddRange(tripDetails);
your str_carSql should be exactly like this:
str_carSql = "insert into members_car (car_id, member_id, model, color, chassis_id, plate_number, code) values (@id,@m_id,@model,@color,@ch_id,@pt_num,@code)"
Good Luck
View model is a class that represents the data model used in a specific view. We could use this class as a model for a login page:
public class LoginPageVM
{
[Required(ErrorMessage = "Are you really trying to login without entering username?")]
[DisplayName("Username/e-mail")]
public string UserName { get; set; }
[Required(ErrorMessage = "Please enter password:)")]
[DisplayName("Password")]
public string Password { get; set; }
[DisplayName("Stay logged in when browser is closed")]
public bool RememberMe { get; set; }
}
Using this view model you can define the view (Razor view engine):
@model CamelTrap.Models.ViewModels.LoginPageVM
@using (Html.BeginForm()) {
@Html.EditorFor(m => m);
<input type="submit" value="Save" class="submit" />
}
And actions:
[HttpGet]
public ActionResult LoginPage()
{
return View();
}
[HttpPost]
public ActionResult LoginPage(LoginPageVM model)
{
...code to login user to application...
return View(model);
}
Which produces this result (screen is taken after submitting form, with validation messages):
As you can see, a view model has many roles:
LabelFor
,EditorFor
,DisplayFor
helpers).Another example of a view model and its retrieval: We want to display basic user data, his privileges and users name. We create a special view model, which contains only the required fields. We retrieve data from different entities from database, but the view is only aware of the view model class:
public class UserVM {
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public bool IsAdministrator { get; set; }
public string MothersName { get; set; }
}
Retrieval:
var user = db.userRepository.GetUser(id);
var model = new UserVM() {
ID = user.ID,
FirstName = user.FirstName,
LastName = user.LastName,
IsAdministrator = user.Proviledges.IsAdministrator,
MothersName = user.Mother.FirstName + " " + user.Mother.LastName
}
That might happen because the pojos you are using lack of the precise constructor the service needs. That is, try to generate all the constructors for the pojo or objects (model object) that your serviceClient uses, so that the client can be instanced correctly. In your case,regenerate the constructors (with arguments)for your client object (taht is your model object).
print date('H:i');
You have to set the correct timezone in php.ini
.
Look for these lines:
[Date]
; Defines the default timezone used by the date functions
;date.timezone =
It will be something like :
date.timezone ="Europe/Lisbon"
Don't forget to restart your webserver.
You just have to go to your Module settings > Project
and specify a "Project compiler output" and make your modules inherit from project. (For that go to Modules > Paths > Inherit project
.
This did the trick for me.
This question is specific to ASP .NET however I am sure some of you will benefit of system agnostic javascript which is beneficial in many situations.
UPDATE: The way to get url formed outside of the page itself is well described in answers above.
Or you could do a oneliner like following:
new UrlHelper(actionExecutingContext.RequestContext).Action(
"SessionTimeout", "Home",
new {area = string.Empty},
actionExecutingContext.Request.Url!= null?
actionExecutingContext.Request.Url.Scheme : "http"
);
from filter or:
new UrlHelper(this.Request.RequestContext).Action(
"Details",
"Journey",
new { area = productType },
this.Request.Url!= null? this.Request.Url.Scheme : "http"
);
However quite often one needs to get the url of current page, for those cases using Html.Action
and putting he name and controller of page you are in to me feels awkward. My preference in such cases is to use JavaScript instead. This is especially good in systems that are half re-written MVT half web-forms half vb-script half God knows what - and to get URL of current page one needs to use different method every time.
One way is to use JavaScript to get URL is window.location.href
another - document.URL
Here is a nice tutorial, it is what you need. (Source: coursesweb.net/php-mysql)
In this tutorial you can learn how to register, to count, and display in your webpage the number of online users and visitors. The principle is this: each user / visitor is registered in a text file or database. Every time a page of the website is accessed, the php script deletes all records older than a certain time (eg 2 minutes), adds the current user / visitor and takes the number of records left to display.
You can store the online users and visitors in a file on the server, or in a MySQL table. In this case, I think that using a text file to add and read the records is faster than storing them into a MySQL table, which requires more requests.
First it's presented the method with recording in a text file on the server, than the method with MySQL table.
To download the files with the scripts presented in this tutorial, click -> Count Online Users and Visitors.
• Both scripts can be included in ".php" files (with include()
), or in ".html" files (with <script>
), as you can see in the examples presented at the bottom of this page; but the server must run PHP.
To add records in a file on the server with PHP you must set CHMOD 0766 (or CHMOD 0777) permissions to that file, so the PHP can write data in it.
userson.txt
) and give it CHMOD 0777
permissions (in your FTP application, right click on that file, choose Properties, then select Read
, Write
, and Execute
options).usersontxt.php
) having the code below, then copy this php file in the same directory as userson.txt
.The code for usersontxt.php
;
<?php
// Script Online Users and Visitors - http://coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start(); // start Session, if not already started
$filetxt = 'userson.txt'; // the file in which the online users /visitors are stored
$timeon = 120; // number of secconds to keep a user online
$sep = '^^'; // characters used to separate the user name and date-time
$vst_id = '-vst-'; // an identifier to know that it is a visitor, not logged user
/*
If you have an user registration script,
replace $_SESSION['nume'] with the variable in which the user name is stored.
You can get a free registration script from: http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/
// get the user name if it is logged, or the visitors IP (and add the identifier)
$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;
$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i'; // regexp to recognize the line with visitors
$nrvst = 0; // to store the number of visitors
// sets the row with the current user /visitor that must be added in $filetxt (and current timestamp)
$addrow[] = $uvon. $sep. time();
// check if the file from $filetxt exists and is writable
if(is_writable($filetxt)) {
// get into an array the lines added in $filetxt
$ar_rows = file($filetxt, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$nrrows = count($ar_rows);
// number of rows
// if there is at least one line, parse the $ar_rows array
if($nrrows>0) {
for($i=0; $i<$nrrows; $i++) {
// get each line and separate the user /visitor and the timestamp
$ar_line = explode($sep, $ar_rows[$i]);
// add in $addrow array the records in last $timeon seconds
if($ar_line[0]!=$uvon && (intval($ar_line[1])+$timeon)>=time()) {
$addrow[] = $ar_rows[$i];
}
}
}
}
$nruvon = count($addrow); // total online
$usron = ''; // to store the name of logged users
// traverse $addrow to get the number of visitors and users
for($i=0; $i<$nruvon; $i++) {
if(preg_match($rgxvst, $addrow[$i])) $nrvst++; // increment the visitors
else {
// gets and stores the user's name
$ar_usron = explode($sep, $addrow[$i]);
$usron .= '<br/> - <i>'. $ar_usron[0]. '</i>';
}
}
$nrusr = $nruvon - $nrvst; // gets the users (total - visitors)
// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. $nruvon. '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';
// write data in $filetxt
if(!file_put_contents($filetxt, implode("\n", $addrow))) $reout = 'Error: Recording file not exists, or is not writable';
// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";
echo $reout; // output /display the result
?>
4.To show the number of online visitors /users in a ".html" file, use this code:
<script type="text/javascript" src="usersontxt.php?uvon=showon"></script>
This script (and the other presented below) works with $_SESSION. At the beginning of the PHP file in which you use it, you must add: session_start();. Count Online users and visitors using a MySQL table
To register, count and show the number of online visitors and users in a MySQL table, require to perform three SQL queries: Delete the records older than a certain time. Insert a row with the new user /visitor, or, if it is already inserted, Update the timestamp in its column. Select the remaining rows. Here's the code for a script that uses a MySQL table (named "userson") to store and display the Online Users and Visitors.
The code for create_userson.php
:
<?php
header('Content-type: text/html; charset=utf-8');
// HERE add your data for connecting to MySQ database
$host = 'localhost'; // MySQL server address
$user = 'root'; // User name
$pass = 'password'; // User`s password
$dbname = 'database'; // Database name
// connect to the MySQL server
$conn = new mysqli($host, $user, $pass, $dbname);
// check connection
if (mysqli_connect_errno()) exit('Connect failed: '. mysqli_connect_error());
// sql query for CREATE "userson" TABLE
$sql = "CREATE TABLE `userson` (
`uvon` VARCHAR(32) PRIMARY KEY,
`dt` INT(10) UNSIGNED NOT NULL
) CHARACTER SET utf8 COLLATE utf8_general_ci";
// Performs the $sql query on the server to create the table
if ($conn->query($sql) === TRUE) echo 'Table "userson" successfully created';
else echo 'Error: '. $conn->error;
$conn->close();
?>
userson
table (For explanations about the code, see the comments in script).usersmysql.php
):
In both file you must add your personal data for connecting to MySQL database, in the variables: $host
, $user
, $pass
, and $dbname
.The code for usersmysql.php:
<?php
// Script Online Users and Visitors - coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start(); // start Session, if not already started
// HERE add your data for connecting to MySQ database
$host = 'localhost'; // MySQL server address
$user = 'root'; // User name
$pass = 'password'; // User`s password
$dbname = 'database'; // Database name
/*
If you have an user registration script,
replace $_SESSION['nume'] with the variable in which the user name is stored.
You can get a free registration script from: http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/
// get the user name if it is logged, or the visitors IP (and add the identifier)
$vst_id = '-vst-'; // an identifier to know that it is a visitor, not logged user
$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;
$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i'; // regexp to recognize the rows with visitors
$dt = time(); // current timestamp
$timeon = 120; // number of secconds to keep a user online
$nrvst = 0; // to store the number of visitors
$nrusr = 0; // to store the number of usersrs
$usron = ''; // to store the name of logged users
// connect to the MySQL server
$conn = new mysqli($host, $user, $pass, $dbname);
// Define and execute the Delete, Insert/Update, and Select queries
$sqldel = "DELETE FROM `userson` WHERE `dt`<". ($dt - $timeon);
$sqliu = "INSERT INTO `userson` (`uvon`, `dt`) VALUES ('$uvon', $dt) ON DUPLICATE KEY UPDATE `dt`=$dt";
$sqlsel = "SELECT * FROM `userson`";
// Execute each query
if(!$conn->query($sqldel)) echo 'Error: '. $conn->error;
if(!$conn->query($sqliu)) echo 'Error: '. $conn->error;
$result = $conn->query($sqlsel);
// if the $result contains at least one row
if ($result->num_rows > 0) {
// traverse the sets of results and set the number of online visitors and users ($nrvst, $nrusr)
while($row = $result->fetch_assoc()) {
if(preg_match($rgxvst, $row['uvon'])) $nrvst++; // increment the visitors
else {
$nrusr++; // increment the users
$usron .= '<br/> - <i>'.$row['uvon']. '</i>'; // stores the user's name
}
}
}
$conn->close(); // close the MySQL connection
// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. ($nrusr+$nrvst). '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';
// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";
echo $reout; // output /display the result
?>
After you have created these two php files on your server, run the "create_userson.php" on your browser to create the "userson" table.
Include the usersmysql.php
file in the php file in which you want to display the number of online users and visitors.
Or, if you want to insert it in a ".html" file, add this code:
Examples using these scripts
• Including the "usersontxt.php` in a php file:
<!doctype html>
Counter Online Users and Visitors• Including the "usersmysql.php" in a html file:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Counter Online Users and Visitors</title>
<meta name="description" content="PHP script to count and show the number of online users and visitors" />
<meta name="keywords" content="online users, online visitors" />
</head>
<body>
<!-- Includes the script ("usersontxt.php", or "usersmysql.php") -->
<script type="text/javascript" src="usersmysql.php?uvon=showon"></script>
</body>
</html>
Both scripts (with storing data in a text file on the server, or into a MySQL table) will display a result like this: Online: 5
Visitors: 3 Users: 2
Johan is close - it depends on the hardware manufacturer. For example, Samsung Galaxy S phones uses Samsung RFS (proprietary). However, the Nexus S (also made by Samsung) with Android 2.3 uses Ext4 (presumably because Google told them to - the Nexus S is the current Google experience phone). Many community developers have also started moving to Ext4 because of this shift.
Or write to the response stream:
Response.Write("<script>");
Response.Write("window.open('page.html','_blank')");
Response.Write("</script>");
My solution for this. It is not so cool, but works well.
public static boolean isEqualCollection(List<?> a, List<?> b) {
if (a == null || b == null) {
throw new NullPointerException("The list a and b must be not null.");
}
if (a.size() != b.size()) {
return false;
}
List<?> bCopy = new ArrayList<Object>(b);
for (int i = 0; i < a.size(); i++) {
for (int j = 0; j < bCopy.size(); j++) {
if (a.get(i).equals(bCopy.get(j))) {
bCopy.remove(j);
break;
}
}
}
return bCopy.isEmpty();
}
Here is what you can try:
print("id,name,startDate")
cursor = db.<collection_name>.find();
while (cursor.hasNext()) {
jsonObject = cursor.next();
print(jsonObject._id.valueOf() + "," + jsonObject.name + ",\"" + jsonObject.stateDate.toUTCString() +"\"")
}
Save that in a file, say "export.js". Run the following command:
mongo <host>/<dbname> -u <username> -p <password> export.js > out.csv
MySQL disallows indexing a full value of BLOB
, TEXT
and long VARCHAR
columns because data they contain can be huge, and implicitly DB index will be big, meaning no benefit from index.
MySQL requires that you define first N characters to be indexed, and the trick is to choose a number N that’s long enough to give good selectivity, but short enough to save space. The prefix should be long enough to make the index nearly as useful as it would be if you’d indexed the whole column.
Before we go further let us define some important terms. Index selectivity is ratio of the total distinct indexed values and total number of rows. Here is one example for test table:
+-----+-----------+
| id | value |
+-----+-----------+
| 1 | abc |
| 2 | abd |
| 3 | adg |
+-----+-----------+
If we index only the first character (N=1), then index table will look like the following table:
+---------------+-----------+
| indexedValue | rows |
+---------------+-----------+
| a | 1,2,3 |
+---------------+-----------+
In this case, index selectivity is equal to IS=1/3 = 0.33.
Let us now see what will happen if we increase number of indexed characters to two (N=2).
+---------------+-----------+
| indexedValue | rows |
+---------------+-----------+
| ab | 1,2 |
| ad | 3 |
+---------------+-----------+
In this scenario IS=2/3=0.66 which means we increased index selectivity, but we have also increased the size of index. Trick is to find the minimal number N which will result to maximal index selectivity.
There are two approaches you can do calculations for your database table. I will make demonstration on the this database dump.
Let's say we want to add column last_name in table employees to the index, and we want to define the smallest number N which will produce the best index selectivity.
First let us identify the most frequent last names:
select count(*) as cnt, last_name
from employees
group by employees.last_name
order by cnt
+-----+-------------+
| cnt | last_name |
+-----+-------------+
| 226 | Baba |
| 223 | Coorg |
| 223 | Gelosh |
| 222 | Farris |
| 222 | Sudbeck |
| 221 | Adachi |
| 220 | Osgood |
| 218 | Neiman |
| 218 | Mandell |
| 218 | Masada |
| 217 | Boudaillier |
| 217 | Wendorf |
| 216 | Pettis |
| 216 | Solares |
| 216 | Mahnke |
+-----+-------------+
15 rows in set (0.64 sec)
As you can see, the last name Baba is the most frequent one. Now we are going to find the most frequently occurring last_name prefixes, beginning with five-letter prefixes.
+-----+--------+
| cnt | prefix |
+-----+--------+
| 794 | Schaa |
| 758 | Mande |
| 711 | Schwa |
| 562 | Angel |
| 561 | Gecse |
| 555 | Delgr |
| 550 | Berna |
| 547 | Peter |
| 543 | Cappe |
| 539 | Stran |
| 534 | Canna |
| 485 | Georg |
| 417 | Neima |
| 398 | Petti |
| 398 | Duclo |
+-----+--------+
15 rows in set (0.55 sec)
There are much more occurrences of every prefix, which means we have to increase number N until the values are almost the same as in the previous example.
Here are results for N=9
select count(*) as cnt, left(last_name,9) as prefix
from employees
group by prefix
order by cnt desc
limit 0,15;
+-----+-----------+
| cnt | prefix |
+-----+-----------+
| 336 | Schwartzb |
| 226 | Baba |
| 223 | Coorg |
| 223 | Gelosh |
| 222 | Sudbeck |
| 222 | Farris |
| 221 | Adachi |
| 220 | Osgood |
| 218 | Mandell |
| 218 | Neiman |
| 218 | Masada |
| 217 | Wendorf |
| 217 | Boudailli |
| 216 | Cummings |
| 216 | Pettis |
+-----+-----------+
Here are results for N=10.
+-----+------------+
| cnt | prefix |
+-----+------------+
| 226 | Baba |
| 223 | Coorg |
| 223 | Gelosh |
| 222 | Sudbeck |
| 222 | Farris |
| 221 | Adachi |
| 220 | Osgood |
| 218 | Mandell |
| 218 | Neiman |
| 218 | Masada |
| 217 | Wendorf |
| 217 | Boudaillie |
| 216 | Cummings |
| 216 | Pettis |
| 216 | Solares |
+-----+------------+
15 rows in set (0.56 sec)
This are very good results. This means that we can make index on column last_name
with indexing only first 10 characters. In table definition column last_name
is defined as VARCHAR(16)
, and this means we have saved 6 bytes (or more if there are UTF8 characters in the last name) per entry. In this table there are 1637 distinct values multiplied by 6 bytes is about 9KB, and imagine how this number would grow if our table contains million of rows.
You can read other ways of calculating number of N in my post Prefixed indexes in MySQL.
mybytestring.encode(somecodec) is meaningful for these values of somecodec
:
I am not sure what decoding an already decoded unicode text is good for. Trying that with any encoding seems to always try to encode with the system's default encoding first.
Actually you kind of can! Don't hassle with javascript... I was just stuck on the same thing for a website I'm making and if you increase the 'font-size' attribute in CSS for the tag then it automatically increases the height as well. Petty but it's something that bothers me a lot ha ha
The simplest way to display last element in python is
>>> list[-1:] # returns indexed value
[3]
>>> list[-1] # returns value
3
there are many other method to achieve such a goal but these are short and sweet to use.
downloading the email via the POP3 protocol is the easy part of the task. The protocol is quite simple and the only hard part could be advanced authentication methods if you don't want to send a clear text password over the network (and cannot use the SSL encrypted communication channel). See RFC 1939: Post Office Protocol - Version 3 and RFC 1734: POP3 AUTHentication command for details.
The hard part comes when you have to parse the received email, which means parsing MIME format in most cases. You can write quick&dirty MIME parser in a few hours or days and it will handle 95+% of all incoming messages. Improving the parser so it can parse almost any email means:
Debugging a robust MIME parser takes months of work. I know, because I was watching my friend writing one such parser for the component mentioned below and was writing a few unit tests for it too ;-)
Back to the original question.
Following code taken from our POP3 Tutorial page and links would help you:
//
// create client, connect and log in
Pop3 client = new Pop3();
client.Connect("pop3.example.org");
client.Login("username", "password");
// get message list
Pop3MessageCollection list = client.GetMessageList();
if (list.Count == 0)
{
Console.WriteLine("There are no messages in the mailbox.");
}
else
{
// download the first message
MailMessage message = client.GetMailMessage(list[0].SequenceNumber);
...
}
client.Disconnect();
Try CSS Generator.
You can choose values and see the results online. Then you get the code in the clipboard.
This is one example of generated code:
text-shadow: 1px 1px 2px #a8aaad;
filter: dropshadow(color=#a8aaad, offx=1, offy=1);
add one ArrayList to second ArrayList as:
Arraylist1.addAll(Arraylist2);
EDIT : if you want to Create new ArrayList from two existing ArrayList then do as:
ArrayList<String> arraylist3=new ArrayList<String>();
arraylist3.addAll(Arraylist1); // add first arraylist
arraylist3.addAll(Arraylist2); // add Second arraylist
I had the same error and replaced the dot notation with bracket notation to suppress it.
e.g.: obj.name -> obj['name']
If the variable ax.xaxis._autolabelpos = True, matplotlib sets the label position in function _update_label_position in axis.py according to (some excerpts):
bboxes, bboxes2 = self._get_tick_bboxes(ticks_to_draw, renderer)
bbox = mtransforms.Bbox.union(bboxes)
bottom = bbox.y0
x, y = self.label.get_position()
self.label.set_position((x, bottom - self.labelpad * self.figure.dpi / 72.0))
You can set the label position independently of the ticks by using:
ax.xaxis.set_label_coords(x0, y0)
that sets _autolabelpos to False or as mentioned above by changing the labelpad parameter.
What's happening here is the following: You create a new file on your trunk, then you merge it into your branch. In the merge commit this file will be created in your branch also.
When you merge your branch back into the trunk, SVN tries to do the same again: It sees that a file was created in your branch, and tries to create it in your trunk in the merge commit, but it already exists! This creates a tree conflict.
The way to avoid this, is to do a special merge, a reintegration. You can achieve this with the --reintegrate
switch.
You can read about this in the documentation: http://svnbook.red-bean.com/en/1.7/svn.branchmerge.basicmerging.html#svn.branchemerge.basicmerging.reintegrate
When merging your branch back to the trunk, however, the underlying mathematics are quite different. Your feature branch is now a mishmash of both duplicated trunk changes and private branch changes, so there's no simple contiguous range of revisions to copy over. By specifying the --reintegrate option, you're asking Subversion to carefully replicate only those changes unique to your branch. (And in fact, it does this by comparing the latest trunk tree with the latest branch tree: the resulting difference is exactly your branch changes!)
After reintegrating a branch it is highly advisable to remove it, otherwise you will keep getting treeconflicts whenever you merge in the other direction: from the trunk to your branch. (For exactly the same reason as described before.)
There is a way around this too, but I never tried it. You can read it in this post: Subversion branch reintegration in v1.6
alter table company drop constraint Company_CountryID_FK
I had a similar problem as well. The fix was a mix of both. I had a problem with asm-3.1 (as mentioned in the blog post linked by Takahiko. That jar was corrupt. I needed to manually get the jar from the maven central repository. Removing it and retrying just got the corrupt jar again. It then still failed on the asm-parent, which was a POM file containing the HTML with a 301. Again, it required manually getting the file myself. You may want to check what settings XML to see if you're set to a different repository, such as a local nexus server.
When the proper way to get the new one fails, manually grab it yourself.
For a general solution that works regardless of how many digits are in data$anim
, use the sprintf
function. It works like this:
sprintf("%04d", 1)
# [1] "0001"
sprintf("%04d", 104)
# [1] "0104"
sprintf("%010d", 104)
# [1] "0000000104"
In your case, you probably want: data$anim <- sprintf("%06d", data$anim)
You can use String =~ Regex
. It returns position of full regex match in string.
irb> ("abc" =~ %r"abc") == 0
=> true
irb> ("aabc" =~ %r"abc") == 0
=> false
You can use shuf
. On some systems at least (doesn't appear to be in POSIX).
As jleedev pointed out: sort -R
might also be an option. On some systems at least; well, you get the picture. It has been pointed out that sort -R
doesn't really shuffle but instead sort items according to their hash value.
[Editor's note: sort -R
almost shuffles, except that duplicate lines / sort keys always end up next to each other. In other words: only with unique input lines / keys is it a true shuffle. While it's true that the output order is determined by hash values, the randomness comes from choosing a random hash function - see manual.]
the accepted answer works but some of the used methods are now deprecated so I think it is best if I answer this question with updated methods.
this is answer is completely from this guide on google developers
so here is step by step guide:
implement all this in your map activity
MapActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks
in your onCreate
:
private GoogleMap mMap;
private Context context;
private TextView txtStartPoint,txtEndPoint;
private GoogleApiClient mGoogleApiClient;
private Location mLastKnownLocation;
private LatLng mDefaultLocation;
private CameraPosition mCameraPosition;
private boolean mLocationPermissionGranted;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
context = this;
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */,
this /* OnConnectionFailedListener */)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.build();
mGoogleApiClient.connect();
}
in your onConnected
:
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(map);
mapFragment.getMapAsync(this);
in your onMapReady
:
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Do other setup activities here too, as described elsewhere in this tutorial.
// Turn on the My Location layer and the related control on the map.
updateLocationUI();
// Get the current location of the device and set the position of the map.
getDeviceLocation();
}
and these two are methods in onMapReady
:
private void updateLocationUI() {
if (mMap == null) {
return;
}
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
}
if (mLocationPermissionGranted) {
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
} else {
mMap.setMyLocationEnabled(false);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mLastKnownLocation = null;
}
}
private void getDeviceLocation() {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
}
if (mLocationPermissionGranted) {
mLastKnownLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
}
// Set the map's camera position to the current location of the device.
float DEFAULT_ZOOM = 15;
if (mCameraPosition != null) {
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(mCameraPosition));
} else if (mLastKnownLocation != null) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(mLastKnownLocation.getLatitude(),
mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
} else {
Log.d("pouya", "Current location is null. Using defaults.");
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
}
this is very fast , smooth and effective. hope this helps
I didn't need to install any package. Just a simple change in your WebAPI project's web.config is working great:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
Credit goes to: Using CORS in ASP.NET WebAPI Without Being a Rocket Scientist
To reload, you can try this:
window.location.reload(true);
You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree
option for single commands, or the GIT_WORK_TREE
environment variable. There is also the core.worktree
configuration option but it will not work in a bare repository (check the man page for what it does).
# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status
import platform
is_windows = any(platform.win32_ver())
or
import sys
is_windows = hasattr(sys, 'getwindowsversion')
Hi here is an Google Chrome Sample which emails the current Site to an friend. The Basic idea behind is what you want...first of all it fetches the content of the page (not interessting for you)...afterwards it gets the URL (<-- good part)
Additionally it is a nice working code example, which i prefer motstly over reading Documents.
Can be found here: Email this page
I'd suggest using RVM it allows you have multiple versions of Ruby/Rails installed with gem profiles and basically keep all your gems contained from one another. You may want to check out a similar post How can I install Ruby on Rails 3 on OSX
Yes, this happens when manipulating an element which doesn't exist yet (a few contributors here also made a good point with the unique ID). I ran into a similar issue. I also need to pass an argument to the function manipulating the element soon to be rendered.
The solution checked off here didn't help me. Finally I found one that worked right out of the box. And it's very pretty, too - a callback.
Instead of:
$( '#header' ).focus();
or the tempting:
setTimeout( $( '#header' ).focus(), 500 );
Try this:
setTimeout( function() { $( '#header' ).focus() }, 500 );
In my code, testing passing the argument, this didn't work, the timeout was ignored:
setTimeout( alert( 'Hello, '+name ), 1000 );
This works, the timeout ticks:
setTimeout( function() { alert( 'Hello, '+name ) }, 1000 );
It sucks that w3schools doesn't mention it.
Credits go to: makemineatriple.com.
Hopefully, this helps somebody who comes here.
After reading the Quick Start Guide
In your HTML page add an element that CKEditor should replace:
<textarea name="content" id="editor"></textarea>
Load the classic editor build (here CDN location is used):
<script src="https://cdn.ckeditor.com/ckeditor5/10.0.1/classic/ckeditor.js"></script>
Call the ClassicEditor.create() method.
<script>
ClassicEditor
.create( document.querySelector( '#editor' ) )
.catch( error => {
console.error( error );
} );
</script>
Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CKEditor 5 - Classic editor</title>
<script src="https://cdn.ckeditor.com/ckeditor5/10.0.1/classic/ckeditor.js"></script>
</head>
<body>
<h1>Classic editor</h1>
<textarea name="content" id="editor">
<p>This is some sample content.</p>
</textarea>
<script>
ClassicEditor
.create( document.querySelector( '#editor' ) )
.catch( error => {
console.error( error );
} );
</script>
</body>
</html>
This example is for the specific classic editor. FOr other variants, only CDN will change.
You can have many java versions in your system.
I think you should add the java 8 in yours JREs installed or edit.
Take a look my screen:
If you click in edit (check your java 8 path):
Currently you are sending the data as typical POST values, which look like this:
first_name=somename&last_name=somesurname
If you want to send data as json you need to create an object with data and stringify it.
data: JSON.stringify(someobject)
To turn a 2D JavaScript array into an HTML table, you really need but a little bit of code :
function arrayToTable(tableData) {_x000D_
var table = $('<table></table>');_x000D_
$(tableData).each(function (i, rowData) {_x000D_
var row = $('<tr></tr>');_x000D_
$(rowData).each(function (j, cellData) {_x000D_
row.append($('<td>'+cellData+'</td>'));_x000D_
});_x000D_
table.append(row);_x000D_
});_x000D_
return table;_x000D_
}_x000D_
_x000D_
$('body').append(arrayToTable([_x000D_
["John","Slegers",34],_x000D_
["Tom","Stevens",25],_x000D_
["An","Davies",28],_x000D_
["Miet","Hansen",42],_x000D_
["Eli","Morris",18]_x000D_
]));
_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
_x000D_
If you want to load your 2D array from a JSON file, you'll also need a little bit of Ajax code :
$.ajax({
type: "GET",
url: "data.json",
dataType: 'json',
success: function (data) {
$('body').append(arrayToTable(data));
}
});
%r
shows with quotes:
It will be like:
I said: 'There are 10 types of people.'.
If you had used %s
it would have been:
I said: There are 10 types of people..
Run this in the command line (or git bash on windows):
echo "" > $(npm config get userconfig)
npm config edit
echo "" > $(npm config get globalconfig)
npm config --global edit
sudo sh -c 'echo "" > $(npm config get globalconfig)'
Using standard C++ calling (note that you should use namespace std for cout or add using namespace std;)
#include <iostream>
int main()
{
std::cout<<"Hello World!\n";
return 0;
}
Yep you should start anaconda's python in order to use python libs which come with anaconda. Or otherwise you have to manually add anaconda\lib
to pythonpath
which is less trivial. You can start anaconda's python by a full path:
path\to\anaconda\python.exe
or you can run the following two commands as an admin in cmd to make windows pipe every .py
file to anaconda's python:
assoc .py=Python.File
ftype Python.File=C:\path\to\Anaconda\python.exe "%1" %*
after this you'll be able just to call python scripts without specifying the python executable at all.
Use this code for iCheck:
$('.i-checks').iCheck({
checkboxClass: 'icheckbox_square-green',
radioClass: 'iradio_square-green',
}).on('ifChanged', function(e) {
// Get the field name
var isChecked = e.currentTarget.checked;
if (isChecked == true) {
}
});
Always use the getActivity() method to get the context of your attached activity, but always remember one thing: Fragments are slightly unstable and getActivity
returns null some times, so for that, always check the isAdded() method of fragment before getting context by getActivity()
.
Here are easy way to get app's full package. we can use astro file manager app. You can get it on android market. Astro app manager show us app's full package.
To check a space symbol you can use the following approach
if ( c == ' ' ) { /*...*/ }
To check a space and/or a tab symbol (standard blank characters) you can use the following approach
#include <ctype.h>
//...
if ( isblank( c ) ) { /*...*/ }
To check a white space you can use the following approach
#include <ctype.h>
//...
if ( isspace( c ) ) { /*...*/ }
I was having the same error, but had a proper connection string. My problem was that the driver was not being used, therefore was optimized out of the compiled war.
Be sure to import the driver:
import com.microsoft.sqlserver.jdbc.SQLServerDriver;
And then to force it to be included in the final war, you can do something like this:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
That line is in the original question. This will also work:
SQLServerDriver driver = new SQLServerDriver();
its possible if you already have a python installed (pip) you could do a upgrade on mac by
brew upgrade python
Here is some weak adobe documentation on different flash 9 wmode settings.
A note of caution on wmode transparent is here in the adobe bug trac.
And new for flash 10, are two new wmodes: gpu and direct. Please refer to Adobe Knowledge Base about wmode.
man you can use the basic Bootstrap Datepicker this way:
<!DOCTYPE html>
<head runat="server">
<title>Test Zone</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="Css/datepicker.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="../Js/bootstrap-datepicker.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#pickyDate').datepicker({
format: "dd/mm/yyyy"
});
});
</script>
and inside body:
<body>
<div id="testDIV">
<div class="container">
<div class="hero-unit">
<input type="text" placeholder="click to show datepicker" id="pickyDate"/>
</div>
</div>
</div>
datepicker.css and bootstrap-datepicker.js you can download from here on the Download button below "About" on the left side. Hope this help someone, greetings.
Currently Angular CLI doesn't support an option to remove the component, you need to do it manually.
In this jsfiddle you'll find a solution I deviced. The idea is to have a selector pair in html and use (plain) javascript to filter the options in the dependent selector, based on the selected option of the first. For example:
<select id="continents">
<option value = 0>All</option>
<option value = 1>Asia</option>
<option value = 2>Europe</option>
<option value = 3>Africa</option>
</select>
<select id="selectcountries"></select>
Uses (in the jsFiddle)
MAIN.createRelatedSelector
( document.querySelector('#continents') // from select element
,document.querySelector('#selectcountries') // to select element
,{ // values object
Asia: ['China','Japan','North Korea',
'South Korea','India','Malaysia',
'Uzbekistan'],
Europe: ['France','Belgium','Spain','Netherlands','Sweden','Germany'],
Africa: ['Mali','Namibia','Botswana','Zimbabwe','Burkina Faso','Burundi']
}
,function(a,b){return a>b ? 1 : a<b ? -1 : 0;} // sort method
);
[Edit 2021] or use data-attributes, something like:
document.addEventListener("change", checkSelect);
function checkSelect(evt) {
const origin = evt.target;
if (origin.dataset.dependentSelector) {
const selectedOptFrom = origin.querySelector("option:checked")
.dataset.dependentOpt || "n/a";
const addRemove = optData => (optData || "") === selectedOptFrom
? "add" : "remove";
document.querySelectorAll(`${origin.dataset.dependentSelector} option`)
.forEach( opt =>
opt.classList[addRemove(opt.dataset.fromDependent)]("display") );
}
}
_x000D_
[data-from-dependent] {
display: none;
}
[data-from-dependent].display {
display: initial;
}
_x000D_
<select id="source" name="source" data-dependent-selector="#status">
<option>MANUAL</option>
<option data-dependent-opt="ONLINE">ONLINE</option>
<option data-dependent-opt="UNKNOWN">UNKNOWN</option>
</select>
<select id="status" name="status">
<option>OPEN</option>
<option>DELIVERED</option>
<option data-from-dependent="ONLINE">SHIPPED</option>
<option data-from-dependent="UNKNOWN">SHOULD SELECT</option>
<option data-from-dependent="UNKNOWN">MAYBE IN TRANSIT</option>
</select>
_x000D_
Here is an example that will focus on an input using refs (tested in React 16.8.6):
The Child component:
class Child extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return (<input type="text" ref={this.myRef} />);
}
}
The Parent component with the Child component inside:
class Parent extends React.Component {
constructor(props) {
super(props);
this.childRef = React.createRef();
}
componentDidMount() {
this.childRef.current.myRef.current.focus();
}
render() {
return <Child ref={this.childRef} />;
}
}
ReactDOM.render(
<Parent />,
document.getElementById('container')
);
The Parent component with this.props.children:
class Parent extends React.Component {
constructor(props) {
super(props);
this.childRef = React.createRef();
}
componentDidMount() {
this.childRef.current.myRef.current.focus();
}
render() {
const ChildComponentWithRef = React.forwardRef((props, ref) =>
React.cloneElement(this.props.children, {
...props,
ref
})
);
return <ChildComponentWithRef ref={this.childRef} />
}
}
ReactDOM.render(
<Parent>
<Child />
</Parent>,
document.getElementById('container')
);
I have a code very similar to yours and if it works onPause () and onResume (). When changing the fragment, these functions are activated respectively.
Code in fragment:
@Override
public void onResume() {
super.onResume();
sensorManager.registerListener(this, proximidad, SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(this, brillo, SensorManager.SENSOR_DELAY_NORMAL);
Log.e("Frontales","resume");
}
@Override
public void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
Log.e("Frontales","Pause");
}
Log when change of fragment:
05-19 22:28:54.284 2371-2371/madi.cajaherramientas E/Frontales: resume
05-19 22:28:57.002 2371-2371/madi.cajaherramientas E/Frontales: Pause
05-19 22:28:58.697 2371-2371/madi.cajaherramientas E/Frontales: resume
05-19 22:29:00.840 2371-2371/madi.cajaherramientas E/Frontales: Pause
05-19 22:29:02.248 2371-2371/madi.cajaherramientas E/Frontales: resume
05-19 22:29:03.718 2371-2371/madi.cajaherramientas E/Frontales: Pause
Fragment onCreateView:
View rootView;
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_proximidad, container, false);
ButterKnife.bind(this,rootView);
inflar();
setTextos();
return rootView;
}
Action when I pulse back (in the activity where I load the fragment):
@Override
public void onBackPressed() {
int count = getFragmentManager().getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
} else {
getFragmentManager().popBackStack();
}
}
I have solved it by importing FormModule in a shared.module and importing the shared.module in all other modules. My case is the FormModule is used in multiple modules.
here's a working version for MSSQL 2000. I've modified the 2005 code found here: http://sqlfool.com/2011/01/identity-columns-are-you-nearing-the-limits/
/* Define how close we are to the value limit
before we start throwing up the red flag.
The higher the value, the closer to the limit. */
DECLARE @threshold DECIMAL(3,2);
SET @threshold = .85;
/* Create a temp table */
CREATE TABLE #identityStatus
(
database_name VARCHAR(128)
, table_name VARCHAR(128)
, column_name VARCHAR(128)
, data_type VARCHAR(128)
, last_value BIGINT
, max_value BIGINT
);
DECLARE @dbname sysname;
DECLARE @sql nvarchar(4000);
-- Use an cursor to iterate through the databases since in 2000 there's no sp_MSForEachDB command...
DECLARE c cursor FAST_FORWARD FOR
SELECT
name
FROM
master.dbo.sysdatabases
WHERE
name NOT IN('master', 'model', 'msdb', 'tempdb');
OPEN c;
FETCH NEXT FROM c INTO @dbname;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = N'Use [' + @dbname + '];
Insert Into #identityStatus
Select ''' + @dbname + ''' As [database_name]
, Object_Name(id.id) As [table_name]
, id.name As [column_name]
, t.name As [data_type]
, IDENT_CURRENT(Object_Name(id.id)) As [last_value]
, Case
When t.name = ''tinyint'' Then 255
When t.name = ''smallint'' Then 32767
When t.name = ''int'' Then 2147483647
When t.name = ''bigint'' Then 9223372036854775807
End As [max_value]
From
syscolumns As id
Join systypes As t On id.xtype = t.xtype
Where
id.colstat&1 = 1 -- this identifies the identity columns (as far as I know)
';
EXECUTE sp_executesql @sql;
FETCH NEXT FROM c INTO @dbname;
END
CLOSE c;
DEALLOCATE c;
/* Retrieve our results and format it all prettily */
SELECT database_name
, table_name
, column_name
, data_type
, last_value
, CASE
WHEN last_value < 0 THEN 100
ELSE (1 - CAST(last_value AS FLOAT(4)) / max_value) * 100
END AS [percentLeft]
, CASE
WHEN CAST(last_value AS FLOAT(4)) / max_value >= @threshold
THEN 'warning: approaching max limit'
ELSE 'okay'
END AS [id_status]
FROM #identityStatus
ORDER BY percentLeft;
/* Clean up after ourselves */
DROP TABLE #identityStatus;
You can use mkdir:
#include <sys/stat.h>
#include <sys/types.h>
int result = mkdir("/home/me/test.txt", 0777);
It is better to run the inner loop several times with the performance timing only once and average by dividing inner loop repetitions than to run the whole thing (loop + performance timing) several times and average. This will reduce the overhead of the performance timing code vs your actual profiled section.
Wrap your timer calls for the appropriate system. For Windows, QueryPerformanceCounter is pretty fast and "safe" to use.
You can use "rdtsc" on any modern X86 PC as well but there may be issues on some multicore machines (core hopping may change timer) or if you have speed-step of some sort turned on.
I think your best best is to run the VNC server with a different geometry on a different port. I would try based on the man page
$vncserver :0 -geometry 1600x1200 $vncserver :1 -geometry 1440x900
Then you can connect from work to one port and from home to another.
Edit: Then use xmove to move windows between the two x-servers.
The primary flag seems to only work for vagrant ssh
for me.
In the past I have used the following method to hack around the issue.
# stage box intended for configuration closely matching production if ARGV[1] == 'stage' config.vm.define "stage" do |stage| box_setup stage, \ "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml" end end
For me the issue got fixed when I changed
<id name="personID" column="person_id">
<generator class="native"/>
</id>
to
<id name="personID" column="person_id">
<generator class="increment"/>
</id>
in my Person.hbm.xml
.
after that I re-encountered that same error for an another field(mobno). I tried restarting my IDE, recreating the database with previous back issue got eventually fixed when I re-create my tables using (without ENGINE=InnoDB DEFAULT CHARSET=latin1;
and removing underscores in the field name)
CREATE TABLE `tbl_customers` (
`pid` bigint(20) NOT NULL,
`title` varchar(4) NOT NULL,
`dob` varchar(10) NOT NULL,
`address` varchar(100) NOT NULL,
`country` varchar(4) DEFAULT NULL,
`hometp` int(12) NOT NULL,
`worktp` int(12) NOT NULL,
`mobno` varchar(12) NOT NULL,
`btcfrom` varchar(8) NOT NULL,
`btcto` varchar(8) NOT NULL,
`mmname` varchar(20) NOT NULL
)
instead of
CREATE TABLE `tbl_person` (
`person_id` bigint(20) NOT NULL,
`person_nic` int(10) NOT NULL,
`first_name` varchar(20) NOT NULL,
`sur_name` varchar(20) NOT NULL,
`person_email` varchar(20) NOT NULL,
`person_password` varchar(512) NOT NULL,
`mobno` varchar(10) NOT NULL DEFAULT '1',
`role` varchar(10) NOT NULL,
`verified` int(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I probably think this due to using ENGINE=InnoDB DEFAULT CHARSET=latin1;
, because I once got the error org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Unknown column 'mob_no' in 'field list'
even though it was my previous column name, which even do not exist in my current table. Even after backing up the database(with modified column name, using InnoDB engine) I still got that same error with old field name. This probably due to caching in that Engine.
These are all a matter of convenience.
Basically, if the question were 'Do we need to use body-parser
?' The answer is 'No'. We can come up with the same information from the client-post-request using a more circuitous route that will generally be less flexible and will increase the amount of code we have to write to get the same information.
This is kind of the same as asking 'Do we need to use express
to begin with?' Again, the answer there is no, and again, really it all comes down to saving us the hassle of writing more code to do the basic things that express comes with 'built-in'.
On the surface - body-parser
makes it easier to get at the information contained in client requests in a variety of formats instead of making you capture the raw data streams and figuring out what format the information is in, much less manually parsing that information into useable data.
It's enabled by default. Probably you just tried on an expression that failed to autocomplete.
In case you deactivated it somehow... you can enable it in the Visual Studio settings. Just browse to the Editor settings, then to the subgroup C/C++ and activate it again... should read something like "List members automatically" or "Auto list members" (sorry, I have the german Visual Studio).
Upon typing something like std::cout. a dropwdownlist with possible completitions should pop up.
To create an image with width equals screen width, and height proportionally set according to aspect ratio, do the following.
Glide.with(context).load(url).asBitmap().into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
// creating the image that maintain aspect ratio with width of image is set to screenwidth.
int width = imageView.getMeasuredWidth();
int diw = resource.getWidth();
if (diw > 0) {
int height = 0;
height = width * resource.getHeight() / diw;
resource = Bitmap.createScaledBitmap(resource, width, height, false);
}
imageView.setImageBitmap(resource);
}
});
Hope this helps.
You can use reference type in generic arguments, not primitive type. So here you should use
Map<String, Integer> myMap = new HashMap<String, Integer>();
and store value as
myMap.put("abc", 5);
I think 2 update calls should do
update VersionedFields
set Value = replace(value,'<iframe','<a><iframe')
update VersionedFields
set Value = replace(value,'> </iframe>','</a>')
Issue maybe occured because of the file/script created/downloaded from a windows machine. Please try converting into linux file format.
dos2unix ./script_name.sh
or
dos2unix ~/.bashrc
The function :getargc
below may be what you're looking for.
@echo off
setlocal enableextensions enabledelayedexpansion
call :getargc argc %*
echo Count is %argc%
echo Args are %*
endlocal
goto :eof
:getargc
set getargc_v0=%1
set /a "%getargc_v0% = 0"
:getargc_l0
if not x%2x==xx (
shift
set /a "%getargc_v0% = %getargc_v0% + 1"
goto :getargc_l0
)
set getargc_v0=
goto :eof
It basically iterates once over the list (which is local to the function so the shifts won't affect the list back in the main program), counting them until it runs out.
It also uses a nifty trick, passing the name of the return variable to be set by the function.
The main program just illustrates how to call it and echos the arguments afterwards to ensure that they're untouched:
C:\Here> xx.cmd 1 2 3 4 5
Count is 5
Args are 1 2 3 4 5
C:\Here> xx.cmd 1 2 3 4 5 6 7 8 9 10 11
Count is 11
Args are 1 2 3 4 5 6 7 8 9 10 11
C:\Here> xx.cmd 1
Count is 1
Args are 1
C:\Here> xx.cmd
Count is 0
Args are
C:\Here> xx.cmd 1 2 "3 4 5"
Count is 3
Args are 1 2 "3 4 5"
An even better idea is to use the requests_toolbelt library, which can dump out both requests and responses as strings for you to print to the console. It handles all the tricky cases with files and encodings which the above solution does not handle well.
It's as easy as this:
import requests
from requests_toolbelt.utils import dump
resp = requests.get('https://httpbin.org/redirect/5')
data = dump.dump_all(resp)
print(data.decode('utf-8'))
Source: https://toolbelt.readthedocs.org/en/latest/dumputils.html
You can simply install it by typing:
pip install requests_toolbelt
Use the -isEqualToString:
method to compare the value of two strings. Using the C ==
operator will simply compare the addresses of the objects.
if ([category isEqualToString:@"Some String"])
{
// Do stuff...
}
I made an improvement in order to obtain not only the blocked processes but also the blocking process:
DECLARE @Table TABLE
(
SPID INT, Status VARCHAR(MAX), LOGIN VARCHAR(MAX), HostName VARCHAR(MAX), BlkBy VARCHAR(MAX), DBName VARCHAR(MAX), Command VARCHAR(MAX), CPUTime INT, DiskIO INT, LastBatch VARCHAR(MAX), ProgramName VARCHAR(MAX), SPID_1 INT, REQUESTID INT
)
INSERT INTO @Table EXEC sp_who2
SELECT *
FROM @Table
WHERE
BlkBy not like ' .'
or
SPID in (SELECT BlkBy from @Table where BlkBy not like ' .')
delete from @Table
Try:
var Wrapper = React.createClass({
render: function() {
return (
<div className="wrapper">
before
{this.props.children}
after
</div>
);
}
});
See Multiple Components: Children and Type of the Children props in the docs for more info.
I have figured out that I can convert the keyCode of the event to a character by using the following function:
var char = String.fromCharCode(v_code);
From there I would then append the character to a string, and when the enter key is pressed send the string to the server. I'm sorry if my question seemed somewhat cryptic, and the title meaning something almost completely off-topic, it's early in the morning and I haven't had breakfast yet ;).
Thanks for all your help guys.
I think that more accurate is this syntax:
SELECT CONVERT(CHAR(10), GETDATE(), 103)
I add SELECT and GETDATE() for instant testing purposes :)
If you are interested in understand performance, the best answer is to use a profiler.
Otherwise, System.Diagnostics.StopWatch provides a high resolution timer.
Sometimes you install Python on Windows and it doesn't configure the path correctly.
Make sure you enter [Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")
in PowerShell to configure it correctly.
You also have to either restart PowerShell or your whole computer to get it to really be fixed.
i was facing same issue today in xcode 8 version 8.3.2
right click on issue --> reveal in log
then you are able to check what is causing that issue
By default maven does not include any files from "src/main/java".
You have two possible way to that.
put all your resource files (different than java files) to "src/main/resources" - this is highly recommended
Add to your pom (resource plugin):
?
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
The obligatory
#define FOR for
and
#define ONE 1
#define TWO 2
...
Who knew?
A version using MSHTA and javascript. Change %jsfunc% to whateve jscript function you want to call
@echo off
::Invoke a javascript function using mhta
set jsfunc=new Date().getDay()
set dialog="about:<script>resizeTo(0,0);new ActiveXObject('Scripting.FileSystemObject').
set dialog=%dialog%GetStandardStream(1).WriteLine(%jsfunc%);close();</script>"
for /f "tokens=* delims=" %%p in ('mshta.exe %dialog%') do set ndow=%%p
::get dow string from array of strings
for /f "tokens=%ndow%" %%d in ("Mon Tue Wed Thu Fri Sat Sun") do set dow=%%d
echo dow is : %ndow% %dow%
pause
I had the same issue. The solution was to add the link to the JQuery file as a trusted site in IE.
Could you use the SQLPATH environment variable to tell sqlplus where to look for the scripts you are trying to run? I believe you could use HOST to set SQLPATH in the script too.
There could potentially be problems if two scripts have the same name and both directories are in the SQLPATH.
Always safe to use either Comparator or Comparable interface to provide sorting implementation (if the object is not a String or Wrapper classes for primitive data types) . As an example for a comparator implementation to sort employees based on name
List<Employees> empList = new LinkedList<Employees>(EmpSet);
class EmployeeComparator implements Comparator<Employee> {
public int compare(Employee e1, Employee e2) {
return e1.getName().compareTo(e2.getName());
}
}
Collections.sort(empList , new EmployeeComparator ());
Comparator is useful when you need to have different sorting algorithm on same object (Say emp name, emp salary, etc). Single mode sorting can be implemented by using Comparable interface in to the required object.
I figured out what it was! When I cleared the fields using the each() method, it also cleared the hidden field which the php needed to run:
if ($_POST['action'] == 'addRunner')
I used the :not() on the selection to stop it from clearing the hidden field.
sleep
doesn't work because the display can only be updated after your main thread returns to the system. NSTimer is the way to go. To do this, you need to implement methods which will be called by the timer to change the buttons. An example:
- (void)button_circleBusy:(id)sender {
firstButton.enabled = NO;
// 60 milliseconds is .06 seconds
[NSTimer scheduledTimerWithTimeInterval:.06 target:self selector:@selector(goToSecondButton:) userInfo:nil repeats:NO];
}
- (void)goToSecondButton:(id)sender {
firstButton.enabled = YES;
secondButton.enabled = NO;
[NSTimer scheduledTimerWithTimeInterval:.06 target:self selector:@selector(goToThirdButton:) userInfo:nil repeats:NO];
}
...
I had the same problem, however using Codeblocks. Because of this problem i quited programming because everytime i just wanted to throw my computer out of the window.
I want to thank user963228 whos answer is really a solution to that. You have to put Application Experience on Manual startup(you can do it by searching services in windows 7 start menu, and then find Application Experience and click properties).
This problem happens when people want to tweak theyr windows 7 machine, and they decide to disable some pointless services, so they google some tweaking guide and most of those guides say that Application Experience is safe to disable.
I think this problem should be linked to windows 7 problem not VS problem and it should be more visible - it took me long time to find this solution.
Thanks again!
Looks like the path you gave doesn't have any bootstrap files in them.
href="~/lib/bootstrap/dist/css/bootstrap.min.css"
Make sure the files exist over there , else point the files to the correct path, which should be in your case
href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"
select * from my_table where my_field Like '[a-z][a-z]%'
You could try this method.
const sortListByRanking = (rankingList, listToSort) => {
let result = []
for (let id of rankingList) {
for (let item of listToSort) {
if (item && item[1] === id) {
result.push(item)
}
}
}
return result
}
Store their UserId and a RememberMeToken. When they login with remember me checked generate a new RememberMeToken (which invalidate any other machines which are marked are remember me).
When they return look them up by the remember me token and make sure the UserId matches.
If you are asking whether there is a built in Pythonic range
-like function, there isn't. You have to do it the brute force way. Maybe rangy would be of interest to you.
You're trying to concatenate a string and an integer, which is incorrect.
Change print(numlist.pop(2)+" has been removed")
to any of these:
Explicit int
to str
conversion:
print(str(numlist.pop(2)) + " has been removed")
Use ,
instead of +
:
print(numlist.pop(2), "has been removed")
String formatting:
print("{} has been removed".format(numlist.pop(2)))
Instead using entire link we can make as below (solution concerns jsp files)
With JSTL we can make it like: To link resource like css, js:
<link rel="stylesheet" href="${pageContext.request.contextPath}/style/sample.css" />
<script src="${pageContext.request.contextPath}/js/sample.js"></script>
To simply make a link:
<a id=".." class=".." href="${pageContext.request.contextPath}/jsp/sample.jsp">....</a>
It's worth to get familiar with tags
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
There is also jsp method to do it like below, but better way like above:
<link rel="stylesheet" href="<%=request.getContextPath()%>/style/sample.css" />
<script type="text/javascript" src="<%=request.getContextPath()%>/js/sample.js"></script>
To simply make a link:
<a id=".." class=".." href="<%=request.getContextPath()%>/jsp/sample.jsp">....</a>
From command line -
Hadoop fs -copyFromLocal
Hadoop fs -copyToLocal
Or you also use spark FileSystem library to get or put hdfs file.
Hope this is helpful.
Yes. It is possible :D
SELECT SUM(totalHours) totalHours
FROM
(
select sum(hours) totalHours from resource
UNION ALL
select sum(hours) totalHours from projects-time
) s
As a sidenote, the tablename projects-time
must be delimited to avoid syntax error. Delimiter symbols vary on RDBMS you are using.
If you are using a Dockerfile, try:
ENTRYPOINT ["tail", "-f", "/dev/null"]
(Obviously this is for dev purposes only, you shouldn't need to keep a container alive unless it's running a process eg. nginx...)
As what I have understand on your question, this is what you want.
Here is a jsFiddle of the below:
$('.childDiv').click(function() {_x000D_
$(this).parent().find('.childDiv').css('background-color', '#ffffff');_x000D_
$(this).css('background-color', '#ff0000');_x000D_
});
_x000D_
.parentDiv {_x000D_
border: 1px solid black;_x000D_
padding: 10px;_x000D_
width: 80px;_x000D_
margin: 5px;_x000D_
display: relative;_x000D_
}_x000D_
.childDiv {_x000D_
border: 1px solid blue;_x000D_
height: 50px;_x000D_
margin: 10px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>_x000D_
<div id="divParent1" class="parentDiv">_x000D_
Group 1_x000D_
<div id="child1" class="childDiv">_x000D_
Child 1_x000D_
</div>_x000D_
<div id="child2" class="childDiv">_x000D_
Child 2_x000D_
</div>_x000D_
</div>_x000D_
<div id="divParent2" class="parentDiv">_x000D_
Group 2_x000D_
<div id="child1" class="childDiv">_x000D_
Child 1_x000D_
</div>_x000D_
<div id="child2" class="childDiv">_x000D_
Child 2_x000D_
</div>_x000D_
</div>
_x000D_
Not so elegant, but simple :)
- (BOOL) isNumber: (NSString*)input
{
return [input doubleValue] != 0 || [input isEqualToString:@"0"] || [input isEqualToString:@"0.0"];
}
Use the HEREDOC syntax. You can mix single and double quotes, variables and even function calls with unaltered / unescaped html markup.
echo <<<MYTAG
<tr><td> <input type="hidden" name="type" value="$var1" ></td></tr>
<tr><td> <input type="hidden" name="type" value="$var2" ></td></tr>
<tr><td> <input type="hidden" name="type" value="$var3" ></td></tr>
<tr><td> <input type="hidden" name="type" value="$var4" ></td></tr>
MYTAG;
DECLARE @StringToFind VARCHAR(100) = "Text To Count"
SELECT (LEN([Field To Search]) - LEN(REPLACE([Field To Search],@StringToFind,'')))/COALESCE(NULLIF(LEN(@StringToFind), 0), 1) --protect division from zero
FROM [Table To Search]
Just add onsubmit
event handler for your form:
<form action="insert.php" onsubmit="return myFunction()" method="post">
Remove onclick
from button
and make it input
with type submit
<input type="submit" value="Submit">
And add boolean return statements to your function:
function myFunction() {
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
var ok = true;
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("pass1").style.borderColor = "#E34234";
document.getElementById("pass2").style.borderColor = "#E34234";
return false;
}
else {
alert("Passwords Match!!!");
}
return ok;
}
You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...
For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.
One simple thing you could do is abstract the test inside a function.
local function isempty(s)
return s == nil or s == ''
end
if isempty(foo) then
foo = "default value"
end
you may use like that
System.out.println(Integer.decode("0x4d2")) // output 1234
//and vice versa
System.out.println(Integer.toHexString(1234); // output is 4d2);
Create the Java code that can receive an argument as a command line argument.
class TestCode{
public static void main(String args[]){
System.out.println("first argument is: "+args[0]);
}
}
Run the program without arguments (press F6).
In the Output window, at the bottom, click the double yellow arrow (or the yellow button) to open a Run dialog.
If the argument you need to pass is testArgument
, then here in this window pass the argument as application.args=testArgument
.
This will give the output as follows in the same Output window:
first argument is: testArgument
For Maven, the instructions are similar, but change the exec.args
property instead:
exec.args=-classpath %classpath package.ClassName PARAM1 PARAM2 PARAM3
Note: Use single quotes for string parameters that contain spaces.
If I'm interpreting right, this question seems to ask for something like a minus (-) operation between strings, i.e. the opposite of the built-in plus (+) operation (concatenation).
Unlike the previous answers, I'm trying to define such an operation that must obey the property:
IF c = a + b THEN c - a = b AND c - b = a
We need only three built-in Ruby methods to achieve this:
'abracadabra'.partition('abra').values_at(0,2).join == 'cadabra'
.
I won't explain how it works because it can be easily understood running one method at a time.
Here is a proof of concept code:
# minus_string.rb
class String
def -(str)
partition(str).values_at(0,2).join
end
end
# Add the following code and issue 'ruby minus_string.rb' in the console to test
require 'minitest/autorun'
class MinusString_Test < MiniTest::Test
A,B,C='abra','cadabra','abracadabra'
def test_C_eq_A_plus_B
assert C == A + B
end
def test_C_minus_A_eq_B
assert C - A == B
end
def test_C_minus_B_eq_A
assert C - B == A
end
end
One last word of advice if you're using a recent Ruby version (>= 2.0): use Refinements instead of monkey-patching String like in the previous example.
It is as easy as:
module MinusString
refine String do
def -(str)
partition(str).values_at(0,2).join
end
end
end
and add using MinusString
before the blocks where you need it.
Command Line option - Ubuntu
sudo apt-get install python-software-properties
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
Then in terminal
sudo apt-get install oracle-java8-installer
When there are multiple Java installations on your System, the Java version to use as default can be chosen. To do this, execute the following command.
sudo update-alternatives --config java
sudo update-alternatives --config javac
sudo update-alternatives --config javaws
Edit - Manual Java Installation
Download oracle jdk
http://www.oracle.com/technetwork/java/javase/downloads/index.html
Extract zip into desired folder
e.g /usr/local/ after extract /usr/local/jdk1.8.0_65
Setup
sudo update-alternatives --install /usr/bin/java java /usr/local/jdk1.8.0_65/bin/java 1
sudo update-alternatives --install /usr/bin/javac javac /usr/local/jdk1.8.0_65/bin/javac 1
sudo update-alternatives --install /usr/bin/javaws javaws /usr/local/jdk1.8.0_65/bin/javaws 1
sudo update-alternatives --set java /usr/local/jdk1.8.0_65/bin/java
sudo update-alternatives --set javac /usr/local/jdk1.8.0_65/bin/javac
sudo update-alternatives --set javaws /usr/local/jdk1.8.0_65/bin/javaws
Edit /etc/environment set JAVA_HOME path for external applications like Eclipse and Idea
<style type="text/css">
div {
text-align: center;
}
.img1{
width: 150px;
height: 150px;
border-radius: 50%;
}
span{
display: block;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type='password' class='secondInput mt-4 mr-1' placeholder="Password">
<span class='dif'></span>
<br>
<button>ADD</button>
</div>
<script type="text/javascript">
$('button').click(function() {
$('.dif').html("<img/>");
})
You can also try this, if this is what you need:
<style type="text/css">
....
table td div {height:20px;overflow-y:hidden;}
table td.col1 div {width:100px;}
table td.col2 div {width:300px;}
</style>
<table>
<tbody>
<tr><td class="col1"><div>test</div></td></tr>
<tr><td class="col2"><div>test</div></td></tr>
</tbody>
</table>
First list the desired characters
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
Use the str_shuffle($string) function. This function will provide you a randomly shuffled string.
$alpha=substr(str_shuffle($chars), 0, 50);
50 is the Length of string.
this is how I do it
function run_ajax(obj) {
$.ajax({
type:"POST",
url: prefix,
data: obj.pdata,
dataType: 'json',
error: function(data) {
//do error stuff
},
success: function(data) {
if(obj.func){
obj.func(data);
}
}
});
}
alert_func(data){
//do what you want with data
}
var obj= {};
obj.pdata = {sumbit:"somevalue"}; // post variable data
obj.func = alert_func;
run_ajax(obj);
You probably want this (to make it like a normal CSS background-image declaration):
$('myObject').css('background-image', 'url(' + imageUrl + ')');
The bash script "corstest" below works for me. It is based on Jun's comment above.
usage
corstest [-v] url
examples
./corstest https://api.coindesk.com/v1/bpi/currentprice.json
https://api.coindesk.com/v1/bpi/currentprice.json Access-Control-Allow-Origin: *
the positive result is displayed in green
./corstest https://github.com/IonicaBizau/jsonrequest
https://github.com/IonicaBizau/jsonrequest does not support CORS
you might want to visit https://enable-cors.org/ to find out how to enable CORS
the negative result is displayed in red and blue
the -v option will show the full curl headers
corstest
#!/bin/bash
# WF 2018-09-20
# https://stackoverflow.com/a/47609921/1497139
#ansi colors
#http://www.csc.uvic.ca/~sae/seng265/fall04/tips/s265s047-tips/bash-using-colors.html
blue='\033[0;34m'
red='\033[0;31m'
green='\033[0;32m' # '\e[1;32m' is too bright for white bg.
endColor='\033[0m'
#
# a colored message
# params:
# 1: l_color - the color of the message
# 2: l_msg - the message to display
#
color_msg() {
local l_color="$1"
local l_msg="$2"
echo -e "${l_color}$l_msg${endColor}"
}
#
# show the usage
#
usage() {
echo "usage: [-v] $0 url"
echo " -v |--verbose: show curl result"
exit 1
}
if [ $# -lt 1 ]
then
usage
fi
# commandline option
while [ "$1" != "" ]
do
url=$1
shift
# optionally show usage
case $url in
-v|--verbose)
verbose=true;
;;
esac
done
if [ "$verbose" = "true" ]
then
curl -s -X GET $url -H 'Cache-Control: no-cache' --head
fi
origin=$(curl -s -X GET $url -H 'Cache-Control: no-cache' --head | grep -i access-control)
if [ $? -eq 0 ]
then
color_msg $green "$url $origin"
else
color_msg $red "$url does not support CORS"
color_msg $blue "you might want to visit https://enable-cors.org/ to find out how to enable CORS"
fi
To get the count of certain type extensions using LINQ you could use this simple code:
Dim exts() As String = {".docx", ".ppt", ".pdf"}
Dim query = (From f As FileInfo In directory.GetFiles()).Where(Function(f) exts.Contains(f.Extension.ToLower()))
Response.Write(query.Count())
If you need to duplicate more than a few redirects, you might consider using a map:
# map is outside of server block
map $uri $redirect_uri {
~^/issue1/?$ http://example.com/shop/issues/custom_isse_name1;
~^/issue2/?$ http://example.com/shop/issues/custom_isse_name2;
~^/issue3/?$ http://example.com/shop/issues/custom_isse_name3;
# ... or put these in an included file
}
location / {
try_files $uri $uri/ @redirect-map;
}
location @redirect-map {
if ($redirect_uri) { # redirect if the variable is defined
return 301 $redirect_uri;
}
}