If both application have the same signature (meaning that both APPS are yours and signed with the same key), you can call your other app activity as follows:
Intent LaunchIntent = getActivity().getPackageManager().getLaunchIntentForPackage(CALC_PACKAGE_NAME);
startActivity(LaunchIntent);
Hope it helps.
The simplest solution to run two Python processes concurrently is to run them from a bash file, and tell each process to go into the background with the &
shell operator.
python script1.py &
python script2.py &
For a more controlled way to run many processes in parallel, look into the Supervisor project, or use the multiprocessing module to orchestrate from inside Python.
Not sure about elegant, but this ought to be pretty readable at least. For a sources.list it's fine to read all the lines before hand, for something larger you might want to change "in place" while looping through it.
#!/usr/bin/env python
# Open file for reading and writing
with open("sources.list", "r+") as sources_file:
# Read all the lines
lines = sources_file.readlines()
# Rewind and truncate
sources_file.seek(0)
sources_file.truncate()
# Loop through the lines, adding them back to the file.
for line in lines:
if line.startswith("# deb"):
sources_file.write(line[2:])
else:
sources_file.write(line)
EDIT: Use with
-statement for better file-handling. Also forgot to rewind before truncate before.
This code allows you to retrieve the content of the first paragraph of the page in plain text.
Parts of this answer come from here and thus here. See MediaWiki API documentation for more information.
// action=parse: get parsed text
// page=Baseball: from the page Baseball
// format=json: in json format
// prop=text: send the text content of the article
// section=0: top content of the page
$url = 'http://en.wikipedia.org/w/api.php?format=json&action=parse&page=Baseball&prop=text§ion=0';
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_USERAGENT, "TestScript"); // required by wikipedia.org server; use YOUR user agent with YOUR contact information. (otherwise your IP might get blocked)
$c = curl_exec($ch);
$json = json_decode($c);
$content = $json->{'parse'}->{'text'}->{'*'}; // get the main text content of the query (it's parsed HTML)
// pattern for first match of a paragraph
$pattern = '#<p>(.*)</p>#Us'; // http://www.phpbuilder.com/board/showthread.php?t=10352690
if(preg_match($pattern, $content, $matches))
{
// print $matches[0]; // content of the first paragraph (including wrapping <p> tag)
print strip_tags($matches[1]); // Content of the first paragraph without the HTML tags.
}
Since ant 1.9.1 you can use a if:set condition : https://ant.apache.org/manual/ifunless.html
I had similar issues. I had installed 32 bit version of Java on a 64 bit machine.
By uninstalling that version and installing 64 bit version of Java. I was able to resolve the issue.
Define this class and then set your text field to use the class and this automates the whole hiding keyboard when return is pressed automatically.
class TextFieldWithReturn: UITextField, UITextFieldDelegate
{
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
self.delegate = self
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
textField.resignFirstResponder()
return true
}
}
Then all you need to do in the storyboard is set the fields to use the class:
There's also a C standard built-in library to get command line arguments: getopt
You can check it on Wikipedia or in Argument-parsing helpers for C/Unix.
ILookup Interface is used in .net 3.5 with linq.
The HashTable is the base class that is weakly type; the DictionaryBase abstract class is stronly typed and uses internally a HashTable.
I found a a strange thing about Dictionary, when we add the multiple entries in Dictionary, the order in which the entries are added is maintained. Thus if I apply a foreach on the Dictionary, I will get the records in the same order I have inserted them.
Whereas, this is not true with normal HashTable, as when I add same records in Hashtable the order is not maintained. As far as my knowledge goes, Dictionary is based on Hashtable, if this is true, why my Dictionary maintains the order but HashTable does not?
As to why they behave differently, it's because Generic Dictionary implements a hashtable, but is not based on System.Collections.Hashtable. The Generic Dictionary implementation is based on allocating key-value-pairs from a list. These are then indexed with the hashtable buckets for random access, but when it returns an enumerator, it just walks the list in sequential order - which will be the order of insertion as long as entries are not re-used.
shiv govind Birlasoft.:)
Since -f
caused another problem, I developed another solution.
The -f
flag does not solved my problem because my onbuild
image looks for a file in a folder and had to call like this:
-f foo/bar/Dockerfile foo/bar
instead of
-f foo/bar/Dockerfile .
Also note that this is only solution for some cases as -f
flag
In my case I dropped the foreign key and I still could not drop the index. That was because there was yet another table that had a foreign key to this table on the same fields. After I dropped the foreign key on the other table I could drop the indexes on this table.
I do not know if this is relevant for anyone reading this, but I just had the problem that I wanted to
I wanted to do it with JRE classes only (no Apache Commons or similar). A quick web search did not show me sample code snippets doing both at the same time, only each task separately. Because this requires to read the same file twice, I figured it might be worth the while to write some code which unifies both tasks, calculating the checksum on the fly while downloading the file. This is my result (sorry if it is not perfect Java, but I guess you get the idea anyway):
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.security.DigestOutputStream; // new
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
void downloadFile(String fromURL, String toFile, BigInteger md5)
throws IOException, NoSuchAlgorithmException
{
ReadableByteChannel in = Channels.newChannel(new URL(fromURL).openStream());
MessageDigest md5Digest = MessageDigest.getInstance("MD5");
WritableByteChannel out = Channels.newChannel(
//new FileOutputStream(toFile)); // old
new DigestOutputStream(new FileOutputStream(toFile), md5Digest)); // new
ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024); // 1 MB
while (in.read(buffer) != -1) {
buffer.flip();
//md5Digest.update(buffer.asReadOnlyBuffer()); // old
out.write(buffer);
buffer.clear();
}
BigInteger md5Actual = new BigInteger(1, md5Digest.digest());
if (! md5Actual.equals(md5))
throw new RuntimeException(
"MD5 mismatch for file " + toFile +
": expected " + md5.toString(16) +
", got " + md5Actual.toString(16)
);
}
You can use the built-in forEach
function for arrays.
Like this:
//this sets all product descriptions to a max length of 10 characters
data.products.forEach( (element) => {
element.product_desc = element.product_desc.substring(0,10);
});
Your version wasn't wrong though. It should look more like this:
for(let i=0; i<data.products.length; i++){
console.log(data.products[i].product_desc); //use i instead of 0
}
Try this:
public void LoadData()
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Stocks;Integrated Security=True;Pooling=False");
SqlDataAdapter sda = new SqlDataAdapter("Select * From [Stocks].[dbo].[product]", con);
DataTable dt = new DataTable();
sda.Fill(dt);
DataGridView1.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = DataGridView1.Rows.Add();
DataGridView1.Rows[n].Cells[0].Value = item["ProductCode"].ToString();
DataGridView1.Rows[n].Cells[1].Value = item["Productname"].ToString();
DataGridView1.Rows[n].Cells[2].Value = item["qty"].ToString();
if ((bool)item["productstatus"])
{
DataGridView1.Rows[n].Cells[3].Value = "Active";
}
else
{
DataGridView1.Rows[n].Cells[3].Value = "Deactive";
}
Swift 3 & IOS 10.2
UIApplication.shared.open(URL(string: "http://www.stackoverflow.com")!, options: [:], completionHandler: nil)
Swift 3 & IOS 10.2
Below function to save files, just pass your base64 file, it return filename save it in DB.
import fs from 'fs';
const uuid = require('uuid/v1');
/*Download the base64 image in the server and returns the filename and path of image.*/
function saveImage(baseImage) {
/*path of the folder where your project is saved. (In my case i got it from config file, root path of project).*/
const uploadPath = "/home/documents/project";
//path of folder where you want to save the image.
const localPath = `${uploadPath}/uploads/images/`;
//Find extension of file
const ext = baseImage.substring(baseImage.indexOf("/")+1, baseImage.indexOf(";base64"));
const fileType = baseImage.substring("data:".length,baseImage.indexOf("/"));
//Forming regex to extract base64 data of file.
const regex = new RegExp(`^data:${fileType}\/${ext};base64,`, 'gi');
//Extract base64 data.
const base64Data = baseImage.replace(regex, "");
const filename = `${uuid()}.${ext}`;
//Check that if directory is present or not.
if(!fs.existsSync(`${uploadPath}/uploads/`)) {
fs.mkdirSync(`${uploadPath}/uploads/`);
}
if (!fs.existsSync(localPath)) {
fs.mkdirSync(localPath);
}
fs.writeFileSync(localPath+filename, base64Data, 'base64');
return filename;
}
If you return to a fragment from the back stack it does not re-create the fragment but re-uses the same instance and starts with onCreateView()
in the fragment lifecycle, see Fragment lifecycle.
So if you want to store state you should use instance variables and not rely on onSaveInstanceState()
.
Here is an example that replaces all instances of 1 or more white space characters in a column with an underscore using regular expression -
select distinct on (pd)
regexp_replace(rndc.pd, '\\s+', '_','g') as pd
from rndc14_ndc_mstr rndc;
I have just found ActiveSharp - Automatic INotifyPropertyChanged, I have yet to use it, but it looks good.
To quote from it's web site...
Send property change notifications without specifying property name as a string.
Instead, write properties like this:
public int Foo
{
get { return _foo; }
set { SetValue(ref _foo, value); } // <-- no property name here
}
Note that there is no need to include the name of the property as a string. ActiveSharp reliably and correctly figures that out for itself. It works based on the fact that your property implementation passes the backing field (_foo) by ref. (ActiveSharp uses that "by ref" call to identify which backing field was passed, and from the field it identifies the property).
Your returned format will be limited by the return type you declare. So yes, you can declare the property as a string and return the formatted value of something. In the "get" you can put whatever data retrieval code you need. So if you need to access some numeric value, simply put your return statement as:
private decimal _myDecimalValue = 15.78m;
public string MyFormattedValue
{
get { return _myDecimalValue.ToString("c"); }
private set; //makes this a 'read only' property.
}
Looking at Oracle's support site, it could be one of two things (may be #2 in your case, but including both).
Problem 1:
Enable administrative share for C$ (Please check with your System Admin to do this or See Microsoft document http://support.microsoft.com/kb/314984)
Check that it is ok:
Retry the installation
Problem 2: Remove the OracleRemExecService before doing the Oracle Client 12c Release 1 32-bit or 64-bit installation on the same Microsoft Windows x64 (64-bit) after installing the Oracle 64-bit or 32-bit software .
( This service is having a intelligence .Once someone tries to stop it this service gets deleted. This is due to the fact ,that this service is not running from the Oracle Home like other oracle services ,but from temp . For example : C:\Users\AppData\Local\Temp\oraremservi... )
Or you can do that with ES6 template literal:
<a :href="`/job/${r.id}`"
How about this?
if (element.hasClass("class1 class2")
I wanted to add an answer if the checkboxes are being generated in a loop. For example if your structure is like this (Assuming you are using server side constructs on your View
, like a foreach
loop):
<li id="checkboxlist" class="list-group-item card">
<div class="checkbox checkbox-inline">
<label><input type="checkbox" id="checkbox1">Checkbox 1</label>
<label><input type="checkbox" id="checkbox2">Checkbox 2</label>
</div>
</li>
<li id="checkboxlist" class="list-group-item card">
<div class="checkbox checkbox-inline">
<label><input type="checkbox" id="checkbox1">Checkbox 1</label>
<label><input type="checkbox" id="checkbox2">Checkbox 2</label>
</div>
</li>
Corresponding Jquery
:
$(".list-group-item").each(function (i, li) {
var currentli = $(li);
$(currentli).find("#checkbox1").on('change', function () {
$(currentli).find("#checkbox2").not(this).prop('checked',false);
});
$(currentli).find("#checkbox2").on('change', function () {
$(currentli).find("#checkbox1").not(this).prop('checked', false);
});
});
Working DEMO: https://jsfiddle.net/gr67qk20/
It's part of the Oracle analytic functions.
If you want to see python version then you should use py -V
instead of python -V
C:\Users\ghasan>py -V
Python 3.7.1
If you want to go to python's running environment then you should use py
instead of python
C:\Users\ghasan>py
Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:57:15) [MSC v.1915 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Here you can run the python program as:
print('Hello Python')
Hello Python
Well, goto
, but that is ugly, and not always possible. You can also place the loops into a method (or an anon-method) and use return
to exit back to the main code.
// goto
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 100; j++)
{
goto Foo; // yeuck!
}
}
Foo:
Console.WriteLine("Hi");
vs:
// anon-method
Action work = delegate
{
for (int x = 0; x < 100; x++)
{
for (int y = 0; y < 100; y++)
{
return; // exits anon-method
}
}
};
work(); // execute anon-method
Console.WriteLine("Hi");
Note that in C# 7 we should get "local functions", which (syntax tbd etc) means it should work something like:
// local function (declared **inside** another method)
void Work()
{
for (int x = 0; x < 100; x++)
{
for (int y = 0; y < 100; y++)
{
return; // exits local function
}
}
};
Work(); // execute local function
Console.WriteLine("Hi");
You can try this:
echo n | copy /-y <SOURCE> <DESTINATION>
-y
simply prompts before overwriting and we can pipe n to all those questions. So this would in essence just copy non-existing files. :)
In Java, you cannot set a value in ArrayList by assigning to it, there's a set()
method to call:
String a = words.get(0);
words.set(0, words.get(words.size() - 1));
words.set(words.size() - 1, a)
I use this query here to get all relevant info (relevant for me, at least :-)) from SQL Server:
SELECT
SERVERPROPERTY('productversion') as 'Product Version',
SERVERPROPERTY('productlevel') as 'Product Level',
SERVERPROPERTY('edition') as 'Product Edition',
SERVERPROPERTY('buildclrversion') as 'CLR Version',
SERVERPROPERTY('collation') as 'Default Collation',
SERVERPROPERTY('instancename') as 'Instance',
SERVERPROPERTY('lcid') as 'LCID',
SERVERPROPERTY('servername') as 'Server Name'
That gives you an output something like this:
Product Version Product Level Product Edition CLR Version
10.0.2531.0 SP1 Developer Edition (64-bit) v2.0.50727
Default Collation Instance LCID Server Name
Latin1_General_CI_AS NULL 1033 *********
JavaScript is case-sensitive. The b
in getElementbyId
should be capitalized.
var content = document.getElementById("edit").innerHTML;
Consider you have two tables.
MASTER TABLE
x------x--------------------x
| Id | Name |
x------x--------------------x
| 1 | A |
| 2 | B |
| 3 | C |
x------x--------------------x
DETAILS TABLE
x------x--------------------x-------x
| Id | PERIOD | QTY |
x------x--------------------x-------x
| 1 | 2014-01-13 | 10 |
| 1 | 2014-01-11 | 15 |
| 1 | 2014-01-12 | 20 |
| 2 | 2014-01-06 | 30 |
| 2 | 2014-01-08 | 40 |
x------x--------------------x-------x
There are many situations where we need to replace INNER JOIN
with CROSS APPLY
.
1. Join two tables based on TOP n
results
Consider if we need to select Id
and Name
from Master
and last two dates for each Id
from Details table
.
SELECT M.ID,M.NAME,D.PERIOD,D.QTY
FROM MASTER M
INNER JOIN
(
SELECT TOP 2 ID, PERIOD,QTY
FROM DETAILS D
ORDER BY CAST(PERIOD AS DATE)DESC
)D
ON M.ID=D.ID
The above query generates the following result.
x------x---------x--------------x-------x
| Id | Name | PERIOD | QTY |
x------x---------x--------------x-------x
| 1 | A | 2014-01-13 | 10 |
| 1 | A | 2014-01-12 | 20 |
x------x---------x--------------x-------x
See, it generated results for last two dates with last two date's Id
and then joined these records only in the outer query on Id
, which is wrong. This should be returning both Ids
1 and 2 but it returned only 1 because 1 has the last two dates. To accomplish this, we need to use CROSS APPLY
.
SELECT M.ID,M.NAME,D.PERIOD,D.QTY
FROM MASTER M
CROSS APPLY
(
SELECT TOP 2 ID, PERIOD,QTY
FROM DETAILS D
WHERE M.ID=D.ID
ORDER BY CAST(PERIOD AS DATE)DESC
)D
and forms the following result.
x------x---------x--------------x-------x
| Id | Name | PERIOD | QTY |
x------x---------x--------------x-------x
| 1 | A | 2014-01-13 | 10 |
| 1 | A | 2014-01-12 | 20 |
| 2 | B | 2014-01-08 | 40 |
| 2 | B | 2014-01-06 | 30 |
x------x---------x--------------x-------x
Here's how it works. The query inside CROSS APPLY
can reference the outer table, where INNER JOIN
cannot do this (it throws compile error). When finding the last two dates, joining is done inside CROSS APPLY
i.e., WHERE M.ID=D.ID
.
2. When we need INNER JOIN
functionality using functions.
CROSS APPLY
can be used as a replacement with INNER JOIN
when we need to get result from Master
table and a function
.
SELECT M.ID,M.NAME,C.PERIOD,C.QTY
FROM MASTER M
CROSS APPLY dbo.FnGetQty(M.ID) C
And here is the function
CREATE FUNCTION FnGetQty
(
@Id INT
)
RETURNS TABLE
AS
RETURN
(
SELECT ID,PERIOD,QTY
FROM DETAILS
WHERE ID=@Id
)
which generated the following result
x------x---------x--------------x-------x
| Id | Name | PERIOD | QTY |
x------x---------x--------------x-------x
| 1 | A | 2014-01-13 | 10 |
| 1 | A | 2014-01-11 | 15 |
| 1 | A | 2014-01-12 | 20 |
| 2 | B | 2014-01-06 | 30 |
| 2 | B | 2014-01-08 | 40 |
x------x---------x--------------x-------x
ADDITIONAL ADVANTAGE OF CROSS APPLY
APPLY
can be used as a replacement for UNPIVOT
. Either CROSS APPLY
or OUTER APPLY
can be used here, which are interchangeable.
Consider you have the below table(named MYTABLE
).
x------x-------------x--------------x
| Id | FROMDATE | TODATE |
x------x-------------x--------------x
| 1 | 2014-01-11 | 2014-01-13 |
| 1 | 2014-02-23 | 2014-02-27 |
| 2 | 2014-05-06 | 2014-05-30 |
| 3 | NULL | NULL |
x------x-------------x--------------x
The query is below.
SELECT DISTINCT ID,DATES
FROM MYTABLE
CROSS APPLY(VALUES (FROMDATE),(TODATE))
COLUMNNAMES(DATES)
which brings you the result
x------x-------------x
| Id | DATES |
x------x-------------x
| 1 | 2014-01-11 |
| 1 | 2014-01-13 |
| 1 | 2014-02-23 |
| 1 | 2014-02-27 |
| 2 | 2014-05-06 |
| 2 | 2014-05-30 |
| 3 | NULL |
x------x-------------x
Execute the command in this format:
ALTER [ COLUMN ] column { SET | DROP } NOT NULL
Android Studio Users:
If you want to use grade, go to http://search.maven.org/ and search for your maven repo. Then, click on the "latest version" and in the details page on the bottom left you will see "Gradle" where you can then copy/paste that link into your app's build.gradle.
I faced this problem when I copied my images (no matter JPEG or PNG) into the drawable folder manually. There might be different kinds of temporary solutions to this problem, but one best eternal way is to use the Drawable importer plugin for Android studio.
Install it by going to: menu File ? Settings ? Plugins ? Browse Repositories ? search "Drawable". You'll find Drawable importer as the first option. Click install on the right panel.
Use it by right clicking on the Drawable resource folder and then new. Now you can see four new options added to the bottom of the list, and among those you will find your appropriate option. In this case the "Batch drawable import" would do the trick.
Use $PSVersionTable.PSVersion
to determine the engine version. If the variable does not exist, it is safe to assume the engine is version 1.0
.
Note that $Host.Version
and (Get-Host).Version
are not reliable - they reflect
the version of the host only, not the engine. PowerGUI,
PowerShellPLUS, etc. are all hosting applications, and
they will set the host's version to reflect their product
version — which is entirely correct, but not what you're looking for.
PS C:\> $PSVersionTable.PSVersion
Major Minor Build Revision
----- ----- ----- --------
4 0 -1 -1
Building upon @Mark D's answer I would use web.config transforms to set all the various cookies to Secure. This includes setting anonymousIdentification cookieRequireSSL
and httpCookies requireSSL
.
To that end you'd setup your web.Release.config as:
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<system.web>
<httpCookies xdt:Transform="SetAttributes(httpOnlyCookies)" httpOnlyCookies="true" />
<httpCookies xdt:Transform="SetAttributes(requireSSL)" requireSSL="true" />
<anonymousIdentification xdt:Transform="SetAttributes(cookieRequireSSL)" cookieRequireSSL="true" />
</system.web>
</configuration>
If you're using Roles and Forms Authentication with the ASP.NET Membership Provider
(I know, it's ancient) you'll also want to set the roleManager cookieRequireSSL
and the forms requireSSL
attributes as secure too. If so, your web.release.config might look like this (included above plus new tags for membership API):
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<system.web>
<httpCookies xdt:Transform="SetAttributes(httpOnlyCookies)" httpOnlyCookies="true" />
<httpCookies xdt:Transform="SetAttributes(requireSSL)" requireSSL="true" />
<anonymousIdentification xdt:Transform="SetAttributes(cookieRequireSSL)" cookieRequireSSL="true" />
<roleManager xdt:Transform="SetAttributes(cookieRequireSSL)" cookieRequireSSL="true" />
<authentication>
<forms xdt:Transform="SetAttributes(requireSSL)" requireSSL="true" />
</authentication>
</system.web>
</configuration>
Background on web.config transforms here: http://go.microsoft.com/fwlink/?LinkId=125889
Obviously this goes beyond the original question of the OP but if you don't set them all to secure you can expect that a security scanning tool will notice and you'll see red flags appear on the report. Ask me how I know. :)
document.getElementById("tblBlah").rows[i].columns[j].innerHTML;
Should be:
document.getElementById("tblBlah").rows[i].cells[j].innerHTML;
But I get the distinct impression that the row/cell you need is the one clicked by the user. If so, the simplest way to achieve this would be attaching an event to the cells in your table:
function alertInnerHTML(e)
{
e = e || window.event;//IE
alert(this.innerHTML);
}
var theTbl = document.getElementById('tblBlah');
for(var i=0;i<theTbl.length;i++)
{
for(var j=0;j<theTbl.rows[i].cells.length;j++)
{
theTbl.rows[i].cells[j].onclick = alertInnerHTML;
}
}
That makes all table cells clickable, and alert it's innerHTML. The event object will be passed to the alertInnerHTML
function, in which the this
object will be a reference to the cell that was clicked. The event object offers you tons of neat tricks on how you want the click event to behave if, say, there's a link in the cell that was clicked, but I suggest checking the MDN and MSDN (for the window.event object)
according to this snippet i use this code and it's working fine:
using System;
using System.IO;
using System.IO.Compression;
using System.Text;
namespace CompressString
{
internal static class StringCompressor
{
/// <summary>
/// Compresses the string.
/// </summary>
/// <param name="text">The text.</param>
/// <returns></returns>
public static string CompressString(string text)
{
byte[] buffer = Encoding.UTF8.GetBytes(text);
var memoryStream = new MemoryStream();
using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Compress, true))
{
gZipStream.Write(buffer, 0, buffer.Length);
}
memoryStream.Position = 0;
var compressedData = new byte[memoryStream.Length];
memoryStream.Read(compressedData, 0, compressedData.Length);
var gZipBuffer = new byte[compressedData.Length + 4];
Buffer.BlockCopy(compressedData, 0, gZipBuffer, 4, compressedData.Length);
Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gZipBuffer, 0, 4);
return Convert.ToBase64String(gZipBuffer);
}
/// <summary>
/// Decompresses the string.
/// </summary>
/// <param name="compressedText">The compressed text.</param>
/// <returns></returns>
public static string DecompressString(string compressedText)
{
byte[] gZipBuffer = Convert.FromBase64String(compressedText);
using (var memoryStream = new MemoryStream())
{
int dataLength = BitConverter.ToInt32(gZipBuffer, 0);
memoryStream.Write(gZipBuffer, 4, gZipBuffer.Length - 4);
var buffer = new byte[dataLength];
memoryStream.Position = 0;
using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
{
gZipStream.Read(buffer, 0, buffer.Length);
}
return Encoding.UTF8.GetString(buffer);
}
}
}
}
You need to set the password for root@localhost
to be blank. There are two ways:
The MySQL SET PASSWORD
command:
SET PASSWORD FOR root@localhost=PASSWORD('');
Using the command-line mysqladmin
tool:
mysqladmin -u root -pCURRENTPASSWORD password ''
Based on few of the comments above, difference is I just used lambda
Executors.newFixedThreadPool(10, r -> new Thread(r, "my-threads-%d"))
I finally found my way through. In short, let's say your username is joe
and you hold a website under your personal filesystem /home/joe/path/to/website
.
You literally have to tell the system that nginx
is your pal.
Place nginx
in joe
group :
sudo gpasswd -a nginx joe
After that if it still doesn't work, check right access of /home/joe
directory. That's probably the reason why nginx can't reach the file because even if he is your friend now you have to open him the door to your house :
sudo chmod g+x /home/joe
That's it. That's literally all you have to do to give nginx access to your local files :)
I don't think there are security concerns with this method because nginx
is the high authority and only an admin can change the group. nginx
can now read what's in joe
directories. It's only a security breach if the holder of the nginx
account is different with the user you open directory access from, but in my case I'm the holder of both parties, that is in a local context.
I have a tip for those, who want to get various aggregated values from the same table.
Lets say I have table with users and table with points the users acquire. So the connection between them is 1:N (one user, many points records).
Now in the table 'points' I also store the information about for what did the user get the points (login, clicking a banner etc.). And I want to list all users ordered by SUM(points)
AND then by SUM(points WHERE type = x)
. That is to say ordered by all the points user has and then by points the user got for a specific action (eg. login).
The SQL would be:
SELECT SUM(points.points) AS points_all, SUM(points.points * (points.type = 7)) AS points_login
FROM user
LEFT JOIN points ON user.id = points.user_id
GROUP BY user.id
The beauty of this is in the SUM(points.points * (points.type = 7))
where the inner parenthesis evaluates to either 0 or 1 thus multiplying the given points value by 0 or 1, depending on wheteher it equals to the the type of points we want.
Unfortunately, it's not in the .NET Framework itself. My wish is that you could integrate with FileZilla, but I don't think it exposes an interface. They do have scripting I think, but it won't be as clean obviously.
I've used CuteFTP in a project which does SFTP. It exposes a COM component which I created a .NET wrapper around. The catch, you'll find, is permissions. It runs beautifully under the Windows credentials which installed CuteFTP, but running under other credentials requires permissions to be set in DCOM.
There is no way to create an array of a predefined size without also supplying values for the elements of that array.
The best way to initialize an array like that is array_fill
. By far preferable over the various loop-and-insert solutions.
$my_array = array_fill(0, $size_of_the_array, $some_data);
Every position in the $my_array
will contain $some_data
.
The first zero in array_fill
just indicates the index from where the array needs to be filled with the value.
function bytesToSize(bytes) {_x000D_
var sizes = ['B', 'K', 'M', 'G', 'T', 'P'];_x000D_
for (var i = 0; i < sizes.length; i++) {_x000D_
if (bytes <= 1024) {_x000D_
return bytes + ' ' + sizes[i];_x000D_
} else {_x000D_
bytes = parseFloat(bytes / 1024).toFixed(2)_x000D_
}_x000D_
}_x000D_
return bytes + ' P';_x000D_
}_x000D_
_x000D_
console.log(bytesToSize(234));_x000D_
console.log(bytesToSize(2043));_x000D_
console.log(bytesToSize(20433242));_x000D_
console.log(bytesToSize(2043324243));_x000D_
console.log(bytesToSize(2043324268233));_x000D_
console.log(bytesToSize(2043324268233343));
_x000D_
Look at the Subfloats section of http://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions.
\begin{figure}[htp]
\centering
\label{figur}\caption{equation...}
\subfloat[Subcaption 1]{\label{figur:1}\includegraphics[width=60mm]{explicit3185.eps}}
\subfloat[Subcaption 2]{\label{figur:2}\includegraphics[width=60mm]{explicit3183.eps}}
\\
\subfloat[Subcaption 3]{\label{figur:3}\includegraphics[width=60mm]{explicit1501.eps}}
\subfloat[Subcaption 4]{\label{figur:4}\includegraphics[width=60mm]{explicit23185.eps}}
\\
\subfloat[Subcaption 5]{\label{figur:5}\includegraphics[width=60mm]{explicit23183.eps}}
\subfloat[Subcaption 6]{\label{figur:6}\includegraphics[width=60mm]{explicit21501.eps}}
\end{figure}
Try
String[] splited = str.split("\\s");
http://download.oracle.com/javase/tutorial/essential/regex/pre_char_classes.html
Just call dict()
on the list of tuples directly
>>> my_list = [('a', 1), ('b', 2)]
>>> dict(my_list)
{'a': 1, 'b': 2}
You want to do the check for undefined
first. If you do it the other way round, it will generate an error if the array is undefined.
if (array === undefined || array.length == 0) {
// array empty or does not exist
}
This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null
values, other types of objects with a length
property, etc. It is also not very idiomatic JavaScript.
The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length
property.
if (!Array.isArray(array) || !array.length) {
// array does not exist, is not an array, or is empty
// ? do not attempt to process array
}
To break it down:
Array.isArray()
, unsurprisingly, checks whether its argument is an array. This weeds out values like null
, undefined
and anything else that is not an array.
Note that this will also eliminate array-like objects, such as the arguments
object and DOM NodeList
objects. Depending on your situation, this might not be the behavior you're after.
The array.length
condition checks whether the variable's length
property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0
or array.length !== 0
are not required here.
The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.
In those cases, I tend to go for the following, more idiomatic JavaScript:
if (!array || !array.length) {
// array or array.length are falsy
// ? do not attempt to process array
}
Or, more frequently, its inverse:
if (array && array.length) {
// array and array.length are truthy
// ? probably OK to process array
}
With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:
if (!array?.length) {
// array or array.length are falsy
// ? do not attempt to process array
}
Or the opposite:
if (array?.length) {
// array and array.length are truthy
// ? probably OK to process array
}
Use ObjectDataProvider:
<ObjectDataProvider x:Key="enumValues"
MethodName="GetValues" ObjectType="{x:Type System:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:ExampleEnum"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
and then bind to static resource:
ItemsSource="{Binding Source={StaticResource enumValues}}"
Find this solution at this blog
If the types can be directly cast this is the cleanest way to do it:
var target = yourList.ConvertAll(x => (TargetType)x);
If the types can't be directly cast then you can map the properties from the orginal type to the target type.
var target = yourList.ConvertAll(x => new TargetType { SomeValue = x.SomeValue });
If you are interested in understand performance, the best answer is to use a profiler.
Otherwise, System.Diagnostics.StopWatch provides a high resolution timer.
Unfortunately, there isn't a good way to browse for files with a JavaScript API. Fortunately, it's easy to create a file input in JavaScript, bind an event handler to its change
event, and simulate a user clicking on it. We can do this without modifications to the page itself:
$('<input type="file" multiple>').on('change', function () {
console.log(this.files);
}).click();
this.files
on the second line is an array that contains filename, timestamps, size, and type.
What worked for me was to import the project with "File -> New -> Project from Version Control" then choose your online source (GitHub for example). This way all the .gradle files were created in the import.
why not simply
new Date (timestamp);
A date is a date, the formatting of it is a different matter.
make sure your ftp transfers are in binary mode.
EventArgs e
is a parameter called e that contains the event data, see the EventArgs MSDN page for more information.
Object Sender
is a parameter called Sender that contains a reference to the control/object that raised the event.
Event Arg Class: http://msdn.microsoft.com/en-us/library/system.eventargs.aspx
Example:
protected void btn_Click (object sender, EventArgs e){
Button btn = sender as Button;
btn.Text = "clicked!";
}
Edit: When Button is clicked, the btn_Click event handler will be fired. The "object sender" portion will be a reference to the button which was clicked
There is no such thing as a byte or short literal. You need to cast to short using (short)100
First cast your Edit text like this:
TextView tekst = (TextView) findViewById(R.id.editText1);
tekst.setText(text);
And after that close the DB not befor this line...
myDataBaseHelper.close();
Try this:
<?php
$handle = fopen ("specialchars.csv","r");
echo '<table border="1"><tr><td>First name</td><td>Last name</td></tr><tr>';
while ($data = fgetcsv ($handle, 1000, ";")) {
$data = array_map("utf8_encode", $data); //added
$num = count ($data);
for ($c=0; $c < $num; $c++) {
// output data
echo "<td>$data[$c]</td>";
}
echo "</tr><tr>";
}
?>
You can easily use ng-show such as :
<div ng-repeater="item in items">
<div>{{item.description}}</div>
<div ng-show="isExists(item)">available</div>
<div ng-show="!isExists(item)">oh no, you don't have it</div>
</div>
For more complex tests, you can use ng-switch statements :
<div ng-repeater="item in items">
<div>{{item.description}}</div>
<div ng-switch on="isExists(item)">
<span ng-switch-when="true">Available</span>
<span ng-switch-default>oh no, you don't have it</span>
</div>
</div>
As others have mentioned, and counter to what the method name would imply, writelines
does not add line separators. This is a textbook case for a generator. Here is a contrived example:
def item_generator(things):
for item in things:
yield item
yield '\n'
def write_things_to_file(things):
with open('path_to_file.txt', 'wb') as f:
f.writelines(item_generator(things))
Benefits: adds newlines explicitly without modifying the input or output values or doing any messy string concatenation. And, critically, does not create any new data structures in memory. IO (writing to a file) is when that kind of thing tends to actually matter. Hope this helps someone!
Late to the game maybe but I stumbled upon this semantics issue while trying to make a REST API.
To expand a little on Wrikken's answer, I think you could use either 409 Conflict
or 403 Forbidden
depending on the situation - in short, use a 403 error when the user can do absolutely nothing to resolve the conflict and complete the request (e.g. they can't send a DELETE
request to explicitly remove the resource), or use 409 if something could possibly be done.
10.4.4 403 Forbidden
The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.
Nowadays, someone says "403" and a permissions or authentication issue comes to mind, but the spec says that it's basically the server telling the client that it's not going to do it, don't ask it again, and here's why the client shouldn't.
As for PUT
vs. POST
... POST
should be used to create a new instance of a resource when the user has no means to or shouldn't create an identifier for the resource. PUT
is used when the resource's identity is known.
9.6 PUT
...
The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request -- the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource. If the server desires that the request be applied to a different URI,
it MUST send a 301 (Moved Permanently) response; the user agent MAY then make its own decision regarding whether or not to redirect the request.
Use the with statement.
{% with total=business.employees.count %}
{{ total }} employee{{ total|pluralize }}
{% endwith %}
I can't imply the code in first paragraph in this answer. Maybe the template language had deprecated the old format.
Look at the ScriptManager.RegisterStartupScript method if you're using a ScriptManager or any Ajax controls/asynchronous postbacks.
Edit:
Actually, the function you want is probably ScriptManager.RegisterClientScriptBlock
you need to make county_ID
as index for the right frame:
frame_2.join ( frame_1.set_index( [ 'county_ID' ], verify_integrity=True ),
on=[ 'countyid' ], how='left' )
for your information, in pandas left join breaks when the right frame has non unique values on the joining column. see this bug.
so you need to verify integrity before joining by , verify_integrity=True
Redirect the output to DEVNULL:
import os
import subprocess
FNULL = open(os.devnull, 'w')
retcode = subprocess.call(['echo', 'foo'],
stdout=FNULL,
stderr=subprocess.STDOUT)
It is effectively the same as running this shell command:
retcode = os.system("echo 'foo' &> /dev/null")
Update: This answer applies to the original question relating to python 2.7. As of python >= 3.3 an official subprocess.DEVNULL
symbol was added.
retcode = subprocess.call(['echo', 'foo'],
stdout=subprocess.DEVNULL,
stderr=subprocess.STDOUT)
For me was a problem with Lombok, because it requires Annotation Processing to be enabled. You can find this checkbox on Settings > Build > Compiler > Annotation Processors
Edit: Warning! This answer worked on my XAMPP OsX environment, but when I deployed it to AWS EC2 it did NOT prevent the upload attempt.
I was tempted to delete this answer as it is WRONG But instead I will explain what tripped me up
My file upload field is named 'upload' so I was getting "The upload failed to upload.". This message comes from this line in validation.php:
in resources/lang/en/validaton.php:
'uploaded' => 'The :attribute failed to upload.',
And this is the message displayed when the file is larger than the limit set by PHP.
I want to over-ride this message, which you normally can do by passing a third parameter $messages array to Validator::make() method.
However I can't do that as I am calling the POST from a React Component, which renders the form containing the csrf field and the upload field.
So instead, as a super-dodgy-hack, I chose to get into my view that displays the messages and replace that specific message with my friendly 'file too large' message.
Here is what works if the file to smaller than the PHP file size limit:
In case anyone else is using Laravel FormRequest class, here is what worked for me on Laravel 5.7:
This is how I set a custom error message and maximum file size:
I have an input field <input type="file" name="upload">
. Note the CSRF token is required also in the form (google laravel csrf_field for what this means).
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class Upload extends FormRequest
{
...
...
public function rules() {
return [
'upload' => 'required|file|max:8192',
];
}
public function messages()
{
return [
'upload.required' => "You must use the 'Choose file' button to select which file you wish to upload",
'upload.max' => "Maximum file size to upload is 8MB (8192 KB). If you are uploading a photo, try to reduce its resolution to make it under 8MB"
];
}
}
I know this thread is a bit old, but it took me some time to get to the heart of this, so I wanted to share.
In my project, I had the main script in a parent directory, and, to differentiate the modules, I put all the supporting modules in a sub-folder called "modules". In my main script, I import these modules like this (for a module called report.py):
from modules.report import report, reportError
If I call my main script, this works. HOWEVER, I wanted to test each module by including a main()
in each, and calling each directly, as:
python modules/report.py
Now Python complains that it can't find "a module called modules". The key here is that, by default, Python includes the folder of the script in its search path, BUT NOT THE CWD. So what this error says, really, is "I can't find a modules subfolder". The is because there is no "modules" subdirectory from the directory where the report.py module resides.
I find that the neatest solution to this is to append the CWD in Python search path by including this at the top:
import sys
sys.path.append(".")
Now Python searches the CWD (current directory), finds the "modules" sub-folder, and all is well.
Here is the solution that I used inspired from the answer of sajib-khan. The default configuration is not set; it's my personal account on GitLab and the other specified is my company account. Here is what I did:
ssh-keygen -t rsa -f ~/.ssh/company -C "[email protected]"
nano ~/.ssh/config
Host company.gitlab.com
HostName gitlab.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/company
ssh-add -D
ssh -T [email protected]
Welcome to GitLab, @hugo.sohm!
ssh -T [email protected]
Welcome to GitLab, @HugoSohm!
Company account
git clone [email protected]:group/project.git
Personal/default account
git clone [email protected]:username/project.git
Here is the source that I used.
You could also use box-shadow
property with higher value of blur and rgba()
color to set opacity level.
Sounds like a better choice in your case.
box-shadow: 0 30px 40px rgba(0,0,0,.1);
Here's an example program that will send myfile.mp3 by streaming it from disk (that is, it doesn't read the whole file into memory before sending the file). The server listens on port 2000.
[Update] As mentioned by @Aftershock in the comments, util.pump
is gone and was replaced with a method on the Stream prototype called pipe
; the code below reflects this.
var http = require('http'),
fileSystem = require('fs'),
path = require('path');
http.createServer(function(request, response) {
var filePath = path.join(__dirname, 'myfile.mp3');
var stat = fileSystem.statSync(filePath);
response.writeHead(200, {
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size
});
var readStream = fileSystem.createReadStream(filePath);
// We replaced all the event handlers with a simple call to readStream.pipe()
readStream.pipe(response);
})
.listen(2000);
Taken from http://elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/
They are many ways to shutdown a spring application. One is to call close() on the ApplicationContext
:
ApplicationContext ctx =
SpringApplication.run(HelloWorldApplication.class, args);
// ...
ctx.close()
Your question suggest you want to close your application by doing Ctrl+C
, that is frequently used to terminate a command. In this case...
Use endpoints.shutdown.enabled=true
is not the best recipe. It means you expose an end-point to terminate your application. So, depending on your use case and your environment, you will have to secure it...
Ctrl+C
should work very well in your case. I assume your issue is caused by the ampersand (&) More explanation:
A Spring Application Context may have register a shutdown hook with the JVM runtime. See ApplicationContext documentation.
I don't know if Spring Boot configure this hook automatically as you said. I assume it is.
On Ctrl+C
, your shell sends an INT
signal to the foreground application. It means "please interrupt your execution". The application can trap this signal and do cleanup before its termination (the hook registered by Spring), or simply ignore it (bad).
nohup
is command that execute the following program with a trap to ignore the HUP signal. HUP is used to terminate program when you hang up (close your ssh connexion for example). Moreover it redirects outputs to avoid that your program blocks on a vanished TTY. nohup
does NOT ignore INT signal. So it does NOT prevent Ctrl+C
to work.
I assume your issue is caused by the ampersand (&), not by nohup. Ctrl+C
sends a signal to the foreground processes. The ampersand causes your application to be run in background. One solution: do
kill -INT pid
Use kill -9
or kill -KILL
is bad because the application (here the JVM) cannot trap it to terminate gracefully.
Another solution is to bring back your application in foreground. Then Ctrl+C
will work. Have a look on Bash Job control, more precisely on fg
.
If you are going to use any DDOS provider like Akamai, they have a maximum limitation of 8k in the response header size. So essentially try to limit your response header size below 8k.
By default the docker daemon always runs as the root user, therefore you need to prepend sudo
to your Docker command(s).
If you don’t want to use sudo when you use the docker command, create a Unix group called docker and add users to it. When the docker daemon starts, it makes the ownership of the Unix socket read/writable by the docker group.
Create the docker group.
$ sudo groupadd docker
Add your user to the docker group.
$ sudo usermod -aG docker $USER
Log out and log back in so that your group membership is re-evaluated.
Verify that you can docker commands without sudo.
$ docker run hello-world
This command downloads a test image and runs it in a container. When the container runs, it prints an informational message and exits.
The steps outlined above comes from the official Docker documentation.
There's no way to do this. See https://github.com/angular/angular.js/issues/263. Depending on what you're doing you can use a boolean to just not going into the body of the loop. Something like:
var keepGoing = true;
angular.forEach([0,1,2], function(count){
if(keepGoing) {
if(count == 1){
keepGoing = false;
}
}
});
Like codehead said, you'd have to iterate over the array indices instead of its elements. I prefer this variant over the C-style for
loop:
for my $i (0 .. $#x) {
print "$i: $x[$i]\n";
}
In some cases of which I can't remember why but $('#selectlist').val()
won't always return the correct item value, so I use $('#selectlist option:selected').val()
instead.
You can do as follows
1.Remove href
attribute from anchor(a
) tag
2.Set pointer cursor in css to ng click elements
[ng-click],
[data-ng-click],
[x-ng-click] {
cursor: pointer;
}
Handy one-liner
pkl() (
python -c 'import pickle,sys;d=pickle.load(open(sys.argv[1],"rb"));print(d)' "$1"
)
pkl my.pkl
Will print __str__
for the pickled object.
The generic problem of visualizing an object is of course undefined, so if __str__
is not enough, you will need a custom script.
Just a tip: Remember to put the code detection on document.ready, otherwise it might not work. That was my case.
How about tr {outline: thin solid black;}
? Works for me on tr or tbody elements, and appears to be compatible with the most browsers, including IE 8+ but not before.
You cannot initialize reference types by default other than null. You have to make them readonly. So this could work;
readonly MyStruct[] MyArray = new MyStruct[]{
new MyStruct{ label = "a", id = 1},
new MyStruct{ label = "b", id = 5},
new MyStruct{ label = "c", id = 1}
};
Both the field name and the value should be url encoded. format of the post data and query string are the same
The .net way of doing is something like this
NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(String.Empty);
outgoingQueryString.Add("field1","value1");
outgoingQueryString.Add("field2", "value2");
string postdata = outgoingQueryString.ToString();
This will take care of encoding the fields and the value names
I came here with the same Error, though one with a different origin.
It is caused by unsupported float index in 1.12.0 and newer numpy versions even if the code should be considered as valid.
An int
type is expected, not a np.float64
Solution: Try to install numpy 1.11.0
sudo pip install -U numpy==1.11.0.
I have a 2010 iMac with 8GB of RAM, running Eclipse Neon.2 Release (4.6.2) with Java 1.8.0_25. With the VM argument -Xmx6g, I ran the following code:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < Integer.MAX_VALUE; i++) {
try {
sb.append('a');
} catch (Throwable e) {
System.out.println(i);
break;
}
}
System.out.println(sb.toString().length());
This prints:
Requested array size exceeds VM limit
1207959550
So, it seems that the max array size is ~1,207,959,549. Then I realized that we don't actually care if Java runs out of memory: we're just looking for the maximum array size (which seems to be a constant defined somewhere). So:
for (int i = 0; i < 1_000; i++) {
try {
char[] array = new char[Integer.MAX_VALUE - i];
Arrays.fill(array, 'a');
String string = new String(array);
System.out.println(string.length());
} catch (Throwable e) {
System.out.println(e.getMessage());
System.out.println("Last: " + (Integer.MAX_VALUE - i));
System.out.println("Last: " + i);
}
}
Which prints:
Requested array size exceeds VM limit
Last: 2147483647
Last: 0
Requested array size exceeds VM limit
Last: 2147483646
Last: 1
Java heap space
Last: 2147483645
Last: 2
So, it seems the max is Integer.MAX_VALUE - 2, or (2^31) - 3
P.S. I'm not sure why my StringBuilder
maxed out at 1207959550
while my char[]
maxed out at (2^31)-3. It seems that AbstractStringBuilder
doubles the size of its internal char[]
to grow it, so that probably causes the issue.
use List<T>
. Internally it uses arrays and arrays do use contiguous memory.
If you want to make your PK auto increment, you need to set the ID column property for that primary key.
See the picture below for better understanding.
// My source is: http://techatplay.wordpress.com/2013/11/22/oracle-sql-developer-create-auto-incrementing-primary-key/
SELECT date_column_name FROM table_name WHERE EXTRACT(YEAR FROM date_column_name) = 2020
System.Diagnostics.ProcessStartInfo psi =
new System.Diagnostics.ProcessStartInfo(@"program_to_call.exe");
psi.RedirectStandardOutput = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi); ////
System.IO.StreamReader myOutput = proc.StandardOutput;
proc.WaitForExit(2000);
if (proc.HasExited)
{
string output = myOutput.ReadToEnd();
}
You can use Collections.list()
to convert an Enumeration
to a List
in one line:
List<T> list = Collections.list(enumeration);
There's no similar method to get a Set
, however you can still do it one line:
Set<T> set = new HashSet<T>(Collections.list(enumeration));
In Ruby 2.1.3 things have changed:
> endDate = Date.new(2014, 1, 2)
=> #<Date: 2014-01-02 ((2456660j,0s,0n),+0s,2299161j)>
> beginDate = Date.new(2014, 1, 1)
=> #<Date: 2014-01-01 ((2456659j,0s,0n),+0s,2299161j)>
> days = endDate - beginDate
=> (1/1)
> days.class
=> Rational
> days.to_i
=> 1
You can make an Embedded class
, which contains your two keys, and then have a reference to that class as EmbeddedId
in your Entity
.
You would need the @EmbeddedId
and @Embeddable
annotations.
@Entity
public class YourEntity {
@EmbeddedId
private MyKey myKey;
@Column(name = "ColumnA")
private String columnA;
/** Your getters and setters **/
}
@Embeddable
public class MyKey implements Serializable {
@Column(name = "Id", nullable = false)
private int id;
@Column(name = "Version", nullable = false)
private int version;
/** getters and setters **/
}
Another way to achieve this task is to use @IdClass
annotation, and place both your id
in that IdClass
. Now you can use normal @Id
annotation on both the attributes
@Entity
@IdClass(MyKey.class)
public class YourEntity {
@Id
private int id;
@Id
private int version;
}
public class MyKey implements Serializable {
private int id;
private int version;
}
I find git stash very useful for temporal handling of all 'dirty' states.
On the offchance that it's useful to anyone else, this will give you a comma-delimited list of the columns in each table:
SELECT table_name,GROUP_CONCAT(column_name ORDER BY ordinal_position)
FROM information_schema.columns
WHERE table_schema = DATABASE()
GROUP BY table_name
ORDER BY table_name
Note : When using tables with a high number of columns and/or with long field names, be aware of the group_concat_max_len limit, which can cause the data to get truncated.
Steps I followed for an overall dark theme including file browser:
Preferences
->Theme...
Adaptive.sublime-theme
I like the a.push.apply(a, b)
method described above, and if you want you can always create a library function like this:
Array.prototype.append = function(array)
{
this.push.apply(this, array)
}
and use it like this
a = [1,2]
b = [3,4]
a.append(b)
I don't know if this is really any different, but rather than iterate over the query cursor, you could do something like this:
query.exec(function (err, results){
if (err) res.writeHead(500, err.message)
else if (!results.length) res.writeHead(404);
else {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.write(JSON.stringify(results.map(function (msg){ return {msgId: msg.fileName}; })));
}
res.end();
});
I realize that this is from over 6 years ago. However, I think there is a solution that nobody here has mentioned that is way easier than regexing
function isAJSON(string) {
try {
JSON.parse(string)
} catch(e) {
if(e instanceof SyntaxError) return false;
};
return true;
}
To check if any module in a project is 'old':
npm outdated
'outdated' will check every module defined in package.json
and see if there is a newer version in the NPM registry.
For example, say xml2js 0.2.6
(located in node_modules
in the current project) is outdated because a newer version exists (0.2.7). You would see:
[email protected] node_modules/xml2js current=0.2.6
To update all dependencies, if you are confident this is desirable:
npm update
Or, to update a single dependency such as xml2js
:
npm update xml2js
You have an extra '{' before return type. You may also want to put '==' instead of '=' in if and else condition.
.NET 4.0+ has a generic Enum.TryParse
ContentEnum content;
Enum.TryParse(fileContentMessage, out content);
git remote add coworker git://path/to/coworkers/repo.git
git fetch coworker
git checkout --track coworker/foo
This will setup a local branch foo
, tracking the remote branch coworker/foo
. So when your co-worker has made some changes, you can easily pull them:
git checkout foo
git pull
Response to comments:
Cool :) And if I'd like to make my own changes to that branch, should I create a second local branch "bar" from "foo" and work there instead of directly on my "foo"?
You don't need to create a new branch, even though I recommend it. You might as well commit directly to foo
and have your co-worker pull your branch. But that branch already exists and your branch foo
need to be setup as an upstream branch to it:
git branch --set-upstream foo colin/foo
assuming colin
is your repository (a remote to your co-workers repository) defined in similar way:
git remote add colin git://path/to/colins/repo.git
When using with a reactive bootstrap table, i did not find that the
table.classname td {
syntax worked as there was no <table>
tag at all. Often modules like this don't use the outer tag but just dive right in maybe using <thead>
and <tbody>
for grouping at most.
Simply specifying like this worked great though
td.classname {
max-width: 500px;
text-overflow: initial;
white-space: wrap;
word-wrap: break-word;
}
as it directly overrides the <td>
and can be used only on the elements you want to change. Maybe in your case use
thead.medium td {
font-size: 40px;
}
tbody.small td {
font-size:25px;
}
for consistent font sizing with a bigger header.
In Java, the optimizations are usually done at the JVM level. At runtime, the JVM perform some "complicated" analysis to determine which methods to inline. It can be aggressive in inlining, and the Hotspot JVM actually can inline non-final methods.
The java compilers almost never inline any method call (the JVM does all of that at runtime). They do inline compile time constants (e.g. final static primitive values). But not methods.
For more resources:
Article: The Java HotSpot Performance Engine: Method Inlining Example
Wiki: Inlining in OpenJDK, not fully populated but contains links to useful discussions.
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
It's possible to have http://test_site.com and https://production_site.com. Then hardcoding the url is a bad idea. I would suggest this:
{{app.request.scheme ~ '://' ~ app.request.host ~ asset('bundle/myname/img/image.gif')}}
As of version 3.0.0, you can get the current route by calling:
this.context.router.location.pathname
Sample code is below:
var NavLink = React.createClass({
contextTypes: {
router: React.PropTypes.object
},
render() {
return (
<Link {...this.props}></Link>
);
}
});
As per Jenkins Documentation,
BUILD_NUMBER
is used. This number is identify how many times jenkins run this build process
$BUILD_NUMBER
is general syntax for it.
Inside single quotes everything is preserved literally, without exception.
That means you have to close the quotes, insert something, and then re-enter again.
'before'"$variable"'after'
'before'"'"'after'
'before'\''after'
Word concatenation is simply done by juxtaposition. As you can verify, each of the above lines is a single word to the shell. Quotes (single or double quotes, depending on the situation) don't isolate words. They are only used to disable interpretation of various special characters, like whitespace, $
, ;
... For a good tutorial on quoting see Mark Reed's answer. Also relevant: Which characters need to be escaped in bash?
You should absolutely avoid building shell commands by concatenating variables. This is a bad idea similar to concatenation of SQL fragments (SQL injection!).
Usually it is possible to have placeholders in the command, and to supply the command together with variables so that the callee can receive them from the invocation arguments list.
For example, the following is very unsafe. DON'T DO THIS
script="echo \"Argument 1 is: $myvar\""
/bin/sh -c "$script"
If the contents of $myvar
is untrusted, here is an exploit:
myvar='foo"; echo "you were hacked'
Instead of the above invocation, use positional arguments. The following invocation is better -- it's not exploitable:
script='echo "arg 1 is: $1"'
/bin/sh -c "$script" -- "$myvar"
Note the use of single ticks in the assignment to script
, which means that it's taken literally, without variable expansion or any other form of interpretation.
Use is_null or ===
operator.
is_null($result['column'])
$result['column'] === NULL
Don't use delete as it won't remove an element from an array it will only set it as undefined, which will then not be reflected correctly in the length of the array.
If you know the key you should use splice i.e.
myArray.splice(key, 1);
For someone in Steven's position you can try something like this:
for (var key in myArray) {
if (key == 'bar') {
myArray.splice(key, 1);
}
}
or
for (var key in myArray) {
if (myArray[key] == 'bar') {
myArray.splice(key, 1);
}
}
It is working, but it wont modify the caller object, but returning a new String.
So you just need to assign it to a new String variable, or to itself:
string = string.replace("to", "xyz");
or
String newString = string.replace("to", "xyz");
API Docs
public String replace (CharSequence target, CharSequence replacement)
Since: API Level 1
Copies this string replacing occurrences of the specified target sequence with another sequence. The string is processed from the beginning to the end.
Parameters
target
the sequence to replace.replacement
the replacement
sequence.Returns the resulting string.
Throws NullPointerException
if target or replacement is null.
>>> s = "123mango abcd mango kiwi peach"
>>> s.split("mango", 1)
['123', ' abcd mango kiwi peach']
>>> s.split("mango", 1)[1]
' abcd mango kiwi peach'
My solution uses onTouchListener
but doesn't restricts from its use. It creates a wrapper for onTouchListener
if necessary where setup onItemSelectedListener
.
public class Spinner extends android.widget.Spinner {
/* ...constructors... */
private OnTouchListener onTouchListener;
private OnItemSelectedListener onItemSelectedListener;
@Override
public void setOnItemSelectedListener(OnItemSelectedListener listener) {
onItemSelectedListener = listener;
super.setOnTouchListener(wrapTouchListener(onTouchListener, onItemSelectedListener));
}
@Override
public void setOnTouchListener(OnTouchListener listener) {
onTouchListener = listener;
super.setOnTouchListener(wrapTouchListener(onTouchListener, onItemSelectedListener));
}
private OnTouchListener wrapTouchListener(final OnTouchListener onTouchListener, final OnItemSelectedListener onItemSelectedListener) {
return onItemSelectedListener != null ? new OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
Spinner.super.setOnItemSelectedListener(onItemSelectedListener);
return onTouchListener != null && onTouchListener.onTouch(view, motionEvent);
}
} : onTouchListener;
}
}
I faced the same problem but I was using Lombok and my UploadFileResponse pojo was a builder.
public ResponseEntity<UploadFileResponse>
To solve I added @Getter annotation:
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Getter
public class UploadFileResponse
Like this:
String versionRelease = BuildConfig.VERSION_NAME;
versionRelease :- 2.1.17
Please make sure your import package is correct ( import package your_application_package_name
, otherwise it will not work properly).
You can also use the computeIfAbsent()
method in the HashMap
class.
In the following example, map
stores a list of transactions (integers) that are applied to the key (the name of the bank account). To add 2 transactions of 100
and 200
to checking_account
you can write:
HashMap<String, ArrayList<Integer>> map = new HashMap<>();
map.computeIfAbsent("checking_account", key -> new ArrayList<>())
.add(100)
.add(200);
This way you don't have to check to see if the key checking_account
exists or not.
computeIfAbsent()
. Really elegant!
The 2nd line should be written as:
$form.append('<input type="button" value="button">');
The absolute divs are taken out of the flow of the document so the containing div does not have any content except for the padding. Give #box a height to fill it out.
#box {
background-color: #000;
position: relative;
padding: 10px;
width: 220px;
height:30px;
}
For Me This worked Perfectly Convert(varchar(8),DATEADD(SECOND,DATEDIFF(SECOND,LogInTime,LogOutTime),0),114)
and the Output is HH:MM:SS which is shown accurately in my case.
Note: there is no guarantee this code will work in future versions of the .Net framework. Using private .Net framework internals as done here through reflection is probably not good overall. Use the interop solution mentioned at the bottom, as the Windows API is less likely to change.
If you are looking for a Folder picker that looks more like the Windows 7 dialog, with the ability to copy and paste from a textbox at the bottom and the navigation pane on the left with favorites and common locations, then you can get access to that in a very lightweight way.
The FolderBrowserDialog UI is very minimal:
But you can have this instead:
Here's a class that opens a Vista-style folder picker using the .Net private IFileDialog
interface, without directly using interop in the code (.Net takes care of that for you). It falls back to the pre-Vista dialog if not in a high enough Windows version. Should work in Windows 7, 8, 9, 10 and higher (theoretically).
using System;
using System.Reflection;
using System.Windows.Forms;
namespace MyCoolCompany.Shuriken {
/// <summary>
/// Present the Windows Vista-style open file dialog to select a folder. Fall back for older Windows Versions
/// </summary>
public class FolderSelectDialog {
private string _initialDirectory;
private string _title;
private string _fileName = "";
public string InitialDirectory {
get { return string.IsNullOrEmpty(_initialDirectory) ? Environment.CurrentDirectory : _initialDirectory; }
set { _initialDirectory = value; }
}
public string Title {
get { return _title ?? "Select a folder"; }
set { _title = value; }
}
public string FileName { get { return _fileName; } }
public bool Show() { return Show(IntPtr.Zero); }
/// <param name="hWndOwner">Handle of the control or window to be the parent of the file dialog</param>
/// <returns>true if the user clicks OK</returns>
public bool Show(IntPtr hWndOwner) {
var result = Environment.OSVersion.Version.Major >= 6
? VistaDialog.Show(hWndOwner, InitialDirectory, Title)
: ShowXpDialog(hWndOwner, InitialDirectory, Title);
_fileName = result.FileName;
return result.Result;
}
private struct ShowDialogResult {
public bool Result { get; set; }
public string FileName { get; set; }
}
private static ShowDialogResult ShowXpDialog(IntPtr ownerHandle, string initialDirectory, string title) {
var folderBrowserDialog = new FolderBrowserDialog {
Description = title,
SelectedPath = initialDirectory,
ShowNewFolderButton = false
};
var dialogResult = new ShowDialogResult();
if (folderBrowserDialog.ShowDialog(new WindowWrapper(ownerHandle)) == DialogResult.OK) {
dialogResult.Result = true;
dialogResult.FileName = folderBrowserDialog.SelectedPath;
}
return dialogResult;
}
private static class VistaDialog {
private const string c_foldersFilter = "Folders|\n";
private const BindingFlags c_flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
private readonly static Assembly s_windowsFormsAssembly = typeof(FileDialog).Assembly;
private readonly static Type s_iFileDialogType = s_windowsFormsAssembly.GetType("System.Windows.Forms.FileDialogNative+IFileDialog");
private readonly static MethodInfo s_createVistaDialogMethodInfo = typeof(OpenFileDialog).GetMethod("CreateVistaDialog", c_flags);
private readonly static MethodInfo s_onBeforeVistaDialogMethodInfo = typeof(OpenFileDialog).GetMethod("OnBeforeVistaDialog", c_flags);
private readonly static MethodInfo s_getOptionsMethodInfo = typeof(FileDialog).GetMethod("GetOptions", c_flags);
private readonly static MethodInfo s_setOptionsMethodInfo = s_iFileDialogType.GetMethod("SetOptions", c_flags);
private readonly static uint s_fosPickFoldersBitFlag = (uint) s_windowsFormsAssembly
.GetType("System.Windows.Forms.FileDialogNative+FOS")
.GetField("FOS_PICKFOLDERS")
.GetValue(null);
private readonly static ConstructorInfo s_vistaDialogEventsConstructorInfo = s_windowsFormsAssembly
.GetType("System.Windows.Forms.FileDialog+VistaDialogEvents")
.GetConstructor(c_flags, null, new[] { typeof(FileDialog) }, null);
private readonly static MethodInfo s_adviseMethodInfo = s_iFileDialogType.GetMethod("Advise");
private readonly static MethodInfo s_unAdviseMethodInfo = s_iFileDialogType.GetMethod("Unadvise");
private readonly static MethodInfo s_showMethodInfo = s_iFileDialogType.GetMethod("Show");
public static ShowDialogResult Show(IntPtr ownerHandle, string initialDirectory, string title) {
var openFileDialog = new OpenFileDialog {
AddExtension = false,
CheckFileExists = false,
DereferenceLinks = true,
Filter = c_foldersFilter,
InitialDirectory = initialDirectory,
Multiselect = false,
Title = title
};
var iFileDialog = s_createVistaDialogMethodInfo.Invoke(openFileDialog, new object[] { });
s_onBeforeVistaDialogMethodInfo.Invoke(openFileDialog, new[] { iFileDialog });
s_setOptionsMethodInfo.Invoke(iFileDialog, new object[] { (uint) s_getOptionsMethodInfo.Invoke(openFileDialog, new object[] { }) | s_fosPickFoldersBitFlag });
var adviseParametersWithOutputConnectionToken = new[] { s_vistaDialogEventsConstructorInfo.Invoke(new object[] { openFileDialog }), 0U };
s_adviseMethodInfo.Invoke(iFileDialog, adviseParametersWithOutputConnectionToken);
try {
int retVal = (int) s_showMethodInfo.Invoke(iFileDialog, new object[] { ownerHandle });
return new ShowDialogResult {
Result = retVal == 0,
FileName = openFileDialog.FileName
};
}
finally {
s_unAdviseMethodInfo.Invoke(iFileDialog, new[] { adviseParametersWithOutputConnectionToken[1] });
}
}
}
// Wrap an IWin32Window around an IntPtr
private class WindowWrapper : IWin32Window {
private readonly IntPtr _handle;
public WindowWrapper(IntPtr handle) { _handle = handle; }
public IntPtr Handle { get { return _handle; } }
}
}
}
I developed this as a cleaned up version of .NET Win 7-style folder select dialog by Bill Seddon of lyquidity.com (I have no affiliation). I wrote my own because his solution requires an additional Reflection class that isn't needed for this focused purpose, uses exception-based flow control, doesn't cache the results of its reflection calls. Note that the nested static VistaDialog
class is so that its static reflection variables don't try to get populated if the Show
method is never called.
It is used like so in a Windows Form:
var dialog = new FolderSelectDialog {
InitialDirectory = musicFolderTextBox.Text,
Title = "Select a folder to import music from"
};
if (dialog.Show(Handle)) {
musicFolderTextBox.Text = dialog.FileName;
}
You can of course play around with its options and what properties it exposes. For example, it allows multiselect in the Vista-style dialog.
Also, please note that Simon Mourier gave an answer that shows how to do the exact same job using interop against the Windows API directly, though his version would have to be supplemented to use the older style dialog if in an older version of Windows. Unfortunately, I hadn't found his post yet when I worked up my solution. Name your poison!
If you're trying to do it in a Xamarin Forms PCL project, the above solutions using IsAssignableFrom
gives an error:
Error: 'Type' does not contain a definition for 'IsAssignableFrom' and no extension method 'IsAssignableFrom' accepting a first argument of type 'Type' could be found (are you missing a using directive or an assembly reference?)
because IsAssignableFrom
asks for a TypeInfo
object.
You can use the GetTypeInfo()
method from System.Reflection
:
typeof(BaseClass).GetTypeInfo().IsAssignableFrom(typeof(unknownType).GetTypeInfo())
To get current date/time in javascript:
var date = new Date();
If you need milliseconds for easy server-side interpretation use
var value = date.getTime();
For formatting dates into a user readable string see this
Then just write to hidden field:
document.getElementById("DATE").value = value;
Try multiple-select, especially multiple-items. Looks to be much clean and managed solution, with tons of examples. You can also view the source.
<div>
<div class="form-group row">
<label class="col-sm-2">
Basic Select
</label>
<div class="col-sm-10">
<select multiple="multiple">
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">
Group Select
</label>
<div class="col-sm-10">
<select multiple="multiple">
<optgroup label="Group 1">
<option value="1">1</option>
<option value="2">2</option>
</optgroup>
<optgroup label="Group 2">
<option value="6">6</option>
<option value="7">7</option>
</optgroup>
<optgroup label="Group 3">
<option value="11">11</option>
<option value="12">12</option>
</optgroup>
</select>
</div>
</div>
</div>
<script>
$(function() {
$('select').multipleSelect({
multiple: true,
multipleWidth: 60
})
})
</script>
On Ubuntu, I had to sudo apt-get update
and then the nodejs install worked.
These are the current declaration and initialization methods for a simple array.
string[] array = new string[2]; // creates array of length 2, default values
string[] array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2
string[] array = new[] { "A", "B" }; // created populated array of length 2
Note that other techniques of obtaining arrays exist, such as the Linq ToArray()
extensions on IEnumerable<T>
.
Also note that in the declarations above, the first two could replace the string[]
on the left with var
(C# 3+), as the information on the right is enough to infer the proper type. The third line must be written as displayed, as array initialization syntax alone is not enough to satisfy the compiler's demands. The fourth could also use inference. So if you're into the whole brevity thing, the above could be written as
var array = new string[2]; // creates array of length 2, default values
var array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2
var array = new[] { "A", "B" }; // created populated array of length 2
=VLOOKUP(lookup_value,table_array,col_index_num,range_lookup)
will solve this issue.
This will search for a value in the first column to the left and return the value in the same row from a specific column.
Try This:
$.ajax({
url:"",
type: "POST",
data: new FormData($('#uploadDatabaseForm')[0]),
contentType:false,
cache: false,
processData:false,
success:function (msg) {}
});
Since it seems to be nowhere mentioned an approach to simulate references as known from e.g. C++ is to use an "update" function and pass that instead of the actual variable (or rather, "name"):
def need_to_modify(update):
update(42) # set new value 42
# other code
def call_it():
value = 21
def update_value(new_value):
nonlocal value
value = new_value
need_to_modify(update_value)
print(value) # prints 42
This is mostly useful for "out-only references" or in a situation with multiple threads / processes (by making the update function thread / multiprocessing safe).
Obviously the above does not allow reading the value, only updating it.
This is a verbatim string, and changes the escaping rules - the only character that is now escaped is ", escaped to "". This is especially useful for file paths and regex:
var path = @"c:\some\location";
var tsql = @"SELECT *
FROM FOO
WHERE Bar = 1";
var escaped = @"a "" b";
etc
Roc answer is a great help. I would like to add a small block to it:
mRecyclerView.scrollToPosition(mAdapter.getItemCount() - 1);
If empName is a VARCHAR(50) column:
ALTER TABLE Employees MODIFY COLUMN empName VARCHAR(50) AFTER department;
EDIT
Per the comments, you can also do this:
ALTER TABLE Employees CHANGE COLUMN empName empName VARCHAR(50) AFTER department;
Note that the repetition of empName
is deliberate. You have to tell MySQL that you want to keep the same column name.
You should be aware that both syntax versions are specific to MySQL. They won't work, for example, in PostgreSQL or many other DBMSs.
Another edit: As pointed out by @Luis Rossi in a comment, you need to completely specify the altered column definition just before the AFTER
modifier. The above examples just have VARCHAR(50)
, but if you need other characteristics (such as NOT NULL
or a default value) you need to include those as well. Consult the docs on ALTER TABLE
for more info.
I used this solution for same problem.
HTML code should change to this:
<input type="text" name="username" />
<input type="text" name="password" id="txt_password" />
and jQuery code should be in document.ready
:
$('#txt_password').focus(function(){
$(this).attr('type','password');
});
yes - the engine will throw different exceptions for different conditions.
you will change this part to catch the exception and do something different
EXCEPTION
WHEN OTHERS THEN
here is a reference
http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96624/07_errs.htm
Consider also just doing mkdir -p data/images
in your Makefile, if the directory needs to be there during build.
If that's not good enough, just create an empty file in data/images and ignore data.
touch data/images/.gitignore
git add data/images/.gitignore
git commit -m "Add empty .gitignore to keep data/images around"
echo data >> .gitignore
git add .gitignore
git commit -m "Add data to .gitignore"
Not exactly the case of this question but can be helpful. I got this exception when i call mkdirs() on new file instead of its parent
File file = new java.io.File(path);
//file.mkdirs(); // wrong!
file.getParentFile().mkdirs(); // correct!
if (!file.exists()) {
file.createNewFile();
}
There is npm-package jsfiddle-downloader
.
Use the Git History Diff plugin for easy side-by-side branch diffing:
https://marketplace.visualstudio.com/items?itemName=huizhou.githd
Visit the link above and scroll down to the animated GIF image titled Diff Branch. You'll see you can easily pick any branch and do side-by-side comparison with the branch you are on! It is like getting a preview of what you will see in the GitHub Pull Request. For other Git stuff I prefer Visual Studio Code's built-in functionality or Git Lens as others have mentioned.
However, the above plugin is outstanding for doing branch diffing (i.e., for those doing a rebase Git flow and need to preview before a force push up to a GitHub PR).
body
parameter within the mailto
string%0D%0A
as newlineThe mailto
URI Scheme is specified by by RFC2368 (July 1998) and RFC6068 (October 2010).
Below is an extract of section 5 of this last RFC:
[...] line breaks in the body of a message MUST be encoded with
"%0D%0A"
.
Implementations MAY add a final line break to the body of a message even if there is no trailing"%0D%0A"
in the body [...]
See also in section 6 the example from the same RFC:
<mailto:[email protected]?body=send%20current-issue%0D%0Asend%20index>
The above mailto
body corresponds to:
send current-issue
send index
Python itself comes with an editor that you can access from the IDLE File > New File menu option.
Write the code in that file, save it as [filename].py and then (in that same file editor window) press F5 to execute the code you created in the IDLE Shell window.
Note: it's just been the easiest and most straightforward way for me so far.
You can do it with just a few lines of pure js codes.
var date = new Date(1324339200000);
var dateToStr = date.toUTCString().split(' ');
var cleanDate = dateToStr[2] + ' ' + dateToStr[1] ;
console.log(cleanDate);
returns Dec 20. Hope it helps.
VSCode will never refresh the file if you have changes in that file that are not saved to disk. However, if the file is open and does not have changes, it will replace with the changes on disk, that is true.
There is currently no way to disable this behaviour.
I too have struggled with this new pagespeed metric.
Although I have found no practical way to get my score back up to %100 there are a few things I have found helpful.
Combining all css into one file helped a lot. All my sites are back up to %95 - %98.
The only other thing I could think of was to inline all the necessary css (which appears to be most of it - at least for my pages) on the first page to get the sweet high score. Although it may help your speed score this will probably make your page load slower though.
To access the raw RGB values of an UIImage in Swift 5 use the underlying CGImage and its dataProvider:
import UIKit
let image = UIImage(named: "example.png")!
guard let cgImage = image.cgImage,
let data = cgImage.dataProvider?.data,
let bytes = CFDataGetBytePtr(data) else {
fatalError("Couldn't access image data")
}
assert(cgImage.colorSpace?.model == .rgb)
let bytesPerPixel = cgImage.bitsPerPixel / cgImage.bitsPerComponent
for y in 0 ..< cgImage.height {
for x in 0 ..< cgImage.width {
let offset = (y * cgImage.bytesPerRow) + (x * bytesPerPixel)
let components = (r: bytes[offset], g: bytes[offset + 1], b: bytes[offset + 2])
print("[x:\(x), y:\(y)] \(components)")
}
print("---")
}
https://www.ralfebert.de/ios/examples/image-processing/uiimage-raw-pixels/
how about the one liner for creating a key value pair?
let result = { ["foo"]: "some value" };
and some iterator function like reduce
to dynamically convert an array to a dictionary
var options = [_x000D_
{ key: "foo", value: 1 },_x000D_
{ key: "bar", value: {id: 2, name: "two"} },_x000D_
{ key: "baz", value: {["active"]: true} },_x000D_
];_x000D_
_x000D_
var result = options.reduce((accumulator, current) => {_x000D_
accumulator[current.key] = current.value;_x000D_
return accumulator;_x000D_
}, {});_x000D_
_x000D_
console.log(result);
_x000D_
It is actually a 3 step process to connect to a PostgreSQL server remotely through pgAdmin3.
Note: I use Ubuntu 11.04 and PostgreSQL 8.4.
You have to make PostgreSQL listening for remote incoming TCP connections because the default settings allow to listen only for connections on the loopback interface. To be able to reach the server remotely you have to add the following line into the file /etc/postgresql/8.4/main/postgresql.conf:
listen_addresses = '*'
PostgreSQL by default refuses all connections it receives from any remote address, you have to relax these rules by adding this line to /etc/postgresql/8.4/main/pg_hba.conf:
host all all 0.0.0.0/0 md5
This is an access control rule that let anybody login in from any address if he can provide a valid password (the md5 keyword). You can use needed network/mask instead of 0.0.0.0/0 .
When you have applied these modifications to your configuration files you need to restart PostgreSQL server. Now it is possible to login to your server remotely, using the username and password.
You can check this out. Use foreach loop over a DataColumn provided with your DataTable.
foreach(DataColumn column in dtTable.Columns)
{
// do here whatever you want to...
}
If I had to do this with a regex, I'd do it like this:
s = re.sub(r'\.jpg$', '', s)
As others already said, there seems to be no good solution to do that easily.
But to keep your code clean I suggest creating a seperate class that hides the ugly XAML.
How to use after we created the ButtonEx-class:
<Window x:Class="MyApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:wpfEx="clr-namespace:WpfExtensions"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<wpfEx:ButtonEx HoverBackground="Red"></wpfEx:ButtonEx>
</Grid>
</Window>
ButtonEx.xaml.cs
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace WpfExtensions
{
/// <summary>
/// Standard button with extensions
/// </summary>
public partial class ButtonEx : Button
{
readonly static Brush DefaultHoverBackgroundValue = new BrushConverter().ConvertFromString("#FFBEE6FD") as Brush;
public ButtonEx()
{
InitializeComponent();
}
public Brush HoverBackground
{
get { return (Brush)GetValue(HoverBackgroundProperty); }
set { SetValue(HoverBackgroundProperty, value); }
}
public static readonly DependencyProperty HoverBackgroundProperty = DependencyProperty.Register(
"HoverBackground", typeof(Brush), typeof(ButtonEx), new PropertyMetadata(DefaultHoverBackgroundValue));
}
}
ButtonEx.xaml
Note: This contains all the original XAML from System.Windows.Controls.Button
<Button x:Class="WpfExtensions.ButtonEx"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
x:Name="buttonExtension">
<Button.Resources>
<Style x:Key="FocusVisual">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<Rectangle Margin="2" SnapsToDevicePixels="true" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="10" StrokeDashArray="1 2"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<SolidColorBrush x:Key="Button.Static.Background" Color="#FFDDDDDD"/>
<SolidColorBrush x:Key="Button.Static.Border" Color="#FF707070"/>
<SolidColorBrush x:Key="Button.MouseOver.Background" Color="#FFBEE6FD"/>
<SolidColorBrush x:Key="Button.MouseOver.Border" Color="#FF3C7FB1"/>
<SolidColorBrush x:Key="Button.Pressed.Background" Color="#FFC4E5F6"/>
<SolidColorBrush x:Key="Button.Pressed.Border" Color="#FF2C628B"/>
<SolidColorBrush x:Key="Button.Disabled.Background" Color="#FFF4F4F4"/>
<SolidColorBrush x:Key="Button.Disabled.Border" Color="#FFADB2B5"/>
<SolidColorBrush x:Key="Button.Disabled.Foreground" Color="#FF838383"/>
</Button.Resources>
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="FocusVisualStyle" Value="{StaticResource FocusVisual}"/>
<Setter Property="Background" Value="{StaticResource Button.Static.Background}"/>
<Setter Property="BorderBrush" Value="{StaticResource Button.Static.Border}"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Padding" Value="1"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
<ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsDefaulted" Value="true">
<Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Background" TargetName="border" Value="{Binding Path=HoverBackground, ElementName=buttonExtension}"/>
<Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/>
</Trigger>
<Trigger Property="IsPressed" Value="true">
<Setter Property="Background" TargetName="border" Value="{StaticResource Button.Pressed.Background}"/>
<Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Pressed.Border}"/>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Background" TargetName="border" Value="{StaticResource Button.Disabled.Background}"/>
<Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Disabled.Border}"/>
<Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="{StaticResource Button.Disabled.Foreground}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Button.Style>
</Button>
Tip: You can add an UserControl with name "ButtonEx" to your project in VS Studio and then copy paste the stuff above in.
Ps 2: As pointed out by Justin, check out Facebook's new Share Dialog. Will leave the answer as is for posterity. This answer is obsolete
Short answer, yes there's a similar option for Facebook, that doesn't require javascript (well, there's some minimal inline JS that is not compulsory, see note).
Ps: The onclick
part only helps you customise the popup a little bit but is not required for the code to work ... it will work just fine without it.
<a href="https://www.facebook.com/sharer/sharer.php?u=URLENCODED_URL&t=TITLE"
onclick="javascript:window.open(this.href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600');return false;"
target="_blank" title="Share on Facebook">
</a>
<a href="https://twitter.com/share?url=URLENCODED_URL&via=TWITTER_HANDLE&text=TEXT"
onclick="javascript:window.open(this.href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600');return false;"
target="_blank" title="Share on Twitter">
</a>
I was facing the same issue. I needed to place the JDK before the JRE in PATH in order to resolve.
If anyone has, like I do, an Estimating workbook with a default number of visible pricing sheets, a Summary and a larger number of hidden and 'protected' worksheets full of sensitive data but may need to create additional visible worksheets to arrive at a proper price, I have variant of the above responses that creates the said visible worksheets based on a protected hidden "Master". I have used the code provided by @/jean-fran%c3%a7ois-corbett and @thanos-a in combination with simple VBA as shown below.
Sub sbInsertWorksheetAfter()
'This adds a new visible worksheet after the last visible worksheet
ThisWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)
'This copies the content of the HIDDEN "Master" worksheet to the new VISIBLE ActiveSheet just created
ThisWorkbook.Sheets("Master").Cells.Copy _
Destination:=ActiveSheet.Cells
'This gives the the new ActiveSheet a default name
With ActiveSheet
.Name = Sheet12.Name & " copied"
End With
'This changes the name of the ActiveSheet to the user's preference
Dim sheetname As String
With ActiveSheet
sheetname = InputBox("Enter name of this Worksheet")
.Name = sheetname
End With
End Sub
NSDate *currentDate = [NSDate date];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setHour:10];
NSDate *date = [gregorian dateByAddingComponents:comps toDate:currentDate options:0];
[comps release];
Not tested in xcode though :)
I am using Memurai which is Redis-compatible cache and datastore for Windows. It is also recommended by Microsoft open tech as it written on their former project here.
This project is no longer being actively maintained. If you are looking for a Windows version of Redis, you may want to check out Memurai. Please note that Microsoft is not officially endorsing this product in any way.
Suppose I have integer = 0123456789101112
. Now, this integer can be converted into a string by the stringstream
class.
Here is the code in C++:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n,i;
string s;
stringstream st;
for(i=0;i<=12;i++)
{
st<<i;
}
s=st.str();
cout<<s<<endl;
return 0;
}
Mayb it's easier (and has more performance) if you delegate the event handling to another element, for example your table
$('idOfYourTable').on("click", "input:checkbox", function(){
});
in this way you will have only one event handler, and this will work also for newly added elements. This requires jQuery >= 1.7
Otherwise use delegate()
$('idOfYourTable').delegate("input:checkbox", "click", function(){
});
My mistake was that I was creating classes in resource package...
Creating classes in src/main/java solved the issue.
Should you try this class Map
:
var myMap = new Map();_x000D_
_x000D_
// setting the values_x000D_
myMap.set("1", 'value1');_x000D_
myMap.set("2", 'value2');_x000D_
myMap.set("3", 'value3');_x000D_
_x000D_
myMap.size; // 3_x000D_
_x000D_
// getting the values_x000D_
myMap.get("1"); // "value associated with "value1"_x000D_
myMap.get("2"); // "value associated with "value1"_x000D_
myMap.get("3"); // "value associated with "value3"
_x000D_
Notice: key and value can be any type.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
The solution provided by Barry above is excellent, but there's is the "flicker-problem".
As soon as the Value is above zero the OnPaint will be envoked repeatedly and the text will flicker.
There is a solution to this. We do not need VisualStyles for the object since we will be drawing it with our own code.
Add the following code to the custom object Barry wrote and you will avoid the flicker:
[DllImportAttribute("uxtheme.dll")]
private static extern int SetWindowTheme(IntPtr hWnd, string appname, string idlist);
protected override void OnHandleCreated(EventArgs e)
{
SetWindowTheme(this.Handle, "", "");
base.OnHandleCreated(e);
}
I did not write this myself. It found it here: https://stackoverflow.com/a/299983/1163954
I've testet it and it works.
The best way to put is that hg forget
is identical to hg remove
except that it leaves the files behind in your working copy. The files are left behind as untracked files and can now optionally be ignored with a pattern in .hgignore
.
In other words, I cannot tell if you used hg forget
or hg remove
when I pull from you. A file that you ran hg forget
on will be deleted when I update to that changeset — just as if you had used hg remove
instead.
Pay attention to one aspect when doing "purchase_date>(sysdate-30)": "sysdate" is the current date, hour, minute and second. So "sysdate-30" is not exactly "30 days ago", but "30 days ago at this exact hour".
If your purchase dates have 00.00.00 in hours, minutes, seconds, better doing:
where trunc(purchase_date)>trunc(sysdate-30)
(this doesn't take hours, minutes and seconds into account).
zvolkov's answer is the perfect one to find out if there is such a customer. If you need to use the customer afterwards, you can do:
Customer customer = list.FirstOrDefault(cus => cus.FirstName == "John");
if (customer != null)
{
// Use customer
}
I know this isn't what you were asking, but I thought I'd pre-empt a follow-on question :) (Of course, this only finds the first such customer... to find all of them, just use a normal where
clause.)
Quoted from http://maven.apache.org/settings.html:
There are two locations where a settings.xml file may live:
The Maven install: $M2_HOME/conf/settings.xml
A user's install: ${user.home}/.m2/settings.xml
So, usually for a specific user you edit
/home/*username*/.m2/settings.xml
To set environment for all local users, you might think about changing the first path.
AMD
CommonJS:
Example
upper.js file
exports.uppercase = str => str.toUpperCase()
main.js file
const uppercaseModule = require('uppercase.js')
uppercaseModule.uppercase('test')
Summary
Resources:
Check the manual for mysql_fetch_object()
. It returns an object, not an array of objects.
I'm guessing you want something like this
$results = mysql_query("SELECT * FROM sidemenu WHERE `menu_id`='".$menu."' ORDER BY `id` ASC LIMIT 1", $con);
$sidemenus = array();
while ($sidemenu = mysql_fetch_object($results)) {
$sidemenus[] = $sidemenu;
}
Might I suggest you have a look at PDO. PDOStatement::fetchAll(PDO::FETCH_OBJ)
does what you assumed mysql_fetch_object()
to do
<img id="uxcMyImageId" src"myImage" width="100" height="100" />
specifying width and height in the image tag is a good practice..this way when the page loads there is space allocated for the image and the layout does not suffer any jerks even if the image takes a long time to load.
You can't do that. You could try telling your problem from a more high level point of view (i.e. what exactly do you want to accomplish with the casted variable) for a different solution.
You could go with something like this:
public abstract class Message {
// ...
}
public class Message<T> : Message {
}
public abstract class MessageProcessor {
public abstract void ProcessMessage(Message msg);
}
public class SayMessageProcessor : MessageProcessor {
public override void ProcessMessage(Message msg) {
ProcessMessage((Message<Say>)msg);
}
public void ProcessMessage(Message<Say> msg) {
// do the actual processing
}
}
// Dispatcher logic:
Dictionary<Type, MessageProcessor> messageProcessors = {
{ typeof(Say), new SayMessageProcessor() },
{ typeof(string), new StringMessageProcessor() }
}; // properly initialized
messageProcessors[msg.GetType().GetGenericArguments()[0]].ProcessMessage(msg);
A string to char array is as simple as
String str = "someString";
char[] charArray = str.toCharArray();
Can you explain a little more on what you are trying to do?
* Update *
if I am understanding your new comment, you can use a byte array and example is provided.
byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();
for (byte b : bytes) {
System.out.format("0x%x ", b);
}
With the following output
0x65 0x10 0xf3 0x29
This worked for me, as documented on this page:
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
StringWriter sw = new StringWriter();
trans.transform(new DOMSource(document), new StreamResult(sw));
return sw.toString();
Use the INTERVAL
type to it. E.g:
--yesterday
SELECT NOW() - INTERVAL '1 DAY';
--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;
Then you can do the following on your query:
SELECT
org_id,
count(accounts) AS COUNT,
((date_at) - INTERVAL '1 DAY') AS dateat
FROM
sourcetable
WHERE
date_at <= now() - INTERVAL '130 DAYS'
GROUP BY
org_id,
dateat;
You can append multiple operands. E.g.: how to get last day of current month?
SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';
You can also create an interval using make_interval
function, useful when you need to create it at runtime (not using literals):
SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);
Configuration
The styles and scripts options in your angular.json configuration now allow to reference a package directly:
before: "styles": ["../node_modules/bootstrap/dist/css/bootstrap.css"]
after: "styles": ["bootstrap/dist/css/bootstrap.css"]
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/ng6",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css","bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
"jquery/dist/jquery.min.js",
"bootstrap/dist/js/bootstrap.min.js"
]
},
Angular v6 Onwards
CLI projects in angular 6 onwards will be using angular.json
instead of .angular-cli.json
for build and project configuration.
Each CLI workspace has projects, each project has targets, and each target can have configurations.Docs
. {
"projects": {
"my-project-name": {
"projectType": "application",
"architect": {
"build": {
"configurations": {
"production": {},
"demo": {},
"staging": {},
}
},
"serve": {},
"extract-i18n": {},
"test": {},
}
},
"my-project-name-e2e": {}
},
}
OPTION-1
execute npm install bootstrap@4 jquery --save
The JavaScript parts of Bootstrap
are dependent on jQuery
. So you need the jQuery
JavaScript
library file too.
In your angular.json add the file paths to the styles and scripts array in under build
target
NOTE:
Before v6 the Angular CLI project configuration was stored in <PATH_TO_PROJECT>/.angular-cli.json.
As of v6 the location of the file changed to angular.json.
Since there is no longer a leading dot, the file is no longer hidden by default and is on the same level.
which also means that file paths in angular.json should not contain leading dots and slash
i.e you can provide an absolute path instead of a relative path
In .angular-cli.json
file Path was "../node_modules/"
In angular.json
it is "node_modules/"
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/ng6",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css","node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": ["node_modules/jquery/dist/jquery.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js"]
},
OPTION 2
Add files from CDN (Content Delivery Network) to your project CDN LINK
Open file src/index.html and insert
the <link>
element at the end of the head section to include the Bootstrap CSS file
a <script>
element to include jQuery at the bottom of the body section
a <script>
element to include Popper.js at the bottom of the body section
a <script>
element to include the Bootstrap JavaScript file at the bottom of the body section
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Angular</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<app-root>Loading...</app-root>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
OPTION 3
Execute npm install bootstrap
In src/styles.css
add the following line:
@import "~bootstrap/dist/css/bootstrap.css";
OPTION-4
ng-bootstrap It contains a set of native Angular directives based on Bootstrap’s markup and CSS. As a result, it's not dependent on jQuery or Bootstrap’s JavaScript
npm install --save @ng-bootstrap/ng-bootstrap
After Installation import it in your root module and register it in @NgModule
imports` array
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
@NgModule({
declarations: [AppComponent, ...],
imports: [NgbModule.forRoot(), ...],
bootstrap: [AppComponent]
})
NOTE
ng-bootstrap
requires Bootstrap's 4 css to be added in your project. you need to Install it explicitly via:
npm install bootstrap@4 --save
In your angular.json add the file paths to the styles array in under build
target
"styles": [
"src/styles.css",
"node_modules/bootstrap/dist/css/bootstrap.min.css"
],
<input type="text" value="3" class="field left" readonly>
No styling necessary.
See <input>
on MDN https://developer.mozilla.org/en/docs/Web/HTML/Element/input#Attributes
$this->db1->where('tennant_id', $tennant_id);
$this->db1->order_by('id', 'DESC');
return $this->db1->get('courses')->result();
Haven't seen this solution yet so here's how I did it without using read_csv:
df.rename(columns={'A':'','B':''})
If you rename all your column names to empty strings your table will return without a header.
And if you have a lot of columns in your table you can just create a dictionary first instead of renaming manually:
df_dict = dict.fromkeys(df.columns, '')
df.rename(columns = df_dict)
You could use https://github.com/anywhichway/benchtest which wraps existing Mocha unit tests with performance tests.
I encountered the same problem in the code and What I did is I found out all the changes I have made from the last correct compilation. And I have observed one function declaration was without ";" and also it was passing a value and I have declared it to pass nothing "void". this method will surely solve the problem for many.
Viscon
You can try Alasql JavaScript library which can work together with XLSX.js library for easy export of Angular.js data. This is an example of controller with exportData() function:
function myCtrl($scope) {
$scope.exportData = function () {
alasql('SELECT * INTO XLSX("john.xlsx",{headers:true}) FROM ?',[$scope.items]);
};
$scope.items = [{
name: "John Smith",
email: "[email protected]",
dob: "1985-10-10"
}, {
name: "Jane Smith",
email: "[email protected]",
dob: "1988-12-22"
}];
}
See full HTML and JavaScript code for this example in jsFiddle.
UPDATED Another example with coloring cells.
Also you need to include two libraries:
You can do this using the sysctl utility:
sysctl -n hw.ncpu
Short of writing a full application, us Python guys can achieve files of any size with four lines, same snippet on Windows and Linux (the os.stat()
line is just a check):
>>> f = open('myfile.txt','w')
>>> f.seek(1024-1) # an example, pick any size
>>> f.write('\x00')
>>> f.close()
>>> os.stat('myfile.txt').st_size
1024L
>>>
Delete remote branch
git push origin :<branchname>
Delete local branch
git branch -D <branchname>
Delete local branch steps:
The HTML5 history spec is quirky.
history.pushState()
doesn't dispatch a popstate
event or load a new page by itself. It was only meant to push state into history. This is an "undo" feature for single page applications. You have to manually dispatch a popstate
event or use history.go()
to navigate to the new state. The idea is that a router can listen to popstate
events and do the navigation for you.
Some things to note:
history.pushState()
and history.replaceState()
don't dispatch popstate
events.history.back()
, history.forward()
, and the browser's back and forward buttons do dispatch popstate
events.history.go()
and history.go(0)
do a full page reload and don't dispatch popstate
events.history.go(-1)
(back 1 page) and history.go(1)
(forward 1 page) do dispatch popstate
events.You can use the history API like this to push a new state AND dispatch a popstate event.
history.pushState({message:'New State!'}, 'New Title', '/link');
window.dispatchEvent(new PopStateEvent('popstate', {
bubbles: false,
cancelable: false,
state: history.state
}));
Then listen for popstate
events with a router.
make sure your folder permissions are set so that a directory listing is allowed then just point your anchor to that folder using chmod 701 (that might be risky though) for example
<a href="./downloads/folder_i_want_to_display/" >Go to downloads page</a>
make sure that you have no index.html any index file on that directory
Step 1: (Install qemu-kvm)
sudo apt install qemu-kvm
Step 2: (Add your user to kvm group using)
sudo adduser username kvm
Step 3: (If still showing permission denied)
sudo chown username /dev/kvm
Final step:
ls -al /dev/kvm
Last Updated Version is with xCode 6.1
class StampInfoTableViewCell: UITableViewCell{
@IBOutlet weak var stampDate: UILabel!
@IBOutlet weak var numberText: UILabel!
override init?(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required init(coder aDecoder: NSCoder) {
//fatalError("init(coder:) has not been implemented")
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
The point about generics is to give compile-time type safety - which means that types need to be known at compile-time.
You can call generic methods with types only known at execution time, but you have to use reflection:
// For non-public methods, you'll need to specify binding flags too
MethodInfo method = GetType().GetMethod("DoesEntityExist")
.MakeGenericMethod(new Type[] { t });
method.Invoke(this, new object[] { entityGuid, transaction });
Ick.
Can you make your calling method generic instead, and pass in your type parameter as the type argument, pushing the decision one level higher up the stack?
If you could give us more information about what you're doing, that would help. Sometimes you may need to use reflection as above, but if you pick the right point to do it, you can make sure you only need to do it once, and let everything below that point use the type parameter in a normal way.
That doesn't work because, judging by the rest of the code, the initial value of the text input is "Default text" - which is more than one character, and so your if
condition is always true.
The simplest way to make it work, it seems to me, is to account for this case:
var value = $(this).val();
if ( value.length > 0 && value != "Default text" ) ...
with DataFrame: df_data
>>> df_data
id name value
0 a ampha 1
1 b beta 2
2 c ce 3
I tried:
>>> getattr(df_data, 'value').isin([1]).any()
True
>>> getattr(df_data, 'value').isin(['1']).any()
True
but:
>>> 1 in getattr(df_data, 'value')
True
>>> '1' in getattr(df_data, 'value')
False
So fun :D
If you have a worksheet with many rows that all contain the formula, by far the easiest method is to copy a row that is without data (but it does contain formulas), and then "insert copied cells" below/above the row where you want to add. The formulas remain. In a pinch, it is OK to use a row with data. Just clear it or overwrite it after pasting.
I'm sure the solution is that your oldDateString is something like "2009-10-20". Obviously this does not contain any time data lower than days. If you format this string with your new formatter where should it get the minutes, seconds and milliseconds from?
So the result is absolutely correct: 2009-10-20 00:00:00.000
What you'll need to solve this, is the original timestamp (incl. time data) before your first formatting.
try this code
Intent photo= new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(photo, CAMERA_PIC_REQUEST);
This behavior is explicitly documented in String.split(String regex)
(emphasis mine):
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
If you want those trailing empty strings included, you need to use String.split(String regex, int limit)
with a negative value for the second parameter (limit
):
String[] array = values.split("\\|", -1);
I was using a virtual environment on Ubuntu 18.04, and since I only wanted to install it as a client, I only had to do:
sudo apt install libpq-dev
pip install psycopg2
And installed without problems. Of course, you can use the binary as other answers said, but I preferred this solution since it was stated in a requirements.txt file.
I had this problem when I was trying to add a directory to svn. I solved it by going into repo browser. Right clicking in the left window, choosing add folder and adding the directory directly in the repo browser.
I then deleted the directory locally (after backup of course) did a clean up and svn update and everything was working again.