I am not getting your question properly but as per your heading, you can convert any type of object to string by using toString()
function on a String
Object.
A practical example using a jQuery example might be
var today = new Date();
$('#'+[today.getMonth()+1, today.getDate(), today.getFullYear()].join("_")).whatever();
I do that in a calendar tool that I am using, this way on the page load, I can do certain things with today's date.
Open a visual command console (Visual Studio Command Prompt)
dumpbin /ARCHIVEMEMBERS openssl.x86.lib
or
lib /LIST openssl.x86.lib
or just open it with 7-zip :) its an AR archive
In javascript,
You can use the list of all options of multiselect dropdown which will be an Array.Then loop through it to make Selected attributes as false in each Objects.
for(var i=0;i<list.length;i++)
{
if(list[i].Selected==true)
{
list[i].Selected=false;
}
}
Your action method considers model type asList<string>
. But, in your view you are waiting for IEnumerable<Standings.Models.Teams>
.
You can solve this problem with changing the model in your view to List<string>
.
But, the best approach would be to return IEnumerable<Standings.Models.Teams>
as a model from your action method. Then you haven't to change model type in your view.
But, in my opinion your models are not correctly implemented. I suggest you to change it as:
public class Team
{
public int Position { get; set; }
public string HomeGround {get; set;}
public string NickName {get; set;}
public int Founded { get; set; }
public string Name { get; set; }
}
Then you must change your action method as:
public ActionResult Index()
{
var model = new List<Team>();
model.Add(new Team { Name = "MU"});
model.Add(new Team { Name = "Chelsea"});
...
return View(model);
}
And, your view:
@model IEnumerable<Standings.Models.Team>
@{
ViewBag.Title = "Standings";
}
@foreach (var item in Model)
{
<div>
@item.Name
<hr />
</div>
}
You may use EmptyDataText
as shown below:
<asp:GridView ID="_gridView" RunAt="server" AutoGenerateColumns="false"
EmptyDataText="No entries found.">
It does not show headers, it renders your message "No entries found." instead.
In Rails 4.1.0, I have faced problem with saving latitude and longitude to MySql database. It can't save large fraction number with float data type. And I change the data type to decimal and working for me.
def change change_column :cities, :latitude, :decimal, :precision => 15, :scale => 13 change_column :cities, :longitude, :decimal, :precision => 15, :scale => 13 end
You can get the "computed" styles of any element.
IE uses something called "currentStyle", Firefox (and I assume other "standard compliant" browsers) uses "defaultView.getComputedStyle".
You'll need to write a cross browser function to do this, or use a good Javascript framework like prototype or jQuery (search for "getStyle" in the prototype javascript file, and "curCss" in the jquery javascript file).
That said if you need the height or width you should probably use element.offsetHeight and element.offsetWidth.
The value returned is Null, so if I have Javascript that needs to know the width of something to do some logic (I increase the width by 1%, not to a specific value)
Mind, if you add an inline style to the element in question, it can act as the "default" value and will be readable by Javascript on page load, since it is the element's inline style property:
<div style="width:50%">....</div>
The solution of @Chrispix is dangerous! Trusting all certificates allows anybody to do a man in the middle attack! Just send ANY certificate to the client and it will accept it!
Add your certificate(s) to a custom trust manager like described in this post: Trusting all certificates using HttpClient over HTTPS
Although it is a bit more complex to establish a secure connection with a custom certificate, it will bring you the wanted ssl encryption security without the danger of man in the middle attack!
To know the names of different desktop browsers (Firefox, IE, Opera, Edge, Chrome). Except Safari.
function getBrowserName() {
var browserName = '';
var userAgent = navigator.userAgent;
(typeof InstallTrigger !== 'undefined') && (browserName = 'Firefox');
( /* @cc_on!@*/ false || !!document.documentMode) && (browserName = 'IE');
(!!window.chrome && userAgent.match(/OPR/)) && (browserName = 'Opera');
(!!window.chrome && userAgent.match(/Edge/)) && (browserName = 'Edge');
(!!window.chrome && !userAgent.match(/(OPR|Edge)/)) && (browserName = 'Chrome');
/**
* Expected returns
* Firefox, Opera, Edge, Chrome
*/
return browserName;
}
Works in the following browser versions:
Opera - 58.0.3135.79
Firefox - 65.0.2 (64-bit)
IE - 11.413.15063 (JS Fiddle no longer supports IE just paste in Console)
Edge - 44.17763.1.0
Chrome - 72.0.3626.121 (Official Build) (64-bit)
View the gist here and the fiddle here
The original code snippet no longer worked for Chrome and I forgot where I found it. It had safari before but I no longer have access to safari so I cannot verify anymore.
Only the Firefox and IE codes were part of the original snippet.
The checking for Opera, Edge, and Chrome is straight forward. They have differences in the userAgent. OPR
only exists in Opera. Edge
only exists in Edge. So to check for Chrome these string shouldn't be there.
As for the Firefox and IE, I cannot explain what they do.
I'll be adding this functionality to a package i'm writing
Instead of having to account for window.location.protocol and window.location.origin, and possibly missing a specified port number, etc., just grab everything up to the 3rd "/":
// get nth occurrence of a character c in the calling string
String.prototype.nthIndex = function (n, c) {
var index = -1;
while (n-- > 0) {
index++;
if (this.substring(index) == "") return -1; // don't run off the end
index += this.substring(index).indexOf(c);
}
return index;
}
// get the base URL of the current page by taking everything up to the third "/" in the URL
function getBaseURL() {
return document.URL.substring(0, document.URL.nthIndex(3,"/") + 1);
}
In SQL Developer you can right-click on the package body then select RUN. The 'Run PL/SQL' window will let you edit the PL/SQL Block. Clicking OK will give you a window pane titled 'Output Variables - Log' with an output variables tab. You can select your output variables on the left and the result is shown on the right side. Very handy and fast.
I've used Rapid with T-SQL and I think there was something similiar to this.
Writing your own delcare-begin-end script where you loop through the cursor, as with DCookie's example, is always a good exercise to do every now and then. It will work with anything and you will know that your code works.
In C++17 :
#include <experimental/filesystem>
bool is_file_exist(std::string& str) {
namespace fs = std::experimental::filesystem;
fs::path p(str);
return fs::exists(p);
}
First, I would like to clarify something. Is this a post back (trip back to server) never occur, or is it the post back occurs, but it never gets into the ddlCountry_SelectedIndexChanged event handler?
I am not sure which case you are having, but if it is the second case, I can offer some suggestion. If it is the first case, then the following is FYI.
For the second case (event handler never fires even though request made), you may want to try the following suggestions:
Beware that when calling Control.DataBind(), view state and post back information would no longer be available from the control. In the case of view state is on, between post back, values of the DropDownList would be kept intact (the list does not to be rebound). If you issue another DataBind in OnLoad, it would clear out its view state data, and the SelectedIndexChanged event would never be fired.
In the case of view state is turned off, you have no choice but to rebind the list every time. When a post back occurs, there are internal ASP.NET calls to populate the value from Request.Params to the appropriate controls, and I suspect happen at the time between OnInit and OnLoad. In this case, restoring the list values in OnInit will enable the system to fire events correctly.
Thanks for your time reading this, and welcome everyone to correct if I am wrong.
You have two options, a PL/SQL block or SQL*Plus bind variables:
var z number
execute my_stored_proc (-1,2,0.01,:z)
print z
If all you want to do is store some static values in a lookup table, you can use an Object Literal (the same format used by JSON) to do it compactly:
var table = { one: [1,10,5], two: [2], three: [3, 30, 300] }
And then access them using JavaScript's associative array syntax:
alert(table['one']); // Will alert with [1,10,5]
alert(table['one'][1]); // Will alert with 10
v4l support has been dropped in recent kernel versions (including the one shipped with Ubuntu 11.04).
EDIT: Your question is connected to a recent message that was sent to the OpenCV users group, which has instructions to compile OpenCV 2.2 in Ubuntu 11.04. Your approach is not ideal.
In C, if time efficiency is crucial and integer overflows will wrap, one could do if ((unsigned)(value-min) <= (max-min)) ...
. If 'max' and 'min' are independent variables, the extra subtraction for (max-min) will waste time, but if that expression can be precomputed at compile time, or if it can be computed once at run-time to test many numbers against the same range, the above expression may be computed efficiently even in the case where the value is within range (if a large fraction of values will be below the valid range, it may be faster to use if ((value >= min) && (value <= max)) ...
because it will exit early if value is less than min).
Before using an implementation like that, though, benchmark one one's target machine. On some processors, the two-part expression may be faster in all cases since the two comparisons may be done independently whereas in the subtract-and-compare method the subtraction has to complete before the compare can execute.
In xcode 6, provisioning profiles are stored under Xcode > Preferences > accounts. Press "View details". On selecting your profile, you will get option to revoke it under settings(gear) icon below.
A new line is just whitespace to the browser and won't be treated any different to a normal space (" "). To get a new line, you must insert <BR />
elements.
Another attempt to solve the problem: Type the text into the textarea and then add some JavaScript behind a button to convert the invisible characters to something readable and dump the result to a DIV
. That will tell you what your browser wants.
this worked for me , pyrotex answer didn' reset select fields, took his, here' my edit:
// Use a whitelist of fields to minimize unintended side effects.
$(':text, :password, :file', '#myFormId').val('');
// De-select any checkboxes, radios and drop-down menus
$(':input,select option', '#myFormId').removeAttr('checked').removeAttr('selected');
//this is for selecting the first entry of the select
$('select option:first', '#myFormId').attr('selected',true);
If you want to pass in an array of Doctrine entities, try something like this (Symfony 3.0+):
protected $entities;
protected $selectedEntities;
public function __construct($entities = null, $selectedEntities = null)
{
$this->entities = $entities;
$this->selectedEntities = $selectedEntities;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('entities', 'entity', [
'class' => 'MyBundle:MyEntity',
'choices' => $this->entities,
'property' => 'id',
'multiple' => true,
'expanded' => true,
'data' => $this->selectedEntities,
]);
}
SELECT
o.name
FROM
sys.sql_modules sm
INNER JOIN sys.objects o ON
o.object_id = sm.object_id
WHERE
sm.definition LIKE '%<table name>%'
Just keep in mind that this will also turn up SPs where the table name is in the comments or where the table name is a substring of another table name that is being used. For example, if you have tables named "test" and "test_2" and you try to search for SPs with "test" then you'll get results for both.
this function help you to get parameter from URL in JS
function getQuery(q) {
return (window.location.search.match(new RegExp('[?&]' + q + '=([^&]+)')) || [, null])[1];
}
you need to convert to char first because converting to int adds those days to 1900-01-01
select CONVERT (datetime,convert(char(8),rnwl_efctv_dt ))
here are some examples
select CONVERT (datetime,5)
1900-01-06 00:00:00.000
select CONVERT (datetime,20100101)
blows up, because you can't add 20100101 days to 1900-01-01..you go above the limit
convert to char first
declare @i int
select @i = 20100101
select CONVERT (datetime,convert(char(8),@i))
Shortest answer, given your timezone being TZ
:
LocalDateTime start = LocalDate.now(TZ).atStartOfDay()
LocalDateTime end = start.plusDays(1)
Compare using isAfter()
and isBefore()
methods, or convert it using toEpochSecond()
or toInstant()
methods.
You can use the .position() for this
var link = $(element);
var position = link.position(); //cache the position
var right = $(window).width() - position.left - link.width();
var bottom = $(window).height() - position.top - link.height();
You want a config.site file. Try:
$ mkdir -p ~/local/share $ cat << EOF > ~/local/share/config.site CPPFLAGS=-I$HOME/local/include LDFLAGS=-L$HOME/local/lib ... EOF
Whenever you invoke an autoconf generated configure script with --prefix=$HOME/local, the config.site will be read and all the assignments will be made for you. CPPFLAGS and LDFLAGS should be all you need, but you can make any other desired assignments as well (hence the ... in the sample above). Note that -I flags belong in CPPFLAGS and not in CFLAGS, as -I is intended for the pre-processor and not the compiler.
just for the record. I followed all clean/rebuild and update SDK-Tools here, but in the end it turned out disable Instant Run, to solve my issue.
Go to: Android Studio -> Preferences -> Build,ExecutionDeployment -> Instant Run
With Java 8 you may try this :
public Map<String, Object> toKeyValuePairs(Object instance) {
return Arrays.stream(Bean.class.getDeclaredMethods())
.collect(Collectors.toMap(
Method::getName,
m -> {
try {
Object result = m.invoke(instance);
return result != null ? result : "";
} catch (Exception e) {
return "";
}
}));
}
Let's first look at the definitions of these words before evaluating what the difference is in HTML:
English definition:
In HTML context:
When the browser parses the HTML, it creates a tree data structure wich basically is an in memory representation of the HTML. It the tree data structure contains nodes which are HTML elements and text. Attributes and properties relate to this is the following manner:
It is also important to realize that the mapping of these properties is not 1 to 1. In other words, not every attribute which we give on an HTML element will have a similar named DOM property.
Furthermore have different DOM elements different properties. For example, an <input>
element has a value property which is not present on a <div>
property.
Let's take the following HTML document:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> <!-- charset is a attribute -->
<meta name="viewport" content="width=device-width"> <!-- name and content are attributes -->
<title>JS Bin</title>
</head>
<body>
<div id="foo" class="bar foobar">hi</div> <!-- id and class are attributes -->
</body>
</html>
Then we inspect the <div>
, in the JS console:
console.dir(document.getElementById('foo'));
We see the following DOM properties (chrome devtools, not all properties shown):
class
is reserved keyword in JS). But actually 2 properties, classList
and className
.There aren't a lot of "Best Practices" yet. Those of us that are using inline-styles, for React components, are still very much experimenting.
There are a number of approaches that vary wildly: React inline-style lib comparison chart
What we refer to as "style" actually includes quite a few concepts:
React is already managing the state of your components, this makes styles of state and behavior a natural fit for colocation with your component logic.
Instead of building components to render with conditional state-classes, consider adding state-styles directly:
// Typical component with state-classes
<li
className={classnames({ 'todo-list__item': true, 'is-complete': item.complete })} />
// Using inline-styles for state
<li className='todo-list__item'
style={(item.complete) ? styles.complete : {}} />
Note that we're using a class to style appearance but no longer using any .is-
prefixed class for state and behavior.
We can use Object.assign
(ES6) or _.extend
(underscore/lodash) to add support for multiple states:
// Supporting multiple-states with inline-styles
<li 'todo-list__item'
style={Object.assign({}, item.complete && styles.complete, item.due && styles.due )}>
Now that we're using Object.assign
it becomes very simple to make our component reusable with different styles. If we want to override the default styles, we can do so at the call-site with props, like so: <TodoItem dueStyle={ fontWeight: "bold" } />
. Implemented like this:
<li 'todo-list__item'
style={Object.assign({},
item.due && styles.due,
item.due && this.props.dueStyles)}>
Personally, I don't see compelling reason to inline layout styles. There are a number of great CSS layout systems out there. I'd just use one.
That said, don't add layout styles directly to your component. Wrap your components with layout components. Here's an example.
// This couples your component to the layout system
// It reduces the reusability of your component
<UserBadge
className="col-xs-12 col-sm-6 col-md-8"
firstName="Michael"
lastName="Chan" />
// This is much easier to maintain and change
<div class="col-xs-12 col-sm-6 col-md-8">
<UserBadge
firstName="Michael"
lastName="Chan" />
</div>
For layout support, I often try to design components to be 100%
width
and height
.
This is the most contentious area of the "inline-style" debate. Ultimately, it's up to the component your designing and the comfort of your team with JavaScript.
One thing is certain, you'll need the assistance of a library. Browser-states (:hover
, :focus
), and media-queries are painful in raw React.
I like Radium because the syntax for those hard parts is designed to model that of SASS.
Often you'll see a style object outside of the module. For a todo-list component, it might look something like this:
var styles = {
root: {
display: "block"
},
item: {
color: "black"
complete: {
textDecoration: "line-through"
},
due: {
color: "red"
}
},
}
Adding a bunch of style logic to your template can get a little messy (as seen above). I like to create getter functions to compute styles:
React.createClass({
getStyles: function () {
return Object.assign(
{},
item.props.complete && styles.complete,
item.props.due && styles.due,
item.props.due && this.props.dueStyles
);
},
render: function () {
return <li style={this.getStyles()}>{this.props.item}</li>
}
});
I discussed all of these in more detail at React Europe earlier this year: Inline Styles and when it's best to 'just use CSS'.
I'm happy to help as you make new discoveries along the way :) Hit me up -> @chantastic
This is a very old post, but I thought I should post my solution of a similar problem I faced recently.
Answer : I solved this issue by displaying the tr element as a block element i.e. specifying a CSS of display:block for the tr element. You can see this in code sample below.
<style>_x000D_
tr {_x000D_
display: block;_x000D_
padding-bottom: 20px;_x000D_
}_x000D_
table {_x000D_
border: 1px solid red;_x000D_
}_x000D_
</style>_x000D_
<table>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>_x000D_
<h2>Lorem Ipsum</h2>_x000D_
<p>Fusce sodales lorem nec magna iaculis a fermentum lacus facilisis. Curabitur sodales risus sit amet neque fringilla feugiat. Ut tellus nulla, bibendum at faucibus ut, convallis eget neque. In hac habitasse platea dictumst. Nullam elit enim, gravida_x000D_
eu blandit ut, pellentesque nec turpis. Proin faucibus, sem sed tempor auctor, ipsum velit pellentesque lorem, ut semper lorem eros ac eros. Vivamus mi urna, tempus vitae mattis eget, pretium sit amet sapien. Curabitur viverra lacus non tortor_x000D_
luctus vitae euismod purus hendrerit. Praesent ut venenatis eros. Nulla a ligula erat. Mauris lobortis tempus nulla non scelerisque._x000D_
</p>_x000D_
</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
<br>_x000D_
<br>This TEXT IS BELOW and OUTSIDE the TABLE element. NOTICE how the red table border is pushed down below the end of paragraph due to bottom padding being specified for the tr element. The key point here is that the tr element must be displayed as a block_x000D_
in order for padding to apply at the tr level.
_x000D_
I had the same issue for bootstrap modal
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
If this is your case just add the component to the module declarations and entryComponents as other responses suggest, but also add this to your module
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
imports: [
NgbModule.forRoot(),
...
]
Probably the simplest way is using subplot2grid
, described in Customizing Location of Subplot Using GridSpec.
ax = plt.subplot2grid((2, 2), (0, 0))
is equal to
import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(2, 2)
ax = plt.subplot(gs[0, 0])
so bmu's example becomes:
import numpy as np
import matplotlib.pyplot as plt
# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)
# plot it
fig = plt.figure(figsize=(8, 6))
ax0 = plt.subplot2grid((1, 3), (0, 0), colspan=2)
ax0.plot(x, y)
ax1 = plt.subplot2grid((1, 3), (0, 2))
ax1.plot(y, x)
plt.tight_layout()
plt.savefig('grid_figure.pdf')
onStart()
onStart()
to monitor changes
that impact your UI, You have to unregister it in onStop()onResume()
onStart()
normally dispatch work to a background thread, whose return values are:
START_STICKY to automatically restart if killed, to keep it active.
START_REDELIVER_INTENT
for auto restart and retry if the service was killed before stopSelf().
onResume()
is called by the OS after the device goes to sleep or after an Alert or other partial-screen child activity leaves a portion of the previous window visible so a method is need to re-initialize fields (within a try structure with a catch of exceptions).
Such a situation does not cause onStop()
to be invoked when the child closes.
onResume()
is called without onStart()
when the activity resumes from the backgroundFor More details you can visits Android_activity_lifecycle_gotcha And Activity Lifecycle
function test(a) {_x000D_
var x = (a.value || a.options[a.selectedIndex].value); //crossbrowser solution =)_x000D_
alert(x);_x000D_
}
_x000D_
<select onchange="test(this)" id="select_id">_x000D_
<option value="0">-Select-</option>_x000D_
<option value="1">Communication</option>_x000D_
<option value="2">Communication</option>_x000D_
<option value="3">Communication</option>_x000D_
</select>
_x000D_
Personal opinion: Use them only where they are required. (See TheTXI's answer above for the required list.)
Since the compiler doesn't require them, you can put them all over, but why? The compiler won't tell you where you forgot one, so you'll end up with inconsistent use.
[This opinion is specific to SQL Server. Other databases may have more-stringent requirements. If you're writing SQL to run on multiple databases, your requirements may vary.]
tpdi stated above, "in a script, as you're sending more than one statement, you need it." That's actually not correct. You don't need them.
PRINT 'Semicolons are optional'
PRINT 'Semicolons are optional'
PRINT 'Semicolons are optional';
PRINT 'Semicolons are optional';
Output:
Semicolons are optional
Semicolons are optional
Semicolons are optional
Semicolons are optional
If you don't know the position of the item, you may need to find the index first:
old_index = list1.index(item)
then move it:
list1.insert(new_index, list1.pop(old_index))
or IMHO a cleaner way:
try:
list1.remove(item)
list1.insert(new_index, item)
except ValueError:
pass
change the input boxes like
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
and js code as
function showMe (box) {
var chboxs = document.getElementsByName("c1");
var vis = "none";
for(var i=0;i<chboxs.length;i++) {
if(chboxs[i].checked){
vis = "block";
break;
}
}
document.getElementById(box).style.display = vis;
}
here is a demo fiddle
I was able to resolve this issue (as others mentioned in comments) by disabling "Enable Promotion of Distributed Transactions for RPC" (i.e. setting it to False
):
As requested by @WonderWorker, you can do this via SQL script:
EXEC master.dbo.sp_serveroption
@server = N'[mylinkedserver]',
@optname = N'remote proc transaction promotion',
@optvalue = N'false'
Let's say you have a checkbox with the class (bootstrap) .form-check-input. Then you can use an image for an example as the check mark.
SCSS code:
<input class="form-check-input" type="checkbox">
.form-check-input {
width: 22px;
height: 22px;
-webkit-appearance: none;
-moz-appearance: none;
-o-appearance: none;
appearance:none;
outline: 1px solid blue;
&:checked
{
background: white url('blue.svg') no-repeat;
background-size: 20px 20px;
background-position: 50% 50%;
}
}
I know that this isn't an answer to the initial question ... but you often want to clip the inner content of that rounded corner border you just created.
Chris Cavanagh has come up with an excellent way to do just this.
I have tried a couple different approaches to this ... and I think this one rocks.
Here is the xaml below:
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Background="Black"
>
<!-- Rounded yellow border -->
<Border
HorizontalAlignment="Center"
VerticalAlignment="Center"
BorderBrush="Yellow"
BorderThickness="3"
CornerRadius="10"
Padding="2"
>
<Grid>
<!-- Rounded mask (stretches to fill Grid) -->
<Border
Name="mask"
Background="White"
CornerRadius="7"
/>
<!-- Main content container -->
<StackPanel>
<!-- Use a VisualBrush of 'mask' as the opacity mask -->
<StackPanel.OpacityMask>
<VisualBrush Visual="{Binding ElementName=mask}"/>
</StackPanel.OpacityMask>
<!-- Any content -->
<Image Source="http://chriscavanagh.files.wordpress.com/2006/12/chriss-blog-banner.jpg"/>
<Rectangle
Height="50"
Fill="Red"/>
<Rectangle
Height="50"
Fill="White"/>
<Rectangle
Height="50"
Fill="Blue"/>
</StackPanel>
</Grid>
</Border>
</Page>
just ran into the same problem and solved it with the following line of code:
selectize.addOption({text: "My Default Value", value: "My Default Value"});
selectize.setValue("My Default Value");
You have a variety of options. One would be to use PHP as the template engine it is:
<?php
// Draw the page
?>
<div>
<h3><a href="#">First</a></h3>
<div>Lorem ipsum dolor sit amet.</div>
</div>
<?php
// Done drawing.
?>
Another would be to use single quotes, which let you leave double quotes unquoted and also support newlines in literals:
<?php
echo '<div>
<h3><a href="#">First</a></h3>
<div>Lorem ipsum dolor sit amet.</div>
</div>';
?>
Another would be to use a HEREDOC, which leaves double quotes untouched, supports newlines, and also expands any variables inside:
<?php
echo <<<EOS
<div>
<h3><a href="#">First</a></h3>
<div>Lorem ipsum dolor sit amet.</div>
</div>
EOS;
?>
You can create style element and insert it into DOM
$("<style type='text/css'> .redbold{ color:#f00; font-weight:bold;} </style>").appendTo("head");
$("<div/>").addClass("redbold").text("SOME NEW TEXT").appendTo("body");
tested on Opera10 FF3.5 iE8 iE6
I guess your problem is that jQuery is not loaded in your iframes.
The safest approach is to rely on pure DOM-based methods to parse your content.
Or else, start with jQuery, and then once inside your iframes, test once if typeof window.jQuery == 'undefined'
, if it's true, jQuery is not enabled inside it and fallback on DOM-based method.
For inversion from 0 to 1 and back you can use this library InvertImages, which provides support for IE 10. I also tested with IE 11 and it should work.
graphics.h
appears to something once bundled with Borland and/or Turbo C++, in the 90's.
http://www.daniweb.com/software-development/cpp/threads/17709/88149#post88149
It's unlikely that you will find any support for that file with modern compiler. For other graphics libraries check the list of "related" questions (questions related to this one). E.g., "A Simple, 2d cross-platform graphics library for c or c++?".
DateTime.Now is what you're searching for...
I ran into this issue due to a silly mistake. Make sure the date actually exists!
For example:
September 31, 2015 does not exist.
EXEC dbo.SearchByDateRange @Start = '20150901' , @End = '20150931'
So this fails with the message:
Error converting data type varchar to datetime.
To fix it, input a valid date:
EXEC dbo.SearchByDateRange @Start = '20150901' , @End = '20150930'
And it executes just fine.
With angular 6 spread operator and concat not work. You can resolve it easy:
result.push(...data);
import { timer } from 'rxjs';
await timer(1000).pipe(take(1)).toPromise();
this works better for me
Windows 8.1 add:
--allow-file-access-from-files
to the end of the target text box after the quotes.
EX: "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files
Works like a charm
From Erlang Programming (2009): Erlang concurrency is fast and scalable. Its processes are lightweight in that the Erlang virtual machine does not create an OS thread for every created process. They are created, scheduled, and handled in the VM, independent of underlying operating system.
Erlang implements a preemptive scheduler, which allows each process to run for a set period of time without blocking a system thread for too long, which gives each process some cpu time to be executed. The number of system threads depends on the number of cores if I'm not mistaking, and processes can be removed from one thread and moved to another if the load becomes uneven, this is all handled by the Erlang scheduler.
So if you are simply using the unsophisticated API, like I often am (I use it in ipython a lot), then this is simply
yscale('log')
plot(...)
Hope this helps someone looking for a simple answer! :).
I've seen projects implemented using a number of different approaches, each have their merits and drawbacks.
I'd say the resource method you've chosen makes a lot of sense. It would be interesting to see other people's answers too as I often wonder if there's a better way of doing things like this. I've seen numerous resources that all point to the using resources method, including one right here on SO.
I have always had good luck with using background images instead of trusting all browsers to interpret the bullet in exactly the same way. This would also give you tight control over the size of the bullet.
.moreLinks li {
background: url("bullet.gif") no-repeat left 5px;
padding-left: 1em;
}
Also, you may want to move your DIV
outside of the UL
. It's invalid markup as you have it now. You can use a list header LH
if you must have it inside the list.
In Korean version of Windows 10, this problem happened because my Windows user name was in Korean not in English. After the user name was made again in English, the problem was cleared.
These instructions are for XCode 6.4 (since I couldn't find the update for the recent versions even this was a bit outdated)
a) Part on the developers' website:
Sign in into: https://developer.apple.com/
Member Center
Certificates, Identifiers & Profiles
Certificates>All
Click "+" to add, and then follow the instructions. You will need to open "Keychain Access.app", there under "Keychain Access" menu > "Certificate Assistant>", choose "Request a Certificate From a Certificate Authority" etc.
b) XCode part:
After all, you need to go to XCode, and open XCode>Preferences..., choose your Apple ID > View Details... > click that rounded arrow to update as well as "+" to check for iOS Distribution or iOS Developer Signing Identities.
Also just another nice function i like to use when i want to compute i.e. first/last day of the last month or other relative timedeltas etc. ...
The relativedelta function from dateutil function (a powerful extension to the datetime lib)
import datetime as dt
from dateutil.relativedelta import relativedelta
#get first and last day of this and last month)
today = dt.date.today()
first_day_this_month = dt.date(day=1, month=today.month, year=today.year)
last_day_last_month = first_day_this_month - relativedelta(days=1)
print (first_day_this_month, last_day_last_month)
>2015-03-01 2015-02-28
Some thing like this.
import React from 'react';_x000D_
import {_x000D_
BrowserRouter as Router, Route, NavLink, Switch, Link_x000D_
} from 'react-router-dom';_x000D_
_x000D_
import '../assets/styles/App.css';_x000D_
_x000D_
const Home = () =>_x000D_
<NormalNavLinks>_x000D_
<h1>HOME</h1>_x000D_
</NormalNavLinks>;_x000D_
const About = () =>_x000D_
<NormalNavLinks>_x000D_
<h1>About</h1>_x000D_
</NormalNavLinks>;_x000D_
const Help = () =>_x000D_
<NormalNavLinks>_x000D_
<h1>Help</h1>_x000D_
</NormalNavLinks>;_x000D_
_x000D_
const AdminHome = () =>_x000D_
<AdminNavLinks>_x000D_
<h1>root</h1>_x000D_
</AdminNavLinks>;_x000D_
_x000D_
const AdminAbout = () =>_x000D_
<AdminNavLinks>_x000D_
<h1>Admin about</h1>_x000D_
</AdminNavLinks>;_x000D_
_x000D_
const AdminHelp = () =>_x000D_
<AdminNavLinks>_x000D_
<h1>Admin Help</h1>_x000D_
</AdminNavLinks>;_x000D_
_x000D_
_x000D_
const AdminNavLinks = (props) => (_x000D_
<div>_x000D_
<h2>Admin Menu</h2>_x000D_
<NavLink exact to="/admin">Admin Home</NavLink>_x000D_
<NavLink to="/admin/help">Admin Help</NavLink>_x000D_
<NavLink to="/admin/about">Admin About</NavLink>_x000D_
<Link to="/">Home</Link>_x000D_
{props.children}_x000D_
</div>_x000D_
);_x000D_
_x000D_
const NormalNavLinks = (props) => (_x000D_
<div>_x000D_
<h2>Normal Menu</h2>_x000D_
<NavLink exact to="/">Home</NavLink>_x000D_
<NavLink to="/help">Help</NavLink>_x000D_
<NavLink to="/about">About</NavLink>_x000D_
<Link to="/admin">Admin</Link>_x000D_
{props.children}_x000D_
</div>_x000D_
);_x000D_
_x000D_
const App = () => (_x000D_
<Router>_x000D_
<div>_x000D_
<Switch>_x000D_
<Route exact path="/" component={Home}/>_x000D_
<Route path="/help" component={Help}/>_x000D_
<Route path="/about" component={About}/>_x000D_
_x000D_
<Route exact path="/admin" component={AdminHome}/>_x000D_
<Route path="/admin/help" component={AdminHelp}/>_x000D_
<Route path="/admin/about" component={AdminAbout}/>_x000D_
</Switch>_x000D_
_x000D_
</div>_x000D_
</Router>_x000D_
);_x000D_
_x000D_
_x000D_
export default App;
_x000D_
In Entity Framework 6.1+ you can use this attribute on your model:
[Index(IsUnique=true)]
You can find it in this namespace:
using System.ComponentModel.DataAnnotations.Schema;
If your model field is a string, make sure it is not set to nvarchar(MAX) in SQL Server or you will see this error with Entity Framework Code First:
Column 'x' in table 'dbo.y' is of a type that is invalid for use as a key column in an index.
The reason is because of this:
SQL Server retains the 900-byte limit for the maximum total size of all index key columns."
(from: http://msdn.microsoft.com/en-us/library/ms191241.aspx )
You can solve this by setting a maximum string length on your model:
[StringLength(450)]
Your model will look like this now in EF CF 6.1+:
public class User
{
public int UserId{get;set;}
[StringLength(450)]
[Index(IsUnique=true)]
public string UserName{get;set;}
}
Update:
if you use Fluent:
public class UserMap : EntityTypeConfiguration<User>
{
public UserMap()
{
// ....
Property(x => x.Name).IsRequired().HasMaxLength(450).HasColumnAnnotation("Index", new IndexAnnotation(new[] { new IndexAttribute("Index") { IsUnique = true } }));
}
}
and use in your modelBuilder:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// ...
modelBuilder.Configurations.Add(new UserMap());
// ...
}
Update 2
for EntityFrameworkCore see also this topic: https://github.com/aspnet/EntityFrameworkCore/issues/1698
Update 3
for EF6.2 see: https://github.com/aspnet/EntityFramework6/issues/274
Update 4
ASP.NET Core Mvc 2.2 with EF Core:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Unique { get; set; }
Unrelated to mockito, one can catch the exception and assert its properties. To verify that the exception did happen, assert a false condition within the try block after the statement that throws the exception.
Assert does throw an AssertionError if you run your app with assertions turned on.
int a = 42;
assert a >= 0 && d <= 10;
If you run this with, say: java -ea -jar peiska.jar
It shall throw an java.lang.AssertionError
As pointed out by others, Python 3's int
does not have a maximum size, but if you just need something that's guaranteed to be higher than any other int
value, then you can use the float value for Infinity, which you can get with float("inf")
.
It's canonical to use references for this; precedence: ostream::operator<<
. Pointers and references here are, for all ordinary purposes, the same speed/size/safety.
Just for those interested you can avoid writing custom function by passing NULL as last parameter (if you do not intend to do extra processing of returned data).
In this case default internal function is used.
Details
http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTWRITEDATA
Example
#include <stdio.h>
#include <curl/curl.h>
int main(void)
{
CURL *curl;
FILE *fp;
CURLcode res;
char *url = "http://stackoverflow.com";
char outfilename[FILENAME_MAX] = "page.html";
curl = curl_easy_init();
if (curl)
{
fp = fopen(outfilename,"wb");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
fclose(fp);
}
return 0;
}
You can get Google Drive to automatically convert csv files to Google Sheets by appending
?convert=true
to the end of the api url you are calling.
EDIT: Here is the documentation on available parameters: https://developers.google.com/drive/v2/reference/files/insert
Also, while searching for the above link, I found this question has already been answered here:
You can use the following code to check if a textbox object is null/empty
'Checks if the box is null
If Me.TextBox & "" <> "" Then
'Enter Code here...
End if
I had this error when i was using the azure storage as a static website, the js files that are copied had the content type as text/plain; charset=utf-8
and i changed the content type to application/javascript
It started working.
If you want the indentation, you have to specify it to the TransformerFactory
.
TransformerFactory tf = TransformerFactory.newInstance();
tf.setAttribute("indent-number", new Integer(2));
Transformer t = tf.newTransformer();
You may easily override the onKey() event in activity and fragments to hide the keyboard.
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (keyCode == event.KEYCODE_ENTER) {
intiateLoginProcess();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getCurrentFocus()
.getWindowToken(), 0);
return true;
}
}
return false;
}
class Timer
{
private $startTime = null;
public function __construct($showSeconds = true)
{
$this->startTime = microtime(true);
echo 'Working - please wait...' . PHP_EOL;
}
public function __destruct()
{
$endTime = microtime(true);
$time = $endTime - $this->startTime;
$hours = (int)($time / 60 / 60);
$minutes = (int)($time / 60) - $hours * 60;
$seconds = (int)$time - $hours * 60 * 60 - $minutes * 60;
$timeShow = ($hours == 0 ? "00" : $hours) . ":" . ($minutes == 0 ? "00" : ($minutes < 10 ? "0" . $minutes : $minutes)) . ":" . ($seconds == 0 ? "00" : ($seconds < 10 ? "0" . $seconds : $seconds));
echo 'Job finished in ' . $timeShow . PHP_EOL;
}
}
$t = new Timer(); // echoes "Working, please wait.."
[some operations]
unset($t); // echoes "Job finished in h:m:s"
Use SQL Profiler and use a filter on it to get the most expensive queries.
It is better to process HTML as a template than to build nodes via JavaScript (HTML is not XML after all.) You can keep your IFRAME's HTML syntax clean by using a template and then appending the template's contents into another DIV.
<div id="placeholder"></div>
<script id="iframeTemplate" type="text/html">
<iframe src="...">
<!-- replace this line with alternate content -->
</iframe>
</script>
<script type="text/javascript">
var element,
html,
template;
element = document.getElementById("placeholder");
template = document.getElementById("iframeTemplate");
html = template.innerHTML;
element.innerHTML = html;
</script>
Here's how I did it:
This is my PostsController
Post::create([
'title' => request('title'),
'body' => request('body'),
'user_id' => auth()->id()
]);
And this is my Post Model.
protected $fillable = ['title', 'body','user_id'];
And try refreshing the migration if its just on test instance
$ php artisan migrate:refresh
Note: migrate: refresh will delete all the previous posts, users
Accuracy is also important.
What option 3 does is basically replace all the but any whitespaces with a +1
and then evaluates this to count up the 1
's giving you the word count.
It's the most accurate and fastest method of the four that I've done here.
Please note it is slower than return str.split(" ").length;
but it's accurate when compared to Microsoft Word.
See file ops/s and returned word count below.
Here's a link to run this bench test. https://jsbench.me/ztk2t3q3w5/1
// This is the fastest at 111,037 ops/s ±2.86% fastest_x000D_
var str = "All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy.";_x000D_
function WordCount(str) {_x000D_
return str.split(" ").length;_x000D_
}_x000D_
console.log(WordCount(str));_x000D_
// Returns 241 words. Not the same as Microsoft Word count, of by one._x000D_
_x000D_
// This is the 2nd fastest at 46,835 ops/s ±1.76% 57.82% slower_x000D_
var str = "All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy.";_x000D_
function WordCount(str) {_x000D_
return str.split(/(?!\W)\S+/).length;_x000D_
}_x000D_
console.log(WordCount(str));_x000D_
// Returns 241 words. Not the same as Microsoft Word count, of by one._x000D_
_x000D_
// This is the 3rd fastest at 37,121 ops/s ±1.18% 66.57% slower_x000D_
var str = "All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy.";_x000D_
function countWords(str) {_x000D_
var str = str.replace(/\S+/g,"\+1");_x000D_
return eval(str);_x000D_
}_x000D_
console.log(countWords(str));_x000D_
// Returns 240 words. Same as Microsoft Word count._x000D_
_x000D_
// This is the slowest at 89 ops/s 17,270 ops/s ±2.29% 84.45% slower_x000D_
var str = "All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy.";_x000D_
function countWords(str) {_x000D_
var str = str.replace(/(?!\W)\S+/g,"1").replace(/\s*/g,"");_x000D_
return str.lastIndexOf("");_x000D_
}_x000D_
console.log(countWords(str));_x000D_
// Returns 240 words. Same as Microsoft Word count.
_x000D_
By default , maven looks at these folders for java and test classes respectively - src/main/java and src/test/java
When the src is specified with the test classes under source and the scope for junit dependency in pom.xml is mentioned as test - org.unit will not be found by maven.
As long as the value of width is auto, the element can have horizontal margin, padding and border without becoming wider than its container (unless of course the sum of margin-left + border-left-width + padding-left + padding-right + border-right-width + margin-right is larger than the container). The width of its content box will be whatever is left when the margin, padding and border have been subtracted from the container’s width.
On the other hand, if you specify width:100%, the element’s total width will be 100% of its containing block plus any horizontal margin, padding and border (unless you’ve used box-sizing:border-box, in which case only margins are added to the 100% to change how its total width is calculated). This may be what you want, but most likely it isn’t.
Source:
http://www.456bereastreet.com/archive/201112/the_difference_between_widthauto_and_width100/
Using java.time
framework built into Java 8
int year = 2015;
int month = 12;
int day = 22;
LocalDate.of(year, month, day); //2015-12-22
LocalDate.parse("2015-12-22"); //2015-12-22
//with custom formatter
DateTimeFormatter.ofPattern formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate.parse("22-12-2015", formatter); //2015-12-22
If you need also information about time(hour,minute,second) use some conversion from LocalDate
to LocalDateTime
LocalDate.parse("2015-12-22").atStartOfDay() //2015-12-22T00:00
This following works better if you need to scroll to an arbitrary item in the list (rather than always to the bottom):
function scrollIntoView(element, container) {
var containerTop = $(container).scrollTop();
var containerBottom = containerTop + $(container).height();
var elemTop = element.offsetTop;
var elemBottom = elemTop + $(element).height();
if (elemTop < containerTop) {
$(container).scrollTop(elemTop);
} else if (elemBottom > containerBottom) {
$(container).scrollTop(elemBottom - $(container).height());
}
}
You're very close, the problem is you're comparing a DateTime to a TimeOfDay. What you need to do is add the .TimeOfDay property to the end of your Convert.ToDateTime() functions.
Below, I have written an answer for n
equals to 5, but you can apply same approach to draw DFAs for any value of n
and 'any positional number system' e.g binary, ternary...
First lean the term 'Complete DFA', A DFA defined on complete domain in d:Q × S?Q is called 'Complete DFA'. In other words we can say; in transition diagram of complete DFA there is no missing edge (e.g. from each state in Q there is one outgoing edge present for every language symbol in S). Note: Sometime we define partial DFA as d ? Q × S?Q (Read: How does “d:Q × S?Q” read in the definition of a DFA).
Step-1: When you divide a number ? by n
then reminder can be either 0, 1, ..., (n - 2) or (n - 1). If remainder is 0
that means ? is divisible by n
otherwise not. So, in my DFA there will be a state qr that would be corresponding to a remainder value r
, where 0 <= r <= (n - 1)
, and total number of states in DFA is n
.
After processing a number string ? over S, the end state is qr implies that ? % n => r (% reminder operator).
In any automata, the purpose of a state is like memory element. A state in an atomata stores some information like fan's switch that can tell whether the fan is in 'off' or in 'on' state. For n = 5, five states in DFA corresponding to five reminder information as follows:
Using above information, we can start drawing transition diagram TD of five states as follows:
Figure-1
So, 5 states for 5 remainder values. After processing a string ? if end-state becomes q0 that means decimal equivalent of input string is divisible by 5. In above figure q0 is marked final state as two concentric circle.
Additionally, I have defined a transition rule d:(q0, 0)?q0 as a self loop for symbol '0'
at state q0, this is because decimal equivalent of any string consist of only '0'
is 0 and 0 is a divisible by n
.
Step-2: TD above is incomplete; and can only process strings of '0'
s. Now add some more edges so that it can process subsequent number's strings. Check table below, shows new transition rules those can be added next step:
+-------------------------------------+ ¦Number¦Binary¦Remainder(%5)¦End-state¦ +------+------+-------------+---------¦ ¦One ¦1 ¦1 ¦q1 ¦ +------+------+-------------+---------¦ ¦Two ¦10 ¦2 ¦q2 ¦ +------+------+-------------+---------¦ ¦Three ¦11 ¦3 ¦q3 ¦ +------+------+-------------+---------¦ ¦Four ¦100 ¦4 ¦q4 ¦ +-------------------------------------+
'1'
there should be a transition rule d:(q0, 1)?q1 '10'
, end-state should be q2, and to process '10'
, we just need to add one more transition rule d:(q1, 0)?q2'11'
, end-state is q3, and we need to add a transition rule d:(q1, 1)?q3'100'
, end-state is q4. TD already processes prefix string '10'
and we just need to add a new transition rule d:(q2, 0)?q4Figure-2
Step-3: Five = 101
Above transition diagram in figure-2 is still incomplete and there are many missing edges, for an example no transition is defined for d:(q2, 1)-?. And the rule should be present to process strings like '101'
.
Because '101'
= 5 is divisible by 5, and to accept '101'
I will add d:(q2, 1)?q0 in above figure-2.
Path: ?(q0)-1?(q1)-0?(q2)-1?(q0)
with this new rule, transition diagram becomes as follows:
Figure-3
Below in each step I pick next subsequent binary number to add a missing edge until I get TD as a 'complete DFA'.
Step-4: Six = 110.
We can process '11'
in present TD in figure-3 as: ?(q0)-11?(q3) -0?(?). Because 6 % 5 = 1 this means to add one rule d:(q3, 0)?q1.
Figure-4
Step-5: Seven = 111
+--------------------------------------------------------------+ ¦Number¦Binary¦Remainder(%5)¦End-state¦ Path ¦ Add ¦ +------+------+-------------+---------+------------+-----------¦ ¦Seven ¦111 ¦7 % 5 = 2 ¦q2 ¦ q0-11?q3 ¦ q3-1?q2 ¦ +--------------------------------------------------------------+
Figure-5
Step-6: Eight = 1000
+----------------------------------------------------------+ ¦Number¦Binary¦Remainder(%5)¦End-state¦ Path ¦ Add ¦ +------+------+-------------+---------+----------+---------¦ ¦Eight ¦1000 ¦8 % 5 = 3 ¦q3 ¦q0-100?q4 ¦ q4-0?q3 ¦ +----------------------------------------------------------+
Figure-6
Step-7: Nine = 1001
+----------------------------------------------------------+ ¦Number¦Binary¦Remainder(%5)¦End-state¦ Path ¦ Add ¦ +------+------+-------------+---------+----------+---------¦ ¦Nine ¦1001 ¦9 % 5 = 4 ¦q4 ¦q0-100?q4 ¦ q4-1?q4 ¦ +----------------------------------------------------------+
Figure-7
In TD-7, total number of edges are 10 == Q × S = 5 × 2. And it is a complete DFA that can accept all possible binary strings those decimal equivalent is divisible by 5.
Step-1 Exactly same as for binary, use figure-1.
Step-2 Add Zero, One, Two
+------------------------------------------------------+ ¦Decimal¦Ternary¦Remainder(%5)¦End-state¦ Add ¦ +-------+-------+-------------+---------+--------------¦ ¦Zero ¦0 ¦0 ¦q0 ¦ d:(q0,0)?q0 ¦ +-------+-------+-------------+---------+--------------¦ ¦One ¦1 ¦1 ¦q1 ¦ d:(q0,1)?q1 ¦ +-------+-------+-------------+---------+--------------¦ ¦Two ¦2 ¦2 ¦q2 ¦ d:(q0,2)?q3 ¦ +------------------------------------------------------+
Figure-8
Step-3 Add Three, Four, Five
+-----------------------------------------------------+ ¦Decimal¦Ternary¦Remainder(%5)¦End-state¦ Add ¦ +-------+-------+-------------+---------+-------------¦ ¦Three ¦10 ¦3 ¦q3 ¦ d:(q1,0)?q3 ¦ +-------+-------+-------------+---------+-------------¦ ¦Four ¦11 ¦4 ¦q4 ¦ d:(q1,1)?q4 ¦ +-------+-------+-------------+---------+-------------¦ ¦Five ¦12 ¦0 ¦q0 ¦ d:(q1,2)?q0 ¦ +-----------------------------------------------------+
Figure-9
Step-4 Add Six, Seven, Eight
+-----------------------------------------------------+ ¦Decimal¦Ternary¦Remainder(%5)¦End-state¦ Add ¦ +-------+-------+-------------+---------+-------------¦ ¦Six ¦20 ¦1 ¦q1 ¦ d:(q2,0)?q1 ¦ +-------+-------+-------------+---------+-------------¦ ¦Seven ¦21 ¦2 ¦q2 ¦ d:(q2,1)?q2 ¦ +-------+-------+-------------+---------+-------------¦ ¦Eight ¦22 ¦3 ¦q3 ¦ d:(q2,2)?q3 ¦ +-----------------------------------------------------+
Figure-10
Step-5 Add Nine, Ten, Eleven
+-----------------------------------------------------+ ¦Decimal¦Ternary¦Remainder(%5)¦End-state¦ Add ¦ +-------+-------+-------------+---------+-------------¦ ¦Nine ¦100 ¦4 ¦q4 ¦ d:(q3,0)?q4 ¦ +-------+-------+-------------+---------+-------------¦ ¦Ten ¦101 ¦0 ¦q0 ¦ d:(q3,1)?q0 ¦ +-------+-------+-------------+---------+-------------¦ ¦Eleven ¦102 ¦1 ¦q1 ¦ d:(q3,2)?q1 ¦ +-----------------------------------------------------+
Figure-11
Step-6 Add Twelve, Thirteen, Fourteen
+------------------------------------------------------+ ¦Decimal ¦Ternary¦Remainder(%5)¦End-state¦ Add ¦ +--------+-------+-------------+---------+-------------¦ ¦Twelve ¦110 ¦2 ¦q2 ¦ d:(q4,0)?q2 ¦ +--------+-------+-------------+---------+-------------¦ ¦Thirteen¦111 ¦3 ¦q3 ¦ d:(q4,1)?q3 ¦ +--------+-------+-------------+---------+-------------¦ ¦Fourteen¦112 ¦4 ¦q4 ¦ d:(q4,2)?q4 ¦ +------------------------------------------------------+
Figure-12
Total number of edges in transition diagram figure-12 are 15 = Q × S = 5 * 3 (a complete DFA). And this DFA can accept all strings consist over {0, 1, 2} those decimal equivalent is divisible by 5.
If you notice at each step, in table there are three entries because at each step I add all possible outgoing edge from a state to make a complete DFA (and I add an edge so that qr state gets for remainder is r
)!
To add further, remember union of two regular languages are also a regular. If you need to design a DFA that accepts binary strings those decimal equivalent is either divisible by 3 or 5, then draw two separate DFAs for divisible by 3 and 5 then union both DFAs to construct target DFA (for 1 <= n <= 10 your have to union 10 DFAs).
If you are asked to draw DFA that accepts binary strings such that decimal equivalent is divisible by 5 and 3 both then you are looking for DFA of divisible by 15 ( but what about 6 and 8?).
Note: DFAs drawn with this technique will be minimized DFA only when there is no common factor between number n
and base e.g. there is no between 5 and 2 in first example, or between 5 and 3 in second example, hence both DFAs constructed above are minimized DFAs. If you are interested to read further about possible mini states for number n
and base b
read paper: Divisibility and State Complexity.
below I have added a Python script, I written it for fun while learning Python library pygraphviz. I am adding it I hope it can be helpful for someone in someway.
So we can apply above trick to draw DFA to recognize number strings in any base 'b'
those are divisible a given number 'n'
. In that DFA total number of states will be n
(for n
remainders) and number of edges should be equal to 'b' * 'n' — that is complete DFA: 'b' = number of symbols in language of DFA and 'n' = number of states.
Using above trick, below I have written a Python Script to Draw DFA for input base
and number
. In script, function divided_by_N
populates DFA's transition rules in base * number
steps. In each step-num, I convert num
into number string num_s
using function baseN()
. To avoid processing each number string, I have used a temporary data-structure lookup_table
. In each step, end-state for number string num_s
is evaluated and stored in lookup_table
to use in next step.
For transition graph of DFA, I have written a function draw_transition_graph
using Pygraphviz library (very easy to use). To use this script you need to install graphviz
. To add colorful edges in transition diagram, I randomly generates color codes for each symbol get_color_dict
function.
#!/usr/bin/env python
import pygraphviz as pgv
from pprint import pprint
from random import choice as rchoice
def baseN(n, b, syms="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
""" converts a number `n` into base `b` string """
return ((n == 0) and syms[0]) or (
baseN(n//b, b, syms).lstrip(syms[0]) + syms[n % b])
def divided_by_N(number, base):
"""
constructs DFA that accepts given `base` number strings
those are divisible by a given `number`
"""
ACCEPTING_STATE = START_STATE = '0'
SYMBOL_0 = '0'
dfa = {
str(from_state): {
str(symbol): 'to_state' for symbol in range(base)
}
for from_state in range(number)
}
dfa[START_STATE][SYMBOL_0] = ACCEPTING_STATE
# `lookup_table` keeps track: 'number string' -->[dfa]--> 'end_state'
lookup_table = { SYMBOL_0: ACCEPTING_STATE }.setdefault
for num in range(number * base):
end_state = str(num % number)
num_s = baseN(num, base)
before_end_state = lookup_table(num_s[:-1], START_STATE)
dfa[before_end_state][num_s[-1]] = end_state
lookup_table(num_s, end_state)
return dfa
def symcolrhexcodes(symbols):
"""
returns dict of color codes mapped with alphabets symbol in symbols
"""
return {
symbol: '#'+''.join([
rchoice("8A6C2B590D1F4E37") for _ in "FFFFFF"
])
for symbol in symbols
}
def draw_transition_graph(dfa, filename="filename"):
ACCEPTING_STATE = START_STATE = '0'
colors = symcolrhexcodes(dfa[START_STATE].keys())
# draw transition graph
tg = pgv.AGraph(strict=False, directed=True, decorate=True)
for from_state in dfa:
for symbol, to_state in dfa[from_state].iteritems():
tg.add_edge("Q%s"%from_state, "Q%s"%to_state,
label=symbol, color=colors[symbol],
fontcolor=colors[symbol])
# add intial edge from an invisible node!
tg.add_node('null', shape='plaintext', label='start')
tg.add_edge('null', "Q%s"%START_STATE,)
# make end acception state as 'doublecircle'
tg.get_node("Q%s"%ACCEPTING_STATE).attr['shape'] = 'doublecircle'
tg.draw(filename, prog='circo')
tg.close()
def print_transition_table(dfa):
print("DFA accepting number string in base '%(base)s' "
"those are divisible by '%(number)s':" % {
'base': len(dfa['0']),
'number': len(dfa),})
pprint(dfa)
if __name__ == "__main__":
number = input ("Enter NUMBER: ")
base = input ("Enter BASE of number system: ")
dfa = divided_by_N(number, base)
print_transition_table(dfa)
draw_transition_graph(dfa)
Execute it:
~/study/divide-5/script$ python script.py
Enter NUMBER: 5
Enter BASE of number system: 4
DFA accepting number string in base '4' those are divisible by '5':
{'0': {'0': '0', '1': '1', '2': '2', '3': '3'},
'1': {'0': '4', '1': '0', '2': '1', '3': '2'},
'2': {'0': '3', '1': '4', '2': '0', '3': '1'},
'3': {'0': '2', '1': '3', '2': '4', '3': '0'},
'4': {'0': '1', '1': '2', '2': '3', '3': '4'}}
~/study/divide-5/script$ ls
script.py filename.png
~/study/divide-5/script$ display filename
Output:
DFA accepting number strings in base 4 those are divisible by 5
Similarly, enter base = 4 and number = 7 to generate - dfa accepting number string in base '4' those are divisible by '7'
Btw, try changing filename
to .png
or .jpeg
.
References those I use to write this script:
➊ Function baseN
from "convert integer to a string in a given numeric base in python"
➋ To install "pygraphviz": "Python does not see pygraphviz"
➌ To learn use of Pygraphviz: "Python-FSM"
➍ To generate random hex color codes for each language symbol: "How would I make a random hexdigit code generator using .join and for loops?"
There is no format specifier for bool. You can print it using some of the existing specifiers for printing integral types or do something more fancy:
printf("%s", x?"true":"false");
In at least in ubuntu 16.10, the default python3
is python3.5
. As such, all of the python3-X
packages will be installed for python3.5 and not for python3.6.
You can verify this by checking the shebang of pip3
:
$ head -n1 $(which pip3)
#!/usr/bin/python3
Fortunately, the pip installed by the python3-pip
package is installed into the "shared" /usr/lib/python3/dist-packages
such that python3.6 can also take advantage of it.
You can install packages for python3.6 by doing:
python3.6 -m pip install ...
For example:
$ python3.6 -m pip install requests
$ python3.6 -c 'import requests; print(requests.__file__)'
/usr/local/lib/python3.6/dist-packages/requests/__init__.py
SELECT {FN LENGTH('123-345-566')} - {FN LENGTH({FN REPLACE('123-345-566', '#', '')})} FROM DUAL
In fact if you write any C extensions for your Ruby projects there is really only one way to define a Module method.
rb_define_singleton_method
I know this self business just opens up all kinds of other questions so you could do better by searching each part.
Objects first.
foo = Object.new
Can I make a method for foo?
Sure
def foo.hello
'hello'
end
What do I do with it?
foo.hello
==>"hello"
Just another object.
foo.methods
You get all the Object methods plus your new one.
def foo.self
self
end
foo.self
Just the foo Object.
Try to see what happens if you make foo from other Objects like Class and Module. The examples from all the answers are nice to play with but you have to work with different ideas or concepts to really understand what is going on with the way the code is written. So now you have lots of terms to go look at.
Singleton, Class, Module, self, Object, and Eigenclass was brought up but Ruby doesn't name Object Models that way. It's more like Metaclass. Richard or __why shows you the idea here. http://viewsourcecode.org/why/hacking/seeingMetaclassesClearly.html And if the blows you away then try looking up Ruby Object Model in search. Two videos that I know of on YouTube are Dave Thomas and Peter Cooper. They try to explain that concept too. It took Dave a long time to get it so don't worry. I'm still working on it too. Why else would I be here? Thanks for your question. Also take a look at the standard library. It has a Singleton Module just as an FYI.
This is pretty good. https://www.youtube.com/watch?v=i4uiyWA8eFk
You can use sed
for this too -
sed -n '320123'p filename
This will print line number 320123.
If you want a range then you can do -
sed -n '320123,320150'p filename
If you want from a particular line to the very end then -
sed -n '320123,$'p filename
use
pattern.compile("\"");
String s= p.toString()+"yourcontent"+p.toString();
will give result as yourcontent
as is
There is no version 1.3.0
for rope
. 1.3.0
refers to the package cached-property
. The highest available version of rope
is 0.9.4
.
You can install different versions with conda install package=version
. But in this case there is only one version of rope
so you don't need that.
The reason you see the cached-property
in this listing is because it contains the string "rope"
: "cached-p rope erty"
py35_0
means that you need python version 3.5
for this specific version. If you only have python3.4
and the package is only for version 3.5
you cannot install it with conda.
I am not quite sure on the defaults
either. It should be an indication that this package is inside the default conda channel.
This gives capital Letters to all major words
library(lettercase)
xString = str_title_case(xString)
None of these solutions worked for me, however I was able to fix it by taking the width and subtracting the width of the scroll bar. I'm not sure how cross-browser compatible this is.
From v1.10.2 onwards, you can also use ..
dt <- data.table(a=1:2, b=2:3, c=3:4)
keep_cols = c("a", "c")
dt[, ..keep_cols]
In my case, this has been resolved by going to control panel > java > security > then add url in the exception site list. Then apply. Test again the site and it should now allow you to run the local java.
It turns out that because of a peculiar mixture of javascript frameworks that I needed to initiate the script using an event listener provide by one of the other frameworks.
You can use also util methods mentioned in this blog: Getting cell witdth and height from excel with Apache POI. It can solve your problem.
Copy & paste from that blog:
static public class PixelUtil {
public static final short EXCEL_COLUMN_WIDTH_FACTOR = 256;
public static final short EXCEL_ROW_HEIGHT_FACTOR = 20;
public static final int UNIT_OFFSET_LENGTH = 7;
public static final int[] UNIT_OFFSET_MAP = new int[] { 0, 36, 73, 109, 146, 182, 219 };
public static short pixel2WidthUnits(int pxs) {
short widthUnits = (short) (EXCEL_COLUMN_WIDTH_FACTOR * (pxs / UNIT_OFFSET_LENGTH));
widthUnits += UNIT_OFFSET_MAP[(pxs % UNIT_OFFSET_LENGTH)];
return widthUnits;
}
public static int widthUnits2Pixel(short widthUnits) {
int pixels = (widthUnits / EXCEL_COLUMN_WIDTH_FACTOR) * UNIT_OFFSET_LENGTH;
int offsetWidthUnits = widthUnits % EXCEL_COLUMN_WIDTH_FACTOR;
pixels += Math.floor((float) offsetWidthUnits / ((float) EXCEL_COLUMN_WIDTH_FACTOR / UNIT_OFFSET_LENGTH));
return pixels;
}
public static int heightUnits2Pixel(short heightUnits) {
int pixels = (heightUnits / EXCEL_ROW_HEIGHT_FACTOR);
int offsetWidthUnits = heightUnits % EXCEL_ROW_HEIGHT_FACTOR;
pixels += Math.floor((float) offsetWidthUnits / ((float) EXCEL_ROW_HEIGHT_FACTOR / UNIT_OFFSET_LENGTH));
return pixels;
}
}
So when you want to get cell width and height you can use this to get value in pixel, values are approximately.
PixelUtil.heightUnits2Pixel((short) row.getHeight())
PixelUtil.widthUnits2Pixel((short) sh.getColumnWidth(columnIndex));
strip
removes the whitespace from the beginning and end of the string. If you want the whitespace, don't call strip.
This does not require a switch statement. It is clearer, more concise, faster, and optimises better, to use if else statements...
var d = this.dealer;
if (1 <= d && d <= 11) { // making sure in range 1..11
if (d <= 4) {
alert("1 to 4");
} else if (d <= 8) {
alert("5 to 8");
} else {
alert("9 to 11");
}
} else {
alert("not in range");
}
Speed test
I was curious about the overhead of using a switch instead of the simpler if...else..., so I put together a jsFiddle to examine it... http://jsfiddle.net/17x9w1eL/
Chrome: switch was around 70% slower than if else
Firefox: switch was around 5% slower than if else
IE: switch was around 5% slower than if else
Safari: switch was around 95% slower than if else
Notes:
Assigning to the local variable is optional, especially if your code is going to be automatically optimised later.
For numeric ranges, I like to use this kind of construction...
if (1 <= d && d <= 11) {...}
... because to me it reads closer to the way you would express a range in maths (1 <= d <= 11), and when I'm reading the code, I can read that as "if d is between 1 and 11".
Clearer
A few people don't think this is clearer. I'd say it is not less clear as the structure is close to identical to the switch option. The main reason it is clearer is that every part of it is readable and makes simple intuitive sense.
My concern, with "switch (true)", is that it can appear to be a meaningless line of code. Many coders, reading that will not know what to make of it.
For my own code, I'm more willing to use obscure structures from time to time, but if anyone else will look at it, I try to use clearer constructs. I think it is better to use the constructs for what they are intended.
Optimisation
In a modern environment, code is often going to be minified for production, so you can write clear concise code, with readable variable names and helpful comments. There's no clear reason to use switch in this way.
I also tried putting both constructs through a minifier. The if/else structure compresses well, becoming a single short expression using nested ternary operators. The switch statement when minified remains a switch, complete with "switch", "case" and "break" tokens, and as a result is considerably longer in code.
How switch(true) works
I think "switch(true) is obscure, but it seems some people just want to use it, so here's an explanation of why it works...
A switch/case statement works by matching the part in the switch with each case, and then executing the code on the first match. In most use cases, we have a variable or non-constant expression in the switch, and then match it.
With "switch(true), we will find the first expression in the case statements that is true. If you read "switch (true)" as "find the first expression that is true", the code feels more readable.
If you have merged cells,
Sub OneCell()
Sheets("Sheet2").range("B1:B3").value = Sheets("Sheet1").range("A1:A3").value
End Sub
that doesn't copy cells as they are, where previous code does copy exactly as they look like (merged).
How I placed a border around my UI view (main - SubscriptionAd) in Storyboard is to place it inside another UI view (background - BackgroundAd). The Background UIView has a background colour that matches the border colour i want, and the Main UIView has constraints value 2 from each side.
I will link the background view to my ViewController and then turn the border on and off by changing the background colour.
Even tidier:
select string = replace(replace(replace(' select single spaces',' ','<>'),'><',''),'<>',' ')
Output:
select single spaces
Here follows a working code to calculate crc16 CCITT. I tested it and the results matched with those provided by http://www.lammertbies.nl/comm/info/crc-calculation.html.
unsigned short crc16(const unsigned char* data_p, unsigned char length){
unsigned char x;
unsigned short crc = 0xFFFF;
while (length--){
x = crc >> 8 ^ *data_p++;
x ^= x>>4;
crc = (crc << 8) ^ ((unsigned short)(x << 12)) ^ ((unsigned short)(x <<5)) ^ ((unsigned short)x);
}
return crc;
}
First answer on SO.
I have encountered the same problem and found @alex 's code very helpful. I have made some simple modifications in order to pass in as many parameters as needed through HashMap, and have basically copied parseNetworkResponse()
from StringRequest. I have searched online and so surprised to find out that such a common task is so rarely answered. Anyway, I wish the code could help:
public class MultipartRequest extends Request<String> {
private MultipartEntity entity = new MultipartEntity();
private static final String FILE_PART_NAME = "image";
private final Response.Listener<String> mListener;
private final File file;
private final HashMap<String, String> params;
public MultipartRequest(String url, Response.Listener<String> listener, Response.ErrorListener errorListener, File file, HashMap<String, String> params)
{
super(Method.POST, url, errorListener);
mListener = listener;
this.file = file;
this.params = params;
buildMultipartEntity();
}
private void buildMultipartEntity()
{
entity.addPart(FILE_PART_NAME, new FileBody(file));
try
{
for ( String key : params.keySet() ) {
entity.addPart(key, new StringBody(params.get(key)));
}
}
catch (UnsupportedEncodingException e)
{
VolleyLog.e("UnsupportedEncodingException");
}
}
@Override
public String getBodyContentType()
{
return entity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try
{
entity.writeTo(bos);
}
catch (IOException e)
{
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
/**
* copied from Android StringRequest class
*/
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
@Override
protected void deliverResponse(String response)
{
mListener.onResponse(response);
}
And you may use the class as following:
HashMap<String, String> params = new HashMap<String, String>();
params.put("type", "Some Param");
params.put("location", "Some Param");
params.put("contact", "Some Param");
MultipartRequest mr = new MultipartRequest(url, new Response.Listener<String>(){
@Override
public void onResponse(String response) {
Log.d("response", response);
}
}, new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley Request Error", error.getLocalizedMessage());
}
}, f, params);
Volley.newRequestQueue(this).add(mr);
The approach that I used for a modal presented view controller was to check the class of the presented controller. If the presented view controller was ViewController2
then I would execute some code.
UIViewController *vc = [self presentedViewController];
if ([vc isKindOfClass:[ViewController2 class]]) {
NSLog(@"this is VC2");
}
All the answers provide sufficient details to the question. However, let me add something more.
Why are we using these Interfaces:
Which interface does what:
When to use which interface:
According to http://jtuts.com/2014/08/26/difference-between-crudrepository-and-jparepository-in-spring-data-jpa/
Generally the best idea is to use CrudRepository or PagingAndSortingRepository depending on whether you need sorting and paging or not.
The JpaRepository should be avoided if possible, because it ties you repositories to the JPA persistence technology, and in most cases you probably wouldn’t even use the extra methods provided by it.
In general you put your translations in resource files, e.g. resources.resx.
Each specific culture has a different name, e.g. resources.nl.resx, resources.fr.resx, resources.de.resx, …
Now the most important part of a solution is to maintain your translations. In Visual Studio install the Microsoft MAT tool: Multilingual App Toolkit (MAT). Works with winforms, wpf, asp.net (core), uwp, …
In general, e.g. for a WPF solution, in the WPF project
[assembly: System.Resources.NeutralResourcesLanguage("en")]
What you will see is that a new folder will be created, called "MultilingualResources" containing a ....nl.xlf
file.
The only thing you now have to do is:
(the .xlf files should open with the "Multilingual Editor", if this is not the case, right mouse click on the .xlf file, select "Open With…" and select "Multilingual Editor".
Have fun! now you can also see what has not been translated, export translations in xlf to external translation companies, import them again, recycle translations from other projects etc...
More info:
You can use the maven-shade-plugin.
After configuring the shade plugin in your build the command mvn package
will create one single jar with all dependencies merged into it.
The most simple way is to use Record type Record<number, productDetails >
interface productDetails {
productId : number ,
price : number ,
discount : number
};
const myVar : Record<number, productDetails> = {
1: {
productId : number ,
price : number ,
discount : number
}
}
If you have standart output redirect to "nohup.out" just see who use this file
lsof | grep nohup.out
For input and button:
$('button').prop('disabled', true);
For anchor:
$('a').attr('disabled', true);
Checked in firefox, chrome.
#include <stdio.h>
#include <math.h>
/*
To define a new type name with typedef, follow these steps:
1. Write the statement as if a variable of the desired type were being declared.
2. Where the name of the declared variable would normally appear, substitute the new type name.
3. In front of everything, place the keyword typedef.
*/
// typedef a primitive data type
typedef double distance;
// typedef struct
typedef struct{
int x;
int y;
} point;
//typedef an array
typedef point points[100];
points ps = {0}; // ps is an array of 100 point
// typedef a function
typedef distance (*distanceFun_p)(point,point) ; // TYPE_DEF distanceFun_p TO BE int (*distanceFun_p)(point,point)
// prototype a function
distance findDistance(point, point);
int main(int argc, char const *argv[])
{
// delcare a function pointer
distanceFun_p func_p;
// initialize the function pointer with a function address
func_p = findDistance;
// initialize two point variables
point p1 = {0,0} , p2 = {1,1};
// call the function through the pointer
distance d = func_p(p1,p2);
printf("the distance is %f\n", d );
return 0;
}
distance findDistance(point p1, point p2)
{
distance xdiff = p1.x - p2.x;
distance ydiff = p1.y - p2.y;
return sqrt( (xdiff * xdiff) + (ydiff * ydiff) );
}
For anyone interested, I ran into this same issue when using css modules and react css modules.
Most components have an associated css module style, and in this example my Button has its own css file, as does the Promo parent component. But I want to pass some additional styles to Button from Promo
So the style
able Button looks like this:
Button.js
import React, { Component } from 'react'
import CSSModules from 'react-css-modules'
import styles from './Button.css'
class Button extends Component {
render() {
let button = null,
className = ''
if(this.props.className !== undefined){
className = this.props.className
}
button = (
<button className={className} styleName='button'>
{this.props.children}
</button>
)
return (
button
);
}
};
export default CSSModules(Button, styles, {allowMultiple: true} )
In the above Button component the Button.css styles handle the common button styles. In this example just a .button
class
Then in my component where I want to use the Button, and I also want to modify things like the position of the button, I can set extra styles in Promo.css
and pass through as the className
prop. In this example again called .button
class. I could have called it anything e.g. promoButton
.
Of course with css modules this class will be .Promo__button___2MVMD
whereas the button one will be something like .Button__button___3972N
Promo.js
import React, { Component } from 'react';
import CSSModules from 'react-css-modules';
import styles from './Promo.css';
import Button from './Button/Button'
class Promo extends Component {
render() {
return (
<div styleName='promo' >
<h1>Testing the button</h1>
<Button className={styles.button} >
<span>Hello button</span>
</Button>
</div>
</Block>
);
}
};
export default CSSModules(Promo, styles, {allowMultiple: true} );
Thanks to dee for the answer above with the Scrape() subroutine. The code worked perfectly as written, and I was able to then convert the code to work with the specific website I am trying to scrape.
I do not have enough reputation to upvote or to comment, but I do actually have some minor improvements to add to dee's answer:
You will need to add the VBA Reference via "Tools\References" to "Microsoft HTML Object Library in order for the code to compile.
I commented out the Browser.Visible line and added the comment as follows
'if you need to debug the browser page, uncomment this line:
'Browser.Visible = True
And I added a line to close the browser before Set Browser = Nothing:
Browser.Quit
Thanks again dee!
ETA: this works on machines with IE9, but not machines with IE8. Anyone have a fix?
Found the fix myself, so came back here to post it. The ClassName function is available in IE9. For this to work in IE8, you use querySelectorAll, with a dot preceding the class name of the object you are looking for:
'Set repList = doc.getElementsByClassName("reportList") 'only works in IE9, not in IE8
Set repList = doc.querySelectorAll(".reportList") 'this works in IE8+
This happens because in r6 it shows an error when you try to extend private styles.
Refer to this link
Here's a flowchart based on this answer. See also, using script
to emulate a terminal.
SWIFT 4 Update
@IBOutlet weak var tripDetails: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(GameViewController.tapFunction))
tripDetails.isUserInteractionEnabled = true
tripDetails.addGestureRecognizer(tap)
}
@objc func tapFunction(sender:UITapGestureRecognizer) {
print("tap working")
}
Maybe powershell -Command "Get-AppLockerFileInformation....."
Take a look at powershell /?
JMF was abandoned. VLC is more up to date and it reads everything. https://stackoverflow.com/a/5160010
I think vlc beats every other software out there yet, or at least the ones that I know...
The simplest solution would be to keep track of the item size and the number of items, and then create a buffer of the appropriate number of bytes:
typedef struct circular_buffer
{
void *buffer; // data buffer
void *buffer_end; // end of data buffer
size_t capacity; // maximum number of items in the buffer
size_t count; // number of items in the buffer
size_t sz; // size of each item in the buffer
void *head; // pointer to head
void *tail; // pointer to tail
} circular_buffer;
void cb_init(circular_buffer *cb, size_t capacity, size_t sz)
{
cb->buffer = malloc(capacity * sz);
if(cb->buffer == NULL)
// handle error
cb->buffer_end = (char *)cb->buffer + capacity * sz;
cb->capacity = capacity;
cb->count = 0;
cb->sz = sz;
cb->head = cb->buffer;
cb->tail = cb->buffer;
}
void cb_free(circular_buffer *cb)
{
free(cb->buffer);
// clear out other fields too, just to be safe
}
void cb_push_back(circular_buffer *cb, const void *item)
{
if(cb->count == cb->capacity){
// handle error
}
memcpy(cb->head, item, cb->sz);
cb->head = (char*)cb->head + cb->sz;
if(cb->head == cb->buffer_end)
cb->head = cb->buffer;
cb->count++;
}
void cb_pop_front(circular_buffer *cb, void *item)
{
if(cb->count == 0){
// handle error
}
memcpy(item, cb->tail, cb->sz);
cb->tail = (char*)cb->tail + cb->sz;
if(cb->tail == cb->buffer_end)
cb->tail = cb->buffer;
cb->count--;
}
I had run into a similar issue with terminal not updating the java version to match the version installed on the mac.
There was no issue with the JAVA_HOME environmental variable being set
I have come up with a temporary and somewhat painful but working solution.
In you .bash_profile add the line:
export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_11.jdk/Contents/Home"
(This is the path on my machine but may be different on yours, make sure to get yours. The paths should match up to /Library/Java/JavaVirtualMachines/)
the run source ~/.bash_profile
As I mentioned this is a temporary band-aid solution because the java home path is being hard-coded. There is really no way to set the path to get the latest as that is what Apple is supposedly doing for terminal already and the issue is that Apple's java_home environment variable is not getting updated.
This is an old post, but here is my solution :
Thread.currentThread().dumpStack();
More info and more methods there : http://javarevisited.blogspot.fr/2013/04/how-to-get-current-stack-trace-in-java-thread.html
^\d+(()|(\.\d+)?)$
Came up with this. Allows both integer and decimal, but forces a complete decimal (leading and trailing numbers) if you decide to enter a decimal.
You don't have to create an empty view for this.
In the controller:
if (Request.IsAjaxRequest())
return PartialView();
else
return View();
returning a PartialViewResult will override the layout definition when rendering the respons.
Note that if you want to comment out a single line of printing erb you should do like this
<%#= ["Buck", "Papandreou"].join(" you ") %>
If you also want the ability to work with arbitrary json including nested lists and dicts, and nicely handle invalid lookup paths, here's my solution:
from functools import reduce
def get_furthest(s, path):
'''
Gets the furthest value along a given key path in a subscriptable structure.
subscriptable, list -> any
:param s: the subscriptable structure to examine
:param path: the lookup path to follow
:return: a tuple of the value at the furthest valid key, and whether the full path is valid
'''
def step_key(acc, key):
s = acc[0]
if isinstance(s, str):
return (s, False)
try:
return (s[key], acc[1])
except LookupError:
return (s, False)
return reduce(step_key, path, (s, True))
def get_val(s, path):
val, successful = get_furthest(s, path)
if successful:
return val
else:
raise LookupError('Invalid lookup path: {}'.format(path))
def set_val(s, path, value):
get_val(s, path[:-1])[path[-1]] = value
In many cases an element must be positioned for z-index
to work.
Indeed, applying position: relative
to the elements in the question would likely solve the problem (but there's not enough code provided to know for sure).
Actually, position: fixed
, position: absolute
and position: sticky
will also enable z-index
, but those values also change the layout. With position: relative
the layout isn't disturbed.
Essentially, as long as the element isn't position: static
(the default setting) it is considered positioned and z-index
will work.
Many answers to "Why isn't z-index working?" questions assert that z-index
only works on positioned elements. As of CSS3, this is no longer true.
Elements that are flex items or grid items can use z-index
even when position
is static
.
From the specs:
Flex items paint exactly the same as inline blocks, except that order-modified document order is used in place of raw document order, and
z-index
values other thanauto
create a stacking context even ifposition
isstatic
.5.4. Z-axis Ordering: the
z-index
propertyThe painting order of grid items is exactly the same as inline blocks, except that order-modified document order is used in place of raw document order, and
z-index
values other thanauto
create a stacking context even ifposition
isstatic
.
Here's a demonstration of z-index
working on non-positioned flex items: https://jsfiddle.net/m0wddwxs/
Since awk and perl are closely related...
Perl equivalents of @Dennis's awk solutions:
To print the second line:
perl -ne 'print if $. == 2' file
To print the second field:
perl -lane 'print $F[1]' file
To print the third field of the fifth line:
perl -lane 'print $F[2] if $. == 5' file
Perl equivalent of @Glenn's solution:
Print the j'th field of the i'th line
perl -lanse 'print $F[$j-1] if $. == $i' -- -i=5 -j=3 file
Perl equivalents of @Hai's solutions:
if you are looking for second columns that contains abc:
perl -lane 'print if $F[1] =~ /abc/' foo
... and if you want to print only a particular column:
perl -lane 'print $F[2] if $F[1] =~ /abc/' foo
... and for a particular line number:
perl -lane 'print $F[2] if $F[1] =~ /abc/ && $. == 5' foo
-l
removes newlines, and adds them back in when printing
-a
autosplits the input line into array @F
, using whitespace as the delimiter
-n
loop over each line of the input file
-e
execute the code within quotes
$F[1]
is the second element of the array, since Perl starts at 0
$.
is the line number
From the MySql site.
Starting with version 6.7, Connector/Net will no longer include the MySQL for Visual Studio integration. That functionality is now available in a separate product called MySQL for Visual Studio available using the MySQL Installer for Windows (see http://dev.mysql.com/tech-resources/articles/mysql-installer-for-windows.html).
This is very simple you are trying to convert an integer to a list object !!! of course it will fail and it should ...
To demonstrate/prove this to you by using the example you provided ...just use type function for each case as below and the results will speak for itself !
>>> type(cow)
<class 'range'>
>>>
>>> type(cow[0])
<class 'int'>
>>>
>>> type(0)
<class 'int'>
>>>
>>> >>> list(0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>>
In addition to some of the other answers, you could also access the HTML element via:
var htmlEl = document.body.parentNode;
Then you could get the inner HTML content:
var inner = htmlEl.innerHTML;
Doing so this way seems to be marginally faster. If you are just obtaining the HTML element, however, document.body.parentNode
seems to be quite a bit faster.
After you have the HTML element, you can mess with the attributes with the getAttribute
and setAttribute
methods.
For the DOCTYPE, you could use document.doctype
, which was elaborated upon in this question.
create a class create a object globally and call this
using System.IO;
using System.Reflection;
public class LogWriter
{
private string m_exePath = string.Empty;
public LogWriter(string logMessage)
{
LogWrite(logMessage);
}
public void LogWrite(string logMessage)
{
m_exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
try
{
using (StreamWriter w = File.AppendText(m_exePath + "\\" + "log.txt"))
{
Log(logMessage, w);
}
}
catch (Exception ex)
{
}
}
public void Log(string logMessage, TextWriter txtWriter)
{
try
{
txtWriter.Write("\r\nLog Entry : ");
txtWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
DateTime.Now.ToLongDateString());
txtWriter.WriteLine(" :");
txtWriter.WriteLine(" :{0}", logMessage);
txtWriter.WriteLine("-------------------------------");
}
catch (Exception ex)
{
}
}
}
Laravel Framework 5.6.26
return more than one array then we use compact('array1', 'array2', 'array3', ...)
to return view.
viewblade
is the frontend (view) blade.
return view('viewblade', compact('view1','view2','view3','view4'));
A pure JavaScript solution ought to be offered as well, as the solution is not difficult:
var a = [].filter.call(el.attributes, function(at) { return /^data-/.test(at.name); });
This gives an array of attribute objects, which have name
and value
properties:
if (a.length) {
var firstAttributeName = a[0].name;
var firstAttributeValue = a[0].value;
}
Edit: To take it a step further, you can get a dictionary by iterating the attributes and populating a data object:
var data = {};
[].forEach.call(el.attributes, function(attr) {
if (/^data-/.test(attr.name)) {
var camelCaseName = attr.name.substr(5).replace(/-(.)/g, function ($0, $1) {
return $1.toUpperCase();
});
data[camelCaseName] = attr.value;
}
});
You could then access the value of, for example, data-my-value="2"
as data.myValue
;
Edit: If you wanted to set data attributes on your element programmatically from an object, you could:
Object.keys(data).forEach(function(key) {
var attrName = "data-" + key.replace(/[A-Z]/g, function($0) {
return "-" + $0.toLowerCase();
});
el.setAttribute(attrName, data[key]);
});
EDIT: If you are using babel or TypeScript, or coding only for es6 browsers, this is a nice place to use es6 arrow functions, and shorten the code a bit:
var a = [].filter.call(el.attributes, at => /^data-/.test(at.name));
axios.get
accepts a request config as the second parameter (not query string params).
You can use the params
config option to set query string params as follows:
axios.get('/api', {
params: {
foo: 'bar'
}
});
Just add use of origin in your if you use node.js as server...
like this
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
We Need response for origin
You can use the CSS property word-wrap:break-word;
, which will break words if they are too long for your span width.
span { _x000D_
display:block;_x000D_
width:150px;_x000D_
word-wrap:break-word;_x000D_
}
_x000D_
<span>VeryLongLongLongLongLongLongLongLongLongLongLongLongExample</span>
_x000D_
Is there a particular reason you have chosen XML config files? I have done XML configs in the past, and they have often turned out to be more of a headache than anything else.
I guess the real question is whether using something like the Preferences API might work better in your situation.
Reasons to use the Preferences API over a roll-your-own XML solution:
Avoids typical XML ugliness (DocumentFactory, etc), along with avoiding 3rd party libraries to provide the XML backend
Built in support for default values (no special handling required for missing/corrupt/invalid entries)
No need to sanitize values for XML storage (CDATA wrapping, etc)
Guaranteed status of the backing store (no need to constantly write XML out to disk)
Backing store is configurable (file on disk, LDAP, etc.)
Multi-threaded access to all preferences for free
By default, Maven doesn't bundle dependencies in the JAR file it builds, and you're not providing them on the classpath when you're trying to execute your JAR file at the command-line. This is why the Java VM can't find the library class files when trying to execute your code.
You could manually specify the libraries on the classpath with the -cp
parameter, but that quickly becomes tiresome.
A better solution is to "shade" the library code into your output JAR file. There is a Maven plugin called the maven-shade-plugin to do this. You need to register it in your POM, and it will automatically build an "uber-JAR" containing your classes and the classes for your library code too when you run mvn package
.
To simply bundle all required libraries, add the following to your POM:
<project>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
...
</project>
Once this is done, you can rerun the commands you used above:
$ mvn package
$ java -cp target/bil138_4-0.0.1-SNAPSHOT.jar tr.edu.hacettepe.cs.b21127113.bil138_4.App
If you want to do further configuration of the shade plugin in terms of what JARs should be included, specifying a Main-Class for an executable JAR file, and so on, see the "Examples" section on the maven-shade-plugin site.
The oracle limit is 1000 parameters. The issue has been resolved by hibernate in version 4.1.7 although by splitting the passed parameter list in sets of 500 see JIRA HHH-1123
This is a useful article which graphically shows the explanation of the reset command.
https://git-scm.com/docs/git-reset
Reset --hard can be quite dangerous as it overwrites your working copy without checking, so if you haven't commited the file at all, it is gone.
As for Source tree, there is no way I know of to undo commits. It would most likely use reset under the covers anyway
A vb version
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
For saleAMT As Decimal = 0.01D To 0.99D Step 0.01D
Dim foo As New CashDrawer(0, 0, 0)
Dim chg As List(Of Money) = foo.MakeChange(saleAMT, 1D)
Dim t As Decimal = 1 - saleAMT
Debug.WriteLine(t.ToString("C2"))
For Each c As Money In chg
Debug.WriteLine(String.Format("{0} of {1}", c.Count.ToString("N0"), c.moneyValue.ToString("C2")))
Next
Next
End Sub
Class CashDrawer
Private _drawer As List(Of Money)
Public Sub New(Optional ByVal QTYtwoD As Integer = -1, _
Optional ByVal QTYoneD As Integer = -1, _
Optional ByVal QTYfifty As Integer = -1, _
Optional ByVal QTYquarters As Integer = -1, _
Optional ByVal QTYdimes As Integer = -1, _
Optional ByVal QTYnickels As Integer = -1, _
Optional ByVal QTYpennies As Integer = -1)
_drawer = New List(Of Money)
_drawer.Add(New Money(2D, QTYtwoD))
_drawer.Add(New Money(1D, QTYoneD))
_drawer.Add(New Money(0.5D, QTYfifty))
_drawer.Add(New Money(0.25D, QTYquarters))
_drawer.Add(New Money(0.1D, QTYdimes))
_drawer.Add(New Money(0.05D, QTYnickels))
_drawer.Add(New Money(0.01D, QTYpennies))
End Sub
Public Function MakeChange(ByVal SaleAmt As Decimal, _
ByVal amountTendered As Decimal) As List(Of Money)
Dim change As Decimal = amountTendered - SaleAmt
Dim rv As New List(Of Money)
For Each c As Money In Me._drawer
change -= (c.NumberOf(change) * c.moneyValue)
If c.Count > 0 Then
rv.Add(c)
End If
Next
If change <> 0D Then Throw New ArithmeticException
Return rv
End Function
End Class
Class Money
'-1 equals unlimited qty
Private _qty As Decimal 'quantity in drawer
Private _value As Decimal 'value money
Private _count As Decimal = 0D
Public Sub New(ByVal theValue As Decimal, _
ByVal theQTY As Decimal)
Me._value = theValue
Me._qty = theQTY
End Sub
ReadOnly Property moneyValue As Decimal
Get
Return Me._value
End Get
End Property
Public Function NumberOf(ByVal theAmount As Decimal) As Decimal
If (Me._qty > 0 OrElse Me._qty = -1) AndAlso Me._value <= theAmount Then
Dim ct As Decimal = Math.Floor(theAmount / Me._value)
If Me._qty <> -1D Then 'qty?
'limited qty
If ct > Me._qty Then 'enough
'no
Me._count = Me._qty
Me._qty = 0D
Else
'yes
Me._count = ct
Me._qty -= ct
End If
Else
'unlimited qty
Me._count = ct
End If
End If
Return Me._count
End Function
ReadOnly Property Count As Decimal
Get
Return Me._count
End Get
End Property
End Class
End Class
Notice another equivalent problem: Creating an SQL query that returns (1) if the condition is satisfied and an empty result otherwise. Notice that a solution to this problem is more general and can easily be used with the above answers to achieve the question that you asked. Since this problem is more general, I am proving its solution in addition to the beautiful solutions presented above to your problem.
SELECT DISTINCT 1 AS Expr1
FROM [User]
WHERE (UserID = 20070022)
To follow the example given here, but to clarify syntax with the use of header files, the function forward declaration contains the optional parameter default value.
myfile.h
void myfunc(int blah, int mode = 0);
myfile.cpp
void myfunc(int blah, int mode) /* mode = 0 */
{
if (mode == 0)
do_something();
else
do_something_else();
}
The &
makes the command run in the background.
From man bash
:
If a command is terminated by the control operator &, the shell executes the command in the background in a subshell. The shell does not wait for the command to finish, and the return status is 0.
font/woff2
For nginx add the following to the mime.types
file:
font/woff2 woff2;
Old Answer
The mime type (sometime written as mimetype) for WOFF2 fonts has been proposed as application/font-woff2
.
Also, if you refer to the spec (http://dev.w3.org/webfonts/WOFF2/spec/) you will see that font/woff2
is being discussed. I suspect that the filal mime type for all fonts will eventually be the more logical font/*
(font/ttf
, font/woff2
etc)...
N.B. WOFF2 is still in 'Working Draft' status -- not yet adopted officially.
If you are building UI without drag and drop (without using storyboard) and want to navigate default page or ViewController.swift to another page? Follow these steps 1) add a class (.swift) 2) Import UIKit 3) Declare class name like
class DemoNavigationClass :UIViewController{
override func viewDidLoad(){
let lbl_Hello = UILabel(frame: CGRect(x:self.view.frame.width/3, y:self.view.frame.height/2, 200, 30));
lbl_Hello.text = "You are on Next Page"
lbl_Hello.textColor = UIColor.white
self.view.addSubview(lbl_Hello)
}
}
after creating second page come back to first page (ViewController.swift) Here make a button in viewDidLoad method
let button = UIButton()
button.frame = (frame: CGRect(x: self.view.frame.width/3, y: self.view.frame.height/1.5, width: 200, height: 50))
button.backgroundColor = UIColor.red
button.setTitle("Go to Next ", for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
self.view.addSubview(button)
now define buttonAction method outside of viewDidLoad() in same class
func buttonAction(sender: UIButton!)
{
let obj : DemoNavigationClass = DemoNavigationClass();
self.navigationController?.pushViewController(obj, animated: true)
}
Keep one thing that i forget in main.storyboard there is a scene with a arrow, select that arrow and press delete button
now drag and drop a navigationcontroller and delete tableview which comes with navaigation controller. select navigationcontroller press control on keyboard and drag it in to another scene on storyboard that is ViewController. This mean that your viewcontroller become root viewcontroller hope this help you Thanks in main.storyboard , drag and drop navigationcontroller,
Just get the position of the last character occurrence.
for(String serverId : serverIds) {
sb.append(serverId);
sb.append(",");
}
sb.deleteCharAt(sb.lastIndexOf(","));
Since lastIndexOf
will perform a reverse search, and you know that it will find at the first try, performance won't be an issue here.
EDIT
Since I keep getting ups on my answer (thanks folks ), it is worth regarding that:
On Java 8 onward it would just be more legible and explicit to use StringJoiner. It has one method for a simple separator, and an overload for prefix and suffix.
Examples taken from here: example
Example using simple separator:
StringJoiner mystring = new StringJoiner("-"); // Joining multiple strings by using add() method mystring.add("Logan"); mystring.add("Magneto"); mystring.add("Rogue"); mystring.add("Storm"); System.out.println(mystring);
Output:
Logan-Magneto-Rogue-Storm
Example with suffix and prefix:
StringJoiner mystring = new StringJoiner(",", "(", ")"); // Joining multiple strings by using add() method mystring.add("Negan"); mystring.add("Rick"); mystring.add("Maggie"); mystring.add("Daryl"); System.out.println(mystring);
Output
(Negan,Rick,Maggie,Daryl)
If you're just using a vanilla form (not a ModelForm), you can set a Field initial value ( https://docs.djangoproject.com/en/2.2/ref/forms/fields/#django.forms.Field.initial ) like
class MyForm(forms.Form):
my_field = forms.BooleanField(initial=True)
If you're using a ModelForm, you can set a default value on the model field ( https://docs.djangoproject.com/en/2.2/ref/models/fields/#default ), which will apply to the resulting ModelForm, like
class MyModel(models.Model):
my_field = models.BooleanField(default=True)
Finally, if you want to dynamically choose at runtime whether or not your field will be selected by default, you can use the initial parameter to the form when you initialize it:
form = MyForm(initial={'my_field':True})
The DLL must be present at all times - as the name indicates, a reference only tells VS that you're trying to use stuff from the DLL. In the project file, VS stores the actual path and file name of the referenced DLL. If you move or delete it, VS is not able to find it anymore.
I usually create a libs
folder within my project's folder where I copy DLLs that are not installed to the GAC. Then, I actually add this folder to my project in VS (show hidden files in VS, then right-click and "Include in project"). I then reference the DLLs from the folder, so when checking into source control, the library is also checked in. This makes it much easier when more than one developer will have to change the project.
(Please make sure to set the build type to "none" and "don't copy to output folder" for the DLL in your project.)
PS: I use a German Visual Studio, so the captions I quoted may not exactly match the English version...
I have a shared hosting on GoDaddy. I needed an answer to this question, too, and after searching around I found that it is possible.
I wrote an .htaccess file, put it in the same folder as my action page. Here are the contents of the .htaccess file:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
Here is my ajax call:
$.ajax({
url: 'http://www.mydomain.com/myactionpagefolder/gbactionpage.php', //server script to process data
type: 'POST',
xhr: function() { // custom xhr
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
}
return myXhr;
},
//Ajax events
beforeSend: beforeSendHandler,
success: completeHandler,
error: errorHandler,
// Form data
data: formData,
//Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false
});
See this article for reference:
Header set Access-Control-Allow-Origin in .htaccess doesn't work
Actually, using the converter like that breaks two-way binding, plus as I said above, you can't use that with enumerations either. The better way to do this is with a simple style against a ListBox, like this:
Note: Contrary to what DrWPF.com stated in their example, do not put the ContentPresenter inside the RadioButton or else if you add an item with content such as a button or something else, you will not be able to set focus or interact with it. This technique solves that. Also, you need to handle the graying of the text as well as removing of margins on labels or else it will not render correctly. This style handles both for you as well.
<Style x:Key="RadioButtonListItem" TargetType="{x:Type ListBoxItem}" >
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<DockPanel LastChildFill="True" Background="{TemplateBinding Background}" HorizontalAlignment="Stretch" VerticalAlignment="Center" >
<RadioButton IsChecked="{TemplateBinding IsSelected}" Focusable="False" IsHitTestVisible="False" VerticalAlignment="Center" Margin="0,0,4,0" />
<ContentPresenter
Content = "{TemplateBinding ContentControl.Content}"
ContentTemplate = "{TemplateBinding ContentControl.ContentTemplate}"
ContentStringFormat = "{TemplateBinding ContentControl.ContentStringFormat}"
HorizontalAlignment = "{TemplateBinding Control.HorizontalContentAlignment}"
VerticalAlignment = "{TemplateBinding Control.VerticalContentAlignment}"
SnapsToDevicePixels = "{TemplateBinding UIElement.SnapsToDevicePixels}" />
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="RadioButtonList" TargetType="ListBox">
<Style.Resources>
<Style TargetType="Label">
<Setter Property="Padding" Value="0" />
</Style>
</Style.Resources>
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="ItemContainerStyle" Value="{StaticResource RadioButtonListItem}" />
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBox}">
<ItemsPresenter SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="TextBlock.Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" />
</Trigger>
</Style.Triggers>
</Style>
<Style x:Key="HorizontalRadioButtonList" BasedOn="{StaticResource RadioButtonList}" TargetType="ListBox">
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<VirtualizingStackPanel Background="Transparent" Orientation="Horizontal" />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
</Style>
You now have the look and feel of radio buttons, but you can do two-way binding, and you can use an enumeration. Here's how...
<ListBox Style="{StaticResource RadioButtonList}"
SelectedValue="{Binding SomeVal}"
SelectedValuePath="Tag">
<ListBoxItem Tag="{x:Static l:MyEnum.SomeOption}" >Some option</ListBoxItem>
<ListBoxItem Tag="{x:Static l:MyEnum.SomeOtherOption}">Some other option</ListBoxItem>
<ListBoxItem Tag="{x:Static l:MyEnum.YetAnother}" >Yet another option</ListBoxItem>
</ListBox>
Also, since we explicitly separated out the style that tragets the ListBoxItem rather than putting it inline, again as the other examples have shown, you can now create a new style off of it to customize things on a per-item basis such as spacing. (This will not work if you simply try to target ListBoxItem as the keyed style overrides generic control targets.)
Here's an example of putting a margin of 6 above and below each item. (Note how you have to explicitly apply the style via the ItemContainerStyle property and not simply targeting ListBoxItem in the ListBox's resource section for the reason stated above.)
<Window.Resources>
<Style x:Key="SpacedRadioButtonListItem" TargetType="ListBoxItem" BasedOn="{StaticResource RadioButtonListItem}">
<Setter Property="Margin" Value="0,6" />
</Style>
</Window.Resources>
<ListBox Style="{StaticResource RadioButtonList}"
ItemContainerStyle="{StaticResource SpacedRadioButtonListItem}"
SelectedValue="{Binding SomeVal}"
SelectedValuePath="Tag">
<ListBoxItem Tag="{x:Static l:MyEnum.SomeOption}" >Some option</ListBoxItem>
<ListBoxItem Tag="{x:Static l:MyEnum.SomeOtherOption}">Some other option</ListBoxItem>
<ListBoxItem Tag="{x:Static l:MyEnum.YetAnother}" >Ter another option</ListBoxItem>
</ListBox>
You are supposed to download the jar files that contain these libraries. Libraries may be used by adding them to the classpath.
For Commons Net you need to download the binary files from Commons Net download page. Then you have to extract the file and add the commons-net-2-2.jar file to some location where you can access it from your application e.g. to /lib.
If you're running your application from the command-line you'll have to define the classpath in the java command: java -cp .;lib/commons-net-2-2.jar myapp
. More info about how to set the classpath can be found from Oracle documentation. You must specify all directories and jar files you'll need in the classpath excluding those implicitely provided by the Java runtime. Notice that there is '.' in the classpath, it is used to include the current directory in case your compiled class is located in the current directory.
For more advanced reading, you might want to read about how to define the classpath for your own jar files, or the directory structure of a war file when you're creating a web application.
If you are using an IDE, such as Eclipse, you have to remember to add the library to your build path before the IDE will recognize it and allow you to use the library.
Just in case you want to something like:
echo date('G \h\o\u\r\s i \m\i\n\u\t\e\s', mktime(0, 90)); //will return 1 hours 30 minutes
echo date('G \j\a\m i \m\e\n\i\t', mktime(0, 90)); //will return 1 jam 30 menit
I think that I remember looking at a performance comparison between int.TryParse and int.Parse Regex and char.IsNumber and char.IsNumber was fastest. At any rate, whatever the performance, here's one more way to do it.
bool isNumeric = true;
foreach (char c in "12345")
{
if (!Char.IsNumber(c))
{
isNumeric = false;
break;
}
}
The app can't be run natively, but it could be run on an emulator. You can use ManyMo to embed them in a website and make users add your app to their home screen. This link should be useful for making the app more realistic. Users could then only press the share button and add the app to their home screen. All data will be deleted when the "app" is closed in their iOS devices so you should use the Internet/cloud for storage. It can't access camera or multi touch, but it may be useful.
Try out following:
SELECT *
FROM
(SELECT rownum AS rn,
a.*
FROM
(WITH DATA AS -- creating dummy data
( SELECT 'MOHAN' AS NAME, 200 AS SALARY FROM DUAL
UNION ALL
SELECT 'AKSHAY' AS NAME, 500 AS SALARY FROM DUAL
UNION ALL
SELECT 'HARI' AS NAME, 300 AS SALARY FROM DUAL
UNION ALL
SELECT 'RAM' AS NAME, 400 AS SALARY FROM DUAL
)
SELECT D.* FROM DATA D ORDER BY SALARY DESC
) A
)
WHERE rn = 3; -- specify N'th highest here (In this case fetching 3'rd highest)
Cheers!
Turgut gave the right solution. Just for clarity, you need to add close after writing.
function openWin()
{
myWindow=window.open('','','width=200,height=100');
myWindow.document.write("<p>This is 'myWindow'</p>");
myWindow.document.close(); //missing code
myWindow.focus();
myWindow.print();
}
In your Model Class add a json property annotation, also have a default constructor
@JsonProperty("user_name")
private String userName;
@JsonProperty("first_name")
private String firstName;
@JsonProperty("last_name")
private String lastName;
This works in Ubuntu
Type this to find out the PID
ps aux | grep java
All the running process regarding to java will be shown
In my case is
johnjoe 3315 9.1 4.0 1465240 335728 ? Sl 09:42 3:19 java -jar batch.jar
Now kill it kill -9 3315
The zombie process finally stopped.
For those who want to do this in pure javascript, look at:
As Joe comment it, KeyboardEvent is now the standard.
Same example to fire an enter (keyCode 13):
const ke = new KeyboardEvent('keydown', {
bubbles: true, cancelable: true, keyCode: 13
});
document.body.dispatchEvent(ke);
You can use this page help you to find the right keyboard event.
Outdated answer:
You can do something like (here for Firefox)
var ev = document.createEvent('KeyboardEvent');
// Send key '13' (= enter)
ev.initKeyEvent(
'keydown', true, true, window, false, false, false, false, 13, 0);
document.body.dispatchEvent(ev);
You can use the null coalescing double question marks to test for nulls in a string or other nullable value type:
textBox1.Text = s ?? "Is null";
The operator '??' asks if the value of 's' is null and if not it returns 's'; if it is null it returns the value on the right of the operator.
More info here: https://msdn.microsoft.com/en-us/library/ms173224.aspx
And also worth noting there's a null-conditional operator ?. and ?[ introduced in C# 6.0 (and VB) in VS2015
textBox1.Text = customer?.orders?[0].description ?? "n/a";
This returns "n/a" if description is null, or if the order is null, or if the customer is null, else it returns the value of description.
More info here: https://msdn.microsoft.com/en-us/library/dn986595.aspx
No. Not like you have your code. There isn't any class named Boolean. Now with all the answers you have you should be able to create one and use it. You do know how to create classes don't you? I only came here because I was just wondering this idea myself. Many people might say "Why? You have to just know how Ruby uses Boolean". Which is why you got the answers you did. So thanks for the question. Food for thought. Why doesn't Ruby have a Boolean class?
NameError: uninitialized constant Boolean
Keep in mind that Objects do not have types. They are classes. Objects have data. So that's why when you say data types it's a bit of a misnomer.
Also try rand 2 because rand 1 seems to always give 0. rand 2 will give 1 or 0 click run a few times here. https://repl.it/IOPx/7
Although I wouldn't know how to go about making a Boolean class myself. I've experimented with it but...
class Boolean < TrueClass
self
end
true.is_a?(Boolean) # => false
false.is_a?(Boolean) # => false
At least we have that class now but who knows how to get the right values?
If you are using MacBook Pro (OS X) follow the following steps:
python > Preference > Syntax coloring
For iPhone and iPod touch, create icons that measure:
57 X 57 pixels
114 X 114 pixels (high resolution @2X)
For iPad, create an icon that measures:
72 x 72 pixels
144 X 144 pixels (high resolution @2X)
Stack frame is the packed information related to a function call. This information generally includes arguments passed to th function, local variables and where to return upon terminating. Activation record is another name for a stack frame. The layout of the stack frame is determined in the ABI by the manufacturer and every compiler supporting the ISA must conform to this standard, however layout scheme can be compiler dependent. Generally stack frame size is not limited but there is a concept called "red/protected zone" to allow system calls...etc to execute without interfering with a stack frame.
There is always a SP but on some ABIs (ARM's and PowerPC's for example) FP is optional. Arguments that needed to be placed onto the stack can be offsetted using the SP only. Whether a stack frame is generated for a function call or not depends on the type and number of arguments, local variables and how local variables are accessed generally. On most ISAs, first, registers are used and if there are more arguments than registers dedicated to pass arguments these are placed onto the stack (For example x86 ABI has 6 registers to pass integer arguments). Hence, sometimes, some functions do not need a stack frame to be placed on the stack, just the return address is pushed onto the stack.
There is a special method split
for struct String
:
fn split<'a, P>(&'a self, pat: P) -> Split<'a, P> where P: Pattern<'a>
Split by char:
let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
Split by string:
let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
assert_eq!(v, ["lion", "tiger", "leopard"]);
Split by closure:
let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_numeric()).collect();
assert_eq!(v, ["abc", "def", "ghi"]);
If it is inside some function why don't you just return it:
for (Type type : types) {
for (Type t : types2) {
if (some condition) {
return value;
}
}
}
It seems that k8s expects us to provide a different image tag for every deployment. My default strategy would be to make the CI system generate and push the docker images, tagging them with the build number: xpmatteo/foobar:456
.
For local development it can be convenient to use a script or a makefile, like this:
# create a unique tag
VERSION:=$(shell date +%Y%m%d%H%M%S)
TAG=xpmatteo/foobar:$(VERSION)
deploy:
npm run-script build
docker build -t $(TAG) .
docker push $(TAG)
sed s%IMAGE_TAG_PLACEHOLDER%$(TAG)% foobar-deployment.yaml | kubectl apply -f - --record
The sed
command replaces a placeholder in the deployment document with the actual generated image tag.
Updated with the theme()
function, ggsave()
and the code for the legend background:
df <- data.frame(y = d, x = 1, group = rep(c("gr1", "gr2"), 50))
p <- ggplot(df) +
stat_boxplot(aes(x = x, y = y, color = group),
fill = "transparent" # for the inside of the boxplot
)
Fastest way is using using rect
, as all the rectangle elements inherit from rect:
p <- p +
theme(
rect = element_rect(fill = "transparent") # all rectangles
)
p
More controlled way is to use options of theme
:
p <- p +
theme(
panel.background = element_rect(fill = "transparent"), # bg of the panel
plot.background = element_rect(fill = "transparent", color = NA), # bg of the plot
panel.grid.major = element_blank(), # get rid of major grid
panel.grid.minor = element_blank(), # get rid of minor grid
legend.background = element_rect(fill = "transparent"), # get rid of legend bg
legend.box.background = element_rect(fill = "transparent") # get rid of legend panel bg
)
p
To save (this last step is important):
ggsave(p, filename = "tr_tst2.png", bg = "transparent")
This is the reply I received from Github when I asked them to delete a pull request:
"Thanks for getting in touch! Pull requests can't be deleted through the UI at the moment and we'll only delete pull requests when they contain sensitive information like passwords or other credentials."
Let's use this example. Maybe you want the user of your website to know a field is valid or it needs attention by changing the background color of the field. If the user hits reset then your code should only reset the fields that have data and not bother to loop through every other field on your page.
This jQuery filter will remove the class "highlightCriteria" only for the input or select fields that have this class.
$form.find('input,select').filter(function () {
if((!!this.value) && (!!this.name)) {
$("#"+this.id).removeClass("highlightCriteria");
}
});
I solved this problem by using,
element.scrollIntoView({ behavior: 'smooth', block: 'center' });
This makes the element appear in the center
after scrolling, so I don't have to calculate yOffset
.
Hope it helps...
In the earlier answers weight is passed to the constructor of a new SomeLayoutType.LayoutParams object. Still in many cases it's more convenient to use existing objects - it helps to avoid dealing with parameters we are not interested in.
An example:
// Get our View (TextView or anything) object:
View v = findViewById(R.id.our_view);
// Get params:
LinearLayout.LayoutParams loparams = (LinearLayout.LayoutParams) v.getLayoutParams();
// Set only target params:
loparams.height = 0;
loparams.weight = 1;
v.setLayoutParams(loparams);
The only real difference between a vertical RecyclerView
and a horizontal one is how you set up the LinearLayoutManager
. Here is the code snippet. The full example is below.
LinearLayoutManager horizontalLayoutManagaer = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(horizontalLayoutManagaer);
This fuller example is modeled after my vertical RecyclerView
answer.
Make sure the following dependencies are in your app gradle.build
file:
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:recyclerview-v7:27.1.1'
You can update the version numbers to whatever is the most current.
Add the RecyclerView
to your xml layout.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/rvAnimals"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Each item in our RecyclerView
is going to have a single a colored View
over a TextView
. Create a new layout resource file.
recyclerview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp">
<View
android:id="@+id/colorView"
android:layout_width="100dp"
android:layout_height="100dp"/>
<TextView
android:id="@+id/tvAnimalName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"/>
</LinearLayout>
The RecyclerView
needs an adapter to populate the views in each row (horizontal item) with your data. Create a new java file.
MyRecyclerViewAdapter.java
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
private List<Integer> mViewColors;
private List<String> mAnimals;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
MyRecyclerViewAdapter(Context context, List<Integer> colors, List<String> animals) {
this.mInflater = LayoutInflater.from(context);
this.mViewColors = colors;
this.mAnimals = animals;
}
// inflates the row layout from xml when needed
@Override
@NonNull
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
return new ViewHolder(view);
}
// binds the data to the view and textview in each row
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
int color = mViewColors.get(position);
String animal = mAnimals.get(position);
holder.myView.setBackgroundColor(color);
holder.myTextView.setText(animal);
}
// total number of rows
@Override
public int getItemCount() {
return mAnimals.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
View myView;
TextView myTextView;
ViewHolder(View itemView) {
super(itemView);
myView = itemView.findViewById(R.id.colorView);
myTextView = itemView.findViewById(R.id.tvAnimalName);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
public String getItem(int id) {
return mAnimals.get(id);
}
// allows clicks events to be caught
public void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
Notes
ListViews
and is a common need. You can remove this code if you don't need it.Add the following code to your main activity.
MainActivity.java
public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
private MyRecyclerViewAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// data to populate the RecyclerView with
ArrayList<Integer> viewColors = new ArrayList<>();
viewColors.add(Color.BLUE);
viewColors.add(Color.YELLOW);
viewColors.add(Color.MAGENTA);
viewColors.add(Color.RED);
viewColors.add(Color.BLACK);
ArrayList<String> animalNames = new ArrayList<>();
animalNames.add("Horse");
animalNames.add("Cow");
animalNames.add("Camel");
animalNames.add("Sheep");
animalNames.add("Goat");
// set up the RecyclerView
RecyclerView recyclerView = findViewById(R.id.rvAnimals);
LinearLayoutManager horizontalLayoutManager
= new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(horizontalLayoutManager);
adapter = new MyRecyclerViewAdapter(this, viewColors, animalNames);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}
@Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on item position " + position, Toast.LENGTH_SHORT).show();
}
}
Notes
ItemClickListener
that we defined in our adapter. This allows us to handle item click events in onItemClick
.That's it. You should be able to run your project now and get something similar to the image at the top.
It looks to me as though the basic problem is that you have one wait()
call rather than a loop that waits until there are no more children. You also only wait if the last fork()
is successful rather than if at least one fork()
is successful.
You should only use _exit()
if you don't want normal cleanup operations - such as flushing open file streams including stdout
. There are occasions to use _exit()
; this is not one of them. (In this example, you could also, of course, simply have the children return instead of calling exit()
directly because returning from main()
is equivalent to exiting with the returned status. However, most often you would be doing the forking and so on in a function other than main()
, and then exit()
is often appropriate.)
Hacked, simplified version of your code that gives the diagnostics I'd want. Note that your for
loop skipped the first element of the array (mine doesn't).
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main(void)
{
pid_t child_pid, wpid;
int status = 0;
int i;
int a[3] = {1, 2, 1};
printf("parent_pid = %d\n", getpid());
for (i = 0; i < 3; i++)
{
printf("i = %d\n", i);
if ((child_pid = fork()) == 0)
{
printf("In child process (pid = %d)\n", getpid());
if (a[i] < 2)
{
printf("Should be accept\n");
exit(1);
}
else
{
printf("Should be reject\n");
exit(0);
}
/*NOTREACHED*/
}
}
while ((wpid = wait(&status)) > 0)
{
printf("Exit status of %d was %d (%s)\n", (int)wpid, status,
(status > 0) ? "accept" : "reject");
}
return 0;
}
Example output (MacOS X 10.6.3):
parent_pid = 15820
i = 0
i = 1
In child process (pid = 15821)
Should be accept
i = 2
In child process (pid = 15822)
Should be reject
In child process (pid = 15823)
Should be accept
Exit status of 15823 was 256 (accept)
Exit status of 15822 was 0 (reject)
Exit status of 15821 was 256 (accept)
In-Short Differences are
1) PCL is not going to have Full Access to .NET Framework , where as SharedProject has.
2) #ifdef for platform specific code - you can not write in PCL (#ifdef option isn’t available to you in a PCL because it’s compiled separately, as its own DLL, so at compile time (when the #ifdef is evaluated) it doesn’t know what platform it will be part of. ) where as Shared project you can.
3) Platform specific code is achieved using Inversion Of Control in PCL , where as using #ifdef statements you can achieve the same in Shared Project.
An excellent article which illustrates differences between PCL vs Shared Project can be found at the following link
http://hotkrossbits.com/2015/05/03/xamarin-forms-pcl-vs-shared-project/
You can use angular.extend(dest, src1, src2,...);
In your case it would be :
angular.extend($scope.actions.data, data);
See documentation here :
https://docs.angularjs.org/api/ng/function/angular.extend
Otherwise, if you only get new values from the server, you can do the following
for (var i=0; i<data.length; i++){
$scope.actions.data.push(data[i]);
}
For my use case, i had to remove node_modules directory and run npm install.
$ rm -rf node_modules (make sure you're in the ios project directory)
$ npm install
If you get error "dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.58.dylib", do the following:
$ brew uninstall --force node --ignore-dependencies node
$ brew uninstall icu4c --ignore-dependencies icu4c
$ brew install icu4c
$ brew unlink icu4c && brew link icu4c --force
$ brew install node
$ npm install
I have a file "cost.ini" on the root of my class path. My JAR file is named "cost.jar".
The following code:
try {
//JDK11: replace "UTF-8" with UTF_8 and remove try-catch
String rootPath = decode(getSystemResource("cost.ini").getPath()
.replaceAll("(cost\\.jar!/)?cost\\.ini$|^(file\\:)?/", ""), "UTF-8");
showMessageDialog(null, rootPath, "rootpath", WARNING_MESSAGE);
} catch(UnsupportedEncodingException e) {}
Path returned from .getPath()
has the format:
file:/C:/folder1/folder2/cost.jar!/cost.ini
/C:/folder1/folder2/cost.ini
Every use of File
, leads on exception, if the application provided in JAR format.
if you still stuck or you get this
C:\\\Users\\\name of your\\\AppData\\\Local\\\Programs\\\Python\\\Python36
simply do this replace 2 \ with one
C:\Users\akshay\AppData\Local\Programs\Python\Python36
There is a simpler solution to this. What you describe is the natural behavior of the &
operator and can thus be done primatively:
> c(1,1,NA) & c(1,0,NA) & c(1,NA,NA)
[1] TRUE FALSE NA
If all are 1, then 1 is returned. If any are 0, then 0. If all are NA, then NA.
In your case, the code would be:
DF$Den<-DF$Denial1 & DF$Denial2 & DF$Denial3
In order for this to work, you will need to stop working in character
and use numeric
or logical
types.
Vary the consumer-rate and the producer-rate (using sleep), to better understand the operation of code. The code below is the consumer-producer simulation (over a max-limit on container).
Code for your reference:
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
sem_t semP, semC;
int stock_count = 0;
const int stock_max_limit=5;
void *producer(void *arg) {
int i, sum=0;
for (i = 0; i < 10; i++) {
while(stock_max_limit == stock_count){
printf("stock overflow, production on wait..\n");
sem_wait(&semC);
printf("production operation continues..\n");
}
sleep(1); //production decided here
stock_count++;
printf("P::stock-count : %d\n",stock_count);
sem_post(&semP);
printf("P::post signal..\n");
}
}
void *consumer(void *arg) {
int i, sum=0;
for (i = 0; i < 10; i++) {
while(0 == stock_count){
printf("stock empty, consumer on wait..\n");
sem_wait(&semP);
printf("consumer operation continues..\n");
}
sleep(2); //consumer rate decided here
stock_count--;
printf("C::stock-count : %d\n", stock_count);
sem_post(&semC);
printf("C::post signal..\n");
}
}
int main(void) {
pthread_t tid0,tid1;
sem_init(&semP, 0, 0);
sem_init(&semC, 0, 0);
pthread_create(&tid0, NULL, consumer, NULL);
pthread_create(&tid1, NULL, producer, NULL);
pthread_join(tid0, NULL);
pthread_join(tid1, NULL);
sem_destroy(&semC);
sem_destroy(&semP);
return 0;
}
Thing I like to do is to wrap addition columns in aggregate function, like max()
.
It works very good when you don't expect duplicate values.
Select MAX(cpe.createdon) As MaxDate, cpe.fmgcms_cpeclaimid, MAX(cpe.fmgcms_claimid) As fmgcms_claimid
from Filteredfmgcms_claimpaymentestimate cpe
where cpe.createdon < 'reportstartdate'
group by cpe.fmgcms_cpeclaimid
Then tell read.table not to use row.names
:
systems <- read.table("http://getfile.pl?test.csv",
header=TRUE, sep=",", row.names=NULL)
and now your rows will simply be numbered.
Also look at read.csv
which is a wrapper for read.table
which already sets the sep=','
and header=TRUE
arguments so that your call simplifies to
systems <- read.csv("http://getfile.pl?test.csv", row.names=NULL)
I understand this is a discussion point for a node application, but in the interest of universal JavaScript applications running on a node server, which is how I arrived at this post, I have been researching this for a universal / isomorphic react app I have been building, and the package abab
worked for me. In fact it was the only solution I could find that worked, rather than using the Buffer method also mentioned (I had typescript issues).
(This package is used by jsdom
, which in turn is used by the window
package.)
Getting back to my point; based on this, perhaps if this functionality is already written as an npm package like the one you mentioned, and has it's own algorithm based on W3 spec, you could install and use the abab
package rather than writing you own function that may or may not be accurate based on encoding.
---EDIT---
I started having weird issues today with encoding (not sure why it's started happening now) with package abab
. It seems to encode correctly most of the time, but sometimes on front end it encodes incorrectly. Spent a long time trying to debug, but switched to package base-64
as recommended, and it worked straight away. Definitely seemed to be down to the base64 algorithm of abab
.
If you are looking for features that notebooks in JupyterLab have that traditional Jupyter Notebooks do not, check out the JupyterLab notebooks documentation. There is a simple video showing how to use each of the features in the documentation link.
JupyterLab notebooks have the following features and more:
This will get you the timezone as a PHP variable. I wrote a function using jQuery and PHP. This is tested, and does work!
On the PHP page where you are want to have the timezone as a variable, have this snippet of code somewhere near the top of the page:
<?php
session_start();
$timezone = $_SESSION['time'];
?>
This will read the session variable "time", which we are now about to create.
On the same page, in the <head>
section, first of all you need to include jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
Also in the <head>
section, paste this jQuery:
<script type="text/javascript">
$(document).ready(function() {
if("<?php echo $timezone; ?>".length==0){
var visitortime = new Date();
var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60;
$.ajax({
type: "GET",
url: "http://example.com/timezone.php",
data: 'time='+ visitortimezone,
success: function(){
location.reload();
}
});
}
});
</script>
You may or may not have noticed, but you need to change the url to your actual domain.
One last thing. You are probably wondering what the heck timezone.php is. Well, it is simply this: (create a new file called timezone.php and point to it with the above url)
<?php
session_start();
$_SESSION['time'] = $_GET['time'];
?>
If this works correctly, it will first load the page, execute the JavaScript, and reload the page. You will then be able to read the $timezone variable and use it to your pleasure! It returns the current UTC/GMT time zone offset (GMT -7) or whatever timezone you are in.
You can read more about this on my blog
<input type="file" id="picfile" name="picf" />
<input type="text" id="txtName" style="width: 144px;" />
$("#btncatsave").click(function () {
var Name = $("#txtName").val();
var formData = new FormData();
var totalFiles = document.getElementById("picfile").files.length;
var file = document.getElementById("picfile").files[0];
formData.append("FileUpload", file);
formData.append("Name", Name);
$.ajax({
type: "POST",
url: '/Category_Subcategory/Save_Category',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (msg) {
alert(msg);
},
error: function (error) {
alert("errror");
}
});
});
[HttpPost]
public ActionResult Save_Category()
{
string Name=Request.Form[1];
if (Request.Files.Count > 0)
{
HttpPostedFileBase file = Request.Files[0];
}
}
To multiply, use mult
for signed multiplication and multu
for unsigned multiplication. Note that the result of the multiplication of two 32-bit numbers yields a 64-number. If you want the result back in $v0
that means that you assume the result will fit in 32 bits.
The 32 most significant bits will be held in the HI
special register (accessible by mfhi
instruction) and the 32 least significant bits will be held in the LO
special register (accessible by the mflo
instruction):
E.g.:
li $a0, 5
li $a1, 3
mult $a0, $a1
mfhi $a2 # 32 most significant bits of multiplication to $a2
mflo $v0 # 32 least significant bits of multiplication to $v0
To divide, use div
for signed division and divu
for unsigned division. In this case, the HI
special register will hold the remainder and the LO
special register will hold the quotient of the division.
E.g.:
div $a0, $a1
mfhi $a2 # remainder to $a2
mflo $v0 # quotient to $v0
Convert the collection into an array by using function
Object[] toArray(Object[] a)
There's always Cygwin.
This should work:
window.onload = function() {
document.getElementById('about').className = 'expand';
};
Or if you're using jQuery:
$(function() {
$('#about').addClass('expand');
});
First set a custom attribute into your option for example nameid
(you can set non-standardized attribute of an HTML element, it's allowed):
'<option nameid= "' + n.id + "' value="' + i + '">' + n.names + '</option>'
then you can easily get attribute value using jquery .attr()
:
$('option:selected').attr("nameid")
For Example:
<select id="jobSel" class="longcombo" onchange="GetNameId">
<option nameid="32" value="1">test1</option>
<option nameid="67" value="1">test2</option>
<option nameid="45" value="1">test3</option>
</select>
Jquery:
function GetNameId(){
alert($('#jobSel option:selected').attr("nameid"));
}
Use StringBuilder's append line built-in functions:
StringBuilder sb = new StringBuilder();
sb.AppendLine("First line");
sb.AppendLine("Second line");
sb.AppendLine("Third line");
First line
Second line
Third line
Take a look at the Event Log API. Case a) (bluescreen, user cut the power cord or system hang) causes a note ('system did not shutdown correctly' or something like that) to be left in the 'System' event log the next time the system is rebooted properly. You should be able to access it programmatically using the above API (honestly, I've never used it but it should work).
In my case, I made a custom background which was not recognised.
I removed the <?xml version="1.0" encoding="utf-8"?>
tag from the top of those two XML resources file.
This worked for me, after trying many solutions from the community. @P Fuster's answer made me try this.
Depending on how big your arrays are you might consider an efficient algorithm O(n log n)
def equal_a(a1, a2)
a1sorted = a1.sort
a2sorted = a2.sort
return false if a1.length != a2.length
0.upto(a1.length - 1) do
|i| return false if a1sorted[i] != a2sorted[i]
end
end
Sorting costs O(n log n) and checking each pair costs O(n) thus this algorithm is O(n log n). The other algorithms cannot be faster (asymptotically) using unsorted arrays.
git clean -d -f -i
is the best way to do it.
This will help to clean in a more controlled manner.
-i
stands for interactive.
$date = '2014-02-25';
date('D', strtotime($date));
I received the same message. My fix included: I deleted all the additional sheets (tabs) in the .csv file, eliminated non-numeric characters, resaved the file as comma delimited and loaded in R v 2.15.0 using standard language:
filename<-read.csv("filename",header=TRUE)
As an additional safeguard, I closed the software and reopened before I loaded the csv.