git config --global --unset http.proxy
There are two main differences.
The first one is related to how you will access the relationship. For a unidirectional association, you can navigate the association from one end only.
So, for a unidirectional @ManyToOne
association, it means you can only access the relationship from the child side where the foreign key resides.
If you have a unidirectional @OneToMany
association, it means you can only access the relationship from the parent side which manages the foreign key.
For the bidirectional @OneToMany
association, you can navigate the association in both ways, either from the parent or from the child side.
You also need to use add/remove utility methods for bidirectional associations to make sure that both sides are properly synchronized.
The second aspect is related to performance.
@OneToMany
, unidirectional associations don't perform as well as bidirectional ones.@OneToOne
, a bidirectional association will cause the parent to be fetched eagerly if Hibernate cannot tell whether the Proxy should be assigned or a null value.@ManyToMany
, the collection type makes quite a difference as Sets
perform better than Lists
.According to Jason´s answer we can address only devices that doesn't support hover with pure css media queries. We can also address only devices that support hover, like moogal´s answer in a similar question, with
@media not all and (hover: none)
. It looks weird but it works.
I made a Sass mixin out of this for easier use:
@mixin hover-supported {
@media not all and (hover: none) {
&:hover {
@content;
}
}
}
Update 2019-05-15: I recommend this article from Medium that goes through all different devices that we can target with CSS. Basically it's a mix of these media rules, combine them for specific targets:
@media (hover: hover) {
/* Device that can hover (desktops) */
}
@media (hover: none) {
/* Device that can not hover with ease */
}
@media (pointer: coarse) {
/* Device with limited pointing accuracy (touch) */
}
@media (pointer: fine) {
/* Device with accurate pointing (desktop, stylus-based) */
}
@media (pointer: none) {
/* Device with no pointing */
}
Example for specific targets:
@media (hover: none) and (pointer: coarse) {
/* Smartphones and touchscreens */
}
@media (hover: hover) and (pointer: fine) {
/* Desktops with mouse */
}
I love mixins, this is how I use my hover mixin to only target devices that supports it:
@mixin on-hover {
@media (hover: hover) and (pointer: fine) {
&:hover {
@content;
}
}
}
button {
@include on-hover {
color: blue;
}
}
select max(m.mark) as maxMarkObtained,su.Subname from Student s
inner join Marks m on s.Stid=m.Stid inner join [Subject] su on
su.Subid=m.Subid group by su.Subname
I have execute it , this should work.
Easily consume SOAP Web services with JavaScript -> Listing B
function fncAddTwoIntegers(a, b)
{
varoXmlHttp = new XMLHttpRequest();
oXmlHttp.open("POST",
"http://localhost/Develop.NET/Home.Develop.WebServices/SimpleService.asmx'",
false);
oXmlHttp.setRequestHeader("Content-Type", "text/xml");
oXmlHttp.setRequestHeader("SOAPAction", "http://tempuri.org/AddTwoIntegers");
oXmlHttp.send(" \
<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' \
xmlns:xsd='http://www.w3.org/2001/XMLSchema' \
xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'> \
<soap:Body> \
<AddTwoIntegers xmlns='http://tempuri.org/'> \
<IntegerOne>" + a + "</IntegerOne> \
<IntegerTwo>" + b + "</IntegerTwo> \
</AddTwoIntegers> \
</soap:Body> \
</soap:Envelope> \
");
return oXmlHttp.responseXML.selectSingleNode("//AddTwoIntegersResult").text;
}
This may not meet all your requirements but it is a start at actually answering your question. (I switched XMLHttpRequest() for ActiveXObject("MSXML2.XMLHTTP")).
There is one more way to achieve it:-
Private Sub UserForm_Initialize()
Dim list As Object
Set list = UserForm1.Controls.Add("Forms.ListBox.1", "hello", True)
With list
.Top = 30
.Left = 30
.Width = 200
.Height = 340
.ColumnHeads = True
.ColumnCount = 2
.ColumnWidths = "100;100"
.MultiSelect = fmMultiSelectExtended
.RowSource = "Sheet1!C4:D25"
End With End Sub
Here, I am using the range C4:D25 as source of data for the columns. It will result in both the columns populated with values.
The properties are self explanatory. You can explore other options by drawing ListBox in UserForm and using "Properties Window (F4)" to play with the option values.
To pull more details - (Here %an
refers to author)
Use this :-
git log --author="username" --pretty=format:"%h - %an, %ar : %s"
c:\python27\python.exe c:\somescript.py %*
Error 127
means one of two things:
$PATH
, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.file -L
on /bin/sh
(to get your default/native format) and on the compiler itself (to see what format it is).if the problem is (2), then you can solve it in a few diff ways:
The http://jsconsole.com ( http://jsconsole.com/remote-debugging.html ) provides a nice way you can use to access the content of you webpage.
In order to get rgba integer value instead of float value, we can do
rgba = cmap(0.5,bytes=True)
So to simplify the code based on answer from Ffisegydd, the code would be like this:
#import colormap
from matplotlib import cm
#normalize item number values to colormap
norm = matplotlib.colors.Normalize(vmin=0, vmax=1000)
#colormap possible values = viridis, jet, spectral
rgba_color = cm.jet(norm(400),bytes=True)
#400 is one of value between 0 and 1000
Try the following:
print "First is: %f" % (first)
print "Second is: %f" % (second)
I am unsure what answer is. But apart from that, this will be:
print "DONE: %f DIVIDED BY %f EQUALS %f, SWEET MATH BRO!" % (first, second, ans)
There's a lot of text on Format String Specifiers. You can google it and get a list of specifiers. One thing I forgot to note:
If you try this:
print "First is: %s" % (first)
It converts the float value in first to a string. So that would work as well.
Answer using TypeScript spread operator (...)
// Your key
const key = 'two';
// Your array
const arr = [
'one',
'two',
'three'
];
// Get either the index or -1
const index = arr.indexOf(key); // returns 0
// Despite a real index, or -1, use spread operator and Array.prototype.slice()
const newArray = (index > -1) ? [
...arr.slice(0, index),
...arr.slice(index + 1)
] : arr;
<div ng-app='app' >
<div ng-controller='MainCtrl' >
<ul>
<li ng-repeat="tab in data">
<input type='checkbox' ng-click='change($index,confirm)' ng-model='confirm' />
{{tab.name}}
</li>
</ul>
{{val}}
</div>
</div>
var app = angular.module('app', []);
app.controller('MainCtrl',function($scope){
$scope.val=[];
$scope.confirm=false;
$scope.data=[
{
name:'vijay'
},
{
name:'krishna'
},{
name:'Nikhil'
}
];
$scope.temp;
$scope.change=function(index,confirm){
console.log(confirm);
if(!confirm){
($scope.val).push($scope.data[index]);
}
else{
$scope.temp=$scope.data[index];
var d=($scope.val).indexOf($scope.temp);
if(d!=undefined){
($scope.val).splice(d,1);
}
}
}
})
There is another way, but...
DO NOT DO THIS IF YOU DO NOT WANT YOUR PASSWORD IN THE SCRIPT FILE (It isn't a good idea to store passwords in scripts, but some of us just like to know how.)
Ok, that was the warning, here's the code:
$username = "John Doe"
$password = "ABCDEF"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
$cred
will have the credentials from John Doe with the password "ABCDEF".
Alternative means to get the password ready for use:
$password = convertto-securestring -String "notverysecretpassword" -AsPlainText -Force
I Hope this Help:
<?php
// The code below creates the class
class Person {
// Creating some properties (variables tied to an object)
public $isAlive = true;
public $firstname;
public $lastname;
public $age;
// Assigning the values
public function __construct($firstname, $lastname, $age) {
$this->firstname = $firstname;
$this->lastname = $lastname;
$this->age = $age;
}
// Creating a method (function tied to an object)
public function greet() {
return "Hello, my name is " . $this->firstname . " " . $this->lastname . ". Nice to meet you! :-)";
}
}
// Creating a new person called "boring 12345", who is 12345 years old ;-)
$me = new Person('boring', '12345', 12345);
// Printing out, what the greet method returns
echo $me->greet();
?>
For More Information You need to Go to codecademy.com
In case one does not have sudo privilege, but still needs to install the library.
Download source for the software/library using:
apt-get source libaio
or
wget https://src.fedoraproject.org/lookaside/pkgs/libaio/libaio-0.3.110.tar.gz/2a35602e43778383e2f4907a4ca39ab8/libaio-0.3.110.tar.gz
unzip the library
Install with the following command to user-specific library:
make prefix=`pwd`/usr install #(Copy from INSTALL file of libaio-0.3.110)
or
make prefix=/path/to/your/lib/libaio install
Include libaio library into LD_LIBRARY_PATH for your app:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/path/to/your/lib/libaio/lib
Now, your app should be able to find libaio.so.1
If you've accidentally or not mixed integers with text data you should at first execute below update command (if not above alter table will fail):
UPDATE the_table SET col_name = replace(col_name, 'some_string', '');
In Java 8 you could use streams and Files.lines
:
List<String> list = null;
try (Stream<String> lines = Files.lines(myPathToTheFile))) {
list = lines.collect(Collectors.toList());
} catch (IOException e) {
LOGGER.error("Failed to load file.", e);
}
Or as a function including loading the file from the file system:
private List<String> loadFile() {
List<String> list = null;
URI uri = null;
try {
uri = ClassLoader.getSystemResource("example.txt").toURI();
} catch (URISyntaxException e) {
LOGGER.error("Failed to load file.", e);
}
try (Stream<String> lines = Files.lines(Paths.get(uri))) {
list = lines.collect(Collectors.toList());
} catch (IOException e) {
LOGGER.error("Failed to load file.", e);
}
return list;
}
I tried following format, working fine
*/5 * * * * wget --quiet -O /dev/null http://localhost/cron.php
Rebase and Cherry-pick is the only way you can keep clean commit history. Avoid using merge and avoid creating merge conflict. If you are using gerrit set one project to Merge if necessary and one project to cherry-pick mode and try yourself.
If you're not too concerned with performance, you could always try listening on a port using the ServerSocket class. If it throws an exception odds are it's being used.
public static boolean isAvailable(int portNr) {
boolean portFree;
try (var ignored = new ServerSocket(portNr)) {
portFree = true;
} catch (IOException e) {
portFree = false;
}
return portFree;
}
EDIT: If all you're trying to do is select a free port then new ServerSocket(0)
will find one for you.
If you create your test classes in a seperate folder which you then add to your build path,
Then you could make the test class an inner class of the class under test by using package correctly to set the namespace. This gives it access to private fields and methods.
But dont forget to remove the folder from the build path for your release build.
I found this problem while trying to install a new clang compiler. Turns out that both the Debian and the LLVM maintainers agree that the alternatives system should be used for alternatives, NOT for versioning.
The solution they propose is something like this:
PATH=/usr/lib/llvm-3.7/bin:$PATH
where /usr/lib/llvm-3.7/bin is a directory that got created by the llvm-3.7 package, and which contains all the tools with their non-suffixed names. With that, llvm-config (version 3.7) appears with its plain name in your PATH. No need to muck around with symlinks, nor to call the llvm-config-3.7 that got installed in /usr/bin.
Also, check for a package named llvm-defaults (or gcc-defaults), which might offer other way to do this (I didn't use it).
This is how I am comparing 2 dates, now() and a date from the table
@if (\Carbon\Carbon::now()->lte($item->client->event_date_from))
.....
.....
@endif
Should work just right. I have used the comparison functions provided by Carbon.
try this script..
#!/bin/bash
NULL="_"
for f in `svn st|grep -v ^\?|sed s/.\ *//`;
do LIST="${LIST} $f $NULL on";
done
dialog --checklist "Select files to commit" 30 60 30 $LIST 2>/tmp/svnlist.txt
svn ci `cat /tmp/svnlist.txt|sed 's/"//g'`
Pretty sure this solves what you're looking for:
HTML:
<table>
<tr><td><button class="editbtn">edit</button></td></tr>
<tr><td><button class="editbtn">edit</button></td></tr>
<tr><td><button class="editbtn">edit</button></td></tr>
<tr><td><button class="editbtn">edit</button></td></tr>
</table>
Javascript (using jQuery):
$(document).ready(function(){
$('.editbtn').click(function(){
$(this).html($(this).html() == 'edit' ? 'modify' : 'edit');
});
});
Edit:
Apparently I should have looked at your sample code first ;)
You need to change (at least) the ID attribute of each element. The ID is the unique identifier for each element on the page, meaning that if you have multiple items with the same ID, you'll get conflicts.
By using classes, you can apply the same logic to multiple elements without any conflicts.
For Mysql please see the LOAD XML
SyntaxDocs.
It should work without any additional XML transformation for the XML you've provided, just specify the format and define the table inside the database firsthand with matching column names:
LOAD XML LOCAL INFILE 'table1.xml'
INTO TABLE table1
ROWS IDENTIFIED BY '<table1>';
There is also a related question:
For Postgresql I do not know.
You can also use the CSS calc() function to subtract the width of your padding from the percentage of your container's width.
An example:
width: calc((100%) - (32px))
Just be sure to make the subtracted width equal to the total padding, not just one half. If you pad both sides of the inner div with 16px, then you should subtract 32px from the final width, assuming that the example below is what you want to achieve.
.outer {_x000D_
width: 200px;_x000D_
height: 120px;_x000D_
background-color: black;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
height: 40px;_x000D_
top: 30px;_x000D_
position: relative;_x000D_
padding: 16px;_x000D_
background-color: teal;_x000D_
}_x000D_
_x000D_
#inner-1 {_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
#inner-2 {_x000D_
width: calc((100%) - (32px));_x000D_
}
_x000D_
<div class="outer" id="outer-1">_x000D_
<div class="inner" id="inner-1"> width of 100% </div>_x000D_
</div>_x000D_
_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
<div class="outer" id="outer-2">_x000D_
<div class="inner" id="inner-2"> width of 100% - 16px </div>_x000D_
</div>
_x000D_
I got this on Firefox (FF58). I fixed this with:
dom.moduleScripts.enabled
in about:config
Source: Import page on mozilla (See Browser compatibility)
type="module"
to your script tag where you import the js file<script type="module" src="appthatimports.js"></script>
./
, /
, ../
or http://
before)import * from "./mylib.js"
For more examples, this blog post is good.
The best way in my opinion is Reflection as others have recommended. Here's a sample that evaluates each local field for null. If it finds one that is not null, method will return false.
public class User {
String id = null;
String name = null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isNull() {
Field fields[] = this.getClass().getDeclaredFields();
for (Field f : fields) {
try {
Object value = f.get(this);
if (value != null) {
return false;
}
}
catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return true;
}
public static void main(String args[]) {
System.out.println(new User().isNull());
}
}
If the OpenSSL headers are in the openssl
sub-directory of the current directory, use:
gcc -I. -o Opentest Opentest.c -lcrypto
The pre-processor looks to create a name such as "./openssl/ssl.h
" from the ".
" in the -I
option and the name specified in angle brackets. If you had specified the names in double quotes (#include "openssl/ssl.h"
), you might never have needed to ask the question; the compiler on Unix usually searches for headers enclosed in double quotes in the current directory automatically, but it does not do so for headers enclosed in angle brackets (#include <openssl/ssl.h>
). It is implementation defined behaviour.
You don't say where the OpenSSL libraries are - you might need to add an appropriate option and argument to specify that, such as '-L /opt/openssl/lib
'.
It means that the method accepts a variable number of arguments ("varargs") of type JID
. Within the method, recipientJids
is presented.
This is handy for cases where you've a method that can optionally handle more than one argument in a natural way, and allows you to write calls which can pass one, two or three parameters to the same method, without having the ugliness of creating an array on the fly.
It also enables idioms such as sprintf
from C; see String.format()
, for example.
This will uninstall a gem installed by bundler:
bundle exec gem uninstall GEM_NAME
Note that this throws
ERROR: While executing gem ... (NoMethodError) undefined method `delete' for #<Bundler::SpecSet:0x00000101142268>
but the gem is actually removed. Next time you run bundle install
the gem will be reinstalled.
In stead of "live" you need to use "on" event, but assign it to the document object:
Use:
$(document).on('hidden.bs.modal', '#Control_id', function (event) {
// code to run on closing
});
In a specific case the issue is due to the maven-archetype-webapp which is released for a dynamic webapp, faceted to the ver.2.5 (see the produced web.xml and the related xsd) and it's related to eclipse. When you try to change the project facet to dynamic webapp > 2.5 the src folder structure will syntactically change (the 2.5 is different from 3.1), but not fisically.
This is why you will face in a null pointer exception if you apply to the changes.
To solve it you have to set from the project facets configuration the Default configuration. Apply the changes, then going into the Java Build Path you have to remove the /src folder and create the /src/main/java folder at least (it's also required /src/main/resources and /src/test/java to be compliant) re-change into the required configuration you desire (3.0, 3.1) and then do apply.
In Spring 3.0.x add the following to your servlet-config.xml (the file that is configured in web.xml as the contextConfigLocation. You need to add the mvc namespace as well but just google for that if you don't know how! ;)
That works for me
<mvc:default-servlet-handler/>
Regards
Ayub Malik
Perhaps try this:
function CCSStylesheetRuleStyle(stylesheet, selectorText, style, value){
var CCSstyle = undefined, rules;
for(var m in document.styleSheets){
if(document.styleSheets[m].href.indexOf(stylesheet) != -1){
rules = document.styleSheets[m][document.all ? 'rules' : 'cssRules'];
for(var n in rules){
if(rules[n].selectorText == selectorText){
CCSstyle = rules[n].style;
break;
}
}
break;
}
}
if(value == undefined)
return CCSstyle[style]
else
return CCSstyle[style] = value
}
To sum up if your remote is called origin
and you're working on master
branch:
git tag -d <tagname>
git push origin :refs/tags/<tagname>
git tag <tagname> <commitId>
git push origin <tagname>
You can also exchange line 4 to git push origin --tags
to push all the changes with tags from your local changes.
Basing on @stuart-golodetz, @greg-hewgill, @eedeep, @ben-hocking answers, comments below their answers and NateS comments below my answer.
DECLARE @x VARCHAR(32) = 'MS-SQL-Server';
SELECT
SUBSTRING(@x,0,CHARINDEX('-',LTRIM(RTRIM(@x)))) A,
SUBSTRING(@x,CHARINDEX('-',LTRIM(RTRIM(@x)))+1,CHARINDEX('-'
,LTRIM(RTRIM(@x)))) B,
SUBSTRING(@x,CHARINDEX('-',REVERSE(LTRIM(RTRIM(@x))))+1,LEN(@x)-1) C
A B C
MS SQL Server
When I started with $ nohup storm dev-zookeper
,
METHOD1 : using jobs
,
prayagupd@prayagupd:/home/vmfest# jobs -l
[1]+ 11129 Running nohup ~/bin/storm/bin/storm dev-zookeeper &
METHOD2 : using ps
command.
$ ps xw
PID TTY STAT TIME COMMAND
1031 tty1 Ss+ 0:00 /sbin/getty -8 38400 tty1
10582 ? S 0:01 [kworker/0:0]
10826 ? Sl 0:18 java -server -Dstorm.options= -Dstorm.home=/root/bin/storm -Djava.library.path=/usr/local/lib:/opt/local/lib:/usr/lib -Dsto
10853 ? Ss 0:00 sshd: vmfest [priv]
TTY column with ?
=> nohup
running programs.
Description
Reference
$ man ps
# then search /PROCESS STATE CODES
Here is template of sort_values according to pandas documentation.
DataFrame.sort_values(by, axis=0,
ascending=True,
inplace=False,
kind='quicksort',
na_position='last',
ignore_index=False, key=None)[source]
In this case it will be like this.
df.sort_values(by=['2'])
API Reference pandas.DataFrame.sort_values
I was able to fix this error by simply initializing a variable that was being used later in my program. At the time, I wasn't using Option Explicit in my class/module.
Update 2020: It's been 7 years since I wrote this answer. It still seems to be getting a lot of attention. In 2013 Newtonsoft Json.Net was THE answer to this problem. Now it's still a good answer to this problem but it's no longer the the only viable option. To add some up-to-date caveats to this answer:
System.Text.Json
serialiser (see below)JavaScriptSerializer
have thankfully passed and this class isn't even in .Net Core. This invalidates a lot of the comparisons ran by Newtonsoft.Are Json.Net's days numbered? It's still used a LOT and it's still used by MS librarties. So probably not. But this does feel like the beginning of the end for this library that may well of just run it's course.
A new kid on the block since writing this is System.Text.Json
which has been added to .Net Core 3.0. Microsoft makes several claims to how this is, now, better than Newtonsoft. Including that it is faster than Newtonsoft. as below, I'd advise you to test this yourself .
I would recommend Json.Net, see example below:
List<data> _data = new List<data>();
_data.Add(new data()
{
Id = 1,
SSN = 2,
Message = "A Message"
});
string json = JsonConvert.SerializeObject(_data.ToArray());
//write string to file
System.IO.File.WriteAllText(@"D:\path.txt", json);
Or the slightly more efficient version of the above code (doesn't use a string as a buffer):
//open file stream
using (StreamWriter file = File.CreateText(@"D:\path.txt"))
{
JsonSerializer serializer = new JsonSerializer();
//serialize object directly into file stream
serializer.Serialize(file, _data);
}
Documentation: Serialize JSON to a file
Why? Here's a feature comparison between common serialisers as well as benchmark tests .
Below is a graph of performance taken from the linked article:
This separate post, states that:
Json.NET has always been memory efficient, streaming the reading and writing large documents rather than loading them entirely into memory, but I was able to find a couple of key places where object allocations could be reduced...... (now) Json.Net (6.0) allocates 8 times less memory than JavaScriptSerializer
Benchmarks appear to be Json.Net 5, the current version (on writing) is 10. What version of standard .Net serialisers used is not mentioned
These tests are obviously from the developers who maintain the library. I have not verified their claims. If in doubt test them yourself.
I also had problems with transformations in IE9, I used -ms-transform: rotate(10deg)
and it didn't work. Tried everything I could, but the problem was in browser mode, to make transformations work, you need to set compatibility mode to "Standard IE9".
Would like to take credit for this but I found a solution here:
https://teamtreehouse.com/forum/how-do-you-make-a-svg-clickable
add the following to the css for the anchor:
a.svg {
position: relative;
display: inline-block;
}
a.svg:after {
content: "";
position: absolute;
top: 0;
right: 0;
bottom: 0;
left:0;
}
<a href="#" class="svg">
<object data="random.svg" type="image/svg+xml">
<img src="random.jpg" />
</object>
</a>
Link works on the svg and on the fallback.
Follow these steps then you can create custom styles for your file upload form:
1.) This is the simple HTML form(please read the HTML comments I have written here bellow)
<form action="#type your action here" method="POST" enctype="multipart/form-data">
<div id="yourBtn" style="height: 50px; width: 100px;border: 1px dashed #BBB; cursor:pointer;" onclick="getFile()">Click to upload!</div>
<!-- this is your file input tag, so i hide it!-->
<div style='height: 0px;width: 0px; overflow:hidden;'><input id="upfile" type="file" value="upload"/></div>
<!-- here you can have file submit button or you can write a simple script to upload the file automatically-->
<input type="submit" value='submit' >
</form>
2.) Then use this simple script to pass the click event to file input tag.
function getFile(){
document.getElementById("upfile").click();
}
Now you can use any type of a styling without worrying how to change default styles. I know this very well, because I have been trying to change the default styles for month and a half. believe me it's very hard because different browsers have different upload input tag. So use this one to build your custom file upload forms.Here is the full AUTOMATED UPLOAD code.
<html>
<style>
#yourBtn{
position: relative;
top: 150px;
font-family: calibri;
width: 150px;
padding: 10px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border: 1px dashed #BBB;
text-align: center;
background-color: #DDD;
cursor:pointer;
}
</style>
<script type="text/javascript">
function getFile(){
document.getElementById("upfile").click();
}
function sub(obj){
var file = obj.value;
var fileName = file.split("\\");
document.getElementById("yourBtn").innerHTML = fileName[fileName.length-1];
document.myForm.submit();
event.preventDefault();
}
</script>
<body>
<center>
<form action="#type your action here" method="POST" enctype="multipart/form-data" name="myForm">
<div id="yourBtn" onclick="getFile()">click to upload a file</div>
<!-- this is your file input tag, so i hide it!-->
<!-- i used the onchange event to fire the form submission-->
<div style='height: 0px; width: 0px;overflow:hidden;'><input id="upfile" type="file" value="upload" onchange="sub(this)"/></div>
<!-- here you can have file submit button or you can write a simple script to upload the file automatically-->
<!-- <input type="submit" value='submit' > -->
</form>
</center>
</body>
</html>
In Fujimoto Youichi's example test01
is a container, whereas test02
is an image.
Before doing docker run
you can remove the original container and then assign the container the same name again:
$ docker stop container01
$ docker commit container01 image01
$ docker rm container01
$ docker run -d -P --name container01 image01
(Using -P
to expose ports to random ports rather than manually assigning).
Use a pattern along these lines:
function getValue(file) {
return lookupValue(file);
}
getValue('myFile.txt').then(function(res) {
// do whatever with res here
});
(although this is a bit redundant, I'm sure your actual code is more complicated)
If you want to ignore the last commit that you have just pushed in the remote branch: this will not remove the commit but just ignoring it by moving the git pointer to the commit one earlier, refered by HEAD^ or HEAD^1
git push origin +HEAD^:branch
But if you have already pushed this commit, and others have pulled the branch. In this case, rewriting your branch's history is undesirable and you should instead revert this commit:
git revert <SHA-1>
git push origin branch
rand()
can be used to generate pseudo-random numbers in C++. In combination with RAND_MAX
and a little math, you can generate random numbers in any arbitrary interval you choose. This is sufficient for learning purposes and toy programs. If you need truly random numbers with normal distribution, you'll need to employ a more advanced method.
This will generate a number from 0.0 to 1.0, inclusive.
float r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
This will generate a number from 0.0 to some arbitrary float
, X
:
float r2 = static_cast <float> (rand()) / (static_cast <float> (RAND_MAX/X));
This will generate a number from some arbitrary LO
to some arbitrary HI
:
float r3 = LO + static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/(HI-LO)));
Note that the rand()
function will often not be sufficient if you need truly random numbers.
Before calling rand()
, you must first "seed" the random number generator by calling srand()
. This should be done once during your program's run -- not once every time you call rand()
. This is often done like this:
srand (static_cast <unsigned> (time(0)));
In order to call rand
or srand
you must #include <cstdlib>
.
In order to call time
, you must #include <ctime>
.
simple synchronous way with node:
let fs = require('fs')
let filename = "your-file.something"
let content = fs.readFileSync(process.cwd() + "/" + filename).toString()
console.log(content)
$("#closeLink").click(closeIt);
Let's say you want to call your function passing some args to it i.e., closeIt(1, false)
. Then, you should build an anonymous function and call closeIt
from it.
$("#closeLink").click(function() {
closeIt(1, false);
});
You can use android:weightSum="2"
on the parent layout combined with android:layout_height="1"
on the child layout.
<LinearLayout
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:weightSum="2"
>
<ImageView
android:layout_height="1"
android:layout_width="wrap_content" />
</LinearLayout>
Late to the party, but for anyone tasked with creating their own or wants to see how this would work, here's the function with an added bonus of rearranging the start-stop values based on the desired increment:
def RANGE(start, stop=None, increment=1):
if stop is None:
stop = start
start = 1
value_list = sorted([start, stop])
if increment == 0:
print('Error! Please enter nonzero increment value!')
else:
value_list = sorted([start, stop])
if increment < 0:
start = value_list[1]
stop = value_list[0]
while start >= stop:
worker = start
start += increment
yield worker
else:
start = value_list[0]
stop = value_list[1]
while start < stop:
worker = start
start += increment
yield worker
Negative increment:
for i in RANGE(1, 10, -1):
print(i)
Or, with start-stop reversed:
for i in RANGE(10, 1, -1):
print(i)
Output:
10
9
8
7
6
5
4
3
2
1
Regular increment:
for i in RANGE(1, 10):
print(i)
Output:
1
2
3
4
5
6
7
8
9
Zero increment:
for i in RANGE(1, 10, 0):
print(i)
Output:
'Error! Please enter nonzero increment value!'
You should be able to do something like this:
byte[] bitmap = GetYourImage();
using(Image image = Image.FromStream(new MemoryStream(bitmap)))
{
image.Save("output.jpg", ImageFormat.Jpeg); // Or Png
}
Look here for more info.
Hopefully this helps.
In your template, you have access to all the variables that are members of the current $scope
. So, tobedone
should be $scope.tobedone
, and then you can display it with {{tobedone}}
, or [[tobedone]]
in your case.
You can do this on a modern Windows machine without third party software. This method is reliable and it will handle data that includes quoted commas, quoted tab characters, CJK characters, etc.
1. Save from Excel
In Excel, save the data to file.txt
using the type Unicode Text (*.txt)
.
2. Start PowerShell
Run powershell
from the Start menu.
3. Load the file in PowerShell
$data = Import-Csv C:\path\to\file.txt -Delimiter "`t" -Encoding BigEndianUnicode
4. Save the data as CSV
$data | Export-Csv file.csv -Encoding UTF8 -NoTypeInformation
function getRemote() {
return $.ajax({
type: "GET",
url: remote_url,
async: false,
success: function (result) {
/* if result is a JSon object */
if (result.valid)
return true;
else
return false;
}
});
}
The following approach is the same as Helge Klein's, except that the popup closes automatically when you click anywhere outside the Popup (including the ToggleButton itself):
<ToggleButton x:Name="Btn" IsHitTestVisible="{Binding ElementName=Popup, Path=IsOpen, Mode=OneWay, Converter={local:BoolInverter}}">
<TextBlock Text="Click here for popup!"/>
</ToggleButton>
<Popup IsOpen="{Binding IsChecked, ElementName=Btn}" x:Name="Popup" StaysOpen="False">
<Border BorderBrush="Black" BorderThickness="1" Background="LightYellow">
<CheckBox Content="This is a popup"/>
</Border>
</Popup>
"BoolInverter" is used in the IsHitTestVisible binding so that when you click the ToggleButton again, the popup closes:
public class BoolInverter : MarkupExtension, IValueConverter
{
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is bool)
return !(bool)value;
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return Convert(value, targetType, parameter, culture);
}
}
...which shows the handy technique of combining IValueConverter and MarkupExtension in one.
I did discover one problem with this technique: WPF is buggy when two popups are on the screen at the same time. Specifically, if your toggle button is on the "overflow popup" in a toolbar, then there will be two popups open after you click it. You may then find that the second popup (your popup) will stay open when you click anywhere else on your window. At that point, closing the popup is difficult. The user cannot click the ToggleButton again to close the popup because IsHitTestVisible is false because the popup is open! In my app I had to use a few hacks to mitigate this problem, such as the following test on the main window, which says (in the voice of Louis Black) "if the popup is open and the user clicks somewhere outside the popup, close the friggin' popup.":
PreviewMouseDown += (s, e) =>
{
if (Popup.IsOpen)
{
Point p = e.GetPosition(Popup.Child);
if (!IsInRange(p.X, 0, ((FrameworkElement)Popup.Child).ActualWidth) ||
!IsInRange(p.Y, 0, ((FrameworkElement)Popup.Child).ActualHeight))
Popup.IsOpen = false;
}
};
// Elsewhere...
public static bool IsInRange(int num, int lo, int hi) =>
num >= lo && num <= hi;
Note that URI encoding is good for the query part, it's not good for the domain. The domain gets encoded using punycode. You need a library like URI.js to convert between a URI and IRI (Internationalized Resource Identifier).
This is correct if you plan on using the string later as a query string:
> encodeURIComponent("http://examplé.org/rosé?rosé=rosé")
'http%3A%2F%2Fexampl%C3%A9.org%2Fros%C3%A9%3Fros%C3%A9%3Dros%C3%A9'
If you don't want ASCII characters like /
, :
and ?
to be escaped, use encodeURI
instead:
> encodeURI("http://examplé.org/rosé?rosé=rosé")
'http://exampl%C3%A9.org/ros%C3%A9?ros%C3%A9=ros%C3%A9'
However, for other use-cases, you might need uri-js instead:
> var URI = require("uri-js");
undefined
> URI.serialize(URI.parse("http://examplé.org/rosé?rosé=rosé"))
'http://xn--exampl-gva.org/ros%C3%A9?ros%C3%A9=ros%C3%A9'
$('#baba option:first').attr('selected',true);
If you are using the Newtonsoft.Json library with ASP.NET to read/deserialize you can use comments in the JSON content:
//"name": "string"
//"id": int
or
/* This is a
comment example */
PS: Single-line comments are only supported with 6+ versions of Newtonsoft Json.
Additional note for people who can't think out of the box: I use the JSON format for basic settings in an ASP.NET web application I made. I read the file, convert it into the settings object with the Newtonsoft library and use it when necessary.
I prefer writing comments about each individual setting in the JSON file itself, and I really don't care about the integrity of the JSON format as long as the library I use is OK with it.
I think this is an 'easier to use/understand' way than creating a separate 'settings.README' file and explaining the settings in it.
If you have a problem with this kind of usage; sorry, the genie is out of the lamp. People would find other usages for JSON format, and there is nothing you can do about it.
Many hours spent to clarify what was that. Please, read this post to get the advanced .HTACCESS
codes and learn what they do.
You can use:
Header append Vary "Accept-Encoding"
#or
Header set Vary "Accept-Encoding"
I just found the solution. It is really very simple:
mDrawerToggle.setDrawerIndicatorEnabled(false);
Hope it will help you.
found the cause to be people opening the spreasheet on a machine accessed via Remote Desktop, and there being a difference in screen resolution between local and remote machines. This affects the controls available from the control toolbox, but yet to experience the issue using an old school forms button control, so my unsatisfactory answer is to use that.
console.log(decodeURI('abc=foo&def=%5Basf%5D&xyz=5')_x000D_
.split('&')_x000D_
.reduce((result, current) => {_x000D_
const [key, value] = current.split('=');_x000D_
_x000D_
result[key] = value;_x000D_
_x000D_
return result_x000D_
}, {}))
_x000D_
To check all ports:
netstat -lnp
To close an open port:
fuser -k port_no/tcp
Example:
fuser -k 8080/tcp
In both cases you can use the sudo
command if needed.
The trick is that you have to set it as position:fixed, but only after the user has scrolled past it.
This is done with something like this, attaching a handler to the window.scroll event
// Cache selectors outside callback for performance.
var $window = $(window),
$stickyEl = $('#the-sticky-div'),
elTop = $stickyEl.offset().top;
$window.scroll(function() {
$stickyEl.toggleClass('sticky', $window.scrollTop() > elTop);
});
This simply adds a sticky
CSS class when the page has scrolled past it, and removes the class when it's back up.
And the CSS class looks like this
#the-sticky-div.sticky {
position: fixed;
top: 0;
}
EDIT- Modified code to cache jQuery objects, faster now.
You are pointing your JAVA_HOME to the JRE which is the Java Runtime Environment. The runtime environment doesn't have a java compiler in its bin folder. You should download the JDK which is the Java Development Kit. Once you've installed that, you can see in your bin folder that there's a file called javac.exe. That's your compiler.
If the new domain you are redirecting your old site to is on a diffrent host, you can simply use a Redirect
Redirect 301 / http://newdomain.com
This will redirect all requests from olddomain
to the newdomain
.
Redirect
directive will not work or may cause a Redirect loop
if your newdomain and olddomain both are on same host, in that case you'll need to use mod-rewrite
to redirect based on the requested host header.
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.)?olddomain\.com$
RewriteRule ^ http://newdomain.com%{REQUEST_URI} [NE,L,R]
If jQuery's error handler is being called and the XHR object contains "parser error", that's probably a parser error coming back from the server.
Is your multiple result scenario when you call the service without a parameter, but it's breaking when you try to supply a parameter to retrieve the single record?
What backend are you returning this from?
On ASMX services, for example, that's often the case when parameters are supplied to jQuery as a JSON object instead of a JSON string. If you provide jQuery an actual JSON object for its "data" parameter, it will serialize that into standard & delimited k,v pairs instead of sending it as JSON.
I followed this simple steps to do this stuff.
DialogFragmentCallbackInterface
with some method like callBackMethod(Object data)
. Which you would calling to pass data.DialogFragmentCallbackInterface
interface in your fragment like MyFragment implements DialogFragmentCallbackInterface
At time of DialogFragment
creation set your invoking fragment MyFragment
as target fragment who created DialogFragment
use myDialogFragment.setTargetFragment(this, 0)
check setTargetFragment (Fragment fragment, int requestCode)
MyDialogFragment dialogFrag = new MyDialogFragment();
dialogFrag.setTargetFragment(this, 1);
Get your target fragment object into your DialogFragment
by calling getTargetFragment()
and cast it to DialogFragmentCallbackInterface
.Now you can use this interface to send data to your fragment.
DialogFragmentCallbackInterface callback =
(DialogFragmentCallbackInterface) getTargetFragment();
callback.callBackMethod(Object data);
That's it all done! just make sure you have implemented this interface in your fragment.
This was previously asked on R-Help, so that's worth reviewing.
One suggestion there was to use readChar()
and then do string manipulation on the result with strsplit()
and substr()
. You can see the logic involved in readChar is much less than read.table.
I don't know if memory is an issue here, but you might also want to take a look at the HadoopStreaming package. This uses Hadoop, which is a MapReduce framework designed for dealing with large data sets. For this, you would use the hsTableReader function. This is an example (but it has a learning curve to learn Hadoop):
str <- "key1\t3.9\nkey1\t8.9\nkey1\t1.2\nkey1\t3.9\nkey1\t8.9\nkey1\t1.2\nkey2\t9.9\nkey2\"
cat(str)
cols = list(key='',val=0)
con <- textConnection(str, open = "r")
hsTableReader(con,cols,chunkSize=6,FUN=print,ignoreKey=TRUE)
close(con)
The basic idea here is to break the data import into chunks. You could even go so far as to use one of the parallel frameworks (e.g. snow) and run the data import in parallel by segmenting the file, but most likely for large data sets that won't help since you will run into memory constraints, which is why map-reduce is a better approach.
You cannot select a row like that. You have to specify a field whose values will be 3
Here is a query that will work, if the field you are comparing against is id
select * from customer where `id` = 3
You need to set the location
header as follows:
header('Location: http://www.example.com/');
Replacing http://www.example.com
of course with the url of your landing page.
Add this where you have finished logging the user in.
Note: When redirecting the user will be immediately redirected so you're message probably won't display.
Additionally, you need to move your PHP code to the top of the file for this solution to work.
On another side note, please see my comment above regarding the use of the deprecated mysql
statements and consider using the newer, safer and improved mysqli
or PDO
statements.
You can use the GetServices
method of ServiceController
class to get an array of all the services. Then, find your service by checking the ServiceName
property of each service. When you've found your service, call the Start
method to start it.
You should also check the Status
property to see what state it is already in before calling start (it may be running, paused, stopped, etc..).
Would recommend using svg for graphical elements. While using css to style your elements.
#box {_x000D_
fill: orange;_x000D_
stroke: black;_x000D_
}
_x000D_
<svg>_x000D_
<rect id="box" x="0" y="0" width="50" height="50"/>_x000D_
</svg>
_x000D_
Something like this in c# would probably do the job. Just make sure you are passing consistent units (If one point is in meters, make sure the second is also in meters)
private static double GetDistance(double x1, double y1, double x2, double y2)
{
return Math.Sqrt(Math.Pow((x2 - x1), 2) + Math.Pow((y2 - y1), 2));
}
Called like so:
double distance = GetDistance(x1, y1, x2, y2)
if(distance <= 5)
{
//Do stuff
}
The use of file.exists() to test for the existence of the directory is a problem in the original post. If subDir included the name of an existing file (rather than just a path), file.exists() would return TRUE, but the call to setwd() would fail because you can't set the working directory to point at a file.
I would recommend the use of file_test(op="-d", subDir), which will return "TRUE" if subDir is an existing directory, but FALSE if subDir is an existing file or a non-existent file or directory. Similarly, checking for a file can be accomplished with op="-f".
Additionally, as described in another comment, the working directory is part of the R environment and should be controlled by the user, not a script. Scripts should, ideally, not change the R environment. To address this problem, I might use options() to store a globally available directory where I wanted all of my output.
So, consider the following solution, where someUniqueTag is just a programmer-defined prefix for the option name, which makes it unlikely that an option with the same name already exists. (For instance, if you were developing a package called "filer", you might use filer.mainDir and filer.subDir).
The following code would be used to set options that are available for use later in other scripts (thus avoiding the use of setwd() in a script), and to create the folder if necessary:
mainDir = "c:/path/to/main/dir"
subDir = "outputDirectory"
options(someUniqueTag.mainDir = mainDir)
options(someUniqueTag.subDir = "subDir")
if (!file_test("-d", file.path(mainDir, subDir)){
if(file_test("-f", file.path(mainDir, subDir)) {
stop("Path can't be created because a file with that name already exists.")
} else {
dir.create(file.path(mainDir, subDir))
}
}
Then, in any subsequent script that needed to manipulate a file in subDir, you might use something like:
mainDir = getOption(someUniqueTag.mainDir)
subDir = getOption(someUniqueTag.subDir)
filename = "fileToBeCreated.txt"
file.create(file.path(mainDir, subDir, filename))
This solution leaves the working directory under the control of the user.
I don't think WPF supports what you are trying to achieve i.e. assigning method to a button using method's name or btn1.Click = "btn1_Click". You will have to use approach suggested in above answers i.e. register button click event with appropriate method btn1.Click += btn1_Click;
You can implement your own Iterator. Your iterator could be constructed to wrap the Iterator returned by the List, or you could keep a cursor and use the List's get(int index) method. You just have to add logic to your Iterator's next method AND the hasNext method to take into account your filtering criteria. You will also have to decide if your iterator will support the remove operation.
I had a PFX file and needed to create KEY file for NGINX, so I did this:
openssl pkcs12 -in file.pfx -out file.key -nocerts -nodes
Then I had to edit the KEY file and remove all content up to -----BEGIN PRIVATE KEY-----
. After that NGINX accepted the KEY file.
Step1: copy all the rpm pkg in given locations
Step2: if createrepo is not already installed, as it will not be by default, install it.
[root@pavangildamysql1 8.0.11_rhel7]# yum install createrepo
Step3: create repository metedata and give below permission
[root@pavangildamysql1 8.0.11_rhel7]# chown -R root.root /scratch/PVN/8.0.11_rhel7
[root@pavangildamysql1 8.0.11_rhel7]# createrepo /scratch/PVN/8.0.11_rhel7
Spawning worker 0 with 3 pkgs
Spawning worker 1 with 3 pkgs
Spawning worker 2 with 3 pkgs
Spawning worker 3 with 2 pkgs
Workers Finished
Saving Primary metadata
Saving file lists metadata
Saving other metadata
Generating sqlite DBs
Sqlite DBs complete
[root@pavangildamysql1 8.0.11_rhel7]# chmod -R o-w+r /scratch/PVN/8.0.11_rhel7
Step4: Create repository file with following contents at /etc/yum.repos.d/mysql.repo
[local]
name=My Awesome Repo
baseurl=file:///scratch/PVN/8.0.11_rhel7
enabled=1
gpgcheck=0
Step5 Run this command to install
[root@pavangildamysql1 local]# yum --nogpgcheck localinstall mysql-commercial-server-8.0.11-1.1.el7.x86_64.rpm
You can use jQuery's css
function to test the CSS properties, eg. if ($('node').css('display') == 'block')
.
Colin is right, that there is no explicit event that gets fired when a specific CSS property gets changed. But you may be able to flip it around, and trigger an event that sets the display, and whatever else.
Also consider using adding CSS classes to get the behavior you want. Often you can add a class to a containing element, and use CSS to affect all elements. I often slap a class onto the body element to indicate that an AJAX response is pending. Then I can use CSS selectors to get the display I want.
Not sure if this is what you're looking for.
By failing to provide a decent solution, you just end up with something worse IMHO.
The common work around is as follows.
T[] ts = new T[n];
is replaced with (assuming T extends Object and not another class)
T[] ts = (T[]) new Object[n];
I prefer the first example, however more academic types seem to prefer the second, or just prefer not to think about it.
Most of the examples of why you can't just use an Object[] equally apply to List or Collection (which are supported), so I see them as very poor arguments.
Note: this is one of the reasons the Collections library itself doesn't compile without warnings. If you this use-case cannot be supported without warnings, something is fundamentally broken with the generics model IMHO.
You could use a named function expression (in this case the function is named abc
), like so:
let click = 0;
canvas.addEventListener('click', function abc(event) {
click++;
if (click >= 50) {
// remove event listener function `abc`
canvas.removeEventListener('click', abc);
}
// More code here ...
}
Quick and dirty working example: http://jsfiddle.net/8qvdmLz5/2/.
More information about named function expressions: http://kangax.github.io/nfe/.
Just created local project (with vagrant) and it was working perfectly when accessed over ip address. Then I added some_name.test to hosts file and tried accessing it that way, but I was getting "bad request - 400" all the time. Wasted hours until I figured out that just changing domain name to some-name.test solves the problem. So at least locally on Mac OS it's not working.
In addition to @csgillespie's answer, segments
is also vectorised to help with this sort of thing:
plot (x, y, ylim=c(0,6))
segments(x,y-sd,x,y+sd)
epsilon <- 0.02
segments(x-epsilon,y-sd,x+epsilon,y-sd)
segments(x-epsilon,y+sd,x+epsilon,y+sd)
String text = "Example";
EditText edtText = (EditText) findViewById(R.id.edtText);
edtText.setText(text);
Check it out EditText
accept only String values if necessary convert it to string.
If int, double, long value, do:
String.value(value);
You could try the fnmatch module, it's got a shell-like wildcard syntax
or can use regular expressions
import re
A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:
So we need three divs:
First let us define the CSS:
#hider
{
position:absolute;
top: 0%;
left: 0%;
width:1600px;
height:2000px;
margin-top: -800px; /*set to a negative number 1/2 of your height*/
margin-left: -500px; /*set to a negative number 1/2 of your width*/
/*
z- index must be lower than pop up box
*/
z-index: 99;
background-color:Black;
//for transparency
opacity:0.6;
}
#popup_box
{
position:absolute;
top: 50%;
left: 50%;
width:10em;
height:10em;
margin-top: -5em; /*set to a negative number 1/2 of your height*/
margin-left: -5em; /*set to a negative number 1/2 of your width*/
border: 1px solid #ccc;
border: 2px solid black;
z-index:100;
}
It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
Here comes the java Script:
$(document).ready(function () {
//hide hider and popup_box
$("#hider").hide();
$("#popup_box").hide();
//on click show the hider div and the message
$("#showpopup").click(function () {
$("#hider").fadeIn("slow");
$('#popup_box').fadeIn("slow");
});
//on click hide the message and the
$("#buttonClose").click(function () {
$("#hider").fadeOut("slow");
$('#popup_box').fadeOut("slow");
});
});
And finally the HTML:
<div id="hider"></div>
<div id="popup_box">
Message<br />
<a id="buttonClose">Close</a>
</div>
<div id="content">
Page's main content.<br />
<a id="showpopup">ClickMe</a>
</div>
I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.
What about this:
double? amount = string.IsNullOrEmpty(strAmount) ? (double?)null : Convert.ToDouble(strAmount);
Of course, this doesn't take into account the convert failing.
This is the same problem as joining together an array with commas. This version correctly produces spaces only between characters, and avoids an unnecessary branch within the loop:
String input = "Hello";
StringBuilder result = new StringBuilder();
if (input.length() > 0) {
result.append(input.charAt(0));
for (int i = 1; i < input.length(); i++) {
result.append(" ");
result.append(input.charAt(i));
}
}
Running commands periodically without cron is possible when we go with while
.
As a command:
while true ; do command ; sleep 100 ; done &
[ ex: # while true; do echo `date` ; sleep 2 ; done & ]
Example:
while true
do echo "Hello World"
sleep 100
done &
Do not forget the last &
as it will put your loop in the background. But you need to find the process id with command "ps -ef | grep your_script" then you need to kill it. So kindly add the '&' when you running the script.
# ./while_check.sh &
Here is the same loop as a script. Create file "while_check.sh" and put this in it:
#!/bin/bash
while true; do
echo "Hello World" # Substitute this line for whatever command you want.
sleep 100
done
Then run it by typing bash ./while_check.sh &
Use sortedWith
to sort a list with Comparator
.
You can then construct a comparator using several ways:
In the year 2020 / 2021 it is even easier with Array.from
to 'convert' from a array-like nodes to an actual array, and then using .map
to loop through the resulting array.
The code is as simple as the follows:
Array.from(tableFields.children).map((child)=>console.log(child))
max(number_one, number_two)
One line code to detect the browser.
If the browser is IE or Edge, It will return true;
let isIE = /edge|msie\s|trident\//i.test(window.navigator.userAgent)
You need to define border-width:1px
Your code should read:
$(this).css({"border-color": "#C1E0FF",
"border-width":"1px",
"border-style":"solid"});
You should ideally use a class and addClass/removeClass
$(this).addClass('borderClass');
$(this).removeClass('borderClass');
and in your CSS:
.borderClass{
border-color: #C1E0FF;
border-width:1px;
border-style: solid;
/** OR USE INLINE
border: 1px solid #C1E0FF;
**/
}
jsfiddle working example: http://jsfiddle.net/gorelative/tVbvF/\
jsfiddle with animate: http://jsfiddle.net/gorelative/j9Xxa/
This just gives you an example of how it could work, you should get the idea.. There are better ways of doing this most likely.. like using a toggle()
For python 3
tup = (1,2,3)
print("this is a tuple %s" % str(tup))
You can try this force-download script. Even if you don't use it, it'll probably point you in the right direction:
<?php
$filename = $_GET['file'];
// required for IE, otherwise Content-disposition is ignored
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
// addition by Jorg Weske
$file_extension = strtolower(substr(strrchr($filename,"."),1));
if( $filename == "" )
{
echo "<html><title>eLouai's Download Script</title><body>ERROR: download file NOT SPECIFIED. USE force-download.php?file=filepath</body></html>";
exit;
} elseif ( ! file_exists( $filename ) )
{
echo "<html><title>eLouai's Download Script</title><body>ERROR: File not found. USE force-download.php?file=filepath</body></html>";
exit;
};
switch( $file_extension )
{
case "pdf": $ctype="application/pdf"; break;
case "exe": $ctype="application/octet-stream"; break;
case "zip": $ctype="application/zip"; break;
case "doc": $ctype="application/msword"; break;
case "xls": $ctype="application/vnd.ms-excel"; break;
case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
default: $ctype="application/octet-stream";
}
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: $ctype");
// change, added quotes to allow spaces in filenames, by Rajkumar Singh
header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile("$filename");
exit();
img {_x000D_
max-width: 80px; /* Also works with percentage value like 100% */_x000D_
height: auto;_x000D_
}
_x000D_
<p>This image is originally 400x400 pixels, but should get resized by the CSS:</p>_x000D_
<img width="400" height="400" src="https://i.stack.imgur.com/aEEkn.png">_x000D_
_x000D_
<p>Let's say the author of the HTML deliberately wants_x000D_
the height to be half the value of the width,_x000D_
this CSS will ignore the HTML author's wishes, which may or may not be what you want:_x000D_
</p>_x000D_
<img width="400" height="200" src="https://i.stack.imgur.com/aEEkn.png">
_x000D_
I recently had this "System.Data.OleDb.OleDbException (0x80004005): External table is not in the expected format." error occur. I was relying on Microsoft Access 2010 Runtime. Prior to the update that was automatically installed on my server on December 12th 2018 my C# code ran fine using Microsoft.ACE.OLEDB.12.0 provider. After the update from December 12th 2018 was installed I started to get the “External table is not in the expected format" in my log file.
I ditched the Microsoft Access 2010 Runtime and installed the Microsoft Access 2013 Runtime and my C# code started to work again with no "System.Data.OleDb.OleDbException (0x80004005): External table is not in the expected format." errors.
2013 version that fixed this error for me https://www.microsoft.com/en-us/download/confirmation.aspx?id=39358
2010 version that worked for me prior to the update that was automatically installed on my server on December 12th. https://www.microsoft.com/en-us/download/confirmation.aspx?id=10910 https://www.microsoft.com/en-us/download/confirmation.aspx?id=10910
I also had this error occur last month in an automated process. The C# code ran fine when I ran it debugging. I found that the service account running the code also needed permissions to the C:\Windows\Temp folder.
You need to install the entire ruby and not just the minimum package. The correct command to use is:
sudo apt install ruby-full
The following command will also not install a complete ruby:
sudo apt-get install ruby2.3-dev
@echo off
set workdir={your working dir. for example - C:\work } set iplist=%workdir%\IP-list.txt
setlocal enabledelayedexpansion
set OUTPUT_FILE=%workdir%\result.csv
>nul copy nul %OUTPUT_FILE%
echo HOSTNAME,LONGNAME,IPADDRESS,STATE >%OUTPUT_FILE%
for /f %%i in (%iplist%) do (
set SERVER_ADDRESS_I=UNRESOLVED
set SERVER_ADDRESS_L=UNRESOLVED
for /f "tokens=1,2,3" %%x in ('ping -a -n 1 %%i ^&^& echo SERVER_IS_UP') do (
if %%x==Pinging set SERVER_ADDRESS_L=%%y
if %%x==Pinging set SERVER_ADDRESS_I=%%z
if %%x==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
)
echo %%i [!SERVER_ADDRESS_L::=!] !SERVER_ADDRESS_I::=! is !SERVER_STATE!
echo %%i,!SERVER_ADDRESS_L::=!,!SERVER_ADDRESS_I::=!,!SERVER_STATE! >>%OUTPUT_FILE%
)
Since I think you are new with Python, lets do the long way, iterate thru your list using for loop and multiply and append each element to a new list.
using for loop
lst = [5, 20 ,15]
product = []
for i in lst:
product.append(i*5)
print product
using list comprehension, this is also same as using for-loop but more 'pythonic'
lst = [5, 20 ,15]
prod = [i * 5 for i in lst]
print prod
To get the value:
$query = $this->db->query("YOUR QUERY");
Then, for single row from(in controller):
$query1 = $query->row();
$data['product'] = $query1;
In view, you can use your own code (above code)
For completeness, Pandas also has a period_range
function for timestamps that are out of bounds:
import pandas as pd
pd.period_range(start='1/1/1626', end='1/08/1627', freq='D')
res/
mipmap-mdpi/ic_launcher.png (48x48 pixels)
mipmap-hdpi/ic_launcher.png (72x72)
mipmap-xhdpi/ic_launcher.png (96x96)
mipmap-xxhdpi/ic_launcher.png (144x144)
mipmap-xxxhdpi/ic_launcher.png (192x192)
MipMap for app icon for launcher
http://android-developers.blogspot.co.uk/2014/10/getting-your-apps-ready-for-nexus-6-and.html
https://androidbycode.wordpress.com/2015/02/14/goodbye-launcher-drawables-hello-mipmaps/
Add this to the scope - https://www.googleapis.com/auth/userinfo.profile
And after authorization is done, get the information from - https://www.googleapis.com/oauth2/v1/userinfo?alt=json
It has loads of stuff - including name, public profile url, gender, photo etc.
Try the UniversalIndentGUI plugin for Notepad++. It re-indents code based on some parameters. It worked well for me.
Just use floatval()
.
E.g.:
$var = '122.34343';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 122.34343
And in case you wonder doubleval()
is just an alias for floatval()
.
And as the other say, in a financial application, float values are critical as these are not precise enough. E.g. adding two floats could result in something like 12.30000000001
and this error could propagate.
you can use
empty($result)
to check if the main array is empty or not.
But since you have a SimpleXMLElement object, you need to query the object if it is empty or not. See http://www.php.net/manual/en/simplexmlelement.count.php
ex:
if (empty($result) || !isset($result['Tags'])) {
return false;
}
if ( !($result['Tags'] instanceof SimpleXMLElement)) {
return false;
}
return ($result['Tags']->count());
Assuming you're using jQuery..
var input = '19 51 2.108997\n20 47 2.1089';
var lines = input.split('\n');
var output = '';
$.each(lines, function(key, line) {
var parts = line.split(' ');
output += '<span>' + parts[0] + ' ' + parts[1] + '</span><span>' + parts[2] + '</span>\n';
});
$(output).appendTo('body');
Yes, it is possible to do with out rebinding by implementing INotifyPropertyChanged Interface.
Pretty Simple example is available here,
http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx
Very easy if you are already using a statelessWidget checkOut my code
class _MyThirdPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Understanding Material-Cards'),
),
body: SingleChildScrollView(
child: Column(
children: <Widget>[
_buildStack(),
_buildCard(),
SingleCard(),
_inkwellCard()
],
)),
);
}
}
First things is this is only for advanced developers persons Who all are now beginner to php dont use this function if you are using the huge project in core php use this function
function displayAllRecords($serverName, $userName, $password, $databaseName,$sqlQuery='')
{
$databaseConnectionQuery = mysqli_connect($serverName, $userName, $password, $databaseName);
if($databaseConnectionQuery === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
return false;
}
$resultQuery = mysqli_query($databaseConnectionQuery,$sqlQuery);
$fetchFields = mysqli_fetch_fields($resultQuery);
$fetchValues = mysqli_fetch_fields($resultQuery);
if (mysqli_num_rows($resultQuery) > 0)
{
echo "<table class='table'>";
echo "<tr>";
foreach ($fetchFields as $fetchedField)
{
echo "<td>";
echo "<b>" . $fetchedField->name . "<b></a>";
echo "</td>";
}
echo "</tr>";
while($totalRows = mysqli_fetch_array($resultQuery))
{
echo "<tr>";
for($eachRecord = 0; $eachRecord < count($fetchValues);$eachRecord++)
{
echo "<td>";
echo $totalRows[$eachRecord];
echo "</td>";
}
echo "<td><a href=''><button>Edit</button></a></td>";
echo "<td><a href=''><button>Delete</button></a></td>";
echo "</tr>";
}
echo "</table>";
}
else
{
echo "No Records Found in";
}
}
All set now Pass the arguments as For Example
$queryStatment = "SELECT * From USERS "; $testing = displayAllRecords('localhost','root','root@123','email',$queryStatment); echo $testing;
Here
localhost
indicates Name of the host
,
root
indicates the username for database
root@123
indicates the password for the database
$queryStatment
for generating Query
hope it helps
Any command that takes references as arguments will accept the --all
option documented in the man page for git rev-list
as follows:
--all
Pretend as if all the refs in $GIT_DIR/refs/ are listed on the
command line as <commit>.
So for instance git log -Sstring --all
will display all commits that mention string
and that are accessible from a branch or from a tag (I'm assuming that your dangling commits are at least named with a tag).
The solution takes two steps!
First, complete the user, domain, and proxy fields in cntlm.ini
. The username and domain should probably be whatever you use to log in to Windows at your office, eg.
Username employee1730
Domain corporate
Proxy proxy.infosys.corp:8080
Then test cntlm with a command such as
cntlm.exe -c cntlm.ini -I -M http://www.bbc.co.uk
It will ask for your password (again whatever you use to log in to Windows_). Hopefully it will print 'http 200 ok' somewhere, and print your some cryptic tokens authentication information. Now add these to cntlm.ini
, eg:
Auth NTLM
PassNT A2A7104B1CE00000000000000007E1E1
PassLM C66000000000000000000000008060C8
Finally, set the http_proxy
environment variable in Windows (assuming you didn't change with the Listen
field which by default is set to 3128
) to the following
http://localhost:3128
I don't know the real reason but Maven pushes developers to install all libraries (custom too) into some maven repositories, so scope:system
is not well liked, A simple workaround is to use maven-install-plugin
follow the usage:
write your dependency in this way
<dependency>
<groupId>com.mylib</groupId>
<artifactId>mylib-core</artifactId>
<version>0.0.1</version>
</dependency>
then, add maven-install-plugin
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
<executions>
<execution>
<id>install-external</id>
<phase>clean</phase>
<configuration>
<file>${basedir}/lib/mylib-core-0.0.1.jar</file>
<repositoryLayout>default</repositoryLayout>
<groupId>com.mylib</groupId>
<artifactId>mylib-core</artifactId>
<version>0.0.1</version>
<packaging>jar</packaging>
<generatePom>true</generatePom>
</configuration>
<goals>
<goal>install-file</goal>
</goals>
</execution>
</executions>
</plugin>
pay attention to phase:clean
, to install your custom library into your repository, you have to run mvn clean
and then mvn install
I had an issue for integers while wanting consistent formatting.
A rewrite for completeness:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
// floating point formatting example
cout << fixed << setprecision(2) << 122.345 << endl;
// Output: 122.34
// integer formatting example
cout << fixed << setprecision(2) << double(122) << endl;
// Output: 122.00
}
Try code below:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("package_name", "Class_name"));
if (intent.resolveActivity(getPackageManager()) != null)
{
startActivity(intent);
}
Get All Parent Iframe functions and HTML
var parent = $(window.frameElement).parent();
//alert(parent+"TESTING");
var parentElement=window.frameElement.parentElement.parentElement.parentElement.parentElement;
var Ifram=parentElement.children;
var GetUframClass=Ifram[9].ownerDocument.activeElement.className;
var Decision_URLLl=parentElement.ownerDocument.activeElement.contentDocument.URL;
Old question but worth adding an answer if using .NET Core 3.0 or later. JSON serialization/deserialization is built into the framework (System.Text.Json), so you don't have to use third party libraries any more. Here's an example based off the top answer given by @Icarus
using System;
using System.Collections.Generic;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var json = "[{\"Name\":\"John Smith\", \"Age\":35}, {\"Name\":\"Pablo Perez\", \"Age\":34}]";
// use the built in Json deserializer to convert the string to a list of Person objects
var people = System.Text.Json.JsonSerializer.Deserialize<List<Person>>(json);
foreach (var person in people)
{
Console.WriteLine(person.Name + " is " + person.Age + " years old.");
}
}
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
}
}
The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:
argument_list ::= positional_arguments ["," starred_and_keywords]
["," keywords_arguments]
| starred_and_keywords ["," keywords_arguments]
| keywords_arguments
Specifically, a keyword argument looks like this: tag='insider trading!'
while a positional argument looks like this: ..., exchange, ...
. The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.
Also, when an argument has a default value, such as price=None
, that means you don't have to provide it. If you don't provide it, it will use the default value instead.
To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity)
# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)
# Some positional, some keyword (all keywords at end):
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity, tag='insider trading!')
You could use jQuery to add an event listener on the document DOM.
$(document).on("click", function () {_x000D_
console.log('clicked');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
String.equals()
requires invoking instanceof
operator while compareTo()
requires not. My colleague has noted large performance drop-down caused by excessive numbers of instanceof
calls in equals()
method, however my test has proved compareTo()
to be only slightly faster.
I was using, however, Java 1.6. On other versions (or other JDK vendors) the difference could be larger.
The test compared each-to-each string in 1000 element arrays, repeated 10 times.
Bit more detail:
private void Form1_Load(object sender, EventArgs e)
{
Timer MyTimer = new Timer();
MyTimer.Interval = (45 * 60 * 1000); // 45 mins
MyTimer.Tick += new EventHandler(MyTimer_Tick);
MyTimer.Start();
}
private void MyTimer_Tick(object sender, EventArgs e)
{
MessageBox.Show("The form will now be closed.", "Time Elapsed");
this.Close();
}
As others have mentioned: CSS-3 says that you can use the rgba(...)
syntax to specify a border color with an opacity (alpha) value.
here's a quick example if you'd like to check it.
It works in Safari and Chrome (probably works in all webkit browsers).
It works in Firefox
I doubt that it works at all in IE, but I suspect that there is some filter or behavior that will make it work.
There's also this stackoverflow post, which suggests some other issues--namely, that the border renders on-top-of any background color (or background image) that you've specified; thus limiting the usefulness of border alpha in many cases.
I used MP4Box to decode the atom tags in the mp4. (MP4Box -v myfile.mp4) I also used ffmpeg to convert the mp41 to mp42. After comparing the differences and experimenting, I found that IE11 did not like that my original mp4 had two avC1 atoms inside stsd.
After deleting the duplicate avC1 in my original mp41 mp4, IE11 would play the mp4.
In the terminal: For Xcode 9.x and above
$ open /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app
For Xcode-beta 9.x and above
$ open /Applications/Xcode-beta.app/Contents/Developer/Applications/Simulator.app
As it appears you have the values as text, and not the numeric True/False, then you can use either COUNTIF
or SUMPRODUCT
=IF(SUMPRODUCT(--(A2:D2="False")),"False","True")
=IF(COUNTIF(A3:D3,"False*"),"False","True")
XDocument xdoc = XDocument.Load("data.xml");
var lv1s = xdoc.Root.Descendants("level1");
var lvs = lv1s.SelectMany(l=>
new string[]{ l.Attribute("name").Value }
.Union(
l.Descendants("level2")
.Select(l2=>" " + l2.Attribute("name").Value)
)
);
foreach (var lv in lvs)
{
result.AppendLine(lv);
}
Ps. You have to use .Root on any of these versions.
I think the hash-value is only used client-side, so you can't get it with php.
you could redirect it with javascript to php though.
As suggested in an earlier answer, we need to include two additional files - jquery.fileupload-process.js
and then jquery.fileupload-validate.js
However as I need to perform some additional ajax calls while adding a file, I am subscribing to the fileuploadadd
event to perform those calls. Regarding such a usage the author of this plugin suggested the following
Please have a look here: https://github.com/blueimp/jQuery-File-Upload/wiki/Options#wiki-callback-options
Adding additional event listeners via bind (or on method with jQuery 1.7+) method is the preferred option to preserve callback settings by the jQuery File Upload UI version.
Alternatively, you can also simply start the processing in your own callback, like this: https://github.com/blueimp/jQuery-File-Upload/blob/master/js/jquery.fileupload-process.js#L50
Using the combination of the two suggested options, the following code works perfectly for me
$fileInput.fileupload({
url: 'upload_url',
type: 'POST',
dataType: 'json',
autoUpload: false,
disableValidation: false,
maxFileSize: 1024 * 1024,
messages: {
maxFileSize: 'File exceeds maximum allowed size of 1MB',
}
});
$fileInput.on('fileuploadadd', function(evt, data) {
var $this = $(this);
var validation = data.process(function () {
return $this.fileupload('process', data);
});
validation.done(function() {
makeAjaxCall('some_other_url', { fileName: data.files[0].name, fileSizeInBytes: data.files[0].size })
.done(function(resp) {
data.formData = data.formData || {};
data.formData.someData = resp.SomeData;
data.submit();
});
});
validation.fail(function(data) {
console.log('Upload error: ' + data.files[0].error);
});
});
If you don't care about the actual key, a concise way to iterate over all the Map's values would be to use its values()
method
Map<String, List<String>> myMap;
for ( List<String> stringList : myMap.values() ) {
for ( String myString : stringList ) {
// process the string here
}
}
The values()
method is part of the Map interface and returns a Collection view of the values in the map.
I think you are a bit confused. You should read a good tutorial/book on pointers.
This tutorial is very good for starters(clearly explains what &
and *
are). And yeah don't forget to read the book Pointers in C by Kenneth Reek.
The difference between &
and *
is very clear.
Example:
#include <stdio.h>
int main(){
int x, *p;
p = &x; /* initialise pointer(take the address of x) */
*p = 0; /* set x to zero */
printf("x is %d\n", x);
printf("*p is %d\n", *p);
*p += 1; /* increment what p points to i.e x */
printf("x is %d\n", x);
(*p)++; /* increment what p points to i.e x */
printf("x is %d\n", x);
return 0;
}
Since all answers are using COUNT()
, you can also use MAX()
to get the number of columns in a specific table as
SELECT MAX(ORDINAL_POSITION) NumberOfColumnsInTable
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_CATALOG = 'YourDatabaseNameHere'
AND
TABLE_SCHEMA = 'YourSchemaNameHere'
AND
TABLE_NAME = 'YourTableNameHere';
a[len(a):]
- This gets you the length of a to the end. It selects a range. If you reverse a[:len(a)]
it will get you the beginning to whatever is len(a)
.
ul {
margin:0;
list-style-type: none;
}
li:before { content: "- ";}
If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".
Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".
All tables within bootstrap stretch according to the container they're in. You can put your tables inside a .span
element to control the size. This SO Question may help you out
Those solutions mentioned change how your program work.
You can off course put #if DEBUG
and #endif
around the Console calls, but if you really want to prevent the window from closing only on your dev machine under Visual Studio or if VS isn't running only if you explicitly configure it, and you don't want the annoying 'Press any key to exit...'
when running from the command line, the way to go is to use the System.Diagnostics.Debugger
API's.
If you only want that to work in DEBUG
, simply wrap this code in a [Conditional("DEBUG")] void BreakConditional()
method.
// Test some configuration option or another
bool launch;
var env = Environment.GetEnvironmentVariable("LAUNCH_DEBUGGER_IF_NOT_ATTACHED");
if (!bool.TryParse(env, out launch))
launch = false;
// Break either if a debugger is already attached, or if configured to launch
if (launch || Debugger.IsAttached) {
if (Debugger.IsAttached || Debugger.Launch())
Debugger.Break();
}
This also works to debug programs that need elevated privileges, or that need to be able to elevate themselves.
From Microsoft documentation:
PAGEIOLATCH_SH
Occurs when a task is waiting on a latch for a buffer that is in an
I/O
request. The latch request is in Shared mode. Long waits may indicate problems with the disk subsystem.
In practice, this almost always happens due to large scans over big tables. It almost never happens in queries that use indexes efficiently.
If your query is like this:
Select * from <table> where <col1> = <value> order by <PrimaryKey>
, check that you have a composite index on (col1, col_primary_key)
.
If you don't have one, then you'll need either a full INDEX SCAN
if the PRIMARY KEY
is chosen, or a SORT
if an index on col1
is chosen.
Both of them are very disk I/O
consuming operations on large tables.
For the current branch, here are two good choices:
% git rev-parse --abbrev-ref --symbolic-full-name @{u}
origin/mainline
or
% git for-each-ref --format='%(upstream:short)' $(git symbolic-ref -q HEAD)
origin/mainline
That answer is also here, to a slightly different question which was (wrongly) marked as a duplicate.
There's a great blog post on this here:
http://www.kylejlarson.com/blog/2011/fixed-elements-and-scrolling-divs-in-ios-5/
Along with a demo here:
http://www.kylejlarson.com/files/iosdemo/
In summary, you can use the following on a div containing your main content:
.scrollable {
position: absolute;
top: 50px;
left: 0;
right: 0;
bottom: 0;
overflow: scroll;
-webkit-overflow-scrolling: touch;
}
The problem I think you're describing is when you try to scroll up within a div that is already at the top - it then scrolls up the page instead of up the div and causes a bounce effect at the top of the page. I think your question is asking how to get rid of this?
In order to fix this, the author suggests that you use ScrollFix to auto increase the height of scrollable divs.
It's also worth noting that you can use the following to prevent the user from scrolling up e.g. in a navigation element:
document.addEventListener('touchmove', function(event) {
if(event.target.parentNode.className.indexOf('noBounce') != -1
|| event.target.className.indexOf('noBounce') != -1 ) {
event.preventDefault(); }
}, false);
Unfortunately there are still some issues with ScrollFix (e.g. when using form fields), but the issues list on ScrollFix is a good place to look for alternatives. Some alternative approaches are discussed in this issue.
Other alternatives, also mentioned in the blog post, are Scrollability and iScroll
maybe this plugin may be useful: http://www.farinspace.com/jquery-image-preload-plugin/
yu have to install the correct version for your computer 32 or 63 bits thats all
try this.
^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$
you can test regular expression at http://www.regular-expressions.info/javascriptexample.html easily.
Is the site's HTML valid? Run it through w3c validation service.
Yes, just override the printMe()
method:
class Son extends Dad {
public static final String me = "son";
@Override
public void printMe() {
System.out.println(me);
}
}
just searched the same stuff on my KDE environment.
Feel free to use clipcopy
and clippaste
KDE:
> echo "TEST CLIP FROM TERMINAL" | clipcopy
> clippaste
TEST CLIP FROM TERMINAL
Though you may prefer the pure Python solution provided by the python-daemon module, there is a daemon(3)
function in libc
-- at least, on BSD and Linux -- which will do the right thing.
Calling it from python is easy:
import ctypes
ctypes.CDLL(None).daemon(0, 0) # Read the man-page for the arguments' meanings
The only remaining thing to do is creation (and locking) of the PID-file. But that you can handle yourself...
Swift has a powerful type inference. Lets get rid of "if let" or "guard let" boilerplate and force unwraps using functional approach:
let json: Dictionary<String, Any>? = ["current": ["temperature": 10]]
/// Curry
public func curry<A, B, C>(_ f: @escaping (A, B) -> C) -> (A) -> (B) -> C {
return { a in
{ f(a, $0) }
}
}
/// Function that takes key and optional dictionary and returns optional value
public func extract<Key, Value>(_ key: Key, _ json: Dictionary<Key, Any>?) -> Value? {
return json.flatMap {
cast($0[key])
}
}
/// Function that takes key and return function that takes optional dictionary and returns optional value
public func extract<Key, Value>(_ key: Key) -> (Dictionary<Key, Any>?) -> Value? {
return curry(extract)(key)
}
/// Precedence group for our operator
precedencegroup RightApplyPrecedence {
associativity: right
higherThan: AssignmentPrecedence
lowerThan: TernaryPrecedence
}
/// Apply. g § f § a === g(f(a))
infix operator § : RightApplyPrecedence
public func §<A, B>(_ f: (A) -> B, _ a: A) -> B {
return f(a)
}
/// Wrapper around operator "as".
public func cast<A, B>(_ a: A) -> B? {
return a as? B
}
let temperature = (extract("temperature") § extract("current") § json) ?? NSNotFound
Just one line of code and no force unwraps or manual type casting. This code works in playground, so you can copy and check it. Here is an implementation on GitHub.
This should do the trick:
<table width="400" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="50" height="40" valign="top" rowspan="3">
<img alt="" src="" width="40" height="40" style="margin: 0; border: 0; padding: 0; display: block;">
</td>
<td width="350" height="40" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">LAST FIRST</a><br>
REALTOR | P 123.456.789
</td>
</tr>
<tr>
<td width="350" height="70" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="" src="" width="200" height="60" style="margin: 0; border: 0; padding: 0; display: block;">
</td>
</tr>
<tr>
<td width="350" height="20" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
</td>
</tr>
</table>
UPDATE: Adjusted code per the comments:
After viewing your jsFiddle, an important thing to note about tables is that table cell widths in each additional row all have to be the same width as the first, and all cells must add to the total width of your table.
Here is an example that will NOT WORK:
<table width="600" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="200" bgcolor="#252525">
</td>
<td width="400" bgcolor="#454545">
</td>
</tr>
<tr>
<td width="300" bgcolor="#252525">
</td>
<td width="300" bgcolor="#454545">
</td>
</tr>
</table>
Although the 2nd row does add up to 600, it (and any additional rows) must have the same 200-400 split as the first row, unless you are using colspans. If you use a colspan, you could have one row, but it needs to have the same width as the cells it is spanning, so this works:
<table width="600" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="200" bgcolor="#252525">
</td>
<td width="400" bgcolor="#454545">
</td>
</tr>
<tr>
<td width="600" colspan="2" bgcolor="#353535">
</td>
</tr>
</table>
Not a full tutorial, but I hope that helps steer you in the right direction in the future.
Here is the code you are after:
<table width="900" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="57" height="43" valign="top" rowspan="2">
<img alt="Rashel Adragna" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_head.png" width="47" height="43" style="margin: 0; border: 0; padding: 0; display: block;">
</td>
<td width="843" height="43" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">RASHEL ADRAGNA</a><br>
REALTOR | P 855.900.24KW
</td>
</tr>
<tr>
<td width="843" height="64" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="Zopa Realty Group logo" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_logo.png" width="177" height="54" style="margin: 0; border: 0; padding: 0; display: block;">
</td>
</tr>
<tr>
<td width="843" colspan="2" height="20" valign="bottom" align="center" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
</td>
</tr>
</table>
You'll note that I've added an extra 10px to some of your table cells. This in combination with align/valigns act as padding between your cells. It is a clever way to aviod actually having to add padding, margins or empty padding cells.
I found the simplest way:
gnome-terminal --tab -e 'command 1' --tab -e 'command 2'
I use tmux
instead of using terminal directly. So what I want is really a single and simple command/shell file to build the development env
with several tmux
windows. The shell code is as below:
#!/bin/bash
tabs="adb ana repo"
gen_params() {
local params=""
for tab in ${tabs}
do
params="${params} --tab -e 'tmux -u attach-session -t ${tab}'"
done
echo "${params}"
}
cmd="gnome-terminal $(gen_params)"
eval $cmd
Repeat the parent's dependency in child pom.xml and insert the exclusion there:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>com.vaadin.external.google</groupId>
<artifactId>android-json</artifactId>
</exclusion>
</exclusions>
</dependency>
ES6 modules support in Node.js is fairly recent; even in the bleeding-edge versions, it is still experimental. With Node.js 10, you can start Node.js with the --experimental-modules
flag, and it will likely work.
To import on older Node.js versions - or standard Node.js 10 - use CommonJS syntax:
const fs = require('fs');
You can realize this layout using CSS table-cells.
Modify your HTML slightly as follows:
<div id="header">
<div class="container">
<div class="logoBar">
<img src="http://placehold.it/50x40" />
</div>
<div id="searchBar">
<input type="text" />
</div>
<div class="button orange" id="myAccount">My Account</div>
<div class="button red" id="basket">Basket (2)</div>
</div>
</div>
Just remove the wrapper element around the two .button
elements.
Apply the following CSS:
#header {
background-color: #323C3E;
width:100%;
}
.container {
display: table;
width: 100%;
}
.logoBar, #searchBar, .button {
display: table-cell;
vertical-align: middle;
width: auto;
}
.logoBar img {
display: block;
}
#searchBar {
background-color: #FFF2BC;
width: 90%;
padding: 0 50px 0 10px;
}
#searchBar input {
width: 100%;
}
.button {
white-space: nowrap;
padding:22px;
}
Apply display: table
to .container
and give it 100% width.
For .logoBar
, #searchBar
, .button
, apply display: table-cell
.
For the #searchBar
, set the width to 90%, which force all the other elements to compute a shrink-to-fit width and the search bar will expand to fill in the rest of the space.
Use text-align and vertical-align in the table cells as needed.
See demo at: http://jsfiddle.net/audetwebdesign/zWXQt/
Use casting of types:
int main() {
int a;
float b, c, d;
a = 750;
b = a / (float)350;
c = 750;
d = c / (float)350;
printf("%.2f %.2f", b, d);
// output: 2.14 2.14
}
This is another way to solve that:
int main() {
int a;
float b, c, d;
a = 750;
b = a / 350.0; //if you use 'a / 350' here,
//then it is a division of integers,
//so the result will be an integer
c = 750;
d = c / 350;
printf("%.2f %.2f", b, d);
// output: 2.14 2.14
}
However, in both cases you are telling the compiler that 350 is a float, and not an integer. Consequently, the result of the division will be a float, and not an integer.
I have found another solution but quite different and i'll explain it
Basically, i used the tag to show the image, but i wanted to go to another page when the image was clicked and here is how i did it.
<a href="the-url-you-want-to-go-when-image-is-clicked.com" />
<img src="image-source-url-location.com" />
If you put it right next to each other, separated by a new line, i guess when you click the image, it goes to the tag which has the href to the other site you want to redirect.
managementObjects.Cast<ManagementBaseObject>().ToList();
is a good choice.
You could improve performance by pre-initialising the list capacity:
public static class Helpers
{
public static List<T> CollectionToList<T>(this System.Collections.ICollection other)
{
var output = new List<T>(other.Count);
output.AddRange(other.Cast<T>());
return output;
}
}
Sample of the Recursive Level:
DECLARE @VALUE_CODE AS VARCHAR(5);
--SET @VALUE_CODE = 'A' -- Specify a level
WITH ViewValue AS
(
SELECT ValueCode
, ValueDesc
, PrecedingValueCode
FROM ValuesTable
WHERE PrecedingValueCode IS NULL
UNION ALL
SELECT A.ValueCode
, A.ValueDesc
, A.PrecedingValueCode
FROM ValuesTable A
INNER JOIN ViewValue V ON
V.ValueCode = A.PrecedingValueCode
)
SELECT ValueCode, ValueDesc, PrecedingValueCode
FROM ViewValue
--WHERE PrecedingValueCode = @VALUE_CODE -- Specific level
--WHERE PrecedingValueCode IS NULL -- Root
Just add them in one line command 2>> error 1>> output
However, note that >>
is for appending if the file already has data. Whereas, >
will overwrite any existing data in the file.
So, command 2> error 1> output
if you do not want to append.
Just for completion's sake, you can write 1>
as just >
since the default file descriptor is the output. so 1>
and >
is the same thing.
So, command 2> error 1> output
becomes, command 2> error > output
"".join may be used to copy the string in a list to a variable
>>> myList = list("Hello World")
>>> myString = "".join(myList)
>>> print(myList)
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> print(myString)
Hello World
This kind of query should work - after rewriting with explicit JOIN
syntax:
SELECT something
FROM master parent
JOIN master child ON child.parent_id = parent.id
LEFT JOIN second parentdata ON parentdata.id = parent.secondary_id
LEFT JOIN second childdata ON childdata.id = child.secondary_id
WHERE parent.parent_id = 'rootID'
The tripping wire here is that an explicit JOIN
binds before "old style" CROSS JOIN
with comma (,
). I quote the manual here:
In any case
JOIN
binds more tightly than the commas separatingFROM
-list items.
After rewriting the first, all joins are applied left-to-right (logically - Postgres is free to rearrange tables in the query plan otherwise) and it works.
Just to make my point, this would work, too:
SELECT something
FROM master parent
LEFT JOIN second parentdata ON parentdata.id = parent.secondary_id
, master child
LEFT JOIN second childdata ON childdata.id = child.secondary_id
WHERE child.parent_id = parent.id
AND parent.parent_id = 'rootID'
But explicit JOIN
syntax is generally preferable, as your case illustrates once again.
And be aware that multiple (LEFT
) JOIN
can multiply rows:
toString
is a method, so you should add parenthesis ()
to make the function call.
> a = [1,2,3]
[ 1, 2, 3 ]
> a.toString()
'1,2,3'
Besides, if you want to use strings as keys, then you should consider using a Object
instead of Array
, and use JSON.stringify
to return a string.
> var aa = {}
> aa['a'] = 'aaa'
> JSON.stringify(aa)
'{"a":"aaa","b":"bbb"}'
i have tested a sample and i would like to share this sample and i am sure it's quite help full. I have done all thing in body, first creating an structure there on click of button you will call a function selectallelement(); on mouse click which will pass the id of that div about which you want to know the childrens. I have given alerts here on different level so u can test where r u now in the coding .
<body>
<h1>javascript to count the number of children of given child</h1>
<div id="count">
<span>a</span>
<span>s</span>
<span>d</span>
<span>ff</span>
<div>fsds</div>
<p>fffff</p>
</div>
<button type="button" onclick="selectallelement('count')">click</button>
<p>total element no.</p>
<p id="sho">here</p>
<script>
function selectallelement(divid)
{
alert(divid);
var ele = document.getElementById(divid).children;
var match = new Array();
var i = fillArray(ele,match);
alert(i);
document.getElementById('sho').innerHTML = i;
}
function fillArray(e1,a1)
{
alert("we are here");
for(var i =0;i<e1.length;i++)
{
if(e1[i].id.indexOf('count') == 0)
a1.push(e1[i]);
}
return i;
}
</script>
</body>
USE THIS I AM SURE U WILL GET YOUR ANSWER ...THANKS
I wrote a script to automate complex sparse checkouts.
#!/usr/bin/env python
'''
This script makes a sparse checkout of an SVN tree in the current working directory.
Given a list of paths in an SVN repository, it will:
1. Checkout the common root directory
2. Update with depth=empty for intermediate directories
3. Update with depth=infinity for the leaf directories
'''
import os
import getpass
import pysvn
__author__ = "Karl Ostmo"
__date__ = "July 13, 2011"
# =============================================================================
# XXX The os.path.commonprefix() function does not behave as expected!
# See here: http://mail.python.org/pipermail/python-dev/2002-December/030947.html
# and here: http://nedbatchelder.com/blog/201003/whats_the_point_of_ospathcommonprefix.html
# and here (what ever happened?): http://bugs.python.org/issue400788
from itertools import takewhile
def allnamesequal(name):
return all(n==name[0] for n in name[1:])
def commonprefix(paths, sep='/'):
bydirectorylevels = zip(*[p.split(sep) for p in paths])
return sep.join(x[0] for x in takewhile(allnamesequal, bydirectorylevels))
# =============================================================================
def getSvnClient(options):
password = options.svn_password
if not password:
password = getpass.getpass('Enter SVN password for user "%s": ' % options.svn_username)
client = pysvn.Client()
client.callback_get_login = lambda realm, username, may_save: (True, options.svn_username, password, True)
return client
# =============================================================================
def sparse_update_with_feedback(client, new_update_path):
revision_list = client.update(new_update_path, depth=pysvn.depth.empty)
# =============================================================================
def sparse_checkout(options, client, repo_url, sparse_path, local_checkout_root):
path_segments = sparse_path.split(os.sep)
path_segments.reverse()
# Update the middle path segments
new_update_path = local_checkout_root
while len(path_segments) > 1:
path_segment = path_segments.pop()
new_update_path = os.path.join(new_update_path, path_segment)
sparse_update_with_feedback(client, new_update_path)
if options.verbose:
print "Added internal node:", path_segment
# Update the leaf path segment, fully-recursive
leaf_segment = path_segments.pop()
new_update_path = os.path.join(new_update_path, leaf_segment)
if options.verbose:
print "Will now update with 'recursive':", new_update_path
update_revision_list = client.update(new_update_path)
if options.verbose:
for revision in update_revision_list:
print "- Finished updating %s to revision: %d" % (new_update_path, revision.number)
# =============================================================================
def group_sparse_checkout(options, client, repo_url, sparse_path_list, local_checkout_root):
if not sparse_path_list:
print "Nothing to do!"
return
checkout_path = None
if len(sparse_path_list) > 1:
checkout_path = commonprefix(sparse_path_list)
else:
checkout_path = sparse_path_list[0].split(os.sep)[0]
root_checkout_url = os.path.join(repo_url, checkout_path).replace("\\", "/")
revision = client.checkout(root_checkout_url, local_checkout_root, depth=pysvn.depth.empty)
checkout_path_segments = checkout_path.split(os.sep)
for sparse_path in sparse_path_list:
# Remove the leading path segments
path_segments = sparse_path.split(os.sep)
start_segment_index = 0
for i, segment in enumerate(checkout_path_segments):
if segment == path_segments[i]:
start_segment_index += 1
else:
break
pruned_path = os.sep.join(path_segments[start_segment_index:])
sparse_checkout(options, client, repo_url, pruned_path, local_checkout_root)
# =============================================================================
if __name__ == "__main__":
from optparse import OptionParser
usage = """%prog [path2] [more paths...]"""
default_repo_url = "http://svn.example.com/MyRepository"
default_checkout_path = "sparse_trunk"
parser = OptionParser(usage)
parser.add_option("-r", "--repo_url", type="str", default=default_repo_url, dest="repo_url", help='Repository URL (default: "%s")' % default_repo_url)
parser.add_option("-l", "--local_path", type="str", default=default_checkout_path, dest="local_path", help='Local checkout path (default: "%s")' % default_checkout_path)
default_username = getpass.getuser()
parser.add_option("-u", "--username", type="str", default=default_username, dest="svn_username", help='SVN login username (default: "%s")' % default_username)
parser.add_option("-p", "--password", type="str", dest="svn_password", help="SVN login password")
parser.add_option("-v", "--verbose", action="store_true", default=False, dest="verbose", help="Verbose output")
(options, args) = parser.parse_args()
client = getSvnClient(options)
group_sparse_checkout(
options,
client,
options.repo_url,
map(os.path.relpath, args),
options.local_path)
public void reverse() {
head = reverseNodes(null, head);
}
private Node reverseNodes(Node prevNode, Node currentNode) {
if (currentNode == null)
return prevNode;
Node nextNode = currentNode.next;
currentNode.next = prevNode;
return reverseNodes(currentNode, nextNode);
}
You can do it in this way with Swift 3.0:
let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)
let year = components.year
let month = components.month
let day = components.day
print(year)
print(month)
print(day)
It's the same origin policy, you have to use a JSON-P interface or a proxy running on the same host.
I had a similar experience.
The error was triggered when I initialize a variable on the driver (master), but then tried to use it on one of the workers. When that happens, Spark Streaming will try to serialize the object to send it over to the worker, and fail if the object is not serializable.
I solved the error by making the variable static.
Previous non-working code
private final PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
Working code
private static final PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
Credits:
From Apple Docs
You can use subscript syntax to retrieve a value from the dictionary for a particular key. Because it is possible to request a key for which no value exists, a dictionary’s subscript returns an optional value of the dictionary’s value type. If the dictionary contains a value for the requested key, the subscript returns an optional value containing the existing value for that key. Otherwise, the subscript returns nil:
if let airportName = airports["DUB"] {
print("The name of the airport is \(airportName).")
} else {
print("That airport is not in the airports dictionary.")
}
// prints "The name of the airport is Dublin Airport."
I highly recommend argparse
which comes with Python 2.7 and later.
The argparse
module reduces boiler plate code and makes your code more robust, because the module handles all standard use cases (including subcommands), generates the help and usage for you, checks and sanitize the user input - all stuff you have to worry about when you are using sys.argv
approach. And it is for free (built-in).
Here a small example:
import argparse
parser = argparse.ArgumentParser("simple_example")
parser.add_argument("counter", help="An integer will be increased by 1 and printed.", type=int)
args = parser.parse_args()
print(args.counter + 1)
and the output for python prog.py -h
usage: simple_example [-h] counter
positional arguments:
counter counter will be increased by 1 and printed.
optional arguments:
-h, --help show this help message and exit
and for python prog.py 1
as you would expect:
2
CHARINDEX is what you are looking for
select CHARINDEX('@', '[email protected]')
-----------
8
(1 row(s) affected)
-or-
select CHARINDEX('c', 'abcde')
-----------
3
(1 row(s) affected)
You can also use the following query to get Schemas for a specific Database user:
select s.schema_id, s.name as schema_name
from sys.schemas s
inner join sys.sysusers u on u.uid = s.principal_id
where u.name='DataBaseUserUserName'
order by s.name
They have slightly different purposes.
exec()
is for calling a system command, and perhaps dealing with the output yourself. system()
is for executing a system command and immediately displaying the output - presumably text. passthru()
is for executing a system command which you wish the raw return from - presumably something binary.Regardless, I suggest you not use any of them. They all produce highly unportable code.
I usually use sys.platform
(docs) to get the platform. sys.platform
will distinguish between linux, other unixes, and OS X, while os.name
is "posix
" for all of them.
For much more detailed information, use the platform module. This has cross-platform functions that will give you information on the machine architecture, OS and OS version, version of Python, etc. Also it has os-specific functions to get things like the particular linux distribution.
Here is a very recent answer to this question from the file: 07reader.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');
date_default_timezone_set('Europe/London');
/** Include PHPExcel_IOFactory */
require_once '../Classes/PHPExcel/IOFactory.php';
if (!file_exists("05featuredemo.xlsx")) {
exit("Please run 05featuredemo.php first." . EOL);
}
echo date('H:i:s') , " Load from Excel2007 file" , EOL;
$callStartTime = microtime(true);
$objPHPExcel = PHPExcel_IOFactory::load("05featuredemo.xlsx");
$callEndTime = microtime(true);
$callTime = $callEndTime - $callStartTime;
echo 'Call time to read Workbook was ' , sprintf('%.4f',$callTime) , " seconds" , EOL;
// Echo memory usage
echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true) / 1024 / 1024) , " MB" , EOL;
echo date('H:i:s') , " Write to Excel2007 format" , EOL;
$callStartTime = microtime(true);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
$callEndTime = microtime(true);
$callTime = $callEndTime - $callStartTime;
echo date('H:i:s') , " File written to " , str_replace('.php', '.xlsx', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL;
echo 'Call time to write Workbook was ' , sprintf('%.4f',$callTime) , " seconds" , EOL;
// Echo memory usage
echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true) / 1024 / 1024) , " MB" , EOL;
// Echo memory peak usage
echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL;
// Echo done
echo date('H:i:s') , " Done writing file" , EOL;
echo 'File has been created in ' , getcwd() , EOL;
In my case, @
caused some sort of encoding problem, I still prefer my old way:
curl -d "$(cat /path/to/file)" https://example.com
addItem(Object) takes an object. The default JComboBox renderer calls toString() on that object and that's what it shows as the label.
So, don't pass in a String to addItem(). Pass in an object whose toString() method returns the label you want. The object can contain any number of other data fields also.
Try passing this into your combobox and see how it renders. getSelectedItem() will return the object, which you can cast back to Widget to get the value from.
public final class Widget {
private final int value;
private final String label;
public Widget(int value, String label) {
this.value = value;
this.label = label;
}
public int getValue() {
return this.value;
}
public String toString() {
return this.label;
}
}
The best way to do it is:
return this.StatusCode(StatusCodes.Status418ImATeapot, "Error message");
'StatusCodes' has every kind of return status and you can see all of them in this link https://httpstatuses.com/
Once you choose your StatusCode, return it with a message.
With java8 streaming API:
List values = map.entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toList());
You can use us jquery function getJson :
$(function(){
$.getJSON('/api/rest/abc', function(data) {
console.log(data);
});
});
You can size your label according to text and other related controls using two ways-
For iOS 7.0 and above
CGSize labelTextSize = [labelText boundingRectWithSize:CGSizeMake(labelsWidth, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{
NSFontAttributeName : labelFont
}
context:nil].size;
before iOS 7.0 this could be used to calculate label size
CGSize labelTextSize = [label.text sizeWithFont:label.font
constrainedToSize:CGSizeMake(label.frame.size.width, MAXFLOAT)
lineBreakMode:NSLineBreakByWordWrapping];
// reframe other controls based on labelTextHeight
CGFloat labelTextHeight = labelTextSize.height;
If you do not want to calculate the size of the label's text than you can use -sizeToFit on the instance of UILabel as-
[label setNumberOfLines:0]; // for multiline label
[label setText:@"label text to set"];
[label sizeToFit];// call this to fit size of the label according to text
// after this you can get the label frame to reframe other related controls
I had a similar issue and found that it was much simpler to to get rid of the Excel files as soon as possible. As part of the first steps in my package I used Powershell to extract the data out of the Excel files into CSV files. My own Excel files were simple but here
Extract and convert all Excel worksheets into CSV files using PowerShell
is an excellent article by Tim Smith on extracting data from multiple Excel files and/or multiple sheets.
Once the Excel files have been converted to CSV the data import is much less complicated.
The break
keyword does exactly that. Here is a contrived example:
public static void main(String[] args) {
int i = 0;
while (i++ < 10) {
if (i == 5) break;
}
System.out.println(i); //prints 5
}
If you were actually using nested loops, you would be able to use labels.
I have done this without using any function.
$arr = array("1", "2", "3", "4", "5", "4", "2", "1");
$len = count($arr);
for ($i = 0; $i < $len; $i++) {
$temp = $arr[$i];
$j = $i;
for ($k = 0; $k < $len; $k++) {
if ($k != $j) {
if ($temp == $arr[$k]) {
echo $temp."<br>";
$arr[$k]=" ";
}
}
}
}
for ($i = 0; $i < $len; $i++) {
echo $arr[$i] . " <br><br>";
}
Remove the line /*# sourceMappingURL=bootstrap.css.map */
in bootstrap.css
If the error persists, clean the cache of the browser (CTRL + F5).
You can also try this
// create a thread
Thread newWindowThread = new Thread(new ThreadStart(() =>
{
// create and show the window
FaxImageLoad obj = new FaxImageLoad(destination);
obj.Show();
// start the Dispatcher processing
System.Windows.Threading.Dispatcher.Run();
}));
// set the apartment state
newWindowThread.SetApartmentState(ApartmentState.STA);
// make the thread a background thread
newWindowThread.IsBackground = true;
// start the thread
newWindowThread.Start();
This one-liner should work:
npm start --prefix path/to/your/app
You are looking for the command scandir.
$path = '/tmp';
$files = scandir($path);
Following code will remove .
and ..
from the returned array from scandir
:
$files = array_diff(scandir($path), array('.', '..'));
First of all, all the reasons are subjective. It's more like a matter of taste rather than a reason.
Personally, I find heredoc quite useless and use it occasionally, most of the time when I need to get some HTML into a variable and don't want to bother with output buffering, to form an HTML email message for example.
Formatting doesn't fit general indentation rules, but I don't think it's a big deal.
//some code at it's proper level
$this->body = <<<HERE
heredoc text sticks to the left border
but it seems OK to me.
HERE;
$this->title = "Feedback";
//and so on
As for the examples in the accepted answer, it is merely cheating.
String examples, in fact, being more concise if one won't cheat on them
$sql = "SELECT * FROM $tablename
WHERE id in [$order_ids_list]
AND product_name = 'widgets'";
$x = 'The point of the "argument" was to illustrate the use of here documents';
I can see that the init has the following override:
Init(CALLBACK_FUNC_EX callback_func, void * callback_parm)
where CALLBACK_FUNC_EX
is
typedef void (*CALLBACK_FUNC_EX)(int, void *);
UPDATE T1,T2
INNER JOIN T1 ON T1.Brands = T2.Brands
SET
T1.Inci = T2.Inci
WHERE
T1.Category= T2.Category
AND
T1.Date = T2.Date