I found a fix...
.text {
font-size: 15px; /* for firefox */
*font-size: 90%; /* % restart the antialiasing for ie, note the * hack */
font-weight: bold; /* needed, don't know why! */
}
You Can Now Delete App.
On October 4, 2018, Apple released a new update of the appstoreconnect (previously iTunesConnect).
It's now easier to manage apps you no longer need in App Store Connect by removing them from your main view in My Apps, even if they haven't been submitted for approval. You must have the Legal or Admin role to remove apps.
From the homepage, click My Apps, then choose the app you want to remove. Scroll to the Additional Information section, then click Remove App. In the dialog that appears, click Remove. You can restore a removed app at any time, as long as the app name is not currently in use by another developer.
From the homepage, click My Apps. In the upper right-hand corner, click the arrow next to All Statuses. From the drop-down menu, choose Removed Apps. Choose the app you want to restore. Scroll to the Additional Information section, then click Restore App.
You can show the removed app by clicking on all Statuses on the top right of the screen and then select Removed Apps. Thank you @Daniel for the tips.
Please note:
you can only remove apps if all versions of that app are in one of the following states: Prepare for Submission, Invalid Binary, Developer Rejected, Rejected, Metadata Rejected, Developer, Removed from Sale.
If you want to scroll automatic without show scroll motion then you need to write following code:
mRecyclerView.getLayoutManager().scrollToPosition(position);
If you want to display scroll motion then you need to add following code. =>Step 1: You need to declare SmoothScroller.
RecyclerView.SmoothScroller smoothScroller = new
LinearSmoothScroller(this.getApplicationContext()) {
@Override
protected int getVerticalSnapPreference() {
return LinearSmoothScroller.SNAP_TO_START;
}
};
=>step 2: You need to add this code any event you want to perform scroll to specific position. =>First you need to set target position to SmoothScroller.
smoothScroller.setTargetPosition(position);
=>Then you need to set SmoothScroller to LayoutManager.
mRecyclerView.getLayoutManager().startSmoothScroll(smoothScroller);
You can use one-line heredoc
cat <<< "This is coming from the stdin"
the above is the same as
cat <<EOF
This is coming from the stdin
EOF
or you can redirect output from a command, like
diff <(ls /bin) <(ls /usr/bin)
or you can read as
while read line
do
echo =$line=
done < some_file
or simply
echo something | read param
Are you thinking about something like this?
$('ul li').each(function(i)
{
$(this).attr('rel'); // This is your rel value
});
string stringtodate = ((DateTime)row.Cells[4].Value).ToString("MM-dd-yyyy");
textBox9.Text = stringtodate;
One thing you could do would be to create a dictionary. Might be a little sloppy considering your looking for 64 elements but it gets the job done. Im not sure if its the "preferred way" to do it but it worked for me using an array of structs.
var tasks = [0:[forTasks](),1:[forTasks](),2:[forTasks](),3:[forTasks](),4:[forTasks](),5:[forTasks](),6:[forTasks]()]
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
My code work well just as the answer above. The reason is that the json from jackson is different with the json sent from controller.
String test1= mapper.writeValueAsString(result1);
And the json is like(which can be deserialized normally):
{"code":200,"message":"god","data":[{"nics":null,"status":null,"desktopOperatorType":null,"marker":null,"user_name":null,"user_group":null,"user_email":null,"product_id":null,"image_id":null,"computer_name":"AAAA","desktop_id":null,"created":null,"ip_address":null,"security_groups":null,"root_volume":null,"data_volumes":null,"availability_zone":null,"ou_name":null,"login_status":null,"desktop_ip":null,"ad_id":null},{"nics":null,"status":null,"desktopOperatorType":null,"marker":null,"user_name":null,"user_group":null,"user_email":null,"product_id":null,"image_id":null,"computer_name":"BBBB","desktop_id":null,"created":null,"ip_address":null,"security_groups":null,"root_volume":null,"data_volumes":null,"availability_zone":null,"ou_name":null,"login_status":null,"desktop_ip":null,"ad_id":null}]}
but the json send from the another service just like:
{"code":200,"message":"????????","data":[{"nics":"","status":"","metadata":"","desktopOperatorType":"","marker":"","user_name":"csrgzbsjy","user_group":"ADMINISTRATORS","user_email":"","product_id":"","image_id":"","computer_name":"B-jiegou-all-15","desktop_id":"6360ee29-eb82-416b-aab8-18ded887e8ff","created":"2018-11-12T07:45:15.000Z","ip_address":"192.168.2.215","security_groups":"","root_volume":"","data_volumes":"","availability_zone":"","ou_name":"","login_status":"","desktop_ip":"","ad_id":""},{"nics":"","status":"","metadata":"","desktopOperatorType":"","marker":"","user_name":"glory_2147","user_group":"ADMINISTRATORS","user_email":"","product_id":"","image_id":"","computer_name":"H-pkpm-all-357","desktop_id":"709164e4-d3e6-495d-9c1e-a7b82e30bc83","created":"2018-11-09T09:54:09.000Z","ip_address":"192.168.2.235","security_groups":"","root_volume":"","data_volumes":"","availability_zone":"","ou_name":"","login_status":"","desktop_ip":"","ad_id":""}]}
You can notice the difference when dealing with the param without initiation. Be careful
The general end of line comment, // eslint-disable-line
, does not need anything after it: no need to look up a code to specify what you wish ES Lint to ignore.
If you need to have any syntax ignored for any reason other than a quick debugging, you have problems: why not update your delint config?
I enjoy // eslint-disable-line
to allow me to insert console
for a quick inspection of a service, without my development environment holding me back because of the breach of protocol. (I generally ban console
, and use a logging class - which sometimes builds upon console
.)
You lookup the value of the data with findData()
and then use setCurrentIndex()
QComboBox* combo = new QComboBox;
combo->addItem("100",100.0); // 2nd parameter can be any Qt type
combo->addItem .....
float value=100.0;
int index = combo->findData(value);
if ( index != -1 ) { // -1 for not found
combo->setCurrentIndex(index);
}
As stated in other answers, you can check the mime type by checking the signature of the file in the first bytes of the file.
But what other answers are doing is loading the entire file in memory in order to check the signature, which is very wasteful and could easily freeze your browser if you select a big file by accident or not.
/**_x000D_
* Load the mime type based on the signature of the first bytes of the file_x000D_
* @param {File} file A instance of File_x000D_
* @param {Function} callback Callback with the result_x000D_
* @author Victor www.vitim.us_x000D_
* @date 2017-03-23_x000D_
*/_x000D_
function loadMime(file, callback) {_x000D_
_x000D_
//List of known mimes_x000D_
var mimes = [_x000D_
{_x000D_
mime: 'image/jpeg',_x000D_
pattern: [0xFF, 0xD8, 0xFF],_x000D_
mask: [0xFF, 0xFF, 0xFF],_x000D_
},_x000D_
{_x000D_
mime: 'image/png',_x000D_
pattern: [0x89, 0x50, 0x4E, 0x47],_x000D_
mask: [0xFF, 0xFF, 0xFF, 0xFF],_x000D_
}_x000D_
// you can expand this list @see https://mimesniff.spec.whatwg.org/#matching-an-image-type-pattern_x000D_
];_x000D_
_x000D_
function check(bytes, mime) {_x000D_
for (var i = 0, l = mime.mask.length; i < l; ++i) {_x000D_
if ((bytes[i] & mime.mask[i]) - mime.pattern[i] !== 0) {_x000D_
return false;_x000D_
}_x000D_
}_x000D_
return true;_x000D_
}_x000D_
_x000D_
var blob = file.slice(0, 4); //read the first 4 bytes of the file_x000D_
_x000D_
var reader = new FileReader();_x000D_
reader.onloadend = function(e) {_x000D_
if (e.target.readyState === FileReader.DONE) {_x000D_
var bytes = new Uint8Array(e.target.result);_x000D_
_x000D_
for (var i=0, l = mimes.length; i<l; ++i) {_x000D_
if (check(bytes, mimes[i])) return callback("Mime: " + mimes[i].mime + " <br> Browser:" + file.type);_x000D_
}_x000D_
_x000D_
return callback("Mime: unknown <br> Browser:" + file.type);_x000D_
}_x000D_
};_x000D_
reader.readAsArrayBuffer(blob);_x000D_
}_x000D_
_x000D_
_x000D_
//when selecting a file on the input_x000D_
fileInput.onchange = function() {_x000D_
loadMime(fileInput.files[0], function(mime) {_x000D_
_x000D_
//print the output to the screen_x000D_
output.innerHTML = mime;_x000D_
});_x000D_
};
_x000D_
<input type="file" id="fileInput">_x000D_
<div id="output"></div>
_x000D_
You can use this outside activities - all you need is to provide a Context
:
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
Then to retrieve your different widgets, you inflate a layout:
View view = inflater.inflate( R.layout.myNewInflatedLayout, null );
Button myButton = (Button) view.findViewById( R.id.myButton );
EDIT as of July 2014
Davide's answer on how to get the LayoutInflater
is actually more correct than mine (which is still valid though).
Another quick and dirty answer is that you can just convert your list to an array using:
import numpy as np
arr = np.asarray(listname)
This works in my case:
@RequestMapping(value = "/savedata",
params = {"textArea", "localKey", "localFile"})
@ResponseBody
public void saveData(@RequestParam(value = "textArea") String textArea,
@RequestParam(value = "localKey") String localKey,
@RequestParam(value = "localFile") String localFile) {
}
Thanks a lot guys!
I overlooked my ECLIPSE VERSION it was 64Bit and 3.6
I had to make sure it's 32Bit Eclipse, 32 Bit JVM so i uninstalled Eclipse & all JVM for clean start. Installed 32Bit JDK1.6 from here and 32Bit Eclipse from here
Integers are trivial; this you already know. The deep problem is how to deal with floating-point values. At that point, you've got to know a bit more about how floating point values actually work.
The key is Double.doubleToLongBits(), which lets you get at the IEEE representation of the number. (The method's really a direct cast under the hood, with a bit of magic for dealing with NaN values.) Once a double has been converted to a long, you can just use 0x8000000000000000L as a mask to select the sign bit; if zero, the value is positive, and if one, it's negative.
Check if your project files are read-only. Remove the read-only property by right clicking on the project folder and select properties. In the properties screen remove the read-only checkbox. I came across the same problem, and this solved it for me.
you can Add contextual classes to every single row as follows:
<tr class="table-success"></tr>
<tr class="table-error"></tr>
<tr class="table-warning"></tr>
<tr class="table-info"></tr>
<tr class="table-danger"></tr>
You can also add them to table data same as above
You can set your table size by setting classes as table-sm and so on.
You can add custom classes and add your own styling:
<table class="table">
<thead style = "color:red;background-color:blue">
<tr>
<th></th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>Asdf</td>
<td>qwerty</td>
</tr>
</tbody>
</table>
This way you can add custom styling. I have showed inline styling just for example how it works, you can add classes and call them in your css as well.
Others have answered in terms of how to handle the specific escaping in this case.
A broader answer is not to try to do it yourself. Use an XML API - there are plenty available for just about every modern programming platform in existence.
XML APIs will handle things like this for you automatically, making it a lot harder to go wrong. Unless you're writing an XML API yourself, you should rarely need to worry about the details like this.
This is a very partial answer to your question, but I hope still useful.
Microsoft SQL Server 2008 implements two features that are extremely useful for managing hierarchical data:
Have a look at "Model Your Data Hierarchies With SQL Server 2008" by Kent Tegels on MSDN for starts. See also my own question: Recursive same-table query in SQL Server 2008
Just do:
SET
You can also do SET prefix
to see all variables with names starting with prefix
.
For example, if you want to read only derbydb from the environment variables, do the following:
set derby
...and you will get the following:
DERBY_HOME=c:\Users\amro-a\Desktop\db-derby-10.10.1.1-bin\db-derby-10.10.1.1-bin
Above answers almost all correct but for those who doesn't undestand those answers Android has powerfull class Intent with help of it you share data between not only activity but another components of Android (broadcasr receiver, servises for content provide we use ContetnResolver class no Intent). In your activity you build intent
Intent intent = new Intent(context,SomeActivity.class);
intent.putExtra("key",value);
startActivity(intent);
In your receving activity you have
public class SomeActivity extends AppCompactActivity {
public void onCreate(...){
...
SomeObject someObject = getIntent().getExtras().getParceable("key");
}
}
You have to implement Parceable or Serializable interface on your object in order to share between activities. It is hard to implement Parcealbe rather than Serializable interface on object that's why android has plugin especially for this.Download it and use it
Here is example which can give you some hints to iterate through existing array and add items to new array. I use UnderscoreJS Module to use as my utility file.
You can download from (https://npmjs.org/package/underscore)
$ npm install underscore
Here is small snippet to demonstrate how you can do it.
var _ = require("underscore");
var calendars = [1, "String", {}, 1.1, true],
newArray = [];
_.each(calendars, function (item, index) {
newArray.push(item);
});
console.log(newArray);
I don't think this DateTimePicker has been mentioned before:
A WPF DateTimePicker That Works Like the One in Winforms
That one is in VB and has some bugs. I converted it to C# and made a new version with bug fixes.
Note: I used the Calendar control in WPFToolkit so that I could use .NET 3.5 instead of .NET 4. If you are using .NET 4, just remove references to "wpftc" in the XAML.
You really don't need jQuery for this.
var myarr = ["I", "like", "turtles"];
var arraycontainsturtles = (myarr.indexOf("turtles") > -1);
Hint: indexOf returns a number, representing the position where the specified searchvalue occurs for the first time, or -1 if it never occurs
or
function arrayContains(needle, arrhaystack)
{
return (arrhaystack.indexOf(needle) > -1);
}
It's worth noting that array.indexOf(..)
is not supported in IE < 9, but jQuery's indexOf(...)
function will work even for those older versions.
Actually, there are five words commonly used when we talk about layers of reference models (or protocol stacks): data
, segment
, packet
, frame
and bit
. And the term PDU (Protocol Data Unit
) is used to refer to the packets in different layers of the OSI model. Thus PDU gives an abstract idea of the data packets. The PDU has a different meaning in different layers still we can use it as a common term.
When we come to your question, we can call all of them by using the general term PDU
, but if you want to call them specifically at a given layer:
Here is a diagram, since a picture is worth a thousand words:
What you are trying to do is add additional information to each item in the list that you already created so
alist[ 'from form', 'stuff 2', 'stuff 3']
for j in range( 0,len[alist]):
temp= []
temp.append(alist[j]) # alist[0] is 'from form'
temp.append('t') # slot for first piece of data 't'
temp.append('-') # slot for second piece of data
blist.append(temp) # will be alist with 2 additional fields for extra stuff assocated with each item in alist
I've written something that detects if the page contains the anchor that was clicked on, and if not, goes to the normal page, otherwise it scrolls to the specific section:
$('a[href*=\\#]').on('click',function(e) {
var target = this.hash;
var $target = $(target);
console.log(targetname);
var targetname = target.slice(1, target.length);
if(document.getElementById(targetname) != null) {
e.preventDefault();
}
$('html, body').stop().animate({
'scrollTop': $target.offset().top-120 //or the height of your fixed navigation
}, 900, 'swing', function () {
window.location.hash = target;
});
});
I have a small solution
let data = [{id: 1}, {id: 2}, {id: 3}, {id: 2}, {id: 3}]
let result = data.filter((value, index, self) => self.findIndex((m) => m.id === value.id ) === index))
For generic class it is necessary to create a wrapper class. For Example:
Set<String>[] sets = new HashSet<>[10]
results in: "Cannot create a generic array"
Use instead:
class SetOfS{public Set<String> set = new HashSet<>();}
SetOfS[] sets = new SetOfS[10];
I'm a novice, but this is my self taught way of doing it:
ifstream input_file("example.txt", ios::in | ios::binary)
streambuf* buf_ptr = input_file.rdbuf(); //pointer to the stream buffer
input.get(); //extract one char from the stream, to activate the buffer
input.unget(); //put the character back to undo the get()
size_t file_size = buf_ptr->in_avail();
//a value of 0 will be returned if the stream was not activated, per line 3.
In Jenkins file add
cleanWs()
This will delete the workspace after the build is complete
I found that if the value passed is a string type, it must be followed by 'px' (i.e. 90px), where if the value is an integer, it will append the px automatically. the width and height properties are more forgiving (either type works).
var x = "90";
var y = "120"
$(selector).css( { left: x, top: y } ) //doesn't work
$(selector).css( { left: x + "px", top: y + "px" } ) //does work
x = 90;
y = 120;
$(selector).css( { left: x, top: y } ) //does work
When I did just a remove the option remained in the ddl on the view, but was gone in the html (if u inspect the page)
$("#ddlSelectList option[value='2']").remove(); //removes the option with value = 2
$('#ddlSelectList').val('').trigger('chosen:updated'); //refreshes the drop down list
How you loop through an array, depends on the presence of new line characters. With new line characters separating the array elements, the array can be referred to as "$array"
, otherwise it should be referred to as "${array[@]}"
. The following script will make it clear:
#!/bin/bash
mkdir temp
mkdir temp/aaa
mkdir temp/bbb
mkdir temp/ccc
array=$(ls temp)
array1=(aaa bbb ccc)
array2=$(echo -e "aaa\nbbb\nccc")
echo '$array'
echo "$array"
echo
for dirname in "$array"; do
echo "$dirname"
done
echo
for dirname in "${array[@]}"; do
echo "$dirname"
done
echo
echo '$array1'
echo "$array1"
echo
for dirname in "$array1"; do
echo "$dirname"
done
echo
for dirname in "${array1[@]}"; do
echo "$dirname"
done
echo
echo '$array2'
echo "$array2"
echo
for dirname in "$array2"; do
echo "$dirname"
done
echo
for dirname in "${array2[@]}"; do
echo "$dirname"
done
rmdir temp/aaa
rmdir temp/bbb
rmdir temp/ccc
rmdir temp
With itertools
you will obtain another generator object so in most of the cases you will need another step the take the first N elements (N
). There are at least two simpler solutions (a little bit less efficient in terms of performance but very handy) to get the elements ready to use from a generator
:
Using list comprehension:
first_N_element=[generator.next() for i in range(N)]
Otherwise:
first_N_element=list(generator)[:N]
Where N
is the number of elements you want to take (e.g. N=5 for the first five elements).
JQuery .is
will test all specified elements and return true if at least one of them matches selector:
if ($(":checkbox[name='choices']", form).is(":checked"))
{
// one or more checked
}
else
{
// nothing checked
}
There is ! My solution works when you create an app, but you want to use facebook authentification on your website. This solution below is NOT needed when you want to create an app integrated to FB page.
The thing is that you can't put "localhost" as a domain in the facebook configuration page of your app. Security reasons ?
You need to go to your host file, in OSX / Linux etc/hosts and add the following line : 127.0.0.1 dev.yourdomain.com
The domain you put whatever you want. One mistake is to add this line : localhost dev.yourdomain.com (at least on osx snow leopard in doesnt work).
Then you have to clear your dns cache. On OSX : type dscacheutil -flushcache in the terminal. Finally, go back to the online facebook developer website, and in the configuration page of your app, you can add the domain "dev.yourdomain.com".
If you use a program such as Mamp, Easyphp or whatever, make sure the port for Apache is 80.
This solution should work for Windows because it also has a hosts file. Nevertheless, as far as I remember Windows 7 doesnt use this file anymore, but this trick should work if you find a way to force windows to use a hosts file.
You can do it programmatically:
ddlColor.DataSource = from p in db.ProductTypes
where p.ProductID == pID
orderby p.Color
select new { p.Color };
ddlColor.DataTextField = "Color";
ddlColor.DataBind();
ddlColor.Items.Insert(0, new ListItem("Select", "NA"));
Or add it in markup as:
<asp:DropDownList .. AppendDataBoundItems="true">
<Items>
<asp:ListItem Text="Select" Value="" />
</Items>
</asp:DropDownList>
This query will get you all the tables in the database
USE [DatabaseName];
SELECT * FROM information_schema.tables;
background-clip
and box-shadow
properties.1) Set background-clip: content-box
- this restricts the background only to the content itself (instead of covering both the padding and border)
2) Add an inner box-shadow
with the spread radius set to the same value as the padding.
So say the padding is 10px - set box-shadow: inset 0 0 0 10px lightGreen
- which will make only the padding area light green.
nav {_x000D_
width: 80%;_x000D_
height: 50px;_x000D_
background-color: gray;_x000D_
float: left;_x000D_
padding: 10px; /* 10px padding */_x000D_
border: 2px solid red;_x000D_
background-clip: content-box; /* <---- */_x000D_
box-shadow: inset 0 0 0 10px lightGreen; /* <-- 10px spread radius */_x000D_
}_x000D_
ul {_x000D_
list-style: none;_x000D_
}_x000D_
li {_x000D_
display: inline-block;_x000D_
}
_x000D_
<h2>The light green background color shows the padding of the element</h2>_x000D_
<nav>_x000D_
<ul>_x000D_
<li><a href="index.html">Home</a>_x000D_
</li>_x000D_
<li><a href="/about/">About</a>_x000D_
</li>_x000D_
<li><a href="/blog/">Blog</a>_x000D_
</li>_x000D_
</ul>_x000D_
</nav>
_x000D_
For a thorough tutorial covering this technique see this great css-tricks post
use Extension
import java.text.NumberFormat
val Int.commaString: String
get() = NumberFormat.getInstance().format(this)
val String.commaString: String
get() = NumberFormat.getNumberInstance().format(this.toDouble())
val Long.commaString: String
get() = NumberFormat.getInstance().format(this)
val Double.commaString: String
get() = NumberFormat.getInstance().format(this)
result
1234.commaString => 1,234
"1234.456".commaString => 1,234.456
1234567890123456789.commaString => 1,234,567,890,123,456,789
1234.456.commaString => 1,234.456
I found this solution worked perfectly fine for me. Doesn't require any third party apis
'test' is actually a folder will lots of file inside.
String folderPath= "C:\Users\Desktop\test";
String zipPath = "C:\Users\Desktop\test1.zip";
private boolean zipDirectory(String folderPath, String zipPath) throws IOException{
byte[] buffer = new byte[1024];
FileInputStream fis = null;
ZipOutputStream zos = null;
try{
zos = new ZipOutputStream(new FileOutputStream(zipPath));
updateSourceFolder(new File(folderPath));
if (sourceFolder == null) {
zos.close();
return false;
}
generateFileAndFolderList(new File(folderPath));
for (String unzippedFile: fileList) {
System.out.println(sourceFolder + unzippedFile);
ZipEntry entry = new ZipEntry(unzippedFile);
zos.putNextEntry(entry);
if ((unzippedFile.substring(unzippedFile.length()-1)).equals(File.separator))
continue;
try{
fis = new FileInputStream(sourceFolder + unzippedFile);
int len=0;
while ((len = fis.read(buffer))>0) {
zos.write(buffer,0,len);
}
} catch(IOException e) {
return false;
} finally {
if (fis != null)
fis.close();
}
}
zos.closeEntry();
} catch(IOException e) {
return false;
} finally {
zos.close();
fileList = null;
sourceFolder = null;
}
return true;
}
private void generateFileAndFolderList(File node) {
if (node.isFile()) {
fileList.add(generateZipEntry(node.getAbsoluteFile().toString()));
}
if (node.isDirectory()) {
String dir = node.getAbsoluteFile().toString();
fileList.add(dir.substring(sourceFolder.length(), dir.length()) + File.separator);
String[] subNode = node.list();
for (String fileOrFolderName : subNode) {
generateFileAndFolderList(new File(node, fileOrFolderName));
}
}
}
private void updateSourceFolder(File node) {
if (node.isFile() || node.isDirectory()) {
String sf = node.getAbsoluteFile().toString();
sourceFolder = sf.substring(0, (sf.lastIndexOf("/") > 0 ? sf.lastIndexOf("/") : sf.lastIndexOf("\\")));
sourceFolder += File.separator;
} else
sourceFolder = null;
}
private String generateZipEntry(String file) {
return file.substring(sourceFolder.length(), file.length());
}
Config file:
worker_processes 4; # 2 * Number of CPUs
events {
worker_connections 19000; # It's the key to high performance - have a lot of connections available
}
worker_rlimit_nofile 20000; # Each connection needs a filehandle (or 2 if you are proxying)
# Total amount of users you can serve = worker_processes * worker_connections
more info: Optimizing nginx for high traffic loads
According to 3.9 version of Docker compose, you can use image: myapp:tag
to specify name and tag.
version: "3.9"
services:
webapp:
build:
context: .
dockerfile: Dockerfile
image: webapp:tag
Reference: https://docs.docker.com/compose/compose-file/compose-file-v3/
It's easier than you wonder.
If you are working with a separated by semicolon file and header too:
$ (head -n1 file.csv && sort file.csv | grep -v <header>) | column -s";" -t
If you are working with array (using tab as separator):
for((i=0;i<array_size;i++));
do
echo stringarray[$i] $'\t' numberarray[$i] $'\t' anotherfieldarray[$i] >> tmp_file.csv
done;
cat file.csv | column -t
There is a list option in Data validation. If this is combined with a VLOOKUP formula you would be able to convert the selected value into a number.
The steps in Excel 2010 are:
In a cell enter a formula like this
=VLOOKUP(A2,$D$3:$E$5,2,FALSE)
which will return the matching value from the second part of your list.
Alternatively, Form controls can be placed on a worksheet. They can be linked to a range and return the position number of the selected value to a specific cell.
The steps in Excel 2010 are:
If you really want to eke out performance (with big arrays), numexpr can be used, which takes advantage of multiple cores.
Setup:
>>> import numpy as np
>>> Data = np.random.randn(64, 64, 64, 2)
>>> x, y = Data[...,0], Data[...,1]
With numexpr
:
>>> import numexpr as ne
>>> %timeit result = ne.evaluate("complex(x, y)")
573 µs ± 21.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Compared to fast numpy method:
>>> %timeit result = np.empty(x.shape, dtype=complex); result.real = x; result.imag = y
1.39 ms ± 5.74 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
URLEncoder
is the way to go. You only need to keep in mind to encode only the individual query string parameter name and/or value, not the entire URL, for sure not the query string parameter separator character &
nor the parameter name-value separator character =
.
String q = "random word £500 bank $";
String url = "https://example.com?q=" + URLEncoder.encode(q, StandardCharsets.UTF_8);
When you're still not on Java 10 or newer, then use StandardCharsets.UTF_8.toString()
as charset argument, or when you're still not on Java 7 or newer, then use "UTF-8"
.
Note that spaces in query parameters are represented by +
, not %20
, which is legitimately valid. The %20
is usually to be used to represent spaces in URI itself (the part before the URI-query string separator character ?
), not in query string (the part after ?
).
Also note that there are three encode()
methods. One without Charset
as second argument and another with String
as second argument which throws a checked exception. The one without Charset
argument is deprecated. Never use it and always specify the Charset
argument. The javadoc even explicitly recommends to use the UTF-8 encoding, as mandated by RFC3986 and W3C.
All other characters are unsafe and are first converted into one or more bytes using some encoding scheme. Then each byte is represented by the 3-character string "%xy", where xy is the two-digit hexadecimal representation of the byte. The recommended encoding scheme to use is UTF-8. However, for compatibility reasons, if an encoding is not specified, then the default encoding of the platform is used.
By default, MomentJS parses in local time. If only a date string (with no time) is provided, the time defaults to midnight.
In your code, you create a local date and then convert it to the UTC timezone (in fact, it makes the moment instance switch to UTC mode), so when it is formatted, it is shifted (depending on your local time) forward or backwards.
If the local timezone is UTC+N (N being a positive number), and you parse a date-only string, you will get the previous date.
Here are some examples to illustrate it (my local time offset is UTC+3 during DST):
>>> moment('07-18-2013', 'MM-DD-YYYY').utc().format("YYYY-MM-DD HH:mm")
"2013-07-17 21:00"
>>> moment('07-18-2013 12:00', 'MM-DD-YYYY HH:mm').utc().format("YYYY-MM-DD HH:mm")
"2013-07-18 09:00"
>>> Date()
"Thu Jul 25 2013 14:28:45 GMT+0300 (Jerusalem Daylight Time)"
If you want the date-time string interpreted as UTC, you should be explicit about it:
>>> moment(new Date('07-18-2013 UTC')).utc().format("YYYY-MM-DD HH:mm")
"2013-07-18 00:00"
or, as Matt Johnson mentions in his answer, you can (and probably should) parse it as a UTC date in the first place using moment.utc()
and include the format string as a second argument to prevent ambiguity.
>>> moment.utc('07-18-2013', 'MM-DD-YYYY').format("YYYY-MM-DD HH:mm")
"2013-07-18 00:00"
To go the other way around and convert a UTC date to a local date, you can use the local()
method, as follows:
>>> moment.utc('07-18-2013', 'MM-DD-YYYY').local().format("YYYY-MM-DD HH:mm")
"2013-07-18 03:00"
Isn't this what default constructors are for?
class MyModel
{
public MyModel()
{
this.ReturnDate = DateTime.Now;
}
public date ReturnDate {get; set;};
}
Currently there's no search support for Docker Registry v2.
There was a long-running thread on the topic. The current plan is to support search with an extension in the end, which should be ready by v2.1.
As a workaround, execute the following on the machine where your registry v2 is running:
> docker exec -it <your_registry_container_id> bash
> ls /var/lib/registry/docker/registry/v2/repositories/
The images are in subdirectories corresponding to their namespace, e.g. jwilder/nginx-proxy
The recommended way to do date/time manipulation is to use a Calendar
object:
Calendar cal = Calendar.getInstance(); // locale-specific
cal.setTime(dateObject);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long time = cal.getTimeInMillis();
Change the FormBorderStyle
to one of the fixed values: FixedSingle
, Fixed3D
,
FixedDialog
or FixedToolWindow
.
The FormBorderStyle
property is under the Appearance category.
Or check this:
// Define the border style of the form to a dialog box.
form1.FormBorderStyle = FormBorderStyle.FixedDialog;
// Set the MaximizeBox to false to remove the maximize box.
form1.MaximizeBox = false;
// Set the MinimizeBox to false to remove the minimize box.
form1.MinimizeBox = false;
// Set the start position of the form to the center of the screen.
form1.StartPosition = FormStartPosition.CenterScreen;
// Display the form as a modal dialog box.
form1.ShowDialog();
As an alternative to using git config --global http.proxy address:port
, you can set the proxy on the command line:
git -c "http.proxy=address:port" clone https://...
The advantage is the proxy is not persistently set. Under Bash you might set an alias:
alias git-proxy='git -c "http.proxy=address:port"'
Just to complement the other fine answers provided, as I too recently wanted a single error/exception handling component in a simple SpringBoot app containing filters that may throw exceptions, with other exceptions potentially thrown from controller methods.
Fortunately, it seems there is nothing to prevent you from combining your controller advice with an override of Spring's default error handler to provide consistent response payloads, allow you to share logic, inspect exceptions from filters, trap specific service-thrown exceptions, etc.
E.g.
@ControllerAdvice
@RestController
public class GlobalErrorHandler implements ErrorController {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ValidationException.class)
public Error handleValidationException(
final ValidationException validationException) {
return new Error("400", "Incorrect params"); // whatever
}
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public Error handleUnknownException(final Exception exception) {
return new Error("500", "Unexpected error processing request");
}
@RequestMapping("/error")
public ResponseEntity handleError(final HttpServletRequest request,
final HttpServletResponse response) {
Object exception = request.getAttribute("javax.servlet.error.exception");
// TODO: Logic to inspect exception thrown from Filters...
return ResponseEntity.badRequest().body(new Error(/* whatever */));
}
@Override
public String getErrorPath() {
return "/error";
}
}
I'd use an Inline Function from performance perspective, see below: Note that symbols like '+','-' etc will not be removed
CREATE FUNCTION [dbo].[UDF_RemoveNumericStringsFromString]
(
@str varchar(100)
)
RETURNS TABLE AS RETURN
WITH Tally (n) as
(
-- 100 rows
SELECT TOP (Len(@Str)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
FROM (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) a(n)
CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) b(n)
)
SELECT OutStr = STUFF(
(SELECT SUBSTRING(@Str, n,1) st
FROM Tally
WHERE ISNUMERIC(SUBSTRING(@Str, n,1)) = 1
FOR XML PATH(''),type).value('.', 'varchar(100)'),1,0,'')
GO
/*Use it*/
SELECT OutStr
FROM dbo.UDF_RemoveNumericStringsFromString('fjkfhk759734977fwe9794t23')
/*Result set
759734977979423 */
You can define it with more than 100 characters...
extension Sequence where Element: Hashable {
func unique() -> [Element] {
NSOrderedSet(array: self as! [Any]).array as! [Element]
}
}
Today I ran on a Windows Git Bash:
$ npm i node -g
and got the following output:
> [email protected] preinstall C:\Users\X\AppData\Roaming\npm\node_modules\node
> node installArchSpecificPackage
+ [email protected]
added 1 package and audited 1 package in 23.368s
found 0 vulnerabilities
C:\Users\X\AppData\Roaming\npm\node -> C:\Users\X\AppData\Roaming\npm\node_modules\node\bin\node
+ [email protected]
added 2 packages from 1 contributor in 26.089s
Read more about it at https://www.npmjs.com/package/node.
Check the GridView1.SelectedRow is not null:
if (GridView1.SelectedRow == null) return;
string DeleteThis = GridView1.SelectedRow.Cells[0].Text;
I'll add my solution here. We can use floor when values are above 0 and ceil when they are less than zero:
function truncateToInt(x)
{
if(x > 0)
{
return Math.floor(x);
}
else
{
return Math.ceil(x);
}
}
Then:
y = truncateToInt(2.9999); // results in 2
y = truncateToInt(-3.118); //results in -3
Notice: This answer was written when Math.trunc(x)
was fairly new and not supported by a lot of browsers. Today, modern browsers support Math.trunc(x)
.
It's not really a bug, just a difference in implantation by the browser vendors.
As a rule avoid browser sniffing. There is a nifty jQuery fix which is hinted at in the answers.
This is what works for me: $('html:not(:animated),body:not(:animated)').scrollTop()
To compile with release build as shown below:
static_cast< Type* >(ptr)
static_cast in C++ can be used in scenarios where all type casting can be verified at compile time.
dynamic_cast< Type* >(ptr)
dynamic_cast in C++ can be used to perform type safe down casting. dynamic_cast is run time polymorphism. The dynamic_cast operator, which safely converts from a pointer (or reference) to a base type to a pointer (or reference) to a derived type.
eg 1:
#include <iostream>
using namespace std;
class A
{
public:
virtual void f(){cout << "A::f()" << endl;}
};
class B : public A
{
public:
void f(){cout << "B::f()" << endl;}
};
int main()
{
A a;
B b;
a.f(); // A::f()
b.f(); // B::f()
A *pA = &a;
B *pB = &b;
pA->f(); // A::f()
pB->f(); // B::f()
pA = &b;
// pB = &a; // not allowed
pB = dynamic_cast<B*>(&a); // allowed but it returns NULL
return 0;
}
For more information click here
eg 2:
#include <iostream>
using namespace std;
class A {
public:
virtual void print()const {cout << " A\n";}
};
class B {
public:
virtual void print()const {cout << " B\n";}
};
class C: public A, public B {
public:
void print()const {cout << " C\n";}
};
int main()
{
A* a = new A;
B* b = new B;
C* c = new C;
a -> print(); b -> print(); c -> print();
b = dynamic_cast< B*>(a); //fails
if (b)
b -> print();
else
cout << "no B\n";
a = c;
a -> print(); //C prints
b = dynamic_cast< B*>(a); //succeeds
if (b)
b -> print();
else
cout << "no B\n";
}
You can try the following:
theAnchorText = "I'm home";
OR
theAnchorText = 'I\'m home';
Please find below codes for ios 10 request permission sample for info.plist
.
You can modify for your custom message.
<key>NSCameraUsageDescription</key>
<string>${PRODUCT_NAME} Camera Usage</string>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>${PRODUCT_NAME} BluetoothPeripheral</string>
<key>NSCalendarsUsageDescription</key>
<string>${PRODUCT_NAME} Calendar Usage</string>
<key>NSContactsUsageDescription</key>
<string>${PRODUCT_NAME} Contact fetch</string>
<key>NSHealthShareUsageDescription</key>
<string>${PRODUCT_NAME} Health Description</string>
<key>NSHealthUpdateUsageDescription</key>
<string>${PRODUCT_NAME} Health Updates</string>
<key>NSHomeKitUsageDescription</key>
<string>${PRODUCT_NAME} HomeKit Usage</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>${PRODUCT_NAME} Use location always</string>
<key>NSLocationUsageDescription</key>
<string>${PRODUCT_NAME} Location Updates</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>${PRODUCT_NAME} WhenInUse Location</string>
<key>NSAppleMusicUsageDescription</key>
<string>${PRODUCT_NAME} Music Usage</string>
<key>NSMicrophoneUsageDescription</key>
<string>${PRODUCT_NAME} Microphone Usage</string>
<key>NSMotionUsageDescription</key>
<string>${PRODUCT_NAME} Motion Usage</string>
<key>kTCCServiceMediaLibrary</key>
<string>${PRODUCT_NAME} MediaLibrary Usage</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>${PRODUCT_NAME} PhotoLibrary Usage</string>
<key>NSRemindersUsageDescription</key>
<string>${PRODUCT_NAME} Reminder Usage</string>
<key>NSSiriUsageDescription</key>
<string>${PRODUCT_NAME} Siri Usage</string>
<key>NSSpeechRecognitionUsageDescription</key>
<string>${PRODUCT_NAME} Speech Recognition Usage</string>
<key>NSVideoSubscriberAccountUsageDescription</key>
<string>${PRODUCT_NAME} Video Subscribe Usage</string>
iOS 11 and plus, If you want to add photo/image to your library then you must add this key
<key>NSPhotoLibraryAddUsageDescription</key>
<string>${PRODUCT_NAME} library Usage</string>
If you don't have a database, where will the PERMANENT record of your users' login data be stored? Sure, while the user is logged in, the minimal user information required for your site to work can be stored in a session or cookie. But after they log out, then what? The session goes away, the cookie can be hacked.
So your user comes back to your site. He tries to log in. What trustworthy thing does your site compare his login info to?
Matt Ball answered it correctly. I would say about it with examples.
Consider running a program compiled in Turbo-Borland C/C++ (version 3.1 from the year 1991) compiler and let it run under a 32-bit version of windows like Win 98/2000 etc.
It's a 16-bit compiler. And you will see all your programs have 16-bit pointers. Why is it so when your OS is 32bit? Because your compiler has set up the execution environment of 16 bit and the 32-bit version of OS supported it.
What is commonly called as JRE (Java Runtime Environment) provides a Java program with all the resources it may need to execute.
Actually, runtime environment is brain product of idea of Virtual Machines. A virtual machine implements the raw interface between hardware and what a program may need to execute. The runtime environment adopts these interfaces and presents them for the use of the programmer. A compiler developer would need these facilities to provide an execution environment for its programs.
See from How to Replace String in File works in a simple way and is an answer that works with replace
fin = open("data.txt", "rt")
fout = open("out.txt", "wt")
for line in fin:
fout.write(line.replace('pyton', 'python'))
fin.close()
fout.close()
using LINQ and Lamba, i wanted to return two field values and assign it to single entity object field;
as Name = Fname + " " + LName;
See my below code which is working as expected; hope this is useful;
Myentity objMyEntity = new Myentity
{
id = obj.Id,
Name = contxt.Vendors.Where(v => v.PQS_ID == obj.Id).Select(v=> new { contact = v.Fname + " " + v.LName}).Single().contact
}
no need to declare the 'contact'
I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray()
According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.
This will work for you:
$phpExcel = new PHPExcel();
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
To apply font style to complete excel document:
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getDefaultStyle()
->applyFromArray($styleArray);
For swift 3 & 4
let customView = Bundle.main.loadNibNamed("CustomView", owner: nil, options: nil)?.first as? CustomView
If you choose to use a generic collection, such as List<MyObject>
instead of ArrayList
, you'll find that the List<MyObject>
will provide both generic and non-generic enumerators that you can use.
using System.Collections;
class MyObjects : IEnumerable<MyObject>
{
List<MyObject> mylist = new List<MyObject>();
public MyObject this[int index]
{
get { return mylist[index]; }
set { mylist.Insert(index, value); }
}
public IEnumerator<MyObject> GetEnumerator()
{
return mylist.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
Generally there are two ways to do it, a converter class or a property in the Viewmodel that essentially converts the value for you.
I tend to use the property approach if it is a one off conversion. If you want to reuse it, use the converter. Below, find an example of the converter:
<ValueConversion(GetType(Boolean), GetType(Visibility))> _
Public Class BoolToVisibilityConverter
Implements IValueConverter
Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
If value IsNot Nothing Then
If value = True Then
Return Visibility.Visible
Else
Return Visibility.Collapsed
End If
Else
Return Visibility.Collapsed
End If
End Function
Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
Throw New NotImplementedException
End Function
End Class
A ViewModel property method would just check the boolean property value, and return a visibility based on that. Be sure to implement INotifyPropertyChanged and call it on both the Boolean and Visibility properties to updated properly.
JLabel label = new JLabel("fax", SwingConstants.RIGHT);
You can target that div from your stylesheet in a number of ways.
Simply use
.col-md-6:first-child {
background-color: blue;
}
Another way is to assign a class to one div and then apply the style to that class.
<div class="col-md-6 blue"></div>
.blue {
background-color: blue;
}
There are also inline styles.
<div class="col-md-6" style="background-color: blue"></div>
Your example code works fine to me. I'm not sure if I undestand what you intend to do, but if you want a blue background on the second div just remove the bg-primary
class from the section and add you custom class to the div.
.blue {_x000D_
background-color: blue;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<section id="about">_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<!-- Columns are always 50% wide, on mobile and desktop -->_x000D_
<div class="col-xs-6">_x000D_
<h2 class="section-heading text-center">Title</h2>_x000D_
<p class="text-faded text-center">.col-md-6</p>_x000D_
</div>_x000D_
<div class="col-xs-6 blue">_x000D_
<h2 class="section-heading text-center">Title</h2>_x000D_
<p class="text-faded text-center">.col-md-6</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</section>
_x000D_
For those like me who are brand new to this, here is code with const and an actual way to compare the byte[]'s. I got all of this code from stackoverflow but defined consts so values could be changed and also
// 24 = 192 bits
private const int SaltByteSize = 24;
private const int HashByteSize = 24;
private const int HasingIterationsCount = 10101;
public static string HashPassword(string password)
{
// http://stackoverflow.com/questions/19957176/asp-net-identity-password-hashing
byte[] salt;
byte[] buffer2;
if (password == null)
{
throw new ArgumentNullException("password");
}
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, SaltByteSize, HasingIterationsCount))
{
salt = bytes.Salt;
buffer2 = bytes.GetBytes(HashByteSize);
}
byte[] dst = new byte[(SaltByteSize + HashByteSize) + 1];
Buffer.BlockCopy(salt, 0, dst, 1, SaltByteSize);
Buffer.BlockCopy(buffer2, 0, dst, SaltByteSize + 1, HashByteSize);
return Convert.ToBase64String(dst);
}
public static bool VerifyHashedPassword(string hashedPassword, string password)
{
byte[] _passwordHashBytes;
int _arrayLen = (SaltByteSize + HashByteSize) + 1;
if (hashedPassword == null)
{
return false;
}
if (password == null)
{
throw new ArgumentNullException("password");
}
byte[] src = Convert.FromBase64String(hashedPassword);
if ((src.Length != _arrayLen) || (src[0] != 0))
{
return false;
}
byte[] _currentSaltBytes = new byte[SaltByteSize];
Buffer.BlockCopy(src, 1, _currentSaltBytes, 0, SaltByteSize);
byte[] _currentHashBytes = new byte[HashByteSize];
Buffer.BlockCopy(src, SaltByteSize + 1, _currentHashBytes, 0, HashByteSize);
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, _currentSaltBytes, HasingIterationsCount))
{
_passwordHashBytes = bytes.GetBytes(SaltByteSize);
}
return AreHashesEqual(_currentHashBytes, _passwordHashBytes);
}
private static bool AreHashesEqual(byte[] firstHash, byte[] secondHash)
{
int _minHashLength = firstHash.Length <= secondHash.Length ? firstHash.Length : secondHash.Length;
var xor = firstHash.Length ^ secondHash.Length;
for (int i = 0; i < _minHashLength; i++)
xor |= firstHash[i] ^ secondHash[i];
return 0 == xor;
}
In in your custom ApplicationUserManager, you set the PasswordHasher property the name of the class which contains the above code.
The same instance for SP2010; the Links List webpart will not automatically open in a new window, rather user must manually rt click Link object and select Open in New Window.
The add/ insert Link option withkin SP2010 will allow a user to manually configure the link to open in a new window.
Maybe SP2012 release will adrress this...
Use the wc utility with the print the byte counts (-c
) option:
$ SO="stackoverflow"
$ echo -n "$SO" | wc -c
13
You'll have to use the do not output the trailing newline (-n
) option for echo
. Otherwise, the newline character will also be counted.
Try a simple where query
var filtered = unfilteredApps.Where(i => !excludedAppIds.Contains(i.Id));
The except method uses equality, your lists contain objects of different types, so none of the items they contain will be equal!
I went through this when trying to get a clientcert and private key out of a keystore.
The link above posted by welsh was great, but there was an extra step on my redhat distribution. If curl is built with NSS ( run curl --version
to see if you see NSS listed) then you need to import the keys into an NSS keystore. I went through a bunch of convoluted steps, so this may not be the cleanest way, but it got things working
So export the keys into .p12
keytool -importkeystore -srckeystore $jksfile -destkeystore $p12file \ -srcstoretype JKS -deststoretype PKCS12 \ -srcstorepass $jkspassword -deststorepass $p12password -srcalias $myalias -destalias $myalias \ -srckeypass $keypass -destkeypass $keypass -noprompt
And generate the pem file that holds only the key
echo making ${fileroot}.key.pem openssl pkcs12 -in $p12 -out ${fileroot}.key.pem \ -passin pass:$p12password \ -passout pass:$p12password -nocerts
mkdir ~/nss chmod 700 ~/nss certutil -N -d ~/nss
pks12util -i <mykeys>.p12 -d ~/nss -W <password for cert >
Now curl should work.
curl --insecure --cert <client cert alias>:<password for cert> \ --key ${fileroot}.key.pem <URL>
As I mentioned, there may be other ways to do this, but at least this was repeatable for me. If curl is compiled with NSS support, I was not able to get it to pull the client cert from a file.
You could try something like
<form name="message" method="post">
<section>
<div>
<label for="name">Name</label>
<input id="name" type="text" value="" name="name">
</div>
<div>
<label for="email">Email</label>
<input id="email" type="text" value="" name="email">
</div>
</section>
<section>
<div>
<label for="subject">Subject</label>
<input id="subject" type="text" value="" name="subject">
</div>
<div class="full">
<label for="message">Message</label>
<input id="message" type="text" value="" name="message">
</div>
</section>
</form>
and then css it like
form { width: 400px; }
form section div { float: left; }
form section div.full { clear: both; }
form section div label { display: block; }
I imported a project as 'Existing Maven Project' and was getting this issue.
Resolution: Changed Java Build Path of JRE System Library to Workspace defailt JRE [jdk 1.8]
Steps:
Right click on project -> build path -> configure build path -> Libraries Tab -> double click JRE System Library -> change to Workspace defailt JRE [jdk 1.8]
At the beginning of your file you set raw_input
to 0. Do not do this, at it modifies the built-in raw_input()
function. Therefore, whenever you call raw_input()
, it is essentially calling 0()
, which raises the error. To remove the error, remove the first line of your code:
M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54
def intro():
print("Welcome! This program will convert measures for you.")
main()
def main():
print("Select operation.")
print("1.Miles to Kilometers")
print("2.Fahrenheit to Celsius")
print("3.Gallons to liters")
print("4.Pounds to kilograms")
print("5.Inches to centimeters")
choice = input("Enter your choice by number: ")
if choice == '1':
convertMK()
elif choice == '2':
converCF()
elif choice == '3':
convertGL()
elif choice == '4':
convertPK()
elif choice == '5':
convertPK()
else:
print("Error")
def convertMK():
input_M = float(raw_input(("Miles: ")))
M_conv = (M) * input_M
print("Kilometers: %f\n" % M_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def converCF():
input_F = float(raw_input(("Fahrenheit: ")))
F_conv = (input_F - 32) * 5/9
print("Celcius: %f\n") % F_conv
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def convertGL():
input_G = float(raw_input(("Gallons: ")))
G_conv = input_G * 3.6
print("Centimeters: %f\n" % G_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertPK():
input_P = float(raw_input(("Pounds: ")))
P_conv = input_P * 0.45
print("Centimeters: %f\n" % P_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertIC():
input_cm = float(raw_input(("Inches: ")))
inches_conv = input_cm * 2.54
print("Centimeters: %f\n" % inches_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def end():
print("This program will close.")
exit()
intro()
This Worked for me. i implemented this solution in reactJS
const requestOptions = {`enter code here`
method: 'GET',
headers: { 'Content-Type': 'application/json' }
};
fetch(`${url}`, requestOptions)
.then((res) => {
return res.blob();
})
.then((blob) => {
const href = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = href;
link.setAttribute('download', 'config.json'); //or any other extension
document.body.appendChild(link);
link.click();
})
.catch((err) => {
return Promise.reject({ Error: 'Something Went Wrong', err });
})
this function takes the number and precision and returns the rounded off number
float roundoff(float num,int precision)
{
int temp=(int )(num*pow(10,precision));
int num1=num*pow(10,precision+1);
temp*=10;
temp+=5;
if(num1>=temp)
num1+=10;
num1/=10;
num1*=10;
num=num1/pow(10,precision+1);
return num;
}
it converts the floating point number into int by left shifting the point and checking for the greater than five condition.
I'll talk about the HashMap and TreeMap implementation in Java:
HashMap -- implement basic map interface
Map m = Collections.synchronizedMap(new HashMap(...));
TreeMap -- implement navigable map interface
SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));
To sum, the biggest difference between HashMap and TreeMap is that TreeMap implements NavigableMap<K,V>
, which provide the feature of ordered iteration. Besides, both HashMap and TreeMap are members of Java Collection framework. You can investigate the source code of Java to know more about their implementations.
I got here with a similar problem with my Gradle build and fixed it in a similar way:
Unable to load class hudson.model.User due to missing dependency javax/servlet/ServletException
fixed with:
dependencies {
implementation('javax.servlet:javax.servlet-api:3.0.1')
}
A simple alternative solution:
Paste the URL into a json to csv converter
Open the CSV file in either Excel or Open Office
Use the spreadsheet tools to parse the data
I think this means that
You have three options to solve this
Use maven-compiler-plugin version or later, because
NOTE: Since 3.8.0 the default value has changed from 1.5 to 1.6 See https://maven.apache.org/plugins/maven-compiler-plugin/compile-mojo.html#target
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
Indicate to the maven-compiler-plugin to use source level 6 and target 6 (or later).
Best practice recommended by https://maven.apache.org/plugins/maven-compiler-plugin/
Also note that at present the default source setting is 1.6 and the default target setting is 1.6, independently of the JDK you run Maven with. You are highly encouraged to change these defaults by setting source and target as described in Setting the -source and -target of the Java Compiler.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
or use
<properties>
<maven.compiler.source>1.6</maven.compiler.source>
<maven.compiler.target>1.6</maven.compiler.target>
</properties>
<a href="<?php echo $_SERVER['DOCUMENT_ROOT'].'/hello.html'; ?>">go with php</a>
<br />
<a href="/hello.html">go to with html</a>
Try this yourself and find that they are not exactly the same.
$_SERVER['DOCUMENT_ROOT']
renders an actual file path (on my computer running as it's own server, C:/wamp/www/
HTML's /
renders the root of the server url, in my case, localhost/
But C:/wamp/www/hello.html
and localhost/hello.html
are in fact the same file
There are some problems with your code. First I advise to use parametrized queries so you avoid SQL Injection attacks and also parameter types are discovered by framework:
var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con);
cmd.Parameters.AddWithValue("@id", id.Text);
Second, as you are interested only in one value getting returned from the query, it is better to use ExecuteScalar
:
var name = cmd.ExecuteScalar();
if (name != null)
{
position = name.ToString();
Response.Write("User Registration successful");
}
else
{
Console.WriteLine("No Employee found.");
}
The last thing is to wrap SqlConnection
and SqlCommand
into using
so any resources used by those will be disposed of:
string position;
using (SqlConnection con = new SqlConnection("server=free-pc\\FATMAH; Integrated Security=True; database=Workflow; "))
{
con.Open();
using (var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con))
{
cmd.Parameters.AddWithValue("@id", id.Text);
var name = cmd.ExecuteScalar();
if (name != null)
{
position = name.ToString();
Response.Write("User Registration successful");
}
else
{
Console.WriteLine("No Employee found.");
}
}
}
If you are using ASP.NET Core MVC, the answers above are ever so slightly altered...
In my action method (which returns async Task<JsonResult>
) I add the line (anywhere before the return statement):
Response.Headers.Add("Content-Disposition", $"attachment; filename={myFileName}");
There's a few useful functions for dealing with errno
s. (Just to make it clear, these are built-in to libc
-- I'm just providing sample implementations because some people find reading code clearer than reading English.)
#include <string.h>
char *strerror(int errnum);
/* you can think of it as being implemented like this: */
static char strerror_buf[1024];
const char *sys_errlist[] = {
[EPERM] = "Operation not permitted",
[ENOENT] = "No such file or directory",
[ESRCH] = "No such process",
[EINTR] = "Interrupted system call",
[EIO] = "I/O error",
[ENXIO] = "No such device or address",
[E2BIG] = "Argument list too long",
/* etc. */
};
int sys_nerr = sizeof(sys_errlist) / sizeof(char *);
char *strerror(int errnum) {
if (0 <= errnum && errnum < sys_nerr && sys_errlist[errnum])
strcpy(strerror_buf, sys_errlist[errnum]);
else
sprintf(strerror_buf, "Unknown error %d", errnum);
return strerror_buf;
}
strerror
returns a string describing the error number you've passed to it. Caution, this is not thread- or interrupt-safe; it is free to rewrite the string and return the same pointer on the next invocation. Use strerror_r
if you need to worry about that.
#include <stdio.h>
void perror(const char *s);
/* you can think of it as being implemented like this: */
void perror(const char *s) {
fprintf(stderr, "%s: %s\n", s, strerror(errno));
}
perror
prints out the message you give it, plus a string describing the current errno
, to standard error.
In most cases, you shouldn't use a regex for that.
os.path.splitext(filename)[0]
This will also handle a filename like .bashrc
correctly by keeping the whole name.
As far as I know, transitions currently work in Safari, Chrome, Firefox, Opera and Internet Explorer 10+.
This should produce a fade effect for you in these browsers:
a {_x000D_
background-color: #FF0;_x000D_
}_x000D_
_x000D_
a:hover {_x000D_
background-color: #AD310B;_x000D_
-webkit-transition: background-color 1000ms linear;_x000D_
-ms-transition: background-color 1000ms linear;_x000D_
transition: background-color 1000ms linear;_x000D_
}
_x000D_
<a>Navigation Link</a>
_x000D_
Note: As pointed out by Gerald in the comments, if you put the transition on the a
, instead of on a:hover
it will fade back to the original color when your mouse moves away from the link.
This might come in handy, too: CSS Fundamentals: CSS 3 Transitions
Put the path of your chrome application and do not forget to put th %s at the end. I am still trying to open the browser with html code without saving the file... I will add the code when I'll find how.
import webbrowser
chromedir= "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s"
webbrowser.get(chromedir).open("http://pythonprogramming.altervista.org")
If you want to fill NaN for a specific column you can use loc:
d1 = {"Col1" : ['A', 'B', 'C'],
"fruits": ['Avocado', 'Banana', 'NaN']}
d1= pd.DataFrame(d1)
output:
Col1 fruits
0 A Avocado
1 B Banana
2 C NaN
d1.loc[ d1.Col1=='C', 'fruits' ] = 'Carrot'
output:
Col1 fruits
0 A Avocado
1 B Banana
2 C Carrot
You can use bellow code to get route name in blade file
request()->route()->uri
Regarding David Elizondo's answer, this can give false positives. It also does not give zeroes where the values don't match.
DECLARE @t1 TABLE (
ColID int IDENTITY,
Col2 int
)
DECLARE @t2 TABLE (
ColID int IDENTITY,
Col2 int
)
INSERT INTO @t1 (Col2) VALUES (123)
INSERT INTO @t1 (Col2) VALUES (234)
INSERT INTO @t1 (Col2) VALUES (456)
INSERT INTO @t1 (Col2) VALUES (1)
INSERT INTO @t2 (Col2) VALUES (123)
INSERT INTO @t2 (Col2) VALUES (345)
INSERT INTO @t2 (Col2) VALUES (456)
INSERT INTO @t2 (Col2) VALUES (2)
SELECT
t1.Col2 AS t1Col2,
t2.Col2 AS t2Col2,
ISNULL(NULLIF(t1.Col2, t2.Col2), 1) AS MyDesiredResult
FROM @t1 AS t1
JOIN @t2 AS t2 ON t1.ColID = t2.ColID
t1Col2 t2Col2 MyDesiredResult
----------- ----------- ---------------
123 123 1
234 345 234 <- Not a zero
456 456 1
1 2 1 <- Not a match
delete this line:
jsonp: 'jsonp_callback',
Or replace this line:
url: 'http://url.of.my.server/submit?callback=json_callback',
because currently you are asking jQuery to create a random callback function name with callback=?
and then telling jQuery that you want to use jsonp_callback
instead.
Take a look at this:
(reprinted from the expired blog page http://jamiethompson.co.uk/web/2008/06/17/publish-subscribe-with-jquery/ based on the archived version at http://web.archive.org/web/20130120010146/http://jamiethompson.co.uk/web/2008/06/17/publish-subscribe-with-jquery/)
June 17th, 2008
With a view to writing a jQuery UI integrated with the offline functionality of Google Gears i’ve been toying with some code to poll for network connection status using jQuery.
The basic premise is very simple. We create an instance of a network detection object which will poll a URL at regular intervals. Should these HTTP requests fail we can assume that network connectivity has been lost, or the server is simply unreachable at the current time.
$.networkDetection = function(url,interval){
var url = url;
var interval = interval;
online = false;
this.StartPolling = function(){
this.StopPolling();
this.timer = setInterval(poll, interval);
};
this.StopPolling = function(){
clearInterval(this.timer);
};
this.setPollInterval= function(i) {
interval = i;
};
this.getOnlineStatus = function(){
return online;
};
function poll() {
$.ajax({
type: "POST",
url: url,
dataType: "text",
error: function(){
online = false;
$(document).trigger('status.networkDetection',[false]);
},
success: function(){
online = true;
$(document).trigger('status.networkDetection',[true]);
}
});
};
};
You can view the demo here. Set your browser to work offline and see what happens…. no, it’s not very exciting.
What is exciting though (or at least what is exciting me) is the method by which the status gets relayed through the application. I’ve stumbled upon a largely un-discussed method of implementing a pub/sub system using jQuery’s trigger and bind methods.
The demo code is more obtuse than it need to be. The network detection object publishes ’status ‘events to the document which actively listens for them and in turn publishes ‘notify’ events to all subscribers (more on those later). The reasoning behind this is that in a real world application there would probably be some more logic controlling when and how the ‘notify’ events are published.
$(document).bind("status.networkDetection", function(e, status){
// subscribers can be namespaced with multiple classes
subscribers = $('.subscriber.networkDetection');
// publish notify.networkDetection even to subscribers
subscribers.trigger("notify.networkDetection", [status])
/*
other logic based on network connectivity could go here
use google gears offline storage etc
maybe trigger some other events
*/
});
Because of jQuery’s DOM centric approach events are published to (triggered on) DOM elements. This can be the window or document object for general events or you can generate a jQuery object using a selector. The approach i’ve taken with the demo is to create an almost namespaced approach to defining subscribers.
DOM elements which are to be subscribers are classed simply with “subscriber” and “networkDetection”. We can then publish events only to these elements (of which there is only one in the demo) by triggering a notify event on $(“.subscriber.networkDetection”)
The #notifier
div which is part of the .subscriber.networkDetection
group of subscribers then has an anonymous function bound to it, effectively acting as a listener.
$('#notifier').bind("notify.networkDetection",function(e, online){
// the following simply demonstrates
notifier = $(this);
if(online){
if (!notifier.hasClass("online")){
$(this)
.addClass("online")
.removeClass("offline")
.text("ONLINE");
}
}else{
if (!notifier.hasClass("offline")){
$(this)
.addClass("offline")
.removeClass("online")
.text("OFFLINE");
}
};
});
So, there you go. It’s all pretty verbose and my example isn’t at all exciting. It also doesn’t showcase anything interesting you could do with these methods, but if anyone’s at all interested to dig through the source feel free. All the code is inline in the head of the demo page
I've incurred in a weird behaviour using [].
We have Model "classes" with fields initialised to some value. E.g.:
require([
"dojo/_base/declare",
"dijit/_WidgetBase",
], function(declare, parser, ready, _WidgetBase){
declare("MyWidget", [_WidgetBase], {
field1: [],
field2: "",
function1: function(),
function2: function()
});
});
I found that when the fields are initialised with []
then it would be shared by all Model objects. Making changes to one affects all others.
This doesn't happen initialising them with new Array()
. Same for the initialisation of Objects ({}
vs new Object()
)
TBH I am not sure if its a problem with the framework we were using (Dojo)
Your tables should have as immediate children just tbody
and thead
elements, with the rows within*. So, amend the HTML to be:
<table border="1" width="100%" id="test">
<tbody>
<tr>
<td>
<table border="1" width="100%">
<tbody>
<tr>
<td>table 2</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
</tbody>
</table>
Then amend your selector slightly to this:
#test > tbody > tr:last-child { background:#ff0000; }
See it in action here. That makes use of the child selector, which:
...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.
So, you are targeting only direct children of tbody
elements that are themselves direct children of your #test
table.
The above is the neatest solution, as you don't need to over-ride any styles. The alternative would be to stick with your current set-up, and over-ride the background style for the inner table, like this:
#test tr:last-child { background:#ff0000; }
#test table tr:last-child { background:transparent; }
* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:
...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.
decimal d = 2;
int i = (int) d;
This should work just fine.
You could do this:
Map<String, List<Student>> map = new HashMap<String, List<Student>>();
List<Student> studlist = new ArrayList<Student>();
studlist.add(new Student("1726", "John", "New York"));
map.put("New York", studlist);
the keys will be locations and the values list of students. So later you can get a group of students just by using:
studlist = map.get("New York");
When calling the "name" element of $array, which is correct?:
$array[name]
$array['name']
Both will often work, but only the quoted form is correct. define('name', 0);
and watch the bugs fly. I've seen this way too much.
How can you force form elements be submitted as an array?
Append empty brackets to the name attribute: multiple <input type="checkbox" name="checkboxes[]" />
elements will be converted to an array on the server (e.g. $_POST['checkboxes'][0..n]
). I don't think it's 100% PHP-specific, but it sure beats looping through $_POST
for every possible 'checkboxes'.$i
element.
mysql_, mysqli_, or PDO?
Only one truly wrong answer here: the mysql_ library doesn't do prepared statements and can no longer excuse it's capacity for evil. Naming a function, one expected to be called multiple times per executed query, "mysql_real_escape_string()
", is just salt in the wound.
You can use zero-length positive look-aheads to specify each of your constraints separately:
(?=.{8,})(?=.*\p{Lu}.*\p{Lu})(?=.*[!@#$&*])(?=.*[0-9])(?=.*\p{Ll}.*\p{Ll})
If your regex engine doesn't support the \p
notation and pure ASCII is enough, then you can replace \p{Lu}
with [A-Z]
and \p{Ll}
with [a-z]
.
If anyone is looking to come back to the local environment after setting the minikube env, use following command.
eval $(docker-machine env -u)
If you have multiple files or directories and you want to zip them into independent *.gz
file you can do this. Optional -type f -atime
find -name "httpd-log*.txt" -type f -mtime +1 -exec tar -vzcf {}.gz {} \;
This will compress
httpd-log01.txt
httpd-log02.txt
to
httpd-log01.txt.gz
httpd-log02.txt.gz
https://code.google.com/p/worlddb/downloads/list
This database has multi languages country names, region names, city names and they's latitude and longitude number and country's alpha2 code .
You can download the derby-10.10.1.1.jar from the Maven Repository and place it in your WEB-INF/lib folder, like this Application/WEB-INF/lib/derby-10.10.1.1.jar. Your embedded AnnotationConfigEmbeddedWebApplicationContext will pickup the database driver and your webserver will start running without any issues :-)
git push --dry-run
git diff --stat HEAD remote/branch
I needed a solution for this issue as well and I used the answers in this thread to come up with the following:
.directive('tpReport', ['$parse', '$http', '$compile', '$templateCache', function($parse, $http, $compile, $templateCache)
{
var getTemplateUrl = function(type)
{
var templateUrl = '';
switch (type)
{
case 1: // Table
templateUrl = 'modules/tpReport/directives/table-report.tpl.html';
break;
case 0:
templateUrl = 'modules/tpReport/directives/default.tpl.html';
break;
default:
templateUrl = '';
console.log("Type not defined for tpReport");
break;
}
return templateUrl;
};
var linker = function (scope, element, attrs)
{
scope.$watch('data', function(){
var templateUrl = getTemplateUrl(scope.data[0].typeID);
var data = $templateCache.get(templateUrl);
element.html(data);
$compile(element.contents())(scope);
});
};
return {
controller: 'tpReportCtrl',
template: '<div>{{data}}</div>',
// Remove all existing content of the directive.
transclude: true,
restrict: "E",
scope: {
data: '='
},
link: linker
};
}])
;
Include in your html:
<tp-report data='data'></tp-report>
This directive is used for dynamically loading report templates based on the dataset retrieved from the server.
It sets a watch on the scope.data property and whenever this gets updated (when the users requests a new dataset from the server) it loads the corresponding directive to show the data.
my solucion is compile with other version
build.gradle (app)
compileSdkVersion 21
Good Luck
Have you tried the =DateValue()
function?
To include time value, just add the functions together:
=DateValue(A1)+TimeValue(A1)
Wow. I know this is an ancient thread but all I can say is do not call TimeZone.setDefault() in any user-level code. This always sets the Timezone for the whole JVM and is nearly always a very bad idea. Learn to use the joda.time library or the new DateTime class in Java 8 which is very similar to the joda.time library.
Try this it worked for me
Write this in your Controller
public class DemoController: Controller
public async Task<FileStreamResult> GetLogoImage(string logoimage)
{
string str = "" ;
var filePath = Server.MapPath("~/App_Data/" + SubfolderName);//If subfolder exist otherwise leave.
// DirectoryInfo dir = new DirectoryInfo(filePath);
string[] filePaths = Directory.GetFiles(@filePath, "*.*");
foreach (var fileTemp in filePaths)
{
str= fileTemp.ToString();
}
return File(new MemoryStream(System.IO.File.ReadAllBytes(str)), System.Web.MimeMapping.GetMimeMapping(str), Path.GetFileName(str));
}
Here is my view
<div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>
I have the same problem. I avoid it with remove.packages("Package making this confusion")
and it works. In my case, I don't need the second package, so that is not a very good idea.
Two things to keep in mind Content-Type and the Encoding
1) What if the file is css
if (/.(css)$/.test(path)) {
res.writeHead(200, {'Content-Type': 'text/css'});
res.write(data, 'utf8');
}
2) What if the file is jpg/png
if (/.(jpg)$/.test(path)) {
res.writeHead(200, {'Content-Type': 'image/jpg'});
res.end(data,'Base64');
}
Above one is just a sample code to explain the answer and not the exact code pattern.
Take a look at this question and this question for some good answers on C++ object instantiation.
This basic idea is that objects instantiated on the heap (using new) need to be cleaned up manually, those instantiated on the stack (without new) are automatically cleaned up when they go out of scope.
void SomeFunc()
{
Point p1 = Point(0,0);
} // p1 is automatically freed
void SomeFunc2()
{
Point *p1 = new Point(0,0);
delete p1; // p1 is leaked unless it gets deleted
}
In here:
if (ValidationUtils.isNullOrEmpty(lastName)) {
registrationErrors.add(ValidationErrors.LAST_NAME);
}
if (!ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
you check for null or empty value on lastname, but in isEmailValid you don't check for empty value. Something like this should do
if (ValidationUtils.isNullOrEmpty(email) || !ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
or better yet, fix your ValidationUtils.isEmailValid() to cope with null email values. It shouldn't crash, it should just return false.
Try this for immediate child elements of type div
$("#foo > div")[0].children.length
Use double braces {{
or }}
so your code becomes:
sb.AppendLine(String.Format("public {0} {1} {{ get; private set; }}",
prop.Type, prop.Name));
// For prop.Type of "Foo" and prop.Name of "Bar", the result would be:
// public Foo Bar { get; private set; }
Try use the command jar -xvf fileName.jar and then do export the content of the decompressed file into a new Java project into Eclipse.
I'm sure there's a more efficient way to do it, but I would probably do this:
string getTenDigitNumber(string input)
{
StringBuilder sb = new StringBuilder();
for(int i - 0; i < input.Length; i++)
{
int junk;
if(int.TryParse(input[i], ref junk))
sb.Append(input[i]);
}
return sb.ToString();
}
I had this problem when I try to write a very long url, the following works.
image_url = %w(
http://minio.127.0.0.1.xip.io:9000/
bucket29/docs/b7cfab0e-0119-452c-b262-1b78e3fccf38/
28ed3774-b234-4de2-9a11-7d657707f79c?
X-Amz-Algorithm=AWS4-HMAC-SHA256&
X-Amz-Credential=ABABABABABABABABA
%2Fus-east-1%2Fs3%2Faws4_request&
X-Amz-Date=20170702T000940Z&
X-Amz-Expires=3600&X-Amz-SignedHeaders=host&
X-Amz-Signature=ABABABABABABABABABABAB
ABABABABABABABABABABABABABABABABABABA
).join
Note, there must not be any newlines, white spaces when the url string is formed. If you want newlines, then use HEREDOC.
Here you have indentation for readability, ease of modification, without the fiddly quotes and backslashes on every line. The cost of joining the strings should be negligible.
This will occur in SQL Server as well if you don't run all of the statements at once. If you are highlighting a set of statements and executing the following:
DECLARE @LoopVar INT
SET @LoopVar = (SELECT COUNT(*) FROM SomeTable)
And then try to highlight another set of statements such as:
PRINT 'LoopVar is: ' + CONVERT(NVARCHAR(255), @LoopVar)
You will receive this error.
To convert utf-8 data, you can't assume a 1-1 correspondence between bytes and characters. Try this:
String file_string = new String(bytes, "UTF-8");
(Bah. I see I'm way to slow in hitting the Post Your Answer button.)
To read an entire file as a String, do something like this:
public String openFileToString(String fileName) throws IOException
{
InputStream is = new BufferedInputStream(new FileInputStream(fileName));
try {
InputStreamReader rdr = new InputStreamReader(is, "UTF-8");
StringBuilder contents = new StringBuilder();
char[] buff = new char[4096];
int len = rdr.read(buff);
while (len >= 0) {
contents.append(buff, 0, len);
}
return buff.toString();
} finally {
try {
is.close();
} catch (Exception e) {
// log error in closing the file
}
}
}
jQuery allows you to specify if you want the ajax request to be asynchronous or not. You can simply make the ajax requests synchronous and then the rest of the code won't execute until they return.
For example:
jQuery.ajax({
async: false,
//code
});
Steps:
Go to conf
folder of your apache tomcat server. In my case,its apache-tomcat-7.0.61\conf
as I am using apache-tomcat-7.0.61
Open server.xml
and change the port number from 8080 to any other port as your wish. For example:8081,8082,8087 etc
Now go to bin
folder and run shutdown.bat
Now restart the server through eclipse.
Now your project will work without any interruption.
All the previous answers have an always-active mousemove handler. If the handler is jQuery, the additional processing jQuery performs can add up. Especially if the user is using a gaming mouse, as many as 500 events per second can occur.
This solution avoids handling every mousemove event. This result in a small timing error, but which you can adjust to your need.
function setIdleTimeout(millis, onIdle, onUnidle) {
var timeout = 0;
startTimer();
function startTimer() {
timeout = setTimeout(onExpires, millis);
document.addEventListener("mousemove", onActivity);
document.addEventListener("keydown", onActivity);
}
function onExpires() {
timeout = 0;
onIdle();
}
function onActivity() {
if (timeout) clearTimeout(timeout);
else onUnidle();
//since the mouse is moving, we turn off our event hooks for 1 second
document.removeEventListener("mousemove", onActivity);
document.removeEventListener("keydown", onActivity);
setTimeout(startTimer, 1000);
}
}
First of all to see how many revisions you are behind locally, you should do a git fetch
to make sure you have the latest info from your remote.
The default output of git status
tells you how many revisions you are ahead or behind, but usually I find this too verbose:
$ git status
# On branch master
# Your branch and 'origin/master' have diverged,
# and have 2 and 1 different commit each, respectively.
#
nothing to commit (working directory clean)
I prefer git status -sb
:
$ git status -sb
## master...origin/master [ahead 2, behind 1]
In fact I alias this to simply git s
, and this is the main command I use for checking status.
To see the diff in the "ahead revisions" of master
, I can exclude the "behind revisions" from origin/master
:
git diff master..origin/master^
To see the diff in the "behind revisions" of origin/master
, I can exclude the "ahead revisions" from master
:
git diff origin/master..master^^
If there are 5 revisions ahead or behind it might be easier to write like this:
git diff master..origin/master~5
git diff origin/master..master~5
UPDATE
To see the ahead/behind revisions, the branch must be configured to track another branch. For me this is the default behavior when I clone a remote repository, and after I push a branch with git push -u remotename branchname
. My version is 1.8.4.3, but it's been working like this as long as I remember.
As of version 1.8, you can set the tracking branch like this:
git branch --track test-branch
As of version 1.7, the syntax was different:
git branch --set-upstream test-branch
I found this maven
repo where you could download from directly a zip
file containing all the jars you need.
The solution I prefer is using Maven
, it is easy and you don't have to download each jar
alone. You can do it with the following steps:
Create an empty folder anywhere with any name you prefer, for example spring-source
Create a new file named pom.xml
Copy the xml below into this file
Open the spring-source
folder in your console
Run mvn install
After download finished, you'll find spring jars in /spring-source/target/dependencies
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>spring-source-download</groupId>
<artifactId>SpringDependencies</artifactId>
<version>1.0</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.8</version>
<executions>
<execution>
<id>download-dependencies</id>
<phase>generate-resources</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/dependencies</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Also, if you need to download any other spring project, just copy the dependency
configuration from its corresponding web page.
For example, if you want to download Spring Web Flow
jars, go to its web page, and add its dependency
configuration to the pom.xml
dependencies
, then run mvn install
again.
<dependency>
<groupId>org.springframework.webflow</groupId>
<artifactId>spring-webflow</artifactId>
<version>2.3.2.RELEASE</version>
</dependency>
I'd use a set myself, but here's yet another way:
uniquewords = []
while True:
ipta = raw_input("Word: ")
if ipta == "":
break
if not ipta in uniquewords:
uniquewords.append(ipta)
print "There are", len(uniquewords), "unique words!"
Using the indexOf function was not cutting it on my collection of REST resources.
I had to create a function that retrieves the array index of a resource sitting in a collection of resources:
factory.getResourceIndex = function(resources, resource) {
var index = -1;
for (var i = 0; i < resources.length; i++) {
if (resources[i].id == resource.id) {
index = i;
}
}
return index;
}
$scope.unassignedTeams.splice(CommonService.getResourceIndex($scope.unassignedTeams, data), 1);
I found out it was:
$ git fetch upstream
$ git merge upstream/master
I think CodeIgniter 3 recommends to set $config['base_url']
to a full url manually in order to avoid HTTP header injection.
If you are not concerned about it, you can simply add the following lines in your
application/config/config.php
defined('BASE_URL') OR define('BASE_URL', (is_https() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . dirname($_SERVER['SCRIPT_NAME']) . '/');
$config['base_url'] = BASE_URL;
In this way you also have BASE_URL
constant available in all your project code (including the views) and you don't have to use functions:
config_item('base_url') //returns BASE_URL
$this->config->item('base_url'); //returns BASE_URL
Try this:
UPDATE test
SET
field = 1
WHERE id = 123 and condition
To my knowledge, Ejabberd (http://www.ejabberd.im/) is the parent, this is XMPP server which provide quite good features of open source, Whatsapp uses some modified version of this, facebook messaging also uses a modified version of this. Some more chat applications likes Samsung's ChatOn, Nimbuzz messenger all use ejabberd based ones and Erlang solutions also have modified version of this ejabberd which they claim to be highly scalable and well tested with more performance improvements and renamed as MongooseIM.
Ejabberd is the server which has most of the featured implemented when compared to other. Since it is build in Erlang it is highly scalable horizontally.
If you are using pyenv, it is possible to delete your virtual environment:
$ pyenv virtualenv-delete <name>
It is also possible to open the pdf link in a new window and let the browser handle the rest:
window.open(pdfUrl, '_blank');
or:
window.open(pdfUrl);
$users = $dbh->query($sql);
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
Here $users
is a PDOStatement
object over which you can iterate. The first iteration outputs all results, the second does nothing since you can only iterate over the result once. That's because the data is being streamed from the database and iterating over the result with foreach
is essentially shorthand for:
while ($row = $users->fetch()) ...
Once you've completed that loop, you need to reset the cursor on the database side before you can loop over it again.
$users = $dbh->query($sql);
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
echo "<br/>";
$result = $users->fetch(PDO::FETCH_ASSOC);
foreach($result as $key => $value) {
echo $key . "-" . $value . "<br/>";
}
Here all results are being output by the first loop. The call to fetch
will return false
, since you have already exhausted the result set (see above), so you get an error trying to loop over false
.
In the last example you are simply fetching the first result row and are looping over it.
In my case, since I could not append a cache busting timestamp to the css url it turned out that I had to manually refresh the application pool in IIS 7.5.7600.
Every other avenue was pursued, right down to disabling the caching entirely for the site and also for the local browser (like ENTIRELY disabled for both), still didn't do the trick. Also "restarting" the website did nothing.
Same position as me? [Site Name] > "Application Pool" > "Recycle" is your last resort...
You are allowed to use IDs that start with a digit in your HTML5 documents:
The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.
There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.
But querySelector
method uses CSS3 selectors for querying the DOM and CSS3 doesn't support ID selectors that start with a digit:
In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit.
Use a value like b22
for the ID attribute and your code will work.
Since you want to select an element by ID you can also use .getElementById
method:
document.getElementById('22')
adding to the top answer: here is some sample code from PHP and Jquery:
$("#button").click(function () {
$.ajax({
type: "POST",
url: "handler.php",
data: dataString,
success: function(data) {
if(data.status == "success"){
/* alert("Thank you for subscribing!");*/
$(".title").html("");
$(".message").html(data.message)
.hide().fadeIn(1000, function() {
$(".message").append("");
}).delay(1000).fadeOut("fast");
/* setTimeout(function() {
window.location.href = "myhome.php";
}, 2500);*/
}
else if(data.status == "error"){
alert("Error on query!");
}
}
});
return false;
}
});
PHP - send custom message / status:
$response_array['status'] = 'success'; /* match error string in jquery if/else */
$response_array['message'] = 'RFQ Sent!'; /* add custom message */
header('Content-type: application/json');
echo json_encode($response_array);
check for this by calling the library jquery after the noconflict.js or that this calling more than once jquery library after the noconflict.js
You can actually replicate what is inside NavLink something like this
const NavLink = ( {
to,
exact,
children
} ) => {
const navLink = ({match}) => {
return (
<li class={{active: match}}>
<Link to={to}>
{children}
</Link>
</li>
)
}
return (
<Route
path={typeof to === 'object' ? to.pathname : to}
exact={exact}
strict={false}
children={navLink}
/>
)
}
just look into NavLink source code and remove parts you don't need ;)
Here is how you do in Eloquent
$users = User::whereIn('id', array(1, 2, 3))->get();
And if you are using Query builder then :
$users = DB::table('users')->whereIn('id', array(1, 2, 3))->get();
You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:
import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values
... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.
Dim connString as String ="server=localhost;userid=root;password=123456;database=uni_park_db"
Dim conn as MySqlConnection(connString)
Dim cmd as MysqlCommand
Dim dt as New DataTable
Dim ireturn as Boolean
Private Sub Insert_Car()
Dim sql as String = "insert into members_car (car_id, member_id, model, color, chassis_id, plate_number, code) values (@car_id,@member_id,@model,@color,@chassis_id,@plate_number,@code)"
Dim cmd = new MySqlCommand(sql, conn)
cmd.Paramaters.AddwithValue("@car_id", txtCar.Text)
cmd.Paramaters.AddwithValue("@member_id", txtMember.Text)
cmd.Paramaters.AddwithValue("@model", txtModel.Text)
cmd.Paramaters.AddwithValue("@color", txtColor.Text)
cmd.Paramaters.AddwithValue("@chassis_id", txtChassis.Text)
cmd.Paramaters.AddwithValue("@plate_number", txtPlateNo.Text)
cmd.Paramaters.AddwithValue("@code", txtCode.Text)
Try
conn.Open()
If cmd.ExecuteNonQuery() > 0 Then
ireturn = True
End If
conn.Close()
Catch ex as Exception
ireturn = False
conn.Close()
End Try
Return ireturn
End Sub
add an alias to global gitconfig(/home/user/.gitconfig) with below command.
git config --global alias.pushall '!f(){ for var in $(git remote show); do echo "pushing to $var"; git push $var; done; }; f'
Once you commit code, we say
git push
to push to origin by default. After above alias, we can say
git pushall
and code will be updated to all remotes including origin remote.
In confing.yml
# app/config/config.yml
twig:
globals:
version: '%app.version%'
In Twig view
# twig view
{{ version }}
I think the easiest (and maybe most elegant) solution here is to leverage the fact that you can set default
to a callable. So, to get around admin's special handling of auto_now, you can just declare the field like so:
from django.utils import timezone
date_field = models.DateField(default=timezone.now)
It's important that you don't use timezone.now()
as the default value wouldn't update (i.e., default gets set only when the code is loaded). If you find yourself doing this a lot, you could create a custom field. However, this is pretty DRY already I think.
This worked for me well :
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/TestDataGenerator.fxml"));
loader.setClassLoader(getClass().getClassLoader());
Parent root = loader.load();
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
You could also declaratively define a bean of type ServiceLocatorFactoryBean that will act as a Factory class. it supported by Spring 3.
A FactoryBean implementation that takes an interface which must have one or more methods with the signatures (typically, MyService getService() or MyService getService(String id)) and creates a dynamic proxy which implements that interface
Here's an example of implementing the Factory pattern using Spring
I had the same problem when I used code-first migrations to build my database for an MVC 5 application. I eventually found the seed method in my configuration.cs file to be causing the issue. My seed method was creating a table entry for the table containing the foreign key before creating the entry with the matching primary key.
In Windows, capitalization in paths doesn't matter. In Linux it does.
When you autoload, use "Foo" not "foo".
I believe that will do the trick.
I think it works when you take it out of autoloading because codeigniter is smart enough to figure out the capitalization in the path and classes are case independent in php.
I think, It will work.
.Myclass tr td:first-child{ }
or
.Myclass td:first-child { }
There are no auto incrementing features in Oracle for a column. You need to create a SEQUENCE object. You can use the sequence like:
insert into table(batch_id, ...) values(my_sequence.nextval, ...)
...to return the next number. To find out the last created sequence nr (in your session), you would use:
my_sequence.currval
This site has several complete examples on how to use sequences.
For me, I used margin-left: auto; which is more responsive with horizontal resizing.
Simply chain the replace
functions like this
strs = "abc&def#ghi"
print strs.replace('&', '\&').replace('#', '\#')
# abc\&def\#ghi
If the replacements are going to be more in number, you can do this in this generic way
strs, replacements = "abc&def#ghi", {"&": "\&", "#": "\#"}
print "".join([replacements.get(c, c) for c in strs])
# abc\&def\#ghi
Using ~*
can improve greatly on performance, with functionality of INSTR.
SELECT id FROM groups WHERE name ~* 'adm'
return rows with name that contains OR equals to 'adm'.
Just do:
echo substr($string, 0, -3);
You don't need to use a strlen
call, since, as noted in the substr docs:
If length is given and is negative, then that many characters will be omitted from the end of string
Yes, you can enforce the constraint only when the value is not NULL. This can be easily tested with the following example:
CREATE DATABASE t;
USE t;
CREATE TABLE parent (id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (id INT NULL,
parent_id INT NULL,
FOREIGN KEY (parent_id) REFERENCES parent(id)
) ENGINE=INNODB;
INSERT INTO child (id, parent_id) VALUES (1, NULL);
-- Query OK, 1 row affected (0.01 sec)
INSERT INTO child (id, parent_id) VALUES (2, 1);
-- ERROR 1452 (23000): Cannot add or update a child row: a foreign key
-- constraint fails (`t/child`, CONSTRAINT `child_ibfk_1` FOREIGN KEY
-- (`parent_id`) REFERENCES `parent` (`id`))
The first insert will pass because we insert a NULL in the parent_id
. The second insert fails because of the foreign key constraint, since we tried to insert a value that does not exist in the parent
table.
JToken.Type
is available after a successful parse. This can be used to eliminate some of the preamble in the answers above and provide insight for finer control of the result. Entirely invalid input (e.g., "{----}".IsValidJson();
will still throw an exception).
public static bool IsValidJson(this string src)
{
try
{
var asToken = JToken.Parse(src);
return asToken.Type == JTokenType.Object || asToken.Type == JTokenType.Array;
}
catch (Exception) // Typically a JsonReaderException exception if you want to specify.
{
return false;
}
}
Json.Net reference for JToken.Type
: https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JTokenType.htm
I use this to avoid negative interval.
var seconds = (date1< date2)? (date2- date1).TotalSeconds: (date1 - date2).TotalSeconds;
from os.path import dirname
from os.path import abspath
def get_file_parent_dir_path():
"""return the path of the parent directory of current file's directory """
current_dir_path = dirname(abspath(__file__))
path_sep = os.path.sep
components = current_dir_path.split(path_sep)
return path_sep.join(components[:-1])
@echo off
color 0B
echo =============================================================================
echo.
echo ClockworkMod Recovery for SAMSUNG GALAXY SIII E210L
echo.
echo ClockworkMod Recovery (v6.0.1.2 Touch)
echo.
echo ¡ô¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¡ô
echo ¨U ¨U
echo ¨U SAMSUNG GALAXY SIII E210L ¨U
echo ¡ô¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¡ô
echo.
echo 1) (Settings\Developer options©¥ USB debugging)
echo.
echo 2) CWM SAMSUNG GALAXY SIII E210L
echo.
echo 3) THANK!!!!!!
echo.
echo =============================================================================
echo ARE YOU READY? GO! ¡·¡·¡·
@pause
echo.
echo adb...
adb.exe kill-server
adb.exe wait-for-device
echo wiat¸!
echo.
echo conect...
adb.exe push IMG /data/local/tmp/
adb.exe shell su -c "dd if=/data/local/tmp/GANGSTAR-VEGAS-1.3.0-APK-Andropalace.net.apk of=/mnt/sdcard/Android/GANGSTAR-VEGAS-1.3.0-APK-Andropalace.net.apk
adb.exe shell su -c "rm /data/local/tmp/bootloader.img"
adb.exe shell su -c "rm /data/local/tmp/recovery.img"
echo ===============================================================
echo ClockworkMod Recovery!
echo.
@pause
I always use Gliffy works perfectly and does lots of things including class diagrams.
In addition to Xavi Martínez's answer avoiding the jump on click
Avoiding Jump
$(document).ready(function(){
// show active tab
if(location.hash) {
$('a[href=' + location.hash + ']').tab('show');
}
// set hash on click without jumb
$(document.body).on("click", "a[data-toggle]", function(e) {
e.preventDefault();
if(history.pushState) {
history.pushState(null, null, this.getAttribute("href"));
}
else {
location.hash = this.getAttribute("href");
}
$('a[href=' + location.hash + ']').tab('show');
return false;
});
});
// set hash on popstate
$(window).on('popstate', function() {
var anchor = location.hash || $("a[data-toggle=tab]").first().attr("href");
$('a[href=' + anchor + ']').tab('show');
});
Nested tabs
implementation with "_" character as separator
$(document).ready(function(){
// show active tab
if(location.hash) {
var tabs = location.hash.substring(1).split('_');
$.each(tabs,function(n){
$('a[href=#' + tabs[n] + ']').tab('show');
});
$('a[href=' + location.hash + ']').tab('show');
}
// set hash on click without jumb
$(document.body).on("click", "a[data-toggle]", function(e) {
e.preventDefault();
if(history.pushState) {
history.pushState(null, null, this.getAttribute("href"));
}
else {
location.hash = this.getAttribute("href");
}
var tabs = location.hash.substring(1).split('_');
//console.log(tabs);
$.each(tabs,function(n){
$('a[href=#' + tabs[n] + ']').tab('show');
});
$('a[href=' + location.hash + ']').tab('show');
return false;
});
});
// set hash on popstate
$(window).on('popstate', function() {
var anchor = location.hash || $("a[data-toggle=tab]").first().attr("href");
var tabs = anchor.substring(1).split('_');
$.each(tabs,function(n){
$('a[href=#' + tabs[n] + ']').tab('show');
});
$('a[href=' + anchor + ']').tab('show');
});
Here's what is (IMO) by far the best solution in one line, per modern javascript standards:
const str1 = 'abc';
const str2 = 'abc';
return (str1 === str2); // true
const str1 = 'abcd';
const str2 = 'abc';
return (str1 === str2); // false
const str1 = 'abc';
const str2 = 'abcd';
return (str1 === str2); // false
I had the same problem while installing Brotli
ERROR
Failed building wheel for Brotli
I solved it by downloading the .whl
file from here
and installing it using the below command
C:\Users\{user_name}\Downloads>pip install Brotli-1.0.9-cp39-cp39-win_amd64.whl
Although the question is already answered, there is an eloquent way to do it.
Use just the column name to denote last non-empty row of that column.
For example:
If your data is in A1:A100
and you want to be able to add some more data to column A, say it can be A1:A105
or even A1:A1234
later, you can use this range:
A1:A
So to get last non-empty value in a range, we will use 2 functions:
The answer is =INDEX(B3:B,COUNTA(B3:B))
.
Here is the explanation:
COUNTA(range)
returns number of values in a range, we can use this to get the count of rows.
INDEX(range, row, col)
returns the value in a range at position row
and col
(col=1
if not specified)
Examples:
INDEX(A1:C5,1,1) = A1
INDEX(A1:C5,1) = A1 # implicitly states that col = 1
INDEX(A1:C5,1,2) = A2
INDEX(A1:C5,2,1) = B1
INDEX(A1:C5,2,2) = B2
INDEX(A1:C5,3,1) = C1
INDEX(A1:C5,3,2) = C2
For the picture above, our range will be B3:B
. So we will count how many values are there in range B3:B
by COUNTA(B3:B)
first. In the left side, it will produce 8
since there are 8 values while it will produce 9
in the right side. We also know that the last value is in the 1st column of the range B3:B
so the col
parameter of INDEX
must be 1 and the row
parameter should be COUNTA(B3:B)
.
PS: please upvote @bloodymurderlive's answer since he wrote it first, I'm just explaining it here.
Step 1) Make sure postgress is installed in your system ( If it's already installed and you can run postgress server on your machine move to step (2)
apt-get install postgresql postgresql-contrib (sol - fatal error: libpq-fe.h: No such file or directory)
sudo apt-get install ruby-dev (required to install postgress below)
sudo gem install pg
sudo service postgresql restart
Step 2) Some of the c++ files are trying to access libpq-fe.h
directly and cant find. So we need to manually search every such file and replace libpq-fe.h
with postgresql/libpq-fe.h
Command for searching all occurrences of libpq-fe.h
in all dir and subdir is grep -rnw ./ -e 'libpq-fe.h'
3) Go to All the file listed by command run in step 2 and manually change libpq-fe.h
with postgresql/libpq-fe.h
.
As per comment from @Paul, If display: block is specified, span stops to be an inline element and an element after it appears on next line.
I came here to find solution to my span height problem and I got a solution of my own
Adding overflow:hidden;
and keeing it inline will solve the problem just tested in IE8 Quirks mode
Since the string "North" might be the beginning of a street name, e.g. "Northern Boulevard", street directions are always between the street number and the street name, and separated from street number and street name.
Public Function strReplace(varValue As Variant) as Variant
Select Case varValue
Case "Avenue"
strReplace = "Ave"
Case " North "
strReplace = " N "
Case Else
strReplace = varValue
End Select
End Function
I have turned the accepted answer into a robust script. You'll find it in my git-extensions repository.
$ git-prune --help
Remove old local branches that do not exist in <remote> any more.
With --test, only print which local branches would be deleted.
Usage: git-prune [-t|--test|-f|--force] <remote>
SELECT last_value, increment_by from "other_schema".id_seq;
for adding a seq to a column where the schema is not public try this.
nextval('"other_schema".id_seq'::regclass)
With java-8, you can do it this way.
double[] arr = frameList.stream().mapToDouble(Double::doubleValue).toArray(); //via method reference
double[] arr = frameList.stream().mapToDouble(d -> d).toArray(); //identity function, Java unboxes automatically to get the double value
What it does is :
Stream<Double>
from the listDoubleStream
toArray()
to get the array.It's still valid to use IE=edge,chrome=1.
But, since the chrome frame project has been wound down the chrome=1 part is redundant for browsers that don't already have the chrome frame plug in installed.
I use the following for correctness nowadays
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
if not a:
print("List is empty")
Using the implicit booleanness of the empty list
is quite pythonic.
Add @ResponseBody
annotation, which will write return data in output stream.
You can't set the field having data-type "text". Only because of that thing you are getting this error. Try to change the data-type with int
I wanted to post an answer that there is a case where the variable won't be found.
Cyclical imports may break the module behavior.
For example:
first.py
import second
var = 1
second.py
import first
print(first.var) # will throw an error because the order of execution happens before var gets declared.
main.py
import first
On this is example it should be obvious, but in a large code-base, this can be really confusing.
Use the .split()
method. When specifying an empty string as the separator, the split()
method will return an array with one element per character.
entry = prompt("Enter your name")
entryArray = entry.split("");
Just Go To *Startmenu >>Java >>Configure Java >> Security >> Edit site list >> copy and paste your Link with problem >> OK Problem fixed :)*
Close Code 1006
is a special code that means the connection was closed abnormally (locally) by the browser implementation.
If your browser client reports close code 1006
, then you should be looking at the websocket.onerror(evt)
event for details.
However, Chrome will rarely report any close code 1006
reasons to the Javascript side. This is likely due to client security rules in the WebSocket spec to prevent abusing WebSocket. (such as using it to scan for open ports on a destination server, or for generating lots of connections for a denial-of-service attack).
Note that Chrome will often report a close code 1006
if there is an error during the HTTP Upgrade to Websocket (this is the step before a WebSocket is technically "connected"). For reasons such as bad authentication or authorization, or bad protocol use (such as requesting a subprotocol, but the server itself doesn't support that same subprotocol), or even an attempt at talking to a server location that isn't a WebSocket (such as attempting to connect to ws://images.google.com/
)
Fundamentally, if you see a close code 1006
, you have a very low level error with WebSocket itself (similar to "Unable to Open File" or "Socket Error"), not really meant for the user, as it points to a low level issue with your code and implementation. Fix your low level issues, and then when you are connected, you can then include more reasonable error codes. You can accomplish this in terms of scope or severity in your project. Example: info and warning level are part of your project's specific protocol, and don't cause the connection to terminate. With severe or fatal messages reporting also using your project's protocol to convey as much detail as you want, and then closing the connection using the limited abilities of the WebSocket close flow.
Be aware that WebSocket close codes are very strictly defined, and the close reason phrase/message cannot exceed 123 characters in length (this is an intentional WebSocket limitation).
But not all is lost, if you are just wanting this information for debugging reasons, the detail of the closure, and its underlying reason is often reported with a fair amount of detail in Chrome's Javascript console.
You can use -O-
(uppercase o) to redirect content to the stdout (standard output) or to a file (even special files like /dev/null
/dev/stderr
/dev/stdout
)
wget -O- http://yourdomain.com
Or:
wget -O- http://yourdomain.com > /dev/null
Or: (same result as last command)
wget -O/dev/null http://yourdomain.com
EDIT: The code below does NOT work. I was always assuming that new Date().getTime() returned the number of seconds since the 1st of January 1970 IN THE CURRENT TIMEZONE. This is not the case: getTime() returns the number of seconds in UTC. So, the code below does gross over-adjusting. Thank you everybody!]
First of all, thank you for your fantastic insights. I guess my question had the wrong title... it should have been "Get the UTC Unix Timestamp for an existing date".
So, if I have a date object:
var d = new Date(2009,01,31)
I was after a function that would tell me "The UTC Unix Timestamp".
This function seems to be the real trick:
Date.prototype.getUTCUnixTime = function (){
return Math.floor( new Date(
this.getUTCFullYear(),
this.getUTCMonth(),
this.getUTCDate(),
this.getUTCHours(),
this.getUTCMinutes(),
this.getUTCSeconds()
).getTime() / 1000);
}
Note that it works on "this" This means that I can do:
var n = new Date(2008,10,10)
...
...
n.getUTCUnixTime();
And get the number of seconds since the 1st of Jan 1970 in Unix time. Right?
It's a little insane, to me, that Javascript stores everything in UTC times, but then in order to get that number I have to create a new Date object passing the individual UTC getters and then finally call getTime() for that...
Merc.
Besides using multiple proxies or proxy-networks, you might want to try the planet-lab. (And probably there are other similar institutions around).
The social solution would be to post a question on some board that you are searching for volunteers that proxy your requests. (They only have to allow for one destination in their proxy config thus the danger of becoming spam-whores is relatively low.) You should prepare credentials that ensure your partners of the authenticity of the claim that the destination is indeed your computer.
For users of GitHub, this worked for me:
git reset --hard <full_hash_of_commit_to_reset_to>
git push --force
This will "correct" the branch history on your local machine and the GitHub server, but anyone who has sync'ed this branch with the server since the bad commit will have the history on their local machine. If they have permission to push to the branch directly then these commits will show right back up when they sync.
All everyone else needs to do is the git reset
command from above to "correct" the branch on their local machine. Of course they would need to be wary of any local commits made to this branch after the target hash. Cherry pick/backup and reapply those as necessary, but if you are in a protected branch then the number of people who can commit directly to it is likely limited.
In my project , I use the XMLHttpRequest to send multipart/form-data. I think it will fit you to.
and the uploader code
let xhr = new XMLHttpRequest();
xhr.open('POST', 'http://www.example.com/rest/api', true);
xhr.withCredentials = true;
xhr.send(formData);
Here is example : https://github.com/wangzilong/angular2-multipartForm
Setp 1 : Download the following apk files. 1)com.google.android.gms.apk (https://androidfilehost.com/?fid=95916177934534438) 2)com.android.vending-4.4.22.apk (https://androidfilehost.com/?fid=23203820527945795)
Step 2 : Create a new AVD without the google API's
Step 3 : Run the AVD (Start the emulator)
Step 4 : Install the downloaded apks using adb .
1)adb install com.google.android.gms-6.7.76_\(1745988-038\)-6776038-minAPI9.apk
2)adb install com.android.vending-4.4.22.apk
adb come up with android sdks/studio
Step 5 : Create the application in google developer console
Step 6 : Configure the api key in your Androidmanifest.xml and google api version.
Note : In step1 you need to download the apk based on your Android API level(..18,19,21..) and google play services version (5,5.1,6,6.5......)
This will work 100%.
Other posters are probably correct...there might be spaces mixed in with your tabs. Try doing a search & replace to replace all tabs with a few spaces.
Try this:
import sys
def Factorial(n): # return factorial
result = 1
for i in range (1,n):
result = result * i
print "factorial is ",result
return result
print Factorial(10)
You can try to use this
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape
android:innerRadius="0dp"
android:shape="ring"
android:thicknessRatio="2"
android:useLevel="false" >
<solid android:color="@color/button_blue_two" />
</shape>
</item>
and you don't have to bother the width and height aspect ratio if you are using this for a textview
For a very simple case like this, a comprehension, as in Ismail Badawi's answer is definitely the way to go.
But when things get more complicated, and you need to start writing multi-clause or nested comprehensions with complex expressions in them, it's worth looking into other alternatives. There are a few different (quasi-)standard ways to specify XPath-style searches on nested dict-and-list structures, such as JSONPath, DPath, and KVC. And there are nice libraries on PyPI for them.
Here's an example with the library named dpath
, showing how it can simplify something just a bit more complicated:
>>> dd = {
... 'fruits': [{'value': 'apple', 'blah': 2}, {'value': 'banana', 'blah': 3}],
... 'vehicles': [{'value': 'cars', 'blah':4}]}
>>> {key: [{'value': d['value']} for d in value] for key, value in dd.items()}
{'fruits': [{'value': 'apple'}, {'value': 'banana'}],
'vehicles': [{'value': 'cars'}]}
>>> dpath.util.search(dd, '*/*/value')
{'fruits': [{'value': 'apple'}, {'value': 'banana'}],
'vehicles': [{'value': 'cars'}]}
Or, using jsonpath-ng
:
>>> [d['value'] for key, value in dd.items() for d in value]
['apple', 'banana', 'cars']
>>> [m.value for m in jsonpath_ng.parse('*.[*].value').find(dd)]
['apple', 'banana', 'cars']
This one may not look quite as simple at first glance, because find
returns match objects, which include all kinds of things besides just the matched value, such as a path directly to each item. But for more complex expressions, being able to specify a path like '*.[*].value'
instead of a comprehension clause for each *
can make a big difference. Plus, JSONPath is a language-agnostic specification, and there are even online testers that can be very handy for debugging.