Changing Command Execute Timeout in Management Studio:
Click on Tools -> Options
Select Query Execution from tree on left side and enter command timeout in "Execute Timeout" control.
Changing Command Timeout in Server:
In the object browser tree right click on the server which give you timeout and select "Properties" from context menu.
Now in "Server Properties -....." dialog click on "Connections" page in "Select a Page" list (on left side). On the right side you will get property
Remote query timeout (in seconds, 0 = no timeout):
[up/down control]
you can set the value in up/down control.
Nowadays you can use
try {
String s = CompletableFuture.supplyAsync(() -> br.readLine())
.get(1, TimeUnit.SECONDS);
} catch (TimeoutException e) {
System.out.println("Time out has occurred");
} catch (InterruptedException | ExecutionException e) {
// Handle
}
I'm having a very similar problem. In the past, this has been related to serialization problems. If you are still having this problem, can you verify that you can correctly serialize the objects you are returning. Specifically, if you are using Linq-To-Sql objects that have relationships, there are known serialization problems if you put a back reference on a child object to the parent object and mark that back reference as a DataMember.
You can verify serialization by writing a console app that serializes and deserializes your objects using the DataContractSerializer on the server side and whatever serialization methods your client uses. For example, in our current application, we have both WPF and Compact Framework clients. I wrote a console app to verify that I can serialize using a DataContractSerializer and deserialize using an XmlDesserializer. You might try that.
Also, if you are returning Linq-To-Sql objects that have child collections, you might try to ensure that you have eagerly loaded them on the server side. Sometimes, because of lazy loading, the objects being returned are not populated and may cause the behavior you are seeing where the request is sent to the service method multiple times.
If you have solved this problem, I'd love to hear how because I'm stuck with it too. I have verified that my issue is not serialization so I'm at a loss.
UPDATE: I'm not sure if it will help you any but the Service Trace Viewer Tool just solved my problem after 5 days of very similar experience to yours. By setting up tracing and then looking at the raw XML, I found the exceptions that were causing my serialization problems. It was related to Linq-to-SQL objects that occasionally had more child objects than could be successfully serialized. Adding the following to your web.config file should enable tracing:
<sharedListeners>
<add name="sharedListener"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData="c:\Temp\servicetrace.svclog" />
</sharedListeners>
<sources>
<source name="System.ServiceModel" switchValue="Verbose, ActivityTracing" >
<listeners>
<add name="sharedListener" />
</listeners>
</source>
<source name="System.ServiceModel.MessageLogging" switchValue="Verbose">
<listeners>
<add name="sharedListener" />
</listeners>
</source>
</sources>
The resulting file can be opened with the Service Trace Viewer Tool or just in IE to examine the results.
PHP's getimagesize()
returns an array of data. The first two items in the array are the two items you're interested in: the width and height. To get these, you would simply request the first two indexes in the returned array:
var $imagedata = getimagesize("someimage.jpg");
print "Image width is: " . $imagedata[0];
print "Image height is: " . $imagedata[1];
For further information, see the documentation.
A little late to the party, so mostly a reminder to me next time I do this search!
I have been able to use:
p/x *(&vec[2])@4
to print 4 elements (as hex) from vec
starting at vec[2]
.
For O(1) complexity of head,tail
operation you should use deque
however.
Following way:
from collections import deque
l = deque([1,2,3,4,5,6,7,8,9])
head, tail = l.popleft(), l
It's useful when you must iterate through all elements of the list. For example in naive merging 2 partitions in merge sort.
Use a loop on the split values
string values = "0,1,2,3,4,5,6,7,8,9";
foreach(string value in values.split(','))
{
//do something with individual value
}
<a href="<?php echo $_SERVER['DOCUMENT_ROOT'].'/hello.html'; ?>">go with php</a>
<br />
<a href="/hello.html">go to with html</a>
Try this yourself and find that they are not exactly the same.
$_SERVER['DOCUMENT_ROOT']
renders an actual file path (on my computer running as it's own server, C:/wamp/www/
HTML's /
renders the root of the server url, in my case, localhost/
But C:/wamp/www/hello.html
and localhost/hello.html
are in fact the same file
This worked for me.
Go to Project --> Properties --> Run/Debug Settings --> Click on the configuration & click "Edit", it will now open a "Edit Configuration".
Hit on "Search Project" , select the binary file from the "Binaries" and hit ok.
Note : Before doing all this, make sure you have done the below
--> Binary is generated once you execute "Build All" or (Ctrl+B)
You are trying to read xls
with explicit implementation poi classes for xlsx
.
G:\Selenium Jar Files\TestData\Data.xls
Either use HSSFWorkbook
and HSSFSheet
classes or make your implementation more generic by using shared interfaces, like;
Change:
XSSFWorkbook workbook = new XSSFWorkbook(file);
To:
org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(file);
And Change:
XSSFSheet sheet = workbook.getSheetAt(0);
To:
org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
According to https://github.com/composer/composer/issues/2119 you could extend your local composer.json
to state that it provides the extension (which it doesn't really do - that's why you shouldn't publicly publish your package, only use it internally).
Commons-net surely. :) Most open source projects use it these days.
yc
Thanks to everyone's contributions to this question, I've come up with the following script. Change the values for $SvcName
and $SvrName
to suit your needs. This script will start the remote service if it is stopped, or stop it if it is started. And it uses the cool .WaitForStatus
method to wait while the service responds.
#Change this values to suit your needs:
$SvcName = 'Spooler'
$SvrName = 'remotePC'
#Initialize variables:
[string]$WaitForIt = ""
[string]$Verb = ""
[string]$Result = "FAILED"
$svc = (get-service -computername $SvrName -name $SvcName)
Write-host "$SvcName on $SvrName is $($svc.status)"
Switch ($svc.status) {
'Stopped' {
Write-host "Starting $SvcName..."
$Verb = "start"
$WaitForIt = 'Running'
$svc.Start()}
'Running' {
Write-host "Stopping $SvcName..."
$Verb = "stop"
$WaitForIt = 'Stopped'
$svc.Stop()}
Default {
Write-host "$SvcName is $($svc.status). Taking no action."}
}
if ($WaitForIt -ne "") {
Try { # For some reason, we cannot use -ErrorAction after the next statement:
$svc.WaitForStatus($WaitForIt,'00:02:00')
} Catch {
Write-host "After waiting for 2 minutes, $SvcName failed to $Verb."
}
$svc = (get-service -computername $SvrName -name $SvcName)
if ($svc.status -eq $WaitForIt) {$Result = 'SUCCESS'}
Write-host "$Result`: $SvcName on $SvrName is $($svc.status)"
}
Of course, the account you run this under will need the proper privileges to access the remote computer and start and stop services. And when executing this against older remote machines, you might first have to install WinRM 3.0 on the older machine.
I also encountered that problem.Check if database name already exist in Mysql,and rename the old one.
I unistalled the original version of python (2.6.6) and install 2.7(with option make && make altinstall
) but when I tried install something with yum didn't work.
So I solved this issue as follow:
# ln -s /usr/local/bin/python /usr/bin/python
rpm -Uvh python-2.6.6-36.el6.i686.rpm
Done
If the constructor with width, height and weight is not working, try using the constructor with width and height. And then manually set the weight.
And if you want the width to be set according to the weight, set width as 0 in the constructor. Same applies for height. Below code works for me.
LinearLayout.LayoutParams childParam1 = new LinearLayout.LayoutParams(0,LinearLayout.LayoutParams.MATCH_PARENT);
childParam1.weight = 0.3f;
child1.setLayoutParams(childParam1);
LinearLayout.LayoutParams childParam2 = new LinearLayout.LayoutParams(0,LinearLayout.LayoutParams.MATCH_PARENT);
childParam2.weight = 0.7f;
child2.setLayoutParams(childParam2);
parent.setWeightSum(1f);
parent.addView(child1);
parent.addView(child2);
Actually you are right: it runs another instance of make. A possible solution would be:
.PHONY : clearscr fresh clean all
all :
compile executable
clean :
rm -f *.o $(EXEC)
fresh : clean clearscr all
clearscr:
clear
By calling make fresh
you get first the clean
target, then the clearscreen
which runs clear
and finally all
which does the job.
EDIT Aug 4
What happens in the case of parallel builds with make’s -j
option?
There's a way of fixing the order. From the make manual, section 4.2:
Occasionally, however, you have a situation where you want to impose a specific ordering on the rules to be invoked without forcing the target to be updated if one of those rules is executed. In that case, you want to define order-only prerequisites. Order-only prerequisites can be specified by placing a pipe symbol (|) in the prerequisites list: any prerequisites to the left of the pipe symbol are normal; any prerequisites to the right are order-only: targets : normal-prerequisites | order-only-prerequisites
The normal prerequisites section may of course be empty. Also, you may still declare multiple lines of prerequisites for the same target: they are appended appropriately. Note that if you declare the same file to be both a normal and an order-only prerequisite, the normal prerequisite takes precedence (since they are a strict superset of the behavior of an order-only prerequisite).
Hence the makefile becomes
.PHONY : clearscr fresh clean all
all :
compile executable
clean :
rm -f *.o $(EXEC)
fresh : | clean clearscr all
clearscr:
clear
EDIT Dec 5
It is not a big deal to run more than one makefile instance since each command inside the task will be a sub-shell anyways. But you can have reusable methods using the call function.
log_success = (echo "\x1B[32m>> $1\x1B[39m")
log_error = (>&2 echo "\x1B[31m>> $1\x1B[39m" && exit 1)
install:
@[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
command1 # this line will be a subshell
command2 # this line will be another subshell
@command3 # Use `@` to hide the command line
$(call log_error, "It works, yey!")
uninstall:
@[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
....
$(call log_error, "Nuked!")
Thanks to @Yiling. That was a hint.
<bean id="propertyConfigurer"
class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="searchSystemEnvironment" value="true" />
<property name="locations">
<list>
<value>file:#{systemEnvironment['FILE_PATH']}/first.properties</value>
<value>file:#{systemEnvironment['FILE_PATH']}/second.properties</value>
<value>file:#{systemEnvironment['FILE_PATH']}/third.properties</value>
</list>
</property>
</bean>
After this, you should have one environment variable named 'FILE_PATH'. Make sure you restart your terminal/IDE after creating that environment variable.
The executable code produced from a Java or C# compiler is not interpretted -- it is compiled to native code "just in time" (JIT). So, the first time code in a Java/C# program is encountered during execution, there is some overhead as the "runtime compiler" (aka JIT compiler) turns the byte code (Java) or IL code (C#) into native machine instructions. However, the next time that code is encountered while the application is still running, the native code is executed immediately. This explains how some Java/C# programs appear to be slow initially, but then perform better the longer they run. A good example is an ASP.Net web site. The very first time the web site is accessed, it may be a bit slower as the C# code is compiled to native code by the JIT compiler. Subsequent accesses result in a much faster web site -- server and client side caching aside.
You can create an HTTP GET
request and pipe its response
into a writable file stream:
const http = require('http'); // or 'https' for https:// URLs
const fs = require('fs');
const file = fs.createWriteStream("file.jpg");
const request = http.get("http://i3.ytimg.com/vi/J---aiyznGQ/mqdefault.jpg", function(response) {
response.pipe(file);
});
If you want to support gathering information on the command line--like specifying a target file or directory, or URL--check out something like Commander.
If you are using Java 8 and you want the last segment in a file path you can do.
Path path = Paths.get("example/path/to/file");
String lastSegment = path.getFileName().toString();
If you have a url such as http://base_path/some_segment/id
you can do.
final Path urlPath = Paths.get("http://base_path/some_segment/id");
final Path lastSegment = urlPath.getName(urlPath.getNameCount() - 1);
When dealing with day-of-week calculations, it's important to take account of the current DATEFIRST
settings. This query will always correctly exclude weekend days, using @@DATEFIRST
to account for any possible setting for the first day of the week.
SELECT *
FROM your_table
WHERE ((DATEPART(dw, date_created) + @@DATEFIRST) % 7) NOT IN (0, 1)
Assuming array
is a character array that does not end in \0
, you will want to use strncpy
:
char * strncpy(char * destination, const char * source, size_t num);
like so:
strncpy(string, array, 20);
string[20] = '\0'
Then string
will be a null terminated C string, as desired.
To stop apache process try this command
ps aux | grep tomcat | awk '{print $2}' | xargs kill -9
Urls should not have spaces in them. If you need to address one that does, use its encoded value of %20
You can also use df.assign
:
In [1559]: df
Out[1559]:
A B C
0 0 NaN NaN
1 4 NaN NaN
2 5 NaN NaN
3 6 NaN NaN
4 7 NaN NaN
5 7 NaN NaN
6 6 NaN NaN
7 5 NaN NaN
In [1560]: mylist = [2,5,6,8,12,16,26,32]
In [1567]: df = df.assign(D=mylist)
In [1568]: df
Out[1568]:
A B C D
0 0 NaN NaN 2
1 4 NaN NaN 5
2 5 NaN NaN 6
3 6 NaN NaN 8
4 7 NaN NaN 12
5 7 NaN NaN 16
6 6 NaN NaN 26
7 5 NaN NaN 32
Just wanted to put my 2 cents in. I modified @Ajay Singh's function to handle countdown and count up Here is a snip from the jsfiddle.
var countDown = Math.floor(Date.now() / 1000)
runClock(null, function(e, r){ console.log( e.seconds );}, countDown);
var t = setInterval(function(){
runClock(function(){
console.log('done');
clearInterval(t);
},function(timeElapsed, timeRemaining){
console.log( timeElapsed.seconds );
}, countDown);
}, 100);
Simply unregister the default StringHttpMessageConverter
instance:
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
/**
* Unregister the default {@link StringHttpMessageConverter} as we want Strings
* to be handled by the JSON converter.
*
* @param converters List of already configured converters
* @see WebMvcConfigurationSupport#addDefaultHttpMessageConverters(List)
*/
@Override
protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.stream()
.filter(c -> c instanceof StringHttpMessageConverter)
.findFirst().ifPresent(converters::remove);
}
}
Tested with both controller action handler methods and controller exception handlers:
@RequestMapping("/foo")
public String produceFoo() {
return "foo";
}
@ExceptionHandler(FooApiException.class)
public String fooException(HttpServletRequest request, Throwable e) {
return e.getMessage();
}
Final notes:
extendMessageConverters
is available since Spring 4.1.3, if are running on a previous version you can implement the same technique using configureMessageConverters
, it just takes a little bit more work.For rails 3.2.3 and latest version of rails you can start server by:
First install all gem with command: bundle install
or bundle
.
Then Configure your database to the database.yml
.
Create new database: rake db:create
Then start rails server.
rails server
orrails s
You could try the fnmatch module, it's got a shell-like wildcard syntax
or can use regular expressions
import re
I was not even concentrating, here is how to do it
$DOCDIR = [Environment]::GetFolderPath("MyDocuments")
$TARGETDIR = '$DOCDIR\MatchedLog'
if(!(Test-Path -Path $TARGETDIR )){
New-Item -ItemType directory -Path $TARGETDIR
}
Adding some information here, as it took me awhile to find the hadoop jobtracker web-dashboard in HDInsight (Azure's Hadoop), and a colleague finally showed me where it was. There is a shortcut on the head node called "Hadoop Yarn Status" which is just a link to a local http page (http://headnodehost:9014/cluster in my case). When opened the dashboard looked like this:
In that dashboard you can find your failed application, and then after clicking into it you can look at the logs of the individual map and reduce jobs.
In my case it seemed to still be running out of memory in the reducers, even though I had cranked the memory in the configuration already. For some reason it was not surfacing the "java outofmemory" errors I got earlier though.
Its not the best way to do it but it works:
$ git stash apply
$ >> resolve your conflict <<
$ >> do what you want to do with your code <<
$ git checkout HEAD -- file/path/to/your/file
Not an answer Or Why 'tricky' is bad:
>> a = Array(1)
>> a = Split(Join(a, "||") & "||2", "||")
>> WScript.Echo a(0) + a(1)
>>
12
Use the Bootstrap 4 h-100
class for height:100%;
<div class="container-fluid h-100">
<div class="row justify-content-center h-100">
<div class="col-4 hidden-md-down" id="yellow">
XXXX
</div>
<div class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8">
Form Goes Here
</div>
</div>
</div>
https://www.codeply.com/go/zxd6oN1yWp
You'll also need ensure any parent(s) are also 100% height (or have a defined height)...
html,body {
height: 100%;
}
Note: 100% height is not the same as "remaining" height.
Related: Bootstrap 4: How to make the row stretch remaining height?
you can also use iloc:
df.iloc[[1,3],:]
This will not work if the indexes in your dataframe do not correspond to the order of the rows due to prior computations. In that case use:
df.index.isin([1,3])
... as suggested in other responses.
If you have the char array null terminated, you can assign the char array to the string:
char[] chArray = "some characters";
String String(chArray);
As for your loop code, it looks right, but I will try on my controller to see if I get the same problem.
I have resolved this issue in react by using it like this.
window.$('#modal-id').modal();
I run foreach loop with error element, look like
foreach($_FILES['userfile']['error'] as $k=>$v)
{
$uploadfile = 'uploads/'. basename($_FILES['userfile']['name'][$k]);
if (move_uploaded_file($_FILES['userfile']['tmp_name'][$k], $uploadfile))
{
echo "File : ", $_FILES['userfile']['name'][$k] ," is valid, and was successfully uploaded.\n";
}
else
{
echo "Possible file : ", $_FILES['userfile']['name'][$k], " upload attack!\n";
}
}
It seems that the deletion command was not officially documented in Kafka 0.8.1.x because of a known bug (https://issues.apache.org/jira/browse/KAFKA-1397).
Nevertheless, the command was still shipped in the code and can be executed as:
bin/kafka-run-class.sh kafka.admin.DeleteTopicCommand --zookeeper localhost:2181 --topic test
In the meantime, the bug got fixed and the deletion command is now officially available from Kafka 0.8.2.0 as:
bin/kafka-topics.sh --delete --zookeeper localhost:2181 --topic test
In case anyone is using custom DataSource
@Bean(name = "managementDataSource")
@ConfigurationProperties(prefix = "management.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
Properties should look like the following. Notice the @ConfigurationProperties with prefix. The prefix is everything before the actual property name
management.datasource.test-on-borrow=true
management.datasource.validation-query=SELECT 1
A reference for Spring Version 1.4.4.RELEASE
In your .xml file within Button add this line--
android:textAllCaps="false"
Here are 3 examples:
$(document).on('click', 'ul li a', function (e) {_x000D_
e.preventDefault();_x000D_
_x000D_
var example1 = $(this).parents('ul:first').attr('id');_x000D_
$('#results').append('<p>Result from example 1: <strong>' + example1 + '</strong></p>');_x000D_
_x000D_
var example2 = $(this).parents('ul:eq(0)').attr('id');_x000D_
$('#results').append('<p>Result from example 2: <strong>' + example2 + '</strong></p>');_x000D_
_x000D_
var example3 = $(this).closest('ul').attr('id');_x000D_
$('#results').append('<p>Result from example 3: <strong>' + example3 + '</strong></p>');_x000D_
_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<ul id ="myList">_x000D_
<li><a href="www.example.com">Click here</a></li>_x000D_
</ul>_x000D_
_x000D_
<div id="results">_x000D_
<h1>Results:</h1>_x000D_
</div>
_x000D_
Let me know whether it was helpful.
If the sites are on separate domains, the calling page can't access the height of the iframe due to cross-browser domain restrictions. If you have access to both sites, you may be able to use the [document domain hack].1 Then anroesti's links should help.
like this:
import operator
list1 = sorted(csv1, key=operator.itemgetter(1, 2))
You need to use the DataGridViewColumn.AutoSizeMode
property.
You can use one of these values for column 0 and 1:
AllCells: The column width adjusts to fit the contents of all cells in the column, including the header cell.
AllCellsExceptHeader: The column width adjusts to fit the contents of all cells in the column, excluding the header cell.
DisplayedCells: The column width adjusts to fit the contents of all cells in the column that are in rows currently displayed onscreen, including the header cell.
DisplayedCellsExceptHeader: The column width adjusts to fit the contents of all cells in the column that are in rows currently displayed onscreen, excluding the header cell.
Then you use the Fill value for column 2
The column width adjusts so that the widths of all columns exactly fills the display area of the control...
this.DataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
this.DataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
this.DataGridView1.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
As pointed out by other users, the default value can be set at datagridview
level with DataGridView.AutoSizeColumnsMode
property.
this.DataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
this.DataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
could be:
this.DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
Important note:
If your grid is bound to a datasource and columns are auto-generated (AutoGenerateColumns
property set to True), you need to use the DataBindingComplete
event to apply style AFTER columns have been created.
In some scenarios (change cells value by code for example), I had to call DataGridView1.AutoResizeColumns();
to refresh the grid.
You can easily re-export the default import:
export {default as Comp1} from './Comp1.jsx';
export {default as Comp2} from './Comp2.jsx';
export {default as Comp3} from './Comp3.jsx';
There also is a proposal for ES7 ES8 that will let you write export Comp1 from '…';
.
You should use only one mediaplayer object
public class PlayaudioActivity extends Activity {
private MediaPlayer mp;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.button1);
Button b2 = (Button) findViewById(R.id.button2);
final TextView t = (TextView) findViewById(R.id.textView1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.far);
mp.start();
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.beet);
mp.start();
}
});
}
private void stopPlaying() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}
Follow these steps to create CSR (Code Signing Identity):
On your Mac, go to the folder 'Applications' ? 'Utilities' and open 'Keychain Access.'
Go to 'Keychain Access' ? Certificate Assistant ? Request a Certificate from a Certificate Authority. ?
Fill out the information in the Certificate Information window as specified below and click "Continue."
• In the User Email Address field, enter the email address to identify with this certificate
• In the Common Name field, enter your name
• In the Request group, click the "Saved to disk" option
?
Save the file to your hard drive.
Use this CSR (.certSigningRequest) file to create project/application certificates and profiles, in Apple developer account.
It works for me.
public class Program
{
public static void main(String[] args) {
String str = "This is a string.\nThis is a long string.";
str = str.replaceAll("(\r\n|\n)", "<br />");
System.out.println(str);
}
}
Result:
This is a string.<br />This is a long string.
Your problem is somewhere else.
The mysql docs have a whole page dedicated to this error: http://dev.mysql.com/doc/refman/5.0/en/gone-away.html
of note are
You can also get these errors if you send a query to the server that is incorrect or too large. If mysqld receives a packet that is too large or out of order, it assumes that something has gone wrong with the client and closes the connection. If you need big queries (for example, if you are working with big BLOB columns), you can increase the query limit by setting the server's max_allowed_packet variable, which has a default value of 1MB. You may also need to increase the maximum packet size on the client end. More information on setting the packet size is given in Section B.5.2.10, “Packet too large”.
You can get more information about the lost connections by starting mysqld with the --log-warnings=2 option. This logs some of the disconnected errors in the hostname.err file
<Context docBase="yourAppName" path="" reloadable="true">
go to Tomcat server.xml file and set path blank
set ROOT=c:\programs
set SRC_ROOT=%ROOT%\System\Source
I found the solution of this problem and i should work i'm sure about this because i also face the same problem
here is my solution----->
var request = require('request');
//set url
var url = 'http://localhost:8088/example';
//set header
var headers = {
'Authorization': 'Your authorization'
};
//set form data
var form = {first_name: first_name, last_name: last_name};
//set request parameter
request.post({headers: headers, url: url, form: form, method: 'POST'}, function (e, r, body) {
var bodyValues = JSON.parse(body);
res.send(bodyValues);
});
In my case, I forgot to tell the type controller that the response is a JSON object. response.setContentType("application/json");
After some time with Google I asked on the ask ubuntu chat room.
A user there was king enough to help me find the solution I was looking for and i wanted to share so that any following suers running into this may find it:
grep -P "(^|\s)abc(\s|$)"
gives the result I was looking for. -P is an experimental implementation of perl regexps.
grepping for abc
and then using filters like grep -v '@abc'
(this is far from perfect...) should also work, but my patch does something similar.
There's also:
getent $HOSTNAME
or possibly:
getent `uname -n`
On Solaris 11 the ifconfig command is considered legacy and is being replaced by ipadm
ipadm show-addr
will show the IP addresses on the system for Solaris 11 and later.
A pure RESTful API should use the underlying protocol standard features:
For HTTP, the RESTful API should comply with existing HTTP standard headers. Adding a new HTTP header violates the REST principles. Do not re-invent the wheel, use all the standard features in HTTP/1.1 standards - including status response codes, headers, and so on. RESTFul web services should leverage and rely upon the HTTP standards.
RESTful services MUST be STATELESS. Any tricks, such as token based authentication that attempts to remember the state of previous REST requests on the server violates the REST principles. Again, this is a MUST; that is, if you web server saves any request/response context related information on the server in attempt to establish any sort of session on the server, then your web service is NOT Stateless. And if it is NOT stateless it is NOT RESTFul.
Bottom-line: For authentication/authorization purposes you should use HTTP standard authorization header. That is, you should add the HTTP authorization / authentication header in each subsequent request that needs to be authenticated. The REST API should follow the HTTP Authentication Scheme standards.The specifics of how this header should be formatted are defined in the RFC 2616 HTTP 1.1 standards – section 14.8 Authorization of RFC 2616, and in the RFC 2617 HTTP Authentication: Basic and Digest Access Authentication.
I have developed a RESTful service for the Cisco Prime Performance Manager application. Search Google for the REST API document that I wrote for that application for more details about RESTFul API compliance here. In that implementation, I have chosen to use HTTP "Basic" Authorization scheme. - check out version 1.5 or above of that REST API document, and search for authorization in the document.
A simple solution would be to iterate through the Controls
list in a foreach
loop. Something like this:
foreach (Control child in Controls)
{
// Code that executes for each control.
}
So now you have your iterator, child
, which is of type Control
. Now do what you will with that, personally I found this in a project I did a while ago in which it added an event for this control, like this:
child.MouseDown += new MouseEventHandler(dragDown);
I can understand your pain. In my case the error got resolved by performing below steps:
Hope this helps.
Another approach besides using if
or guard
statements to do the optional binding is to extend Optional
with:
extension Optional {
func ifValue(_ valueHandler: (Wrapped) -> Void) {
switch self {
case .some(let wrapped): valueHandler(wrapped)
default: break
}
}
}
ifValue
receives a closure and calls it with the value as an argument when the optional is not nil. It is used this way:
var helloString: String? = "Hello, World!"
helloString.ifValue {
print($0) // prints "Hello, World!"
}
helloString = nil
helloString.ifValue {
print($0) // This code never runs
}
You should probably use an if
or guard
however as those are the most conventional (thus familiar) approaches used by Swift programmers.
Add:
DELIMITER
at the beginning and end of the SP.validar_egreso
; at the beginning@variableName
.This works for me. (I modified some part of your script so ANYONE can run it with out having your tables).
DROP PROCEDURE IF EXISTS `validar_egreso`;
DELIMITER $$
CREATE DEFINER='root'@'localhost' PROCEDURE `validar_egreso` (
IN codigo_producto VARCHAR(100),
IN cantidad INT,
OUT valido INT(11)
)
BEGIN
DECLARE resta INT;
SET resta = 0;
SELECT (codigo_producto - cantidad) INTO resta;
IF(resta > 1) THEN
SET valido = 1;
ELSE
SET valido = -1;
END IF;
SELECT valido;
END $$
DELIMITER ;
-- execute the stored procedure
CALL validar_egreso(4, 1, @val);
-- display the result
select @val;
You might want to check HTML frames, which can do pretty much exactly what you are looking for. They are considered outdated however.
Joke? :)
How about echo "12|23|11" | awk '{split($0,a,"|"); print a[3] a[2] a[1]}'
This is my output:
p2> echo "12|23|11" | awk '{split($0,a,"|"); print a[3] a[2] a[1]}'
112312
so I guess it's working after all..
The group_concat supports its own order by clause
http://mahmudahsan.wordpress.com/2008/08/27/mysql-the-group_concat-function/
So you should be able to write:
SELECT li.clientid, group_concat(li.views order by views) AS views,
group_concat(li.percentage order by percentage)
FROM table_views GROUP BY client_id
The secrets
module is new in Python 3.6. This is better than the random
module for cryptography or security uses.
To randomly print an integer in the inclusive range 0-9:
from secrets import randbelow
print(randbelow(10))
For details, see PEP 506.
If you use JSON.NET with old version which didn't JObject.
This is another simple way to make a dynamic object from JSON: https://github.com/chsword/jdynamic
NuGet Install
PM> Install-Package JDynamic
Support using string index to access member like:
dynamic json = new JDynamic("{a:{a:1}}");
Assert.AreEqual(1, json["a"]["a"]);
Test Case
And you can use this util as following :
Get the value directly
dynamic json = new JDynamic("1");
//json.Value
2.Get the member in the json object
dynamic json = new JDynamic("{a:'abc'}");
//json.a is a string "abc"
dynamic json = new JDynamic("{a:3.1416}");
//json.a is 3.1416m
dynamic json = new JDynamic("{a:1}");
//json.a is integer: 1
3.IEnumerable
dynamic json = new JDynamic("[1,2,3]");
/json.Length/json.Count is 3
//And you can use json[0]/ json[2] to get the elements
dynamic json = new JDynamic("{a:[1,2,3]}");
//json.a.Length /json.a.Count is 3.
//And you can use json.a[0]/ json.a[2] to get the elements
dynamic json = new JDynamic("[{b:1},{c:1}]");
//json.Length/json.Count is 2.
//And you can use the json[0].b/json[1].c to get the num.
Other
dynamic json = new JDynamic("{a:{a:1} }");
//json.a.a is 1.
For the Spring Tool Suit (Extension of Eclipse), in Windows is
Alt + Shift + Q, C
update mytable set title=trim(replace(REPLACE(title,CHAR(13),''),CHAR(10),''));
Above is working for fine.
With C++11 the iteration syntax is simple. You still iterate over pairs, but accessing just the key is easy.
#include <iostream>
#include <map>
int main()
{
std::map<std::string, int> myMap;
myMap["one"] = 1;
myMap["two"] = 2;
myMap["three"] = 3;
for ( const auto &myPair : myMap ) {
std::cout << myPair.first << "\n";
}
}
ALTER TABLE MyTable MODIFY Col3 varchar(20) NULL;
Example simple (worked):
var a=Number.parseFloat($("#budget_project").val()); // from input field
var b=Number.parseFloat(html); // from ajax
var c=a-b;
$("#result").html(c.toFixed(2)); // put to id='result' (div or others)
Try this one
.parent_div{
display: flex;
}
I've did a "Update-Package –reinstall Microsoft.AspNet.Mvc" to fix it in Visual Studio 2015.
I disagree with the accepted answer here by Óscar López. That answer is inaccurate!
It is NOT @JoinColumn
which indicates that this entity is the owner of the relationship. Instead, it is the @ManyToOne
annotation which does this (in his example).
The relationship annotations such as @ManyToOne
, @OneToMany
and @ManyToMany
tell JPA/Hibernate to create a mapping. By default, this is done through a seperate Join Table.
@JoinColumn
The purpose of
@JoinColumn
is to create a join column if one does not already exist. If it does, then this annotation can be used to name the join column.
MappedBy
The purpose of the
MappedBy
parameter is to instruct JPA: Do NOT create another join table as the relationship is already being mapped by the opposite entity of this relationship.
Remember: MappedBy
is a property of the relationship annotations whose purpose is to generate a mechanism to relate two entities which by default they do by creating a join table. MappedBy
halts that process in one direction.
The entity not using MappedBy
is said to be the owner of the relationship because the mechanics of the mapping are dictated within its class through the use of one of the three mapping annotations against the foreign key field. This not only specifies the nature of the mapping but also instructs the creation of a join table. Furthermore, the option to suppress the join table also exists by applying @JoinColumn annotation over the foreign key which keeps it inside the table of the owner entity instead.
So in summary: @JoinColumn
either creates a new join column or renames an existing one; whilst the MappedBy
parameter works collaboratively with the relationship annotations of the other (child) class in order to create a mapping either through a join table or by creating a foreign key column in the associated table of the owner entity.
To illustrate how MapppedBy
works, consider the code below. If MappedBy
parameter were to be deleted, then Hibernate would actually create TWO join tables! Why? Because there is a symmetry in many-to-many relationships and Hibernate has no rationale for selecting one direction over the other.
We therefore use MappedBy
to tell Hibernate, we have chosen the other entity to dictate the mapping of the relationship between the two entities.
@Entity
public class Driver {
@ManyToMany(mappedBy = "drivers")
private List<Cars> cars;
}
@Entity
public class Cars {
@ManyToMany
private List<Drivers> drivers;
}
Adding @JoinColumn(name = "driverID") in the owner class (see below), will prevent the creation of a join table and instead, create a driverID foreign key column in the Cars table to construct a mapping:
@Entity
public class Driver {
@ManyToMany(mappedBy = "drivers")
private List<Cars> cars;
}
@Entity
public class Cars {
@ManyToMany
@JoinColumn(name = "driverID")
private List<Drivers> drivers;
}
I found this worked for me.
$username = 'user'
$password = 'password'
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword
Start-Process Notepad.exe -Credential $credential
Updated: changed to using single quotes to avoid special character issues noted by Paddy.
Ok to generalize the technique of how many bits you need to represent a number is done this way. You have R symbols for a representation and you want to know how many bits, solve this equation R=2^n or log2(R)=n. Where n is the numbers of bits and R is the number of symbols for the representation.
For the decimal number system R=9 so we solve 9=2^n, the answer is 3.17 bits per decimal digit. Thus a 3 digit number will need 9.51 bits or 10. A 1000 digit number needs 3170 bits
how about using limit 0,1
for mysql optimisation
and about your code:
$DBH = new PDO( "connection string goes here" );
$STH - $DBH -> prepare( "select figure from table1" );
$STH -> execute();
$result = $STH ->fetch(PDO::FETCH_ASSOC)
echo $result["figure"];
$DBH = null;
sometimes whenever you copy cURL, it contains --compressed. Remove it while import->Paste Raw Text-->click on import. It will also solve the problem if you are getting the syntax error in postman while importing any cURL.
Generally, when people copy cURL from any proxy tools like Charles, it happens.
try
java -cp "your_jar.jar:lib/referenced_jar.jar" com.your.main.Main
If you are on windows, you should use ;
instead of :
None
is a singleton, therefore identity comparison will always work, whereas an object can fake the equality comparison via .__eq__()
.
You can use the && symbol between commands to execute the second command only if the first succeeds. More info here http://commandwindows.com/command1.htm
Also check if your xampp is installed in the main directory like C or D or E and not in or within a folder of that directory? i.e. ( "D:/Xampp" or is it "D:/something/Xampp") if its not in the main path of the directory, it will show this error.
copy your xampp directory from "D:\Something\Xampp" to "D:"
So it becomes like this "D:\Xampp"
and the issue will be resolved.
The instance in which you're using a single character (i.e. | or &) is a bitwise comparison of the results. As long as your language evaluates these expressions to a binary value they should return the same results. As a best practice, however, you should use the logical operator as that's what you mean (I think).
Select * from people p, address a where p.id = a.person_id and a.zip='97229';
Or you must TRY using JOIN
which is a more efficient and better way to do this as Gordon Linoff in the comments below also says that you need to learn this.
SELECT p.*, a.street, a.city FROM persons AS p
JOIN address AS a ON p.id = a.person_id
WHERE a.zip = '97299';
Here p.*
means it will show all the columns of PERSONS table.
I just had to do this to get this to work on windows 7 64.
Open up a command prompt (cmd.exe) and type:
set CLASSPATH=C:\Program Files\Java\jdk1.7.0_01\bin
Make sure you reopen all running command prompt Windows to get the environment variable updated as well.
This builds on the answer by CMS by removing any non-alphabetic characters including underscores, which \w
does not remove.
function toLowerCamelCase(str) {
return str.replace(/[^A-Za-z0-9]/g, ' ').replace(/^\w|[A-Z]|\b\w|\s+/g, function (match, index) {
if (+match === 0 || match === '-' || match === '.' ) {
return ""; // or if (/\s+/.test(match)) for white spaces
}
return index === 0 ? match.toLowerCase() : match.toUpperCase();
});
}
toLowerCamelCase("EquipmentClass name");
toLowerCamelCase("Equipment className");
toLowerCamelCase("equipment class name");
toLowerCamelCase("Equipment Class Name");
toLowerCamelCase("Equipment-Class-Name");
toLowerCamelCase("Equipment_Class_Name");
toLowerCamelCase("Equipment.Class.Name");
toLowerCamelCase("Equipment/Class/Name");
// All output e
Adding the right repository in Project build.gradle solved the issue. In my case Google Maven Repository was needed and was added as below in the build.gradle
repositories {
google()
}
refer to this link for declaring repositories: https://docs.gradle.org/current/userguide/declaring_repositories.html
I encountered with same error and resolved it with redeployment after removing deployment.
Try using @Html.DropDownList
instead:
<td>Account: </td>
<td>@Html.DropDownList("accountid", new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))</td>
@Html.DropDownListFor
expects a lambda as its first argument, not a string
for the ID as you specify.
Other than that, without knowing what getUserAccounts()
consists of, suffice to say it needs to return some sort of collection (IEnumerable
for example) that has at least 1 object in it. If it returns null
the property in the ViewBag won't have anything.
I had the same problem, but its an easy fix! Just set
status bar is initially hidden = YES
then add an row by clicking on the plus right after the text status bar is initially hidden
, then set the text to
view controller-based status bar appearance
by clicking the arrows, and set it to NO
Hope this helps!
const string message = "Hello" + ",world" + exclam;
The +
operator has left-to-right associativity, so the equivalent parenthesized expression is:
const string message = (("Hello" + ",world") + exclam);
As you can see, the two string literals "Hello"
and ",world"
are "added" first, hence the error.
One of the first two strings being concatenated must be a std::string
object:
const string message = string("Hello") + ",world" + exclam;
Alternatively, you can force the second +
to be evaluated first by parenthesizing that part of the expression:
const string message = "Hello" + (",world" + exclam);
It makes sense that your first example (hello + ",world" + "!"
) works because the std::string
(hello
) is one of the arguments to the leftmost +
. That +
is evaluated, the result is a std::string
object with the concatenated string, and that resulting std::string
is then concatenated with the "!"
.
As for why you can't concatenate two string literals using +
, it is because a string literal is just an array of characters (a const char [N]
where N
is the length of the string plus one, for the null terminator). When you use an array in most contexts, it is converted into a pointer to its initial element.
So, when you try to do "Hello" + ",world"
, what you're really trying to do is add two const char*
s together, which isn't possible (what would it mean to add two pointers together?) and if it was it wouldn't do what you wanted it to do.
Note that you can concatenate string literals by placing them next to each other; for example, the following two are equivalent:
"Hello" ",world"
"Hello,world"
This is useful if you have a long string literal that you want to break up onto multiple lines. They have to be string literals, though: this won't work with const char*
pointers or const char[N]
arrays.
You can use the jquery .length property
var numItems = $('.item').length;
For those who want some background info, here's a short article explaining why overflow: hidden
works. It has to do with the so-called block formatting context. This is part of W3C's spec (ie is not a hack) and is basically the region occupied by an element with a block-type flow.
Every time it is applied, overflow: hidden
creates a new block formatting context. But it's not the only property capable of triggering that behaviour. Quoting a presentation by Fiona Chan from Sydney Web Apps Group:
- float: left / right
- overflow: hidden / auto / scroll
- display: table-cell and any table-related values / inline-block
- position: absolute / fixed
I used to check $_POST
until I got into a trouble with larger POST data and uploaded files. There are configuration directives post_max_size
and upload_max_filesize
- if any of them is exceeded, $_POST
array is not populated.
So the "safe way" is to check $_SERVER['REQUEST_METHOD']
. You still have to use isset()
on every $_POST
variable though, and it does not matter, whether you check or don't check $_SERVER['REQUEST_METHOD']
.
EDIT: Please see the answer from PascalPrecht (the author of angular-translate) for a better solution.
The asynchronous nature of the loading causes the problem. You see, with {{ pageTitle | translate }}
, Angular will watch the expression; when the localization data is loaded, the value of the expression changes and the screen is updated.
So, you can do that yourself:
.controller('FirstPageCtrl', ['$scope', '$filter', function ($scope, $filter) {
$scope.$watch(
function() { return $filter('translate')('HELLO_WORLD'); },
function(newval) { $scope.pageTitle = newval; }
);
});
However, this will run the watched expression on every digest cycle. This is suboptimal and may or may not cause a visible performance degradation. Anyway it is what Angular does, so it cant be that bad...
You can define an interface as array with simply extending the Array interface.
export interface MyInterface extends Array<MyType> { }
With this, any object which implements the MyInterface
will need to implement all function calls of arrays and only will be able to store objects with the MyType
type.
LENGTH()
returns the length of the string measured in bytes.
CHAR_LENGTH()
returns the length of the string measured in characters.
This is especially relevant for Unicode, in which most characters are encoded in two bytes. Or UTF-8, where the number of bytes varies. For example:
select length(_utf8 '€'), char_length(_utf8 '€')
--> 3, 1
As you can see the Euro sign occupies 3 bytes (it's encoded as 0xE282AC
in UTF-8) even though it's only one character.
If the error happens to be because your data has NAs, then you need to set the glm() function options of how you would like to treat the NA cases. More information on this is found in a relevant post here: https://stats.stackexchange.com/questions/46692/how-the-na-values-are-treated-in-glm-in-r
.shadow {
-moz-box-shadow: 3px 3px 5px 6px #ccc;
-webkit-box-shadow: 3px 3px 5px 6px #ccc;
box-shadow: 3px 3px 5px 6px #ccc;
}
Is your MySQL server version 5.5.3 or greater?
The utf8mb4, utf16, and utf32 character sets were added in MySQL 5.5.3.
http://dev.mysql.com/doc/refman/5.5/en/charset-unicode-sets.html
this.setState({ [`${event.target.id}`]: event.target.value}, () => {
console.log("State updated: ", JSON.stringify(this.state[event.target.id]));
});
Please mind the quote character.
SELECT
[oj].[name] [TableName],
[ac].[name] [ColumnName],
[dc].[name] [DefaultConstraintName],
[dc].[definition]
FROM
sys.default_constraints [dc],
sys.all_objects [oj],
sys.all_columns [ac]
WHERE
(
([oj].[type] IN ('u')) AND
([oj].[object_id] = [dc].[parent_object_id]) AND
([oj].[object_id] = [ac].[object_id]) AND
([dc].[parent_column_id] = [ac].[column_id])
)
you can move to another fragment by using the FragmentManager transactions. Fragment can not be called like activities,. Fragments exists on the existance of activities.
You can call another fragment by writing the code below:
FragmentTransaction t = this.getFragmentManager().beginTransaction();
Fragment mFrag = new MyFragment();
t.replace(R.id.content_frame, mFrag);
t.commit();
here "R.id.content_frame" is the id of the layout on which you want to replace the fragment.
you can also add the other fragment incase of replace.
Just using this code: If you want backpressed disable, you dont use super.OnBackPressed();
@Override
public void onBackPressed() {
}
GNU find
find /path -type f -name "*.py" -exec md5sum "{}" +;
Passing the :value
option to f.label
will ensure the label tag's for
attribute is the same as the id of the corresponding radio_button
<% form_for(@message) do |f| %>
<%= f.radio_button :contactmethod, 'email' %>
<%= f.label :contactmethod, 'Email', :value => 'email' %>
<%= f.radio_button :contactmethod, 'sms' %>
<%= f.label :contactmethod, 'SMS', :value => 'sms' %>
<% end %>
See ActionView::Helpers::FormHelper#label
the :value option, which is designed to target labels for radio_button tags
Input. We will start with the text of the input shown in the question since the question did not provide the csv input:
Lines <- "Dates Bajaj_close Hero_close
3/14/2013 1854.8 1669.1
3/15/2013 1850.3 1684.45
3/18/2013 1812.1 1690.5
3/19/2013 1835.9 1645.6
3/20/2013 1840 1651.15
3/21/2013 1755.3 1623.3
3/22/2013 1820.65 1659.6
3/25/2013 1802.5 1617.7
3/26/2013 1801.25 1571.85
3/28/2013 1799.55 1542"
zoo. "ts"
class series normally do not represent date indexes but we can create a zoo series that does (see zoo package):
library(zoo)
z <- read.zoo(text = Lines, header = TRUE, format = "%m/%d/%Y")
Alternately, if you have already read this into a data frame DF
then it could be converted to zoo as shown on the second line below:
DF <- read.table(text = Lines, header = TRUE)
z <- read.zoo(DF, format = "%m/%d/%Y")
In either case above z
ia a zoo series with a "Date"
class time index. One could also create the zoo series, zz
, which uses 1, 2, 3, ... as the time index:
zz <- z
time(zz) <- seq_along(time(zz))
ts. Either of these could be converted to a "ts"
class series:
as.ts(z)
as.ts(zz)
The first has a time index which is the number of days since the Epoch (January 1, 1970) and will have NAs for missing days and the second will have 1, 2, 3, ... as the time index and no NAs.
Monthly series. Typically "ts"
series are used for monthly, quarterly or yearly series. Thus if we were to aggregate the input into months we could reasonably represent it as a "ts"
series:
z.m <- as.zooreg(aggregate(z, as.yearmon, mean), freq = 12)
as.ts(z.m)
The $http
legacy promise methods success
and error
have been deprecated. Use the standard then
method instead. Have a look at the docs https://docs.angularjs.org/api/ng/service/$http
Now the right way to use is:
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
The response object has these properties:
A response status code between 200 and 299 is considered a success status and will result in the success callback being called.
Demo :
<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
Based on your question:
<connectionStrings>
<add name="itmall" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True" />
</connectionStrings>
Refer links:
http://www.connectionstrings.com/store-connection-string-in-webconfig/
Retrive connection string from web.config file:
write the below code in your file where you want;
string connstring=ConfigurationManager.ConnectionStrings["itmall"].ConnectionString;
SqlConnection con = new SqlConnection(connstring);
or you can go in your way like
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["itmall"].ConnectionString);
Note:
The "name" which you gave in web.config file and name which you used in connection string must be same(like "itmall" in this solution.)
Be aware that if your string number contains more than 15 significant digits float(s)
will round it.In those cases it is better to use Decimal
Here is an explanation and some code samples: https://docs.python.org/3/library/sys.html#sys.float_info
It is not only the table cell which is growing, the table itself can grow, too. To avoid this you can assign a fixed width to the table which in return forces the cell width to be respected:
table {
table-layout: fixed;
width: 120px; /* Important */
}
td {
width: 30px;
}
(Using overflow: hidden
and/or text-overflow: ellipsis
is optional but highly recommended for a better visual experience)
So if your situation allows you to assign a fixed width to your table, this solution might be a better alternative to the other given answers (which do work with or without a fixed width)
A simple solution is to install jshon
library :
jshon -l < /tmp/test.json
2
String
vs string
Argument of type 'String' is not assignable to parameter of type 'string'.
'string' is a primitive, but 'String' is a wrapper object.
Prefer using 'string' when possible.
String Object
// error
class SVGStorageUtils {
store: object;
constructor(store: object) {
this.store = store;
}
setData(key: String = ``, data: object) {
sessionStorage.setItem(key, JSON.stringify(data));
}
getData(key: String = ``) {
const obj = JSON.parse(sessionStorage.getItem(key));
}
}
string primitive
// ok
class SVGStorageUtils {
store: object;
constructor(store: object) {
this.store = store;
}
setData(key: string = ``, data: object) {
sessionStorage.setItem(key, JSON.stringify(data));
}
getData(key: string = ``) {
const obj = JSON.parse(sessionStorage.getItem(key));
}
}
This worked for me
if( cb && typeof( eval( cb ) ) === "function" ){
eval( cb + "()" );
}
It does work in Firefox (including 2.0.0.20
). See http://jsbin.com/akili (add /edit
to the url to edit):
<p id="one">One</p>
<a href="#" onclick="document.getElementById('one').id = 'two'; return false">Link2</a>
The first click changes the id
to "two"
, the second click errors because the element with id="one"
now can't be found!
Perhaps you have another element already with id="two"
(FYI you can't have more than one element with the same id
).
Your tables should have as immediate children just tbody
and thead
elements, with the rows within*. So, amend the HTML to be:
<table border="1" width="100%" id="test">
<tbody>
<tr>
<td>
<table border="1" width="100%">
<tbody>
<tr>
<td>table 2</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
</tbody>
</table>
Then amend your selector slightly to this:
#test > tbody > tr:last-child { background:#ff0000; }
See it in action here. That makes use of the child selector, which:
...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.
So, you are targeting only direct children of tbody
elements that are themselves direct children of your #test
table.
The above is the neatest solution, as you don't need to over-ride any styles. The alternative would be to stick with your current set-up, and over-ride the background style for the inner table, like this:
#test tr:last-child { background:#ff0000; }
#test table tr:last-child { background:transparent; }
* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:
...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.
try this one
<dependency>
<groupId>com.hynnet</groupId>
<artifactId>oracle-driver-ojdbc6</artifactId>
<version>12.1.0.1</version>
</dependency>
$total_ratings
is an array.
This question has been already answered in Unicode characters in Windows command line - how?
You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.
Answer if you only want to use for each loop ..
for (WebElement s : options) {
int i = options.indexOf(s);
System.out.println(options.get(i).getText());
}
EDIT: In summary, back in 2010 when this question was asked the most common way to solve this problem was to save a reference to the context where the setTimeout
function call is made, because setTimeout
executes the function with this
pointing to the global object:
var that = this;
if (this.options.destroyOnHide) {
setTimeout(function(){ that.tip.destroy() }, 1000);
}
In the ES5 spec, just released a year before that time, it introduced the bind
method, this wasn't suggested in the original answer because it wasn't yet widely supported and you needed polyfills to use it but now it's everywhere:
if (this.options.destroyOnHide) {
setTimeout(function(){ this.tip.destroy() }.bind(this), 1000);
}
The bind
function creates a new function with the this
value pre-filled.
Now in modern JS, this is exactly the problem arrow functions solve in ES6:
if (this.options.destroyOnHide) {
setTimeout(() => { this.tip.destroy() }, 1000);
}
Arrow functions do not have a this
value of its own, when you access it, you are accessing the this
value of the enclosing lexical scope.
HTML5 also standardized timers back in 2011, and you can pass now arguments to the callback function:
if (this.options.destroyOnHide) {
setTimeout(function(that){ that.tip.destroy() }, 1000, this);
}
See also:
Use a packet sniffer like Wireshark to look at what happens. You need to see a SYN-flagged packet outgoing, a SYN+ACK-flagged incoming and then a ACK-flagged outgoing. After that, the port is considered open on the local side.
If you only see the first packet and the error message comes after several seconds of waiting, the other side is not answering at all (like in: unplugged cable, overloaded server, misguided packet was discarded) and your local network stack aborts the connection attempt. If you see RST packets, the host actually denies the connection. If you see "ICMP Port unreachable" or host unreachable packets, a firewall or the target host inform you of the port actually being closed.
Of course you cannot expect the service to be available at all times (consider all the points of failure in between you and the data), so you should try again later.
If you just need a simple fixed size:
class SizedCollectionView: UIICollectionView {
override func common() {
super.common()
let l = UICollectionViewFlowLayout()
l.itemSize = CGSize(width: 42, height: 42)
collectionViewLayout = l
}
}
That's all there is to it.
In storyboard, just change the class from UICollectionView to SizedCollectionView.
Notice the base class there is "UI 'I' CollectionView". 'I' for Initializer.
It's not that easy to add an initializer to a collection view. Here's a common approach:
import UIKit
class UIICollectionView: UICollectionView {
private var commoned: Bool = false
override func didMoveToWindow() {
super.didMoveToWindow()
if window != nil && !commoned {
commoned = true
common()
}
}
internal func common() {
}
}
In most projects, you need "a collection view with an initializer". So you will probably anyway have UIICollectionView
(note the extra I for Initializer!) in your project.
function arrayColumn(arr, n) {_x000D_
return arr.map(x=> x[n]);_x000D_
}_x000D_
_x000D_
var twoDimensionalArray = [_x000D_
[1, 2, 3],_x000D_
[4, 5, 6],_x000D_
[7, 8, 9]_x000D_
];_x000D_
_x000D_
console.log(arrayColumn(twoDimensionalArray, 1));
_x000D_
I use the IDE Phpstorm,but I think it maybe the same as AS.
1.You should reinstall the svn. And choose option modify.
And next step,you can see the command line client tools.
Let's choose first one: Will be installed on local hard drive.
2.Now restart you computer.
Go to the svn location,all the time it will be C:\Program Files\TortoiseSVN\bin.
If you see the svn.exe
in C:\Program Files\TortoiseSVN\bin,it proved that we reinstall command line client successfully.
Copy C:\Program Files\TortoiseSVN\bin\svn.exe
into the IDE.
3.Restart you IDE.It is ok!
I was getting this error after adding the include files and linking the library. It was because the lib was built with non-unicode and my application was unicode. Matching them fixed it.
If you like to avoid both changes()=0
and INSERT OR IGNORE
even if you cannot afford deleting the row - You can use this logic;
First, insert (if not exists) and then update by filtering with the unique key.
-- Table structure
CREATE TABLE players (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_name VARCHAR (255) NOT NULL
UNIQUE,
age INTEGER NOT NULL
);
-- Insert if NOT exists
INSERT INTO players (user_name, age)
SELECT 'johnny', 20
WHERE NOT EXISTS (SELECT 1 FROM players WHERE user_name='johnny' AND age=20);
-- Update (will affect row, only if found)
-- no point to update user_name to 'johnny' since it's unique, and we filter by it as well
UPDATE players
SET age=20
WHERE user_name='johnny';
Notice: I haven't tested it to see the which triggers are being called, but I assume the following:
in this way you can have a single SQL command
-- Table structure
CREATE TABLE players (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_name VARCHAR (255) NOT NULL
UNIQUE,
age INTEGER NOT NULL
);
-- Single command to insert or update
INSERT OR REPLACE INTO players
(id, user_name, age)
VALUES ((SELECT id from players WHERE user_name='johnny' AND age=20),
'johnny',
20);
Edit: added option 2.
4 GB minus what is in use by the system if you link with /LARGEADDRESSAWARE.
Of course, you should be even more careful with pointer arithmetic if you set that flag.
Unlike in Python 2, the zip
function in Python 3 returns an iterator. Iterators can only be exhausted (by something like making a list out of them) once. The purpose of this is to save memory by only generating the elements of the iterator as you need them, rather than putting it all into memory at once. If you want to reuse your zipped object, just create a list out of it as you do in your second example, and then duplicate the list by something like
test2 = list(zip(lis1,lis2))
zipped_list = test2[:]
zipped_list_2 = list(test2)
Using plain javascript
<html>
<head>
<!-- define on/off styles -->
<style type="text/css">
.on { background:blue; }
.off { background:red; }
</style>
<!-- define the toggle function -->
<script language="javascript">
function toggleState(item){
if(item.className == "on") {
item.className="off";
} else {
item.className="on";
}
}
</script>
</head>
<body>
<!-- call 'toggleState' whenever clicked -->
<input type="button" id="btn" value="button"
class="off" onclick="toggleState(this)" />
</body>
</html>
Using jQuery
If you use jQuery, you can do it using the toggle function, or using the toggleClass function inside click event handler, like this:
$(document).ready(function(){
$('a#myButton').click(function(){
$(this).toggleClass("btnClicked");
});
});
Using jQuery UI effects, you can animate transitions: http://jqueryui.com/demos/toggleClass/
For example :
In MainActivity :
Intent intent = new Intent(this, OtherActivity.class);
intent.putExtra(OtherActivity.KEY_EXTRA, yourDataObject);
startActivity(intent);
In OtherActivity :
public static final String KEY_EXTRA = "com.example.yourapp.KEY_BOOK";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String yourDataObject = null;
if (getIntent().hasExtra(KEY_EXTRA)) {
yourDataObject = getIntent().getStringExtra(KEY_EXTRA);
} else {
throw new IllegalArgumentException("Activity cannot find extras " + KEY_EXTRA);
}
// do stuff
}
More informations here : http://developer.android.com/reference/android/content/Intent.html
I've briefly covered a simple way to do this with Google Spreadsheets (importHTML
) and in Python (Pandas read_html
and to_csv
) as well as an example Python script in my SO answer here: https://stackoverflow.com/a/28083469/1588795.
I test the several propositions by running them into a large loop. I used microsoft visual studio 2015 as compiler and my processor is an i7, 8Hz, 2GHz.
long start = clock();
int a = 0;
//100000000
std::string ret;
for (int i = 0; i < 60000000; i++)
{
ret.append(1, ' ');
//ret += ' ';
//ret.push_back(' ');
//ret.insert(ret.end(), 1, ' ');
//ret.resize(ret.size() + 1, ' ');
}
long stop = clock();
long test = stop - start;
return 0;
According to this test, results are :
operation time(ms) note
------------------------------------------------------------------------
append 66015
+= 67328 1.02 time slower than 'append'
resize 83867 1.27 time slower than 'append'
push_back & insert 90000 more than 1.36 time slower than 'append'
Conclusion
+=
seems more understandable, but if you mind about speed, use append
Also, note that "the local IP" might not be a particularly unique thing. If you are on several physical networks (wired+wireless+bluetooth, for example, or a server with lots of Ethernet cards, etc.), or have TAP/TUN interfaces setup, your machine can easily have a whole host of interfaces.
This is an old question. But if you're using a virtualenv with python, place the contents of the downloaded libav bin
folder in the Scripts
folder of your virtualenv.
H.264 is a new standard for video compression which has more advanced compression methods than the basic MPEG-4 compression. One of the advantages of H.264 is the high compression rate. It is about 1.5 to 2 times more efficient than MPEG-4 encoding. This high compression rate makes it possible to record more information on the same hard disk.
The image quality is also better and playback is more fluent than with basic MPEG-4 compression. The most interesting feature however is the lower bit-rate required for network transmission.
So the 3 main advantages of H.264 over MPEG-4 compression are:
- Small file size for longer recording time and better network transmission.
- Fluent and better video quality for real time playback
- More efficient mobile surveillance applicationH264 is now enshrined in MPEG4 as part 10 also known as AVC
Refer to: http://www.velleman.eu/downloads/3/h264_vs_mpeg4_en.pdf
Hope this helps.
First time I have added a video link for solving your problem but I learned it was a bad idea. This time I'll explain it briefly.
Android studio is compatible with github but you need adjust something:
Setup the Github plugins in the Android Studio settings
Download the git version control system from this link and setup https://git-scm.com/
settings >> version control >> git
program files >> git >> bin >> git.exe
Settings >> Version control >> Github
you will see login and password for your Github account. Apply the settings.VCS >> enable version control integration >> git
VCS >> import into version control >> share project on Github
and enter your master password. Now you can use VCS update buttons for updating your project to Github
Convert an iterable to a list may have a cost. Instead, to get the the first item, you can use:
next(iter(keys))
Or, if you want to iterate over all items, you can use:
items = iter(keys)
while True:
try:
item = next(items)
except StopIteration as e:
pass # finish
Here's one view on the singleton methods:
I have found these various "singleton" methods to be useful for passing a single value to an API that requires a collection of that value. Of course, this works best when the code processing the passed-in value does not need to add to the collection.
Use the range
type. If the user enter a date:
select *
from table
where
update_date
<@
tsrange('2013-05-03', '2013-05-03'::date + 1, '[)');
If the user enters timestamps then you don't need the ::date + 1
part
http://www.postgresql.org/docs/9.2/static/rangetypes.html
http://www.postgresql.org/docs/9.2/static/functions-range.html
The best way I found, aside of using a dedicated commit GUI, is to use git difftool -d
- This opens your diff tool in directory comparison mode, comparing HEAD with current dirty folder.
public static void main(String s[])
{
BufferedImage image = null;
try
{
image = ImageIO.read(new File("your image path"));
} catch (Exception e)
{
e.printStackTrace();
}
ImageIcon imageIcon = new ImageIcon(fitimage(image, label.getWidth(), label.getHeight()));
jLabel1.setIcon(imageIcon);
}
private Image fitimage(Image img , int w , int h)
{
BufferedImage resizedimage = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = resizedimage.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(img, 0, 0,w,h,null);
g2.dispose();
return resizedimage;
}
I used tmux-powerline to fully pimp my tmux status bar. I was googling for a way to change to background of the status bar when your typing a tmux command. When I stumbled on this post I thought I should mention it for completeness.
Update: This project is in a maintenance mode and no future functionality is likely to be added. tmux-powerline, with all other powerline projects, is replaced by the new unifying powerline. However this project is still functional and can serve as a lightweight alternative for non-python users.
The problem is that you do not have a public void main(String[] args)
method in the class you attempt to invoke.
It
static
Note, that you HAVE actually specified an existing class (otherwise the error would have been different), but that class lacks the main method.
dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))
na.omit(dat)
x1 x2
1 1 100
3 3 300
5 5 500
Dictionaries in Python are data structures that store key-value pairs. You can use them like associative arrays. Curly braces are used when declaring dictionaries:
d = {'One': 1, 'Two' : 2, 'Three' : 3 }
print d['Two'] # prints "2"
Curly braces are not used to denote control levels in Python. Instead, Python uses indentation for this purpose.
I think you really need some good resources for learning Python in general. See https://stackoverflow.com/q/175001/10077
Try this
var json = '{ "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" }';
json = $.parseJSON(json);
var i = 0, req_index = "";
$.each(json, function(index, value){
if(index == 'key2'){
req_index = i;
}
i++;
});
alert(req_index);
When you use a command substitution (i.e., the $(...)
construct), you are creating a subshell. Subshells inherit variables from their parent shells, but this only works one way: A subshell cannot modify the environment of its parent shell.
Your variable e
is set within a subshell, but not the parent shell. There are two ways to pass values from a subshell to its parent. First, you can output something to stdout, then capture it with a command substitution:
myfunc() {
echo "Hello"
}
var="$(myfunc)"
echo "$var"
The above outputs:
Hello
For a numerical value in the range of 0 through 255, you can use return
to pass the number as the exit status:
mysecondfunc() {
echo "Hello"
return 4
}
var="$(mysecondfunc)"
num_var=$?
echo "$var - num is $num_var"
This outputs:
Hello - num is 4
Using a
instead of w
should let you update the file instead of creating a new one/overwriting everything in the existing file.
See this answer for a difference in the modes.
yes, of course! in fact, writing if(pointer) is a more convenient way of writing rather than if(pointer != NULL) because: 1. it is easy to debug 2. easy to understand 3. if accidently, the value of NULL is defined, then also the code will not crash
This might help...
test_list = [5, 8]
test_list[0] = None
print test_list
#prints [None, 8]
Many of the List implementation support limited support to add/remove, and Arrays.asList(membersArray) is one of that. You need to insert the record in java.util.ArrayList or use the below approach to convert into ArrayList.
With the minimal change in your code, you can do below to convert a list to ArrayList. The first solution is having a minimum change in your solution, but the second one is more optimized, I guess.
String[] membersArray = request.getParameterValues('members');
ArrayList<String> membersList = new ArrayList<>(Arrays.asList(membersArray));
OR
String[] membersArray = request.getParameterValues('members');
ArrayList<String> membersList = Stream.of(membersArray).collect(Collectors.toCollection(ArrayList::new));
Accessing The Current Route
Get current route name in Blade templates
{{ Route::currentRouteName() }}
for more info https://laravel.com/docs/5.5/routing#accessing-the-current-route
One option would be to reduce
the keys()
:
var o = {
a: {value:1},
b: {value:2},
c: {value:3}
};
Object.keys(o).reduce(function (previous, key) {
return previous + o[key].value;
}, 0);
With this, you'll want to specify an initial value or the 1st round will be 'a' + 2
.
If you want the result as an Object ({ value: ... }
), you'll have to initialize and return the object each time:
Object.keys(o).reduce(function (previous, key) {
previous.value += o[key].value;
return previous;
}, { value: 0 });
git fetch
git branch --track branch-name origin/branch-name
First command makes sure you have remote branch in local repository. Second command creates local branch which tracks remote branch. It assumes that your remote name is origin
and branch name is branch-name
.
--track
option is enabled by default for remote branches and you can omit it.
You can't control the timeout due to UnknownHostException
. These are DNS timings. You can only control the connect timeout given a valid host. None of the preceding answers addresses this point correctly.
But I find it hard to believe that you are really getting an UnknownHostException
when you specify an IP address rather than a hostname.
EDIT To control Java's DNS timeouts see this answer.
Well, the simple regex is this:
/^dbo\..*_fn$/
It would be better, however, to use the string manipulation functionality of whatever programming language you're using to slice off the first four and the last three characters of the string and check whether they're what you want.
Symbolic or soft link (files or directories, more flexible and self documenting)
# Source Link
ln -s /home/jake/doc/test/2000/something /home/jake/xxx
Hard link (files only, less flexible and not self documenting)
# Source Link
ln /home/jake/doc/test/2000/something /home/jake/xxx
More information: man ln
/home/jake/xxx
is like a new directory. To avoid "is not a directory: No such file or directory" error, as @trlkly comment, use relative path in the target, that is, using the example:
cd /home/jake/
ln -s /home/jake/doc/test/2000/something xxx
Do you actually have the single quotes in your command? I don't think they are necessary. Plus, I think you also need --no-auth-cache
and --non-interactive
Here is what I use (no single quotes)
--non-interactive --no-auth-cache --username XXXX --password YYYY
See the Client Credentials Caching documentation in the svnbook for more information.
You can get value by using id for that element in onclick function
function dosomething(){
var buttonValue = document.getElementById('buttonId').value;
}
If you just want simple parallelism, you can do this:
var bag = new ConcurrentBag<object>();
var tasks = myCollection.Select(async item =>
{
// some pre stuff
var response = await GetData(item);
bag.Add(response);
// some post stuff
});
await Task.WhenAll(tasks);
var count = bag.Count;
If you need something more complex, check out Stephen Toub's ForEachAsync
post.
To read a specific set of columns from a dataset you, there are several other options:
1) With fread
from the data.table
-package:
You can specify the desired columns with the select
parameter from fread
from the data.table
package. You can specify the columns with a vector of column names or column numbers.
For the example dataset:
library(data.table)
dat <- fread("data.txt", select = c("Year","Jan","Feb","Mar","Apr","May","Jun"))
dat <- fread("data.txt", select = c(1:7))
Alternatively, you can use the drop
parameter to indicate which columns should not be read:
dat <- fread("data.txt", drop = c("Jul","Aug","Sep","Oct","Nov","Dec"))
dat <- fread("data.txt", drop = c(8:13))
All result in:
> data
Year Jan Feb Mar Apr May Jun
1 2009 -41 -27 -25 -31 -31 -39
2 2010 -41 -27 -25 -31 -31 -39
3 2011 -21 -27 -2 -6 -10 -32
UPDATE: When you don't want fread
to return a data.table, use the data.table = FALSE
-parameter, e.g.: fread("data.txt", select = c(1:7), data.table = FALSE)
2) With read.csv.sql
from the sqldf
-package:
Another alternative is the read.csv.sql
function from the sqldf
package:
library(sqldf)
dat <- read.csv.sql("data.txt",
sql = "select Year,Jan,Feb,Mar,Apr,May,Jun from file",
sep = "\t")
3) With the read_*
-functions from the readr
-package:
library(readr)
dat <- read_table("data.txt",
col_types = cols_only(Year = 'i', Jan = 'i', Feb = 'i', Mar = 'i',
Apr = 'i', May = 'i', Jun = 'i'))
dat <- read_table("data.txt",
col_types = list(Jul = col_skip(), Aug = col_skip(), Sep = col_skip(),
Oct = col_skip(), Nov = col_skip(), Dec = col_skip()))
dat <- read_table("data.txt", col_types = 'iiiiiii______')
From the documentation an explanation for the used characters with col_types
:
each character represents one column: c = character, i = integer, n = number, d = double, l = logical, D = date, T = date time, t = time, ? = guess, or _/- to skip the column
You can use
app:cardBackgroundColor="@color/red"
or
android:backgroundTint="@color/red"
I use this solution for responsive boxes of different rations:
HTML:
<div class="box ratio1_1">
<div class="box-content">
... CONTENT HERE ...
</div>
</div>
CSS:
.box-content {
width: 100%; height: 100%;
top: 0;right: 0;bottom: 0;left: 0;
position: absolute;
}
.box {
position: relative;
width: 100%;
}
.box::before {
content: "";
display: block;
padding-top: 100%; /*square for no ratio*/
}
.ratio1_1::before { padding-top: 100%; }
.ratio1_2::before { padding-top: 200%; }
.ratio2_1::before { padding-top: 50%; }
.ratio4_3::before { padding-top: 75%; }
.ratio16_9::before { padding-top: 56.25%; }
See demo on JSfiddle.net
Here is my solution to the problem. I think it's similar in approach, but a little simpler than some of the other answers. It also allows for an arbitrary number of sub-dictionaries and seems to work for any datatype (I even tested it on a dictionary which had functions as values):
def pprint(web, level):
for k,v in web.items():
if isinstance(v, dict):
print('\t'*level, f'{k}: ')
level += 1
pprint(v, level)
level -= 1
else:
print('\t'*level, k, ": ", v)
EDIT: Putting the right solution first, originally from this question. It's the only one that searches relative to the module directory:
use FindBin; # locate this script
use lib "$FindBin::Bin/.."; # use the parent directory
use yourlib;
There's many other ways that search for libraries relative to the current directory. You can invoke perl with the -I argument, passing the directory of the other module:
perl -I.. yourscript.pl
You can include a line near the top of your perl script:
use lib '..';
You can modify the environment variable PERL5LIB before you run the script:
export PERL5LIB=$PERL5LIB:..
The push(@INC) strategy can also work, but it has to be wrapped in BEGIN{} to make sure that the push is run before the module search:
BEGIN {push @INC, '..'}
use yourlib;
I tried some of the other answers here, but originalEvent was also undefined. Upon inspection, found a TouchList classed property (as suggested by another poster) and managed to get to pageX/Y this way:
var x = e.changedTouches[0].pageX;
Go to Start > Configure Tomcat >
This worked for me!
To add rows to existing DataTable in Dataset:
DataRow drPartMtl = DSPartMtl.Tables[0].NewRow();
drPartMtl["Group"] = "Group";
drPartMtl["BOMPart"] = "BOMPart";
DSPartMtl.Tables[0].Rows.Add(drPartMtl);
Chacha, per the PHP documentation: "Set to a non-empty value if the script was queried through the HTTPS protocol." So your if statement there will return false in many cases where HTTPS is indeed on. You'll want to verify that $_SERVER['HTTPS']
exists and is non-empty. In cases where HTTPS is not set correctly for a given server, you can try checking if $_SERVER['SERVER_PORT'] == 443
.
But note that some servers will also set $_SERVER['HTTPS']
to a non-empty value, so be sure to check this variable also.
Reference: Documentation for $_SERVER
and $HTTP_SERVER_VARS
[deprecated]
The match attribute indicates on which parts the template transformation is going to be applied. In that particular case the "/" means the root of the xml document. The value you have to provide into the match attribute should be XPath expression. XPath is the language you have to use to refer specific parts of the target xml file.
To gain a meaningful understanding of what else you can put into match attribute you need to understand what xpath is and how to use it. I suggest yo look at links I've provided for youat the bottom of the answer.
Could I write "table" or any other html tag instead of "/" ?
Yes you can. But this depends what exactly you are trying to do. if your target xml file contains HMTL elements and you are triyng to apply this xsl:template on them it makes sense to use table, div or anithing else.
Here a few links:
Signed variables can be 0, positive or negative.
Unsigned variables can be 0 or positive.
Unsigned variables are used sometimes because more bits can be used to represent the actual value. Giving you a larger range. Also you can ensure that a negative value won't be passed to your function for example.
Actually, if you're working with jQuery, as of version 1.4.3 1.4.4 (because of the bug as mentioned in the comments below), data-*
attributes are supported through .data()
:
As of jQuery 1.4.3 HTML 5
data-
attributes will be automatically pulled in to jQuery's data object.Note that strings are left intact while JavaScript values are converted to their associated value (this includes booleans, numbers, objects, arrays, and null). The
data-
attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).
The jQuery.fn.data
function will return all of the data-
attribute inside an object as key-value pairs, with the key being the part of the attribute name after data-
and the value being the value of that attribute after being converted following the rules stated above.
I've also created a simple demo if that doesn't convince you: http://jsfiddle.net/yijiang/WVfSg/
Saw an interesting one the other day, maybe week, on a blog that I can't remember. Basically I can't take credit for this but I thought it might have some useful application.
Say you wanted an abstract class to be seen by another assembly but you don't want someone to be able to inherit from it. Sealed won't work because it's abstract for a reason, other classes in that assembly do inherit from it. Private won't work because you might want to declare a Parent class somewhere in the other assembly.
namespace Base.Assembly { public abstract class Parent { internal abstract void SomeMethod(); } //This works just fine since it's in the same assembly. public class ChildWithin : Parent { internal override void SomeMethod() { } } } namespace Another.Assembly { //Kaboom, because you can't override an internal method public class ChildOutside : Parent { } public class Test { //Just fine private Parent _parent; public Test() { //Still fine _parent = new ChildWithin(); } } }
As you can see, it effectively allows someone to use the Parent class without being able to inherit from.
The full code with details about how to install as MySQL plugin are here: https://github.com/lucasepe/lib_mysqludf_haversine
I posted this last year as comment. Since kindly @TylerCollier suggested me to post as answer, here it is.
Another way is to write a custom UDF function that returns the haversine distance from two points. This function can take in input:
lat1 (real), lng1 (real), lat2 (real), lng2 (real), type (string - optinal - 'km', 'ft', 'mi')
So we can write something like this:
SELECT id, name FROM MY_PLACES WHERE haversine_distance(lat1, lng1, lat2, lng2) < 40;
to fetch all records with a distance less then 40 kilometers. Or:
SELECT id, name FROM MY_PLACES WHERE haversine_distance(lat1, lng1, lat2, lng2, 'ft') < 25;
to fetch all records with a distance less then 25 feet.
The core function is:
double
haversine_distance( UDF_INIT* initid, UDF_ARGS* args, char* is_null, char *error ) {
double result = *(double*) initid->ptr;
/*Earth Radius in Kilometers.*/
double R = 6372.797560856;
double DEG_TO_RAD = M_PI/180.0;
double RAD_TO_DEG = 180.0/M_PI;
double lat1 = *(double*) args->args[0];
double lon1 = *(double*) args->args[1];
double lat2 = *(double*) args->args[2];
double lon2 = *(double*) args->args[3];
double dlon = (lon2 - lon1) * DEG_TO_RAD;
double dlat = (lat2 - lat1) * DEG_TO_RAD;
double a = pow(sin(dlat * 0.5),2) +
cos(lat1*DEG_TO_RAD) * cos(lat2*DEG_TO_RAD) * pow(sin(dlon * 0.5),2);
double c = 2.0 * atan2(sqrt(a), sqrt(1-a));
result = ( R * c );
/*
* If we have a 5th distance type argument...
*/
if (args->arg_count == 5) {
str_to_lowercase(args->args[4]);
if (strcmp(args->args[4], "ft") == 0) result *= 3280.8399;
if (strcmp(args->args[4], "mi") == 0) result *= 0.621371192;
}
return result;
}
I came across this really great talk by Facebook engineers about the Efficient Storage of Billions of Photos in a database
I know it's a bit old question but still people try to find efficient solution so instead you should use FULLTEXT index (it's available from MySQL 5.6.4).
Query on table with +35mil records by triple like
in where block took ~2.5s but after adding index on these fields and using BOOLEAN MODE inside match ... against ...
it took only 0.05s.
First add an Enrty
and Category
class:
public class Entry { public string Id { get; set; } public string Title { get; set; } public string Updated { get; set; } public string Summary { get; set; } public string GPoint { get; set; } public string GElev { get; set; } public List<string> Categories { get; set; } } public class Category { public string Label { get; set; } public string Term { get; set; } }
Then use LINQ to XML
XDocument xDoc = XDocument.Load("path"); List<Entry> entries = (from x in xDoc.Descendants("entry") select new Entry() { Id = (string) x.Element("id"), Title = (string)x.Element("title"), Updated = (string)x.Element("updated"), Summary = (string)x.Element("summary"), GPoint = (string)x.Element("georss:point"), GElev = (string)x.Element("georss:elev"), Categories = (from c in x.Elements("category") select new Category { Label = (string)c.Attribute("label"), Term = (string)c.Attribute("term") }).ToList(); }).ToList();
Remove leading + trailing '0':
list = [i.strip('0') for i in listOfNum ]
Remove leading '0':
list = [ i.lstrip('0') for i in listOfNum ]
Remove trailing '0':
list = [ i.rstrip('0') for i in listOfNum ]
In 99.9% of all cases it is bad program design to share non-constant, global variables between files. There are very few cases when you actually need to do this: they are so rare that I cannot come up with any valid cases. Declarations of hardware registers perhaps.
In most of the cases, you should either use (possibly inlined) setter/getter functions ("public"), static variables at file scope ("private"), or incomplete type implementations ("private") instead.
In those few rare cases when you need to share a variable between files, do like this:
// file.h
extern int my_var;
// file.c
#include "file.h"
int my_var = something;
// main.c
#include "file.h"
use(my_var);
Never put any form of variable definition in a h-file.
Escaping the path with apostrophes is correct, but the start command takes a parameter containing the title of the new window. This parameter is detected by the surrounding apostrophes, so your application is not executed.
Try something like this:
start "Dummy Title" "c:\path with spaces\app.exe" param1 "param with spaces"
Is EmailHandler
really the full name of your servlet class, i.e. it's not in a package like com.something.EmailHandler
? It has to be fully-qualified in web.xml
.
A little late to the party, but this worked for me. Hopefully someone else finds it useful.
<div ng-repeat="video in videos" ng-if="$index < 3">
...
</div>
I'd like to point out that if you want to play with threads in C++, if you use cout
you can get some interesting results.
Consider this code:
#include <string>
#include <iostream>
#include <thread>
using namespace std;
void task(int taskNum, string msg) {
for (int i = 0; i < 5; ++i) {
cout << "#" << taskNum << ": " << msg << endl;
}
}
int main() {
thread t1(task, 1, "AAA");
thread t2(task, 2, "BBB");
t1.join();
t2.join();
return 0;
}
// g++ ./thread.cpp -o thread.out -ansi -pedantic -pthread -std=c++0x
Now, the output comes all shuffled. It can yield different results too, try executing several times:
##12:: ABABAB
##12:: ABABAB
##12:: ABABAB
##12:: ABABAB
##12:: ABABAB
You can use printf
to get it right, or you can use mutex
.
#1: AAA
#2: BBB
#1: AAA
#2: BBB
#1: AAA
#2: BBB
#1: AAA
#2: BBB
#1: AAA
#2: BBB
Have fun!
(since I ran into this today)
Be careful when using ES2015 fat arrow syntax:
This will fail :
it('accesses the network', done => {
this.timeout(500); // will not work
// *this* binding refers to parent function scope in fat arrow functions!
// i.e. the *this* object of the describe function
done();
});
EDIT: Why it fails:
As @atoth mentions in the comments, fat arrow functions do not have their own this binding. Therefore, it's not possible for the it function to bind to this of the callback and provide a timeout function.
Bottom line: Don't use arrow functions for functions that need an increased timeout.
Single line- There are two ways, you can simply change.
1- Pragmatically (Swift 3)
Just add the following code
yourLabel.numberOfLines = 1;
yourLabel.minimumScaleFactor = 0.7;
yourLabel.adjustsFontSizeToFitWidth = true;
2 - Using UILabel Attributes inspector
i- Select your label- Set number of lines 1.
ii- Autoshrink- Select Minimum Font Scale from drop down
iii- Set Minimum Font Scale value as you wish , I have set 0.7 as in below image. (default is 0.5)
It is not stuck, it will take some time normally 5-7 mins , it also depends upon internet connection, so wait for some time. It will take time only for first launch.
Update: Check the latest log file in your C:\Users\<User>\.gradle\daemon\x.y
folder to see what it's downloading.
When you convert an address or object to a lat/long it is called Geocoding.
There are a lot geocoding solutions around. The solution right for your project will depend on the acceptability of the licensing terms of each geocoding solution. Both Microsoft Virtual Earth and Google Maps offer solutions which are free to use under a very restrictive licenses...
https://developers.google.com/maps/documentation/javascript/tutorial
There is an open source project called auto-py-to-exe on GitHub. Actually it also just uses PyInstaller internally but since it is has a simple GUI that controls PyInstaller it may be a comfortable alternative. It can also output a standalone file in contrast to other solutions. They also provide a video showing how to set it up.
GUI:
Output:
Currently, no, not without resorting to trickery. borders on elements are supposed to run the entire length of whatever side of the element box they apply to.
Just give the individual button elements a unique name. When pressed, the button's name is available as a request parameter the usual way like as with input elements.
You only need to make sure that the button inputs have type="submit"
as in <input type="submit">
and <button type="submit">
and not type="button"
, which only renders a "dead" button purely for onclick
stuff and all.
E.g.
<form action="${pageContext.request.contextPath}/myservlet" method="post">
<input type="submit" name="button1" value="Button 1" />
<input type="submit" name="button2" value="Button 2" />
<input type="submit" name="button3" value="Button 3" />
</form>
with
@WebServlet("/myservlet")
public class MyServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
MyClass myClass = new MyClass();
if (request.getParameter("button1") != null) {
myClass.method1();
} else if (request.getParameter("button2") != null) {
myClass.method2();
} else if (request.getParameter("button3") != null) {
myClass.method3();
} else {
// ???
}
request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);
}
}
Alternatively, use <button type="submit">
instead of <input type="submit">
, then you can give them all the same name, but an unique value. The value of the <button>
won't be used as label, you can just specify that yourself as child.
E.g.
<form action="${pageContext.request.contextPath}/myservlet" method="post">
<button type="submit" name="button" value="button1">Button 1</button>
<button type="submit" name="button" value="button2">Button 2</button>
<button type="submit" name="button" value="button3">Button 3</button>
</form>
with
@WebServlet("/myservlet")
public class MyServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
MyClass myClass = new MyClass();
String button = request.getParameter("button");
if ("button1".equals(button)) {
myClass.method1();
} else if ("button2".equals(button)) {
myClass.method2();
} else if ("button3".equals(button)) {
myClass.method3();
} else {
// ???
}
request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);
}
}
Excellent answer already provide onsite here.
See the summary below:
Since you tagged Java-ee as well - then YES it is possible.
and in core java as well it is possible using static blocks
and check this How can you run a Java program without main method?
Edit:
as already pointed out in other answers - it does not support from Java 7
One way:
var1="1:2:3:4:5"
var2=${var1##*:}
Another, using an array:
var1="1:2:3:4:5"
saveIFS=$IFS
IFS=":"
var2=($var1)
IFS=$saveIFS
var2=${var2[@]: -1}
Yet another with an array:
var1="1:2:3:4:5"
saveIFS=$IFS
IFS=":"
var2=($var1)
IFS=$saveIFS
count=${#var2[@]}
var2=${var2[$count-1]}
Using Bash (version >= 3.2) regular expressions:
var1="1:2:3:4:5"
[[ $var1 =~ :([^:]*)$ ]]
var2=${BASH_REMATCH[1]}
Not sure if the most efficient way, but this worked for me:
from pyspark.sql.functions import col
df1.alias('a').join(df2.alias('b'),col('b.id') == col('a.id')).select([col('a.'+xx) for xx in a.columns] + [col('b.other1'),col('b.other2')])
The trick is in:
[col('a.'+xx) for xx in a.columns] : all columns in a
[col('b.other1'),col('b.other2')] : some columns of b
Use button.layer.cornerRadius
, button.layer.borderColor
and button.layer.borderWidth
.
Note that borderColor
requires a CGColor
, so you could say (Swift 3/4):
button.backgroundColor = .clear
button.layer.cornerRadius = 5
button.layer.borderWidth = 1
button.layer.borderColor = UIColor.black.cgColor
If the performance is an issue, you can use this command in MS_DOS:
dir /OD >d:\dir.txt
This command generate a dir.txt file in **d:** root the have all files sorted by date. And then read the file from your code. Also, you add other filters by * and ?.
AJAX file uploads are now possible by passing a FormData
object to the data
property of the $.ajax
request.
As the OP specifically asked for a jQuery implementation, here you go:
<form id="upload" enctype="multipart/form-data" action="@Url.Action("JsonSave", "Survey")" method="POST">
<input type="file" name="fileUpload" id="fileUpload" size="23" /><br />
<button>Upload!</button>
</form>
$('#upload').submit(function(e) {
e.preventDefault(); // stop the standard form submission
$.ajax({
url: this.action,
type: this.method,
data: new FormData(this),
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data.UploadedFileCount + ' file(s) uploaded successfully');
},
error: function(xhr, error, status) {
console.log(error, status);
}
});
});
public JsonResult Survey()
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
// save file as required here...
}
return Json(new { UploadedFileCount = Request.Files.Count });
}
More information on FormData at MDN
To open IIS Manager, click Start, type inetmgr in the Search Programs and Files box, and then press ENTER.
if the IIS Manager doesn't open that means you need to install it.
So, Follow the instruction at this link: https://docs.microsoft.com/en-us/iis/install/installing-iis-7/installing-iis-on-windows-vista-and-windows-7