I had the same problem what caused it was that I already had created a pod from the docker image via the .yml file, however I mistyped the name, i.e test-app:1.0.1 when I needed test-app:1.0.2 in my .yml file. So I did kubectl delete pods --all
to remove the faulty pod then redid the kubectl create -f name_of_file.yml
which solved my problem.
check your image cmd
using the command docker inspect image_name
. The output might be like this:
"Cmd": [
"/bin/bash",
"-c",
"#(nop) ",
"CMD [\"/bin/bash\"]"
],
So use the command docker exec -it container_id /bin/bash
. If your cmd
output is different like this:
"Cmd": [
"/bin/sh",
"-c",
"#(nop) ",
"CMD [\"/bin/sh\"]"
],
Use /bin/sh
instead of /bin/bash
in the command above.
You can use System.Reflection.Assembly.Load*() methods and then grab their AssemblyInfo.
This trick worked for me too: In Eclipse right-click on the project and then Maven > Update Dependencies.
As mentioned by MatBailie This is much more safe since it is not a dynamic query and ther are lesser chances of sql injection . I Added one situation where you even want the where clause to be dynamic . XX YY are Columns names
CREATE PROCEDURE [dbo].[DASH_getTP_under_TP]
(
@fromColumnName varchar(10) ,
@toColumnName varchar(10) ,
@ID varchar(10)
)
as
begin
-- this is the column required for where clause
declare @colname varchar(50)
set @colname=case @fromUserType
when 'XX' then 'XX'
when 'YY' then 'YY'
end
select SelectedColumnId from (
select
case @toColumnName
when 'XX' then tablename.XX
when 'YY' then tablename.YY
end as SelectedColumnId,
From tablename
where
(case @fromUserType
when 'XX' then XX
when 'YY' then YY
end)= ISNULL(@ID , @colname)
) as tbl1 group by SelectedColumnId
end
UPDATE:
You'll also want to goto Security -> Server Roles
, and for public
check the permissions for TSQL Default TCP/TSQL Default VIA/TSQL Local Machine/TSQL Named Pipes
and remove the connect
permission
Boot strapping the dictionary meaning is to start up with minimum resources. In the Context of an OS the OS should be able to swiftly load once the Power On Self Test (POST) determines that its safe to wake up the CPU. The boot strap code will be run from the BIOS. BIOS is a small sized ROM. Generally it is a jump instruction to the set of instructions which will load the Operating system to the RAM. The destination of the Jump is the Boot sector in the Hard Disk. Once the bios program checks it is a valid Boot sector which contains the starting address of the stored OS, ie whether it is a valid MBR (Master Boot Record) or not. If its a valid MBR the OS will be copied to the memory (RAM)from there on the OS takes care of Memory and Process management.
This works with font awesome:
<button class="btn btn-outline-success">
<i class="fa fa-print" aria-hidden="true"></i>
Print
</button>
I saw this thread when I was trying to split a file in files with 100 000 lines. A better solution than sed for that is:
split -l 100000 database.sql database-
It will give files like:
database-aaa
database-aab
database-aac
...
List last updated on December 1, 2020:
As of November 30, 2020, AWS now has EC2 Mac instances:
We previously used and had good experiences with:
Here are some other sites that I am aware of:
When we were with MacStadium, we loved them. We had great connectivity/uptime. When I've needed hands-on support to plug in a Time Machine backup, they've been great. They performed a seamless upgrade to better hardware for us over one weekend (when we could afford a bit of downtime), and that went off without a hitch. Highly recommended. (Not affiliated - just happy).
In April of 2020, we stopped using MacStadium, simply because we no longer needed a Mac server. If I need another Mac host, I would be happy to go back to them.
Problem is the same for me in phpMyAdmin. I just created a table without any const. Later I modified the ID to a Primary key. Then I changed the ID to Auto-inc. That solved the issue.
ALTER TABLE `users` CHANGE `ID` `ID` INT(11) NOT NULL AUTO_INCREMENT;
Just set using JS as follows:
<script>
var vid = document.getElementById("myVideo");
vid.autoplay = false;
vid.load();
</script>
Set true
to turn on autoplay. Set false
to turn off autoplay.
http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_av_prop_autoplay
You forgot calling your method:
static void Main(string[] args)
{
StringAddString s = new StringAddString();
s.AddString();
}
it should stop your console, but the result might not be what you expected, you should change your code a little bit:
Console.WriteLine(string.Join(",", strings2));
Also late in the game, but doing some researches and stumbled across here. As others have mentioned, it's just almost close to impossible if it was automated, but if your design/requirement can involve in some cases (but not all the time) human interactions to review whether it is profane or not, you may consider ML. https://docs.microsoft.com/en-us/azure/cognitive-services/content-moderator/text-moderation-api#profanity is my current choice right now for multiple reasons:
For my need, it was/is based on public-friendly commercial service (OK, videogames) which other users may/will see the username, but the design requires that it has to go through profanity filter to reject offensive username. The sad part about this is the classic "clbuttic" issue will most likely occur since usernames are usually single word (up to N characters) of sometimes multiple words concatenated... Again, Microsoft's cognitive service will not flag "Assist" as Text.HasProfanity=true but may flag one of the categories probability to be high.
As the OP inquires, what about "a$$", here's a result when I passed it through the filter:, as you can see, it has determined it's not profane, but it has high probability that it is, so flags as recommendations of reviewing (human interactions).
When probability is high, I can either return back "I'm sorry, that name is already taken" (even if it isn't) so that it is less offensive to anti-censorship persons or something, if we don't want to integrate human review, or return "Your username have been notified to the live operation department, you may wait for your username to be reviewed and approved or chose another username". Or whatever...
By the way, the cost/price for this service is quite low for my purpose (how often does the username gets changed?), but again, for OP maybe the design demands more intensive queries and may not be ideal to pay/subscribe for ML-services, or cannot have human-review/interactions. It all depends on the design... But if design does fit the bill, perhaps this can be OP's solution.
If interested, I can list the cons in the comment in the future.
just to extend @GabLeRoux's answer:
[<img src="https://img.youtube.com/vi/<VIDEO ID>/maxresdefault.jpg" width="50%">](https://youtu.be/<VIDEO ID>)
this way you will be able to adjust the size of the thumbnail image in the README.md file on you Github repo.
Here is another. We had a need to provide friendly names for our EnumValues. We used the System.ComponentModel.DescriptionAttribute to show a custom string value for each enum value.
public static class StaticClass
{
public static string GetEnumDescription(Enum currentEnum)
{
string description = String.Empty;
DescriptionAttribute da;
FieldInfo fi = currentEnum.GetType().
GetField(currentEnum.ToString());
da = (DescriptionAttribute)Attribute.GetCustomAttribute(fi,
typeof(DescriptionAttribute));
if (da != null)
description = da.Description;
else
description = currentEnum.ToString();
return description;
}
public static List<string> GetEnumFormattedNames<TEnum>()
{
var enumType = typeof(TEnum);
if (enumType == typeof(Enum))
throw new ArgumentException("typeof(TEnum) == System.Enum", "TEnum");
if (!(enumType.IsEnum))
throw new ArgumentException(String.Format("typeof({0}).IsEnum == false", enumType), "TEnum");
List<string> formattedNames = new List<string>();
var list = Enum.GetValues(enumType).OfType<TEnum>().ToList<TEnum>();
foreach (TEnum item in list)
{
formattedNames.Add(GetEnumDescription(item as Enum));
}
return formattedNames;
}
}
In Use
public enum TestEnum
{
[Description("Something 1")]
Dr = 0,
[Description("Something 2")]
Mr = 1
}
static void Main(string[] args)
{
var vals = StaticClass.GetEnumFormattedNames<TestEnum>();
}
This will end returning "Something 1", "Something 2"
The easiest way to do this is to use jQuery : jQuery UI combobox/autocomplete
uint16_t
is unsigned 16-bit integer.
unsigned short int
is unsigned short integer, but the size is implementation dependent. The standard only says it's at least 16-bit (i.e, minimum value of UINT_MAX
is 65535
). In practice, it usually is 16-bit, but you can't take that as guaranteed.
Note:
uint16_t
.inttypes.h
and stdint.h
are both introduced in C99. If you are using C89, define your own type.uint16_t
may not be provided in certain implementation(See reference below), but unsigned short int
is always available.Reference: C11(ISO/IEC 9899:201x) §7.20 Integer types
For each type described herein that the implementation provides) shall declare that typedef name and define the associated macros. Conversely, for each type described herein that the implementation does not provide, shall not declare that typedef name nor shall it define the associated macros. An implementation shall provide those types described as ‘‘required’’, but need not provide any of the others (described as ‘optional’’).
I am using bootstrap calender for future date not allow with allow change in months & year only..
var j = jQuery.noConflict();
j(function () {
j(".datepicker").datepicker({ dateFormat: "dd-M-yy" }).val()
});
j(function () {
j(".Futuredatenotallowed").datepicker({
changeMonth: true,
maxDate: 0,
changeYear: true,
dateFormat: 'dd-M-yy',
language: "tr"
}).on('changeDate', function (ev) {
$(this).blur();
$(this).datepicker('hide');
}).val()
});
What is usage of "Constructor Chain"?
You use it for calling one constructor from another constructor.
How can implement "Constructor Chain"?
Use ": this (yourProperties)" keyword after definition of constructor. for example:
Class MyBillClass
{
private DateTime requestDate;
private int requestCount;
public MyBillClass()
{
/// ===== we naming "a" constructor ===== ///
requestDate = DateTime.Now;
}
public MyBillClass(int inputCount) : this()
{
/// ===== we naming "b" constructor ===== ///
/// ===== This method is "Chained Method" ===== ///
this.requestCount= inputCount;
}
}
Why is it useful?
Important reason is reduce coding, and prevention of duplicate code. such as repeated code for initializing property
Suppose some property in class must be initialized with specific value (In our sample, requestDate). And class have 2 or more constructor. Without "Constructor Chain", you must repeat initializaion code in all constractors of class.
How it work? (Or, What is execution sequence in "Constructor Chain")?
in above example, method "a" will be executed first, and then instruction sequence will return to method "b".
In other word, above code is equal with below:
Class MyBillClass
{
private DateTime requestDate;
private int requestCount;
public MyBillClass()
{
/// ===== we naming "a" constructor ===== ///
requestDate = DateTime.Now;
}
public MyBillClass(int inputCount) : this()
{
/// ===== we naming "b" constructor ===== ///
// ===== This method is "Chained Method" ===== ///
/// *** --- > Compiler execute "MyBillClass()" first, And then continue instruction sequence from here
this.requestCount= inputCount;
}
}
If i try the regex posted by @chubbsondubs on http://regex101.com using the 'g' flag, there are matches, that contain only ',' or an empty string.
With this regex:
(?:"([^"]*)"|([^,]*))(?:[,])
i can match the parts of the CSV (inlcuding quoted parts). (The line must be terminated with a ',' otherwise the last part isn't recognized.)
https://regex101.com/r/dF9kQ8/4
If the CSV looks like:
"",huhu,"hel lo",world,
there are 4 matches:
''
'huhu'
'hel lo'
'world'
Elements have to paint to an integer number of pixels, and as the other answers covered, percentages are indeed respected.
An important note is that pixels in this case means css pixels, not screen pixels, so a 200px container with a 50.7499% child will be rounded to 101px css pixels, which then get rendered onto 202px on a retina screen, and not 400 * .507499 ~= 203px.
Screen density is ignored in this calculation, and there is no way to paint* an element to specific retina subpixel sizes. You can't have elements' backgrounds or borders rendered at less than 1 css pixel size, even though the actual element's size could be less than 1 css pixel as Sandy Gifford showed.
[*] You can use some techniques like 0.5 offset box-shadow, etc, but the actual box model properties will paint to a full CSS pixel.
If you (or other searchers of this question) were actually interested in creating a contiguous array to fill with integers, consider bytearray and memoryivew:
# cast() is available starting Python 3.3
size = 10**6
ints = memoryview(bytearray(size)).cast('i')
ints.contiguous, ints.itemsize, ints.shape
# (True, 4, (250000,))
ints[0]
# 0
ints[0] = 16
ints[0]
# 16
I also wanted this and came up with this solution (I'm only using the date part - a default time makes no sense as a PropertyGrid default):
public class DefaultDateAttribute : DefaultValueAttribute {
public DefaultDateAttribute(short yearoffset)
: base(DateTime.Now.AddYears(yearoffset).Date) {
}
}
This just creates a new attribute that you can add to your DateTime property. E.g. if it defaults to DateTime.Now.Date:
[DefaultDate(0)]
I had the same issue today on windows 32 bit,with node 0.10.25, and grunt 0.4.5.
I followed dongho's answer, with just few extra steps. here are the steps I used to solve the error:
1) create your package.json
$ npm init
2) install grunt for this project, this will be installed under node_modules/. --save-dev will add this module to devDependency in your package.json
$ npm install grunt --save-dev
3) then create gruntfile.js
, with a sample code like this:
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
files: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js'],
options: {
globals: {
jQuery: true
}
}
},
watch: {
files: ['<%= jshint.files %>'],
tasks: ['jshint']
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['jshint']);
};
here, src/**/*.js
and test/**/*.js
should be the paths to actual JS files you are using in your project
4) run npm install grunt-contrib-jshint --save-dev
5) run npm install grunt-contrib-watch --save-dev
6) run $ grunt
Note: when you require common package like concat, uglify etc, you need to add those modules via npm install
, just the way we installed jshint and watch in step 4 & 5
From JPA 2.1 you can use AttributeConverter.
Create an enumerated class like so:
public enum NodeType {
ROOT("root-node"),
BRANCH("branch-node"),
LEAF("leaf-node");
private final String code;
private NodeType(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}
And create a converter like this:
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter(autoApply = true)
public class NodeTypeConverter implements AttributeConverter<NodeType, String> {
@Override
public String convertToDatabaseColumn(NodeType nodeType) {
return nodeType.getCode();
}
@Override
public NodeType convertToEntityAttribute(String dbData) {
for (NodeType nodeType : NodeType.values()) {
if (nodeType.getCode().equals(dbData)) {
return nodeType;
}
}
throw new IllegalArgumentException("Unknown database value:" + dbData);
}
}
On the entity you just need:
@Column(name = "node_type_code")
You luck with @Converter(autoApply = true)
may vary by container but tested to work on Wildfly 8.1.0. If it doesn't work you can add @Convert(converter = NodeTypeConverter.class)
on the entity class column.
Seeing that it's a fairly popular question - the answer is YES.
For a column column
in table table
containing all of your coma separated values:
CREATE TEMPORARY TABLE temp (val CHAR(255));
SET @S1 = CONCAT("INSERT INTO temp (val) VALUES ('",REPLACE((SELECT GROUP_CONCAT( DISTINCT `column`) AS data FROM `table`), ",", "'),('"),"');");
PREPARE stmt1 FROM @s1;
EXECUTE stmt1;
SELECT DISTINCT(val) FROM temp;
Please remember however to not store CSV in your DB
Per @Mark Amery - as this translates coma separated values into an INSERT
statement, be careful when running it on unsanitised data
Just to reiterate, please don't store CSV in your DB; this function is meant to translate CSV into sensible DB structure and not to be used anywhere in your code. If you have to use it in production, please rethink your DB structure
The right way is:
db.users.find({awards: {$elemMatch: {award:'National Medal', year:1975}}})
$elemMatch
allows you to match more than one component within the same array element.
Without $elemMatch
mongo will look for users with National Medal in some year and some award in 1975s, but not for users with National Medal in 1975.
See MongoDB $elemMatch Documentation for more info. See Read Operations Documentation for more information about querying documents with arrays.
Handy if you are already in the directory you want to add to PATH:
set PATH=%PATH%;%CD%
It works with the standard Windows cmd, but not in PowerShell.
For PowerShell, the %CD%
equivalent is [System.Environment]::CurrentDirectory
.
Just to add one case to unutbu's list.
One of the biggest practical differences for me of numpy ndarrays compared to numpy matrices or matrix languages like matlab, is that the dimension is not preserved in reduce operations. Matrices are always 2d, while the mean of an array, for example, has one dimension less.
For example demean rows of a matrix or array:
with matrix
>>> m = np.mat([[1,2],[2,3]])
>>> m
matrix([[1, 2],
[2, 3]])
>>> mm = m.mean(1)
>>> mm
matrix([[ 1.5],
[ 2.5]])
>>> mm.shape
(2, 1)
>>> m - mm
matrix([[-0.5, 0.5],
[-0.5, 0.5]])
with array
>>> a = np.array([[1,2],[2,3]])
>>> a
array([[1, 2],
[2, 3]])
>>> am = a.mean(1)
>>> am.shape
(2,)
>>> am
array([ 1.5, 2.5])
>>> a - am #wrong
array([[-0.5, -0.5],
[ 0.5, 0.5]])
>>> a - am[:, np.newaxis] #right
array([[-0.5, 0.5],
[-0.5, 0.5]])
I also think that mixing arrays and matrices gives rise to many "happy" debugging hours. However, scipy.sparse matrices are always matrices in terms of operators like multiplication.
You can rearrange columns directly by specifying their order:
df = df[['a', 'y', 'b', 'x']]
In the case of larger dataframes where the column titles are dynamic, you can use a list comprehension to select every column not in your target set and then append the target set to the end.
>>> df[[c for c in df if c not in ['b', 'x']]
+ ['b', 'x']]
a y b x
0 1 -1 2 3
1 2 -2 4 6
2 3 -3 6 9
3 4 -4 8 12
To make it more bullet proof, you can ensure that your target columns are indeed in the dataframe:
cols_at_end = ['b', 'x']
df = df[[c for c in df if c not in cols_at_end]
+ [c for c in cols_at_end if c in df]]
I don't think this is possible. There appears to be an open Jira for it:
SPR-6702: Explicitly set response Content-Type in @ResponseBody
My favourite CSV parser is one built into .NET library. This is a hidden treasure inside Microsoft.VisualBasic namespace. Below is a sample code:
using Microsoft.VisualBasic.FileIO;
var path = @"C:\Person.csv"; // Habeeb, "Dubai Media City, Dubai"
using (TextFieldParser csvParser = new TextFieldParser(path))
{
csvParser.CommentTokens = new string[] { "#" };
csvParser.SetDelimiters(new string[] { "," });
csvParser.HasFieldsEnclosedInQuotes = true;
// Skip the row with the column names
csvParser.ReadLine();
while (!csvParser.EndOfData)
{
// Read current line fields, pointer moves to the next line.
string[] fields = csvParser.ReadFields();
string Name = fields[0];
string Address = fields[1];
}
}
Remember to add reference to Microsoft.VisualBasic
More details about the parser is given here: http://codeskaters.blogspot.ae/2015/11/c-easiest-csv-parser-built-in-net.html
You could create a dict comprehension of just the elements whose values are None, and then update back into the original:
tmp = dict((k,"") for k,v in mydict.iteritems() if v is None)
mydict.update(tmp)
Update - did some performance tests
Well, after trying dicts of from 100 to 10,000 items, with varying percentage of None values, the performance of Alex's solution is across-the-board about twice as fast as this solution.
Your question almost spells the SQL for this:
DELETE FROM table WHERE id IN (1, 4, 6, 7)
It can also be achieved by:
jest --findRelatedTests path/to/fileA.js
Reference (Jest CLI Options)
How can that be achieved in the Nx monorepo? Here is the answer (in directory /path/to/workspace
):
npx nx test api --findRelatedTests=apps/api/src/app/mytest.spec.ts
Reference & more information: How to test a single Jest test file in Nx #6
4 years after the question got posted, but maybe it will help others who run into this problem. The answer has been posted elsewhere on StackExchange as well, but I lost the link and it's hard to find.
ANSWER: In jQueryTOOLS, the jQuery 'core' is also embedded if you use the default download.
When you load jQuery and jQuery tools, jQuery core gets defined twice and will 'unset' any plugins. 'Draggable' (from jQuery-UI) is such a plug-in.
The solution is to use jQuery tools WITHOUT the jQuery 'core' files and everything will work fine.
I am trying to push value in an array state and set value like this and define state array and push value by map function.
this.state = {
createJob: [],
totalAmount:Number=0
}
your_API_JSON_Array.map((_) => {
this.setState({totalAmount:this.state.totalAmount += _.your_API_JSON.price})
this.state.createJob.push({ id: _._id, price: _.your_API_JSON.price })
return this.setState({createJob: this.state.createJob})
})
If you don't need to worry about scientific or other expressions of numbers and are only working with strings that could be numbers with or without a period:
Function
def is_float(s):
result = False
if s.count(".") == 1:
if s.replace(".", "").isdigit():
result = True
return result
Lambda version
is_float = lambda x: x.replace('.','',1).isdigit() and "." in x
Example
if is_float(some_string):
some_string = float(some_string)
elif some_string.isdigit():
some_string = int(some_string)
else:
print "Does not convert to int or float."
This way you aren't accidentally converting what should be an int, into a float.
The top solutions here did not work for me out-of-the-box, so I came up with this which should work for any horizontal scrolling collection view with flow layout and only one section:
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
// Add inset to the collection view if there are not enough cells to fill the width.
CGFloat cellSpacing = ((UICollectionViewFlowLayout *) collectionViewLayout).minimumLineSpacing;
CGFloat cellWidth = ((UICollectionViewFlowLayout *) collectionViewLayout).itemSize.width;
NSInteger cellCount = [collectionView numberOfItemsInSection:section];
CGFloat inset = (collectionView.bounds.size.width - (cellCount * cellWidth) - ((cellCount - 1)*cellSpacing)) * 0.5;
inset = MAX(inset, 0.0);
return UIEdgeInsetsMake(0.0, inset, 0.0, 0.0);
}
For private static variables, I found this way:
function Class()
{
}
Class.prototype = new function()
{
_privateStatic = 1;
this.get = function() { return _privateStatic; }
this.inc = function() { _privateStatic++; }
};
var o1 = new Class();
var o2 = new Class();
o1.inc();
console.log(o1.get());
console.log(o2.get()); // 2
A plain JavaScript solution, assuming jsonObj
already contains JSON:
Loop over it looking for the matching Id, set the corresponding Username, and break
from the loop after the matched item has been modified:
for (var i = 0; i < jsonObj.length; i++) {
if (jsonObj[i].Id === 3) {
jsonObj[i].Username = "Thomas";
break;
}
}
Here's the same thing wrapped in a function:
function setUsername(id, newUsername) {
for (var i = 0; i < jsonObj.length; i++) {
if (jsonObj[i].Id === id) {
jsonObj[i].Username = newUsername;
return;
}
}
}
// Call as
setUsername(3, "Thomas");
I would use a ByteArrayOutputStream
. And on finish you can call:
new String( baos.toByteArray(), codepage );
or better:
baos.toString( codepage );
For the String
constructor, the codepage
can be a String
or an instance of java.nio.charset.Charset. A possible value is java.nio.charset.StandardCharsets.UTF_8.
The method toString()
accepts only a String
as a codepage
parameter (stand Java 8).
I've never actually used this, but try view.getClass().getGenericSuperclass()
I was having the same issue in asp.NET razor C#
I had a ComboBox
filled with titles from an EventMessage
, and I wanted to show the Content of this message with its selected value to show it in a label or TextField
or any other Control
...
My ComboBox
was filled like this:
@Html.DropDownList("EventBerichten", new SelectList(ViewBag.EventBerichten, "EventBerichtenID", "Titel"), new { @class = "form-control", onchange = "$(this.form).submit();" })
In my EventController
I had a function to go to the page, in which I wanted to show my ComboBox
(which is of a different model type, so I had to use a partial view)?
The function to get from index to page in which to load the partial view:
public ActionResult EventDetail(int id)
{
Event eventOrg = db.Event.Include(s => s.Files).SingleOrDefault(s => s.EventID == id);
// EventOrg eventOrg = db.EventOrgs.Find(id);
if (eventOrg == null)
{
return HttpNotFound();
}
ViewBag.EventBerichten = GetEventBerichtenLijst(id);
ViewBag.eventOrg = eventOrg;
return View(eventOrg);
}
The function for the partial view is here:
public PartialViewResult InhoudByIdPartial(int id)
{
return PartialView(
db.EventBericht.Where(r => r.EventID == id).ToList());
}
The function to fill EventBerichten:
public List<EventBerichten> GetEventBerichtenLijst(int id)
{
var eventLijst = db.EventBericht.ToList();
var berLijst = new List<EventBerichten>();
foreach (var ber in eventLijst)
{
if (ber.EventID == id )
{
berLijst.Add(ber);
}
}
return berLijst;
}
The partialView Model looks like this:
@model IEnumerable<STUVF_back_end.Models.EventBerichten>
<table>
<tr>
<th>
EventID
</th>
<th>
Titel
</th>
<th>
Inhoud
</th>
<th>
BerichtDatum
</th>
<th>
BerichtTijd
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.EventID)
</td>
<td>
@Html.DisplayFor(modelItem => item.Titel)
</td>
<td>
@Html.DisplayFor(modelItem => item.Inhoud)
</td>
<td>
@Html.DisplayFor(modelItem => item.BerichtDatum)
</td>
<td>
@Html.DisplayFor(modelItem => item.BerichtTijd)
</td>
</tr>
}
</table>
VIEUW: This is the script used to get my output in the view
<script type="text/javascript">
$(document).ready(function () {
$("#EventBerichten").change(function () {
$("#log").ajaxError(function (event, jqxhr, settings, exception) {
alert(exception);
});
var BerichtSelected = $("select option:selected").first().text();
$.get('@Url.Action("InhoudByIdPartial")',
{ EventBerichtID: BerichtSelected }, function (data) {
$("#target").html(data);
});
});
});
</script>
@{
Html.RenderAction("InhoudByIdPartial", Model.EventID);
}
<fieldset>
<legend>Berichten over dit Evenement</legend>
<div>
@Html.DropDownList("EventBerichten", new SelectList(ViewBag.EventBerichten, "EventBerichtenID", "Titel"), new { @class = "form-control", onchange = "$(this.form).submit();" })
</div>
<br />
<div id="target">
</div>
<div id="log">
</div>
</fieldset>
I finally found my maven repo mirror is down. I changed to another one, problem solved.
once I need to fix the height of a particular valued row by using inline CSS as following..
<tr><td colspan="4" style="height: 10px;">xxxyyyzzz</td></tr>
Since JSON.parse() method requires the Object keys to be enclosed within quotes for it to work correctly, we would first have to convert the string into a JSON formatted string before calling JSON.parse() method.
var obj = '{ firstName:"John", lastName:"Doe" }';_x000D_
_x000D_
var jsonStr = obj.replace(/(\w+:)|(\w+ :)/g, function(matchedStr) {_x000D_
return '"' + matchedStr.substring(0, matchedStr.length - 1) + '":';_x000D_
});_x000D_
_x000D_
obj = JSON.parse(jsonStr); //converts to a regular object_x000D_
_x000D_
console.log(obj.firstName); // expected output: John_x000D_
console.log(obj.lastName); // expected output: Doe
_x000D_
This would work even if the string has a complex object (like the following) and it would still convert correctly. Just make sure that the string itself is enclosed within single quotes.
var strObj = '{ name:"John Doe", age:33, favorites:{ sports:["hoops", "baseball"], movies:["star wars", "taxi driver"] }}';_x000D_
_x000D_
var jsonStr = strObj.replace(/(\w+:)|(\w+ :)/g, function(s) {_x000D_
return '"' + s.substring(0, s.length-1) + '":';_x000D_
});_x000D_
_x000D_
var obj = JSON.parse(jsonStr);_x000D_
console.log(obj.favorites.movies[0]); // expected output: star wars
_x000D_
I have this function for this case ..
Function GetValue(r As Range, Tag As String) As Integer
Dim c, nRet As String
Dim n, x As Integer
Dim bNum As Boolean
c = r.Value
n = InStr(c, Tag)
For x = n + 1 To Len(c)
Select Case Mid(c, x, 1)
Case ":": bNum = True
Case " ": Exit For
Case Else: If bNum Then nRet = nRet & Mid(c, x, 1)
End Select
Next
GetValue = val(nRet)
End Function
To fill cell BC .. (assumed that you check cell A1)
Worksheets("Übersicht_2013").Cells(i, "BC") = GetValue(range("A1"),"S")
str = "\x12\x34\x56\x78\x9a\xbc\xde\xf1\x23\x45\x67\x89\xab\xcd\xef\x12\x34\x56\x78\x9a"
require 'cgi'
CGI.escape(str)
# => "%124Vx%9A%BC%DE%F1%23Eg%89%AB%CD%EF%124Vx%9A"
Taken from @J-Rou's comment
Just for the sake of completeness: there are IPv4-mapped IPv6 addresses, where you can embed an IPv4 address in an IPv6 address (may not be supported by every IPv6 equipment).
Example: I run a server on my machine, which can be accessed via http://127.0.0.1:19983/solr
. If I access it via an IPv4-mapped IPv6 address then I access it via http://[::ffff:127.0.0.1]:19983/solr
(which will be converted to http://[::ffff:7f00:1]:19983/solr
)
Calendar tCalendar = Calendar.getInstance();
tCalendar.setTime(date);
date is a java.util.Date object. You may use Calendar.getInstance() as well to obtain the Calendar instance(much more efficient).
There is an important detail that has been omitted in the answer above.
MySQL imposes a limit of 65,535 bytes for the max size of each row.
The size of a VARCHAR
column is counted towards the maximum row size, while TEXT
columns are assumed to be storing their data by reference so they only need 9-12 bytes. That means even if the "theoretical" max size of your VARCHAR
field is 65,535 characters you won't be able to achieve that if you have more than one column in your table.
Also note that the actual number of bytes required by a VARCHAR
field is dependent on the encoding of the column (and the content). MySQL counts the maximum possible bytes used toward the max row size, so if you use a multibyte encoding like utf8mb4
(which you almost certainly should) it will use up even more of your maximum row size.
Correction: Regardless of how MySQL computes the max row size, whether or not the VARCHAR
/TEXT
field data is ACTUALLY stored in the row or stored by reference depends on your underlying storage engine. For InnoDB the row format affects this behavior. (Thanks Bill-Karwin)
Reasons to use TEXT
:
Reasons to use VARCHAR
:
This is a workaround for the chrome bug: change the rel attribute to stylesheet! Keep the original link though. Works like a charm:
I came up with this workaround because we also have a requirement to be able to update customer's sites / production code and I didn't find any of the other solutions to work.
For [1], you can't: these operators are made to return a value, not perform operations.
The expression
a ? b : c
evaluates to b
if a
is true and evaluates to c
if a
is false.
The expression
b ?? c
evaluates to b
if b
is not null and evaluates to c
if b
is null.
If you write
return a ? b : c;
or
return b ?? c;
they will always return something.
For [2], you can write a function that returns the right value that performs your "multiple operations", but that's probably worse than just using if/else
.
Just wanted to add something: I found tim cooper's answer very useful, I used it to make a method which accepts an array of positions and does the insert on all of them so here that is:
EDIT: Looks like my old function assumed $insertstr
was only 1 character and that the array was sorted. This works for arbitrary character length.
function stringInsert($str, $pos, $insertstr) {
if (!is_array($pos)) {
$pos = array($pos);
} else {
asort($pos);
}
$insertionLength = strlen($insertstr);
$offset = 0;
foreach ($pos as $p) {
$str = substr($str, 0, $p + $offset) . $insertstr . substr($str, $p + $offset);
$offset += $insertionLength;
}
return $str;
}
Yes that is correct. "Boolean variables only have two possible values: true (1) and false (0)." cpp tutorial on boolean values
You use ComponentScan to scan multiple packages using
@ComponentScan({"com.my.package.first","com.my.package.second"})
Just to make it clear, you can use f-string formatting. This has almost the same syntax as the format
method, but make it a bit nicer.
Example:
print(f'{numvar:.9f}')
More reading about the new f string:
Here is a diagram of the execution times of the various tested methods (from last link above):
If you use multiple users at android, verify that the app is uninstalled everywhere.
if you are using for certain text field then use the class
<style>
.inputForm{
border-radius:5px;
-moz-border-radius:5px;
-webkit-border-radius:5px;
}
</style>
and in html code use
<input type="text" class="inputForm">
or if u want to do this for all the input type text field means use
<style>
input[type="text"]{
border-radius:5px;
-moz-border-radius:5px;
-webkit-border-radius:5px;
}
</style>
and in html code
<input type="text" name="name">
SOLUTION
This means that you are missing the right for using it. Create it with Netsh Commands for Hypertext Transfer Protocol > add urlacl.
1) Open "Command Line Interface (CLI)" called "Command shell" with Win+R write "cmd"
2) Open CLI windows like administrator with mouse context menu on opened windows or icon "Run as administrator"
3) Insert command to register url
netsh http add urlacl url=http://{ip_addr}:{port}/ user=everyone
NOTE:
netsh http delete urlacl url=http://{ip_addr}:{port}/
The ConnectTimeout option allows you to tell your ssh client how long you're willing to wait for a connection before returning an error. By setting ConnectTimeout to 1, you're effectively saying "try for at most 1 second and then fail if you haven't connected yet".
The problem is that when you connect by name, the DNS lookup can take several seconds. Connecting by IP address is much faster, and may actually work in one second or less. What sinelaw is experiencing is that every attempt to connect by DNS name is failing to occur within one second. The default setting of ConnectTimeout defers to the linux kernel connect timeout, which is usually pretty long.
You can pass an ArrayList<E>
the same way, if the E
type is Serializable
.
You would call the putExtra (String name, Serializable value)
of Intent
to store, and getSerializableExtra (String name)
for retrieval.
Example:
ArrayList<String> myList = new ArrayList<String>();
intent.putExtra("mylist", myList);
In the other Activity:
ArrayList<String> myList = (ArrayList<String>) getIntent().getSerializableExtra("mylist");
This code is working fine for me in a loop
$remove = array(
"market_value",
"sector_id"
);
foreach($remove as $key){
unset($obj_name->$key);
}
Angular 1.1.5 introduced the ng-if directive. That's the best solution for this particular problem. If you are using an older version of Angular, consider using angular-ui's ui-if directive.
If you arrived here looking for answers to the general question of "conditional logic in templates" also consider:
Original answer:
Here is a not-so-great "ng-if" directive:
myApp.directive('ngIf', function() {
return {
link: function(scope, element, attrs) {
if(scope.$eval(attrs.ngIf)) {
// remove '<div ng-if...></div>'
element.replaceWith(element.children())
} else {
element.replaceWith(' ')
}
}
}
});
that allows for this HTML syntax:
<div ng-repeat="message in data.messages" ng-class="message.type">
<hr>
<div ng-if="showFrom(message)">
<div>From: {{message.from.name}}</div>
</div>
<div ng-if="showCreatedBy(message)">
<div>Created by: {{message.createdBy.name}}</div>
</div>
<div ng-if="showTo(message)">
<div>To: {{message.to.name}}</div>
</div>
</div>
replaceWith() is used to remove unneeded content from the DOM.
Also, as I mentioned on Google+, ng-style can probably be used to conditionally load background images, should you want to use ng-show instead of a custom directive. (For the benefit of other readers, Jon stated on Google+: "both methods use ng-show which I'm trying to avoid because it uses display:none and leaves extra markup in the DOM. This is a particular problem in this scenario because the hidden element will have a background image which will still be loaded in most browsers.").
See also How do I conditionally apply CSS styles in AngularJS?
The angular-ui ui-if directive watches for changes to the if condition/expression. Mine doesn't. So, while my simple implementation will update the view correctly if the model changes such that it only affects the template output, it won't update the view correctly if the condition/expression answer changes.
E.g., if the value of a from.name changes in the model, the view will update. But if you delete $scope.data.messages[0].from
, the from name will be removed from the view, but the template will not be removed from the view because the if-condition/expression is not being watched.
For those who use Data Binding:
Add the following static method to any class
@BindingAdapter("app:thumbTintCompat")
public static void setThumbTint(SeekBar seekBar, @ColorInt int color) {
seekBar.getThumb().setColorFilter(color, PorterDuff.Mode.SRC_IN);
}
Add app:thumbTintCompat
attribute to your SeekBar
<SeekBar
android:id="@+id/seek_bar"
style="@style/Widget.AppCompat.SeekBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:thumbTintCompat="@{@android:color/white}"
/>
That's it. Now you can use app:thumbTintCompat
with any SeekBar
. The progress tint can be configured in the same way.
Note: this method is also compatble with pre-lollipop devices.
litersOfPetrol = Float.parseFloat(df.format(litersOfPetrol));
System.out.println("liters of petrol before putting in editor : "+litersOfPetrol);
You print Float here
, that has no format at all.
To print formatted float, just use
String formatted = df.format(litersOfPetrol);
System.out.println("liters of petrol before putting in editor : " + formatted);
As far as I know, QPixmap
is used for displaying images and QImage
for reading them. There are QPixmap::convertFromImage()
and QPixmap::fromImage()
functions to convert from QImage
.
It is at the same location: ~/.android/debug.keystore
Change the rule on your <a>
element from:
.navigation ul a {
color: #000;
display: block;
padding: 0 65px 0 0;
text-decoration: none;
}?
to
.navigation ul a {
color: #000;
display: block;
padding: 0 65px 0 0;
text-decoration: none;
width:100%;
text-align:center;
}?
Just add two new rules (width:100%;
and text-align:center;
). You need to make the anchor expand to take up the full width of the list item and then text-align center it.
I suppose this depends on your architecture and whatever else you may need to consider, but you could also take the object-oriented approach and use a class.
class ClassName {
private $site_url;
function __construct( $url ) {
$this->site_url = $url;
}
public function parts( string $part ) {
echo 'http://' . $this->site_url . 'content/' . $part . '.php';
}
# You could build a bunch of other things here
# too and still have access to $this->site_url.
}
Then you can create and use the object wherever you'd like.
$obj = new ClassName($site_url);
$obj->parts('part_argument');
This could be overkill for what OP was specifically trying to achieve, but it's at least an option I wanted to put on the table for newcomers since nobody mentioned it yet.
The advantage here is scalability and containment. For example, if you find yourself needing to pass the same variables as references to multiple functions for the sake of a common task, that could be an indicator that a class is in order.
If there is nothing to lose you could also just delete your fork just go to settings... go to danger zone section below and click delete repository. It will ask you to input the repository name and your password after. After that you just fork the original again.
The only real difference between RPC and RMI is that there is objects involved in RMI: instead of invoking functions through a proxy function, we invoke methods through a proxy.
I was also strugling with this issue and the answer is way easier than those provided over here. you can just look for it using xpath and unset it it the following method:
unset($XML->xpath("NODESNAME[@id='test']")[0]->{0});
this code will look for a node named "NODESNAME" with the id attribute "test" and remove the first occurence.
remember to save the xml using $XML->saveXML(...);
To represent the fact that the value is not present you have two choices:
1) If the whole char
range is meaningful and you cannot reserve any value, then use char*
instead of char
:
char** c = new char*[N];
c[0] = NULL; // no character
*c[1] = ' '; // ordinary character
*c[2] = 'a'; // ordinary character
*c[3] = '\0' // zero-code character
Then you'll have c[i] == NULL
for when character is not present and otherwise *c[i]
for ordinary characters.
2) If you don't need some values representable in char
then reserve one for indicating that value is not present, for example the '\0'
character.
char* c = new char[N];
c[0] = '\0'; // no character
c[1] = ' '; // ordinary character
c[2] = 'a'; // ordinary character
Then you'll have c[i] == '\0'
for when character is not present and ordinary characters otherwise.
You can use round function. Here some example
numpy.round([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01],2)
array([ 21.53, 8.13, 3.97, 10.08])
IF you want change just display representation, I would not recommended to alter printing format globally, as it suggested above. I would format my output in place.
>>a=np.array([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01])
>>> print([ "{:0.2f}".format(x) for x in a ])
['21.53', '8.13', '3.97', '10.08']
You can also try mapping framework based on Dozer, but with Excel mapping declaration. They've got some tools and additional cool features. Check at http://openl-tablets.sf.net/mapper
<select id="countries" onfocus="this.defaultIndex=this.selectedIndex;" onchange="this.selectedIndex=this.defaultIndex;">
<option value="1">Country1</option>
<option value="2">Country2</option>
<option value="3">Country3</option>
<option value="4">Country4</option>
<option value="5">Country5</option>
<option value="6">Country6</option>
<option value="7" selected="selected">Country7</option>
<option value="8">Country8</option>
<option value="9">Country9</option>
</select>
Tested and working in IE 6, 7 & 8b2, Firefox 2 & 3, Opera 9.62, Safari 3.2.1 for Windows and Google Chrome.
"^" For the begining of the line "$" for the end of it. Eg.:
var re = /^abc$/;
Would match "abc" but not "1abc" or "abc1". You can learn more at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
To be able to use std::unordered_map
(or one of the other unordered associative containers) with a user-defined key-type, you need to define two things:
A hash function; this must be a class that overrides operator()
and calculates the hash value given an object of the key-type. One particularly straight-forward way of doing this is to specialize the std::hash
template for your key-type.
A comparison function for equality; this is required because the hash cannot rely on the fact that the hash function will always provide a unique hash value for every distinct key (i.e., it needs to be able to deal with collisions), so it needs a way to compare two given keys for an exact match. You can implement this either as a class that overrides operator()
, or as a specialization of std::equal
, or – easiest of all – by overloading operator==()
for your key type (as you did already).
The difficulty with the hash function is that if your key type consists of several members, you will usually have the hash function calculate hash values for the individual members, and then somehow combine them into one hash value for the entire object. For good performance (i.e., few collisions) you should think carefully about how to combine the individual hash values to ensure you avoid getting the same output for different objects too often.
A fairly good starting point for a hash function is one that uses bit shifting and bitwise XOR to combine the individual hash values. For example, assuming a key-type like this:
struct Key
{
std::string first;
std::string second;
int third;
bool operator==(const Key &other) const
{ return (first == other.first
&& second == other.second
&& third == other.third);
}
};
Here is a simple hash function (adapted from the one used in the cppreference example for user-defined hash functions):
namespace std {
template <>
struct hash<Key>
{
std::size_t operator()(const Key& k) const
{
using std::size_t;
using std::hash;
using std::string;
// Compute individual hash values for first,
// second and third and combine them using XOR
// and bit shifting:
return ((hash<string>()(k.first)
^ (hash<string>()(k.second) << 1)) >> 1)
^ (hash<int>()(k.third) << 1);
}
};
}
With this in place, you can instantiate a std::unordered_map
for the key-type:
int main()
{
std::unordered_map<Key,std::string> m6 = {
{ {"John", "Doe", 12}, "example"},
{ {"Mary", "Sue", 21}, "another"}
};
}
It will automatically use std::hash<Key>
as defined above for the hash value calculations, and the operator==
defined as member function of Key
for equality checks.
If you don't want to specialize template inside the std
namespace (although it's perfectly legal in this case), you can define the hash function as a separate class and add it to the template argument list for the map:
struct KeyHasher
{
std::size_t operator()(const Key& k) const
{
using std::size_t;
using std::hash;
using std::string;
return ((hash<string>()(k.first)
^ (hash<string>()(k.second) << 1)) >> 1)
^ (hash<int>()(k.third) << 1);
}
};
int main()
{
std::unordered_map<Key,std::string,KeyHasher> m6 = {
{ {"John", "Doe", 12}, "example"},
{ {"Mary", "Sue", 21}, "another"}
};
}
How to define a better hash function? As said above, defining a good hash function is important to avoid collisions and get good performance. For a real good one you need to take into account the distribution of possible values of all fields and define a hash function that projects that distribution to a space of possible results as wide and evenly distributed as possible.
This can be difficult; the XOR/bit-shifting method above is probably not a bad start. For a slightly better start, you may use the hash_value
and hash_combine
function template from the Boost library. The former acts in a similar way as std::hash
for standard types (recently also including tuples and other useful standard types); the latter helps you combine individual hash values into one. Here is a rewrite of the hash function that uses the Boost helper functions:
#include <boost/functional/hash.hpp>
struct KeyHasher
{
std::size_t operator()(const Key& k) const
{
using boost::hash_value;
using boost::hash_combine;
// Start with a hash value of 0 .
std::size_t seed = 0;
// Modify 'seed' by XORing and bit-shifting in
// one member of 'Key' after the other:
hash_combine(seed,hash_value(k.first));
hash_combine(seed,hash_value(k.second));
hash_combine(seed,hash_value(k.third));
// Return the result.
return seed;
}
};
And here’s a rewrite that doesn’t use boost, yet uses good method of combining the hashes:
namespace std
{
template <>
struct hash<Key>
{
size_t operator()( const Key& k ) const
{
// Compute individual hash values for first, second and third
// http://stackoverflow.com/a/1646913/126995
size_t res = 17;
res = res * 31 + hash<string>()( k.first );
res = res * 31 + hash<string>()( k.second );
res = res * 31 + hash<int>()( k.third );
return res;
}
};
}
I've just tested a few browsers using this silly bit of JavaScript:
function log_newline(msg, test_value) {_x000D_
if (!test_value) { _x000D_
test_value = document.getElementById('test').value;_x000D_
}_x000D_
console.log(msg + ': ' + (test_value.match(/\r/) ? 'CR' : '')_x000D_
+ ' ' + (test_value.match(/\n/) ? 'LF' : ''));_x000D_
}_x000D_
_x000D_
log_newline('HTML source');_x000D_
log_newline('JS string', "foo\nbar");_x000D_
log_newline('JS template literal', `bar_x000D_
baz`);
_x000D_
<textarea id="test" name="test">_x000D_
_x000D_
</textarea>
_x000D_
IE8 and Opera 9 on Windows use \r\n
. All the other browsers I tested (Safari 4 and Firefox 3.5 on Windows, and Firefox 3.0 on Linux) use \n
. They can all handle \n
just fine when setting the value, though IE and Opera will convert that back to \r\n
again internally. There's a SitePoint article with some more details called Line endings in Javascript.
Note also that this is independent of the actual line endings in the HTML file itself (both \n
and \r\n
give the same results).
When submitting a form, all browsers canonicalize newlines to %0D%0A
in URL encoding. To see that, load e.g. data:text/html,<form><textarea name="foo">foo%0abar</textarea><input type="submit"></form>
and press the submit button. (Some browsers block the load of the submitted page, but you can see the URL-encoded form values in the console.)
I don't think you really need to do much of any determining, though. If you just want to split the text on newlines, you could do something like this:
lines = foo.value.split(/\r\n|\r|\n/g);
When using java -cp
you are required to provide fully qualified main class name, e.g.
java -cp com.mycompany.MyMain
When using java -jar myjar.jar
your jar file must provide the information about main class via manifest.mf contained into the jar file in folder META-INF
:
Main-Class: com.mycompany.MyMain
I have faced the same problem. It happens when you turn on 2 Step Verification (MFA). Just Turn off 2 Step Verification and your problem should be solved.
You'll find the answer to your question in the help page for ?axis
.
Here is one of the help page examples, modified with your data:
Option 1: use xaxp
to define the axis labels
plot(x,y, xaxt="n")
axis(1, xaxp=c(10, 200, 19), las=2)
Option 2: Use at
and seq()
to define the labels:
plot(x,y, xaxt="n")
axis(1, at = seq(10, 200, by = 10), las=2)
Both these options yield the same graphic:
PS. Since you have a large number of labels, you'll have to use additional arguments to get the text to fit in the plot. I use las
to rotate the labels.
Note: you should use the accepted answer if possible. It's better than mine.
It's quite easy with the GD library.
It's built in usually, you probably have it (use phpinfo()
to check)
$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");
imagejpeg($image, "folder/file.jpg");
The above answer is better (faster) for most situations, but with GD you can also modify it in some form (cropping for example).
$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");
imagecopy($image, $image, 0, 140, 0, 0, imagesx($image), imagesy($image));
imagejpeg($image, "folder/file.jpg");
This only works if allow_url_fopen
is true
(it is by default)
An HTTP GET request can't contain data to be posted to the server. However, you can add a query string to the request.
angular.http provides an option for it called params
.
$http({
url: user.details_path,
method: "GET",
params: {user_id: user.id}
});
See: http://docs.angularjs.org/api/ng.$http#get and https://docs.angularjs.org/api/ng/service/$http#usage (shows the params
param)
You should install IIS sub components from
Control Panel
-> Programs and Features
-> Turn Windows features on or off
Internet Information Services
has subsection World Wide Web Services
/ Application Development Features
There you must check ASP.NET
(.NET Extensibility
, ISAPI Extensions
, ISAPI Filters
will be selected automatically). Double check that specific versions are checked. Under Windows Server 2012 R2, these options are split into 4 & 4.5.
Run from cmd
:
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir
Finally check in IIS manager, that your application uses application pool with .NET framework version v4.0.
Also, look at this answer.
A char
variable is actually an 8-bit integral value. It will have values from 0
to 255
. These are ASCII codes. 0
stands for the C-null character, and 255
stands for an empty symbol.
So, when you write the following assignment:
char a = 'a';
It is the same thing as:
char a = 97;
So, you can compare two char
variables using the >
, <
, ==
, <=
, >=
operators:
char a = 'a';
char b = 'b';
if( a < b ) printf("%c is smaller than %c", a, b);
if( a > b ) printf("%c is smaller than %c", a, b);
if( a == b ) printf("%c is equal to %c", a, b);
You can try this:
HTML
<table>
<tr>
<td class="shrink">element1</td>
<td class="shrink">data</td>
<td class="shrink">junk here</td>
<td class="expand">last column</td>
</tr>
<tr>
<td class="shrink">elem</td>
<td class="shrink">more data</td>
<td class="shrink">other stuff</td>
<td class="expand">again, last column</td>
</tr>
<tr>
<td class="shrink">more</td>
<td class="shrink">of </td>
<td class="shrink">these</td>
<td class="expand">rows</td>
</tr>
</table>
CSS
table {
border: 1px solid green;
border-collapse: collapse;
width:100%;
}
table td {
border: 1px solid green;
}
table td.shrink {
white-space:nowrap
}
table td.expand {
width: 99%
}
in my case, i was sure that the action is correct, but i was passing wrong URL, i passed the website link without the http:// in it's beginning, so it caused the same issue, here is my manifest (part of it)
<activity
android:name=".MyBrowser"
android:label="MyBrowser Activity" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="com.dsociety.activities.MyBrowser" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" />
</intent-filter>
</activity>
when i code the following, the same Exception is thrown at run time :
Intent intent = new Intent();
intent.setAction("com.dsociety.activities.MyBrowser");
intent.setData(Uri.parse("www.google.com")); // should be http://www.google.com
startActivity(intent);
I do the following in my eBay listings:
<p style="border:solid thick darkblue; border-radius: 1em;
border-width:3px; padding-left:9px; padding-top:6px;
padding-bottom:6px; margin:2px; width:980px;">
This produces a box border with rounded corners.You can play with the variables.
Please review the following documentation. It will definitely solve the problem. http://www.programmersought.com/article/55001874709/
Looks like the best approach (in 2018) is to use legend.key.size
under the theme
object. (e.g., see here).
#Set-up:
library(ggplot2)
library(gridExtra)
gp <- ggplot(data = mtcars, aes(mpg, cyl, colour = factor(cyl))) +
geom_point()
This is real easy if you are using theme_bw()
:
gpbw <- gp + theme_bw()
#Change spacing size:
g1bw <- gpbw + theme(legend.key.size = unit(0, 'lines'))
g2bw <- gpbw + theme(legend.key.size = unit(1.5, 'lines'))
g3bw <- gpbw + theme(legend.key.size = unit(3, 'lines'))
grid.arrange(g1bw,g2bw,g3bw,nrow=3)
However, this doesn't work quite so well otherwise (e.g., if you need the grey background on your legend symbol):
g1 <- gp + theme(legend.key.size = unit(0, 'lines'))
g2 <- gp + theme(legend.key.size = unit(1.5, 'lines'))
g3 <- gp + theme(legend.key.size = unit(3, 'lines'))
grid.arrange(g1,g2,g3,nrow=3)
#Notice that the legend symbol squares get bigger (that's what legend.key.size does).
#Let's [indirectly] "control" that, too:
gp2 <- g3
g4 <- gp2 + theme(legend.key = element_rect(size = 1))
g5 <- gp2 + theme(legend.key = element_rect(size = 3))
g6 <- gp2 + theme(legend.key = element_rect(size = 10))
grid.arrange(g4,g5,g6,nrow=3) #see picture below, left
Notice that white squares begin blocking legend title (and eventually the graph itself if we kept increasing the value).
#This shows you why:
gt <- gp2 + theme(legend.key = element_rect(size = 10,color = 'yellow' ))
I haven't quite found a work-around for fixing the above problem... Let me know in the comments if you have an idea, and I'll update accordingly!
$layers
...Just use this css method:
body{
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
You can find the same answer here: How to disable text selection highlighting using CSS?
Switch the order of the functions or do a forward declaration of the writefiles function and it will work I think.
A more consistent and robust way is to use NextResponderTextField
You can configure it totally from interface builder with no need for setting the delegate or using view.tag
.
All you need to do is
UITextField
to be NextResponderTextField
nextResponderField
to point to the next responder it can be anything UITextField
or any UIResponder
subclass. It can be also a UIButton and the library is smart enough to trigger the TouchUpInside
event of the button only if it's enabled.
Here is the library in action:
5. Something else - there must be other solutions out there?
You're right, there is! And it is called JWT (JSON Web Tokens).
JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA.
I highly recommend looking into JWTs. They're a much simpler solution to the problem when compared against alternative solutions.
In Mvc 4 you can use AcceptVerbsAttribute, I think this is a very clean solution
[AcceptVerbs(WebRequestMethods.Http.Get, WebRequestMethods.Http.Post)]
public IHttpActionResult Login()
{
// Login logic
}
Not the solution, but you can use debug key for signing release builds to avoid blocking the installation from Google Play Protect. It looks like Play Protect doesn't warn for builds signed with automatically generated debug.keystore
.
Note that your debug builds are not unsigned, they are just signed with a debug key.
Of course, you cannot use the build for production distribution (Google Play, Amazon, etc.), but it's still worth for pre-production internal testing which requires a high-frequency feedback loop.
You can add a task to build release with debug.keystore by adding the configuration in build.gradle
, something like:
android {
buildTypes {
// add after the `release` definition
releaseDebugKey { initWith release }
}
signingConfigs {
// use debug.keystore for releaseDebugKey builds
releaseDebugKey { initWith debug }
}
}
then execute ./gradlew assembleReleaseDebugKey
to build a release build with debug key.
To quickly see the differences with older revisions of a file:
git show -1 filename.txt
> to compare against the last revision of file
git show -2 filename.txt
> to compare against the 2nd last revision
git show -3 fielname.txt
> to compare against the last 3rd last revision
There's a nice way to eject webpack.config.js from angular-cli. Just run:
$ ng eject
This will generate webpack.config.js in the root folder of your project, and you're free to configure it the way you want. The downside of this is that build/start scripts in your package.json will be replaced with the new commands and instead of
$ ng serve
you would have to do something like
$ npm run build & npm run start
This method should work in all the recent versions of angular-cli (I personally tried a few, with the oldest being 1.0.0-beta.21, and the latest 1.0.0-beta.32.3)
Probably there's something wrong with the input values for X and/or T. The function from the question works ok:
import numpy as np
from math import e
def sigmoid(X, T):
return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))
X = np.array([[1, 2, 3], [5, 0, 0]])
T = np.array([[1, 2], [1, 1], [4, 4]])
print(X.dot(T))
# Just to see if values are ok
print([1. / (1. + e ** el) for el in [-5, -10, -15, -16]])
print()
print(sigmoid(X, T))
Result:
[[15 16]
[ 5 10]]
[0.9933071490757153, 0.9999546021312976, 0.999999694097773, 0.9999998874648379]
[[ 0.99999969 0.99999989]
[ 0.99330715 0.9999546 ]]
Probably it's the dtype of your input arrays. Changing X to:
X = np.array([[1, 2, 3], [5, 0, 0]], dtype=object)
Gives:
Traceback (most recent call last):
File "/[...]/stackoverflow_sigmoid.py", line 24, in <module>
print sigmoid(X, T)
File "/[...]/stackoverflow_sigmoid.py", line 14, in sigmoid
return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))
AttributeError: exp
Exceptions are usually immutable: you can't change their message after they've been created. What you can do, though, is chain exceptions:
throw new TransactionProblemException(transNbr, originalException);
The stack trace will look like
TransactionProblemException : transNbr
at ...
at ...
caused by OriginalException ...
at ...
at ...
Header exists:
if (Request.Headers["XYZComponent"] != null)
or even better:
string xyzHeader = Request.Headers["XYZComponent"];
bool isXYZ;
if (bool.TryParse(xyzHeader, out isXYZ) && isXYZ)
which will check whether it is set to true. This should be fool-proof because it does not care on leading/trailing whitespace and is case-insensitive (bool.TryParse
does work on null
)
Addon: You could make this more simple with this extension method which returns a nullable boolean. It should work on both invalid input and null.
public static bool? ToBoolean(this string s)
{
bool result;
if (bool.TryParse(s, out result))
return result;
else
return null;
}
Usage (because this is an extension method and not instance method this will not throw an exception on null
- it may be confusing, though):
if (Request.Headers["XYZComponent"].ToBoolean() == true)
It's a "precompiled header file" -- any headers you include in stdafx.h are pre-processed to save time during subsequent compilations. You can read more about it here on MSDN.
If you're building a cross-platform application, check "Empty project" when creating your project and Visual Studio won't put any files at all in your project.
Try the top
command. It's an interactive command that will display the running processes.
You may also use the Apple's "Activity Monitor" application (located in /Applications/Utilities/
).
It provides an actually quite nice GUI. You can see all the running processes, filter them by users, get extended informations about them (CPU, memory, network, etc), monitor them, etc...
Probably your best choice, unless you want to stick with the terminal (in such a case, read the top
or ps
manual, as those commands have a bunch of options).
Convert an ArrayList to an object array
ArrayList has a constructor that takes a Collection, so the common idiom is:
List<T> list = new ArrayList<T>(Arrays.asList(array));
Which constructs a copy of the list created by the array.
now, Arrays.asList(array)
will wrap the array, so changes to the list
will affect the array, and visa versa. Although you can't add or remove
please try to install the dependencie with pip, run this command:
sudo pip install -U setuptools
Just use GETDATE()
or GETUTCDATE()
(if you want to get the "universal" UTC time, instead of your local server's time-zone related time).
INSERT INTO [Business]
([IsDeleted]
,[FirstName]
,[LastName]
,[LastUpdated]
,[LastUpdatedBy])
VALUES
(0, 'Joe', 'Thomas',
GETDATE(), <LastUpdatedBy, nvarchar(50),>)
I don't have enough rep to comment here, so I'm submitting a new answer to improve on dogbane's answer. The dot . in the regexp
[[ sed-4.2.2.tar.bz2 =~ tar.bz2$ ]] && echo matched
will actually match any character, not only the literal dot between 'tar.bz2', for example
[[ sed-4.2.2.tar4bz2 =~ tar.bz2$ ]] && echo matched
[[ sed-4.2.2.tar§bz2 =~ tar.bz2$ ]] && echo matched
or anything that doesn't require escaping with '\'. The strict syntax should then be
[[ sed-4.2.2.tar.bz2 =~ tar\.bz2$ ]] && echo matched
or you can go even stricter and also include the previous dot in the regex:
[[ sed-4.2.2.tar.bz2 =~ \.tar\.bz2$ ]] && echo matched
Ok found the answer. exchange()
is the best way. Oddly the HttpEntity
class doesn't have a setBody()
method (it has getBody()
), but it is still possible to set the request body, via the constructor.
// Create the request body as a MultiValueMap
MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
body.add("field", "value");
// Note the body object as first parameter!
HttpEntity<?> httpEntity = new HttpEntity<Object>(body, requestHeaders);
ResponseEntity<MyModel> response = restTemplate.exchange("/api/url", HttpMethod.POST, httpEntity, MyModel.class);
If the goal is to have a reusable RestTemplate which is in general useful for attaching the same header to a series of similar request a org.springframework.boot.web.client.RestTemplateCustomizer
parameter can be used with a RestTemplateBuilder
:
String accessToken= "<the oauth 2 token>";
RestTemplate restTemplate = new RestTemplateBuilder(rt-> rt.getInterceptors().add((request, body, execution) -> {
request.getHeaders().add("Authorization", "Bearer "+accessToken);
return execution.execute(request, body);
})).build();
Reason of the error: Package name left blank while creating a class. This make use of default package. Thus causes this error.
Quick fix:
helloWorld
inside the src
folder.helloWorld.java
file in that package. Just drag and drop on
the package. Error should disappear.Explanation:
Latest version of Eclipse required java11 or above. The module
feature is introduced in java9 and onward. It was proposed in 2005 for Java7 but later suspended. Java is object oriented based. And module is the moduler approach which can be seen in language like C. It was harder to implement it, due to which it took long time for the release. Source: Understanding Java 9 Modules
When you create a new project in Eclipse then by default module feature is selected. And in Eclipse-2020-09-R, a pop-up appears which ask for creation of module-info.java
file. If you select don't create
then module-info.java
will not create and your project will free from this issue.
Best practice is while crating project, after giving project name. Click on next
button instead of finish
. On next page at the bottom it ask for creation of module-info.java
file. Select or deselect as per need.
If selected: (by default) click on finish
button and give name for module. Now while creating a class don't forget to give package name. Whenever you create a class just give package name. Any name, just don't left it blank.
If deselect: No issue
In my case it was a spelling mistake in the database name in connection string.
Use chocolatey in PowerShell
choco install ruby -y
refreshenv
gem install bundler
If you don't want to alter the CSS file, this is what works for me. In HTML, add style with color:
<i class="fa fa-cog" style="color:#fff;"></i>
I would do something like:
$(documento).on('click', '#answer', function() {
feedback('hey there');
});
You can redirect print with the >>
operator.
f = open(filename,'w')
print >>f, 'whatever' # Python 2.x
print('whatever', file=f) # Python 3.x
In most cases, you're better off just writing to the file normally.
f.write('whatever')
or, if you have several items you want to write with spaces between, like print
:
f.write(' '.join(('whatever', str(var2), 'etc')))
I was having same issue. After some digging I realized that many post/pre-install scripts would try to install various dependencies and some times specific repositories are used. A better way is to disable certificate check for https module for nodejs that worked for me.
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"
You simply can't use View as a Header of ListView.
Because the view which is being passed in has to be inflated.
Look at my answer at Android ListView addHeaderView() nullPointerException for predefined Views for more info.
EDIT:
Look at this tutorial Android ListView and ListActivity - Tutorial .
EDIT 2: This link is broken Android ListActivity with a header or footer
In the HTML form I have not added following line, so no attachment was going:
enctype="multipart/form-data"
After adding above line in form (as below), the attachment went perfect.
<form id="form1" name="form1" method="post" action="form_phpm_mailer.php" enctype="multipart/form-data">
More powerful slug generation method on pure JavaScript. It's basically support transliteration for all Cyrillic characters and many Umlauts (German, Danish, France, Turkish, Ukrainian and etc.) but can be easily extended.
function makeSlug(str)_x000D_
{_x000D_
var from="? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? a a ä á à â å c c e e e é è ê æ g g ö ó ø ? ô o ? ? n ? r s ü ß r l d þ h ? i ï í î j k l n n n r š s t u ú û ? ù ü u u ý ÿ ž z z ç ? ?".split(' ');_x000D_
var to= "a b v g d e e zh z i y k l m n o p r s t u f h ts ch sh shch # y # e yu ya a a ae a a a a c c e e e e e e e g g oe o o o o o m n n p r s ue ss r l d th h h i i i i j k l n n n r s s t u u u u u u u u y y z z z c ye g".split(' ');_x000D_
_x000D_
str = str.toLowerCase();_x000D_
_x000D_
// remove simple HTML tags_x000D_
str = str.replace(/(<[a-z0-9\-]{1,15}[\s]*>)/gi, '');_x000D_
str = str.replace(/(<\/[a-z0-9\-]{1,15}[\s]*>)/gi, '');_x000D_
str = str.replace(/(<[a-z0-9\-]{1,15}[\s]*\/>)/gi, '');_x000D_
_x000D_
str = str.replace(/^\s+|\s+$/gm,''); // trim spaces_x000D_
_x000D_
for(i=0; i<from.length; ++i)_x000D_
str = str.split(from[i]).join(to[i]);_x000D_
_x000D_
// Replace different kind of spaces with dashes_x000D_
var spaces = [/( | | )/gi, /(—|–|‑)/gi,_x000D_
/[(_|=|\\|\,|\.|!)]+/gi, /\s/gi];_x000D_
_x000D_
for(i=0; i<from.length; ++i)_x000D_
str = str.replace(spaces[i], '-');_x000D_
str = str.replace(/-{2,}/g, "-");_x000D_
_x000D_
// remove special chars like &_x000D_
str = str.replace(/&[a-z]{2,7};/gi, '');_x000D_
str = str.replace(/&#[0-9]{1,6};/gi, '');_x000D_
str = str.replace(/&#x[0-9a-f]{1,6};/gi, '');_x000D_
_x000D_
str = str.replace(/[^a-z0-9\-]+/gmi, ""); // remove all other stuff_x000D_
str = str.replace(/^\-+|\-+$/gm,''); // trim edges_x000D_
_x000D_
return str;_x000D_
};_x000D_
_x000D_
_x000D_
document.getElementsByTagName('pre')[0].innerHTML = makeSlug(" <br/> ‪???&???<strong>??_????</strong>?…???????????\r???\n?–?????? ??????\t \n?\t??????´? ??\\?????–????????\t????.Danke schön!ich heiße=?áÞÿá-Skånske,København çagatay rí gé tor zöldülésetekrol - . ");
_x000D_
<div>_x000D_
<pre>Hello world!</pre>_x000D_
</div>
_x000D_
The standard Mysql rename statement is:
ALTER [ONLINE | OFFLINE] [IGNORE] TABLE tbl_name
CHANGE [COLUMN] old_col_name new_col_name column_definition
[FIRST|AFTER col_name]
for this example:
ALTER TABLE xyz CHANGE manufacurerid manufacturerid datatype(length)
Reference: MYSQL 5.1 ALTER TABLE Syntax
You're trying to pass file objects as filenames. Try using
infile = '110331_HS1A_1_rtTA.result'
outfile = '2.txt'
at the top of your code.
(Not only does the doubled usage of open()
cause that problem with trying to open the file again, it also means that infile
and outfile
are never closed during the course of execution, though they'll probably get closed once the program ends.)
This is gonna delete all the remote branches that are not present locally (in ruby):
bs = `git branch`.split; bs2 = `git branch -r | grep origin`.split.reject { |b| bs.include?(b.split('/')[1..-1].join('/')) }; bs2.each { |b| puts `git push origin --delete #{b.split('/')[1..-1].join('/')}` }
Explained:
# local branches
bs = `git branch`.split
# remote branches
bs2 = `git branch -r | grep origin`.split
# reject the branches that are present locally (removes origin/ in front)
bs2.reject! { |b| bs.include?(b.split('/')[1..-1].join('/')) }
# deletes the branches (removes origin/ in front)
bs2.each { |b| puts `git push origin --delete #{b.split('/')[1..-1].join('/')}` }
you can use QString::fromAscii()
QByteArray data = entity->getData();
QString s_data = QString::fromAscii(data.data());
with data()
returning a char*
for QT5, you should use fromCString()
instead, as fromAscii()
is deprecated, see https://bugreports.qt-project.org/browse/QTBUG-21872 https://bugreports.qt.io/browse/QTBUG-21872
It's very simple. Git doesn't care about what's the name of its directory. It only cares what's inside. So you can simply do:
# copy the directory into newrepo dir that exists already (else create it)
$ cp -r gitrepo1 newrepo
# remove .git from old repo to delete all history and anything git from it
$ rm -rf gitrepo1/.git
Note that the copy is quite expensive if the repository is large and with a long history. You can avoid it easily too:
# move the directory instead
$ mv gitrepo1 newrepo
# make a copy of the latest version
# Either:
$ mkdir gitrepo1; cp -r newrepo/* gitrepo1/ # doesn't copy .gitignore (and other hidden files)
# Or:
$ git clone --depth 1 newrepo gitrepo1; rm -rf gitrepo1/.git
# Or (look further here: http://stackoverflow.com/q/1209999/912144)
$ git archive --format=tar --remote=<repository URL> HEAD | tar xf -
Once you create newrepo
, the destination to put gitrepo1
could be anywhere, even inside newrepo
if you want it. It doesn't change the procedure, just the path you are writing gitrepo1
back.
I would do this:
function Hello() {
console.trace();
}
Downloading java dependencies is possible, if you actually really need to download them into a folder.
Example:
apply plugin: 'java'
dependencies {
runtime group: 'com.netflix.exhibitor', name: 'exhibitor-standalone', version: '1.5.2'
runtime group: 'org.apache.zookeeper', name: 'zookeeper', version: '3.4.6'
}
repositories { mavenCentral() }
task getDeps(type: Copy) {
from sourceSets.main.runtimeClasspath
into 'runtime/'
}
Download the dependencies (and their dependencies) into the folder runtime
when you execute gradle getDeps
.
This snippet might help in removing the xticks only.
from matplotlib import pyplot as plt
plt.xticks([])
This snippet might help in removing the xticks and yticks both.
from matplotlib import pyplot as plt
plt.xticks([]),plt.yticks([])
You can kill the process which is running the container.
With this command you can list the processes related with the docker container:
ps -aux | grep $(docker ps -a | grep container-name | awk '{print $1}')
Now you have the process ids to kill with kill or kill -9.
Two ways to read file into list in python (note these are not either or) -
with
- supported from python 2.5 and abovewith
This is the pythonic way of opening and reading files.
#Sample 1 - elucidating each step but not memory efficient
lines = []
with open("C:\name\MyDocuments\numbers") as file:
for line in file:
line = line.strip() #or some other preprocessing
lines.append(line) #storing everything in memory!
#Sample 2 - a more pythonic and idiomatic way but still not memory efficient
with open("C:\name\MyDocuments\numbers") as file:
lines = [line.strip() for line in file]
#Sample 3 - a more pythonic way with efficient memory usage. Proper usage of with and file iterators.
with open("C:\name\MyDocuments\numbers") as file:
for line in file:
line = line.strip() #preprocess line
doSomethingWithThisLine(line) #take action on line instead of storing in a list. more memory efficient at the cost of execution speed.
the .strip()
is used for each line of the file to remove \n
newline character that each line might have. When the with
ends, the file will be closed automatically for you. This is true even if an exception is raised inside of it.
This could be considered inefficient as the file descriptor might not be closed immediately. Could be a potential issue when this is called inside a function opening thousands of files.
data = [line.strip() for line in open("C:/name/MyDocuments/numbers", 'r')]
Note that file closing is implementation dependent. Normally unused variables are garbage collected by python interpreter. In cPython (the regular interpreter version from python.org), it will happen immediately, since its garbage collector works by reference counting. In another interpreter, like Jython or Iron Python, there may be a delay.
Dependencies can be updated by using "Maven --> Update Project.." in Eclipse using m2e plugin, after pom.xml file modification.
i believe the following code will only run after form1
is closed
while (true)
{
if (form1.Visible == false)
form2.Show();
}
Why not start your form2
from form1
instead?
Form2 form2 = new Form2();
private void button1_Click_1(object sender, EventArgs e)
{
if (richTextBox1.Text != null)
{
form1.Visible=false;
form2.Show();
}
else MessageBox.Show("Insert Attributes First !");
}
XJC is included in the bin directory in the JDK starting with Java SE 6. For an example see:
The contents of the blog are the following:
Processing Atom Feeds with JAXB Atom is an XML format for representing web feeds. A standard format allows reader applications to display feeds from different sources. In this example we will process the Atom feed for this blog.
Demo
In this example we will use JAXB to convert the Atom XML feed corresponding to this blog to objects and then back to XML.
import java.io.InputStream;
import java.net.URL;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
import org.w3._2005.atom.FeedType;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance("org.w3._2005.atom");
Unmarshaller unmarshaller = jc.createUnmarshaller();
URL url = new URL("http://bdoughan.blogspot.com/atom.xml");
InputStream xml = url.openStream();
JAXBElement<feedtype> feed = unmarshaller.unmarshal(new StreamSource(xml), FeedType.class);
xml.close();
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(feed, System.out);
}
}
JAXB Model
The following model was generated by the schema to Java compiler (XJC). I have omitted the get/set methods and comments to save space.
xjc -d generated http://www.kbcafe.com/rss/atom.xsd.xml
package-info
@XmlSchema(
namespace = "http://www.w3.org/2005/Atom",
elementFormDefault = XmlNsForm.QUALIFIED)
@XmlAccessorType(XmlAccessType.FIELD)
package org.w3._2005.atom;
import javax.xml.bind.annotation.*;
CategoryType
package org.w3._2005.atom;
import java.util.*;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.namespace.QName;
@XmlType(name = "categoryType")
public class CategoryType {
@XmlAttribute(required = true)
protected String term;
@XmlAttribute
@XmlSchemaType(name = "anyURI")
protected String scheme;
@XmlAttribute
protected String label;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlSchemaType(name = "anyURI")
protected String base;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "language")
protected String lang;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}
Content Type
package org.w3._2005.atom;
import java.util.*;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.namespace.QName;
@XmlType(name = "contentType", propOrder = {"content"})
public class ContentType {
@XmlMixed
@XmlAnyElement(lax = true)
protected List<Object> content;
@XmlAttribute
protected String type;
@XmlAttribute
@XmlSchemaType(name = "anyURI")
protected String src;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlSchemaType(name = "anyURI")
protected String base;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "language")
protected String lang;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}
DateTimeType
package org.w3._2005.atom;
import java.util.*;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
@XmlType(name = "dateTimeType", propOrder = {"value"})
public class DateTimeType {
@XmlValue
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar value;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlSchemaType(name = "anyURI")
protected String base;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "language")
protected String lang;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}
EntryType
package org.w3._2005.atom;
import java.util.*;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.namespace.QName;
@XmlType(name = "entryType", propOrder = {"authorOrCategoryOrContent"})
public class EntryType {
@XmlElementRefs({
@XmlElementRef(name = "id", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "rights", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "summary", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "title", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "author", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "source", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "updated", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "category", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "content", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "published", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "contributor", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "link", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class)
})
@XmlAnyElement(lax = true)
protected List<Object> authorOrCategoryOrContent;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlSchemaType(name = "anyURI")
protected String base;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "language")
protected String lang;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}
FeedType
package org.w3._2005.atom;
import java.util.*;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.namespace.QName;
@XmlType(name = "feedType", propOrder = {"authorOrCategoryOrContributor"})
public class FeedType {
@XmlElementRefs({
@XmlElementRef(name = "link", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "updated", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "category", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "rights", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "contributor", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "title", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "id", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "generator", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "icon", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "subtitle", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "author", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "entry", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "logo", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class)
})
@XmlAnyElement(lax = true)
protected List<Object> authorOrCategoryOrContributor;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlSchemaType(name = "anyURI")
protected String base;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "language")
protected String lang;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}
GeneratorType
package org.w3._2005.atom;
import java.util.*;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.namespace.QName;
@XmlType(name = "generatorType", propOrder = {"value"})
public class GeneratorType {
@XmlValue
protected String value;
@XmlAttribute
@XmlSchemaType(name = "anyURI")
protected String uri;
@XmlAttribute
protected String version;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlSchemaType(name = "anyURI")
protected String base;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "language")
protected String lang;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}
IconType
package org.w3._2005.atom;
import java.util.*;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.namespace.QName;
@XmlType(name = "iconType", propOrder = {"value"})
public class IconType {
@XmlValue
@XmlSchemaType(name = "anyURI")
protected String value;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlSchemaType(name = "anyURI")
protected String base;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "language")
protected String lang;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}
IdType
package org.w3._2005.atom;
import java.util.*;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.namespace.QName;
@XmlType(name = "idType", propOrder = {"value"})
public class IdType {
@XmlValue
@XmlSchemaType(name = "anyURI")
protected String value;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlSchemaType(name = "anyURI")
protected String base;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "language")
protected String lang;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}
LinkType
package org.w3._2005.atom;
import java.math.BigInteger;
import java.util.*;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.namespace.QName;
@XmlType(name = "linkType", propOrder = {"content"})
public class LinkType {
@XmlValue
protected String content;
@XmlAttribute(required = true)
@XmlSchemaType(name = "anyURI")
protected String href;
@XmlAttribute
protected String rel;
@XmlAttribute
protected String type;
@XmlAttribute
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "NMTOKEN")
protected String hreflang;
@XmlAttribute
protected String title;
@XmlAttribute
@XmlSchemaType(name = "positiveInteger")
protected BigInteger length;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlSchemaType(name = "anyURI")
protected String base;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "language")
protected String lang;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}
LogoType
package org.w3._2005.atom;
import java.util.*;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.namespace.QName;
@XmlType(name = "logoType", propOrder = {"value"})
public class LogoType {
@XmlValue
@XmlSchemaType(name = "anyURI")
protected String value;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlSchemaType(name = "anyURI")
protected String base;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "language")
protected String lang;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}
PersonType
package org.w3._2005.atom;
import java.util.*;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.namespace.QName;
@XmlType(name = "personType", propOrder = {"nameOrUriOrEmail"})
public class PersonType {
@XmlElementRefs({
@XmlElementRef(name = "email", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "name", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "uri", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class)
})
@XmlAnyElement(lax = true)
protected List<Object> nameOrUriOrEmail;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlSchemaType(name = "anyURI")
protected String base;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "language")
protected String lang;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}
SourceType
package org.w3._2005.atom;
import java.util.*;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.namespace.QName;
@XmlType(name = "sourceType", propOrder = {"authorOrCategoryOrContributor"})
public class SourceType {
@XmlElementRefs({
@XmlElementRef(name = "updated", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "category", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "subtitle", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "logo", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "generator", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "icon", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "title", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "id", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "author", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "contributor", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "link", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
@XmlElementRef(name = "rights", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class)
})
@XmlAnyElement(lax = true)
protected List<Object> authorOrCategoryOrContributor;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlSchemaType(name = "anyURI")
protected String base;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "language")
protected String lang;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}
TextType
package org.w3._2005.atom;
import java.util.*;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.namespace.QName;
@XmlType(name = "textType", propOrder = {"content"})
public class TextType {
@XmlMixed
@XmlAnyElement(lax = true)
protected List<Object> content;
@XmlAttribute
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String type;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlSchemaType(name = "anyURI")
protected String base;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "language")
protected String lang;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}
UriType
package org.w3._2005.atom;
import java.util.*;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.namespace.QName;
@XmlType(name = "uriType", propOrder = {"value"})
public class UriType {
@XmlValue
@XmlSchemaType(name = "anyURI")
protected String value;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlSchemaType(name = "anyURI")
protected String base;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "language")
protected String lang;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}
As answered here, if you're on Mac, it is located at
/Users/MyUserName/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/Docker.qcow2
As of version 1.3 there's a service in module ng: $interval
function countController($scope, $interval){
$scope.countDown = 10;
$interval(function(){console.log($scope.countDown--)},1000,0);
}??
Use with caution:
Note: Intervals created by this service must be explicitly destroyed when you are finished with them. In particular they are not automatically destroyed when a controller's scope or a directive's element are destroyed. You should take this into consideration and make sure to always cancel the interval at the appropriate moment. See the example below for more details on how and when to do this.
db.collection.findOne().sort({age:-1}) //get Max without need for limit(1)
Use either of the Map
implementations bundled with Java 6 and later that implement NavigableMap
(the successor to SortedMap
):
TreeMap
if running single-threaded, or if the map is to be read-only across threads after first being populated. ConcurrentSkipListMap
if manipulating the map across threads.NavigableMap
FYI, the SortedMap
interface was succeeded by the NavigableMap
interface.
You would only need to use SortedMap
if using 3rd-party implementations that have not yet declared their support of NavigableMap
. Of the maps bundled with Java, both of the implementations that implement SortedMap
also implement NavigableMap
.
s SortedMap the best answer? TreeMap?
As others mentioned, SortedMap
is an interface while TreeMap
is one of multiple implementations of that interface (and of the more recent NavigableMap
.
Having an interface allows you to write code that uses the map without breaking if you later decide to switch between implementations.
NavigableMap< Employee , Project > currentAssignments = new TreeSet<>() ;
currentAssignments.put( alice , writeAdCopyProject ) ;
currentAssignments.put( bob , setUpNewVendorsProject ) ;
This code still works if later change implementations. Perhaps you later need a map that supports concurrency for use across threads. Change that declaration to:
NavigableMap< Employee , Project > currentAssignments = new ConcurrentSkipListMap<>() ;
…and the rest of your code using that map continues to work.
There are ten implementations of Map
bundled with Java 11. And more implementations provided by 3rd parties such as Google Guava.
Here is a graphic table I made highlighting the various features of each. Notice that two of the bundled implementations keep the keys in sorted order by examining the key’s content. Also, EnumMap
keeps its keys in the order of the objects defined on that enum. Lastly, the LinkedHashMap
remembers original insertion order.
To fix both Headers and Columns, you can use the following plugin:
Updated in July 2019
Recently is emerged also a pure CSS solution that is based on CSS property position: sticky;
(here for more details about it) applied onto each TH
item (instead of their parent container)
This is jquery code which is used to fixed the div when it touch a top of browser hope it will help a lot.
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.js'></script>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(function() {
$.fn.scrollBottom = function() {
return $(document).height() - this.scrollTop() - this.height();
};
var $el = $('#sidebar>div');
var $window = $(window);
var top = $el.parent().position().top;
$window.bind("scroll resize", function() {
var gap = $window.height() - $el.height() - 10;
var visibleFoot = 172 - $window.scrollBottom();
var scrollTop = $window.scrollTop()
if (scrollTop < top + 10) {
$el.css({
top: (top - scrollTop) + "px",
bottom: "auto"
});
} else if (visibleFoot > gap) {
$el.css({
top: "auto",
bottom: visibleFoot + "px"
});
} else {
$el.css({
top: 0,
bottom: "auto"
});
}
}).scroll();
});
});//]]>
</script>
Just in case, don't forget to guard range size before applying it to the string. Otherwise, you will get crash if the user will do this:
Type maximum length text Insert something (Nothing will be inserted due to length limitation, but iOS doesn't know about it) Undo insertion (You get crash, cause range will be greater than actual string size)
Also, using iOS 13 users can accidentally trigger this by gestures
I suggest you add to your project this
extension String {
func replace(with text: String, in range: NSRange) -> String? {
guard range.location + range.length <= self.count else { return nil }
return (self as NSString).replacingCharacters(in: range, with: text)
}
}
And use it like this:
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
guard let newText = textView.text.replace(with: text, in: range) else { return false }
return newText.count < maxNumberOfCharacters
}
Otherwise, you will constantly be getting crashed in your app
Everything is very simple
To get list of all untracked files use command git status with option -u (--untracked-files)
git status -u
I found that this answer was causing some crashes on Android versions 9 and 10. I think it's a good approach but when I was looking at some Android code I found out it was missing a constructor. The answer is quite old so at the time there probably was no need for it. When I added the missing constructor and called it from the creator the crash was fixed.
So here is the edited code:
public class CustomView extends LinearLayout {
private int stateToSave;
...
@Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
// your custom state
ss.stateToSave = this.stateToSave;
return ss;
}
@Override
protected void dispatchSaveInstanceState(SparseArray<Parcelable> container)
{
dispatchFreezeSelfOnly(container);
}
@Override
public void onRestoreInstanceState(Parcelable state) {
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
// your custom state
this.stateToSave = ss.stateToSave;
}
@Override
protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container)
{
dispatchThawSelfOnly(container);
}
static class SavedState extends BaseSavedState {
int stateToSave;
SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in) {
super(in);
this.stateToSave = in.readInt();
}
// This was the missing constructor
@RequiresApi(Build.VERSION_CODES.N)
SavedState(Parcel in, ClassLoader loader)
{
super(in, loader);
this.stateToSave = in.readInt();
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(this.stateToSave);
}
public static final Creator<SavedState> CREATOR =
new ClassLoaderCreator<SavedState>() {
// This was also missing
@Override
public SavedState createFromParcel(Parcel in, ClassLoader loader)
{
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ? new SavedState(in, loader) : new SavedState(in);
}
@Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in, null);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
This is what I do when i want to send email with attachment, work fine. :)
public class NewClass {
public static void main(String[] args) {
try {
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465"); // smtp port
Authenticator auth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username-gmail", "password-gmail");
}
};
Session session = Session.getDefaultInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("[email protected]"));
msg.setSubject("Try attachment gmail");
msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
//add atleast simple body
MimeBodyPart body = new MimeBodyPart();
body.setText("Try attachment");
//do attachment
MimeBodyPart attachMent = new MimeBodyPart();
FileDataSource dataSource = new FileDataSource(new File("file-sent.txt"));
attachMent.setDataHandler(new DataHandler(dataSource));
attachMent.setFileName("file-sent.txt");
attachMent.setDisposition(MimeBodyPart.ATTACHMENT);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(body);
multipart.addBodyPart(attachMent);
msg.setContent(multipart);
Transport.send(msg);
} catch (AddressException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
} catch (MessagingException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
To directly answer this question's original title "How to delete rows from a pandas DataFrame based on a conditional expression" (which I understand is not necessarily the OP's problem but could help other users coming across this question) one way to do this is to use the drop method:
df = df.drop(some labels)
df = df.drop(df[<some boolean condition>].index)
Example
To remove all rows where column 'score' is < 50:
df = df.drop(df[df.score < 50].index)
In place version (as pointed out in comments)
df.drop(df[df.score < 50].index, inplace=True)
Multiple conditions
(see Boolean Indexing)
The operators are:
|
foror
,&
forand
, and~
fornot
. These must be grouped by using parentheses.
To remove all rows where column 'score' is < 50 and > 20
df = df.drop(df[(df.score < 50) & (df.score > 20)].index)
Tested in Nexus 5:
adb shell input keyevent 26 #Pressing the lock button
adb shell input touchscreen swipe 930 880 930 380 #Swipe UP
adb shell input text XXXX #Entering your passcode
adb shell input keyevent 66 #Pressing Enter
Worked for me.
You can use lists comprehensions:
strip_list = [item.strip() for item in lines]
Or the map
function:
# with a lambda
strip_list = map(lambda it: it.strip(), lines)
# without a lambda
strip_list = map(str.strip, lines)
MSalters solution is a good one but basically re-implements boost::assign::map_list_of
. If you have boost, you can use it directly:
#include <boost/assign/list_of.hpp>
#include <boost/unordered_map.hpp>
#include <iostream>
using boost::assign::map_list_of;
enum eee { AA,BB,CC };
const boost::unordered_map<eee,const char*> eeeToString = map_list_of
(AA, "AA")
(BB, "BB")
(CC, "CC");
int main()
{
std::cout << " enum AA = " << eeeToString.at(AA) << std::endl;
return 0;
}
Try this:
var frm = document.getElementById('search-theme-form') || null;
if(frm) {
frm.action = 'whatever_you_need.ext'
}
You can also specify context location relatively to current classpath, which may be preferable
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Just to let everyone out there know that is using Linq to Entities the methods above will not work...
If you try to do something like
var max = new[]{0}
.Concat((From y In context.MyTable _
Where y.MyField = value _
Select y.MyCounter))
.Max();
It will throw an exception:
System.NotSupportedException: The LINQ expression node type 'NewArrayInit' is not supported in LINQ to Entities..
I would suggest just doing
(From y In context.MyTable _
Where y.MyField = value _
Select y.MyCounter))
.OrderByDescending(x=>x).FirstOrDefault());
And the FirstOrDefault
will return 0 if your list is empty.
import json
def is_json(myjson):
try:
json_object = json.loads(myjson)
except ValueError as e:
return False
return True
Which prints:
print is_json("{}") #prints True
print is_json("{asdf}") #prints False
print is_json('{ "age":100}') #prints True
print is_json("{'age':100 }") #prints False
print is_json("{\"age\":100 }") #prints True
print is_json('{"age":100 }') #prints True
print is_json('{"foo":[5,6.8],"foo":"bar"}') #prints True
Convert a JSON string to a Python dictionary:
import json
mydict = json.loads('{"foo":"bar"}')
print(mydict['foo']) #prints bar
mylist = json.loads("[5,6,7]")
print(mylist)
[5, 6, 7]
Convert a python object to JSON string:
foo = {}
foo['gummy'] = 'bear'
print(json.dumps(foo)) #prints {"gummy": "bear"}
If you want access to low-level parsing, don't roll your own, use an existing library: http://www.json.org/
Great tutorial on python JSON module: https://pymotw.com/2/json/
sudo cpan JSON::XS
echo '{"foo":[5,6.8],"foo":"bar" bar}' > myjson.json
json_xs -t none < myjson.json
Prints:
, or } expected while parsing object/hash, at character offset 28 (before "bar}
at /usr/local/bin/json_xs line 183, <STDIN> line 1.
json_xs
is capable of syntax checking, parsing, prittifying, encoding, decoding and more:
Simply add to your <head>
<meta charset="UTF-8">
You should use setStroke
to set a stroke of the Graphics2D
object.
The example at http://www.java2s.com gives you some code examples.
The following code produces the image below:
import java.awt.*;
import java.awt.geom.Line2D;
import javax.swing.*;
public class FrameTest {
public static void main(String[] args) {
JFrame jf = new JFrame("Demo");
Container cp = jf.getContentPane();
cp.add(new JComponent() {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(10));
g2.draw(new Line2D.Float(30, 20, 80, 90));
}
});
jf.setSize(300, 200);
jf.setVisible(true);
}
}
(Note that the setStroke
method is not available in the Graphics
object. You have to cast it to a Graphics2D
object.)
This post has been rewritten as an article here.
If you have multiple versions of a package / module, you need to be using virtualenv (emphasis mine):
virtualenv
is a tool to create isolated Python environments.The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into
/usr/lib/python2.7/site-packages
(or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded.Or more generally, what if you want to install an application and leave it be? If an application works, any change in its libraries or the versions of those libraries can break the application.
Also, what if you can’t install packages into the global
site-packages
directory? For instance, on a shared host.In all these cases,
virtualenv
can help you. It creates an environment that has its own installation directories, that doesn’t share libraries with other virtualenv environments (and optionally doesn’t access the globally installed libraries either).
That's why people consider insert(0,
to be wrong -- it's an incomplete, stopgap solution to the problem of managing multiple environments.
My open source application BugTracker.NET includes a POP3 client that can parse MIME. Both the POP3 code and the MIME code are from other authors, but you can see how it all fits together in my app.
For the MIME parsing, I use http://anmar.eu.org/projects/sharpmimetools/.
See the file POP3Main.cs, POP3Client.cs, and insert_bug.aspx
With Java 8:
hm.forEach((k, v) -> {
System.out.println("Key = " + k + " - " + v);
});
I use this for most situations, keep the seed if there is a need to repeat the sequence
var seed = (int) DateTime.Now.Ticks;
var random = new Random(seed);
or
var random = new Random((int)DateTime.Now.Ticks);
Try this in your CSS:
input {
text-align: right;
}
To align the text in the center:
input {
text-align: center;
}
But, it should be left-aligned, as that is the default - and appears to be the most user friendly.
Because tuple(3, 4)
is not the correct syntax to create a tuple. The correct syntax is -
tuple([3, 4])
or
(3, 4)
You can see it from here - https://docs.python.org/2/library/functions.html#tuple
As an alternative option you could install OpenSSH http://www.mls-software.com/opensshd.html and then simply ssh user@host -pw password -m command_run
Edit: After a response from user2687375 when installing, select client only. Once this is done you should be able to initiate SSH from command.
Then you can create an ssh batch script such as
ECHO OFF
CLS
:MENU
ECHO.
ECHO ........................
ECHO SSH servers
ECHO ........................
ECHO.
ECHO 1 - Web Server 1
ECHO 2 - Web Server 2
ECHO E - EXIT
ECHO.
SET /P M=Type 1 - 2 then press ENTER:
IF %M%==1 GOTO WEB1
IF %M%==2 GOTO WEB2
IF %M%==E GOTO EOF
REM ------------------------------
REM SSH Server details
REM ------------------------------
:WEB1
CLS
call ssh [email protected]
cmd /k
:WEB2
CLS
call ssh [email protected]
cmd /k
<?php if( $_product->getTypeId() == 'simple' ): ?>
//your code for simple products only
<?php endif; ?>
<?php if( $_product->getTypeId() == 'grouped' ): ?>
//your code for grouped products only
<?php endif; ?>
So on. It works! Magento 1.6.1, place in the view.phtml
To someone who really understands how JS works this question might seem off, however most people who use JS do not have such a deep level of insight (and don't necessarily need it) and to them this is a fairly confusing point, I will try to answer from that perspective.
JS is synchronous in the way its code is executed. each line only runs after the line before it has completed and if that line calls a function after that is complete etc...
The main point of confusion arises from the fact that your browser is able to tell JS to execute more code at anytime (similar to how you can execute more JS code on a page from the console). As an example JS has Callback functions who's purpose is to allow JS to BEHAVE asynchronously so further parts of JS can run while waiting for a JS function that has been executed (I.E. a GET
call) to return back an answer, JS will continue to run until the browser has an answer at that point the event loop (browser) will execute the JS code that calls the callback function.
Since the event loop (browser) can input more JS to be executed at any point in that sense JS is asynchronous (the primary things that will cause a browser to input JS code are timeouts, callbacks and events)
I hope this is clear enough to be helpful to somebody.
NOW() is the replacement of Oracle Sysdate in Postgres.
Try "Select now()", it will give you the system timestamp.
Documentation is quite clear: https://docs.python.org/2/library/json.html
json.load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
Deserialize fp (a .read()-supporting file-like object containing a JSON document) to a Python object using this conversion table.
json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
Deserialize s (a str or unicode instance containing a JSON document) to a Python object using this conversion table.
So load
is for a file, loads
for a string
Well maybe you forgot to add "$route" when declaring the dependencies of your Controller:
app.controller('NameCtrl', ['$scope','$route', function($scope,$route) {
// $route.reload(); Then this should work fine.
}]);
There's yet another way to do it using Shared Connections, ie: somebody initiates the connection, using a password, and every subsequent connection will multiplex over the same channel, negating the need for re-authentication. ( And its faster too )
# ~/.ssh/config
ControlMaster auto
ControlPath ~/.ssh/pool/%r@%h
then you just have to log in, and as long as you are logged in, the bash script will be able to open ssh connections.
You can then stop your script from working when somebody has not already opened the channel by:
ssh ... -o KbdInteractiveAuthentication=no ....
Check your project build is in Debug mode not Release, I had some problem for debugging always I forget to change Release mode to Debug (Xamarin Users)
Go to File->Invalidate Caches/ Restart. After restarting the preview window will come.
Still the preview window is not opened, Go to View -> Tool window -> click Preview
Use private API -[UIDevice _deviceInfoForKey:]
carefully, you won't be rejected by Apple,
// works on both simulators and real devices, iOS 8 to iOS 12
NSString *deviceModelName(void) {
// For Simulator
NSString *modelName = NSProcessInfo.processInfo.environment[@"SIMULATOR_DEVICE_NAME"];
if (modelName.length > 0) {
return modelName;
}
// For real devices and simulators, except simulators running on iOS 8.x
UIDevice *device = [UIDevice currentDevice];
NSString *selName = [NSString stringWithFormat:@"_%@ForKey:", @"deviceInfo"];
SEL selector = NSSelectorFromString(selName);
if ([device respondsToSelector:selector]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
modelName = [device performSelector:selector withObject:@"marketing-name"];
#pragma clang diagnostic pop
}
return modelName;
}
Running on a simulator, NSProcessInfo.processInfo.environment
contains a key named "SIMULATOR_CAPABILITIES", the value of which is a plist file. Then you open the plist file, you will get the model name's key "marketing-name".
To retrieve path of msbuild 15 (Visual Studio 2017) with batch from registry w/o additional tools:
set regKey=HKLM\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7
set regValue=15.0
for /f "skip=2 tokens=3,*" %%A in ('reg.exe query %regKey% /v %regValue% 2^>nul') do (
set vs17path=%%A %%B
)
set msbuild15path = %vs17path%\MSBuild\15.0\Bin\MSBuild.exe
Better available tools:
import * as saveAsFunctions from 'file-saver';
..........
.......
let saveAs;
beforeEach(() => {
saveAs = jasmine.createSpy('saveAs');
})
it('should generate the excel on sample request details page', () => {
spyOn(saveAsFunctions, 'saveAs').and.callFake(saveAs);
expect(saveAsFunctions.saveAs).toHaveBeenCalled();
})
This worked for me.
The problem is
listModel.addElement(listaRosa.getSelectedValue());
listModel.removeElement(listaRosa.getSelectedValue());
you may be adding an element and immediatly removing it since both add and remove operations are on the same listModel.
Try
private void aggiungiTitolareButtonActionPerformed(java.awt.event.ActionEvent evt) {
DefaultListModel lm2 = (DefaultListModel) listaTitolari.getModel();
DefaultListModel lm1 = (DefaultListModel) listaRosa.getModel();
if(lm2 == null)
{
lm2 = new DefaultListModel();
listaTitolari.setModel(lm2);
}
lm2.addElement(listaTitolari.getSelectedValue());
lm1.removeElement(listaTitolari.getSelectedValue());
}
Assuming a Windows installation, do please refer to this:
http://www.oracle-base.com/articles/misc/ManualOracleUninstall.php
- Uninstall all Oracle components using the Oracle Universal Installer (OUI).
- Run regedit.exe and delete the HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE key. This contains registry entires for all Oracle products.
- Delete any references to Oracle services left behind in the following part of the registry:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Ora*
It should be pretty obvious which ones relate to Oracle.- Reboot your machine.
- Delete the "C:\Oracle" directory, or whatever directory is your ORACLE_BASE.
- Delete the "C:\Program Files\Oracle" directory.
- Empty the contents of your "C:\temp" directory.
- Empty your recycle bin.
Calling additional attention to some great comments that were left here:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ORACLE
key from the registry.%ORACLE_HOME%
.%PATH%
.This set of instructions happens to match an almost identical process that I had reverse-engineered myself over the years after a few messed-up Oracle installs, and has almost always met the need.
Note that even if the OUI is no longer available or doesn't work, simply following the remaining steps should still be sufficient.
(Revision #7 reverted as to not misquote the original source, and to not remove credit to the other comments that contributed to the answer. Further edits are appreciated (and then please remove this comment), if a way can be found to maintain these considerations.)
None of the solutions worked for me. I noticed that the problem was only occuring in one xaml file, and not in other xaml or c# files.
I had an extension called QuickConverter that allows to create custom bindings with in-line converters. This was messing up with Intellisense and this was not detected as an error while building or running the app.
My advice is:
Seems everyone's got an answer to this one. I like the solution from @Web_Designer. But it doesn't need to be as complex as that and you can still get the blurry inner shadow you're looking for.
http://dabblet.com/gist/3877605
.depth {
display: block;
padding: 50px;
color: black;
font: bold 7em Arial, sans-serif;
position: relative;
}
.depth:before {
content: attr(title);
color: transparent;
position: absolute;
text-shadow: 2px 2px 4px rgba(255,255,255,0.3);
}
function routeToRoom(userId, passw, cb) {
var roomId = 0;
var nStore = require('nstore/lib/nstore').extend(require('nstore/lib/nstore/query')());
var users = nStore.new('data/users.db', function() {
users.find({
user: userId,
pass: passw
}, function(err, results) {
if (err) {
roomId = -1;
} else {
roomId = results.creationix.room;
}
cb(roomId);
});
});
}
routeToRoom("alex", "123", function(id) {
console.log(id);
});
You need to use callbacks. That's how asynchronous IO works. Btw sys.puts
is deprecated
Other solutions didn't work in one of my projects and I've ending up checking overflow css property
function haveScrollbar() {
var style = window.getComputedStyle(document.body);
return style["overflow-y"] != "hidden";
}
but it will only work if scrollbar appear disappear by changing the prop it will not work if the content is equal or smaller than the window.
Please set your form action attribute as below it will solve your problem.
<form name="addProductForm" id="addProductForm" action="javascript:;" enctype="multipart/form-data" method="post" accept-charset="utf-8">
jQuery code:
$(document).ready(function () {
$("#addProductForm").submit(function (event) {
//disable the default form submission
event.preventDefault();
//grab all form data
var formData = $(this).serialize();
$.ajax({
url: 'addProduct.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function () {
alert('Form Submitted!');
},
error: function(){
alert("error in ajax form submission");
}
});
return false;
});
});
tl;dr
"Foo" and "bar" as metasyntactic variables were popularised by MIT and DEC, the first references are in work on LISP and PDP-1 and Project MAC from 1964 onwards.
Many of these people were in MIT's Tech Model Railroad Club, where we find the first documented use of "foo" in tech circles in 1959 (and a variant in 1958).
Both "foo" and "bar" (and even "baz") were well known in popular culture, especially from Smokey Stover and Pogo comics, which will have been read by many TMRC members.
Also, it seems likely the military FUBAR contributed to their popularity.
The use of lone "foo" as a nonsense word is pretty well documented in popular culture in the early 20th century, as is the military FUBAR. (Some background reading: FOLDOC FOLDOC Jargon File Jargon File Wikipedia RFC3092)
OK, so let's find some references.
STOP PRESS! After posting this answer, I discovered this perfect article about "foo" in the Friday 14th January 1938 edition of The Tech ("MIT's oldest and largest newspaper & the first newspaper published on the web"), Volume LVII. No. 57, Price Three Cents:
On Foo-ism
The Lounger thinks that this business of Foo-ism has been carried too far by its misguided proponents, and does hereby and forthwith take his stand against its abuse. It may be that there's no foo like an old foo, and we're it, but anyway, a foo and his money are some party. (Voice from the bleachers- "Don't be foo-lish!")
As an expletive, of course, "foo!" has a definite and probably irreplaceable position in our language, although we fear that the excessive use to which it is currently subjected may well result in its falling into an early (and, alas, a dark) oblivion. We say alas because proper use of the word may result in such happy incidents as the following.
It was an 8.50 Thermodynamics lecture by Professor Slater in Room 6-120. The professor, having covered the front side of the blackboard, set the handle that operates the lift mechanism, turning meanwhile to the class to continue his discussion. The front board slowly, majestically, lifted itself, revealing the board behind it, and on that board, writ large, the symbols that spelled "FOO"!
The Tech newspaper, a year earlier, the Letter to the Editor, September 1937:
By the time the train has reached the station the neophytes are so filled with the stories of the glory of Phi Omicron Omicron, usually referred to as Foo, that they are easy prey.
...
It is not that I mind having lost my first four sons to the Grand and Universal Brotherhood of Phi Omicron Omicron, but I do wish that my fifth son, my baby, should at least be warned in advance.
Hopefully yours,
Indignant Mother of Five.
And The Tech in December 1938:
General trend of thought might be best interpreted from the remarks made at the end of the ballots. One vote said, '"I don't think what I do is any of Pulver's business," while another merely added a curt "Foo."
The first documented "foo" in tech circles is probably 1959's Dictionary of the TMRC Language:
FOO: the sacred syllable (FOO MANI PADME HUM); to be spoken only when under inspiration to commune with the Deity. Our first obligation is to keep the Foo Counters turning.
These are explained at FOLDOC. The dictionary's compiler Pete Samson said in 2005:
Use of this word at TMRC antedates my coming there. A foo counter could simply have randomly flashing lights, or could be a real counter with an obscure input.
And from 1996's Jargon File 4.0.0:
Earlier versions of this lexicon derived 'baz' as a Stanford corruption of bar. However, Pete Samson (compiler of the TMRC lexicon) reports it was already current when he joined TMRC in 1958. He says "It came from "Pogo". Albert the Alligator, when vexed or outraged, would shout 'Bazz Fazz!' or 'Rowrbazzle!' The club layout was said to model the (mythical) New England counties of Rowrfolk and Bassex (Rowrbazzle mingled with (Norfolk/Suffolk/Middlesex/Essex)."
A year before the TMRC dictionary, 1958's MIT Voo Doo Gazette ("Humor suplement of the MIT Deans' office") (PDF) mentions Foocom, in "The Laws of Murphy and Finagle" by John Banzhaf (an electrical engineering student):
Further research under a joint Foocom and Anarcom grant expanded the law to be all embracing and universally applicable: If anything can go wrong, it will!
Also 1964's MIT Voo Doo (PDF) references the TMRC usage:
Yes! I want to be an instant success and snow customers. Send me a degree in: ...
Foo Counters
Foo Jung
Let's find "foo", "bar" and "foobar" published in code examples.
So, Jargon File 4.4.7 says of "foobar":
Probably originally propagated through DECsystem manuals by Digital Equipment Corporation (DEC) in 1960s and early 1970s; confirmed sightings there go back to 1972.
The first published reference I can find is from February 1964, but written in June 1963, The Programming Language LISP: its Operation and Applications by Information International, Inc., with many authors, but including Timothy P. Hart and Michael Levin:
Thus, since "FOO" is a name for itself, "COMITRIN" will treat both "FOO" and "(FOO)" in exactly the same way.
Also includes other metasyntactic variables such as: FOO CROCK GLITCH / POOT TOOR / ON YOU / SNAP CRACKLE POP / X Y Z
I expect this is much the same as this next reference of "foo" from MIT's Project MAC in January 1964's AIM-064, or LISP Exercises by Timothy P. Hart and Michael Levin:
car[((FOO . CROCK) . GLITCH)]
It shares many other metasyntactic variables like: CHI / BOSTON NEW YORK / SPINACH BUTTER STEAK / FOO CROCK GLITCH / POOT TOOP / TOOT TOOT / ISTHISATRIVIALEXCERCISE / PLOOP FLOT TOP / SNAP CRACKLE POP / ONE TWO THREE / PLANE SUB THRESHER
For both "foo" and "bar" together, the earliest reference I could find is from MIT's Project MAC in June 1966's AIM-098, or PDP-6 LISP by none other than Peter Samson:
EXPLODE, like PRIN1, inserts slashes, so (EXPLODE (QUOTE FOO/ BAR)) PRIN1's as (F O O // / B A R) or PRINC's as (F O O / B A R).
Some more recallations.
@Walter Mitty recalled on this site in 2008:
I second the jargon file regarding Foo Bar. I can trace it back at least to 1963, and PDP-1 serial number 2, which was on the second floor of Building 26 at MIT. Foo and Foo Bar were used there, and after 1964 at the PDP-6 room at project MAC.
John V. Everett recalls in 1996:
When I joined DEC in 1966, foobar was already being commonly used as a throw-away file name. I believe fubar became foobar because the PDP-6 supported six character names, although I always assumed the term migrated to DEC from MIT. There were many MIT types at DEC in those days, some of whom had worked with the 7090/7094 CTSS. Since the 709x was also a 36 bit machine, foobar may have been used as a common file name there.
Foo and bar were also commonly used as file extensions. Since the text editors of the day operated on an input file and produced an output file, it was common to edit from a .foo file to a .bar file, and back again.
It was also common to use foo to fill a buffer when editing with TECO. The text string to exactly fill one disk block was IFOO$HXA127GA$$. Almost all of the PDP-6/10 programmers I worked with used this same command string.
Daniel P. B. Smith in 1998:
Dick Gruen had a device in his dorm room, the usual assemblage of B-battery, resistors, capacitors, and NE-2 neon tubes, which he called a "foo counter." This would have been circa 1964 or so.
Robert Schuldenfrei in 1996:
The use of FOO and BAR as example variable names goes back at least to 1964 and the IBM 7070. This too may be older, but that is where I first saw it. This was in Assembler. What would be the FORTRAN integer equivalent? IFOO and IBAR?
Paul M. Wexelblat in 1992:
The earliest PDP-1 Assembler used two characters for symbols (18 bit machine) programmers always left a few words as patch space to fix problems. (Jump to patch space, do new code, jump back) That space conventionally was named FU: which stood for Fxxx Up, the place where you fixed Fxxx Ups. When spoken, it was known as FU space. Later Assemblers ( e.g. MIDAS allowed three char tags so FU became FOO, and as ALL PDP-1 programmers will tell you that was FOO space.
Bruce B. Reynolds in 1996:
On the IBM side of FOO(FU)BAR is the use of the BAR side as Base Address Register; in the middle 1970's CICS programmers had to worry out the various xxxBARs...I think one of those was FRACTBAR...
Here's a straight IBM "BAR" from 1955.
Other early references:
1973 foo bar International Joint Council on Artificial Intelligence
1975 foo bar International Joint Council on Artificial Intelligence
I haven't been able to find any references to foo bar as "inverted foo signal" as suggested in RFC3092 and elsewhere.
Here are a some of even earlier F00s but I think they're coincidences/false positives:
The fact that the first digit has to be in the range 5-9
only applies in case of two digits. So, check for that in the case of 2 digits, and allow any more digits directly:
^([5-9]\d|\d{3,})$
This regexp has beginning/ending anchors to make sure you're checking all digits, and the string actually represents a number. The |
means "or", so either [5-9]\d
or any number with 3 or more digits. \d
is simply a shortcut for [0-9]
.
Edit: To disallow numbers like 001
:
^([5-9]\d|[1-9]\d{2,})$
This forces the first digit to be not a zero in the case of 3 or more digits.
use this class inside nav tag
class="navbar navbar-expand-lg navbar-light bg-light sticky-top"
For bootstrap 4
Don't call methods within the Fragment that require getActivity() until onStart in the parent Activity.
private MyFragment myFragment;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
myFragment = new MyFragment();
ft.add(android.R.id.content, youtubeListFragment).commit();
//Other init calls
//...
}
@Override
public void onStart()
{
super.onStart();
//Call your Fragment functions that uses getActivity()
myFragment.onPageSelected();
}
For a bandpass filter, ws is a tuple containing the lower and upper corner frequencies. These represent the digital frequency where the filter response is 3 dB less than the passband.
wp is a tuple containing the stop band digital frequencies. They represent the location where the maximum attenuation begins.
gpass is the maximum attenutation in the passband in dB while gstop is the attentuation in the stopbands.
Say, for example, you wanted to design a filter for a sampling rate of 8000 samples/sec having corner frequencies of 300 and 3100 Hz. The Nyquist frequency is the sample rate divided by two, or in this example, 4000 Hz. The equivalent digital frequency is 1.0. The two corner frequencies are then 300/4000 and 3100/4000.
Now lets say you wanted the stopbands to be down 30 dB +/- 100 Hz from the corner frequencies. Thus, your stopbands would start at 200 and 3200 Hz resulting in the digital frequencies of 200/4000 and 3200/4000.
To create your filter, you'd call buttord as
fs = 8000.0
fso2 = fs/2
N,wn = scipy.signal.buttord(ws=[300/fso2,3100/fso2], wp=[200/fs02,3200/fs02],
gpass=0.0, gstop=30.0)
The length of the resulting filter will be dependent upon the depth of the stop bands and the steepness of the response curve which is determined by the difference between the corner frequency and stopband frequency.
use moment.js to solve this issue in 2 lines, html5 date input type only accept "YYYY-MM-DD" this format. I solve my problem this way.
var today = moment().format('YYYY-MM-DD');
$('#datePicker').val(today);
this is simplest way to solve this issue.
So, the concept of a "wildcard" in Regular Expressions works a bit differently. In order to match "any character" you would use "." The "*" modifier means, match any number of times.
I know StackOverflow is not the place for opinion based answers, but I actually have a good opinion on when to shelve changes with a stash.
When you make changes in your workspace/working tree, if you need to perform any branch based operations like a merge, push, fetch or pull, you must be at a clean commit point. So if you have workspace changes you need to commit them. But what if you don't want to commit them? What if they are experimental? Something you don't want part of your commit history? Something you don't want others to see when you push to GitHub?
In that case, you can do a hard reset. But if you do a hard reset you will lose all of your local working tree changes because everything gets overwritten to where it was at the time of the last commit and you'll lose all of your changes.
So, as for the answer of 'when should you stash', the answer is when you need to get back to a clean commit point with a synchronized working tree/index/commit, but you don't want to lose your local changes in the process. Just shelve your changes in a stash and you're good.
And once you've done your stash and then merged or pulled or pushed, you can just stash pop or apply and you're back to where you started from.
GitHub is constantly adding new features, but as of right now, there is now way to save a stash there. Again, the idea of a stash is that it's local and private. Nobody else can peek into your stash without physical access to your workstation. Kinda the same way git reflog is private with the git log is public. It probably wouldn't be private if it was pushed up to GitHub.
One trick might be to do a diff of your workspace, check the diff into your git repository, commit and then push. Then you can do a pull from home, get the diff and then unwind it. But that's a pretty messy way to achieve those results.
git diff > git-dif-file.diff
getStringCellValue returns NumberFormatException if the cell type is numeric. If you don't want to change the cell type to string, you can do this.
String rsdata = "";
try {
rsdata = cell.getStringValue();
} catch (NumberFormatException ex) {
rsdata = cell.getNumericValue() + "";
}
More based on the feeling, but this is the error you would get if you missed to declare a bean in the context configuration, so try adding
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10000000"/>
</bean>
A great blog describing 14 address finders: https://www.conversion-uplift.co.uk/free-address-lookup-tools/
Many address autocomplete services, including Google's Places API, appears to offer international address support but it has limited accuracy.
For example, New Zealand address and geolocation data are free to download from Land Information New Zealand (LINZ). When a user search for an address such as 76 Francis St Hauraki from Google or Address Doctor, a positive match is returned. The land parcel was matched but not the postal/delivery address, which is either 76A or 76B. The problem is amplified with apartments and units on a single land parcel.
For 100% accuracy, use a country-specific address finder instead such as https://www.addy.co.nz for NZ address autocomplete.
Perhaps this is lame but you can also just point them both at some external object:
var cities = [];
function ParentCtrl() {
var vm = this;
vm.cities = cities;
vm.cities[0] = 'Oakland';
}
function ChildCtrl($scope) {
var vm = this;
vm.cities = cities;
}
The benefit here is that edits in ChildCtrl now propogate back to the data in the parent.
I also ran into this error. Restart the PC works for me.
Add the @Configuration
annotation in the RestTemplateSOMENAME which extends the RestTemplate class.
@Configuration
public class RestTemplateClass extends RestTemplate {
}
Then in your controller class you can use the Autowired annotation as follows.
@Autowired
RestTemplateClass restTemplate;
I have also read that for some servers one for example needs only annotate persistence contexts, but in some servers, the injection should be done manually.
One suggestion I'll make since no one yet has said it: PLEASE PLEASE PLEASE make a backup of your whole .xcodeproj file BEFORE you start modifying it's contents. Screwing up the project file and having no backup will lead to a very very unpleasant experience.
Being able to back out of an edit can be a godsend.
There is the "Compare" plugin. You can install it via Plugins > Plugin Manager.
Alternatively you can install a specialized file compare software like WinMerge.