This is my answer,
<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p>
First Name: <span id="fname"></span><br>
Last Name: <span id="lname"></span><br>
</p>
<script>
var txt = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
//var jsonData = eval ("(" + txt + ")");
var jsonData = JSON.parse(txt);
for (var i = 0; i < jsonData.employees.length; i++) {
var counter = jsonData.employees[i];
//console.log(counter.counter_name);
alert(counter.firstName);
}
</script>
</body>
</html>
Use the constructor which takes an int ("capacity") as an argument:
List<string> = new List<string>(10);
EDIT: I should add that I agree with Frederik. You are using the List in a way that goes against the entire reasoning behind using it in the first place.
EDIT2:
EDIT 2: What I'm currently writing is a base class offering default functionality as part of a bigger framework. In the default functionality I offer, the size of the List is known in advanced and therefore I could have used an array. However, I want to offer any base class the chance to dynamically extend it and therefore I opt for a list.
Why would anyone need to know the size of a List with all null values? If there are no real values in the list, I would expect the length to be 0. Anyhow, the fact that this is cludgy demonstrates that it is going against the intended use of the class.
Long story short, node draws from V8, which is internally single-threaded. There are ways to work around the constraints for CPU-intensive tasks.
At one point (0.7) the authors tried to introduce isolates as a way of implementing multiple threads of computation, but were ultimately removed: https://groups.google.com/forum/#!msg/nodejs/zLzuo292hX0/F7gqfUiKi2sJ
Try this:
Pattern p = Pattern.compile(?<=\\<(any_tag)\\>)(\\s*.*\\s*)(?=\\<\\/(any_tag)\\>);
Matcher m = p.matcher(anyString);
For example:
String str = "<TR> <TD>1Q Ene</TD> <TD>3.08%</TD> </TR>";
Pattern p = Pattern.compile("(?<=\\<TD\\>)(\\s*.*\\s*)(?=\\<\\/TD\\>)");
Matcher m = p.matcher(str);
while(m.find()){
Log.e("Regex"," Regex result: " + m.group())
}
Output:
10 Ene
3.08%
As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:
MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();
It's easy enough to write the equivalent of CopyTo
in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream
.
For efficient purposes you could check whether the stream returned is already a MemoryStream
:
byte[] data;
using (Stream inputStream = model.File.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
data = memoryStream.ToArray();
}
If you just want the first number to match you can do it like this:
[item for item in a if item[0] == 1]
If you are just searching for tuples with 1 in them:
[item for item in a if 1 in item]
Both of
int main(int argc, char *argv[]);
int main();
are legal definitions of the entry point for a C or C++ program. Stroustrup: C++ Style and Technique FAQ details some of the variations that are possible or legal for your main function.
I was having the same issue and when I checked the environment in Windows 7 it was pointing to c:\users\myname\appdata\composer\version\bin which didn't exists. the file was actually located in C:\ProgramData\ComposerSetup\bin Fixed the location in environment setting and it worked
[
is a command (or a builtin in some shells). It must be separated by whitespace from the preceding statement:
elif [
The problem is that omega
in your case is matrix
of dimensions 1 * 1
. You should convert it to a vector if you wish to multiply t(X) %*% X
by a scalar (that is omega
)
In particular, you'll have to replace this line:
omega = rgamma(1,a0,1) / L0
with:
omega = as.vector(rgamma(1,a0,1) / L0)
everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.)
or c(t(.))
. Both are equivalent.
Here's the modified code that should work:
gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1,
a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
m0 = c(m01, m02)
C0 = matrix(nrow = 2, ncol = 2)
C0[1,1] = 1 / k01
C0[1,2] = 0
C0[2,1] = 0
C0[2,2] = 1 / k02
beta = mvrnorm(1,m0,C0)
omega = as.vector(rgamma(1,a0,1) / L0)
draws = matrix(ncol = 3,nrow = ndraw)
it = -nburn
while (it < ndraw) {
it = it + 1
C1 = solve(solve(C0) + omega * t(X) %*% X)
m1 = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
beta = mvrnorm(1, m1, C1)
a1 = a0 + n / 2
L1 = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2
omega = as.vector(rgamma(1, a1, 1) / L1)
if (it > 0) {
draws[it,1] = beta[1]
draws[it,2] = beta[2]
draws[it,3] = omega
}
}
return(draws)
}
Use onKeyDown
event, and inside that check the key code of the key pressed by user. Key code of Enter
key is 13, check the code and put the logic there.
Check this example:
class CartridgeShell extends React.Component {_x000D_
_x000D_
constructor(props) {_x000D_
super(props);_x000D_
this.state = {value:''}_x000D_
_x000D_
this.handleChange = this.handleChange.bind(this);_x000D_
this.keyPress = this.keyPress.bind(this);_x000D_
} _x000D_
_x000D_
handleChange(e) {_x000D_
this.setState({ value: e.target.value });_x000D_
}_x000D_
_x000D_
keyPress(e){_x000D_
if(e.keyCode == 13){_x000D_
console.log('value', e.target.value);_x000D_
// put the login here_x000D_
}_x000D_
}_x000D_
_x000D_
render(){_x000D_
return(_x000D_
<input value={this.state.value} onKeyDown={this.keyPress} onChange={this.handleChange} fullWidth={true} />_x000D_
)_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(<CartridgeShell/>, document.getElementById('app'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
_x000D_
<div id = 'app' />
_x000D_
Note: Replace the input
element by Material-Ui TextField
and define the other properties also.
You must build an executable file before you can run it. So if you don't “BUILD” your file, then it will not be able to link and load that object file, and hence it does not have the required binary numbers to execute.
So basically right click on the Project -> Build Project -> Run As Local C/C++ Application
should do the trick
You simply need to do a SUBSTR on the string in col3....
Select col1, col2, REPLACE(substr(col3, instr(col3, 'Client Name'),
(instr(col3, '|', instr(col3, 'Client Name') -
instr(col3, 'Client Name'))
),
'Client Name = ',
'')
from Table01
And yes, that is a bad DB design for the reasons stated in the original issue
If you use the NetBeans IDE (latest version at this time is 6.5.1), you can use it to create a basic GUI java application using File->New Project and choose the Java category then Java Desktop Application.
Once created, you will have a simple bare bones GUI app which contains an about box that can be opened using a menu selection. You should be able to adapt this to your needs and learn how to open a dialog from a button click.
You will be able to edit the dialog visually. Delete the items that are there and add some text areas. Play around with it and come back with more questions if you get stuck :)
http://www.asoft.be/prod_netver.html
Use this "good, lightweight, no-install-required program"
Java and Javascript are similar like Car and Carpet are similar.
import os
path = chap_name
if not os.path.exists(path):
os.makedirs(path)
filename = img_alt + '.jpg'
with open(os.path.join(path, filename), 'wb') as temp_file:
temp_file.write(buff)
Key point is to use os.makedirs
in place of os.mkdir
. It is recursive, i.e. it generates all intermediate directories. See http://docs.python.org/library/os.html
Open the file in binary mode as you are storing binary (jpeg) data.
In response to Edit 2, if img_alt sometimes has '/' in it:
img_alt = os.path.basename(img_alt)
This snippet will determine if the element has children using the :parent
selector:
if ($('#myfav').is(':parent')) {
// do something
}
Note that :parent
also considers an element with one or more text nodes to be a parent.
Thus the div
elements in <div>some text</div>
and <div><span>some text</span></div>
will each be considered a parent but <div></div>
is not a parent.
What you should do is create an imap of a certain key to a series of commands, in this case the commands will drop you into normal mode, delete the current word and then put you back in insert:
:imap <C-d> <C-[>diwi
If you are using PHP, try using <?php flush(); ?>
after </head>
and before </body>
or whatever section you want to output quickly (like the header or content). It will output the actually code without waiting for php to end. Don't use this function all the time, or the speed increase won't be noticable.
According to the Java Language Specification (specifically §10.7 Array Members) it is a field:
- The
public
final
fieldlength
, which contains the number of components of the array (length may be positive or zero).
Internally the value is probably stored somewhere in the object header, but that is an implementation detail and depends on the concrete JVM implementation.
The HotSpot VM (the one in the popular Oracle (formerly Sun) JRE/JDK) stores the size in the object-header:
[...] arrays have a third header field, for the array size.
You can just create a shortcut and then right click on it -> properties -> change icon, and just browse for your desired icon. Hope this help.
To set an icon of a shortcut programmatically, see this article using SetIconLocation
:
How Can I Change the Icon for an Existing Shortcut?:
https://devblogs.microsoft.com/scripting/how-can-i-change-the-icon-for-an-existing-shortcut/
Const DESKTOP = &H10&
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace(DESKTOP)
Set objFolderItem = objFolder.ParseName("Test Shortcut.lnk")
Set objShortcut = objFolderItem.GetLink
objShortcut.SetIconLocation "C:\Windows\System32\SHELL32.dll", 13
objShortcut.Save
Hibernate 4 / 5:
Session session = entityManager.unwrap(Session.class);
session.doWork(connection -> doSomeStuffWith(connection));
Calling /search/
should result in "you submitted nothing", but calling /search/?q=
on the other hand should result in "you submitted u''"
Browsers have to add the q=
even when it's empty, because they have to include all fields which are part of the form. Only if you do some DOM manipulation in Javascript (or a custom javascript submit action), you might get such a behavior, but only if the user has javascript enabled. So you should probably simply test for non-empty strings, e.g:
if request.GET.get('q'):
message = 'You submitted: %r' % request.GET['q']
else:
message = 'You submitted nothing!'
If your your list is dynamically generated with unknown number and your target is to always have last div in a new line set last div class to "col-xl-12" and remove other classes so it will always take a full row.
This is a copy of your code corrected so that last div always occupy a full row (I although removed unnecessary classes).
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">_x000D_
<div class="grid">_x000D_
<div class="row">_x000D_
<div class="col-sm-3">Under me should be a DIV</div>_x000D_
<div class="col-md-6 col-sm-5">Under me should be a DIV</div>_x000D_
<div class="col-xl-12">I am the last DIV and I always take a full row for my self!!</div>_x000D_
</div>_x000D_
</div>
_x000D_
If anyone still has this issue - you don't have to change compileSdkVersion
, this just defeats the whole purpose of support libraries.
Instead, use these in your gradle.build
file:
compile 'com.android.support:cardview-v7:+'
compile 'com.android.support:recyclerview-v7:+'
compile 'com.android.support:palette-v7:+'`
This question is a bit old, but for those still arriving here now and using react-router 4.3 it's a bug and got fixed in the beta version 4.4.0. Just upgrade your react-router to version +4.4.0. Be aware that it's a beta version at this moment.
yarn add react-router@next
or
npm install -s [email protected]
I bumped into this problem lately with Windows 10 from another direction, and found the answer from @JonSkeet very helpful in solving my problem.
I also did som further research with a test form and found that when the the current culture was set to "no"
or "nb-NO"
at runtime (Thread.CurrentThread.CurrentCulture = new CultureInfo("no");
), the ToString("yyyy-MM-dd HH:mm:ss") call responded differently in Windows 7 and Windows 10. It returned what I expected in Windows 7 and HH.mm.ss in Windows 10!
I think this is a bit scary! Since I believed that a culture was a culture in any Windows version at least.
Suppose you have df
with columns A
B
C
.
The most simple way is:
df = df.reindex(['B','C','A'], axis=1)
import { Router } from '@angular/router';
//in your constructor
constructor(public router: Router){}
//navigation
link.this.router.navigateByUrl('/home');
It's not clear whether you're asking this because you are new to programming, but if that's the case then you should probably read this article on loops and indeed read some basic materials on programming.
If you already know about control structures and you want the R-specific implementation details then there are dozens of tutorials around, such as this one. The other answer uses replicate
and colMeans
, which is idiomatic when writing in R and probably blazing fast as well, which is important if you want 10,000 iterations.
However, one more general and (for beginners) straightforward way to approach problems of this sort would be to use a for
loop.
> for (ii in 1:5) { + print(ii) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 >
So in your case, if you just wanted to print the mean of your Tandem
object 5 times:
for (ii in 1:5) { Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL) TandemMean <- mean(Tandem) print(TandemMean) }
As mentioned above, replicate
is a more natural way to deal with this specific problem using R. Either way, if you want to store the results - which is surely the case - you'll need to start thinking about data structures like vectors and lists. Once you store something you'll need to be able to access it to use it in future, so a little knowledge is vital.
set.seed(1234) OUT <- runif(100000, 1, 2) tandem <- list() for (ii in 1:10000) { tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) } tandem[1] tandem[100] tandem[20:25]
...creates this output:
> set.seed(1234) > OUT <- runif(100000, 1, 2) > tandem <- list() > for (ii in 1:10000) { + tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) + } > > tandem[1] [[1]] [1] 1.511923 > tandem[100] [[1]] [1] 1.496777 > tandem[20:25] [[1]] [1] 1.500669 [[2]] [1] 1.487552 [[3]] [1] 1.503409 [[4]] [1] 1.501362 [[5]] [1] 1.499728 [[6]] [1] 1.492798 >
A good way to use JSON in C# is with JSON.NET
Quick Starts & API Documentation from JSON.NET - Official site help you work with it.
An example of how to use it:
public class User
{
public User(string json)
{
JObject jObject = JObject.Parse(json);
JToken jUser = jObject["user"];
name = (string) jUser["name"];
teamname = (string) jUser["teamname"];
email = (string) jUser["email"];
players = jUser["players"].ToArray();
}
public string name { get; set; }
public string teamname { get; set; }
public string email { get; set; }
public Array players { get; set; }
}
// Use
private void Run()
{
string json = @"{""user"":{""name"":""asdf"",""teamname"":""b"",""email"":""c"",""players"":[""1"",""2""]}}";
User user = new User(json);
Console.WriteLine("Name : " + user.name);
Console.WriteLine("Teamname : " + user.teamname);
Console.WriteLine("Email : " + user.email);
Console.WriteLine("Players:");
foreach (var player in user.players)
Console.WriteLine(player);
}
I've recently battled with this problem as well, and I've learned two things about the above suggestions.
The misleading aspect of this is that you now have a different value in the cell. Fortuately, when you copy/paste or export to CSV, the apostrophe is not included.
Conclusion: use the apostrophe, not the numberFormatting in order to retain the leading zeros.
To find the directory where your executable is, you can use:
TCHAR szFilePath[_MAX_PATH];
::GetModuleFileName(NULL, szFilePath, _MAX_PATH);
Recent enhancements by NVIDIA have produced a much more robust way to do this.
Essentially they have found a way to avoid the need to install the CUDA/GPU driver inside the containers and have it match the host kernel module.
Instead, drivers are on the host and the containers don't need them. It requires a modified docker-cli right now.
This is great, because now containers are much more portable.
A quick test on Ubuntu:
# Install nvidia-docker and nvidia-docker-plugin
wget -P /tmp https://github.com/NVIDIA/nvidia-docker/releases/download/v1.0.1/nvidia-docker_1.0.1-1_amd64.deb
sudo dpkg -i /tmp/nvidia-docker*.deb && rm /tmp/nvidia-docker*.deb
# Test nvidia-smi
nvidia-docker run --rm nvidia/cuda nvidia-smi
For more details see: GPU-Enabled Docker Container and: https://github.com/NVIDIA/nvidia-docker
I use getActionCommand() to hear buttons. I apply the setActionCommand() to each button so that I can hear whenever an event is execute with event.getActionCommand("The setActionCommand() value of the button").
I use getSource() for JRadioButtons for example. I write methods that returns each JRadioButton so in my Listener Class I can specify an action each time a new JRadioButton is pressed. So for example:
public class SeleccionListener implements ActionListener, FocusListener {}
So with this I can hear button events and radioButtons events. The following are examples of how I listen each one:
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals(GUISeleccion.BOTON_ACEPTAR)) {
System.out.println("Aceptar pressed");
}
In this case GUISeleccion.BOTON_ACEPTAR is a "public static final String" which is used in JButtonAceptar.setActionCommand(BOTON_ACEPTAR).
public void focusGained(FocusEvent focusEvent) {
if (focusEvent.getSource().equals(guiSeleccion.getJrbDat())){
System.out.println("Data radio button");
}
In this one, I get the source of any JRadioButton that is focused when the user hits it. guiSeleccion.getJrbDat() returns the reference to the JRadioButton that is in the class GUISeleccion (this is a Frame)
i was having some issues with windowhandle and tried this one. this one works good for me.
String parentWindowHandler = driver.getWindowHandle();
String subWindowHandler = null;
Set<String> handles = driver.getWindowHandles();
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()){
subWindowHandler = iterator.next();
driver.switchTo().window(subWindowHandler);
System.out.println(subWindowHandler);
}
driver.switchTo().window(parentWindowHandler);
As Apple DOC
targetForAction:withSender:
Returns the target object that responds to an action.
You can't use that method to set target for UIButton
.
Try
addTarget(_:action:forControlEvents:) method
If you love one liners, try:
d=eval('{'+re.sub('\'[\s]*?\'','\':\'',re.sub(r'([^'+input('SEP: ')+',]+)','\''+r'\1'+'\'',open(input('FILE: ')).read().rstrip('\n').replace('\n',',')))+'}')
Input FILE = Path to file, SEP = Key-Value separator character
Not the most elegant or efficient way of doing it, but quite interesting nonetheless :)
Yes, it's possible. But first read, "What happens when I change my username?"
To change your username, click your profile picture in the top right corner, then click Settings
. On the left side, click Account
. Then click Change username
.
Technology used: Windows 7, UFT 32 bit, Data Source ODBC pointing out to 32 bit C:\Windows\System32\odbcad32.exe
, Oracle client with both versions installed 32 bit and 64 bit.
What worked for me:
1.Start -> search for Edit the system environment variables
2.System Variables -> Edit Path
3.Place the path for Oracle client 32 bit
in front of the path for Oracle Client 64 bit
.
Ex:
C:\APP\ORACLE\product\11.2.0\client_32\bin;C:\APP\ORACLE\product\11.2.0\client_64\bin
Process.WaitForExit should be just what you're looking for I think.
JavaScript
(function ($) {
var form= $('#add-form'),
input = $('#exampleFormControlTextarea1');
form.submit(function(event) {
event.preventDefault();
var req = $.ajax({
url: form.attr('action'),
type: 'POST',
data: form.serialize()
});
req.done(function(data) {
if (data === 'success') {
var li = $('<li class="list-group-item">'+ input.val() +'</li>');
li.hide()
.appendTo('.list-group')
.fadeIn();
$('input[type="text"],textarea').val('');
}
});
});
}(jQuery));
HTML
<ul class="list-group col-sm-6 float-left">
<?php
foreach ($data as $item) {
echo '<li class="list-group-item">'.$item.'</li>';
}
?>
</ul>
<form id="add-form" class="col-sm-6 float-right" action="_inc/add-new.php" method="post">
<p class="form-group">
<textarea class="form-control" name="message" id="exampleFormControlTextarea1" rows="3" placeholder="Is there something new?"></textarea>
</p>
<button type="submit" class="btn btn-danger">Add new item</button>
</form>
use this class
public class WCFs
{
// https://192.168.30.8/myservice.svc?wsdl
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "192.168.30.8";
private static final String SERVICE = "/myservice.svc?wsdl";
private static String SOAP_ACTION = "http://tempuri.org/iWCFserviceMe/";
public static Thread myMethod(Runnable rp)
{
String METHOD_NAME = "myMethod";
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("Message", "Https WCF Running...");
return _call(rp,METHOD_NAME, request);
}
protected static HandlerThread _call(final RunProcess rp,final String METHOD_NAME, SoapObject soapReq)
{
final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
int TimeOut = 5*1000;
envelope.dotNet = true;
envelope.bodyOut = soapReq;
envelope.setOutputSoapObject(soapReq);
final HttpsTransportSE httpTransport_net = new HttpsTransportSE(URL, 443, SERVICE, TimeOut);
try
{
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() // use this section if crt file is handmake
{
@Override
public boolean verify(String hostname, SSLSession session)
{
return true;
}
});
KeyStore k = getFromRaw(R.raw.key, "PKCS12", "password");
((HttpsServiceConnectionSE) httpTransport_net.getServiceConnection()).setSSLSocketFactory(getSSLSocketFactory(k, "SSL"));
}
catch(Exception e){}
HandlerThread thread = new HandlerThread("wcfTd"+ Generator.getRandomNumber())
{
@Override
public void run()
{
Handler h = new Handler(Looper.getMainLooper());
Object response = null;
for(int i=0; i<4; i++)
{
response = send(envelope, httpTransport_net , METHOD_NAME, null);
try
{if(Thread.currentThread().isInterrupted()) return;}catch(Exception e){}
if(response != null)
break;
ThreadHelper.threadSleep(250);
}
if(response != null)
{
if(rp != null)
{
rp.setArguments(response.toString());
h.post(rp);
}
}
else
{
if(Thread.currentThread().isInterrupted())
return;
if(rp != null)
{
rp.setExceptionState(true);
h.post(rp);
}
}
ThreadHelper.stopThread(this);
}
};
thread.start();
return thread;
}
private static Object send(SoapSerializationEnvelope envelope, HttpTransportSE androidHttpTransport, String METHOD_NAME, List<HeaderProperty> headerList)
{
try
{
if(headerList != null)
androidHttpTransport.call(SOAP_ACTION + METHOD_NAME, envelope, headerList);
else
androidHttpTransport.call(SOAP_ACTION + METHOD_NAME, envelope);
Object res = envelope.getResponse();
if(res instanceof SoapPrimitive)
return (SoapPrimitive) envelope.getResponse();
else if(res instanceof SoapObject)
return ((SoapObject) envelope.getResponse());
}
catch(Exception e)
{}
return null;
}
public static KeyStore getFromRaw(@RawRes int id, String algorithm, String filePassword)
{
try
{
InputStream inputStream = ResourceMaster.openRaw(id);
KeyStore keystore = KeyStore.getInstance(algorithm);
keystore.load(inputStream, filePassword.toCharArray());
inputStream.close();
return keystore;
}
catch(Exception e)
{}
return null;
}
public static SSLSocketFactory getSSLSocketFactory(KeyStore trustKey, String SSLAlgorithm)
{
try
{
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trustKey);
SSLContext context = SSLContext.getInstance(SSLAlgorithm);//"SSL" "TLS"
context.init(null, tmf.getTrustManagers(), null);
return context.getSocketFactory();
}
catch(Exception e){}
return null;
}
}
The <a>
tag without the "href" can be handy when using multi-level menus and you need to expand the next level but don't want that menu label to be an active link. I have never had any issues using it that way.
Update: The GSOC project and the code there isn't active, but this is: https://github.com/hierynomus/sshj
hierynomus took over as maintainer since early 2015. Here is the older, no longer maintained, Github link:
https://github.com/shikhar/sshj
There was a GSOC project:
http://code.google.com/p/commons-net-ssh/
Code quality seem to be better than JSch, which, while a complete and working implementation, lacks documentation. Project page spots an upcoming beta release, last commit to the repository was mid-august.
Compare the APIs:
http://code.google.com/p/commons-net-ssh/
SSHClient ssh = new SSHClient();
//ssh.useCompression();
ssh.loadKnownHosts();
ssh.connect("localhost");
try {
ssh.authPublickey(System.getProperty("user.name"));
new SCPDownloadClient(ssh).copy("ten", "/tmp");
} finally {
ssh.disconnect();
}
Session session = null;
Channel channel = null;
try {
JSch jsch = new JSch();
session = jsch.getSession(username, host, 22);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword(password);
session.connect();
// exec 'scp -f rfile' remotely
String command = "scp -f " + remoteFilename;
channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
// get I/O streams for remote scp
OutputStream out = channel.getOutputStream();
InputStream in = channel.getInputStream();
channel.connect();
byte[] buf = new byte[1024];
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
while (true) {
int c = checkAck(in);
if (c != 'C') {
break;
}
// read '0644 '
in.read(buf, 0, 5);
long filesize = 0L;
while (true) {
if (in.read(buf, 0, 1) < 0) {
// error
break;
}
if (buf[0] == ' ') {
break;
}
filesize = filesize * 10L + (long) (buf[0] - '0');
}
String file = null;
for (int i = 0;; i++) {
in.read(buf, i, 1);
if (buf[i] == (byte) 0x0a) {
file = new String(buf, 0, i);
break;
}
}
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
// read a content of lfile
FileOutputStream fos = null;
fos = new FileOutputStream(localFilename);
int foo;
while (true) {
if (buf.length < filesize) {
foo = buf.length;
} else {
foo = (int) filesize;
}
foo = in.read(buf, 0, foo);
if (foo < 0) {
// error
break;
}
fos.write(buf, 0, foo);
filesize -= foo;
if (filesize == 0L) {
break;
}
}
fos.close();
fos = null;
if (checkAck(in) != 0) {
System.exit(0);
}
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
channel.disconnect();
session.disconnect();
}
} catch (JSchException jsche) {
System.err.println(jsche.getLocalizedMessage());
} catch (IOException ioe) {
System.err.println(ioe.getLocalizedMessage());
} finally {
channel.disconnect();
session.disconnect();
}
}
I always go back to this article SQL Server 2005 XQuery and XML-DML - Part 1 to know how to use the XML features in SQL Server 2005.
For basic XPath know-how, I'd recommend the W3Schools tutorial.
If you use Three20
, then use the autoresizesForKeyboard
property. Just set in the your view controller's -initWithNibName:bundle
method
self.autoresizesForKeyboard = YES
This takes care of:
Done and done.
Sorry, my english is not that good. But i like to improve the upvoted answers. I think that using Dictionary is more simple and clean.
class Program
{
static void Main(string[] args)
{
agencia ag1 = new agencia()
{
name = "Iquique",
data = new object[] { new object[] {"Lucas", 20 }, new object[] {"Fernando", 15 } }
};
agencia ag2 = new agencia()
{
name = "Valparaiso",
data = new object[] { new object[] { "Rems", 20 }, new object[] { "Perex", 15 } }
};
agencia agn = new agencia()
{
name = "Santiago",
data = new object[] { new object[] { "Jhon", 20 }, new object[] { "Karma", 15 } }
};
Dictionary<string, agencia> dic = new Dictionary<string, agencia>
{
{ "Iquique", ag1 },
{ "Valparaiso", ag2 },
{ "Santiago", agn }
};
string da = Newtonsoft.Json.JsonConvert.SerializeObject(dic);
Console.WriteLine(da);
Console.ReadLine();
}
}
public class agencia
{
public string name { get; set; }
public object[] data { get; set; }
}
This code generate the following json (This is desired format)
{
"Iquique":{
"name":"Iquique",
"data":[
[
"Lucas",
20
],
[
"Fernando",
15
]
]
},
"Valparaiso":{
"name":"Valparaiso",
"data":[
[
"Rems",
20
],
[
"Perex",
15
]
]
},
"Santiago":{
"name":"Santiago",
"data":[
[
"Jhon",
20
],
[
"Karma",
15
]
]
}
}
From Unix.SE: A simple command-line utility called gpustat
now exists: https://github.com/wookayin/gpustat.
It is free software (MIT license) and is packaged in pypi. It is a wrapper of nvidia-smi
.
You could use the ExcelStorage Class of the FileHelpers library, it's very easy and simple... you will need Excel 2000 or later installed on the machine.
The FileHelpers is a free and easy to use .NET library to import/export data from fixed length or delimited records in files, strings or streams.
You can add the 'muted' and 'autoplay' attributes together to enable autoplay for android devices.
e.g.
<video id="video" class="video" autoplay muted >
_x000D_
In your ipython_config.py
file, search for the following lines
# c.InteractiveShellApp.matplotlib = None
and
# c.InteractiveShellApp.pylab = None
and uncomment them. Then, change None
to the backend that you're using (I use 'qt4'
) and save the file. Restart IPython, and matplotlib and pylab should be loaded - you can use the dir()
command to verify which modules are in the global namespace.
I got it!
$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$vId&key=dldfsd981asGhkxHxFf6JqyNrTqIeJ9sjMKFcX4");
$duration = json_decode($dur, true);
foreach ($duration['items'] as $vidTime) {
$vTime= $vidTime['contentDetails']['duration'];
}
There it returns the time for YouTube API version 3 (the key is made up by the way ;). I used $vId
that I had gotten off of the returned list of the videos from the channel I am showing the videos from...
It works. Google REALLY needs to include the duration in the snippet so you can get it all with one call instead of two... it's on their 'wontfix' list.
Let's use the latest fat arrow functions:
navigator.geolocation.getCurrentPosition((loc) => {
console.log('The location in lat lon format is: [', loc.coords.latitude, ',', loc.coords.longitude, ']');
})
In order to get last N records you can execute below query:
db.yourcollectionname.find({$query: {}, $orderby: {$natural : -1}}).limit(yournumber)
if you want only one last record:
db.yourcollectionname.findOne({$query: {}, $orderby: {$natural : -1}})
Note: In place of $natural
you can use one of the columns from your collection.
If you have an Array of strings, you can also initialize it like this:
array = %w{1 2 3}
just separate each element with any whitespace
I usually use Criteria when I don't know what the inputs will be used on which pieces of data. Like on a search form where the user can enter any of 1 to 50 items and I don't know what they will be searching for. It is very easy to just append more to the criteria as I go through checking for what the user is searching for. I think it would be a little more troublesome to put an HQL query in that circumstance. HQL is great though when I know exactly what I want.
I ended up creating my own plugin. Here it is in case this helps anyone:
(function($) {
$.fn.countTo = function(options) {
// merge the default plugin settings with the custom options
options = $.extend({}, $.fn.countTo.defaults, options || {});
// how many times to update the value, and how much to increment the value on each update
var loops = Math.ceil(options.speed / options.refreshInterval),
increment = (options.to - options.from) / loops;
return $(this).each(function() {
var _this = this,
loopCount = 0,
value = options.from,
interval = setInterval(updateTimer, options.refreshInterval);
function updateTimer() {
value += increment;
loopCount++;
$(_this).html(value.toFixed(options.decimals));
if (typeof(options.onUpdate) == 'function') {
options.onUpdate.call(_this, value);
}
if (loopCount >= loops) {
clearInterval(interval);
value = options.to;
if (typeof(options.onComplete) == 'function') {
options.onComplete.call(_this, value);
}
}
}
});
};
$.fn.countTo.defaults = {
from: 0, // the number the element should start at
to: 100, // the number the element should end at
speed: 1000, // how long it should take to count between the target numbers
refreshInterval: 100, // how often the element should be updated
decimals: 0, // the number of decimal places to show
onUpdate: null, // callback method for every time the element is updated,
onComplete: null, // callback method for when the element finishes updating
};
})(jQuery);
Here's some sample code of how to use it:
<script type="text/javascript"><!--
jQuery(function($) {
$('.timer').countTo({
from: 50,
to: 2500,
speed: 1000,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
});
//--></script>
<span class="timer"></span>
View the demo on JSFiddle: http://jsfiddle.net/YWn9t/
Okay, that's the start of long story - made short abort parsing a command line in C ...
/**
* Helper function to parse the command line
* @param argc Argument Counter
* @param argv Argument Vector
* @param prog Program Instance Reference to fill with options
*/
bool parseCommandLine(int argc, char* argv[], DuplicateFileHardLinker* prog) {
bool pathAdded = false;
// Iterate over all arguments...
for (int i = 1; i<argc; i++) {
// Is argv a command line option?
if (argv[i][0] == '-' || argv[i][0] == '/') {
// ~~~~~~ Optionally Cut that part vvvvvvvvvvvvv for sake of simplicity ~~~~~~~
// Check for longer options
if (stricmp( &argv[i][1], "NoFileName") == 0 ||
strcmp( &argv[i][1], "q1" ) == 0 ) {
boNoFileNameLog = true;
} else if (strcmp( &argv[i][1], "HowAreYou?") == 0 ) {
logInfo( "SECRET FOUND: Well - wow I'm glad ya ask me.");
} else {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Now here comes the main thing:
//
// Check for one-character options
while (char option = *++argv[i]) {
switch (option) {
case '?':
// Show program usage
logInfo(L"Options:");
logInfo(L" /q\t>Quite mode");
logInfo(L" /v\t>Verbose mode");
logInfo(L" /d\t>Debug mode");
return false;
// Log options
case 'q':
setLogLevel(LOG_ERROR);
break;
case 'v':
setLogLevel(LOG_VERBOSE);
break;
case 'd':
setLogLevel(LOG_DEBUG);
break;
default:
logError(L"'%s' is an illegal command line option!"
" Use /? to see valid options!", option);
return false;
} // switch one-char-option
} // while one-char-options
} // else one vs longer options
} // if isArgAnOption
//
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ So that's it! ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// What follows now is are some useful extras...
//
else {
// The command line options seems to be a path...
WCHAR tmpPath[MAX_PATH_LENGTH];
mbstowcs(tmpPath, argv[i], sizeof(tmpPath));
// Check if the path is existing!
//...
prog->addPath(tmpPath); // Comment or remove to get a working example
pathAdded = true;
}
}
// Check for parameters
if (!pathAdded) {
logError("You need to specify at least one folder to process!\n"
"Use /? to see valid options!");
return false;
}
return true;
}
int main(int argc, char* argv[]) {
try {
// Parse the command line
if ( !parseCommandLine(argc, argv, prog) ) {
return 1;
}
// I know that sample is just to show how the nicely parse command-line arguments
// So Please excuse more nice useful C-glatter that follows now...
}
catch ( LPCWSTR err ) {
DWORD dwError = GetLastError();
if ( wcslen(err) > 0 ) {
if ( dwError != 0 ) {
logError(dwError, err);
}
else {
logError(err);
}
}
return 2;
}
}
#define LOG_ERROR 1
#define LOG_INFO 0
#define LOG_VERBOSE -1
#define LOG_DEBUG -2
/** Logging level for the console output */
int logLevel = LOG_INFO;
void logError(LPCWSTR message, ...) {
va_list argp;
fwprintf(stderr, L"ERROR: ");
va_start(argp, message);
vfwprintf(stderr, message, argp);
va_end(argp);
fwprintf(stderr, L"\n");
}
void logInfo(LPCWSTR message, ...) {
if ( logLevel <= LOG_INFO ) {
va_list argp;
va_start(argp, message);
vwprintf(message, argp);
va_end(argp);
wprintf(L"\n");
}
}
Note that this version will also support combining arguments: So instead of writing /h /s -> /hs will also work.
Sorry for being the n-th person posting here - however I wasn't really satisfied with all the stand-alone-versions I saw here. Well, the library ones are quiet nice. So I would prefer the libUCW option parser, Arg or Getopt over a home-made ones.
Note you may change:
*++argv[i]
-> (++argv*)[0]
It is longer and less cryptic, but still cryptic.
Okay, let's break it down:
argv[i]-> access i-th element in the argv-char pointer field
++*... -> will forward the argv-pointer by one char
... [0]-> will follow the pointer read the char
++(...) -> bracket are there so we'll increase the pointer and not the char value itself.
It is so nice that in C#, the pointers 'died' - long live the pointers!!
I guess I misunderstood what was being asked. Re-re-reading, it looks like Tim's answer is what you want. Let me just add this, however: if you want to catch an exception from open
, then open
has to be wrapped in a try
. If the call to open
is in the header of a with
, then the with
has to be in a try
to catch the exception. There's no way around that.
So the answer is either: "Tim's way" or "No, you're doing it correctly.".
Previous unhelpful answer to which all the comments refer:
import os
if os.path.exists(fName):
with open(fName, 'rb') as f:
try:
# do stuff
except : # whatever reader errors you care about
# handle error
Ultimately you want to review the datetime documentation and become familiar with the formatting variables, but here are some examples to get you started:
import datetime
print('Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Timestamp: {:%Y-%b-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Date now: %s' % datetime.datetime.now())
print('Date today: %s' % datetime.date.today())
today = datetime.date.today()
print("Today's date is {:%b, %d %Y}".format(today))
schedule = '{:%b, %d %Y}'.format(today) + ' - 6 PM to 10 PM Pacific'
schedule2 = '{:%B, %d %Y}'.format(today) + ' - 1 PM to 6 PM Central'
print('Maintenance: %s' % schedule)
print('Maintenance: %s' % schedule2)
The output:
Timestamp: 2014-10-18 21:31:12
Timestamp: 2014-Oct-18 21:31:12
Date now: 2014-10-18 21:31:12.318340
Date today: 2014-10-18
Today's date is Oct, 18 2014
Maintenance: Oct, 18 2014 - 6 PM to 10 PM Pacific
Maintenance: October, 18 2014 - 1 PM to 6 PM Central
Reference link: https://docs.python.org/3.4/library/datetime.html#strftime-strptime-behavior
You have several techniques to do it.
This post - read the part about the revert will explain in details what we want to do and how to do it.
Here is the most simple solution to your problem:
# Checkout the desired branch
git checkout <branch>
# Undo the desired commit
git revert <commit>
# Update the remote with the undo of the code
git push origin <branch>
The revert command will create a new commit with the undo of the original commit.
I have found a way to use JSONP
method in $http
directly and with support of params
in the config object:
params = {
'a': b,
'callback': 'JSON_CALLBACK'
};
$http({
url: url,
method: 'JSONP',
params: params
})
SQL Server does not track the order of inserted rows, so there is no reliable way to get that information given your current table structure. Even if employee_id
is an IDENTITY
column, it is not 100% foolproof to rely on that for order of insertion (since you can fill gaps and even create duplicate ID values using SET IDENTITY_INSERT ON
). If employee_id
is an IDENTITY
column and you are sure that rows aren't manually inserted out of order, you should be able to use this variation of your query to select the data in sequence, newest first:
SELECT
ROW_NUMBER() OVER (ORDER BY EMPLOYEE_ID DESC) AS ID,
EMPLOYEE_ID,
EMPLOYEE_NAME
FROM dbo.CSBCA1_5_FPCIC_2012_EES207201222743
ORDER BY ID;
You can make a change to your table to track this information for new rows, but you won't be able to derive it for your existing data (they will all me marked as inserted at the time you make this change).
ALTER TABLE dbo.CSBCA1_5_FPCIC_2012_EES207201222743
-- wow, who named this?
ADD CreatedDate DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;
Note that this may break existing code that just does INSERT INTO dbo.whatever SELECT/VALUES()
- e.g. you may have to revisit your code and define a proper, explicit column list.
call below method on div or body tag onclick="show(event);" function show(event) {
var x = event.clientX;
var y = event.clientY;
var ele = document.getElementById("tt");
var width = ele.offsetWidth;
var height = ele.offsetHeight;
var half=(width/2);
if(x>half)
{
// alert('right click');
gallery.next();
}
else
{
// alert('left click');
gallery.prev();
}
}
If you really want to generate a debug APK (for testing purpose) that can run without the development server, Congrats! here I am to help you. :)
Everyone is saying that we need to run two commands react-native bundle ...
and then gradlew assembleDebug
but the generated APK still doesnot work without development server. After many research & try I figured out that we need to change in the gradle file (as in step-2). Just follow these steps:
/android/app/src/main
create a folder assets
android > app > build.gradle
project.ext.react = [
...
bundleInDebug: true, // add this line
]
react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
cd android
gradlew assembleDebug
This will create app-debug.apk
file in android/app/build/outputs/apk/debug
directory, which you can install & run without dev-server.
gem list --no-version | grep -v -e 'psych' -e 'rdoc' -e 'openssl' -e 'json' -e 'io-console' -e 'bigdecimal' | xargs sudo gem uninstall -ax
grep here is excluding default gems. All other gems will be uninstalled. You can also precede it with sudo
in case you get permission issues.
Your mistake is looking for range
, which gives you the range
of a vector, for example:
range(c(10, -5, 100))
gives
-5 100
Instead, look at the :
operator to give sequences (with a step size of one):
1:100
or you can use the seq
function to have a bit more control. For example,
##Step size of 2
seq(1, 100, by=2)
or
##length.out: desired length of the sequence
seq(1, 100, length.out=5)
If i understand your question you want to have the overlay just over the image and not cover everything?
I'd set the parent DIV (i renamed in content in the jsfiddle) position to relative, as the overlay should be positioned relative to this div not the window.
.content
{
position: relative;
}
I did some pocking around and updated your fiddle to just have the overlay sized to the img which (I think) is what you want, let me know anyway :) http://jsfiddle.net/b9Vyw/
The "Check for Modifications" command in tortoise will display a list of all changed files in the working copy. "Commit" will show all changed files as well (that you can then commit). "Revert" will also show changed files (that you can then revert).
if you have FK constraints and you don't want to remove the constraint from the table. use "index" instead of primary. then you will be able to alter it's type to auto increment
These snippets all perform exactly the same thing:
element.on('click', function () { ... });
element.bind('click', function () { ... });
element.click(function () { ... });
However, they are very different from these, which all perform the same thing:
element.on('click', 'selector', function () { ... });
element.delegate('click', 'selector', function () { ... });
$('selector').live('click', function () { ... });
The second set of event handlers use event delegation and will work for dynamically added elements. Event handlers that use delegation are also much more performant. The first set will not work for dynamically added elements, and are much worse for performance.
jQuery's on()
function does not introduce any new functionality that did not already exist, it is just an attempt to standardize event handling in jQuery (you no longer have to decide between live, bind, or delegate).
Yes, you can 'refresh' a Google Map like this:
google.maps.event.trigger(map, 'resize');
This basically sends a signal to your map to redraw it.
Hope that helps!
Changing the ssh exectuable from builtin to nativ under settings/version control/git did the trick for me.
As the answers above are not showing all strategy details. For example, some answer is missing the details about the import resolve
option and the recursive
which has many sub options as ours
, theirs
, patience
, renormalize
, etc.
Therefore, I would recommend to visit the official git
documentation which explains all the possible features features:
We will create another array of indexes from 0 to n-1 Then zip this to the original array and then sort it on the basis of the original values
ar = [1,2,3,4,5]
new_ar = list(zip(ar,[i for i in range(len(ar))]))
new_ar.sort()
`
I think you want to change the setting called "DropDownStyle" to be "DropDownList".
Now you can do df['column'].dt.date
Note that for datetime objects, if you don't see the hour when they're all 00:00:00, that's not pandas. That's iPython notebook trying to make things look pretty.
You can sit elements next to each other by using the CSS float property:
#first {
float: left;
}
#second {
float: left;
}
You'd need to make sure that the wrapper div allows for the floating in terms of width, and margins etc are set correctly.
#! /bin/sh
next=$1
while [ -n "${next}" ] ; do
last=$next
shift
next=$1
done
echo $last
Use \overset{above}{main}
in math mode. In your case, \overset{a}{\#}
.
If you are trying to use mysqlclient
on WINDOWS with this failure, try to install the lower version instead:
pip install mysqlclient==1.3.4
I've just had the same problem.
You only get the text twice in your result if you include a match group (in brackets) and the 'g' (global) modifier. The first item always is the first result, normally OK when using match(reg) on a short string, however when using a construct like:
while ((result = reg.exec(string)) !== null){
console.log(result);
}
the results are a little different.
Try the following code:
var regEx = new RegExp('([0-9]+ (cat|fish))','g'), sampleString="1 cat and 2 fish";
var result = sample_string.match(regEx);
console.log(JSON.stringify(result));
// ["1 cat","2 fish"]
var reg = new RegExp('[0-9]+ (cat|fish)','g'), sampleString="1 cat and 2 fish";
while ((result = reg.exec(sampleString)) !== null) {
console.dir(JSON.stringify(result))
};
// '["1 cat","cat"]'
// '["2 fish","fish"]'
var reg = new RegExp('([0-9]+ (cat|fish))','g'), sampleString="1 cat and 2 fish";
while ((result = reg.exec(sampleString)) !== null){
console.dir(JSON.stringify(result))
};
// '["1 cat","1 cat","cat"]'
// '["2 fish","2 fish","fish"]'
(tested on recent V8 - Chrome, Node.js)
The best answer is currently a comment which I can't upvote, so credit to @Mic.
Wonderful answer! I needed to fill in the empty cells in a column where there were titles in cells that applied to the empty cells below until the next title cell.
I used your code above to develop the code that is below my example sheet here. I applied this code as a macro ctl/shft/D to rapidly run down the column copying the titles.
--- Example Spreadsheet ------------ Title1 is copied to rows 2 and 3; Title2 is copied to cells below it in rows 5 and 6. After the second run of the Macro the active cell is the Title3 cell.
' **row** **Column1** **Column2**
' 1 Title1 Data 1 for title 1
' 2 Data 2 for title 1
' 3 Data 3 for title 1
' 4 Title2 Data 1 for title 2
' 5 Data 2 for title 2
' 6 Data 3 for title 2
' 7 Title 3 Data 1 for title 3
----- CopyDown code ----------
Sub CopyDown()
Dim Lastrow As String, FirstRow As String, strtCell As Range
'
' CopyDown Macro
' Copies the current cell to any empty cells below it.
'
' Keyboard Shortcut: Ctrl+Shift+D
'
Set strtCell = ActiveCell
FirstRow = strtCell.Address
' Lastrow is address of the *list* of empty cells
Lastrow = Range(Selection, Selection.End(xlDown).Offset(-1, 0)).Address
' MsgBox Lastrow
Range(Lastrow).Formula = strtCell.Formula
Range(Lastrow).End(xlDown).Select
End Sub
Not sure if you can do that with multi-line code, but multi-line variables can be done:
Here is the relevant chunk:
I figured out how to use both <![CDATA[ along with <%= for variables, which allows you to code without worry.
You basically have to terminate the CDATA tags before the VB variable and then re-add it after so the CDATA does not capture the VB code. You need to wrap the entire code block in a tag because you will you have multiple CDATA blocks.
Dim script As String = <code><![CDATA[
<script type="text/javascript">
var URL = ']]><%= domain %><![CDATA[/mypage.html';
</script>]]>
</code>.value
I guess the dirtiest solution is this:
list(eval('0, 0, 0, 11, 0, 0, 0, 11'))
One possible reason of why scroll.fullScroll(View.FOCUS_DOWN)
might not work even wrapped in .post()
is that the view is not laid out. In this case View.doOnLayout() could be a better option:
scroll.doOnLayout(){
scroll.fullScroll(View.FOCUS_DOWN)
}
Or, something more elaborated for the brave souls: https://chris.banes.dev/2019/12/03/suspending-views/
You're using the @ symbol, which removes the need for escaping your backslashes.
Remove the @ or replace \\ with \
You guys are completely right numbers can only go in the numeric field. I use the exact same thing as already listed with a bit of css styling on a span tag:
<span>$</span><input type="number" min="0.01" step="0.01" max="2500" value="25.67">
Then add a bit of styling magic:
span{
position:relative;
margin-right:-20px
}
input[type='number']{
padding-left:20px;
text-align:left;
}
Here is a simple solution.
Set the size attribute of your view controller in the storyboard to "Freeform" and set the size you want. Make sure it's big enough to fit the full content of your scroll view.
Add your scroll view and set the constraints as you normally would. i.e. if you wants the scroll view to be the size of your view, then attach your top, bottom, leading, trailing margins to the superview as you normally would.
Now just make sure there are constraints in the subviews of the scrollview that connect the top and bottom of the scroll view. Same for left and right if you have horizontal scrolling.
I'm quite sure you won't get this 32Bit DLL working in Office 64Bit. The DLL needs to be updated by the author to be compatible with 64Bit versions of Office.
The code changes you have found and supplied in the question are used to convert calls to APIs that have already been rewritten for Office 64Bit. (Most Windows APIs have been updated.)
From: http://technet.microsoft.com/en-us/library/ee681792.aspx:
"ActiveX controls and add-in (COM) DLLs (dynamic link libraries) that were written for 32-bit Office will not work in a 64-bit process."
Edit:
Further to your comment, I've tried the 64Bit DLL version on Win 8 64Bit with Office 2010 64Bit. Since you are using User Defined Functions called from the Excel worksheet you are not able to see the error thrown by Excel and just end up with the #VALUE
returned.
If we create a custom procedure within VBA and try one of the DLL functions we see the exact error thrown. I tried a simple function of swe_day_of_week
which just has a time as an input and I get the error Run-time error '48' File not found: swedll32.dll
.
Now I have the 64Bit DLL you supplied in the correct locations so it should be found which suggests it has dependencies which cannot be located as per https://stackoverflow.com/a/8607250/1733206
I've got all the .NET frameworks installed which would be my first guess, so without further information from the author it might be difficult to find the problem.
Edit2: And after a bit more investigating it appears the 64Bit version you have supplied is actually a 32Bit version. Hence the error message on the 64Bit Office. You can check this by trying to access the '64Bit' version in Office 32Bit.
You can make a cookie never end by setting it to whatever date plus one more than the current year like this :
var d = new Date();
document.cookie = "username=John Doe; expires=Thu, 18 Dec " + (d.getFullYear() + 1) + " 12:00:00 UTC";
You could do something like:
find . -type d > dirs.txt
to create the list of directories, then
xargs mkdir -p < dirs.txt
to create the directories on the destination.
I use google-api-php-client v2.2.2 I get a new token with fetchAccessTokenWithRefreshToken();
if function call without params, it returns an updated access token and the refreshed token is not lost.
if ($client->getAccessToken() && $client->isAccessTokenExpired()) {
$new_token=$client->fetchAccessTokenWithRefreshToken();
$token_data = $client->verifyIdToken();
}
With java lambdas (available since java 8) you can simply convert javax.swing.filechooser.FileFilter
to java.io.FileFilter
in one line.
javax.swing.filechooser.FileFilter swingFilter = new FileNameExtensionFilter("jpeg files", "jpeg");
java.io.FileFilter ioFilter = file -> swingFilter.accept(file);
new File("myDirectory").listFiles(ioFilter);
Using styles.xml (value)
Very Easy solution , change colorPrimary as your choice and it will change color of button text of alert box.
<style name="MyAlertDialogStyle" parent="android:Theme.Material.Dialog.Alert">
<!-- Used for the buttons -->
<item name="colorAccent">@android:color/white</item>
<!-- Used for the title and text -->
<item name="android:textColorPrimary">@color/black</item>
<!-- Used for the background -->
<item name="android:background">#ffffff</item>
<item name="android:colorPrimary">@color/white</item>
<item name="android:colorAccent">@color/white</item>
<item name="android:windowEnterAnimation">@anim/bottom_left_enter</item>
</style>
Alternative (Using Java)
@SuppressLint("ResourceAsColor")
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
AlertDialog dialog = new AlertDialog.Builder(view.getContext(), R.style.MyAlertDialogStyle)
.setTitle("Royal Frolics")
.setIcon(R.mipmap.ic_launcher)
.setMessage(message)
.setPositiveButton("OK", (dialog1, which) -> {
//do nothing
result.confirm();
}).create();
Objects.requireNonNull(dialog.getWindow()).getAttributes().windowAnimations = R.style.MyAlertDialogStyle;
dialog.show();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(R.color.white);
return true;
}
This piece of vba worked for me:
Sub connect()
Dim Password As String
Dim SQLStr As String
'OMIT Dim Cn statement
Dim Server_Name As String
Dim User_ID As String
Dim Database_Name As String
'OMIT Dim rs statement
Set rs = CreateObject("ADODB.Recordset") 'EBGen-Daily
Server_Name = Range("b2").Value
Database_name = Range("b3").Value ' Name of database
User_ID = Range("b4").Value 'id user or username
Password = Range("b5").Value 'Password
SQLStr = "SELECT * FROM ComputingNotesTable"
Set Cn = CreateObject("ADODB.Connection") 'NEW STATEMENT
Cn.Open "Driver={MySQL ODBC 5.2.2 Driver};Server=" & _
Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
rs.Open SQLStr, Cn, adOpenStatic
Dim myArray()
myArray = rs.GetRows()
kolumner = UBound(myArray, 1)
rader = UBound(myArray, 2)
For K = 0 To kolumner ' Using For loop data are displayed
Range("a5").Offset(0, K).Value = rs.Fields(K).Name
For R = 0 To rader
Range("A5").Offset(R + 1, K).Value = myArray(K, R)
Next
Next
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub
Put it all in one document and use this:
/* Smartphones (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px) {
/* Styles */
}
/* Smartphones (landscape) ----------- */
@media only screen
and (min-width : 321px) {
/* Styles */
}
/* Smartphones (portrait) ----------- */
@media only screen
and (max-width : 320px) {
/* Styles */
}
/* iPads (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px) {
/* Styles */
}
/* iPads (landscape) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape) {
/* Styles */
}
/* iPads (portrait) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait) {
/* Styles */
}
/* Desktops and laptops ----------- */
@media only screen
and (min-width : 1224px) {
/* Styles */
}
/* Large screens ----------- */
@media only screen
and (min-width : 1824px) {
/* Styles */
}
/* iPhone 4 - 5s ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */
}
/* iPhone 6 ----------- */
@media
only screen and (max-device-width: 667px)
only screen and (-webkit-device-pixel-ratio: 2) {
/* Styles */
}
/* iPhone 6+ ----------- */
@media
only screen and (min-device-width : 414px)
only screen and (-webkit-device-pixel-ratio: 3) {
/*** You've spent way too much on a phone ***/
}
/* Samsung Galaxy S7 Edge ----------- */
@media only screen
and (-webkit-min-device-pixel-ratio: 3),
and (min-resolution: 192dpi)and (max-width:640px) {
/* Styles */
}
Source: http://css-tricks.com/snippets/css/media-queries-for-standard-devices/
At this point, I would definitely consider using em
values instead of pixels. For more information, check this post: https://zellwk.com/blog/media-query-units/.
This question was merged with the more appropriate question, why hash tables should use prime sized arrays, and not power of 2. For hash functions itself there are plenty of good answers here, but for the related question, why some security-critical hash tables, like glibc, use prime-sized arrays, there's none yet.
Generally power of 2 tables are much faster. There the expensive h % n => h & bitmask
, where the bitmask can be calculated via clz
("count leading zeros") of the size n. A modulo function needs to do integer division which is about 50x slower than a logical and
. There are some tricks to avoid a modulo, like using Lemire's https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/, but generally fast hash tables use power of 2, and secure hash tables use primes.
Why so?
Security in this case is defined by attacks on the collision resolution strategy, which is with most hash tables just linear search in a linked list of collisions. Or with the faster open-addressing tables linear search in the table directly. So with power of 2 tables and some internal knowledge of the table, e.g. the size or the order of the list of keys provided by some JSON interface, you get the number of right bits used. The number of ones on the bitmask. This is typically lower than 10 bits. And for 5-10 bits it's trivial to brute force collisions even with the strongest and slowest hash functions. You don't get the full security of your 32bit or 64 bit hash functions anymore. And the point is to use fast small hash functions, not monsters such as murmur or even siphash.
So if you provide an external interface to your hash table, like a DNS resolver, a programming language, ... you want to care about abuse folks who like to DOS such services. It's normally easier for such folks to shut down your public service with much easier methods, but it did happen. So people did care.
So the best options to prevent from such collision attacks is either
1) to use prime tables, because then
2) use better measures against the actual attack, together with fast power of 2 sizes.
There's a wide-spread myth that more secure hash functions help to prevent such attacks, which is wrong as I explained. There's no security with low bits only. This would only work with prime-sized tables, but this would use a combination of the two slowest methods, slow hash plus slow prime modulo.
Hash functions for hash tables primarily need to be small (to be inlinable) and fast. Security can come only from preventing linear search in the collisions. And not to use trivially bad hash functions, like ones insensitive to some values (like \0 when using multiplication).
Using random seeds is also a good option, people started with that first, but with enough information of the table even a random seed does not help much, and dynamic languages typically make it trivial to get the seed via other methods, as it's stored in known memory locations.
If you have a Decimal or similar numeric type, you can use:
Math.Round(myNumber, 2)
EDIT: So, in your case, it would be:
Public Class Form1
Private Sub btncalc_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles btncalc.Click
txtA.Text = Math.Round((Val(txtD.Text) / Val(txtC.Text) * Val(txtF.Text) / Val(txtE.Text)), 2)
txtB.Text = Math.Round((Val(txtA.Text) * 1000 / Val(txtG.Text)), 2)
End Sub
End Class
Here is another option:
JAVASCRIPT
var initTopPosition= $('#myElementToStick').offset().top;
$(window).scroll(function(){
if($(window).scrollTop() > initTopPosition)
$('#myElementToStick').css({'position':'fixed','top':'0px'});
else
$('#myElementToStick').css({'position':'absolute','top':initTopPosition+'px'});
});
Your #myElementToStick
should start with position:absolute
CSS property.
psql --set=sslmode=require -h localhost -p 2345 -U thirunas \
-d postgres -f test_schema.ddl
Another Example for securely connecting to Azure's managed Postgres database:
psql --file=product_data.sql --host=hostname.postgres.database.azure.com --port=5432 \
--username=postgres@postgres-esprit --dbname=product_data \
--set=sslmode=verify-full --set=sslrootcert=/opt/ssl/BaltimoreCyberTrustRoot.crt.pem
As Ajay beniwal mentioned above you need to use Apply to start digestion.
var app = angular.module('test', []);
app.controller('TestCtrl', function ($scope) {
$scope.testValue = 0;
setInterval(function() {
console.log($scope.testValue++);
$scope.$apply()
}, 500);
});
Do not use regular expressions to parse HTML.
But if you ever need to find all regexp matches in a string, use the findall
function.
import re
line = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</form> more text?'
matches = re.findall('<form>(.*?)</form>', line, re.DOTALL)
print(matches)
# Output: ['Form 1', 'Form 2']
You can just replace like this,
var someString = "23/03/2012";
someString.replace(/\//g, "-");
It works for me..
With a running instance of myExecutableName
having a PID 15073
:
hitting Tab twice after $ gdb myExecu
in the command line, will automagically autocompletes to:
$ gdb myExecutableName 15073
and will attach gdb to this process. That's nice!
On Mac OSX, manually delete these 2 directories under your pathToPython/site-packages/ will work:
for example, to remove pyasn1, which is a distutils installed project:
To find out where is your site-packages:
python -m site
"
is the correct way, the third of your tests:
<option value=""asd">test</option>
You can see this working below, or on jsFiddle.
alert($("option")[0].value);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select>_x000D_
<option value=""asd">Test</option>_x000D_
</select>
_x000D_
Alternatively, you can delimit the attribute value with single quotes:
<option value='"asd'>test</option>
From my understanding if the branch to be deleted can be reached by another branch, you can delete it safely using
git branch -d [branch]
and your work is not lost. Remember that a branch is not a snapshot, but a pointer to one. So when you delete a branch you delete a pointer.
You won't even lose work if you delete a branch which cannot be reached by another one. Of course it won't be as easy as checking out the commit hash, but you can still do it. That's why Git is unable to delete a branch which cannot be reached by using -d
. Instead you have to use
git branch -D [branch]
This is part of a must watch video from Scott Chacon about Git. Check minute 58:00 when he talks about branches and how delete them.
For Spring 4, using Spring Boot we can have the following example without using the anti-pattern of getting the Bean from the ApplicationContext directly:
package com.yourproject;
@SpringBootApplication
public class TestBed implements CommandLineRunner {
private MyService myService;
@Autowired
public TestBed(MyService myService){
this.myService = myService;
}
public static void main(String... args) {
SpringApplication.run(TestBed.class, args);
}
@Override
public void run(String... strings) throws Exception {
System.out.println("myService: " + MyService );
}
}
@Service
public class MyService{
public String getSomething() {
return "something";
}
}
Make sure that all your injected services are under com.yourproject
or its subpackages.
Be careful when using the isa
function. This will be true if your object is of the specified type or one of its subclasses. You have to use strcmp
with the class
function to test if the object is specifically that type and not a subclass.
Try this one also...
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
_x000D_
<p>Click the button to join two arrays.</p>_x000D_
_x000D_
<button onclick="myFunction()">Try it</button>_x000D_
_x000D_
<p id="demo"></p>_x000D_
<p id="demo1"></p>_x000D_
<script>_x000D_
function myFunction() {_x000D_
var hege = [{_x000D_
1: "Cecilie",_x000D_
2: "Lone"_x000D_
}];_x000D_
var stale = [{_x000D_
1: "Emil",_x000D_
2: "Tobias"_x000D_
}];_x000D_
var hege = hege.concat(stale);_x000D_
document.getElementById("demo1").innerHTML = hege;_x000D_
document.getElementById("demo").innerHTML = stale;_x000D_
}_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
For Asp.Net core you better use
<partial name="_MyPartialView" model="MyModel" />
So for example
@foreach (var item in Model)
{
<partial name="_MyItemView" model="item" />
}
You can use iconSize
like this:
floatingActionButton: FloatingActionButton(
onPressed: () {
// Add your onPressed code here
},
child: IconButton(
icon: isPlaying
? Icon(
Icons.pause_circle_outline,
)
: Icon(
Icons.play_circle_outline,
),
iconSize: 40,
onPressed: () {
setState(() {
isPlaying = !isPlaying;
});
},
),
),
I've found version 0.7.1 Alpha of PuTTY Connection Manager to be the most stable (it was previously hidden on the forums). It's available from PuTTY Connection Manager – Website Down.
In bootstrap 4, you can use 'w-100' class (w as width, and 100 as 100%)
You can find documentation here: https://getbootstrap.com/docs/4.0/utilities/sizing/
Those are good ideas for your implementation, but if you are presenting a cheese making interface to a user. They don't care how many holes the cheese has or what internals go into making cheese. The user of your code just wants "gouda" or "parmesean" right?
So why not do this:
# cheese_user.py
from cheeses import make_gouda, make_parmesean
gouda = make_gouda()
paremesean = make_parmesean()
And then you can use any of the methods above to actually implement the functions:
# cheeses.py
class Cheese(object):
def __init__(self, *args, **kwargs):
#args -- tuple of anonymous arguments
#kwargs -- dictionary of named arguments
self.num_holes = kwargs.get('num_holes',random_holes())
def make_gouda():
return Cheese()
def make_paremesean():
return Cheese(num_holes=15)
This is a good encapsulation technique, and I think it is more Pythonic. To me this way of doing things fits more in line more with duck typing. You are simply asking for a gouda object and you don't really care what class it is.
You have to duplicate the repo
You can see this doc (from github)
To create a duplicate of a repository without forking, you need to run a special clone command against the original repository and mirror-push to the new one.
In the following cases, the repository you're trying to push to--like exampleuser/new-repository or exampleuser/mirrored--should already exist on GitHub. See "Creating a new repository" for more information.
Mirroring a repository
To make an exact duplicate, you need to perform both a bare-clone and a mirror-push.
Open up the command line, and type these commands:
$ git clone --bare https://github.com/exampleuser/old-repository.git # Make a bare clone of the repository $ cd old-repository.git $ git push --mirror https://github.com/exampleuser/new-repository.git # Mirror-push to the new repository $ cd .. $ rm -rf old-repository.git # Remove our temporary local repository
If you want to mirror a repository in another location, including getting updates from the original, you can clone a mirror and periodically push the changes.
$ git clone --mirror https://github.com/exampleuser/repository-to-mirror.git # Make a bare mirrored clone of the repository $ cd repository-to-mirror.git $ git remote set-url --push origin https://github.com/exampleuser/mirrored # Set the push location to your mirror
As with a bare clone, a mirrored clone includes all remote branches and tags, but all local references will be overwritten each time you fetch, so it will always be the same as the original repository. Setting the URL for pushes simplifies pushing to your mirror. To update your mirror, fetch updates and push, which could be automated by running a cron job.
$ git fetch -p origin $ git push --mirror
From the documentation:
We can add to a list in many ways:
assert [1,2] + 3 + [4,5] + 6 == [1, 2, 3, 4, 5, 6]
assert [1,2].plus(3).plus([4,5]).plus(6) == [1, 2, 3, 4, 5, 6]
//equivalent method for +
def a= [1,2,3]; a += 4; a += [5,6]; assert a == [1,2,3,4,5,6]
assert [1, *[222, 333], 456] == [1, 222, 333, 456]
assert [ *[1,2,3] ] == [1,2,3]
assert [ 1, [2,3,[4,5],6], 7, [8,9] ].flatten() == [1, 2, 3, 4, 5, 6, 7, 8, 9]
def list= [1,2]
list.add(3) //alternative method name
list.addAll([5,4]) //alternative method name
assert list == [1,2,3,5,4]
list= [1,2]
list.add(1,3) //add 3 just before index 1
assert list == [1,3,2]
list.addAll(2,[5,4]) //add [5,4] just before index 2
assert list == [1,3,5,4,2]
list = ['a', 'b', 'z', 'e', 'u', 'v', 'g']
list[8] = 'x'
assert list == ['a', 'b', 'z', 'e', 'u', 'v', 'g', null, 'x']
You can also do:
def myNewList = myList << "fifth"
If you have a BASH shell on your mac/linux in-front of you, you try out the below steps to understand the redirection practically :
Create a 2 line script called zz.sh
#!/bin/bash
echo "Hello. This is a proper command"
junk_errorcommand
Currently, simply executing the script sends both STDOUT and STDERR to the screen.
./zz.sh
Now start with the standard redirection :
zz.sh > zfile.txt
In the above, "echo" (STDOUT) goes into the zfile.txt. Whereas "error" (STDERR) is displayed on the screen.
The above is the same as :
zz.sh 1> zfile.txt
Now you can try the opposite, and redirect "error" STDERR into the file. The STDOUT from "echo" command goes to the screen.
zz.sh 2> zfile.txt
Combining the above two, you get:
zz.sh 1> zfile.txt 2>&1
Explanation:
Eventually, you can pack the whole thing inside nohup command & to run it in the background:
nohup zz.sh 1> zfile.txt 2>&1&
Get-ADPrincipalGroupMembership username | select name
Got it from another answer but the script works magic. :)
You can change the background of the canvas by doing this:
<head>
<style>
canvas {
background-color: blue;
}
</style>
</head>
Here i post my code, after i have pushed myself for one working day to find this solution.
Function to get the last saved record :
private function getLastId($query) {
$conn = $this->getDoctrine()->getConnection();
$stmt = $conn->prepare($query);
$stmt->execute();
$lastId = $stmt->fetch()['id'];
return $lastId;
}
Another Function which call the above function
private function clientNum() {
$lastId = $this->getLastId("SELECT id FROM client ORDER BY id DESC LIMIT 1");
$noClient = 'C' . sprintf("%06d", $lastId + 1); // C000002 if the last record ID is 1
return $noClient;
}
This one works for the surname case...
With different types of separators, and it keeps the same separator:
jean-frederic --> Jean-Frederic
jean frederic --> Jean Frederic
The code works with the GWT client side.
public static String capitalize (String givenString) {
String Separateur = " ,.-;";
StringBuffer sb = new StringBuffer();
boolean ToCap = true;
for (int i = 0; i < givenString.length(); i++) {
if (ToCap)
sb.append(Character.toUpperCase(givenString.charAt(i)));
else
sb.append(Character.toLowerCase(givenString.charAt(i)));
if (Separateur.indexOf(givenString.charAt(i)) >=0)
ToCap = true;
else
ToCap = false;
}
return sb.toString().trim();
}
I just learnt this myself the other day: the this keyword defines that method has being an extension of the class that proceeds it. So for your example, MyClass will have a new extension method called Foo (which doesn't accept any parameter and returns an int; it can be used as with any other public method).
That's all. You may want to revoke the old certificate on developer.apple.com too.
Step 1: Xcode -> Product -> Archives -> Click manage certificate
Step 2: Add iOS distribution
Thanks to Flek for answering my question in his comment:
<div ng-app="myApp" scroll id="page" ng-class="{min:boolChangeClass}">
<header></header>
<section></section>
</div>
app = angular.module('myApp', []);
app.directive("scroll", function ($window) {
return function(scope, element, attrs) {
angular.element($window).bind("scroll", function() {
if (this.pageYOffset >= 100) {
scope.boolChangeClass = true;
} else {
scope.boolChangeClass = false;
}
scope.$apply();
});
};
});
I just tested this and it works fine
var d = new Date(1441121836000);
The data object has a constructor which takes milliseconds as an argument.
Using PuTTY's pscp.exe (which I have in an $env:path
directory):
pscp -sftp -pw passwd c:\filedump\* user@host:/Outbox/
mv c:\filedump\* c:\backup\*
I think that using colnames
and rownames
makes the most sense; here's why.
Using names
has several disadvantages. You have to remember that it means "column names", and it only works with data frame, so you'll need to call colnames
whenever you use matrices. By calling colnames
, you only have to remember one function. Finally, if you look at the code for colnames
, you will see that it calls names
in the case of a data frame anyway, so the output is identical.
rownames
and row.names
return the same values for data frame and matrices; the only difference that I have spotted is that where there aren't any names, rownames
will print "NULL" (as does colnames
), but row.names
returns it invisibly. Since there isn't much to choose between the two functions, rownames
wins on the grounds of aesthetics, since it pairs more prettily withcolnames
. (Also, for the lazy programmer, you save a character of typing.)
The selector returns an array of jQuery objects. If no matching elements are found, it returns an empty array. You can check the .length
of the collection returned by the selector or check whether the first array element is 'undefined'.
You can use any the following examples inside an IF statement and they all produce the same result. True, if the selector found a matching element, false otherwise.
$('#notAnElement').length > 0
$('#notAnElement').get(0) !== undefined
$('#notAnElement')[0] !== undefined
CLIENT
namespace SocketKlient
{
class Program
{
static Socket Klient;
static IPEndPoint endPoint;
static void Main(string[] args)
{
Klient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
string command;
Console.WriteLine("Write IP address");
command = Console.ReadLine();
IPAddress Address;
while(!IPAddress.TryParse(command, out Address))
{
Console.WriteLine("wrong IP format");
command = Console.ReadLine();
}
Console.WriteLine("Write port");
command = Console.ReadLine();
int port;
while (!int.TryParse(command, out port) && port > 0)
{
Console.WriteLine("Wrong port number");
command = Console.ReadLine();
}
endPoint = new IPEndPoint(Address, port);
ConnectC(Address, port);
while(Klient.Connected)
{
Console.ReadLine();
Odesli();
}
}
public static void ConnectC(IPAddress ip, int port)
{
IPEndPoint endPoint = new IPEndPoint(ip, port);
Console.WriteLine("Connecting...");
try
{
Klient.Connect(endPoint);
Console.WriteLine("Connected!");
}
catch
{
Console.WriteLine("Connection fail!");
return;
}
Task t = new Task(WaitForMessages);
t.Start();
}
public static void SendM()
{
string message = "Actualy date is " + DateTime.Now;
byte[] buffer = Encoding.UTF8.GetBytes(message);
Console.WriteLine("Sending: " + message);
Klient.Send(buffer);
}
public static void WaitForMessages()
{
try
{
while (true)
{
byte[] buffer = new byte[64];
Console.WriteLine("Waiting for answer");
Klient.Receive(buffer, 0, buffer.Length, 0);
string message = Encoding.UTF8.GetString(buffer);
Console.WriteLine("Answer: " + message);
}
}
catch
{
Console.WriteLine("Disconnected");
}
}
}
}
Try this:
Integer startIn = null;
try {
startIn = Integer.valueOf(startField.getText());
} catch (NumberFormatException e) {
.
.
.
}
if (startIn == null) {
// Prompt for value...
}
If you don't mind always including .sh on the script file name, then you can keep the same script for Cygwin and Unix (Macbook).
To illustrate:
1. Always include .sh to your script file name, e.g., test1.sh
2. test1.sh looks like the following as an example:
3. On Windows with Cygwin, you type "test1.sh" to run#!/bin/bash
echo '$0 = ' $0
echo '$1 = ' $1
filepath=$1
4. On a Unix, you also type "test1.sh" to run
Note: On Windows, you need to use the file explorer to do following once:
1. Open the file explorer
2. Right-click on a file with .sh extension, like test1.sh
3. Open with... -> Select sh.exe
After this, your Windows 10 remembers to execute all .sh files with sh.exe.
Note: Using this method, you do not need to prepend your script file name with bash to run
You can also do this by passing function with onclick event
<a onclick="getColor(this);" color="red">
<script type="text/javascript">
function getColor(el)
{
color = $(el).attr('color');
alert(color);
}
</script>
You can use the bootstrap grid system. as Yoann said
<div class="container">
<div class="row">
<form role="form">
<div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
</div>
<div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
<label for="exampleInputEmail1">Name</label>
<input type="text" class="form-control" id="exampleInputEmail1" placeholder="Enter Name">
</div>
<div class="clearfix"></div>
<div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
<label for="exampleInputPassword1">Confirm Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Confirm Password">
</div>
</form>
<div class="clearfix">
</div>
</div>
</div>
This takes care of nulls
var body = JObject.Parse("anyjsonString");
body?.SelectToken("path-string-prop")?.ToString();
body?.SelectToken("path-double-prop")?.ToObject<double>();
What platform does the path come from? Windows paths are different from POSIX paths are different from Mac OS 9 paths are different from RISC OS paths are different...
If it's a web app where the filename can come from different platforms there is no one solution. However a reasonable stab is to use both '\' (Windows) and '/' (Linux/Unix/Mac and also an alternative on Windows) as path separators. Here's a non-RegExp version for extra fun:
var leafname= pathname.split('\\').pop().split('/').pop();
React hooks are a new way (still being developed) to access the core features of react such as state
without having to use classes, in your example if you want to increment a counter directly in the handler function without specifying it directly in the onClick
prop, you could do something like:
...
const [count, setCounter] = useState(0);
const [moreStuff, setMoreStuff] = useState(...);
...
const setCount = () => {
setCounter(count + 1);
setMoreStuff(...);
...
};
and onClick:
<button onClick={setCount}>
Click me
</button>
Let's quickly explain what is going on in this line:
const [count, setCounter] = useState(0);
useState(0)
returns a tuple where the first parameter count
is the current state of the counter and setCounter
is the method that will allow us to update the counter's state. We can use the setCounter
method to update the state of count
anywhere - In this case we are using it inside of the setCount
function where we can do more things; the idea with hooks is that we are able to keep our code more functional and avoid class based components if not desired/needed.
I wrote a complete article about hooks with multiple examples (including counters) such as this codepen, I made use of useState
, useEffect
, useContext
, and custom hooks. I could get into more details about how hooks work on this answer but the documentation does a very good job explaining the state hook and other hooks in detail, hope it helps.
update: Hooks are not longer a proposal, since version 16.8 they're now available to be used, there is a section in React's site that answers some of the FAQ.
Have you checked your folder structure? It seems to me like Express can't find your root directory, which should be a a folder named "site" right under your default directory. Here is how it should look like, according to the tutorial:
node_modules/
.bin/
express/
mongoose/
path/
site/
css/
img/
js/
index.html
package.json
For example on my machine, I started getting the same error as you when I renamed my "site" folder as something else. So I would suggest you check that you have the index.html page inside a "site" folder that sits on the same path as your server.js file.
Hope that helps!
You can't use CUDA for GPU Programming as CUDA is supported by NVIDIA devices only. If you want to learn GPU Computing I would suggest you to start CUDA and OpenCL simultaneously. That would be very much beneficial for you.. Talking about CUDA, you can use mCUDA. It doesn't require NVIDIA's GPU..
I recommend php-ffmpeg library.
Extracting image
You can extract a frame at any timecode using the
FFMpeg\Media\Video::frame
method.This code returns a
FFMpeg\Media\Frame
instance corresponding to the second 42. You can pass anyFFMpeg\Coordinate\TimeCode
as argument, see dedicated documentation below for more information.
$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(42));
$frame->save('image.jpg');
If you want to extract multiple images from the video, you can use the following filter:
$video
->filters()
->extractMultipleFrames(FFMpeg\Filters\Video\ExtractMultipleFramesFilter::FRAMERATE_EVERY_10SEC, '/path/to/destination/folder/')
->synchronize();
$video
->save(new FFMpeg\Format\Video\X264(), '/path/to/new/file');
By default, this will save the frames as jpg images.
You are able to override this using setFrameFileType
to save the frames in another format:
$frameFileType = 'jpg'; // either 'jpg', 'jpeg' or 'png'
$filter = new ExtractMultipleFramesFilter($frameRate, $destinationFolder);
$filter->setFrameFileType($frameFileType);
$video->addFilter($filter);
URL url = Test.class.getResource(args[0]); // reading demo file path from
// same location where class
File input=null;
try {
input = new File(url.toURI());
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Just download and install "Samsung Kies" from this link. and everything would work as required.
Before installing, uninstall the drivers you have installed for your device.
Update:
Two possible solutions:
Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:
sudo apt-get install bison flex
There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.
You can try this
var str = 'hello world !!';
str = str.replace(/\s+/g, '-');
It will even replace multiple spaces with single '-'.
If TomCat is install. Perhaps it is not installed Java EE. Services-> plug-ins-> additional plug-ins-> in the search dial tomcat. and install the module java ee. then in the services, servers, add the tomcat server.
Those look much like Bonjour / mDNS requests to me. Those packets use multicast IP address 224.0.0.251 and port 5353.
The most likely source for this is Apple iTunes, which comes pre-installed on Mac computers (and is a popular install on Windows machines as well). Apple iTunes uses it to discover other iTunes-compatible devices in the same WiFi network.
mDNS is also used (primarily by Apple's Mac and iOS devices) to discover mDNS-compatible devices such as printers on the same network.
If this is a Linux box instead, it's probably the Avahi daemon then. Avahi is ZeroConf/Bonjour compatible and installed by default, but if you don't use DNS-SD or mDNS, it can be disabled.
I haven't done any benchmarks, but this recipe "works for me".
The short version: use '%x' % val
, then unhexlify
the result. The devil is in the details, though, as unhexlify
requires an even number of hex digits, which %x
doesn't guarantee. See the docstring, and the liberal inline comments for details.
from binascii import unhexlify
def long_to_bytes (val, endianness='big'):
"""
Use :ref:`string formatting` and :func:`~binascii.unhexlify` to
convert ``val``, a :func:`long`, to a byte :func:`str`.
:param long val: The value to pack
:param str endianness: The endianness of the result. ``'big'`` for
big-endian, ``'little'`` for little-endian.
If you want byte- and word-ordering to differ, you're on your own.
Using :ref:`string formatting` lets us use Python's C innards.
"""
# one (1) hex digit per four (4) bits
width = val.bit_length()
# unhexlify wants an even multiple of eight (8) bits, but we don't
# want more digits than we need (hence the ternary-ish 'or')
width += 8 - ((width % 8) or 8)
# format width specifier: four (4) bits per hex digit
fmt = '%%0%dx' % (width // 4)
# prepend zero (0) to the width, to zero-pad the output
s = unhexlify(fmt % val)
if endianness == 'little':
# see http://stackoverflow.com/a/931095/309233
s = s[::-1]
return s
...and my nosetest unit tests ;-)
class TestHelpers (object):
def test_long_to_bytes_big_endian_small_even (self):
s = long_to_bytes(0x42)
assert s == '\x42'
s = long_to_bytes(0xFF)
assert s == '\xff'
def test_long_to_bytes_big_endian_small_odd (self):
s = long_to_bytes(0x1FF)
assert s == '\x01\xff'
s = long_to_bytes(0x201FF)
assert s == '\x02\x01\xff'
def test_long_to_bytes_big_endian_large_even (self):
s = long_to_bytes(0xab23456c8901234567)
assert s == '\xab\x23\x45\x6c\x89\x01\x23\x45\x67'
def test_long_to_bytes_big_endian_large_odd (self):
s = long_to_bytes(0x12345678901234567)
assert s == '\x01\x23\x45\x67\x89\x01\x23\x45\x67'
def test_long_to_bytes_little_endian_small_even (self):
s = long_to_bytes(0x42, 'little')
assert s == '\x42'
s = long_to_bytes(0xFF, 'little')
assert s == '\xff'
def test_long_to_bytes_little_endian_small_odd (self):
s = long_to_bytes(0x1FF, 'little')
assert s == '\xff\x01'
s = long_to_bytes(0x201FF, 'little')
assert s == '\xff\x01\x02'
def test_long_to_bytes_little_endian_large_even (self):
s = long_to_bytes(0xab23456c8901234567, 'little')
assert s == '\x67\x45\x23\x01\x89\x6c\x45\x23\xab'
def test_long_to_bytes_little_endian_large_odd (self):
s = long_to_bytes(0x12345678901234567, 'little')
assert s == '\x67\x45\x23\x01\x89\x67\x45\x23\x01'
A simple algorithm that gives you random numbers without duplicates can be found in the book Programming Pearls p. 127.
Attention: The resulting array contains the numbers in order! If you want them in random order, you have to shuffle the array, either with Fisher–Yates shuffle or by using a List and call Collections.shuffle()
.
The benefit of this algorithm is that you do not need to create an array with all the possible numbers and the runtime complexity is still linear O(n)
.
public static int[] sampleRandomNumbersWithoutRepetition(int start, int end, int count) {
Random rng = new Random();
int[] result = new int[count];
int cur = 0;
int remaining = end - start;
for (int i = start; i < end && count > 0; i++) {
double probability = rng.nextDouble();
if (probability < ((double) count) / (double) remaining) {
count--;
result[cur++] = i;
}
remaining--;
}
return result;
}
Instead of JSONObject , you can use ObjectMapper to convert java object to json string
ObjectMapper mapper = new ObjectMapper();
String requestBean = mapper.writeValueAsString(yourObject);
Arrays
in Java have a defined size, you cannot change it later by adding or removing elements (you can read some basics here).
Instead, use a List
:
ArrayList<String> mylist = new ArrayList<String>();
mylist.add(mystring); //this adds an element to the list.
Of course, if you know beforehand how many strings you are going to put in your array, you can create an array of that size and set the elements by using the correct position:
String[] myarray = new String[numberofstrings];
myarray[23] = string24; //this sets the 24'th (first index is 0) element to string24.
In the XML file set the android:checkedButton
field in your RadioGroup
, with the id of your default RadioButton
:
<RadioGroup
....
android:checkedButton="@+id/button_1">
<RadioButton
android:id="@+id/button_1"
...../>
<RadioButton
android:id="@+id/button_2"
...../>
<RadioButton
android:id="@+id/button_3"
...../>
</RadioGroup>
If the cube is directly inside the container:
#container:hover > #cube { background-color: yellow; }
If cube is next to (after containers closing tag) the container:
#container:hover + #cube { background-color: yellow; }
If the cube is somewhere inside the container:
#container:hover #cube { background-color: yellow; }
If the cube is a sibling of the container:
#container:hover ~ #cube { background-color: yellow; }
yum -y install zlib-devel openssl-devel cpio expat-devel gettext-devel
Get the required version of GIT from https://www.kernel.org/pub/software/scm/git/
wget https://www.kernel.org/pub/software/scm/git/{version.gz}
tar -xzvf git-version.gz
cd git-version
./configure
make
make install
I usually expand each log out into it's own channel and then to a separate log file, certainly makes things easier when you are trying to debug specific issues. So my logging section looks like the following:
logging {
channel default_file {
file "/var/log/named/default.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel general_file {
file "/var/log/named/general.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel database_file {
file "/var/log/named/database.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel security_file {
file "/var/log/named/security.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel config_file {
file "/var/log/named/config.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel resolver_file {
file "/var/log/named/resolver.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel xfer-in_file {
file "/var/log/named/xfer-in.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel xfer-out_file {
file "/var/log/named/xfer-out.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel notify_file {
file "/var/log/named/notify.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel client_file {
file "/var/log/named/client.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel unmatched_file {
file "/var/log/named/unmatched.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel queries_file {
file "/var/log/named/queries.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel network_file {
file "/var/log/named/network.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel update_file {
file "/var/log/named/update.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel dispatch_file {
file "/var/log/named/dispatch.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel dnssec_file {
file "/var/log/named/dnssec.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
channel lame-servers_file {
file "/var/log/named/lame-servers.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
category default { default_file; };
category general { general_file; };
category database { database_file; };
category security { security_file; };
category config { config_file; };
category resolver { resolver_file; };
category xfer-in { xfer-in_file; };
category xfer-out { xfer-out_file; };
category notify { notify_file; };
category client { client_file; };
category unmatched { unmatched_file; };
category queries { queries_file; };
category network { network_file; };
category update { update_file; };
category dispatch { dispatch_file; };
category dnssec { dnssec_file; };
category lame-servers { lame-servers_file; };
};
Hope this helps.
Remove @ResponseBody annotation from your use parameters in method. Like this;
@Autowired
ProjectService projectService;
@RequestMapping(path = "/add", method = RequestMethod.POST)
public ResponseEntity<Project> createNewProject(Project newProject){
Project project = projectService.save(newProject);
return new ResponseEntity<Project>(project,HttpStatus.CREATED);
}
In such cases, you are better off re-adding the whitespace which makes the syntax error immediate apparent:
function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
document.getElementById("content").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","data/"+id+".html",true);xmlhttp.send();
}
There's a } too many. Also, after the closing } of the function, you should add a ; before the xmlhttp.open()
And finally, I don't see what that anonymous function does up there. It's never executed or referenced. Are you sure you pasted the correct code?
How to extract text from a PDF file?
The first thing to understand is the PDF format. It has a public specification written in English, see ISO 32000-2:2017 and read the more than 700 pages of PDF 1.7 specification. You certainly at least need to read the wikipedia page about PDF
Once you understood the details of the PDF format, extracting text is more or less easy (but what about text appearing in figures or images; its figure 1)? Don't expect writing a perfect software text extractor alone in a few weeks....
In general, extracting text from a PDF file is an ill defined problem. For a human reader some text could be made (as a figure) from different dots, or a photo, etc...
The Google search engine is capable of extracting text from PDF, but is rumored to need more than half a billion lines of source code. Do you have the necessary resources (in man power, in budget) to develop a competitor?
A possibility might be to print the PDF to some virtual printer (e.g. using GhostScript or Firefox), then to use OCR techniques to extract text.
I would recommend instead to work on the data representation which has generated that PDF file, for example on the original LaTeX code (or Lout code) or on OOXML code.
I think you've forgotten initialize your string "str": You need initialize the string before using strcat. And also you need that tmp were a string, not a single char. Try change this:
char str[1024]; // Only declares size
char tmp = '.';
for
char str[1024] = "Hello World"; //Now you have "Hello World" in str
char tmp[2] = ".";
You have a variable that is equal to None and you're attempting to access an attribute of it called 'something'.
foo = None
foo.something = 1
or
foo = None
print(foo.something)
Both will yield an AttributeError: 'NoneType'
in case you like to keep/need the image as a placeholder, you could change the opacity to 0 with an onerror and some CSS to set the image size. This way you will not see the broken link, but the page loads as normal.
<img src="<your-image-link->" onerror="this.style.opacity='0'" />
img {
width: 75px;
height: 100px;
}
The bold property of the font itself is read only, but the actual font property of the text box is not. You can change the font of the textbox to bold as follows:
textBox1.Font = new Font(textBox1.Font, FontStyle.Bold);
And then back again:
textBox1.Font = new Font(textBox1.Font, FontStyle.Regular);
Assuming you don't want to create another class, you can always let the deserializer give you a dictionary of key-value-pairs, like so:
string s = //{ "user" : { "id" : 12345, "screen_name" : "twitpicuser"}};
var serializer = new JavaScriptSerializer();
var result = serializer.DeserializeObject(s);
You'll get back something, where you can do:
var userId = int.Parse(result["user"]["id"]); // or (int)result["user"]["id"] depending on how the JSON is serialized.
// etc.
Look at result
in the debugger to see, what's in there.
A header (.h
, .hpp
, ...) file contains
class X { ... };
)inline int get_cpus() { ... }
)void help();
)extern int debug_enabled;
)A source file (.c
, .cpp
, .cxx
) contains
void help() { ... }
or void X::f() { ... }
)int debug_enabled = 1;
)However, the convention that headers are named with a .h
suffix and source files are named with a .cpp
suffix is not really required. One can always tell a good compiler how to treat some file, irrespective of its file-name suffix ( -x <file-type>
for gcc. Like -x c++
).
Source files will contain definitions that must be present only once in the whole program. So if you include a source file somewhere and then link the result of compilation of that file and then the one of the source file itself together, then of course you will get linker errors, because you have those definitions now appear twice: Once in the included source file, and then in the file that included it. That's why you had problems with including the .cpp
file.
Core dependencies for tag library:
> <dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
The key to debugging situations like these is to run the subquery/inline view on its' own to see what the output is:
SELECT TOP 1
dm.marker_value,
dum.profile_id
FROM DPS_USR_MARKERS dum (NOLOCK)
JOIN DPS_MARKERS dm (NOLOCK) ON dm.marker_id= dum.marker_id
AND dm.marker_key = 'moneyBackGuaranteeLength'
ORDER BY dm.creation_date
Running that, you would see that the profile_id
value didn't match the u.id
value of u162231993
, which would explain why any mbg
references would return null
(thanks to the left join; you wouldn't get anything if it were an inner join).
You've coded yourself into a corner using TOP
, because now you have to tweak the query if you want to run it for other users. A better approach would be:
SELECT u.id,
x.marker_value
FROM DPS_USER u
LEFT JOIN (SELECT dum.profile_id,
dm.marker_value,
dm.creation_date
FROM DPS_USR_MARKERS dum (NOLOCK)
JOIN DPS_MARKERS dm (NOLOCK) ON dm.marker_id= dum.marker_id
AND dm.marker_key = 'moneyBackGuaranteeLength'
) x ON x.profile_id = u.id
JOIN (SELECT dum.profile_id,
MAX(dm.creation_date) 'max_create_date'
FROM DPS_USR_MARKERS dum (NOLOCK)
JOIN DPS_MARKERS dm (NOLOCK) ON dm.marker_id= dum.marker_id
AND dm.marker_key = 'moneyBackGuaranteeLength'
GROUP BY dum.profile_id) y ON y.profile_id = x.profile_id
AND y.max_create_date = x.creation_date
WHERE u.id = 'u162231993'
With that, you can change the id
value in the where
clause to check records for any user in the system.
Use this command to trigger the notification center notification from the terminal.
osascript -e 'display notification "Lorem ipsum dolor sit amet" with title "Title"'
See the image for reference :- (Soruce :- Android Studio-Image Assets option and Android Office Site )
try this working fine
jQuery("body").load(window.location.href);
Open a new worksheet on the related instance (Alt-F10)
and run the following query
SELECT view_name, owner
FROM sys.all_views
ORDER BY owner, view_name
My case it solved i was using
@Html.DropDownList(model => model.TypeId ...)
using
@Html.DropDownListFor(model => model.TypeId ...)
will solve it
Can you use date as a factor?
Yes, but you probably shouldn't.
...or should you use
as.Date
on a date column?
Yes.
Which leads us to this:
library(scales)
df$Month <- as.Date(df$Month)
ggplot(df, aes(x = Month, y = AvgVisits)) +
geom_bar(stat = "identity") +
theme_bw() +
labs(x = "Month", y = "Average Visits per User") +
scale_x_date(labels = date_format("%m-%Y"))
in which I've added stat = "identity"
to your geom_bar
call.
In addition, the message about the binwidth wasn't an error. An error will actually say "Error" in it, and similarly a warning will always say "Warning" in it. Otherwise it's just a message.
If you want device ID information use TelephonyManager. Here is the link for that :
http://facinatingandroid.blogspot.in/2011/09/android-device-information.html
and also check this :
http://sree.cc/google/android/reading-phone-device-details-in-android
Yes, it is possible both in Sublime Text 2 and 3 (which you should really upgrade to if you haven't already). Select View ? Ruler ? 80
(there are several other options there as well). If you like to actually wrap your text at 80 columns, select View ? Word Wrap Column ? 80
. Make sure that View ? Word Wrap
is selected.
To make your selections permanent (the default for all opened files or views), open Preferences ? Settings—User
and use any of the following rules:
{
// set vertical rulers in specified columns.
// Use "rulers": [80] for just one ruler
// default value is []
"rulers": [80, 100, 120],
// turn on word wrap for source and text
// default value is "auto", which means off for source and on for text
"word_wrap": true,
// set word wrapping at this column
// default value is 0, meaning wrapping occurs at window width
"wrap_width": 80
}
These settings can also be used in a .sublime-project
file to set defaults on a per-project basis, or in a syntax-specific .sublime-settings
file if you only want them to apply to files written in a certain language (Python.sublime-settings
vs. JavaScript.sublime-settings
, for example). Access these settings files by opening a file with the desired syntax, then selecting Preferences ? Settings—More ? Syntax Specific—User
.
As always, if you have multiple entries in your settings file, separate them with commas ,
except for after the last one. The entire content should be enclosed in curly braces { }
. Basically, make sure it's valid JSON.
If you'd like a key combo to automatically set the ruler at 80 for a particular view/file, or you are interested in learning how to set the value without using the mouse, please see my answer here.
Finally, as mentioned in another answer, you really should be using a monospace font in order for your code to line up correctly. Other types of fonts have variable-width letters, which means one 80-character line may not appear to be the same length as another 80-character line with different content, and your indentations will look all messed up. Sublime has monospace fonts set by default, but you can of course choose any one you want. Personally, I really like Liberation Mono. It has glyphs to support many different languages and Unicode characters, looks good at a variety of different sizes, and (most importantly for a programming font) clearly differentiates between 0
and O
(digit zero and capital letter oh) and 1
and l
(digit one and lowercase letter ell), which not all monospace fonts do, unfortunately. Version 2.0 and later of the font are licensed under the open-source SIL Open Font License 1.1 (here is the FAQ).
While your solution should work, it can be difficult to read depending on the skill level of your fellow programmers. Additionally, it moves functionality away from the call site. Which can make maintenance a little more difficult.
I'm not sure if your goal is to get the keys into a vector or print them to cout so I'm doing both. You may try something like this:
std::map<int, int> m;
std::vector<int> key, value;
for(std::map<int,int>::iterator it = m.begin(); it != m.end(); ++it) {
key.push_back(it->first);
value.push_back(it->second);
std::cout << "Key: " << it->first << std::endl();
std::cout << "Value: " << it->second << std::endl();
}
Or even simpler, if you are using Boost:
map<int,int> m;
pair<int,int> me; // what a map<int, int> is made of
vector<int> v;
BOOST_FOREACH(me, m) {
v.push_back(me.first);
cout << me.first << "\n";
}
Personally, I like the BOOST_FOREACH version because there is less typing and it is very explicit about what it is doing.
For those who want a dumb down answer like me
Something like how to steps as 1, 2, 3
Here it is what I did
First create the HTML markup
<div class="thumb" data-image-src="images/img.jpg"></div>
Then before your ending body tag, add this script
I included the ending body on the code below as an example
So becareful when you copy
<script>
var list = document.getElementsByClassName('thumb');
for (var i = 0; i < list.length; i++) {
var src = list[i].getAttribute('data-image-src');
list[i].style.backgroundImage="url('" + src + "')";
}
</script>
</body>
git rev-parse --show-toplevel
could be enough if executed within a git repo.
From git rev-parse
man page:
--show-toplevel
Show the absolute path of the top-level directory.
For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":
git rev-parse --git-dir
That would give the path of the .git
directory.
The OP mentions:
git rev-parse --show-prefix
which returns the local path under the git repo root. (empty if you are at the git repo root)
Note: for simply checking if one is in a git repo, I find the following command quite expressive:
git rev-parse --is-inside-work-tree
And yes, if you need to check if you are in a .git
git-dir folder:
git rev-parse --is-inside-git-dir
There is no built-in way that I know of to do this so you will need to come up with a custom solution depending on how complicated your form is. You should read this post:
Convert HTML forms to read-only (Update: broken post link, archived link)
EDIT: Based on your update, why are you so worried about having it read-only? You can do it via client-side but if not you will have to add the required tag to each control or convert the data and display it as raw text with no controls. If you are trying to make it read-only so that the next post will be unmodified then you have a problem because anyone can mess with the post to produce whatever they want so when you do in fact finally receive the data you better be checking it again to make sure it is valid.
According to documentation class date
is a parent for class datetime
. And isinstance()
method will give you True
in all cases. If you need to distinguish datetime
from date
you should check name of the class
import datetime
datetime.datetime.now().__class__.__name__ == 'date' #False
datetime.datetime.now().__class__.__name__ == 'datetime' #True
datetime.date.today().__class__.__name__ == 'date' #True
datetime.date.today().__class__.__name__ == 'datetime' #False
I've faced with this problem when i have different formatting rules for dates and dates with time
You definitely need to put in the column order, otherwise how is SQL Server supposed to know which one goes first? Here's what you would need to do in your code:
public class MyTable
{
[Key, Column(Order = 0)]
public string SomeId { get; set; }
[Key, Column(Order = 1)]
public int OtherId { get; set; }
}
You can also look at this SO question. If you want official documentation, I would recommend looking at the official EF website. Hope this helps.
EDIT: I just found a blog post from Julie Lerman with links to all kinds of EF 6 goodness. You can find whatever you need here.
Couldn't add this as a comment, but in case anyone is interested in using the accepted answer with subplots, the divider should be formed on specific axes object (rather than on the numpy.ndarray returned from plt.subplots)
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots(ncols=2, nrows=2)
for row in ax:
for col in row:
im = col.imshow(data, cmap='bone')
divider = make_axes_locatable(col)
cax = divider.append_axes('right', size='5%', pad=0.05)
fig.colorbar(im, cax=cax, orientation='vertical')
plt.show()
Depending on what font you're using you can set max-width
on the paragraph with a calculated value. It will not be exact, but I've found that in most cases that does not matter.
p {
max-width: calc(30em * 0.5);
}
The number you multiply with depends on what font it is, and how much a character takes up in a em square. More characters = less accurate.
The horizontal scrollbar can appear if the container-fluid
div is placed directly inside the body
.
The correct way to use a container-fluid
structure is:
<body>
<section>
<div class="container-fluid">
<div class="row">
<!-- content goes here -->
</div>
</div>
</section>
</body>
So, try wrapping your container-fluid
DIVs inside an outer div, such as a <div id="wrap">
or a <section>
or <article>
or <aside>
or other specialized <div>
, and presto! no horizontal scrollbar.
Again in this issue also I found Instant Run buggy. When I disable the Instant run and run the app again App starts successfully installing in the Device without showing any error Window. I hope google will sort out these Issues with Instant run soon.
Steps to disable Instant Run from Android Studio:
File > Settings > Build,Execution,Deployment > Instant Run > Un-check (Enable Instant Run to hot swap code)
Try this one:
select * from MyTab T where date_add(T.runTime, INTERVAL 20 MINUTE) < NOW()
NOTE: this should work if you're using MySQL DateTime format. If you're using Unix Timestamp (integer), then it would be even easier:
select * from MyTab T where UNIX_TIMESTAMP() - T.runTime > 20*60
UNIX_TIMESTAMP() function returns you current unix timestamp.
The context object allows you to manipulate the canvas; you can draw rectangles for example and a lot more.
If you want to get the width and height, you can just use the standard HTML attributes width
and height
:
var canvas = document.getElementById( 'yourCanvasID' );
var ctx = canvas.getContext( '2d' );
alert( canvas.width );
alert( canvas.height );
In addition to the answer of Dyppl, I think it would be nice to place this inside the OnDataContextChanged
event:
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
// Unforunately we cannot bind from the viewmodel to the code behind so easily, the dependency property is not available in XAML. (for some reason).
// To work around this, we create the binding once we get the viewmodel through the datacontext.
var newViewModel = e.NewValue as MyViewModel;
var executablePathBinding = new Binding
{
Source = newViewModel,
Path = new PropertyPath(nameof(newViewModel.ExecutablePath))
};
BindingOperations.SetBinding(LayoutRoot, ExecutablePathProperty, executablePathBinding);
}
We have also had cases were we just saved the DataContext
to a local property and used that to access viewmodel properties. The choice is of course yours, I like this approach because it is more consistent with the rest. You can also add some validation, like null checks. If you actually change your DataContext
around, I think it would be nice to also call:
BindingOperations.ClearBinding(myText, TextBlock.TextProperty);
to clear the binding of the old viewmodel (e.oldValue
in the event handler).
If you are to use the
<!-- saved from url=(0014)about:internet -->
or
<!-- saved from url=(0016)http://localhost -->
make sure the HTML file is saved in windows/dos format with "\r\n" as line breaks after the statement. Otherwise I couldn't make it work.
I have not used Selenium 2. Selenium 1.x has selenium.getTable("tablename".columnNumber.rowNumber)
to reach the required cell. May be you can use webdriverbackedselenium
and do this.
And you can get the total rows and columns by using
int numOfRows = selenium.getXpathCount("//table[@id='tableid']//tr")
int numOfCols=selenium.getXpathCount("//table[@id='tableid']//tr//td")
Could your issue be linked to this other SO question "checkout problem"?
i.e.: a problem related to:
git checkout -b [<new_branch>] [<start_point>]
, with [<start_point>]
referring to the name of a commit at which to start the new branch, and 'origin/remote-name'
is not that.git branch
does support a start_point being the name of a remote branch)Note: what the checkout.sh script says is:
if test '' != "$newbranch$force$merge"
then
die "git checkout: updating paths is incompatible with switching branches/forcing$hint"
fi
It is like the syntax git checkout -b [] [remote_branch_name] was both renaming the branch and resetting the new starting point of the new branch, which is deemed incompatible.
Source: http://www.cyberciti.biz/faq/linux-unix-bsd-nginx-413-request-entity-too-large/
Edit the conf file of nginx:
nano /etc/nginx/nginx.conf
Add a line in the http section:
http {
client_max_body_size 100M;
}
Doen't use MB it will not work, only the M!
Also do not forget to restart nginx
systemctl restart nginx
You can actually a method called after()
in newer version of Chrome, Firefox and Opera. The downside of this method is that Internet Explorer doesn't support it yet.
Example:
// You could create a simple node
var node = document.createElement('p')
// And then get the node where you want to append the created node after
var existingNode = document.getElementById('id_of_the_element')
// Finally you can append the created node to the exisitingNode
existingNode.after(node)
A simple HTML Code to test that is:
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
<p id='up'>Up</p>_x000D_
<p id="down">Down</p>_x000D_
<button id="switchBtn" onclick="switch_place()">Switch place</button>_x000D_
<script>_x000D_
function switch_place(){_x000D_
var downElement = document.getElementById("down")_x000D_
var upElement = document.getElementById("up")_x000D_
downElement.after(upElement);_x000D_
document.getElementById('switchBtn').innerHTML = "Switched!"_x000D_
}_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
As expected, it moves the up element after the down element
How about something like:
SELECT mt.*
FROM MyTable mt INNER JOIN
(
SELECT id, MIN(record_date) AS MinDate
FROM MyTable
GROUP BY id
) t ON mt.id = t.id AND mt.record_date = t.MinDate
This gets the minimum date per ID, and then gets the values based on those values. The only time you would have duplicates is if there are duplicate minimum record_dates for the same ID.
You can also use momentjs for this sort of things. Momentjs is best at parse, validate, manipulate, and display dates in JavaScript.
I used this pipe from Urish, which works fine for me:
https://github.com/urish/angular2-moment/blob/master/src/DateFormatPipe.ts
In the args parameter you can put your date format like: "dd/mm/yyyy"
This error usually occurs if you have not included the xmlns:mm
properly, it occurs usually in the first line of code.
for me it was..
xmlns:mm="http://millennialmedia.com/android/schema"
that i missed in first line of the code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:mm="http://millennialmedia.com/android/schema"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_marginTop="50dp"
android:layout_marginBottom="50dp"
android:background="@android:color/transparent" >