You can use JQuery .load() method:
$( "#content" ).load( "ajax/test.html div#content" );
Use the .data()
method:
$('div').data('info', '222');
Note that this doesn't create an actual data-info
attribute. If you need to create the attribute, use .attr()
:
$('div').attr('data-info', '222');
char letter;
for(int i=0; i<text.length(); i++)
{
letter = text.charAt(i);
if(letter>='A' && letter<='Z')
System.out.println((int)letter - 'A'+1);
if(letter>='a' && letter<= 'z')
System.out.println((int)letter - 'a'+1);
}
You don't need ANY of these other fancy answers. Below is a simplistic example that doesn't have all the Margin
, Height
, Width
properties set in the XAML, but should be enough to show how to get this done at a basic level.
XAML
Build a Window
page like you would normally and add your fields to it, say a Label
and TextBox
control inside a StackPanel
:
<StackPanel Orientation="Horizontal">
<Label Name="lblUser" Content="User Name:" />
<TextBox Name="txtUser" />
</StackPanel>
Then create a standard Button
for Submission ("OK" or "Submit") and a "Cancel" button if you like:
<StackPanel Orientation="Horizontal">
<Button Name="btnSubmit" Click="btnSubmit_Click" Content="Submit" />
<Button Name="btnCancel" Click="btnCancel_Click" Content="Cancel" />
</StackPanel>
Code-Behind
You'll add the Click
event handler functions in the code-behind, but when you go there, first, declare a public variable where you will store your textbox value:
public static string strUserName = String.Empty;
Then, for the event handler functions (right-click the Click
function on the button XAML, select "Go To Definition", it will create it for you), you need a check to see if your box is empty. You store it in your variable if it is not, and close your window:
private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
if (!String.IsNullOrEmpty(txtUser.Text))
{
strUserName = txtUser.Text;
this.Close();
}
else
MessageBox.Show("Must provide a user name in the textbox.");
}
Calling It From Another Page
You're thinking, if I close my window with that this.Close()
up there, my value is gone, right? NO!! I found this out from another site: http://www.dreamincode.net/forums/topic/359208-wpf-how-to-make-simple-popup-window-for-input/
They had a similar example to this (I cleaned it up a bit) of how to open your Window
from another and retrieve the values:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btnOpenPopup_Click(object sender, RoutedEventArgs e)
{
MyPopupWindow popup = new MyPopupWindow(); // this is the class of your other page
//ShowDialog means you can't focus the parent window, only the popup
popup.ShowDialog(); //execution will block here in this method until the popup closes
string result = popup.strUserName;
UserNameTextBlock.Text = result; // should show what was input on the other page
}
}
Cancel Button
You're thinking, well what about that Cancel button, though? So we just add another public variable back in our pop-up window code-behind:
public static bool cancelled = false;
And let's include our btnCancel_Click
event handler, and make one change to btnSubmit_Click
:
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
cancelled = true;
strUserName = String.Empty;
this.Close();
}
private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
if (!String.IsNullOrEmpty(txtUser.Text))
{
strUserName = txtUser.Text;
cancelled = false; // <-- I add this in here, just in case
this.Close();
}
else
MessageBox.Show("Must provide a user name in the textbox.");
}
And then we just read that variable in our MainWindow
btnOpenPopup_Click
event:
private void btnOpenPopup_Click(object sender, RoutedEventArgs e)
{
MyPopupWindow popup = new MyPopupWindow(); // this is the class of your other page
//ShowDialog means you can't focus the parent window, only the popup
popup.ShowDialog(); //execution will block here in this method until the popup closes
// **Here we find out if we cancelled or not**
if (popup.cancelled == true)
return;
else
{
string result = popup.strUserName;
UserNameTextBlock.Text = result; // should show what was input on the other page
}
}
Long response, but I wanted to show how easy this is using public static
variables. No DialogResult
, no returning values, nothing. Just open the window, store your values with the button events in the pop-up window, then retrieve them afterwards in the main window function.
When server first starts the my.ini
may not be created where everyone has stated. I was able to find mine in C:\Documents and Settings\All Users\Application Data\MySQL\MySQL Server 5.6
This location has the defaults for every setting.
# CLIENT SECTION
# ----------------------------------------------------------------------
#
# The following options will be read by MySQL client applications.
# Note that only client applications shipped by MySQL are guaranteed
# to read this section. If you want your own MySQL client program to
# honor these values, you need to specify it as an option during the
# MySQL client library initialization.
#
[client]
# pipe
# socket=0.0
port=4306 !!!!!!!!!!!!!!!!!!!Change this!!!!!!!!!!!!!!!!!
[mysql]
no-beep
default-character-set=utf8
You must type in the same name in your select query as your entity or class(case sensitive) . i.e. select user from className/Entity Name user;
Change your positioning a bit:
.container {
border: 1px solid #DDDDDD;
width: 200px;
height: 200px;
position:relative;
}
.tag {
float: left;
position: absolute;
left: 0px;
top: 0px;
background-color: green;
}
You need to set relative positioning on the container and then absolute on the inner tag div. The inner tag's absolute positioning will be with respect to the outer relatively positioned div. You don't even need the z-index rule on the tag div.
Here is a solution which blocks all non numeric input from being entered into the text-field.
html
<input type="text" id="numbersOnly" />
javascript
var input = document.getElementById('numbersOnly');
input.onkeydown = function(e) {
var k = e.which;
/* numeric inputs can come from the keypad or the numeric row at the top */
if ( (k < 48 || k > 57) && (k < 96 || k > 105)) {
e.preventDefault();
return false;
}
};?
Placing @Transient
on getter with private field worked for me.
private String name;
@Transient
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
Inside a module
Option Explicit
dim objExcelApp as Excel.Application
dim wb as Excel.Workbook
sub Initialize()
set objExcelApp = new Excel.Application
end sub
sub ProcessDataWorkbook()
dim ws as Worksheet
set wb = objExcelApp.Workbooks.Open("path to my workbook")
set ws = wb.Sheets(1)
ws.Cells(1,1).Value = "Hello"
ws.Cells(1,2).Value = "World"
'Close the workbook
wb.Close
set wb = Nothing
end sub
sub Release()
set objExcelApp = Nothing
end sub
I use something like this:
in a file "EnumToString.h":
#undef DECL_ENUM_ELEMENT
#undef DECL_ENUM_ELEMENT_VAL
#undef DECL_ENUM_ELEMENT_STR
#undef DECL_ENUM_ELEMENT_VAL_STR
#undef BEGIN_ENUM
#undef END_ENUM
#ifndef GENERATE_ENUM_STRINGS
#define DECL_ENUM_ELEMENT( element ) element,
#define DECL_ENUM_ELEMENT_VAL( element, value ) element = value,
#define DECL_ENUM_ELEMENT_STR( element, descr ) DECL_ENUM_ELEMENT( element )
#define DECL_ENUM_ELEMENT_VAL_STR( element, value, descr ) DECL_ENUM_ELEMENT_VAL( element, value )
#define BEGIN_ENUM( ENUM_NAME ) typedef enum tag##ENUM_NAME
#define END_ENUM( ENUM_NAME ) ENUM_NAME; \
const char* GetString##ENUM_NAME(enum tag##ENUM_NAME index);
#else
#define BEGIN_ENUM( ENUM_NAME) const char * GetString##ENUM_NAME( enum tag##ENUM_NAME index ) {\
switch( index ) {
#define DECL_ENUM_ELEMENT( element ) case element: return #element; break;
#define DECL_ENUM_ELEMENT_VAL( element, value ) DECL_ENUM_ELEMENT( element )
#define DECL_ENUM_ELEMENT_STR( element, descr ) case element: return descr; break;
#define DECL_ENUM_ELEMENT_VAL_STR( element, value, descr ) DECL_ENUM_ELEMENT_STR( element, descr )
#define END_ENUM( ENUM_NAME ) default: return "Unknown value"; } } ;
#endif
then in any header file you make the enum declaration, day enum.h
#include "EnumToString.h"
BEGIN_ENUM(Days)
{
DECL_ENUM_ELEMENT(Sunday) //will render "Sunday"
DECL_ENUM_ELEMENT(Monday) //will render "Monday"
DECL_ENUM_ELEMENT_STR(Tuesday, "Tuesday string") //will render "Tuesday string"
DECL_ENUM_ELEMENT(Wednesday) //will render "Wednesday"
DECL_ENUM_ELEMENT_VAL_STR(Thursday, 500, "Thursday string") // will render "Thursday string" and the enum will have 500 as value
/* ... and so on */
}
END_ENUM(MyEnum)
then in a file called EnumToString.c:
#include "enum.h"
#define GENERATE_ENUM_STRINGS // Start string generation
#include "enum.h"
#undef GENERATE_ENUM_STRINGS // Stop string generation
then in main.c:
int main(int argc, char* argv[])
{
Days TheDay = Monday;
printf( "%d - %s\n", TheDay, GetStringDay(TheDay) ); //will print "1 - Monday"
TheDay = Thursday;
printf( "%d - %s\n", TheDay, GetStringDay(TheDay) ); //will print "500 - Thursday string"
return 0;
}
this will generate "automatically" the strings for any enums declared this way and included in "EnumToString.c"
getDay()
returns the day of the week. To get the date, use date.getDate()
. getMonth()
retrieves the month, but month is zero based, so using getMonth()+1
should give you the right month. Time value seems to be ok here, albeit the hour is 23 here (GMT+1). If you want universal values, add UTC
to the methods (e.g. date.getUTCFullYear()
, date.getUTCHours()
)
var timestamp = 1301090400,
date = new Date(timestamp * 1000),
datevalues = [
date.getFullYear(),
date.getMonth()+1,
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
];
alert(datevalues); //=> [2011, 3, 25, 23, 0, 0]
Here is what you are looking for:
Service hangs up at WaitForExit after calling batch file
It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.
This is a pretty clean way to do it:
myStr = ("firstPartOfMyString"+
"secondPartOfMyString"+
"thirdPartOfMyString")
First confirm that you have in C:/python##/Lib/Site-packages/ a folder dateutil, perhaps you download it, you should already have pip,matplotlib, six##,,confirm you have installed dateutil by--- go to the cmd, cd /python, you should have a folder /Scripts. cd to Scripts, then type --pip install python-dateutil -- ----This applies to windows 7 Ultimate 32bit, Python 3.4------
Before creating a new branch always the best practice is to have the latest of repo in your local machine. Follow these steps for error free branch creation.
1. $ git branch (check which branches exist and which one is currently active (prefixed with *). This helps you avoid creating duplicate/confusing branch name)
2. $ git branch <new_branch> (creates new branch)
3. $ git checkout new_branch
4. $ git add . (After making changes in the current branch)
5. $ git commit -m "type commit msg here"
6. $ git checkout master (switch to master branch so that merging with new_branch can be done)
7. $ git merge new_branch (starts merging)
8. $ git push origin master (push to the remote server)
I referred this blog and I found it to be a cleaner approach.
Setting the icon
property when creating the BrowserWindow
only has an effect on Windows and Linux.
To set the icon on OS X, you can use electron-packager and set the icon using the --icon
switch.
It will need to be in .icns format for OS X. There is an online icon converter which can create this file from your .png.
res.sendFile( __dirname + "/public/" + "index1.html" );
where __dirname
will manage the name of the directory that the currently executing script ( server.js
) resides in.
Using the client instead of resource:
s3 = boto3.client('s3')
bucket='bucket_name'
result = s3.list_objects(Bucket = bucket, Prefix='/something/')
for o in result.get('Contents'):
data = s3.get_object(Bucket=bucket, Key=o.get('Key'))
contents = data['Body'].read()
print(contents)
grep -r -e string directory
-r
is for recursive; -e
is optional but its argument specifies the regex to search for. Interestingly, POSIX grep
is not required to support -r
(or -R
), but I'm practically certain that System V in practice they (almost) all do. Some versions of grep
did, sogrep
support -R
as well as (or conceivably instead of) -r
; AFAICT, it means the same thing.
Try Using
CONVERT(nvarchar(10),@ID)
This is similar to cast but is less expensive(in terms of time consumed)
Make sure you have jQuery UI base and the color picker widget included on your page (as well as a copy of jQuery 1.3):
<link rel="stylesheet" href="http://dev.jquery.com/view/tags/ui/latest/themes/flora/flora.all.css" type="text/css" media="screen" title="Flora (Default)">
<script type="text/javascript" src="http://dev.jquery.com/view/tags/ui/latest/ui/ui.core.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/tags/ui/latest/ui/ui.colorpicker.js"></script>
If you have those included, try posting your source so we can see what's going on.
If you want to use hex codes, you should add -e
option to enable interpretation of backslash escapes by echo (but the result is the same as with echo
CtrlRCtrlB). And as wallyk said, you probably want to add -n
to prevent the output of a newline:
echo -en '\x12\x02' > /dev/ttyS0
Also make sure that /dev/ttyS0
is the port you want.
Start your command with a space and it won't be included in the history.
Be aware that this does require the environment variable $HISTCONTROL
to be set.
Check that the following command returns ignorespace
or
ignoreboth
#> echo $HISTCONTROL
To add the environment variable if missing, the following line can be
added to the bash profile. E.g. %HOME/.bashrc
export HISTCONTROL=ignorespace
After sourcing the profile again space prefixed commands will not be written to $HISTFILE
$(this).closest('div')
is same as $(this).parents('div').eq(0)
.
this works with "NA"
not for NA
comments = c("no","yes","NA")
for (l in 1:length(comments)) {
#if (!is.na(comments[l])) print(comments[l])
if (comments[l] != "NA") print(comments[l])
}
I have encounter the same issue and found that i have forgot to prefix the commit message with project identifier. Project identifier is must in our case followed by the commit message. So at the server end it doesn't found the prefix and raised the issue.
I think you are looking for this ?
$('#your_id').html('<p>name</p><p><span style="font-size:xx-small;">ajde</span></p><p><em>da</em></p>').text();
The default media type in a POST request is application/x-www-form-urlencoded
. This is a format for encoding key-value pairs. The keys can be duplicate. Each key-value pair is separated by an &
character, and each key is separated from its value by an =
character.
For example:
Name: John Smith
Grade: 19
Is encoded as:
Name=John+Smith&Grade=19
This is placed in the request body after the HTTP headers.
It might be a little late to the discussion but inevitably someone will stumble onto this post like I did. I found the answer I was looking for and thought I'd post my own take on it. The following JSfiddle includes how to layer .PNG's with transparency. Jerska's mention of the transparency attribute for the div's CSS was the solution: http://jsfiddle.net/jyef3fqr/
HTML:
<button id="toggle-box">toggle</button>
<div id="box" style="display:none;" ><img src="x"></div>
<button id="toggle-box2">toggle</button>
<div id="box2" style="display:none;"><img src="xx"></div>
<button id="toggle-box3">toggle</button>
<div id="box3" style="display:none;" ><img src="xxx"></div>
CSS:
#box {
background-color: #ffffff;
height:400px;
width: 1200px;
position: absolute;
top:30px;
z-index:1;
}
#box2 {
background-color: #ffffff;
height:400px;
width: 1200px;
position: absolute;
top:30px;
z-index:2;
background-color : transparent;
}
#box3 {
background-color: #ffffff;
height:400px;
width: 1200px;
position: absolute;
top:30px;
z-index:2;
background-color : transparent;
}
body {background-color:#c0c0c0; }
JS:
$('#toggle-box').click().toggle(function() {
$('#box').animate({ width: 'show' });
}, function() {
$('#box').animate({ width: 'hide' });
});
$('#toggle-box2').click().toggle(function() {
$('#box2').animate({ width: 'show' });
}, function() {
$('#box2').animate({ width: 'hide' });
});
$('#toggle-box3').click().toggle(function() {
$('#box3').animate({ width: 'show' });
}, function() {
$('#box3').animate({ width: 'hide' });
});
And my original inspiration:http://jsfiddle.net/5g1zwLe3/ I also used paint.net for creating the transparent PNG's, or rather the PNG's with transparent BG's.
These need to go as different commands e.g.:
NAME=sam; echo "$NAME"
NAME=sam && echo "$NAME"
The expansion $NAME
to empty string is done by the shell earlier, before running echo
, so at the time the NAME
variable is passed to the echo
command's environment, the expansion is already done (to null string).
To get the same result in one command:
NAME=sam printenv NAME
I solved the problem like that: go to Run
and Select Clean and Rerun
.
Using inputStream.available()
It is always acceptable for System.in.available() to return 0.
I've found the opposite - it always returns the best value for the number of bytes available. Javadoc for InputStream.available()
:
Returns an estimate of the number of bytes that can be read (or skipped over)
from this input stream without blocking by the next invocation of a method for
this input stream.
An estimate is unavoidable due to timing/staleness. The figure can be a one-off underestimate because new data are constantly arriving. However it always "catches up" on the next call - it should account for all arrived data, bar that arriving just at the moment of the new call. Permanently returning 0 when there are data fails the condition above.
First Caveat: Concrete subclasses of InputStream are responsible for available()
InputStream
is an abstract class. It has no data source. It's meaningless for it to have available data. Hence, javadoc for available()
also states:
The available method for class InputStream always returns 0.
This method should be overridden by subclasses.
And indeed, the concrete input stream classes do override available(), providing meaningful values, not constant 0s.
Second Caveat: Ensure you use carriage-return when typing input in Windows.
If using System.in
, your program only receives input when your command shell hands it over. If you're using file redirection/pipes (e.g. somefile > java myJavaApp or somecommand | java myJavaApp ), then input data are usually handed over immediately. However, if you manually type input, then data handover can be delayed. E.g. With windows cmd.exe shell, the data are buffered within cmd.exe shell. Data are only passed to the executing java program following carriage-return (control-m or <enter>
). That's a limitation of the execution environment. Of course, InputStream.available() will return 0 for as long as the shell buffers the data - that's correct behaviour; there are no available data at that point. As soon as the data are available from the shell, the method returns a value > 0. NB: Cygwin uses cmd.exe too.
Just use this:
byte[] inputData = new byte[1024];
int result = is.read(inputData, 0, is.available());
// result will indicate number of bytes read; -1 for EOF with no data read.
OR equivalently,
BufferedReader br = new BufferedReader(new InputStreamReader(System.in, Charset.forName("ISO-8859-1")),1024);
// ...
// inside some iteration / processing logic:
if (br.ready()) {
int readCount = br.read(inputData, bufferOffset, inputData.length-bufferOffset);
}
Declare this:
public static int readInputStreamWithTimeout(InputStream is, byte[] b, int timeoutMillis)
throws IOException {
int bufferOffset = 0;
long maxTimeMillis = System.currentTimeMillis() + timeoutMillis;
while (System.currentTimeMillis() < maxTimeMillis && bufferOffset < b.length) {
int readLength = java.lang.Math.min(is.available(),b.length-bufferOffset);
// can alternatively use bufferedReader, guarded by isReady():
int readResult = is.read(b, bufferOffset, readLength);
if (readResult == -1) break;
bufferOffset += readResult;
}
return bufferOffset;
}
Then use this:
byte[] inputData = new byte[1024];
int readCount = readInputStreamWithTimeout(System.in, inputData, 6000); // 6 second timeout
// readCount will indicate number of bytes read; -1 for EOF with no data read.
I made this procedure for us to use at work.
cd ~
curl -s https://pypi.python.org/packages/source/p/pip/pip-1.3.1.tar.gz | tar xvz
cd pip-1.3.1
python setup.py install --user
cd ~
rm -rf pip-1.3.1
$HOME/.local/bin/pip install --user --upgrade pip distribute virtualenvwrapper
# Might want these three in your .bashrc
export PATH=$PATH:$HOME/.local/bin
export VIRTUALENVWRAPPER_VIRTUALENV_ARGS="--distribute"
source $HOME/.local/bin/virtualenvwrapper.sh
mkvirtualenv mypy
workon mypy
pip install --upgrade distribute
pip install pudb # Or whatever other nice package you might want.
Key points for the security minded:
I didn't see any answers that show users where we can find a Global Temp table. You can view Local and Global temp tables in the same location when navigating within SSMS. Screenshot below taken from this link.
Databases --> System Databases --> tempdb --> Temporary Tables
There are 3 different things we are using here :
So lets understand how spring data jpa and spring + hibernate works-
Let's say you are using spring + hibernate for your application. Now you need to have dao interface and implementation where you will be writing crud operation using SessionFactory of hibernate. Let say you are writing dao class for Employee class, tomorrow in your application you might need to write similiar crud operation for any other entity. So there is lot of boilerplate code we can see here.
Now Spring data jpa allow us to define dao interfaces by extending its repositories(crudrepository, jparepository) so it provide you dao implementation at runtime. You don't need to write dao implementation anymore.Thats how spring data jpa makes your life easy.
Another option if you want to get away from the command line is to use SourceTree.
Here are some additional resources on how to get set up:
About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :
Basically, flatMap
is the equivalent of Promise.then
.
For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay
operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)
Historically, it's been impossible to make these things disappear as they are user settings and not considered part of the page you have control over.
However, as of 2017, the @page
at-rule has been standardized, which can be used to hide the page title and date in modern browsers:
@page { size: auto; margin: 0mm; }
Print headers/footers and print margins
When printing Web documents, margins are set in the browser's Page Setup (or Print Setup) dialog box. These margin settings, although set within the browser, are controlled at the operating system/printer driver level and are not controllable at the HTML/CSS/DOM level. (For CSS-controlled printed page headers and footers see Printing Headers .)
The settings must be big enough to encompass the printer's physical non-printing areas. Further, they must be big enough to encompass the header and footer that the browser is usually configured to print (typically the page title, page number, URL and date). Note that these headers and footers, although specified by the browser and usually configurable through user preferences, are not part of the Web page itself and therefore are not controllable by CSS. In CSS terms, they fall outside the Page Box CSS2.1 Section 13.2.
... i.e. setting a margin of 0 hides the page title because the title is printed in the margin.
Credit to Vigneswaran S for this tip.
If they're both strings you can just do:
#define STR3 STR1 STR2
This then expands to:
#define STR3 "s" "1"
and in the C language, separating two strings with space as in "s" "1"
is exactly equivalent to having a single string "s1"
.
Data type Range Storage
bigint -2^63 (-9,223,372,036,854,775,808) to 2^63-1 (9,223,372,036,854,775,807) 8 Bytes
int -2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647) 4 Bytes
smallint -2^15 (-32,768) to 2^15-1 (32,767) 2 Bytes
tinyint 0 to 255 1 Byte
Example
The following example creates a table using the bigint, int, smallint, and tinyint data types. Values are inserted into each column and returned in the SELECT statement.
CREATE TABLE dbo.MyTable
(
MyBigIntColumn bigint
,MyIntColumn int
,MySmallIntColumn smallint
,MyTinyIntColumn tinyint
);
GO
INSERT INTO dbo.MyTable VALUES (9223372036854775807, 214483647,32767,255);
GO
SELECT MyBigIntColumn, MyIntColumn, MySmallIntColumn, MyTinyIntColumn
FROM dbo.MyTable;
If you don't want to list the fields, and the structure of the tables is the same, you can do:
INSERT INTO `table2` SELECT * FROM `table1`;
or if you want to create a new table with the same structure:
CREATE TABLE new_tbl [AS] SELECT * FROM orig_tbl;
Reference for insert select; Reference for create table select
You can change the array type without converting like this:
a.dtype = numpy.float32
but first you have to change all the integers to something that will be interpreted as the corresponding float. A very slow way to do this would be to use python's struct
module like this:
def toi(i):
return struct.unpack('i',struct.pack('f',float(i)))[0]
...applied to each member of your array.
But perhaps a faster way would be to utilize numpy's ctypeslib tools (which I am unfamiliar with)
- edit -
Since ctypeslib doesnt seem to work, then I would proceed with the conversion with the typical numpy.astype
method, but proceed in block sizes that are within your memory limits:
a[0:10000] = a[0:10000].astype('float32').view('int32')
...then change the dtype when done.
Here is a function that accomplishes the task for any compatible dtypes (only works for dtypes with same-sized items) and handles arbitrarily-shaped arrays with user-control over block size:
import numpy
def astype_inplace(a, dtype, blocksize=10000):
oldtype = a.dtype
newtype = numpy.dtype(dtype)
assert oldtype.itemsize is newtype.itemsize
for idx in xrange(0, a.size, blocksize):
a.flat[idx:idx + blocksize] = \
a.flat[idx:idx + blocksize].astype(newtype).view(oldtype)
a.dtype = newtype
a = numpy.random.randint(100,size=100).reshape((10,10))
print a
astype_inplace(a, 'float32')
print a
I recommend checking out Microsoft's SQL Server sample databases: https://github.com/Microsoft/sql-server-samples/releases/tag/adventureworks
The AdventureWorks sample uses a very clear and consistent naming convention that uses schema names for the organization of database objects.
If this is ASP.net-Core then you are mixing web API versions. Have the action return a derived IActionResult
because in your current code the framework is treating HttpResponseMessage
as a model.
[Route("api/[controller]")]
public class DownloadController : Controller {
//GET api/download/12345abc
[HttpGet("{id}"]
public async Task<IActionResult> Download(string id) {
Stream stream = await {{__get_stream_based_on_id_here__}}
if(stream == null)
return NotFound(); // returns a NotFoundResult with Status404NotFound response.
return File(stream, "application/octet-stream"); // returns a FileStreamResult
}
}
Generally, I find RandomUtils (from Apache commons lang) an easier way to generate random numbers than java.util.Random
If you have a <script>
tag anywhere on your page (even in the HTML, even if it is an empty tag with a src
), then a transition
must be activated by some event (it won't fire automatically when the page loads).
Using SpringApplication.run(Class<?> primarySource, String... arg)
worked for me. E.g.:
@SpringBootApplication
public class YourApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(YourApplication.class, args);
}
}
finally I found... it will work nice when table displays only 3 rows... if rows are more change should be accordingly...
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return 30;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
cell.textLabel.text =[NSString stringWithFormat:@"Hello roe no. %d",[indexPath row]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell * theCell = (UITableViewCell *)[tableView
cellForRowAtIndexPath:indexPath];
CGPoint tableViewCenter = [tableView contentOffset];
tableViewCenter.y += myTable.frame.size.height/2;
[tableView setContentOffset:CGPointMake(0,theCell.center.y-65) animated:YES];
[tableView reloadData];
}
In addition to the above posts, i'd like to point out that "man ls" will give you a nice manual about the "ls" ( List " command.
Also, using ls -la myFile will list & show all the facts about that file.
This timer will fire a "Hello" alertbox after 30 seconds. However, everytime you click the reset timer button it clears the timerHandle then re-sets it again. Once it's fired, the game ends.
<script type="text/javascript">
var timerHandle = setTimeout("alert('Hello')",3000);
function resetTimer() {
window.clearTimeout(timerHandle);
timerHandle = setTimeout("alert('Hello')",3000);
}
</script>
<body>
<button onclick="resetTimer()">Reset Timer</button>
</body>
All error codes are on "CFNetwork Errors Codes References" on the documentation (link)
A small extraction for CFURL and CFURLConnection Errors:
kCFURLErrorUnknown = -998,
kCFURLErrorCancelled = -999,
kCFURLErrorBadURL = -1000,
kCFURLErrorTimedOut = -1001,
kCFURLErrorUnsupportedURL = -1002,
kCFURLErrorCannotFindHost = -1003,
kCFURLErrorCannotConnectToHost = -1004,
kCFURLErrorNetworkConnectionLost = -1005,
kCFURLErrorDNSLookupFailed = -1006,
kCFURLErrorHTTPTooManyRedirects = -1007,
kCFURLErrorResourceUnavailable = -1008,
kCFURLErrorNotConnectedToInternet = -1009,
kCFURLErrorRedirectToNonExistentLocation = -1010,
kCFURLErrorBadServerResponse = -1011,
kCFURLErrorUserCancelledAuthentication = -1012,
kCFURLErrorUserAuthenticationRequired = -1013,
kCFURLErrorZeroByteResource = -1014,
kCFURLErrorCannotDecodeRawData = -1015,
kCFURLErrorCannotDecodeContentData = -1016,
kCFURLErrorCannotParseResponse = -1017,
kCFURLErrorInternationalRoamingOff = -1018,
kCFURLErrorCallIsActive = -1019,
kCFURLErrorDataNotAllowed = -1020,
kCFURLErrorRequestBodyStreamExhausted = -1021,
kCFURLErrorFileDoesNotExist = -1100,
kCFURLErrorFileIsDirectory = -1101,
kCFURLErrorNoPermissionsToReadFile = -1102,
kCFURLErrorDataLengthExceedsMaximum = -1103,
For next examples assumed that you use C++11. Example with ranged-based for loops:
for (auto &attack : m_attack) // access by reference to avoid copying
{
if (attack->m_num == input)
{
attack->makeDamage();
}
}
You should use const auto &attack
depending on the behavior of makeDamage()
.
You can use std::for_each
from standard library + lambdas:
std::for_each(m_attack.begin(), m_attack.end(),
[](Attack * attack)
{
if (attack->m_num == input)
{
attack->makeDamage();
}
}
);
If you are uncomfortable using std::for_each
, you can loop over m_attack
using iterators:
for (auto attack = m_attack.begin(); attack != m_attack.end(); ++attack)
{
if (attack->m_num == input)
{
attack->makeDamage();
}
}
Use m_attack.cbegin()
and m_attack.cend()
to get const
iterators.
There newer ways to connect Node.js and C++. Please, loot at Nan.
EDIT
The fastest and easiest way is nbind. If you want to write asynchronous add-on you can combine Asyncworker
class from nan.
Use HAVING MIN(...)
Something like:
SELECT MIN(price) AS price, pricegroup
FROM articles_prices
WHERE articleID=10
GROUP BY pricegroup
HAVING MIN(price) > 0;
You can define an upstream and use it in proxy_pass
http://rohanambasta.blogspot.com/2016/02/redirect-nginx-request-to-upstream.html
server {
listen 8082;
location ~ /(.*) {
proxy_pass test_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_redirect off;
}
}
upstream test_server
{
server test-server:8989
}
I also found that System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke()
is not always dispatcher of target control, just as dotNet wrote in his answer. I didn't had access to control's own dispatcher, so I used Application.Current.Dispatcher
and it solved the problem.
Best way to copy all files from one folder to another using PHP
<?php
$src = "/home/www/example.com/source/folders/123456"; // source folder or file
$dest = "/home/www/example.com/test/123456"; // destination folder or file
shell_exec("cp -r $src $dest");
echo "<H2>Copy files completed!</H2>"; //output when done
?>
I though I'd add one more way. In my case I supply this to com.hazelcast.config.XmlConfigBuilder
which only needs java.util.Properties
to resolve some properties inside the Hazelcast XML configuration file, i.e. it only calls getProperty(String)
method. So, this allowed me to do what I needed:
@RequiredArgsConstructor
public class SpringReadOnlyProperties extends Properties {
private final org.springframework.core.env.Environment delegate;
@Override
public String getProperty(String key) {
return delegate.getProperty(key);
}
@Override
public String getProperty(String key, String defaultValue) {
return delegate.getProperty(key, defaultValue);
}
@Override
public synchronized String toString() {
return getClass().getName() + "{" + delegate + "}";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
SpringReadOnlyProperties that = (SpringReadOnlyProperties) o;
return delegate.equals(that.delegate);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), delegate);
}
private void throwException() {
throw new RuntimeException("This method is not supported");
}
//all methods below throw the exception
* override all methods *
}
P.S. I ended up not using this specifically for Hazelcast because it only resolves properties for XML file but not at runtime. Since I also use Spring, I decided to go with a custom org.springframework.cache.interceptor.AbstractCacheResolver#getCacheNames
. This resolves properties for both situations, at least if you use properties in cache names.
A little late reply, but what I found in Notepad++ v7.8.6 is, on RMB (Right Mouse Button), on selection text, it gives an option called "Style token" where it shows "Using 1st/2nd/3rd/4th/5th style" to highlight the selected text in different pre-defined colors
If you are looking to avoid multiple code lines to save space, maybe this syntax could be useful:
java.util.ArrayList lisFieldNames = new ArrayList() {
{
add("value1");
add("value2");
}
};
Removing new lines, you can show it compressed as:
java.util.ArrayList lisFieldNames = new ArrayList() {
{
add("value1"); add("value2"); (...);
}
};
I think this is cleaner:
import inspect
print inspect.stack()[0][1]
and gets the same information as:
print inspect.getfile(inspect.currentframe())
Where [0] is the current frame in the stack (top of stack) and [1] is for the file name, increase to go backwards in the stack i.e.
print inspect.stack()[1][1]
would be the file name of the script that called the current frame. Also, using [-1] will get you to the bottom of the stack, the original calling script.
Use empty() and/or is_null()
http://www.php.net/empty http://www.php.net/is_null
Empty alone will achieve your current usage, is_null would just make more control possible if you wanted to distinguish between a field that is null and a field that is empty.
This may be helpful if you have more than one python versions installed and dont know how to tell your ide's to use a specific version.
anaconda
. Latest version can be found hereanaconda-navigator
in terminalcreate
and then choose your python version in that. install
in that. Hope it helps!!
Use references all the time and pointers only when you have to refer to NULL
which reference cannot refer.
See this FAQ : http://www.parashift.com/c++-faq-lite/references.html#faq-8.6
In Oracle:
SELECT 'Hello world' FROM dual
Dual equivalent in SQL Server:
SELECT 'Hello world'
In addition to Shane Kms answer, if you've activated Nuget Package Restore, you edit the NuGet.config located in the .nuget-folder as follows:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<repositoryPath>..\..\ExtLibs\Packages</repositoryPath>
</configuration>
Notice the extra "..\", as it backtracks from the .nuget-folder and not the solution folder.
No, it sets all members/elements that haven't been explicitly set to their default-initialisation value, which is zero for numeric types.
By using ''
you are making it to string. Use without inverted commas it will work fine.
For showing result of batch file in text file, you can use
this command
chdir > test.txt
This command will redirect result to test.txt.
When you open test.txt you will found current path of directory in test.txt
Try this demo please: http://jsfiddle.net/sgpw2/
Thanks Jan for spaces \s
rest there is some good detail in this link:
http://www.jquery4u.com/syntax/jquery-basic-regex-selector-examples/#.UHKS5UIihlI
Hope it fits your need :)
code
$(function() {
$("#field").bind("keyup", function(event) {
var regex = /^[a-zA-Z\s]+$/;
if (regex.test($("#field").val())) {
$('.validation').html('valid');
} else {
$('.validation').html("FAIL regex");
}
});
});?
I got this problem after moving a project and deleting it's packages folder. Nuget was showning that MSTest.TestAdapter and MSTest.TestFramework v 1.3.2 was installed. The fix seemed to be to open VS as administrator and build After that I was able to re-open and build without having admin priviledge.
I had the same issue after an upgrade from VS2013 to VS2015.
The project I was working at referenced itself. While VS2013 didn't care, VS2015 didn't like that and I got that error. After deleting the reference, the error was gone. It took me around 4 hours to find that out...
This is right from the manual:
http://docs.python.org/2/library/bisect.html
8.5.1. Searching Sorted Lists
The above bisect() functions are useful for finding insertion points but can be tricky or awkward to use for common searching tasks. The following five functions show how to transform them into the standard lookups for sorted lists:
def index(a, x):
'Locate the leftmost value exactly equal to x'
i = bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
raise ValueError
So with the slight modification your code should be:
def index(a, x):
'Locate the leftmost value exactly equal to x'
i = bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
return -1
There is another way of controlling error handling that works well for loops. Create a string variable called here
and use the variable to determine how a single error handler handles the error.
The code template is:
On error goto errhandler
Dim here as String
here = "in loop"
For i = 1 to 20
some code
Next i
afterloop:
here = "after loop"
more code
exitproc:
exit sub
errhandler:
If here = "in loop" Then
resume afterloop
elseif here = "after loop" Then
msgbox "An error has occurred" & err.desc
resume exitproc
End if
Make a service call like this:
public async void SaveActivationCode(ActivationCodes objAC)
{
var client = new HttpClient();
client.BaseAddress = new Uri(baseAddress);
HttpResponseMessage response = await client.PutAsJsonAsync(serviceAddress + "/SaveActivationCode" + "?apiKey=445-65-1216", objAC);
}
And Service method like this:
public HttpResponseMessage PutSaveActivationCode(ActivationCodes objAC)
{
}
PutAsJsonAsync takes care of Serialization and deserialization over the network
As others have mentioned: CSS-3 says that you can use the rgba(...)
syntax to specify a border color with an opacity (alpha) value.
here's a quick example if you'd like to check it.
It works in Safari and Chrome (probably works in all webkit browsers).
It works in Firefox
I doubt that it works at all in IE, but I suspect that there is some filter or behavior that will make it work.
There's also this stackoverflow post, which suggests some other issues--namely, that the border renders on-top-of any background color (or background image) that you've specified; thus limiting the usefulness of border alpha in many cases.
Easy way to remove public from laravel 5 url. You just need to cut index.php and .htaccess from public directory and paste it in the root directory,thats all and replace two lines in index.php as
require __DIR__.'/bootstrap/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
Note: The above method is just for the beginners as they might be facing problem in setting up virtual host and The best solution is to setup virtual host on local machine and point it to the public directory of the project.
In my case the file is a shell script (*.sh
file) meant to deploy our project to a local development server, for my developers.
The shell script should work consistently and may be updated; so I tracked it in the same Git project as the code which the script is meant to deploy.
The shell script runs one executable, and then allows that executable to run; so the script is still running; so my shell still has the script open; so it's locked.
I Ctrl+C
'd to kill the script (so now my local dev server is no longer accessible), now I can checkout freely.
File.new
and File.open
default to read mode ('r'
) as a safety mechanism, to avoid possibly overwriting a file. We have to explicitly tell Ruby to use write mode ('w'
is the most common way) if we're going to output to the file.
If the text to be output is a string, rather than write:
File.open('foo.txt', 'w') { |fo| fo.puts "bar" }
or worse:
fo = File.open('foo.txt', 'w')
fo.puts "bar"
fo.close
Use the more succinct write
:
File.write('foo.txt', 'bar')
write
has modes allowed so we can use 'w'
, 'a'
, 'r+'
if necessary.
open
with a block is useful if you have to compute the output in an iterative loop and want to leave the file open as you do so. write
is useful if you are going to output the content in one blast then close the file.
See the documentation for more information.
Make sure to target x86 on your project in Visual Studio. This should fix your trouble.
delete[] monsters;
Is incorrect because monsters
isn't a pointer to a dynamically allocated array, it is an array of pointers. As a class member it will be destroyed automatically when the class instance is destroyed.
Your other implementation is the correct one as the pointers in the array do point to dynamically allocated Monster
objects.
Note that with your current memory allocation strategy you probably want to declare your own copy constructor and copy-assignment operator so that unintentional copying doesn't cause double deletes. (If you you want to prevent copying you could declare them as private and not actually implement them.)
People tend to over complicate things by giving the definition which says:
flatMap transform the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable
I swear this definition still confuses me but I am going to explain it in the simplest way which is by using an example
Our Situation: we have an observable which returns data(simple URL) that we are going to use to make an HTTP call that will return an observable containing the data we need so you can visualize the situation like this:
Observable 1
|_
Make Http Call Using Observable 1 Data (returns Observable_2)
|_
The Data We Need
so as you can see we can't reach the data we need directly so the first way to retrieve the data we can use just normal subscriptions like this:
Observable_1.subscribe((URL) => {
Http.get(URL).subscribe((Data_We_Need) => {
console.log(Data_We_Need);
});
});
this works but as you can see we have to nest subscriptions to get our data this currently does not look bad but imagine we have 10 nested subscriptions that would become unmaintainable.
so a better way to handle this is just to use the operator flatMap
which will do the same thing but makes us avoid that nested subscription:
Observable_1
.flatMap(URL => Http.get(URL))
.subscribe(Data_We_Need => console.log(Data_We_Need));
Also check if the script has no batch seperator commands (remove the 'GO' statements on a single line).
txt_name.value
txt_name.onkeyup = e=> alert(txt_name.value);
_x000D_
<input type="text" id="txt_name" />
_x000D_
I found "display:flex"
style is a good way to make these elements in same line. No matter what kind of element in the div. Especially if the input class is form-control,other solutions like bootstrap, inline-block will not work well.
Example:
<div style="display:flex; flex-direction: row; justify-content: center; align-items: center">
<label for="Student">Name:</label>
<input name="Student" />
</div>
More detail about display:flex:
flex-direction: row, column
justify-content: flex-end, center, space-between, space-around
align-items: stretch, flex-start, flex-end, center
class LinkedStack:
'''LIFO Stack implementation using a singly linked list for storage.'''
_ToList = []
#---------- nested _Node class -----------------------------
class _Node:
'''Lightweight, nonpublic class for storing a singly linked node.'''
__slots__ = '_element', '_next' #streamline memory usage
def __init__(self, element, next):
self._element = element
self._next = next
#--------------- stack methods ---------------------------------
def __init__(self):
'''Create an empty stack.'''
self._head = None
self._size = 0
def __len__(self):
'''Return the number of elements in the stack.'''
return self._size
def IsEmpty(self):
'''Return True if the stack is empty'''
return self._size == 0
def Push(self,e):
'''Add element e to the top of the Stack.'''
self._head = self._Node(e, self._head) #create and link a new node
self._size +=1
self._ToList.append(e)
def Top(self):
'''Return (but do not remove) the element at the top of the stack.
Raise exception if the stack is empty
'''
if self.IsEmpty():
raise Exception('Stack is empty')
return self._head._element #top of stack is at head of list
def Pop(self):
'''Remove and return the element from the top of the stack (i.e. LIFO).
Raise exception if the stack is empty
'''
if self.IsEmpty():
raise Exception('Stack is empty')
answer = self._head._element
self._head = self._head._next #bypass the former top node
self._size -=1
self._ToList.remove(answer)
return answer
def Count(self):
'''Return how many nodes the stack has'''
return self.__len__()
def Clear(self):
'''Delete all nodes'''
for i in range(self.Count()):
self.Pop()
def ToList(self):
return self._ToList
Try to Install the android tracker plugin. you will find it on the studio.
Restart the studio
you'd use another join, something along these lines:
SELECT toD.dom_url AS ToURL,
fromD.dom_url AS FromUrl,
rvw.*
FROM reviews AS rvw
LEFT JOIN domain AS toD
ON toD.Dom_ID = rvw.rev_dom_for
LEFT JOIN domain AS fromD
ON fromD.Dom_ID = rvw.rev_dom_from
EDIT:
All you're doing is joining in the table multiple times. Look at the query in the post: it selects the values from the Reviews tables (aliased as rvw), that table provides you 2 references to the Domain table (a FOR and a FROM).
At this point it's a simple matter to left join the Domain table to the Reviews table. Once (aliased as toD) for the FOR, and a second time (aliased as fromD) for the FROM.
Then in the SELECT list, you will select the DOM_URL fields from both LEFT JOINS of the DOMAIN table, referencing them by the table alias for each joined in reference to the Domains table, and alias them as the ToURL and FromUrl.
For more info about aliasing in SQL, read here.
var myItem = myList.Find(item => item.property == "something");
cat(capture.output(print(my.list), file="test.txt"))
from R: Export and import a list to .txt file https://stackoverflow.com/users/1855677/42 is the only thing that worked for me. This outputs the list of lists as it is in the text file
From the Mongo docs:
The
$not
operator only affects other operators and cannot check fields and documents independently. So, use the$not
operator for logical disjunctions and the$ne
operator to test the contents of fields directly.
Since you are testing the field directly $ne
is the right operator to use here.
Edit:
A situation where you would like to use $not
is:
db.inventory.find( { price: { $not: { $gt: 1.99 } } } )
That would select all documents where:
Any crawler or spider will read your index.htm
or equivalent, that is exposed to the web, they will read the source code for that page, and find everything that is associated to that webpage and contains subdirectories. If they find a "contact us" button, there may be is included the path to the webpage or php that deal with the contact-us action, so they now have one more subdirectory/folder name to crawl and dig more. But even so, if that folder has a index.htm
or equivalent file, it will not list all the files in such folder.
If by mistake, the programmer never included an index.htm
file in such folder, then all the files will be listed on your computer screen, and also for the crawler/spider to keep digging. But, if you created a folder www.yoursite.com/nombresinistro75crazyragazzo19/
and put several files in there, and never published any button or never exposed that folder address anywhere in the net, keeping only in your head, chances are that nobody ever will find that path, with crawler or spider, for more sophisticated it can be.
Except, of course, if they can enter your FTP or access your site control panel.
This may be a little too short, but for my own private use, it works great
read -n 1 -p "Push master upstream? [Y/n] " reply;
if [ "$reply" != "" ]; then echo; fi
if [ "$reply" = "${reply#[Nn]}" ]; then
git push upstream master
fi
The read -n 1
just reads one character. No need to hit enter. If it's not a 'n' or 'N', it is assumed to be a 'Y'. Just pressing enter means Y too.
(as for the real question: make that a bash script and change your alias to point to that script instead of what is was pointing to before)
You can change the value of a bool all you want. As for an if:
if randombool == True:
works, but you can also use:
if randombool:
If you want to test whether something is false you can use:
if randombool == False
but you can also use:
if not randombool:
The second div is position: static
(the default) so the z-index does not apply to it.
You need to position (set the position property to anything other than static
, you probably want relative
in this case) anything you want to give a z-index
to.
I also faced the similar problem with JSON output format. This code worked for me with the above JSON format.
package com.test.ameba;
import java.util.List;
public class OutputRanges {
public List<Range> OutputRanges;
public String Message;
public String Entity;
/**
* @return the outputRanges
*/
public List<Range> getOutputRanges() {
return OutputRanges;
}
/**
* @param outputRanges the outputRanges to set
*/
public void setOutputRanges(List<Range> outputRanges) {
OutputRanges = outputRanges;
}
/**
* @return the message
*/
public String getMessage() {
return Message;
}
/**
* @param message the message to set
*/
public void setMessage(String message) {
Message = message;
}
/**
* @return the entity
*/
public String getEntity() {
return Entity;
}
/**
* @param entity the entity to set
*/
public void setEntity(String entity) {
Entity = entity;
}
}
package com.test;
public class Range {
public String Name;
/**
* @return the name
*/
public String getName() {
return Name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
Name = name;
}
public Object[] Value;
/**
* @return the value
*/
public Object[] getValue() {
return Value;
}
/**
* @param value the value to set
*/
public void setValue(Object[] value) {
Value = value;
}
}
package com.test.ameba;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JSONTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String jsonString ="{\"OutputRanges\":[{\"Name\":\"ABF_MEDICAL_RELATIVITY\",\"Value\":[[1.3628407124839714]]},{\"Name\":\" ABF_RX_RELATIVITY\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_Unique_ID_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_FIRST_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_AMEBA_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_Effective_Date_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_AMEBA_MODEL\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_UC_ER_COPAY_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_INN_OON_DED_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_COINSURANCE_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_PCP_SPEC_COPAY_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_INN_OON_OOP_MAX_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_IP_OP_COPAY_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_PHARMACY_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_PLAN_ADMIN_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]}],\"Message\":\"\",\"Entity\":null}";
ObjectMapper mapper = new ObjectMapper();
OutputRanges OutputRanges=null;
try {
OutputRanges = mapper.readValue(jsonString, OutputRanges.class);
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("OutputRanges :: "+OutputRanges);;
System.out.println("OutputRanges.getOutputRanges() :: "+OutputRanges.getOutputRanges());;
for (Range r : OutputRanges.getOutputRanges()) {
System.out.println(r.getName());
}
}
}
A better approach is:
int x = rand.nextInt(max - min + 1) + min;
Your formula generates numbers between min
and min + max
.
Random random = new Random(1234567);
int min = 5;
int max = 20;
while (true) {
int x = (int)(Math.random() * max) + min;
System.out.println(x);
if (x < min || x >= max) { break; }
}
Result:
10
16
13
21 // Oops!!
See it online here: ideone
It means you allow every (*
) user-agent/crawler to access the root (/
) of your site. You're okay.
<head>
<style>
div.scroll
{
background-color:#00FFFF;
width:40%;
height:200PX;
FLOAT: left;
margin-left: 5%;
padding: 1%;
overflow:scroll;
}
</style>
</head>
<body>
<div class="scroll">You can use the overflow property when you want to have better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better </div>
</body>
</html>
Meteor's strength is in it's real-time updates feature which works well for some of the social applications you see nowadays where you see everyone's updates for what you're working on. These updates center around replicating subsets of a MongoDB collection underneath the covers as local mini-mongo (their client side MongoDB subset) database updates on your web browser (which causes multiple render events to be fired on your templates). The latter part about multiple render updates is also the weakness. If you want your UI to control when the UI refreshes (e.g., classic jQuery AJAX pages where you load up the HTML and you control all the AJAX calls and UI updates), you'll be fighting this mechanism.
Meteor uses a nice stack of Node.js plugins (Handlebars.js, Spark.js, Bootstrap css, etc. but using it's own packaging mechanism instead of npm) underneath along w/ MongoDB for the storage layer that you don't have to think about. But sometimes you end up fighting it as well...e.g., if you want to customize the Bootstrap theme, it messes up the loading sequence of Bootstrap's responsive.css file so it no longer is responsive (but this will probably fix itself when Bootstrap 3.0 is released soon).
So like all "full stack frameworks", things work great as long as your app fits what's intended. Once you go beyond that scope and push the edge boundaries, you might end up fighting the framework...
This is from the msdn article here:
https://blogs.msdn.microsoft.com/tomarcher/2006/05/10/are-hash-codes-unique/
"While you will hear people state that hash codes generate a unique value for a given input, the fact is that, while difficult to accomplish, it is technically feasible to find two different data inputs that hash to the same value. However, the true determining factors regarding the effectiveness of a hash algorithm lie in the length of the generated hash code and the complexity of the data being hashed."
So just use a hash algorithm suitable to your data size and it will have unique hashcodes.
The answer by @Federico Giorgi was a very good answer. It helpt me. Therefore, I did the following, in order to produce multiple lines in the same plot from the data of a single dataset, I used a for loop. Legend can be added as well.
plot(tab[,1],type="b",col="red",lty=1,lwd=2, ylim=c( min( tab, na.rm=T ),max( tab, na.rm=T ) ) )
for( i in 1:length( tab )) { [enter image description here][1]
lines(tab[,i],type="b",col=i,lty=1,lwd=2)
}
axis(1,at=c(1:nrow(tab)),labels=rownames(tab))
No. From the XHTML 1.0 Spec
In XML, fragment identifiers are of type ID, and there can only be a single attribute of type ID per element. Therefore, in XHTML 1.0 the id attribute is defined to be of type ID. In order to ensure that XHTML 1.0 documents are well-structured XML documents, XHTML 1.0 documents MUST use the id attribute when defining fragment identifiers on the elements listed above. See the HTML Compatibility Guidelines for information on ensuring such anchors are backward compatible when serving XHTML documents as media type text/html.
I'm a newbie in Ansible, but I would suggest next solution:
playbook.yml
...
vars:
command_output_full:
stdout: will be overriden below
command_output: {{ command_output_full.stdout }}
...
...
...
tasks:
- name: Create variable from command
command: "echo Hello"
register: command_output_full
- debug: msg="{{ command_output }}"
It should work (and works for me) because Ansible uses lazy evaluation. But it seems it checks validity before the launch, so I have to define command_output_full.stdout
in vars.
And, of course, if it is too many such vars in vars
section, it will look ugly.
Dim thisMonth As New DateTime(DateTime.Today.Year, DateTime.Today.Month, 1)
Dim firstDayLastMonth As DateTime
Dim lastDayLastMonth As DateTime
firstDayLastMonth = thisMonth.AddMonths(-1)
lastDayLastMonth = thisMonth.AddDays(-1)
TEXT
is used for large pieces of string data. If the length of the field exceeed a certain threshold, the text is stored out of row.
VARCHAR
is always stored in row and has a limit of 8000 characters. If you try to create a VARCHAR(x)
, where x > 8000, you get an error:
Server: Msg 131, Level 15, State 3, Line 1
The size () given to the type ‘varchar’ exceeds the maximum allowed for any data type (8000)
These length limitations do not concern VARCHAR(MAX)
in SQL Server 2005, which may be stored out of row, just like TEXT
.
Note that MAX
is not a kind of constant here, VARCHAR
and VARCHAR(MAX)
are very different types, the latter being very close to TEXT
.
In prior versions of SQL Server you could not access the TEXT
directly, you only could get a TEXTPTR
and use it in READTEXT
and WRITETEXT
functions.
In SQL Server 2005 you can directly access TEXT
columns (though you still need an explicit cast to VARCHAR
to assign a value for them).
TEXT
is good:
VARCHAR
is good:
By selecting here I mean issuing any queries that return the value of the column.
By searching here I mean issuing any queries whose result depends on the value of the TEXT
or VARCHAR
column. This includes using it in any JOIN
or WHERE
condition.
As the TEXT
is stored out of row, the queries not involving the TEXT
column are usually faster.
Some examples of what TEXT
is good for:
Some examples of what VARCHAR
is good for:
As a rule of thumb, if you ever need you text value to exceed 200 characters AND do not use join on this column, use TEXT
.
Otherwise use VARCHAR
.
P.S. The same applies to UNICODE
enabled NTEXT
and NVARCHAR
as well, which you should use for examples above.
P.P.S. The same applies to VARCHAR(MAX)
and NVARCHAR(MAX)
that SQL Server 2005+ uses instead of TEXT
and NTEXT
. You'll need to enable large value types out of row
for them with sp_tableoption
if you want them to be always stored out of row.
As mentioned above and here, TEXT
is going to be deprecated in future releases:
The
text in row
option will be removed in a future version of SQL Server. Avoid using this option in new development work, and plan to modify applications that currently usetext in row
. We recommend that you store large data by using thevarchar(max)
,nvarchar(max)
, orvarbinary(max)
data types. To control in-row and out-of-row behavior of these data types, use thelarge value types out of row
option.
The trick to avoid round-off problem is to use a separate number to move through the range, that starts and half the step ahead of start.
# floating point range
def frange(a, b, stp=1.0):
i = a+stp/2.0
while i<b:
yield a
a += stp
i += stp
Alternatively, numpy.arange
can be used.
If nothing works from above solutions follow these steps
From Targets select appnameTests Under "Info"
Change following
Bundle Identifier: com.ProjectName.$(PRODUCT_NAME:rfc1034identifier)
to com.ProjectName.appname
Bundle name: $(PRODUCT_NAME)
Bundle name: appname
Compile & execute
The hexadecimal value you are looking for is %2B
To get it automatically in PHP run your string through urlencode($stringVal)
. And then run it rhough urldecode($stringVal)
to get it back.
If you want the JavaScript to handle it, use escape( str )
Edit
After @bobince's comment I did more reading and he is correct.
Use encodeURIComponent(str)
and decodeURIComponent(str)
. Escape will not convert the characters, only escape them with \
's
file --mime works, but not --mime-type. at least for my RHEL 5.
Or try defining the array as an object. (var cars = {};) Then there is no need to convert to json. This might not be practical in your example but worked well for me.
I am looking for a way to create a select without repeating the conditional query.
I'm assuming that you don't want to repeat Foo-stuff+bar
. You could put your calculation into a derived table:
SELECT CASE WHEN a.TestValue > 2 THEN a.TestValue ELSE 'Fail' END
FROM (SELECT (Foo-stuff+bar) AS TestValue FROM MyTable) AS a
A common table expression would work just as well:
WITH a AS (SELECT (Foo-stuff+bar) AS TestValue FROM MyTable)
SELECT CASE WHEN a.TestValue > 2 THEN a.TestValue ELSE 'Fail' END
FROM a
Also, each part of your switch should return the same datatype, so you may have to cast one or more cases.
To add to @abevieiramota's excellent answer, you can get the euqivalent of tight_layout with constrained_layout. You will still get large horizontal gaps if you use imshow
instead of pcolormesh
because of the 1:1 aspect ratio imposed by imshow
.
import numpy as np
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2, ncols=2, constrained_layout=True)
for ax in axes.flat:
im = ax.pcolormesh(np.random.random((10,10)), vmin=0, vmax=1)
fig.colorbar(im, ax=axes.flat)
plt.show()
Use the radix parameter of parseInt
:
var binary = "1101000";
var digit = parseInt(binary, 2);
console.log(digit);
The id should set as auto-increment
.
To modify an existing id column to auto-increment, just add this
ALTER TABLE card_games MODIFY id int NOT NULL AUTO_INCREMENT;
Try
ps -ef | grep "KEYWORD" | awk '{print $2}'
That command should give you the PID of the processes with KEYWORD in them. In this instance, awk
is returning what is in the 2nd column from the output.
Just offering an alternative as I had this problem and none of the other answers here had the desired effect I wanted. So instead I used a list. Now semantically the information I was outputting could have been regarded as both tabular data but also listed data.
So in the end what I did was:
<ul>
<li class="group">
<span class="title">...</span>
<span class="description">...</span>
<span class="mp3-player">...</span>
<span class="download">...</span>
<span class="shortlist">...</span>
</li>
<!-- looped <li> -->
</ul>
So basically ul
is table
, li
is tr
, and span
is td
.
Then in CSS I set the span
elements to be display:block;
and float:left;
(I prefer that combination to inline-block
as it'll work in older versions of IE, to clear the float effect see: http://css-tricks.com/snippets/css/clear-fix/) and to also have the ellipses:
span {
display: block;
float: left;
width: 100%;
// truncate when long
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
Then all you do is set the max-widths
of your spans and that'll give the list an appearance of a table.
After you changed a Mac which are not the origin one who created the disitribution certificate, you will missing the private key.Just delete the origin certificate and recreate a new one, that works for me~
I think that would be better if we use directly the split function
String toSplit = "/abc/def/ghfj.doc";
String result[] = toSplit.split("/");
String returnValue = result[result.length - 1]; //equals "ghfj.doc"
JavaScript runs in the context of the current HTML document, so it won't be able to determine anything about a current user unless it's in the current page or you do AJAX calls to a server-side script to get more information.
JavaScript will not be able to determine your Windows user name.
you need nested foreach loops
foreach($samplearr as $key => $item){
echo $key;
foreach($item as $detail){
echo $detail['value1'] . " " . $detail['value2']
}
}
You can set the line size as per the width of the window and set wrap off using the following command.
set linesize 160;
set wrap off;
I have used 160 as per my preference you can set it to somewhere between 100 - 200
and setting wrap will not your data and it will display the data properly.
Simple usage of GDB, to debug coredump files:
gdb <executable_path> <coredump_file_path>
A coredump file for a "process" gets created as a "core.pid" file.
After you get inside the GDB prompt (on execution of the above command), type:
...
(gdb) where
This will get you with the information, of the stack, where you can analayze the cause of the crash/fault. Other command, for the same purposes is:
...
(gdb) bt full
This is the same as above. By convention, it lists the whole stack information (which ultimately leads to the crash location).
A simple solution using fscanf
:
void read_ints (const char* file_name)
{
FILE* file = fopen (file_name, "r");
int i = 0;
fscanf (file, "%d", &i);
while (!feof (file))
{
printf ("%d ", i);
fscanf (file, "%d", &i);
}
fclose (file);
}
If your phone number contains spaces, remove them first! Then you can use the accepted answer's solution.
let numbersOnly = busPhone.replacingOccurrences(of: " ", with: "")
if let url = URL(string: "tel://\(numbersOnly)"), UIApplication.shared.canOpenURL(url) {
if #available(iOS 10, *) {
UIApplication.shared.open(url)
} else {
UIApplication.shared.openURL(url)
}
}
Running eclipse and also running Maven will require you to store two path variables, one in your jdk1.7_x_x_x location and also in your jdk1.7_x_x_\bin. If you are using Windows, when you are in your environment variables, do the following:
1) create a USER variable called JAVA_HOME. Point this to the location of your JAVA file. For example: "C:\Program Files\Java\jdk1.7.0_51" (remove the quotes)
2) under the PATH, append %JAVA_HOME% to the PATH. This will add the file location from step 1 to your PATH. This is good for MAVEN
3) if you are using eclipse you need to have the path point to "C:\Program Files\Java\jdk1.7.0_51\bin". Now append %JAVA_HOME%\bin to the end of your path.
4) your path should look something like this: C:\Program Files (x86)\Google\google_appengine\;C:\Users\username\AppData\Roaming\npm;%M2%;%JAVA_HOME%;%JAVA_HOME%\bin
Notes: the items that are enclosed in %'s like %M2% are assigned variables. It looks redundant but necessary. You can confirm that everything works by typing in:
java -version
javac -version
mvn -version
Each of those three statements typed in comman prompt should not return errors.
Check against any long running queries in your database.
Increasing your pool size will only make your webapp live a little longer (and probably get a lot slower)
You can use sql server profiler and filter on duration / reads to see which querys need optimization.
I also see you're probably keeping a global connection?
blnMainConnectionIsCreatedLocal
Let .net do the pooling for you and open / close your connection with a using statement.
Suggestions:
Always open and close a connection like this, so .net can manage your connections and you won't run out of connections:
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
// do some stuff
} //conn disposed
As I mentioned, check your query with sql server profiler and see if you can optimize it. Having a slow query with many requests in a web app can give these timeouts too.
I've made very simple function for marquee. See: http://jsfiddle.net/vivekw/pHNpk/2/ It pauses on mouseover & resumes on mouseleave. Speed can be varied. Easy to understand.
function marquee(a, b) {
var width = b.width();
var start_pos = a.width();
var end_pos = -width;
function scroll() {
if (b.position().left <= -width) {
b.css('left', start_pos);
scroll();
}
else {
time = (parseInt(b.position().left, 10) - end_pos) *
(10000 / (start_pos - end_pos)); // Increase or decrease speed by changing value 10000
b.animate({
'left': -width
}, time, 'linear', function() {
scroll();
});
}
}
b.css({
'width': width,
'left': start_pos
});
scroll(a, b);
b.mouseenter(function() { // Remove these lines
b.stop(); //
b.clearQueue(); // if you don't want
}); //
b.mouseleave(function() { // marquee to pause
scroll(a, b); //
}); // on mouse over
}
$(document).ready(function() {
marquee($('#display'), $('#text')); //Enter name of container element & marquee element
});
Well, your script throws an error and you just need to catch it (and/or prevent it from happening). I had the same error, for me it was an already used port (EADDRINUSE).
You have to explicitly set the position of the parent container along with the position of the child container. The typical way to do that is something like this:
div.parent{
position: relative;
left: 0px; /* stick it wherever it was positioned by default */
top: 0px;
}
div.child{
position: absolute;
left: 10px;
top: 10px;
}
Another simple solution with +=
:
$y = 1;
for ($x = $y; $x <= 15; $y++) {
printf("The number of first paragraph is: $y <br>");
printf("The number of second paragraph is: $x+=2 <br>");
}
Some options:
tr
tr -d '\15\32' < windows.txt > unix.txt
OR
tr -d '\r' < windows.txt > unix.txt
perl
perl -p -e 's/\r$//' < windows.txt > unix.txt
sed
sed 's/^M$//' windows.txt > unix.txt
OR
sed 's/\r$//' windows.txt > unix.txt
To obtain ^M
, you have to type CTRL-V
and then CTRL-M
.
In Bash, you can use parameter expansion to modify a string to all lower-/upper-case:
var1=TesT
var2=tEst
echo ${var1,,} ${var2,,}
echo ${var1^^} ${var2^^}
Don't forget that you can not cross domains because of security.
So if this is the case, you should use JSON.
jQuery has the hasClass() function that returns true if any element in the wrapped set contains the specified class
if (!$(this).hasClass("selected")) {
//do stuff
}
Take a look at my example of use
Here is the code for it
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
<title>Sandbox</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body { background-color: #FFF; font: 16px Helvetica, Arial; color: #000; }
</style>
<!-- jQuery code here -->
<script type="text/javascript">
$(function() {
$('#myButton').click(function(e) {
$('#div2').addClass('selected');
});
$('.thumbs').bind('click',function(e) { alert('You clicked ' + e.target.id ); } );
$('.thumbs').hover(fadeItIn, fadeItOut);
});
function fadeItIn(e) {
if (!$(e.target).hasClass('selected'))
{
$(e.target).fadeTo('normal', 1.0);
}
}
function fadeItOut(e) {
if (!$(e.target).hasClass('selected'))
{
$(e.target).fadeTo('slow', 0.3);
}
}
</script>
</head>
<body>
<div id="div1" class="thumbs" style=" background-color: #0f0; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both;">
One div with a thumbs class
</div>
<div id="div2" class="thumbs" style=" background-color: #f00; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both;">
Another one with a thumbs class
</div>
<input type="button" id="myButton" value="add 'selected' class to red div" />
</body>
</html>
EDIT:
this is just a guess, but are you trying to achieve something like this?
jQuery Code is here-
$(function() {
$('.thumbs').bind('click',function(e) { $(e.target).toggleClass('selected'); } );
$('.thumbs').hover(fadeItIn, fadeItOut);
$('.thumbs').css('opacity', 0.3);
});
function fadeItIn(e) {
if (!$(e.target).hasClass('selected'))
{
$(e.target).fadeTo('normal', 1.0);
}
}
function fadeItOut(e) {
if (!$(e.target).hasClass('selected'))
{
$(e.target).fadeTo('slow', 0.3);
}
}
<div id="div1" class="thumbs" style=" background-color: #0f0; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both; cursor:pointer;">
One div with a thumbs class
</div>
<div id="div2" class="thumbs" style=" background-color: #f00; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both; cursor:pointer;">
Another one with a thumbs class
</div>
IMHO I think that all the models have a great place but the problem I have with the model first approach is in many large businesses with DBA's controlling the databases you do not get the flexibility of building applications without using database first approaches. I have worked on many projects and when it came to deployment they wanted full control.
So as much as I agree with all the possible variations Code First, Model First, Database first, you must consider the actual production environment. So if your system is going to be a large user base application with many users and DBA's running the show then you might consider the Database first option just my opinion.
Following the instructions here http://help.loftware.com/pages/viewpage.action?pageId=27099554 I had to install the Microsoft Access Database Engine 2010 Redistributable before I had the Excel driver installed to use the DSN-less connection I wanted to use from perl.
if i want to check if any speicfic position of command line arguement is passed or not then how to check? like for example in some scenarios 2 command line args will be passed and in some only one will be passed then how do it check wheather the specfic commnad line is passed or not?
public class check {
public static void main(String[] args) {
if(args[0].length()!=0)
{
System.out.println("entered first if");
}
if(args[0].length()!=0 && args[1].length()!=0)
{
System.out.println("entered second if");
}
}
}
So in the above code if args[1] is not passed then i get java.lang.ArrayIndexOutOfBoundsException:
so how do i tackle this where i can check if second arguement is passed or not and if passed then enter it. need assistance asap.
Use non-static position along with greater z-index in child element:
.parent {
position: absolute
z-index: 100;
}
.child {
position: relative;
z-index: 101;
}
A very good solution to this can be found here:
Here's a class that serves as a wrapper to a pyserial object. It allows you to read lines without 100% CPU. It does not contain any timeout logic. If a timeout occurs,
self.s.read(i)
returns an empty string and you might want to throw an exception to indicate the timeout.
It is also supposed to be fast according to the author:
The code below gives me 790 kB/sec while replacing the code with pyserial's readline method gives me just 170kB/sec.
class ReadLine:
def __init__(self, s):
self.buf = bytearray()
self.s = s
def readline(self):
i = self.buf.find(b"\n")
if i >= 0:
r = self.buf[:i+1]
self.buf = self.buf[i+1:]
return r
while True:
i = max(1, min(2048, self.s.in_waiting))
data = self.s.read(i)
i = data.find(b"\n")
if i >= 0:
r = self.buf + data[:i+1]
self.buf[0:] = data[i+1:]
return r
else:
self.buf.extend(data)
ser = serial.Serial('COM7', 9600)
rl = ReadLine(ser)
while True:
print(rl.readline())
e.g.
string str = null;
string retString = null;
str = "This is substring test";
retString = str.Substring(8, 9);
This return "substring"
This should work!
[HttpPost]
public ActionResult RedirectToImages(int id)
{
return RedirectToAction("Index", "ProductImageManeger", new { id = id });
}
[HttpGet]
public ViewResult Index(int id)
{
return View(_db.ProductImages.Where(rs => rs.ProductId == id).ToList());
}
Notice that you don't have to pass the name of view if you are returning the same view as implemented by the action.
Your view should inherit the model as this:
@model <Your class name>
You can then access your model in view as:
@Model.<property_name>
You can simply set the status code of the response to 200 like the following
public ActionResult SomeMethod(parameters...)
{
//others code here
...
Response.StatusCode = 200;
return YourObject;
}
time1
is the key of the most outer dictionary, eg, feb2012
. So then you're trying to index the string, but you can only do this with integers. I think what you wanted was:
for info in courses[time1][course]:
As you're going through each dictionary, you must add another nest.
You can do something like this:
function writeFile(i){
var i = i || 0;
var fileName = 'a_' + i + '.jpg';
fs.exists(fileName, function (exists) {
if(exists){
writeFile(++i);
} else {
fs.writeFile(fileName);
}
});
}
<div class="container-div">
<div class="center-div">
</div>
</div>
.container-div {position:fixed; left: 0; bottom: 0; width: 100%; margin: 0;}
.center-div {width: 200px; margin: 0 auto;}
This should do the same.
DON'T USE A TRANSAPENT OR NULL LAYOUT because then the button
(or the generic view) will no more highlight at click!!!
I had the same problem and finally I found the correct attribute from Android API to solve the problem. It can apply to any view
Use this in the button specifications
android:background="?android:selectableItemBackground"
This requires API 11
MotionEvent is generated only by touching the screen.
Simplest way to truly remove all non-numeric characters:
echo preg_replace('/\D/', '', $string);
\D
represents "any character that is not a decimal digit"
To expand on what Shimi has said, you should only be running your loop from 1 to the square root of n. Then to find the pair, do n / i
, and this will cover the whole problem space.
As was also noted, this is a NP, or 'difficult' problem. Exhaustive search, the way you are doing it, is about as good as it gets for guaranteed answers. This fact is used by encryption algorithms and the like to help secure them. If someone were to solve this problem, most if not all of our current 'secure' communication would be rendered insecure.
Python code:
import math
def divisorGenerator(n):
large_divisors = []
for i in xrange(1, int(math.sqrt(n) + 1)):
if n % i == 0:
yield i
if i*i != n:
large_divisors.append(n / i)
for divisor in reversed(large_divisors):
yield divisor
print list(divisorGenerator(100))
Which should output a list like:
[1, 2, 4, 5, 10, 20, 25, 50, 100]
html, body {
height:100%;
}
body {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Cross browser way of doing this is
var top = ($(window).scrollTop() || $("body").scrollTop());
The Date type is just an alias of the DateTime type used by VB.NET (like int becomes Integer). Both of these types have a Date property that returns you the object with the time part set to 00:00:00.
In order to move a View anywhere on the screen, I would recommend placing it in a full screen layout. By doing so, you won't have to worry about clippings or relative coordinates.
You can try this sample code:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:id="@+id/rootLayout">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MOVE" android:layout_centerHorizontal="true"/>
<ImageView
android:id="@+id/img1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="10dip"/>
<ImageView
android:id="@+id/img2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_centerVertical="true" android:layout_alignParentRight="true"/>
<ImageView
android:id="@+id/img3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_alignParentBottom="true" android:layout_marginBottom="100dip"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:clipChildren="false" android:clipToPadding="false">
<ImageView
android:id="@+id/img4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_marginTop="150dip"/>
</LinearLayout>
</RelativeLayout>
Your activity
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button) findViewById( R.id.btn1 )).setOnClickListener( new OnClickListener()
{
@Override
public void onClick(View v)
{
ImageView img = (ImageView) findViewById( R.id.img1 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img2 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img3 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img4 );
moveViewToScreenCenter( img );
}
});
}
private void moveViewToScreenCenter( View view )
{
RelativeLayout root = (RelativeLayout) findViewById( R.id.rootLayout );
DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics( dm );
int statusBarOffset = dm.heightPixels - root.getMeasuredHeight();
int originalPos[] = new int[2];
view.getLocationOnScreen( originalPos );
int xDest = dm.widthPixels/2;
xDest -= (view.getMeasuredWidth()/2);
int yDest = dm.heightPixels/2 - (view.getMeasuredHeight()/2) - statusBarOffset;
TranslateAnimation anim = new TranslateAnimation( 0, xDest - originalPos[0] , 0, yDest - originalPos[1] );
anim.setDuration(1000);
anim.setFillAfter( true );
view.startAnimation(anim);
}
The method moveViewToScreenCenter
gets the View's absolute coordinates and calculates how much distance has to move from its current position to reach the center of the screen. The statusBarOffset
variable measures the status bar height.
I hope you can keep going with this example. Remember that after the animation your view's position is still the initial one. If you tap the MOVE button again and again the same movement will repeat. If you want to change your view's position do it after the animation is finished.
This worked for me:
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(.*)
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
SELECT c.* FROM(
SELECT '071235' AS token UNION ALL SELECT '07113'
UNION ALL SELECT '071343'
UNION ALL SELECT '0713SA'
UNION ALL SELECT '071443') AS c
JOIN (
SELECT '0712%' AS pattern UNION ALL SELECT '0711%'
UNION ALL SELECT '071343') AS d
ON c.token LIKE d.pattern
071235
07113
071343
I seriously do think that it is code smell if you need to mock static methods, too.
The only time this seems overkill to me, is libs like Guava, but you shouldn't need to mock this kind anyway cause it's part of the logic... (stuff like Iterables.transform(..))
That way your own code stays clean, you can mock out all your dependencies in a clean way, and you have an anti corruption layer against external dependencies.
I've seen PowerMock in practice and all the classes we needed it for were poorly designed. Also the integration of PowerMock at times caused serious problems
(e.g. https://code.google.com/p/powermock/issues/detail?id=355)
PS: Same holds for private methods, too. I don't think tests should know about the details of private methods. If a class is so complex that it tempts to mock out private methods, it's probably a sign to split up that class...
You may get an error like this when trying to build an app that uses a VectorDrawable for an Adaptive Icon. And your XML file contains "android:fillColor"
with a <gradient>
block:
res/drawable/icon_with_gradient.xml
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="96dp"
android:height="96dp"
android:viewportHeight="100"
android:viewportWidth="100">
<path
android:pathData="M1,1 H99 V99 H1Z"
android:strokeColor="?android:attr/colorAccent"
android:strokeWidth="2">
<aapt:attr name="android:fillColor">
<gradient
android:endColor="#156a12"
android:endX="50"
android:endY="99"
android:startColor="#1e9618"
android:startX="50"
android:startY="1"
android:type="linear" />
</aapt:attr>
</path>
</vector>
Gradient fill colors are commonly used in Adaptive Icons, such as in the tutorials here, here and here.
Even though the layout preview works fine, when you build the app, you will see an error like this:
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:mergeDebugResources'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
> Error while processing Project/app/src/main/res/drawable/icon_with_gradient.xml : null
(More info shown when the gradle build is run with --stack-trace flag):
Caused by: java.lang.NullPointerException
at com.android.ide.common.vectordrawable.VdPath.addGradientIfExists(VdPath.java:614)
at com.android.ide.common.vectordrawable.VdTree.parseTree(VdTree.java:149)
at com.android.ide.common.vectordrawable.VdTree.parse(VdTree.java:129)
at com.android.ide.common.vectordrawable.VdParser.parse(VdParser.java:39)
at com.android.ide.common.vectordrawable.VdPreview.getPreviewFromVectorXml(VdPreview.java:197)
at com.android.builder.png.VectorDrawableRenderer.generateFile(VectorDrawableRenderer.java:224)
at com.android.build.gradle.tasks.MergeResources$MergeResourcesVectorDrawableRenderer.generateFile(MergeResources.java:413)
at com.android.ide.common.resources.MergedResourceWriter$FileGenerationWorkAction.run(MergedResourceWriter.java:409)
The solution is to move the file icon_with_gradient.xml
to drawable-v24/icon_with_gradient.xml
or drawable-v26/icon_with_gradient.xml
. It's because gradient fills are only supported in API 24 (Android 7) and above. More info here: VectorDrawable: Invalid drawable tag gradient
Your debut
and fin
values are floating point values, not integers, because taille
is a float.
Make those values integers instead:
item = plateau[int(debut):int(fin)]
Alternatively, make taille
an integer:
taille = int(sqrt(len(plateau)))
Its all about the library versions compatibility
I was facing this strange bug couple of 2 hours. I resolved this error by doing these steps
hange your build.gradle dependencies into
implementation 'com.google.android.gms:play-services-maps:17.0.0'
to
implementation 'com.google.android.gms:play-services-maps:15.0.0'
Using the html5 audio tag and jquery:
// appending HTML5 Audio Tag in HTML Body
$('<audio id="chatAudio">
<source src="notify.ogg" type="audio/ogg">
<source src="notify.mp3" type="audio/mpeg">
</audio>').appendTo('body');
// play sound
$('#chatAudio')[0].play();
Code from here.
In my implementation I added the audio embed directly into the HTML without jquery append.
This seems unnecessary, but VBA is a strange place. If you declare an array variable, then set it using Array()
then pass the variable into your function, VBA will be happy.
Sub test()
Dim fString As String
Dim arr() As Variant
arr = Array("foo", "bar")
fString = processArr(arr)
End Sub
Also your function processArr()
could be written as:
Function processArr(arr() As Variant) As String
processArr = Replace(Join(arr()), " ", "")
End Function
If you are into the whole brevity thing.
I have solved as plist file.
Add a NSAppTransportSecurity : Dictionary.
Add Subkey named " NSAllowsArbitraryLoads " as Boolean : YES
I think it is important to mention, now that this question is over 1 year old, that Socket.IO has since come out and seems to be the primary way to work with sockets in the browser now; it is also compatible with Node.js as far as I know.
Performance wise there is no difference. The only purpose of having const_iterator
over iterator
is to manage the accessesibility of the container on which the respective iterator runs. You can understand it more clearly with an example:
std::vector<int> integers{ 3, 4, 56, 6, 778 };
If we were to read & write the members of a container we will use iterator:
for( std::vector<int>::iterator it = integers.begin() ; it != integers.end() ; ++it )
{*it = 4; std::cout << *it << std::endl; }
If we were to only read the members of the container integers
you might wanna use const_iterator which doesn't allow to write or modify members of container.
for( std::vector<int>::const_iterator it = integers.begin() ; it != integers.end() ; ++it )
{ cout << *it << endl; }
NOTE: if you try to modify the content using *it in second case you will get an error because its read-only.
Implementation via recursion (dynamic programming), in Java, with test case (TestNG).
PrintPermutation.java
import java.util.Arrays;
/**
* Print permutation of n elements.
*
* @author eric
* @date Oct 13, 2018 12:28:10 PM
*/
public class PrintPermutation {
/**
* Print permutation of array elements.
*
* @param arr
* @return count of permutation,
*/
public static int permutation(int arr[]) {
return permutation(arr, 0);
}
/**
* Print permutation of part of array elements.
*
* @param arr
* @param n
* start index in array,
* @return count of permutation,
*/
private static int permutation(int arr[], int n) {
int counter = 0;
for (int i = n; i < arr.length; i++) {
swapArrEle(arr, i, n);
counter += permutation(arr, n + 1);
swapArrEle(arr, n, i);
}
if (n == arr.length - 1) {
counter++;
System.out.println(Arrays.toString(arr));
}
return counter;
}
/**
* swap 2 elements in array,
*
* @param arr
* @param i
* @param k
*/
private static void swapArrEle(int arr[], int i, int k) {
int tmp = arr[i];
arr[i] = arr[k];
arr[k] = tmp;
}
}
PrintPermutationTest.java (test case via TestNG)
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* PrintPermutation test.
*
* @author eric
* @date Oct 14, 2018 3:02:23 AM
*/
public class PrintPermutationTest {
@Test
public void test() {
int arr[] = new int[] { 0, 1, 2, 3 };
Assert.assertEquals(PrintPermutation.permutation(arr), 24);
int arrSingle[] = new int[] { 0 };
Assert.assertEquals(PrintPermutation.permutation(arrSingle), 1);
int arrEmpty[] = new int[] {};
Assert.assertEquals(PrintPermutation.permutation(arrEmpty), 0);
}
}
Simply you can set in php
file as
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
PHP's strtotime
function will interpret timezone codes, like UTC. If you get the date from the database/client without the timezone code, but know it's UTC, then you can append it.
Assuming you get the date with timestamp code (like "Fri Mar 23 2012 22:23:03 GMT-0700 (PDT)", which is what Javascript code ""+(new Date())
gives):
$time = strtotime($dateWithTimeZone);
$dateInLocal = date("Y-m-d H:i:s", $time);
Or if you don't, which is likely from MySQL, then:
$time = strtotime($dateInUTC.' UTC');
$dateInLocal = date("Y-m-d H:i:s", $time);
the command posted by Milad and Sandy did not work for me with mstsc. i had to add TERMSRV to the /generic switch. i found this information here: https://gist.github.com/jdforsythe/48a022ee22c8ec912b7e
cmdkey /generic:TERMSRV/<server> /user:<username> /pass:<password>
i could then use mstsc /v:<server>
without getting prompted for the login.
Try this:
<div class="rmz-srchbg">
<input type="text" id="globalsearchstr" name="search" value="" class="rmz-txtbox">
<input type="submit" value=" " id="srchbtn" class="rmz-srchico">
<br style="clear:both;">
</div>
<script>
$(function(){
$('#globalsearchstr').on('focus mouseenter', function(){
$(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat");
});
});
</script>
Here you can find every thing you need:
http://web.eecs.umich.edu/~sugih/courses/eecs487/glut-howto/#win
The CURL extension ext/curl
is not installed or enabled in your PHP installation. Check the manual for information on how to install or enable CURL on your system.
sudo apt-get install libv4l-dev
Editing for RH based systems :
On a Fedora 16 to install pygame 1.9.1 (in a virtualenv):
sudo yum install libv4l-devel
sudo ln -s /usr/include/libv4l1-videodev.h /usr/include/linux/videodev.h
You're comparing apples to oranges here:
webHttpBinding is the REST-style binding, where you basically just hit a URL and get back a truckload of XML or JSON from the web service
basicHttpBinding and wsHttpBinding are two SOAP-based bindings which is quite different from REST. SOAP has the advantage of having WSDL and XSD to describe the service, its methods, and the data being passed around in great detail (REST doesn't have anything like that - yet). On the other hand, you can't just browse to a wsHttpBinding endpoint with your browser and look at XML - you have to use a SOAP client, e.g. the WcfTestClient or your own app.
So your first decision must be: REST vs. SOAP (or you can expose both types of endpoints from your service - that's possible, too).
Then, between basicHttpBinding and wsHttpBinding, there differences are as follows:
basicHttpBinding is the very basic binding - SOAP 1.1, not much in terms of security, not much else in terms of features - but compatible to just about any SOAP client out there --> great for interoperability, weak on features and security
wsHttpBinding is the full-blown binding, which supports a ton of WS-* features and standards - it has lots more security features, you can use sessionful connections, you can use reliable messaging, you can use transactional control - just a lot more stuff, but wsHttpBinding is also a lot *heavier" and adds a lot of overhead to your messages as they travel across the network
For an in-depth comparison (including a table and code examples) between the two check out this codeproject article: Differences between BasicHttpBinding and WsHttpBinding
You can use scroll-behavior: smooth;
to get this done without Javascript
https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior
git checkout my_other_branch
git add my_file my_other_file
git commit -m
And provide your commit message.
I have found we can pass Django variables to javascript functions like this:-
<button type="button" onclick="myJavascriptFunction('{{ my_django_variable }}')"></button>
<script>
myJavascriptFunction(djangoVariable){
alert(djangoVariable);
}
</script>
For one, I'd strongly suggest updating to the latest Android Studio (0.3.7 as of now); there are tons of bug fixes.
You're running into bug https://code.google.com/p/android/issues/detail?id=57692, which is that if you try to use the UI to rename modules or your project, it doesn't update the build files. Sorry, it's really broken right now. I'd suggest changing the directory names directly in the filesystem, and updating your settings.gradle
file to reflect the changes. Your project on disk should look something like this (with many more files than what's shown here):
projectFolder
|--settings.gradle
|--applicationModuleFolder
| |--build.gradle
| |--src
it uses projectFolder's name as the project name and applicationModuleFolder as the name of the module that your Android App lives in (the upper and lower outlined boxes in your screenshot, respectively). I think the way your project is set up now, they both have the same name; you can rename both to the same new name if you like, or you can give them different names; it doesn't matter.
Once they're renamed, edit your settings.gradle
file; it will look something like:
include ':applicationModuleFolder'
just change the name to your new name there as well. Once these changes are made, click the Sync Project with Gradle Files button in the toolbar (if you're running a very old version of Android Studio, it may not have that button, so you can close the project and reopen it in that case) and it should pick up the changes.
Warning: This might inflate executable file size a little bit and cost a little runtime performance. IMO, this would be better if golang has such feature like macro or function decorator.
If you want to mock functions without changing its API, the easiest way is to change the implementation a little bit:
func getPage(url string) string {
if GetPageMock != nil {
return GetPageMock()
}
// getPage real implementation goes here!
}
func downloader() {
if GetPageMock != nil {
return GetPageMock()
}
// getPage real implementation goes here!
}
var GetPageMock func(url string) string = nil
var DownloaderMock func() = nil
This way we can actually mock one function out of the others. For more convenient we can provide such mocking boilerplate:
// download.go
func getPage(url string) string {
if m.GetPageMock != nil {
return m.GetPageMock()
}
// getPage real implementation goes here!
}
func downloader() {
if m.GetPageMock != nil {
return m.GetPageMock()
}
// getPage real implementation goes here!
}
type MockHandler struct {
GetPage func(url string) string
Downloader func()
}
var m *MockHandler = new(MockHandler)
func Mock(handler *MockHandler) {
m = handler
}
In test file:
// download_test.go
func GetPageMock(url string) string {
// ...
}
func TestDownloader(t *testing.T) {
Mock(&MockHandler{
GetPage: GetPageMock,
})
// Test implementation goes here!
Mock(new(MockHandler)) // Reset mocked functions
}
There are a couple of variables to set the max number of connections. Most likely, you're running out of file numbers first. Check ulimit -n. After that, there are settings in /proc, but those default to the tens of thousands.
More importantly, it sounds like you're doing something wrong. A single TCP connection ought to be able to use all of the bandwidth between two parties; if it isn't:
ping -s 1472
...)tc
iperf
Possibly I have misunderstood. Maybe you're doing something like Bittorrent, where you need lots of connections. If so, you need to figure out how many connections you're actually using (try netstat
or lsof
). If that number is substantial, you might:
ulimit -n
. Still, ~1000 connections (default on my system) is quite a few.iostat -x
?Also, if you are using a consumer-grade NAT router (Linksys, Netgear, DLink, etc.), beware that you may exceed its abilities with thousands of connections.
I hope this provides some help. You're really asking a networking question.
instead of getting Notepad++, You can simply Open the file with Wordpad and then Save As - Plain Text document
Think of void as the "empty structure". Let me explain.
Every function takes a sequence of parameters, where each parameter has a type. In fact, we could package up the parameters into a structure, with the structure slots corresponding to the parameters. This makes every function have exactly one argument. Similarly, functions produce a result, which has a type. It could be a boolean, or it could be float, or it could be a structure, containing an arbitrary set of other typed values. If we want a languge that has multiple return values, it is easy to just insist they be packaged into a structure. In fact, we could always insist that a function returned a structure. Now every function takes exactly one argument, and produces exactly one value.
Now, what happens when I need a function that produces "no" value? Well, consider what I get when I form a struct with 3 slots: it holds 3 values. When I have 2 slots, it holds two values. When it has one slot, one value. And when it has zero slots, it holds... uh, zero values, or "no" value". So, I can think of a function returning void as returning a struct containing no values. You can even decide that "void" is just a synonym for the type represented by the empty structure, rather than a keyword in the language (maybe its just a predefined type :)
Similarly, I can think of a function requiring no values as accepting an empty structure, e.g., "void".
I can even implement my programming language this way. Passing a void value takes up zero bytes, so passing void values is just a special case of passing other values of arbitrary size. This makes it easy for the compiler to treat the "void" result or argument. You probably want a langauge feature that can throw a function result away; in C, if you call the non-void result function foo in the following statement: foo(...); the compiler knows that foo produces a result and simply ignores it. If void is a value, this works perfectly and now "procedures" (which are just an adjective for a function with void result) are just trivial special cases of general functions.
Void* is a bit funnier. I don't think the C designers thought of void in the above way; they just created a keyword. That keyword was available when somebody needed a point to an arbitrary type, thus void* as the idiom in C. It actually works pretty well if you interpret void as an empty structure. A void* pointer is the address of a place where that empty structure has been put.
Casts from void* to T* for other types T, also work out with this perspective. Pointer casts are a complete cheat that work on most common architectures to take advantage of the fact that if a compound type T has an element with subtype S placed physically at the beginning of T in its storage layout, then casting S* to T* and vice versa using the same physical machine address tends to work out, since most machine pointers have a single representation. Replacing the type S by the type void gives exactly the same effect, and thus casting to/from void* works out.
The PARLANSE programming language implements the above ideas pretty closely. We goofed in its design, and didn't pay close attention to "void" as a return type and thus have langauge keywords for procedure. Its mostly just a simple syntax change but its one of things you don't get around to once you get a large body working code in a language.
You can use the following in Firebase (FCM) to get the token:
FirebaseInstanceId.getInstance().getToken();
Safe Methods : Get Resource/No modification in resource
Idempotent : No change in resource status if requested many times
Unsafe Methods : Create or Update Resource/Modification in resource
Non-Idempotent : Change in resource status if requested many times
According to your requirement :
1) For safe and idempotent operation (Fetch Resource) use --------- GET METHOD
2) For unsafe and non-idempotent operation (Insert Resource) use--------- POST METHOD
3) For unsafe and idempotent operation (Update Resource) use--------- PUT METHOD
3) For unsafe and idempotent operation (Delete Resource) use--------- DELETE METHOD
**node_modules
This works for me
recursive approach to ignore all node_modules present in sub folders
Maybe python changed since this question, all of the below seem to work well
Python2.7
int(1324343032.324325235 * 1000) / 1000.0
float(int(1324343032.324325235 * 1000)) / 1000
round(int(1324343032.324325235 * 1000) / 1000.0,3)
# result for all of the above is 1324343032.324
If you have a JSON string and want to "prettify" it, but don't want to serialise it to and from a known C# type then the following does the trick (using JSON.NET):
using System;
using System.IO;
using Newtonsoft.Json;
class JsonUtil
{
public static string JsonPrettify(string json)
{
using (var stringReader = new StringReader(json))
using (var stringWriter = new StringWriter())
{
var jsonReader = new JsonTextReader(stringReader);
var jsonWriter = new JsonTextWriter(stringWriter) { Formatting = Formatting.Indented };
jsonWriter.WriteToken(jsonReader);
return stringWriter.ToString();
}
}
}
This could also caused by mismatching brace/parenthesis.
$(TARGET}:
do_something
Just use parenthesises and you'll be fine.
<script type="text/javascript">
$("ol li:nth-child(1)").addClass('olli1');
$("ol li:nth-child(2)").addClass("olli2");
$("ol li:nth-child(3)").addClass("olli3");
$("ol li:nth-child(4)").addClass("olli4");
$("ol li:nth-child(5)").addClass("olli5");
$("ol li:nth-child(6)").addClass("olli6");
$("ol li:nth-child(7)").addClass("olli7");
$("ol li:nth-child(8)").addClass("olli8");
$("ol li:nth-child(9)").addClass("olli9");
$("ol li:nth-child(10)").addClass("olli10");
$("ol li:nth-child(11)").addClass("olli11");
$("ol li:nth-child(12)").addClass("olli12");
$("ol li:nth-child(13)").addClass("olli13");
$("ol li:nth-child(14)").addClass("olli14");
$("ol li:nth-child(15)").addClass("olli15");
$("ol li:nth-child(16)").addClass("olli16");
$("ol li:nth-child(17)").addClass("olli17");
$("ol li:nth-child(18)").addClass("olli18");
$("ol li:nth-child(19)").addClass("olli19");
$("ol li:nth-child(20)").addClass("olli20");
</script>
change this to
<script type="text/javascript">
jQuery(document).ready(function ($) {
$("ol li:nth-child(1)").addClass('olli1');
$("ol li:nth-child(2)").addClass("olli2");
$("ol li:nth-child(3)").addClass("olli3");
$("ol li:nth-child(4)").addClass("olli4");
$("ol li:nth-child(5)").addClass("olli5");
$("ol li:nth-child(6)").addClass("olli6");
$("ol li:nth-child(7)").addClass("olli7");
$("ol li:nth-child(8)").addClass("olli8");
$("ol li:nth-child(9)").addClass("olli9");
$("ol li:nth-child(10)").addClass("olli10");
$("ol li:nth-child(11)").addClass("olli11");
$("ol li:nth-child(12)").addClass("olli12");
$("ol li:nth-child(13)").addClass("olli13");
$("ol li:nth-child(14)").addClass("olli14");
$("ol li:nth-child(15)").addClass("olli15");
$("ol li:nth-child(16)").addClass("olli16");
$("ol li:nth-child(17)").addClass("olli17");
$("ol li:nth-child(18)").addClass("olli18");
$("ol li:nth-child(19)").addClass("olli19");
$("ol li:nth-child(20)").addClass("olli20");
});
</script>
There is the option to use OleDB
and use the Excel sheets like datatables in a database...
Just an example.....
string con =
@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\temp\test.xls;" +
@"Extended Properties='Excel 8.0;HDR=Yes;'";
using(OleDbConnection connection = new OleDbConnection(con))
{
connection.Open();
OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection);
using(OleDbDataReader dr = command.ExecuteReader())
{
while(dr.Read())
{
var row1Col0 = dr[0];
Console.WriteLine(row1Col0);
}
}
}
This example use the Microsoft.Jet.OleDb.4.0
provider to open and read the Excel file. However, if the file is of type xlsx (from Excel 2007 and later), then you need to download the Microsoft Access Database Engine components and install it on the target machine.
The provider is called Microsoft.ACE.OLEDB.12.0;
. Pay attention to the fact that there are two versions of this component, one for 32bit and one for 64bit. Choose the appropriate one for the bitness of your application and what Office version is installed (if any). There are a lot of quirks to have that driver correctly working for your application. See this question for example.
Of course you don't need Office installed on the target machine.
While this approach has some merits, I think you should pay particular attention to the link signaled by a comment in your question Reading excel files from C#. There are some problems regarding the correct interpretation of the data types and when the length of data, present in a single excel cell, is longer than 255 characters
I have found another way of forcing re-run CI builds and other triggers:
git commit --amend --no-edit
without any changes. This will recreate the last commit in the current branch.git push --force-with-lease origin pr-branch
.You can try Restlet edition for android:
The source can be downloaded from Restlet website:
You could use macros to simulate the repeat-until syntax.
#define repeat do
#define until(exp) while(!(exp))
From the docs
IF boolean-expression THEN
statements
ELSE
statements
END IF;
So in your above example the code should look as follows:
IF select count(*) from orders > 0
THEN
DELETE from orders
ELSE
INSERT INTO orders values (1,2,3);
END IF;
You were missing: END IF;
first, check that the array actually exists, you could try something like
if (isset($votes)) {
// Do bad things to the votes array
}
If you using roles you could check for ROLE_USER
that is the solution i use:
if (TRUE === $this->get('security.authorization_checker')->isGranted('ROLE_USER')) {
// user is logged in
}
Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
//section.SectionInformation.UnprotectSection();
section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
config.Save();