The method System.Web.UI.Page.RegisterClientScriptBlock has been deprecated for some time (along with the other Page.Register* methods), ever since .NET 2.0 as shown by MSDN.
Instead use the .NET 2.0 Page.ClientScript.Register* methods. - (The ClientScript property expresses an instance of the ClientScriptManager class )
Guessing the problem
If you are saying your JavaScript alert box occurs before the page's content is visibly rendered, and therefore the page remains white (or still unrendered) when the alert box is dismissed by the user, then try using the Page.ClientScript.RegisterStartupScript(..) method instead because it runs the given client-side code when the page finishes loading - and its arguments are similar to what you're using already.
Also check for general JavaScript errors in the page - this is often seen by an error icon in the browser's status bar. Sometimes a JavaScript error will hold up or disturb unrelated elements on the page.
I will give here the kind of answer i usually don't like to read, but i think that as there are other answers telling you how to achive what you want, it could be nice to rethink if what you are trying to achive is really a good idea.
First, you should think if it is a good idea to show the items in a non-standard way, with a separator charater diferent than the provided.
I don't know the reasons for that, but let's suppose you have good reasons.
The ways propossed here to achive that consist in add content to your markup, mainly trough the CSS :before pseudoclass. This content is really modifing your DOM structure, adding those items to it.
When you use standard "ol" numeration, you will have a rendered content in which the "li" text is selectable, but the number preceding it is not selectable. That is, the standard numbering system seems to be more "decoration" than real content. If you add content for numbers using for example those ":before" methods, this content will be selectable, and dued to this, performing undesired vopy/paste issues, or accesibility issues with screen readers that will read this "new" content in addition to the standard numeration system.
Perhaps another approach could be to style the numbers using images, although this alternative will bring its own problems (numbers not shown when images are disabled, text size for number not changing, ...).
Anyway, the reason for this answer is not just to propose this "images" alternative, but to make people think in the consequences of trying to change the standard numeration system for ordered lists.
I use a package.json
for my packages and a config.js
for my configuration, which looks like:
var config = {};
config.twitter = {};
config.redis = {};
config.web = {};
config.default_stuff = ['red','green','blue','apple','yellow','orange','politics'];
config.twitter.user_name = process.env.TWITTER_USER || 'username';
config.twitter.password= process.env.TWITTER_PASSWORD || 'password';
config.redis.uri = process.env.DUOSTACK_DB_REDIS;
config.redis.host = 'hostname';
config.redis.port = 6379;
config.web.port = process.env.WEB_PORT || 9980;
module.exports = config;
I load the config from my project:
var config = require('./config');
and then I can access my things from config.db_host
, config.db_port
, etc... This lets me either use hardcoded parameters, or parameters stored in environmental variables if I don't want to store passwords in source control.
I also generate a package.json
and insert a dependencies section:
"dependencies": {
"cradle": "0.5.5",
"jade": "0.10.4",
"redis": "0.5.11",
"socket.io": "0.6.16",
"twitter-node": "0.0.2",
"express": "2.2.0"
}
When I clone the project to my local machine, I run npm install
to install the packages. More info on that here.
The project is stored in GitHub, with remotes added for my production server.
The find
method returns a Cursor
instance, which allows you to iterate over all matching documents.
To get the first document that matches the given criteria you need to use find_one
. The result of find_one
is a dictionary.
You can always use the list
constructor to return a list of all the documents in the collection but bear in mind that this will load all the data in memory and may not be what you want.
You should do that if you need to reuse the cursor and have a good reason not to use rewind()
Demo using find
:
>>> import pymongo
>>> conn = pymongo.MongoClient()
>>> db = conn.test #test is my database
>>> col = db.spam #Here spam is my collection
>>> cur = col.find()
>>> cur
<pymongo.cursor.Cursor object at 0xb6d447ec>
>>> for doc in cur:
... print(doc) # or do something with the document
...
{'a': 1, '_id': ObjectId('54ff30faadd8f30feb90268f'), 'b': 2}
{'a': 1, 'c': 3, '_id': ObjectId('54ff32a2add8f30feb902690'), 'b': 2}
Demo using find_one
:
>>> col.find_one()
{'a': 1, '_id': ObjectId('54ff30faadd8f30feb90268f'), 'b': 2}
For white Toolbar Title and White Up arrow, use following theme:
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
Open Source: CMU Sphinx
Shareware: http://www.e-speaking.com/ (Windows)
Commercial: Dragon NaturallySpeaking (Windows)
Although there are some good answers for this question. I would like to give another answer here with several examples of loop
.
O(n): Time Complexity of a loop is considered as O(n) if the loop variables is incremented / decremented by a constant amount. For example following functions have O(n) time complexity.
// Here c is a positive integer constant
for (int i = 1; i <= n; i += c) {
// some O(1) expressions
}
for (int i = n; i > 0; i -= c) {
// some O(1) expressions
}
O(n^c): Time complexity of nested loops is equal to the number of times the innermost statement is executed. For example the following sample loops have O(n^2) time complexity
for (int i = 1; i <=n; i += c) {
for (int j = 1; j <=n; j += c) {
// some O(1) expressions
}
}
for (int i = n; i > 0; i += c) {
for (int j = i+1; j <=n; j += c) {
// some O(1) expressions
}
For example Selection sort and Insertion Sort have O(n^2) time complexity.
O(Logn) Time Complexity of a loop is considered as O(Logn) if the loop variables is divided / multiplied by a constant amount.
for (int i = 1; i <=n; i *= c) {
// some O(1) expressions
}
for (int i = n; i > 0; i /= c) {
// some O(1) expressions
}
For example Binary Search has O(Logn) time complexity.
O(LogLogn) Time Complexity of a loop is considered as O(LogLogn) if the loop variables is reduced / increased exponentially by a constant amount.
// Here c is a constant greater than 1
for (int i = 2; i <=n; i = pow(i, c)) {
// some O(1) expressions
}
//Here fun is sqrt or cuberoot or any other constant root
for (int i = n; i > 0; i = fun(i)) {
// some O(1) expressions
}
One example of time complexity analysis
int fun(int n)
{
for (int i = 1; i <= n; i++)
{
for (int j = 1; j < n; j += i)
{
// Some O(1) task
}
}
}
Analysis:
For i = 1, the inner loop is executed n times.
For i = 2, the inner loop is executed approximately n/2 times.
For i = 3, the inner loop is executed approximately n/3 times.
For i = 4, the inner loop is executed approximately n/4 times.
…………………………………………………….
For i = n, the inner loop is executed approximately n/n times.
So the total time complexity of the above algorithm is (n + n/2 + n/3 + … + n/n)
, Which becomes n * (1/1 + 1/2 + 1/3 + … + 1/n)
The important thing about series (1/1 + 1/2 + 1/3 + … + 1/n)
is equal to O(Logn). So the time complexity of the above code is O(nLogn).
Here's two simple examples
> x <- letters[1:4]
> replace(x, 3, 'Z') #replacing 'c' by 'Z'
[1] "a" "b" "Z" "d"
>
> y <- 1:10
> replace(y, c(4,5), c(20,30)) # replacing 4th and 5th elements by 20 and 30
[1] 1 2 3 20 30 6 7 8 9 10
Your code is correct. Just test to ensure it is being called like:
<script>
function doIt(){
alert("here i am!");
__doPostBack('ctl00$ctl00$bLogout','')
}
</script>
<iframe onload="doIt()"></iframe>
A covering index is one which can satisfy all requested columns in a query without performing a further lookup into the clustered index.
There is no such thing as a covering query.
Have a look at this Simple-Talk article: Using Covering Indexes to Improve Query Performance.
For anyone who doesn't have the guarantee that the list will not be null, you can use the null-conditional operator to safely check for null and empty lists in a single conditional statement:
if (list?.Any() != true)
{
// Handle null or empty list
}
Just use event.getSource()
frim within actionPerformed
Cast it to the component
for Ex, if you need combobox
JComboBox comboBox = (JComboBox) event.getSource();
JTextField txtField = (JTextField) event.getSource();
use appropriate api to get the value,
for Ex.
Object selected = comboBox.getSelectedItem(); etc.
I have used a tool in my work its LDRA tool suite
It is used for testing the c/c++ code but it also can check against coding standards such as MISRA etc.
I had the same issue earlier, but my situation was a bit different in the front-end. I'll share my scenario anyway, maybe someone might find it useful.
I had an api call to /api/user/register
in the frontend with email, password and username as request body. On submitting the form(register form), a handler function is called which initiates the fetch call to /api/user/register
. I used the event.preventDefault()
in the beginning line of this handler function, all other lines,like forming the request body as well the fetch call was written after the event.preventDefault()
. This returned a pending promise
.
But when I put the request body formation code above the event.preventDefault()
, it returned the real promise. Like this:
event.preventDefault();
const data = {
'email': email,
'password': password
}
fetch(...)
...
instead of :
const data = {
'email': email,
'password': password
}
event.preventDefault();
fetch(...)
...
Short variant:
my_var = some_value if 'my_var' not in globals() else my_var:
Although it might be heresy in today's world - in the past you would do the following non-css code. This works in everything up to and including today's browsers but - as I have said - it is heresy in today's world:
<center>
<table>
...
</table>
</center>
What you need is some way to tell that you want to center a table and the person is using an older browser. Then insert the "<center>" commands around the table. Otherwise - use css.
Surprisingly - if you want to center everything in the BODY area - you just can use the standard
text-align: center;
css command and in IE8 (at least) it will center everything on the page including tables.
Also If you want you result set data in list .please use below LOC:
public List<String> dbselect(String query)
{
List<String> dbdata=new ArrayList<String>();
try {
dbResult=statement.executeQuery(query);
ResultSetMetaData metadata=dbResult.getMetaData();
for(int i=0;i>=metadata.getColumnCount();i++)
{
dbdata.add(dbResult.getString(i));
}
return dbdata;
} catch (SQLException e) {
return null;
}
}
The best solution i found out is to mute the video
HTML
<video loop muted autoplay id="videomain">
<source src="videoname.mp4" type="video/mp4">
</video>
If you know this when the page is rendered, which it sounds like you do because the database has a value, it's better to disable it when rendered instead of JavaScript. To do that, just add the readonly
attribute (or disabled
, if you want to remove it from the form submission as well) to the <input>
, like this:
<input type="text" disabled="disabled" />
//or...
<input type="text" readonly="readonly" />
Not really an answer to the specific question, but if there are others, like me, who are getting this error in fastAPI and end up here:
It is probably because your route response has a value that can't be JSON serialised by jsonable_encoder
. For me it was WKBElement: https://github.com/tiangolo/fastapi/issues/2366
Like in the issue, I ended up just removing the value from the output.
Chrome has a very nice feature called 'USB Web debugging' which allows to see the mobile device's debug console on your PC when connected via USB.
EDIT: Seems that the ADB is not supported on Windows 8, but this link seems to provide a solution:
http://mikemurko.com/general/chrome-remote-debugging-nexus-7-on-windows-8/
The problem I see here is that "sum" is an aggregate function.
first, you need to fix the query itself.
Select sum(c_counts + f_counts) total, [column to group sums by]
from table
group by [column to group sums by]
then, you can sort it:
Select *
from (query above) a
order by total
EDIT: But see post by Virat. Perhaps what you want is not the sum of your total fields over a group, but just the sum of those fields for each record. In that case, Virat has the right solution.
Or you can use RFlutter Alert library for that. It is easily customizable and easy-to-use. Its default style includes rounded corners and you can add buttons as much as you want.
Basic Alert:
Alert(context: context, title: "RFLUTTER", desc: "Flutter is awesome.").show();
Alert with Button:
Alert(
context: context,
type: AlertType.error,
title: "RFLUTTER ALERT",
desc: "Flutter is more awesome with RFlutter Alert.",
buttons: [
DialogButton(
child: Text(
"COOL",
style: TextStyle(color: Colors.white, fontSize: 20),
),
onPressed: () => Navigator.pop(context),
width: 120,
)
],
).show();
You can also define generic alert styles.
*I'm one of developer of RFlutter Alert.
This example is from http://bootsnipp.com/snippets/featured/multi-level-dropdown-menu-bs3
Works for me in Bootstrap v3.1.1.
<div class="container">
<div class="row">
<h2>Multi level dropdown menu in Bootstrap 3</h2>
<hr>
<div class="dropdown">
<a id="dLabel" role="button" data-toggle="dropdown" class="btn btn-primary" data-target="#" href="/page.html">
Dropdown <span class="caret"></span>
</a>
<ul class="dropdown-menu multi-level" role="menu" aria-labelledby="dropdownMenu">
<li><a href="#">Some action</a></li>
<li><a href="#">Some other action</a></li>
<li class="divider"></li>
<li class="dropdown-submenu">
<a tabindex="-1" href="#">Hover me for more options</a>
<ul class="dropdown-menu">
<li><a tabindex="-1" href="#">Second level</a></li>
<li class="dropdown-submenu">
<a href="#">Even More..</a>
<ul class="dropdown-menu">
<li><a href="#">3rd level</a></li>
<li><a href="#">3rd level</a></li>
</ul>
</li>
<li><a href="#">Second level</a></li>
<li><a href="#">Second level</a></li>
</ul>
</li>
</ul>
</div>
</div>
.dropdown-submenu {
position: relative;
}
.dropdown-submenu>.dropdown-menu {
top: 0;
left: 100%;
margin-top: -6px;
margin-left: -1px;
-webkit-border-radius: 0 6px 6px 6px;
-moz-border-radius: 0 6px 6px;
border-radius: 0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
display: block;
}
.dropdown-submenu>a:after {
display: block;
content: " ";
float: right;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 5px 0 5px 5px;
border-left-color: #ccc;
margin-top: 5px;
margin-right: -10px;
}
.dropdown-submenu:hover>a:after {
border-left-color: #fff;
}
.dropdown-submenu.pull-left {
float: none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
left: -100%;
margin-left: 10px;
-webkit-border-radius: 6px 0 6px 6px;
-moz-border-radius: 6px 0 6px 6px;
border-radius: 6px 0 6px 6px;
}
Again, after searching for the problem of converting nested lists with N levels into an N-dimensional array I found nothing, so here's my way around it:
import numpy as np
new_array=np.array([[[coord for coord in xk] for xk in xj] for xj in xi], ndmin=3) #this case for N=3
If you had the problem, opened SDK manager, installed the requested updates, returned to Android Studio and had the problem again, IT IS RECOMMENDED TO RESTART ANDROID STUDIO befor trying anything else.
Gradle will run automatically and chances are that your problem will be over. You will very possibly be told install the appropriate SDK TOOLS package, which is found in your SDK MANAGER under the second tab (sdk's are not the same as sdk tools, they are complementary packages).
You don't even need to hunt the tools package, if you click on the link under the error message, Android Studio should call SDK Manager to install the package automatically.
Restart Android Studio again and you should be up and running much faster than if you attempted workarounds.
RULE OF THUMB> restart your application before messing with options and configurations.
No, you would have to use a for-loop for that.
for (int i = 0; i < lst1.Count; i++)
{
//lst1[i]...
//lst2[i]...
}
You can't do something like
foreach (var objCurrent1 int lst1, var objCurrent2 in lst2)
{
//...
}
A "floating point number" is how computers usually represent numbers that are not integers -- basically, a number with a decimal point. In C++ you declare them with float
instead of int
. A floating point exception is an error that occurs when you try to do something impossible with a floating point number, such as divide by zero.
hope this will help you
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tbl_name'
AND table_schema = 'db_name'
AND column_name = 'column_name'
or
delimiter '//'
CREATE PROCEDURE addcol() BEGIN
IF NOT EXISTS(
SELECT * FROM information_schema.COLUMNS
WHERE COLUMN_NAME='new_column' AND TABLE_NAME='tablename' AND TABLE_SCHEMA='the_schema'
)
THEN
ALTER TABLE `the_schema`.`the_table`
ADD COLUMN `new_column` TINYINT(1) NOT NULL DEFAULT 1;;
END IF;
END;
//
delimiter ';'
CALL addcol();
DROP PROCEDURE addcol;
in c#.net
this.WindowState = FormWindowState.Minimized
Some of what is explained above is meant only for placing an SMS in a 'ready to launch' state.
as Senthil Mg said you can use sms manager to send the sms directly but SMSManager
has been moved to android.telephony.SmsManager
I know it's not a lot of more info, but it might help someone some day.
theBoolean ^= true;
Fewer keystrokes if your variable is longer than four letters
Edit: code tends to return useful results when used as Google search terms. The code above doesn't. For those who need it, it's bitwise XOR as described here.
If you're using ASP.NET MVC and Web API chances are you have the Newtonsoft.Json NuGet package installed.This library has a class called JObject which allows you to pass through multiple parameters:
Api Controller:
public class ProductController : ApiController
{
[HttpPost]
public void Post(Newtonsoft.Json.Linq.JObject data)
{
System.Diagnostics.Debugger.Break();
Product product = data["product"].ToObject<Product>();
Product product2 = data["product2"].ToObject<Product>();
int someRandomNumber = data["randomNumber"].ToObject<int>();
string productName = product.ProductName;
string product2Name = product2.ProductName;
}
}
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
}
View:
<script src="~/Scripts/angular.js"></script>
<script type="text/javascript">
var myApp = angular.module("app", []);
myApp.controller('controller', function ($scope, $http) {
$scope.AddProducts = function () {
var product = {
ProductID: 0,
ProductName: "Orange",
}
var product2 = {
ProductID: 1,
ProductName: "Mango",
}
var data = {
product: product,
product2: product2,
randomNumber:12345
};
$http.post("/api/Product", data).
success(function (data, status, headers, config) {
}).
error(function (data, status, headers, config) {
alert("An error occurred during the AJAX request");
});
}
});
</script>
<div ng-app="app" ng-controller="controller">
<input type="button" ng-click="AddProducts()" value="Get Full Name" />
</div>
In your link.php your echo
statement must be like this:
echo '<a href="pass.php?link=' . $a . '>Link 1</a>';
echo '<a href="pass.php?link=' . $b . '">Link 2</a>';
Then in your pass.php you cannot use $a
because it was not initialized with your intended string value.
You can directly compare it to a string like this:
if($_GET['link'] == 'Link1')
Another way is to initialize the variable first to the same thing you did with link.php. And, a much better way is to include the $a
and $b
variables in a single PHP file, then include that in all pages where you are going to use those variables as Tim Cooper mention on his post. You can also include this in a session.
Found simple solution - no need to remove "initial view controller check" from storyboard and editing project Info tab and use makeKeyAndVisible
, just place
self.window.rootViewController = rootVC;
in
- (BOOL) application:didFinishLaunchingWithOptions:
In .net 4.0 Microsoft removed the ability to add DLLs to the Assembly simply by dragging and dropping.
Instead you need to use gacutil.exe, or create an installer to do it. Microsoft actually doesn’t recommend using gacutil, but I went that route anyway.
To use gacutil on a development machine go to:
Start -> programs -> Microsoft Visual studio 2010 -> Visual Studio Tools -> Visual Studio Command Prompt (2010)
Then use these commands to uninstall and Reinstall respectively. Note I did NOT include .dll
in the uninstall command.
gacutil /u myDLL
gacutil /i "C:\Program Files\Custom\myDLL.dll"
To use Gacutil on a non-development machine you will have to copy the executable and config file from your dev machine to the production machine. It looks like there are a few different versions of Gacutil. The one that worked for me, I found here:
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\gacutil.exe
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\gacutil.exe.config
Copy the files here or to the appropriate .net folder;
C:\Windows\Microsoft.NET\Framework\v4.0.30319
Then use these commands to uninstall and reinstall respectively
"C:\Users\BHJeremy\Desktop\Installing to the Gac in .net 4.0\gacutil.exe" /u "myDLL"
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\gacutil.exe" /i "C:\Program Files\Custom\myDLL.dll"
To really fine-tune things, I recommend placing the appropriate selections in browser-targeting wrappers. This was the only thing that worked for me when I could not get IE7 and IE8 to "play nicely with others" (as I am currently working for a software company who continues to support them).
/* color or background image for all browsers, of course */
#myBackground {
background-color:#666;
}
/* target chrome & safari without disrupting IE7-8 */
@media screen and (-webkit-min-device-pixel-ratio:0) {
#myBackground {
-khtml-opacity:.50;
opacity:.50;
}
}
/* target firefox without disrupting IE */
@-moz-document url-prefix() {
#myBackground {
-moz-opacity:.50;
opacity:0.5;
}
}
/* and IE last so it doesn't blow up */
#myBackground {
opacity:.50;
filter:alpha(opacity=50);
filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0.5);
}
I may have redundancies in the above code -- if anyone wishes to clean it up further, feel free!
HTML:
<div id="left"></div>
<div id="content">
<textarea cols="2" rows="10" id="rules"></textarea>
</div>
CSS:
body{
width:100%;
border:1px solid black;
border-radius:5px;
}
#left{
width:20%;
height:400px;
float:left;
border: 1px solid black;
display:block;
}
#content{
width:78%;
height:400px;
float:left;
border:1px solid black;
text-align:center;
}
textarea
{
margin-top:100px;
width:98%;
}
DEMO: HERE
del /s /q c:\where ever the file is\*
rmdir /s /q c:\where ever the file is\
mkdir c:\where ever the file is\
You can see the default value in Chrome in this link
int64_t g_used_idle_socket_timeout_s = 300 // 5 minutes
In Chrome, as far as I know, there isn't an easy way (as Firefox do) to change the timeout value.
For example string s="(U+007c)"
To remove only the parentheses from s, try the below one:
import re
a=re.sub("\\(","",s)
b=re.sub("\\)","",a)
print(b)
A couple years late, but here is a solution that retrieves both inline styling and external styling:
function css(a) {
var sheets = document.styleSheets, o = {};
for (var i in sheets) {
var rules = sheets[i].rules || sheets[i].cssRules;
for (var r in rules) {
if (a.is(rules[r].selectorText)) {
o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style')));
}
}
}
return o;
}
function css2json(css) {
var s = {};
if (!css) return s;
if (css instanceof CSSStyleDeclaration) {
for (var i in css) {
if ((css[i]).toLowerCase) {
s[(css[i]).toLowerCase()] = (css[css[i]]);
}
}
} else if (typeof css == "string") {
css = css.split("; ");
for (var i in css) {
var l = css[i].split(": ");
s[l[0].toLowerCase()] = (l[1]);
}
}
return s;
}
Pass a jQuery object into css()
and it will return an object, which you can then plug back into jQuery's $().css()
, ex:
var style = css($("#elementToGetAllCSS"));
$("#elementToPutStyleInto").css(style);
:)
Likewise,
$myNewObj->setNewVar = 'newVal';
yields a stdClass object - auto casted
I found this out today by misspelling:
$GLOBASLS['myObj']->myPropertyObj->myProperty = 'myVal';
Cool!
You can use If function Write in the cell where you want to input the date the following formula: =IF(MODIFIED-CELLNUMBER<>"",IF(CELLNUMBER-WHERE-TO-INPUT-DATE="",NOW(),CELLNUMBER-WHERE-TO-INPUT-DATE),"")
Sometime you API backend could not respect the contract, and send plain text (ie. Proxy error: Could not proxy request ...
, or <html><body>NOT FOUND</body></html>
).
In this case, you will need to handle both cases: 1) a valid json response error, or 2) text payload as fallback (when response payload is not a valid json).
I would suggest this to handle both cases:
// parse response as json, or else as txt
static consumeResponseBodyAs(response, jsonConsumer, txtConsumer) {
(async () => {
var responseString = await response.text();
try{
if (responseString && typeof responseString === "string"){
var responseParsed = JSON.parse(responseString);
if (Api.debug) {
console.log("RESPONSE(Json)", responseParsed);
}
return jsonConsumer(responseParsed);
}
} catch(error) {
// text is not a valid json so we will consume as text
}
if (Api.debug) {
console.log("RESPONSE(Txt)", responseString);
}
return txtConsumer(responseString);
})();
}
then it become more easy to tune the rest handler:
class Api {
static debug = true;
static contribute(entryToAdd) {
return new Promise((resolve, reject) => {
fetch('/api/contributions',
{ method: 'POST',
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify(entryToAdd) })
.catch(reject);
.then(response => Api.consumeResponseBodyAs(response,
(json) => {
if (!response.ok) {
// valid json: reject will use error.details or error.message or http status
reject((json && json.details) || (json && json.message) || response.status);
} else {
resolve(json);
}
},
(txt) => reject(txt)// not json: reject with text payload
)
);
});
}
With pure Javascript, you'd have to cycle through each option, and check the value of it individually.
// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
// lowercase comparison for case-insensitivity
(op[i].value.toLowerCase() == "stackoverflow")
? op[i].disabled = true
: op[i].disabled = false ;
}
Without enabling non-targeted elements:
// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
// lowercase comparison for case-insensitivity
if (op[i].value.toLowerCase() == "stackoverflow") {
op[i].disabled = true;
}
}
With jQuery you can do this with a single line:
$("option[value='stackoverflow']")
.attr("disabled", "disabled")
.siblings().removeAttr("disabled");
Without enabling non-targeted elements:
$("option[value='stackoverflow']").attr("disabled", "disabled");
? Note that this is not case insensitive. "StackOverflow" will not equal "stackoverflow". To get a case-insensitive match, you'd have to cycle through each, converting the value to a lower case, and then check against that:
$("option").each(function(){
if ($(this).val().toLowerCase() == "stackoverflow") {
$(this).attr("disabled", "disabled").siblings().removeAttr("disabled");
}
});
Without enabling non-targeted elements:
$("option").each(function(){
if ($(this).val().toLowerCase() == "stackoverflow") {
$(this).attr("disabled", "disabled");
}
});
Here is a similar question to yours. (Practically the same.)
What ways are there to validate PHP code?
Edit
The top answer there suggest this resource:
http://www.meandeviation.com/tutorials/learnphp/php-syntax-check/v4/syntax-check.php
Finally found a quick and easy solution by adding two lines in the android/build.gradle
file.
googlePlayServicesVersion = "16.+"
firebaseVersion = "17.6.0"
Please follow this 100% correct.
It is simple actually, like C programming you just need to pass the array indices on the right hand side while declaration. But yeah the syntax will be like [0:3] for 4 elements.
reg a[0:3];
This will create a 1D of array of single bit. Similarly 2D array can be created like this:
reg [0:3][0:2];
Now in C suppose you create a 2D array of int, then it will internally create a 2D array of 32 bits. But unfortunately Verilog is an HDL, so it thinks in bits rather then bunch of bits (though int datatype is there in Verilog), it can allow you to create any number of bits to be stored inside an element of array (which is not the case with C, you can't store 5-bits in every element of 2D array in C). So to create a 2D array, in which every individual element can hold 5 bit value, you should write this:
reg [0:4] a [0:3][0:2];
It is not the most efficient in the world, but this should work:
get-content $file |
select -Skip 1 |
set-content "$file-temp"
move "$file-temp" $file -Force
This error can happen because some MFC library (eg. mfc120.dll) from which the DLL is dependent is missing in windows/system32 folder.
You technically have two options when speaking of ISO dates.
In general, if you're filtering specifically on Date values alone OR looking to persist date in a neutral fashion. Microsoft recommends using the language neutral format of ymd
or y-m-d
. Which are both valid ISO formats.
Note that the form '2007-02-12' is considered language-neutral only for the data types DATE, DATETIME2, and DATETIMEOFFSET.
Because of this, your safest bet is to persist/filter based on the always netural ymd
format.
The code:
select convert(char(10), getdate(), 126) -- ISO YYYY-MM-DD
select convert(char(8), getdate(), 112) -- ISO YYYYMMDD (safest)
It is session-based, when set the way you did in your question.
https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html
According to this, FOREIGN_KEY_CHECKS
is "Both" for scope. This means it can be set for session:
SET FOREIGN_KEY_CHECKS=0;
or globally:
SET GLOBAL FOREIGN_KEY_CHECKS=0;
Try this:
for (var i in tracks[racer_id].data.points) {
values = tracks[racer_id].data.points[i];
point = new google.maps.LatLng(values.lat, values.lng);
if (values.qst) {
var marker = new google.maps.Marker({map: map, position: point, clickable: true});
tracks[racer_id].markers[i] = marker;
var info = new google.maps.InfoWindow({
content: '<b>Speed:</b> ' + values.inst + ' knots'
});
tracks[racer_id].info[i] = info;
google.maps.event.addListener(tracks[racer_id].markers[i], 'click', function() {
tracks[racer_id].info[i].open(map, tracks[racer_id].markers[i]);
});
}
track_coordinates.push(point);
bd.extend(point);
}
Promises are not callbacks, both are programming idioms that facilitate async programming. Using an async/await-style of programming using coroutines or generators that return promises could be considered a 3rd such idiom. A comparison of these idioms across different programming languages (including Javascript) is here: https://github.com/KjellSchubert/promise-future-task
Here's my standard implementation. I like the labels to be self-descriptive.
Public Sub DoSomething()
On Error GoTo Catch ' Try
' normal code here
Exit Sub
Catch:
'error code: you can get the specific error by checking Err.Number
End Sub
Or, with a Finally
block:
Public Sub DoSomething()
On Error GoTo Catch ' Try
' normal code here
GoTo Finally
Catch:
'error code
Finally:
'cleanup code
End Sub
Yes, Javascript always passes by value, but in an array or object, the value is a reference to it, so you can 'change' the contents.
But, I think you already read it on SO; here you have the documentation you want:
Datetime is a datatype.
Timestamp is a method for row versioning. In fact, in sql server 2008 this column type was renamed (i.e. timestamp is deprecated) to rowversion. It basically means that every time a row is changed, this value is increased. This is done with a database counter which automatically increase for every inserted or updated row.
For more information:
http://www.sqlteam.com/article/timestamps-vs-datetime-data-types
In the meantime urllib2 seems to verify server certificates by default. The warning, that was shown in the past disappeared for 2.7.9 and I currently ran into this problem in a test environment with a self signed certificate (and Python 2.7.9).
My evil workaround (don't do this in production!):
import urllib2
import ssl
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
urllib2.urlopen("https://your-test-server.local", context=ctx)
According to docs calling SSLContext constructor directly should work, too. I haven't tried that.
When learning a new concept I don't like using libraries or code dumps. I found a good description here and in the documentation of how to resize an image by pinching. This answer is a slightly modified summary. You will probably want to add more functionality later, but it will help you get started.
The ImageView
just uses the app logo since it is already available. You can replace it with any image you like, though.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@mipmap/ic_launcher"
android:layout_centerInParent="true"/>
</RelativeLayout>
We use a ScaleGestureDetector
on the activity to listen to touch events. When a scale (ie, pinch) gesture is detected, then the scale factor is used to resize the ImageView
.
public class MainActivity extends AppCompatActivity {
private ScaleGestureDetector mScaleGestureDetector;
private float mScaleFactor = 1.0f;
private ImageView mImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize the view and the gesture detector
mImageView = findViewById(R.id.imageView);
mScaleGestureDetector = new ScaleGestureDetector(this, new ScaleListener());
}
// this redirects all touch events in the activity to the gesture detector
@Override
public boolean onTouchEvent(MotionEvent event) {
return mScaleGestureDetector.onTouchEvent(event);
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
// when a scale gesture is detected, use it to resize the image
@Override
public boolean onScale(ScaleGestureDetector scaleGestureDetector){
mScaleFactor *= scaleGestureDetector.getScaleFactor();
mImageView.setScaleX(mScaleFactor);
mImageView.setScaleY(mScaleFactor);
return true;
}
}
}
You can limit the size of the scaling with something like
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f));
Thanks again to Pinch-to-zoom with multi-touch gestures In Android
You will probably want to do other things like panning and scaling to some focus point. You can develop these things yourself, but if you would like to use a pre-made custom view, copy TouchImageView.java
into your project and use it like a normal ImageView
. It worked well for me and I only ran into one bug. I plan to further edit the code to remove the warning and the parts that I don't need. You can do the same.
Also, notice that by default Jersey will override the response body in case of an http code 400 or more.
In order to get your specified entity as the response body, try to add the following init-param to your Jersey in your web.xml configuration file :
<init-param>
<!-- used to overwrite default 4xx state pages -->
<param-name>jersey.config.server.response.setStatusOverSendError</param-name>
<param-value>true</param-value>
</init-param>
This can be done with MySQL, although it's highly unintuitive:
CREATE PROCEDURE p25 (OUT return_val INT)
BEGIN
DECLARE a,b INT;
DECLARE cur_1 CURSOR FOR SELECT s1 FROM t;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET b = 1;
OPEN cur_1;
REPEAT
FETCH cur_1 INTO a;
UNTIL b = 1
END REPEAT;
CLOSE cur_1;
SET return_val = a;
END;//
Check out this guide: mysql-storedprocedures.pdf
This is an old question asked two years prior to my answer, I am going to post what worked for me anyways.
In my working directory I have two files: Dockerfile & provision.sh
Dockerfile:
FROM centos:6.8
# put the script in the /root directory of the container
COPY provision.sh /root
# execute the script inside the container
RUN /root/provision.sh
EXPOSE 80
# Default command
CMD ["/bin/bash"]
provision.sh:
#!/usr/bin/env bash
yum upgrade
I was able to make the file in the docker container executable by setting the file outside the container as executable chmod 700 provision.sh
then running docker build .
.
You need to use HAVING
, not WHERE
.
The difference is: the WHERE
clause filters which rows MySQL selects. Then MySQL groups the rows together and aggregates the numbers for your COUNT
function.
HAVING
is like WHERE
, only it happens after the COUNT
value has been computed, so it'll work as you expect. Rewrite your subquery as:
( -- where that pid is in the set:
SELECT c2.pid -- of pids
FROM Catalog AS c2 -- from catalog
WHERE c2.pid = c1.pid
HAVING COUNT(c2.sid) >= 2)
You can use CREATE SYNONYM to remote object.
you could also use display: table
insted of tables. Divs are way more flexible than tables.
Example:
.table {_x000D_
display: table;_x000D_
border-collapse: collapse;_x000D_
}_x000D_
_x000D_
.table .table-row {_x000D_
display: table-row;_x000D_
}_x000D_
_x000D_
.table .table-cell {_x000D_
display: table-cell;_x000D_
text-align: left;_x000D_
vertical-align: top;_x000D_
border: 1px solid black;_x000D_
}
_x000D_
<div class="table">_x000D_
<div class="table-row">_x000D_
<div class="table-cell">test</div>_x000D_
<div class="table-cell">test1123</div>_x000D_
</div>_x000D_
<div class="table-row">_x000D_
<div class="table-cell">test</div>_x000D_
<div class="table-cell">test123</div>_x000D_
</div>_x000D_
</div>
_x000D_
I stumbled across this question while hitting this road block myself. I ended up writing a piece of code real quick to handle this ReDim Preserve
on a new sized array (first or last dimension). Maybe it will help others who face the same issue.
So for the usage, lets say you have your array originally set as MyArray(3,5)
, and you want to make the dimensions (first too!) larger, lets just say to MyArray(10,20)
. You would be used to doing something like this right?
ReDim Preserve MyArray(10,20) '<-- Returns Error
But unfortunately that returns an error because you tried to change the size of the first dimension. So with my function, you would just do something like this instead:
MyArray = ReDimPreserve(MyArray,10,20)
Now the array is larger, and the data is preserved. Your ReDim Preserve
for a Multi-Dimension array is complete. :)
And last but not least, the miraculous function: ReDimPreserve()
'redim preserve both dimensions for a multidimension array *ONLY
Public Function ReDimPreserve(aArrayToPreserve,nNewFirstUBound,nNewLastUBound)
ReDimPreserve = False
'check if its in array first
If IsArray(aArrayToPreserve) Then
'create new array
ReDim aPreservedArray(nNewFirstUBound,nNewLastUBound)
'get old lBound/uBound
nOldFirstUBound = uBound(aArrayToPreserve,1)
nOldLastUBound = uBound(aArrayToPreserve,2)
'loop through first
For nFirst = lBound(aArrayToPreserve,1) to nNewFirstUBound
For nLast = lBound(aArrayToPreserve,2) to nNewLastUBound
'if its in range, then append to new array the same way
If nOldFirstUBound >= nFirst And nOldLastUBound >= nLast Then
aPreservedArray(nFirst,nLast) = aArrayToPreserve(nFirst,nLast)
End If
Next
Next
'return the array redimmed
If IsArray(aPreservedArray) Then ReDimPreserve = aPreservedArray
End If
End Function
I wrote this in like 20 minutes, so there's no guarantees. But if you would like to use or extend it, feel free. I would've thought that someone would've had some code like this up here already, well apparently not. So here ya go fellow gearheads.
Try this:
// Code For IMEI AND IMSI NUMBER
String serviceName = Context.TELEPHONY_SERVICE;
TelephonyManager m_telephonyManager = (TelephonyManager) getSystemService(serviceName);
String IMEI,IMSI;
IMEI = m_telephonyManager.getDeviceId();
IMSI = m_telephonyManager.getSubscriberId();
This is the right answer:
myPassedColor = "#ffff8c85"
int colorInt = Color.parseColor(myPassedColor)
When I ran into this problem, trying to run an async method synchronicity from either a setter or a constructor got me into a deadlock on the UI thread, and using an event handler required too many changes in the general design.
The solution was, as often is, to just write explicitly what I wanted to happen implicitly, which was to have another thread handle the operation and to get the main thread to wait for it to finish:
string someValue=null;
var t = new Thread(() =>someValue = SomeAsyncMethod().Result);
t.Start();
t.Join();
You could argue that I abuse the framework, but it works.
If you are using Ubuntu 18.04 or higher with python3.xxx then try this command
$ sudo apt install python3-sklearn
then try your command. hope it will work
Your problem is basically that you never specified the right path to the file.
Try instead, from your main script:
from folder.file import Klasa
Or, with from folder import file
:
from folder import file
k = file.Klasa()
Or again:
import folder.file as myModule
k = myModule.Klasa()
Full Coding Structure
postgresql function
CREATE OR REPLACE FUNCTION admin.usp_itemdisplayid_byitemhead_select(
item_head_list int[])
RETURNS TABLE(item_display_id integer)
LANGUAGE 'sql'
COST 100
VOLATILE
ROWS 1000
AS $BODY$
SELECT vii.item_display_id from admin.view_item_information as vii
where vii.item_head_id = ANY(item_head_list);
$BODY$;
Model
public class CampaignCreator
{
public int item_display_id { get; set; }
public List<int> pitem_head_id { get; set; }
}
.NET CORE function
DynamicParameters _parameter = new DynamicParameters();
_parameter.Add("@item_head_list",obj.pitem_head_id);
string sql = "select * from admin.usp_itemdisplayid_byitemhead_select(@item_head_list)";
response.data = await _connection.QueryAsync<CampaignCreator>(sql, _parameter);
Yes, you can delete your commit without deleting the changes:
git reset @~
We've solved this by replacing some nasty code in our base html file.
Before:
meta http-equiv="X-UA-Compatible" content="IE=Edge;chrome=1"
After:
And the solution came by replacing it with this magical line:
meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"
Initially when i implemented a longClick and a click to perform two separate events the problem i face was that when i had a longclick , the application also performed the action to be performed for a simple click . The solution i realized was to change the return type of the longClick to true which is normally false by default . Change it and it works perfectly .
You can definitely go for typeid(x).name()
where x is the variable name. It actually returns a const char pointer to the data type. Now, look at the following code.
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n = 36;
char c = 'A';
double d = 1.2;
if(*(typeid(n).name()) == 'i'){
cout << "I am an Integer variable" << endl;
}
if(*((char *) typeid(d).name()) == 'd'){
cout << "I am a Double variable" << endl;
}
if(*((char *) typeid(c).name()) == 'c'){
cout << "I am a Char variable" << endl;
}
return 0;
}
Notice how first and second both if works.
Use the formula by tigeravatar:
=COUNTIF($B$2:$B$5,A2)>0 – tigeravatar Aug 28 '13 at 14:50
as conditional formatting. Highlight column A. Choose conditional formatting by forumula. Enter the formula (above) - this finds values in col B that are also in A. Choose a format (I like to use FILL and a bold color).
To find all of those values, highlight col A. Data > Filter and choose Filter by color.
The runtime splits the arguments given at the console at each space.
If you call
myApp.exe arg1 arg2 arg3
The Main Method gets an array of
var args = new string[] {"arg1","arg2","arg3"}
This draws an arc with the center in the specified rectangle. You can draw, half-circles, quarter-circles, etc.
g.drawArc(x - r, y - r, r * 2, r * 2, 0, 360)
This works well for creating scripts, as you do not have to include other files:
#!/bin/bash
ssh <my_user>@<my_host> "bash -s" << EOF
# here you just type all your commmands, as you can see, i.e.
touch /tmp/test1;
touch /tmp/test2;
touch /tmp/test3;
EOF
# you can use '$(which bash) -s' instead of my "bash -s" as well
# but bash is usually being found in a standard location
# so for easier memorizing it i leave that out
# since i dont fat-finger my $PATH that bad so it cant even find /bin/bash ..
For C++, you could do:
export CXXFLAGS=-m32
This works with cmake.
You can try my lib for multiple bluetooth connection :
Parsing is about READING data in one format, so that you can use it to your needs.
I think you need to teach them to think like this. So, this is the simplest way I can think of to explain parsing for someone new to this concept.
Generally, we try to parse data one line at a time because generally it is easier for humans to think this way, dividing and conquering, and also easier to code.
We call field to every minimum undivisible data. Name is field, Age is another field, and Surname is another field. For example.
In a line, we can have various fields. In order to distinguish them, we can delimit fields by separators or by the maximum length assign to each field.
For example: By separating fields by comma
Paul,20,Jones
Or by space (Name can have 20 letters max, age up to 3 digits, Jones up to 20 letters)
Paul 020Jones
Any of the before set of fields is called a record.
To separate between a delimited field record we need to delimit record. A dot will be enough (though you know you can apply CR/LF).
A list could be:
Michael,39,Jordan.Shaquille,40,O'neal.Lebron,24,James.
or with CR/LF
Michael,39,Jordan
Shaquille,40,O'neal
Lebron,24,James
You can say them to list 10 nba (or nlf) players they like. Then, they should type them according to a format. Then make a program to parse it and display each record. One group, can make list in a comma-separated format and a program to parse a list in a fixed size format, and viceversa.
You cannot play two animations since the attribute can be defined only once. Rather why don't you include the second animation in the first and adjust the keyframes to get the timing right?
.image {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
width: 120px;_x000D_
height: 120px;_x000D_
margin:-60px 0 0 -60px;_x000D_
-webkit-animation:spin-scale 4s linear infinite;_x000D_
}_x000D_
_x000D_
@-webkit-keyframes spin-scale { _x000D_
50%{_x000D_
transform: rotate(360deg) scale(2);_x000D_
}_x000D_
100% { _x000D_
transform: rotate(720deg) scale(1);_x000D_
} _x000D_
}
_x000D_
<img class="image" src="http://makeameme.org/media/templates/120/grumpy_cat.jpg" alt="" width="120" height="120">
_x000D_
You can only use await
in an async
method, and Main
cannot be async
.
You'll have to use your own async
-compatible context, call Wait
on the returned Task
in the Main
method, or just ignore the returned Task
and just block on the call to Read
. Note that Wait
will wrap any exceptions in an AggregateException
.
If you want a good intro, see my async
/await
intro post.
If you want install python libs and their dependencies offline, finish following these steps on a machine with the same os, network connected, and python installed:
1) Create a requirements.txt
file with similar content (Note - these are the libraries you wish to download):
Flask==0.12
requests>=2.7.0
scikit-learn==0.19.1
numpy==1.14.3
pandas==0.22.0
One option for creating the requirements file is to use pip freeze > requirements.txt
. This will list all libraries in your environment. Then you can go in to requirements.txt
and remove un-needed ones.
2) Execute command mkdir wheelhouse && pip download -r requirements.txt -d wheelhouse
to download libs and their dependencies to directory wheelhouse
3) Copy requirements.txt into wheelhouse
directory
4) Archive wheelhouse into wheelhouse.tar.gz
with tar -zcf wheelhouse.tar.gz wheelhouse
Then upload wheelhouse.tar.gz
to your target machine:
1) Execute tar -zxf wheelhouse.tar.gz
to extract the files
2) Execute pip install -r wheelhouse/requirements.txt --no-index --find-links wheelhouse
to install the libs and their dependencies
Move all of your state and your handleClick
function from Header
to your MainWrapper
component.
Then pass values as props to all components that need to share this functionality.
class MainWrapper extends React.Component {
constructor() {
super();
this.state = {
sidbarPushCollapsed: false,
profileCollapsed: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
profileCollapsed: !this.state.profileCollapsed
});
}
render() {
return (
//...
<Header
handleClick={this.handleClick}
sidbarPushCollapsed={this.state.sidbarPushCollapsed}
profileCollapsed={this.state.profileCollapsed} />
);
Then in your Header's render() method, you'd use this.props
:
<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>
For Intellij IDEA version 11.0.2
File | Project Structure | Artifacts then you should press alt+insert or click the plus icon and create new artifact choose --> jar --> From modules with dependencies.
Next goto Build | Build artifacts --> choose your artifact.
source: http://blogs.jetbrains.com/idea/2010/08/quickly-create-jar-artifact/
Close the terminal(End the current session). Open it again.
It's just a syntax error. You just have to replace j+3
by j=j+3
or j+=3
.
I believe there is a better solution than rewrite the RegistrationsController. I did exactly the same thing (I just have Organization instead of Company).
If you set properly your nested form, at model and view level, everything works like a charm.
My User model:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable, :lockable and :timeoutable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :owned_organizations, :class_name => 'Organization', :foreign_key => :owner_id
has_many :organization_memberships
has_many :organizations, :through => :organization_memberships
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :name, :username, :owned_organizations_attributes
accepts_nested_attributes_for :owned_organizations
...
end
My Organization Model:
class Organization < ActiveRecord::Base
belongs_to :owner, :class_name => 'User'
has_many :organization_memberships
has_many :users, :through => :organization_memberships
has_many :contracts
attr_accessor :plan_name
after_create :set_owner_membership, :set_contract
...
end
My view : 'devise/registrations/new.html.erb'
<h2>Sign up</h2>
<% resource.owned_organizations.build if resource.owned_organizations.empty? %>
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<p><%= f.label :name %><br />
<%= f.text_field :name %></p>
<p><%= f.label :email %><br />
<%= f.text_field :email %></p>
<p><%= f.label :username %><br />
<%= f.text_field :username %></p>
<p><%= f.label :password %><br />
<%= f.password_field :password %></p>
<p><%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation %></p>
<%= f.fields_for :owned_organizations do |organization_form| %>
<p><%= organization_form.label :name %><br />
<%= organization_form.text_field :name %></p>
<p><%= organization_form.label :subdomain %><br />
<%= organization_form.text_field :subdomain %></p>
<%= organization_form.hidden_field :plan_name, :value => params[:plan] %>
<% end %>
<p><%= f.submit "Sign up" %></p>
<% end %>
<%= render :partial => "devise/shared/links" %>
You can disable the tooltip setting a title with a space on webkit browsers like Chrome and an empty string on Firefox or IE (tested on Chrome 35, FF 29, IE 11, safari mobile)
$('input[type="file"]').attr('title', window.webkitURL ? ' ' : '');
If what you're trying to do is disable an a link, there is no option to do this. I think you can find an answer that will work for you in this question here.
One option here is to use
<a href="/" onclick="return false;">123n</a>
This should work:
override func viewDidLoad() {
super.viewDidLoad()
var button = UIBarButtonItem(title: "YourTitle", style: UIBarButtonItemStyle.Bordered, target: self, action: "goBack")
self.navigationItem.backBarButtonItem = button
}
func goBack()
{
self.navigationController?.popViewControllerAnimated(true)
}
Although it is not recommended since this actually replaces the backButton and it also removed the back arrow and the swipe gesture.
You mean size() don't you?
#{MyBean.somelist.size()}
works for me (using JBoss Seam which has the Jboss EL extensions)
OpenJDK is a reference model and open source, while Oracle JDK is an implementation of the OpenJDK and is not open source. Oracle JDK is more stable than OpenJDK.
OpenJDK is released under GPL v2 license whereas Oracle JDK is licensed under Oracle Binary Code License Agreement.
OpenJDK and Oracle JDK have almost the same code, but Oracle JDK has more classes and some bugs fixed.
So if you want to develop enterprise/commercial software I would suggest to go for Oracle JDK, as it is thoroughly tested and stable.
I have faced lot of problems with application crashes using OpenJDK, which are fixed just by switching to Oracle JDK
Taken from the accepted answers comment by Steve on Dec 20, 2013:
Actually, there's a very easy way to do it: just click off "Block popup windows" in the iMac/Safari browser and it does what I want.
To clarify, when running Safari on Mac OS X El Capitan:
Even if it is really discouraged to use merge cells in Excel (use Center Across Selection
for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).
Hence, you can get the value of merged cells in range B4:B11
in several ways:
Range("B4").Value
Range("B4:B11").Cells(1).Value
Range("B4:B11").Cells(1,1).Value
You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty
.
Also note that Range("B4:B11").Value
won't work (raises an execution error number 13 if you try to Debug.Print
it) because it returns an array.
To get a scrollbar for an ItemsControl
, you can host it in a ScrollViewer
like this:
<ScrollViewer VerticalScrollBarVisibility="Auto">
<ItemsControl>
<uc:UcSpeler />
<uc:UcSpeler />
<uc:UcSpeler />
<uc:UcSpeler />
<uc:UcSpeler />
</ItemsControl>
</ScrollViewer>
All the above answers really help me to construct my answer, because of this I voted for all the answers that other users put it out: But I finally put together my own answer to exact problem I was dealing with:
As question clearly defined I had to access some of the siblings and its children in a dom structure: This solution will iterate over the images in the dom structure and construct image name using product title and save the image to the local directory.
import urlparse
from urllib2 import urlopen
from urllib import urlretrieve
from BeautifulSoup import BeautifulSoup as bs
import requests
def getImages(url):
#Download the images
r = requests.get(url)
html = r.text
soup = bs(html)
output_folder = '~/amazon'
#extracting the images that in div(s)
for div in soup.findAll('div', attrs={'class':'image'}):
modified_file_name = None
try:
#getting the data div using findNext
nextDiv = div.findNext('div', attrs={'class':'data'})
#use findNext again on previous object to get to the anchor tag
fileName = nextDiv.findNext('a').text
modified_file_name = fileName.replace(' ','-') + '.jpg'
except TypeError:
print 'skip'
imageUrl = div.find('img')['src']
outputPath = os.path.join(output_folder, modified_file_name)
urlretrieve(imageUrl, outputPath)
if __name__=='__main__':
url = r'http://www.amazon.com/s/ref=sr_pg_1?rh=n%3A172282%2Ck%3Adigital+camera&keywords=digital+camera&ie=UTF8&qid=1343600585'
getImages(url)
Your regex should work 'as-is'. Assuming that it is doing what you want it to.
wordA(\s*)wordB(?! wordc)
This means match wordA
followed by 0 or more spaces followed by wordB
, but do not match if followed by wordc
. Note the single space between ?!
and wordc
which means that wordA wordB wordc
will not match, but wordA wordB wordc
will.
Here are some example matches and the associated replacement output:
Note that all matches are replaced no matter how many spaces. There are a couple of other points: -
(?! wordc)
is a negative lookahead, so you wont match lines wordA wordB wordc
which is assume is intended (and is why the last line is not matched). Currently you are relying on the space after ?!
to match the whitespace. You may want to be more precise and use (?!\swordc)
. If you want to match against more than one space before wordc you can use (?!\s*wordc)
for 0 or more spaces or (?!\s*+wordc)
for 1 or more spaces depending on what your intention is.
Of course, if you do want to match lines with wordc after wordB then you shouldn't use a negative lookahead.
*
will match 0 or more spaces so it will match wordAwordB. You may want to consider +
if you want at least one space.
(\s*)
- the brackets indicate a capturing group. Are you capturing the whitespace to a group for a reason? If not you could just remove the brackets, i.e. just use \s
.
Update based on comment
Hello the problem is not the expression but the HTML out put that are not considered as whitespace. it's a Joomla website.
Preserving your original regex you can use:
wordA((?:\s| )*)wordB(?!(?:\s| )wordc)
The only difference is that not the regex matches whitespace OR
. I replaced wordc
with \swordc
since that is more explicit. Note as I have already pointed out that the negative lookahead ?!
will not match when wordB is followed by a single whitespace and wordc. If you want to match multiple whitespaces then see my comments above. I also preserved the capture group around the whitespace, if you don't want this then remove the brackets as already described above.
Example matches:
Adding a third option. The "shorthand" version of @AndrewD's second option.
Yes, there are no quotes in the bracket reference.
String one, two, three;
one = two = three = "";
This should work with immutable objects. It doesn't make any sense for mutable objects for example:
Person firstPerson, secondPerson, thirdPerson;
firstPerson = secondPerson = thirdPerson = new Person();
All the variables would be pointing to the same instance. Probably what you would need in that case is:
Person firstPerson = new Person();
Person secondPerson = new Person();
Person thirdPerson = new Person();
Or better yet use an array or a Collection
.
This may not be the best solution. I changed my maven from 3.3.x to 3.2.x. And this issue gone.
For those using Xamarin, I had to add the key NSLocationWhenInUseUsageDescription
to the info.plist manually since it was not available in the dropdowns in either Xamarin 5.5.3 Build 6 or XCode 6.1 - only NSLocationUsageDescription
was in the list, and that caused the CLLocationManager
to continue to fail silently.
Well you're right, REST is stateless. If you use a session the processing will become stateful, subsequent requests will be able to use state (from a session).
In order for a session to be rehydrated, you'll need to supply a key to associate the state. In a normal asp.net application that key is supplied by using a cookie (cookie-sessions) or url parameter (cookieless sessions).
If you need a session forget rest, sessions are irrelevant in REST based designs. If you need a session for validation then use a token or authorise by IP addresses.
If you want to make sure that your base classes and their members are strictly abstract here is a base class that does this for you:
class AbstractBase{
constructor(){}
checkConstructor(c){
if(this.constructor!=c) return;
throw new Error(`Abstract class ${this.constructor.name} cannot be instantiated`);
}
throwAbstract(){
throw new Error(`${this.constructor.name} must implement abstract member`);}
}
class FooBase extends AbstractBase{
constructor(){
super();
this.checkConstructor(FooBase)}
doStuff(){this.throwAbstract();}
doOtherStuff(){this.throwAbstract();}
}
class FooBar extends FooBase{
constructor(){
super();}
doOtherStuff(){/*some code here*/;}
}
var fooBase = new FooBase(); //<- Error: Abstract class FooBase cannot be instantiated
var fooBar = new FooBar(); //<- OK
fooBar.doStuff(); //<- Error: FooBar must implement abstract member
fooBar.doOtherStuff(); //<- OK
Strict mode makes it impossible to log the caller in the throwAbstract method but the error should occur in a debug environment that would show the stack trace.
Here is a version of Carlo's answer that can be used in a class:
class Formatter
{
public function objectToArray($data)
{
if (is_object($data)) {
$data = get_object_vars($data);
}
if (is_array($data)) {
return array_map(array($this, 'objectToArray'), $data);
}
return $data;
}
}
I had the same problem when trying to load Hadoop project in eclipse. I tried the solutions above, and I believe it might have worked in Eclipse Kepler... not even sure anymore (tried too many things).
With all the problems I was having, I decided to move on to Eclipse Luna, and the solutions above did not work for me.
There was another post that recommended changing the ... tag to package. I started doing that, and it would "clear" the errors... However, I start to think that the changes would bite me later - I am not an expert on Maven.
Fortunately, I found out how to remove all the errors. Go to Window->Preferences->Maven-> Error/Warnings and change "Plugin execution not covered by lifecycle..." option to "Ignore". Hope it helps.
class MyComponent extends Component {
constructor(props){
super(props)
this.state = {
inputVal: props.inputValue
}
// preserve the initial state in a new object
this.baseState = this.state
}
resetForm = () => {
this.setState(this.baseState)
}
}
I made a **
automatic-network-drive connector
** using a batch file.
Suddenly there was a networkdrive called "Data for Analysation", and yeah with the double quotes it works proper!
looks a little bit different but works:
net use y: "\\share.blabla.com\Folder\Subfolder\Data for Analysation" /USER:domain\username PW /PERSISTENT:YES
Thx for the Hint :)
Several of these answers suggest that at the top of a module you you do
import logging
logger = logging.getLogger(__name__)
It is my understanding that this is considered very bad practice. The reason is that the file config will disable all existing loggers by default. E.g.
#my_module
import logging
logger = logging.getLogger(__name__)
def foo():
logger.info('Hi, foo')
class Bar(object):
def bar(self):
logger.info('Hi, bar')
And in your main module :
#main
import logging
# load my module - this now configures the logger
import my_module
# This will now disable the logger in my module by default, [see the docs][1]
logging.config.fileConfig('logging.ini')
my_module.foo()
bar = my_module.Bar()
bar.bar()
Now the log specified in logging.ini will be empty, as the existing logger was disabled by fileconfig call.
While is is certainly possible to get around this (disable_existing_Loggers=False), realistically many clients of your library will not know about this behavior, and will not receive your logs. Make it easy for your clients by always calling logging.getLogger locally. Hat Tip : I learned about this behavior from Victor Lin's Website.
So good practice is instead to always call logging.getLogger locally. E.g.
#my_module
import logging
logger = logging.getLogger(__name__)
def foo():
logging.getLogger(__name__).info('Hi, foo')
class Bar(object):
def bar(self):
logging.getLogger(__name__).info('Hi, bar')
Also, if you use fileconfig in your main, set disable_existing_loggers=False, just in case your library designers use module level logger instances.
SELECT x.name, x.summary, (x.summary / COUNT(*)) as percents_of_total
FROM tbl t
INNER JOIN
(SELECT name, SUM(value) as summary
FROM tbl
WHERE year BETWEEN 2000 AND 2001
GROUP BY name) x ON x.name = t.name
GROUP BY x.name, x.summary
I had to (on top of what mentioned here) add the following line to Runpath Search Paths under Build Settings tab:
@executable_path/Frameworks
I have the script all.p
set ...
...
list=system('ls -1B *.dat')
plot for [file in list] file w l u 1:2 t file
Here the two last rows are literal, not heuristic. Then i run
$ gnuplot -p all.p
Change *.dat
to the file type you have, or add file types.
Next step: Add to ~/.bashrc this line
alias p='gnuplot -p ~/./all.p'
and put your file all.p
int your home directory and voila. You can plot all files in any directory by typing p and enter.
EDIT I changed the command, because it didn't work. Previously it contained list(i)=word(system(ls -1B *.dat),i)
.
This looks a little better than your previous version but get rid of that .Activate on that line and see if you still get that error.
Dim sh1 As Worksheet
set sh1 = Workbooks.Add(filenum(lngPosition) & ".csv")
Creates a worksheet object. Not until you create that object do you want to start working with it. Once you have that object you can do the following:
sh1.Range("A69").Paste
sh1.Range("A69").Select
The sh1. explicitely tells Excel which object you are saying to work with... otherwise if you start selecting other worksheets while this code is running you could wind up pasting data to the wrong place.
You can use this library to manipulate the image while uploading. http://www.verot.net/php_class_upload.htm
Lifepaths.class.getClass().getResourceAsStream(...)
loads resources using system class loader, it obviously fails because it does not see your JARs
Lifepaths.class.getResourceAsStream(...)
loads resources using the same class loader that loaded Lifepaths class and it should have access to resources in your JARs
Here's a light weight way to use require and exports in your web client. It's a simple wrapper that creates a "namespace" global variable, and you wrap your CommonJS compatible code in a "define" function like this:
namespace.lookup('org.mydomain.mymodule').define(function (exports, require) {
var extern = require('org.other.module');
exports.foo = function foo() { ... };
});
More docs here:
Also, somewhat in the same vein
Type.IsAssignableFrom(Type c)
"True if c and the current Type represent the same type, or if the current Type is in the inheritance hierarchy of c, or if the current Type is an interface that c implements, or if c is a generic type parameter and the current Type represents one of the constraints of c."
From here: http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx
here is another simple solution to get the selected the text in the form of string, you can use this string easily to append a div element child into your code:
var text = '';
if (window.getSelection) {
text = window.getSelection();
} else if (document.getSelection) {
text = document.getSelection();
} else if (document.selection) {
text = document.selection.createRange().text;
}
text = text.toString();
DECLARE @id INT
DECLARE @filename NVARCHAR(100)
DECLARE @getid CURSOR
SET @getid = CURSOR FOR
SELECT top 3 id,
filename
FROM table
OPEN @getid
WHILE 1=1
BEGIN
FETCH NEXT
FROM @getid INTO @id, @filename
IF @@FETCH_STATUS < 0 BREAK
print @id
END
CLOSE @getid
DEALLOCATE @getid
A SELECT INTO
statement creates the table for you. There is no need for the CREATE TABLE
statement before hand.
What is happening is that you create #ivmy_cash_temp1
in your CREATE
statement, then the DB tries to create it for you when you do a SELECT INTO
. This causes an error as it is trying to create a table that you have already created.
Either eliminate the CREATE TABLE
statement or alter your query that fills it to use INSERT INTO SELECT
format.
If you need a unique ID added to your new row then it's best to use SELECT INTO
... since IDENTITY()
only works with this syntax.
Constants can be declare outside of classes and use within your class. Otherwise the get
property is a nice workaround
const MY_CONSTANT: string = "wazzup";
export class MyClass {
public myFunction() {
alert(MY_CONSTANT);
}
}
This error can be thrown when you import a different library for @Id than Javax.persistance.Id ; You might need to pay attention this case too
In my case I had
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Table;
import org.springframework.data.annotation.Id;
@Entity
public class Status {
@Id
@GeneratedValue
private int id;
when I change the code like this, it got worked
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Table;
import javax.persistence.Id;
@Entity
public class Status {
@Id
@GeneratedValue
private int id;
It seems daft, but I think when you use the same bind variable twice you have to set it twice:
cmd.Parameters.Add("VarA", "24");
cmd.Parameters.Add("VarB", "test");
cmd.Parameters.Add("VarB", "test");
cmd.Parameters.Add("VarC", "1234");
cmd.Parameters.Add("VarC", "1234");
Certainly that's true with Native Dynamic SQL in PL/SQL:
SQL> begin
2 execute immediate 'select * from emp where ename=:name and ename=:name'
3 using 'KING';
4 end;
5 /
begin
*
ERROR at line 1:
ORA-01008: not all variables bound
SQL> begin
2 execute immediate 'select * from emp where ename=:name and ename=:name'
3 using 'KING', 'KING';
4 end;
5 /
PL/SQL procedure successfully completed.
To me the simplest seemed using
datetime.setUTCHours(datetime.getHours());
datetime.setUTCMinutes(datetime.getMinutes());
(i thought the first line could be enough but there are timezones which are off in fractions of hours)
function change() {
myButton1.value=="Open Curtain" ? myButton1.value="Close Curtain" : myButton1.value="Open Curtain";
}
Declaration says "this thing exists somewhere":
int foo(); // function
extern int bar; // variable
struct T
{
static int baz; // static member variable
};
Definition says "this thing exists here; make memory for it":
int foo() {} // function
int bar; // variable
int T::baz; // static member variable
Initialisation is optional at the point of definition for objects, and says "here is the initial value for this thing":
int bar = 0; // variable
int T::baz = 42; // static member variable
Sometimes it's possible at the point of declaration instead:
struct T
{
static int baz = 42;
};
…but that's getting into more complex features.
While this seems to work
Code::query()
->where('to_be_used_by_user_id', '!=' , 2)
->orWhereNull('to_be_used_by_user_id')
->get();
you should not use it for big tables, because as a general rule "or" in your where clause is stopping query to use index. You are going from "Key lookup" to "full table scan"
Instead, try Union
$first = Code::whereNull('to_be_used_by_user_id');
$code = Code::where('to_be_used_by_user_id', '!=' , 2)
->union($first)
->get();
Just wanted to share my solution using sqlalchemy and pandas in python 3. Perhaps, one would find it useful.
import sqlalchemy as sa
import pandas as pd
engine = sa.create_engine("postgresql://postgres:my_password@my_host:my_port/my_db")
values = [val1,val2,val3]
query = sa.text("""
SELECT *
FROM my_table
WHERE col1 IN :values;
""")
query = query.bindparams(values=tuple(values))
df = pd.read_sql(query, engine)
yourList = ["a", "b", "a", "c", "c", "a", "c"]
expected outputs {a: 3, b: 1,c:3}
duplicateFrequencies = {}
for i in set(yourList):
duplicateFrequencies[i] = yourList.count(i)
Cheers!! Reference
As already pointed out by @snishalaka, you can increase the number of inotify watchers.
However, I think the default number is high enough and is only reached when processes are not cleaned up properly. Hence, I simply restarted my computer as proposed on a related github issue and the error message was gone.
Simple regex for any number of digits at the end of a string:
'xxx_456'.match(/\d+$/)[0]; //456
'xxx_4567890'.match(/\d+$/)[0]; //4567890
or use split/pop indeed:
('yyy_xxx_45678901').split(/_/).pop(); //45678901
getattr
calls method by name from an object.
But this object should be parent of calling class.
The parent class can be got by super(self.__class__, self)
class Base:
def call_base(func):
"""This does not work"""
def new_func(self, *args, **kwargs):
name = func.__name__
getattr(super(self.__class__, self), name)(*args, **kwargs)
return new_func
def f(self, *args):
print(f"BASE method invoked.")
def g(self, *args):
print(f"BASE method invoked.")
class Inherit(Base):
@Base.call_base
def f(self, *args):
"""function body will be ignored by the decorator."""
pass
@Base.call_base
def g(self, *args):
"""function body will be ignored by the decorator."""
pass
Inherit().f() # The goal is to print "BASE method invoked."
>>> d = {}
>>> D = set()
>>> type(d)
<type 'dict'>
>>> type(D)
<type 'set'>
What you've made is a dictionary and not a Set.
The update
method in dictionary is used to update the new dictionary from a previous one, like so,
>>> abc = {1: 2}
>>> d.update(abc)
>>> d
{1: 2}
Whereas in sets, it is used to add elements to the set.
>>> D.update([1, 2])
>>> D
set([1, 2])
As of Java 1.7, there's a new way: java.nio.file.Files.write
import java.nio.file.Files;
import java.nio.file.Paths;
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
SecretKey key = kgen.generateKey();
byte[] encoded = key.getEncoded();
Files.write(Paths.get("target-file"), encoded);
Java 1.7 also resolves the embarrassment that Kevin describes: reading a file is now:
byte[] data = Files.readAllBytes(Paths.get("source-file"));
Right-click, then "Open link in new tab"
edit : you can also double-click, it has the same effect
Since 9.6 this is a lot easier as it introduced the function pg_blocking_pids()
to find the sessions that are blocking another session.
So you can use something like this:
select pid,
usename,
pg_blocking_pids(pid) as blocked_by,
query as blocked_query
from pg_stat_activity
where cardinality(pg_blocking_pids(pid)) > 0;
For org.json I've rolled out my own solution, a method that compares to JSONObject instances. I didn't work with complex JSON objects in that project, so I don't know whether this works in all scenarios. Also, given that I use this in unit tests, I didn't put effort into optimizations. Here it is:
public static boolean jsonObjsAreEqual (JSONObject js1, JSONObject js2) throws JSONException {
if (js1 == null || js2 == null) {
return (js1 == js2);
}
List<String> l1 = Arrays.asList(JSONObject.getNames(js1));
Collections.sort(l1);
List<String> l2 = Arrays.asList(JSONObject.getNames(js2));
Collections.sort(l2);
if (!l1.equals(l2)) {
return false;
}
for (String key : l1) {
Object val1 = js1.get(key);
Object val2 = js2.get(key);
if (val1 instanceof JSONObject) {
if (!(val2 instanceof JSONObject)) {
return false;
}
if (!jsonObjsAreEqual((JSONObject)val1, (JSONObject)val2)) {
return false;
}
}
if (val1 == null) {
if (val2 != null) {
return false;
}
} else if (!val1.equals(val2)) {
return false;
}
}
return true;
}
Numpy provides two identical methods to do this. Either use
np.round(data, 2)
or
np.around(data, 2)
as they are equivalent.
See the documentation for more information.
Examples:
>>> import numpy as np
>>> a = np.array([0.015, 0.235, 0.112])
>>> np.round(a, 2)
array([0.02, 0.24, 0.11])
>>> np.around(a, 2)
array([0.02, 0.24, 0.11])
>>> np.round(a, 1)
array([0. , 0.2, 0.1])
Here is a simple solution using rsync:
rsync -av -f"+ */" -f"- *" "$source" "$target"
Probably because of optimizations. Excel 2007 can have a maximum of 16 384 columns and 1 048 576 rows. Strange numbers?
14 bits = 16 384, 20 bits = 1 048 576
14 + 20 = 34 bits = more than one 32 bit register can hold.
But they also need to store the format of the cell (text, number etc) and formatting (colors, borders etc). Assuming they use two 32-bit words (64 bit) they use 34 bits for the cell number and have 30 bits for other things.
Why is that important? In memory they don't need to allocate all the memory needed for the whole spreadsheet but only the memory necessary for your data, and every data is tagged with in what cell it is supposed to be in.
Update 2016:
Found a link to Microsoft's specification for Excel 2013 & 2016
If the jdk.tools is present in the .m2 repository. Still you get the error something like this:
missing artifact: jdk.tools.....c:.../jre/..
In the buildpath->configure build path-->Libraries.Just change JRE system library from JRE to JDK.
Here's an example in React, but it can be translated to jQuery on vanilla JS if you prefer:
class Num extends React.Component {
click = ev => {
const el = ev.currentTarget;
if(document.activeElement !== el) {
setTimeout(() => {
el.select();
}, 0);
}
}
render() {
return <input type="number" min={0} step={15} onMouseDown={this.click} {...this.props} />
}
}
The trick here is to use onMouseDown
because the element has already received focus by the time the "click" event fires (and thus the activeElement
check will fail).
The activeElement
check is necessary so that they user can position their cursor where they want without constantly re-selecting the entire input.
The timeout is necessary because otherwise the text will be selected and then instantly unselected, as I guess the browser does the cursor-positioning check afterwords.
And lastly, the el = ev.currentTarget
is necessary in React because React re-uses event objects and you'll lose the synthetic event by the time the setTimeout fires.
git add B # Add it to the index
git reset A # Remove it from the index
git commit # Commit the index
I am not sure if I see this option here. You can just create a /folder
in your repository and use it directly:
[a relative link](/folder/myrelativefile.md)
No blob or tree or repository name is needed, and it works like a charm.
For my application i made a helper function:
function message( $message , $status = 'success', $redirectPath = null )
{
$redirectPath = $redirectPath == null ? back() : redirect( $redirectPath );
return $redirectPath->with([
'message' => $message,
'status' => $status,
]);
}
message layout, main.layouts.message
:
@if($status)
<div class="center-block affix alert alert-{{$status}}">
<i class="fa fa-{{ $status == 'success' ? 'check' : $status}}"></i>
<span>
{{ $message }}
</span>
</div>
@endif
and import every where to show message:
@include('main.layouts.message', [
'status' => session('status'),
'message' => session('message'),
])
If you have cloned your repo using url that contains your username, then you should also change remote.origin.url
property because otherwise it keeps asking password for the old username.
example:
remote.origin.url=https://<old_uname>@<repo_url>
should change to
remote.origin.url=https://<new_uname>@<repo_url>
Neither way is necessarily correct or incorrect, they are just two different kinds of class elements:
__init__
method are static elements; they belong to the class.__init__
method are elements of the object (self
); they don't belong to the class.You'll see it more clearly with some code:
class MyClass:
static_elem = 123
def __init__(self):
self.object_elem = 456
c1 = MyClass()
c2 = MyClass()
# Initial values of both elements
>>> print c1.static_elem, c1.object_elem
123 456
>>> print c2.static_elem, c2.object_elem
123 456
# Nothing new so far ...
# Let's try changing the static element
MyClass.static_elem = 999
>>> print c1.static_elem, c1.object_elem
999 456
>>> print c2.static_elem, c2.object_elem
999 456
# Now, let's try changing the object element
c1.object_elem = 888
>>> print c1.static_elem, c1.object_elem
999 888
>>> print c2.static_elem, c2.object_elem
999 456
As you can see, when we changed the class element, it changed for both objects. But, when we changed the object element, the other object remained unchanged.
It sounds like you are talking about aggregation. Each instance of your player
class can contain zero or more instances of Airplane
, which, in turn, can contain zero or more instances of Flight
. You can implement this in Python using the built-in list
type to save you naming variables with numbers.
class Flight(object):
def __init__(self, duration):
self.duration = duration
class Airplane(object):
def __init__(self):
self.flights = []
def add_flight(self, duration):
self.flights.append(Flight(duration))
class Player(object):
def __init__ (self, stock = 0, bank = 200000, fuel = 0, total_pax = 0):
self.stock = stock
self.bank = bank
self.fuel = fuel
self.total_pax = total_pax
self.airplanes = []
def add_planes(self):
self.airplanes.append(Airplane())
if __name__ == '__main__':
player = Player()
player.add_planes()
player.airplanes[0].add_flight(5)
There's a short overview at MinGW-w64 Wiki:
Why doesn't mingw-w64 gcc support Dwarf-2 Exception Handling?
The Dwarf-2 EH implementation for Windows is not designed at all to work under 64-bit Windows applications. In win32 mode, the exception unwind handler cannot propagate through non-dw2 aware code, this means that any exception going through any non-dw2 aware "foreign frames" code will fail, including Windows system DLLs and DLLs built with Visual Studio. Dwarf-2 unwinding code in gcc inspects the x86 unwinding assembly and is unable to proceed without other dwarf-2 unwind information.
The SetJump LongJump method of exception handling works for most cases on both win32 and win64, except for general protection faults. Structured exception handling support in gcc is being developed to overcome the weaknesses of dw2 and sjlj. On win64, the unwind-information are placed in xdata-section and there is the .pdata (function descriptor table) instead of the stack. For win32, the chain of handlers are on stack and need to be saved/restored by real executed code.
GCC GNU about Exception Handling:
GCC supports two methods for exception handling (EH):
- DWARF-2 (DW2) EH, which requires the use of DWARF-2 (or DWARF-3) debugging information. DW-2 EH can cause executables to be slightly bloated because large call stack unwinding tables have to be included in th executables.
- A method based on setjmp/longjmp (SJLJ). SJLJ-based EH is much slower than DW2 EH (penalising even normal execution when no exceptions are thrown), but can work across code that has not been compiled with GCC or that does not have call-stack unwinding information.
[...]
Structured Exception Handling (SEH)
Windows uses its own exception handling mechanism known as Structured Exception Handling (SEH). [...] Unfortunately, GCC does not support SEH yet. [...]
See also:
T.innerText = "Position of LF: " + t.value.indexOf("\n");
p3.innerText = t.value.replace("\n", "");
<textarea id="t">Line 1 Line 2</textarea>
<p id='p3'></p>
With postgres 9.3 use -> for object access. 4 example
seed.rb
se = SmartElement.new
se.data =
{
params:
[
{
type: 1,
code: 1,
value: 2012,
description: 'year of producction'
},
{
type: 1,
code: 2,
value: 30,
description: 'length'
}
]
}
se.save
rails c
SELECT data->'params'->0 as data FROM smart_elements;
returns
data
----------------------------------------------------------------------
{"type":1,"code":1,"value":2012,"description":"year of producction"}
(1 row)
You can continue nesting
SELECT data->'params'->0->'type' as data FROM smart_elements;
return
data
------
1
(1 row)
Simple code to check pointer aliasing:
int main () {
int a = 10, b = 20;
int *p1, *p2, *p3, *p4;
p1 = &a;
p2 = &a;
if(p1 == p2){
std::cout<<"p1 and p2 alias each other"<<std::endl;
}
else{
std::cout<<"p1 and p2 do not alias each other"<<std::endl;
}
//------------------------
p3 = &a;
p4 = &b;
if(p3 == p4){
std::cout<<"p3 and p4 alias each other"<<std::endl;
}
else{
std::cout<<"p3 and p4 do not alias each other"<<std::endl;
}
return 0;
}
Output:
p1 and p2 alias each other
p3 and p4 do not alias each other
I'm not on windows, but I think you can use the pgAdmin you just installed to configure a server connection and start the server.
From Java 8 you can use :
Comparator.comparingInt(Dog::getDogAge).reversed();
Can't you just count the rows using select count(*) from table
(or an indexed column instead of * if speed is important)?
If not then maybe this article can point you in the right direction.
This is definitely a bug specially while it's FireFox. I searched alot tried all the above answers and finally got it as bug by many experts over SO. So, I finally came up with this idea by declaring variable like
var called = false;
$("#ColorPalete li").click(function() {
if(!called)
{
called = true;
setTimeout(function(){ //<-----This can be an ajax request but keep in mind to set called=false when you get response or when the function has successfully executed.
alert('I am called');
called = false;
},3000);
}
});
In this way it first checks rather the function was previously called or not.
The answer above was mostly correct, just needed some tweaking for the different parameters in Mac OSX.
ps -A | grep [f]irefox | awk '{print $1}'
you have to create an entry inside res/menu,
override onCreateOptionsMenu
and inflate it
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.yourentry, menu);
return true;
}
an entry for the menu could be:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_cart"
android:icon="@drawable/cart"
android:orderInCategory="100"
android:showAsAction="always"/>
</menu>
Replying to an old post but hopefully somebody might find this useful. Do this instead
final AlertDialog builder = new AlertDialog.Builder(getActivity()).create();
You can then go ahead and do,
builder.dismiss();
Here's a simple extension
on UIBarButtonItem
:
extension UIBarButtonItem {
class func itemWith(colorfulImage: UIImage?, target: AnyObject, action: Selector) -> UIBarButtonItem {
let button = UIButton(type: .custom)
button.setImage(colorfulImage, for: .normal)
button.frame = CGRect(x: 0.0, y: 0.0, width: 44.0, height: 44.0)
button.addTarget(target, action: action, for: .touchUpInside)
let barButtonItem = UIBarButtonItem(customView: button)
return barButtonItem
}
}
DECLARE @t1 TABLE (
TableID int IDENTITY,
FieldValue varchar(20)
)
--<< No empty string
IF EXISTS (
SELECT *
FROM @t1
WHERE FieldValue = ''
) BEGIN
SELECT TableID
FROM @t1
WHERE FieldValue=''
END
ELSE BEGIN
INSERT INTO @t1 (FieldValue) VALUES ('')
SELECT SCOPE_IDENTITY() AS TableID
END
--<< A record with an empty string already exists
IF EXISTS (
SELECT *
FROM @t1
WHERE FieldValue = ''
) BEGIN
SELECT TableID
FROM @t1
WHERE FieldValue=''
END
ELSE BEGIN
INSERT INTO @t1 (FieldValue) VALUES ('')
SELECT SCOPE_IDENTITY() AS TableID
END
Because it appends; it doesn't push. "Appending" adds to the end of a list, "pushing" adds to the front.
Think of a queue vs. a stack.
http://docs.python.org/tutorial/datastructures.html
Edit: To reword my second sentence more exactly, "Appending" very clearly implies adding something to the end of a list, regardless of the underlying implementation. Where a new element gets added when it's "pushed" is less clear. Pushing onto a stack is putting something on "top," but where it actually goes in the underlying data structure completely depends on implementation. On the other hand, pushing onto a queue implies adding it to the end.
You should look at the source of the HashSet
constructor it calls... it's a special constructor that makes the backing Map
a LinkedHashMap
instead of just a HashMap
.
People answering about offline work is active is right. But it was located in different place in my case. To find it in the top bar menu select
In adittion you can clic the help menu in the top bar menu and write "gradle" and it suggest the locations.
I don't know if it's possible to run it just like that.
I usually first copy it with scp and then log in to run it.
scp foo.sh user@host:~
ssh user@host
./foo.sh
Yes it is possible. I have been doing that all the while.
dynamic Obj = JsonConvert.DeserializeObject(<your json string>);
It is a bit trickier for non native type. Suppose inside your Obj, there is a ClassA, and ClassB objects. They are all converted to JObject. What you need to do is:
ClassA ObjA = Obj.ObjA.ToObject<ClassA>();
ClassB ObjB = Obj.ObjB.ToObject<ClassB>();
If you want to have your arguments C style (array of arguments + number of arguments) you can use $@
and $#
.
$#
gives you the number of arguments.
$@
gives you all arguments. You can turn this into an array by args=("$@")
.
So for example:
args=("$@")
echo $# arguments passed
echo ${args[0]} ${args[1]} ${args[2]}
Note that here ${args[0]}
actually is the 1st argument and not the name of your script.
There is built in functionality for this using the JavaScriptSerializer Class:
var json = JavaScriptSerializer.Serialize(data);
The solution for me was file permissions in Windows. Just give full control in the file to all users and it will work. After the import, get the permissions back to what it was before.
I have a related but different scenario. Following is what I am doing:
Note: Code to select/unselect all radio buttons of class 'containerRadio' when the main radio button is selected.
CODE
$('#selectAllWorkLot').click (function ()
{
var previousValue = $(this).attr('previousValue');
if (previousValue == 'checked')
{
resetRadioButtonForSelectAll();
//Unselect All
unSelectAllContainerRadioButtons();
}
else
{
$(this).attr('previousValue', 'checked');
//Select All
selectAllContainerRadioButtons();
}
});
function resetRadioButtonForSelectAll()
{
$('#selectAllWorkLot').removeAttr('checked');
$('#selectAllWorkLot').attr('previousValue', false);
//$('#selectAllWorkLot').prop('checked', false);
}
function selectAllContainerRadioButtons()
{
$('.containerRadio').prop('checked', true);
}
function unSelectAllContainerRadioButtons()
{
$('.containerRadio').prop('checked', false);
}
also, for syndicated content "Authors are encouraged to use the article element instead of the section element when it would make sense to syndicate the contents of the element."
As the other have mentioned, the load event does not bubble. Instead you can manually trigger a load-like event with a custom event:
$('#item').on('namespace/onload', handleOnload).trigger('namespace/onload')
If your element is already listening to a change
event:
$('#item').on('change', handleChange).trigger('change')
I find this works well. Though, I stick to custom events to be more explicit and avoid side effects.
Both GET and POST are used by the browser to request a single resource from the server. Each resource requires a separate GET or POST request.
The GET method is used in one of two ways: When no method is specified, that is when you or the browser is requesting a simple resource such as an HTML page, an image, etc. When a form is submitted, and you choose method=GET on the HTML tag. If the GET method is used with an HTML form, then the data collected through the form is sent to the server by appending a "?" to the end of the URL, and then adding all name=value pairs (name of the html form field and value entered in that field) separated by an "&" Example: GET /sultans/shop//form1.jsp?name=Sam%20Sultan&iceCream=vanilla HTTP/1.0 optional headeroptional header<< empty line >>>
The name=value form data will be stored in an environment variable called QUERY_STRING. This variable will be sent to a processing program (such as JSP, Java servlet, PHP etc.)
Example: POST /sultans/shop//form1.jsp HTTP/1.0 optional headeroptional header<< empty line >>> name=Sam%20Sultan&iceCream=vanilla
When using the post method, the QUERY_STRING environment variable will be empty. Advantages/Disadvantages of GET vs. POST
Advantages of the GET method: Slightly faster Parameters can be entered via a form or by appending them after the URL Page can be bookmarked with its parameters
Disadvantages of the GET method: Can only send 4K worth of data. (You should not use it when using a textarea field) Parameters are visible at the end of the URL
Advantages of the POST method: Parameters are not visible at the end of the URL. (Use for sensitive data) Can send more that 4K worth of data to server
Disadvantages of the POST method: Can cannot be bookmarked with its data
This is not an elegant solution, but what does seem to work is saving to XLSX and then importing it back. The other solutions on this page did not work for me, unsure why.
data.to_excel(filepath, index=False)
data = pd.read_excel(filepath)
So many ways to do it.
From Workbench: File > Run SQL Script -- then follow prompts
From Windows Command Line:
Option 1: mysql -u usr -p
mysql> source file_path.sql
Option 2: mysql -u usr -p '-e source file_path.sql'
Option 3: mysql -u usr -p < file_path.sql
Option 4: put multiple 'source' statements inside of file_path.sql (I do this to drop and recreate schemas/databases which requires multiple files to be run)
mysql -u usr -p < file_path.sql
If you get errors from the command line, make sure you have previously run
cd {!!>>mysqld.exe home directory here<<!!}
mysqld.exe --initialize
This must be run from within the mysqld.exe directory, hence the CD.
Hope this is helpful and not just redundant.
For macOS Sierra, to build wget 1.18 from source with Xcode 8.2.
Install Xcode
Build OpenSSL
Since Xcode doesn't come with OpenSSL lib, you need build by yourself. I found this: https://github.com/sqlcipher/openssl-xcode, follow instruction and build OpenSSL lib. Then, prepare your OpenSSL directory with "include" and "lib/libcrypto.a", "lib/libssl.a" in it.
Let's say it is: "/Users/xxx/openssl-xcode/openssl", so there should be "/Users/xxx/openssl-xcode/openssl/include" for OpenSSL include and "/Users/xxx/openssl-xcode/openssl/lib" for "libcrypto.a" and "libssl.a".
Build wget
Go to wget directory, configure:
./configure --with-ssl=openssl --with-libssl-prefix=/Users/xxx/openssl-xcode/openssl
wget should configure and found OpenSSL, then make:
make
wget made out. Install wget:
make install
Or just copy wget to where you want.
Configure cert
You may find wget cannot verify any https connection, because there is no CA certs for the OpenSSL you built. You need to run:
New way:
If you machine doesn't have "/usr/local/ssl/" dir, first make it.
ln -s /etc/ssl/cert.pem /usr/local/ssl/cert.pem
Old way:
security find-certificate -a -p /Library/Keychains/System.keychain > cert.pem
security find-certificate -a -p /System/Library/Keychains/SystemRootCertificates.keychain >> cert.pem
Then put cert.pem to: "/usr/local/ssl/cert.pem"
DONE: It should be all right now.
Since Windows doesn't have a grep
command, this worked for me in PowerShell:
git log --find-renames --diff-filter=D --summary | Select-String -Pattern "delete mode" | sort -u > deletions.txt
You can use triple quotes (single ' or double "):
a = """
text
text
text
"""
print(a)
Limit is very simple, example limit first 50 rows
val df_subset = data.limit(50)
final Handler handler = new Handler() {
@Override
public void handleMessage(final Message msgs) {
//write your code hear which give error
}
}
new Thread(new Runnable() {
@Override
public void run() {
handler.sendEmptyMessage(1);
//this will call handleMessage function and hendal all error
}
}).start();
Note that ord()
doesn't give you the ASCII value per se; it gives you the numeric value of the character in whatever encoding it's in. Therefore the result of ord('ä')
can be 228 if you're using Latin-1, or it can raise a TypeError
if you're using UTF-8. It can even return the Unicode codepoint instead if you pass it a unicode:
>>> ord(u'?')
12354
If you are using vscodevim extension, then you can harness the power of vim keyboard moves. When you are on a line that you would like to bookmark, in normal mode, you can type:
m {a-z A-Z}
for a possible 52 bookmarks within a file. Small letter alphabets are for bookmarks within a single file. Capital letters preserve their marks across files.
To navigate to a bookmark from within any file, you then need to hit ' {a-z A-Z}
. I don't think these bookmarks stay across different VSCode sessions though.
More vim shortcuts here.
Came here with a similar question, the above didn't work for me in: "rxjs": "^6.0.0"
, in order to generate an observable that emits no data I needed to do:
import {Observable,empty} from 'rxjs';
class ActivatedRouteStub {
params: Observable<any> = empty();
}
A bit late to the party, but I had to solve this for myself recently, though slightly different, it might still help someone with similar circumstances to my own.
I'm using xampp on a laptop to run a purely local website app on windows. (A very specific environment I know). In this instance, I use a html link to a php file and run:
shell_exec('cd C:\path\to\file');
shell_exec('start .');
This opens a local Windows explorer window.
echo -n "text to insert " ;tac filename.txt| tac > newfilename.txt
The first tac
pipes the file backwards (last line first) so the "text to insert" appears last. The 2nd tac
wraps it once again so the inserted line is at the beginning and the original file is in its original order.
We will consider first List type is String and want to convert it to Integer type of List.
List<String> origList = new ArrayList<>(); // assume populated
Add values in the original List.
origList.add("1");
origList.add("2");
origList.add("3");
origList.add("4");
origList.add("8");
Create target List of Integer Type
List<Integer> targetLambdaList = new ArrayList<Integer>();
targetLambdaList=origList.stream().map(Integer::valueOf).collect(Collectors.toList());
Print List values using forEach:
targetLambdaList.forEach(System.out::println);
I am in the same boat as the OP.
Using a Windows command prompt, from directory:
C:\Python34\Scripts>
pip install wheel
seemed to work.
Changing directory to where the whl was located, it just tells me 'pip is not recognized'. Going back to C:\Python34\Scripts>
, then using the full command above to provide the 'where/its/downloaded' location, it says Requirement 'scikit_image-...-win32.whl' looks like a filename, but the filename does not exist
.
So I dropped a copy of the .whl in Python34/Scripts, ran the exact same command over again (with the --find-links=
still going to the other folder), and this time it worked.
I have used the following query. It has worked great for me in the past.
select date(now()) - interval day(now()) day + interval 1 day
I think it is better to copy files from your local computer, because if files number or file size is very big, copying process could be interrupted if your current ssh session would be lost (broken pipe or whatever).
If you have configured ssh key to connect to your remote server, you could use the following command:
rsync -avP -e "ssh -i /home/local_user/ssh/key_to_access_remote_server.pem" remote_user@remote_host.ip:/home/remote_user/file.gz /home/local_user/Downloads/
Where v
option is --verbose
, a
option is --archive
- archive mode, P
option same as --partial
- keep partially transferred files, e
option is --rsh=COMMAND
- specifying the remote shell to use.
Instead of using
int * p;
p = {1,2,3};
we can use
int * p;
p =(int[3]){1,2,3};
You can use the LIKE operator to compare the content of a T-SQL string, e.g.
SELECT * FROM [table] WHERE [field] LIKE '%stringtosearchfor%'.
The percent character '%' is a wild card- in this case it says return any records where [field] at least contains the value "stringtosearchfor".
Change
Range(DataImportColumn & DataImportRow).Offset(0, 2).Value
to
Cells(DataImportRow,DataImportColumn).Value
When you just have the row and the column then you can use the cells()
object. The syntax is Cells(Row,Column)
Also one more tip. You might want to fully qualify your Cells
object. for example
ThisWorkbook.Sheets("WhatEver").Cells(DataImportRow,DataImportColumn).Value
Or you could just do it that way:
public String controllerMethod(@RequestParam(value="myParam[]") String[] myParams){
....
}
That works for example for forms like this:
<input type="checkbox" name="myParam[]" value="myVal1" />
<input type="checkbox" name="myParam[]" value="myVal2" />
This is the simplest solution :)
//slightly improved code without using collection framework
package com.test;
public class TestClass {
private static Link last;
private static Link first;
public static void main(String[] args) {
//Inserting
for(int i=0;i<5;i++){
Link.insert(i+5);
}
Link.printList();
//Deleting
Link.deletefromFirst();
Link.printList();
}
protected static class Link {
private int data;
private Link nextlink;
public Link(int d1) {
this.data = d1;
}
public static void insert(int d1) {
Link a = new Link(d1);
a.nextlink = null;
if (first != null) {
last.nextlink = a;
last = a;
} else {
first = a;
last = a;
}
System.out.println("Inserted -:"+d1);
}
public static void deletefromFirst() {
if(null!=first)
{
System.out.println("Deleting -:"+first.data);
first = first.nextlink;
}
else{
System.out.println("No elements in Linked List");
}
}
public static void printList() {
System.out.println("Elements in the list are");
System.out.println("-------------------------");
Link temp = first;
while (temp != null) {
System.out.println(temp.data);
temp = temp.nextlink;
}
}
}
}