The simplest way to do that is by opening the certificate store you want and then using X509Certificate2UI
.
var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
var selectedCertificate = X509Certificate2UI.SelectFromCollection(
store.Certificates,
"Title",
"MSG",
X509SelectionFlag.SingleSelection);
More information in X509Certificate2UI
on MSDN.
Here's a version with tail recursion and array destructuring.
Far from the fastest performance, but I'm just amused that js can do this now. Even if it isn't optimized for it :(
const getChunks = (arr, chunk_size, acc = []) => {
if (arr.length === 0) { return acc }
const [hd, tl] = [ arr.slice(0, chunk_size), arr.slice(chunk_size) ]
return getChunks(tl, chunk_size, acc.concat([hd]))
}
// USAGE
const my_arr = [1,2,3,4,5,6,7,8,9]
const chunks = getChunks(my_arr, 2)
console.log(chunks) // [[1,2],[3,4], [5,6], [7,8], [9]]
The best you can achieve with HTML only (documentation):
<input type="number" min="0" step="1"/>
_x000D_
Gutch's code is close, but it'll only work right if:
The Approved Method is to do it the other way around. Open the existing document with a PdfStamper, and use the returned PdfContentByte from getOverContent() to write text (and whatever else you might need) directly to the page. No second document needed.
And you can use a ColumnText to handle layout and such for you... no need to get down and dirty with beginText(),setFontAndSize(),drawText(),drawText()...,endText().
Maybe this post is too old but it may help as a suggestion for someone looking around on this : Instead of using:
print_r($this->pdo->errorInfo());
Use PHP implode() function:
echo 'Error occurred:'.implode(":",$this->pdo->errorInfo());
This should print the error code, detailed error information etc. that you would usually get if you were using some SQL User interface.
Hope it helps
I think the source of confusion is the distinction between a node's attribute and the corresponding property.
You're using:
$("a.button").parents("form").attr("onsubmit")
You're directly reading the onsubmit
attribute's value (which must be a string). Instead, you should access the onsubmit
property of the node:
$("a.button").parents("form").prop("onsubmit")
Here's a quick test:
<form id="form1" action="foo1.htm" onsubmit="return valid()"></form>
<script>
window.onload = function () {
var form1 = document.getElementById("form1");
function log(s) {
document.write("<div>" + s + "</div>");
}
function info(v) {
return "(" + typeof v + ") " + v;
}
log("form1 onsubmit property: " + info(form1.onsubmit));
log("form1 onsubmit attribute: " + info(form1.getAttribute("onsubmit")));
};
</script>
This yields:
form1 onsubmit property: (function) function onsubmit(event) { return valid(); } form1 onsubmit attribute: (string) return valid()
I had exactly the same problem and found the solution eventually. My query runs like:
$result = mysqli_query($link,'SELECT * FROM clients WHERE ' . $sql_where . ' AND ' . $sql_where2 . ' ORDER BY acconame ASC ');
In order to display the sql command, all I had to do was to create a variable ($resultstring) with the exact same content as my query and then echo it, like this:<?php echo $resultstring = 'SELECT * FROM clients WHERE ' . $sql_where . ' AND ' . $sql_where2 . ' ORDER BY acconame ASC '; ?>
It works!
You can not use strtotime
as your time format is not within the supported date and time formats of PHP.
Therefor, you have to create a valid date format first making use of createFromFormat function.
//creating a valid date format
$newDate = DateTime::createFromFormat('YmdHi', $longdate);
//formating the date as we want
$finalDate = $newDate->format('D');
For PHP code:
<?php
error_reporting(E_ALL & ~E_NOTICE);
For php.ini
config:
error_reporting = E_ALL & ~E_NOTICE
A great real-world example of where lazy loading comes in handy is with ORM's (Object Relation Mappers) such as Entity Framework and NHibernate.
Say you have an entity Customer which has properties for Name, PhoneNumber, and Orders. Name and PhoneNumber are regular strings but Orders is a navigation property that returns a list of every order the customer ever made.
You often might want to go through all your customer's and get their name and phone number to call them. This is a very quick and simple task, but imagine if each time you created a customer it automatically went and did a complex join to return thousands of orders. The worst part is that you aren't even going to use the orders so it is a complete waste of resources!
This is the perfect place for lazy loading because if the Order property is lazy it will not go fetch all the customer's order unless you actually need them. You can enumerate the Customer objects getting only their Name and Phone Number while the Order property is patiently sleeping, ready for when you need it.
You should try and avoid jQuery in ReactJS. But if you really want to use it, you'd put it in componentDidMount() lifecycle function of the component.
e.g.
class App extends React.Component {
componentDidMount() {
// Jquery here $(...)...
}
// ...
}
Ideally, you'd want to create a reusable Accordion component. For this you could use Jquery, or just use plain javascript + CSS.
class Accordion extends React.Component {
constructor() {
super();
this._handleClick = this._handleClick.bind(this);
}
componentDidMount() {
this._handleClick();
}
_handleClick() {
const acc = this._acc.children;
for (let i = 0; i < acc.length; i++) {
let a = acc[i];
a.onclick = () => a.classList.toggle("active");
}
}
render() {
return (
<div
ref={a => this._acc = a}
onClick={this._handleClick}>
{this.props.children}
</div>
)
}
}
Then you can use it in any component like so:
class App extends React.Component {
render() {
return (
<div>
<Accordion>
<div className="accor">
<div className="head">Head 1</div>
<div className="body"></div>
</div>
</Accordion>
</div>
);
}
}
Codepen link here: https://codepen.io/jzmmm/pen/JKLwEA?editors=0110 (I changed this link to https ^)
The quickest fix for me was doing the following:
cd /usr/local
git reset --hard FETCH_HEAD
Then I retried brew install imagemagick
and it correctly pulled the package from the new mirror, instead of adamv.
If that does not work, ensure that /Library/Caches/Homebrew
does not contain any imagemagick files or folders. Delete them if it does.
Nodejs supports async/await from version 7.6.
Release post: https://v8project.blogspot.com.br/2016/10/v8-release-55.html
Here's what I've been doing to cope with the situation.
I use global imports on a new test class.
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*;
When you are finished writing your test and need to commit, you just CTRL+SHIFT+O to organize the packages. For example, you may just be left with:
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.anyString;
This allows you to code away without getting 'stuck' trying to find the correct package to import.
You will have to assign both left
and right
property 0
value for margin: auto
to center the logo.
So in this case:
#logo {
background:red;
height:50px;
position:absolute;
width:50px;
left: 0;
right: 0;
margin: 0 auto;
}
You might also want to set position: relative
for #header
.
This works because, setting left
and right
to zero will horizontally stretch the absolutely positioned element. Now magic happens when margin
is set to auto
. margin
takes up all the extra space(equally on each side) leaving the content to its specified width
. This results in content becoming center aligned.
It's perfectly possible to template a class on an integer rather than a type. We can assign the templated value to a variable, or otherwise manipulate it in a way we might with any other integer literal:
unsigned int x = N;
In fact, we can create algorithms which evaluate at compile time (from Wikipedia):
template <int N>
struct Factorial
{
enum { value = N * Factorial<N - 1>::value };
};
template <>
struct Factorial<0>
{
enum { value = 1 };
};
// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
int x = Factorial<4>::value; // == 24
int y = Factorial<0>::value; // == 1
}
You can move your proxy authentication and ssl staff to soap handler
port = new SomeService().getServicePort();
Binding binding = ((BindingProvider) port).getBinding();
binding.setHandlerChain(Collections.<Handler>singletonList(new ProxyHandler()));
This is my example, do all network ops
class ProxyHandler implements SOAPHandler<SOAPMessageContext> {
static class TrustAllHost implements HostnameVerifier {
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
}
static class TrustAllCert implements X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
}
private SSLSocketFactory socketFactory;
public SSLSocketFactory getSocketFactory() throws Exception {
// just an example
if (socketFactory == null) {
SSLContext sc = SSLContext.getInstance("SSL");
TrustManager[] trustAllCerts = new TrustManager[] { new TrustAllCert() };
sc.init(null, trustAllCerts, new java.security.SecureRandom());
socketFactory = sc.getSocketFactory();
}
return socketFactory;
}
@Override public boolean handleMessage(SOAPMessageContext msgCtx) {
if (!Boolean.TRUE.equals(msgCtx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)))
return true;
HttpURLConnection http = null;
try {
SOAPMessage outMessage = msgCtx.getMessage();
outMessage.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "UTF-8");
// outMessage.setProperty(SOAPMessage.WRITE_XML_DECLARATION, true); // Not working. WTF?
ByteArrayOutputStream message = new ByteArrayOutputStream(2048);
message.write("<?xml version='1.0' encoding='UTF-8'?>".getBytes("UTF-8"));
outMessage.writeTo(message);
String endpoint = (String) msgCtx.get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY);
URL service = new URL(endpoint);
Proxy proxy = Proxy.NO_PROXY;
//Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("{proxy.url}", {proxy.port}));
http = (HttpURLConnection) service.openConnection(proxy);
http.setReadTimeout(60000); // set your timeout
http.setConnectTimeout(5000);
http.setUseCaches(false);
http.setDoInput(true);
http.setDoOutput(true);
http.setRequestMethod("POST");
http.setInstanceFollowRedirects(false);
if (http instanceof HttpsURLConnection) {
HttpsURLConnection https = (HttpsURLConnection) http;
https.setHostnameVerifier(new TrustAllHost());
https.setSSLSocketFactory(getSocketFactory());
}
http.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
http.setRequestProperty("Content-Length", Integer.toString(message.size()));
http.setRequestProperty("SOAPAction", "");
http.setRequestProperty("Host", service.getHost());
//http.setRequestProperty("Proxy-Authorization", "Basic {proxy_auth}");
InputStream in = null;
OutputStream out = null;
try {
out = http.getOutputStream();
message.writeTo(out);
} finally {
if (out != null) {
out.flush();
out.close();
}
}
int responseCode = http.getResponseCode();
MimeHeaders responseHeaders = new MimeHeaders();
message.reset();
try {
in = http.getInputStream();
IOUtils.copy(in, message);
} catch (final IOException e) {
try {
in = http.getErrorStream();
IOUtils.copy(in, message);
} catch (IOException e1) {
throw new RuntimeException("Unable to read error body", e);
}
} finally {
if (in != null)
in.close();
}
for (Map.Entry<String, List<String>> header : http.getHeaderFields().entrySet()) {
String name = header.getKey();
if (name != null)
for (String value : header.getValue())
responseHeaders.addHeader(name, value);
}
SOAPMessage inMessage = MessageFactory.newInstance()
.createMessage(responseHeaders, new ByteArrayInputStream(message.toByteArray()));
if (inMessage == null)
throw new RuntimeException("Unable to read server response code " + responseCode);
msgCtx.setMessage(inMessage);
return false;
} catch (Exception e) {
throw new RuntimeException("Proxy error", e);
} finally {
if (http != null)
http.disconnect();
}
}
@Override public boolean handleFault(SOAPMessageContext context) {
return false;
}
@Override public void close(MessageContext context) {
}
@Override public Set<QName> getHeaders() {
return Collections.emptySet();
}
}
It use UrlConnection, you can use any library you want in handler. Have fun!
This work for me on fresh install of mac osx (sierra):
sudo chown $(whoami) /etc/shells
sudo echo /usr/local/bin/fish >> /etc/shells
chsh -s /usr/local/bin/fish
sudo chown root /etc/shells
A tab is a tab. How many spaces it consumes is a display issue, and depends on the settings of your shell.
If you want to control the width of your data, then you could use the width
sub-specifiers in the printf
format string. Eg. :
printf("%5d", 2);
It's not a complete solution (if the value is longer than 5 characters, it will not be truncated), but might be ok for your needs.
If you want complete control, you'll probably have to implement it yourself.
You can use CSS property like this:
div {
display: inherit;
}
I hope this helps.
If you are using Spring
return new ResponseEntity<String>("your response", HttpStatus.ACCEPTED);
It works if id value and name value are different:
<input type="password" class="form-control"name="password" id="mainpassword">
password: { required: true, } ,
cpassword: {required: true, equalTo: '#mainpassword' },
I thinks it is vary helpful way.
models.py
from django.db import models
class User(models.Model):
user_name = models.CharField(max_length=100)
password = models.CharField(max_length=32)
forms.py
from django import forms
from Admin.models import *
class User_forms(forms.ModelForm):
class Meta:
model= User
fields=[
'user_name',
'password'
]
widgets = {
'password': forms.PasswordInput()
}
Cursor cursor = myDb.viewData();
if (cursor.moveToFirst()){
do {
String itemname=cursor.getString(cursor.getColumnIndex(myDb.col_2));
String price=cursor.getString(cursor.getColumnIndex(myDb.col_3));
String quantity=cursor.getString(cursor.getColumnIndex(myDb.col_4));
String table_no=cursor.getString(cursor.getColumnIndex(myDb.col_5));
}while (cursor.moveToNext());
}
cursor.requery();
Please! please! please! DO NOT serialize data and place it into your database. Serialize can be used that way, but that's missing the point of a relational database and the datatypes inherent in your database engine. Doing this makes data in your database non-portable, difficult to read, and can complicate queries. If you want your application to be portable to other languages, like let's say you find that you want to use Java for some portion of your app that it makes sense to use Java in, serialization will become a pain in the buttocks. You should always be able to query and modify data in the database without using a third party intermediary tool to manipulate data to be inserted.
it makes really difficult to maintain code, code with portability issues, and data that is it more difficult to migrate to other RDMS systems, new schema, etc. It also has the added disadvantage of making it messy to search your database based on one of the fields that you've serialized.
That's not to say serialize() is useless. It's not... A good place to use it may be a cache file that contains the result of a data intensive operation, for instance. There are tons of others... Just don't abuse serialize because the next guy who comes along will have a maintenance or migration nightmare.
A good example of serialize() and unserialize() could be like this:
$posts = base64_encode(serialize($_POST));
header("Location: $_SERVER[REQUEST_URI]?x=$posts");
Unserialize on the page
if($_GET['x']) {
// unpack serialize and encoded URL
$_POST = unserialize(base64_decode($_GET['x']));
}
For a pandas DataFrame whose index starts at 0 and increments by 1 (i.e., the default values) you can just do:
df.insert(0, 'New_ID', df.index + 880)
if you want New_ID
to be the first column. Otherwise this if you don't mind it being at the end:
df['New_ID'] = df.index + 880
Make sure you are using this org.json: https://mvnrepository.com/artifact/org.json/json
if you are using Java 8 then you can use
import org.json.JSONArray;
import org.json.JSONObject;
JSONArray array = ...;
array.forEach(item -> {
JSONObject obj = (JSONObject) item;
parse(obj);
});
Just added a simple test to prove that it works:
Add the following dependency into your pom.xml
file (To prove that it works, I have used the old jar which was there when I have posted this answer)
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
And the simple test code snippet will be:
import org.json.JSONArray;
import org.json.JSONObject;
public class Test {
public static void main(String args[]) {
JSONArray array = new JSONArray();
JSONObject object = new JSONObject();
object.put("key1", "value1");
array.put(object);
array.forEach(item -> {
System.out.println(item.toString());
});
}
}
output:
{"key1":"value1"}
Like has been mentioned already the progress field needs the keyword event
public event EventHandler<Progress> progress;
But I don't think that's where you actually want your event. I think you actually want the event in TestClass
. How does the following look? (I've never actually tried setting up static events so I'm not sure if the following will compile or not, but I think this gives you an idea of the pattern you should be aiming for.)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
TestClass.progress += SetStatus;
}
private void SetStatus(object sender, Progress e)
{
label1.Text = e.Status;
}
private void button1_Click_1(object sender, EventArgs e)
{
TestClass.Func();
}
}
public class TestClass
{
public static event EventHandler<Progress> progress;
public static void Func()
{
//time consuming code
OnProgress(new Progress("current status"));
// time consuming code
OnProgress(new Progress("some new status"));
}
private static void OnProgress(EventArgs e)
{
if (progress != null)
progress(this, e);
}
}
public class Progress : EventArgs
{
public string Status { get; private set; }
private Progress() {}
public Progress(string status)
{
Status = status;
}
}
For quick readers:
Don’t ever use the types Number, String, Boolean, Symbol, or Object These types refer to non-primitive boxed objects that are almost never used appropriately in JavaScript code.
source: https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html
If you are looking to create an instant messenger for Android, this code should get you started somewhere.
Excerpt from the source :
This is a simple IM application runs on Android, application makes http request to a server, implemented in php and mysql, to authenticate, to register and to get the other friends' status and data, then it communicates with other applications in other devices by socket interface.
EDIT : Just found this! Maybe it's not related to WhatsApp. But you can use the source to understand how chat applications are programmed.
There is a website called Scringo. These awesome people provide their own SDK which you can integrate in your existing application to exploit cool features like radaring, chatting, feedback, etc. So if you are looking to integrate chat in application, you could just use their SDK. And did I say the best part? It's free!
*UPDATE : * Scringo services will be closed down on 15 February, 2015.
Timmerman's solution works great when running the code, but if you don't want to get Undefined name
errors when using pyflakes or a similar linter you could use the following instead:
try:
import __builtin__
input = getattr(__builtin__, 'raw_input')
except (ImportError, AttributeError):
pass
See the page Set Up JDK in Eclipse. From the add button you can add a different version of the JDK...
Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.
The following res:
(resource) references need to point to your model.
<add name="Entities" connectionString="metadata=
res://*/Models.WraithNath.co.uk.csdl|
res://*/Models.WraithNath.co.uk.ssdl|
res://*/Models.WraithNath.co.uk.msl;
Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).
It also may help to specify the assembly rather than using "//*/".
Worst case, you can check everything (a bit slower but should always find the resource) by using
<add name="Entities" connectionString="metadata=
res://*/;provider= <!-- ... -->
In Pandas, I like to use the shape
attribute to get number of rows.
df[df.A > 0].shape[0]
gives the number of rows matching the condition A > 0
, as desired.
I use to just create it without parameters, and then edit the registry HKLM\System\CurrentControlSet\Services\[YourService]
.
This is an old thread, but I happened across it and I'm surprised nobody has put up a complete answer yet. So here goes...
Q: How do I execute this in Terminal?
Confusions and Conflicts:
sudo
to do any of this. This command is reserved for running commands as another user or a 'root' (administrator) user. Great post here.(A person who is just learning how to execute scripts should not be using this command unless there is a real need, like installing a new program. A good place to put your scripts is in your ~/bin folder. You can get there by typing cd ~/bin
or cd $HOME/bin
from the terminal prompt. You will have full permissions in that folder.)
To "execute this script" from the terminal on a Unix/Linux type system, you have to do three things:
Tell the system the location of the script. (pick one)
/path/to/script.sh
). You can verify the full path by typing pwd
or echo $PWD
in the terminal../
for the path (e.g. ./script.sh
). Easy.PATH
and just type the name (e.g. script.sh
). You can verify the system PATH
by typing echo $PATH
or echo -e ${PATH//:/\\n}
if you want a neater list.Tell the system that the script has permission to execute. (pick one)
chmod +x /path/to/script.sh
in the terminal.chmod 755 /path/to/script.sh
if you prefer numbers. There is a great discussion with a cool chart here.Tell the system the type of script. (pick one)
BASH /path/to/script.sh
or PHP /path/to/script.php
) If the script has an extension, such as .php or .py, it is part of the script name and you must include it.#!/bin/bash
) in your example. If you have that as the first line of your script, the system will use that program to execute the script. No need for typing programs or using extensions. PATH
by using #!/usr/bin/env
followed by the program name (e.g. #!/usr/bin/env bash
or #!/usr/bin/env python3
). There are pros and cons as thoroughly discussed here.Depending how you want to implement it (if there was a specific location you wanted the scripts) you could implement a @section
within your _Layout
which would enable you to add additional scripts from the view itself, while still retaining structure. e.g.
<!DOCTYPE html>
<html>
<head>
<title>...</title>
<script src="@Url.Content("~/Scripts/jquery.min.js")"></script>
@RenderSection("Scripts",false/*required*/)
</head>
<body>
@RenderBody()
</body>
</html>
@model MyNamespace.ViewModels.WhateverViewModel
@section Scripts
{
<script src="@Url.Content("~/Scripts/jqueryFoo.js")"></script>
}
Otherwise, what you have is fine. If you don't mind it being "inline" with the view that was output, you can place the <script>
declaration within the view.
I've been searching for an IMAP solution for a while now, and after trying quite a few, I'm going with AE.Net.Mail.
You can download the code by going to the Code tab and click the small 'Download' icon. As the author does not provide any pre-built downloads, you must compile it yourself. (I believe you can get it through NuGet though). There is no longer a .dll in the bin/ folder.
There is no documentation, which I consider a downside, but I was able to whip this up by looking at the source code (yay for open source!) and using Intellisense. The below code connects specifically to Gmail's IMAP server:
// Connect to the IMAP server. The 'true' parameter specifies to use SSL
// which is important (for Gmail at least)
ImapClient ic = new ImapClient("imap.gmail.com", "[email protected]", "pass",
ImapClient.AuthMethods.Login, 993, true);
// Select a mailbox. Case-insensitive
ic.SelectMailbox("INBOX");
Console.WriteLine(ic.GetMessageCount());
// Get the first *11* messages. 0 is the first message;
// and it also includes the 10th message, which is really the eleventh ;)
// MailMessage represents, well, a message in your mailbox
MailMessage[] mm = ic.GetMessages(0, 10);
foreach (MailMessage m in mm)
{
Console.WriteLine(m.Subject);
}
// Probably wiser to use a using statement
ic.Dispose();
Make sure you checkout the Github page for the newest version and some better code examples.
The manual page (or the online GNU manual) pretty much explains everything.
For each result, command {}
is executed. All occurences of {}
are replaced by the filename. ;
is prefixed with a slash to prevent the shell from interpreting it.
Each result is appended to command
and executed afterwards. Taking the command length limitations into account, I guess that this command may be executed more times, with the manual page supporting me:
the total number of invocations of the command will be much less than the number of matched files.
Note this quote from the manual page:
The command line is built in much the same way that xargs builds its command lines
That's why no characters are allowed between {}
and +
except for whitespace. +
makes find detect that the arguments should be appended to the command just like xargs
.
Luckily, the GNU implementation of mv
can accept the target directory as an argument, with either -t
or the longer parameter --target
. It's usage will be:
mv -t target file1 file2 ...
Your find
command becomes:
find . -type f -iname '*.cpp' -exec mv -t ./test/ {} \+
From the manual page:
-exec command ;
Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead.
-exec command {} +
This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command. The command is executed in the starting directory.
Using GNU sed
:
sed "/cdef/aline1\nline2\nline3\nline4" input.txt
If you started with:
abcd
accd
cdef
line
web
this would produce:
abcd
accd
cdef
line1
line2
line3
line4
line
web
If you want to save the changes to the file in-place, say:
sed -i "/cdef/aline1\nline2\nline3\nline4" input.txt
UPDATE: Please see Dylan's or d.c's anwer for a little easier (and more stable) solution, which does not rely on Chrome beeing installed in LocalAppData
!
Even if I agree with Daniel Hilgarth to open a new tab in chrome you just need to execute chrome.exe with your URL as the argument:
Process.Start(@"%AppData%\..\Local\Google\Chrome\Application\chrome.exe",
"http:\\www.YourUrl.com");
Try using second parameter for json_decode function:
$json = json_decode(file_get_contents($file), true);
They work equally well. Performance is about the same given a modern compiler.
I prefer if statements over case statements because they are more readable, and more flexible -- you can add other conditions not based on numeric equality, like " || max < min ". But for the simple case you posted here, it doesn't really matter, just do what's most readable to you.
try this
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
<url-pattern>*.css</url-pattern>
<url-pattern>*.ico</url-pattern>
<url-pattern>*.png</url-pattern>
<url-pattern>*.jpg</url-pattern>
<url-pattern>*.htc</url-pattern>
<url-pattern>*.gif</url-pattern>
</servlet-mapping>
Edit: This is only valid for the servlet 2.5 spec and up.
class Phone {
public Phone getMsg() {
System.out.println("phone...");
return new Phone();
}
}
class Samsung extends Phone{
@Override
public Samsung getMsg() {
System.out.println("samsung...");
return new Samsung();
}
public static void main(String[] args) {
Phone p=new Samsung();
p.getMsg();
}
}
Working jsbin: http://jsbin.com/ANAYeDU/4/edit
Main bit:
function answers()
{
var element = document.getElementById("mySelect");
var elementValue = element.value;
if(elementValue == "To measure time"){
alert("Thats correct");
}
}
You can use Named Sections.
_Layout.cshtml
<head>
<script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
@RenderSection("JavaScript", required: false)
</head>
_SomeView.cshtml
@section JavaScript
{
<script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
<script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}
Alternatively, you could invert the image using the bitwise_not
function of OpenCV:
imagem = cv2.bitwise_not(imagem)
I liked this example.
@SuppressWarnings("unchecked")
private static <T extends Object> T cast(Object obj) {
return (T) obj;
}
You have to make one ajax call to get the required result, in this case you can use Google API to get the same
http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true/false
Build this kind of url and replace the lat long with the one you want to. do the call and response will be in JSON, parse the JSON and you will get the complete address up to street level
If you want to retrieve last 10 records from sql use LIMIT. Suppose the data base contains 20 records.Use the below query
SELECT * FROM TABLE_NAME LIMIT 10,20;
where 10,20 is the offset value.Where 10 represent starting limit and 20 is the ending limit.
i.e 20 -10=10 records
import java.util.*;
import java.io.*;
public class Main {
public static void main(String arg[])throws IOException{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
StringTokenizer st;
String entrada = "";
long x=0, y=0;
while((entrada = br.readLine())!=null){
st = new StringTokenizer(entrada," ");
while(st.hasMoreTokens()){
x = Long.parseLong(st.nextToken());
y = Long.parseLong(st.nextToken());
}
System.out.println(x>y ?(x-y)+"":(y-x)+"");
}
}
}
This solution is a bit more efficient than the one above because it takes up the 2.128 and this takes 1.308 seconds to solve the problem.
try this
final TelephonyManager tm =(TelephonyManager)getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
String deviceid = tm.getDeviceId();
Simplest Answer is "No Direct method of getting it because there is no pre-compiler"
But you can do it by yourself. Use classes and then define variables as final so that it can be assumed as constant throughout the program
Don't forget to use final and variable as public or protected not private otherwise you won't be able to access it from outside that class
Based on the current wording in the original question, the simplest solution is:
Find the maximum value in the file, then add 1 to it.
Use Html helper
<?php echo $this->Html->url($this->here, true); ?>
It'll produce the full url which'll started from http or https
I found this to be extremely helpful in relation to the original question:
Return the value you wish to use in functionOne, then call functionOne within functionTwo, then place the result into a fresh var and reference this new var within functionTwo. This should enable you to use the var declared in functionOne, within functionTwo.
function functionOne() {
var variableThree = 3;
return variableThree;
}
function functionTwo() {
var variableOne = 1;
var var3 = functionOne();
var result = var3 - variableOne;
console.log(variableOne);
console.log(var3);
console.log('functional result: ' + result);
}
functionTwo();
I fixed this problem on CentOS by
I simplified your code to isolate the test for "%" being in the cell. Once you get that to work, you can add in the rest of your code.
Try this:
Option Explicit
Sub DoIHavePercentSymbol()
Dim rng As Range
Set rng = ActiveCell
Do While rng.Value <> Empty
If InStr(rng.Value, "%") = 0 Then
MsgBox "I know nothing about percentages!"
Set rng = rng.Offset(1)
rng.Select
Else
MsgBox "I contain a % symbol!"
Set rng = rng.Offset(1)
rng.Select
End If
Loop
End Sub
InStr
will return the number of times your search text appears in the string. I changed your if
test to check for no matches first.
The message boxes and the .Selects
are there simply for you to see what is happening while you are stepping through the code. Take them out once you get it working.
You did everything correctly!
You might also change the email configuration, depending on if the email server is also the same server. The email configuration is in gitlab.yml for the mails sent by GitLab and also the admin-email.
If you're not set on rolling your own solution, check out this jQuery plugin:
malsup.com/jquery/form/
It will do that and more for you. It's highly recommended.
Change your gradle version in project setting: If you are using mac,click File->Project structure,then change gradle version,here:
And check your build.gradle of project,change dependency of gradle,like this:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.0.1'
}
}
NOTE: Though this is possible, it is not at all recommended as it kind of destroys the reason for inheritance. The best way would be to restructure your application design so that there are NO parent to child dependencies. A parent should not ever need to know its children or their capabilities.
However.. you should be able to do it like:
void calculate(Person p) {
((Student)p).method();
}
a safe way would be:
void calculate(Person p) {
if(p instanceof Student) ((Student)p).method();
}
I would remove them. In my book, dead code like that should be considered errors because it makes you do a double-take and ask yourself "How would I ever execute that line?"
I'm fortunate and my large data sets are saved by the instrument in "chunks" (subsets) of roughly 100 MB (32bit binary). Thus I can do pre-processing steps (deleting uninformative parts, downsampling) sequentially before fusing the data set.
Calling gc ()
"by hand" can help if the size of the data get close to available memory.
Sometimes a different algorithm needs much less memory.
Sometimes there's a trade off between vectorization and memory use.
compare: split
& lapply
vs. a for
loop.
For the sake of fast & easy data analysis, I often work first with a small random subset (sample ()
) of the data. Once the data analysis script/.Rnw is finished data analysis code and the complete data go to the calculation server for over night / over weekend / ... calculation.
Well, since liquibase is open source there's always the source code which you could check.
Some of the data type classes seem to have a method toDatabaseDataType()
which should give you information about what type works (is used) on a specific data base.
The skinny is that a CPU loads data from memory addresses, stores data to memory addresses, and execute instructions sequentially out of memory addresses, with some conditional jumps in the sequence of instructions processed. Each of these three categories of instructions involves computing an address to a memory cell to be used in the machine instruction. Because machine instructions are of a variable length depending on the particular instruction involved, and because we string a variable length of them together as we build our machine code, there is a two step process involved in calculating and building any addresses.
First we laying out the allocation of memory as best we can before we can know what exactly goes in each cell. We figure out the bytes, or words, or whatever that form the instructions and literals and any data. We just start allocating memory and building the values that will create the program as we go, and note down anyplace we need to go back and fix an address. In that place we put a dummy to just pad the location so we can continue to calculate memory size. For example our first machine code might take one cell. The next machine code might take 3 cells, involving one machine code cell and two address cells. Now our address pointer is 4. We know what goes in the machine cell, which is the op code, but we have to wait to calculate what goes in the address cells till we know where that data will be located, i.e. what will be the machine address of that data.
If there were just one source file a compiler could theoretically produce fully executable machine code without a linker. In a two pass process it could calculate all of the actual addresses to all of the data cells referenced by any machine load or store instructions. And it could calculate all of the absolute addresses referenced by any absolute jump instructions. This is how simpler compilers, like the one in Forth work, with no linker.
A linker is something that allows blocks of code to be compiled separately. This can speed up the overall process of building code, and allows some flexibility with how the blocks are later used, in other words they can be relocated in memory, for example adding 1000 to every address to scoot the block up by 1000 address cells.
So what the compiler outputs is rough machine code that is not yet fully built, but is laid out so we know the size of everything, in other words so we can start to calculate where all of the absolute addresses will be located. the compiler also outputs a list of symbols which are name/address pairs. The symbols relate a memory offset in the machine code in the module with a name. The offset being the absolute distance to the memory location of the symbol in the module.
That's where we get to the linker. The linker first slaps all of these blocks of machine code together end to end and notes down where each one starts. Then it calculates the addresses to be fixed by adding together the relative offset within a module and the absolute position of the module in the bigger layout.
Obviously I've oversimplified this so you can try to grasp it, and I have deliberately not used the jargon of object files, symbol tables, etc. which to me is part of the confusion.
you can do this without jQuery:
var form=document.getElementById('form-id');//retrieve the form as a DOM element
var input = document.createElement('input');//prepare a new input DOM element
input.setAttribute('name', inputName);//set the param name
input.setAttribute('value', inputValue);//set the value
input.setAttribute('type', inputType)//set the type, like "hidden" or other
form.appendChild(input);//append the input to the form
form.submit();//send with added input
Here is a recursive function to set the innerHTML of an element that I use in our ad server:
// o: container to set the innerHTML
// html: html text to set.
// clear: if true, the container is cleared first (children removed)
function setHTML(o, html, clear) {
if (clear) o.innerHTML = "";
// Generate a parseable object with the html:
var dv = document.createElement("div");
dv.innerHTML = html;
// Handle edge case where innerHTML contains no tags, just text:
if (dv.children.length===0){ o.innerHTML = html; return; }
for (var i = 0; i < dv.children.length; i++) {
var c = dv.children[i];
// n: new node with the same type as c
var n = document.createElement(c.nodeName);
// copy all attributes from c to n
for (var j = 0; j < c.attributes.length; j++)
n.setAttribute(c.attributes[j].nodeName, c.attributes[j].nodeValue);
// If current node is a leaf, just copy the appropriate property (text or innerHTML)
if (c.children.length == 0)
{
switch (c.nodeName)
{
case "SCRIPT":
if (c.text) n.text = c.text;
break;
default:
if (c.innerHTML) n.innerHTML = c.innerHTML;
break;
}
}
// If current node has sub nodes, call itself recursively:
else setHTML(n, c.innerHTML, false);
o.appendChild(n);
}
}
You can see the demo here.
In Swift 4 I tried all of this previously, but runs only:
@IBAction func myButton(sender: AnyObject) {
sender.setTitle("This is example text one", for:[])
sender.setTitle("This is example text two", for: .normal)
}
Ok I finally got this code working:
<html>
<head>
<title>Demo - Covnert JSON to CSV</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="https://github.com/douglascrockford/JSON-js/raw/master/json2.js"></script>
<script type="text/javascript">
// JSON to CSV Converter
function ConvertToCSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += ','
line += array[i][index];
}
str += line + '\r\n';
}
return str;
}
// Example
$(document).ready(function () {
// Create Object
var items = [
{ name: "Item 1", color: "Green", size: "X-Large" },
{ name: "Item 2", color: "Green", size: "X-Large" },
{ name: "Item 3", color: "Green", size: "X-Large" }];
// Convert Object to JSON
var jsonObject = JSON.stringify(items);
// Display JSON
$('#json').text(jsonObject);
// Convert JSON to CSV & Display CSV
$('#csv').text(ConvertToCSV(jsonObject));
});
</script>
</head>
<body>
<h1>
JSON</h1>
<pre id="json"></pre>
<h1>
CSV</h1>
<pre id="csv"></pre>
</body>
</html>
Thanks alot for all the support to all the contributors.
Praney
Ah-ha! The Lodash Changelog says it all...
"Removed _.pluck
in favor of _.map
with iteratee shorthand"
var objects = [{ 'a': 1 }, { 'a': 2 }];
// in 3.10.1
_.pluck(objects, 'a'); // ? [1, 2]
_.map(objects, 'a'); // ? [1, 2]
// in 4.0.0
_.map(objects, 'a'); // ? [1, 2]
For me this worked:
<TextBlock Text="{Binding Date , StringFormat=g}" Width="130"/>
If want to show seconds also using G instead of g :
<TextBlock Text="{Binding Date , StringFormat=G}" Width="130"/>
Also if want for changing date type to another like Persian , using Language :
<TextBlock Text="{Binding Date , StringFormat=G}" Width="130" Language="fa-IR"/>
NOTE:
The correct answer is correct in that it prevents you from being able to select the text. However, it does not prevent you from being able to copy the text, as I'll show with the next couple of screenshots (as of 7th Nov 2014).
As you can see, we were unable to select the numbers, but we were able to copy them.
Tested on: Ubuntu, Google Chrome 38.0.2125.111.
Here is an example for all six boolean comparison operators (<, ==, >, >=, !=, <=):
BigDecimal big10 = new BigDecimal(10);
BigDecimal big20 = new BigDecimal(20);
System.out.println(big10.compareTo(big20) < -1); // false
System.out.println(big10.compareTo(big20) <= -1); // true
System.out.println(big10.compareTo(big20) == -1); // true
System.out.println(big10.compareTo(big20) >= -1); // true
System.out.println(big10.compareTo(big20) > -1); // false
System.out.println(big10.compareTo(big20) != -1); // false
System.out.println(big10.compareTo(big20) < 0); // true
System.out.println(big10.compareTo(big20) <= 0); // true
System.out.println(big10.compareTo(big20) == 0); // false
System.out.println(big10.compareTo(big20) >= 0); // false
System.out.println(big10.compareTo(big20) > 0); // false
System.out.println(big10.compareTo(big20) != 0); // true
System.out.println(big10.compareTo(big20) < 1); // true
System.out.println(big10.compareTo(big20) <= 1); // true
System.out.println(big10.compareTo(big20) == 1); // false
System.out.println(big10.compareTo(big20) >= 1); // false
System.out.println(big10.compareTo(big20) > 1); // false
System.out.println(big10.compareTo(big20) != 1); // true
below link will open the whatsapp. Here "0123456789" is the contact of the person you want to communicate with.
href="intent://send/0123456789#Intent;scheme=smsto;package=com.whatsapp;action=android.intent.action.SENDTO;end">
Controller :
public ActionResult Refresh(string ID)
{
DetailsViewModel vm = new DetailsViewModel(); // Model
vm.productDetails = _product.GetproductDetails(ID);
/* "productDetails " is a property in "DetailsViewModel"
"GetProductDetails" is a method in "Product" class
"_product" is an interface of "Product" class */
return PartialView("_Details", vm); // Details is a partial view
}
In yore index page you should to have refresh link :
<a href="#" id="refreshItem">Refresh</a>
This Script should be also in your index page:
<script type="text/javascript">
$(function () {
$('a[id=refreshItem]:last').click(function (e) {
e.preventDefault();
var url = MVC.Url.action('Refresh', 'MyController', { itemId: '@(Model.itemProp.itemId )' }); // Refresh is an Action in controller, MyController is a controller name
$.ajax({
type: 'GET',
url: url,
cache: false,
success: function (grid) {
$('#tabItemDetails').html(grid);
clientBehaviors.applyPlugins($("#tabProductDetails")); // "tabProductDetails" is an id of div in your "Details partial view"
}
});
});
});
For anyone who is looking for a solution to this problem in GitBook. This is how I made it work (in GitBook). You need to tag your header explicitly, like this:
# My Anchored Heading {#my-anchor}
Then link to this anchor like this
[link to my anchored heading](#my-anchor)
Solution, and additional examples, may be found here: https://seadude.gitbooks.io/learn-gitbook/
If your app uses CoreData, a nifty trick is to search for the name of the sqlite file using terminal.
find ~ -name my_app_db_name.sqlite
The results will list the full file paths to any simulators that have run your app.
I really wish Apple would just add a button to the iOS Simulator file menu like "Reveal Documents folder in Finder".
I use this:
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
public class IconImageUtilities
{
public static void setIconImage(Window window)
{
try
{
InputStream imageInputStream = window.getClass().getResourceAsStream("/Icon.png");
BufferedImage bufferedImage = ImageIO.read(imageInputStream);
window.setIconImage(bufferedImage);
} catch (IOException exception)
{
exception.printStackTrace();
}
}
}
Just place your image called Icon.png
in the resources folder and call the above method with itself as parameter inside a class extending a class from the Window
family such as JFrame
or JDialog
:
IconImageUtilities.setIconImage(this);
I think this will help you... Creating Threads and Passing Data at Start Time!
Imports System.Threading
' The ThreadWithState class contains the information needed for
' a task, and the method that executes the task.
Public Class ThreadWithState
' State information used in the task.
Private boilerplate As String
Private value As Integer
' The constructor obtains the state information.
Public Sub New(text As String, number As Integer)
boilerplate = text
value = number
End Sub
' The thread procedure performs the task, such as formatting
' and printing a document.
Public Sub ThreadProc()
Console.WriteLine(boilerplate, value)
End Sub
End Class
' Entry point for the example.
'
Public Class Example
Public Shared Sub Main()
' Supply the state information required by the task.
Dim tws As New ThreadWithState( _
"This report displays the number {0}.", 42)
' Create a thread to execute the task, and then
' start the thread.
Dim t As New Thread(New ThreadStart(AddressOf tws.ThreadProc))
t.Start()
Console.WriteLine("Main thread does some work, then waits.")
t.Join()
Console.WriteLine( _
"Independent task has completed main thread ends.")
End Sub
End Class
' The example displays the following output:
' Main thread does some work, then waits.
' This report displays the number 42.
' Independent task has completed; main thread ends.
I had this error after creating an empty ASP.Net application in Visual Studio. As soon as I added a file index.html to the main solution, it worked. So in my case, I just needed to add a file to the root of the project folder.
Use this: http://winginx.com/htaccess
Online converter, nice way and time saver ;)
The following example demonstrates how to POST a JSON via WebClient.UploadString Method:
var vm = new { k = "1", a = "2", c = "3", v= "4" };
using (var client = new WebClient())
{
var dataString = JsonConvert.SerializeObject(vm);
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
client.UploadString(new Uri("http://www.contoso.com/1.0/service/action"), "POST", dataString);
}
Prerequisites: Json.NET library
In Notepad++, use replace all with regular expression. This has advantage over conversion command in menu that you can operate on entire folder w/o having to open each file or drag n drop (on several hundred files it will noticeably become slower) plus you can also set filename wildcard filter.
(\r?\n)|(\r\n?)
to
\n
This will match every possible line ending pattern (single \r, \n or \r\n) back to \n. (Or \r\n if you are converting to windows-style)
To operate on multiple files, either:
import inspect
def my_first_function():
func_name = inspect.stack()[0][3]
print(func_name) # my_first_function
or:
import sys
def my_second_function():
func_name = sys._getframe().f_code.co_name
print(func_name) # my_second_function
I normally set paths in
~/.bashrc
However for Java, I followed instructions at https://askubuntu.com/questions/55848/how-do-i-install-oracle-java-jdk-7
and it was sufficient for me.
you can also define multiple java_home's and have only one of them active (rest commented).
suppose in your bashrc file, you have
export JAVA_HOME=......jdk1.7
#export JAVA_HOME=......jdk1.8
notice 1.8 is commented. Once you do
source ~/.bashrc
jdk1.7 will be in path.
you can switch them fairly easily this way. There are other more permanent solutions too. The link I posted has that info.
Either do it with CSS like the other answers did or change the text style color directly via the onMouseOver and onMouseOut event:
onmouseover="this.bgColor='white'; this.style.color='black'"
onmouseout="this.bgColor='black'; this.style.color='white'"
Dont know, but you could perhaps check the source of one of the Firefox download addons.
Here is the source for one that I use Download Statusbar.
Intel has a peach of an article on this. It's all the same driver. It's just a Device ID mismatch in the Inf file which can be edited, or Windows forced to Install the driver we point it to. Intel's article is very thorough and takes care of every hurdle you come across. The link - https://software.intel.com/en-us/xdk/docs/installing-android-debug-bridge-adb-usb-driver-on-windows
As of late 2018, there is now limited customization available in Firefox!
See these answers:
And this for background info: https://bugzilla.mozilla.org/show_bug.cgi?id=1460109
There's no Firefox equivalent to ::-webkit-scrollbar
and friends.
You'll have to stick with JavaScript.
Plenty of people would like this feature, see: https://bugzilla.mozilla.org/show_bug.cgi?id=77790
As far as JavaScript replacements go, you can try:
As for me, using VSCode and Angular 5, only had to add "node" to types in tsconfig.app.json. Save, and restart the server.
{_x000D_
"compilerOptions": {_x000D_
.._x000D_
"types": [_x000D_
"node"_x000D_
]_x000D_
}_x000D_
.._x000D_
}
_x000D_
One curious thing, is that this problem "cannot find require (", does not happen when excuting with ts-node
SELECT variant (not creating a user defined function):
SELECT IF(
LOCATE(' ', `membername`) > 0,
SUBSTRING(`membername`, 1, LOCATE(' ', `membername`) - 1),
`membername`
) AS memberfirst,
IF(
LOCATE(' ', `membername`) > 0,
SUBSTRING(`membername`, LOCATE(' ', `membername`) + 1),
NULL
) AS memberlast
FROM `user`;
This approach also takes care of:
The UPDATE version would be:
UPDATE `user` SET
`memberfirst` = IF(
LOCATE(' ', `membername`) > 0,
SUBSTRING(`membername`, 1, LOCATE(' ', `membername`) - 1),
`membername`
),
`memberlast` = IF(
LOCATE(' ', `membername`) > 0,
SUBSTRING(`membername`, LOCATE(' ', `membername`) + 1),
NULL
);
Internet Explorer provides a resizeEnd event. Other browsers will trigger the resize event many times while you're resizing.
There are other great answers here that show how to use setTimeout and the .throttle, .debounce methods from lodash and underscore, so I will mention Ben Alman's throttle-debounce jQuery plugin which accomplishes what you're after.
Suppose you have this function that you want to trigger after a resize:
function onResize() {
console.log("Resize just happened!");
};
Throttle Example
In the following example, onResize()
will only be called once every 250 milliseconds during a window resize.
$(window).resize( $.throttle( 250, onResize) );
Debounce Example
In the following example, onResize()
will only be called once at the end of a window resizing action. This achieves the same result that @Mark presents in his answer.
$(window).resize( $.debounce( 250, onResize) );
This can also be done using Hadley's plyr
package, and the rename
function.
library(plyr)
df <- data.frame(foo=rnorm(1000))
df <- rename(df,c('foo'='samples'))
You can rename by the name (without knowing the position) and perform multiple renames at once. After doing a merge, for example, you might end up with:
letterid id.x id.y
1 70 2 1
2 116 6 5
3 116 6 4
4 116 6 3
5 766 14 9
6 766 14 13
Which you can then rename in one step using:
letters <- rename(letters,c("id.x" = "source", "id.y" = "target"))
letterid source target
1 70 2 1
2 116 6 5
3 116 6 4
4 116 6 3
5 766 14 9
6 766 14 13
/*****************************************************************************
* return application path
* @return
*****************************************************************************/
public static String getApplcatonPath(){
CodeSource codeSource = MainApp.class.getProtectionDomain().getCodeSource();
File rootPath = null;
try {
rootPath = new File(codeSource.getLocation().toURI().getPath());
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rootPath.getParentFile().getPath();
}//end of getApplcatonPath()
I had the same problem, and found a nice solution here: http://blog.e-shell.org/134
This is caused by a mismatch in your database encodings, surely because the database from where you got the SQL dump was encoded as SQL_ASCII while the new one is encoded as UTF8. .. Recode is a small tool from the GNU project that let you change on-the-fly the encoding of a given file.
So I just recoded the dumpfile before playing it back:
postgres> gunzip -c /var/backups/pgall_b1.zip | recode iso-8859-1..u8 | psql test
In Debian or Ubuntu systems, recode can be installed via package.
Following the @greg0ire suggestion in comments:
<input type="submit" name="add_tag" value="Lägg till tag" />
In your server side, you'll do something like:
if (request.getParameter("add_tag") != null)
tags.addTag( /*...*/ );
(Since I don't know that language (java?), there may be syntax errors.)
I would prefer the <button>
solution, but it doesn't work as expected on IE < 9.
No, nothing like that exists. The extension method is the way to go, and your name for it (GetValueOrDefault) is a pretty good choice.
First installing the framework globally on the system solved my problem.
machine@debian:/$ sudo pip install djangorestframework
or;
root@debian:/# pip install djangorestframework
I don't think there's a native trim()
method in the JavaScript standard. Maybe Mozilla supplies one, but if you want one in IE, you'll need to write it yourself. There are a few versions on this page.
Variables in single-quotes are not evaluated. Use double quotes:
ssh [email protected] "~/tools/run_pvt.pl $BUILD_NUMBER"
The shell will expand variables in double-quotes, but not in single-quotes. This will change into your desired string before being passed to the ssh
command.
Just use var-args and write your own static method:
public static boolean compareWithMany(String first, String next, String ... rest)
{
if(first.equalsIgnoreCase(next))
return true;
for(int i = 0; i < rest.length; i++)
{
if(first.equalsIgnoreCase(rest[i]))
return true;
}
return false;
}
public static void main(String[] args)
{
final String str = "val1";
System.out.println(compareWithMany(str, "val1", "val2", "val3"));
}
Unfortunately .mov files are not supported with html5 video playback. You can see what filetypes are supported here:
https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats
If you need to be able to play these formats with your html5 video player, you'll need to first convert your videofile--perhaps with something like this:
The other features of CodeLens like: Show Bugs, Show Test Status, etc (other than Show Reference) might be useful.
However, if the only way to disable Show References is to disable CodeLens altogether.
Then, I guess I could do just that.
Furthermore, I would do like I always have, 'right-click on a member and choose Find all References or Ctrl+K, R'
If I wanted to know what references the member -- I too like not having any extra information crammed into my code, like extra white-space.
In short, uncheck Codelens...
The bash script "corstest" below works for me. It is based on Jun's comment above.
usage
corstest [-v] url
examples
./corstest https://api.coindesk.com/v1/bpi/currentprice.json
https://api.coindesk.com/v1/bpi/currentprice.json Access-Control-Allow-Origin: *
the positive result is displayed in green
./corstest https://github.com/IonicaBizau/jsonrequest
https://github.com/IonicaBizau/jsonrequest does not support CORS
you might want to visit https://enable-cors.org/ to find out how to enable CORS
the negative result is displayed in red and blue
the -v option will show the full curl headers
corstest
#!/bin/bash
# WF 2018-09-20
# https://stackoverflow.com/a/47609921/1497139
#ansi colors
#http://www.csc.uvic.ca/~sae/seng265/fall04/tips/s265s047-tips/bash-using-colors.html
blue='\033[0;34m'
red='\033[0;31m'
green='\033[0;32m' # '\e[1;32m' is too bright for white bg.
endColor='\033[0m'
#
# a colored message
# params:
# 1: l_color - the color of the message
# 2: l_msg - the message to display
#
color_msg() {
local l_color="$1"
local l_msg="$2"
echo -e "${l_color}$l_msg${endColor}"
}
#
# show the usage
#
usage() {
echo "usage: [-v] $0 url"
echo " -v |--verbose: show curl result"
exit 1
}
if [ $# -lt 1 ]
then
usage
fi
# commandline option
while [ "$1" != "" ]
do
url=$1
shift
# optionally show usage
case $url in
-v|--verbose)
verbose=true;
;;
esac
done
if [ "$verbose" = "true" ]
then
curl -s -X GET $url -H 'Cache-Control: no-cache' --head
fi
origin=$(curl -s -X GET $url -H 'Cache-Control: no-cache' --head | grep -i access-control)
if [ $? -eq 0 ]
then
color_msg $green "$url $origin"
else
color_msg $red "$url does not support CORS"
color_msg $blue "you might want to visit https://enable-cors.org/ to find out how to enable CORS"
fi
The following also worked for me. ISO 8859-1 is going to save a lot, hahaha - mainly if using Speech Recognition APIs.
Example:
file = open('../Resources/' + filename, 'r', encoding="ISO-8859-1");
i have updated both fiddles. i hope it will make your work done.
html, body
{
height: 100%;
width: 100%;
}
body
{
margin: 0;
}
.outer
{
width: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.inner
{
width: 80%;
margin: 0 auto;
}
html, body
{
height: 100%;
width: 100%;
}
body
{
margin: 0;
display:flex;
}
.outer
{
min-width: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.inner
{
width: 80%;
margin-top:40px;
margin: 0 auto;
}
On Linux/unix/MacOSX use core files (you can enable them with ulimit or compatible system call). On Windows use Microsoft error reporting (you can become a partner and get access to your application crash data).
Add padding. Padding the element will increase the space between its content and its border. However, note that a box-shadow will begin outside the border, not the content, meaning you can't put space between the shadow and the box. Alternatively you could use :before or :after pseudo selectors on the element to create a slightly bigger box that you place the shadow on, like so: http://jsbin.com/aqemew/edit#source
Visibility is an animatable property according to the spec, but transitions on visibility do not work gradually, as one might expect. Instead transitions on visibility delay hiding an element. On the other hand making an element visible works immediately. This is as it is defined by the spec (in the case of the default timing function) and as it is implemented in the browsers.
This also is a useful behavior, since in fact one can imagine various visual effects to hide an element. Fading out an element is just one kind of visual effect that is specified using opacity. Other visual effects might move away the element using e.g. the transform property, also see http://taccgl.org/blog/css-transition-visibility.html
It is often useful to combine the opacity transition with a visibility transition! Although opacity appears to do the right thing, fully transparent elements (with opacity:0) still receive mouse events. So e.g. links on an element that was faded out with an opacity transition alone, still respond to clicks (although not visible) and links behind the faded element do not work (although being visible through the faded element). See http://taccgl.org/blog/css-transition-opacity-for-fade-effects.html.
This strange behavior can be avoided by just using both transitions, the transition on visibility and the transition on opacity. Thereby the visibility property is used to disable mouse events for the element while opacity is used for the visual effect. However care must be taken not to hide the element while the visual effect is playing, which would otherwise not be visible. Here the special semantics of the visibility transition becomes handy. When hiding an element the element stays visible while playing the visual effect and is hidden afterwards. On the other hand when revealing an element, the visibility transition makes the element visible immediately, i.e. before playing the visual effect.
All of the above answers are correct. :) I myself used one of these for my situation. However when I read the question I found that the OP is actually talking about a different scenario than the title of this post, if I didn't get it wrong.
"I need the array to stick around even if the user leaves the activity and then wants to come back at a later time"
He actually wants the data to be stored till the app is open, irrespective of user changing screens within the application.
"however I don't need the array available after the application has been closed completely"
But once the application is closed data should not be preserved.Hence I feel using SharedPreferences
is not the optimal way for this.
What one can do for this requirement is create a class which extends Application
class.
public class MyApp extends Application {
//Pardon me for using global ;)
private ArrayList<CustomObject> globalArray;
public void setGlobalArrayOfCustomObjects(ArrayList<CustomObject> newArray){
globalArray = newArray;
}
public ArrayList<CustomObject> getGlobalArrayOfCustomObjects(){
return globalArray;
}
}
Using the setter and getter the ArrayList can be accessed from anywhere withing the Application. And the best part is once the app is closed, we do not have to worry about the data being stored. :)
Looks like the answers above are for when you are writing and compiling a program, but I'm using a Vendor's software, Catalog.exe
, part of the Voyager
card catalog by "Ex Libris" and I'm getting the error as well:
catalog-error.png http://img805.imageshack.us/img805/8275/catalogerror.png
I have two Windows 7 32-bit machines. The newer one is giving me the error but on the older one it runs fine. I have done a lot of research with Google and here are some of the things I've found that people are saying related to this issue. Maybe one of these things will help fix the error for you, although they didn't work for me:
Run-Time Error 380
(try updating)sfc /scannow
Run as Administrator
)From what others are saying (like David M) I think it could be related to the MSVBM60.DLL
library - but it appears that on both of my computers this file is the exact same (same version, size, date, etc).
Since that file wasn't different I tried to find what other (dll) files the application could be using, so I launched Process Explorer by Sysinternals and took a look at the application (it loads and then crashes when you tell it to "connect"), and the screenshots below are what I found.
screen1.png http://img195.imageshack.us/img195/2231/screen1oo.png
screen2.png http://img88.imageshack.us/img88/2153/screen2ao.png
Now, I'm not a Windows / VB programmer, just a power user, and so I'm about at the end of my knowledge for what to do. I've talked to the software vendor and they recommend reinstalling Windows. That will probably work, but it just bugs me that this program can run on Windows 7, but something on this particular system is causing errors. Finally, this is an image that has been deployed on multiple machines already and so while re-installing Windows once is not a big deal it would save me some serious time if I could figure out a fix or workaround.
I've recently found that blanks in the name of the redirect file will cause the "ambiguous redirect" message.
For example if you redirect to application$(date +%Y%m%d%k%M%S).log
and you specify the wrong formatting characters, the redirect will fail before 10 AM for example. If however, you used application$(date +%Y%m%d%H%M%S).log
it would succeed. This is because the %k
format yields ' 9'
for 9AM where %H
yields '09'
for 9AM.
echo $(date +%Y%m%d%k%M%S)
gives 20140626 95138
echo $(date +%Y%m%d%H%M%S)
gives 20140626095138
The erroneous date might give something like:
echo "a" > myapp20140626 95138.log
where the following is what would be desired:
echo "a" > myapp20140626095138.log
Old question, and the posted answers work great. I'll chime in with another option though.
git reset ORIG_HEAD
ORIG_HEAD
references the commit that HEAD
previously referenced.
The pull
command is:
adb pull source dest
When you write:
adb pull /data/data/path.to.package/databases/data /sdcard/test
It means that you'll pull from /data/data/path.to.package/databases/data
and you'll copy it to /sdcard/test
, but the destination MUST be a local directory. You may write C:\Users\YourName\temp
instead.
For example:
adb pull /data/data/path.to.package/databases/data c:\Users\YourName\temp
As an update, for Angular 7, a very good example, loading plus http interceptor, here: https://nezhar.com/blog/create-a-loading-screen-for-angular-apps/.
For version 6, you need a small adjustment when you use Subject. You need to add the generic type.
loadingStatus: Subject<boolean> = new Subject();
I'm using angular material, so instead of a loading text, you can use mat-spinner.
<mat-spinner></mat-spinner>
Update: the code from the previous page will not complete work (regarding the interceptor part), but here you have the complete solution: https://github.com/nezhar/snypy-frontend
And as Miranda recommended into comments, here is also the solution:
The loading screen component:
loading-screen.component.ts
import { Component, ElementRef, ChangeDetectorRef, OnDestroy, AfterViewInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { LoadingScreenService } from '../services/loading-screen.service';
@Component({
selector: 'app-loading-screen',
templateUrl: './loading-screen.component.html',
styleUrls: ['./loading-screen.component.css']
})
export class LoadingScreenComponent implements AfterViewInit, OnDestroy {
loading: boolean = false;
loadingSubscription: Subscription;
constructor(
private loadingScreenService: LoadingScreenService,
private _elmRef: ElementRef,
private _changeDetectorRef: ChangeDetectorRef
) { }
ngAfterViewInit(): void {
this._elmRef.nativeElement.style.display = 'none';
this.loadingSubscription = this.loadingScreenService.loadingStatus.pipe().subscribe(
(status: boolean) => {
this._elmRef.nativeElement.style.display = status ? 'block' : 'none';
this._changeDetectorRef.detectChanges();
}
);
}
ngOnDestroy() {
console.log("inside destroy loading component");
this.loadingSubscription.unsubscribe();
}
}
loading-screen.component.html
<div id="overlay">
<mat-spinner class="content"></mat-spinner>
</div>
loading-screen.component.css
#overlay {
position: fixed; /* Sit on top of the page content */
display: block; /* Hidden by default */
width: 100%; /* Full width (cover the whole page) */
height: 100%; /* Full height (cover the whole page) */
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(60, 138, 255, 0.1); /* Black background with opacity */
opacity: 0.5;
z-index: 2; /* Specify a stack order in case you're using a different order for other elements */
cursor: progress; /* Add a pointer on hover */
}
.content {
position: absolute;
top: 50%;
left: 50%;
font-size: 50px;
color: white;
transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
}
Don't forget to add the component to your root component. In my case, AppComponent
app.component.html
<app-loading-screen></app-loading-screen>
The service that will manage the component: loading-screen.service.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class LoadingScreenService {
constructor() { }
private _loading: boolean = false;
loadingStatus: Subject<boolean> = new Subject();
get loading(): boolean {
console.log("get loading: " + this._loading);
return this._loading;
}
set loading(value) {
console.log("get loading: " + value);
this._loading = value;
this.loadingStatus.next(value);
}
startLoading() {
console.log("startLoading");
this.loading = true;
}
stopLoading() {
console.log("stopLoading");
this.loading = false;
}
}
Here is the http interceptor, which will show/hide the component, using the previous service.
loading-screen-interceptor.ts
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { LoadingScreenService } from '../services/loading-screen.service';
import { Observable } from 'rxjs';
import { finalize } from 'rxjs/operators';
@Injectable()
export class LoadingScreenInterceptor implements HttpInterceptor {
activeRequests: number = 0;
constructor(
private loadingScreenService: LoadingScreenService
) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log("inside interceptor");
if (this.activeRequests === 0) {
this.loadingScreenService.startLoading();
}
this.activeRequests++;
return next.handle(request).pipe(
finalize(() => {
this.activeRequests--;
if (this.activeRequests === 0) {
this.loadingScreenService.stopLoading();
}
})
)
};
}
And in your app.module.ts, don't forget to config the interceptor
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: LoadingScreenInterceptor,
multi: true
}
]
System.out.println()
also outputs to LogCat. The benefit of using good old System.out.println()
is that you can print an object like System.out.println(object)
to the console if you need to check if a variable is initialized or not.
Log.d
, Log.v
, Log.w
etc methods only allow you to print strings to the console and not objects. To circumvent this (if you desire), you must use String.format
.
range()
and xrange()
take a third parameter that specifies a step. So you can do the following.
range(10, 0, -1)
Which gives
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
But for iteration, you should really be using xrange
instead. So,
xrange(10, 0, -1)
Note for Python 3 users: There are no separate
range
andxrange
functions in Python 3, there is justrange
, which follows the design of Python 2'sxrange
.
You are using field access strategy (determined by @Id annotation). Put any JPA related annotation right above each field instead of getter property
@OneToMany(targetEntity=Student.class, mappedBy="college", fetch=FetchType.EAGER)
private List<Student> students;
I imagine this like that:
<html>
<head>
<script>
var frame_loaded = 0;
function setFrameLoaded()
{
frame_loaded = 1;
alert("Iframe is loaded");
}
$('#click').click(function(){
if(frame_loaded == 1)
console.log('iframe loaded')
} else {
console.log('iframe not loaded')
}
})
</script>
</head>
<button id='click'>click me</button>
<iframe id='MainPopupIframe' onload='setFrameLoaded();' src='http://...' />...</iframe>
C++11 offers std::normal_distribution
, which is the way I would go today.
Here are some solutions in order of ascending complexity:
Add 12 uniform random numbers from 0 to 1 and subtract 6. This will match mean and standard deviation of a normal variable. An obvious drawback is that the range is limited to ±6 – unlike a true normal distribution.
The Box-Muller transform. This is listed above, and is relatively simple to implement. If you need very precise samples, however, be aware that the Box-Muller transform combined with some uniform generators suffers from an anomaly called Neave Effect1.
For best precision, I suggest drawing uniforms and applying the inverse cumulative normal distribution to arrive at normally distributed variates. Here is a very good algorithm for inverse cumulative normal distributions.
1. H. R. Neave, “On using the Box-Muller transformation with multiplicative congruential pseudorandom number generators,” Applied Statistics, 22, 92-97, 1973
You will have to set your custom WebviewClient overriding shouldOverrideUrlLoading method for your webview before loading the url.
mWebView.setWebViewClient(new WebViewClient()
{
@SuppressWarnings("deprecation")
@Override
public boolean shouldOverrideUrlLoading(WebView webView, String url)
{
return shouldOverrideUrlLoading(url);
}
@TargetApi(Build.VERSION_CODES.N)
@Override
public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest request)
{
Uri uri = request.getUrl();
return shouldOverrideUrlLoading(uri.toString());
}
private boolean shouldOverrideUrlLoading(final String url)
{
Log.i(TAG, "shouldOverrideUrlLoading() URL : " + url);
// Here put your code
return true; // Returning True means that application wants to leave the current WebView and handle the url itself, otherwise return false.
}
});
Checkout the example code for handling redirect urls and open PDF without download, in webview. https://gist.github.com/ashishdas09/014a408f9f37504eb2608d98abf49500
Someone has solved this in a simple, reusable way before. DDGReachability
.
EDIT: Or tonymillion/Reachability
.
Yes. Empty or incomplete headers or response body typically caused by broken connections or server side crash can cause 502 errors if accessed via a gateway or proxy.
For more information about the network errors
the most effective method is to use android-async-http
You can use this code to upload a file:
// gather your request parameters
File myFile = new File("/path/to/file.png");
RequestParams params = new RequestParams();
try {
params.put("profile_picture", myFile);
} catch(FileNotFoundException e) {}
// send request
AsyncHttpClient client = new AsyncHttpClient();
client.post(url, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] bytes) {
// handle success response
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] bytes, Throwable throwable) {
// handle failure response
}
});
Note that you can put this code directly into your main Activity, no need to create a background Task explicitly. AsyncHttp will take care of that for you!
Here is what you can try
OpenWindow.document.write(output);
call OpenWindow.init()
when the dom is ready So the parent window will have
OpenWindow.onload = function(){
OpenWindow.init('test');
}
and in the child
function init(txt){
$('#test').text(txt);
}
Why noy just use the theme styles in the table? i.e.
<table>
<thead class="ui-widget-header">
<tr>
<th>Id</th>
<th>Description</th>
</td>
</thead>
<tbody class="ui-widget-content">
<tr>
<td>...</td>
<td>...</td>
</tr>
.
.
.
</tbody>
</table>
And you don't need to use any code...
Insert the below code in didFinishLaunchingWithOptions() in AppDelegate.m
[[UINavigationBar appearance] setBarTintColor:[UIColor
colorWithRed:26.0/255.0 green:184.0/255.0 blue:110.0/255.0 alpha:1.0]];
Use Ctrl+K. This goes clean your console in Visual Studio Code.
Per comments, in later versions of VSCode (1.29 and above) this shortcut is missing / needs to be created manually.
File
> Preferences
> Keyboard Shortcuts
workbench.action.terminal.clear
CTRL
and tap K
. Ctrl + K
should now be listed. Press enter to save this mappingChange when expression
. Type terminalFocus
then press enter.ctrl
+k
you'll get the behaviour you'd have expected to get from running clear
/cls
.Check out JSON2HTML http://json2html.com/ plugin for jQuery. It allows you to specify a transform that would convert your JSON object to HTML template. Use builder on http://json2html.com/ to get json transform object for any desired html template. In your case, it would be a table with row having following transform.
Example:
var transform = {"tag":"table", "children":[
{"tag":"tbody","children":[
{"tag":"tr","children":[
{"tag":"td","html":"${name}"},
{"tag":"td","html":"${age}"}
]}
]}
]};
var data = [
{'name':'Bob','age':40},
{'name':'Frank','age':15},
{'name':'Bill','age':65},
{'name':'Robert','age':24}
];
$('#target_div').html(json2html.transform(data,transform));
After reading your previous comments, it's clear that you misunderstood the Hash::make function. Hash::make uses bcrypt hashing. By design, this means that every time you run Hash::make('password'), the result will be different (due to random salting). That's why you can't verify the password by simply checking the hashed password against the hashed input.
The proper way to validate a hash is by using:
Hash::check($passwordToCheck, $hashedPassword);
So, for example, your login function would be implemented like this:
public static function login($email, $password) {
$user = User::whereEmail($email)->first();
if ( !$user ) return null; //check if user exists
if ( Hash::check($password, $user->password) ) {
return $user;
} else return null;
}
And then you'd call it like this:
$user = User::login('[email protected]', 'password');
if ( !$user ) echo "Invalid credentials.";
else echo "First name: $user->firstName";
I recommend reviewing the Laravel security documentation, as functions already exist in Laravel to perform this type of authorization.
Furthermore, if your custom-made hashing algorithm generates the same hash every time for a given input, it's a security risk. A good one-way hashing algorithm should use random salting.
This clearly is a bad case of controller logic in a view. It would be better to do this in a controller and return the desired view.
[ChildActionOnly]
public ActionResult Results()
{
EnumerableRowCollection<DataRow> custs = ViewBag.Customers;
bool anyRows = custs.Any();
if(anyRows == false)
{
return View("NoResults");
}
else
{
return View("OtherView");
}
}
Modify NoResults.cshtml to a Partial.
And call this as a Partial view in the parent view
@Html.Partial("Results")
You might have to pass the Customer collection as a model to the Result action or in a ViewDataDictionary due to reasons explained here: Can't access ViewBag in a partial view in ASP.NET MVC3
The ChildActionOnly
attribute will make sure you cannot go to this page by navigating and that this view must be rendered as a partial, thus by a parent view. cfr: Using ChildActionOnly in MVC
On Windows XP -
rundll32.exe syssetup,SetupOobeBnk
This will reset the 30 day timer for activation back to 30 days so you can enter in the key normally.
Redirect from http to https://www
RewriteEngine On RewriteCond %{HTTP_HOST} ^example\.com [NC] RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
This will work for sure!
Switch inherits CompoundButton
's attributes, so I would recommend the OnCheckedChangeListener
mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// do something, the isChecked will be
// true if the switch is in the On position
}
});
From Typescript 3.7 on, you can also use nullish coalescing:
let x = foo ?? bar();
Which is the equivalent for checking for null or undefined:
let x = (foo !== null && foo !== undefined) ?
foo :
bar();
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing
While not exactly the same, you could write your code as:
var uemail = localStorage.getItem("useremail") ?? alert('Undefined');
Its not the best way to do it but it works:
$ git stash apply
$ >> resolve your conflict <<
$ >> do what you want to do with your code <<
$ git checkout HEAD -- file/path/to/your/file
On linux box that have python
(with pip
installer), grep
and awk
, install AWS CLI (command line tools for EC2, S3 and many other services)
sudo pip install awscli
then create a .awssecret
file in your home folder with content as below (adjust key, secret and region as needed):
[default]
aws_access_key_id=<YOUR_KEY_HERE>
aws_secret_access_key=<YOUR_SECRET_KEY_HERE>
region=<AWS_REGION>
Make this file read-write to your user only:
sudo chmod 600 .awssecret
and export it to your environment
export AWS_CONFIG_FILE=/home/<your_name>/.awssecret
then run in the terminal (this is a single line command, separated by \
for easy reading here):
aws s3 ls s3://<bucket_name>/foo/bar | \
grep -v -E "(Bucket: |Prefix: |LastWriteTime|^$|--)" | \
awk 'BEGIN {total=0}{total+=$3}END{print total/1024/1024" MB"}'
aws
part lists the bucket (or optionally a 'sub-folder')grep
part removes (using -v
) the lines that match the Regular Expression (using -E
). ^$
is for blank line, --
is for the separator lines in the output of aws s3 ls
awk
simply add to total
the 3rd colum of the resulting output (the size in KB) then display it at the endNOTE this command works for the current bucket or 'folder', not recursively
The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND
command on another connection, but it apparently was "not opening [it] up in sync with the client side".
Well, the main reason would be there was no synchronisation whatsoever. Calling:
cs.send("SEND " + FILE)
cs.close()
would just place the data into a OS buffer; close
would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep
after close
might mitigate the problem, but this is not synchronisation.
The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK
, or better PORT 36250
to indicate where to connect). This would make sure the server is already listening.
The other thing is you must check the return values of send
to make sure how many bytes was taken from your buffer. Or use sendall
.
(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)
Like @sanchit proposed middleware is a nice solution if you are already defining your axios instance globally.
You can create a middleware like:
function createAxiosAuthMiddleware() {
return ({ getState }) => next => (action) => {
const { token } = getState().authentication;
global.axios.defaults.headers.common.Authorization = token ? `Bearer ${token}` : null;
return next(action);
};
}
const axiosAuth = createAxiosAuthMiddleware();
export default axiosAuth;
And use it like this:
import { createStore, applyMiddleware } from 'redux';
const store = createStore(reducer, applyMiddleware(axiosAuth))
It will set the token on every action but you could only listen for actions that change the token for example.
First of all you need to remove the data-toggle attribute. We will use some JQuery, so make sure you include it.
<ul class='nav nav-tabs'>
<li class='active'><a href='#home'>Home</a></li>
<li><a href='#menu1'>Menu 1</a></li>
<li><a href='#menu2'>Menu 2</a></li>
<li><a href='#menu3'>Menu 3</a></li>
</ul>
<div class='tab-content'>
<div id='home' class='tab-pane fade in active'>
<h3>HOME</h3>
<div id='menu1' class='tab-pane fade'>
<h3>Menu 1</h3>
</div>
<div id='menu2' class='tab-pane fade'>
<h3>Menu 2</h3>
</div>
<div id='menu3' class='tab-pane fade'>
<h3>Menu 3</h3>
</div>
</div>
</div>
<script>
$(document).ready(function(){
// Handling data-toggle manually
$('.nav-tabs a').click(function(){
$(this).tab('show');
});
// The on tab shown event
$('.nav-tabs a').on('shown.bs.tab', function (e) {
alert('Hello from the other siiiiiide!');
var current_tab = e.target;
var previous_tab = e.relatedTarget;
});
});
</script>
I think the simplest way it's to use library ContentManager. This library for getting photo or video from a device gallery, cloud or camera. With asynchronous load from the cloud and fixed bugs for some problem devices.
Download via Gradle:
compile 'com.github.stfalcon:contentmanager:0.4.3'
You can find documentation at https://github.com/stfalcon-studio/ContentManager
You can override the default implementation of console.log()
(function () {
var old = console.log;
var logger = document.getElementById('log');
console.log = function (message) {
if (typeof message == 'object') {
logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify(message) : message) + '<br />';
} else {
logger.innerHTML += message + '<br />';
}
}
})();
Demo: Fiddle
Simplest solution in Springboot
I'll give you the simplest one if you use Springboot:
<properties>
<java.version>1.8</java.version>
</properties>
Then, right click on your Eclipse project: Maven > Update project > Update project configuration from pom.xml
That should do.
Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.
If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.
Here's an explanation I wrote recently to help with the void of information on this attribute. http://www.marklio.com/marklio/PermaLink,guid,ecc34c3c-be44-4422-86b7-900900e451f9.aspx (Internet Archive Wayback Machine link)
To quote the most relevant bits:
[Installing .NET] v4 is “non-impactful”. It should not change the behavior of existing components when installed.
The useLegacyV2RuntimeActivationPolicy attribute basically lets you say, “I have some dependencies on the legacy shim APIs. Please make them work the way they used to with respect to the chosen runtime.”
Why don’t we make this the default behavior? You might argue that this behavior is more compatible, and makes porting code from previous versions much easier. If you’ll recall, this can’t be the default behavior because it would make installation of v4 impactful, which can break existing apps installed on your machine.
The full post explains this in more detail. At RTM, the MSDN docs on this should be better.
In this case a relatively simple GROUP BY
can work, but in general, when there are additional columns where you can't order by but you want them from the particular row which they are associated with, you can either join back to the detail using all the parts of the key or use OVER()
:
Runnable example (Wofkflow20 error in original data corrected)
;WITH partitioned AS (
SELECT company
,workflow
,date
,other_columns
,ROW_NUMBER() OVER(PARTITION BY company, workflow
ORDER BY date) AS seq
FROM workflowTable
)
SELECT *
FROM partitioned WHERE seq = 1
I found the solution:
function onClick(e) {alert(this.getLatLng());}
used the method getLatLng() of the marker
assert
is for ensuring that something is true in a debug mode, without it having any effect in a release build. Better to use an if
statement and have an alternate plan for characters that are outside the range, unless the only way to get characters outside the range is through a program bug.
Also, depending on your character encoding, you might find a difference between the Unicode characters 0x80 through 0xff and their char
version.
For the sake of completeness, here is one more option.
Let's start with a definition from python docs:
slice An object usually containing a portion of a sequence. A slice is created using the subscript notation, [] with colons between numbers when several are given, such as in variable_name[1:3:5]. The bracket (subscript) notation uses slice objects internally (or in older versions, __getslice__() and __setslice__()).
Though the slice notation is not directly applicable to iterators in general, the itertools
package contains a replacement function:
from itertools import islice
# print the 100th line
with open('the_file') as lines:
for line in islice(lines, 99, 100):
print line
# print each third line until 100
with open('the_file') as lines:
for line in islice(lines, 0, 100, 3):
print line
The additional advantage of the function is that it does not read the iterator until the end. So you can do more complex things:
with open('the_file') as lines:
# print the first 100 lines
for line in islice(lines, 100):
print line
# then skip the next 5
for line in islice(lines, 5):
pass
# print the rest
for line in lines:
print line
And to answer the original question:
# how to read lines #26 and #30
In [365]: list(islice(xrange(1,100), 25, 30, 4))
Out[365]: [26, 30]
Aggregated List of Libraries
public string SendFile(string filePath)
{
WebResponse response = null;
try
{
string sWebAddress = "Https://www.address.com";
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(sWebAddress);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream stream = wr.GetRequestStream();
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
stream.Write(boundarybytes, 0, boundarybytes.Length);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(filePath);
stream.Write(formitembytes, 0, formitembytes.Length);
stream.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, "file", Path.GetFileName(filePath), Path.GetExtension(filePath));
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
stream.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
stream.Write(buffer, 0, bytesRead);
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
stream.Write(trailer, 0, trailer.Length);
stream.Close();
response = wr.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream);
string responseData = streamReader.ReadToEnd();
return responseData;
}
catch (Exception ex)
{
return ex.Message;
}
finally
{
if (response != null)
response.Close();
}
}
Step-1: Your Model class
public class RechargeMobileViewModel
{
public string CustomerFullName { get; set; }
public string TelecomSubscriber { get; set; }
public int TotalAmount { get; set; }
public string MobileNumber { get; set; }
public int Month { get; set; }
public List<SelectListItem> getAllDaysList { get; set; }
// Define the list which you have to show in Drop down List
public List<SelectListItem> getAllWeekDaysList()
{
List<SelectListItem> myList = new List<SelectListItem>();
var data = new[]{
new SelectListItem{ Value="1",Text="Monday"},
new SelectListItem{ Value="2",Text="Tuesday"},
new SelectListItem{ Value="3",Text="Wednesday"},
new SelectListItem{ Value="4",Text="Thrusday"},
new SelectListItem{ Value="5",Text="Friday"},
new SelectListItem{ Value="6",Text="Saturday"},
new SelectListItem{ Value="7",Text="Sunday"},
};
myList = data.ToList();
return myList;
}
}
Step-2: Call this method to fill Drop down in your controller Action
namespace MvcVariousApplication.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
RechargeMobileViewModel objModel = new RechargeMobileViewModel();
objModel.getAllDaysList = objModel.getAllWeekDaysList();
return View(objModel);
}
}
}
Step-3: Fill your Drop-Down List of View as follows
@model MvcVariousApplication.Models.RechargeMobileViewModel
@{
ViewBag.Title = "Contact";
}
@Html.LabelFor(model=> model.CustomerFullName)
@Html.TextBoxFor(model => model.CustomerFullName)
@Html.LabelFor(model => model.MobileNumber)
@Html.TextBoxFor(model => model.MobileNumber)
@Html.LabelFor(model => model.TelecomSubscriber)
@Html.TextBoxFor(model => model.TelecomSubscriber)
@Html.LabelFor(model => model.TotalAmount)
@Html.TextBoxFor(model => model.TotalAmount)
@Html.LabelFor(model => model.Month)
@Html.DropDownListFor(model => model.Month, new SelectList(Model.getAllDaysList, "Value", "Text"), "-Select Day-")
One of the easiest solutions is using the following protocol:
protocol ScrollViewKeyboardDelegate: class {
var scrollView: UIScrollView? { get set }
func registerKeyboardNotifications()
func unregisterKeyboardNotifications()
}
extension ScrollViewKeyboardDelegate where Self: UIViewController {
func registerKeyboardNotifications() {
NotificationCenter.default.addObserver(
forName: UIResponder.keyboardWillChangeFrameNotification,
object: nil,
queue: nil) { [weak self] notification in
self?.keyboardWillBeShown(notification)
}
NotificationCenter.default.addObserver(
forName: UIResponder.keyboardWillHideNotification,
object: nil,
queue: nil) { [weak self] notification in
self?.keyboardWillBeHidden(notification)
}
}
func unregisterKeyboardNotifications() {
NotificationCenter.default.removeObserver(
self,
name: UIResponder.keyboardWillChangeFrameNotification,
object: nil
)
NotificationCenter.default.removeObserver(
self,
name: UIResponder.keyboardWillHideNotification,
object: nil
)
}
func keyboardWillBeShown(_ notification: Notification) {
let info = notification.userInfo
let key = (info?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)
let aKeyboardSize = key?.cgRectValue
guard let keyboardSize = aKeyboardSize,
let scrollView = self.scrollView else {
return
}
let bottomInset = keyboardSize.height
scrollView.contentInset.bottom = bottomInset
scrollView.scrollIndicatorInsets.bottom = bottomInset
if let activeField = self.view.firstResponder {
let yPosition = activeField.frame.origin.y - bottomInset
if yPosition > 0 {
let scrollPoint = CGPoint(x: 0, y: yPosition)
scrollView.setContentOffset(scrollPoint, animated: true)
}
}
}
func keyboardWillBeHidden(_ notification: Notification) {
self.scrollView?.contentInset = .zero
self.scrollView?.scrollIndicatorInsets = .zero
}
}
extension UIView {
var firstResponder: UIView? {
guard !isFirstResponder else { return self }
return subviews.first(where: {$0.firstResponder != nil })
}
}
When you want to use this protocol, you only need to conform to it and assign your scroll view in your controller as follows:
class MyViewController: UIViewController {
@IBOutlet var scrollViewOutlet: UIScrollView?
var scrollView: UIScrollView?
public override func viewDidLoad() {
super.viewDidLoad()
self.scrollView = self.scrollViewOutlet
self.scrollView?.isScrollEnabled = true
self.registerKeyboardNotifications()
}
extension MyViewController: ScrollViewKeyboardDelegate {}
deinit {
self.unregisterKeyboardNotifications()
}
}
Use the keyword size
instead of fontsize
.
say you define the static getFactorial
function inside a CodeController
then this is the way you need to call a static function, because static properties and methods exists with in the class, not in the objects created using the class.
CodeController::getFactorial($index);
----------------UPDATE----------------
To best practice I think you can put this kind of functions inside a separate file so you can maintain with more easily.
to do that
create a folder inside app
directory and name it as lib
(you can put a name you like).
this folder to needs to be autoload to do that add app/lib
to composer.json
as below. and run the composer dumpautoload
command.
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
............
"app/lib"
]
},
then files inside lib
will autoloaded.
then create a file inside lib
, i name it helperFunctions.php
inside that define the function.
if ( ! function_exists('getFactorial'))
{
/**
* return the factorial of a number
*
* @param $number
* @return string
*/
function getFactorial($date)
{
$fact = 1;
for($i = 1; $i <= $num ;$i++)
$fact = $fact * $i;
return $fact;
}
}
and call it anywhere within the app as
$fatorial_value = getFactorial(225);
I faced this issue on Node 10.X version. below is my working code.
const https = require('https');
exports.handler = (event,context,callback) => {
let body='';
let jsonObject = JSON.stringify(event);
// the post options
var optionspost = {
host: 'example.com',
path: '/api/mypath',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'blah blah',
}
};
let reqPost = https.request(optionspost, function(res) {
console.log("statusCode: ", res.statusCode);
res.on('data', function (chunk) {
body += chunk;
});
res.on('end', function () {
console.log("Result", body.toString());
context.succeed("Sucess")
});
res.on('error', function () {
console.log("Result Error", body.toString());
context.done(null, 'FAILURE');
});
});
reqPost.write(jsonObject);
reqPost.end();
};
Sometimes you want to have your GridView as simple as:
<asp:GridView ID="grid" runat="server" />
You don't want to specify any BoundField, you just want to bind your grid to DataReader. The following code helped me to format DateTime in this situation.
protected void Page_Load(object sender, EventArgs e)
{
grid.RowDataBound += grid_RowDataBound;
// Your DB access code here...
// grid.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection);
// grid.DataBind();
}
void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow)
return;
var dt = (e.Row.DataItem as DbDataRecord).GetDateTime(4);
e.Row.Cells[4].Text = dt.ToString("dd.MM.yyyy");
}
The results shown here.
So if condition equals the value you want then the php document will run "include" and include will add that document to the current window for example:
`
<?php
$isARequest = true;
if ($isARequest){include('request.html');}/*So because $isARequest is true then it will include request.html but if its not a request then it will insert isNotARequest;*/
else if (!$isARequest) {include('isNotARequest.html')}
?>
`
Just in case if you are using Angular.js in your project (as I am) and have a ng-model
set for your <textarea>
, setting the default just inside like:
<textarea ng-model='foo'>Some default value</textarea>
...will not work!
You need to set the default value to the textarea's ng-model
in the respective controller or use ng-init
.
Example 1 (using ng-init
):
var myApp = angular.module('myApp',[]);_x000D_
_x000D_
myApp.controller('MyCtrl', [ '$scope', function($scope){_x000D_
// your controller implementation here_x000D_
}]);
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>_x000D_
<meta charset="utf-8">_x000D_
<title>JS Bin</title>_x000D_
</head>_x000D_
<body ng-app='myApp'>_x000D_
<div ng-controller="MyCtrl">_x000D_
<textarea ng-init='foo="Some default value"' ng-model='foo'></textarea>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
Example 2 (without using ng-init
):
var myApp = angular.module('myApp',[]);_x000D_
_x000D_
myApp.controller('MyCtrl', [ '$scope', function($scope){_x000D_
$scope.foo = 'Some default value';_x000D_
}]);
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>_x000D_
<meta charset="utf-8">_x000D_
<title>JS Bin</title>_x000D_
</head>_x000D_
<body ng-app='myApp'>_x000D_
<div ng-controller="MyCtrl">_x000D_
<textarea ng-model='foo'></textarea>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
Quite simply:
git rm --cached <file>
makes git stop tracking the file completely (leaving it in the filesystem, unlike plain git rm
*)git reset HEAD <file>
unstages any modifications made to the file since the last commit (but doesn't revert them in the filesystem, contrary to what the command name might suggest**). The file remains under revision control.If the file wasn't in revision control before (i.e. you're unstaging a file that you had just git add
ed for the first time), then the two commands have the same effect, hence the appearance of these being "two ways of doing something".
* Keep in mind the caveat @DrewT mentions in his answer, regarding git rm --cached
of a file that was previously committed to the repository. In the context of this question, of a file just added and not committed yet, there's nothing to worry about.
** I was scared for an embarrassingly long time to use the git reset command because of its name -- and still today I often look up the syntax to make sure I don't screw up. (update: I finally took the time to summarize the usage of git reset
in a tldr page, so now I have a better mental model of how it works, and a quick reference for when I forget some detail.)
find($id)
takes an id and returns a single model. If no matching model exist, it returns null
.
findOrFail($id)
takes an id and returns a single model. If no matching model exist, it throws an error1.
first()
returns the first record found in the database. If no matching model exist, it returns null
.
firstOrFail()
returns the first record found in the database. If no matching model exist, it throws an error1.
get()
returns a collection of models matching the query.
pluck($column)
returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists
.
toArray()
converts the model/collection into a simple PHP array.
Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.
Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach
loop is ok, put passing it to array_map
is not. Similarly, if you type-hint an argument as array
, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable
typehint, which can be used to accept both arrays and collections.
If you ever want to get a plain array from a collection, call its all()
method.
1 The error thrown by the findOrFail
and firstOrFail
methods is a ModelNotFoundException
. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.
Another way of doing that is:
String date = dateAndTime.substring(0, dateAndTime.indexOf(" "));
I'm not exactly certain, but I think this might be faster/use less memory than using the .split()
method.
As Blexy already answered, go to "Behavior > Site Content > All Pages".
Just pay attention that "Behavior" appears two times in the left sidebar and we need to click on the second option:
Add "new":
var movies = _db.Movies.OrderBy( m => new { m.CategoryID, m.Name })
That works on my box. It does return something that can be used to sort. It returns an object with two values.
Similar, but different to sorting by a combined column, as follows.
var movies = _db.Movies.OrderBy( m => (m.CategoryID.ToString() + m.Name))
If you use the Anaconda python distribution, you can use the conda list
command to see what was installed by what method:
user@pc:~ $ conda list
# packages in environment at /anaconda3:
#
# Name Version Build Channel
_ipyw_jlab_nb_ext_conf 0.1.0 py36h2fc01ae_0
alabaster 0.7.10 py36h174008c_0
amqp 2.2.2 <pip>
anaconda 5.1.0 py36_2
anaconda-client 1.6.9 py36_0
To grab the entries installed by pip
(including possibly pip
itself):
user@pc:~ $ conda list | grep \<pip
amqp 2.2.2 <pip>
astroid 1.6.2 <pip>
billiard 3.5.0.3 <pip>
blinker 1.4 <pip>
ez-setup 0.9 <pip>
feedgenerator 1.9 <pip>
Of course you probably want to just select the first column, which you can do with (excluding pip
if needed):
user@pc:~ $ conda list | awk '$3 ~ /pip/ {if ($1 != "pip") print $1}'
amqp
astroid
billiard
blinker
ez-setup
feedgenerator
Finally you can grab these values and pip uninstall all of them using the following:
user@pc:~ $ conda list | awk '$3 ~ /pip/ {if ($1 != "pip") print $1}' | xargs pip uninstall -y
Note the use of the -y
flag for the pip uninstall
to avoid having to give confirmation to delete.
You can fix the issue with the following steps:
sudo cd /var/lib/php/session
. If it does not exist then sudo mkdir /var/lib/php/session
or double check the logs to make sure you have the correct path.sudo chmod 666 /var/lib/php/session
.Rerun you script and it should be working fine, however, it's not recommended to leave the folder with full permissions. For security, files and folders should only have the minimum permissions required. The following steps will fix that:
sudo ls -l
to find out the owner of the session file.sudo chown user /var/lib/php/session
.sudo chmod 600 /var/lib/php/session
.NB
You might not need to use the sudo
command.
ClassLoader.class.getResourceAsStream("/path/to/your/xml")
and make sure that your compile script is copying the xml file to where in your CLASSPATH.
If your code is prepared to deal with overflow errors, you can throw an exception if data
is too large.
size_t data = 99999999;
if ( data > INT_MAX )
{
throw std::overflow_error("data is larger than INT_MAX");
}
int convertData = static_cast<int>(data);
Take a look at class java.lang.Character
static member methods (isDigit, isLetter, isLowerCase, ...)
Example:
String str = "Hello World 123 !!";
int specials = 0, digits = 0, letters = 0, spaces = 0;
for (int i = 0; i < str.length(); ++i) {
char ch = str.charAt(i);
if (!Character.isDigit(ch) && !Character.isLetter(ch) && !Character.isSpace(ch)) {
++specials;
} else if (Character.isDigit(ch)) {
++digits;
} else if (Character.isSpace(ch)) {
++spaces;
} else {
++letters;
}
}
$fruit= array_map('trim', $fruit);
Now you should be able to do it directly in the IB.
Not sure though, if this was available when the question was posted originally.
In material ui, state of checkbox can be fetched as
this.refs.complete.state.switched
when mysql.proc is empty, but system always notice "[email protected].%" for table_name no exist,you just root in mysql command line and type:
CHECK TABLE `database`.`table_name` QUICK FAST MEDIUM CHANGED;
flush privileges;
over!
You can not do that directly. You need to use std::remove
algorithm to move the element to be erased to the end of the vector and then use erase
function. Something like: myVector.erase(std::remove(myVector.begin(), myVector.end(), 8), myVec.end());
. See this erasing elements from vector for more details.
Find a complete working example below:
The code by @Android is very good but has few issues, namely:
size = size -1
seems unnecessary.Find below the modified code of @Android as a working example:
WifiScanner.java which is the Main Activity
package com.arjunandroid.wifiscanner;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class WifiScanner extends Activity implements View.OnClickListener{
WifiManager wifi;
ListView lv;
Button buttonScan;
int size = 0;
List<ScanResult> results;
String ITEM_KEY = "key";
ArrayList<String> arraylist = new ArrayList<>();
ArrayAdapter adapter;
/* Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getActionBar().setTitle("Widhwan Setup Wizard");
setContentView(R.layout.activity_wifi_scanner);
buttonScan = (Button) findViewById(R.id.scan);
buttonScan.setOnClickListener(this);
lv = (ListView)findViewById(R.id.wifilist);
wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled() == false)
{
Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
wifi.setWifiEnabled(true);
}
this.adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,arraylist);
lv.setAdapter(this.adapter);
scanWifiNetworks();
}
public void onClick(View view)
{
scanWifiNetworks();
}
private void scanWifiNetworks(){
arraylist.clear();
registerReceiver(wifi_receiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
wifi.startScan();
Log.d("WifScanner", "scanWifiNetworks");
Toast.makeText(this, "Scanning....", Toast.LENGTH_SHORT).show();
}
BroadcastReceiver wifi_receiver= new BroadcastReceiver()
{
@Override
public void onReceive(Context c, Intent intent)
{
Log.d("WifScanner", "onReceive");
results = wifi.getScanResults();
size = results.size();
unregisterReceiver(this);
try
{
while (size >= 0)
{
size--;
arraylist.add(results.get(size).SSID);
adapter.notifyDataSetChanged();
}
}
catch (Exception e)
{
Log.w("WifScanner", "Exception: "+e);
}
}
};
}
activity_wifi_scanner.xml which is the layout file for the Activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/wifilist"
android:layout_width="match_parent"
android:layout_height="312dp"
android:layout_weight="0.97" />
<Button
android:id="@+id/scan"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="bottom"
android:layout_margin="15dp"
android:background="@android:color/holo_green_light"
android:text="Scan Again" />
</LinearLayout>
Also as mentioned above, do not forget to add Wifi permissions in the AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
You can set the figure size if you explicitly create the figure with
plt.figure(figsize=(3,4))
You need to set figure size before calling plt.plot()
To change the format of the saved figure just change the extension in the file name. However, I don't know if any of matplotlib backends support tiff
This works for me:
<c:forEach var="i" begin="1970" end="2000">
<option value="${2000-(i-1970)}">${2000-(i-1970)}
</option>
</c:forEach>
xcopy "$(ProjectDir)Views\Home\Index.cshtml" "$(SolutionDir)MEFMVCPOC\Views\Home"
and if you want to copy entire folders:
xcopy /E /Y "$(ProjectDir)Views" "$(SolutionDir)MEFMVCPOC\Views"
Update: here's the working version
xcopy "$(ProjectDir)Views\ModuleAHome\Index.cshtml" "$(SolutionDir)MEFMVCPOC\Views\ModuleAHome\" /Y /I
Here are some commonly used switches with xcopy
:
- /I - treat as a directory if copying multiple files.
- /Q - Do not display the files being copied.
- /S - Copy subdirectories unless empty.
- /E - Copy empty subdirectories.
- /Y - Do not prompt for overwrite of existing files.
- /R - Overwrite read-only files.
You simply need to make cab
a string:
cab = '6176'
As the error message states, you cannot do <int> in <string>
:
>>> 1 in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not int
>>>
because integers and strings are two totally different things and Python does not embrace implicit type conversion ("Explicit is better than implicit.").
In fact, Python only allows you to use the in
operator with a right operand of type string if the left operand is also of type string:
>>> '1' in '123' # Works!
True
>>>
>>> [] in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list
>>>
>>> 1.0 in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not float
>>>
>>> {} in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not dict
>>>
I thought it has been around a little longer, but according to this,
MySQL 5.7.4 introduces the ability to set server side execution time limits, specified in milliseconds, for top level read-only SELECT statements.
SELECT
/*+ MAX_EXECUTION_TIME(1000) */ --in milliseconds
*
FROM table;
Note that this only works for read-only SELECT statements.
Update: This variable was added in MySQL 5.7.4 and renamed to max_execution_time
in MySQL 5.7.8. (source)
What I did to solve the problem was:
git pull origin [branch]
git push origin [branch]
Also make sure that you are pointing to the right branch by running:
git remote set-url origin [url]
export a=$(script.sh)
Hope this helps. Note there are no spaces between variable and =. To echo the output
echo $a
It's actually much easier with jQuery's promise API:
$.ajax(
type: "GET",
url: requestURL,
).then((success) =>
console.dir(success)
).failure((failureResponse) =>
console.dir(failureResponse)
)
Alternatively, you can pass in of bind
functions to each result callback; the order of parameters is: (success, failure)
. So long as you specify a function with at least 1 parameter, you get access to the response. So, for example, if you wanted to check the response text, you could simply do:
$.ajax(
type: "GET",
url: @get("url") + "logout",
beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)
).failure((response) -> console.log "Request was unauthorized" if response.status is 401
It was giving 415 Http response Code as error,
So I added
httppost.addHeader("Content-Type", "text/xml; charset=utf-8");
Everything alright now, Http: 200
C:\Program Files\MySQL\MySQL Workbench 6.3 CE\sys
paste URL
in to window file,
and get Tables, Procedures, Functions
from this directory
if sum of column is 0 then display empty
select if(sum(column)>0,sum(column),'')
from table
November 2019:
onclick="self.close()"
still works in Chrome while Edge gives a warning that must be confirmed before it will close.
On the other hand the solution onclick="window.open('', '_self', ''); window.close();"
works in both.
Try this in your alice
repository (before pushing):
git config push.default tracking
Or, configure it as the default for your user with git config --global …
.
git push
does default to the origin
repository (which is normally the repository from which you cloned the current repository), but it does not default to pushing the current branch—it defaults to pushing only branches that exist in both the source repository and the destination repository.
The push.default
configuration variable (see git-config(1)) controls what git push
will push when it is not given any “refspec” arguments (i.e. something after a repository name). The default value gives the behavior described above.
Here are possible values for push.default
:
nothing
This forces you to supply a “refspec”.
matching
(the default)
This pushes all branches that exist in both the source repository and the destination repository.
This is completely independent of the branch that is currently checked out.
upstream
or tracking
(Both values mean the same thing. The later was deprecated to avoid confusion with “remote-tracking” branches. The former was introduced in 1.7.4.2, so you will have to use the latter if you are using Git 1.7.3.1.)
These push the current branch to the branch specified by its “upstream” configuration.
current
This pushes the current branch to the branch of the same name at the destination repository.
These last two end up being the same for common cases (e.g. working on local master which uses origin/master as its upstream), but they are different when the local branch has a different name from its “upstream” branch:
git checkout master
# hack, commit, hack, commit
# bug report comes in, we want a fix on master without the above commits
git checkout -b quickfix origin/master # "upstream" is master on origin
# fix, commit
git push
With push.default
equal to upstream
(or tracking
), the push would go to origin
’s master branch. When it is equal to current
, the push would go to origin
’s quickfix branch.
The matching
setting will update bare
’s master in your scenario once it has been established. To establish it, you could use git push origin master
once.
However, the upstream
setting (or maybe current
) seems like it might be a better match for what you expect to happen, so you might want to try it:
# try it once (in Git 1.7.2 and later)
git -c push.default=upstream push
# configure it for only this repository
git config push.default upstream
# configure it for all repositories that do not override it themselves
git config --global push.default upstream
(Again, if you are still using a Git before 1.7.4.2, you will need to use tracking
instead of upstream
).
I tried to execute specific plugging right after clean up i.e. post-clean (default is clean phase). This worked for me with eclipse indigo. Just added post-clean resolved the problem for me.
<executions>
<execution>
<configuration>
</configuration>
<phase>post-clean</phase>
<goals>
<goal>update-widgetset</goal>
</goals>
</execution>
</executions>
Another option which doesn't have the need to create a custom Model is to use a Tuple<>.
@model Tuple<Person,Order>
It's not as clean as creating a new class which contains both, as per Andi's answer, but it is viable.
I regularly use the packaged rio for exporting of all kinds. Using rio, you can input a list, naming each tab and specifying the dataset. rio compiles other in/out packages, and for export to Excel, uses openxlsx.
library(rio)
filename <- "C:/R_code/../file.xlsx"
export(list(sn1 = tempTable1, sn2 = tempTable2, sn3 = tempTable3), filename)
I know that its bit old Q but if u get here by searching a solution so i got a nice one via jquery
jQuery('a[target^="_new"]').click(function() {
var width = window.innerWidth * 0.66 ;
// define the height in
var height = width * window.innerHeight / window.innerWidth ;
// Ratio the hight to the width as the user screen ratio
window.open(this.href , 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));
});
it will open all the <a target="_new">
in a new window
EDIT:
1st, I did some little changes in the original code now it open the new window perfectly followed the user screen ratio (for landscape desktops)
but, I would like to recommend you to use the following code that open the link in new tab if you in mobile (thanks to zvona answer in other question):
jQuery('a[target^="_new"]').click(function() {
return openWindow(this.href);
}
function openWindow(url) {
if (window.innerWidth <= 640) {
// if width is smaller then 640px, create a temporary a elm that will open the link in new tab
var a = document.createElement('a');
a.setAttribute("href", url);
a.setAttribute("target", "_blank");
var dispatch = document.createEvent("HTMLEvents");
dispatch.initEvent("click", true, true);
a.dispatchEvent(dispatch);
}
else {
var width = window.innerWidth * 0.66 ;
// define the height in
var height = width * window.innerHeight / window.innerWidth ;
// Ratio the hight to the width as the user screen ratio
window.open(url , 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));
}
return false;
}
Try Alt+F12 in Visual Studio 2010.
It opens up the Find Symbol dialogue which allows you to search for methods, classes, etc.
First, there is no particularly good reason to use fdopen
if fopen
is an option and open
is the other possible choice. You shouldn't have used open
to open the file in the first place if you want a FILE *
. So including fdopen
in that list is incorrect and confusing because it isn't very much like the others. I will now proceed to ignore it because the important distinction here is between a C standard FILE *
and an OS-specific file descriptor.
There are four main reasons to use fopen
instead of open
.
fopen
provides you with buffering IO that may turn out to be a lot faster than what you're doing with open
.fopen
does line ending translation if the file is not opened in binary mode, which can be very helpful if your program is ever ported to a non-Unix environment (though the world appears to be converging on LF-only (except IETF text-based networking protocols like SMTP and HTTP and such)).FILE *
gives you the ability to use fscanf
and other stdio functions.open
function.In my opinion the line ending translation more often gets in your way than helps you, and the parsing of fscanf
is so weak that you inevitably end up tossing it out in favor of something more useful.
And most platforms that support C have an open
function.
That leaves the buffering question. In places where you are mainly reading or writing a file sequentially, the buffering support is really helpful and a big speed improvement. But it can lead to some interesting problems in which data does not end up in the file when you expect it to be there. You have to remember to fclose
or fflush
at the appropriate times.
If you're doing seeks (aka fsetpos
or fseek
the second of which is slightly trickier to use in a standards compliant way), the usefulness of buffering quickly goes down.
Of course, my bias is that I tend to work with sockets a whole lot, and there the fact that you really want to be doing non-blocking IO (which FILE *
totally fails to support in any reasonable way) with no buffering at all and often have complex parsing requirements really color my perceptions.
You can Change it from:
Menu Settings -> Style Configurator
See on screenshot:
For everyone coming to this thread with fractional seconds in your timestamp use:
to_timestamp('2018-11-03 12:35:20.419000', 'YYYY-MM-DD HH24:MI:SS.FF')