Building on the previous answers, you can leverage the fact that True
is -1 and False
is 0 and shorten your code like this:
Sub Button167_Click()
Range("Y12").Value = _
Abs(Worksheets(1).Shapes("Check Box 1").OLEFormat.Object.Value > 0)
End Sub
If the checkbox is checked, .Value
= 1.
Worksheets(1).Shapes("Check Box 1").OLEFormat.Object.Value > 0
returns True
.
Applying the Abs
function converts True
to 1
.
If the checkbox is unchecked, .Value
= -4146.
Worksheets(1).Shapes("Check Box 1").OLEFormat.Object.Value > 0
returns False
.
Applying the Abs
function converts False
to 0
.
Try this select to find the problematic synonyms, it lists all synonyms that are pointing to an object that does not exist (tables,views,sequences,packages, procedures, functions)
SELECT *
FROM dba_synonyms
WHERE table_owner = 'USER'
AND (
NOT EXISTS (
SELECT *
FROM dba_tables
WHERE dba_synonyms.table_name = dba_tables.TABLE_NAME
)
AND NOT EXISTS (
SELECT *
FROM dba_views
WHERE dba_synonyms.table_name = dba_views.VIEW_NAME
)
AND NOT EXISTS (
SELECT *
FROM dba_sequences
WHERE dba_synonyms.table_name = dba_sequences.sequence_NAME
)
AND NOT EXISTS (
SELECT *
FROM dba_dependencies
WHERE type IN (
'PACKAGE'
,'PROCEDURE'
,'FUNCTION'
)
AND dba_synonyms.table_name = dba_dependencies.NAME
)
)
Resurrecting a very old thread yet again, since none of the answers here worked very well for me.
I found a simple way that seems pretty robust and simple. It worked for me. The idea:
Example:
static class Program
{
[DllImport( "kernel32.dll", SetLastError = true )]
static extern bool AllocConsole();
[DllImport( "kernel32", SetLastError = true )]
static extern bool AttachConsole( int dwProcessId );
static void Main(string[] args)
{
bool consoleMode = Boolean.Parse(args[0]);
if (consoleMode)
{
if (!AttachConsole(-1))
AllocConsole();
Console.WriteLine("consolemode started");
// ...
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
A word of caution : it seems that if you try writing to the console prior to attaching or allocing a console, this approach doesn't work. My guess is the first time you call Console.Write/WriteLine, if there isn't already a console then Windows automatically creates a hidden console somewhere for you. (So perhaps Anthony's ShowConsoleWindow answer is better after you've already written to the console, and my answer is better if you've not yet written to the console). The important thing to note is that this doesn't work:
static void Main(string[] args)
{
Console.WriteLine("Welcome to the program"); //< this ruins everything
bool consoleMode = Boolean.Parse(args[0]);
if (consoleMode)
{
if (!AttachConsole(-1))
AllocConsole();
Console.WriteLine("consolemode started"); //< this doesn't get displayed on the parent console
// ...
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
Click here this is a good tutorial for both window/ubuntu.
apktool1.5.1.jar download from here.
apktool-install-linux-r05-ibot download from here.
dex2jar-0.0.9.15.zip download from here.
jd-gui-0.3.3.linux.i686.tar.gz (java de-complier) download from here.
framework-res.apk ( Located at your android device /system/framework/)
Procedure:
it will become .zip.
Then extract .zip.
Unzip downloaded dex2jar-0.0.9.15.zip file , copy the contents and paste it to unzip folder.
Open terminal and change directory to unzip “dex2jar-0.0.9.15 “
– cd – sh dex2jar.sh classes.dex (result of this command “classes.dex.dex2jar.jar” will be in your extracted folder itself).
Now, create new folder and copy “classes.dex.dex2jar.jar” into it.
Unzip “jd-gui-0.3.3.linux.i686.zip“ and open up the “Java Decompiler” in full screen mode.
Click on open file and select “classes.dex.dex2jar.jar” into the window.
“Java Decompiler” and go to file > save and save the source in a .zip file.
Create “source_code” folder.
Extract the saved .zip and copy the contents to “source_code” folder.
This will be where we keep your source code.
Extract apktool1.5.1.tar.bz2 , you get apktool.jar
Now, unzip “apktool-install-linux-r05-ibot.zip”
Copy “framework-res.apk” , “.apk” and apktool.jar
Paste it to the unzip “apktool-install-linux-r05-ibot” folder (line no 13).
Then open terminal and type:
– cd
– chown -R : ‘apktool.jar’
– chown -R : ‘apktool’
– chown -R : ‘aapt’
– sudo chmod +x ‘apktool.jar’
– sudo chmod +x ‘apktool’
– sudo chmod +x ‘aapt’
– sudo mv apktool.jar /usr/local/bin
– sudo mv apktool /usr/local/bin
– sudo mv aapt /usr/local/bin
– apktool if framework-res.apk – apktool d .apk
Boxing and Unboxing are specifically used to treat value-type objects as reference-type; moving their actual value to the managed heap and accessing their value by reference.
Without boxing and unboxing you could never pass value-types by reference; and that means you could not pass value-types as instances of Object.
On some system may be useful to use this constant because if, for example, you are sending an email, you can use PHP_EOL to have a cross-system script working on more systems... but even if it's useful sometime you can find this constant undefined, modern hosting with latest php engine do not have this problem but I think that a good thing is write a bit code that saves this situation:
<?php
if (!defined('PHP_EOL')) {
if (strtoupper(substr(PHP_OS,0,3) == 'WIN')) {
define('PHP_EOL',"\r\n");
} elseif (strtoupper(substr(PHP_OS,0,3) == 'MAC')) {
define('PHP_EOL',"\r");
} elseif (strtoupper(substr(PHP_OS,0,3) == 'DAR')) {
define('PHP_EOL',"\n");
} else {
define('PHP_EOL',"\n");
}
}
?>
So you can use PHP_EOL without problems... obvious that PHP_EOL should be used on script that should work on more systems at once otherwise you can use \n or \r or \r\n...
Note: PHP_EOL can be
1) on Unix LN == \n
2) on Mac CR == \r
3) on Windows CR+LN == \r\n
Hope this answer help.
Extending the great answer from Dave. You can create a simple HtmlHelper.
public static IHtmlString RenderAsJson(this HtmlHelper helper, object model)
{
return helper.Raw(Json.Encode(model));
}
And in your view:
@Html.RenderAsJson(Model)
This way you can centralize the logic for creating the JSON if you, for some reason, would like to change the logic later.
You may have moved on by now, but... as far as I know there's no way to delete a history entry (or state).
One option I've been looking into is to handle the history yourself in JavaScript and use the window.history
object as a carrier of sorts.
Basically, when the page first loads you create your custom history object (we'll go with an array here, but use whatever makes sense for your situation), then do your initial pushState
. I would pass your custom history object as the state object, as it may come in handy if you also need to handle users navigating away from your app and coming back later.
var myHistory = [];
function pageLoad() {
window.history.pushState(myHistory, "<name>", "<url>");
//Load page data.
}
Now when you navigate, you add to your own history object (or don't - the history is now in your hands!) and use replaceState
to keep the browser out of the loop.
function nav_to_details() {
myHistory.push("page_im_on_now");
window.history.replaceState(myHistory, "<name>", "<url>");
//Load page data.
}
When the user navigates backwards, they'll be hitting your "base" state (your state object will be null) and you can handle the navigation according to your custom history object. Afterward, you do another pushState.
function on_popState() {
// Note that some browsers fire popState on initial load,
// so you should check your state object and handle things accordingly.
// (I did not do that in these examples!)
if (myHistory.length > 0) {
var pg = myHistory.pop();
window.history.pushState(myHistory, "<name>", "<url>");
//Load page data for "pg".
} else {
//No "history" - let them exit or keep them in the app.
}
}
The user will never be able to navigate forward using their browser buttons because they are always on the newest page.
From the browser's perspective, every time they go "back", they've immediately pushed forward again.
From the user's perspective, they're able to navigate backwards through the pages but not forward (basically simulating the smartphone "page stack" model).
From the developer's perspective, you now have a high level of control over how the user navigates through your application, while still allowing them to use the familiar navigation buttons on their browser. You can add/remove items from anywhere in the history chain as you please. If you use objects in your history array, you can track extra information about the pages as well (like field contents and whatnot).
If you need to handle user-initiated navigation (like the user changing the URL in a hash-based navigation scheme), then you might use a slightly different approach like...
var myHistory = [];
function pageLoad() {
// When the user first hits your page...
// Check the state to see what's going on.
if (window.history.state === null) {
// If the state is null, this is a NEW navigation,
// the user has navigated to your page directly (not using back/forward).
// First we establish a "back" page to catch backward navigation.
window.history.replaceState(
{ isBackPage: true },
"<back>",
"<back>"
);
// Then push an "app" page on top of that - this is where the user will sit.
// (As browsers vary, it might be safer to put this in a short setTimeout).
window.history.pushState(
{ isBackPage: false },
"<name>",
"<url>"
);
// We also need to start our history tracking.
myHistory.push("<whatever>");
return;
}
// If the state is NOT null, then the user is returning to our app via history navigation.
// (Load up the page based on the last entry of myHistory here)
if (window.history.state.isBackPage) {
// If the user came into our app via the back page,
// you can either push them forward one more step or just use pushState as above.
window.history.go(1);
// or window.history.pushState({ isBackPage: false }, "<name>", "<url>");
}
setTimeout(function() {
// Add our popstate event listener - doing it here should remove
// the issue of dealing with the browser firing it on initial page load.
window.addEventListener("popstate", on_popstate);
}, 100);
}
function on_popstate(e) {
if (e.state === null) {
// If there's no state at all, then the user must have navigated to a new hash.
// <Look at what they've done, maybe by reading the hash from the URL>
// <Change/load the new page and push it onto the myHistory stack>
// <Alternatively, ignore their navigation attempt by NOT loading anything new or adding to myHistory>
// Undo what they've done (as far as navigation) by kicking them backwards to the "app" page
window.history.go(-1);
// Optionally, you can throw another replaceState in here, e.g. if you want to change the visible URL.
// This would also prevent them from using the "forward" button to return to the new hash.
window.history.replaceState(
{ isBackPage: false },
"<new name>",
"<new url>"
);
} else {
if (e.state.isBackPage) {
// If there is state and it's the 'back' page...
if (myHistory.length > 0) {
// Pull/load the page from our custom history...
var pg = myHistory.pop();
// <load/render/whatever>
// And push them to our "app" page again
window.history.pushState(
{ isBackPage: false },
"<name>",
"<url>"
);
} else {
// No more history - let them exit or keep them in the app.
}
}
// Implied 'else' here - if there is state and it's NOT the 'back' page
// then we can ignore it since we're already on the page we want.
// (This is the case when we push the user back with window.history.go(-1) above)
}
}
When the work I'm doing doesn't warrant using a library, I use these two functions:
function addClass( classname, element ) {
var cn = element.className;
//test for existance
if( cn.indexOf( classname ) != -1 ) {
return;
}
//add a space if the element already has class
if( cn != '' ) {
classname = ' '+classname;
}
element.className = cn+classname;
}
function removeClass( classname, element ) {
var cn = element.className;
var rxp = new RegExp( "\\s?\\b"+classname+"\\b", "g" );
cn = cn.replace( rxp, '' );
element.className = cn;
}
#!/usr/bin/env bash
echo name of script is $0
echo first argument is $1
echo second argument is $2
echo seventeenth argument is $17
echo number of arguments is $#
Edit: please see my comment on question
Use LIMIT with two parameters. For example, to return results 11-60 (where result 1 is the first row), use:
SELECT * FROM foo LIMIT 10, 50
For a solution to return all results, see Thomas' answer.
1) C:\Program Files\xampp\php\php.ini
2) Uncomment the following line on your php.ini file by removing the semicolon.
;extension=php_curl.dll
3) Restart your apache server.
The regex [^ab] will match for example 'ab ab ab ab' but not 'ab', because it will match on the string ' a' or 'b '.
What language/scenario do you have? Can you subtract results from the original set, and just match ab?
If you are using GNU grep, and are parsing input, use the '-v' flag to invert your results, returning all non-matches. Other regex tools also have a 'return nonmatch' function, too.
If I understand correctly, you want everything except for those items which contain 'ab' anywhere.
I picked node-sass implementer for libsass because it is based on node.js.
$ npm install -g node-sass
installs node-sass globally -g
.This will hopefully install all you need, if not read libsass at the bottom.
General format:
$ node-sass [options] <input.scss> [output.css]
$ cat <input.scss> | node-sass > output.css
Examples:
$ node-sass my-styles.scss my-styles.css
compiles a single file manually.$ node-sass my-sass-folder/ -o my-css-folder/
compiles all the files in a folder manually.$ node-sass -w sass/ -o css/
compiles all the files in a folder automatically whenever the source file(s) are modified. -w
adds a watch for changes to the file(s).More usefull options like 'compression' @ here. Command line is good for a quick solution, however, you can use task runners like Grunt.js or Gulp.js to automate the build process.
You can also add the above examples to npm scripts. To properly use npm scripts as an alternative to gulp read this comprehensive article @ css-tricks.com especially read about grouping tasks.
package.json
file in your project directory running $ npm init
will create one. Use it with -y
to skip the questions. "sass": "node-sass -w sass/ -o css/"
to scripts
in package.json
file. It should look something like this:"scripts": {
"test" : "bla bla bla",
"sass": "node-sass -w sass/ -o css/"
}
$ npm run sass
will compile your files.$ npm install -g gulp
installs Gulp globally.package.json
file in your project directory running $ npm init
will create one. Use it with -y
to skip the questions.$ npm install --save-dev gulp
installs Gulp locally. --save-dev
adds gulp
to devDependencies
in package.json
.$ npm install gulp-sass --save-dev
installs gulp-sass locally.gulpfile.js
file in your project root folder with this content:'use strict';
var gulp = require('gulp');
A basic example to transpile
Add this code to your gulpfile.js:
var gulp = require('gulp');
var sass = require('gulp-sass');
gulp.task('sass', function () {
gulp.src('./sass/**/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./css'));
});
$ gulp sass
runs the above task which compiles .scss file(s) in the sass
folder and generates .css file(s) in the css
folder.
To make life easier, let's add a watch so we don't have to compile it manually. Add this code to your gulpfile.js
:
gulp.task('sass:watch', function () {
gulp.watch('./sass/**/*.scss', ['sass']);
});
All is set now! Just run the watch task:
$ gulp sass:watch
As the name of node-sass implies, you can write your own node.js scripts for transpiling. If you are curious, check out node-sass project page.
Libsass is a library that needs to be built by an implementer such as sassC or in our case node-sass. Node-sass contains a built version of libsass which it uses by default. If the build file doesn't work on your machine, it tries to build libsass for your machine. This process requires Python 2.7.x (3.x doesn't work as of today). In addition:
LibSass requires GCC 4.6+ or Clang/LLVM. If your OS is older, this version may not compile. On Windows, you need MinGW with GCC 4.6+ or VS 2013 Update 4+. It is also possible to build LibSass with Clang/LLVM on Windows.
Make sure you log into psql as the owner of the tables.
to find out who own the tables use \dt
psql -h CONNECTION_STRING DBNAME -U OWNER_OF_THE_TABLES
then you can run the GRANTS
To purge the queue you can delete the topic:
bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic test
then re-create it:
bin/kafka-topics.sh --create --zookeeper localhost:2181 \
--replication-factor 1 --partitions 1 --topic test
It seems that till now nobody mention another popular library qs. You can add it
$ yarn add qs
And then use it like that
import qs from 'qs'
const array = { a: { b: 'c' } }
const stringified = qs.stringify(array, { encode: false })
console.log(stringified) //-- outputs a[b]=c
Before everyone jumps on the 'You can't delete rows in an Enumeration' bandwagon, you need to first realize that DataTables are transactional, and do not technically purge changes until you call AcceptChanges()
If you are seeing this exception while calling Delete, you are already in a pending-changes data state. For instance, if you have just loaded from the database, calling Delete would throw an exception if you were inside a foreach loop.
BUT! BUT!
If you load rows from the database and call the function 'AcceptChanges()' you commit all of those pending changes to the DataTable. Now you can iterate through the list of rows calling Delete() without a care in the world, because it simply ear-marks the row for Deletion, but is not committed until you again call AcceptChanges()
I realize this response is a bit dated, but I had to deal with a similar issue recently and hopefully this saves some pain for a future developer working on 10-year-old code :)
P.s. Here is a simple code example added by Jeff:
C#
YourDataTable.AcceptChanges();
foreach (DataRow row in YourDataTable.Rows) {
// If this row is offensive then
row.Delete();
}
YourDataTable.AcceptChanges();
VB.Net
ds.Tables(0).AcceptChanges()
For Each row In ds.Tables(0).Rows
ds.Tables(0).Rows(counter).Delete()
counter += 1
Next
ds.Tables(0).AcceptChanges()
According to the Angular team and this Github issue:
we now have $viewContentLoaded and $includeContentLoaded events that are emitted in ng-view and ng-include respectively. I think this is as close as one can get to knowing when we are done with the compilation.
Based on this, it seems this is currently not possible to do in a reliable way, otherwise Angular would have provided the event out of the box.
Bootstrapping the app implies running the digest cycle on the root scope, and there is also not a digest cycle finished event.
According to the Angular 2 design docs:
Because of multiple digests, it is impossible to determine and notify the component that the model is stable. This is because notification can further change data, which can restart the binding process.
According to this, the fact that this is not possible is one the reasons why the decision was taken to go for a rewrite in Angular 2.
I found this blog post to be very helpful (I am not the author). Summarizing (please read, though):
...delimited identifiers are case sensitive ("table_name" != "Table_Name"), while non quoted identifiers are not, and are transformed to upper case (table_name => TABLE_NAME).
He found DB2, Oracle and Interbase/Firebird are 100% compliant:
PostgreSQL ... lowercases every unquoted identifier, instead of uppercasing it. MySQL ... file system dependent. SQLite and SQL Server ... case of the table and field names are preserved on creation, but they are completely ignored afterwards.
Method proposed @Lelio Faieta is working for me, but because i use bootstrap theme, it remove all bootstrap settings for select2. So I used following code:
$("#remote option").remove();
This way can help you
SELECT TOP 3
1 AS First,
2 AS Second,
3 AS Third
FROM Any_Table_In_Your_DataBase
Any_Table_In_Your_DataBase:
any table which contains more than 3 records, or use any system table. Here we have no concern with data of that table.
You can bring variations in result set by concatenating a column with First, Second and Third columns from Any_Table_In_Your_DataBase
table.
I have reformatted your code.
The error was situated in this line :
printf("%d", (**c));
To fix it, change to :
printf("%d", (*c));
The * retrieves the value from an address. The ** retrieves the value (an address in this case) of an other value from an address.
In addition, the () was optional.
#include <stdio.h>
int main(void)
{
int b = 10;
int *a = NULL;
int *c = NULL;
a = &b;
c = &a;
printf("%d", *c);
return 0;
}
EDIT :
The line :
c = &a;
must be replaced by :
c = a;
It means that the value of the pointer 'c' equals the value of the pointer 'a'. So, 'c' and 'a' points to the same address ('b'). The output is :
10
EDIT 2:
If you want to use a double * :
#include <stdio.h>
int main(void)
{
int b = 10;
int *a = NULL;
int **c = NULL;
a = &b;
c = &a;
printf("%d", **c);
return 0;
}
Output:
10
In my case, the warning occurred because of just the regular type of boolean indexing -- because the series had only np.nan. Demonstration (pandas 1.0.3):
>>> import pandas as pd
>>> import numpy as np
>>> pd.Series([np.nan, 'Hi']) == 'Hi'
0 False
1 True
>>> pd.Series([np.nan, np.nan]) == 'Hi'
~/anaconda3/envs/ms3/lib/python3.7/site-packages/pandas/core/ops/array_ops.py:255: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
res_values = method(rvalues)
0 False
1 False
I think with pandas 1.0 they really want you to use the new 'string'
datatype which allows for pd.NA
values:
>>> pd.Series([pd.NA, pd.NA]) == 'Hi'
0 False
1 False
>>> pd.Series([np.nan, np.nan], dtype='string') == 'Hi'
0 <NA>
1 <NA>
>>> (pd.Series([np.nan, np.nan], dtype='string') == 'Hi').fillna(False)
0 False
1 False
Don't love at which point they tinkered with every-day functionality such as boolean indexing.
<div style="clear:both;"></div>
- may do the trick in some cases; not a "colspan" but may help achieve what you are looking for...
<div id="table">
<div class="table_row">
<div class="table_cell1"></div>
<div class="table_cell2"></div>
<div class="table_cell3"></div>
</div>
<div class="table_row">
<div class="table_cell1"></div>
<div class="table_cell2"></div>
<div class="table_cell3"></div>
</div>
<!-- clear:both will clear any float direction to default, and
prevent the previously defined floats from affecting other elements -->
<div style="clear:both;"></div>
<div class="table_row">
<!-- the float is cleared, you could have 4 divs (columns) or
just one with 100% width -->
<div class="table_cell123"></div>
</div>
</div>
Use ThisWorkbook
which will refer to the original workbook which holds the code.
Alternatively at code start
Dim Wb As Workbook
Set Wb = ActiveWorkbook
sample code that activates all open books before returning to ThisWorkbook
Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
Wb2.Activate
Next
Wb.Activate
End Sub
MySQL is different from most DBMSs use of +
or ||
for concatenation. It uses the CONCAT
function:
SELECT CONCAT(first_name, " ", last_name) AS Name FROM test.student
As @eggyal pointed out in comments, you can enable string concatenation with the ||
operator in MySQL by setting the PIPES_AS_CONCAT
SQL mode.
In my case Mac OS High Sierra 10.13.6
brew -v
OutPut-
Homebrew 2.2.2
Homebrew/homebrew-core (git revision 71aa; last commit 2020-01-07)
Homebrew/homebrew-cask (git revision 84f00; last commit 2020-01-07)
modulus is remainders system.
So 7 % 5 = 2.
5 % 7 = 5
3 % 7 = 3
2 % 7 = 2
1 % 7 = 1
When used inside a function to determine the array index. Is it safe programming ? That is a different question. I guess.
I am just wondering why to use some libraries for JWT token decoding and verification at all.
Encoded JWT token can be created using following pseudocode
var headers = base64URLencode(myHeaders);
var claims = base64URLencode(myClaims);
var payload = header + "." + claims;
var signature = base64URLencode(HMACSHA256(payload, secret));
var encodedJWT = payload + "." + signature;
It is very easy to do without any specific library. Using following code:
using System;
using System.Text;
using System.Security.Cryptography;
public class Program
{
// More info: https://stormpath.com/blog/jwt-the-right-way/
public static void Main()
{
var header = "{\"typ\":\"JWT\",\"alg\":\"HS256\"}";
var claims = "{\"sub\":\"1047986\",\"email\":\"[email protected]\",\"given_name\":\"John\",\"family_name\":\"Doe\",\"primarysid\":\"b521a2af99bfdc65e04010ac1d046ff5\",\"iss\":\"http://example.com\",\"aud\":\"myapp\",\"exp\":1460555281,\"nbf\":1457963281}";
var b64header = Convert.ToBase64String(Encoding.UTF8.GetBytes(header))
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
var b64claims = Convert.ToBase64String(Encoding.UTF8.GetBytes(claims))
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
var payload = b64header + "." + b64claims;
Console.WriteLine("JWT without sig: " + payload);
byte[] key = Convert.FromBase64String("mPorwQB8kMDNQeeYO35KOrMMFn6rFVmbIohBphJPnp4=");
byte[] message = Encoding.UTF8.GetBytes(payload);
string sig = Convert.ToBase64String(HashHMAC(key, message))
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
Console.WriteLine("JWT with signature: " + payload + "." + sig);
}
private static byte[] HashHMAC(byte[] key, byte[] message)
{
var hash = new HMACSHA256(key);
return hash.ComputeHash(message);
}
}
The token decoding is reversed version of the code above.To verify the signature you will need to the same and compare signature part with calculated signature.
UPDATE: For those how are struggling how to do base64 urlsafe encoding/decoding please see another SO question, and also wiki and RFCs
The traceback module and sys.exc_info are overkill for tracking down the source of an exception. That's all in the default traceback. So instead of calling exit(1) just re-raise:
try:
assert "birthday cake" == "ice cream cake", "Should've asked for pie"
except AssertionError:
print 'Houston, we have a problem.'
raise
Which gives the following output that includes the offending statement and line number:
Houston, we have a problem.
Traceback (most recent call last):
File "/tmp/poop.py", line 2, in <module>
assert "birthday cake" == "ice cream cake", "Should've asked for pie"
AssertionError: Should've asked for pie
Similarly the logging module makes it easy to log a traceback for any exception (including those which are caught and never re-raised):
import logging
try:
assert False == True
except AssertionError:
logging.error("Nothing is real but I can't quit...", exc_info=True)
I`d like to add to the already good answers:
The symbols '+', '*' and '-' are sometimes used as shorthand in some older textbooks for OR,? and AND,? and NOT,¬ logical operators in Bool`s algebra. In C/C++ of course we use "and","&&" and "or","||" and "not","!".
Watch out: "true + true" evaluates to 2 in C/C++ via internal representation of true and false as 1 and 0, and the implicit cast to int!
int main ()
{
std::cout << "true - true = " << true - true << std::endl;
// This can be used as signum function:
// "(x > 0) - (x < 0)" evaluates to +1 or -1 for numbers.
std::cout << "true - false = " << true - false << std::endl;
std::cout << "false - true = " << false - true << std::endl;
std::cout << "false - false = " << false - false << std::endl << std::endl;
std::cout << "true + true = " << true + true << std::endl;
std::cout << "true + false = " << true + false << std::endl;
std::cout << "false + true = " << false + true << std::endl;
std::cout << "false + false = " << false + false << std::endl << std::endl;
std::cout << "true * true = " << true * true << std::endl;
std::cout << "true * false = " << true * false << std::endl;
std::cout << "false * true = " << false * true << std::endl;
std::cout << "false * false = " << false * false << std::endl << std::endl;
std::cout << "true / true = " << true / true << std::endl;
// std::cout << true / false << std::endl; ///-Wdiv-by-zero
std::cout << "false / true = " << false / true << std::endl << std::endl;
// std::cout << false / false << std::endl << std::endl; ///-Wdiv-by-zero
std::cout << "(true || true) = " << (true || true) << std::endl;
std::cout << "(true || false) = " << (true || false) << std::endl;
std::cout << "(false || true) = " << (false || true) << std::endl;
std::cout << "(false || false) = " << (false || false) << std::endl << std::endl;
std::cout << "(true && true) = " << (true && true) << std::endl;
std::cout << "(true && false) = " << (true && false) << std::endl;
std::cout << "(false && true) = " << (false && true) << std::endl;
std::cout << "(false && false) = " << (false && false) << std::endl << std::endl;
}
yields :
true - true = 0
true - false = 1
false - true = -1
false - false = 0
true + true = 2
true + false = 1
false + true = 1
false + false = 0
true * true = 1
true * false = 0
false * true = 0
false * false = 0
true / true = 1
false / true = 0
(true || true) = 1
(true || false) = 1
(false || true) = 1
(false || false) = 0
(true && true) = 1
(true && false) = 0
(false && true) = 0
(false && false) = 0
It'll vary depending on resources, but you could run the script bellow and see for yourself ;)
<?php
$tests = 100000;
for ($i = 0; $i < $tests; $i++)
{
$string = md5(rand());
$position = rand(0, 31);
$start1 = microtime(true);
$char1 = $string[$position];
$end1 = microtime(true);
$time1[$i] = $end1 - $start1;
$start2 = microtime(true);
$char2 = substr($string, $position, 1);
$end2 = microtime(true);
$time2[$i] = $end2 - $start2;
$start3 = microtime(true);
$char3 = $string{$position};
$end3 = microtime(true);
$time3[$i] = $end3 - $start3;
}
$avg1 = array_sum($time1) / $tests;
echo 'the average float microtime using "array[]" is '. $avg1 . PHP_EOL;
$avg2 = array_sum($time2) / $tests;
echo 'the average float microtime using "substr()" is '. $avg2 . PHP_EOL;
$avg3 = array_sum($time3) / $tests;
echo 'the average float microtime using "array{}" is '. $avg3 . PHP_EOL;
?>
Some reference numbers (on an old CoreDuo machine)
$ php 1.php
the average float microtime using "array[]" is 1.914701461792E-6
the average float microtime using "substr()" is 2.2536706924438E-6
the average float microtime using "array{}" is 1.821768283844E-6
$ php 1.php
the average float microtime using "array[]" is 1.7251944541931E-6
the average float microtime using "substr()" is 2.0931363105774E-6
the average float microtime using "array{}" is 1.7225742340088E-6
$ php 1.php
the average float microtime using "array[]" is 1.7293763160706E-6
the average float microtime using "substr()" is 2.1037721633911E-6
the average float microtime using "array{}" is 1.7249774932861E-6
It seems that using the []
or {}
operators is more or less the same.
Unless you're using spaces in there, you should be able to use | wc -w
on the first line.
wc
is "Word Count", which simply counts the words in the input file. If you send only one line, it'll tell you the amount of columns.
I don't think you can give a path to curl, but you can CD to the location, download and CD back.
cd target/path && { curl -O URL ; cd -; }
Or using subshell.
(cd target/path && curl -O URL)
Both ways will only download if path exists. -O
keeps remote file name. After download it will return to original location.
If you need to set filename explicitly, you can use small -o
option:
curl -o target/path/filename URL
You can also do something:
SELECT CAST(CAST(34512367.392 AS decimal(30,9)) AS NVARCHAR(100))
Output:
34512367.392000000
Download and run the latest MSI. The MSI will update your installed node and npm.
If you're talking MS SQL, here's the most efficient way. This retrieves the current identity seed from a table based on whatever column is the identity.
select IDENT_CURRENT('TableName') as LastIdentity
Using MAX(id)
is more generic, but for example I have an table with 400 million rows that takes 2 minutes to get the MAX(id)
. IDENT_CURRENT
is nearly instantaneous...
You can simply use the toCharArray()
to convert a string to char array:
Scanner s=new Scanner(System.in);
System.out.print("Enter some String:");
String str=s.nextLine();
char a[]=str.toCharArray();
Using iconv looks like best solution but i my case I have Notice form this function: "Detected an illegal character in input string in" (without igonore). I use 2 functions to manipulate ASCII strings convert it to array of ASCII code and then serialize:
public static function ToAscii($string) {
$strlen = strlen($string);
$charCode = array();
for ($i = 0; $i < $strlen; $i++) {
$charCode[] = ord(substr($string, $i, 1));
}
$result = json_encode($charCode);
return $result;
}
public static function fromAscii($string) {
$charCode = json_decode($string);
$result = '';
foreach ($charCode as $code) {
$result .= chr($code);
};
return $result;
}
I’ve run into this problem too. I'm using Nginx with HHVM, below solution fixed my issue:
sudo semanage fcontext -a -t httpd_sys_rw_content_t "/etc/nginx/fastcgi_temp(/.*)?"
sudo restorecon -R -v /etc/nginx/fastcgi_temp
I tried a lot ways and it's not working tho, not sure is it because i'm using shared transition from fragment to activity containing the edit text.
Btw my edittext is also wrapped in LinearLayout.
I added a slight delay to request focus and below code worked for me: (Kotlin)
et_search.postDelayed({
editText.requestFocus()
showKeyboard()
},400) //only 400 is working fine, even 300 / 350, the cursor is not showing
showKeyboard()
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
As wordpress api has changed, you can´t use get_posts with param 'post_name'. I´ve modified Maartens function a bit:
function get_post_id_by_slug( $slug, $post_type = "post" ) {
$query = new WP_Query(
array(
'name' => $slug,
'post_type' => $post_type,
'numberposts' => 1,
'fields' => 'ids',
) );
$posts = $query->get_posts();
return array_shift( $posts );
}
The following solution is not a single statement for altering multiple columns, but yes, it makes life simple:
Generate a table's CREATE
script.
Replace CREATE TABLE
with ALTER TABLE [TableName] ALTER COLUMN
for first line
Remove unwanted columns from list.
Change the columns data types as you want.
Perform a Find and Replace… as follows:
NULL
,NULL; ALTER TABLE [TableName] ALTER COLUMN
Run the script.
Hope it will save lot of time :))
By this code for formating price in product list
echo Mage::helper('core')->currency($_product->getPrice());
If you're just after console logging here's what I'd do:
export default class App extends Component {
componentDidMount() {
console.log('I was triggered during componentDidMount')
}
render() {
console.log('I was triggered during render')
return (
<div> I am the App component </div>
)
}
}
Shouldn't be any need for those packages just to do console logging.
If somebody needs this solution in Swift 5:
private func resizeImage(image: UIImage, newHeight: CGFloat) -> UIImage {
let scale = newHeight / image.size.height
let newWidth = image.size.width * scale
UIGraphicsBeginImageContext(CGSize(width:newWidth, height:newHeight))
image.draw(in:CGRect(x:0, y:0, width:newWidth, height:newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
Ambiguous date formats are interpreted according to the language of the login. This works
set dateformat mdy
select CAST('03/28/2011 18:03:40' AS DATETIME)
This doesn't
set dateformat dmy
select CAST('03/28/2011 18:03:40' AS DATETIME)
If you use parameterised queries with the correct datatype you avoid these issues. You can also use the unambiguous "unseparated" format yyyyMMdd hh:mm:ss
Apart from the previous use cases, you can also use Docker Compose to create directories in case you want to make new dummy folders on docker-compose up
:
volumes:
- .:/ftp/
- /ftp/node_modules
- /ftp/files
The problem happens whenever a process uses port 80.
You can run Netstat which is available in XAMPP Control Panel and check which process uses port 80 in your system.
For me it wasn't IIS, but Skype.
Turn off that process/application and then start the Apache services.
This cannot be done in one statement. You will have to use 2 statements
DELETE FROM TB1 WHERE PersonID = '2';
DELETE FROM TB2 WHERE PersonID = '2';
One way to fix it is by modifying the assembly redirect in the web.config file.
Modify the following:
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
to
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="4.0.0.0" />
</dependentAssembly>
So the oldVersion attribute should change from "...-4.0.0.0" to "...-5.2.3.0".
One way is using a template function in your directive:
...
template: function(tElem, tAttrs){
return '<div ng-include="' + tAttrs.template + '" />';
}
...
Use doubleval()
. But be very careful about using decimals in financial transactions, and validate that user input very carefully.
The tibble
package now has a dedicated function that converts row names to an explicit variable.
library(tibble)
rownames_to_column(mtcars, var="das_Auto") %>% head
Gives:
das_Auto mpg cyl disp hp drat wt qsec vs am gear carb
1 Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
2 Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
3 Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
4 Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
5 Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
6 Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
Looking at Ruby only:
TL;DR
Use none?
passing it a block with ==
for the comparison:
[1, 2].include?(1)
#=> true
[1, 2].none? { |n| 1 == n }
#=> false
Array#include?
accepts one argument and uses ==
to check against each element in the array:
player = [1, 2, 3]
player.include?(1)
#=> true
Enumerable#none?
can also accept one argument in which case it uses ===
for the comparison. To get the opposing behaviour to include?
we omit the parameter and pass it a block using ==
for the comparison.
player.none? { |n| 7 == n }
#=> true
!player.include?(7) #notice the '!'
#=> true
In the above example we can actually use:
player.none?(7)
#=> true
That's because Integer#==
and Integer#===
are equivalent. But consider:
player.include?(Integer)
#=> false
player.none?(Integer)
#=> false
none?
returns false
because Integer === 1 #=> true
. But really a legit notinclude?
method should return true
. So as we did before:
player.none? { |e| Integer == e }
#=> true
Please note that PrimeFaces supports the standard JSF 2.0+ keywords:
@this
Current component.@all
Whole view.@form
Closest ancestor form of current component.@none
No component.and the standard JSF 2.3+ keywords:
@child(n)
nth child.@composite
Closest composite component ancestor.@id(id)
Used to search components by their id ignoring the component tree structure and naming containers.@namingcontainer
Closest ancestor naming container of current component.@parent
Parent of the current component.@previous
Previous sibling.@next
Next sibling.@root
UIViewRoot instance of the view, can be used to start searching from the root instead the current component.But, it also comes with some PrimeFaces specific keywords:
@row(n)
nth row.@widgetVar(name)
Component with given widgetVar.And you can even use something called "PrimeFaces Selectors" which allows you to use jQuery Selector API. For example to process all inputs in a element with the CSS class myClass
:
process="@(.myClass :input)"
See:
phpPgAdmin might work for you, if you're already familiar with phpMyAdmin.
Please note that development of phpPgAdmin has moved to github per this notice but the SourceForge link above is for historical / documentation purposes.
But really there are dozens of tools that can do this.
I think its works for everyone
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Search</title>
</head>
<body>
<form action="" method="post">
<input type="text" placeholder="Search" name="search">
<button type="submit" name="submit">Search</button>
</form>
</body>
</html>
<?php
if (isset($_POST['submit'])) {
$searchValue = $_POST['search'];
$con = new mysqli("localhost", "root", "", "testing");
if ($con->connect_error) {
echo "connection Failed: " . $con->connect_error;
} else {
$sql = "SELECT * FROM customer_info WHERE name OR email LIKE '%$searchValue%'";
$result = $con->query($sql);
while ($row = $result->fetch_assoc()) {
echo $row['name'] . "<br>";
echo $row['email'] . "<br>";
}
}
}
?>
I've had a similar issue, that took a bit to troubleshoot, so I thought to share it:
The namespace that could not be resolved in my case was Company.Project.Common.Models.EF. I had added a file in a new Company.Project.BusinessLogic.Common namespace.
The majority of the files were having a
using Company.Project;
And then referencing the models as Common.Models.EF. All the files that also had a
using Company.Project.BusinessLogic;
Were failing as VS could not determine which namespace to use.
The solution has been to change the second namespace to Company.Project.BusinessLogic.CommonServices
instead of this
UPDATE staff SET salary = 1200 WHERE name = 'Bob';
UPDATE staff SET salary = 1200 WHERE name = 'Jane';
UPDATE staff SET salary = 1200 WHERE name = 'Frank';
UPDATE staff SET salary = 1200 WHERE name = 'Susan';
UPDATE staff SET salary = 1200 WHERE name = 'John';
you can use
UPDATE staff SET salary = 1200 WHERE name IN ('Bob', 'Frank', 'John');
I deleted folders build
inside a project. After cleaned and rebuilt it in Android Studio. Then corrected errors in build.gradle and AndroidManifest.
I have been struggling with how to add query string parameters to my URL. I couldn't make it work until I realized that I needed to add ?
at the end of my URL, otherwise it won't work. This is very important as it will save you hours of debugging, believe me: been there...done that.
Below, is a simple API Endpoint that calls the Open Weather API and passes APPID
, lat
and lon
as query parameters and return weather data as a JSON
object. Hope this helps.
//Load the request module
var request = require('request');
//Load the query String module
var querystring = require('querystring');
// Load OpenWeather Credentials
var OpenWeatherAppId = require('../config/third-party').openWeather;
router.post('/getCurrentWeather', function (req, res) {
var urlOpenWeatherCurrent = 'http://api.openweathermap.org/data/2.5/weather?'
var queryObject = {
APPID: OpenWeatherAppId.appId,
lat: req.body.lat,
lon: req.body.lon
}
console.log(queryObject)
request({
url:urlOpenWeatherCurrent,
qs: queryObject
}, function (error, response, body) {
if (error) {
console.log('error:', error); // Print the error if one occurred
} else if(response && body) {
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
res.json({'body': body}); // Print JSON response.
}
})
})
Or if you want to use the querystring
module, make the following changes
var queryObject = querystring.stringify({
APPID: OpenWeatherAppId.appId,
lat: req.body.lat,
lon: req.body.lon
});
request({
url:urlOpenWeatherCurrent + queryObject
}, function (error, response, body) {...})
Remember there are two independent git repos we are talking about. Your local repo with your code and the remote running somewhere else.
Your are right, when you change a branch, HEAD points to your current branch. All of this is happening on your local git repo. Not the remote repo, which could be owned by another developer, or siting on a sever in your office, or github, or another directory on the filesystem, or etc...
Your computer (local repo) has no business changing the HEAD pointer on the remote git repo. It could be owned by a different developer for example.
One more thing, what your computer calls origin/XXX is your computer's understanding of the state of the remote at the time of the last fetch.
So what would "organically" update origin/HEAD? It would be activity on the remote git repo. Not your local repo.
People have mentioned
git symbolic-ref HEAD refs/head/my_other_branch
Normally, that is used when there is a shared central git repo on a server for use by the development team. It would be a command executed on the remote computer. You would see this as activity on the remote git repo.
I just had this issue and tried setting it to a different port, but the only thing I needed to do was to delete my [app_directory]/tmp/pids/server.pid
and everything was good to go.
time.second helps a lot put that at the top of your python.
BASH solution, if you want to make this a command (e.g. if you need to do this frequently):
addnums () {
local total=0
while read val; do
(( total += val ))
done
echo $total
}
Then usage:
addnums < /tmp/nums
Try setting both min-height
and min-width
, with display:block
:
img {
display:block;
min-height:100%;
min-width:100%;
}
(fiddle)
Provided your image's containing element is position:relative
or position:absolute
, the image will cover the container. However, it will not be centred.
You can easily centre the image if you know whether it will overflow horizontally (set margin-left:-50%
) or vertically (set margin-top:-50%
). It may be possible to use CSS media queries (and some mathematics) to figure that out.
You can use the below mentioned solution
var idleTime;
$(document).ready(function () {
reloadPage();
$('html').bind('mousemove click mouseup mousedown keydown keypress keyup submit change mouseenter scroll resize dblclick', function () {
clearTimeout(idleTime);
reloadPage();
});
});
function reloadPage() {
clearTimeout(idleTime);
idleTime = setTimeout(function () {
location.reload();
}, 3000);
}
On a responsive site for mobiles the whole thing has to be positioned absolute on a relative div. And fixed height. Media Query set for relevance.
@media only screen and (max-width: 480px){_x000D_
.scroll-wrapper{_x000D_
position:absolute;_x000D_
overflow-x:scroll;_x000D_
}
_x000D_
how do I programmatically add an event to the user's calendar?
Which calendar?
Is there a common API they all share?
No, no more than there is a "common API they all share" for Windows calendar apps. There are some common data formats (e.g., iCalendar) and Internet protocols (e.g., CalDAV), but no common API. Some calendar apps don't even offer an API.
If there are specific calendar applications you wish to integrate with, contact their developers and determine if they offer an API. So, for example, the Calendar application from the Android open source project, that Mayra cites, offers no documented and supported APIs. Google has even explicitly told developers to not use the techniques outlined in the tutorial Mayra cites.
Another option is for you to add events to the Internet calendar in question. For example, the best way to add events to the Calendar application from the Android open source project is to add the event to the user's Google Calendar via the appropriate GData APIs.
UPDATE
Android 4.0 (API Level 14) added a CalendarContract
ContentProvider
.
How to post file using an object in memory (like a JSON object):
import axios from 'axios';
import * as FormData from 'form-data'
async function sendData(jsonData){
// const payload = JSON.stringify({ hello: 'world'});
const payload = JSON.stringify(jsonData);
const bufferObject = Buffer.from(payload, 'utf-8');
const file = new FormData();
file.append('upload_file', bufferObject, "b.json");
const response = await axios.post(
lovelyURL,
file,
headers: file.getHeaders()
).toPromise();
console.log(response?.data);
}
Just by consulting the dictionary, you can see that concurrent (from latin) means to run together, converge, agree; ergo there is a need to synchronize because there is competition on the same resources. Parallel (from greek) means to duplicate on the side; ergo to do the same thing at the same time.
What about:
DECLARE @DOB datetime
SET @DOB='19851125'
SELECT Datepart(yy,convert(date,GETDATE())-@DOB)-1900
Wouldn't that avoid all those rounding, truncating and ofsetting issues?
from this tutorial: https://www.tutorialkart.com/opencv/python/opencv-python-get-image-size/
import cv2
# read image
img = cv2.imread('/home/ubuntu/Walnut.jpg', cv2.IMREAD_UNCHANGED)
# get dimensions of image
dimensions = img.shape
# height, width, number of channels in image
height = img.shape[0]
width = img.shape[1]
channels = img.shape[2]
from this other tutorial: https://www.pyimagesearch.com/2018/07/19/opencv-tutorial-a-guide-to-learn-opencv/
image = cv2.imread("jp.png")
(h, w, d) = image.shape
Please double check things before posting answers.
I solved that adding a Web facet.
To call a specific exception such as FileNotFoundException use this format
if (-not (Test-Path $file))
{
throw [System.IO.FileNotFoundException] "$file not found."
}
To throw a general exception use the throw command followed by a string.
throw "Error trying to do a task"
When used inside a catch, you can provide additional information about what triggered the error
Add "-O file.tgz" or "-O file.tar.gz" at the end wget command and extract "file.tgz" or "file.tar.gz"
Here is the sample code for google colab-
!wget -q --trust-server-names https://downloads.apache.org/spark/spark-3.0.0/spark-3.0.0-bin-hadoop2.7.tgz -O file.tgz
print("Download completed successfully !!!")
!tar zxvf file.tgz
Note- Please ensure that http path for tgz is valid and file is not corrupted
ClassPath is affected depending on what you provide. There are a couple of ways to set something on the classpath:
spark.driver.extraClassPath
or it's alias --driver-class-path
to set extra classpaths on the node running the driver.spark.executor.extraClassPath
to set extra class path on the Worker nodes.If you want a certain JAR to be effected on both the Master and the Worker, you have to specify these separately in BOTH flags.
Following the same rules as the JVM:
:
--conf "spark.driver.extraClassPath=/opt/prog/hadoop-aws-2.7.1.jar:/opt/prog/aws-java-sdk-1.10.50.jar"
;
--conf "spark.driver.extraClassPath=/opt/prog/hadoop-aws-2.7.1.jar;/opt/prog/aws-java-sdk-1.10.50.jar"
This depends on the mode which you're running your job under:
Client mode - Spark fires up a Netty HTTP server which distributes the files on start up for each of the worker nodes. You can see that when you start your Spark job:
16/05/08 17:29:12 INFO HttpFileServer: HTTP File server directory is /tmp/spark-48911afa-db63-4ffc-a298-015e8b96bc55/httpd-84ae312b-5863-4f4c-a1ea-537bfca2bc2b
16/05/08 17:29:12 INFO HttpServer: Starting HTTP Server
16/05/08 17:29:12 INFO Utils: Successfully started service 'HTTP file server' on port 58922.
16/05/08 17:29:12 INFO SparkContext: Added JAR /opt/foo.jar at http://***:58922/jars/com.mycode.jar with timestamp 1462728552732
16/05/08 17:29:12 INFO SparkContext: Added JAR /opt/aws-java-sdk-1.10.50.jar at http://***:58922/jars/aws-java-sdk-1.10.50.jar with timestamp 1462728552767
Cluster mode - In cluster mode spark selected a leader Worker node to execute the Driver process on. This means the job isn't running directly from the Master node. Here, Spark will not set an HTTP server. You have to manually make your JARS available to all the worker node via HDFS/S3/Other sources which are available to all nodes.
In "Submitting Applications", the Spark documentation does a good job of explaining the accepted prefixes for files:
When using spark-submit, the application jar along with any jars included with the --jars option will be automatically transferred to the cluster. Spark uses the following URL scheme to allow different strategies for disseminating jars:
- file: - Absolute paths and file:/ URIs are served by the driver’s HTTP file server, and every executor pulls the file from the driver HTTP server.
- hdfs:, http:, https:, ftp: - these pull down files and JARs from the URI as expected
- local: - a URI starting with local:/ is expected to exist as a local file on each worker node. This means that no network IO will be incurred, and works well for large files/JARs that are pushed to each worker, or shared via NFS, GlusterFS, etc.
Note that JARs and files are copied to the working directory for each SparkContext on the executor nodes.
As noted, JARs are copied to the working directory for each Worker node. Where exactly is that? It is usually under /var/run/spark/work
, you'll see them like this:
drwxr-xr-x 3 spark spark 4096 May 15 06:16 app-20160515061614-0027
drwxr-xr-x 3 spark spark 4096 May 15 07:04 app-20160515070442-0028
drwxr-xr-x 3 spark spark 4096 May 15 07:18 app-20160515071819-0029
drwxr-xr-x 3 spark spark 4096 May 15 07:38 app-20160515073852-0030
drwxr-xr-x 3 spark spark 4096 May 15 08:13 app-20160515081350-0031
drwxr-xr-x 3 spark spark 4096 May 18 17:20 app-20160518172020-0032
drwxr-xr-x 3 spark spark 4096 May 18 17:20 app-20160518172045-0033
And when you look inside, you'll see all the JARs you deployed along:
[*@*]$ cd /var/run/spark/work/app-20160508173423-0014/1/
[*@*]$ ll
total 89988
-rwxr-xr-x 1 spark spark 801117 May 8 17:34 awscala_2.10-0.5.5.jar
-rwxr-xr-x 1 spark spark 29558264 May 8 17:34 aws-java-sdk-1.10.50.jar
-rwxr-xr-x 1 spark spark 59466931 May 8 17:34 com.mycode.code.jar
-rwxr-xr-x 1 spark spark 2308517 May 8 17:34 guava-19.0.jar
-rw-r--r-- 1 spark spark 457 May 8 17:34 stderr
-rw-r--r-- 1 spark spark 0 May 8 17:34 stdout
The most important thing to understand is priority. If you pass any property via code, it will take precedence over any option you specify via spark-submit
. This is mentioned in the Spark documentation:
Any values specified as flags or in the properties file will be passed on to the application and merged with those specified through SparkConf. Properties set directly on the SparkConf take highest precedence, then flags passed to spark-submit or spark-shell, then options in the spark-defaults.conf file
So make sure you set those values in the proper places, so you won't be surprised when one takes priority over the other.
Lets analyze each option in question:
--jars
vs SparkContext.addJar
: These are identical, only one is set through spark submit and one via code. Choose the one which suites you better. One important thing to note is that using either of these options does not add the JAR to your driver/executor classpath, you'll need to explicitly add them using the extraClassPath
config on both.SparkContext.addJar
vs SparkContext.addFile
: Use the former when you have a dependency that needs to be used with your code. Use the latter when you simply want to pass an arbitrary file around to your worker nodes, which isn't a run-time dependency in your code.--conf spark.driver.extraClassPath=...
or --driver-class-path
: These are aliases, doesn't matter which one you choose--conf spark.driver.extraLibraryPath=..., or --driver-library-path ...
Same as above, aliases.--conf spark.executor.extraClassPath=...
: Use this when you have a dependency which can't be included in an uber JAR (for example, because there are compile time conflicts between library versions) and which you need to load at runtime.--conf spark.executor.extraLibraryPath=...
This is passed as the java.library.path
option for the JVM. Use this when you need a library path visible to the JVM.Would it be safe to assume that for simplicity, I can add additional application jar files using the 3 main options at the same time:
You can safely assume this only for Client mode, not Cluster mode. As I've previously said. Also, the example you gave has some redundant arguments. For example, passing JARs to --driver-library-path
is useless, you need to pass them to extraClassPath
if you want them to be on your classpath. Ultimately, what you want to do when you deploy external JARs on both the driver and the worker is:
spark-submit --jars additional1.jar,additional2.jar \
--driver-class-path additional1.jar:additional2.jar \
--conf spark.executor.extraClassPath=additional1.jar:additional2.jar \
--class MyClass main-application.jar
@Baba's answer is great. But you don't need to use explode
because fputcsv
takes an array as a parameter
For instance, if you have a three columns, four lines document, here's a more straight version:
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="sample.csv"');
$user_CSV[0] = array('first_name', 'last_name', 'age');
// very simple to increment with i++ if looping through a database result
$user_CSV[1] = array('Quentin', 'Del Viento', 34);
$user_CSV[2] = array('Antoine', 'Del Torro', 55);
$user_CSV[3] = array('Arthur', 'Vincente', 15);
$fp = fopen('php://output', 'wb');
foreach ($user_CSV as $line) {
// though CSV stands for "comma separated value"
// in many countries (including France) separator is ";"
fputcsv($fp, $line, ',');
}
fclose($fp);
Here are some classes I use for long-polling in C#. There are basically 6 classes (see below).
aspose pdf works pretty well. then again, you have to pay for it
Have you tried using gzip.open?
with gzip.open('my.csv', 'rb') as data_file:
I was trying to open a file that had been compressed but had the extension '.csv' instead of 'csv.gz'. This error kept showing up until I used gzip.open
Use the square bracket syntax:
if (!empty($row["title"])) {
$catList[$row["datasource_id"]] = $row["title"];
}
$row["datasource_id"]
is the key for where the value of $row["title"]
is stored in.
For Ruby programmers here is how you can assert. Have to include Minitest to get the asserts
assert(@driver.find_element(:tag_name => "body").text.include?("Name"))
I would use GCJ (GNU Compiler for Java) in your situation. It's an AOT (ahead of time) compiler for Java, much like GCC is for C. Instead of interpreting code, or generating intermediate java code to be run at a later time by the Java VM, it generates machine code.
GCJ is available on almost any Linux system through its respective package manager (if available). After installation, the GCJ compiler should be added to the path so that it can be invoked through the terminal. If you're using Windows, you can download and install GCJ through Cygwin or MinGW.
I would strongly recommend, however, that you rewrite your source for another language that is meant to be compiled, such as C++. Java is meant to be a portable, interpreted language. Compiling it to machine code is completely against what the language was developed for.
in some versions the code below might not work
mydict = dict(zip(df.id, df.value))
so make it explicit
id_=df.id.values
value=df.value.values
mydict=dict(zip(id_,value))
Note i used id_ because the word id is reserved word
Search MSDN for "How to: Set Environment Variables for Projects". (It's Project>Properties>Configuration Properties>Debugging "Environment" and "Merge Environment" properties for those who are in a rush.)
The syntax is NAME=VALUE and macros can be used (for example, $(OutDir)).
For example, to prepend C:\Windows\Temp to the PATH:
PATH=C:\WINDOWS\Temp;%PATH%
Similarly, to append $(TargetDir)\DLLS to the PATH:
PATH=%PATH%;$(TargetDir)\DLLS
Use a JSON library to parse the string and retrieve the value.
The following very basic example uses the built-in JSON parser from Android.
String jsonString = "{ \"name\" : \"John\", \"age\" : \"20\", \"address\" : \"some address\" }";
JSONObject jsonObject = new JSONObject(jsonString);
int age = jsonObject.getInt("age");
More advanced JSON libraries, such as jackson, google-gson, json-io or genson, allow you to convert JSON objects to Java objects directly.
Bootstrap 4 has added .no-gutters class.
Bootstrap 3.4 has added .row-no-gutters class
Bootstrap 3: I always add this style to my Bootstrap LESS / SASS:
.row-no-padding {
[class*="col-"] {
padding-left: 0 !important;
padding-right: 0 !important;
}
}
Then in the HTML you can write:
<div class="row row-no-padding">
If you want to only target the child columns you can use the child selector (Thanks John Wu).
.row-no-padding > [class*="col-"] {
padding-left: 0 !important;
padding-right: 0 !important;
}
You may also want to remove padding only for certain device sizes (SASS example):
/* Small devices (tablets, 768px and up) */
@media (min-width: $screen-sm-min) and (max-width: $screen-sm-max) {
.row-sm-no-padding {
[class*="col-"] {
padding-left: 0 !important;
padding-right: 0 !important;
}
}
}
You can remove the max-width part of the media query if you want it to support small devices upwards.
on unix vim --version
tells you the various locations of the vim config files :
system vimrc file: "$VIM/vimrc"
user vimrc file: "$HOME/.vimrc"
2nd user vimrc file: "~/.vim/vimrc"
user exrc file: "$HOME/.exrc"
defaults file: "$VIMRUNTIME/defaults.vim"
fall-back for $VIM: "/usr/share/vim"
I was getting a similar issue from the Apache Lounge 32 bit version. After downloading the 64 bit version, the issue was resolved.
Here is an excellent video explain the steps involved: https://www.youtube.com/watch?v=17qhikHv5hY
private static final String FILE_HEADER ="meter_Number,latestDate";
private static final String COMMA_DELIMITER = ",";
private static final String NEW_LINE_SEPARATOR = "\n";
static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:m m:ss");
private void writeToCsv(Map<String, Date> meterMap) {
try {
Iterator<Map.Entry<String, Date>> iter = meterMap.entrySet().iterator();
FileWriter fw = new FileWriter("smaple.csv");
fw.append(FILE_HEADER.toString());
fw.append(NEW_LINE_SEPARATOR);
while (iter.hasNext()) {
Map.Entry<String, Date> entry = iter.next();
try {
fw.append(entry.getKey());
fw.append(COMMA_DELIMITER);
fw.append(formatter.format(entry.getValue()));
fw.append(NEW_LINE_SEPARATOR);
} catch (Exception e) {
e.printStackTrace();
} finally {
iter.remove();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
I made this work in this way:
<button class="btn" ng-click='toggleClass($event)'>button one</button>
<button class="btn" ng-click='toggleClass($event)'>button two</button>
in your controller:
$scope.toggleClass = function (event) {
$(event.target).toggleClass('active');
}
This trick worked for me too: In Eclipse right-click on the project and then Maven > Update Dependencies.
You can use At
from pydash:
from pydash import at
dict = {'a': 1, 'b': 2, 'c': 3}
list = at(dict, 'a', 'b')
list == [1, 2]
change your
return @str1+'present in the string' ;
to
set @r = @str1+'present in the string'
Based on Aydin's answer I would suggest a less "duplicatious" implementation (because we could easily get the Type
from the Enum
value itself, instead of providing it as a parameter :
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
public static string GetDisplayName(this Enum enumValue)
{
return enumValue.GetType().GetMember(enumValue.ToString())
.First()
.GetCustomAttribute<DisplayAttribute>()
.Name;
}
EDIT (based upon @Vahagn Nahapetyan's comment)
public static string GetDisplayName(this Enum enumValue)
{
return enumValue.GetType()?
.GetMember(enumValue.ToString())?
.First()?
.GetCustomAttribute<DisplayAttribute>()?
.Name;
}
Now we can use it very clean in this way:
public enum Season
{
[Display(Name = "The Autumn")]
Autumn,
[Display(Name = "The Weather")]
Winter,
[Display(Name = "The Tease")]
Spring,
[Display(Name = "The Dream")]
Summer
}
Season.Summer.GetDisplayName();
Which results in
"The Dream"
It sounds like you need an OR instead:
<button type="submit" [disabled]="!validate || !SAForm.valid">Add</button>
This will disable the button if not validate or if not SAForm.valid.
You don't need the separate fill item. In fact, it's invalid. You just have to add a solid
block to the shape
. The subsequent stroke
draws on top of the solid
:
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="5dp" />
<solid android:color="@android:color/white" />
<stroke
android:width="1dip"
android:color="@color/bggrey" />
</shape>
You also don't need the layer-list
if you only have one shape
.
About access
<ol class="viewer-nav">
<li *ngFor="let section of sections"
[attr.data-sectionvalue]="section.value"
(click)="get_data($event)">
{{ section.text }}
</li>
</ol>
And
get_data(event) {
console.log(event.target.dataset.sectionvalue)
}
Now click on Add a generic credential and provide the following values
(1) Internet or network adress: git:https://tfs.donamain name (2) username: your username (3) password: your password
this should fix it
All REST APIs accept a filter_path parameter that can be used to reduce the response returned by elasticsearch. This parameter takes a comma separated list of filters expressed with the dot notation.
You can do this:
var $html = $('<iframe width="854" height="480" src="http://www.youtube.com/embed/gYKqrjq5IjU?feature=oembed" frameborder="0" allowfullscreen></iframe>'); _x000D_
var str = $html.prop('outerHTML');_x000D_
console.log(str);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
_x000D_
If your keyboard is set to English US (International) rather than English US the double quotation marks don't work. This is why the single quotation marks worked in your case.
In case that it serves to someone, I leave here the Windows 10 base register for Python 3.4.4 - 64 bit:
Por si alguien lo necesita todavía, este es el registro base de Windows 10 para Python 3.4.4:
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4]
"DisplayName"="Python 3.4 (64-bit)"
"SupportUrl"="http://www.python.org/"
"Version"="3.4.4"
"SysVersion"="3.4"
"SysArchitecture"="64bit"
[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\Help]
[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\Help\Main Python Documentation]
@="C:\\Python34\\Doc\\python364.chm"
[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\Idle]
@="C:\\Python34\\Lib\\idlelib\\idle.pyw"
[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\IdleShortcuts]
@=dword:00000001
[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\InstalledFeatures]
[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\InstallPath]
@="C:\\Python34\\"
"ExecutablePath"="C:\\Python34\\python.exe"
"WindowedExecutablePath"="C:\\Python34\\pythonw.exe"
[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\PythonPath]
@="C:\\Python34\\Lib\\;C:\\Python34\\DLLs\\"
For Python 3 users:
changing the encoding from 'ascii' to 'latin1' works.
Also, you can try finding the encoding automatically by reading the top 10000 bytes using the below snippet:
import chardet
with open("dataset_path", 'rb') as rawdata:
result = chardet.detect(rawdata.read(10000))
print(result)
If you care about the sequence of the terms, you may consider using a syntax like
select * from T where C like'%David%Moses%Robi%'
You can synchronize your code over the class. That would be simplest.
public class Test
{
private static int count = 0;
private static final Object lock= new Object();
public synchronized void foo()
{
synchronized(Test.class)
{
count++;
}
}
}
Hope you find this answer useful.
The best way to find the position of item in the list is by using Collections interface,
Eg,
List<Integer> sampleList = Arrays.asList(10,45,56,35,6,7);
Collections.binarySearch(sampleList, 56);
Output : 2
You can't run cd
this way, because cd
isn't a real program; it's a built-in part of the command-line, and all it does is change the command-line's environment. It doesn't make sense to run it in a subprocess, because then you're changing that subprocess's environment — but that subprocess closes immediately, discarding its environment.
To set the current working directory in your actual Java program, you should write:
System.setProperty("user.dir", "C:\\Program Files\\Flowella");
You can delete it in the terminal via:
jupyter kernelspec uninstall yourKernel
where yourKernel
is the name of the kernel you want to delete.
$content = $_POST['content_name'];
$lines = explode("\n", $content);
foreach( $lines as $index => $line )
{
$lines[$index] = $line . '<br/>';
}
// $lines contains your lines
try kill -s 9 `ps -ef |grep "Nov 11" |grep -v grep | awk '{print $2}'`
To kill processes of November 11
or
kill -s 9 `ps -ef |grep amarok|grep -v grep | awk '{print $2}'`
To kill processes that contain the word amarok
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY"></script>
<script>
var latitude = '';
var longitude = '';
var geocoder = new google.maps.Geocoder();
geocoder.geocode(
{
componentRestrictions: {
country: 'IN',
postalCode: '744102'
}
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
console.log(latitude + ", " + longitude);
} else {
alert("Request failed.")
}
});
</script>
https://developers.google.com/maps/documentation/javascript/geocoding#ComponentFiltering
Which version of IntelliJ are you using? Note that since last year, IntelliJ exists in two versions:
(see differences here)
In case you are using the Community Edition, you will not be able to manage a Tomcat installation.
In case you are using the Ultimate Edition, you can have a look at:
How do I configure a web framework for my project?
)..navbar-right {
margin-left:auto;
margin-right:auto;
max-width :40%;
float:none !important;
}
just copy this code and change max-width
as you like
Here you go: ES5
var test = 'Hello World';
if( test.indexOf('World') >= 0){
// Found world
}
With ES6 best way would be to use includes
function to test if the string contains the looking work.
const test = 'Hello World';
if (test.includes('World')) {
// Found world
}
For Alpine Linux:
apk add openssl-dev
You must create a new XMLHttpRequest instance and load the contents of the json file.
This tip work for me (https://codepen.io/KryptoniteDove/post/load-json-file-locally-using-pure-javascript):
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'my_data.json', true); // Replace 'my_data' with the path to your file
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
loadJSON(function(response) {
// Parse JSON string into object
var actual_JSON = JSON.parse(response);
});
You can do this with dynamic objects:
var dynamicKeyValueArray = new[] { new {Key = "K1", Value = 10}, new {Key = "K2", Value = 5} };
foreach(var keyvalue in dynamicKeyValueArray)
{
Console.Log(keyvalue.Key);
Console.Log(keyvalue.Value);
}
This is an years old bug.
Check your adb version like this : (the adb path is given with the error itself)
C:\Users\<your_user_name_>\AppData\Local\Android\Sdk\platform-tools\adb.exe --version
output :
Android Debug Bridge version 1.0.41
Version 29.0.4-5871666
Installed as C:\Users\sunil\AppData\Local\Android\Sdk\platform-tools\adb.exe
It means this adb comes from the latest sdk platform tools 29.0.4. Check the latest version from official site here.
If you already have the latest version of ADB installed, and still getting the error, this is a known issue. Google hasn't yet provided any other ADB. Click on the "never show again" option and continue.
For the record, this is documented in How do I add resources to my JAR? (illustrated for unit tests but the same applies for a "regular" resource):
To add resources to the classpath for your unit tests, you follow the same pattern as you do for adding resources to the JAR except the directory you place resources in is
${basedir}/src/test/resources
. At this point you would have a project directory structure that would look like the following:my-app |-- pom.xml `-- src |-- main | |-- java | | `-- com | | `-- mycompany | | `-- app | | `-- App.java | `-- resources | `-- META-INF | |-- application.properties `-- test |-- java | `-- com | `-- mycompany | `-- app | `-- AppTest.java `-- resources `-- test.properties
In a unit test you could use a simple snippet of code like the following to access the resource required for testing:
... // Retrieve resource InputStream is = getClass().getResourceAsStream("/test.properties" ); // Do something with the resource ...
If you're looking to match non-blank values or empty cells and having difficulty with wildcard character, I found the solution below from here.
Dim n as Integer
n = Worksheets("Sheet1").Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count
You can handle all your actions in function of your message in onMessageReceived() in your service extending FirebaseMessagingService. In order to do that, you must send a message containing exclusively data, using for example Advanced REST client in Chrome. Then you send a POST to https://fcm.googleapis.com/fcm/send using in "Raw headers":
Content-Type: application/json Authorization: key=YOUR_PERSONAL_FIREBASE_WEB_API_KEY
And a json message in the field "Raw payload".
Warning, if there is the field "notification" in your json, your message will never be received when app in background in onMessageReceived(), even if there is a data field ! For example, doing that, message work just if app in foreground:
{
"condition": " 'Symulti' in topics || 'SymultiLite' in topics",
"priority" : "normal",
"time_to_live" : 0,
"notification" : {
"body" : "new Symulti update !",
"title" : "new Symulti update !",
"icon" : "ic_notif_symulti"
},
"data" : {
"id" : 1,
"text" : "new Symulti update !"
}
}
In order to receive your message in all cases in onMessageReceived(), simply remove the "notification" field from your json !
Example:
{
"condition": " 'Symulti' in topics || 'SymultiLite' in topics",
"priority" : "normal",
"time_to_live" : 0,,
"data" : {
"id" : 1,
"text" : "new Symulti update !",
"link" : "href://www.symulti.com"
}
}
and in your FirebaseMessagingService :
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String message = "";
obj = remoteMessage.getData().get("text");
if (obj != null) {
try {
message = obj.toString();
} catch (Exception e) {
message = "";
e.printStackTrace();
}
}
String link = "";
obj = remoteMessage.getData().get("link");
if (obj != null) {
try {
link = (String) obj;
} catch (Exception e) {
link = "";
e.printStackTrace();
}
}
Intent intent;
PendingIntent pendingIntent;
if (link.equals("")) { // Simply run your activity
intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
} else { // open a link
String url = "";
if (!link.equals("")) {
intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(link));
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
}
pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = null;
try {
notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notif_symulti) // don't need to pass icon with your message if it's already in your app !
.setContentTitle(URLDecoder.decode(getString(R.string.app_name), "UTF-8"))
.setContentText(URLDecoder.decode(message, "UTF-8"))
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(pendingIntent);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (notificationBuilder != null) {
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(id, notificationBuilder.build());
} else {
Log.d(TAG, "error NotificationManager");
}
}
}
}
Enjoy !
Instant
corresponds to time on the prime meridian (Greenwich).
Whereas LocalDateTime
relative to OS time zone settings, and
cannot represent an instant without additional information such as an offset or time-zone.
To add to the above answers, there's a good article: Useful JVM Flags – Part 8 (GC Logging) by Patrick Peschlow.
A brief excerpt:
The flag -XX:+PrintGC
(or the alias -verbose:gc
) activates the “simple” GC logging mode
By default the GC log is written to stdout. With -Xloggc:<file>
we may instead specify an output file. Note that this flag implicitly sets -XX:+PrintGC
and -XX:+PrintGCTimeStamps
as well.
If we use -XX:+PrintGCDetails
instead of -XX:+PrintGC
, we activate the “detailed” GC logging mode which differs depending on the GC algorithm used.
With -XX:+PrintGCTimeStamps
a timestamp reflecting the real time passed in seconds since JVM start is added to every line.
If we specify -XX:+PrintGCDateStamps
each line starts with the absolute date and time.
I have a similar problem and the solution I am currently using uses Go 1.11 modules. I have the following structure
- projects
- go.mod
- go.sum
- project1
- main.go
- project2
- main.go
- package1
- lib.go
- package2
- lib.go
And I am able to import package1 and package2 from project1 and project2 by using
import (
"projects/package1"
"projects/package2"
)
After running go mod init projects
. I can use go build
from project1 and project2 directories or I can do go build -o project1/exe project1/*.go
from the projects directory.
The downside of this method is that all your projects end up sharing the same dependency list in go.mod. I am still looking for a solution to this problem, but it looks like it might be fundamental.
private void ButtonOpenWebActionPerformed(java.awt.event.ActionEvent evt) {
try {
String url = "https://www.google.com";
java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
} catch (java.io.IOException e) {
System.out.println(e.getMessage());
}
}
I know this is an old post and has been answered many times. I too was wondering if JavaScript had a function that would do this. I was doing some math programming and needed to concatenate two numbers.
So the what if I needed to combine two numbers 17 and 29. Sure I can turn them into strings and concatenate them then turn the new string back into a number. That seems to work pretty well and I can go on with my code, but lets take a look here and try to figure out what is really happening here.
What are we doing to these two numbers, how do we take 17 and 29 and turn it into one thousand seven hundred and twenty-nine? Well we can multiply 17 by 100 then add 29. And how about 172 and 293 to get one hundred seventy-two thousand two hundred and ninety-three? Multiply 172 by 1000 and add 293. But what about only 2 and 9? Multiply 2 by 10 then add 9 to get 29.
So hopefully by now a pattern should be apparent to you. We can devise a math formula to do this calculation for us rather than just using strings. To concatenate any two numbers, a and b, we need to take the product of a and 10 to the power of length b then add b.
So how do we get the length of number b? Well, we could turn b into a string and get the length property of it.
a * Math.pow(10, new String(b).length) + b;
But there has to be a better way to do this without strings, right? Yes there is.
For any two numbers, a and b, with any base B. We are going to multiply a by base B to the power of length b (using log base of b then flooring it to get the nearest whole number then adding 1 to it) then adding b.
So now our code looks like this:
a * Math.pow(10, Math.floor(Math.log10(b)) + 1) + b;
But wait, what if I wanted to do this in base 2 or base 8? How can I do that? We can't use our formula that we just created with any other base but base 10. The JavaScript Math object already has built-in functions for base 10 and 2 (just Math.log), but how do we get log functions for any other base? We divide the log of b by the log of base. Math.log(b) / Math.log(base).
So now we have our fully functioning math based code for concatenating two numbers:
function concatenate(a, b, base) {
return a * Math.pow(base, Math.floor(Math.log(b) / Math.log(base)) + 1) + b;
}
var a = 17, var b = 29;
var concatenatedNumber = concatenate(a, b, 10);
// concatenatedNumber = 1729
If you knew you were only going to be doing base 10 math, you could add a check for base is undefined then set base = 10:
function concatenate(a, b, base) {
if(typeof base == 'undefined') {
base = 10;
}
return a * Math.pow(base, Math.floor(Math.log(b) / Math.log(base)) + 1) + b;
}
var a = 17, b = 29;
var newNumber = concatenate(a, b); // notice I did not use the base argument
// newNumber = 1729
To make it easier for me, I used the prototype to add the function to the Number object:
Number.prototype.concatenate = function(b, base) {
if(typeof base == 'undefined') {
base = 10;
}
return this * Math.pow(base, Math.floor(Math.log(b) / Math.log(base)) + 1) + b;
};
var a = 17;
var newNumber = a.concatenate(29);
// newNumber = 1729
In addition to the answers given above, check the last line of the error message in your console. In my case, the 'site-packages' path in sys.path.append('.....') was wrong.
Using a comma may not be sufficient if you have multiple jQuery objects that need to be joined.
The .add() method adds the selected elements to the result set:
// classA OR classB
jQuery('.classA').add('.classB');
It's more verbose than '.classA, .classB'
, but lets you build more complex selectors like the following:
// (classA which has <p> descendant) OR (<div> ancestors of classB)
jQuery('.classA').has('p').add(jQuery('.classB').parents('div'));
Minor variation of phillfri's answer which was already a variation of Geoff's answer: I added the ability to handle completely empty tables that contain no data for the Array Code.
Sub AddDataRow(tableName As String, NewData As Variant)
Dim sheet As Worksheet
Dim table As ListObject
Dim col As Integer
Dim lastRow As Range
Set sheet = Range(tableName).Parent
Set table = sheet.ListObjects.Item(tableName)
'First check if the last row is empty; if not, add a row
If table.ListRows.Count > 0 Then
Set lastRow = table.ListRows(table.ListRows.Count).Range
If Application.CountBlank(lastRow) < lastRow.Columns.Count Then
table.ListRows.Add
End If
End If
'Iterate through the last row and populate it with the entries from values()
If table.ListRows.Count = 0 Then 'If table is totally empty, set lastRow as first entry
table.ListRows.Add Position:=1
Set lastRow = table.ListRows(1).Range
Else
Set lastRow = table.ListRows(table.ListRows.Count).Range
End If
For col = 1 To lastRow.Columns.Count
If col <= UBound(NewData) + 1 Then lastRow.Cells(1, col) = NewData(col - 1)
Next col
End Sub
JMeter can be launched in non-GUI mode as follows:
jmeter -n -t /path/to/your/test.jmx -l /path/to/results/file.jtl
You can set what would you like to see in result jtl file via playing with JMeter Properties.
See jmeter.properties
file under /bin folder of your JMeter installation and look for those starting with
jmeter.save.saveservice.
Defaults are listed below:
#jmeter.save.saveservice.output_format=csv
#jmeter.save.saveservice.assertion_results_failure_message=false
#jmeter.save.saveservice.assertion_results=none
#jmeter.save.saveservice.data_type=true
#jmeter.save.saveservice.label=true
#jmeter.save.saveservice.response_code=true
#jmeter.save.saveservice.response_data=false
#jmeter.save.saveservice.response_data.on_error=false
#jmeter.save.saveservice.response_message=true
#jmeter.save.saveservice.successful=true
#jmeter.save.saveservice.thread_name=true
#jmeter.save.saveservice.time=true
#jmeter.save.saveservice.subresults=true
#jmeter.save.saveservice.assertions=true
#jmeter.save.saveservice.latency=true
#jmeter.save.saveservice.samplerData=false
#jmeter.save.saveservice.responseHeaders=false
#jmeter.save.saveservice.requestHeaders=false
#jmeter.save.saveservice.encoding=false
#jmeter.save.saveservice.bytes=true
#jmeter.save.saveservice.url=false
#jmeter.save.saveservice.filename=false
#jmeter.save.saveservice.hostname=false
#jmeter.save.saveservice.thread_counts=false
#jmeter.save.saveservice.sample_count=false
#jmeter.save.saveservice.idle_time=false
#jmeter.save.saveservice.timestamp_format=ms
#jmeter.save.saveservice.timestamp_format=yyyy/MM/dd HH:mm:ss.SSS
#jmeter.save.saveservice.default_delimiter=,
#jmeter.save.saveservice.default_delimiter=\t
#jmeter.save.saveservice.print_field_names=false
#jmeter.save.saveservice.xml_pi=<?xml-stylesheet type="text/xsl" href="../extras/jmeter-results-detail-report_21.xsl"?>
#jmeter.save.saveservice.base_prefix=~/
#jmeter.save.saveservice.autoflush=false
Uncomment the one you are interested in and set it's value to change the default. Another option is override property in user.properties
file or provide it as a command-line argument using -J
key as follows:
jmeter -Jjmeter.save.saveservice.print_field_names=true -n /path/to/your/test.jmx -l /path/to/results/file.jtl
See Apache JMeter Properties Customization Guide for more details on what can be done using JMeter Properties.
I had this problem even after setting the config properly. git config
My scenario was issuing git command through supervisor (in Linux). On further debugging, supervisor was not reading the git config from home folder. Hence, I had to set the environment HOME variable in the supervisor config so that it can locate the git config correctly. It's strange that supervisor was not able to locate the git config just from the username configured in supervisor's config (/etc/supervisor/conf.d).
Another case I just had - when the request size is bigger than the request size set in IIS as a limit, then you can get that error too.
Check the IIS request limit and increase it if it's lower than you need. Here is how you can check and change the IIS request limit:
I just found also another thread in stack IIS 7.5 hosted WCF service throws EndpointNotFoundException with 404 only for large requests
Jenkins has a link to their REST API in the bottom right of each page. This link appears on every page of Jenkins and points you to an API output for the exact page you are browsing. That should provide some understanding into how to build the API URls.
You can additionally use some wrapper, like I do, in Python, using http://jenkinsapi.readthedocs.io/en/latest/
Here is their website: https://wiki.jenkins-ci.org/display/JENKINS/Remote+access+API
You can use tabindex
<div tabindex="-1" id="tries"></div>
The tabindex value can allow for some interesting behaviour.
From the friendly Wikipedia:
The stdlib.h and stddef.h header files define a datatype called size_t which is used to represent the size of an object. Library functions that take sizes expect them to be of type size_t, and the sizeof operator evaluates to size_t.
The actual type of size_t is platform-dependent; a common mistake is to assume size_t is the same as unsigned int, which can lead to programming errors, particularly as 64-bit architectures become more prevalent.
Also, check Why size_t matters
In JDK7, "more NIO features" should have methods to apply the visitor pattern over a file tree or just the immediate contents of a directory - no need to find all the files in a potentially huge directory before iterating over them.
My favorite approach, without external libraries:
try {
URI uri = new URI(name);
// perform checks for scheme, authority, host, etc., based on your requirements
if ("mailto".equals(uri.getScheme()) {/*Code*/}
if (uri.getHost() == null) {/*Code*/}
} catch (URISyntaxException e) {
}
Only checked
and checked="checked"
are valid. Your other options depend on error recovery in browsers.
checked="yes"
and checked="true"
are particularly bad as they imply that checked="no"
and checked="false"
will set the default state to be unchecked … which they will not.
Did you try the tool named VBReFormer (http://www.decompiler-vb.net/) ? We used it a lot the past year in order to get back the source code of our application (source code we had lost 6 years ago) and it worked fine. We were also able to make some user interface changes directly from vbreformer and save them into the exe file.
A very simple method for single-line files, requiring GNU echo from coreutils:
/bin/echo -n $(cat $file)
table td {
border-right:1px solid #000;
height: 100%;
}
Just you add height under the border property.
I know I'm a bit late, but was able to fix this issue by following the docs directly.
Add the meta-data tag to AndroidManifest.xml
(so the system knows)
<activity
android:name=".Sub"
android:label="Sub-Activity"
android:parentActivityName=".MainChooser"
android:theme="@style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainChooser" />
</activity>
Next, enable the back (up) button in your MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_child);
// my_child_toolbar is defined in the layout file
Toolbar myChildToolbar =
(Toolbar) findViewById(R.id.my_child_toolbar);
setSupportActionBar(myChildToolbar);
// Get a support ActionBar corresponding to this toolbar
ActionBar ab = getSupportActionBar();
// Enable the Up button
ab.setDisplayHomeAsUpEnabled(true);
}
And, you will be all set up!
Source: Android Developer Documentation
yes you can use MapView in v2... for further details you can get help from this
https://gist.github.com/joshdholtz/4522551
SomeFragment.java
public class SomeFragment extends Fragment implements OnMapReadyCallback{
MapView mapView;
GoogleMap map;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.some_layout, container, false);
// Gets the MapView from the XML layout and creates it
mapView = (MapView) v.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
return v;
}
@Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
/*
//in old Api Needs to call MapsInitializer before doing any CameraUpdateFactory call
try {
MapsInitializer.initialize(this.getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
*/
// Updates the location and zoom of the MapView
/*CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
map.animateCamera(cameraUpdate);*/
map.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(43.1, -87.9)));
}
@Override
public void onResume() {
mapView.onResume();
super.onResume();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<permission
android:name="com.example.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.example.permission.MAPS_RECEIVE"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="your_key"/>
<activity
android:name=".HomeActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
some_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<com.google.android.gms.maps.MapView android:id="@+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
Cancelation of requests issued with $http
is not supported with the current version of AngularJS. There is a pull request opened to add this capability but this PR wasn't reviewed yet so it is not clear if its going to make it into AngularJS core.
You need to change public void klik(PaintEventArgs pea, EventArgs e)
to public void klik(object sender, System.EventArgs e)
because there is no Click
event handler with parameters PaintEventArgs pea, EventArgs e
.
pd.read_excel(file_name)
sometimes this code gives an error for xlsx files as: XLRDError:Excel xlsx file; not supported
instead , you can use openpyxl
engine to read excel file.
df_samples = pd.read_excel(r'filename.xlsx', engine='openpyxl')
It worked for me
You would do that by providing a fully qualified name, e.g.:
SELECT tbl_names.id as id, name, section FROM tbl_names, tbl_section WHERE tbl_names.id = tbl_section.id
Which would give you the id of tbl_names
Sorting in an ORDER BY
is done by the first column, and then by each additional column in the specified statement.
For instance, consider the following data:
Column1 Column2
======= =======
1 Smith
2 Jones
1 Anderson
3 Andrews
The query
SELECT Column1, Column2 FROM thedata ORDER BY Column1, Column2
would first sort by all of the values in Column1
and then sort the columns by Column2
to produce this:
Column1 Column2
======= =======
1 Anderson
1 Smith
2 Jones
3 Andrews
In other words, the data is first sorted in Column1
order, and then each subset (Column1
rows that have 1
as their value) are sorted in order of the second column.
The difference between the two statements you posted is that the rows in the first one would be sorted first by prod_price
(price order, from lowest to highest), and then by order of name (meaning that if two items have the same price, the one with the lower alpha value for name would be listed first), while the second would sort in name order only (meaning that prices would appear in order based on the prod_name
without regard for price).
In order to make it work, you have to set property GroupName of both radio buttons to the same value:
<asp:RadioButton id="rbMetric" runat="server" GroupName="measurementSystem"></asp:RadioButton>
<asp:RadioButton id="rbUS" runat="server" GroupName="measurementSystem"></asp:RadioButton>
Personally, I prefer to use a RadioButtonList:
<asp:RadioButtonList ID="rblMeasurementSystem" runat="server">
<asp:ListItem Text="Metric" Value="metric" />
<asp:ListItem Text="US" Value="us" />
</asp:RadioButtonList>
You can also overload the increment/decrement operators for your enumerated type.
I can't understand why this JAXB IllegalAnnotationException is thrown
I also was getting the ### counts of IllegalAnnotationExceptions
exception and it seemed to be due to an improper dependency hierarchy in my Spring wiring.
I figured it out by putting a breakpoint in the JAXB code when it does the throw. For me this was at com.sun.xml.bind.v2.runtime.IllegalAnnotationsException$Builder.check()
. Then I dumped the list
variable which gives something like:
[org.mortbay.jetty.Handler is an interface, and JAXB can't handle interfaces.
this problem is related to the following location:
at org.mortbay.jetty.Handler
at public org.mortbay.jetty.Handler[] org.mortbay.jetty.handler.HandlerCollection.getHandlers()
at org.mortbay.jetty.handler.HandlerCollection
at org.mortbay.jetty.handler.ContextHandlerCollection
at com.mprew.ec2.commons.server.LocalContextHandlerCollection
at private com.mprew.ec2.commons.server.LocalContextHandlerCollection com.mprew.ec2.commons.services.jaxws_asm.SetLocalContextHandlerCollection.arg0
at com.mprew.ec2.commons.services.jaxws_asm.SetLocalContextHandlerCollection,
org.mortbay.jetty.Handler does not have a no-arg default constructor.]
....
The does not have a no-arg default constructor
seemed to me to be misleading. Maybe I wasn't understanding what the exception was saying. But it did indicate that there was a problem with my LocalContextHandlerCollection
. I removed a dependency loop and the error cleared.
Hopefully this will be helpful to others.
As mentioned by MatBailie This is much more safe since it is not a dynamic query and ther are lesser chances of sql injection . I Added one situation where you even want the where clause to be dynamic . XX YY are Columns names
CREATE PROCEDURE [dbo].[DASH_getTP_under_TP]
(
@fromColumnName varchar(10) ,
@toColumnName varchar(10) ,
@ID varchar(10)
)
as
begin
-- this is the column required for where clause
declare @colname varchar(50)
set @colname=case @fromUserType
when 'XX' then 'XX'
when 'YY' then 'YY'
end
select SelectedColumnId from (
select
case @toColumnName
when 'XX' then tablename.XX
when 'YY' then tablename.YY
end as SelectedColumnId,
From tablename
where
(case @fromUserType
when 'XX' then XX
when 'YY' then YY
end)= ISNULL(@ID , @colname)
) as tbl1 group by SelectedColumnId
end
It will fail to work when:
You are redirecting the response to a new request by response.sendRedirect("page.jsp")
. The newly created request object will of course not contain the attributes anymore and they will not be accessible in the redirected JSP. You need to forward rather than redirect. E.g.
request.setAttribute("name", "value");
request.getRequestDispatcher("page.jsp").forward(request, response);
You are accessing it the wrong way or using the wrong name. Assuming that you have set it using the name "name"
, then you should be able to access it in the forwarded JSP page as follows:
${name}
I found a nice solution which does not need an event to be triggered:
@FXML
private Button cancelButton;
close(new Event(cancelButton, stage, null));
@FXML
private void close(Event event) {
((Node)(event.getSource())).getScene().getWindow().hide();
}
Yes, your example would work fine.
As for exposing your classes, you can export
a class just like anything else:
class Animal {...}
module.exports = Animal;
Or the shorter:
module.exports = class Animal {
};
Once imported into another module, then you can treat it as if it were defined in that file:
var Animal = require('./Animal');
class Cat extends Animal {
...
}
You can also user java Regular Expression. String.split() also uses the expression internally. Refer http://download.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html
If you dont have a .gitignore file, first use:
touch .gitignore
then this command to add lines in your gitignore file:
echo 'application/cache' >> .gitignore
Be careful about new lines
you can achieve vertical aligning with display:table-cell
:
#section1 {
height: 90%;
text-align:center;
display:table;
width:100%;
}
#section1 h1 {display:table-cell; vertical-align:middle}
Update - CSS3
For an alternate way to vertical align, you can use the following css 3 which should be supported in all the latest browsers:
#section1 {
height: 90%;
width:100%;
display:flex;
align-items: center;
justify-content: center;
}
It turns out that you can create 32-bit ODBC connections using C:\Windows\SysWOW64\odbcad32.exe
. My solution was to create the 32-bit ODBC connection as a System DSN. This still didn't allow me to connect to it since .NET couldn't look it up. After significant and fruitless searching to find how to get the OdbcConnection class to look for the DSN in the right place, I stumbled upon a web site that suggested modifying the registry to solve a different problem.
I ended up creating the ODBC connection directly under HKLM\Software\ODBC
. I looked in the SysWOW6432 key to find the parameters that were set up using the 32-bit version of the ODBC administration tool and recreated this in the standard location. I didn't add an entry for the driver, however, as that was not installed by the standard installer for the app either.
After creating the entry (by hand), I fired up my windows service and everything was happy.
To center the canvas element horizontally, you must specify it as a block level and leave its left and right margin properties to the browser:
canvas{
margin-right: auto;
margin-left: auto;
display: block;
}
If you wanted to center it vertically, the canvas element needs to be absolutely positioned:
canvas{
position: absolute;
top: 50%;
transform: translate(0, -50%);
}
If you wanted to center it horizontally and vertically, do:
canvas{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
For more info visit: https://www.w3.org/Style/Examples/007/center.en.html
the wmic bios get serialnumber
command call the Win32_BIOS
wmi class and get the value of the SerialNumber
property, which retrieves the serial number of the BIOS Chip of your system.
To further work with array of maps, the followings could help:
@RequestMapping(value = "/process", method = RequestMethod.POST, headers = "Accept=application/json")
public void setLead(@RequestBody Collection<? extends Map<String, Object>> payload) throws Exception {
List<Map<String,Object>> maps = new ArrayList<Map<String,Object>>();
maps.addAll(payload);
}
Beside sys.argv
, also take a look at the argparse module, which helps define options and arguments for scripts.
The argparse module makes it easy to write user-friendly command-line interfaces.
Per Arvand:
Eclipse: Simply type android.R.layout.simple_list_item_1 somewhere in code, hold Ctrl, hover over simple_list_item_1, and from the dropdown that appears select Open declaration in layout/simple_list_item_1.xml. It'll direct you to the contents of the XML.
From there, if you then hover over the resulting simple_list_item_1.xml tab in the Editor, you'll see the file is located at C:\Data\applications\Android\android-sdk\platforms\android-19\data\res\layout\simple_list_item_1.xml (or equivalent location for your installation).
Put a z-indez
of -1
on your absolute (or relative) positioned element.
This will pull it out of the stacking context. (I think.) Read more wonderful things about "stacking contexts" here: https://philipwalton.com/articles/what-no-one-told-you-about-z-index/
Rather give names of the column on which you want to merge:
exporttab <- merge(x=dwd_nogap, y=dwd_gap, by.x='x1', by.y='x2', fill=-9999)
As of EF 5.0, you need to include the System.ComponentModel.DataAnnotations.Schema
namespace.
For installing standard toolboxes: Just insert your CD/DVD of MATLAB and start installing, when you see typical/Custom, choose custom and check the toolboxes you want to install and uncheck the others which are installed already.
I modified Zack's answer since I wanted spaces and interpolation but not newlines and used:
%W[
It's a nice day "#{name}"
for a walk!
].join(' ')
where name = 'fred'
this produces It's a nice day "fred" for a walk!
cout.fill( '0' );
cout.width( 3 );
cout << value;
/*This code will use gridview sum inside data list*/
SumOFdata(grd_DataDetail);
private void SumOFEPFWages(GridView grd)
{
Label lbl_TotAmt = (Label)grd.FooterRow.FindControl("lblTotGrossW");
/*Sum of the total Amount of the day*/
foreach (GridViewRow gvr in grd.Rows)
{
Label lbl_Amount = (Label)gvr.FindControl("lblGrossS");
lbl_TotAmt.Text = (Convert.ToDouble(lbl_Amount.Text) + Convert.ToDouble(lbl_TotAmt.Text)).ToString();
}
}
var i = [NaN, 1,2,3];
var j = i.map(i =>{ return isNaN(i) ? 0 : i});
console.log(j)
_x000D_
To select rows according to one 'cell_type' (e.g. 'hesc'), use ==
:
expr[expr$cell_type == "hesc", ]
To select rows according to two or more different 'cell_type', (e.g. either 'hesc' or 'bj fibroblast'), use %in%
:
expr[expr$cell_type %in% c("hesc", "bj fibroblast"), ]
short recursive variant:
find . -type f -exec cat {} + | grep -c 'string'
You can use -m -c -r to make migration, model and controller.
php artisan make:model Post -m -c -r
Try:
next(g)
Check out this neat table that shows the differences in syntax between 2 and 3 when it comes to this.
My prefered way to center a box both vertically and horizontally, is the following technique :
display: table;
display: table-cell;
vertical-align: middle;
text-align: center;
display: inline-block;
text-align: left;
or text-align: right;
, unless you want text to be centeredThe elegance of this technique, is that you can add your content to the content box without worrying about its height or width!
body {
margin : 0;
}
.outer-container {
position : absolute;
display: table;
width: 100%; /* This could be ANY width */
height: 100%; /* This could be ANY height */
background: #ccc;
}
.inner-container {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.centered-content {
display: inline-block;
text-align: left;
background: #fff;
padding : 20px;
border : 1px solid #000;
}
_x000D_
<div class="outer-container">
<div class="inner-container">
<div class="centered-content">
You can put anything here!
</div>
</div>
</div>
_x000D_
See also this Fiddle!
Yes, I know you can achieve more or less the same flexibility with transform: translate(-50%, -50%);
or transform: translate3d(-50%,-50%, 0);
, the technique I'm proposing has far better browser support. Even with browsers prefixes like -webkit
, -ms
or -moz
, transform
doesn't offer quite the same browser support.
So if you care about older browsers (eg. IE9 and below), you should not use transform
for positioning.
var customView = UIView()
@IBAction func drawView(_ sender: AnyObject) {
customView.frame = CGRect.init(x: 0, y: 0, width: 100, height: 200)
customView.backgroundColor = UIColor.black //give color to the view
customView.center = self.view.center
self.view.addSubview(customView)
}
When I tried '.* in windows (Notepad ++) it would match everything after first ' until end of last line.
To capture everything until end of that line I typed the following:
'.*?\n
This would only capture everything from ' until end of that line.
You can specify credentials by adding a new Generic Credential of your proxy server in Windows Credentials Manager:
1 In Web.config
<system.net>
<defaultProxy enabled="true" useDefaultCredentials="true">
<proxy usesystemdefault="True" />
</defaultProxy>
</system.net>
Internet or network address: your proxy address
User name: your user name
Password: you pass
This configuration worked for me, without change the code.
Its not quite fine to downgrade everytime, you may need to make following changes as shown below:
import tensorflow as tf
#Keras
from tensorflow.keras.models import Sequential, Model, load_model, save_model
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.layers import Dense, Activation, Dropout, Input, Masking, TimeDistributed, LSTM, Conv1D, Embedding
from tensorflow.keras.layers import GRU, Bidirectional, BatchNormalization, Reshape
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.layers import Reshape, Dropout, Dense,Multiply, Dot, Concatenate,Embedding
from tensorflow.keras import optimizers
from tensorflow.keras.callbacks import ModelCheckpoint
The point is that instead of using
from keras.layers import Reshape, Dropout, Dense,Multiply, Dot, Concatenate,Embedding
you need to add
from tensorflow.keras.layers import Reshape, Dropout, Dense,Multiply, Dot, Concatenate,Embedding
See following snippet :
$(document).on("click", "a.deleteText", function() {_x000D_
if (confirm('Are you sure ?')) {_x000D_
$(this).prev('span.text').remove();_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class="container">_x000D_
<span class="text">some text</span>_x000D_
<a href="#" class="deleteText"><span class="delete-icon"> x Delete </span></a>_x000D_
</div>
_x000D_
You can use LIMIT 2,1
instead of WHERE row_number() = 3
.
As the documentation explains, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return.
Keep in mind that it's an 0-based index. So, if you want the line number n, the first argument should be n-1. The second argument will always be 1, because you just want one row. For example, if you want the line number 56 of a table customer
:
SELECT * FROM customer LIMIT 55,1
Or you could try:
propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType), null);
//But this will cause problems if your string value IsNullOrEmplty...
In Controller, your method should be;
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ResponseEntity<SaveResponse> uploadAttachment(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
....
Further, you need to update application.yml (or application.properties) to support maximum file size and request size.
spring:
http:
multipart:
max-file-size: 5MB
max-request-size: 20MB
The only way that comes to mind for this from a consumer point of view is to actually consume the messages and count them then.
The Kafka broker exposes JMX counters for number of messages received since start-up but you cannot know how many of them have been purged already.
In most common scenarios, messages in Kafka is best seen as an infinite stream and getting a discrete value of how many that is currently being kept on disk is not relevant. Furthermore things get more complicated when dealing with a cluster of brokers which all have a subset of the messages in a topic.
gflags
utility to turn on user-mode stack traces.UMDH
to take multiple snapshots of your program's memory. Take a snapshot before memory gets allocated, and take a second snapshot after a point at which you believe that your program has leaked memory. You might want to add pauses or prompts in your program to give you a chance to run UMDH
and take the snapshots.UMDH
again, this time in its mode that does a diff between the two snapshots. It will then generate a report containing the call stacks of suspected memory leaks.gflags
settings when you're done.UMDH
will give you more information than the CRT debug heap because it is watching memory allocations across your entire process; it can even tell you if third-party components are leaking.
in Content script , i add script tag to the head which binds a 'onmessage' handler, inside the handler i use , eval to execute code. In booth content script i use onmessage handler as well , so i get two way communication. Chrome Docs
//Content Script
var pmsgUrl = chrome.extension.getURL('pmListener.js');
$("head").first().append("<script src='"+pmsgUrl+"' type='text/javascript'></script>");
//Listening to messages from DOM
window.addEventListener("message", function(event) {
console.log('CS :: message in from DOM', event);
if(event.data.hasOwnProperty('cmdClient')) {
var obj = JSON.parse(event.data.cmdClient);
DoSomthingInContentScript(obj);
}
});
pmListener.js is a post message url listener
//pmListener.js
//Listen to messages from Content Script and Execute Them
window.addEventListener("message", function (msg) {
console.log("im in REAL DOM");
if (msg.data.cmnd) {
eval(msg.data.cmnd);
}
});
console.log("injected To Real Dom");
This way , I can have 2 way communication between CS to Real Dom. Its very usefull for example if you need to listen webscoket events , or to any in memory variables or events.
Nothing worked for me until I updated my kotlin plugin dependency.
Try this:
1. Invalidate cahce and restart.
2. Sync project (at least try to)
3. Go File -> Project Structure -> Suggestions
4. If there is an update regarding Kotlin, update it.
Hope it will help someone.
Make sure it's not blocked at your settings
http://www.howtogeek.com/howto/16404/how-to-disable-the-new-geolocation-feature-in-google-chrome/
I have many problems trying to solve this one... tried the obvious, but did not work. It just append an empty function somehow.
array_of_functions.push(function() { first_function('a string') });
I solved it by using an array of strings, and later with eval:
array_of_functions.push("first_function('a string')");
for (var Func of array_of_functions) {
eval(Func);
}
For your particular example, I would just do this, since you obviously don't care about actually having the browser get the redirect anyway (by virtue of accepting the answer you have already accepted):
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index() {
// obviously these values might come from somewhere non-trivial
return Index(2, "text");
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(int someValue, string anotherValue) {
// would probably do something non-trivial here with the param values
return View();
}
That works easily and there is no funny business really going on - this allows you to maintain the fact that the second one really only accepts HTTP POST requests (except in this instance, which is under your control anyway) and you don't have to use TempData either, which is what the link you posted in your answer is suggesting.
I would love to know what is "wrong" with this, if there is anything. Obviously, if you want to really have sent to the browser a redirect, this isn't going to work, but then you should ask why you would be trying to convert that regardless, since it seems odd to me.
Hope that helps.
The following may work as well.
function isNumeric(v) {
return v.length > 0 && !isNaN(v) && v.search(/[A-Z]|[#]/ig) == -1;
};
I think the response from W5ALIVE is closest to what I use to find the last row of data in a column. Assuming I am looking for the last row with data in Column A, though, I would use the following for the more generic lookup:
=MAX(IFERROR(MATCH("*",A:A,-1),0),IFERROR(MATCH(9.99999999999999E+307,A:A,1),0))
The first MATCH will find the last text cell and the second MATCH finds the last numeric cell. The IFERROR function returns zero if the first MATCH finds all numeric cells or if the second match finds all text cells.
Basically this is a slight variation of W5ALIVE's mixed text and number solution.
In testing the timing, this was significantly quicker than the equivalent LOOKUP variations.
To return the actual value of that last cell, I prefer to use indirect cell referencing like this:
=INDIRECT("A"&MAX(IFERROR(MATCH("*",A:A,-1),0),IFERROR(MATCH(9.99999999999999E+307,A:A,1),0)))
The method offered by sancho.s is perhaps a cleaner option, but I would modify the portion that finds the row number to this:
=INDEX(MAX((A:A<>"")*(ROW(A:A))),1)
the only difference being that the ",1" returns the first value while the ",0" returns the entire array of values (all but one of which are not needed). I still tend to prefer addressing the cell to the index function there, in other words, returning the cell value with:
=INDIRECT("A"&INDEX(MAX((A:A<>"")*(ROW(A:A))),1))
Great thread!
This one was not included:
System.Windows.Forms.Application.ExecutablePath;
~Joe