CSS
body {
background: rgb(204,204,204);
}
page[size="A4"] {
background: white;
width: 21cm;
height: 29.7cm;
display: block;
margin: 0 auto;
margin-bottom: 0.5cm;
box-shadow: 0 0 0.5cm rgba(0,0,0,0.5);
}
@media print {
body, page[size="A4"] {
margin: 0;
box-shadow: 0;
}
}
HTML
<page size="A4"></page>
<page size="A4"></page>
<page size="A4"></page>
Piece of cake.
Use 960Grids Go to the automatic layout builder and make a two column, fluid design. Build a left column to the width of grids that works....this is the only challenge using grids and it's very easy once you read a tutorial. In a nutshell, each column in a grid is a certain width, and you set the amount of columns you want to use. To get a column that's exactly a certain width, you have to adjust your math so that your column width is exact. Not too tough.
No chance of wrapping because others have already fought that battle for you. Compatibility back as far as you likely will ever need to go. Quick and easy....Now, download, customize and deploy.
Voila. Grids FTW.
I understand the original poster was looking for a simple solution, but unfortunately there really is no simple solution.
Nevertheless, I've recently created an open-source freeware clipping library (written in Delphi, C++ and C#) which clips all kinds of polygons (including self-intersecting ones). This library is pretty simple to use: http://sourceforge.net/projects/polyclipping/ .
you'll have to pre-scale that drawable before you use it as a background
Even tried all suggestions, in my case (Office x64 - Visual Studio 2017), the only way to have both access engines on a Office 64x installation so you can use it on Visual Studio and using a 2016+ version of Office, is to install the 2010 version of the Engine.
First install the x64 from this page
https://www.microsoft.com/en-us/download/details.aspx?id=54920
and then the x86 version from this one
https://www.microsoft.com/en-us/download/details.aspx?id=13255
I'm not sure whether you think about:
select * from friend f
where not exists (
select 1 from likes l where f.id1 = l.id and f.id2 = l.id2
)
it works only if id1 is related with id1 and id2 with id2 not both.
It is good to save all the private images and docs in storage directory then you will have full control over file ether you can allow certain type of user to access the file or restrict.
Make a route/docs and point to any controller method:
public function docs() {
//custom logic
//check if user is logged in or user have permission to download this file etc
return response()->download(
storage_path('app/users/documents/4YPa0bl0L01ey2jO2CTVzlfuBcrNyHE2TV8xakPk.png'),
'filename.png',
['Content-Type' => 'image/png']
);
}
When you will hit localhost:8000/docs
file will be downloaded if any exists.
The file must be in root/storage/app/users/documents
directory according to above code, this was tested on Laravel 5.4
.
A branch is nothing but a commit pointer. As such, it doesn't track metadata like "who created me." See for yourself. Try cat .git/refs/heads/<branch>
in your repository.
That written, if you're really into tracking this information in your repository, check out branch descriptions. They allow you to attach arbitrary metadata to branches, locally at least.
Also DarVar's answer below is a very clever way to get at this information.
Replace
<div style="display:table;">
<div style="display:table-cell;"></div>
<div style="display:table-cell;"></div>
</div>
with
<table>
<tr><td>content cell1</td></tr>
<tr><td>content cell1</td></tr>
</table>
Look at all the issues surrounding trying to make divs perform like tables. They had to add table-xxx to mimic table layouts
Tables are supported and work very well in all browsers. Why ditch them? the fact that they had to mimic them is proof they did their job and well.
In my opinion use the best tool for the job and if you want tabulated data or something that resembles tabulated data tables just work.
Very Late reply I know but worth voicing.
You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.
So if you want to use your code, you could do:
df = DataFrame(eval(data))
But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:
data = []
for row in result_set:
data.append({'value': row["tag_expression"], 'key': row["tag_name"]})
But probably even this is not needed, as depending on what is exactly in your result_set
you could probably:
DataFrame(result_set)
read_sql_query
function to do this for you (see docs on this)I've used the implementation above and just now I came to know that it doesn't work on iPad running iOS 13. I had to add these lines before present() call in order to make it work
//avoiding to crash on iPad
if let popoverController = activityViewController.popoverPresentationController {
popoverController.sourceRect = CGRect(x: UIScreen.main.bounds.width / 2, y: UIScreen.main.bounds.height / 2, width: 0, height: 0)
popoverController.sourceView = self.view
popoverController.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
}
That's how it works for me
func shareData(_ dataToShare: [Any]){
let activityViewController = UIActivityViewController(activityItems: dataToShare, applicationActivities: nil)
//exclude some activity types from the list (optional)
//activityViewController.excludedActivityTypes = [
//UIActivity.ActivityType.postToFacebook
//]
//avoiding to crash on iPad
if let popoverController = activityViewController.popoverPresentationController {
popoverController.sourceRect = CGRect(x: UIScreen.main.bounds.width / 2, y: UIScreen.main.bounds.height / 2, width: 0, height: 0)
popoverController.sourceView = self.view
popoverController.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
}
self.present(activityViewController, animated: true, completion: nil)
}
box-sizing: border-box;
width: 100%;
padding: 5px;
box-sizing: border box; makes it so that padding, margin and border are included in the width calculations.
Solution One: You can use new react HOOKS API. Currently in React v16.8.0
Hooks let you use more of React’s features without classes. Hooks provide a more direct API to the React concepts you already know: props, state, context, refs, and lifecycle. Hooks solves all the problems addressed with Recompose.
A Note from the Author of recompose
(acdlite, Oct 25 2018):
Hi! I created Recompose about three years ago. About a year after that, I joined the React team. Today, we announced a proposal for Hooks. Hooks solves all the problems I attempted to address with Recompose three years ago, and more on top of that. I will be discontinuing active maintenance of this package (excluding perhaps bugfixes or patches for compatibility with future React releases), and recommending that people use Hooks instead. Your existing code with Recompose will still work, just don't expect any new features.
Solution Two:
If you are using react version that does not support hooks, no worries, use recompose
(A React utility belt for function components and higher-order components.) instead. You can use recompose
for attaching lifecycle hooks, state, handlers etc
to a function component.
Here’s a render-less component that attaches lifecycle methods via the lifecycle HOC (from recompose).
// taken from https://gist.github.com/tsnieman/056af4bb9e87748c514d#file-auth-js-L33
function RenderlessComponent() {
return null;
}
export default lifecycle({
componentDidMount() {
const { checkIfAuthed } = this.props;
// Do they have an active session? ("Remember me")
checkIfAuthed();
},
componentWillReceiveProps(nextProps) {
const {
loadUser,
} = this.props;
// Various 'indicators'..
const becameAuthed = (!(this.props.auth) && nextProps.auth);
const isCurrentUser = (this.props.currentUser !== null);
if (becameAuthed) {
loadUser(nextProps.auth.uid);
}
const shouldSetCurrentUser = (!isCurrentUser && nextProps.auth);
if (shouldSetCurrentUser) {
const currentUser = nextProps.users[nextProps.auth.uid];
if (currentUser) {
this.props.setCurrentUser({
'id': nextProps.auth.uid,
...currentUser,
});
}
}
}
})(RenderlessComponent);
It depends on a server configuration. If you're working with PHP under Linux or similar, you can control it using .htaccess configuration file, like so:
#set max post size
php_value post_max_size 20M
And, yes, I can personally attest to the fact that this works :)
If you're using IIS, I don't have any idea how you'd set this particular value.
As an addition to @C??? answer, make sure the title of the tooltip has not already been set manually in the HTML element. In my case, the span class for the tooltip already had a fixed tittle text, because of this my JQuery function $('[data-toggle="tooltip"]').prop('title', 'your new title');
did not work.
When I removed the title attribute in the HTML span class, the jQuery was working.
So:
<span class="showTooltip" data-target="#showTooltip" data-id="showTooltip">
<span id="MyTooltip" class="fas fa-info-circle" data-toggle="tooltip" data-placement="top" title="this is my pre-set title text"></span>
</span>
Should becode:
<span class="showTooltip" data-target="#showTooltip" data-id="showTooltip">
<span id="MyTooltip" class="fas fa-info-circle" data-toggle="tooltip" data-placement="top"></span>
</span>
I searched for multiple options to get my git reset to specific commit, but most of them aren't so satisfactory.
I generally use this to reset the git to the specific commit in source tree.
select commit to reset on sourcetree.
In dropdowns select the active branch , first Parent Only
And right click on "Reset branch to this commit" and select hard reset option (soft, mixed and hard)
and then go to terminal git push -f
You should be all set!
What if you specified the default value to return, instead of using default(T)?
public static T GetQueryString<T>(string key, T defaultValue) {...}
It makes calling it easier too:
var intValue = GetQueryString("intParm", Int32.MinValue);
var strValue = GetQueryString("strParm", "");
var dtmValue = GetQueryString("dtmPatm", DateTime.Now); // eg use today's date if not specified
The downside being you need magic values to denote invalid/missing querystring values.
I had the same need & quickly patched an existing code to be able to do something like this:
if( $('.scroll').hasHandlers('mouseout') ) // could be click, or '*'...
{
... code ..
}
It works for event delegation too:
if ( $('#main').hasHandlers('click','.simple-search') ) ...
It is available here : jquery-handler-toolkit.js
0000 0000 -> this is an 8-bit binary number. A digit represents a bit.
You count like so:
0000 0000 ? (0)
0000 0001 ? (1)
0000 0010 ? (2)
0000 0011 ? (3)
Each bit can be one of two values: on or off. The total highest number can be represented by multiplication:
2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 - 1 = 255
Or
2^8 - 1.
We subtract one because the first number is 0.
255 can hold quite a bit (no pun intended) of values.
As we use more bits the max value goes up exponentially. Therefore for many purposes, adding more bits is overkill.
Just to augment the accepted answer with a brief newbie-friendly short answer, you probably don't need exec
.
If you're still here, the following discussion should hopefully reveal why. When you run, say,
sh -c 'command'
you run a sh
instance, then start command
as a child of that sh
instance. When command
finishes, the sh
instance also finishes.
sh -c 'exec command'
runs a sh
instance, then replaces that sh
instance with the command
binary, and runs that instead.
Of course, both of these are useless in this limited context; you simply want
command
There are some fringe situations where you want the shell to read its configuration file or somehow otherwise set up the environment as a preparation for running command
. This is pretty much the sole situation where exec command
is useful.
#!/bin/sh
ENVIRONMENT=$(some complex task)
exec command
This does some stuff to prepare the environment so that it contains what is needed. Once that's done, the sh
instance is no longer necessary, and so it's a (minor) optimization to simply replace the sh
instance with the command
process, rather than have sh
run it as a child process and wait for it, then exit as soon as it finishes.
Similarly, if you want to free up as much resources as possible for a heavyish command at the end of a shell script, you might want to exec
that command as an optimization.
If something forces you to run sh
but you really wanted to run something else, exec something else
is of course a workaround to replace the undesired sh
instance (like for example if you really wanted to run your own spiffy gosh
instead of sh
but yours isn't listed in /etc/shells
so you can't specify it as your login shell).
The second use of exec
to manipulate file descriptors is a separate topic. The accepted answer covers that nicely; to keep this self-contained, I'll just defer to the manual for anything where exec
is followed by a redirect instead of a command name.
A stateless system can be seen as a box [black? ;)] where at any point in time the value of the output(s) depends only on the value of the input(s) [after a certain processing time]
A stateful system instead can be seen as a box where at any point in time the value of the output(s) depends on the value of the input(s) and of an internal state, so basicaly a stateful system is like a state machine with "memory" as the same set of input(s) value can generate different output(s) depending on the previous input(s) received by the system.
From the parallel programming point of view, a stateless system, if properly implemented, can be executed by multiple threads/tasks at the same time without any concurrency issue [as an example think of a reentrant function] A stateful system will requires that multiple threads of execution access and update the internal state of the system in an exclusive way, hence there will be a need for a serialization [synchronization] point.
This is actually a bug in the tutorials code. I was having the same issue and I finally realized the issue was in the "note_edit.xml" file.
Some of the layout_heigh/width attributes were set to "match_parent" which is not a valid value, they're supposed to be set to "fill_parent".
This was throwing a bug, that was causing the generation of the R.java file to fail. So, if you're having this issue, or a similar one, check all of your xml files and make sure that none of them have any errors.
I had originally asked myself the question "Do I need a PDB file deployed to my customer's machine?", and after reading this post, decided to exclude the file.
Everything worked fine, until today, when I was trying to figure out why a message box containing an Exception.StackTrace
was missing the file and line number information - necessary for troubleshooting the exception. I re-read this post and found the key nugget of information: that although the PDB is not necessary for the app to run, it is necessary for the file and line numbers to be present in the StackTrace
string. I included the PDB file in the executable folder and now all is fine.
It seems that the extension cannot be found anymore using "Visual Studio Team Services". Instead, by following the link in Using Visual Studio Code & Team Foundation Version Control on "Get the TFVC plugin working in Visual Studio Code" you get to the Azure Repos Extension for Visual Studio Code GitHub. There it is explained that you now have to look for "Team Azure Repos".
Also, please note, that with the new Settings editor in Visual Studio Code the additional slashes do not have to be added. The path to tf.exe for VS 2017 - if specified using the "user friendly" Settings editor - would be just
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe
It's also possible to select attributes regardless of their content, in modern browsers
with:
[data-my-attribute] {
/* Styles */
}
[anything] {
/* Styles */
}
For example: http://codepen.io/jasonm23/pen/fADnu
Works on a very significant percentage of browsers.
Note this can also be used in a JQuery selector, or using document.querySelector
<form id="form1" runat="server">
<input type="search" name="Search" placeholder="Search for a Product..." list="datalist1"
required="">
<datalist id="datalist1" runat="server">
</datalist>
</form>
protected void Page_Load(object sender, EventArgs e)
{
autocomplete();
}
protected void autocomplete()
{
Database p = new Database();
DataSet ds = new DataSet();
ds = p.sqlcall("select [name] from [stu_reg]");
int row = ds.Tables[0].Rows.Count;
string abc="";
for (int i = 0; i < row;i++ )
abc = abc + "<option>"+ds.Tables[0].Rows[i][0].ToString()+"</option>";
datalist1.InnerHtml = abc;
}
Here Database is a File (Database.cs) In Which i have created on method named sqlcall for retriving data from database.
This solution may help you if you know your problem is limited to Facades and you are running Laravel 5.5 or above.
Install laravel-ide-helper
composer require --dev barryvdh/laravel-ide-helper
Add this conditional statement in your AppServiceProvider
to register the helper class.
public function register()
{
if ($this->app->environment() !== 'production') {
$this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
}
// ...
}
Then run php artisan ide-helper:generate
to generate a file to help the IDE understand Facades. You will need to restart Visual Studio Code.
References
https://laracasts.com/series/how-to-be-awesome-in-phpstorm/episodes/16
dic = {'female':1, 'male':0}
w['female'] = w['female'].replace(dic)
.replace has as argument a dictionary in which you may change and do whatever you want or need.
long int n;
scanf("%ld", &n);
printf("%ld", n);
long long int n;
scanf("%lld", &n);
printf("%lld", n);
Hope you've cleared..
In my case, boolean values in my Python dict were the problem. JSON boolean values are in lowercase ("true", "false") whereas in Python they are in Uppercase ("True", "False"). Couldn't find this solution anywhere online but hope it helps.
I access main properties using $root
.
Vue.component("example", {
template: `<div>$root.message</div>`
});
...
<example></example>
It's easiest to just use .read()
to read the partial or entire response, then write it into a file you've opened in a known good location.
I had the same error but finally I solved it by suppressing PHP errors
Just put this code error_reporting(0);
at the top of your print page
<?php
error_reporting(0); //hide php errors
if( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once dirname(__FILE__) . '/tohtml/tcpdf/tcpdf.php';
.... //continue
Solution 1:
For 32bit: Run "mysql.exe" from: C:\Program Files\MySQL\MySQL Server 5.6\bin
For 64bit: Run "MySQLInstanceConfig.exe" from: C:\Program Files\MySQL\MySQL Server 5.6\bin
Solution 2:
The error (2002) Can't connect to ... normally means that there is no MySQL server running on the system or that you are using an incorrect Unix socket file name or TCP/IP port number when trying to connect to the server. You should also check that the TCP/IP port you are using has not been blocked by a firewall or port blocking service.
The error (2003) Can't connect to MySQL server on 'server' (10061) indicates that the network connection has been refused. You should check that there is a MySQL server running, that it has network connections enabled, and that the network port you specified is the one configured on the server.
Source: http://dev.mysql.com/doc/refman/5.6/en/starting-server.html Visit it for more information.
Import lodash
using
$ npm i --save lodash
var _ = require('lodash');
var objArrayList =
[
{ name: "user1"},
{ name: "user2"},
{ name: "user2"}
];
var Obj = _.find(objArrayList, { name: "user2" });
// Obj ==> { name: "user2"}
Beware if your page is including other .jsp or .jspf (fragment)! If you don't set
<%@ page session="false" %>
on them as well, the parent page will end up starting a new session and setting the JSESSIONID cookie.
For .jspf pages in particular, this happens if you configured your web.xml with such a snippet:
<jsp-config>
<jsp-property-group>
<url-pattern>*.jspf</url-pattern>
</jsp-property-group>
</jsp-config>
in order to enable scriptlets inside them.
In general Value Objects should be Immutable. Like Integer or String objects in Java. We can use them for transferring data between software layers. If the software layers or services running in different remote nodes like in a microservices environment or in a legacy Java Enterprise App. We must make almost exact copies of two classes. This is the where we met DTOs.
|-----------| |--------------|
| SERVICE 1 |--> Credentials DTO >--------> Credentials DTO >-- | AUTH SERVICE |
|-----------| |--------------|
In legacy Java Enterprise Systems DTOs can have various EJB stuff in it.
I do not know this is a best practice or not but I personally use Value Objects in my Spring MVC/Boot Projects like this:
|------------| |------------------| |------------|
-> Form | | -> Form | | -> Entity | |
| Controller | | Service / Facade | | Repository |
<- View | | <- View | | <- Entity / Projection View | |
|------------| |------------------| |------------|
Controller layer doesn't know what are the entities are. It communicates with Form and View Value Objects. Form Objects has JSR 303 Validation annotations (for instance @NotNull) and View Value Objects have Jackson Annotations for custom serialization. (for instance @JsonIgnore)
Service layer communicates with repository layer via using Entity Objects. Entity objects have JPA/Hibernate/Spring Data annotations on it. Every layer communicates with only the lower layer. The inter-layer communication is prohibited because of circular/cyclic dependency.
User Service ----> XX CANNOT CALL XX ----> Order Service
Some ORM Frameworks have the ability of projection via using additional interfaces or classes. So repositories can return View objects directly. There for you do not need an additional transformation.
For instance this is our User entity:
@Entity
public final class User {
private String id;
private String firstname;
private String lastname;
private String phone;
private String fax;
private String address;
// Accessors ...
}
But you should return a Paginated list of users that just include id, firstname, lastname. Then you can create a View Value Object for ORM projection.
public final class UserListItemView {
private String id;
private String firstname;
private String lastname;
// Accessors ...
}
You can easily get the paginated result from repository layer. Thanks to spring you can also use just interfaces for projections.
List<UserListItemView> find(Pageable pageable);
Don't worry for other conversion operations BeanUtils.copy
method works just fine.
none of the above worked for me. My situation is slightly different, my remote branch is not at origin. but in a different repository.
git remote add remoterepo GIT_URL.git
git fetch remoterepo
git checkout -b branchname remoterepo/branchname
tip: if you don't see the remote branch in the following output git branch -v -a
there is no way to check it out.
Confirmed working on 1.7.5.4
i = Your_int_value
Write bytes value like this for example:
the_file.write(i.to_bytes(2,"little"))
Depend of you int value size and the bit order your prefer
You can use the auto_now
and auto_now_add
options for updated_at
and created_at
respectively.
class MyModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
I removed the tag in the .project .
<buildCommand>
<name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
<arguments>
</arguments>
</buildCommand>
It's worked very well for me.
Matcher m = Pattern.compile("^\"(.*)\"$").matcher(value);
String strUnquoted = value;
if (m.find()) {
strUnquoted = m.group(1);
}
Use body-parser Parse the body with what it will be:
app.use(bodyParser.text());
app.use(bodyParser.urlencoded());
app.use(bodyParser.raw());
app.use(bodyParser.json());
ie. If you are supposed to get raw text file, run .text()
.
Thats what body-parser currently supports
I solved the error by modifying the following property in hibernate.cfg.xml
<property name="hibernate.hbm2ddl.auto">validate</property>
Earlier, the table was getting deleted each time I ran the program and now it doesnt, as hibernate only validates the schema and does not affect changes to it.
As far as I know you can also change from validate to update e.g.:
<property name="hibernate.hbm2ddl.auto">update</property>
We can Supply parameter in different way after some search I found some useful
<plugin>
<artifactId>${release.artifactId}</artifactId>
<version>${release.version}-${release.svm.version}</version>...
...
Actually in my application I need to save and supply SVN Version as parameter so i have implemented as above .
While Running build we need supply value for those parameter as follows.
RestProj_Bizs>mvn clean install package -Drelease.artifactId=RestAPIBiz -Drelease.version=10.6 -Drelease.svm.version=74
Here I am supplying
release.artifactId=RestAPIBiz
release.version=10.6
release.svm.version=74
It worked for me. Thanks
I guess
@foo = ("aAa", "bbb");
@bar = grep(/^aaa/i, @foo);
print join ",",@bar;
would do the trick.
I too got the similar problem and I did like below..
Rt click the project, navigate to Run As --> click 6 Maven Clean and your build will be success..
Month start from 0. 0 = January, 1 = February, 2 = March, ..., 11 = December.
As mentioned in the error, the official manual and the comments:
Replace
public function TSStatus($host, $queryPort)
with
public function __construct($host, $queryPort)
Use the LayoutInflater as I shown below.
public View myView() {
View v; // Creating an instance for View Object
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.myview, null);
TextView text1 = v.findViewById(R.id.dolphinTitle);
Button btn1 = v.findViewById(R.id.dolphinMinusButton);
TextView text2 = v.findViewById(R.id.dolphinValue);
Button btn2 = v.findViewById(R.id.dolphinPlusButton);
return v;
}
One needs to make sure the space between the variables and '&' sign. Check the image. (Red one showing invalid commands)
The correct solution is
Dim copyToRow: copyToRow = 5
Rows(copyToRow & ":" & copyToRow).Select
gettimeofday will return time accurate to microseconds within the resolution of the system clock. You might also want to check out the High Res Timers project on SourceForge.
I often do binary rpm per packaging proprietary apps - also moster as websphere - on linux. So my experience could be useful also a you, besides that it would better to do a TRUE RPM if you can. But i digress.
So the a basic step for packaging your (binary) program is as follow - in which i suppose the program is toybinprog with version 1.0, have a conf to be installed in /etc/toybinprog/toybinprog.conf and have a bin to be installed in /usr/bin called tobinprog :
mkdir -p ~/rpmbuild/{RPMS,SRPMS,BUILD,SOURCES,SPECS,tmp}
cat <<EOF >~/.rpmmacros
%_topdir %(echo $HOME)/rpmbuild
%_tmppath %{_topdir}/tmp
EOF
cd ~/rpmbuild
mkdir toybinprog-1.0
mkdir -p toybinprog-1.0/usr/bin
mkdir -p toybinprog-1.0/etc/toybinprog
install -m 755 toybinprog toybinprog-1.0/usr/bin
install -m 644 toybinprog.conf toybinprog-1.0/etc/toybinprog/
tar -zcvf toybinprog-1.0.tar.gz toybinprog-1.0/
cp toybinprog-1.0.tar.gz SOURCES/
cat <<EOF > SPECS/toybinprog.spec
# Don't try fancy stuff like debuginfo, which is useless on binary-only
# packages. Don't strip binary too
# Be sure buildpolicy set to do nothing
%define __spec_install_post %{nil}
%define debug_package %{nil}
%define __os_install_post %{_dbpath}/brp-compress
Summary: A very simple toy bin rpm package
Name: toybinprog
Version: 1.0
Release: 1
License: GPL+
Group: Development/Tools
SOURCE0 : %{name}-%{version}.tar.gz
URL: http://toybinprog.company.com/
BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root
%description
%{summary}
%prep
%setup -q
%build
# Empty section.
%install
rm -rf %{buildroot}
mkdir -p %{buildroot}
# in builddir
cp -a * %{buildroot}
%clean
rm -rf %{buildroot}
%files
%defattr(-,root,root,-)
%config(noreplace) %{_sysconfdir}/%{name}/%{name}.conf
%{_bindir}/*
%changelog
* Thu Apr 24 2009 Elia Pinto <[email protected]> 1.0-1
- First Build
EOF
rpmbuild -ba SPECS/toybinprog.spec
And that's all.
Hope this help
Try this:
foreach(GridViewRow row in GridView1.Rows) {
if(row.RowType == DataControlRowType.DataRow) {
HyperLink myHyperLink = row.FindControl("myHyperLinkID") as HyperLink;
}
}
If you are handling RowDataBound event, it's like this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink myHyperLink = e.Row.FindControl("myHyperLinkID") as HyperLink;
}
}
We can add drawable .xml like below
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="1dp"
android:color="@color/color_C4CDD5"/>
<corners android:radius="8dp"/>
<solid
android:color="@color/color_white"/>
</shape>
@DougW has clearly answered this question, but I still like to add some codes here to explain Doug's points. (And correct errors in the code above)
Solution 1: URL-encode the POST data with a content-type header :application/x-www-form-urlencoded .
Note: you do not need to urlencode $_POST[] fields one by one, http_build_query() function can do the urlencoding job nicely.
$fields = array(
'mediaupload'=>$file_field,
'username'=>$_POST["username"],
'password'=>$_POST["password"],
'latitude'=>$_POST["latitude"],
'longitude'=>$_POST["longitude"],
'datetime'=>$_POST["datetime"],
'category'=>$_POST["category"],
'metacategory'=>$_POST["metacategory"],
'caption'=>$_POST["description"]
);
$fields_string = http_build_query($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
Solution 2: Pass the array directly as the post data without URL-encoding, while the Content-Type header will be set to multipart/form-data.
$fields = array(
'mediaupload'=>$file_field,
'username'=>$_POST["username"],
'password'=>$_POST["password"],
'latitude'=>$_POST["latitude"],
'longitude'=>$_POST["longitude"],
'datetime'=>$_POST["datetime"],
'category'=>$_POST["category"],
'metacategory'=>$_POST["metacategory"],
'caption'=>$_POST["description"]
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
Both code snippets work, but using different HTTP headers and bodies.
You need to read the file in chunks of suitable size:
def md5_for_file(f, block_size=2**20):
md5 = hashlib.md5()
while True:
data = f.read(block_size)
if not data:
break
md5.update(data)
return md5.digest()
NOTE: Make sure you open your file with the 'rb' to the open - otherwise you will get the wrong result.
So to do the whole lot in one method - use something like:
def generate_file_md5(rootdir, filename, blocksize=2**20):
m = hashlib.md5()
with open( os.path.join(rootdir, filename) , "rb" ) as f:
while True:
buf = f.read(blocksize)
if not buf:
break
m.update( buf )
return m.hexdigest()
The update above was based on the comments provided by Frerich Raabe - and I tested this and found it to be correct on my Python 2.7.2 windows installation
I cross-checked the results using the 'jacksum' tool.
jacksum -a md5 <filename>
The property file task is for editing properties files. It contains all sorts of nice features that allow you to modify entries. For example:
<propertyfile file="build.properties">
<entry key="build_number"
type="int"
operation="+"
value="1"/>
</propertyfile>
I've incremented my build_number
by one. I have no idea what the value was, but it's now one greater than what it was before.
<echo>
task to build a property file instead of <propertyfile>
. You can easily layout the content and then use <propertyfile>
to edit that content later on.Example:
<echo file="build.properties">
# Default Configuration
source.dir=1
dir.publish=1
# Source Configuration
dir.publish.html=1
</echo>
Example:
<propertyfile file="default.properties"
comment="Default Configuration">
<entry key="source.dir" value="1"/>
<entry key="dir.publish" value="1"/>
<propertyfile>
<propertyfile file="source.properties"
comment="Source Configuration">
<entry key="dir.publish.html" value="1"/>
<propertyfile>
<concat destfile="build.properties">
<fileset dir="${basedir}">
<include name="default.properties"/>
<include name="source.properties"/>
</fileset>
</concat>
<delete>
<fileset dir="${basedir}">
<include name="default.properties"/>
<include name="source.properties"/>
</fileset>
</delete>
Untested / could be better:
<form action="page-you're-submitting-to.html" method="POST">
<a href="#" onclick="document.forms[0].submit();return false;"><img src="whatever.jpg" /></a>
</form>
First, you don't need to define both of those locations. Just use classpath:config/properties/database.properties
. In a WAR, WEB-INF/classes
is a classpath entry, so it will work just fine.
After that, I think what you mean is you want to use Spring's schema-based configuration to create a configurer. That would go like this:
<context:property-placeholder location="classpath:config/properties/database.properties"/>
Note that you don't need to "ignoreResourceNotFound" anymore. If you need to define the properties separately using util:properties
:
<context:property-placeholder properties-ref="jdbcProperties" ignore-resource-not-found="true"/>
There's usually not any reason to define them separately, though.
p = {1,2,3} is wrong.
You can never use this:
int * p;
p = {1,2,3};
loop is right
int *p,i;
p = malloc(3*sizeof(int));
for(i = 0; i<3; ++i)
p[i] = i;
I have run into this before an came to the same conclusion about cross database queries as you. What I ended up doing was using schemas to divide the table space that way I could keep the tables grouped but still query them all.
Using OpenSSL's EVP interface (the following is for OpenSSL 1.1):
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <openssl/evp.h>
bool computeHash(const std::string& unhashed, std::string& hashed)
{
bool success = false;
EVP_MD_CTX* context = EVP_MD_CTX_new();
if(context != NULL)
{
if(EVP_DigestInit_ex(context, EVP_sha256(), NULL))
{
if(EVP_DigestUpdate(context, unhashed.c_str(), unhashed.length()))
{
unsigned char hash[EVP_MAX_MD_SIZE];
unsigned int lengthOfHash = 0;
if(EVP_DigestFinal_ex(context, hash, &lengthOfHash))
{
std::stringstream ss;
for(unsigned int i = 0; i < lengthOfHash; ++i)
{
ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];
}
hashed = ss.str();
success = true;
}
}
}
EVP_MD_CTX_free(context);
}
return success;
}
int main(int, char**)
{
std::string pw1 = "password1", pw1hashed;
std::string pw2 = "password2", pw2hashed;
std::string pw3 = "password3", pw3hashed;
std::string pw4 = "password4", pw4hashed;
hashPassword(pw1, pw1hashed);
hashPassword(pw2, pw2hashed);
hashPassword(pw3, pw3hashed);
hashPassword(pw4, pw4hashed);
std::cout << pw1hashed << std::endl;
std::cout << pw2hashed << std::endl;
std::cout << pw3hashed << std::endl;
std::cout << pw4hashed << std::endl;
return 0;
}
The advantage of this higher level interface is that you simply need to swap out the EVP_sha256()
call with another digest's function, e.g. EVP_sha512()
, to use a different digest. So it adds some flexibility.
I don't have an 11g instance available today but could you not use:
SELECT group_id,
LISTAGG(name, ',') WITHIN GROUP (ORDER BY name) AS names
FROM (
SELECT UNIQUE
group_id,
name
FROM demotable
)
GROUP BY group_id
All This Work :)
Model
public partial class ClientMessage
{
public int IdCon { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
Controller
public class TestAjaxBeginFormController : Controller{
projectNameEntities db = new projectNameEntities();
public ActionResult Index(){
return View();
}
[HttpPost]
public ActionResult GetClientMessages(ClientMessage Vm) {
var model = db.ClientMessages.Where(x => x.Name.Contains(Vm.Name));
return PartialView("_PartialView", model);
}
}
View index.cshtml
@model projectName.Models.ClientMessage
@{
Layout = null;
}
<script src="~/Scripts/jquery-1.9.1.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script>
//\\\\\\\ JS retrun message SucccessPost or FailPost
function SuccessMessage() {
alert("Succcess Post");
}
function FailMessage() {
alert("Fail Post");
}
</script>
<h1>Page Index</h1>
@using (Ajax.BeginForm("GetClientMessages", "TestAjaxBeginForm", null , new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "SuccessMessage",
OnFailure = "FailMessage" ,
UpdateTargetId = "resultTarget"
}, new { id = "MyNewNameId" })) // set new Id name for Form
{
@Html.AntiForgeryToken()
@Html.EditorFor(x => x.Name)
<input type="submit" value="Search" />
}
<div id="resultTarget"> </div>
View _PartialView.cshtml
@model IEnumerable<projectName.Models.ClientMessage >
<table>
@foreach (var item in Model) {
<tr>
<td>@Html.DisplayFor(modelItem => item.IdCon)</td>
<td>@Html.DisplayFor(modelItem => item.Name)</td>
<td>@Html.DisplayFor(modelItem => item.Email)</td>
</tr>
}
</table>
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.
Avoid /etc/*release* files and run this command instead, it is far more reliable and gives more details:
rpm -qia '*release*'
As above mentioned paths are correct. But i think if we just return a local array variable of a function sometimes it returns garbage values as its elements.
in-order to avoid that i had to create the array dynamically and proceed. Which is something like this.
int* func()
{
int* Arr = new int[100];
return Arr;
}
int main()
{
int* ArrResult = func();
cout << ArrResult[0] << " " << ArrResult[1] << endl;
return 0;
}
I recompiled the package specification, even though the change was only in the package body. This resolved my issue
A rewrite of the answer by Sarfraz would be something like this, I think:
<script>
document.getElementById('change').onclick = changeColor;
function changeColor() {
document.body.style.color = "purple";
return false;
}
</script>
You'd either have to put this script at the bottom of your page, right before the closing body tag, or put the handler assignment in a function called onload - or if you're using jQuery there's the very elegant $(document).ready(function() { ... } );
Note that when you assign event handlers this way, it takes the functionality out of your HTML. Also note you set it equal to the function name -- no (). If you did onclick = myFunc();
the function would actually execute when the handler is being set.
And I'm curious -- you knew enough to script changing the background color, but not the text color? strange:)
for Xamarin Android
Using command //get the file directory
Image image =new Image() { Source = file.Path };
then in command adb pull //the image file path here
UPDATE table1 SET (col1, col2) = (col2, col3) FROM othertable WHERE othertable.col1 = 123;
I just looked at this page as I had this issue. For me I had floating point numbers calculated from an array but even after designating the variables as floating points the error was still given, here's the simple fix and example code underneath which was causing the issue.
Example PHP
<?php
$subtotal = 0; //Warning fixed
$shippingtotal = 0; //Warning fixed
$price = array($row3['price']);
$shipping = array($row3['shipping']);
$values1 = array_sum($price);
$values2 = array_sum($shipping);
(float)$subtotal += $values1; // float is irrelevant $subtotal creates warning
(float)$shippingtotal += $values2; // float is irrelevant $shippingtotal creates warning
?>
On Windows, create a batch file with the following line in it:
start cmd /k "C:\Anaconda3\Scripts\activate.bat C:\Anaconda3 & activate env"
The first path contained in quotes is the path to the activate.bat file in the Anaconda installation. The path on your system might be different. The name following the activate command of course should be your desired environment name.
Then run the batch file when you need to open an Anaconda prompt.
I found an easier way by looking at the R script generated by Rattle. It looks like below:
correlations <- cor(mydata[,c(1,3,5:87,89:90,94:98)], use="pairwise", method="spearman")
There's an article over on MSDN that has a sample application for zipping and unzipping files and folders purely in C#. I've been using some of the classes in that successfully for a long time. The code is released under the Microsoft Permissive License, if you need to know that sort of thing.
EDIT: Thanks to Cheeso for pointing out that I'm a bit behind the times. The MSDN example I pointed to is in fact using DotNetZip and is really very fully-featured these days. Based on my experience of a previous version of this I'd happily recommend it.
SharpZipLib is also quite a mature library and is highly rated by people, and is available under the GPL license. It really depends on your zipping needs and how you view the license terms for each of them.
Rich
In this case, using WebView#loadDataWithBaseUrl()
is better than WebView#loadUrl()
!
webView.loadDataWithBaseURL(url,
data,
"text/html",
"utf-8",
null);
url: url/path String pointing to the directory all your JavaScript files and html links have their origin. If null, it's about:blank. data: String containing your hmtl file, read with BufferedReader for example
In Vuetify 2.x, v-layout and v-flex are replaced by v-row and v-col respectively. To center the content both vertically and horizontally, we have to instruct the v-row component to do it:
<v-container fill-height>
<v-row justify="center" align="center">
<v-col cols="12" sm="4">
Centered both vertically and horizontally
</v-col>
</v-row>
</v-container>
Convert both completed
and total
to double
or at least cast them to double
when doing the devision. I.e. cast the varaibles to double not just the result.
Fair warning, there is a floating point precision problem when working with float
and double
.
java provides support for Unicode i.e it supports all world wide alphabets. Hence the size of char in java is 2 bytes. And range is 0 to 65535.
In short: this happens likely when you are hot-deploying webapps. For instance, your ide+development server hot-deploys a war again. Threads, that have been created previously are still running. But meanwhile their classloader/context is invalid and faces the IllegalAccessException / IllegalStateException becouse its orgininating webapp (the former runtime-environment) has been redeployed.
So, as states here, a restart does not permanently resolve this issue. Instead, it is better to find/implement a managed Thread Pool, s.th. like this to handle the termination of threads appropriately. In JavaEE you will use these ManagedThreadExeuctorServices. A similar opinion and reference here.
Examples for this are the EvictorThread of Apache Commons Pool, that "cleans" pooled instances according to the pool's configuration (max idle etc.).
You can set the click handler in xml with these attribute:
android:onClick="onClick"
android:clickable="true"
Don't forget the clickable attribute, without it, the click handler isn't called.
main.xml
...
<TextView
android:id="@+id/click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:textSize="55sp"
android:onClick="onClick"
android:clickable="true"/>
...
MyActivity.java
public class MyActivity extends Activity {
public void onClick(View v) {
...
}
}
I think you can't do that but atleast you can update it. In order to edit an existing row in a DataTable, you need to locate the DataRow you want to edit, and then assign the updated values to the desired columns.
Example,
DataSet1.Tables(0).Rows(4).Item(0) = "Updated Company Name"
DataSet1.Tables(0).Rows(4).Item(1) = "Seattle"
Another approach of offsetting is to have two empty rows, for example:
<div class="col-md-4"></div>
<div class="col-md-4">Centered Content</div>
<div class="col-md-4"></div>
Functions mysql_
are not supported any longer and have been removed in PHP 7
. You must use mysqli_
instead. However it's not recommended method now. You should consider PDO
with better security solutions.
$result = mysqli_query($con, "SELECT option_value FROM wp_10_options WHERE option_name='homepage' LIMIT 1");
$row = mysqli_fetch_assoc($result);
echo $row['option_value'];
db will show the current Database name type: db.dropDatabase();
1- select the database to drop by using 'use' keyword.
2- then type db.dropDatabase();
The $.fn.equals(...)
solution is probably the cleanest and most elegant one.
I have tried something quick and dirty like this:
JSON.stringify(a) == JSON.stringify(b)
It is probably expensive, but the comfortable thing is that it is implicitly recursive, while the elegant solution is not.
Just my 2 cents.
var formValues = {
firstName: $('#firstName').val(),
lastName: $('#lastName').val(),
phone: $('#phoneNumber').val(),
address: $('#address').val()
};
Note this will contain the values of the elements at the point in time the object literal was interpreted, not when the properties of the object are accessed. You'd need to write a getter for that.
My solution using C++11 regex (#include <regex>
), it can be used for more precise check, like unsigned int
, double
etc:
static const std::regex INT_TYPE("[+-]?[0-9]+");
static const std::regex UNSIGNED_INT_TYPE("[+]?[0-9]+");
static const std::regex DOUBLE_TYPE("[+-]?[0-9]+[.]?[0-9]+");
static const std::regex UNSIGNED_DOUBLE_TYPE("[+]?[0-9]+[.]?[0-9]+");
bool isIntegerType(const std::string& str_)
{
return std::regex_match(str_, INT_TYPE);
}
bool isUnsignedIntegerType(const std::string& str_)
{
return std::regex_match(str_, UNSIGNED_INT_TYPE);
}
bool isDoubleType(const std::string& str_)
{
return std::regex_match(str_, DOUBLE_TYPE);
}
bool isUnsignedDoubleType(const std::string& str_)
{
return std::regex_match(str_, UNSIGNED_DOUBLE_TYPE);
}
You can find this code at http://ideone.com/lyDtfi, this can be easily modified to meet the requirements.
iirc :
cat filename.txt | awk '{ print $2 $4 }'
or, as mentioned in the comments :
awk '{ print $2 $4 }' filename.txt
For example this simple Makefile should be sufficient:
CC=gcc CFLAGS=-Wall all: program program: program.o program.o: program.c program.h headers.h clean: rm -f program program.o run: program ./program
Note there must be <tab>
on the next line after clean and run, not spaces.
UPDATE Comments below applied
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}
So you can use:
myvar = getURLParameter('myvar');
you may want it to be printed as '1' or as 'a'.
In case you want '1' as input then :
int a = 1;
char b = (char)(a + '0');
System.out.println(b);
In case you want 'a' as input then :
int a = 1;
char b = (char)(a-1 + 'a');
System.out.println(b);
java turns the ascii value to char :)
The docs explicitly says that java.sql.Date
will throw:
IllegalArgumentException
- if the date given is not in the JDBC date escape format (yyyy-[m]m-[d]d
)
Also you shouldn't need to convert a date to a String
then to a sql.date
, this seems superfluous (and bug-prone!). Instead you could:
java.sql.Date sqlDate := new java.sql.Date(now.getTime());
prs.setDate(2, sqlDate);
prs.setDate(3, sqlDate);
You could use the :first-child and :last-child pseudo-selectors
:
tr td:first-child{
color:red;
}
tr td:last-child {
color:green
}
Or you can use other way like
// To first child
tr td:nth-child(1){
color:red;
}
// To last child
tr td:nth-last-child(1){
color:green;
}
Both way are perfectly working
Here you can benchmark all supported hashes on your hardware, supported by your version of node.js. Some are cryptographic, and some is just for a checksum. Its calculating "Hello World" 1 million times for each algorithm. It may take around 1-15 seconds for each algorithm (Tested on the Standard Google Computing Engine with Node.js 4.2.2).
for(var i1=0;i1<crypto.getHashes().length;i1++){
var Algh=crypto.getHashes()[i1];
console.time(Algh);
for(var i2=0;i2<1000000;i2++){
crypto.createHash(Algh).update("Hello World").digest("hex");
}
console.timeEnd(Algh);
}
Result:
DSA: 1992ms
DSA-SHA: 1960ms
DSA-SHA1: 2062ms
DSA-SHA1-old: 2124ms
RSA-MD4: 1893ms
RSA-MD5: 1982ms
RSA-MDC2: 2797ms
RSA-RIPEMD160: 2101ms
RSA-SHA: 1948ms
RSA-SHA1: 1908ms
RSA-SHA1-2: 2042ms
RSA-SHA224: 2176ms
RSA-SHA256: 2158ms
RSA-SHA384: 2290ms
RSA-SHA512: 2357ms
dsaEncryption: 1936ms
dsaWithSHA: 1910ms
dsaWithSHA1: 1926ms
dss1: 1928ms
ecdsa-with-SHA1: 1880ms
md4: 1833ms
md4WithRSAEncryption: 1925ms
md5: 1863ms
md5WithRSAEncryption: 1923ms
mdc2: 2729ms
mdc2WithRSA: 2890ms
ripemd: 2101ms
ripemd160: 2153ms
ripemd160WithRSA: 2210ms
rmd160: 2146ms
sha: 1929ms
sha1: 1880ms
sha1WithRSAEncryption: 1957ms
sha224: 2121ms
sha224WithRSAEncryption: 2290ms
sha256: 2134ms
sha256WithRSAEncryption: 2190ms
sha384: 2181ms
sha384WithRSAEncryption: 2343ms
sha512: 2371ms
sha512WithRSAEncryption: 2434ms
shaWithRSAEncryption: 1966ms
ssl2-md5: 1853ms
ssl3-md5: 1868ms
ssl3-sha1: 1971ms
whirlpool: 2578ms
if anyone else has this situation: i am creating an email verification to log in to my app so my users arent signed in yet, however i used the below to check for an email entered on the login which is a variation of @firecape solution
ApplicationUser user = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindByEmail(Email.Text);
you will also need the following:
using Microsoft.AspNet.Identity;
and
using Microsoft.AspNet.Identity.Owin;
You can add it to your shell configuration file, e.g. $HOME/.bashrc
or more globally in /etc/environment
.
After adding these lines the changes won't reflect instantly in GUI based system's you have to exit the terminal or create a new one and in server logout the session and login to reflect these changes.
if ( $('#myfav').children().length > 0 ) {
// do something
}
This should work. The children()
function returns a JQuery object that contains the children. So you just need to check the size and see if it has at least one child.
Shows all your disks; total, used and free capacity. You can alter the output by various command-line options.
You can get it from http://www.paulsadowski.com/WSH/cmdprogs.htm, http://unxutils.sourceforge.net/ or somewhere else. It's a standard unix-util like du.
df -h
will show all your drive's used and available disk space. For example:
M:\>df -h
Filesystem Size Used Avail Use% Mounted on
C:/cygwin/bin 932G 78G 855G 9% /usr/bin
C:/cygwin/lib 932G 78G 855G 9% /usr/lib
C:/cygwin 932G 78G 855G 9% /
C: 932G 78G 855G 9% /cygdrive/c
E: 1.9T 1.3T 621G 67% /cygdrive/e
F: 1.9T 201G 1.7T 11% /cygdrive/f
H: 1.5T 524G 938G 36% /cygdrive/h
M: 1.5T 524G 938G 36% /cygdrive/m
P: 98G 67G 31G 69% /cygdrive/p
R: 98G 14G 84G 15% /cygdrive/r
Cygwin is available for free from: https://www.cygwin.com/ It adds many powerful tools to the command prompt. To get just the available space on drive M (as mapped in windows to a shared drive), one could enter in:
M:\>df -h | grep M: | awk '{print $4}'
<a onclick="MyFunc()">blabla..</a>
There is nothing more in @Html.ActionLink that you could utilize in this case. And razor is evel by itself, drop it from where you can.
In my case I was processing a set of jar files contained in a directory. After I processed them I tried to delete them from that directory, but they wouldn't delete. I was using JarFile to process them and the problem was that I forgot to close the JarFile when I was done.
Simply outputting something is PowerShell is a thing of beauty - and one its greatest strengths. For example, the common Hello, World! application is reduced to a single line:
"Hello, World!"
It creates a string object, assigns the aforementioned value, and being the last item on the command pipeline it calls the .toString()
method and outputs the result to STDOUT
(by default). A thing of beauty.
The other Write-*
commands are specific to outputting the text to their associated streams, and have their place as such.
While working with selected cells as shown by @tbur can be useful, it's also not the only option available.
You can use Range() like so:
If Worksheets("Sheet1").Range("A1").MergeCells Then
Do something
Else
Do something else
End If
Or:
If Worksheets("Sheet1").Range("A1:C1").MergeCells Then
Do something
Else
Do something else
End If
Alternately, you can use Cells():
If Worksheets("Sheet1").Cells(1, 1).MergeCells Then
Do something
Else
Do something else
End If
You should use options.addAll(allPoints);
instead of options.add(point);
You can try a rebase --interactive
session to amend your old commit (provided you did not already push those commits to another repo).
Sometimes the thing fixed in b.2. cannot be amended to the not-quite perfect commit it fixes, because that commit is buried deeply in a patch series.
That is exactly what interactive rebase is for: use it after plenty of "a"s and "b"s, by rearranging and editing commits, and squashing multiple commits into one.Start it with the last commit you want to retain as-is:
git rebase -i <after-this-commit>
An editor will be fired up with all the commits in your current branch (ignoring merge commits), which come after the given commit.
You can reorder the commits in this list to your heart's content, and you can remove them. The list looks more or less like this:
pick deadbee The oneline of this commit
pick fa1afe1 The oneline of the next commit
...
The oneline descriptions are purely for your pleasure; git rebase will not look at them but at the commit names ("deadbee" and "fa1afe1" in this example), so do not delete or edit the names.
By replacing the command "pick" with the command "edit", you can tell git rebase to stop after applying that commit, so that you can edit the files and/or the commit message, amend the commit, and continue rebasing.
From http://psoug.org/reference/roles.html, create a procedure on your database for your user to do it:
CREATE OR REPLACE PROCEDURE GRANT_SELECT(to_user in varchar2) AS
CURSOR ut_cur IS SELECT table_name FROM user_tables;
RetVal NUMBER;
sCursor INT;
sqlstr VARCHAR2(250);
BEGIN
FOR ut_rec IN ut_cur
LOOP
sqlstr := 'GRANT SELECT ON '|| ut_rec.table_name || ' TO ' || to_user;
sCursor := dbms_sql.open_cursor;
dbms_sql.parse(sCursor,sqlstr, dbms_sql.native);
RetVal := dbms_sql.execute(sCursor);
dbms_sql.close_cursor(sCursor);
END LOOP;
END grant_select;
You can try disabling selinux and try once again using the following command
setenforce 0
Andy's response worked for me by escaping $path:
git submodule foreach "(git checkout master; git pull; cd ..; git add \$path; git commit -m 'Submodule Sync')"
The easiest way to match both
^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$
and
^[0-9]{3}-[0-9]{3}-[0-9]{4}$
is to use alternation ((...|...)
): specify them as two mostly-separate options:
^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$
By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234
, not (123)123-1234
. So you might want to write:
^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$
(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)
May want to look at Kiran Chand's Blog post, he uses custom metadata on the view model such as:
[HtmlProperties(Size = 5, MaxLength = 10)]
public string Title { get; set; }
This is combined with custom templates that make use of the metadata. A clean and simple approach in my opinion but I would like to see this common use case built-in to mvc.
Note that as others have pointed out mysql_real_escape_string() will solve the problem (as will addslashes), however you should always use mysql_real_escape_string() for security reasons - consider:
SELECT * FROM valid_users WHERE username='$user' AND password='$password'
What if the browser sends
user="admin' OR (user=''"
password="') AND ''='"
The query becomes:
SELECT * FROM valid_users
WHERE username='admin' OR (user='' AND password='') AND ''=''
i.e. the security checks are completely bypassed.
C.
I know it's too late, but with API 2.0 you can do
from command line with:
curl https://api.bitbucket.org/2.0/repositories/<user>/<repo>/filehistory/<branch>/<path_file>
or in php with:
$data = json_decode(file_get_contents("https://api.bitbucket.org/2.0/repositories/<user>/<repo>/filehistory/<branch>/<path_file>", true));
then you have the history of your file (from the most recent commit to the oldest one):
{
"pagelen": 50,
"values": [
{
"links": {
"self": {
"href": "https://api.bitbucket.org/2.0/repositories/<user>/<repo>/src/<hash>/<path_file>"
},
"meta": {
"href": "https://api.bitbucket.org/2.0/repositories/<user>/<repo>/src/<HEAD>/<path_file>?format=meta"
},
"history": {
"href": "https://api.bitbucket.org/2.0/repositories/<user>/<repo>/filehistory/<HEAD>/<path_file>"
}
},
"commit": {
"hash": "<HEAD>",
"type": "commit",
"links": {
"self": {
"href": "https://api.bitbucket.org/2.0/repositories/<user>/<repo>/commit/<HEAD>"
},
"html": {
"href": "https://bitbucket.org/<user>/<repo>/commits/<HEAD>"
}
}
},
"attributes": [],
"path": "<path_file>",
"type": "commit_file",
"size": 31
},
{
"links": {
"self": {
"href": "https://api.bitbucket.org/2.0/repositories/<user>/<repo>/src/<HEAD~1>/<path_file>"
},
"meta": {
"href": "https://api.bitbucket.org/2.0/repositories/<user>/<repo>/src/<HEAD~1>/<path_file>?format=meta"
},
"history": {
"href": "https://api.bitbucket.org/2.0/repositories/<user>/<repo>/filehistory/<HEAD~1>/<path_file>"
}
},
"commit": {
"hash": "<HEAD~1>",
"type": "commit",
"links": {
"self": {
"href": "https://api.bitbucket.org/2.0/repositories/<user>/<repo>/commit/<HEAD~1>"
},
"html": {
"href": "https://bitbucket.org/<user>/<repo>/commits/<HEAD~1>"
}
}
},
"attributes": [],
"path": "<path_file>",
"type": "commit_file",
"size": 20
}
],
"page": 1
}
where values
> links
> self
provides the file at the moment in the history which you can retrieve it with curl <link>
or file_get_contents(<link>)
.
Eventually, from the command line you can filter with:
curl https://api.bitbucket.org/2.0/repositories/<user>/<repo>/filehistory/<branch>/<path_file>?fields=values.links.self
in php, just make a foreach
loop on the array $data
.
Note: if <path_file>
has a /
you have to convert it in %2F
.
See the doc here: https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Busername%7D/%7Brepo_slug%7D/filehistory/%7Bnode%7D/%7Bpath%7D
I'm running into this on a project myself - I had a table inside a div that was spilling out of the bottom of the div. None of the height fixes I tried worked, but I found a weird fix for it, and that is to put a paragraph at the bottom of the div with just a period in it. Then style the "color" of the text to be the same as the background of the container. Worked neat as you please and no javascript required. A non-breaking space will not work - nor does a transparent image.
Apparently it just needed to see that there is some content below the table in order to stretch to contain it. I wonder if this will work for anyone else.
This is the sort of thing that makes designers resort to table-based layouts - the amount of time I've spent figuring this stuff out and making it cross-browser compatible is driving me crazy.
To explain the problem, your error is as follows:
LoadError: cannot load such file -- uglifier
(in /home/cool_tech/cool_tech/app/assets/javascripts/application.js)
This means somewhere in application.js
, your app is referencing uglifier
(probably in the manifest
area at the top of the file). To fix the issue, you either need to remove the reference to uglifier
, or make sure the uglifier
file is present in your app, hence the answers you've been provided
Fix
If you've had no luck with adding the gem to your GemFile, a quick fix would be to remove any reference to uglifier
in your application.js
manifest. This, of course, will be temporary, but will at least allow you to precompile your assets
If n is not too high, another option could be to use split('') with a string of n characters :
<div ng-controller="MainCtrl">
<div ng-repeat="a in 'abcdefgh'.split('')">{{$index}}</div>
</div>
There is already a Connect Middleware for Timeout support:
var timeout = express.timeout // express v3 and below
var timeout = require('connect-timeout'); //express v4
app.use(timeout(120000));
app.use(haltOnTimedout);
function haltOnTimedout(req, res, next){
if (!req.timedout) next();
}
If you plan on using the Timeout middleware as a top-level middleware like above, the haltOnTimedOut
middleware needs to be the last middleware defined in the stack and is used for catching the timeout event. Thanks @Aichholzer for the update.
Keep in mind that if you roll your own timeout middleware, 4xx status codes are for client errors and 5xx are for server errors. 408s are reserved for when:
The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time.
TL;DR
event.preventDefault()
Prevents the browsers default behaviour (such as opening a link), but does not stop the event from bubbling up the DOM.event.stopPropagation()
Prevents the event from bubbling up the DOM, but does not stop the browsers default behaviour.return false;
Usually seen in jQuery code, it Prevents the browsers default behaviour, Prevents the event from bubbling up the DOM, and immediately Returns from any callback.
One should checkout this really nice & easy 4 min read with examples from where the above piece was copied from.
This should do the trick as well:
find . -type f -print -exec cat {} \;
Means:
find = linux `find` command finds filenames, see `man find` for more info
. = in current directory
-type f = only files, not directories
-print = show found file
-exec = additionally execute another linux command
cat = linux `cat` command, see `man cat`, displays file contents
{} = placeholder for the currently found filename
\; = tell `find` command that it ends now here
You further can combine searches trough boolean operators like -and
or -or
. find -ls
is nice, too.
Use Java's replaceAll(String regex, String replacement)
For example, Use a substitution char for the quotes and then replace that char with \"
String newstring = String.replaceAll("%","\"");
or replace all instances of \"
with \\\"
String newstring = String.replaceAll("\"","\\\"");
readlink -f filename
gives the full absolute path. but if the file is a symlink, u'll get the final resolved name.
Have a look at camlistore. It is not really Git-based, but I find it more appropriate for what you have to do.
Last I looked -- a couple of years ago -- there wasn't an easy option and the "solution" (which I did not agree with) was screen-scraping a number of websites. It may be easier now but I would still be surprised to see something, well, useful.
The problem here is that the data is immensely valuable (and very expensive), so while defining a method of retrieving it would be easy, getting the trading venues to part with their data would be next to impossible. Some of the MTFs (currently) provide their data for free but I'm not sure how you would get it without paying someone else, like Reuters, for it.
Try using white-space: nowrap;
in the container style (instead of overflow: hidden;
)
With dynamic allocation, using malloc:
int** x;
x = malloc(dimension1_max * sizeof(*x));
for (int i = 0; i < dimension1_max; i++) {
x[i] = malloc(dimension2_max * sizeof(x[0]));
}
//Writing values
x[0..(dimension1_max-1)][0..(dimension2_max-1)] = Value;
[...]
for (int i = 0; i < dimension1_max; i++) {
free(x[i]);
}
free(x);
This allocates an 2D array of size dimension1_max
* dimension2_max
. So, for example, if you want a 640*480 array (f.e. pixels of an image), use dimension1_max
= 640, dimension2_max
= 480. You can then access the array using x[d1][d2]
where d1
= 0..639, d2
= 0..479.
But a search on SO or Google also reveals other possibilities, for example in this SO question
Note that your array won't allocate a contiguous region of memory (640*480 bytes) in that case which could give problems with functions that assume this. So to get the array satisfy the condition, replace the malloc block above with this:
int** x;
int* temp;
x = malloc(dimension1_max * sizeof(*x));
temp = malloc(dimension1_max * dimension2_max * sizeof(x[0]));
for (int i = 0; i < dimension1_max; i++) {
x[i] = temp + (i * dimension2_max);
}
[...]
free(temp);
free(x);
Using balexandre's info:
SELECT usesysid, usename FROM pg_stat_activity;
I'm assuming you're talking about com.google.common.base.Predicate<T>
from Guava.
From the API:
Determines a
true
orfalse
value for a given input. For example, aRegexPredicate
might implementPredicate<String>
, and return true for any string that matches its given regular expression.
This is essentially an OOP abstraction for a boolean
test.
For example, you may have a helper method like this:
static boolean isEven(int num) {
return (num % 2) == 0; // simple
}
Now, given a List<Integer>
, you can process only the even numbers like this:
List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
for (int number : numbers) {
if (isEven(number)) {
process(number);
}
}
With Predicate
, the if
test is abstracted out as a type. This allows it to interoperate with the rest of the API, such as Iterables
, which have many utility methods that takes Predicate
.
Thus, you can now write something like this:
Predicate<Integer> isEven = new Predicate<Integer>() {
@Override public boolean apply(Integer number) {
return (number % 2) == 0;
}
};
Iterable<Integer> evenNumbers = Iterables.filter(numbers, isEven);
for (int number : evenNumbers) {
process(number);
}
Note that now the for-each loop is much simpler without the if
test. We've reached a higher level of abtraction by defining Iterable<Integer> evenNumbers
, by filter
-ing using a Predicate
.
Iterables.filter
Predicate
allows Iterables.filter
to serve as what is called a higher-order function. On its own, this offers many advantages. Take the List<Integer> numbers
example above. Suppose we want to test if all numbers are positive. We can write something like this:
static boolean isAllPositive(Iterable<Integer> numbers) {
for (Integer number : numbers) {
if (number < 0) {
return false;
}
}
return true;
}
//...
if (isAllPositive(numbers)) {
System.out.println("Yep!");
}
With a Predicate
, and interoperating with the rest of the libraries, we can instead write this:
Predicate<Integer> isPositive = new Predicate<Integer>() {
@Override public boolean apply(Integer number) {
return number > 0;
}
};
//...
if (Iterables.all(numbers, isPositive)) {
System.out.println("Yep!");
}
Hopefully you can now see the value in higher abstractions for routines like "filter all elements by the given predicate", "check if all elements satisfy the given predicate", etc make for better code.
Unfortunately Java doesn't have first-class methods: you can't pass methods around to Iterables.filter
and Iterables.all
. You can, of course, pass around objects in Java. Thus, the Predicate
type is defined, and you pass objects implementing this interface instead.
The same happened for me with eslint
module. EsLinter throw Parsing error: Invalid left-hand side in assignment expression
for await in second if statement.
if (condition_one) {
let result = await myFunction()
}
if (condition_two) {
let result = await myFunction() // eslint parsing error
}
As strange as it sounds what fixed this error was to add ; semicolon at the end of line where await occurred.
if (condition_one) {
let result = await myFunction();
}
if (condition_two) {
let result = await myFunction();
}
The solution mentioned in ".gitignore file not ignoring" is a bit extreme, but should work:
# rm all files
git rm -r --cached .
# add all files as per new .gitignore
git add .
# now, commit for new .gitignore to apply
git commit -m ".gitignore is now working"
(make sure to commit first your changes you want to keep, to avoid any incident as jball037 comments below.
The --cached
option will keep your files untouched on your disk though.)
You also have other more fine-grained solution in the blog post "Making Git ignore already-tracked files":
git rm --cached `git ls-files -i --exclude-standard`
Bassim suggests in his edit:
In case you get an error message like
fatal: path spec '...' did not match any files
, there might be files with spaces in their path.You can remove all other files with option
--ignore-unmatch
:
git rm --cached --ignore-unmatch `git ls-files -i --exclude-standard`
but unmatched files will remain in your repository and will have to be removed explicitly by enclosing their path with double quotes:
git rm --cached "<path.to.remaining.file>"
Arrays.sort(arr, Collections.reverseOrder());
for(int i = 0; i < arr.length; i++){
System.out.print( " " +arr[i]);
}
And move Arrays.sort()
out of that for loop.. You are sorting the same array on each iteration..
In my case image path
was wrong! So firstly, you might want to check if image path is correct :)
If you are in Chrome you can check the Post Data
Here is How to check the Post data
For others, if clearfix does not solve this for you, add margins to the non-floated sibling that is/are the same as the width(s) of the floated sibling(s).
You can just look through and use shift()
Your method signature is:
- (void) myTest:(NSString *)
withAString happens to be the parameter (the name is misleading, it looks like it is part of the selector's signature).
If you call the function in this manner:
[self performSelector:@selector(myTest:) withObject:myString];
It will work.
But, as the other posters have suggested, you may want to rename the method:
- (void)myTestWithAString:(NSString*)aString;
And call:
[self performSelector:@selector(myTestWithAString:) withObject:myString];
It is clear from the error.
The HtmlHelpers appended with "For" expects lambda expression as a parameter.
If you are passing the value directly, better use Normal one.
e.g.
Instead of TextboxFor(....) use Textbox()
syntax for TextboxFor will be like Html.TextBoxFor(m=>m.Property)
In your scenario you can use basic for loop, as it will give you index to use.
@for(int i=0;i<Model.Theme.Count;i++)
{
@Html.LabelFor(m=>m.Theme[i].name)
@for(int j=0;j<Model.Theme[i].Products.Count;j++) )
{
@Html.LabelFor(m=>m.Theme[i].Products[j].name)
@for(int k=0;k<Model.Theme[i].Products[j].Orders.Count;k++)
{
@Html.TextBoxFor(m=>Model.Theme[i].Products[j].Orders[k].Quantity)
@Html.TextAreaFor(m=>Model.Theme[i].Products[j].Orders[k].Note)
@Html.EditorFor(m=>Model.Theme[i].Products[j].Orders[k].DateRequestedDeliveryFor)
}
}
}
I do believe that the correct answer has already been provided by @Alex V, yet the answer does require some modernization as it is over five years old now.
There are two main issues:
Never use object
as a parameter name. It is a reservered word. With this being said, @Alex V's provided function will not work in strict mode
.
The addEvent
function provided by @Alex V does not return the event object
if the addEventListener
method is used. Another parameter should be added to the addEvent
function to allow for this.
NOTE: The new parameter to addEvent
has been made optional so that migrating to this new function version will not break any previous calls to this function. All legacy uses will be supported.
Here is the updated addEvent
function with these changes:
/*
function: addEvent
@param: obj (Object)(Required)
- The object which you wish
to attach your event to.
@param: type (String)(Required)
- The type of event you
wish to establish.
@param: callback (Function)(Required)
- The method you wish
to be called by your
event listener.
@param: eventReturn (Boolean)(Optional)
- Whether you want the
event object returned
to your callback method.
*/
var addEvent = function(obj, type, callback, eventReturn)
{
if(obj == null || typeof obj === 'undefined')
return;
if(obj.addEventListener)
obj.addEventListener(type, callback, eventReturn ? true : false);
else if(obj.attachEvent)
obj.attachEvent("on" + type, callback);
else
obj["on" + type] = callback;
};
An example call to the new addEvent
function:
var watch = function(evt)
{
/*
Older browser versions may return evt.srcElement
Newer browser versions should return evt.currentTarget
*/
var dimensions = {
height: (evt.srcElement || evt.currentTarget).innerHeight,
width: (evt.srcElement || evt.currentTarget).innerWidth
};
};
addEvent(window, 'resize', watch, true);
A version without error-handling:
Function sheetExists(sheetToFind As String) As Boolean
sheetExists = False
For Each sheet In Worksheets
If sheetToFind = sheet.name Then
sheetExists = True
Exit Function
End If
Next sheet
End Function
Nothing less likely to be outdated that the official docs: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/
My best solution (so far) for calculating the number of days difference:
// This assumes that you already have two Date objects: startDate, endDate
// Also, that you want to ignore any time portions
Calendar startCale=new GregorianCalendar();
Calendar endCal=new GregorianCalendar();
startCal.setTime(startDate);
endCal.setTime(endDate);
endCal.add(Calendar.YEAR,-startCal.get(Calendar.YEAR));
endCal.add(Calendar.MONTH,-startCal.get(Calendar.MONTH));
endCal.add(Calendar.DATE,-startCal.get(Calendar.DATE));
int daysDifference=endCal.get(Calendar.DAY_OF_YEAR);
Note, however, that this assumes less than a year's difference!
I am posting a way to use _netrc
to download materials from the site www.course.com.
If someone is going to use the coursera-dl to download the open-class materials on www.coursera.com, and on the Windows OS someone wants to use a file like ".netrc" which is in like-Unix OS to add the option -n
instead of -U <username> -P <password>
for convenience. He/she can do it like this:
Check the home path on Windows OS: setx HOME %USERPROFILE%
(refer to VonC's answer). It will save the HOME
environment variable as C:\Users\"username"
.
Locate into the directory C:\Users\"username"
and create a file name _netrc
.NOTE: there is NOT any suffix.
the content is like: machine coursera-dl login <user> password <pass>
Use a command like coursera-dl -n --path PATH <course name>
to download the class materials. More coursera-dl options details for this page.
You can define style rules which only apply to specific elements inside your div
with id divContainer
like this:
#divContainer input { ... }
#divContainer input[type="radio"] { ... }
#divContainer input[type="text"] { ... }
/* etc */
Mozilla recently released the awesome L20n or localization 2.0. In their own words L20n is
an open source, localization-specific scripting language used to process gender, plurals, conjugations, and most of the other quirky elements of natural language.
Their js implementation is on the github L20n repository.
In my case it was a ":" character in a folder name prevenitng the git repo to checkout on windows.
A very interesting project is disruptor. It has a ringbuffer and is used from what I know in financial applications.
See here: code of ringbuffer
I checked both Guava's EvictingQueue and ArrayDeque.
ArrayDeque does not limit growth if it's full it will double size and hence is not precisely acting like a ringbuffer.
EvictingQueue does what it promises but internally uses a Deque to store things and just bounds memory.
Hence, if you care about memory being bounded ArrayDeque is not fullfilling your promise. If you care about object count EvictingQueue uses internal composition (bigger object size).
A simple and memory efficient one can be stolen from jmonkeyengine. verbatim copy
import java.util.Iterator;
import java.util.NoSuchElementException;
public class RingBuffer<T> implements Iterable<T> {
private T[] buffer; // queue elements
private int count = 0; // number of elements on queue
private int indexOut = 0; // index of first element of queue
private int indexIn = 0; // index of next available slot
// cast needed since no generic array creation in Java
public RingBuffer(int capacity) {
buffer = (T[]) new Object[capacity];
}
public boolean isEmpty() {
return count == 0;
}
public int size() {
return count;
}
public void push(T item) {
if (count == buffer.length) {
throw new RuntimeException("Ring buffer overflow");
}
buffer[indexIn] = item;
indexIn = (indexIn + 1) % buffer.length; // wrap-around
count++;
}
public T pop() {
if (isEmpty()) {
throw new RuntimeException("Ring buffer underflow");
}
T item = buffer[indexOut];
buffer[indexOut] = null; // to help with garbage collection
count--;
indexOut = (indexOut + 1) % buffer.length; // wrap-around
return item;
}
public Iterator<T> iterator() {
return new RingBufferIterator();
}
// an iterator, doesn't implement remove() since it's optional
private class RingBufferIterator implements Iterator<T> {
private int i = 0;
public boolean hasNext() {
return i < count;
}
public void remove() {
throw new UnsupportedOperationException();
}
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return buffer[i++];
}
}
}
In addition to cookies and localStorage
, there's at least one other place you can store "semi-persistent" client data: window.name
. Any string value you assign to window.name
will stay there until the window is closed.
To test it out, just open the console and type window.name = "foo"
, then refresh the page and type window.name
; it should respond with foo
.
This is a bit of a hack, but if you don't want cookies filled with unnecessary data being sent to the server with every request, and if you can't use localStorage
for whatever reason (legacy clients), it may be an option to consider.
window.name
has another interesting property: it's visible to windows served from other domains; it's not subject to the same-origin policy like nearly every other property of window
. So, in addition to storing "semi-persistent" data there while the user navigates or refreshes the page, you can also use it for CORS-free cross-domain communication.
Note that window.name
can only store strings, but with the wide availability of JSON
, this shouldn't be much of an issue even for complex data.
I had to include double quotes with the table name.
db=> \d
List of relations
Schema | Name | Type | Owner
--------+-----------------------------------------------+-------+-------
public | COMMONDATA_NWCG_AGENCIES | table | dan
...
db=> \d COMMONDATA_NWCG_AGENCIES
Did not find any relation named "COMMONDATA_NWCG_AGENCIES".
???
Double quotes:
db=> \d "COMMONDATA_NWCG_AGENCIES"
Table "public.COMMONDATA_NWCG_AGENCIES"
Column | Type | Collation | Nullable | Default
--------------------------+-----------------------------+-----------+----------+---------
ID | integer | | not null |
...
Lots and lots of double quotes:
db=> select ID from COMMONDATA_NWCG_AGENCIES limit 1;
ERROR: relation "commondata_nwcg_agencies" does not exist
LINE 1: select ID from COMMONDATA_NWCG_AGENCIES limit 1;
^
db=> select ID from "COMMONDATA_NWCG_AGENCIES" limit 1;
ERROR: column "id" does not exist
LINE 1: select ID from "COMMONDATA_NWCG_AGENCIES" limit 1;
^
db=> select "ID" from "COMMONDATA_NWCG_AGENCIES" limit 1;
ID
----
1
(1 row)
This is postgres 11. The CREATE TABLE statements from this dump had double quotes as well:
DROP TABLE IF EXISTS "COMMONDATA_NWCG_AGENCIES";
CREATE TABLE "COMMONDATA_NWCG_AGENCIES" (
...
Recursive traverse object or array with array or objects elements:
function traverse(&$objOrArray)
{
foreach ($objOrArray as $key => &$value)
{
if (is_array($value) || is_object($value))
{
traverse($value);
}
else
{
// DO SOMETHING
}
}
}
this works....
<script language="javascript">
(function($) {
$.fn.MessageBox = function(msg) {
return this.each(function(){
alert(msg);
})
};
})(jQuery);?
</script>
.
<body>
<div class="Title">Welcome!</div>
<input type="button" value="ahaha" onclick="$(this).MessageBox('msg');" />
</body>
edit
you are using a failsafe jQuery code using the $ alias... it should be written like:
(function($) {
// plugin code here, use $ as much as you like
})(jQuery);
or
jQuery(function($) {
// your code using $ alias here
});
note that it has a 'jQuery' word in each of it....
If you have OS(64bit) and SSMS(64bit) and already install the AccessDatabaseEngine(64bit) and you still received an error, try this following solutions:
1: direct opening the sql server import and export wizard.
if you able to connect using direct sql server import and export wizard, then importing from SSMS is the issue, it's like activating 32bit if you import data from SSMS.
Instead of installing AccessDatabaseEngine(64bit) , try to use the AccessDatabaseEngine(32bit) , upon installation, windows will stop you for continuing the installation if you already have another app installed , if so , then use the following steps. This is from the MICROSOFT. The Quiet Installation.
If Office 365 is already installed, side by side detection will prevent the installation from proceeding. Instead perform a /quiet install of these components from command line. To do so, download the desired AccessDatabaseEngine.exe or AccessDatabaeEngine_x64.exe to your PC, open an administrative command prompt, and provide the installation path and switch Ex: C:\Files\AccessDatabaseEngine.exe /quiet
or check in the Addition Information content from the link below,
https://www.microsoft.com/en-us/download/details.aspx?id=54920
It's best to use miske's answer.
If you really want to use natecarlson's repository, the instructions just below can do any of the following:
apt-get update
gives a 404
error after add-apt-repository
apt-get update
gives a NO_PUBKEY
error after manually adding it to /etc/apt/sources.list
Open a terminal and run the following:
sudo -i
Enter your password if necessary, then paste the following into the terminal:
export GOOD_RELEASE='precise'
export BAD_RELEASE="`lsb_release -cs`"
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-add-repository -y ppa:natecarlson/maven3
mv natecarlson-maven3-${BAD_RELEASE}.list natecarlson-maven3-${GOOD_RELEASE}.list
sed -i "s/${BAD_RELEASE}/${GOOD_RELEASE}/" natecarlson-maven3-${GOOD_RELEASE}.list
apt-get update
exit
echo Done!
If you installed natecarlson's repository (either using add-apt-repository
or manually added to /etc/apt/sources.list
) and you don't want it anymore, open a terminal and run the following:
sudo -i
Enter your password if necessary, then paste the following into the terminal:
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-get update
exit
echo Done!
Two possibilities :
via script task and builtin javascript engine (if using jdk >= 1.6)
<project>
<property name="propA" value="This is a value"/>
<script language="javascript">
project.setProperty('propB', project.getProperty('propA').
replace(" ", "_"));
</script>
<echo>$${propB} => ${propB}</echo>
</project>
or using Ant addon Flaka
<project xmlns:fl="antlib:it.haefelinger.flaka">
<property name="propA" value="This is a value"/>
<fl:let> propB := replace('${propA}', '_', ' ')</fl:let>
<echo>$${propB} => ${propB}</echo>
</project>
to overwrite exisiting property propA simply replace propB with propA
You could also just create a Group Policy Preference and have it create the reg key for you. (no scripting involved)
I know this is an old post, but this may help clarify:
$('#searchField')
.val('')// [property value] e.g. what is visible / will be submitted
.attr('value', '');// [attribute value] e.g. <input value="preset" ...
Changing [attribute value] has no effect if there is a [property value]. (user || js altered input)
Solution
It is possible to use str_detect
of the stringr
package included in the tidyverse
package. str_detect
returns True
or False
as to whether the specified vector contains some specific string. It is possible to filter using this boolean value. See Introduction to stringr for details about stringr
package.
library(tidyverse)
# - Attaching packages -------------------- tidyverse 1.2.1 -
# ? ggplot2 2.2.1 ? purrr 0.2.4
# ? tibble 1.4.2 ? dplyr 0.7.4
# ? tidyr 0.7.2 ? stringr 1.2.0
# ? readr 1.1.1 ? forcats 0.3.0
# - Conflicts --------------------- tidyverse_conflicts() -
# ? dplyr::filter() masks stats::filter()
# ? dplyr::lag() masks stats::lag()
mtcars$type <- rownames(mtcars)
mtcars %>%
filter(str_detect(type, 'Toyota|Mazda'))
# mpg cyl disp hp drat wt qsec vs am gear carb type
# 1 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4
# 2 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 Mazda RX4 Wag
# 3 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 Toyota Corolla
# 4 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1 Toyota Corona
The good things about Stringr
We should use rather stringr::str_detect()
than base::grepl()
. This is because there are the following reasons.
stringr
package start with the prefix str_
, which makes the code easier to read.stringr
package is always the data.frame (or value), then comes the parameters.(Thank you Paolo)object <- "stringr"
# The functions with the same prefix `str_`.
# The first argument is an object.
stringr::str_count(object) # -> 7
stringr::str_sub(object, 1, 3) # -> "str"
stringr::str_detect(object, "str") # -> TRUE
stringr::str_replace(object, "str", "") # -> "ingr"
# The function names without common points.
# The position of the argument of the object also does not match.
base::nchar(object) # -> 7
base::substr(object, 1, 3) # -> "str"
base::grepl("str", object) # -> TRUE
base::sub("str", "", object) # -> "ingr"
Benchmark
The results of the benchmark test are as follows. For large dataframe, str_detect
is faster.
library(rbenchmark)
library(tidyverse)
# The data. Data expo 09. ASA Statistics Computing and Graphics
# http://stat-computing.org/dataexpo/2009/the-data.html
df <- read_csv("Downloads/2008.csv")
print(dim(df))
# [1] 7009728 29
benchmark(
"str_detect" = {df %>% filter(str_detect(Dest, 'MCO|BWI'))},
"grepl" = {df %>% filter(grepl('MCO|BWI', Dest))},
replications = 10,
columns = c("test", "replications", "elapsed", "relative", "user.self", "sys.self"))
# test replications elapsed relative user.self sys.self
# 2 grepl 10 16.480 1.513 16.195 0.248
# 1 str_detect 10 10.891 1.000 9.594 1.281
you need surrounded my constraint-layout with a ScrollView tag and gave it the property android:isScrollContainer="true".
If you are experienced with SQL Server, I would recommend ASP.NET.
ADO.NET gives you good access to SQL Server, and with SMO, you will also have just about the best access to SQL Server features. You can access SQL Server from other environments, but nothing is quite as integrated or predictable.
You can call your stored procs with SqlCommand and process the results the SqlDataReader and you'll be in business.
If you know what context managers are then you need nothing more to understand __enter__
and __exit__
magic methods. Lets see a very simple example.
In this example I am opening myfile.txt with help of open function. The try/finally block ensures that even if an unexpected exception occurs myfile.txt will be closed.
fp=open(r"C:\Users\SharpEl\Desktop\myfile.txt")
try:
for line in fp:
print(line)
finally:
fp.close()
Now I am opening same file with with statement:
with open(r"C:\Users\SharpEl\Desktop\myfile.txt") as fp:
for line in fp:
print(line)
If you look at the code, I didn't close the file & there is no try/finally block. Because with statement automatically closes myfile.txt . You can even check it by calling print(fp.closed)
attribute -- which returns True
.
This is because the file objects (fp in my example) returned by open function has two built-in methods __enter__
and __exit__
. It is also known as context manager. __enter__
method is called at the start of with block and __exit__
method is called at the end. Note: with statement only works with objects that support the context mamangement protocol i.e. they have __enter__
and __exit__
methods. A class which implement both methods is known as context manager class.
Now lets define our own context manager class.
class Log:
def __init__(self,filename):
self.filename=filename
self.fp=None
def logging(self,text):
self.fp.write(text+'\n')
def __enter__(self):
print("__enter__")
self.fp=open(self.filename,"a+")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("__exit__")
self.fp.close()
with Log(r"C:\Users\SharpEl\Desktop\myfile.txt") as logfile:
print("Main")
logfile.logging("Test1")
logfile.logging("Test2")
I hope now you have basic understanding of both __enter__
and __exit__
magic methods.
Just added the
set /p NetworkLocation= Enter name for network?
echo %NetworkLocation% >> netlist.txt
sequence to my netsh batch job. It now shows me the location I respond as the point for that sample. I continuously >> the output file so I know now "home", "work", "Starbucks", etc. Looking for clear air, I can eavulate the lowest use channels and whether there are 5 or just all 2.4 MHz WLANs around.
For me this problem was related to the API that I was using not being deployed. For example, I used a ZSDK_API.jar
as a reference.
To fix the issue I had to right click on the project and select properties. From JAVA BUILD PATH, I had to add the API that was not being deployed. This was weird as the app was throwing MainActivity class not found and in reality the error was caused by the DiscoveryHandler class not being found.
Hopes this helps someone.
Try this- Close the project then open it. It links with svn automatically,if project was checked out from valid svn path.
The C++ way of solving conversions (not the classical C) is illustrated with the program below. Note that the intent is to be able to use the same formatting facilities offered by iostream like precision, fill character, padding, hex, and the manipulators, etcetera.
Compile and run this program, then study it. It is simple
#include "iostream"
#include "iomanip"
#include "sstream"
using namespace std;
int main()
{
// Converting the content of a char array or a string to a double variable
double d;
string S;
S = "4.5";
istringstream(S) >> d;
cout << "\nThe value of the double variable d is " << d << endl;
istringstream("9.87654") >> d;
cout << "\nNow the value of the double variable d is " << d << endl;
// Converting a double to string with formatting restrictions
double D=3.771234567;
ostringstream Q;
Q.fill('#');
Q << "<<<" << setprecision(6) << setw(20) << D << ">>>";
S = Q.str(); // formatted converted double is now in string
cout << "\nThe value of the string variable S is " << S << endl;
return 0;
}
Prof. Martinez
you might consider using the Relative and Absolute positining.
`.container {
position: relative;
}
.tag {
position: absolute;
}`
I have tested it there, also if you want it to change its position use this as its margin:
top: 20px;
left: 10px;
It will place it 20 pixels from top and 10 pixels from left; but leave this one if not necessary.
Migrating from Glyphicons to Font Awesome is quite easy.
Include a reference to Font Awesome (either locally, or use the CDN).
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
Then run a search and replace where you search for glyphicon glyphicon-
and replace it with fa fa-
, and also change the enclosing element from <span
to <i
. Most of the CSS class names are the same. Some have changed though, so you have to manually fix those.
You can use Linq to XML to do this:
XDocument doc = XDocument.Load("input.xml");
var q = from node in doc.Descendants("Setting")
let attr = node.Attribute("name")
where attr != null && attr.Value == "File1"
select node;
q.ToList().ForEach(x => x.Remove());
doc.Save("output.xml");
Windows 10 uwp
application.
Try this:
webview.Navigate(new Uri("ms-appx-web:///index.html"));
To continue off of bobince's answer
In es6 you can now actually create a class
So now you can do:
class Shape {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return `Shape at ${this.x}, ${this.y}`;
}
}
So extend to a circle (as in the other answer) you can do:
class Circle extends Shape {
constructor(x, y, r) {
super(x, y);
this.r = r;
}
toString() {
let shapeString = super.toString();
return `Circular ${shapeString} with radius ${this.r}`;
}
}
Ends up a bit cleaner in es6 and a little easier to read.
Here is a good example of it in action:
class Shape {_x000D_
constructor(x, y) {_x000D_
this.x = x;_x000D_
this.y = y;_x000D_
}_x000D_
_x000D_
toString() {_x000D_
return `Shape at ${this.x}, ${this.y}`;_x000D_
}_x000D_
}_x000D_
_x000D_
class Circle extends Shape {_x000D_
constructor(x, y, r) {_x000D_
super(x, y);_x000D_
this.r = r;_x000D_
}_x000D_
_x000D_
toString() {_x000D_
let shapeString = super.toString();_x000D_
return `Circular ${shapeString} with radius ${this.r}`;_x000D_
}_x000D_
}_x000D_
_x000D_
let c = new Circle(1, 2, 4);_x000D_
_x000D_
console.log('' + c, c);
_x000D_
statmodels graphics also gives a nice view of correlation matrix
import statsmodels.api as sm
import matplotlib.pyplot as plt
corr = dataframe.corr()
sm.graphics.plot_corr(corr, xnames=list(corr.columns))
plt.show()
You Can use:
string path = Path.GetFullPath(FileName);
it will return the Full path of that mentioned file.
In my case, this error was due to the Network connection error that i was noticed in log.
The best regexp which I could find up till now is in here https://www.npmjs.com/package/base64-regex
which is in the current version looks like:
module.exports = function (opts) {
opts = opts || {};
var regex = '(?:[A-Za-z0-9+\/]{4}\\n?)*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)';
return opts.exact ? new RegExp('(?:^' + regex + '$)') :
new RegExp('(?:^|\\s)' + regex, 'g');
};
Everything you need to know about underscore template is here. Only 3 things to keep in mind:
<% %>
- to execute some code<%= %>
- to print some value in template<%- %>
- to print some values HTML escapedThat's all about it.
Simple example:
var tpl = _.template("<h1>Some text: <%= foo %></h1>");
then tpl({foo: "blahblah"})
would be rendered to the string <h1>Some text: blahblah</h1>
It may be of interest that both Outlook and Outlook Express can generate these multipart image email formats, if you insert the image files using the Insert / Picture menu function.
Obviously the email type must be set to HTML (not plain text).
Any other method (e.g. drag/drop, or any command-line invocation) results in the image(s) being sent as an attachment.
If you then send such an email to yourself, you can see how it is formatted! :)
FWIW, I am looking for a standalone windows executable which does inline images from the command line mode, but there seem to be none. It's a path which many have gone up... One can do it with say Outlook Express, by passing it an appropriately formatted .eml file.
With ES6 the most performant way would be to use a Map.
var myMap = new Map();
myMap.set(1, 'myVal');
myMap.set(2, { catName: 'Meow', age: 3 });
myMap.get(1);
myMap.get(2);
You can use ES6 features today using a shim (https://github.com/es-shims/es6-shim).
Performance will vary depending on the browser and scenario. But here is one example where Map
is most performant: https://jsperf.com/es6-map-vs-object-properties/2
REFERENCE https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map
The "0x" counts towards the eight character count. You need "%#010x"
.
Note that #
does not append the 0x to 0 - the result will be 0000000000
- so you probably actually should just use "0x%08x"
anyway.
In Bootstrap 4 they use
box-shadow: 0 0 0 0px rgba(0,123,255,0);
on :focus, si i solved my problem with
a.active.focus,
a.active:focus,
a.focus,
a:active.focus,
a:active:focus,
a:focus,
button.active.focus,
button.active:focus,
button.focus,
button:active.focus,
button:active:focus,
button:focus,
.btn.active.focus,
.btn.active:focus,
.btn.focus,
.btn:active.focus,
.btn:active:focus,
.btn:focus {
outline: 0;
outline-color: transparent;
outline-width: 0;
outline-style: none;
box-shadow: 0 0 0 0 rgba(0,123,255,0);
}
Here is the way to add/append a row in pandas DataFrame
def add_row(df, row):
df.loc[-1] = row
df.index = df.index + 1
return df.sort_index()
add_row(df, [1,2,3])
It can be used to insert/append a row in empty or populated pandas DataFrame
If you want to print multiple rows, you can iterate through the result by using a cursor. e.g. print all names from sys.database_principals
DECLARE @name nvarchar(128)
DECLARE cur CURSOR FOR
SELECT name FROM sys.database_principals
OPEN cur
FETCH NEXT FROM cur INTO @name;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @name
FETCH NEXT FROM cur INTO @name;
END
CLOSE cur;
DEALLOCATE cur;
Presumably, since you're not providing a value for the DB_ID
column, that value is being populated by a row-level before insert trigger defined on the table. That trigger, presumably, is selecting the value from a sequence.
Since the data was moved (presumably recently) from the production database, my wager would be that when the data was copied, the sequence was not modified as well. I would guess that the sequence is generating values that are much lower than the largest DB_ID
that is currently in the table leading to the error.
You could confirm this suspicion by looking at the trigger to determine which sequence is being used and doing a
SELECT <<sequence name>>.nextval
FROM dual
and comparing that to
SELECT MAX(db_id)
FROM cmdb_db
If, as I suspect, the sequence is generating values that already exist in the database, you could increment the sequence until it was generating unused values or you could alter it to set the INCREMENT
to something very large, get the nextval once, and set the INCREMENT
back to 1.
Sometime I have to work from home and connect to office through vpn. Internal domain names should be resolved to different IPs at home. There are several names that have to be changed between office and home. For example:
At office, a => 192.168.0.3, b => 192.168.0.52.
At home, a => 10.6.1.7, b => 10.4.5.23.
My solution is to create two files: C:\WINDOWS\system32\drivers\etc\hosts-home and C:\WINDOWS\system32\drivers\etc\hosts-office. Each of them contains set of name-to-IP mapping. From Administrator PowerShell, When I work at the office, execute
C:\WINDOWS\system32> cp .\drivers\etc\hosts-office .\drivers\etc\hosts
When I arrive at home, execute
C:\WINDOWS\system32> cp .\drivers\etc\hosts-home .\drivers\etc\hosts
And if you would like to use an existing context, rather than a new context which would be loaded from xml configuration by org.springframework.web.context.ContextLoaderListener, then see -> https://stackoverflow.com/a/40694787/3004747
In addition to answer of @jww, I would like to say that the configuration in openssl-ca.cnf,
default_days = 1000 # How long to certify for
defines the default number of days the certificate signed by this root-ca will be valid. To set the validity of root-ca itself you should use '-days n' option in:
openssl req -x509 -days 3000 -config openssl-ca.cnf -newkey rsa:4096 -sha256 -nodes -out cacert.pem -outform PEM
Failing to do so, your root-ca will be valid for only the default one month and any certificate signed by this root CA will also have validity of one month.
Perhaps appending DateTime.Now.Ticks
instead, is a tiny bit faster since you won't be creating 3 strings and the ticks value will always be unique also.
In Command line we can check our installed ng version.
ng -v OR ng --version OR ng version
This will give you like this :
_ _ ____ _ ___
/ \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _|
/ ? \ | '_ \ / _` | | | | |/ _` | '__| | | | | | |
/ ___ \| | | | (_| | |_| | | (_| | | | |___| |___ | |
/_/ \_\_| |_|\__, |\__,_|_|\__,_|_| \____|_____|___|
|___/
Angular CLI: 1.6.5
Node: 8.0.0
OS: linux x64
Angular:
...
If you use Spring Framework. There is: org.springframework.util.MultiValueMap
.
To create unmodifiable multi value map:
Map<String,List<String>> map = ...
MultiValueMap<String, String> multiValueMap = CollectionUtils.toMultiValueMap(map);
Or use org.springframework.util.LinkedMultiValueMap
In Excel, you can set a Range.NumberFormat
to any string as you would find in the "Custom" format selection. Essentially, you have two choices:
You have a view model to which your view is strongly typed => use strongly typed helpers:
<%= Html.DropDownListFor(
x => x.SelectedAccountId,
new SelectList(Model.Accounts, "Value", "Text")
) %>
Also notice that I use a SelectList
for the second argument.
And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:
public ActionResult AccountTransaction()
{
var accounts = Services.AccountServices.GetAccounts(false);
var viewModel = new AccountTransactionView
{
Accounts = accounts.Select(a => new SelectListItem
{
Text = a.Description,
Value = a.AccountId.ToString()
})
};
return View(viewModel);
}
After creating your QVBoxLayout
in Qt Designer, right-click on the background of your widget/dialog/window (not the QVBoxLayout
, but the parent widget) and select Lay Out -> Lay Out in a Grid from the bottom of the context-menu. The QVBoxLayout
should now stretch to fit the window and will resize automatically when the entire window is resized.
Note: The following applies to Windows PowerShell.
See the next section for the cross-platform PowerShell Core (v6+) edition.
On PSv5.1 or higher, where >
and >>
are effectively aliases of Out-File
, you can set the default encoding for >
/ >>
/ Out-File
via the $PSDefaultParameterValues
preference variable:
$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
On PSv5.0 or below, you cannot change the encoding for >
/ >>
, but, on PSv3 or higher, the above technique does work for explicit calls to Out-File
.
(The $PSDefaultParameterValues
preference variable was introduced in PSv3.0).
On PSv3.0 or higher, if you want to set the default encoding for all cmdlets that support
an -Encoding
parameter (which in PSv5.1+ includes >
and >>
), use:
$PSDefaultParameterValues['*:Encoding'] = 'utf8'
If you place this command in your $PROFILE
, cmdlets such as Out-File
and Set-Content
will use UTF-8 encoding by default, but note that this makes it a session-global setting that will affect all commands / scripts that do not explicitly specify an encoding via their -Encoding
parameter.
Similarly, be sure to include such commands in your scripts or modules that you want to behave the same way, so that they indeed behave the same even when run by another user or a different machine; however, to avoid a session-global change, use the following form to create a local copy of $PSDefaultParameterValues
:
$PSDefaultParameterValues = @{ '*:Encoding' = 'utf8' }
Caveat: PowerShell, as of v5.1, invariably creates UTF-8 files _with a (pseudo) BOM_, which is customary only in the Windows world - Unix-based utilities do not recognize this BOM (see bottom); see this post for workarounds that create BOM-less UTF-8 files.
For a summary of the wildly inconsistent default character encoding behavior across many of the Windows PowerShell standard cmdlets, see the bottom section.
The automatic $OutputEncoding
variable is unrelated, and only applies to how PowerShell communicates with external programs (what encoding PowerShell uses when sending strings to them) - it has nothing to do with the encoding that the output redirection operators and PowerShell cmdlets use to save to files.
PowerShell is now cross-platform, via its PowerShell Core edition, whose encoding - sensibly - defaults to BOM-less UTF-8, in line with Unix-like platforms.
This means that source-code files without a BOM are assumed to be UTF-8, and using >
/ Out-File
/ Set-Content
defaults to BOM-less UTF-8; explicit use of the utf8
-Encoding
argument too creates BOM-less UTF-8, but you can opt to create files with the pseudo-BOM with the utf8bom
value.
If you create PowerShell scripts with an editor on a Unix-like platform and nowadays even on Windows with cross-platform editors such as Visual Studio Code and Sublime Text, the resulting *.ps1
file will typically not have a UTF-8 pseudo-BOM:
Conversely, files that do have the UTF-8 pseudo-BOM can be problematic on Unix-like platforms, as they cause Unix utilities such as cat
, sed
, and awk
- and even some editors such as gedit
- to pass the pseudo-BOM through, i.e., to treat it as data.
bash
with, say, text=$(cat file)
or text=$(<file)
- the resulting variable will contain the pseudo-BOM as the first 3 bytes.Regrettably, the default character encoding used in Windows PowerShell is wildly inconsistent; the cross-platform PowerShell Core edition, as discussed in the previous section, has commendably put and end to this.
Note:
The following doesn't aspire to cover all standard cmdlets.
Googling cmdlet names to find their help topics now shows you the PowerShell Core version of the topics by default; use the version drop-down list above the list of topics on the left to switch to a Windows PowerShell version.
As of this writing, the documentation frequently incorrectly claims that ASCII is the default encoding in Windows PowerShell - see this GitHub docs issue.
Cmdlets that write:
Out-File
and >
/ >>
create "Unicode" - UTF-16LE - files by default - in which every ASCII-range character (too) is represented by 2 bytes - which notably differs from Set-Content
/ Add-Content
(see next point); New-ModuleManifest
and Export-CliXml
also create UTF-16LE files.
Set-Content
(and Add-Content
if the file doesn't yet exist / is empty) uses ANSI encoding (the encoding specified by the active system locale's ANSI legacy code page, which PowerShell calls Default
).
Export-Csv
indeed creates ASCII files, as documented, but see the notes re -Append
below.
Export-PSSession
creates UTF-8 files with BOM by default.
New-Item -Type File -Value
currently creates BOM-less(!) UTF-8.
The Send-MailMessage
help topic also claims that ASCII encoding is the default - I have not personally verified that claim.
Start-Transcript
invariably creates UTF-8 files with BOM, but see the notes re -Append
below.
Re commands that append to an existing file:
>>
/ Out-File -Append
make no attempt to match the encoding of a file's existing content.
That is, they blindly apply their default encoding, unless instructed otherwise with -Encoding
, which is not an option with >>
(except indirectly in PSv5.1+, via $PSDefaultParameterValues
, as shown above).
In short: you must know the encoding of an existing file's content and append using that same encoding.
Add-Content
is the laudable exception: in the absence of an explicit -Encoding
argument, it detects the existing encoding and automatically applies it to the new content.Thanks, js2010. Note that in Windows PowerShell this means that it is ANSI encoding that is applied if the existing content has no BOM, whereas it is UTF-8 in PowerShell Core.
This inconsistency between Out-File -Append
/ >>
and Add-Content
, which also affects PowerShell Core, is discussed in this GitHub issue.
Export-Csv -Append
partially matches the existing encoding: it blindly appends UTF-8 if the existing file's encoding is any of ASCII/UTF-8/ANSI, but correctly matches UTF-16LE and UTF-16BE.
To put it differently: in the absence of a BOM, Export-Csv -Append
assumes UTF-8 is, whereas Add-Content
assumes ANSI.
Start-Transcript -Append
partially matches the existing encoding: It correctly matches encodings with BOM, but defaults to potentially lossy ASCII encoding in the absence of one.
Cmdlets that read (that is, the encoding used in the absence of a BOM):
Get-Content
and Import-PowerShellDataFile
default to ANSI (Default
), which is consistent with Set-Content
.
ANSI is also what the PowerShell engine itself defaults to when it reads source code from files.
By contrast, Import-Csv
, Import-CliXml
and Select-String
assume UTF-8 in the absence of a BOM.
My problem
get_courses(); //// To load the course list
$("#course").val(course); //// Setting default value of the list
I had the same issue . The Only difference from your code is that I was loading the select box through an ajax call and soon as the ajax call was executed I had set the default value of the select box
The Solution
get_courses();
setTimeout(function() {
$("#course").val(course);
}, 10);
 
is the numeric reference for the entity reference
— they are the exact same thing. It's likely your editor is simply inserting the numberic reference instead of the named one.
See the Wikipedia page for the non-breaking space.
This should do the trick:
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
} // Author: silentnuke
Don't forget to add the internet permission in your manifest.
The answer that worked for me was indeed what OP mentions in his 2015 update: uncheck these two boxes in your Python run config:
I already had the run config set to use the proper venv, so PyCharm doing additional work to add things to the path was not necessary. Instead it was causing errors.
If using the following HTML:
<button id="submit-button"></button>
Style can be applied through JS using the style object available on an HTMLElement.
To set height and width to 200px of the above example button, this would be the JS:
var myButton = document.getElementById('submit-button');
myButton.style.height = '200px';
myButton.style.width= '200px';
I believe with this method, you are not directly writing CSS (inline or external), but using JavaScript to programmatically alter CSS Declarations.
The nproc command shows the number of processing units available:
$ nproc
Sample outputs: 4
lscpu gathers CPU architecture information form /proc/cpuinfon in human-read-able format:
$ lscpu
Sample outputs:
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
CPU(s): 8
On-line CPU(s) list: 0-7
Thread(s) per core: 1
Core(s) per socket: 4
CPU socket(s): 2
NUMA node(s): 1
Vendor ID: GenuineIntel
CPU family: 6
Model: 15
Stepping: 7
CPU MHz: 1866.669
BogoMIPS: 3732.83
Virtualization: VT-x
L1d cache: 32K
L1i cache: 32K
L2 cache: 4096K
NUMA node0 CPU(s): 0-7
There is equally formatDate
const format = 'dd/MM/yyyy';
const myDate = '2019-06-29';
const locale = 'en-US';
const formattedDate = formatDate(myDate, format, locale);
According to the API it takes as param either a date string, a Date object, or a timestamp.
Gotcha: Out of the box, only en-US
is supported.
If you need to add another locale, you need to add it and register it in you app.module, for example for Spanish:
import { registerLocaleData } from '@angular/common';
import localeES from "@angular/common/locales/es";
registerLocaleData(localeES, "es");
Don't forget to add corresponding import:
import { formatDate } from "@angular/common";
The following example demonstrates how to POST a JSON via WebClient.UploadString Method:
var vm = new { k = "1", a = "2", c = "3", v= "4" };
using (var client = new WebClient())
{
var dataString = JsonConvert.SerializeObject(vm);
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
client.UploadString(new Uri("http://www.contoso.com/1.0/service/action"), "POST", dataString);
}
Prerequisites: Json.NET library
This code- (sets currency to GB(Britain/UK/England/£) then prints a line. Then sets currency to US/$ and prints a line)
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB",false);
Console.WriteLine("bbbbbbb {0:c}",4321.2);
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US",false);
Console.WriteLine("bbbbbbb {0:c}",4321.2);
Will display-
bbbbbbb £4,321.20
bbbbbbb $4,321.20
For a list of culture names e.g. en-GB en-US e.t.c.
http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo(v=vs.80).aspx
Short answer: Fabulous.
Long answer: Something like....
static SomeSingleton *instance = NULL;
@implementation SomeSingleton
+ (id) instance {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (instance == NULL){
instance = [[super allocWithZone:NULL] init];
}
});
return instance;
}
+ (id) allocWithZone:(NSZone *)paramZone {
return [[self instance] retain];
}
- (id) copyWithZone:(NSZone *)paramZone {
return self;
}
- (id) autorelease {
return self;
}
- (NSUInteger) retainCount {
return NSUIntegerMax;
}
- (id) retain {
return self;
}
@end
Be sure to read the dispatch/once.h header to understand what's going on. In this case the header comments are more applicable than the docs or man page.
This error is coming because some process is already running on 8081 port. Stop that process and then run your command, it will run your code. For this first list all the process which are using this port by typing
lsof -i :8081
This command will list the process id (PID) of the process and then kill the node process by using
kill -9 <PID>
Here PID is the process id of the node process.
Its always better to go for a generic reusable function in your project which returns whether the extension loaded. You can use the following function to check -
function isExtensionLoaded($extension_name){
return extension_loaded($extension_name);
}
Usage
echo isExtensionLoaded('curl');
echo isExtensionLoaded('gd');
I know this is an old question, but I was looking for the similar thing. Determine when the 'X' was clicked to clear the search box. None of the answers here helped me at all. One was close but also affected when the user hit the 'enter' button, it would fire the same result as clicking the 'X'.
I found this answer on another post and it works perfect for me and only fires when the user clears the search box.
$("input").bind("mouseup", function(e){
var $input = $(this),
oldValue = $input.val();
if (oldValue == "") return;
// When this event is fired after clicking on the clear button
// the value is not cleared yet. We have to wait for it.
setTimeout(function(){
var newValue = $input.val();
if (newValue == ""){
// capture the clear
$input.trigger("cleared");
}
}, 1);
});
From oracle Sql developer, execute the below in sql worksheet:
create user lctest identified by lctest;
grant dba to lctest;
then right click on "Oracle connection" -> new connection, then make everything lctest from connection name to user name password. Test connection shall pass. Then after connected you will see the schema.