Sample Usage:
import paramiko
paramiko.util.log_to_file("paramiko.log")
# Open a transport
host,port = "example.com",22
transport = paramiko.Transport((host,port))
# Auth
username,password = "bar","foo"
transport.connect(None,username,password)
# Go!
sftp = paramiko.SFTPClient.from_transport(transport)
# Download
filepath = "/etc/passwd"
localpath = "/home/remotepasswd"
sftp.get(filepath,localpath)
# Upload
filepath = "/home/foo.jpg"
localpath = "/home/pony.jpg"
sftp.put(localpath,filepath)
# Close
if sftp: sftp.close()
if transport: transport.close()
There isn't currently a built-in PowerShell method for doing the SFTP part. You'll have to use something like psftp.exe or a PowerShell module like Posh-SSH.
Here is an example using Posh-SSH:
# Set the credentials
$Password = ConvertTo-SecureString 'Password1' -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential ('root', $Password)
# Set local file path, SFTP path, and the backup location path which I assume is an SMB path
$FilePath = "C:\FileDump\test.txt"
$SftpPath = '/Outbox'
$SmbPath = '\\filer01\Backup'
# Set the IP of the SFTP server
$SftpIp = '10.209.26.105'
# Load the Posh-SSH module
Import-Module C:\Temp\Posh-SSH
# Establish the SFTP connection
$ThisSession = New-SFTPSession -ComputerName $SftpIp -Credential $Credential
# Upload the file to the SFTP path
Set-SFTPFile -SessionId ($ThisSession).SessionId -LocalFile $FilePath -RemotePath $SftpPath
#Disconnect all SFTP Sessions
Get-SFTPSession | % { Remove-SFTPSession -SessionId ($_.SessionId) }
# Copy the file to the SMB location
Copy-Item -Path $FilePath -Destination $SmbPath
Some additional notes:
That should give you a decent starting point.
I've searched around and found that this fork of SharpSSH and SSH.NET are the most up to date and best maintained libraries for SFTP (not to be confused with FTPS) communication in .NET. SSH.NET is a clean .NET 4.0 implementation of the SFTP protocol, and I've used it in a couple of solutions with flying colors and great success.
The original SharpSsh seems to be dead and most other solutions either require installation of Windows executables or a bucketload of cash (or worse; both).
Below code works for me
public static void sftpsript(String filepath) {
try {
String user ="demouser"; // username for remote host
String password ="demo123"; // password of the remote host
String host = "demo.net"; // remote host address
JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
sftpChannel.disconnect();
session.disconnect();
}catch(Exception ex){
ex.printStackTrace();
}
}
OR using StrictHostKeyChecking as "NO" (security consequences)
public static void sftpsript(String filepath) {
try {
String user ="demouser"; // username for remote host
String password ="demo123"; // password of the remote host
String host = "demo.net"; // remote host address
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);;
session.setPassword(password);
System.out.println("user=="+user+"\n host=="+host);
session.connect();
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
sftpChannel.disconnect();
session.disconnect();
}catch(Exception ex){
ex.printStackTrace();
}
}
You mention batch files, am I correct then assuming that you're talking about a Windows system? If so you cannot use sshpass, and you will have to switch to a different option.
Two of such options, that follow diametrically opposite philosophies are:
Either way, switching from password to PKI authentication is strongly recommended.
SFTP is not FTP over SSH, it's a different protocol and being similar to SCP, it's offers more capabilities.
pscp and psftp are very customizable(options) and light weight. Open source to boot.
http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html
What about running the google-drive-ftp-adapter application in your local pc and then connect your filezilla client to that application? The google-drive-ftp-adapter application is not an online service, but its an alternative solution to connect to google drive through ftp.
The google-drive-ftp-adapter is an open source application hosted in github and it is a kind of standalone ftp-server java application that connects to your google drive in behalf of you, acting as a bridge (or adapter) between your ftp client and the google drive service. Once you have running the google-drive-ftp adapter, you can connect your preferred FTP client to the google-drive-ftp-adapter ftp server in your localhost (or wherever the app is running, like in a remote machine) to manage your files.
I use it in conjunction with beyond compare to synchronize my local files against the ones I have in the google drive and it serves well for the purpose.
This is the current github link hosting the google-drive-ftp-adapter repository: https://github.com/andresoviedo/google-drive-ftp-adapter
The built in FTP command doesn't have a facility for security. Use cUrl instead. It's scriptable, far more robust and has FTP security.
Update Sep 2017 - tl;dr
Download a single file from a remote ftp server to your machine:
sftp {user}@{host}:{remoteFileName} {localFileName}
Upload a single file from your machine to a remote ftp server:
sftp {user}@{host}:{remote_dir} <<< $'put {local_file_path}'
Original answer:
Ok, so I feel a little dumb. But I figured it out. I almost had it at the top with:
sftp user@host remoteFile localFile
The only documentation shown in the terminal is this:
sftp [user@]host[:file ...]
sftp [user@]host[:dir[/]]
However, I came across this site which shows the following under the synopsis:
sftp [-vC1 ] [-b batchfile ] [-o ssh_option ] [-s subsystem | sftp_server ] [-B buffer_size ] [-F ssh_config ] [-P sftp_server path ] [-R num_requests ] [-S program ] host
sftp [[user@]host[:file [file]]]
sftp [[user@]host[:dir[/]]]
So the simple answer is you just do :
after your user and host then the remote file and local filename. Incredibly simple!
Single line, sftp copy remote file:
sftp username@hostname:remoteFileName localFileName
sftp kyle@kylesserver:/tmp/myLogFile.log /tmp/fileNameToUseLocally.log
Update Feb 2016
In case anyone is looking for the command to do the reverse of this and push a file from your local computer to a remote server in one single line sftp
command, user @Thariama below posted the solution to accomplish that. Hat tip to them for the extra code.
sftp {user}@{host}:{remote_dir} <<< $'put {local_file_path}'
If you have to do private key validation; at Command Prompt(cmd), run
First;
set PATH=C:\PuttySetupLocation
Second;
pscp -i C:/MyPrivateKeyFile.ppk C:/MySourceFile.jar [email protected]:/home/ubuntu
Also, if you need extra options look at the following link. https://the.earth.li/~sgtatham/putty/0.60/htmldoc/Chapter5.html
For another un-free option try edtFTPnet/PRO. It has comprehensive support for SFTP, and also supports FTPS (and of course FTP) if required.
It's the default SSH port and SFTP is usually carried over an SSH tunnel.
While the example works, its not the correct way to handle the streams...
You need to ensure the closing of the files/streams with the using clause.. Also, add try/catch to handle IO errors...
public void DownloadAll()
{
string host = @"sftp.domain.com";
string username = "myusername";
string password = "mypassword";
string remoteDirectory = "/RemotePath/";
string localDirectory = @"C:\LocalDriveFolder\Downloaded\";
using (var sftp = new SftpClient(host, username, password))
{
sftp.Connect();
var files = sftp.ListDirectory(remoteDirectory);
foreach (var file in files)
{
string remoteFileName = file.Name;
if ((!file.Name.StartsWith(".")) && ((file.LastWriteTime.Date == DateTime.Today))
using (Stream file1 = File.OpenWrite(localDirectory + remoteFileName))
{
sftp.DownloadFile(remoteDirectory + remoteFileName, file1);
}
}
}
}
I have just been in a similar position with regards to setting the 777 permissions on the apache website hosting directory. After a little bit of tinkering it seems that changing the group ownership of the folder to the "apache" group allowed access to the folder based on the user group.
1) make sure that the group ownership of the folder is set to the group apache used / generates for use. (check /etc/groups, mine was www-data on Ubuntu)
2) set the folder permissions to 774 to stop "everyone" from having any change access, but allowing the owner and group permissions required.
3) add your user account to the group that has permission on the folder (mine was www-data).
FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.
Some references:
Though you can use any other client that allows automation.
You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).
Combine WinSCP scripting capabilities with Windows Scheduler:
A typical WinSCP script for upload (with SFTP) looks like:
open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close
With FTP, just replace the sftp://
with the ftp://
and remove the -hostkey="..."
switch.
Similarly for download: How to schedule an automatic FTP download on Windows?
WinSCP can even generate a script from an imported FileZilla session.
For details, see the guide to FileZilla automation.
(I'm the author of WinSCP)
Another option, if you are using SFTP, is the psftp.exe
client from PuTTY suite.
Try this code.
public void send (String fileName) {
String SFTPHOST = "host:IP";
int SFTPPORT = 22;
String SFTPUSER = "username";
String SFTPPASS = "password";
String SFTPWORKINGDIR = "file/to/transfer";
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
System.out.println("preparing the host information for sftp.");
try {
JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
session.setPassword(SFTPPASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
System.out.println("Host connected.");
channel = session.openChannel("sftp");
channel.connect();
System.out.println("sftp channel opened and connected.");
channelSftp = (ChannelSftp) channel;
channelSftp.cd(SFTPWORKINGDIR);
File f = new File(fileName);
channelSftp.put(new FileInputStream(f), f.getName());
log.info("File transfered successfully to host.");
} catch (Exception ex) {
System.out.println("Exception found while tranfer the response.");
} finally {
channelSftp.exit();
System.out.println("sftp Channel exited.");
channel.disconnect();
System.out.println("Channel disconnected.");
session.disconnect();
System.out.println("Host Session disconnected.");
}
}
Another way would be to use lftp:
lftp sftp://user:password@host -e "put local-file.name; bye"
The disadvantage of this method is that other users on the computer can read the password from tools like ps
and that the password can become part of your shell history.
A more secure alternative which is available since LFTP 4.5.0 is setting the LFTP_PASSWORD
environment variable and executing lftp with --env-password
. Here's a full example:
LFTP_PASSWORD="just_an_example"
lftp --env-password sftp://user@host -e "put local-file.name; bye"
LFTP also includes a cool mirroring feature (can include delete after confirmed transfer --Remove-source-files
):
lftp -e 'mirror -R /local/log/path/ /remote/path/' --env-password -u user sftp.foo.com
Paramiko supports SFTP. I've used it, and I've used Twisted. Both have their place, but you might find it easier to start with Paramiko.
The issue is with the Version of JSCH jar you are using.
Update it to latest jar.
I was also getting the same error and this solution worked.
You can download latest jar from
There is a nice comparison of the 3 mature Java libraries for SFTP: Commons VFS, SSHJ and JSch
To sum up SSHJ has the clearest API and it's the best out of them if you don't need other storages support provided by Commons VFS.
Here is edited SSHJ example from github:
final SSHClient ssh = new SSHClient();
ssh.loadKnownHosts(); // or, to skip host verification: ssh.addHostKeyVerifier(new PromiscuousVerifier())
ssh.connect("localhost");
try {
ssh.authPassword("user", "password"); // or ssh.authPublickey(System.getProperty("user.name"))
final SFTPClient sftp = ssh.newSFTPClient();
try {
sftp.get("test_file", "/tmp/test.tmp");
} finally {
sftp.close();
}
} finally {
ssh.disconnect();
}
WinSCp now supports S3 protocol
First, make sure your AWS user with S3 access permissions has an “Access key ID” created. You also have to know the “Secret access key”. Access keys are created and managed on Users page of IAM Management Console.
Make sure New site node is selected.
On the New site node, select Amazon S3 protocol.
Enter your AWS user Access key ID and Secret access key
Save your site settings using the Save button.
Login using the Login button.
set DSKTOPDIR="D:\test"
set IPADDRESS="23.23.3.23"
>%DSKTOPDIR%\script.ftp ECHO cd %PAY_REP%
>>%DSKTOPDIR%\script.ftp ECHO mget *.report
>>%DSKTOPDIR%\script.ftp ECHO bye
:: run PSFTP Commands
psftp <domain>@%IPADDRESS% -b %DSKTOPDIR%\script.ftp
Set values using set commands before above lines.
I believe this helps you.
Referre psfpt setup for below link https://www.ssh.com/ssh/putty/putty-manuals/0.68/Chapter6.html
The answers with {file1,file2,file3}
works only with bash (on remote or locally)
The real way is :
scp user@remote:'/path1/file1 /path2/file2 /path3/file3' /localPath
You can use script like this for mac:
for f in $(curl -s -l -u user:pass ftp://your_ftp_server_ip/folder/)
do curl -O -u user:pass ftp://your_ftp_server_ip/folder/$f
done
The ssh2 functions aren't very good. Hard to use and harder yet to install, using them will guarantee that your code has zero portability. My recommendation would be to use phpseclib, a pure PHP SFTP implementation.
Just summarising @libing's answer with a sample that worked for me.
val gson = Gson()
val todoItem: TodoItem = gson.fromJson(this.assets.readAssetsFile("versus.json"), TodoItem::class.java)
private fun AssetManager.readAssetsFile(fileName : String): String = open(fileName).bufferedReader().use{it.readText()}
Without this extension function the same can be achieved by using BufferedReader
and InputStreamReader
this way:
val i: InputStream = this.assets.open("versus.json")
val br = BufferedReader(InputStreamReader(i))
val todoItem: TodoItem = gson.fromJson(br, TodoItem::class.java)
Comparing various suggestions (as well as comparing in the context of single-character replacements with various sizes and positions of the target).
In this particular case, splitting on the targets and joining on the replacements (in this case, empty string) is the fastest by at least a factor of 3. Ultimately, performance is different depending on the number of replacements, where the replacements are in the source, and the size of the source. #ymmv
(full results here)
| Test | Compare | Elapsed |
|---------------------------|---------|--------------------------------------------------------------------|
| SplitJoin | 1.00x | 29023 ticks elapsed (2.9023 ms) [in 10K reps, 0.00029023 ms per] |
| Replace | 2.77x | 80295 ticks elapsed (8.0295 ms) [in 10K reps, 0.00080295 ms per] |
| RegexCompiled | 5.27x | 152869 ticks elapsed (15.2869 ms) [in 10K reps, 0.00152869 ms per] |
| LinqSplit | 5.43x | 157580 ticks elapsed (15.758 ms) [in 10K reps, 0.0015758 ms per] |
| Regex, Uncompiled | 5.85x | 169667 ticks elapsed (16.9667 ms) [in 10K reps, 0.00169667 ms per] |
| Regex | 6.81x | 197551 ticks elapsed (19.7551 ms) [in 10K reps, 0.00197551 ms per] |
| RegexCompiled Insensitive | 7.33x | 212789 ticks elapsed (21.2789 ms) [in 10K reps, 0.00212789 ms per] |
| Regex Insentive | 7.52x | 218164 ticks elapsed (21.8164 ms) [in 10K reps, 0.00218164 ms per] |
(note: the Perf
and Vs
are timing extensions I wrote)
void test(string title, string sample, string target, string replacement) {
var targets = target.ToCharArray();
var tox = "[" + target + "]";
var x = new Regex(tox);
var xc = new Regex(tox, RegexOptions.Compiled);
var xci = new Regex(tox, RegexOptions.Compiled | RegexOptions.IgnoreCase);
// no, don't dump the results
var p = new Perf/*<string>*/();
p.Add(string.Join(" ", title, "Replace"), n => targets.Aggregate(sample, (res, curr) => res.Replace(new string(curr, 1), replacement)));
p.Add(string.Join(" ", title, "SplitJoin"), n => String.Join(replacement, sample.Split(targets)));
p.Add(string.Join(" ", title, "LinqSplit"), n => String.Concat(sample.Select(c => targets.Contains(c) ? replacement : new string(c, 1))));
p.Add(string.Join(" ", title, "Regex"), n => Regex.Replace(sample, tox, replacement));
p.Add(string.Join(" ", title, "Regex Insentive"), n => Regex.Replace(sample, tox, replacement, RegexOptions.IgnoreCase));
p.Add(string.Join(" ", title, "Regex, Uncompiled"), n => x.Replace(sample, replacement));
p.Add(string.Join(" ", title, "RegexCompiled"), n => xc.Replace(sample, replacement));
p.Add(string.Join(" ", title, "RegexCompiled Insensitive"), n => xci.Replace(sample, replacement));
var trunc = 40;
var header = sample.Length > trunc ? sample.Substring(0, trunc) + "..." : sample;
p.Vs(header);
}
void Main()
{
// also see https://stackoverflow.com/questions/7411438/remove-characters-from-c-sharp-string
"Control".Perf(n => { var s = "*"; });
var text = "My name @is ,Wan.;'; Wan";
var clean = new[] { '@', ',', '.', ';', '\'' };
test("stackoverflow", text, string.Concat(clean), string.Empty);
var target = "o";
var f = "x";
var replacement = "1";
var fillers = new Dictionary<string, string> {
{ "short", new String(f[0], 10) },
{ "med", new String(f[0], 300) },
{ "long", new String(f[0], 1000) },
{ "huge", new String(f[0], 10000) }
};
var formats = new Dictionary<string, string> {
{ "start", "{0}{1}{1}" },
{ "middle", "{1}{0}{1}" },
{ "end", "{1}{1}{0}" }
};
foreach(var filler in fillers)
foreach(var format in formats) {
var title = string.Join("-", filler.Key, format.Key);
var sample = string.Format(format.Value, target, filler.Value);
test(title, sample, target, replacement);
}
}
Are u sure u want to remove only last character. What if the user press backspace from the middle of the word.. Its better to get the value from the field and replace the divs html. On keyup
$("#div").html($("#input").val());
The best solution is toString
(as stated above):
function getRealObjectType(obj: {}): string {
return Object.prototype.toString.call(obj).match(/\[\w+ (\w+)\]/)[1].toLowerCase();
}
FAIR WARNING: toString
considers NaN
a number
so you must manually safeguard later with Number.isNaN(value)
.
The other solution suggested, using Object.getPrototypeOf
fails with null
and undefined
try this code its very simple and usefull
public boolean isMockLocationEnabled() {
boolean isMockLocation = false;
try {
//if marshmallow
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
AppOpsManager opsManager = (AppOpsManager) getApplicationContext().getSystemService(Context.APP_OPS_SERVICE);
isMockLocation = (opsManager.checkOp(AppOpsManager.OPSTR_MOCK_LOCATION, android.os.Process.myUid(), BuildConfig.APPLICATION_ID)== AppOpsManager.MODE_ALLOWED);
} else {
// in marshmallow this will always return true
isMockLocation = !android.provider.Settings.Secure.getString(getApplicationContext().getContentResolver(), "mock_location").equals("0");
}
} catch (Exception e) {
return isMockLocation;
}
return isMockLocation;
}
You know, using a custom deleter isn't the best way to go, as you will have to mention it all over your code.
Instead, as you are allowed to add specializations to namespace-level classes in ::std
as long as custom types are involved and you respect the semantics, do that:
Specialize std::default_delete
:
template <>
struct ::std::default_delete<Bar> {
default_delete() = default;
template <class U>
constexpr default_delete(default_delete<U>) noexcept {}
void operator()(Bar* p) const noexcept { destroy(p); }
};
And maybe also do std::make_unique()
:
template <>
inline ::std::unique_ptr<Bar> ::std::make_unique<Bar>() {
auto p = create();
if (!p)
throw std::runtime_error("Could not `create()` a new `Bar`.");
return { p };
}
These are usually to make sure that the browser gets a new version when the site gets updated with a new version, e.g. as part of our build process we'd have something like this:
/Resources/Combined.css?v=x.x.x.buildnumber
Since this changes with every new code push, the client's forced to grab a new version, just because of the querystring. Look at this page (at the time of this answer) for example:
<link ... href="http://sstatic.net/stackoverflow/all.css?v=c298c7f8233d">
I think instead of a revision number the SO team went with a file hash, which is an even better approach, even with a new release, the browsers only forced to grab a new version when the file actually changes.
Both of these approaches allow you to set the cache header to something ridiculously long, say 20 years...yet when it changes, you don't have to worry about that cache header, the browser sees a different querystring and treats it as a different, new file.
The issue is how you're attempting to get the value. Things like...
if ( document.frm_new_user_request.u_isid.value == '' )
won't work. You need to find the element you want to get the value of first. It's not quite like a server side language where you can type in an object's reference name and a period to get or assign values.
document.getElementById('[id goes here]').value;
will work. Note: JavaScript is case-sensitive
I would recommend using:
var variablename = document.getElementById('[id goes here]');
or
var variablename = document.getElementById('[id goes here]').value;
After wasting so much time i got to know that there was mistake in my syntax to connect with DB. I was using colon ":" instead of slash "/".
(1) if you use sid below is the syntax to get connection:
**"jdbc:oracle:thin:@{hostname}:{port}:{SID}"**
(2) if you use service name, below is the syntax to get connection:
"**jdbc:oracle:thin:@//{hostname}:{port}/{servicename}**"
I can see that documentation as far back as Java 1.2.
While it's true that in general you shouldn't rely on a hash code implementation remaining the same, it's now documented behaviour for java.lang.String
, so changing it would count as breaking existing contracts.
Wherever possible, you shouldn't rely on hash codes staying the same across versions etc - but in my mind java.lang.String
is a special case simply because the algorithm has been specified... so long as you're willing to abandon compatibility with releases before the algorithm was specified, of course.
Here's what finally worked for me. You'll have to convert the code to suit your own needs, but this will do it.
$fname = filter_input(INPUT_POST, "name");
$img = filter_input(INPUT_POST, "image");
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$img = base64_decode($img);
file_put_contents($fname, $img);
print "Image has been saved!";
df.drop('columnname', axis =1, inplace = True)
or else you can go with
del df['colname']
To delete multiple columns based on column numbers
df.drop(df.iloc[:,1:3], axis = 1, inplace = True)
To delete multiple columns based on columns names
df.drop(['col1','col2',..'coln'], axis = 1, inplace = True)
If using MS Visual C++ 10.0, you can do this with standard library facilities:
Concurrency::wait(milliseconds);
you will need:
#include <concrt.h>
Working my way through Fluent Python (Ramalho) - highly recommended. List comprehension one-ish-liners inspired by Chapter 2:
onlyascii = ''.join([s for s in data if ord(s) < 127])
onlymatch = ''.join([s for s in data if s in
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'])
Although many correct answers have already been given, the classical (read non-DOM) approach would be like this:
document.forms['yourform']['yourtextarea'].value = 'yourvalue';
where in the HTML your textarea is nested somewhere in a form like this:
<form name="yourform">
<textarea name="yourtextarea" rows="10" cols="60"></textarea>
</form>
And as it happens, that would work with Netscape Navigator 4 and Internet Explorer 3 too. And, not unimportant, Internet Explorer on mobile devices.
DAO is native to Access and by far the best for general use. ADO has its place, but it is unlikely that this is it.
Dim rs As DAO.Recordset
Dim db As Database
Dim strSQL as String
Set db=CurrentDB
strSQL = "select * from table where some condition"
Set rs = db.OpenRecordset(strSQL)
Do While Not rs.EOF
rs.Edit
rs!SomeField = "Abc"
rs!OtherField = 2
rs!ADate = Date()
rs.Update
rs.MoveNext
Loop
There is a few benefits of using modules. You can use it only with Apple's framework unless module map is created. @import
is a bit similar to pre-compiling headers files when added to .pch
file which is a way to tune app the compilation process. Additionally you do not have to add libraries in the old way, using @import
is much faster and efficient in fact. If you still look for a nice reference I will highly recommend you reading this article.
The answers didn't work for me with postgresql 9.1+
This is what I had to do (you can check more in the manual here)
UPDATE schema.TableA as A
SET "columnA" = "B"."columnB"
FROM schema.TableB as B
WHERE A.id = B.id;
You can omit the schema, if you are using the default schema for both tables.
You need only to write:
GRANT DBA TO NewDBA;
Because this already makes the user a DB Administrator
I have create a eclipse plugin to create activity in one click .
Just download the Plugin from https://docs.google.com/file/d/0B63U_IjxUP_GMkdYZzc1Y3lEM1U/edit?usp=sharing
Paste the plugin in the dropins folder in Eclipse and restart eclipse
For more details please see my blog
http://shareatramachandran.blogspot.in/2013/06/android-activity-plugin-for-eclispe.html
Need your comment on this if it was helpful...
try this instead
Set TxtRng = ActiveWorkbook.Sheets("Game").Range("A1")
ADDITION
Maybe the file is corrupt - this has happened to me several times before and the only solution is to copy everything out into a new file.
Please can you try the following:
Does this run?
Sub varchanger()
With Excel.Application
.ScreenUpdating = True
.Calculation = Excel.xlCalculationAutomatic
.EnableEvents = True
End With
On Error GoTo Whoa:
Dim myBook As Excel.Workbook
Dim mySheet As Excel.Worksheet
Dim Rng As Excel.Range
Set myBook = Excel.Workbooks("MyFullyQualified.xlsm")
Set mySheet = myBook.Worksheets("mySheet")
Set Rng = mySheet.Range("A1")
'ActiveSheet.Unprotect
Rng.Value = "SubTotal"
Excel.Workbooks("MyFullyQualified.xlsm").Worksheets("mySheet").Range("A1").Value = "Asdf"
LetsContinue:
Exit Sub
Whoa:
MsgBox Err.Number
GoTo LetsContinue
End Sub
Faced this recently on XCode 7.3.1 - for me, I noticed RAM usage going to 100% on to CleanMyMac3. The problem magically fixed itself after I restarted my machine. In all fairness however, I'd already gone ahead and tried the accepted-answer, so you'll want to do the same before you restart just in case :-)
In build:app
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.proyecto.marketdillo"
minSdkVersion 14
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0-rc02'
implementation 'com.google.firebase:firebase-core:16.0.7'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:support-v4:28.0.0-rc02'
implementation 'com.android.support:design:28.0.0-rc02'
implementation 'com.google.firebase:firebase-auth:16.1.0'
implementation 'com.squareup.picasso:picasso:2.5.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.google.firebase:firebase-firestore:17.1.5'
implementation 'com.android.support:multidex:1.0.3'
}
apply plugin: 'com.google.gms.google-services'
Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.
Discord supports Markdown and uses highlight.js to highlight code-blocks.
Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.
To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).
```language
message
```
Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).
Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.
Try my code. Here you can set all properties of UIButton like text colour, background colour, corner radius, etc.
extension UIButton {
func btnCorner() {
layer.cornerRadius = 10
clipsToBounds = true
backgroundColor = .blue
}
}
Now call like this
yourBtnName.btnCorner()
JQUERY
$("#video1").bind("ended", function() {
//TO DO: Your code goes here...
});
HTML
<video id="video1" width="420">
<source src="path/filename.mp4" type="video/mp4">
Your browser does not support HTML5 video.
</video>
Event types HTML Audio and Video DOM Reference
Use array_splice
rather than unset
:
$array = array(1,2,3,4,5);
foreach($array as $i => $info)
{
if($info == 1 || $info == 2)
{
array_splice($array, $i, 1);
}
}
print_r($array);
Another native solution (in coffee):
el = document.getElementsByTagName 'b'
docFrag = document.createDocumentFragment()
docFrag.appendChild el.firstChild while el.childNodes.length
el.parentNode.replaceChild docFrag, el
I don't know if it's faster than user113716's solution, but it might be easier to understand for some.
Well, you would typically use
System.out.println("print something");
which doesn't require any imports. However, since out is a static field inside of System, you could write use a static import like this:
import static java.lang.System.*;
class Test {
public static void main(String[] args) {
out.println("print something");
}
}
Take a look at this link. Typically you would only do this if you are using a lot of static methods from a particular class, like I use it all the time for junit asserts, and easymock.
I will suggest move all templates to separate files, and don't do spagetti inside repeat
take a look here:
html:
<div ng-repeat = "data in comments">
<div ng-include src="buildUrl(data.type)"></div>
</div>
js:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.comments = [
{"_id":"52fb84fac6b93c152d8b4569",
"post_id":"52fb84fac6b93c152d8b4567",
"user_id":"52df9ab5c6b93c8e2a8b4567",
"type":"hoot"},
{"_id":"52fb798cc6b93c74298b4568",
"post_id":"52fb798cc6b93c74298b4567",
"user_id":"52df9ab5c6b93c8e2a8b4567",
"type":"story"},
{"_id":"52fb7977c6b93c5c2c8b456b",
"post_id":"52fb7977c6b93c5c2c8b456a",
"user_id":"52df9ab5c6b93c8e2a8b4567",
"type":"article"}
];
$scope.buildUrl = function(type) {
return type + '.html';
}
});
You need to precede the lines starting with gcc
and rm
with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line).
The result should look like this:
PROG = semsearch
all: $(PROG)
%: %.c
gcc -o $@ $< -lpthread
clean:
rm $(PROG)
Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:
PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread
clean: ; rm $(PROG)
I had the exact same error message doing a database export via Sequel Pro on a mac. I was the root user so i knew it wasn't permissions. Then i tried it with mysqldump and got a different error message: Got error: 1449: The user specified as a definer ('joey'@'127.0.0.1') does not exist when using LOCK TABLES
Ahh, I had restored this database from a backup on the dev site and I hadn't created that user on this machine. "grant all on . to 'joey'@'127.0.0.1' identified by 'joeypass'; " did the trick.
hth
timeout is a key parameter to this problem.
however it's not suit for me.
i found there is not gunicorn timeout error when i set workers=1.
when i look though my code, i found some socket connect (socket.send & socket.recv) in server init.
socket.recv will block my code and that's why it always timeout when workers>1
hope to give some ideas to the people who have some problem with me
Run the Process Monitor to see what resources(Network, File, Registry, Threads) are being consumed and see any unnecessary resource(remote https, costly file reads) are being consumed
I had similar problem. When I run the process monitor I found that my fusion log is enabled so there are many into the disk which delayed the loading of dll after disabling fusion log IIS Express it is faster.
Promise returned from $http
can not be binded directly (I dont exactly know why).
I'm using wrapping service that works perfectly for me:
.factory('DocumentsList', function($http, $q){
var d = $q.defer();
$http.get('/DocumentsList').success(function(data){
d.resolve(data);
});
return d.promise;
});
and bind to it in controller:
function Ctrl($scope, DocumentsList) {
$scope.Documents = DocumentsList;
...
}
UPDATE!:
In Angular 1.2 auto-unwrap promises was removed. See http://docs.angularjs.org/guide/migration#templates-no-longer-automatically-unwrap-promises
nametext
is an std::string
but these do not have the stream insertion operator (<<
) like output streams do.
To concatenate strings you can use the append
member function (or its equivalent, +=
, which works in the exact same way) or the +
operator, which creates a new string as a result of concatenating the previous two.
I always use below approach. I've created one table in database as Table1 with only one column i.e. Row_Id Number (Long Integer) and its value is 0
INSERT INTO <TABLE_NAME_TO_RESET>
SELECT Row_Id AS <COLUMN_NAME_TO_RESET>
FROM Table1;
This will insert one row with 0 value in AutoNumber column, later delete that row.
You can try creating a css for your font with font-face (like explained here)
Step #1
Create a css file with font face and place it somewhere, like in assets/fonts
customfont.css
@font-face {
font-family: YourFontFamily;
src: url("/assets/font/yourFont.otf") format("truetype");
}
Step #2
Add the css to your .angular-cli.json in the styles
config
"styles":[
//...your other styles
"assets/fonts/customFonts.css"
]
Do not forget to restart ng serve
after doing this
Step #3
Use the font in your code
component.css
span {font-family: YourFontFamily; }
you can multiplication using lambda
foo=[1,2,3,4]
bar=[1,2,5,55]
l=map(lambda x,y:x*y,foo,bar)
I was able to do this
>>> [x if x % 2 != 0 else x * 100 for x in range(1,10)]
[1, 200, 3, 400, 5, 600, 7, 800, 9]
>>>
That is the mode with which you are opening the file. "wb" means that you are writing to the file (w), and that you are writing in binary mode (b).
Check out the documentation for more: clicky
I came across amplify.js. It's really simple to use. To store a value, let's call it "myValue", you do:
amplify.store("myKey", "myValue")
And to access it, you do
amplify.store("myKey")
NITZ is a form of NTP and is sent to the mobile device over Layer 3 or NAS layers. Commonly this message is seen as GMM Info and contains the following informaiton:
Certain carriers dont support this and some support it and have it setup incorrectly.
LAYER 3 SIGNALING MESSAGE
Time: 9:38:49.800
GMM INFORMATION 3GPP TS 24.008 ver 12.12.0 Rel 12 (9.4.19)
M Protocol Discriminator (hex data: 8)
(0x8) Mobility Management message for GPRS services
M Skip Indicator (hex data: 0) Value: 0 M Message Type (hex data: 21) Message number: 33
O Network time zone (hex data: 4680) Time Zone value: GMT+2:00 O Universal time and time zone (hex data: 47716070 70831580) Year: 17 Month: 06 Day: 07 Hour: 07 Minute :38 Second: 51 Time zone value: GMT+2:00 O Network Daylight Saving Time (hex data: 490100) Daylight Saving Time value: No adjustment
Layer 3 data: 08 21 46 80 47 71 60 70 70 83 15 80 49 01 00
I had this error for my XXX element and it was because my XSD was wrongly formatted according to javax.xml.bind v2.2.11 . I think it's using an older XSD format but I didn't bother to confirm.
My initial wrong XSD was alike the following:
<xs:element name="Document" type="Document"/>
...
<xs:complexType name="Document">
<xs:sequence>
<xs:element name="XXX" type="XXX_TYPE"/>
</xs:sequence>
</xs:complexType>
The good XSD format for my migration to succeed was the following:
<xs:element name="Document">
<xs:complexType>
<xs:sequence>
<xs:element ref="XXX"/>
</xs:sequence>
</xs:complexType>
</xs:element>
...
<xs:element name="XXX" type="XXX_TYPE"/>
And so on for every similar XSD nodes.
I know it's an old question but maybe someone can use this solution:
int size = 0; // Fill all bits with zero (0)
size = ~size; // Negate all bits, thus all bits are set to one (1)
So far we have -1 as result 'till size is a signed int.
size = (unsigned int)size >> 1; // Shift the bits of size one position to the right.
As Standard says, bits that are shifted in are 1 if variable is signed and negative and 0 if variable would be unsigned or signed and positive.
As size is signed and negative we would shift in sign bit which is 1, which is not helping much, so we cast to unsigned int, forcing to shift in 0 instead, setting the sign bit to 0 while letting all other bits remain 1.
cout << size << endl; // Prints out size which is now set to maximum positive value.
We could also use a mask and xor but then we had to know the exact bitsize of the variable. With shifting in bits front, we don't have to know at any time how many bits the int has on machine or compiler nor need we include extra libraries.
Yes, kill should be fine if you're running Jenkins with the built-in Winstone container. This Jenkins Wiki page has some tips on how to set up control scripts for Jenkins.
You may want to have a look at the code here. Although it doesn't answer your question directly you could adapt the generic class types that are used to map between data classes and business objects.
Also by using generic you run the conversion process as quickly as possible.
In case you want to work with the original MNIST files, here is how you can deserialize them.
If you haven't downloaded the files yet, do that first by running the following in the terminal:
wget http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz
wget http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz
wget http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz
wget http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz
Then save the following as deserialize.py
and run it.
import numpy as np
import gzip
IMG_DIM = 28
def decode_image_file(fname):
result = []
n_bytes_per_img = IMG_DIM*IMG_DIM
with gzip.open(fname, 'rb') as f:
bytes_ = f.read()
data = bytes_[16:]
if len(data) % n_bytes_per_img != 0:
raise Exception('Something wrong with the file')
result = np.frombuffer(data, dtype=np.uint8).reshape(
len(bytes_)//n_bytes_per_img, n_bytes_per_img)
return result
def decode_label_file(fname):
result = []
with gzip.open(fname, 'rb') as f:
bytes_ = f.read()
data = bytes_[8:]
result = np.frombuffer(data, dtype=np.uint8)
return result
train_images = decode_image_file('train-images-idx3-ubyte.gz')
train_labels = decode_label_file('train-labels-idx1-ubyte.gz')
test_images = decode_image_file('t10k-images-idx3-ubyte.gz')
test_labels = decode_label_file('t10k-labels-idx1-ubyte.gz')
The script doesn't normalize the pixel values like in the pickled file. To do that, all you have to do is
train_images = train_images/255
test_images = test_images/255
declare @sexo as char(1)
select @sexo='F'
select * from pessoa
where isnull(Sexo,0) =isnull(@Sexo,0)
Long answer:
Floating-point numbers have three components:
Essentially, this works out to sign * 2^exponent * (1 + fraction)
. The “size”
of the number, it’s exponent, is irrelevant to us, because it only scales the
value of the fraction portion. Knowing that log10(n)
gives the number of
digits of n
,† we can determine the precision of a floating point number
with log10(largest_possible_fraction)
. Because each bit in a float stores 2
possibilities, a binary number of n
bits can store a number up to 2n - 1
(a
total of 2n
values where one of the values is zero). This gets a bit
hairier, because it turns out that floating point numbers are stored with one
less bit of fraction than they can use, because zeroes are represented specially
and all non-zero numbers have at least one non-zero binary bit.‡
Combining this, the digits of precision for a floating point number is
log10(2n)
, where n
is the number of bits of the floating point number’s
fraction. A 32-bit float has 24 bits of fraction for ˜7.22 decimal digits of
precision, and a 64-bit double has 53 bits of fraction for ˜15.95 decimal digits
of precision.
For more on floating point accuracy, you might want to read about the concept of a machine epsilon.
† For n = 1
at least — for other numbers your formula will look more like
?log10(|n|)? + 1
.
‡ “This rule is variously called the leading bit convention, the implicit bit convention, or the hidden bit convention.” (Wikipedia)
Often, you will want a fast install from local archives, without probing PyPI.
First, download the archives that fulfill your requirements:
$ pip install --download <DIR> -r requirements.txt
Then, install using –find-links
and –no-index
:
$ pip install --no-index --find-links=[file://]<DIR> -r requirements.txt
You can use replace
instead of gsub
.
"hello _there_".replace(/_(.*?)_/g, "<div>\$1</div>")
Note that if you're using NSButton there is no setTitle
func, instead, it's a property.
@IBOutlet weak var classToButton: NSButton!
. . .
classToButton.title = "Some Text"
=
, the indent command can take motions. So, gg
to get the start of the file, =
to indent, G
to the end of the file, gg=G
.
result = map(str.strip, hello)
its a way to do things over and over indefinitely such that every option is used.
for example if you wanted to get all the links on an html page you will want to have recursions because when you get all the links on page 1 you will want to get all the links on each of the links found on the first page. then for each link to a newpage you will want those links and so on... in other words it is a function that calls itself from inside itself.
when you do this you need a way to know when to stop or else you will be in an endless loop so you add an integer param to the function to track the number of cycles.
in c# you will have something like this:
private void findlinks(string URL, int reccursiveCycleNumb) {
if (reccursiveCycleNumb == 0)
{
return;
}
//recursive action here
foreach (LinkItem i in LinkFinder.Find(URL))
{
//see what links are being caught...
lblResults.Text += i.Href + "<BR>";
findlinks(i.Href, reccursiveCycleNumb - 1);
}
reccursiveCycleNumb -= reccursiveCycleNumb;
}
You would use the read.csv
function; for example:
dat = read.csv("spam.csv", header = TRUE)
You can also reference this tutorial for more details.
Note: make sure the .csv
file to read is in your working directory (using getwd()
) or specify the right path to file. If you want, you can set the current directory using setwd
.
I assume you are using windows. Open the command prompt and type ipconfig
and find out your local address (on your pc) it should look something like 192.168.1.13
or 192.168.0.5
where the end digit is the one that changes. It should be next to IPv4 Address.
If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13
If you have a virtual host then you will need root to edit the hosts file.
If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.
See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.
Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).
If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow
to allow,deny
in the httpd.conf
file. You can access this by the WAMP menu.
To eliminate possible causes of the issue for now set your config file to
<Directory />
Options FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
<RequireAll>
Require all granted
</RequireAll>
</Directory>
As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.
Config file that fixed the problem:
https://gist.github.com/samvaughton/6790739
Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.
Unfortunately, I don't believe there really is a better way of doing this due to the nature of Java's handling of primitive types, boxing, arrays and generics. In particular:
List<T>.toArray
won't work because there's no conversion from Integer
to int
int
as a type argument for generics, so it would have to be an int
-specific method (or one which used reflection to do nasty trickery).I believe there are libraries which have autogenerated versions of this kind of method for all the primitive types (i.e. there's a template which is copied for each type). It's ugly, but that's the way it is I'm afraid :(
Even though the Arrays
class came out before generics arrived in Java, it would still have to include all the horrible overloads if it were introduced today (assuming you want to use primitive arrays).
your_string = 'Hello world';
words_array = your_tring.split(' ');
string_without_space = '';
for(i=0; i<words_array.length; i++){
new_text += words_array[i];
}
console.log("The new word:" new_text);
The output:
HelloWorld
You could specify the online Javadoc location for a particular JAR in Eclipse. This saved my day when I wasn't able to find any downloadable Javadocs for Kafka.
Package Explorer
, right click on the intended JAR (under the project's Referenced Libraries or Maven Dependences or anything as such) and click on Properties
.Javadoc Location
.Javadoc location path
field under Javadoc URL, enter the URL of the online Javadocs, which most likely ends with /<version>/javadoc/
. For example, Kafka 2.3.0's Javadocs are located at http://www.apache.org/dist/kafka/2.3.0/javadoc/ (you might want to change https
to http
in your URL, as it raised an invalid location warning after clicking on Validate...
for me).For checking existence one can also use (works for both, files and folders):
Not Dir(DirFile, vbDirectory) = vbNullString
The result is True
if a file or a directory exists.
Example:
If Not Dir("C:\Temp\test.xlsx", vbDirectory) = vbNullString Then MsgBox "exists" Else MsgBox "does not exist" End If
This is an old post, but I was looking for answer to this same question,
Why not try something like:
scale_color_manual(values = c("foo" = "#999999", "bar" = "#E69F00"))
If you have categorical values, I don't see a reason why this should not work.
Simple, fast, accurate
SELECT x.Amount
FROM (SELECT amount,
Count(1) OVER (partition BY 'A') AS TotalRows,
Row_number() OVER (ORDER BY Amount ASC) AS AmountOrder
FROM facttransaction ft) x
WHERE x.AmountOrder = Round(x.TotalRows / 2.0, 0)
Code:
private static void RegisterServices(IKernel kernel)
{
Mock<IProductRepository> mock=new Mock<IProductRepository>();
mock.Setup(x => x.Products).Returns(new List<Product>
{
new Product {Name = "Football", Price = 23},
new Product {Name = "Surf board", Price = 179},
new Product {Name = "Running shose", Price = 95}
});
kernel.Bind<IProductRepository>().ToConstant(mock.Object);
}
but see exception.
protected override void OnLoad(EventArgs e) {
base.OnLoad(e);
CenterToParent();
}
It's probably caused by a local network connectivity issue (but also a DNS error is possible). Unfortunately HResult
is generic, however you can determine the exact issue catching HttpRequestException
and then inspecting InnerException
: if it's a WebException
then you can check the WebException.Status
property, for example WebExceptionStatus.NameResolutionFailure
should indicate a DNS resolution problem.
It may happen, there isn't much you can do.
What I'd suggest to always wrap that (network related) code in a loop with a try
/catch
block (as also suggested here for other fallible operations). Handle known exceptions, wait a little (say 1000 msec) and try again (for say 3 times). Only if failed all times then you can quit/report an error to your users. Very raw example like this:
private const int NumberOfRetries = 3;
private const int DelayOnRetry = 1000;
public static async Task<HttpResponseMessage> GetFromUrlAsync(string url) {
using (var client = new HttpClient()) {
for (int i=1; i <= NumberOfRetries; ++i) {
try {
return await client.GetAsync(url);
}
catch (Exception e) when (i < NumberOfRetries) {
await Task.Delay(DelayOnRetry);
}
}
}
}
As an extension to @VinaySajip answer. There are additional nargs
worth mentioning.
parser.add_argument('dir', nargs=1, default=os.getcwd())
N (an integer). N arguments from the command line will be gathered together into a list
parser.add_argument('dir', nargs='*', default=os.getcwd())
'*'. All command-line arguments present are gathered into a list. Note that it generally doesn't make much sense to have more than one positional argument with nargs='*'
, but multiple optional arguments with nargs='*'
is possible.
parser.add_argument('dir', nargs='+', default=os.getcwd())
'+'. Just like '*', all command-line args present are gathered into a list. Additionally, an error message will be generated if there wasn’t at least one command-line argument present.
parser.add_argument('dir', nargs=argparse.REMAINDER, default=os.getcwd())
argparse.REMAINDER
. All the remaining command-line arguments are gathered into a list. This is commonly useful for command line utilities that dispatch to other command line utilities
If the nargs
keyword argument is not provided, the number of arguments consumed is determined by the action. Generally this means a single command-line argument will be consumed and a single item (not a list) will be produced.
Edit (copied from a comment by @Acumenus) nargs='?'
The docs say: '?'. One argument will be consumed from the command line if possible and produced as a single item. If no command-line argument is present, the value from default will be produced.
The following works for me.
string strToday = DateTime.Today.ToString("MM/dd/yyyy");
You can check this solved your problem...
#headermenu ul{
text-align: center;
}
#headermenu li {
list-style-type: none;
display: inline-block;
}
#headermenu ul li a{
float: left;
}
If you want to use glyph icons with bootstrap 2.3.2, Add the font files from bootstrap 3 to your project folder then copy this to your css file
@font-face {
font-family: 'Glyphicons Halflings';
src: url('../fonts/glyphicons-halflings-regular.eot');
src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}
I solved my issue by doing this:
Strangely it started working again after that.
SQLite Boolean Datatype:
SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true).
You can convert boolean to int in this way:
int flag = (boolValue)? 1 : 0;
You can convert int back to boolean as follows:
// Select COLUMN_NAME values from db.
// This will be integer value, you can convert this int value back to Boolean as follows
Boolean flag2 = (intValue == 1)? true : false;
If you want to explore sqlite, here is a tutorial.
I have given one answer here. It is working for them.
To get the titles for dates greater than a week ago today, use this:
SELECT title, MIN(date_key_no) AS intro_date FROM table HAVING MIN(date_key_no)>= TO_NUMBER(TO_CHAR(SysDate, 'YYYYMMDD')) - 7
If you absolutely must use HTML to give your text color, you have to use the (deprecated) <font>
-tag:
<h2><font color="#006699">Process Report</font></h2>
But otherwise, I strongly recommend you to do as rekire said: use CSS.
River of News for the iPad took about 400 hours of development to get to version 1.0 and I don't know how many hours my designer spent (20-50?). At US labor rates that's at least $40,000. But that sort of tight development was only possible because it was a one man operation. There is an enormous amount of overhead added when you separate the person writing the code from the person deciding what the product is going to do.
If you are going to send it offshore you'd better know exactly what you want. With the language and time difference it's very hard to do iterative design where you are exploring what is possible.
I think you need to use Expr
with ->set()
(However THIS IS NOT SAFE and you shouldn't do it):
$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
->set('u.username', $qb->expr()->literal($username))
->set('u.email', $qb->expr()->literal($email))
->where('u.id = ?1')
->setParameter(1, $editId)
->getQuery();
$p = $q->execute();
It's much safer to make all your values parameters instead:
$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
->set('u.username', '?1')
->set('u.email', '?2')
->where('u.id = ?3')
->setParameter(1, $username)
->setParameter(2, $email)
->setParameter(3, $editId)
->getQuery();
$p = $q->execute();
SET
SET @var_name = value
OR
SET @var := value
both operators = and := are accepted
SELECT
SELECT col1, @var_name := col2 from tb_name WHERE "conditon";
if multiple record sets found only the last value in col2 is keep (override);
SELECT col1, col2 INTO @var_name, col3 FROM .....
in this case the result of select is not containing col2 values
Ex both methods used
-- TRIGGER_BEFORE_INSERT --- setting a column value from calculations
...
SELECT count(*) INTO @NR FROM a_table WHERE a_condition;
SET NEW.ord_col = IFNULL( @NR, 0 ) + 1;
...
I just got this, and I'm on Xcode 7.2.1... It appeared when I downloaded iOS 9.3. Check your Project -> Base SDK and if it isn't the same or ahead of your device version, then that's the issue. I didn't see anything in the "Updates" section, but when I searched "Xcode" in the App Store it had an update for 7.3.
Upgrading to iOS 9.3 and Xcode 7.3 requires Mac OS X v10.11 (El Capitan) for Xcode to run, and that's why auto update isn't upgrading Xcode versions.
As DimtryB mentioned, by default the keystore is under the user directory. But if you are trying to update the cacerts
file, so that the JVM can pick the keys, then you will have to update the cacerts
file under jre/lib/security
. You can also view the keys by executing the command keytool -list -keystore cacerts
to see if your certificate is added.
Try this one -
SELECT *
FROM ...
WHERE EXISTS(SELECT 1
FROM sys.columns c
WHERE c.[object_id] = OBJECT_ID('dbo.Tags')
AND c.name = 'ModifiedByUser'
)
Dont use a foreach then. Use a 'for loop'. Your code is a bit messed up but you could do something like...
for (Int32 i = 0; i < dt_pattern.Rows.Count; i++)
{
double yATmax = ToDouble(dt_pattern.Rows[i+1]["Ampl"].ToString()) + AT;
}
Note you would have to take into account during the last row there will be no 'i+1' so you will have to use an if statement to catch that.
I had the error when using gpg-agent as my ssh-agent and using a gpg subkey as my ssh key https://wiki.archlinux.org/index.php/GnuPG#gpg-agent.
I suspect that the problem was caused by having an invalid pin entry tty for gpg caused by my sleep+lock command used in my sway config
bindsym $mod+Shift+l exec "sh -c 'gpg-connect-agent reloadagent /bye>/dev/null; systemctl suspend; swaylock'"
or just the sleep/suspend
Reset the pin entry tty to fix the problem
gpg-connect-agent updatestartuptty /bye > /dev/null
and the fix for my sway sleep+lock command:
bindsym $mod+Shift+l exec "sh -c 'gpg-connect-agent reloadagent /bye>/dev/null; systemctl suspend; swaylock; gpg-connect-agent updatestartuptty /bye > /dev/null'"
The classical answer that works in almost every environment is
SELECT ID, Name, blah, blah
FROM TableB TB
LEFT JOIN TableA TA
ON TB.ID=TA.ID
WHERE TA.ID IS NULL
sometimes NOT EXISTS may be not implemented (not working).
If you want to set the "1234" button, you need to use its "id":
document.getElementById("_1234").checked = true;
When you're using the browser API ("getElementById"), you don't use selector syntax; you just pass the actual "id" value you're looking for. You use selector syntax with jQuery or .querySelector()
and .querySelectorAll()
.
In the client side handle the click event of the button, use the ClientID property to get he id of the button:
$(document).ready(function() {
$("#<%=myButton.ClientID %>,#<%=muSecondButton.ClientID%>").click(
function() {
$.get("/myPage.aspx",{id:$(this).attr('id')},function(data) {
// do something with the data
return false;
}
});
});
In your page on the server:
protected void Page_Load(object sender,EventArgs e) {
// check if it is an ajax request
if (Request.Headers["X-Requested-With"] == "XMLHttpRequest") {
if (Request.QueryString["id"]==myButton.ClientID) {
// call the click event handler of the myButton here
Response.End();
}
if (Request.QueryString["id"]==mySecondButton.ClientID) {
// call the click event handler of the mySecondButton here
Response.End();
}
}
}
I find using str.format
much more elegant:
>>> '{0: <5}'.format('s')
's '
>>> '{0: <5}'.format('ss')
'ss '
>>> '{0: <5}'.format('sss')
'sss '
>>> '{0: <5}'.format('ssss')
'ssss '
>>> '{0: <5}'.format('sssss')
'sssss'
If you want to align the string to the right use >
instead of <
:
>>> '{0: >5}'.format('ss')
' ss'
Edit 1:
As mentioned in the comments: the 0
in '{0: <5}'
indicates the argument’s index passed to str.format()
.
Edit 2: In python3 one could use also f-strings:
sub_str='s'
for i in range(1,6):
s = sub_str*i
print(f'{s:>5}')
' s'
' ss'
' sss'
' ssss'
'sssss'
or:
for i in range(1,5):
s = sub_str*i
print(f'{s:<5}')
's '
'ss '
'sss '
'ssss '
'sssss'
of note, in some places above, ' '
(single quotation marks) were added to emphasize the width of the printed strings.
* {
transform: scale(1.1, 1.1)
}
this will transform every element on the page
1024 is appropriate for a wide variety of circumstances, although in practice you may see better performance with a larger or smaller buffer size.
This would depend on a number of factors including file system block size and CPU hardware.
It is also common to choose a power of 2 for the buffer size, since most underlying hardware is structured with fle block and cache sizes that are a power of 2. The Buffered classes allow you to specify the buffer size in the constructor. If none is provided, they use a default value, which is a power of 2 in most JVMs.
Regardless of which buffer size you choose, the biggest performance increase you will see is moving from nonbuffered to buffered file access. Adjusting the buffer size may improve performance slightly, but unless you are using an extremely small or extremely large buffer size, it is unlikely to have a signifcant impact.
In .NET 5 / C# 8:
You can write the code marked as the answer as:
public static class StringExtensions
{
public static string TrimLastCharacters(this string str) => string.IsNullOrEmpty(str) ? str : str.TrimEnd(str[^1]);
}
However, as mentioned in the answer, this removes all occurrences of that last character. If you only want to remove the last character you should instead do:
public static string RemoveLastCharacter(this string str) => string.IsNullOrEmpty(str) ? str : str[..^1];
A quick explanation for the new stuff in C# 8:
The ^
is called the "index from end operator". The ..
is called the "range operator". ^1
is a shortcut for arr.length - 1
. You can get all items after the first character of an array with arr[1..]
or all items before the last with arr[..^1]
. These are just a few quick examples. For more information, see https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8, "Indices and ranges" section.
i have same issue with react-native library called linear-gradient, but i think the problem caused by adding blank space between -L -L... here the screen of error
im trying all solution in this page, thank you for help
Using Bryan McLemore answer, I extended it to support objects that throw in a safe manor with the Swift 2.0 defer ability.
func synchronized( lock:AnyObject, block:() throws -> Void ) rethrows
{
objc_sync_enter(lock)
defer {
objc_sync_exit(lock)
}
try block()
}
What you should do is to check if activity is finishing before showing alert. For this purpose isFinishing()
method is defined within Activity class.
Here is what you should do:
if(!isFinishing())
{
alert.show();
}
I too had this problem when i was trying out Gelocation API. I then started IIS express through visual studio and then accessed the page and It worked without any issue in all browsers.
If you have a class that you use in an activity and you want to have access the ressource in that class, I recommend you to define a context as a private variable in class and initial it in constructor:
public class MyClass (){
private Context context;
public MyClass(Context context){
this.context=context;
}
public testResource(){
String s=context.getString(R.string.testString).toString();
}
}
Making an instant of class in your activity:
MyClass m=new MyClass(this);
try this:
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.io.IOUtils;
public class JsonParsing {
public static void main(String[] args) throws Exception {
InputStream is =
JsonParsing.class.getResourceAsStream( "sample-json.txt");
String jsonTxt = IOUtils.toString( is );
JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );
double coolness = json.getDouble( "coolness" );
int altitude = json.getInt( "altitude" );
JSONObject pilot = json.getJSONObject("pilot");
String firstName = pilot.getString("firstName");
String lastName = pilot.getString("lastName");
System.out.println( "Coolness: " + coolness );
System.out.println( "Altitude: " + altitude );
System.out.println( "Pilot: " + lastName );
}
}
and this is your sample-json.txt , should be in json format
{
'foo':'bar',
'coolness':2.0,
'altitude':39000,
'pilot':
{
'firstName':'Buzz',
'lastName':'Aldrin'
},
'mission':'apollo 11'
}
IE supports CSS expressions:
width:expression(document.body.clientWidth > 955 ? "955px": "100%" );
but they are not standard and are not portable across browsers. Avoid them if possible. They are deprecated since IE8.
You are allowed to use IDs that start with a digit in your HTML5 documents:
The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.
There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.
But querySelector
method uses CSS3 selectors for querying the DOM and CSS3 doesn't support ID selectors that start with a digit:
In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit.
Use a value like b22
for the ID attribute and your code will work.
Since you want to select an element by ID you can also use .getElementById
method:
document.getElementById('22')
Implement your adapter Filterable:
public class vJournalAdapter extends ArrayAdapter<JournalModel> implements Filterable{
private ArrayList<JournalModel> items;
private Context mContext;
....
then create your Filter class:
private class JournalFilter extends Filter{
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
List<JournalModel> allJournals = getAllJournals();
if(constraint == null || constraint.length() == 0){
result.values = allJournals;
result.count = allJournals.size();
}else{
ArrayList<JournalModel> filteredList = new ArrayList<JournalModel>();
for(JournalModel j: allJournals){
if(j.source.title.contains(constraint))
filteredList.add(j);
}
result.values = filteredList;
result.count = filteredList.size();
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.count == 0) {
notifyDataSetInvalidated();
} else {
items = (ArrayList<JournalModel>) results.values;
notifyDataSetChanged();
}
}
}
this way, your adapter is Filterable, you can pass filter item to adapter's filter and do the work. I hope this will be helpful.
Assume that we want to get a list of certain images from a PHP server using the POST method.
You have to provide two parameters in the form for the POST method. Here is how you are going to do.
app.controller('gallery-item', function ($scope, $http) {
var url = 'service.php';
var data = new FormData();
data.append("function", 'getImageList');
data.append('dir', 'all');
$http.post(url, data, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function (response) {
// This function handles success
console.log('angular:', response);
}, function (response) {
// this function handles error
});
});
I have tested it on my system and it works.
What about just using a global variable within your library, like so?
single.dart
:
library singleton;
var Singleton = new Impl();
class Impl {
int i;
}
main.dart
:
import 'single.dart';
void main() {
var a = Singleton;
var b = Singleton;
a.i = 2;
print(b.i);
}
Or is this frowned upon?
The singleton pattern is necessary in Java where the concept of globals doesn't exist, but it seems like you shouldn't need to go the long way around in Dart.
As mentioned above, you need the autoreload
extension. If you want it to automatically start every time you launch ipython
, you need to add it to the ipython_config.py
startup file:
It may be necessary to generate one first:
ipython profile create
Then include these lines in ~/.ipython/profile_default/ipython_config.py
:
c.InteractiveShellApp.exec_lines = []
c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')
As well as an optional warning in case you need to take advantage of compiled Python code in .pyc
files:
c.InteractiveShellApp.exec_lines.append('print "Warning: disable autoreload in ipython_config.py to improve performance." ')
edit: the above works with version 0.12.1 and 0.13
As other users explained here about the usage of allowoveride directive, which is used to give permission to .htaccess usage. one thing I want to point out that never use allowoverride all if other users have access to write .htaccess instead use allowoveride as to permit certain modules.
Such as AllowOverride AuthConfig mod_rewrite
Instead of
AllowOverride All
Because module like mod_mime can render your server side files as plain text.
You can try something like this:
Thread.getAllStackTraces().keySet().forEach((t) -> System.out.println(t.getName() + "\nIs Daemon " + t.isDaemon() + "\nIs Alive " + t.isAlive()));
and you can obviously get more thread characteristic if you need.
We need to remember that the {% endif %}
comes after the {% else %}
.
So this is an example:
{% if someTest %}
<p> Something is True </p>
{% else %}
<p> Something is False </p>
{% endif %}
Update - As stated in some of the comments, running
brew cleanup
could possibly fix this error, if that alone doesn't fix it, you might try upgrading individual packages or all your brew packages.
I just had this same problem. Upgrading Homebrew and then cleaning up worked for me. This error likely showed up for me because of a mismatch in package versions. None of the above solutions resolved my error, but running the following homebrew commands did.
Caution - This will upgrade all your brew packages, including, but not limited to PHP. If you only want to upgrade specific packages make sure to be specific.
brew upgrade // for upgrading all packages -- this is the command I used
brew upgrade {package} // for upgrading a specific package
and finally
brew cleanup
After two dozens of comments to understand the situation, it was found that the libhdf5.so.7
was actually a symlink (with several levels of indirection) to a file that was not shared between the queued processes and the interactive processes. This means even though the symlink itself lies on a shared filesystem, the contents of the file do not and as a result the process was seeing different versions of the library.
For future reference: other than checking LD_LIBRARY_PATH
, it's always a good idea to check a library with nm -D
to see if the symbols actually exist. In this case it was found that they do exist in interactive mode but not when run in the queue. A quick md5sum
revealed that the files were actually different.
<?php
echo preg_replace( '#<li[^>]+>#', '<li class="col-sm-4">',
wp_nav_menu(
array(
'menu' => $nav_menu,
'container' => false,
'container_class' => false,
'menu_class' => false,
'items_wrap' => '%3$s',
'depth' => 1,
'echo' => false
)
)
);
?>
you can also skip creating dictionary altogether. i used below approach to same problem .
mappedItems: {};
items.forEach(item => {
if (mappedItems[item.key]) {
mappedItems[item.key].push({productId : item.productId , price : item.price , discount : item.discount});
} else {
mappedItems[item.key] = [];
mappedItems[item.key].push({productId : item.productId , price : item.price , discount : item.discount}));
}
});
Join on one-to-many relation in JPQL looks as follows:
select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName
When several properties are specified in select
clause, result is returned as Object[]
:
Object[] temp = (Object[]) em.createNamedQuery("...")
.setParameter("groupName", groupName)
.getSingleResult();
String fname = (String) temp[0];
String lname = (String) temp[1];
By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table
to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:
@Entity @Table(name = "Users")
public class User implements Serializable { ... }
You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model
Post.objects.all().delete()
and to delete any Post with a future publication date
Post.objects.filter(pub_date__gt=datetime.now()).delete()
You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.
EDIT:
Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForm
s and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.
Solution without charts
Function SelectionToPicture(nome)
'save location ( change if you want )
FName = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\" & nome & ".jpg"
'copy selection and get size
Selection.CopyPicture xlScreen, xlBitmap
w = Selection.Width
h = Selection.Height
With ThisWorkbook.ActiveSheet
.Activate
Dim chtObj As ChartObject
Set chtObj = .ChartObjects.Add(100, 30, 400, 250)
chtObj.Name = "TemporaryPictureChart"
'resize obj to picture size
chtObj.Width = w
chtObj.Height = h
ActiveSheet.ChartObjects("TemporaryPictureChart").Activate
ActiveChart.Paste
ActiveChart.Export FileName:=FName, FilterName:="jpg"
chtObj.Delete
End With
End Function
jquery provides val()
function and not value()
. You can check empty string using jquery
if($('#person_data[document_type]').val() != ''){}
C++ provides a good mechanism to manage the life time of an object though class/struct constructs. This is one of the best features of C++ over other languages.
When you have member variables exposed through ref or pointer it violates the encapsulation in principle. This idiom enables the consumer of the class to change the state of an object of A without it(A) having any knowledge or control of it. It also enables the consumer to hold on to a ref/pointer to A's internal state, beyond the life time of the object of A. This is bad design. Instead the class could be refactored to hold a ref/pointer to the shared object (not own it) and these could be set using the constructor (Mandate the life time rules). The shared object's class may be designed to support multithreading/concurrency as the case may apply.
If it's installed with homebrew try just typing down mysql.server
in terminal and that should be it.
AFAIK it executable will be under /usr/local/bin/mysql.server.
If not you can always run following "locate mysql.server" which will tell you where to find such file.
Few things:
Why are your use-permissions and use-features tags in your activity tag. Generally, permissions are included as direct children of your <manifest>
tag. This could be part of the problem.
According to the android camera open documentation, a runtime exception is thrown:
if connection to the camera service fails (for example, if the camera is in use by another process or device policy manager has disabled the camera)
Have you tried checking if the camera is being used by something else or if your policy manager has some setting where the camera is turned off?
Don't forget the <uses-feature android:name="android.hardware.camera.autofocus" />
for autofocus.
While I'm not sure if any of these will directly help you, I think they're worth investigating if for no other reason than to simply rule out. Due diligence if you will.
EDIT
As mentioned in the comments below, the solution was to move the uses-permissions
up to above the application tag.
Yes, you need to specify the encoding of the file you want to read.
Yes, this means that you have to know the encoding of the file you want to read.
No, there is no general way to guess the encoding of any given "plain text" file.
The one-arguments constructors of FileReader
always use the platform default encoding which is generally a bad idea.
Since Java 11 FileReader
has also gained constructors that accept an encoding: new FileReader(file, charset)
and new FileReader(fileName, charset)
.
In earlier versions of java, you need to use new InputStreamReader(
new FileInputStream(pathToFile)
, <encoding>)
.
You can compile with either Cygwin's g++
or MinGW (via stand-alone or using Cygwin package). However, in order to run it, you need to add the Cygwin1.dll
(and others) PATH to the system Windows PATH, before any cygwin style paths.
Thus add: ;C:\cygwin64\bin
to the end of your Windows system PATH
variable.
Also, to compile for use in CMD or PowerShell, you may need to use:
x86_64-w64-mingw32-g++.exe -static -std=c++11 prog_name.cc -o prog_name.exe
(This invokes the cross-compiler, if installed.)
Alternative solution for rows of NA
s using janitor
package
myData %>% remove_empty("rows")
If you are willing to make use of C++11 std::async
and std::future
for running your tasks, then you can utilize the wait_for
function of std::future
to check if the thread is still running in a neat way like this:
#include <future>
#include <thread>
#include <chrono>
#include <iostream>
int main() {
using namespace std::chrono_literals;
/* Run some task on new thread. The launch policy std::launch::async
makes sure that the task is run asynchronously on a new thread. */
auto future = std::async(std::launch::async, [] {
std::this_thread::sleep_for(3s);
return 8;
});
// Use wait_for() with zero milliseconds to check thread status.
auto status = future.wait_for(0ms);
// Print status.
if (status == std::future_status::ready) {
std::cout << "Thread finished" << std::endl;
} else {
std::cout << "Thread still running" << std::endl;
}
auto result = future.get(); // Get result.
}
If you must use std::thread
then you can use std::promise
to get a future object:
#include <future>
#include <thread>
#include <chrono>
#include <iostream>
int main() {
using namespace std::chrono_literals;
// Create a promise and get its future.
std::promise<bool> p;
auto future = p.get_future();
// Run some task on a new thread.
std::thread t([&p] {
std::this_thread::sleep_for(3s);
p.set_value(true); // Is done atomically.
});
// Get thread status using wait_for as before.
auto status = future.wait_for(0ms);
// Print status.
if (status == std::future_status::ready) {
std::cout << "Thread finished" << std::endl;
} else {
std::cout << "Thread still running" << std::endl;
}
t.join(); // Join thread.
}
Both of these examples will output:
Thread still running
This is of course because the thread status is checked before the task is finished.
But then again, it might be simpler to just do it like others have already mentioned:
#include <thread>
#include <atomic>
#include <chrono>
#include <iostream>
int main() {
using namespace std::chrono_literals;
std::atomic<bool> done(false); // Use an atomic flag.
/* Run some task on a new thread.
Make sure to set the done flag to true when finished. */
std::thread t([&done] {
std::this_thread::sleep_for(3s);
done = true;
});
// Print status.
if (done) {
std::cout << "Thread finished" << std::endl;
} else {
std::cout << "Thread still running" << std::endl;
}
t.join(); // Join thread.
}
Edit:
There's also the std::packaged_task
for use with std::thread
for a cleaner solution than using std::promise
:
#include <future>
#include <thread>
#include <chrono>
#include <iostream>
int main() {
using namespace std::chrono_literals;
// Create a packaged_task using some task and get its future.
std::packaged_task<void()> task([] {
std::this_thread::sleep_for(3s);
});
auto future = task.get_future();
// Run task on new thread.
std::thread t(std::move(task));
// Get thread status using wait_for as before.
auto status = future.wait_for(0ms);
// Print status.
if (status == std::future_status::ready) {
// ...
}
t.join(); // Join thread.
}
I stumbled upon this today: Element.redraw() for prototype.js
Using:
Element.addMethods({
redraw: function(element){
element = $(element);
var n = document.createTextNode(' ');
element.appendChild(n);
(function(){n.parentNode.removeChild(n)}).defer();
return element;
}
});
However, I've noticed sometimes that you must call redraw() on the problematic element directly. Sometimes redrawing the parent element won't solve the problem the child is experiencing.
Good article about the way browsers render elements: Rendering: repaint, reflow/relayout, restyle
FWIW CloudFront supports streaming as well. Might be better than plain streaming from instances.
Same issue, go to App Store and update Xcode
Yes it's counter-intuitive and does not seem very pythonic, but it actually just mimics the unix API design, where these calld are C POSIX functions. Check man 3 popen
&& man 3 system
Somewhat more convenient snippet to replace os.system that I use:
from subprocess import (PIPE, Popen)
def invoke(command):
'''
Invoke command as a new system process and return its output.
'''
return Popen(command, stdout=PIPE, shell=True).stdout.read()
result = invoke('echo Hi, bash!')
# Result contains standard output (as you expected it in the first place).
you can create the folder using the following depending on your ansible version.
Latest version 2<
- name: Create Folder
file:
path: "{{project_root}}/conf"
recurse: yes
state: directory
Older version:
- name: Create Folder
file:
path="{{project_root}}/conf"
recurse: yes
state=directory
Refer - http://docs.ansible.com/ansible/latest/file_module.html
I you only want to see what was printed in the console you could simple add the "printed" part somewhere in your HTML so it will appear in on the webpage. You could do it for yourself, but there is a javascript file that does this for you. You can read about it here:
http://www.hnldesign.nl/work/code/mobileconsole-javascript-console-for-mobile-devices/
The code is available from Github; you can download it and paste it into a javascipt file and add it in to your HTML
Because of double print function. I suggest you to use return
instead of print
inside the function definition.
def lyrics():
return "The very first line"
print(lyrics())
OR
def lyrics():
print("The very first line")
lyrics()
it doesn't, however, solve the problem, because on e.g. open SUSE Tumbleweed, custom source build is triggering the same 401 error on default web page, which is configured accordingly with Indexes and
Require all granted
I encountered the exact same problem today, Ryan.
In my src (or your root) directory, my log4j.properties file now has the following addition
# https://issues.apache.org/jira/browse/AXIS2-4363
log4j.category.org.apache.axiom=WARN
Thanks for the heads up as to how to do this, Benjamin.
Modify Mysql encryption
ALTER USER 'lcherukuri'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
Nice shorthand for Multiple variable assignments
{% set label_cls, field_cls = "col-md-7", "col-md-3" %}
The following should do it:
$("input[type='checkbox']").click(function() {
var index = $(this).attr('name').substr(2);
$('table tr').each(function() {
$('td:eq(' + index + ')',this).toggle();
});
});
This is untested code, but the principle is that you choose the table cell in each row that corresponds to the chosen index extracted from the checkbox name. You could of course limit the selectors with a class or an ID.
It is simply possible with childElementCount
in pure javascript
var countItems = document.getElementsByTagName("ul")[0].childElementCount;_x000D_
console.log(countItems);
_x000D_
<div id="selected">_x000D_
<ul>_x000D_
<li>29</li>_x000D_
<li>16</li>_x000D_
<li>5</li>_x000D_
<li>8</li>_x000D_
<li>10</li>_x000D_
<li>7</li>_x000D_
</ul>_x000D_
</div>
_x000D_
We have one more option to do order by
public Cursor getlistbyrank(String rank) {
try {
//This can be used
return db.`query("tablename", null, null, null, null, null, rank +"DESC",null );
OR
return db.rawQuery("SELECT * FROM table order by rank", null);
} catch (SQLException sqle) {
Log.e("Exception on query:-", "" + sqle.getMessage());
return null;
}
}
You can use this two method for order
Had a similar issue in adding "Start Command Prompt with Ruby" to context menu as it involves passing parameters along with the patch of cmd. Followed a similar procedure as the solution above
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\*\shell\Cmd With Ruby]
@="Cmd With Ruby"
"Icon"="C:\\Windows\\System32\\cmd.exe"
[HKEY_CLASSES_ROOT\*\shell\Cmd With Ruby\command]
@="\"C:\\Windows\\System32\\cmd.exe\" \"/E:ON /K
\"C:\\Ruby25-x64\\bin\\setrbvars.cmd\"\" \"--cd=%1\"\""
[HKEY_CLASSES_ROOT\Directory\shell\bash]
@="Cmd With Ruby"
"Icon"="C:\\Windows\\System32\\cmd.exe"
[HKEY_CLASSES_ROOT\Directory\shell\bash\command]
@="\"C:\\Windows\\System32\\cmd.exe\" \"/E:ON /K
\"C:\\Ruby25-x64\\bin\\setrbvars.cmd\"\" \"--cd=%1\"\""
[HKEY_CLASSES_ROOT\Directory\Background\shell\bash]
@="Cmd With Ruby"
"Icon"="C:\\Windows\\System32\\cmd.exe"
[HKEY_CLASSES_ROOT\Directory\Background\shell\bash\command]
@="\"C:\\Windows\\System32\\cmd.exe\" \"/E:ON /K
\"C:\\Ruby25-x64\\bin\\setrbvars.cmd\"\" \"--cd=%v.\"\""
The following is an algorithm which gives correct but not totally precise since it does not take into account leap year. It also assumes 30 days in a month. A good usage for example is if someone lives in an address from 12/11/2010 to 11/10/2011, it can quickly tells that the person lives there for 10 months and 29 days. From 12/11/2010 to 11/12/2011 is 11 months and 1 day. For certain types of applications, that kind of precision is sufficient. This is for those types of applications because it aims for simplicity:
var datediff = function(start, end) {
var diff = { years: 0, months: 0, days: 0 };
var timeDiff = end - start;
if (timeDiff > 0) {
diff.years = end.getFullYear() - start.getFullYear();
diff.months = end.getMonth() - start.getMonth();
diff.days = end.getDate() - start.getDate();
if (diff.months < 0) {
diff.years--;
diff.months += 12;
}
if (diff.days < 0) {
diff.months = Math.max(0, diff.months - 1);
diff.days += 30;
}
}
return diff;
};
You can do it using jQuery. Example:
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$.ajax({
url : "next.php",
type: "POST",
data : "name=Denniss",
success: function(data)
{
//data - response from server
$('#response_div').html(data);
}
});
</script>
You can use Simpsons rule or the Trapezium rule to calculate the area under a graph given a table of y-values at a regular interval.
Python script that calculates Simpsons rule:
def integrate(y_vals, h):
i = 1
total = y_vals[0] + y_vals[-1]
for y in y_vals[1:-1]:
if i % 2 == 0:
total += 2 * y
else:
total += 4 * y
i += 1
return total * (h / 3.0)
h
is the offset (or gap) between y values, and y_vals
is an array of well, y values.
Example (In same file as above function):
y_values = [13, 45.3, 12, 1, 476, 0]
interval = 1.2
area = integrate(y_values, interval)
print("The area is", area)
I resolved this problem by renaming the DLL. The DLL had been manually renamed when it was uploaded to its shared location (a version number was appended to the file name). Removing the version number from the downloaded file resolved the issue.
In simple words:
var x = (day == "yes") ? "Good Day!" : (day == "no") ? "Good Night!" : "";
Here is a simple 3 step ES6 implementation using function binding in the parent constructor. This is the first way the official react tutorial recommends (there is also public class fields syntax not covered here). You can find all of this information here https://reactjs.org/docs/handling-events.html
Binding Parent Functions so Children Can Call Them (And pass data up to the parent! :D )
Parent Function
handleFilterApply(filterVals){}
Parent Constructor
this.handleFilterApply = this.handleFilterApply.bind(this);
Prop Passed to Child
onApplyClick = {this.handleFilterApply}
Child Event Call
onClick = {() => {props.onApplyClick(filterVals)}
In 2018 a lot of browsers support the Flexbox and Grid which are very powerful CSS display modes that overshine classical methods such as Faux Columns or Tabular Displays (which are treated later in this answer).
In order to implement this with the Grid, it is enough to specify display: grid and grid-template-columns on the container. The grid-template-columns depends on the number of columns you have, in this example I will use 3 columns, hence the property will look: grid-template-columns: auto auto auto, which basically means that each of the columns will have auto width.
Full working example with Grid:
html, body {_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
.grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: auto auto auto;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
.grid-item {_x000D_
padding: 20px;_x000D_
}_x000D_
_x000D_
.a {_x000D_
background-color: DarkTurquoise;_x000D_
}_x000D_
_x000D_
.b {_x000D_
background-color: LightSalmon;_x000D_
}_x000D_
_x000D_
.c {_x000D_
background-color: LightSteelBlue;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Three Columns with Grid</title>_x000D_
<link rel="stylesheet" type="text/css" href="style.css">_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="grid-container">_x000D_
<div class="grid-item a">_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis. Pellentesque accumsan nunc non arcu tincidunt auctor eget ut magna. In vel est egestas, ultricies dui a, gravida diam. Vivamus tempor facilisis lectus nec porta.</p>_x000D_
</div>_x000D_
<div class="grid-item b">_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis. Pellentesque accumsan nunc non arcu tincidunt auctor eget ut magna. In vel est egestas, ultricies dui a, gravida diam. Vivamus tempor facilisis lectus nec porta. Donec commodo elit mattis, bibendum turpis eu, malesuada nunc. Vestibulum sit amet dui tincidunt, mattis nisl et, tincidunt eros. Vivamus eu ultrices sapien. Integer leo arcu, lobortis sed tellus in, euismod ultricies massa. Mauris gravida quis ligula nec dignissim. Proin elementum mattis fringilla. Donec id malesuada orci, eu aliquam ipsum. Vestibulum fermentum elementum egestas. Quisque sit amet tempor mi.</p>_x000D_
</div>_x000D_
<div class="grid-item c">_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis.</p>_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
Another way would be to use the Flexbox by specifying display: flex on the container of the columns, and giving the columns a relevant width. In the example that I will be using, which is with 3 columns, you basically need to split 100% in 3, so it's 33.3333% (close enough, who cares about 0.00003333... which isn't visible anyway).
Full working example using Flexbox:
html, body {_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
.flex-container {_x000D_
display: flex;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
.flex-column {_x000D_
padding: 20px;_x000D_
width: 33.3333%;_x000D_
}_x000D_
_x000D_
.a {_x000D_
background-color: DarkTurquoise;_x000D_
}_x000D_
_x000D_
.b {_x000D_
background-color: LightSalmon;_x000D_
}_x000D_
_x000D_
.c {_x000D_
background-color: LightSteelBlue;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Three Columns with Flexbox</title>_x000D_
<link rel="stylesheet" type="text/css" href="style.css">_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="flex-container">_x000D_
<div class="flex-column a">_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis. Pellentesque accumsan nunc non arcu tincidunt auctor eget ut magna. In vel est egestas, ultricies dui a, gravida diam. Vivamus tempor facilisis lectus nec porta.</p>_x000D_
</div>_x000D_
<div class="flex-column b">_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis. Pellentesque accumsan nunc non arcu tincidunt auctor eget ut magna. In vel est egestas, ultricies dui a, gravida diam. Vivamus tempor facilisis lectus nec porta. Donec commodo elit mattis, bibendum turpis eu, malesuada nunc. Vestibulum sit amet dui tincidunt, mattis nisl et, tincidunt eros. Vivamus eu ultrices sapien. Integer leo arcu, lobortis sed tellus in, euismod ultricies massa. Mauris gravida quis ligula nec dignissim. Proin elementum mattis fringilla. Donec id malesuada orci, eu aliquam ipsum. Vestibulum fermentum elementum egestas. Quisque sit amet tempor mi.</p>_x000D_
</div>_x000D_
<div class="flex-column c">_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis.</p>_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
The Flexbox and Grid are supported by all major browsers since 2017/2018, fact also confirmed by caniuse.com: Can I use grid, Can I use flex.
There are also a number of classical solutions, used before the age of Flexbox and Grid, like OneTrueLayout Technique, Faux Columns Technique, CSS Tabular Display Technique and there is also a Layering Technique.
I do not recommend using these methods for they have a hackish nature and are not so elegant in my opinion, but it is good to know them for academic reasons.
A solution for equally height-ed columns is the CSS Tabular Display Technique that means to use the display:table feature. It works for Firefox 2+, Safari 3+, Opera 9+ and IE8.
The code for the CSS Tabular Display:
#container {_x000D_
display: table;_x000D_
background-color: #CCC;_x000D_
margin: 0 auto;_x000D_
}_x000D_
_x000D_
.row {_x000D_
display: table-row;_x000D_
}_x000D_
_x000D_
.col {_x000D_
display: table-cell;_x000D_
}_x000D_
_x000D_
#col1 {_x000D_
background-color: #0CC;_x000D_
width: 200px;_x000D_
}_x000D_
_x000D_
#col2 {_x000D_
background-color: #9F9;_x000D_
width: 300px;_x000D_
}_x000D_
_x000D_
#col3 {_x000D_
background-color: #699;_x000D_
width: 200px;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="rowWraper" class="row">_x000D_
<div id="col1" class="col">_x000D_
Column 1<br />Lorem ipsum<br />ipsum lorem_x000D_
</div>_x000D_
<div id="col2" class="col">_x000D_
Column 2<br />Eco cologna duo est!_x000D_
</div>_x000D_
<div id="col3" class="col">_x000D_
Column 3_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Even if there is a problem with the auto-expanding of the width of the table-cell it can be resolved easy by inserting another div withing the table-cell and giving it a fixed width. Anyway, the over-expanding of the width happens in the case of using extremely long words (which I doubt anyone would use a, let's say, 600px long word) or some div's who's width is greater than the table-cell's width.
The Faux Column Technique is the most popular classical solution to this problem, but it has some drawbacks such as, you have to resize the background tiled image if you want to resize the columns and it is also not an elegant solution.
The OneTrueLayout Technique consists of creating a padding-bottom of an extreme big height and cut it out by bringing the real border position to the "normal logical position" by applying a negative margin-bottom of the same huge value and hiding the extent created by the padding with overflow: hidden applied to the content wraper. A simplified example would be:
Working example:
.wraper {_x000D_
overflow: hidden; /* This is important */_x000D_
}_x000D_
_x000D_
.floatLeft {_x000D_
float: left;_x000D_
}_x000D_
_x000D_
.block {_x000D_
padding-left: 20px;_x000D_
padding-right: 20px;_x000D_
padding-bottom: 30000px; /* This is important */_x000D_
margin-bottom: -30000px; /* This is important */_x000D_
width: 33.3333%;_x000D_
box-sizing: border-box; /* This is so that the padding right and left does not affect the width */_x000D_
}_x000D_
_x000D_
.a {_x000D_
background-color: DarkTurquoise;_x000D_
}_x000D_
_x000D_
.b {_x000D_
background-color: LightSalmon;_x000D_
}_x000D_
_x000D_
.c {_x000D_
background-color: LightSteelBlue;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
<title>OneTrueLayout</title>_x000D_
</head>_x000D_
<body>_x000D_
<div class="wraper">_x000D_
<div class="block floatLeft a">_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras malesuada ipsum pretium tellus condimentum aliquam. Donec eget tempor mi, a consequat enim. Mauris a massa id nisl sagittis iaculis.</p>_x000D_
</div>_x000D_
<div class="block floatLeft b">_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras malesuada ipsum pretium tellus condimentum aliquam. Donec eget tempor mi, a consequat enim. Mauris a massa id nisl sagittis iaculis. Duis mattis diam vitae tellus ornare, nec vehicula elit luctus. In auctor urna ac ante bibendum, a gravida nunc hendrerit. Praesent sed pellentesque lorem. Nam neque ante, egestas ut felis vel, faucibus tincidunt risus. Maecenas egestas diam massa, id rutrum metus lobortis non. Sed quis tellus sed nulla efficitur pharetra. Fusce semper sapien neque. Donec egestas dolor magna, ut efficitur purus porttitor at. Mauris cursus, leo ac porta consectetur, eros quam aliquet erat, condimentum luctus sapien tellus vel ante. Vivamus vestibulum id lacus vel tristique.</p>_x000D_
</div>_x000D_
<div class="block floatLeft c">_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras malesuada ipsum pretium tellus condimentum aliquam. Donec eget tempor mi, a consequat enim. Mauris a massa id nisl sagittis iaculis. Duis mattis diam vitae tellus ornare, nec vehicula elit luctus. In auctor urna ac ante bibendum, a gravida nunc hendrerit.</p>_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
The Layering Technique must be a very neat solution that involves absolute positioning of div's withing a main relative positioned wrapper div. It basically consists of a number of child divs and the main div. The main div has imperatively position: relative to it's css attribute collection. The children of this div are all imperatively position:absolute. The children must have top and bottom set to 0 and left-right dimensions set to accommodate the columns with each another. For example if we have two columns, one of width 100px and the other one of 200px, considering that we want the 100px in the left side and the 200px in the right side, the left column must have {left: 0; right: 200px} and the right column {left: 100px; right: 0;}
In my opinion the unimplemented 100% height within an automated height container is a major drawback and the W3C should consider revising this attribute (which since 2018 is solvable with Flexbox and Grid).
Other resources: link1, link2, link3, link4, link5 (important)
These are the tools you see
Press the F12
This is how I delete files
if ((System.IO.File.Exists(fileName)))
{
System.IO.File.Delete(fileName);
}
Also make sure that the file name you are passing in your delete, is the accurate path
EDIT
You could use the following event instead as well or just use the code in this snippet and use in your method
void GridView1_SelectedIndexChanged(Object sender, EventArgs e)
{
// Get the currently selected row using the SelectedRow property.
GridViewRow row = CustomersGridView.SelectedRow;
//Debug this line and see what value is returned if it contains the full path.
//If it does not contain the full path then add the path to the string.
string fileName = row.Cells[0].Text
if(fileName != null || fileName != string.empty)
{
if((System.IO.File.Exists(fileName))
System.IO.File.Delete(fileName);
}
}
In XCode 7+ the location is now
/Applications/Xcode.app/Contents/Developer/Applications/Simulator.app
Run it from the command line
$ open -a Simulator
Hope that helps somebody
Make the DropDownStyle to DropDownList
stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
The answer posted above/earlier that was reported to replace CHAR(13)CHAR(10) carriage return:
REPLACE(REPLACE(REPLACE(MyField, CHAR(13) + CHAR(10), 'something else'), CHAR(13), 'something else'), CHAR(10), 'something else')
Will never get to the REPLACE(MyField, CHAR(13) + CHAR(10), 'something else')
portion of the code and will return the unwanted result of:
'something else''something else'
And NOT the desired result of a single:
'something else'
That would require the REPLACE script to be rewritten as such:
REPLACE(REPLACE(REPLACE(MyField, CHAR(10), 'something else'), CHAR(13), 'something else'), CHAR(13) + CHAR(10), 'something else')
As the flow first tests the 1st/Furthest Left REPLACE statement, then upon failure will continue to test the next REPLACE statement.
consider
data={'fld':'hello'}
now
jsonify(data)
will yield {'fld':'hello'} and
json.dumps(data)
gives
"<html><body><p>{'fld':'hello'}</p></body></html>"
Select Help->About
for 64 bit.. it would say version as 64 bit Edition.
I see this in IE 9.. may be true with lesser versions too..
None of these answers worked for me.
Instead, I had to use the Call command:
Call "\\Path To Program\Program.exe" <parameters>
I'm not sure this actually waits for completion... the C++ Redistributable I was installing went fast enough that it didn't matter
Actually I think OZ_ may be somewhat correct.
If you have the route '/users/:userId'
and navigate to '/users/'
(note the trailing /), $routeParams
in your controller should be an object containing userId: ""
in 1.1.5. So no the paramater userId
isn't completely ignored, but I think it's the best you're going to get.
Unblock multi-line comment
Ctrl+5
Multi-line comment
Ctrl+4
NOTE: For my version of Spyder (3.1.4) if I highlighted the entire multi-line comment and used Ctrl+5 the block remained commented out. Only after highlighting a small portion of the multi-line comment did Ctrl+5 work.
Evaluate
might suit:
http://www.mrexcel.com/forum/showthread.php?t=62067
Function Eval(Ref As String)
Application.Volatile
Eval = Evaluate(Ref)
End Function
You could also do this is plain in html with a meta tag:
<html>
<head>
<meta http-equiv="refresh" content="0;url=new.aspx" />
</head>
<body>
</body>
</html>
Comment This Line in gradle.properties
android.useAndroidX=true
I ended up finding MinimalistTelnet and adapted it to my uses. I ended up needing to be able to heavily modify the code due to the unique** device that I am attempting to attach to.
** Unique in this instance can be validly interpreted as brain-dead.
Classes that start with "apple-" plus classes that contain " apple-"
$("div[class^='apple-'],div[class*=' apple-']")
The C# and VB.NET compilers often generate different IL for operations that are apparently equivalent in both languages. It just so happens that C# does the "expected" thing when you write stringvar == null
, but VB.NET does not. To get the same effect in VB.NET you have to force true reference equality with the Is
operator.
Here's a very intuitive approach :
if 'property' in dir(a):
a.property
Did you set the bind option to allow remote access on the redis server?
Before (file /etc/redis/redis.conf
)
bind 127.0.0.1
After
bind 0.0.0.0
and run sudo service redis-server restart
to restart the server. If that's not the problem, you might want to check any firewalls that might block the access.
Important: If you don't use a firewall (iptables, ufw..) to control who connects to the port in use, ANYONE can connect to this Redis instance. Without using Redis' AUTH
that means anyone can access/change/delete your data. Be safe!
This is the Kotlin way:
In fragment_map.xml
you should have:
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
In your MapFragment.kt
you should have:
private fun setupMap() {
(childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?)!!.getMapAsync(this)
}
Call setupMap()
in onCreateView
.
Found the code that I referred to in my comment above. To test it, do this:
Sheet1
change the cell height and width of say A1
as shown in the snapshot below. Start Timer
button on the sheet and click on Assign Macros
. Select StartTimer
macro.End Timer
button on the sheet and click on Assign Macros
. Select EndTimer
macro.Now click on Start Timer button and you will see the time getting updated in cell A1
. To stop time updates, Click on End Timer button.
Code (TRIED AND TESTED)
Public Declare Function SetTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long, _
ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long
Public Declare Function KillTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long) As Long
Public TimerID As Long, TimerSeconds As Single, tim As Boolean
Dim Counter As Long
'~~> Start Timer
Sub StartTimer()
'~~ Set the timer for 1 second
TimerSeconds = 1
TimerID = SetTimer(0&, 0&, TimerSeconds * 1000&, AddressOf TimerProc)
End Sub
'~~> End Timer
Sub EndTimer()
On Error Resume Next
KillTimer 0&, TimerID
End Sub
Sub TimerProc(ByVal HWnd As Long, ByVal uMsg As Long, _
ByVal nIDEvent As Long, ByVal dwTimer As Long)
'~~> Update value in Sheet 1
Sheet1.Range("A1").Value = Time
End Sub
SNAPSHOT
The following should work:
var="pid: 1234"
var=${var:5}
Are you sure bash
is the shell executing your script?
Even the POSIX-compliant
var=${var#?????}
would be preferable to using an external process, although this requires you to hard-code the 5 in the form of a fixed-length pattern.
I think it may be worth mentioning that [ConditionalAttribute]
is in the System.Diagnostics;
namespace. I stumbled a bit when I got:
Error 2 The type or namespace name 'ConditionalAttribute' could not be found (are you missing a using directive or an assembly reference?)
after using it for the first time (I thought it would have been in System
).
you can simply use the get/set method for set the value
$("#select").select2("val"); //get the value
$("#select").select2("val", "CA"); //set the value
or you can do this:
$('#select').val("E").change(); // you must enter the Value instead of the string
I think this question has been pretty well answered, but I just wanted to add a method using Python 3.8 and the new assignment expression (walrus operator) since it is stylistically simple.
import socket
host = "127.0.0.1"
port = 31337
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen()
con, addr = s.accept()
msg_list = []
while (walrus_msg := con.recv(3)) != b'\r\n':
msg_list.append(walrus_msg)
print(msg_list)
In this case, 3 bytes are received from the socket and immediately assigned to walrus_msg
. Once the socket receives a b'\r\n'
it breaks the loop. walrus_msg
are added to a msg_list
and printed after the loop breaks. This script is basic but was tested and works with a telnet session.
NOTE: The parenthesis around the (walrus_msg := con.recv(3))
are needed. Without this, while walrus_msg := con.recv(3) != b'\r\n':
evaluates walrus_msg
to True
instead of the actual data on the socket.
I had this problem with a SOA system written in Java. I was running both the client and the server on different physical machines and they worked fine for a long time, then those nasty connection resets appeared in the client log and there wasn't anything strange in the server log. Restarting both client and server didn't solve the problem. Finally we discovered that the heap on the server side was rather full so we increased the memory available to the JVM: problem solved! Note that there was no OutOfMemoryError in the log: memory was just scarce, not exhausted.
Add a border
to the regular item, the same color
as the background
, so that it cannot be seen. That way the item has a border: 1px
whether it is being hovered or not.
am using this simple one
´´´´ class Connect {
public $url;
public $path;
public $username;
public $password;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, "$this->username:$this->password");
//PROPFIND request that lists all requested properties.
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PROPFIND");
$response = curl_exec($ch);
curl_close($ch);
You need the ip of the other pc and do:
scp user@ip_of_remote_pc:/home/user/stuff.php /Users/djorge/Desktop
it will ask you for 'user's password on the other pc.
npm ws was the answer for me. I found it less intrusive and more straight forward. With it was also trivial to mix websockets with rest services. Shared simple code on this post.
var WebSocketServer = require("ws").Server;
var http = require("http");
var express = require("express");
var port = process.env.PORT || 5000;
var app = express();
app.use(express.static(__dirname+ "/../"));
app.get('/someGetRequest', function(req, res, next) {
console.log('receiving get request');
});
app.post('/somePostRequest', function(req, res, next) {
console.log('receiving post request');
});
app.listen(80); //port 80 need to run as root
console.log("app listening on %d ", 80);
var server = http.createServer(app);
server.listen(port);
console.log("http server listening on %d", port);
var userId;
var wss = new WebSocketServer({server: server});
wss.on("connection", function (ws) {
console.info("websocket connection open");
var timestamp = new Date().getTime();
userId = timestamp;
ws.send(JSON.stringify({msgType:"onOpenConnection", msg:{connectionId:timestamp}}));
ws.on("message", function (data, flags) {
console.log("websocket received a message");
var clientMsg = data;
ws.send(JSON.stringify({msg:{connectionId:userId}}));
});
ws.on("close", function () {
console.log("websocket connection close");
});
});
console.log("websocket server created");
Run command rndc querylog on
or add querylog yes;
to options{};
section in named.conf
to activate that channel.
Also make sure you’re checking correct directory if your bind is chrooted.
In my case mysqlnd.so
extension had been installed. BUT i hadn't pdo_mysqlnd.so
. So, the problem had been solved by replacing pdo_mysql.so
with pdo_mysqlnd.so
.
You are incorrectly using the super
and this
keyword. Here is an example of how they work:
class Animal {
public name: string;
constructor(name: string) {
this.name = name;
}
move(meters: number) {
console.log(this.name + " moved " + meters + "m.");
}
}
class Horse extends Animal {
move() {
console.log(super.name + " is Galloping...");
console.log(this.name + " is Galloping...");
super.move(45);
}
}
var tom: Animal = new Horse("Tommy the Palomino");
Animal.prototype.name = 'horseee';
tom.move(34);
// Outputs:
// horseee is Galloping...
// Tommy the Palomino is Galloping...
// Tommy the Palomino moved 45m.
Explanation:
super.name
, this refers to the prototype chain of the object tom
, not the object tom
self. Because we have added a name property on the Animal.prototype
, horseee will be outputted.this.name
, the this
keyword refers to the the tom object itself. move
method of the Animal base class. This method is called from Horse class move method with the syntax super.move(45);
. Using the super
keyword in this context will look for a move
method on the prototype chain which is found on the Animal prototype.Remember TS still uses prototypes under the hood and the class
and extends
keywords are just syntactic sugar over prototypical inheritance.
The core problem is what you define line and whether end-on-line character sequence is part of the line or not. UNIX-based editors (such as VIM) or tools (such as Git) use EOL character sequence as line terminator, therefore it's a part of the line. It's similar to use of semicolon (;) in C and Pascal. In C semicolon terminates statements, in Pascal it separates them.
Kotlin has an one-liner
context.cacheDir.deleteRecursively()
What to do if :foo
in its natural form contains slashes? You wouldn't want it to Isn't that the distinction the recommendation is attempting to preserve? It specifically notes,
The similarity to unix and other disk operating system filename conventions should be taken as purely coincidental, and should not be taken to indicate that URIs should be interpreted as file names.
If one was building an online interface to a backup program, and wished to express the path as a part of the URL path, it would make sense to encode the slashes in the file path, as that is not really part of the hierarchy of the resource - and more importantly, the route. /backups/2016-07-28content//home/dan/
loses the root of the filesystem in the double slash. Escaping the slashes is the appropriate way to distinguish, as I read it.
It should be:
ClientThread hey = clients.get(clients.size() - 1);
clients.remove(hey);
Or you can do
clients.remove(clients.size() - 1);
The minus ones are because size() returns the number of elements, but the ArrayList's first element's index is 0 and not 1.
Not in bash (that I know of), but:
cp `ls | grep -v Music` /target_directory
I know this is not exactly what you were looking for, but it will solve your example.
request.user.get_username()
will return a string of the users email.
request.user.username
will return a method.
Paul Randal has an exccellent discussion of this problem on his blog: http://www.sqlskills.com/blogs/paul/post/backup-log-with-no_log-use-abuse-and-undocumented-trace-flags-to-stop-it.aspx
First Option:
OPEN package.json and add "--port port-no" in "serve" section.
Just like below, I have done it.
{
"name": "app-name",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve --port 8090",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
}
Second Option: If You want through command prompt
npm run serve --port 8090
To sum up. If we want to see if two pointers point to the same memory location we can do that. Also if we want to compare the contents of the memory pointed to by two pointers we can do that too, just remeber to dereference them first.
If we have
int *a = something;
int *b = something;
which are two pointers of the same type we can:
Compare memory address:
a==b
and compare contents:
*a==*b
You can convert the QString type to python string by just using the str
function. Assuming you are not using any Unicode characters you can get a python
string as below:
text = str(combobox1.currentText())
If you are using any unicode characters, you can do:
text = unicode(combobox1.currentText())
Strangely enough, none of these worked for me when building on a Nexus 7 running 4.4.2 (API 19). For the most part, at least with the latest version of Android Studio (1.2.1.1) after creating a blank activity app, the:
android:theme="@style/AppTheme"
is in the application element, not the activity element. If I removed the above code or tried to change it to:
android:theme="@android:style/Theme.Holo.Light.NoActionBar"
the app won't run...if this is happening to you, just go into your styles.xml file (res > values > styles.xml) and add the .NoTitleBar to the end of the parent like this block:
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"></style>
No changes to the AndroidManifest file are needed.
the css you are showing must be applied to a block element, like a div. So :
<div id="#rectangle"></div>
I ran into this error because I was trying to pass in a date from localStorage
. Passing the date into a new Date
object, and then calling .toISOString() did the trick for me:
const dateFromStorage = localStorage.getItem('someDate');
const date = new Date(dateFromStorage);
const momentDate = moment(date.toISOString());
This suppressed any warnings in the console.
Here is another simple way to do it
<a class="nav-link"
href='@Url.Action("Print1", "DeviceCertificates", new { Area = "Diagnostics"})\@Model.ID'>Print</a>
Where is @Model.ID
is a parameter
And here there is a second example.
<a class="nav-link"
href='@Url.Action("Print1", "DeviceCertificates", new { Area = "Diagnostics"})\@Model.ID?param2=ViewBag.P2¶m3=ViewBag.P3'>Print</a>
Use the String.replaceAll()
method in Java.
replaceAll should be good enough for your problem.
<a href="newsletter_01.pdf" target="_blank">Read more</a>
Target _blank will force the browser to open it in a new window
May be I am oversimplifying?
Just add the following code:
Open sFileName For Input as iFileNum
Line Input #iFileNum, dummy1
Line Input #iFileNum, dummy2
........
Sundar
Note that the ::first-letter
selector does not work with inline elements, so it must be either block
or inline-block
, as follows:
.m_title {display:inline-block}
.m_title:first-letter {text-transform: uppercase}
I had this error while trying to run an embedded system (using django of course) on a Raspberry Pi 2 (and not a VM)
Running this:
sudo pip install Django
Made the trick!
Not naturally, no... However, a googling of the thing gave this: http://phpjs.org/functions/isset:454
There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.
This can not have a variable:
create function Func() returns table
as
return
select 10 as ColName
You have to do like this instead:
create function Func()
returns @T table(ColName int)
as
begin
declare @Var int
set @Var = 10
insert into @T(ColName) values (@Var)
return
end
have all the pages in distinct div areas
<div style="" id="page1">
First Page Contents
</div>
<div style="display:none" id="page2">
Second Page Contents
</div>
then use a js script to workout what you are viewing (like within an hashtag style) to navigate. Either that, or ajax to get the response from a specific file (like /pages/page1.html
)
var $prehashval = "";
function loop()
{
if (location.hash.slice(1)!=$prehashval)
hashChanged();
$prehashval = location.hash.slice(1);
setTimeout("loop()", 100);
}
function hashChanged()
{
var $output;
switch (location.hash.slice(1))
{
case "page1":
document.getElementById('page1').style.display = "";
document.getElementById('page2').style.display = "none";
break;
case "page2":
document.getElementById('page1').style.display = "none";
document.getElementById('page2').style.display = "";
break;
default:
$output = location.hash.slice(1);
}
}
loop();
The second time you're referring to div2, you're not using the # id selector.
There's no element named div2.
Try element.getBoundingClientRect()
.
It will return an object with properties
Check that the width and height of the element's BoundingClientRect
are not zero which is the value of hidden or non-visible elements. If the values are greater than zero the element should be visible in the body. Then check if the bottom
property is less than screen.height
which would imply that the element is withing the viewport. (Technically you would also have to account for the top of the browser window including the searchbar, buttons, etc.)
view.setPadding(0,padding,0,0);
This will set the top padding to padding
-pixels.
If you want to set it in dp
instead, you can do a conversion:
float scale = getResources().getDisplayMetrics().density;
int dpAsPixels = (int) (sizeInDp*scale + 0.5f);