The below steps should be the simple fix to your problem
- Project->Properties->ProjectFacet-->Uncheck jsf apply and OK.
- Project->Maven->UpdateProject-->This will solve the issue.
Here while on Updating Project Maven will automatically chooses the Dynamic web module
Using Java
int nDigits = Math.floor(Math.log10(Math.abs(the_integer))) + 1;
use import java.lang.Math.*;
in the beginning
Using C
int nDigits = floor(log10(abs(the_integer))) + 1;
use inclue math.h
in the beginning
I know I am late it the game, but the issue still exists even after google has made fix on the android.support.v7.widget.RecyclerView
The issue I get now is RecyclerView
with layout_height=wrap_content
not taking height of all the items issue inside ScrollView
that only happens on Marshmallow and Nougat+ (API 23, 24, 25) versions.
(UPDATE: Replacing ScrollView
with android.support.v4.widget.NestedScrollView
works on all versions. I somehow missed testing accepted solution. Added this in my github project as demo.)
After trying different things, I have found workaround that fixes this issue.
Here is my layout structure in a nutshell:
<ScrollView>
<LinearLayout> (vertical - this is the only child of scrollview)
<SomeViews>
<RecyclerView> (layout_height=wrap_content)
<SomeOtherViews>
The workaround is the wrap the RecyclerView
with RelativeLayout
. Don't ask me how I found this workaround!!! ¯\_(?)_/¯
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
Complete example is available on GitHub project - https://github.com/amardeshbd/android-recycler-view-wrap-content
Here is a demo screencast showing the fix in action:
For Visual Studio 2017
and Visual Studio 2015
, IIS Express
settings is stored in the hidden .vs
directory and the path is something like this .vs\config\applicationhost.config
, add binding like below will work
<bindings>
<binding protocol="http" bindingInformation="*:8802:localhost" />
<binding protocol="http" bindingInformation="*:8802:127.0.0.1" />
</bindings>
Using the selectedOptions
property:
var yourSelect = document.getElementById("your-select-id");
alert(yourSelect.selectedOptions[0].value);
It works in all browsers except Internet Explorer.
Use
jQuery(document).
instead of
$(document).
or
Within the function, $ points to jQuery as you would expect
(function ($) {
$(document).
}(jQuery));
Sharing a personal case if it helps. It is that a virtual environment was previously arranged. Its path can be displayed by
echo $VIRTUAL_ENV
Make sure that the it is writable to the current user. If not, using
sudo ipython
would certainly clear off the warning message.
In anaconda, if $VIRTUAL_ENV is independently arranged, one can simply delete this folder or rename it, and then restart the shell. Anaconda will recover to its default setup.
I didn't check all the code but my guess is that the error is in the malloc call. You have to replace
double *ptr = malloc(sizeof(double*) * TIME);
for
double *ptr = malloc(sizeof(double) * TIME);
since you want to allocate size for a double (not the size of a pointer to a double).
Simplified Java 8
IntelliJ suggests to simplify the top answer to the:
Arrays.sort(queries, Comparator.comparingDouble(a -> a[0]));
window.location.href
is what you need. But also if you are using react router you might find useful checking out useLocation and useHistory hooks.
Both create an object with a pathname attribute you can read and are useful for a bunch of other stuff. Here's a youtube video explaining react router hooks
Both will give you what you need (without the domain name):
import { useHistory ,useLocation } from 'react-router-dom';
const location = useLocation()
location.pathname
const history = useHistory()
history.location.pathname
A slightly more complicated way would be to use setInterval()
to check mouse position and compare to last check. If the mouse hasn't moved in a set amount of time, the user is probably idle.
This has the added advantage of telling if the user is idle, instead of just checking if the window is not active.
As many people have pointed out, this is not always a good way to check whether the user or browser window is idle, as the user might not even be using the mouse or is watching a video, or similar. I am just suggesting one possible way to check for idle-ness.
As an improvement on Peters code above you can use this:
var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
if (!roleManager.RoleExists("Member"))
roleManager.Create(new IdentityRole("Member"));
For PyTorch v1.0 and possibly above:
>>> import torch
>>> var = torch.tensor([[1,0], [0,1]])
# Using .size function, returns a torch.Size object.
>>> var.size()
torch.Size([2, 2])
>>> type(var.size())
<class 'torch.Size'>
# Similarly, using .shape
>>> var.shape
torch.Size([2, 2])
>>> type(var.shape)
<class 'torch.Size'>
You can cast any torch.Size object to a native Python list:
>>> list(var.size())
[2, 2]
>>> type(list(var.size()))
<class 'list'>
In PyTorch v0.3 and 0.4:
Simply list(var.size())
, e.g.:
>>> import torch
>>> from torch.autograd import Variable
>>> from torch import IntTensor
>>> var = Variable(IntTensor([[1,0],[0,1]]))
>>> var
Variable containing:
1 0
0 1
[torch.IntTensor of size 2x2]
>>> var.size()
torch.Size([2, 2])
>>> list(var.size())
[2, 2]
By including:
#include <byteswap.h>
you can get an optimized version of machine-dependent byte-swapping functions. Then, you can easily use the following functions:
__bswap_32 (uint32_t input)
or
__bswap_16 (uint16_t input)
For the basic tooltip, you want:
<span title="This is my tooltip"> Hover on me to see tooltip! </span>
_x000D_
Since you mentioned reflection in your question;
boolean isArray = myArray.getClass().isArray();
boolean isCollection = Collection.class.isAssignableFrom(myList.getClass());
boolean isMap = Map.class.isAssignableFrom(myMap.getClass());
Yes it stops execution so this is generally preferable to HAVING COUNT(*) > 0
which often won't.
With EXISTS
if you look at the execution plan you will see that the actual number of rows coming out of table1
will not be more than 1 irrespective of number of matching records.
In some circumstances SQL Server can convert the tree for the COUNT
query to the same as the one for EXISTS
during the simplification phase (with a semi join and no aggregate operator in sight) an example of that is discussed in the comments here.
For more complicated sub trees than shown in the question you may occasionally find the COUNT
performs better than EXISTS
however. Because the semi join needs only retrieve one row from the sub tree this can encourage a plan with nested loops for that part of the tree - which may not work out optimal in practice.
First step get container id:
docker ps
This will show you something like
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1170fe9e9460 localhost:5000/python:env-7e847468c4d73a0f35e9c5164046ad88 "./run_notebook.sh" 26 seconds ago Up 25 seconds 0.0.0.0:8989->9999/tcp SLURM_TASK-303337_0
1170fe9e9460
is the container id in this case.
Second, enter the docker :
docker exec -it [container_id] bash
so in the above case:
docker exec -it 1170fe9e9460 bash
it is compatible with all the browsers, change values to fit your application
background: #fdfdfd;
background: -moz-linear-gradient(top, #fdfdfd 0%, #f6f6f6 60%, #f2f2f2 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#fdfdfd), color-stop(60%,#f6f6f6), color-stop(100%,#f2f2f2));
background: -webkit-linear-gradient(top, #fdfdfd 0%,#f6f6f6 60%,#f2f2f2 100%);
background: -o-linear-gradient(top, #fdfdfd 0%,#f6f6f6 60%,#f2f2f2 100%);
background: -ms-linear-gradient(top, #fdfdfd 0%,#f6f6f6 60%,#f2f2f2 100%);
background: linear-gradient(to bottom, #fdfdfd 0%,#f6f6f6 60%,#f2f2f2 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fdfdfd', endColorstr='#f2f2f2',GradientType=0
You don't need the separate fill item. In fact, it's invalid. You just have to add a solid
block to the shape
. The subsequent stroke
draws on top of the solid
:
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="5dp" />
<solid android:color="@android:color/white" />
<stroke
android:width="1dip"
android:color="@color/bggrey" />
</shape>
You also don't need the layer-list
if you only have one shape
.
since I have no enough reputation to comment after the highest post, so I add here.
use '|' on linux platform to save disk space.
thx @Hariboo, add events/triggers/routints parameters
mysqldump -x -u [uname] -p[pass] -C --databases db_name --events --triggers --routines | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/ ' | awk '{ if (index($0,"GTID_PURGED")) { getline; while (length($0) > 0) { getline; } } else { print $0 } }' | grep -iv 'set @@' | trickle -u 10240 mysql -u username -p -h localhost DATA-BASE-NAME
some issues/tips:
Error: ......not exist when using LOCK TABLES
# --lock-all-tables,-x , this parameter is to keep data consistency because some transaction may still be working like schedule.
# also you need check and confirm: grant all privileges on *.* to root@"%" identified by "Passwd";
ERROR 2006 (HY000) at line 866: MySQL server has gone away mysqldump: Got errno 32 on write
# set this values big enough on destination mysql server, like: max_allowed_packet=1024*1024*20
# use compress parameter '-C'
# use trickle to limit network bandwidth while write data to destination server
ERROR 1419 (HY000) at line 32730: You do not have the SUPER privilege and binary logging is enabled (you might want to use the less safe log_bin_trust_function_creators variable)
# set SET GLOBAL log_bin_trust_function_creators = 1;
# or use super user import data
ERROR 1227 (42000) at line 138: Access denied; you need (at least one of) the SUPER privilege(s) for this operation mysqldump: Got errno 32 on write
# add sed/awk to avoid some privilege issues
hope this help!
Two things: Change the variables x
, y
, z
as int
and call the method as Math.max(Math.max(x,y),z)
as it accepts two parameters only.
In Summary, change below:
String x = keyboard.nextLine();
String y = keyboard.nextLine();
String z = keyboard.nextLine();
int max = Math.max(x,y,z);
to
int x = keyboard.nextInt();
int y = keyboard.nextInt();
int z = keyboard.nextInt();
int max = Math.max(Math.max(x,y),z);
First you download ODBC driver psqlodbc_09_01_0200-x64.zip then you installed it.After that go to START->Program->Administrative tools then you select Data Source ODBC then you double click on the same after that you select PostgreSQL 30 then you select configure then you provide proper details such as db name user Id host name password of the same database in this way you will configured your DSN connection.After That you will check SSL should be allow .
Then you go on next tab system DSN then you select ADD tabthen select postgreSQL_ANSI_64X ODBC after you that you have created PostgreSQL ODBC connection.
Via Moment.js
Jsfiddle: http://jsfiddle.net/guhokemk/1/
function compare(dateTimeA, dateTimeB) {
var momentA = moment(dateTimeA,"DD/MM/YYYY");
var momentB = moment(dateTimeB,"DD/MM/YYYY");
if (momentA > momentB) return 1;
else if (momentA < momentB) return -1;
else return 0;
}
alert(compare("11/07/2015", "10/07/2015"));
The method returns 1 if dateTimeA
is greater than dateTimeB
The method returns 0 if dateTimeA
equals dateTimeB
The method returns -1 if dateTimeA
is less than dateTimeB
This is really weird, why nobody is mentioning the /IM switch ?! I've been using it for a long time in backup jobs. But I tried googling just now and I couldn't land on a single web page that says anything about it even on MS website !!! Also found so many user posts complaining about the same issue!!
Anyway.. to use Robocopy to overwrite EVERYTHING what ever size or time in source or distination you must include these three switches in your command (/IS /IT /IM)
/IS :: Include Same files. (Includes same size files)
/IT :: Include Tweaked files. (Includes same files with different Attributes)
/IM :: Include Modified files (Includes same files with different times).
This is the exact command I use to transfer few TeraBytes of mostly 1GB+ files (ISOs - Disk Images - 4K Videos):
robocopy B:\Source D:\Destination /E /J /COPYALL /MT:1 /DCOPY:DATE /IS /IT /IM /X /V /NP /LOG:A:\ROBOCOPY.LOG
I did a small test for you .. and here is the result:
Total Copied Skipped Mismatch FAILED Extras
Dirs : 1028 1028 0 0 0 169
Files : 8053 8053 0 0 0 1
Bytes : 649.666 g 649.666 g 0 0 0 1.707 g
Times : 2:46:53 0:41:43 0:00:00 0:41:44
Speed : 278653398 Bytes/sec.
Speed : 15944.675 MegaBytes/min.
Ended : Friday, August 21, 2020 7:34:33 AM
Dest, Disk: WD Gold 6TB (Compare the write speed with my result)
Even with those "Extras", that's for reporting only because of the "/X" switch. As you can see nothing was Skipped and Total number and size of all files are equal to the Copied. Sometimes It will show small number of skipped files when I abuse it and cancel it multiple times during operation but even with that the values in the first 2 columns are always Equal. I also confirmed that once before by running a PowerShell script that scans all files in destination and generate a report of all time-stamps.
Some performance tips from my history with it and so many tests & troubles!:
. Despite of what most users online advise to use maximum threads "/MT:128" like it's a general trick to get the best performance ... PLEASE DON'T USE "/MT:128" WITH VERY LARGE FILES ... that's a big mistake and it will decrease your drive performance dramatically after several runs .. it will create very high fragmentation or even cause the files system to fail in some cases and you end up spending valuable time trying to recover a RAW partition and all that nonsense. And above all that, It will perform 4-6 times slower!!
I use moment to solve the problem. For example
var startDate = moment('2015-07-06 08:00', 'YYYY-MM-DD HH:mm').toDate();
You can create another script file separately for the functions and invoke the script file whenever you want to call the function. This will help you to keep your code clean.
Function Definition : Create a new script file
Function Call : Invoke the script file
In order to get all the details I had to add the -v option to romaintaz answer:
keytool -v -list -keystore <FileName>.keystore
inline
and inline-block
elements are affected by whitespace in the HTML.
The simplest way to fix your problem is to remove the whitespace between </div>
and <div id="col2">
, see: http://jsfiddle.net/XCDsu/15/
There are other possible solutions, see: bikeshedding CSS3 property alternative?
Here are two solutions, I am using Oracle SQL server:
1) using over clause:
with org_table as
(select 1 id, 'Ali' uname
from dual
union
select 1, 'June'
from dual
union
select 2, 'Jame'
from dual
union
select 2, 'July' from dual)
select id, uname
from (select a.id,
a.uname,
ROW_NUMBER() OVER(PARTITION BY a.id ORDER BY a.id) AS freq
from org_table a)
where freq = 1
2) Using sub-query:
with org_table as
(select 1 id, 'Ali' uname
from dual
union
select 1, 'June'
from dual
union
select 2, 'Jame'
from dual
union
select 2, 'July' from dual)
select a.id,
(select b.uname
from org_table b
where b.id = a.id
and rownum = 1)
from (select distinct id from org_table) a
Select Name,
case
when Age = 13 then 'Thirteen'
when Age = 14 then 'Fourteen'
when Age = 15 then 'Fifteen'
when Age = 16 then 'Sixteen'
when Age = 17 then 'Seventeen'
when Age = 18 then 'Eighteen'
when Age = 19 then 'Nineteen'
else 'Adult'
end as AgeBracket
FROM Person
Try the following:
if ((select VisitCount from PageImage where PID=@pid and PageNumber=5) is NULL)
begin
update PageImage
set VisitCount=1
where PID=@pid and PageNumber=@pageno
end
else
begin
update PageImage
set VisitCount=VisitCount+1
where PID=@pid and PageNumber=@pageno
end
I know this post is getting outdated, but here's what they asked. In your style sheet:
.social {
width: 330px;
height: 75px;
float: right;
text-align: left;
padding: 10px 0;
border-bottom: dotted 1px #6d6d6d;
}
[class~="first"] {
padding-top:0;
}
[class~="last"] {
border:0;
}
But it may be a bad way to use selectors. Also, if you need multiple "first" extension, you'll have to be sure to set different name, or to refine your selector.
[class="social first"] {...}
I hope this will help someone, it can be pretty handy in some situation.
For exemple, if you have a tiny piece of css that has to be linked to many different components, and you don't want to write a hundred time the same code.
div.myClass1 {font-weight:bold;}
div.myClass2 {font-style:italic;}
...
div.myClassN {text-shadow:silver 1px 1px 1px;}
div.myClass1.red {color:red;}
div.myClass2.red {color:red;}
...
div.myClassN.red {color:red;}
Becomes:
div.myClass1 {font-weight:bold;}
div.myClass2 {font-style:italic;}
...
div.myClassN {text-shadow:silver 1px 1px 1px;}
[class~=red] {color:red;}
You don't have that kind of control with a bare a
tag. But you can hook up the tag's onclick
handler to call window.open(...)
with the right parameters. See here for examples:
https://developer.mozilla.org/En/DOM/Window.open
I still don't think you can force window over tab directly though-- that depends on the browser and the user's settings.
Protected members can be accessed from derived classes. Private ones can't.
class Base {
private:
int MyPrivateInt;
protected:
int MyProtectedInt;
public:
int MyPublicInt;
};
class Derived : Base
{
public:
int foo1() { return MyPrivateInt;} // Won't compile!
int foo2() { return MyProtectedInt;} // OK
int foo3() { return MyPublicInt;} // OK
};??
class Unrelated
{
private:
Base B;
public:
int foo1() { return B.MyPrivateInt;} // Won't compile!
int foo2() { return B.MyProtectedInt;} // Won't compile
int foo3() { return B.MyPublicInt;} // OK
};
In terms of "best practice", it depends. If there's even a faint possibility that someone might want to derive a new class from your existing one and need access to internal members, make them Protected, not Private. If they're private, your class may become difficult to inherit from easily.
you can format date just making this type of the code.In javascript.
// for eg.
var inputdate=document.getElementById("getdate").value);
var datecomp= inputdate.split('.');
Var Date= new Date(datecomp[2], datecomp[1]-1, datecomp[0]);
//new date( Year,Month,Date)
If you'd like to check if the argument exists, you can check if the # of arguments is greater than or equal to your target argument number.
The following script demonstrates how this works
#!/usr/bin/env bash
if [ $# -ge 3 ]
then
echo script has at least 3 arguments
fi
produces the following output
$ ./test.sh
~
$ ./test.sh 1
~
$ ./test.sh 1 2
~
$ ./test.sh 1 2 3
script has at least 3 arguments
$ ./test.sh 1 2 3 4
script has at least 3 arguments
Based on this article, I have put together the following snippet that provides some very basic functionality:
<div id = "container"></div>
<script>
function setPDFHeight(){
$("#pdfObject")[0].height = $("#pdfObject")[0].offsetHeight;
}
$('#container').append('<div align="center" style="width: 100%; height:100%; overflow: auto !important; -webkit-overflow-scrolling: touch !important;">\
<object id="pdfObject" width="100%" height="1000000000000" align="center" data="content/lessons/12/t.pdf" type="application/pdf" onload="setPDFHeight()">You have no plugin installed</object></div>');
</script>
Obviously it is far from perfect (given that it practically expands your page height to infinity), but it's the only viable workaround I've found so far.
Given a Window object myWindow, myWindow.Show() will open it modelessly and myWindow.ShowDialog() will open it modally. However, even the latter doesn't block, from what I remember.
wt = tt - cpu tm.
Tt = cpu tm + wt.
Where wt
is a waiting time and tt
is turnaround time. Cpu time is also called burst time.
I had to modify this slightly to be used on a Windows System. Here's the one-liner version for a windows box.
openssl.exe s_client -connect yoursitename.com:443 > CertInfo.txt && openssl x509 -text -in CertInfo.txt | find "Signature Algorithm" && del CertInfo.txt /F
Tested on Server 2012 R2 using http://iweb.dl.sourceforge.net/project/gnuwin32/openssl/0.9.8h-1/openssl-0.9.8h-1-bin.zip
Example downloader class without Alamofire:
class Downloader {
class func load(URL: NSURL) {
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
let request = NSMutableURLRequest(URL: URL)
request.HTTPMethod = "GET"
let task = session.dataTaskWithRequest(request, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if (error == nil) {
// Success
let statusCode = (response as NSHTTPURLResponse).statusCode
println("Success: \(statusCode)")
// This is your file-variable:
// data
}
else {
// Failure
println("Failure: %@", error.localizedDescription);
}
})
task.resume()
}
}
This is how to use it in your own code:
class Foo {
func bar() {
if var URL = NSURL(string: "http://www.mywebsite.com/myfile.pdf") {
Downloader.load(URL)
}
}
}
Swift 3 Version
Also note to download large files on disk instead instead in memory. see `downloadTask:
class Downloader {
class func load(url: URL, to localUrl: URL, completion: @escaping () -> ()) {
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = try! URLRequest(url: url, method: .get)
let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Success: \(statusCode)")
}
do {
try FileManager.default.copyItem(at: tempLocalUrl, to: localUrl)
completion()
} catch (let writeError) {
print("error writing file \(localUrl) : \(writeError)")
}
} else {
print("Failure: %@", error?.localizedDescription);
}
}
task.resume()
}
}
If you have an interface in your controller
public myController(IXInterface Xinstance){}
You must register them to Dependency Injection container.
container.Bind<IXInterface>().To<XClass>().InRequestScope();
Laravel is not actually that slow. 500-1000ms is absurd; I got it down to 20ms in debug mode.
The problem was Vagrant/VirtualBox + shared folders. I didn't realize they incurred such a performance hit. I guess because Laravel has so many dependencies (loads ~280 files) and each of those file reads is slow, it adds up really quick.
kreeves pointed me in the right direction, this blog post describes a new feature in Vagrant 1.5 that lets you rsync your files into the VM rather than using a shared folder.
There's no native rsync client on Windows, so you'll have to use cygwin. Install it, and make sure to check off Net/rsync. Add C:\cygwin64\bin
to your paths. [Or you can install it on Win10/Bash]
Vagrant introduces the new feature. I'm using Puphet, so my Vagrantfile looks a bit funny. I had to tweak it to look like this:
data['vm']['synced_folder'].each do |i, folder|
if folder['source'] != '' && folder['target'] != '' && folder['id'] != ''
config.vm.synced_folder "#{folder['source']}", "#{folder['target']}",
id: "#{folder['id']}",
type: "rsync",
rsync__auto: "true",
rsync__exclude: ".hg/"
end
end
Once you're all set up, try vagrant up
. If everything goes smoothly your machine should boot up and it should copy all the files over. You'll need to run vagrant rsync-auto
in a terminal to keep the files up to date. You'll pay a little bit in latency, but for 30x faster page loads, it's worth it!
If you're using PhpStorm, it's auto-upload feature works even better than rsync. PhpStorm creates a lot of temporary files which can trip up file watchers, but if you let it handle the uploads itself, it works nicely.
One more option is to use lsyncd. I've had great success using this on Ubuntu host -> FreeBSD guest. I haven't tried it on a Windows host yet.
Based on your comments in this answer, I do what you're trying to do like this:
module.exports = function (app, db) {
var module = {};
module.auth = function (req, res) {
// This will be available 'outside'.
// Authy stuff that can be used outside...
};
// Other stuff...
module.pickle = function(cucumber, herbs, vinegar) {
// This will be available 'outside'.
// Pickling stuff...
};
function jarThemPickles(pickle, jar) {
// This will be NOT available 'outside'.
// Pickling stuff...
return pickleJar;
};
return module;
};
I structure pretty much all my modules like that. Seems to work well for me.
I have a longer test to try. This takes an average of 160 ns to read each line as add it to a List (Which is likely to be what you intended as dropping the newlines is not very useful.
public static void main(String... args) throws IOException {
final int runs = 5 * 1000 * 1000;
final ServerSocket ss = new ServerSocket(0);
new Thread(new Runnable() {
@Override
public void run() {
try {
Socket serverConn = ss.accept();
String line = "Hello World!\n";
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(serverConn.getOutputStream()));
for (int count = 0; count < runs; count++)
br.write(line);
serverConn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
Socket conn = new Socket("localhost", ss.getLocalPort());
long start = System.nanoTime();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
List<String> responseData = new ArrayList<String>();
while ((line = in.readLine()) != null) {
responseData.add(line);
}
long time = System.nanoTime() - start;
System.out.println("Average time to read a line was " + time / runs + " ns.");
conn.close();
ss.close();
}
prints
Average time to read a line was 158 ns.
If you want to build a StringBuilder, keeping newlines I would suggets the following approach.
Reader r = new InputStreamReader(conn.getInputStream());
String line;
StringBuilder sb = new StringBuilder();
char[] chars = new char[4*1024];
int len;
while((len = r.read(chars))>=0) {
sb.append(chars, 0, len);
}
Still prints
Average time to read a line was 159 ns.
In both cases, the speed is limited by the sender not the receiver. By optimising the sender, I got this timing down to 105 ns per line.
You can use ng-required for your validation scenario ("if these 3 fields are filled in, then this field is required":
<div ng-app>
<input type="text" ng-model="field1" placeholder="Field1">
<input type="text" ng-model="field2" placeholder="Field2">
<input type="text" ng-model="field3" placeholder="Field3">
<input type="text" ng-model="dependentField" placeholder="Custom validation"
ng-required="field1 && field2 && field3">
</div>
Another important fact is that reject()
DOES NOT terminate control flow like a return
statement does. In contrast throw
does terminate control flow.
Example:
new Promise((resolve, reject) => {_x000D_
throw "err";_x000D_
console.log("NEVER REACHED");_x000D_
})_x000D_
.then(() => console.log("RESOLVED"))_x000D_
.catch(() => console.log("REJECTED"));
_x000D_
vs
new Promise((resolve, reject) => {_x000D_
reject(); // resolve() behaves similarly_x000D_
console.log("ALWAYS REACHED"); // "REJECTED" will print AFTER this_x000D_
})_x000D_
.then(() => console.log("RESOLVED"))_x000D_
.catch(() => console.log("REJECTED"));
_x000D_
You want to be able to pass in a Class and get a type-safe instance of that class? Try the following:
public static void main(String [] args) throws Exception {
String s = instanceOf(String.class);
}
public static <T> T instanceOf (Class<T> clazz) throws Exception {
return clazz.newInstance();
}
In python 3.x. you use
print("Hello, World")
In Python 2.x. you use
print "Hello, World!"
the answers here are correct and i liked @Jyo the Whiff idea of a show and hide fragment implementation except the way he has it currently would hide the fragment on the first run so i added a slight change in that i added the isAdded check and show the fragment if its not already
public void showHideCardPreview(int id) {
FragmentManager fm = getSupportFragmentManager();
Bundle b = new Bundle();
b.putInt(Constants.CARD, id);
cardPreviewFragment.setArguments(b);
FragmentTransaction ft = fm.beginTransaction()
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
if (!cardPreviewFragment.isAdded()){
ft.add(R.id.full_screen_container, cardPreviewFragment);
ft.show(cardPreviewFragment);
} else {
if (cardPreviewFragment.isHidden()) {
Log.d(TAG,"++++++++++++++++++++ show");
ft.show(cardPreviewFragment);
} else {
Log.d(TAG,"++++++++++++++++++++ hide");
ft.hide(cardPreviewFragment);
}
}
ft.commit();
}
A tty
is a physical terminal-teletype port on a computer (usually a serial port).
The word teletype is a shorting of the telegraph typewriter, or teletypewriter device from the 1930s - itself an electromagnetic device which replaced the telegraph encoding machines of the 1830s and 1840s.
A pty
is a pseudo-teletype port provided by a computer Operating System Kernel to connect software programs emulating terminals, such as ssh, xterm, or screen.
A terminal is simply a computer's user interface that uses text for input and output.
These use pseudo-teletype ports however, their naming and implementations have diverged a little.
Linux mounts a special file system devpts on /dev (the 's' presumably standing for serial) that creates a corresponding entry in /dev/pts
for every new terminal window you open, e.g. /dev/pts/0
macOS/FreeBSD also use the /dev file structure however, they use a numbered TTY
naming convention ttys
for every new terminal window you open e.g. /dev/ttys002
Microsoft Windows still has the concept of an LPT
port for Line Printer Terminals within it's Command Shell for output to a printer.
./me casts raise_dead()
I was looking for something like this, but I also needed to reuse the same string minus two parameters so I ended up with something like:
my_exe ()
{
mysql -sN -e "select $1 from heat.stack where heat.stack.name=\"$2\";"
}
This is something I use to monitor openstack heat stack creation. In this case I expect two conditions, an action 'CREATE' and a status 'COMPLETE' on a stack named "Somestack"
To get those variables I can do something like:
ACTION=$(my_exe action Somestack)
STATUS=$(my_exe status Somestack)
if [[ "$ACTION" == "CREATE" ]] && [[ "$STATUS" == "COMPLETE" ]]
...
If you don't globally store your map object reference, I recommend
if (L.DomUtil.get('map-canvas') !== undefined) {
L.DomUtil.get('map-canvas')._leaflet_id = null;
}
where <div id="map-canvas"></div>
is the object the map has been drawn into.
This way you avoid recreating the html element, which would happen, were you to remove()
it.
Building on Chad's answer, you also want to add that function to the onload event to ensure it is resized when the page loads as well.
jQuery.event.add(window, "load", resizeFrame);
jQuery.event.add(window, "resize", resizeFrame);
function resizeFrame()
{
var h = $(window).height();
var w = $(window).width();
$("#elementToResize").css('height',(h < 768 || w < 1024) ? 500 : 400);
}
Was running into this problem using several different localhost servers. Finally got my app up and running on the phone in seconds just by using the Python simple server. It only takes a few seconds so is worth a try before getting into any more complicated solutions. First, make sure you have Python installed. cmd+r
and type python
for Windows or $ python --version
in mac terminal.
Next:
cd <your project root>
$ python -m SimpleHTTPServer 8000
Then just find the address of your host machine on the network, I used System Preferences/Sharing
on mac to find it. Tap that into your Android device and should load your index.html
and you should be good.
If not then the problem is something else and you may want to look into some of the other suggested solutions. Good luck!
* EDIT *
Another quick solution to try if you're using Chrome is the Web Server for Chrome extension. I found it a quick and super easy way to get access to localhost on my phone. Just make sure to check Accessible to local network
under the Options
and it should work on your cell without any problem.
The tool that richardtz suggests is excellent.
Another one that is amazing and comes with a 30 day free trial is Araxis Merge. This one does a 3 way merge and is much more feature complete than winmerge, but it is a commercial product.
You might also like to check out Scott Hanselman's developer tool list, which mentions a couple more in addition to winmerge
For this format (assuming datepart has the format dd-mm-yyyy) in plain javascript use dateString2Date
.
[Edit] Added an ES6 utility method to parse a date string using a format string parameter (format
) to inform the method about the position of date/month/year in the input string.
var result = document.querySelector('#result');_x000D_
_x000D_
result.textContent = _x000D_
`*Fixed\ndateString2Date('01-01-2016 00:03:44'):\n => ${_x000D_
dateString2Date('01-01-2016 00:03:44')}`;_x000D_
_x000D_
result.textContent += _x000D_
`\n\n*With formatting\ntryParseDateFromString('01-01-2016 00:03:44', 'dmy'):\n => ${_x000D_
tryParseDateFromString('01-01-2016 00:03:44', "dmy").toUTCString()}`;_x000D_
_x000D_
result.textContent += _x000D_
`\n\nWith formatting\ntryParseDateFromString('03/01/2016', 'mdy'):\n => ${_x000D_
tryParseDateFromString('03/01/1943', "mdy").toUTCString()}`;_x000D_
_x000D_
// fixed format dd-mm-yyyy_x000D_
function dateString2Date(dateString) {_x000D_
var dt = dateString.split(/\-|\s/);_x000D_
return new Date(dt.slice(0,3).reverse().join('-') + ' ' + dt[3]);_x000D_
}_x000D_
_x000D_
// multiple formats (e.g. yyyy/mm/dd or mm-dd-yyyy etc.)_x000D_
function tryParseDateFromString(dateStringCandidateValue, format = "ymd") {_x000D_
if (!dateStringCandidateValue) { return null; }_x000D_
let mapFormat = format_x000D_
.split("")_x000D_
.reduce(function (a, b, i) { a[b] = i; return a;}, {});_x000D_
const dateStr2Array = dateStringCandidateValue.split(/[ :\-\/]/g);_x000D_
const datePart = dateStr2Array.slice(0, 3);_x000D_
let datePartFormatted = [_x000D_
+datePart[mapFormat.y],_x000D_
+datePart[mapFormat.m]-1,_x000D_
+datePart[mapFormat.d] ];_x000D_
if (dateStr2Array.length > 3) {_x000D_
dateStr2Array.slice(3).forEach(t => datePartFormatted.push(+t));_x000D_
}_x000D_
// test date validity according to given [format]_x000D_
const dateTrial = new Date(Date.UTC.apply(null, datePartFormatted));_x000D_
return dateTrial && dateTrial.getFullYear() === datePartFormatted[0] &&_x000D_
dateTrial.getMonth() === datePartFormatted[1] &&_x000D_
dateTrial.getDate() === datePartFormatted[2]_x000D_
? dateTrial :_x000D_
null;_x000D_
}
_x000D_
<pre id="result"></pre>
_x000D_
Add a new Production Certificate here, then download the .cer file and double click it to add it to Keychain.
All will be fine now, don't forget to restart Xcode!!!
I do realize that my answer is way late for this question but I think the community would like a newer approach to this issue.
It sounds like you would benefit from using an automation utility. If you were using a windows PC I would recommend AutoHotkey. I haven't used automation utilities on a Mac, but this Ask Different post has several suggestions, though none appear to be free.
This is not a VBA solution. These macros run outside of Excel and can interact with programs using keyboard strokes, mouse movements and clicks.
Basically you record or write a simple automation macro that waits for the Excel "Save As" dialogue box to become active, hits enter/return to complete the save action and then waits for the "Save As" window to close. You can set it to run in a continuous loop until you manually end the macro.
Here's a simple version of a Windows AutoHotkey script that would accomplish what you are attempting to do on a Mac. It should give you an idea of the logic involved.
; ' Infinite loop. End the macro by closing the program from the Windows taskbar.
Loop {
; ' Wait for ANY "Save As" dialogue box in any program.
; ' BE CAREFUL!
; ' Ignore the "Confirm Save As" dialogue if attempt is made
; ' to overwrite an existing file.
WinWait, Save As,,, Confirm Save As
IfWinNotActive, Save As,,, Confirm Save As
WinActivate, Save As,,, Confirm Save As
WinWaitActive, Save As,,, Confirm Save As
sleep, 250 ; ' 0.25 second delay
Send, {ENTER} ; ' Save the Excel file.
; ' Wait for the "Save As" dialogue box to close.
WinWaitClose, Save As,,, Confirm Save As
}
Your function has a couple of smallint
parameters.
But in the call, you are using numeric literals that are presumed to be type integer
.
A string literal or string constant ('123'
) is not typed immediately. It remains type "unknown" until assigned or cast explicitly.
However, a numeric literal or numeric constant is typed immediately. Per documentation:
A numeric constant that contains neither a decimal point nor an exponent is initially presumed to be type
integer
if its value fits in typeinteger
(32 bits); otherwise it is presumed to be typebigint
if its value fits in typebigint
(64 bits); otherwise it is taken to be typenumeric
. Constants that contain decimal points and/or exponents are always initially presumed to be typenumeric
.
More explanation and links in this related answer:
Add explicit casts for the smallint
parameters or quote them.
CREATE OR REPLACE FUNCTION f_typetest(smallint)
RETURNS bool AS 'SELECT TRUE' LANGUAGE sql;
Incorrect call:
SELECT * FROM f_typetest(1);
Correct calls:
SELECT * FROM f_typetest('1');
SELECT * FROM f_typetest(smallint '1');
SELECT * FROM f_typetest(1::int2);
SELECT * FROM f_typetest('1'::int2);
db<>fiddle here
Old sqlfiddle.
If you're looking to do something with a list of files, you can use find combined with the bash $()
construct (better than backticks since it's allowed to nest).
for example, say you're at the top level of your project directory and you want a list of all C files starting with "btree". The command:
find . -type f -name 'btree*.c'
will return a list of them. But this doesn't really help with doing something with them.
So, let's further assume you want to search all those file for the string "ERROR" or edit them all. You can execute one of:
grep ERROR $(find . -type f -name 'btree*.c')
vi $(find . -type f -name 'btree*.c')
to do this.
The bit rate is a measure of the number of bits that are transmitted per unit of time.
The baud rate, which is also known as symbol rate, measures the number of symbols that are transmitted per unit of time. A symbol typically consists of a fixed number of bits depending on what the symbol is defined as(for example 8bit or 9bit data). The baud rate is measured in symbols per second.
Take an example, where an ascii character 'R' is transmitted over a serial channel every one second.
The binary equivalent is 01010010.
So in this case, the baud rate is 1(one symbol transmitted per second) and the bit rate is 8 (eight bits are transmitted per second).
You need to SAVE your code file with the ".py" extension. Then, on the 'Tools/Build System' menu, make sure your build system is set to either 'auto' or 'Python'. What that message is telling you is there is no valid Python file to 'build' (or, in this case just run).
You can use MessageDigest in the following way:
public static String getSHA256(String data){
StringBuffer sb = new StringBuffer();
try{
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(data.getBytes());
byte byteData[] = md.digest();
for (int i = 0; i < byteData.length; i++) {
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
} catch(Exception e){
e.printStackTrace();
}
return sb.toString();
}
I think you are misinterpreting the source of the error; rExternalTotal appears to be equal to a single cell.
rReportData.offset(0,0) is equal to rReportData
rReportData.offset(261,0).end(xlUp) is likely also equal to rReportData, as you offset by 261 rows and then use the .end(xlUp) function which selects the top of a contiguous data range.
If you are interested in the sum of just a column, you can just refer to the whole column:
dExternalTotal = Application.WorksheetFunction.Sum(columns("A:A"))
or
dExternalTotal = Application.WorksheetFunction.Sum(columns((rReportData.column))
The worksheet function sum will correctly ignore blank spaces.
Let me know if this helps!
Try this:
SELECT [DocumentID]
,[tmpRez].value('/x[2]', 'varchar(20)') AS [Status]
,[tmpRez].value('/x[3]', 'datetime') AS [DateCreated]
FROM (
SELECT [DocumentID]
,cast('<x>' + max(cast([ID] AS VARCHAR(10)) + '</x><x>' + [Status] + '</x><x>' + cast([DateCreated] AS VARCHAR(20))) + '</x>' AS XML) AS [tmpRez]
FROM DocumentStatusLogs
GROUP BY DocumentID
) AS [tmpQry]
You need to set permissions within SSRS in two places to give yourself initial access. The set-up program only gives access to Builtin\Administrators, to gain access in order to do this you need to right click you browser link and choose Run as administrator.
Simple example
Shamelessly adapted from: http://www.gnu.org/software/automake/manual/html_node/Creating-amhello.html and tested on Ubuntu 14.04 Automake 1.14.1.
Makefile.am
SUBDIRS = src
dist_doc_DATA = README.md
README.md
Some doc.
configure.ac
AC_INIT([automake_hello_world], [1.0], [[email protected]])
AM_INIT_AUTOMAKE([-Wall -Werror foreign])
AC_PROG_CC
AC_CONFIG_HEADERS([config.h])
AC_CONFIG_FILES([
Makefile
src/Makefile
])
AC_OUTPUT
src/Makefile.am
bin_PROGRAMS = autotools_hello_world
autotools_hello_world_SOURCES = main.c
src/main.c
#include <config.h>
#include <stdio.h>
int main (void) {
puts ("Hello world from " PACKAGE_STRING);
return 0;
}
Usage
autoreconf --install
mkdir build
cd build
../configure
make
sudo make install
autoconf_hello_world
sudo make uninstall
This outputs:
Hello world from automake_hello_world 1.0
Notes
autoreconf --install
generates several template files which should be tracked by Git, including Makefile.in
. It only needs to be run the first time.
make install
installs:
/usr/local/bin
README.md
to /usr/local/share/doc/automake_hello_world
On GitHub for you to try it out.
Change display:inline to display:inline-block
.test {
width:200px;
display:inline-block;
overflow: auto;
white-space: nowrap;
margin:0px auto;
border:1px red solid;
}
Ultimately they both produce the same HTML but Html.TextBoxFor() is strongly typed where as Html.TextBox isn't.
1: @Html.TextBox("Name")
2: Html.TextBoxFor(m => m.Name)
will both produce
<input id="Name" name="Name" type="text" />
So what does that mean in terms of use?
Generally two things:
TextBoxFor
will generate your input names for you. This is usually just the property name but for properties of complex types can include an underscore such as 'customer_name'TextBoxFor
version will allow you to use compile time checking. So if you change your model then you can check whether there are any errors in your views.It is generally regarded as better practice to use the strongly typed versions of the HtmlHelpers that were added in MVC2.
You get your browser's language for your button. There's no way to change it programmatically.
All of this works for me:
@Echo Off
Echo Directory = %~dp0
Echo Object Name With Quotations=%0
Echo Object Name Without Quotes=%~0
Echo Bat File Drive = %~d0
Echo Full File Name = %~n0%~x0
Echo File Name Without Extension = %~n0
Echo File Extension = %~x0
Pause>Nul
Output:
Directory = D:\Users\Thejordster135\Desktop\Code\BAT\
Object Name With Quotations="D:\Users\Thejordster135\Desktop\Code\BAT\Path_V2.bat"
Object Name Without Quotes=D:\Users\Thejordster135\Desktop\Code\BAT\Path_V2.bat
Bat File Drive = D:
Full File Name = Path.bat
File Name Without Extension = Path
File Extension = .bat
In the new ES2015 standard for JavaScript (formerly called ES6), objects can be created with computed keys: Object Initializer spec.
The syntax is:
var obj = {
[myKey]: value,
}
If applied to the OP's scenario, it would turn into:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
return {
[this.attr('name')]: this.attr('value'),
};
})
callback(null, inputs);
}
Note: A transpiler is still required for browser compatiblity.
Using Babel or Google's traceur, it is possible to use this syntax today.
In earlier JavaScript specifications (ES5 and below), the key in an object literal is always interpreted literally, as a string.
To use a "dynamic" key, you have to use bracket notation:
var obj = {};
obj[myKey] = value;
In your case:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
var key = this.attr('name')
, value = this.attr('value')
, ret = {};
ret[key] = value;
return ret;
})
callback(null, inputs);
}
The std::string object returned by ss.str() is a temporary object that will have a life time limited to the expression. So you cannot assign a pointer to a temporary object without getting trash.
Now, there is one exception: if you use a const reference to get the temporary object, it is legal to use it for a wider life time. For example you should do:
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
stringstream ss("this is a string\n");
string str(ss.str());
const char* cstr1 = str.c_str();
const std::string& resultstr = ss.str();
const char* cstr2 = resultstr.c_str();
cout << cstr1 // Prints correctly
<< cstr2; // No more error : cstr2 points to resultstr memory that is still alive as we used the const reference to keep it for a time.
system("PAUSE");
return 0;
}
That way you get the string for a longer time.
Now, you have to know that there is a kind of optimisation called RVO that say that if the compiler see an initialization via a function call and that function return a temporary, it will not do the copy but just make the assigned value be the temporary. That way you don't need to actually use a reference, it's only if you want to be sure that it will not copy that it's necessary. So doing:
std::string resultstr = ss.str();
const char* cstr2 = resultstr.c_str();
would be better and simpler.
How do these new categories relate to the existing rvalue and lvalue categories?
A C++03 lvalue is still a C++11 lvalue, whereas a C++03 rvalue is called a prvalue in C++11.
For non-servers this requires Remote Server Administration Tools for Windows __
You're getting None
because list.sort()
it operates in-place, meaning that it doesn't return anything, but modifies the list itself. You only need to call a.sort()
without assigning it to a
again.
There is a built in function sorted()
, which returns a sorted version of the list - a = sorted(a)
will do what you want as well.
Here's a summary of the ways to call external programs and the advantages and disadvantages of each:
os.system("some_command with args")
passes the command and arguments to your system's shell. This is nice because you can actually run multiple commands at once in this manner and set up pipes and input/output redirection. For example:
os.system("some_command < input_file | another_command > output_file")
However, while this is convenient, you have to manually handle the escaping of shell characters such as spaces, etc. On the other hand, this also lets you run commands which are simply shell commands and not actually external programs. See the documentation.
stream = os.popen("some_command with args")
will do the same thing as os.system
except that it gives you a file-like object that you can use to access standard input/output for that process. There are 3 other variants of popen that all handle the i/o slightly differently. If you pass everything as a string, then your command is passed to the shell; if you pass them as a list then you don't need to worry about escaping anything. See the documentation.
The Popen
class of the subprocess
module. This is intended as a replacement for os.popen
but has the downside of being slightly more complicated by virtue of being so comprehensive. For example, you'd say:
print subprocess.Popen("echo Hello World", shell=True, stdout=subprocess.PIPE).stdout.read()
instead of:
print os.popen("echo Hello World").read()
but it is nice to have all of the options there in one unified class instead of 4 different popen functions. See the documentation.
The call
function from the subprocess
module. This is basically just like the Popen
class and takes all of the same arguments, but it simply waits until the command completes and gives you the return code. For example:
return_code = subprocess.call("echo Hello World", shell=True)
See the documentation.
If you're on Python 3.5 or later, you can use the new subprocess.run
function, which is a lot like the above but even more flexible and returns a CompletedProcess
object when the command finishes executing.
The os module also has all of the fork/exec/spawn functions that you'd have in a C program, but I don't recommend using them directly.
The subprocess
module should probably be what you use.
Finally please be aware that for all methods where you pass the final command to be executed by the shell as a string and you are responsible for escaping it. There are serious security implications if any part of the string that you pass can not be fully trusted. For example, if a user is entering some/any part of the string. If you are unsure, only use these methods with constants. To give you a hint of the implications consider this code:
print subprocess.Popen("echo %s " % user_input, stdout=PIPE).stdout.read()
and imagine that the user enters something "my mama didnt love me && rm -rf /" which could erase the whole filesystem.
You can use the union operator (+
) to combine arrays and keep the keys of the added array. For example:
<?php
$arr1 = array('foo' => 'bar');
$arr2 = array('baz' => 'bof');
$arr3 = $arr1 + $arr2;
print_r($arr3);
// prints:
// array(
// 'foo' => 'bar',
// 'baz' => 'bof',
// );
So you could do $_GET += array('one' => 1);
.
There's more info on the usage of the union operator vs array_merge
in the documentation at http://php.net/manual/en/function.array-merge.php.
We had a problem like this some weeks before. If you set a breakpoint and have a deep look into this.Controls
, the problem reveals it's nature: you have to recurse through all child controls.
The code could look like this:
private void CleanForm()
{
traverseControlsAndSetTextEmpty(this);
}
private void traverseControlsAndSetTextEmpty(Control control)
{
foreach(var c in control.Controls)
{
if (c is TextBox) ((TextBox)c).Text = String.Empty;
traverseControlsAndSetTextEmpty(c);
}
}
From book :
Choose a Random Row Using an Offset
Still another technique that avoids problems found in the preceding alternatives is to count the rows in the data set and return a random number between 0 and the count. Then use this number as an offset when querying the data set
$rand = "SELECT ROUND(RAND() * (SELECT COUNT(*) FROM Bugs))";
$offset = $pdo->query($rand)->fetch(PDO::FETCH_ASSOC);
$sql = "SELECT * FROM Bugs LIMIT 1 OFFSET :offset";
$stmt = $pdo->prepare($sql);
$stmt->execute( $offset );
$rand_bug = $stmt->fetch();
Use this solution when you can’t assume contiguous key values and you need to make sure each row has an even chance of being selected.
Try with this code, you will get the image preview while uploading
<input type='file' id="upload" onChange="readURL(this);"/>
<img id="img" src="#" alt="your image" />
function readURL(input){
var ext = input.files[0]['name'].substring(input.files[0]['name'].lastIndexOf('.') + 1).toLowerCase();
if (input.files && input.files[0] && (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg"))
var reader = new FileReader();
reader.onload = function (e) {
$('#img').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}else{
$('#img').attr('src', '/assets/no_preview.png');
}
}
How about this? Again, using indices
> m <- c(1:5)
> m
[1] 1 2 3 4 5
> m[1:length(m)-1]
[1] 1 2 3 4
or
> m[-(length(m))]
[1] 1 2 3 4
Please use the following query to list the tables in your DB.
select name from sys.Tables
In Addition, you can add a where
condition, to skip system generated tables and lists only user created table by adding type ='U'
Ex : select name from sys.Tables where type ='U'
You can employ the use of data in jQuery and catch all of the events which then tests it against it's last value (untested):
$(document).ready(function() {
$("#fieldId").bind("keyup keydown keypress change blur", function() {
if ($(this).val() != jQuery.data(this, "lastvalue") {
alert("changed");
}
jQuery.data(this, "lastvalue", $(this).val());
});
});
This would work pretty good against a long list of items too. Using jQuery.data
means you don't have to create a javascript variable to track the value. You could do $("#fieldId1, #fieldId2, #fieldId3, #fieldId14, etc")
to track many fields.
UPDATE: Added blur
to the bind
list.
Yes, you will need the mysql c++ connector library. Read on below, where I explain how to get the example given by mysql developers to work.
Note(and solution): IDE: I tried using Visual Studio 2010, but just a few sconds ago got this all to work, it seems like I missed it in the manual, but it suggests to use Visual Studio 2008. I downloaded and installed VS2008 Express for c++, followed the steps in chapter 5 of manual and errors are gone! It works. I'm happy, problem solved. Except for the one on how to get it to work on newer versions of visual studio. You should try the mysql for visual studio addon which maybe will get vs2010 or higher to connect successfully. It can be downloaded from mysql website
Whilst trying to get the example mentioned above to work, I find myself here from difficulties due to changes to the mysql dev website. I apologise for writing this as an answer, since I can't comment yet, and will edit this as I discover what to do and find the solution, so that future developers can be helped.(Since this has gotten so big it wouldn't have fitted as a comment anyways, haha)
@hd1 link to "an example" no longer works. Following the link, one will end up at the page which gives you link to the main manual. The main manual is a good reference, but seems to be quite old and outdated, and difficult for new developers, since we have no experience especially if we missing a certain file, and then what to add.
@hd1's link has moved, and can be found with a quick search by removing the url components, keeping just the article name, here it is anyways: http://dev.mysql.com/doc/connector-cpp/en/connector-cpp-examples-complete-example-1.html
Getting 7.5 MySQL Connector/C++ Complete Example 1 to work
Downloads:
-Get the mysql c++ connector, even though it is bigger choose the installer package, not the zip.
-Get the boost libraries from boost.org, since boost is used in connection.h and mysql_connection.h from the mysql c++ connector
Now proceed:
-Install the connector to your c drive, then go to your mysql server install folder/lib and copy all libmysql files, and paste in your connector install folder/lib/opt
-Extract the boost library to your c drive
Next:
It is alright to copy the code as it is from the example(linked above, and ofcourse into a new c++ project). You will notice errors:
-First: change
cout << "(" << __FUNCTION__ << ") on line " »
<< __LINE__ << endl;
to
cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;
Not sure what that tiny double arrow is for, but I don't think it is part of c++
-Second: Fix other errors of them by reading Chapter 5 of the sql manual, note my paragraph regarding chapter 5 below
[Note 1]: Chapter 5 Building MySQL Connector/C++ Windows Applications with Microsoft Visual Studio If you follow this chapter, using latest c++ connecter, you will likely see that what is in your connector folder and what is shown in the images are quite different. Whether you look in the mysql server installation include and lib folders or in the mysql c++ connector folders' include and lib folders, it will not match perfectly unless they update the manual, or you had a magic download, but for me they don't match with a connector download initiated March 2014.
Just follow that chapter 5,
-But for c/c++, General, Additional Include Directories include the "include" folder from the connector you installed, not server install folder
-While doing the above, also include your boost folder see note 2 below
-And for the Linker, General.. etc use the opt folder from connector/lib/opt
*[Note 2]*A second include needs to happen, you need to include from the boost library variant.hpp, this is done the same as above, add the main folder you extracted from the boost zip download, not boost or lib or the subfolder "variant" found in boostmainfolder/boost.. Just the main folder as the second include
Next:
What is next I think is the Static Build, well it is what I did anyways. Follow it.
Then build/compile. LNK errors show up(Edit: Gone after changing ide to visual studio 2008). I think it is because I should build connector myself(if you do this in visual studio 2010 then link errors should disappear), but been working on trying to get this to work since Thursday, will see if I have the motivation to see this through after a good night sleep(and did and now finished :) ).
You need to import the map
operator:
import 'rxjs/add/operator/map'
Or more generally:
import 'rxjs/Rx';
Notice: For versions of RxJS 6.x.x
and above, you will have to use pipeable operators as shown in the code snippet below:
import { map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
// ...
export class MyComponent {
constructor(private http: HttpClient) { }
getItems() {
this.http.get('https://example.com/api/items').pipe(map(data => {})).subscribe(result => {
console.log(result);
});
}
}
This is caused by the RxJS team removing support for using See the breaking changes in RxJS' changelog for more info.
From the changelog:
operators: Pipeable operators must now be imported from rxjs like so:
import { map, filter, switchMap } from 'rxjs/operators';
. No deep imports.
I ran into this recently and eventually found that this was caused by a network timeout from the endpoint we were hitting. Fortunately for us we were able to increase the timeout duration.
To verify this was our issue (and actually not an issue with net http), I made the same request with curl and confirmed that the request was being terminated.
With SQL 2012 and later, you could use TRY_CAST
/TRY_CONVERT
to try converting to a numeric type, e.g. TRY_CAST(answer AS float) IS NOT NULL
-- note though that this will match scientific notation too (1+E34). (If you use decimal
, then scientific notation won't match)
The best examples are those with fasm, because fasm doesn't use a linker, which hides the complexity of windows programming by another opaque layer of complexity. If you're content with a program that writes into a gui window, then there is an example for that in fasm's example directory.
If you want a console program, that allows redirection of standard in and standard out that is also possible. There is a (helas highly non-trivial) example program available that doesn't use a gui, and works strictly with the console, that is fasm itself. This can be thinned out to the essentials. (I've written a forth compiler which is another non-gui example, but it is also non-trivial).
Such a program has the following command to generate a proper header for 32-bit executable, normally done by a linker.
FORMAT PE CONSOLE
A section called '.idata' contains a table that helps windows during startup to couple names of functions to the runtimes addresses. It also contains a reference to KERNEL.DLL which is the Windows Operating System.
section '.idata' import data readable writeable
dd 0,0,0,rva kernel_name,rva kernel_table
dd 0,0,0,0,0
kernel_table:
_ExitProcess@4 DD rva _ExitProcess
CreateFile DD rva _CreateFileA
...
...
_GetStdHandle@4 DD rva _GetStdHandle
DD 0
The table format is imposed by windows and contains names that are looked up in system files, when the program is started. FASM hides some of the complexity behind the rva keyword. So _ExitProcess@4 is a fasm label and _exitProcess is a string that is looked up by Windows.
Your program is in section '.text'. If you declare that section readable writeable and executable, it is the only section you need to add.
section '.text' code executable readable writable
You can call all the facilities you declared in the .idata section. For a console program you need _GetStdHandle to find he filedescriptors for standard in and standardout (using symbolic names like STD_INPUT_HANDLE which fasm finds in the include file win32a.inc). Once you have the file descriptors you can do WriteFile and ReadFile. All functions are described in the kernel32 documentation. You are probably aware of that or you wouldn't try assembler programming.
In summary: There is a table with asci names that couple to the windows OS. During startup this is transformed into a table of callable addresses, which you use in your program.
set -x
enables a mode of the shell where all executed commands are printed to the terminal. In your case it's clearly used for debugging, which is a typical use case for set -x
: printing every command as it is executed may help you to visualize the control flow of the script if it is not functioning as expected.
set +x
disables it.
You can use the following function:
function getCookiesMap(cookiesString) {
return cookiesString.split(";")
.map(function(cookieString) {
return cookieString.trim().split("=");
})
.reduce(function(acc, curr) {
acc[curr[0]] = curr[1];
return acc;
}, {});
}
When, called with document.cookie as parameter, it will return an object, with the cookies keys as keys and the cookies values.
var cookies = getCookiesMap(document.cookie);
var cookieValue = cookies["MYBIGCOOKIE"];
Cmd+Option+Shift? / ? works for me on newest VSCode 1.29.1 and newest OSX High Sierra 10.13.6, Macbook Pro.
This adds a vertical line up/down on screen, like Option+Click/Vertical Drag does in Sublime Text.
To add multiple cursors at any points in your file, including multiple ones on the same line, do Cmd (or Option)+Click anywhere you want, shown in this video. You may also search for text (Cmd+F) that repeats multiple times, then press Option+Return to add cursors at end of EACH word.
map()
doesn't return a list, it returns a map
object.
You need to call list(map)
if you want it to be a list again.
Even better,
from itertools import imap
payIntList = list(imap(int, payList))
Won't take up a bunch of memory creating an intermediate object, it will just pass the ints
out as it creates them.
Also, you can do if choice.lower() == 'n':
so you don't have to do it twice.
Python supports +=
: you can do payIntList[i] += 1000
and numElements += 1
if you want.
If you really want to be tricky:
from itertools import count
for numElements in count(1):
payList.append(raw_input("Enter the pay amount: "))
if raw_input("Do you wish to continue(y/n)?").lower() == 'n':
break
and / or
for payInt in payIntList:
payInt += 1000
print payInt
Also, four spaces is the standard indent amount in Python.
See also a lot of general hints and useful links at the regex tag details page.
Online tutorials
Quantifiers
*
:greedy, *?
:reluctant, *+
:possessive+
:greedy, +?
:reluctant, ++
:possessive?
:optional (zero-or-one){n,m}
:between n & m, {n,}
:n-or-more, {n}
:exactly n{n}
and {n}?
Character Classes
[...]
: any one character, [^...]
: negated/any character but[^]
matches any one character including newlines javascript[\w-[\d]]
/ [a-z-[qz]]
: set subtraction .net, xml-schema, xpath, JGSoft[\w&&[^\d]]
: set intersection java, ruby 1.9+[[:alpha:]]
:POSIX character classes[^\\D2]
, [^[^0-9]2]
, [^2[^0-9]]
get different results in Java? java\d
:digit, \D
:non-digit\w
:word character, \W
:non-word character\s
:whitespace, \S
:non-whitespace\p{L}, \P{L}
, etc.)Escape Sequences
\h
:space-or-tab, \t
:tab\H
:Non horizontal whitespace character, \V
:Non vertical whitespace character, \N
:Non line feed character pcre php5 java-8\v
:vertical tab, \e
:the escape characterAnchors
^
:start of line/input, \b
:word boundary, and \B
:non-word boundary, $
:end of line/input\A
:start of input, \Z
:end of input php, perl, ruby\z
:the very end of input (\Z
in Python) .net, php, pcre, java, ruby, icu, swift, objective-c\G
:start of match php, perl, ruby(Also see "Flavor-Specific Information ? Java ? The functions in Matcher
")
Groups
(...)
:capture group, (?:)
:non-capture group
\1
:backreference and capture-group reference, $1
:capture group reference
(?i:regex)
mean?(?P<group_name>regexp)
mean?(?>)
:atomic group or independent group, (?|)
:branch reset
regular-expressions.info
(?<groupname>regex)
: Overview and naming rules (Non-Stack Overflow links)(?P<groupname>regex)
python, (?<groupname>regex)
.net, (?<groupname>regex)
perl, (?P<groupname>regex)
and (?<groupname>regex)
phpLookarounds
(?=...)
:positive, (?!...)
:negative(?<=...)
:positive, (?<!...)
:negative (not supported by javascript)Modifiers
flag | modifier | flavors |
---|---|---|
c |
current position | perl |
e |
expression | php perl |
g |
global | most |
i |
case-insensitive | most |
m |
multiline | php perl python javascript .net java |
m |
(non)multiline | ruby |
o |
once | perl ruby |
S |
study | php |
s |
single line | unsupported: javascript (workaround) | ruby |
U |
ungreedy | php r |
u |
unicode | most |
x |
whitespace-extended | most |
y |
sticky ? | javascript |
Other:
|
:alternation (OR) operator, .
:any character, [.]
:literal dot character(*PRUNE)
, (*SKIP)
, (*FAIL)
and (*F)
(*BSR_ANYCRLF)
(?R)
, (?0)
and (?1)
, (?-1)
, (?&groupname)
Common Tasks
{...}
Advanced Regex-Fu
(?!a)a
this
except in contexts A, B and CFlavor-Specific Information
(Except for those marked with *
, this section contains non-Stack Overflow links.)
java.util.regex.Matcher
:
matches()
): The match must be anchored to both input-start and -endfind()
): A match may be anywhere in the input string (substrings)lookingAt()
: The match must be anchored to input-start onlyjava.lang.String
functions that accept regular expressions: matches(s)
, replaceAll(s,s)
, replaceFirst(s,s)
, split(s)
, split(s,i)
java.util.regex
preg_match
search
vs match
, how-toregex
, struct regex::Regex
regexp
commandGeneral information
(Links marked with *
are non-Stack Overflow links.)
Examples of regex that can cause regex engine to fail
Tools: Testers and Explainers
(This section contains non-Stack Overflow links.)
You probably want to read in more numbers, not only one. For this, you need a loop
int main()
{
int input = 0;
while(input != -1){
vector<int> V;
cout << "Enter your numbers to be evaluated: " << endl;
cin >> input;
V.push_back(input);
write_vector(V);
}
return 0;
}
Note, with this version, it is not possible to add the number -1 as it is the "end signal". Type numbers as long as you like, it will be aborted when you type -1.
The 2
in Anaconda2
means that the main version of Python will be 2.x rather than the 3.x installed in Anaconda3
. The current release has Python 2.7.13.
The 4.4.0.1
is the version number of Anaconda. The current advertised version is 4.4.0
and I assume the .1
is a minor release or for other similar use. The Windows releases, which I use, just say 4.4.0
in the file name.
Others have now explained the difference between Anaconda and Miniconda, so I'll skip that.
Had the same problem. Since you can still get data using the .data() method, you only have to figure out a way to write to the elements. This is the helper method I use. Like most people have said, you will have to use .attr. I have it replacing any _ with - as I know it does that. I'm not aware of any other characters it replaces...however I have not researched that.
function ExtendElementData(element, object){
//element is what you want to set data on
//object is a hash/js-object
var keys = Object.keys(object);
for (var i = 0; i < keys.length; i++){
var key = keys[i];
$(element).attr('data-'+key.replace("_", "-"), object[key]);
}
}
EDIT: 5/1/2017
I found there were still instances where you could not get the correct data using built in methods so what I use now is as follows:
function setDomData(element, object){
//object is a hash
var keys = Object.keys(object);
for (var i = 0; i < keys.length; i++){
var key = keys[i];
$(element).attr('data-'+key.replace("_", "-"), object[key]);
}
};
function getDomData(element, key){
var domObject = $(element).get(0);
var attKeys = Object.keys(domObject.attributes);
var values = null;
if (key != null){
values = $(element).attr('data-' + key);
} else {
values = {};
var keys = [];
for (var i = 0; i < attKeys.length; i++) {
keys.push(domObject.attributes[attKeys[i]]);
}
for (var i = 0; i < keys.length; i++){
if(!keys[i].match(/data-.*/)){
values[keys[i]] = $(element).attr(keys[i]);
}
}
}
return values;
};
I wrote rabbitmq-dump-queue which allows dumping messages from a RabbitMQ queue to local files and requeuing the messages in their original order.
Example usage (to dump the first 50 messages of queue incoming_1
):
rabbitmq-dump-queue -url="amqp://user:[email protected]:5672/" -queue=incoming_1 -max-messages=50 -output-dir=/tmp
public static void main(String[] args) {
String test = "something hear - to - find some to or tows";
System.out.println("1.result: " + contains("- to -( \\w+) som", test, null));
System.out.println("2.result: " + contains("- to -( \\w+) som", test, 5));
}
static boolean contains(String pattern, String text, Integer fromIndex){
if(fromIndex != null && fromIndex < text.length())
return Pattern.compile(pattern).matcher(text).find();
return Pattern.compile(pattern).matcher(text).find();
}
1.result: true
2.result: true
_x000D_
_x000D_
/* add javascript*/_x000D_
{_x000D_
document.getElementById('abc 1').style.display='none';_x000D_
}_x000D_
/* after that add html*/_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
<title>...</title>_x000D_
</head>_x000D_
<body>_x000D_
<table border = 2>_x000D_
<tr id = "abc 1">_x000D_
<td>abcd</td>_x000D_
</tr>_x000D_
<tr id ="abc 2">_x000D_
<td>efgh</td>_x000D_
</tr>_x000D_
</table>_x000D_
</body>_x000D_
</html>_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
Did you maybe use some <tab>
instead of spaces?
Try remove all the spaces before the code and readd them using <space>
characters, just to be sure it's not a <tab>
.
Some other ideas not mentioned yet:
switch(true){
case in_array($p, array('home', '')):
$current_home = 'current'; break;
case preg_match('/^users\.(online|location|featured|new|browse|search|staff)$/', $p):
$current_users = 'current'; break;
case 'forum' == $p:
$current_forum = 'current'; break;
}
Someone will probably complain about readability issues with #2, but I would have no problem inheriting code like that.
I was encountering this error while compiling my application with SDL. This was caused by SDL defining it's own main function in SDL_main.h. To prevent SDL define the main function an SDL_MAIN_HANDLED macro has to be defined before the SDL.h header is included.
Array loop:
for(var i = 0; i < things.length; i++){
var thing = things[i];
console.log(thing);
}
Object loop:
for(var prop in obj){
var propValue = obj[prop];
console.log(propValue);
}
Instead of comparison methods you may want to just define several types of "Comparator" subclasses inside the Person class. That way you can pass them into standard Collections sorting methods.
From memory, it's either this
SELECT * FROM sys.objects
WHERE type = 'PK'
AND object_id = OBJECT_ID ('tableName')
or this..
SELECT * FROM sys.objects
WHERE type = 'PK'
AND parent_object_id = OBJECT_ID ('tableName')
I think one of them should probably work depending on how the data is stored but I am afraid I have no access to SQL to actually verify the same.
Can I see (...) the real SQL
If you want to see the SQL sent directly to the database (that is formatted similar to your example), you'll have to use some kind of jdbc driver proxy like P6Spy (or log4jdbc).
Alternatively you can enable logging of the following categories (using a log4j.properties
file here):
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE
The first is equivalent to hibernate.show_sql=true
, the second prints the bound parameters among other things.
The cause for this might be your current NPM registry. Try to check for a .npmrc
file. These can be at various locations:
/path/to/my/project/.npmrc
)~/.npmrc
)$PREFIX/etc/npmrc
)/path/to/npm/npmrc
)Within these there can be something like
registry=https://mycustomregistry.example.org
which will take priority over the default one (http://registry.npmjs.org/
). You can delete this line in the file or use the default registry like that:
npm <command> --registry http://registry.npmjs.org/
If you have plugin for Maven in Eclipse, you can do following:
right click on your project -> Maven -> Enable Dependency Management
This will convert your project to Maven and creates a pom.xml
. Fast and simple...
"net send" is a command using a background service called "messenger". This service has been removed from Windows 7. ie You cannot use 'net send' on Vista nor Win7 / Win8.
Pity though , I loved using it.
There is alternatives, but that requires you to download and install software on each pc you want to use, this software runs as background services, and i would advise one to be very very very very careful of using these kind of software as they can potentially cause seriously damage one's system or impair the systems securities.
winsent innocenti / winsent messenger
****This command is risky because of what is stated above***
Go to Control Panel\User Accounts\Credential Manager
and select Windows Credential
then remove account of git.
I had the same problem, however, it worked for me with the following settings:
bulk insert schema.table
from '\\your\data\source.csv'
with (
datafiletype = 'char'
,format = 'CSV'
,firstrow = 2
,fieldterminator = '|'
,rowterminator = '\n'
,tablock
)
My CSV-File looks like this:
"col1"|"col2"
"val1"|"val2"
"val3"|"val4"
My problem was, I had rowterminator set to '0x0a' before, it did not work. Once I changed it to '\n', it started working...
Normaly, you can create a reference for an interface. But you cant create an instance for interface.
I forgot to tell a bug when i use I use req.session.email = req.param('email'), the server error says cannot sett property email of undefined.
The reason of this error is a wrong order of app.use. You must configure express in this order:
app.use(express.cookieParser());
app.use(express.session({ secret: sessionVal }));
app.use(app.route);
If the issue is case sensitivity (which can be a problem when checking out to a Mac, as well as Windows) and you don't have the option of checking out onto a *nix system, the following should work. Here's the process from the beginning:
% svn co http://[domain]/svn/mortgages mortgages
(Checkout ensues… then…)
svn: In directory 'mortgages/trunk/images/rates'
svn: Can't open file 'mortgages/trunk/images/rates/.svn/tmp/text-base/Header_3_nobookmark.gif.svn-base': No such file or directory
Here SVN is trying to check out two files with similar names that differ only by case - Header_3_noBookmark.gif
and Header_3_nobookmark.gif
. Mac filesystems default to case insensitivity in a way that causes SVN to choke in situations like this. So...
% cd mortgages/trunk/images/rates/
% svn up
svn: Working copy '.' locked
svn: run 'svn cleanup' to remove locks (type 'svn help cleanup' for details)
However, running svn cleanup
doesn't work, as we know.
% svn cleanup
svn: In directory '.'
svn: Error processing command 'modify-wcprop' in '.'
svn: 'spacer.gif' is not under version control
spacer.gif
isn't the problem here… It just can't move past the previous error to the next file. So I deleted all of the files from the directory other than .svn
, and removed the SVN log. This made cleanup work, so that I could check out and rename the offending file.
% rm *; rm -rf .svn/log; svn cleanup
% svn up Header_3_nobookmark.gif
A Header_3_nobookmark.gif
Updated to revision 1087.
% svn mv Header_3_nobookmark.gif foo
A foo
D Header_3_nobookmark.gif
% svn up
A spacer.gif
A Header_3_noBookmark.gif
Following this, I was able to go back to the root directory of the project, and run svn up
to check out the rest of it.
In a servlet based artifact, such as @WebServlet
, @WebFilter
and @WebListener
, you can grab a "plain vanilla" JSF @ManagedBean @RequestScoped
by:
Bean bean = (Bean) request.getAttribute("beanName");
and @ManagedBean @SessionScoped
by:
Bean bean = (Bean) request.getSession().getAttribute("beanName");
and @ManagedBean @ApplicationScoped
by:
Bean bean = (Bean) getServletContext().getAttribute("beanName");
Note that this prerequires that the bean is already autocreated by JSF beforehand. Else these will return null
. You'd then need to manually create the bean and use setAttribute("beanName", bean)
.
If you're able to use CDI @Named
instead of the since JSF 2.3 deprecated @ManagedBean
, then it's even more easy, particularly because you don't anymore need to manually create the beans:
@Inject
private Bean bean;
Note that this won't work when you're using @Named @ViewScoped
because the bean can only be identified by JSF view state and that's only available when the FacesServlet
has been invoked. So in a filter which runs before that, accessing an @Inject
ed @ViewScoped
will always throw ContextNotActiveException
.
Only when you're inside @ManagedBean
, then you can use @ManagedProperty
:
@ManagedProperty("#{bean}")
private Bean bean;
Note that this doesn't work inside a @Named
or @WebServlet
or any other artifact. It really works inside @ManagedBean
only.
If you're not inside a @ManagedBean
, but the FacesContext
is readily available (i.e. FacesContext#getCurrentInstance()
doesn't return null
), you can also use Application#evaluateExpressionGet()
:
FacesContext context = FacesContext.getCurrentInstance();
Bean bean = context.getApplication().evaluateExpressionGet(context, "#{beanName}", Bean.class);
which can be convenienced as follows:
@SuppressWarnings("unchecked")
public static <T> T findBean(String beanName) {
FacesContext context = FacesContext.getCurrentInstance();
return (T) context.getApplication().evaluateExpressionGet(context, "#{" + beanName + "}", Object.class);
}
and can be used as follows:
Bean bean = findBean("bean");
This is the longer version of what Eliah Kagan was espousing:
while [ $(( i-- )) -gt 0 ]; do echo -n " "; done
Of course you can use printf for that as well, but not really to my liking:
printf "%$(( i*2 ))s"
This version is Dash compatible:
until [ $(( i=i-1 )) -lt 0 ]; do echo -n " "; done
with i being the initial number.
Why not Attributed String !?!, this is one of the blessing feature of IOS 6.0 :)
NSMutableParagraphStyle *mps = [[NSMutableParagraphStyle alloc] init];
mps.firstLineHeadIndent = 5.0f;
UIColor *placeColor = self.item.bgColor;
textFieldInstance.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"My Place Holder" attributes:@{NSForegroundColorAttributeName: placeColor, NSFontAttributeName : [UIFont systemFontOfSize:7.0f], NSParagraphStyleAttributeName : mps}];
As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:
var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da
For Node.js v5.11.1 and below
Construct a new Buffer
and pass 'base64'
as the second argument:
var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da
If you want to be clean, you can check whether from
exists :
if (typeof Buffer.from === "function") {
// Node 5.10+
buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
// older Node versions, now deprecated
buf = new Buffer(b64string, 'base64'); // Ta-da
}
Constructor will be helpful to prevent instances getting unreal values. For an example set a Person class with height , weight. There can't be a Person with 0m and 0kg
You have to load the db library first. In autoload.php
add :
$autoload['libraries'] = array('database');
Also, try renaming User model class for "User_model".
There is now another way to install the gcc toolchain on OS X through the osx-gcc-installer this includes:
The download is 282MB vs 3GB for Xcode.
If I understood you right, you want to copy $var
in a file (if it's a string).
echo $var > $destdir
In lisp
(defun pick-random (set)
(nth (random (length set)) set))
A friendly method to use is the following, once prop updates it will automatically rerender component:
render {
let textWhenComponentUpdate = this.props.text
return (
<View>
<Text>{textWhenComponentUpdate}</Text>
</View>
)
}
Yes, you can always use null
instead of an object. Just be careful because some methods might throw error.
It would be 1.
also null
s would be factored in in the for loop, but you could use
for(Item i : itemList) {
if (i!= null) {
//code here
}
}
For VB.lovers the VB.NET equivalent of Luke Quinane's code (thanks Luke!)
Imports System
Imports System.Net
Imports System.Runtime.InteropServices
Imports System.ComponentModel
Public Class NetworkConnection
Implements IDisposable
Private _networkName As String
Public Sub New(networkName As String, credentials As NetworkCredential)
_networkName = networkName
Dim netResource = New NetResource() With {
.Scope = ResourceScope.GlobalNetwork,
.ResourceType = ResourceType.Disk,
.DisplayType = ResourceDisplaytype.Share,
.RemoteName = networkName
}
Dim userName = If(String.IsNullOrEmpty(credentials.Domain), credentials.UserName, String.Format("{0}\{1}", credentials.Domain, credentials.UserName))
Dim result = WNetAddConnection2(NetResource, credentials.Password, userName, 0)
If result <> 0 Then
Throw New Win32Exception(result, "Error connecting to remote share")
End If
End Sub
Protected Overrides Sub Finalize()
Try
Dispose (False)
Finally
MyBase.Finalize()
End Try
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Dispose (True)
GC.SuppressFinalize (Me)
End Sub
Protected Overridable Sub Dispose(disposing As Boolean)
WNetCancelConnection2(_networkName, 0, True)
End Sub
<DllImport("mpr.dll")> _
Private Shared Function WNetAddConnection2(netResource As NetResource, password As String, username As String, flags As Integer) As Integer
End Function
<DllImport("mpr.dll")> _
Private Shared Function WNetCancelConnection2(name As String, flags As Integer, force As Boolean) As Integer
End Function
End Class
<StructLayout(LayoutKind.Sequential)> _
Public Class NetResource
Public Scope As ResourceScope
Public ResourceType As ResourceType
Public DisplayType As ResourceDisplaytype
Public Usage As Integer
Public LocalName As String
Public RemoteName As String
Public Comment As String
Public Provider As String
End Class
Public Enum ResourceScope As Integer
Connected = 1
GlobalNetwork
Remembered
Recent
Context
End Enum
Public Enum ResourceType As Integer
Any = 0
Disk = 1
Print = 2
Reserved = 8
End Enum
Public Enum ResourceDisplaytype As Integer
Generic = &H0
Domain = &H1
Server = &H2
Share = &H3
File = &H4
Group = &H5
Network = &H6
Root = &H7
Shareadmin = &H8
Directory = &H9
Tree = &HA
Ndscontainer = &HB
End Enum
use:
var parsedobj = jQuery.parseJSON( jsonObj);
This will only be useful if you don't need the format to stay in string. otherwise you'd have to convert this back to JSON using the JSON library.
Different case but may help someone,
In my case Window firewall was enabled on Server,
Two thinks can be done,
1) Disable windows firewall (your on risk but it will get thing work)
2) Add port in inbound rule.
Thanks .
if __name__ == "__main__":
is basically the top-level script environment, and it specifies the interpreter that ('I have the highest priority to be executed first').
'__main__'
is the name of the scope in which top-level code executes. A module’s __name__
is set equal to '__main__'
when read from standard input, a script, or from an interactive prompt.
if __name__ == "__main__":
# Execute only if run as a script
main()
All the answers here seem to be around service and factory, and that's valid since that was what was being asked about. But it's also important to keep in mind that there are several others including provider()
, value()
, and constant()
.
The key to remember is that each one is a special case of the other. Each special case down the chain allowing you to do the same thing with less code. Each one also having some additional limitation.
To decide when to use which you just see which one allows you to do what you want in less code. Here is an image illustrating just how similar they are:
For a complete step by step breakdown and quick reference of when to use each you can visit the blog post where I got this image from:
On Java 9 or later, Map.entry
can be used, so long as you know that neither the key nor value will be null. If either value could legitimately be null, AbstractMap.SimpleEntry
(as suggested in another answer) or AbstractMap.SimpleImmutableEntry
would be the way to go.
private Map<String, AttributeType> mapConfig(Map<String, String> input, String prefix) {
int subLength = prefix.length();
return input.entrySet().stream().map(e ->
Map.entry(e.getKey().substring(subLength), AttributeType.GetByName(e.getValue())));
}).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
I had a similar issue where I was not able to either install a CRX file into Chrome.
It turns out that since I had my Downloads folder set to a network mapped drive, it would not allow Chrome to install any extensions and would either do nothing (drag and drop on Chrome) or ask me to download the extension (if I clicked a link from the Web Store).
Setting the Downloads folder to a local disk directory instead of a network directory allowed extensions to be installed.
Running: 20.0.1132.57 m
The cursor should be closed after opening it.
Here is an example.
public static int getOrientation(Context context, Uri selectedImage)
{
int orientation = -1;
Cursor cursor = context.getContentResolver().query(selectedImage,
new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);
if (cursor.getCount() != 1)
return orientation;
cursor.moveToFirst();
orientation = cursor.getInt(0);
cursor.close(); // ADD THIS LINE
return orientation;
}
Create Table as select (CTAS) is possible in Hive.
You can try out below command:
CREATE TABLE new_test
row format delimited
fields terminated by '|'
STORED AS RCFile
AS select * from source where col=1
Create table like is also possible in Hive.
Say you have defined your class like this:
@Data
@AllArgsConstructor(staticName = "of")
private class Pair<P,Q> {
public P first;
public Q second;
}
So when you will need to create a new instance, it will need to take the parameters and you will provide it like this as defined in the annotation.
Pair<Integer, String> pair = Pair.of(menuItemId, category);
If you define it like this, you will get the error asked for.
Pair<Integer, String> pair = new Pair(menuItemId, category);
Though It's late to answer. This module can do: https://github.com/danghvu/mod_dumpost
If you have direct access to the remote repo, you could always use:
git reset --soft HEAD^
This works since there is no attempt to modify the non-existent working directory. For more details please see the original answer:
How can I uncommit the last commit in a git bare repository?
If your database client connects with TCP/IP and you have ident auth configured in your pg_hba.conf check that you have an identd installed and running. This is mandatory even if you have only local clients connecting to "localhost".
Also beware that nowadays the identd may have to be IPv6 enabled for Postgresql to welcome clients which connect to localhost.
You can use prototype cells
with a custom height
, and then invoke cellForRowAtIndexPath:
and return its frame.height
.:.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [self tableView:tableView
cellForRowAtIndexPath:indexPath];
return cell.frame.size.height;
}
You can't do that purely with CSS. There is a text-transform
attribute, but it only accepts none
, capitalize
, uppercase
, lowercase
and inherit
.
You might want to look into either a JS solution or a server-side solution for that.
The @Aleks G OnKeyListener() works really well, but I ran it from MainActivity and so had to modify it slightly:
EditText searchBox = (EditText) findViewById(R.id.searchbox);
searchBox.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
//if the enter key was pressed, then hide the keyboard and do whatever needs doing.
InputMethodManager imm = (InputMethodManager) MainActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchBox.getApplicationWindowToken(), 0);
//do what you need on your enter key press here
return true;
}
return false;
}
});
I hope this helps anyone trying to do the same.
Update: There are now better, cleaner solutions to this problem. Please consider the other answers first.
I eventually found an answer to this by ronen on his blog. The problem I was having is due to the method Mockito.mock(Class c)
declaring a return type of Object
. Consequently Spring is unable to infer the bean type from the factory method return type.
Ronen's solution is to create a FactoryBean
implementation that returns mocks. The FactoryBean
interface allows Spring to query the type of objects created by the factory bean.
My mocked bean definition now looks like:
<bean id="mockDaoFactory" name="dao" class="com.package.test.MocksFactory">
<property name="type" value="com.package.Dao" />
</bean>
There is a nice gem especially for uploading files : carrierwave. If the wiki does not help , there is a nice RailsCast about the best way to use it . Summarizing , there is a field type file
in Rails forms , which invokes the file upload dialog. You can use it , but the 'magic' is done by carrierwave
gem .
I don't know what do you mean with "how to write to a file" , but I hope this is a nice start.
Simply git checkout have 2 uses
git checkout <existing_local_branch_name>
git checkout -b <new_feature_branch_name>
will create a new branch with the contents of master and switch to newly created branchYou can find more options at the official site
Look in c:\windows\Microsoft.NET\Framework and you will see various folders starting with "v" indicating the versions of .NET installed.
I guess you could look inside your downloaded code where exactly there is a +
sign (but this might not be very easy).
What I'd do?
I'd find the class/id of the DOM elements that contain the +
sign (suppose it's ".collapsible"
, and with Javascript (actually jQuery):
<script>
$(document).ready(function() {
var content=$(".collapsible").html().replace("+", "-");
$(".collapsible").html(content));
});
</script>
edit
Alright... Sorry I haven't looked at the bootstrap code... but I guess it works with something like slideToggle
, or slideDown and slideUp
... Imagine it's a slideToggle
for the elements of class .collapsible
, which reveal contents of some .info
elements. Then:
$(".collapsible").click(function() {
var content=$(".collapsible").html();
if $(this).next().css("display") === "none") {
$(".collapsible").html(content.replace("+", "-"));
}
else $(".collapsible").html(content.replace("-", "+"));
});
This seems like the opposite thing to do, but since the actual animation runs in parallel, you will check css before animation, and that's why you need to check if it's visible (which will mean it will be hidden once the animation is complete) and then set the corresponding + or -.
try this:
return $this->db->query("
SELECT * FROM myTable
WHERE trans_id IN ( SELECT trans_id FROM myTable WHERE code='B')
AND code!='B'
")->result_array();
Is not active record but is codeigniter's way http://codeigniter.com/user_guide/database/examples.html see Standard Query With Multiple Results (Array Version) section
If still getting error then follow the steps of mysql2 gem installation on Rails 3 on -
http://rorguide.blogspot.com/2011/03/installing-mysql2-gem-on-ruby-192-and.html
where most of the user were able to install mysql2 gem.
private static string GetSetting(string key)
{
return ConfigurationManager.AppSettings[key];
}
private static void SetSetting(string key, string value)
{
Configuration configuration =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
configuration.AppSettings.Settings[key].Value = value;
configuration.Save(ConfigurationSaveMode.Full, true);
ConfigurationManager.RefreshSection("appSettings");
}
I'm using rc.4 and this method works for ES2015(ES6):
import {DomSanitizationService} from '@angular/platform-browser';
@Component({
templateUrl: 'build/pages/veeu/veeu.html'
})
export class VeeUPage {
static get parameters() {
return [NavController, App, MenuController, DomSanitizationService];
}
constructor(nav, app, menu, sanitizer) {
this.app = app;
this.nav = nav;
this.menu = menu;
this.sanitizer = sanitizer;
}
photoURL() {
return this.sanitizer.bypassSecurityTrustUrl(this.mediaItems[1].url);
}
}
In the HTML:
<iframe [src]='photoURL()' width="640" height="360" frameborder="0"
webkitallowfullscreen mozallowfullscreen allowfullscreen>
</iframe>
Using a function will ensure that the value doesn't change after you sanitize it. Also be aware that the sanitization function you use depends on the context.
For images, bypassSecurityTrustUrl
will work but for other uses you need to refer to the documentation:
https://angular.io/docs/ts/latest/api/platform-browser/index/DomSanitizer-class.html
I will also add my experience here in case it helps someone:
At work we commonly use the following two commands to enable IntelliJ IDEA to talk to various servers, for example our internal maven repositories:
[Elevated]C:\Program Files\JetBrains\IntelliJ IDEA {version}\jre64>bin\keytool
-printcert -rfc -sslserver maven.services.{our-company}.com:443 > public.crt
[Elevated]C:\Program Files\JetBrains\IntelliJ IDEA {version}\jre64>bin\keytool
-import -storepass changeit -noprompt -trustcacerts -alias services.{our-company}.com
-keystore lib\security\cacerts -file public.crt
Now, what sometimes happens is that the keytool -printcert
command is unable to communicate with the outside world due to temporary connectivity issues, such as the firewall preventing it, the user forgot to start his VPN, whatever. It is a fact of life that this may happen. This is not actually the problem.
The problem is that when the stupid tool encounters such an error, it does not emit the error message to the standard error device, it emits it to the standard output device!
So here is what ends up happening:
public.crt
file now contains an error message saying keytool error: java.lang.Exception: No certificate from the SSL server
.public.crt
, so it fails, saying keytool error: java.lang.Exception: Input not an X.509 certificate
.Bottom line is: after keytool -printcert ... > public.crt
always dump the contents of public.crt
to make sure it is actually a key and not an error message before proceeding to run keytool -import ... -file public.crt
%s will get all the values until it gets NULL i.e. '\0'.
char str1[] = "This is the end\0";
printf("%s",str1);
will give
This is the end
char str2[] = "this is\0 the end\0";
printf("%s",str2);
will give
this is
As often, guava has what you need.
To go from byte array to int: Ints.fromBytesArray
, doc here
To go from int to byte array: Ints.toByteArray
, doc here
>>> u'a?ä'.encode('ascii', 'ignore')
'a'
Decode the string you get back, using either the charset in the the appropriate meta
tag in the response or in the Content-Type
header, then encode.
The method encode(encoding, errors)
accepts custom handlers for errors. The default values, besides ignore
, are:
>>> u'a?ä'.encode('ascii', 'replace')
b'a??'
>>> u'a?ä'.encode('ascii', 'xmlcharrefreplace')
b'aあä'
>>> u'a?ä'.encode('ascii', 'backslashreplace')
b'a\\u3042\\xe4'
See https://docs.python.org/3/library/stdtypes.html#str.encode
I have build such kind of application using approximatively the same approach except :
UIImage
but instead draw the image in the layer when zooming is 1. Those tiles will be released automatically when memory warnings are issued.Whenever the user start zooming, I acquire the CGPDFPage
and render it using the appropriate CTM. The code in - (void)drawLayer: (CALayer*)layer inContext: (CGContextRef) context
is like :
CGAffineTransform currentCTM = CGContextGetCTM(context);
if (currentCTM.a == 1.0 && baseImage) {
//Calculate ideal scale
CGFloat scaleForWidth = baseImage.size.width/self.bounds.size.width;
CGFloat scaleForHeight = baseImage.size.height/self.bounds.size.height;
CGFloat imageScaleFactor = MAX(scaleForWidth, scaleForHeight);
CGSize imageSize = CGSizeMake(baseImage.size.width/imageScaleFactor, baseImage.size.height/imageScaleFactor);
CGRect imageRect = CGRectMake((self.bounds.size.width-imageSize.width)/2, (self.bounds.size.height-imageSize.height)/2, imageSize.width, imageSize.height);
CGContextDrawImage(context, imageRect, [baseImage CGImage]);
} else {
@synchronized(issue) {
CGPDFPageRef pdfPage = CGPDFDocumentGetPage(issue.pdfDoc, pageIndex+1);
pdfToPageTransform = CGPDFPageGetDrawingTransform(pdfPage, kCGPDFMediaBox, layer.bounds, 0, true);
CGContextConcatCTM(context, pdfToPageTransform);
CGContextDrawPDFPage(context, pdfPage);
}
}
issue is the object containg the CGPDFDocumentRef
. I synchronize the part where I access the pdfDoc
property because I release it and recreate it when receiving memoryWarnings. It seems that the CGPDFDocumentRef
object do some internal caching that I did not find how to get rid of.
Most of the answers here talk about virtual machines. I'm going to give you a one-liner response to this question that has helped me the most over the last couple years of using Docker. It's this:
Docker is just a fancy way to run a process, not a virtual machine.
Now, let me explain a bit more about what that means. Virtual machines are their own beast. I feel like explaining what Docker is will help you understand this more than explaining what a virtual machine is. Especially because there are many fine answers here telling you exactly what someone means when they say "virtual machine". So...
A Docker container is just a process (and its children) that is compartmentalized using cgroups inside the host system's kernel from the rest of the processes. You can actually see your Docker container processes by running ps aux
on the host. For example, starting apache2
"in a container" is just starting apache2
as a special process on the host. It's just been compartmentalized from other processes on the machine. It is important to note that your containers do not exist outside of your containerized process' lifetime. When your process dies, your container dies. That's because Docker replaces pid 1
inside your container with your application (pid 1
is normally the init system). This last point about pid 1
is very important.
As far as the filesystem used by each of those container processes, Docker uses UnionFS-backed images, which is what you're downloading when you do a docker pull ubuntu
. Each "image" is just a series of layers and related metadata. The concept of layering is very important here. Each layer is just a change from the layer underneath it. For example, when you delete a file in your Dockerfile while building a Docker container, you're actually just creating a layer on top of the last layer which says "this file has been deleted". Incidentally, this is why you can delete a big file from your filesystem, but the image still takes up the same amount of disk space. The file is still there, in the layers underneath the current one. Layers themselves are just tarballs of files. You can test this out with docker save --output /tmp/ubuntu.tar ubuntu
and then cd /tmp && tar xvf ubuntu.tar
. Then you can take a look around. All those directories that look like long hashes are actually the individual layers. Each one contains files (layer.tar
) and metadata (json
) with information about that particular layer. Those layers just describe changes to the filesystem which are saved as a layer "on top of" its original state. When reading the "current" data, the filesystem reads data as though it were looking only at the top-most layers of changes. That's why the file appears to be deleted, even though it still exists in "previous" layers, because the filesystem is only looking at the top-most layers. This allows completely different containers to share their filesystem layers, even though some significant changes may have happened to the filesystem on the top-most layers in each container. This can save you a ton of disk space, when your containers share their base image layers. However, when you mount directories and files from the host system into your container by way of volumes, those volumes "bypass" the UnionFS, so changes are not stored in layers.
Networking in Docker is achieved by using an ethernet bridge (called docker0
on the host), and virtual interfaces for every container on the host. It creates a virtual subnet in docker0
for your containers to communicate "between" one another. There are many options for networking here, including creating custom subnets for your containers, and the ability to "share" your host's networking stack for your container to access directly.
Docker is moving very fast. Its documentation is some of the best documentation I've ever seen. It is generally well-written, concise, and accurate. I recommend you check the documentation available for more information, and trust the documentation over anything else you read online, including Stack Overflow. If you have specific questions, I highly recommend joining #docker
on Freenode IRC and asking there (you can even use Freenode's webchat for that!).
Its .net Version mismatch of the dll so try changing to from in app.config or web.config. Generally have a higher Framework than lower because when we add system's dll to the lower version built .net application so it won't work therefore just change to the higher version
Not with pure CSS. The closest equivalent is this:
.class1, .class2 {
some stuff
}
.class2 {
some more stuff
}
Only this worked for me:
#container:hover .cube { background-color: yellow; }
Where .cube
is CssClass of the #cube
.
Tested in Firefox, Chrome and Edge.
This issue can be resolved by unchecking Debug Executable in Edit Scheme.
No, abstract class can never be instantiated.
ISO_8859_1 Worked for me! I was reading text file with comma separated values
public static double periodOfTimeInMillis(Date date1, Date date2) {
return (date2.getTime() - date1.getTime());
}
public static double periodOfTimeInSec(Date date1, Date date2) {
return (date2.getTime() - date1.getTime()) / 1000;
}
public static double periodOfTimeInMin(Date date1, Date date2) {
return (date2.getTime() - date1.getTime()) / (60 * 1000);
}
public static double periodOfTimeInHours(Date date1, Date date2) {
return (date2.getTime() - date1.getTime()) / (60 * 60 * 1000);
}
public static double periodOfTimeInDays(Date date1, Date date2) {
return (date2.getTime() - date1.getTime()) / (24 * 60 * 60 * 1000L);
}
A return value of the previously executed process.
10.4 Getting the return value of a program
In bash, the return value of a program is stored in a special variable called $?.
This illustrates how to capture the return value of a program, I assume that the directory dada does not exist. (This was also suggested by mike)
#!/bin/bash cd /dada &> /dev/null echo rv: $? cd $(pwd) &> /dev/null echo rv: $?
See Bash Programming Manual for more details.
The jQuery method .data()
updates an internal object managed by jQuery through the use of the method, if I'm correct.
If you'd like to update your data-attributes
with some spread, use --
$('body').attr({ 'data-test': 'text' });
-- otherwise, $('body').attr('data-test', 'text');
will work just fine.
Another way you could accomplish this is using --
$.extend( $('body')[0].dataset, { datum: true } );
-- which restricts any attribute change to HTMLElement.prototype.dataset
, not any additional HTMLElement.prototype.attributes
.
If you use the library underscore you can write like this
var unionArr = _.union([34,35,45,48,49], [48,55]);_x000D_
console.log(unionArr);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
_x000D_
CREATE TABLE Employees
(
Id int,
Name varchar(50) not null,
Photo varbinary(max) not null
)
INSERT INTO Employees (Id, Name, Photo)
SELECT 10, 'John', BulkColumn
FROM Openrowset( Bulk 'C:\photo.bmp', Single_Blob) as EmployeePicture
Or you could have done this:
select trunc(sysdate) - to_date('2009-10-01', 'yyyy-mm-dd') from dual
This returns a NUMBER of whole days:
SQL> create view v as
2 select trunc(sysdate) - to_date('2009-10-01', 'yyyy-mm-dd') diff
3 from dual;
View created.
SQL> select * from v;
DIFF
----------
29
SQL> desc v
Name Null? Type
---------------------- -------- ------------------------
DIFF NUMBER(38)
It's possible with JavaScript.
var elem = document.getElementById("myvideo");
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.msRequestFullscreen) {
elem.msRequestFullscreen();
} else if (elem.mozRequestFullScreen) {
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
elem.webkitRequestFullscreen();
}
nchar and char pretty much operate in exactly the same way as each other, as do nvarchar and varchar. The only difference between them is that nchar/nvarchar store Unicode characters (essential if you require the use of extended character sets) whilst varchar does not.
Because Unicode characters require more storage, nchar/nvarchar fields take up twice as much space (so for example in earlier versions of SQL Server the maximum size of an nvarchar field is 4000).
This question is a duplicate of this one.
Update now Chrome also supports MediaRecorder API from v47. The same thing to do would be to use it( guessing native recording method is bound to be faster than work arounds), the API is really easy to use, and you would find tons of answers as to how to upload a blob for the server.
Demo - would work in Chrome and Firefox, intentionally left out pushing blob to server...
Currently, there are three ways to do it:
wav
[ all code client-side, uncompressed recording], you can check out --> Recorderjs. Problem: file size is quite big, more upload bandwidth required.mp3
[ all code client-side, compressed recording], you can check out --> mp3Recorder. Problem: personally, I find the quality bad, also there is this licensing issue.as ogg
[ client+ server(node.js
) code, compressed recording, infinite hours of recording without browser crash ], you can check out --> recordOpus, either only client-side recording, or client-server bundling, the choice is yours.
ogg recording example( only firefox):
var mediaRecorder = new MediaRecorder(stream);
mediaRecorder.start(); // to start recording.
...
mediaRecorder.stop(); // to stop recording.
mediaRecorder.ondataavailable = function(e) {
// do something with the data.
}
Fiddle Demo for ogg recording.
I find it more convenient to use something like the following:
document.querySelector('*').addEventListener('click',function(event){
if( event.target.tagName != "IMG"){
return;
}
// HANDLE CLICK ON IMAGES HERE
});
you will need to convert it to a decimal first, then format it with money format.
EX:
decimal decimalMoneyValue = 1921.39m;
string formattedMoneyValue = String.Format("{0:C}", decimalMoneyValue);
a working example: https://dotnetfiddle.net/soxxuW
You're passing link=$a
and link=$b
in the hrefs for A and B, respectively. They are treated as strings, not variables. The following should fix that for you:
echo '<a href="pass.php?link=' . $a . '">Link 1</a>';
// and
echo '<a href="pass.php?link=' . $b . '">Link 2</a>';
The value of $a
also isn't included on pass.php
. I would suggest making a common variable file and include it on all necessary pages.
I think you need to go with procs for anything real.
A) Writing all your logic in linq means your database is less useful because only your application can consume it.
B) I'm not convinced that object modelling is better than relational modelling anyway.
C) Testing and developing a stored procedure in SQL is a hell of a lot faster than a compile edit cycle in any Visual Studio environment. You just edit, F5 and hit select and you are off to the races.
D) It's easier to manage and deploy stored procedures than assemblies.. you just put the file on the server, and press F5...
E) Linq to sql still writes crappy code at times when you don't expect it.
Honestly, I think the ultimate thing would be for MS to augment t-sql so that it can do a join projection impliclitly the way linq does. t-sql should know if you wanted to do order.lineitems.part, for example.
That can be achieve in plain LaTeX without any specific package.
\documentclass{article}
\begin{document}
This is your only binary choices
\begin{math}
\left\{
\begin{array}{l}
0\\
1
\end{array}
\right.
\end{math}
\end{document}
This code produces something which looks what you seems to need.
The same example as in the @Tombart can be obtained with similar code.
\documentclass{article}
\begin{document}
\begin{math}
f(x)=\left\{
\begin{array}{ll}
1, & \mbox{if $x<0$}.\\
0, & \mbox{otherwise}.
\end{array}
\right.
\end{math}
\end{document}
This code produces very similar results.
Just in the context of this question, I want to post the 2 'APPLY' operators as well:
JOINS:
INNER JOIN = JOIN
OUTER JOIN
LEFT OUTER JOIN = LEFT JOIN
RIGHT OUTER JOIN = RIGHT JOIN
FULL OUTER JOIN = FULL JOIN
CROSS JOIN
SELF-JOIN: This is not exactly a separate type of join. This is basically joining a table to itself using one of the above joins. But I felt it is worth mentioning in the context JOIN discussions as you will hear this term from many in the SQL Developer community.
APPLY:
https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
https://sqlhints.com/2016/10/23/outer-apply-in-sql-server/
Real life example, when to use OUTER / CROSS APPLY in SQL
I find APPLY operator very beneficial as they give better performance than having to do the same computation in a subquery. They are also replacement of many Analytical functions in older versions of SQL Server. That is why I believe that after being comfortable with JOINS, one SQL developer should try to learn the APPLY operators next.
To answer the question that is asked in the beginning:
Why can't the container component call the async API, and then dispatch the actions?
Keep in mind that those docs are for Redux, not Redux plus React. Redux stores hooked up to React components can do exactly what you say, but a Plain Jane Redux store with no middleware doesn't accept arguments to dispatch
except plain ol' objects.
Without middleware you could of course still do
const store = createStore(reducer);
MyAPI.doThing().then(resp => store.dispatch(...));
But it's a similar case where the asynchrony is wrapped around Redux rather than handled by Redux. So, middleware allows for asynchrony by modifying what can be passed directly to dispatch
.
That said, the spirit of your suggestion is, I think, valid. There are certainly other ways you could handle asynchrony in a Redux + React application.
One benefit of using middleware is that you can continue to use action creators as normal without worrying about exactly how they're hooked up. For example, using redux-thunk
, the code you wrote would look a lot like
function updateThing() {
return dispatch => {
dispatch({
type: ActionTypes.STARTED_UPDATING
});
AsyncApi.getFieldValue()
.then(result => dispatch({
type: ActionTypes.UPDATED,
payload: result
}));
}
}
const ConnectedApp = connect(
(state) => { ...state },
{ update: updateThing }
)(App);
which doesn't look all that different from the original — it's just shuffled a bit — and connect
doesn't know that updateThing
is (or needs to be) asynchronous.
If you also wanted to support promises, observables, sagas, or crazy custom and highly declarative action creators, then Redux can do it just by changing what you pass to dispatch
(aka, what you return from action creators). No mucking with the React components (or connect
calls) necessary.
DateTimeUtils obj = new DateTimeUtils();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/M/yyyy hh:mm:ss");
try {
Date date1 = simpleDateFormat.parse("10/10/2013 11:30:10");
Date date2 = simpleDateFormat.parse("13/10/2013 20:35:55");
obj.printDifference(date1, date2);
} catch (ParseException e) {
e.printStackTrace();
}
//1 minute = 60 seconds
//1 hour = 60 x 60 = 3600
//1 day = 3600 x 24 = 86400
public void printDifference(Date startDate, Date endDate) {
//milliseconds
long different = endDate.getTime() - startDate.getTime();
System.out.println("startDate : " + startDate);
System.out.println("endDate : "+ endDate);
System.out.println("different : " + different);
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
System.out.printf(
"%d days, %d hours, %d minutes, %d seconds%n",
elapsedDays, elapsedHours, elapsedMinutes, elapsedSeconds);
}
out put is :
startDate : Thu Oct 10 11:30:10 SGT 2013
endDate : Sun Oct 13 20:35:55 SGT 2013
different : 291945000
3 days, 9 hours, 5 minutes, 45 seconds
Another option for plotting inline from an array of images could be:
import IPython
def showimg(a):
IPython.display.display(PIL.Image.fromarray(a))
where a is an array
a.shape
(720, 1280, 3)
Use this code:
public bool roomSelected()
{
foreach (RadioButton rb in GroupBox1.Controls)
{
if (rb.Checked == true)
{
return true;
}
}
return false;
}
You can also change standard fonts with setTextAppearance
(requires API 16), see https://stackoverflow.com/a/36301508/2914140:
<style name="styleA">
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold</item>
<item name="android:textColor">?android:attr/textColorPrimary</item>
</style>
<style name="styleB">
<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">normal</item>
<item name="android:textColor">?android:attr/textColorTertiary</item>
</style>
if(condition){
TextViewCompat.setTextAppearance(textView, R.style.styleA);
} else {
TextViewCompat.setTextAppearance(textView,R.style.styleB);
}
as a possible solution: Add some extra more content to the title. Overwrite this css style:
.fc-day-grid-event .fc-content {
white-space: normal;
}
Your code is perfectly fine, you are just not looking at the right location to find your file. Since you haven't provided absolute path, your file will be created relative to the current working folder (more precisely in the current working folder in your case).
Your current working folder is set by Qt Creator. Go to Projects >> Your selected build >> Press the 'Run' button (next to 'Build) and you will see what it is on this page which of course you can change as well.
There are different papers on both sites, I think that you only need to choose your side. Personally I prefer Plurar for tables naming, and of course singular for column naming.
I like how you can read this:
SELECT CustomerName FROM Customers WHERE CustomerID = 100;
Really we have OOP, and is great, but most people keep using Relational Databases, no Object Databases. There is no need to follow the OOP concepts for Relational Databases.
Another example, you have a table Teams, that keep TeamID, TeamColor but also PlayerID, and will have same teamID and TeamColor for certain amount of PlayerID...
To Which team the player belongs?
SELECT * FROM Teams WHERE PlayerID = X
All Players from X Team?
SELECT * FROM Players INNER JOIN Teams ON Players.PlayerID = Teams.PlayerID WHERE Teams.TeamID = X
All this sound good to you?
Anyways, also take a look to naming conventions used by W3Schools:
PyPy has had Python 3 support for a while, but according to this HackerNoon post by Anthony Shaw from April 2nd, 2018, PyPy3 is still several times slower than PyPy (Python 2).
For many scientific calculations, particularly matrix calculations, numpy is a better choice (see FAQ: Should I install numpy or numpypy?).
Pypy does not support gmpy2. You can instead make use of gmpy_cffi though I haven't tested its speed and the project had one release in 2014.
For Project Euler problems, I make frequent use of PyPy, and for simple numerical calculations often from __future__ import division
is sufficient for my purposes, but Python 3 support is still being worked on as of 2018, with your best bet being on 64-bit Linux. Windows PyPy3.5 v6.0, the latest as of December 2018, is in beta.
Assuming y, m, d
are all int
, how about:
CAST(CAST(y AS varchar) + '-' + CAST(m AS varchar) + '-' + CAST(d AS varchar) AS DATETIME)
Please see my other answer for SQL Server 2012 and above
If you like getting random Command Timeout errors in SQLServer then leave off the semi-colon at the end of your CommandText strings.
I don't know if this is documented anywhere or if it is a bug, but it does happen and I have learnt this from bitter experience.
I have verifiable and reproducible examples using SQLServer 2008.
aka -> In practice, always include the terminator even if you're just sending one statement to the database.
You can do
array = ['1', '2', '3']
As others have noted, you can also initialize an array with %w notation like so:
array = %w(1 2 3)
or
array = %w[1 2 3]
Please note that in both cases each element is a string, rather than an integer. So if you want an array whose elements are integers, you should not wrap each element with apostrophes:
array_of_integers = [1, 2, 3]
Also, you don't need to put comma in between the elements (which is necessary when creating an array without this %w notation). If you do this (which I often did by mistake), as in:
wrong_array = %w(1, 2, 3)
its elements will be three strings ---- "1,", "2,", "3". So if you do:
puts wrong_array
the output will be:
1,
2,
3
=>nil
which is not what we want here.
Hope this helps to clarify the point!
With jQuery, it is possible, however not using ajax.
function LoadPage(){
$.get('http://a_site.com/a_page.html', function(data) {
$('#siteloader').html(data);
});
}
And then place onload="LoadPage()"
in the body tag.
Although if you follow this route, a php version might be better:
echo htmlspecialchars(file_get_contents("some URL"));
To put it on one line:
currentLoad = IIf(IsNumeric(oXLSheet2.Cells(4, 6).Value), CInt(oXLSheet2.Cells(4, 6).Value), 0)