Linux is now officially supported in brew - see the Homebrew 2.0.0 blog post. As shown on https://brew.sh, just copy/paste this into a command prompt:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
In my case, all I had to do was add the following User variable on Windows:
Variable name: HOME
Variable value: %USERPROFILE%
How to set a Environment Variable (You can use the User variables for username section if you are not a system administrator)
Best way to solve this until a fix is available (if a fix comes) is to force IE compatibility mode on the user.
Use <META http-equiv="X-UA-Compatible" content="IE=9">
ideally in the masterpage so all pages in your site get the workaround.
You could try to source your profile file to update your environment:
$ source ~/.profile
Try the SetField method:
table.Rows[i].SetField(column, value);
table.Rows[i].SetField(columnIndex, value);
table.Rows[i].SetField(columnName, value);
This should get the job done and is a bit "cleaner" than using Rows[i][j].
In addition to answer of @gjha:
inline std::string ltrim_copy(const std::string& str)
{
auto it = std::find_if(str.cbegin(), str.cend(),
[](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
return std::string(it, str.cend());
}
inline std::string rtrim_copy(const std::string& str)
{
auto it = std::find_if(str.crbegin(), str.crend(),
[](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
return it == str.crend() ? std::string() : std::string(str.cbegin(), ++it.base());
}
inline std::string trim_copy(const std::string& str)
{
auto it1 = std::find_if(str.cbegin(), str.cend(),
[](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
if (it1 == str.cend()) {
return std::string();
}
auto it2 = std::find_if(str.crbegin(), str.crend(),
[](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
return it2 == str.crend() ? std::string(it1, str.cend()) : std::string(it1, ++it2.base());
}
ls -ltrh /proc | grep YOUR-PID-HERE
For example, my Google Chrome's PID is 11583:
ls -l /proc | grep 11583
dr-xr-xr-x 7 adam adam 0 2011-04-20 16:34 11583
For OSX:
I had installed this via Anaconda, and had a hell of a time getting it to work. What helped was adding the Anaconda bin AND pkgs folder to my PATH.
Since I use fishshell, I did it in my ~/.config/fish/config.fish
file like this:
set -g -x PATH $PATH /Users/cbrevik/anaconda/bin /Users/cbrevik/anaconda/pkgs
If you use fishshell like me, this answer will probably save you some trouble later using pandas as well.
Most of the times, the issue is with the paths you have mentioned for 'java home' and 'javac' tags in settings.xml which is present in your .m2 repository and the issue is not with your path variable or Java_Home variable. If you check and correct the same, you should be able to execute your commands successfully. - Jaihind
I use the way shown below. It submits everything like files.
$(document).on("submit", "form", function(event)
{
event.preventDefault();
var url = $(this).attr("action");
$.ajax({
url: url,
type: 'POST',
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
console.log("error");
}
});
});
I just came across this problem and wanted to find something about the performance, but I couldn't, so I wrote a benchmarking script on my own:
% Config:
rows = 1e6;
runs = 50;
% Start:
orig = round(rand(rows, 1));
t1 = 0;
for i = 1:runs
A = orig;
tic
A(A == 0) = [];
t1 = t1 + toc;
end
t1 = t1 / runs;
t2 = 0;
for i = 1:runs
A = orig;
tic
A = A(A ~= 0);
t2 = t2 + toc;
end
t2 = t2 / runs;
t1
t2
t1 / t2
So you see, the solution using A = A(A ~= 0)
is the quicker of the two :)
bcdiv($number, 1, 2) // 2 varies for digits after the decimal point
This will display exactly two digits after the decimal point.
Advantage:
If you want to display two digits after a float value only and not for int, then use this.
Try this
SELECT CONVERT(varchar(11),getdate(),101) -- Converts to 'mm/dd/yyyy'
SELECT CONVERT(varchar(11),getdate(),103) -- Converts to 'dd/mm/yyyy'
More info here: https://msdn.microsoft.com/en-us/library/ms187928.aspx
if you want to open all your .cpp
files with one command, and have the window split in as many tiles as opened files, you can use:
vim -o $(find name ".cpp")
if you want to include a template in the place you are, you can use:
:r ~/myHeaderTemplate
will import the file "myHeaderTemplate in the place the cursor was before starting the command.
you can conversely select visually some code and save it to a file
when you select visualy, after type ":" in order to enter a command, you'll see "'<,'>" appear after the ":"
'<,'>w ~/myfile $
^ if you add "~/myfile" to the command, the selected part of the file will be saved to myfile.
if you're editing a file an want to copy it :
:saveas newFileWithNewName
I wrote shell script below (named start.sh
).
Because my package.json
has prestart
option.
So I want to run npm start
.
#!/bin/bash
cd /path/to/project
npm start
Then, start start.sh
by pm2.
pm2 start start.sh --name appNameYouLike
.div-table {
display: table;
width: auto;
background-color: #eee;
border: 1px solid #666666;
border-spacing: 5px; /* cellspacing:poor IE support for this */
}
.div-table-row {
display: table-row;
width: auto;
clear: both;
}
.div-table-col {
float: left; /* fix for buggy browsers */
display: table-column;
width: 200px;
background-color: #ccc;
}
Runnable snippet:
.div-table {_x000D_
display: table; _x000D_
width: auto; _x000D_
background-color: #eee; _x000D_
border: 1px solid #666666; _x000D_
border-spacing: 5px; /* cellspacing:poor IE support for this */_x000D_
}_x000D_
.div-table-row {_x000D_
display: table-row;_x000D_
width: auto;_x000D_
clear: both;_x000D_
}_x000D_
.div-table-col {_x000D_
float: left; /* fix for buggy browsers */_x000D_
display: table-column; _x000D_
width: 200px; _x000D_
background-color: #ccc; _x000D_
}
_x000D_
<body>_x000D_
<form id="form1">_x000D_
<div class="div-table">_x000D_
<div class="div-table-row">_x000D_
<div class="div-table-col" align="center">Customer ID</div>_x000D_
<div class="div-table-col">Customer Name</div>_x000D_
<div class="div-table-col">Customer Address</div>_x000D_
</div>_x000D_
<div class="div-table-row">_x000D_
<div class="div-table-col">001</div>_x000D_
<div class="div-table-col">002</div>_x000D_
<div class="div-table-col">003</div>_x000D_
</div>_x000D_
<div class="div-table-row">_x000D_
<div class="div-table-col">xxx</div>_x000D_
<div class="div-table-col">yyy</div>_x000D_
<div class="div-table-col">www</div>_x000D_
</div>_x000D_
<div class="div-table-row">_x000D_
<div class="div-table-col">ttt</div>_x000D_
<div class="div-table-col">uuu</div>_x000D_
<div class="div-table-col">Mkkk</div>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</form>_x000D_
</body>
_x000D_
I have had the unfortunate task of testing threaded code and they are definitely the hardest tests I have ever written.
When writing my tests, I used a combination of delegates and events. Basically it is all about using PropertyNotifyChanged
events with a WaitCallback
or some kind of ConditionalWaiter
that polls.
I am not sure if this was the best approach, but it has worked out for me.
with Kotlin I execute this code:
requireContext().startActivity<YourTargetActivity>()
SELECT TOP 1000 MAX(tel) FROM TableName WHERE Id IN
(
SELECT Id FROM TableName
GROUP BY Id
HAVING COUNT(*) > 1
)
GROUP BY Id
Add this in your Xml - android:background="@android:color/transparent"
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Button"
android:background="@android:color/transparent"
android:textStyle="bold"/>
My particular use-case was selecting a text range inside an editable span element, which, as far as I could see, is not described in any of the answers here.
The main difference is that you have to pass a node of type Text
to the Range
object, as described in the documentation of Range.setStart():
If the startNode is a Node of type Text, Comment, or CDATASection, then startOffset is the number of characters from the start of startNode. For other Node types, startOffset is the number of child nodes between the start of the startNode.
The Text
node is the first child node of a span element, so to get it, access childNodes[0]
of the span element. The rest is the same as in most other answers.
Here a code example:
var startIndex = 1;
var endIndex = 5;
var element = document.getElementById("spanId");
var textNode = element.childNodes[0];
var range = document.createRange();
range.setStart(textNode, startIndex);
range.setEnd(textNode, endIndex);
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
Other relevant documentation:
Range
Selection
Document.createRange()
Window.getSelection()
private List<FileInfo> GetLastUpdatedFileInDirectory(DirectoryInfo directoryInfo)
{
FileInfo[] files = directoryInfo.GetFiles();
List<FileInfo> lastUpdatedFile = null;
DateTime lastUpdate = new DateTime(1, 0, 0);
foreach (FileInfo file in files)
{
if (file.LastAccessTime > lastUpdate)
{
lastUpdatedFile.Add(file);
lastUpdate = file.LastAccessTime;
}
}
return lastUpdatedFile;
}
You can create swap space using the following steps
Here we are creating swap at /home/
dd if=/dev/zero of=/home/swapfile1 bs=1024 count=8388608
Here count is kilobyte count of swap space
mkswap /home/swapfile1
vi /etc/fstab
make entry :
/home/swapfile1 swap swap defaults 0 0
run:
swapon -a
I wrote an article on topis how to [manually install curl on debian linu][1]x.
[1]: http://www.jasom.net/how-to-install-curl-command-manually-on-debian-linux. This is its shortcut:
And restart Apache. If you will have an error during point 6, try to run apt-get install build-essential.
Continuum Analytics now provides instructions on how to setup Anaconda with various IDEs including Pycharm here. However, with Pycharm 5.0.1 running on Unbuntu 15.10 Project Interpreter settings were found via the File | Settings and then under the Project branch of the treeview on the Settings dialog.
Well, excel never pops up the wizard for CSV files. If you rename it to .txt, you'll see the wizard when you do a File>Open in Excel the next time.
I'm always surprised by the extensive use of trailing slashes on non-directory URLs (WordPress among others). This really shouldn't be an either-or debate because putting a slash after a resource is semantically wrong. The web was designed to deliver addressable resources, and those addresses - URLs - were designed to emulate a *nix-style file-system hierarchy. In that context:
Using these guidelines, it's wrong to put a slash after a non-directory resource.
If both are not going to be modified (no adding/deleting items - modifying existing ones is fine as long as you pay heed to threading issues), you can simply pass around data.begin() + 100000
and data.begin() + 101000
, and pretend that they are the begin()
and end()
of a smaller vector.
Or, since vector storage is guaranteed to be contiguous, you can simply pass around a 1000 item array:
T *arrayOfT = &data[0] + 100000;
size_t arrayOfTLength = 1000;
Both these techniques take constant time, but require that the length of data doesn't increase, triggering a reallocation.
It worked for me, but the exe4j can leave a signature when you double click the .exe application
Using the command "where git" find out how command prompt picks up the version. Once you have the path, you can go ahead and uninstall / delete previous version completely. Then if you install and make sure the new installed location is in the path, it should just work fine.
Using git-friendly tools like cmder will make your life much easier. You don't really have to use dual boot or cygwin anymore since the support for git in windows is already top-notch now. (Git for windows installs msysgit which includes all necessary unix tools from MinGW. MinGW has been there for a while and is pretty stable. If you want you can install the full version of msysgit rather than Git for Windows. msysgit is available on Git for windows page at the bottom.)
When you parse the JSON representation, it'll become a JavaScript array of objects.
Because of this, you can use the .length
property of the JavaScript array to see how many elements are contained, and use a for
loop to enumerate it.
Set the user name as data-username
attribute to the button and also a class:
HTML
<input type="button" name="theButton" value="Detail" class="btn" data-username="{{result['username']}}" />
JS
$(document).on('click', '.btn', function() {
var name = $(this).data('username');
if (name != undefined && name != null) {
window.location = '/player_detail?username=' + name;
}
});?
EDIT:
Also, you can simply check for undefined
&& null
using:
$(document).on('click', '.btn', function() {
var name = $(this).data('username');
if (name) {
window.location = '/player_detail?username=' + name;
}
});?
As, mentioned in this answer
if (name) {
}
will evaluate to true if value is not:
The above list represents all possible falsy values in ECMA/Javascript.
How about this?
INSERT OR IGNORE INTO EVENTTYPE (EventTypeName) VALUES 'ANI Received'
(Untested as I don't have SQLite... however this link is quite descriptive.)
Additionally, this should also work:
INSERT INTO EVENTTYPE (EventTypeName)
SELECT 'ANI Received'
WHERE NOT EXISTS (SELECT 1 FROM EVENTTYPE WHERE EventTypeName = 'ANI Received');
You put inside img tag physical path you your image. Instead of that you should put virtual path (according to root of web application) to your image. This value depends on location of your image and your html page.
for example if you have:
/yourDir
-page.html
-66.jpg
in your page.html it should be something like that:
<img src="66.jpg" width="400" height="400" ></img>
second scenario:
/images
-66.jpg
/html
page.html
So your img should look like:
<img src="../images/66.jpg" width="400" height="400" ></img>
What you're doing is creating a temporary. That temporary exists in a scope determined by the compiler, such that it's long enough to satisfy the requirements of where it's going.
As soon as the statement const char* cstr2 = ss.str().c_str();
is complete, the compiler sees no reason to keep the temporary string around, and it's destroyed, and thus your const char *
is pointing to free'd memory.
Your statement string str(ss.str());
means that the temporary is used in the constructor for the string
variable str
that you've put on the local stack, and that stays around as long as you'd expect: until the end of the block, or function you've written. Therefore the const char *
within is still good memory when you try the cout
.
In mi and vivo - Using the above solution is not enough. You must also tell the user to add permission manually. You can help them by opening the right location inside phone settings. Varies for different phone models.
EDIT:
This answer might not work depending if you're not targeting es5
anymore, I'll try to make the answer more complete.
Original Answer
If CommonJS isn't installed (which defines exports
), you have to remove this line from your tsconfig.json
:
"module": "commonjs",
As per the comments, this alone may not work with later versions of tsc
. If that is the case, you can install a module loader like CommonJS, SystemJS or RequireJS and then specify that.
Note:
Look at your main.js
file that tsc
generated. You will find this at the very top:
Object.defineProperty(exports, "__esModule", { value: true });
It is the root of the error message, and after removing "module": "commonjs",
, it will vanish.
I used this bubble sort because I wasnt able to order them by the .value in the options array and it was a number. This way I got them properly ordered. I hope it's useful to you too.
function sortSelect(selElem) {
for (var i=0; i<(selElem.options.length-1); i++)
for (var j=i+1; j<selElem.options.length; j++)
if (parseInt(selElem.options[j].value) < parseInt(selElem.options[i].value)) {
var dummy = new Option(selElem.options[i].text, selElem.options[i].value);
selElem.options[i] = new Option(selElem.options[j].text, selElem.options[j].value);
selElem.options[j] = dummy;
}
}
in addition to @lonkly solution
method:
/**
* lookup a resource id by field name in static R.class
*
* @author - ceph3us
* @param variableName - name of drawable, e.g R.drawable.<b>image</b>
* @param ? - class of resource, e.g R.drawable.class or R.raw.class
* @return integer id of resource
*/
public static int getResId(String variableName, Class<?> ?)
throws android.content.res.Resources.NotFoundException {
try {
// lookup field in class
java.lang.reflect.Field field = ?.getField(variableName);
// always set access when using reflections
// preventing IllegalAccessException
field.setAccessible(true);
// we can use here also Field.get() and do a cast
// receiver reference is null as it's static field
return field.getInt(null);
} catch (Exception e) {
// rethrow as not found ex
throw new Resources.NotFoundException(e.getMessage());
}
}
For anyone else having the same problem, I figured it out myself.
<html>_x000D_
<body>_x000D_
<form target="_blank" action="https://website.com/action.php" method="POST">_x000D_
<input type="hidden" name="fullname" value="Sam" />_x000D_
<input type="hidden" name="city" value="Dubai " />_x000D_
<input onclick="window.location.href = 'https://website.com/my-account';" type="submit" value="Submit request" />_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
All I had to do was add the target="_blank" attribute to inline on form to open the response in a new page and redirect the other page using onclick on the submit button.
$("#ddtypeoftraining option[value=5]").css("display", "none"); $('#ddtypeoftraining').selectpicker('refresh');
As this post gets a bit of popularity I edited it a bit. Spring Boot 2.x.x changed default JDBC connection pool from Tomcat to faster and better HikariCP. Here comes incompatibility, because HikariCP uses different property of jdbc url. There are two ways how to handle it:
OPTION ONE
There is very good explanation and workaround in spring docs:
Also, if you happen to have Hikari on the classpath, this basic setup does not work, because Hikari has no url property (but does have a jdbcUrl property). In that case, you must rewrite your configuration as follows:
app.datasource.jdbc-url=jdbc:mysql://localhost/test
app.datasource.username=dbuser
app.datasource.password=dbpass
OPTION TWO
There is also how-to in the docs how to get it working from "both worlds". It would look like below. ConfigurationProperties bean would do "conversion" for jdbcUrl
from app.datasource.url
@Configuration
public class DatabaseConfig {
@Bean
@ConfigurationProperties("app.datasource")
public DataSourceProperties dataSourceProperties() {
return new DataSourceProperties();
}
@Bean
@ConfigurationProperties("app.datasource")
public HikariDataSource dataSource(DataSourceProperties properties) {
return properties.initializeDataSourceBuilder().type(HikariDataSource.class)
.build();
}
}
Update
If your popover is going to have a selector that is consistent then you can make use of selector
property of popover constructor.
var popOverSettings = {
placement: 'bottom',
container: 'body',
html: true,
selector: '[rel="popover"]', //Sepcify the selector here
content: function () {
return $('#popover-content').html();
}
}
$('body').popover(popOverSettings);
Other ways:
Mutation Event
/Mutation Observer
to identify if a particular element has been inserted on to the ul
or an element.var popOverSettings = { //Save the setting for later use as well
placement: 'bottom',
container: 'body',
html: true,
//content:" <div style='color:red'>This is your div content</div>"
content: function () {
return $('#popover-content').html();
}
}
$('ul').on('DOMNodeInserted', function () { //listed for new items inserted onto ul
$(event.target).popover(popOverSettings);
});
$("button[rel=popover]").popover(popOverSettings);
$('.pop-Add').click(function () {
$('ul').append("<li class='project-name'> <a>project name 2 <button class='pop-function' rel='popover'></button> </a> </li>");
});
But it is not recommended to use DOMNodeInserted Mutation Event for performance issues as well as support. This has been deprecated as well. So your best bet would be to save the setting and bind after you update with new element.
Another recommended way is to use MutationObserver instead of MutationEvent according to MDN, but again support in some browsers are unknown and performance a concern.
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
// create an observer instance
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
$(mutation.addedNodes).popover(popOverSettings);
});
});
// configuration of the observer:
var config = {
attributes: true,
childList: true,
characterData: true
};
// pass in the target node, as well as the observer options
observer.observe($('ul')[0], config);
Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin
not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors
at your server side.
You can fetch request using mode: 'cors'
. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.
So in both condition you need to configure cors
in your server or you need to use custom proxy server.
Bit late for reply but this should do the trick
Type myType = Type.GetType("AssemblyQualifiedName");
your assembly qualified name should be like this
"Boom.Bam.Class, Boom.Bam, Version=1.0.0.262, Culture=neutral, PublicKeyToken=e16dba1a3c4385bd"
EDIT: See the other answers for better solutions
The original newbie approaches that I offered were (opt1):
$qb->where("e.fecha > '" . $monday->format('Y-m-d') . "'");
$qb->andWhere("e.fecha < '" . $sunday->format('Y-m-d') . "'");
And (opt2):
$qb->add('where', "e.fecha between '2012-01-01' and '2012-10-10'");
That was quick and easy and got the original poster going immediately.
Hence the accepted answer.
As per comments, it is the wrong answer, but it's an easy mistake to make, so I'm leaving it here as a "what not to do!"
From CSS
video {
position: fixed; right: 0; bottom: 0;
min-width: 100%; min-height: 100%;
width: auto; height: auto; z-index: -100;
background: url(polina.jpg) no-repeat;
background-size: cover;
}
Updating to 4.0.0
Updating to 4 is as easy as updating your Angular dependencies to the latest version, and double checking if you want animations. This will work for most use cases.
On Linux/Mac:
npm install @angular/{common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router,animations}@latest typescript@latest --save
On Windows:
npm install @angular/common@latest @angular/compiler@latest @angular/compiler-cli@latest @angular/core@latest @angular/forms@latest @angular/http@latest @angular/platform-browser@latest @angular/platform-browser-dynamic@latest @angular/platform-server@latest @angular/router@latest @angular/animations@latest typescript@latest --save
Then run whatever ng serve or npm start command you normally use, and everything should work.
If you rely on Animations, import the new BrowserAnimationsModule
from @angular/platform-browser/animations
in your root NgModule
. Without this, your code will compile and run, but animations will trigger an error. Imports from @angular/core
were deprecated, use imports from the new package
import { trigger, state, style, transition, animate } from '@angular/animations';.
msiexec.exe /x "{588A9A11-1E20-4B91-8817-2D36ACBBBF9F}" /q
on your onCreate method add setHasOptionMenu()
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
Then override your onCreateOptionsMenu
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.add("Menu item")
.setIcon(android.R.drawable.ic_delete)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}
Depends, Do you need the data to be loaded each time you open the view? or only once?
viewDidLoad:
Whatever processing you have that needs to be done once.
viewWilLAppear:
Whatever processing that needs to change every time the page is loaded.
Labels, icons, button titles or most dataInputedByDeveloper usually don't change. Names, photos, links, button status, lists (input Arrays for your tableViews or collectionView) or most dataInputedByUser usually do change.
I is because you are using predefined variables to naming your filename. change your filename from e.g register.asp to registerUser.asp. That will solve your issue
When you use git push origin :staleStuff
, it automatically removes origin/staleStuff
, so when you ran git remote prune origin
, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune
to get rid of branches you have removed.
So what exactly git remote prune
does? Main idea: local branches (not tracking branches) are not touched by git remote prune
command and should be removed manually.
Now, a real-world example for better understanding:
You have a remote repository with 2 branches: master
and feature
. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):
refs/heads/master
(short name master
)refs/heads/feature
(short name feature
)refs/remotes/origin/master
(short name origin/master
)refs/remotes/origin/feature
(short name origin/feature
)Now, a typical scenario:
feature
, merges it into master
and removes feature
branch from remote repository.git fetch
(or git pull
), no references are removed from your local repository, so you still have all those 4 references.git remote prune origin
.feature
branch no longer exists, so refs/remotes/origin/feature
is a stale branch which should be removed. refs/heads/feature
, because git remote prune
does not remove any refs/heads/*
references.It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge
configuration parameter. This parameter is not really required for anything to work (probably except git pull
), so it might be missing.
(updated with example & useful info from comments)
Global events are also deprecated.
Here's a patch, which fixes the browser and event issues:
--- jquery.fancybox-1.3.4.js.orig 2010-11-11 23:31:54.000000000 +0100
+++ jquery.fancybox-1.3.4.js 2013-03-22 23:25:29.996796800 +0100
@@ -26,7 +26,9 @@
titleHeight = 0, titleStr = '', start_pos, final_pos, busy = false, fx = $.extend($('<div/>')[0], { prop: 0 }),
- isIE6 = $.browser.msie && $.browser.version < 7 && !window.XMLHttpRequest,
+ isIE = !+"\v1",
+
+ isIE6 = isIE && window.XMLHttpRequest === undefined,
/*
* Private methods
@@ -322,7 +324,7 @@
loading.hide();
if (wrap.is(":visible") && false === currentOpts.onCleanup(currentArray, currentIndex, currentOpts)) {
- $.event.trigger('fancybox-cancel');
+ $('.fancybox-inline-tmp').trigger('fancybox-cancel');
busy = false;
return;
@@ -389,7 +391,7 @@
content.html( tmp.contents() ).fadeTo(currentOpts.changeFade, 1, _finish);
};
- $.event.trigger('fancybox-change');
+ $('.fancybox-inline-tmp').trigger('fancybox-change');
content
.empty()
@@ -612,7 +614,7 @@
}
if (currentOpts.type == 'iframe') {
- $('<iframe id="fancybox-frame" name="fancybox-frame' + new Date().getTime() + '" frameborder="0" hspace="0" ' + ($.browser.msie ? 'allowtransparency="true""' : '') + ' scrolling="' + selectedOpts.scrolling + '" src="' + currentOpts.href + '"></iframe>').appendTo(content);
+ $('<iframe id="fancybox-frame" name="fancybox-frame' + new Date().getTime() + '" frameborder="0" hspace="0" ' + (isIE ? 'allowtransparency="true""' : '') + ' scrolling="' + selectedOpts.scrolling + '" src="' + currentOpts.href + '"></iframe>').appendTo(content);
}
wrap.show();
@@ -912,7 +914,7 @@
busy = true;
- $.event.trigger('fancybox-cancel');
+ $('.fancybox-inline-tmp').trigger('fancybox-cancel');
_abort();
@@ -957,7 +959,7 @@
title.empty().hide();
wrap.hide();
- $.event.trigger('fancybox-cleanup');
+ $('.fancybox-inline-tmp, select:not(#fancybox-tmp select)').trigger('fancybox-cleanup');
content.empty();
You cannot load images directly with @2x
or @3x
, system selects appropriate image automatically, just specify the name using UIImage
:
UIImage(named: "green-square-Retina")
If you are interested in processing Javascript on the server, there is a new open source library called Jint that allows you to execute server side Javascript. Basically it is a Javascript interpreter written in C#. I have been testing it and so far it looks quite promising.
Here's the description from the site:
Differences with other script engines:
Jint is different as it doesn't use CodeDomProvider technique which is using compilation under the hood and thus leads to memory leaks as the compiled assemblies can't be unloaded. Moreover, using this technique prevents using dynamically types variables the way JavaScript does, allowing more flexibility in your scripts. On the opposite, Jint embeds it's own parsing logic, and really interprets the scripts. Jint uses the famous ANTLR (http://www.antlr.org) library for this purpose. As it uses Javascript as its language you don't have to learn a new language, it has proven to be very powerful for scripting purposes, and you can use several text editors for syntax checking.
On most browsers inactive tabs have low priority execution and this can affect JavaScript timers.
If the values of your transition were calculated using real time elapsed between frames instead fixed increments on each interval, you not only workaround this issue but also can achieve a smother animation by using requestAnimationFrame as it can get up to 60fps if the processor isn't very busy.
Here's a vanilla JavaScript example of an animated property transition using requestAnimationFrame
:
var target = document.querySelector('div#target')_x000D_
var startedAt, duration = 3000_x000D_
var domain = [-100, window.innerWidth]_x000D_
var range = domain[1] - domain[0]_x000D_
_x000D_
function start() {_x000D_
startedAt = Date.now()_x000D_
updateTarget(0)_x000D_
requestAnimationFrame(update)_x000D_
}_x000D_
_x000D_
function update() {_x000D_
let elapsedTime = Date.now() - startedAt_x000D_
_x000D_
// playback is a value between 0 and 1_x000D_
// being 0 the start of the animation and 1 its end_x000D_
let playback = elapsedTime / duration_x000D_
_x000D_
updateTarget(playback)_x000D_
_x000D_
if (playback > 0 && playback < 1) {_x000D_
// Queue the next frame_x000D_
requestAnimationFrame(update)_x000D_
} else {_x000D_
// Wait for a while and restart the animation_x000D_
setTimeout(start, duration/10)_x000D_
}_x000D_
}_x000D_
_x000D_
function updateTarget(playback) {_x000D_
// Uncomment the line below to reverse the animation_x000D_
// playback = 1 - playback_x000D_
_x000D_
// Update the target properties based on the playback position_x000D_
let position = domain[0] + (playback * range)_x000D_
target.style.left = position + 'px'_x000D_
target.style.top = position + 'px'_x000D_
target.style.transform = 'scale(' + playback * 3 + ')'_x000D_
}_x000D_
_x000D_
start()
_x000D_
body {_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
div {_x000D_
position: absolute;_x000D_
white-space: nowrap;_x000D_
}
_x000D_
<div id="target">...HERE WE GO</div>
_x000D_
@UpTheCreek comment:
Fine for presentation issues, but still there are some things that you need to keep running.
If you have background tasks that needs to be precisely executed at given intervals, you can use HTML5 Web Workers. Take a look at Möhre's answer below for more details...
This problem and many others could be avoided by using CSS transitions/animations instead of JavaScript based animations which adds a considerable overhead. I'd recommend this jQuery plugin that let's you take benefit from CSS transitions just like the animate()
methods.
Use:
SELECT t1.Notes,
t2.Name
FROM Table1 t1
JOIN Table2 t2 ON t1.Notes LIKE CONCAT('%', t2.Name ,'%')
A 5-minute video explaining how pointers work:
You can find the follow up to the solr-user group on: solr user mailling list
The prevailing thought is that the NOT operator may only be used to remove results from a query - not just exclude things out of the entire dataset. I happen to like the syntax you suggested mausch - thanks!
Using svcutil, you can create interfaces and classes (data contracts) from the WSDL.
svcutil your.wsdl (or svcutil your.wsdl /l:vb if you want Visual Basic)
This will create a file called "your.cs" in C# (or "your.vb" in VB.NET) which contains all the necessary items.
Now, you need to create a class "MyService" which will implement the service interface (IServiceInterface) - or the several service interfaces - and this is your server instance.
Now a class by itself doesn't really help yet - you'll need to host the service somewhere. You need to either create your own ServiceHost instance which hosts the service, configure endpoints and so forth - or you can host your service inside IIS.
The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.
The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.
Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.
You can use :
$url=getimagesize(“http://www.flickr.com/photos/27505599@N07/2564389539/”);
if(!is_array($url))
{
$default_image =”…/directoryFolder/junal.jpg”;
}
Change the FragmentPagerAdapter
to FragmentStatePagerAdapter
.
Override getItemPosition()
method and return POSITION_NONE
.
Eventually, it will listen to the notifyDataSetChanged()
on view pager.
This answer is for "One Man" Team to solve this problem quickly without reading through too many information about "Team"
Step 1) Go to web browser, open your developer account. Go to Certificates, Identifiers & Profiles. Select Certificates / Production. You will see the certificate that was missing private key listed there. Click Revoke. And follow the instructions to remove this certificate. Step 2) That's it! go back to Xcode to Validate you app. It will now ask you to generate a new certificate. Now you happily uploading your apps.
First you need to get rid of all newline characters in all your text nodes. Then you can use an identity transform to output your DOM tree. Look at the javadoc for TransformerFactory#newTransformer()
.
brbcoding have been able to help me with the appropriate coding i needed, here is it
HTML
<input type="checkbox" id="checkme"/>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
Javascript
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
// when unchecked or checked, run the function
checker.onchange = function(){
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
}
In php, we have two option to concatenate table columns.
First Option using Query
In query, CONCAT keyword used to concatenate two columns
SELECT CONCAT(`SUBJECT`,'_', `YEAR`) AS subject_year FROM `table_name`;
Second Option using symbol ( . )
After fetch the data from database table, assign the values to variable, then using ( . ) Symbol and concatenate the values
$subject = $row['SUBJECT'];
$year = $row['YEAR'];
$subject_year = $subject . "_" . $year;
Instead of underscore( _ ) , we will use the spaces, comma, letters,numbers..etc
Make your property "windowname" a DependencyProperty and keep the remaining same.
Lists of bytes are subscriptable (at least in Python 3.6). This way you can retrieve the decimal value of each byte individually.
>>> intlist = [64, 4, 26, 163, 255]
>>> bytelist = bytes(intlist) # b'@x04\x1a\xa3\xff'
>>> for b in bytelist:
... print(b) # 64 4 26 163 255
>>> [b for b in bytelist] # [64, 4, 26, 163, 255]
>>> bytelist[2] # 26
toggleClass works too:
$(window).on("scroll", function() {
$("nav").toggleClass("shrink", $(this).scrollTop() > 50)
});
Here is a great article explaining ByteBuffer benefits. Following are the key points in the article:
Following are benefits specifically for direct ByteBuffer/MappedByteBuffer. Note that direct buffers are created outside of heap:
Unaffected by gc cycles: Direct buffers won't be moved during garbage collection cycles as they reside outside of heap. TerraCota's BigMemory caching technology seems to rely heavily on this advantage. If they were on heap, it would slow down gc pause times.
Performance boost: In stream IO, read calls would entail system calls, which require a context-switch between user to kernel mode and vice versa, which would be costly especially if file is being accessed constantly. However, with memory-mapping this context-switching is reduced as data is more likely to be found in memory (MappedByteBuffer). If data is available in memory, it is accessed directly without invoking OS, i.e., no context-switching.
Note that MappedByteBuffers are very useful especially if the files are big and few groups of blocks are accessed more frequently.
Your code works for me. Here is my test case:
mysql> CREATE TABLE carmake (country ENUM('Canada', 'United States'));
Query OK, 0 rows affected (0.00 sec)
mysql> SHOW CREATE TABLE carmake;
+---------+-------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+---------+-------------------------------------------------------------------------------------------------------------------------+
| carmake | CREATE TABLE `carmake` (
`country` enum('Canada','United States') default NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 |
+---------+-------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
mysql> ALTER TABLE carmake CHANGE country country ENUM('Sweden','Malaysia');
Query OK, 0 rows affected (0.53 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> SHOW CREATE TABLE carmake;
+---------+--------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+---------+--------------------------------------------------------------------------------------------------------------------+
| carmake | CREATE TABLE `carmake` (
`country` enum('Sweden','Malaysia') default NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 |
+---------+--------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
What error are you seeing?
FWIW this would also work:
ALTER TABLE carmake MODIFY COLUMN country ENUM('Sweden','Malaysia');
I would actually recommend a country table rather than enum column. You may have hundreds of countries which would make for a rather large and awkward enum.
EDIT: Now that I can see your error message:
ERROR 1265 (01000): Data truncated for column 'country' at row 1.
I suspect you have some values in your country column that do not appear in your ENUM
. What is the output of the following command?
SELECT DISTINCT country FROM carmake;
ANOTHER EDIT: What is the output of the following command?
SHOW VARIABLES LIKE 'sql_mode';
Is it STRICT_TRANS_TABLES
or STRICT_ALL_TABLES
? That could lead to an error, rather than the usual warning MySQL would give you in this situation.
YET ANOTHER EDIT: Ok, I now see that you definitely have values in the table that are not in the new ENUM
. The new ENUM
definition only allows 'Sweden'
and 'Malaysia'
. The table has 'USA'
, 'India'
and several others.
LAST EDIT (MAYBE): I think you're trying to do this:
ALTER TABLE carmake CHANGE country country ENUM('Italy', 'Germany', 'England', 'USA', 'France', 'South Korea', 'Australia', 'Spain', 'Czech Republic', 'Sweden', 'Malaysia') DEFAULT NULL;
Mongodb v3.4
You need to do the following to create a secure database:
Make sure the user starting the process has permissions and that the directories exist (/data/db
in this case).
1) Start MongoDB without access control.
mongod --port 27017 --dbpath /data/db
2) Connect to the instance.
mongo --port 27017
3) Create the user administrator (in the admin authentication database).
use admin
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
4) Re-start the MongoDB instance with access control.
mongod --auth --port 27017 --dbpath /data/db
5) Connect and authenticate as the user administrator.
mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"
6) Create additional users as needed for your deployment (e.g. in the test authentication database).
use test
db.createUser(
{
user: "myTester",
pwd: "xyz123",
roles: [ { role: "readWrite", db: "test" },
{ role: "read", db: "reporting" } ]
}
)
7) Connect and authenticate as myTester.
mongo --port 27017 -u "myTester" -p "xyz123" --authenticationDatabase "test"
I basically just explained the short version of the official docs here: https://docs.mongodb.com/master/tutorial/enable-authentication/
For a strict Visual Basic approach, you can convert the floating-point value to an integer to round to said integer. VB is one of the rare languages that rounds on type conversion (most others simply truncate.)
Multiples of 5 or x can be done simply by dividing before and multiplying after the round.
If you want to round and keep decimal places, Math.round(n, d) would work.
It depends on the database to which you're trying to connect, the method by which you created the connection, and the version of Excel that you're using. (Also, most probably, the version of the relevant ODBC driver on your computer.)
The following examples are using SQL Server 2008 and Excel 2007, both on my local machine.
When I used the Data Connection Wizard (on the Data tab of the ribbon, in the Get External Data section, under From Other Sources), I saw the same thing that you did: the Parameters button was disabled, and adding a parameter to the query, something like select field from table where field2 = ?
, caused Excel to complain that the value for the parameter had not been specified, and the changes were not saved.
When I used Microsoft Query (same place as the Data Connection Wizard), I was able to create parameters, specify a display name for them, and enter values each time the query was run. Bringing up the Connection Properties for that connection, the Parameters... button is enabled, and the parameters can be modified and used as I think you want.
I was also able to do this with an Access database. It seems reasonable that Microsoft Query could be used to create parameterized queries hitting other types of databases, but I can't easily test that right now.
This snippet works in IE7 at least
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Test</title>
<style>
#foo {
position: fixed;
bottom: 0;
right: 0;
}
</style>
</head>
<body>
<div id="foo">Hello World</div>
</body>
</html>
If the project is maven placed it in src/main/resources
, in the package phase it will copy it in ../WEB-INF/classes/hibernate.cfg.xml
Another solution is:
>>> "".join(list(hex(255))[2:])
'ff'
Probably an archaic answer, but functional.
You can use pickle
import pickle
dict = {'one': 1, 'two': 2}
file = open('dump.txt', 'wb')
pickle.dump(dict, file)
file.close()
and to read it again
file = open('dump.txt', 'rb')
dict = pickle.load(file)
EDIT: Guess I misread your question, sorry ... but pickle might help all the same. :)
assume that you're trying to run your project inside eclipse, or netbean or stand alone from command line. I have write a method to fix it
public static final String getBasePathForClass(Class<?> clazz) {
File file;
try {
String basePath = null;
file = new File(clazz.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
if (file.isFile() || file.getPath().endsWith(".jar") || file.getPath().endsWith(".zip")) {
basePath = file.getParent();
} else {
basePath = file.getPath();
}
// fix to run inside eclipse
if (basePath.endsWith(File.separator + "lib") || basePath.endsWith(File.separator + "bin")
|| basePath.endsWith("bin" + File.separator) || basePath.endsWith("lib" + File.separator)) {
basePath = basePath.substring(0, basePath.length() - 4);
}
// fix to run inside netbean
if (basePath.endsWith(File.separator + "build" + File.separator + "classes")) {
basePath = basePath.substring(0, basePath.length() - 14);
}
// end fix
if (!basePath.endsWith(File.separator)) {
basePath = basePath + File.separator;
}
return basePath;
} catch (URISyntaxException e) {
throw new RuntimeException("Cannot firgue out base path for class: " + clazz.getName());
}
}
To use, everywhere you want to get base path to read file, you can pass your anchor class to above method, result may be the thing you need :D
Best,
Singleton pattern
public class MyClass() {
private static MyClass instance = null;
/**
* Get instance of my class, Singleton
**/
public static MyClass getInstance() {
if(instance == null) {
instance = new MyClass();
}
return instance;
}
/**
* Private constructor
*/
private MyClass() {
//This will only be called once, by calling getInstanse() method.
}
}
You can use upstream headers (named starting with $http_) and additional custom headers. For example:
add_header X-Upstream-01 $http_x_upstream_01;
add_header X-Hdr-01 txt01;
next, go to console and make request with user's header:
curl -H "X-Upstream-01: HEADER1" -I http://localhost:11443/
the response contains X-Hdr-01, seted by server and X-Upstream-01, seted by client:
HTTP/1.1 200 OK
Server: nginx/1.8.0
Date: Mon, 30 Nov 2015 23:54:30 GMT
Content-Type: text/html;charset=UTF-8
Connection: keep-alive
X-Hdr-01: txt01
X-Upstream-01: HEADER1
I am running Anaconda version 4.3.22 and a python3.6.1 environment, and had this problem. Here's the history and the fix:
pip uninstall opencv-python # -- the original step. failed.
ImportError: DLL load failed: The specified module could not be found.
I did this into my python3.6 environment and got this error.
python -m pip install opencv-python # same package as above.
conda install -c conda-forge opencv # separate install parallel to opencv
pip-install opencv-contrib-python # suggested by another user here. doesn't resolve it.
Next, I tried downloading python3.6 and putting the python3.dll in the folder and in various folders. nothing changed.
finally, this fixed it:
pip uninstall opencv-python
(the other conda-forge version is still installed) This left only the conda version, and that works in 3.6.
>>>import cv2
>>>
working!
Using lxml:
from lxml import etree
# create XML
root = etree.Element('root')
root.append(etree.Element('child'))
# another child with text
child = etree.Element('child')
child.text = 'some text'
root.append(child)
# pretty string
s = etree.tostring(root, pretty_print=True)
print s
Output:
<root>
<child/>
<child>some text</child>
</root>
See the tutorial for more information.
The syntax for creating a new table is
CREATE TABLE new_table
AS
SELECT *
FROM old_table
This will create a new table named new_table
with whatever columns are in old_table
and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.
SELECT INTO
is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.
I know I'm posting late but thought it would help at least a few folks!
Both the examples mentioned by tim and defuz(which are top voted) works perfectly fine. However, there is a minute difference which could be significant at times.
Pymongo provides json_util - you can use that one instead to handle BSON types
Output: { "_id": { "$oid": "abc123" } }
Output: { "_id": "abc123" }
Even though, the first method looks simple, both the method need very minimal effort.
The servlet class should be in the WEB-INF/classes not WEB-INF/src.
Here's a handy short-hand way to install a specific tag or commit from GitHub via bower.json
.
{
"dependencies": {
"your-library-name": "<GITHUB-USERNAME>/<REPOSITORY-NAME>#<TAG-OR-COMMIT>"
}
}
For example:
{
"dependencies": {
"custom-jquery": "jquery/jquery#2.0.3"
}
}
Our approach is simple, but it works! :)
When a user clicks our LogOut button, we simply open the login page (or any page) and close the page we are on...simulating opening in new browser window without any history to go back to.
<input id="btnLogout" onclick="logOut()" class="btn btn-sm btn-warning" value="Logout" type="button"/>
<script>
function logOut() {
window.close = function () {
window.open('Default.aspx', '_blank');
};
}
</script>
Solution : you have to add you ssh key in your git-hub profile. Follow steps to solve this problem
Now you are ready to push your folder
Hope this will be Helpful for you
see this example :
PersonneTest pt=new PersonneTest();
System.out.println(pt.getClass().getDeclaredFields().length);
Field[]x=pt.getClass().getDeclaredFields();
System.out.println(x[1].getName());
For apache Ubuntu 2.4.7 , I finally found you need to white list your virtual host in apache2.conf
# access here, or in any related virtual host.
<Directory /home/gav/public_html/>
Options FollowSymLinks
AllowOverride None
Require all granted
</Directory>
Please have a look at this matplotlib example page. There it is shown how to get the following plot with four individual colorbars for each subplot:
I hope this helps.
You can further have a look here, where you can find a lot of what you can do with matplotlib
.
You can use:
data = pd.read_csv('output_list.txt', sep=" ", header=None)
data.columns = ["a", "b", "c", "etc."]
Add sep=" "
in your code, leaving a blank space between the quotes. So pandas can detect spaces between values and sort in columns. Data columns is for naming your columns.
You should call the bash script using source.
Here is an example:
#!/bin/bash
# Let's call this script venv.sh
source "<absolute_path_recommended_here>/.env/bin/activate"
On your shell just call it like that:
> source venv.sh
Or as @outmind suggested: (Note that this does not work with zsh)
> . venv.sh
There you go, the shell indication will be placed on your prompt.
Maybe this?
throw std::runtime_error(
(std::ostringstream()
<< "Could not load config file '"
<< configfile
<< "'"
).str()
);
It creates a temporary ostringstream, calls the << operators as necessary and then you wrap that in round brackets and call the .str() function on the evaluated result (which is an ostringstream) to pass a temporary std::string to the constructor of runtime_error.
Note: the ostringstream and the string are r-value temporaries and so go out of scope after this line ends. Your exception object's constructor MUST take the input string using either copy or (better) move semantics.
Additional: I don't necessarily consider this approach "best practice", but it does work and can be used at a pinch. One of the biggest issues is that this method requires heap allocations and so the operator << can throw. You probably don't want that happening; however, if your get into that state your probably have way more issues to worry about!
You're currently writing the binary data in the string
-object to your file. This binary data will probably only consist of a pointer to the actual data, and an integer representing the length of the string.
If you want to write to a text file, the best way to do this would probably be with an ofstream
, an "out-file-stream". It behaves exactly like std::cout
, but the output is written to a file.
The following example reads one string from stdin, and then writes this string to the file output.txt
.
#include <fstream>
#include <string>
#include <iostream>
int main()
{
std::string input;
std::cin >> input;
std::ofstream out("output.txt");
out << input;
out.close();
return 0;
}
Note that out.close()
isn't strictly neccessary here: the deconstructor of ofstream
can handle this for us as soon as out
goes out of scope.
For more information, see the C++-reference: http://cplusplus.com/reference/fstream/ofstream/ofstream/
Now if you need to write to a file in binary form, you should do this using the actual data in the string. The easiest way to acquire this data would be using string::c_str()
. So you could use:
write.write( studentPassword.c_str(), sizeof(char)*studentPassword.size() );
I'd just use an if statement. In this case:
Type nodeType = node.GetType();
if (nodeType == typeof(CasusNodeDTO))
{
}
else ...
The other way to do this is:
if (node is CasusNodeDTO)
{
}
else ...
The first example is true for exact types only, where the latter checks for inheritance too.
In my case, package python-pygments
was missed. You can fix it by command:
sudo apt-get install python-pygments
If there is problem with pandoc
. You should install pandoc
and pandoc-citeproc
.
sudo apt-get install pandoc pandoc-citeproc
SELECT
pid,
cid,
pname,
name1,
null
FROM
product p
INNER JOIN
customer1 c ON p.cid = c.cid
UNION
SELECT
pid,
cid,
pname,
null,
name2
FROM
product p
INNER JOIN
customer2 c ON p.cid = c.cid
I needed either: both -alpha background
and -flatten
, or -fill
.
I made a new PNG with a transparent background and a red dot in the middle.
convert image.png -background green -alpha off green.png
failed: it produced an image with black background
convert image.png -background green -alpha background -flatten green.png
produced an image with the correct green background.
Of course, with another file that I renamed image.png
, it failed to do anything. For that file, I found that the color of the transparent pixels was "#d5d5d5" so I filled that color with green:
convert image.png -fill green -opaque "#d5d5d5" green.png
replaced the transparent pixels with the correct green.
It's not a complicated issue to make something similar to boost. Here's a class with just three functions, including the constructor, to replicate what boost did (almost).
template <typename T, typename U>
class create_map
{
private:
std::map<T, U> m_map;
public:
create_map(const T& key, const U& val)
{
m_map[key] = val;
}
create_map<T, U>& operator()(const T& key, const U& val)
{
m_map[key] = val;
return *this;
}
operator std::map<T, U>()
{
return m_map;
}
};
Usage:
std::map mymap = create_map<int, int >(1,2)(3,4)(5,6);
The above code works best for initialization of global variables or static members of a class which needs to be initialized and you have no idea when it gets used first but you want to assure that the values are available in it.
If say, you've got to insert elements into an existing std::map... here's another class for you.
template <typename MapType>
class map_add_values {
private:
MapType mMap;
public:
typedef typename MapType::key_type KeyType;
typedef typename MapType::mapped_type MappedType;
map_add_values(const KeyType& key, const MappedType& val)
{
mMap[key] = val;
}
map_add_values& operator()(const KeyType& key, const MappedType& val) {
mMap[key] = val;
return *this;
}
void to (MapType& map) {
map.insert(mMap.begin(), mMap.end());
}
};
Usage:
typedef std::map<int, int> Int2IntMap;
Int2IntMap testMap;
map_add_values<Int2IntMap>(1,2)(3,4)(5,6).to(testMap);
See it in action with GCC 4.7.2 here: http://ideone.com/3uYJiH
############### EVERYTHING BELOW THIS IS OBSOLETE #################
EDIT: The map_add_values
class below, which was the original solution I had suggested, would fail when it comes to GCC 4.5+. Please look at the code above for how to add values to existing map.
template<typename T, typename U>
class map_add_values
{
private:
std::map<T,U>& m_map;
public:
map_add_values(std::map<T, U>& _map):m_map(_map){}
map_add_values& operator()(const T& _key, const U& _val)
{
m_map[key] = val;
return *this;
}
};
Usage:
std::map<int, int> my_map; // Later somewhere along the code map_add_values<int,int>(my_map)(1,2)(3,4)(5,6);
NOTE: Previously I used a operator []
for adding the actual values. This is not possible as commented by dalle.
##################### END OF OBSOLETE SECTION #####################
You can use a regular expression that matches zeroes at the beginning of the string:
s = s.replace(/^0+/, '');
string dateInString = "01.10.2009";
DateTime startDate = DateTime.Parse(dateInString);
DateTime expiryDate = startDate.AddDays(30);
if (DateTime.Now > expiryDate) {
//... trial expired
}
You can use date function to format it by using the code below:
echo date("g:i a", strtotime("13:30:30 UTC"));
output: 1:30 pm
For me the simple solution works to set cookies in HttpRequestMessage object.
protected async Task<HttpResponseMessage> SendRequest(HttpRequestMessage requestMessage, CancellationToken cancellationToken = default(CancellationToken))
{
requestMessage.Headers.Add("Cookie", $"<Cookie Name 1>=<Cookie Value 1>;<Cookie Name 2>=<Cookie Value 2>");
return await _httpClient.SendAsync(requestMessage, cancellationToken).ConfigureAwait(false);
}
You can see some reports in SSMS:
Right-click the instance name / reports / standard / top sessions
You can see top CPU consuming sessions. This may shed some light on what SQL processes are using resources. There are a few other CPU related reports if you look around. I was going to point to some more DMVs but if you've looked into that already I'll skip it.
You can use sp_BlitzCache to find the top CPU consuming queries. You can also sort by IO and other things as well. This is using DMV info which accumulates between restarts.
This article looks promising.
Some stackoverflow goodness from Mr. Ozar.
edit: A little more advice... A query running for 'only' 5 seconds can be a problem. It could be using all your cores and really running 8 cores times 5 seconds - 40 seconds of 'virtual' time. I like to use some DMVs to see how many executions have happened for that code to see what that 5 seconds adds up to.
The proper way to remove a cookie is to set the max age to 0 and add the cookie back to the HttpServletResponse object.
Most people don't realize or forget to add the cookie back onto the response object. By doing that it will expire and remove the cookie immediately.
...retrieve cookie from HttpServletRequest
cookie.setMaxAge(0);
response.addCookie(cookie);
You should grab a copy of Erica Sadun's mdhelper command line utility (OS X binary & source). It supports listing and extracting the contents of iPhone/iPod Touch backups, including address book & SMS databases, and other application metadata and settings.
Check the API Docs
Methods addOption(data)
and setValue(value)
might be what you are looking for.
Update: Seeing the popularity of this answer, here is some additional info based on comments/requests...
setValue(value, silent)
Resets the selected items to the given value.
If "silent" is truthy (ie:true
,1
), no change event will be fired on the original input.
addOption(data)
Adds an available option, or array of options. If it already exists, nothing will happen.
Note: this does not refresh the options list dropdown (userefreshOptions()
for that).
In response to options being overwritten:
This can happen by re-initializing the select without using the options you initially provided. If you are not intending to recreate the element, simply store the selectize object to a variable:
// 1. Only set the below variables once (ideally)
var $select = $('select').selectize(options); // This initializes the selectize control
var selectize = $select[0].selectize; // This stores the selectize object to a variable (with name 'selectize')
// 2. Access the selectize object with methods later, for ex:
selectize.addOption(data);
selectize.setValue('something', false);
// Side note:
// You can set a variable to the previous options with
var old_options = selectize.settings;
// If you intend on calling $('select').selectize(old_options) or something
Hoodaticus's solution was perfect, thank you, but I also needed it to be re-runnable and found this way to check if it had been done...
IF EXISTS(SELECT * FROM information_schema.columns
WHERE table_name='myTable' AND column_name='myColumn'
AND Table_schema='myDBO' AND column_default IS NULL)
BEGIN
ALTER TABLE [myDBO].[myTable] ADD DEFAULT 0 FOR [myColumn] --Hoodaticus
END
To add one more important information to above provided answers -
For a process
def proc = command.execute();
always try to use
def outputStream = new StringBuffer();
proc.waitForProcessOutput(outputStream, System.err)
//proc.waitForProcessOutput(System.out, System.err)
rather than
def output = proc.in.text;
to capture the outputs after executing commands in groovy as the latter is a blocking call (SO question for reason).
Maybe help, if you want to add some filter:
context.Persons
.Where(c => c.state == myState)
.Select(c => c.age)
.DefaultIfEmpty(0)
.Max();
@Autowired
annotation is defined in the Spring framework.
@Inject
annotation is a standard annotation, which is defined in the standard "Dependency Injection for Java" (JSR-330). Spring (since the version 3.0) supports the generalized model of dependency injection which is defined in the standard JSR-330. (Google Guice frameworks and Picocontainer framework also support this model).
With @Inject
can be injected the reference to the implementation of the Provider
interface, which allows injecting the deferred references.
Annotations @Inject
and @Autowired
- is almost complete analogies. As well as @Autowired
annotation, @Inject
annotation can be used for automatic binding properties, methods, and constructors.
In contrast to @Autowired
annotation, @Inject
annotation has no required
attribute. Therefore, if the dependencies will not be found - will be thrown an exception.
There are also differences in the clarifications of the binding properties. If there is ambiguity in the choice of components for the injection the @Named
qualifier should be added. In a similar situation for @Autowired
annotation will be added @Qualifier
qualifier (JSR-330 defines it's own @Qualifier
annotation and via this qualifier annotation @Named
is defined).
I'm using this on my site (for example here), but I'm using some extra stuff to do lazy loading, meaning extracting the code isn't as straightforward as I would like it to be for putting it in a fiddle.
Also, my templating engine is smarty, but I'm sure you get the idea.
The meat...
Updating the indicators:
<ol class="carousel-indicators">
{assign var='walker' value=0}
{foreach from=$item["imagearray"] key="key" item="value"}
<li data-target="#myCarousel" data-slide-to="{$walker}"{if $walker == 0} class="active"{/if}>
<img src='http://farm{$value["farm"]}.static.flickr.com/{$value["server"]}/{$value["id"]}_{$value["secret"]}_s.jpg'>
</li>
{assign var='walker' value=1 + $walker}
{/foreach}
</ol>
Changing the CSS related to the indicators:
.carousel-indicators {
bottom:-50px;
height: 36px;
overflow-x: hidden;
white-space: nowrap;
}
.carousel-indicators li {
text-indent: 0;
width: 34px !important;
height: 34px !important;
border-radius: 0;
}
.carousel-indicators li img {
width: 32px;
height: 32px;
opacity: 0.5;
}
.carousel-indicators li:hover img, .carousel-indicators li.active img {
opacity: 1;
}
.carousel-indicators .active {
border-color: #337ab7;
}
When the carousel has slid, update the list of thumbnails:
$('#myCarousel').on('slid.bs.carousel', function() {
var widthEstimate = -1 * $(".carousel-indicators li:first").position().left + $(".carousel-indicators li:last").position().left + $(".carousel-indicators li:last").width();
var newIndicatorPosition = $(".carousel-indicators li.active").position().left + $(".carousel-indicators li.active").width() / 2;
var toScroll = newIndicatorPosition + indicatorPosition;
var adjustedScroll = toScroll - ($(".carousel-indicators").width() / 2);
if (adjustedScroll < 0)
adjustedScroll = 0;
if (adjustedScroll > widthEstimate - $(".carousel-indicators").width())
adjustedScroll = widthEstimate - $(".carousel-indicators").width();
$('.carousel-indicators').animate({ scrollLeft: adjustedScroll }, 800);
indicatorPosition = adjustedScroll;
});
And, when your page loads, set the initial scroll position of the thumbnails:
var indicatorPosition = 0;
you should be searching about how to add favicon.ico
. You can try adding favicon.ico
directly in your html pages like this
<link rel="shortcut icon" href="/favicon.png" type="image/png">
<link rel="shortcut icon" type="image/png" href="http://www.example.com/favicon.png" />
Or you can update that in your webserver
. It is advised to add in your webserver
as you don't need to add this in each of your html
pages (assuming no includes
).
To add in your apache
place the favicon.ico
in your root website director and add this in httpd.conf
AddType image/x-icon .ico
Assuming your byteData
array is biger than 32 + byteSalt.length()
...you're going to it's length, not byteSalt.length
. You're trying to copy from beyond the array end.
For completeness, in python 3.6 f-string are introduced in PEP-498. These strings make it possible to
embed expressions inside string literals, using a minimal syntax.
That would mean that for your example you could also use:
f'{self.author} in {self.publication}'
Here's my version:
Utils.eventBoundToFunction = function (element, eventType, fCallback) {
if (!element || !element.data('events') || !element.data('events')[eventType] || !fCallback) {
return false;
}
for (runner in element.data('events')[eventType]) {
if (element.data('events')[eventType][runner].handler == fCallback) {
return true;
}
}
return false;
};
Usage:
Utils.eventBoundToFunction(okButton, 'click', handleOkButtonFunction)
private void datagrid_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
string test = this.datagrid.Columns[e.ColumnIndex].HeaderText;
}
This code will get the HeaderText
value.
You're mixing the parts together instead of separating them cleanly.
printf '\e[1;34m%-6s\e[m' "This is text"
Basically, put the fixed stuff in the format and the variable stuff in the parameters.
Instead of using the conditions
syntax from Rails 2, use Rails 4's where
method instead:
def self.search(search, page = 1 )
wildcard_search = "%#{search}%"
where("name ILIKE :search OR postal_code LIKE :search", search: wildcard_search)
.page(page)
.per_page(5)
end
NOTE: the above uses parameter syntax instead of ? placeholder: these both should generate the same sql.
def self.search(search, page = 1 )
wildcard_search = "%#{search}%"
where("name ILIKE ? OR postal_code LIKE ?", wildcard_search, wildcard_search)
.page(page)
.per_page(5)
end
NOTE: using ILIKE
for the name - postgres case insensitive version of LIKE
public static String cap1stChar(String userIdea)
{
char[] stringArray = userIdea.toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
return userIdea = new String(stringArray);
}
Well, you're missing the letter 'd' in url("~/fonts/Lato-Bol.ttf"); - but assuming that's not it, I would open up your page with developer tools in Chrome and make sure there's no errors loading any of the files (you would probably see an issue in the JavaScript console, or you can check the Network tab and see if anything is red).
(I don't see anything obviously wrong with the code you have posted above)
Other things to check: 1) Are you including your CSS file in your html above the lines where you are trying to use the font-family style? 2) What do you see in the CSS panel in the developer tools for that div? Is font-family: lato crossed out?
All of these answers kinda suck... do not use range() it wont work beyond column Z.
Simply use:
$sheet = $spreadsheet->getActiveSheet();
foreach ($sheet->getColumnIterator() as $column) {
$sheet->getColumnDimension($column->getColumnIndex())->setAutoSize(true);
}
Do this after you have written your data so that the column iterator knows how many columns to iterate over.
ObjectOutputStream.writeObject(clubs)
ObjectInputStream.readObject();
Also, you 'add' logic is logically equivalent to using a Set instead of a List. Lists can have duplicates and Sets cannot. You should consider using a set. After all, can you really have 2 chess clubs in the same school?
I would recommend reading a book on C++ before you go any further, as it would be helpful to get a firmer footing. Accelerated C++ by Koenig and Moo is excellent.
To get the executable path use GetModuleFileName:
TCHAR buffer[MAX_PATH] = { 0 };
GetModuleFileName( NULL, buffer, MAX_PATH );
Here's a C++ function that gets the directory without the file name:
#include <windows.h>
#include <string>
#include <iostream>
wstring ExePath() {
TCHAR buffer[MAX_PATH] = { 0 };
GetModuleFileName( NULL, buffer, MAX_PATH );
std::wstring::size_type pos = std::wstring(buffer).find_last_of(L"\\/");
return std::wstring(buffer).substr(0, pos);
}
int main() {
std::cout << "my directory is " << ExePath() << "\n";
}
Did you try using the Select(filterExpression, sortOrder)
method on DataTable? See here for an example. Note this method will not sort the data table in place, if that is what you are looking for, but it will return a sorted array of rows without using a data view.
To get a position of an element in a vector knowing an iterator pointing to the element, simply subtract v.begin()
from the iterator:
ptrdiff_t pos = find(Names.begin(), Names.end(), old_name_) - Names.begin();
Now you need to check pos
against Names.size()
to see if it is out of bounds or not:
if(pos >= Names.size()) {
//old_name_ not found
}
vector iterators behave in ways similar to array pointers; most of what you know about pointer arithmetic can be applied to vector iterators as well.
Starting with C++11 you can use std::distance
in place of subtraction for both iterators and pointers:
ptrdiff_t pos = distance(Names.begin(), find(Names.begin(), Names.end(), old_name_));
Here is another simple solution using sed.
$ sed -i 's/all.*/& anotherthing/g' filename.txt
Explanation:
all.* means all lines started with 'all'.
& represent the match (ie the complete line that starts with 'all')
then sed replace the former with the later and appends the ' anotherthing' word
When it says that, just open the shell and do git status
. That will give you a decent idea of what could be wrong and the state of your repo.
I can't give you a specific error for this as it happens for many reasons in Github for Windows, like say some problem in updating submodules etc.
msg = request.GET.get('q','default')
if (msg == default):
message = "YOU SUBMITTED NOTHING"
else:
message = "you submitted = %s" %msg"
return HttpResponse(message);
Here is another alternative answer to this issue. This extension method works quite well. This solves the issues of the string being shorter than the maximum length and also the maximum length being negative.
public static string Left( this string str, int length ) {
if (str == null)
return str;
return str.Substring(0, Math.Min(Math.Abs(length), str.Length));
}
Another solution would be to limit the length to be non-negative values, and just zero-out negative values.
public static string Left( this string str, int length ) {
if (str == null)
return str;
return str.Substring(0, Math.Min(Math.Max(0,length), str.Length));
}
You can use this (Swift 3):
UIDevice.current.identifierForVendor!.uuidString
For older versions:
UIDevice.currentDevice().identifierForVendor
or if you want a string:
UIDevice.currentDevice().identifierForVendor!.UUIDString
There is no longer a way to uniquely identify a device after the user uninstalled the app(s). The documentation says:
The value in this property remains the same while the app (or another app from the same vendor) is installed on the iOS device. The value changes when the user deletes all of that vendor’s apps from the device and subsequently reinstalls one or more of them.
You may also want to read this article by Mattt Thompson for more details:
http://nshipster.com/uuid-udid-unique-identifier/
Update for Swift 4.1, you will need to use:
UIDevice.current.identifierForVendor?.uuidString
str(strval).isdigit()
seems to be simple.
Handles values stored in as a string or int or float
You often want to use wildcards with Class
. For instance, Class<? extends JComponent>
, would allow you to specify that the class is some subclass of JComponent
. If you've retrieved the Class
instance from Class.forName
, then you can use Class.asSubclass
to do the cast before attempting to, say, construct an instance.
What not to do
WARNING:
This answer uses ECB. ECB is not an encryption mode, it's only a building block. Using ECB as demonstrated in this answer does not actually encrypt the string securely. Do not use ECB in your code. See Scott's answer for a good solution.
I got it on myself. Actually i found some answer on google and just modified something. The result is completely insecure however.
<?php
define("ENCRYPTION_KEY", "!@#$%^&*");
$string = "This is the original data string!";
echo $encrypted = encrypt($string, ENCRYPTION_KEY);
echo "<br />";
echo $decrypted = decrypt($encrypted, ENCRYPTION_KEY);
/**
* Returns an encrypted & utf8-encoded
*/
function encrypt($pure_string, $encryption_key) {
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$encrypted_string = mcrypt_encrypt(MCRYPT_BLOWFISH, $encryption_key, utf8_encode($pure_string), MCRYPT_MODE_ECB, $iv);
return $encrypted_string;
}
/**
* Returns decrypted original string
*/
function decrypt($encrypted_string, $encryption_key) {
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$decrypted_string = mcrypt_decrypt(MCRYPT_BLOWFISH, $encryption_key, $encrypted_string, MCRYPT_MODE_ECB, $iv);
return $decrypted_string;
}
?>
Simple, In first Activity-
EditText name= (EditText) findViewById(R.id.editTextName);
Button button= (Button) findViewById(R.id.buttonGo);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,Main2Activity.class);
i.putExtra("name",name.getText().toString());
startActivity(i);
}
});
In second Activity-
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
TextView t = (TextView) findViewById(R.id.textView);
Bundle bundle=getIntent().getExtras();
String s=bundle.getString("name");
t.setText(s);
}
You can add if/else conditions if you want.
It looks like request_uri
is deprecated in Ruby on Rails 3.
Using #request_uri is deprecated. Use fullpath instead.
Suppose you have two forms, and you want to hide the property of one form via another:
form1 ob = new form1();
ob.Show(this);
this.Enabled= false;
and when you want to get focus back of form1 via form2 button then:
Form1 ob = new Form1();
ob.Visible = true;
this.Close();
You can read all of the telephone numbers associated with a contact in the following manner:
Uri personUri = ContentUris.withAppendedId(People.CONTENT_URI, personId);
Uri phonesUri = Uri.withAppendedPath(personUri, People.Phones.CONTENT_DIRECTORY);
String[] proj = new String[] {Phones._ID, Phones.TYPE, Phones.NUMBER, Phones.LABEL}
Cursor cursor = contentResolver.query(phonesUri, proj, null, null, null);
Please note that this example (like yours) uses the deprecated contacts API. From eclair onwards this has been replaced with the ContactsContract API.
There's a good topic about this in Stack Overflow question Is 'yield return' slower than "old school" return?.
It says:
ReadAllLines loads all of the lines into memory and returns a string[]. All well and good if the file is small. If the file is larger than will fit in memory, you'll run out of memory.
ReadLines, on the other hand, uses yield return to return one line at a time. With it, you can read any size file. It doesn't load the whole file into memory.
Say you wanted to find the first line that contains the word "foo", and then exit. Using ReadAllLines, you'd have to read the entire file into memory, even if "foo" occurs on the first line. With ReadLines, you only read one line. Which one would be faster?
First download the JavaMail API and make sure the relevant jar files are in your classpath.
Here's a full working example using GMail.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Main {
private static String USER_NAME = "*****"; // GMail user name (just the part before "@gmail.com")
private static String PASSWORD = "********"; // GMail password
private static String RECIPIENT = "[email protected]";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "Welcome to JavaMail!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}
Naturally, you'll want to do more in the catch
blocks than print the stack trace as I did in the example code above. (Remove the catch
blocks to see which method calls from the JavaMail API throw exceptions so you can better see how to properly handle them.)
Thanks to @jodonnel and everyone else who answered. I'm giving him a bounty because his answer led me about 95% of the way to a complete answer.
<html>
<head>
<style type="text/css">
.title {
color: blue;
text-decoration: bold;
text-size: 1em;
}
.author {
color: gray;
}
</style>
</head>
<body>
<p>
<span class="title">La super bonne</span>
<span class="author">proposée par Jérém</span>
</p>
</body>
</html>
On a side note, it would have been much easier to just do this.
You may be able to adapt a version of the C++ virtual constructor idiom. As far as I know, C# doesn't support covariant return types. I believe that's on many peoples' wish lists.
With data.table, the solutions is:
DT[, idnat2 := ifelse(idbp %in% "foreign", "foreign",
ifelse(idbp %in% c("colony", "overseas"), "overseas", "mainland" ))]
The ifelse
is vectorized. The if-else
is not. Here, DT is:
idnat idbp
1 french mainland
2 french colony
3 french overseas
4 foreign foreign
This gives:
idnat idbp idnat2
1: french mainland mainland
2: french colony overseas
3: french overseas overseas
4: foreign foreign foreign
The sample config you provided is actually valid YAML. In fact, YAML meets all of your demands, is implemented in a large number of languages, and is extremely human friendly. I would highly recommend you use it. The PyYAML project provides a nice python module, that implements YAML.
To use the yaml module is extremely simple:
import yaml
config = yaml.safe_load(open("path/to/config.yml"))
^\d{5}(?:[-\s]\d{4})?$
^
= Start of the string.\d{5}
= Match 5 digits (for condition 1, 2, 3)(?:…)
= Grouping[-\s]
= Match a space (for condition 3) or a hyphen (for condition 2)\d{4}
= Match 4 digits (for condition 2, 3)…?
= The pattern before it is optional (for condition 1)$
= End of the string.All the answers provide sufficient details to the question. However, let me add something more.
Why are we using these Interfaces:
Which interface does what:
When to use which interface:
According to http://jtuts.com/2014/08/26/difference-between-crudrepository-and-jparepository-in-spring-data-jpa/
Generally the best idea is to use CrudRepository or PagingAndSortingRepository depending on whether you need sorting and paging or not.
The JpaRepository should be avoided if possible, because it ties you repositories to the JPA persistence technology, and in most cases you probably wouldn’t even use the extra methods provided by it.
You can use
Trace.WriteLine("text");
This will output to the "Output" window in Visual Studio (when debugging).
make sure to have the Diagnostics assembly included:
using System.Diagnostics;
I think an ad-hoc way would be to use the environment variable PYTHONPATH
as described in the documentation: Python2, Python3
# Linux & OSX
export PYTHONPATH=$HOME/dirWithScripts/:$PYTHONPATH
# Windows
set PYTHONPATH=C:\path\to\dirWithScripts\;%PYTHONPATH%
You haven't posted the findvertex
method, but Access Reading Violation with an offset like 0x00000048
means that the Vertex* f;
in your getCost function is receiving null, and when trying to access the member adj
in the null
Vertex pointer (that is, in f
), it is offsetting to adj
(in this case, 72 bytes ( 0x48 bytes in decimal )), it's reading near the 0
or null
memory address.
Doing a read like this violates Operating-System protected memory, and more importantly means whatever you're pointing at isn't a valid pointer. Make sure findvertex
isn't returning null, or do a comparisong for null on f
before using it to keep yourself sane (or use an assert):
assert( f != null ); // A good sanity check
EDIT:
If you have a map
for doing something like a find, you can just use the map's find
method to make sure the vertex exists:
Vertex* Graph::findvertex(string s)
{
vmap::iterator itr = map1.find( s );
if ( itr == map1.end() )
{
return NULL;
}
return itr->second;
}
Just make sure you're still careful to handle the error case where it does return NULL
. Otherwise, you'll keep getting this access violation.
Are there more details? (Is this in a JSP as in the linked webpage?)
If so, you can always just use the fully qualified class name.
rather than:
import foo.bar.*;
Baz myBaz;
you can use
foo.bar.Baz myBaz;
For RHEL-mysql 5.5:
/etc/init.d/mysql stop
/etc/init.d/mysql start --skip-grant-tables
mysql> UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';
mysql> FLUSH PRIVILEGES;
mysql> exit;
mysql -uroot -pnewpwd
mysql>
Try:
public class Main {
public static void main(String[] args) {
String line = "foo,bar,c;qual=\"baz,blurb\",d;junk=\"quux,syzygy\"";
String[] tokens = line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);
for(String t : tokens) {
System.out.println("> "+t);
}
}
}
Output:
> foo
> bar
> c;qual="baz,blurb"
> d;junk="quux,syzygy"
In other words: split on the comma only if that comma has zero, or an even number of quotes ahead of it.
Or, a bit friendlier for the eyes:
public class Main {
public static void main(String[] args) {
String line = "foo,bar,c;qual=\"baz,blurb\",d;junk=\"quux,syzygy\"";
String otherThanQuote = " [^\"] ";
String quotedString = String.format(" \" %s* \" ", otherThanQuote);
String regex = String.format("(?x) "+ // enable comments, ignore white spaces
", "+ // match a comma
"(?= "+ // start positive look ahead
" (?: "+ // start non-capturing group 1
" %s* "+ // match 'otherThanQuote' zero or more times
" %s "+ // match 'quotedString'
" )* "+ // end group 1 and repeat it zero or more times
" %s* "+ // match 'otherThanQuote'
" $ "+ // match the end of the string
") ", // stop positive look ahead
otherThanQuote, quotedString, otherThanQuote);
String[] tokens = line.split(regex, -1);
for(String t : tokens) {
System.out.println("> "+t);
}
}
}
which produces the same as the first example.
As mentioned by @MikeFHay in the comments:
I prefer using Guava's Splitter, as it has saner defaults (see discussion above about empty matches being trimmed by
String#split()
, so I did:Splitter.on(Pattern.compile(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"))
Actually, you should avoid using this
when using react hooks. It causes side effects. That's why react team create react hooks
.
If you remove codes that tries to bind this
, you can just simply pass setName
of Parent
to Child
and call it in handleChange
. Cleaner code!
function Parent() {
const [Name, setName] = useState("");
return <div> {Name} :
<Child setName={setName} ></Child>
</div>
}
function Child(props) {
const [Name, setName] = useState("");
function handleChange(ele) {
setName(ele.target.value);
props.setName(ele.target.value);
}
return (<div>
<input onChange={handleChange} value={Name}></input>
</div>);
}
Moreover, you don't have to create two copies of Name
(one in Parent
and the other one in Child
). Stick to "Single Source of Truth" principle, Child
doesn't have to own the state Name
but receive it from Parent
. Cleanerer node!
function Parent() {
const [Name, setName] = useState("");
return <div> {Name} :
<Child setName={setName} Name={Name}></Child>
</div>
}
function Child(props) {
function handleChange(ele) {
props.setName(ele.target.value);
}
return (<div>
<input onChange={handleChange} value={props.Name}></input>
</div>);
}
Apart from calling java -jar myjar.jar com.mycompany.Myclass
, you can also make the main class in your Manifest a Dispatcher class.
Example:
public class Dispatcher{
private static final Map<String, Class<?>> ENTRY_POINTS =
new HashMap<String, Class<?>>();
static{
ENTRY_POINTS.put("foo", Foo.class);
ENTRY_POINTS.put("bar", Bar.class);
ENTRY_POINTS.put("baz", Baz.class);
}
public static void main(final String[] args) throws Exception{
if(args.length < 1){
// throw exception, not enough args
}
final Class<?> entryPoint = ENTRY_POINTS.get(args[0]);
if(entryPoint==null){
// throw exception, entry point doesn't exist
}
final String[] argsCopy =
args.length > 1
? Arrays.copyOfRange(args, 1, args.length)
: new String[0];
entryPoint.getMethod("main", String[].class).invoke(null,
(Object) argsCopy);
}
}
// Register user's name and ID
if ((!isset($_SESSION['name'])) && (!isset($_SESSION['user_id']))) {
$row = mysql_fetch_assoc($login_result);
$_SESSION['name'] = $row['name'];
$_SESSION['user_id'] = $row['user_id'];
}
header("Location: http://localhost:8080/meet2eat/index.php");
change to
// Register user's name and ID
if ((!isset($_SESSION['name'])) && (!isset($_SESSION['user_id']))) {
$row = mysql_fetch_assoc($login_result);
$_SESSION['name'] = $row['name'];
$_SESSION['user_id'] = $row['user_id'];
header("Location: http://localhost:8080/meet2eat/index.php");
}
You better setup a single test and create a performance test from this test. This way you can monitor the progress using the default tool set.
Note that this solution works if the commit to be removed is the last committed one.
1 - Copy the commit reference you like to go back to from the log:
git log
2 - Reset git to the commit reference:
git reset <commit_ref>
3 - Stash/store the local changes from the wrong commit to use later after pushing to remote:
git stash
4 - Push the changes to remote repository, (-f or --force):
git push -f
5 - Get back the stored changes to local repository:
git stash apply
7 - In case you have untracked/new files in the changes, you need to add them to git before committing:
git add .
6 - Add whatever extra changes you need, then commit the needed files, (or use a dot '.' instead of stating each file name, to commit all files in the local repository:
git commit -m "<new_commit_message>" <file1> <file2> ...
or
git commit -m "<new_commit_message>" .
Expanding on betabandido's answer, you could write a function to inject the attributes as constants into the module:
def module_register_class_constants(klass, attr_prefix):
globals().update(
(name, getattr(klass, name)) for name in dir(klass) if name.startswith(attr_prefix)
)
class Animal(object):
SIZE_HUGE = "Huge"
SIZE_BIG = "Big"
module_register_class_constants(Animal, "SIZE_")
class Horse(Animal):
def printSize(self):
print SIZE_BIG
Use the DecimalFormat class to format the double
//checking even and odd
$num =14;
$even = ($num % 2 == 0);
$odd = ($num % 2 != 0);
if($even){
echo "Number is even.";
} else {
echo "Number is odd.";
}
If you are using Bootstrap 3.3.x then use this code (you need to add class name carousel-fade to your carousel).
.carousel-fade .carousel-inner .item {
-webkit-transition-property: opacity;
transition-property: opacity;
}
.carousel-fade .carousel-inner .item,
.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
opacity: 0;
}
.carousel-fade .carousel-inner .active,
.carousel-fade .carousel-inner .next.left,
.carousel-fade .carousel-inner .prev.right {
opacity: 1;
}
.carousel-fade .carousel-inner .next,
.carousel-fade .carousel-inner .prev,
.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
left: 0;
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
.carousel-fade .carousel-control {
z-index: 2;
}
Try
select * from dataset
where id = 2
order by date limit 1
Been a while since I did sql, so this might need some tweaking.
Shorter and dealing with a column (entire, not just a section of a column):
=COUNTA(A:A)
Beware, a cell containing just a space would be included in the count.
First things first ,
they are not always equal
select 'Hello' from dual where 'Hello ' like 'Hello';
select 'Hello' from dual where 'Hello ' = 'Hello';
when things are not always equal , talking about their performance isn't that relevant.
If you are working on strings and only char variables , then you can talk about performance . But don't use like and "=" as being generally interchangeable .
As you would have seen in many posts ( above and other questions) , in cases when they are equal the performance of like is slower owing to pattern matching (collation)
My code is as follows:
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
// your code here, and if you have to refresh UI put this code:
runOnUiThread(new Runnable() {
public void run() {
//your code
}
});
}
},
5000
);
I needed to remove special characters from an XML file. Here's how I did it. char.ToString() is the hero in this code.
string item = "<item type="line" />"
char DC4 = (char)0x14;
string fixed = item.Replace(DC4.ToString(), string.Empty);
It is faster to slice the string twice, like this:
function spliceSlice(str, index, count, add) {
// We cannot pass negative indexes directly to the 2nd slicing operation.
if (index < 0) {
index = str.length + index;
if (index < 0) {
index = 0;
}
}
return str.slice(0, index) + (add || "") + str.slice(index + count);
}
than using a split followed by a join (Kumar Harsh's method), like this:
function spliceSplit(str, index, count, add) {
var ar = str.split('');
ar.splice(index, count, add);
return ar.join('');
}
Here's a jsperf that compares the two and a couple other methods. (jsperf has been down for a few months now. Please suggest alternatives in comments.)
Although the code above implements functions that reproduce the general functionality of splice
, optimizing the code for the case presented by the asker (that is, adding nothing to the modified string) does not change the relative performance of the various methods.
Use this:
Format(Now, "MMMM dd, yyyy")
More: Format Function
Try this:
Response.Redirect(Request.Url.AbsoluteUri);
Boost.Regex is very good and is slated to become part of the C++0x standard (it's already in TR1).
Personally, I find Boost.Xpressive much nicer to work with. It is a header-only library and it has some nice features such as static regexes (regexes compiled at compile time).
Update: If you're using a C++11 compliant compiler (gcc 4.8 is NOT!), use std::regex unless you have good reason to use something else.
It points to your top level output directory (which by default is target
):
EDIT: As has been pointed out, Codehaus is now sadly defunct. You can find details about these properties from Sonatype here:
If you are ever trying to reference output directories in Maven, you should never use a literal value like target/classes. Instead you should use property references to refer to these directories.
project.build.sourceDirectory project.build.scriptSourceDirectory project.build.testSourceDirectory project.build.outputDirectory project.build.testOutputDirectory project.build.directory
sourceDirectory
,scriptSourceDirectory
, andtestSourceDirectory
provide access to the source directories for the project.outputDirectory
andtestOutputDirectory
provide access to the directories where Maven is going to put bytecode or other build output.directory
refers to the directory which contains all of these output directories.
First off, you need to implement INotifyPropertyChanged
interface in your view model and raise the PropertyChanged
event in the setter of the Rule
property. Otherwise no control that binds to the SelectedRule
property will "know" when it has been changed.
Then, your XAML
<TextBlock Text="{Binding Path=SelectedRule.Name}" />
is perfectly valid if this TextBlock
is outside the ListBox
's ItemTemplate
and has the same DataContext
as the ListBox
.
What language? In Perl style: ^\d+(\.\d*)?$
Here are some high level thoughts and info that might help, aside from the other answers.
Pollyfills are like a compatability patch for specific browsers. Shims are changes to specific arguments. Fallbacks can be used if say a @mediaquery is not compatible with a browser.
It kind of depends on the requirements of what your app/website needs to be compatible with.
You cna check this site out for compatability of specific libraries with specific browsers. https://caniuse.com/
For those facing problem after upgrading their android device to android 10, same PTP Mode option will work as prescribed by user3135185
I was using IntelliJ IDEA 13.1.5 and faced with the same problem after I changed versions of Picasso and Retrofit in dependencies
in build.gradle
file. I tried use many solutions, but without result.
Then I cloned my project from remote git (where I pushed it before changing versions of dependencies) and it worked! After that I just closed current project and imported old project from Gradle file to IntelliJ IDEA again and it worked too! So, I think it was strange bug in intersection of IDEA, Gradle and Android plugin. I hope this information can be useful for IDEA-users or anyone else.
You just put them in __init__.py.
So with test/classes.py being:
class A(object): pass
class B(object): pass
... and test/__init__.py being:
from classes import *
class Helper(object): pass
You can import test and have access to A, B and Helper
>>> import test
>>> test.A
<class 'test.classes.A'>
>>> test.B
<class 'test.classes.B'>
>>> test.Helper
<class 'test.Helper'>
With your code, the vue.js
is trying to access the moment()
method from its scope.
Hence you should use a method like this:
methods: {
moment: function () {
return moment();
}
},
If you want to pass a date to the moment.js
, I suggest to use filters:
filters: {
moment: function (date) {
return moment(date).format('MMMM Do YYYY, h:mm:ss a');
}
}
<span>{{ date | moment }}</span>
After converting your varchar2
date to a true date
datatype, then convert back to varchar2
with the desired mask:
to_char(to_date('01/02/2012','MM/DD/YYYY'),'WW')
If you want the week number in a number
datatype, you can wrap the statement in to_number()
:
to_number(to_char(to_date('01/02/2012','MM/DD/YYYY'),'WW'))
However, you have several week number options to consider:
WW Week of year (1-53) where week 1 starts on the first day of the year and continues to the seventh day of the year.
W Week of month (1-5) where week 1 starts on the first day of the month and ends on the seventh.
IW Week of year (1-52 or 1-53) based on the ISO standard.
If you are getting an error like the one below:
OperationalError: FATAL: no pg_hba.conf entry for host "your ipv6",
user "username", database "postgres", SSL off
then add an entry like the following, with your mac address.
host all all [your ipv6]/128 md5
Every time I go from heavy C++ coding to Java, it takes me a little while to adapt to the lack of const-correctness in Java. This usage of const
in C++ is much different than just declaring constant variables, if you didn't know. Essentially, it ensures that an object is immutable when accessed through a special kind of pointer called a const-pointer When in Java, in places where I'd normally want to return a const-pointer, I instead return a reference with an interface type containing only methods that shouldn't have side effects. Unfortunately, this isn't enforced by the langauge.
Wikipedia offers the following information on the subject:
Interestingly, the Java language specification regards const as a reserved keyword — i.e., one that cannot be used as variable identifier — but assigns no semantics to it. It is thought that the reservation of the keyword occurred to allow for an extension of the Java language to include C++-style const methods and pointer to const type. The enhancement request ticket in the Java Community Process for implementing const correctness in Java was closed in 2005, implying that const correctness will probably never find its way into the official Java specification.
Two things: Change the variables x
, y
, z
as int
and call the method as Math.max(Math.max(x,y),z)
as it accepts two parameters only.
In Summary, change below:
String x = keyboard.nextLine();
String y = keyboard.nextLine();
String z = keyboard.nextLine();
int max = Math.max(x,y,z);
to
int x = keyboard.nextInt();
int y = keyboard.nextInt();
int z = keyboard.nextInt();
int max = Math.max(Math.max(x,y),z);
SELECT number, COUNT(*)
FROM YourTable
GROUP BY number
ORDER BY number
Usefull script which you can delete all data in all tables of a database , replace tt with you databse name :
declare @tablename nvarchar(100)
declare c1 cursor for
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_CATALOG='tt' AND TABLE_TYPE='BASE TABLE'
open c1
fetch next from c1 into @tablename
while @@FETCH_STATUS = 0
begin
print @t1
exec('alter table ' + @tablename + ' nocheck constraint all')
exec('delete from ' + @tablename)
exec ('alter table ' + @tablename + ' check constraint all')
fetch next from c1 into @tablename
end
close c1
DEALLOCATE c1
find $directory -type f -name "*.in"|grep $substring
If you have a standard code signing certificate, some time will be needed for your application to build trust. Microsoft affirms that an Extended Validation (EV) Code Signing Certificate allows us to skip this period of trust-building. According to Microsoft, extended validation certificates allow the developer to immediately establish a reputation with SmartScreen. Otherwise, the users will see a warning like "Windows Defender SmartScreen prevented an unrecognized app from starting. Running this app might put your PC at risk.", with the two buttons: "Run anyway" and "Don't run".
Another Microsoft resource states the following (quote): "Although not required, programs signed by an EV code signing certificate can immediately establish a reputation with SmartScreen reputation services even if no prior reputation exists for that file or publisher. EV code signing certificates also have a unique identifier which makes it easier to maintain reputation across certificate renewals."
My experience is as follows. Since 2005, we have been using regular (non-EV) code signing certificates to sign .MSI, .EXE and .DLL files with time stamps, and there has never been a problem with SmartScreen until 2018, when there was just one case when it took 3 days for a beta version of our application to build trust since we have released it to beta testers, and it was in the middle of certificate validity period. I don't know what SmartScreen might not like in that specific version of our application, but there have been no SmartScreen complaints since then. Therefore, if your certificate is a non-EV, it is a signed application (such as an .MSI file) that will build trust over time, not a certificate. For example, a certificate can be issued a few months ago and used to sign many files, but for each signed file you publish, it may take a few days for SmartScreen to stop complaining about the file after publishing, as was in our case in 2018.
As a conclusion, to avoid the warning completely, i.e. prevent it from happening even suddenly, you need an Extended Validation (EV) code signing certificate.
You can use this snippet
for root, dirs, files in os.walk(directory):
if level > 0:
# do some stuff
else:
break
level-=1
Works for me:
List<Item> list = Task.Run(() => manager.GetList()).Result;
in this way it is not necessary to mark the method with async in the call.
Alter TABLE 'TARGET' add 'ShouldAddColumn' Integer Not Null default "0"
I just checked it in MySQL 5.7 and am really surprised how no one offered a simple answer: NATURAL JOIN
When the tables or (select outcome) have IDENTICAL columns, you can use NATURAL JOIN as a way to find intersection:
For example:
table1:
id, name, jobid
'1', 'John', '1'
'2', 'Jack', '3'
'3', 'Adam', '2'
'4', 'Bill', '6'
table2:
id, name, jobid
'1', 'John', '1'
'2', 'Jack', '3'
'3', 'Adam', '2'
'4', 'Bill', '5'
'5', 'Max', '6'
And here is the query:
SELECT * FROM table1 NATURAL JOIN table2;
Query Result: id, name, jobid
'1', 'John', '1'
'2', 'Jack', '3'
'3', 'Adam', '2'
CASE 1:
char *str = "Hello";
str[0] = 'M' //Warning may be issued by compiler, and will cause segmentation fault upon running the programme
The above sets str to point to the literal value "Hello" which is hard-coded in the program's binary image, which is flagged as read-only in memory, means any change in this String literal is illegal and that would throw segmentation faults.
CASE 2:
const char *str = "Hello";
str[0] = 'M' //Compile time error
CASE 3:
char str[] = "Hello";
str[0] = 'M'; // legal and change the str = "Mello".
My issue was a missing set of quotes;
Foo: bar 'baz'
should be
Foo: "bar 'baz'"
You'll see this in all the directives:
When you use brackets, it means you're passing a bindable property (a variable).
<a [routerLink]="routerLinkVariable"></a>
So this variable (routerLinkVariable) could be defined inside your class and it should have a value like below:
export class myComponent {
public routerLinkVariable = "/home"; // the value of the variable is string!
But with variables, you have the opportunity to make it dynamic right?
export class myComponent {
public routerLinkVariable = "/home"; // the value of the variable is string!
updateRouterLinkVariable(){
this.routerLinkVariable = '/about';
}
Where as without brackets you're passing string only and you can't change it, it's hard coded and it'll be like that throughout your app.
<a routerLink="/home"></a>
UPDATE :
The other speciality about using brackets specifically for routerLink is that you can pass dynamic parameters to the link you're navigating to:
So adding a new variable
export class myComponent {
private dynamicParameter = '129';
public routerLinkVariable = "/home";
Updating the [routerLink]
<a [routerLink]="[routerLinkVariable,dynamicParameter]"></a>
When you want to click on this link, it would become:
<a href="/home/129"></a>
extension Double {
func formatWithDecimalPlaces(decimalPlaces: Int) -> Double {
let formattedString = NSString(format: "%.\(decimalPlaces)f", self) as String
return Double(formattedString)!
}
}
1.3333.formatWithDecimalPlaces(2)
There's a nice one in the BlocksKit framework.
(and the class)
Much like leonardocsouza, I had the same problem. To clarify a bit, this is what my folder structure looked like when I ran node server.js
node_modules/
app/
index.html
server.js
After printing out the __dirname
path, I realized that the __dirname
path was where my server was running (app/
).
So, the answer to your question is this:
If your server.js
file is in the same folder as the files you are trying to render, then
app.use( express.static( path.join( application_root, 'site') ) );
should actually be
app.use(express.static(application_root));
The only time you would want to use the original syntax that you had would be if you had a folder tree like so:
app/
index.html
node_modules
server.js
where index.html
is in the app/
directory, whereas server.js
is in the root directory (i.e. the same level as the app/
directory).
Side note: Intead of calling the path
utility, you can use the syntax application_root + 'site'
to join a path.
Overall, your code could look like:
// Module dependencies.
var application_root = __dirname,
express = require( 'express' ), //Web framework
mongoose = require( 'mongoose' ); //MongoDB integration
//Create server
var app = express();
// Configure server
app.configure( function() {
//Don't change anything here...
//Where to serve static content
app.use( express.static( application_root ) );
//Nothing changes here either...
});
//Start server --- No changes made here
var port = 5000;
app.listen( port, function() {
console.log( 'Express server listening on port %d in %s mode', port, app.settings.env );
});
One of the uses which I found to be very useful is the print_function
from __future__
module.
In Python 2.7, I wanted chars from different print statements to be printed on same line without spaces.
It can be done using a comma(",") at the end, but it also appends an extra space. The above statement when used as :
from __future__ import print_function
...
print (v_num,end="")
...
This will print the value of v_num
from each iteration in a single line without spaces.
try giving AppPool ID or Network Services whichever applicable access HKLM\SYSTEM\CurrentControlSet\services\eventlog\security also. I was getting the same error .. this worked for me. See the error is also saying that the inaccessible logs are Security Logs.
I also gave permission in eventlog\application .
I gave full access everywhere.