You might consider Digest Access Authentication. Essentially the protocol is as follows:
All of this communication is made through headers, which, as jmort253 points out, is generally more secure than communicating sensitive material in the url parameters.
Digest Access Authentication is supported by Spring Security. Notice that, although the docs say that you must have access to your client's plain-text password, you can successfully authenticate if you have the HA1 hash for your client.
Click on "Run code snippet" to see an embedded OpenStreetMap slippy map with a marker on it. This was created with Leaflet.
// Where you want to render the map.
var element = document.getElementById('osm-map');
// Height has to be set. You can do this in CSS too.
element.style = 'height:300px;';
// Create Leaflet map on map element.
var map = L.map(element);
// Add OSM tile leayer to the Leaflet map.
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
// Target's GPS coordinates.
var target = L.latLng('47.50737', '19.04611');
// Set map's center to target with zoom 14.
map.setView(target, 14);
// Place a marker on the same location.
L.marker(target).addTo(map);
_x000D_
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<link href="https://unpkg.com/[email protected]/dist/leaflet.css" rel="stylesheet"/>
<div id="osm-map"></div>
_x000D_
Note:
I used the CDN version of Leaflet here, but you can download the files so you can serve and include them from your own host.
I'm assuming you are using jQuery or something similar. If you are using jQuery, then the following should work:
<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
</head>
<body>
content
</body>
<script type="text/javascript">
$("body").load(url);
</script>
</html>
Here is pure Bootstrap 4 with CSS 3 solution.
<div class="modal fade2" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>
.fade2 {
transform: scale(0.9);
opacity: 0;
transition: all .2s linear;
display: block !important;
}
.fade2.show {
opacity: 1;
transform: scale(1);
}
$('#exampleModal').modal();
function afterModalTransition(e) {
e.setAttribute("style", "display: none !important;");
}
$('#exampleModal').on('hide.bs.modal', function (e) {
setTimeout( () => afterModalTransition(this), 200);
})
Full example here.
Maybe it will help someone.
--
Thank you @DavidDomain too.
I had a similar issue and blogged about it here. I started with the regular expression for alpha numerics, then added in the few basic punctuation characters I liked:
select dump(a,1016), a, b
from
(select regexp_replace(COLUMN,'[[:alnum:]/''%()> -.:=;[]','') a,
COLUMN b
from TABLE)
where a is not null
order by a;
I used dump with the 1016 variant to give out the hex characters I wanted to replace which I could then user in a utl_raw.cast_to_varchar2.
In case that you need to add the http redirect in many sites, you could use it as a c# console program:
class Program
{
static int Main(string[] args)
{
if (args.Length < 3)
{
Console.WriteLine("Please enter an argument: for example insert-redirect ./web.config http://stackoverflow.com");
return 1;
}
if (args.Length == 3)
{
if (args[0].ToLower() == "-insert-redirect")
{
var path = args[1];
var value = args[2];
if (InsertRedirect(path, value))
Console.WriteLine("Redirect added.");
return 0;
}
}
Console.WriteLine("Wrong parameters.");
return 1;
}
static bool InsertRedirect(string path, string value)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(path);
// This should find the appSettings node (should be only one):
XmlNode nodeAppSettings = doc.SelectSingleNode("//system.webServer");
var existNode = nodeAppSettings.SelectSingleNode("httpRedirect");
if (existNode != null)
return false;
// Create new <add> node
XmlNode nodeNewKey = doc.CreateElement("httpRedirect");
XmlAttribute attributeEnable = doc.CreateAttribute("enabled");
XmlAttribute attributeDestination = doc.CreateAttribute("destination");
//XmlAttribute attributeResponseStatus = doc.CreateAttribute("httpResponseStatus");
// Assign values to both - the key and the value attributes:
attributeEnable.Value = "true";
attributeDestination.Value = value;
//attributeResponseStatus.Value = "Permanent";
// Add both attributes to the newly created node:
nodeNewKey.Attributes.Append(attributeEnable);
nodeNewKey.Attributes.Append(attributeDestination);
//nodeNewKey.Attributes.Append(attributeResponseStatus);
// Add the node under the
nodeAppSettings.AppendChild(nodeNewKey);
doc.Save(path);
return true;
}
catch (Exception e)
{
Console.WriteLine($"Exception adding redirect: {e.Message}");
return false;
}
}
}
Or You can use
grep -n . file1 |tail -LineNumberToStartWith|grep regEx
This will take care of numbering the lines in the file
grep -n . file1
This will print the last-LineNumberToStartWith
tail -LineNumberToStartWith
And finally it will grep your desired lines(which will include line number as in orignal file)
grep regEX
It's been a while since I C++'d but these answers are off a bit.
As far as the size goes, 'int' isn't anything. It's a notional value of a standard integer; assumed to be fast for purposes of things like iteration. It doesn't have a preset size.
So, the answers are correct with respect to the differences between int and uint, but are incorrect when they talk about "how large they are" or what their range is. That size is undefined, or more accurately, it will change with the compiler and platform.
It's never polite to discuss the size of your bits in public.
When you compile a program, int does have a size, as you've taken the abstract C/C++ and turned it into concrete machine code.
So, TODAY, practically speaking with most common compilers, they are correct. But do not assume this.
Specifically: if you're writing a 32 bit program, int will be one thing, 64 bit, it can be different, and 16 bit is different. I've gone through all three and briefly looked at 6502 shudder
A brief google search shows this: https://www.tutorialspoint.com/cprogramming/c_data_types.htm This is also good info: https://docs.oracle.com/cd/E19620-01/805-3024/lp64-1/index.html
use int if you really don't care how large your bits are; it can change.
Use size_t and ssize_t if you want to know how large something is.
If you're reading or writing binary data, don't use int. Use a (usually platform/source dependent) specific keyword. WinSDK has plenty of good, maintainable examples of this. Other platforms do too.
I've spent a LOT of time going through code from people that "SMH" at the idea that this is all just academic/pedantic. These ate the people that write unmaintainable code. Sure, it's easy to use type 'int' and use it without all the extra darn typing. It's a lot of work to figure out what they really meant, and a bit mind-numbing.
It's crappy coding when you mix int.
use int and uint when you just want a fast integer and don't care about the range (other than signed/unsigned).
when i write import StringIO it says there is no such module.
From What’s New In Python 3.0:
The
StringIO
andcStringIO
modules are gone. Instead, import theio
module and useio.StringIO
orio.BytesIO
for text and data respectively.
.
A possibly useful method of fixing some Python 2 code to also work in Python 3 (caveat emptor):
try:
from StringIO import StringIO ## for Python 2
except ImportError:
from io import StringIO ## for Python 3
Note: This example may be tangential to the main issue of the question and is included only as something to consider when generically addressing the missing
StringIO
module. For a more direct solution the messageTypeError: Can't convert 'bytes' object to str implicitly
, see this answer.
check the ff post for your solution and don't forget to mark this when you fine this helpful
http://errorbank.blogspot.com/2011/03/list-all-foreign-keys-references-for.html
SELECT
o.conname AS constraint_name,
(SELECT nspname FROM pg_namespace WHERE oid=m.relnamespace) AS source_schema,
m.relname AS source_table,
(SELECT a.attname FROM pg_attribute a WHERE a.attrelid = m.oid AND a.attnum = o.conkey[1] AND a.attisdropped = false) AS source_column,
(SELECT nspname FROM pg_namespace WHERE oid=f.relnamespace) AS target_schema,
f.relname AS target_table,
(SELECT a.attname FROM pg_attribute a WHERE a.attrelid = f.oid AND a.attnum = o.confkey[1] AND a.attisdropped = false) AS target_column
FROM
pg_constraint o LEFT JOIN pg_class f ON f.oid = o.confrelid LEFT JOIN pg_class m ON m.oid = o.conrelid
WHERE
o.contype = 'f' AND o.conrelid IN (SELECT oid FROM pg_class c WHERE c.relkind = 'r');
Here are the common characters which need to be escaped in XML, starting with double quotes:
"
) are escaped to "
&
) is escaped to &
'
) are escaped to '
<
) is escaped to <
>
) is escaped to >
using (var client = new WebClient())
{
client.DownloadFile("http://example.com/file/song/a.mpeg", "a.mpeg");
}
Correct, when you drag a view controller object onto your storyboard in order to create a new scene, it doesn't automatically make the new class for you, too.
Having added a new view controller scene to your storyboard, you then have to:
Create a UIViewController
subclass. For example, go to your target's folder in the project navigator panel on the left and then control-click and choose "New File...". Choose a "Cocoa Touch Class":
And then select a unique name for the new view controller subclass:
Specify this new subclass as the base class for the scene you just added to the storyboard.
Now hook up any IBOutlet
and IBAction
references for this new scene with the new view controller subclass.
cd venv
source bin/activate
export PYTHONPATH='/home/django/srmvenv/lib/python3.4'
python
\>\> import sys
\>\> sys.path
Firstly, I believe that trying to do several things at once is a bad practice in general and I suggest you think over what you are trying to achieve.
It serves as a good theoretical question though and from what I gather the CopyOnWriteArraySet
implementation of java.util.Set
interface satisfies your rather special requirements.
http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/CopyOnWriteArraySet.html
Even if it looks like the module is installed, as far as Python is concerned it isn't since it throws that exception.
Try installing the module again using one of the installation methods shown in the XlsxWriter docs and look out for any installation errors.
If there are none then run a sample program like the following:
import xlsxwriter
workbook = xlsxwriter.Workbook('hello.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write('A1', 'Hello world')
workbook.close()
You can Use this for Curl:
function fakeip()
{
return long2ip( mt_rand(0, 65537) * mt_rand(0, 65535) );
}
function getdata($url,$args=false)
{
global $session;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("REMOTE_ADDR: ".fakeip(),"X-Client-IP: ".fakeip(),"Client-IP: ".fakeip(),"HTTP_X_FORWARDED_FOR: ".fakeip(),"X-Forwarded-For: ".fakeip()));
if($args)
{
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$args);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1:8888");
$result = curl_exec ($ch);
curl_close ($ch);
return $result;
}
Then To Read Json:
$result=getdata("https://example.com");
Then :
///Deocde Json
$data = json_decode($result,true);
///Count
$total=count($data);
$Str='<h1>Total : '.$total.'';
echo $Str;
//You Can Also Make In Table:
foreach ($data as $key => $value)
{
echo ' <td><font face="calibri"color="red">'.$value[type].' </font></td><td><font face="calibri"color="blue">'.$value[category].' </font></td><td><font face="calibri"color="green">'.$value[amount].' </font></tr><tr>';
}
echo "</tr></table>";
}
You Can Also Use This:
echo '<p>Name : '.$data['result']['name'].'</p>
<img src="'.$data['result']['pic'].'"><br>';
Hope this helped.
The simple solution is to remove IndexError by incorporating the condition:
if(index<(len(li)-1))
The error 'index out of range' will not occur now as the last index will not be reached. The idea is to access the next element while iterating. On reaching the penultimate element, you can access the last element.
Use enumerate method to add index or counter to an iterable(list, tuple, etc.). Now using the index+1, we can access the next element while iterating through the list.
li = [0, 1, 2, 3]
running = True
while running:
for index, elem in enumerate(li):
if(index<(len(li)-1)):
thiselem = elem
nextelem = li[index+1]
ref
mimics (or behaves) as a global area just for two scopes:
There is an interesting Video on YouTube about this. Its from Linus Torwalds himself: Goolge Tech Talk: Linus Torvalds on git
What about normal encoded white-space character?
 
/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).*$/
this the simple way to use it while validate atleast 1 uppercase 1 lowercase and 1 number
and this is the example while I use in express validation
check('password')
.notEmpty()
.withMessage('Password cannot be null')
.bail()
.isLength({ min: 6 })
.withMessage('Password must be at least 6 characters')
.bail()
.matches(/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).*$/)
.withMessage(
'Must have atleast 1 uppercase, 1 lowercase letter and 1 number'
),
It can simply be done with a single reduce operation as follows;
var avg = [1,2,3,4].reduce((p,c,_,a) => p + c/a.length,0);_x000D_
console.log(avg)
_x000D_
jQuery transit will probably make your life easier if you are dealing with CSS3 animations through jQuery.
EDIT March 2014 (because my advice has constantly been up and down voted since I posted it)
Let me explain why I was initially hinting towards the plugin above:
Updating the DOM
on each step (i.e. $.animate
) is not ideal in terms of performance.
It works, but will most probably be slower than pure CSS3 transitions or CSS3 animations.
This is mainly because the browser gets a chance to think ahead if you indicate what the transition is going to look like from start to end.
To do so, you can for example create a CSS class for each state of the transition and only use jQuery to toggle the animation state.
This is generally quite neat as you can tweak you animations alongside the rest of your CSS instead of mixing it up with your business logic:
// initial state
.eye {
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
transform: rotate(45deg);
// etc.
// transition settings
-webkit-transition: -webkit-transform 1s linear 0.2s;
-moz-transition: -moz-transform 1s linear 0.2s;
transition: transform 1s linear 0.2s;
// etc.
}
// open state
.eye.open {
transform: rotate(90deg);
}
// Javascript
$('.eye').on('click', function () { $(this).addClass('open'); });
If any of the transform parameters is dynamic you can of course use the style attribute instead:
$('.eye').on('click', function () {
$(this).css({
-webkit-transition: '-webkit-transform 1s ease-in',
-moz-transition: '-moz-transform 1s ease-in',
// ...
// note that jQuery will vendor prefix the transform property automatically
transform: 'rotate(' + (Math.random()*45+45).toFixed(3) + 'deg)'
});
});
A lot more detailed information on CSS3 transitions on MDN.
HOWEVER There are a few other things to keep in mind and all this can get a bit tricky if you have complex animations, chaining etc. and jQuery Transit just does all the tricky bits under the hood:
$('.eye').transit({ rotate: '90deg'}); // easy huh ?
Following is correct way:
xmlhttp.open("GET","getuser.php?fname="+abc ,true);
Since the release of HTML5 one can now simply do:
<div hidden>This div is hidden</div>
Note: This is not supported by some old browsers, most notably IE < 11.
Define a const static instance of the struct with the initial values and then simply assign this value to your variable whenever you want to reset it.
For example:
static const struct x EmptyStruct;
Here I am relying on static initialization to set my initial values, but you could use a struct initializer if you want different initial values.
Then, each time round the loop you can write:
myStructVariable = EmptyStruct;
Andy Hume pretty much gave the answer, I just want to add a few more details.
With this construct you are creating an anonymous function with its own evaluation environment or closure, and then you immediately evaluate it. The nice thing about this is that you can access the variables declared before the anonymous function, and you can use local variables inside this function without accidentally overwriting an existing variable.
The use of the var keyword is very important, because in JavaScript every variable is global by default, but with the keyword you create a new, lexically scoped variable, that is, it is visible by the code between the two braces. In your example, you are essentially creating short aliases to the objects in the YUI library, but it has more powerful uses.
I don't want to leave you without a code example, so I'll put here a simple example to illustrate a closure:
var add_gen = function(n) {
return function(x) {
return n + x;
};
};
var add2 = add_gen(2);
add2(3); // result is 5
What is going on here? In the function add_gen you are creating an another function which will simply add the number n to its argument. The trick is that in the variables defined in the function parameter list act as lexically scoped variables, like the ones defined with var.
The returned function is defined between the braces of the add_gen function so it will have access to the value of n even after add_gen function has finished executing, that is why you will get 5 when executing the last line of the example.
With the help of function parameters being lexically scoped, you can work around the "problems" arising from using loop variables in anonymous functions. Take a simple example:
for(var i=0; i<5; i++) {
setTimeout(function(){alert(i)}, 10);
}
The "expected" result could be the numbers from zero to four, but you get four instances of fives instead. This happens because the anonymous function in setTimeout and the for loop are using the very same i variable, so by the time the functions get evaluated, i will be 5.
You can get the naively expected result by using the technique in your question and the fact, that function parameters are lexically scoped. (I've used this approach in an other answer)
for(var i=0; i<5; i++) {
setTimeout(
(function(j) {
return function(){alert(j)};
})(i), 10);
}
With the immediate evaluation of the outer function you are creating a completely independent variable named j in each iteration, and the current value of i will be copied in to this variable, so you will get the result what was naively expected from the first try.
I suggest you to try to understand the excellent tutorial at http://ejohn.org/apps/learn/ to understand closures better, that is where I learnt very-very much.
Just like any other environment variable, with SET
:
SET PATH=%PATH%;c:\whatever\else
If you want to have a little safety check built in first, check to see if the new path exists first:
IF EXIST c:\whatever\else SET PATH=%PATH%;c:\whatever\else
If you want that to be local to that batch file, use setlocal
:
setlocal
set PATH=...
set OTHERTHING=...
@REM Rest of your script
Read the docs carefully for setlocal
/endlocal
, and have a look at the other references on that site - Functions is pretty interesting too and the syntax is tricky.
The Syntax page should get you started with the basics.
If your line number is 100 to read
head -100 filename | tail -1
json.dumps()
is used to decode JSON datajson.loads
take a string as input and returns a dictionary as output.json.dumps
take a dictionary as input and returns a string as output.import json
# initialize different data
str_data = 'normal string'
int_data = 1
float_data = 1.50
list_data = [str_data, int_data, float_data]
nested_list = [int_data, float_data, list_data]
dictionary = {
'int': int_data,
'str': str_data,
'float': float_data,
'list': list_data,
'nested list': nested_list
}
# convert them to JSON data and then print it
print('String :', json.dumps(str_data))
print('Integer :', json.dumps(int_data))
print('Float :', json.dumps(float_data))
print('List :', json.dumps(list_data))
print('Nested List :', json.dumps(nested_list, indent=4))
print('Dictionary :', json.dumps(dictionary, indent=4)) # the json data will be indented
output:
String : "normal string"
Integer : 1
Float : 1.5
List : ["normal string", 1, 1.5]
Nested List : [
1,
1.5,
[
"normal string",
1,
1.5
]
]
Dictionary : {
"int": 1,
"str": "normal string",
"float": 1.5,
"list": [
"normal string",
1,
1.5
],
"nested list": [
1,
1.5,
[
"normal string",
1,
1.5
]
]
}
| Python | JSON |
|:--------------------------------------:|:------:|
| dict | object |
| list, tuple | array |
| str | string |
| int, float, int- & float-derived Enums | number |
| True | true |
| False | false |
| None | null |
Spring Boot already has support for profile based properties.
Simply add an application-[profile].properties
file and specify the profiles to use using the spring.profiles.active
property.
-Dspring.profiles.active=local
This will load the application.properties
and the application-local.properties
with the latter overriding properties from the first.
myLabel.setHorizontalAlignment(SwingConstants.CENTER);
myLabel.setVerticalAlignment(SwingConstants.CENTER);
If you cannot reconstruct the label for some reason, this is how you edit these properties of a pre-existent JLabel.
You can also use the Termial view to ssh/telnet to your local machine. Doesn't have that funny input box for commands.
You can't select a sheet in a non-active workbook.
You must first activate the workbook, then you can select the sheet.
workbooks("A").activate
workbooks("A").worksheets("B").select
When you use Activate it automatically activates the workbook.
Note you can select >1 sheet in a workbook:
activeworkbook.sheets(array("sheet1","sheet3")).select
but only one sheet can be Active, and if you activate a sheet which is not part of a multi-sheet selection then those other sheets will become un-selected.
str_pad
from the stringr
package is an alternative.
anim = 25499:25504
str_pad(anim, width=6, pad="0")
Add CSS:_x000D_
_x000D_
_x000D_
li {_x000D_
display: table-row;_x000D_
_x000D_
}_x000D_
li div {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
_x000D_
}_x000D_
.check{_x000D_
width:20px;_x000D_
_x000D_
}_x000D_
ul{_x000D_
list-style: none;_x000D_
}_x000D_
_x000D_
<ul>_x000D_
<li>_x000D_
_x000D_
<div><label for="myid1">Subject1</label></div>_x000D_
<div class="check"><input type="checkbox" value="1"name="subject" class="subject-list" id="myid1"></div>_x000D_
</li>_x000D_
<li>_x000D_
_x000D_
<div><label for="myid2">Subject2</label></div>_x000D_
<div class="check" ><input type="checkbox" value="2" class="subject-list" name="subjct" id="myid2"></div>_x000D_
</li>_x000D_
</ul>
_x000D_
This can be an issue when using Source Control and automated deployments to a shared development environment. Where I work we have a very large sample DB on our development tier to work with (a subset of our production data).
Recently I did some work to remove one column from a table and then add some extra ones on the end. I then had to undo my column removal so I re-added it on the end which means the table and all references are correct in the environment but the Source Control automated deployment will no longer work because it complains about the table definition changing.
The real problem here is that the table + indexes are ~120GB and the environment only has ~60GB free so I'll need to either:
a) Rename the existing columns which are in the wrong order, add new columns in the right order, update the data then drop the old columns
OR
b) Rename the table, create a new table with the correct order, insert to the new table from the old and delete from the old as I go along
The SSMS/TFS Schema compare option of using a temp table won't work because there isn't enough room on disc to do it.
I'm not trying to say this is the best way to go about things or that column order really matters, just that I have a scenario where it is an issue and I'm sharing the options I've thought of to fix the issue
You want huge?
Here's a small table: create table foo (id int not null primary key auto_increment, crap char(2000));
insert into foo(crap) values ('');
-- each time you run the next line, the number of rows in foo doubles. insert into foo( crap ) select * from foo;
run it twenty more times, you have over a million rows to play with.
Yes, if he's looking for looks of relations to navigate, this is not the answer. But if by huge he means to test performance and his ability to optimize, this will do it. I did exactly this (and then updated with random values) to test an potential answer I had for another question. (And didn't answer it, because I couldn't come up with better performance than what that asker had.)
Had he asked for "complex", I'd have gien a differnt answer. To me,"huge" implies "lots of rows".
Because you don't need huge to play with tables and relations. Consider a table, by itself, with no nullable columns. How many different kinds of rows can there be? Only one, as all columns must have some value as none can be null.
Every nullable column multiples by two the number of different kinds of rows possible: a row where that column is null, an row where it isn't null.
Now consider the table, not in isolation. Consider a table that is a child table: for every child that has an FK to the parent, that, is a many-to-one, there can be 0, 1 or many children. So we multiply by three times the count we got in the previous step (no rows for zero, one for exactly one, two rows for many). For any grandparent to which the parent is a many, another three.
For many-to-many relations, we can have have no relation, a one-to-one, a one-to-many, many-to-one, or a many-to-many. So for each many-to-many we can reach in a graph from the table, we multiply the rows by nine -- or just like two one-to manys. If the many-to-many also has data, we multiply by the nullability number.
Tables that we can't reach in our graph -- those that we have no direct or indirect FK to, don't multiply the rows in our table.
By recursively multiplying the each table we can reach, we can come up with the number of rows needed to provide one of each "kind", and we need no more than those to test every possible relation in our schema. And we're nowhere near huge.
By the way, in C# 3.5 you can instantiate your object's properties like so:
Person TOM=new Person
{
title = "My title", ID = 1
};
But again, properties must be public.
From the docs:
Packages are dropped into the node_modules folder under the prefix. When installing locally, this means that you can require("packagename") to load its main module, or require("packagename/lib/path/to/sub/module") to load other modules.
Global installs on Unix systems go to {prefix}/lib/node_modules. Global installs on Windows go to {prefix}/node_modules (that is, no lib folder.)
Scoped packages are installed the same way, except they are grouped together in a sub-folder of the relevant node_modules folder with the name of that scope prefix by the @ symbol, e.g. npm install @myorg/package would place the package in {prefix}/node_modules/@myorg/package. See scope for more details.
If you wish to require() a package, then install it locally.
You can get your {prefix}
with npm config get prefix
. (Useful when you installed node with nvm).
The fields of your object have in turn their fields, some of which do not implement Serializable
. In your case the offending class is TransformGroup
. How to solve it?
Serializable
transient
If you use Java and spring MVC you just need to add the following annotation to your method returning your page :
@CrossOrigin(origins = "*")
"*" is to allow your page to be accessible from anywhere. See https://developer.mozilla.org/fr/docs/Web/HTTP/Headers/Access-Control-Allow-Origin for more details about that.
Already @Abubakkar Rangara answered easy way to handle your problem
Alternative is :
String[] result = null;
if(fieldName.endsWith(",")) {
String[] result = fieldName.split(",");
for(int i = 1; i < result.length - 1; i++) {
result[0] = result[0].concat(result[i]);
}
}
In jQuery there is $.isPlainObject()
method for that:
Description: Check to see if an object is a plain object (created using "{}" or "new Object").
>
Data ExportAs in any unix-based environment, you can use the sudo
command:
$ sudo script-name
It will ask for your password (your own, not a separate root
password).
Limit The Query To Display Only The Top 3 Highest Paid Employees. : Query « Oracle PL / SQL
create table employee(
emp_no integer primary key
,lastname varchar2(20) not null
,salary number(3)
);
insert into employee(emp_no,lastname,salary)
values(1,'Tomy',2);
insert into employee(emp_no,lastname,salary)
values(2,'Jacky',3);
insert into employee(emp_no,lastname,salary)
values(3,'Joey',4);
insert into employee(emp_no,lastname,salary)
values(4,'Janey',5);
select lastname, salary
from (SELECT lastname, salary FROM employee ORDER BY salary DESC)
where rownum <= 3 ;
OUTPUT
LASTNAME SALARY
-------------------- ----------
Janey 5
Joey 4
Jacky 3
drop table employee;
Question: How to print the value of a Tensor object in TensorFlow?
Answer:
import tensorflow as tf
# Variable
x = tf.Variable([[1,2,3]])
# initialize
init = (tf.global_variables_initializer(), tf.local_variables_initializer())
# Create a session
sess = tf.Session()
# run the session
sess.run(init)
# print the value
sess.run(x)
Thowable
catches really everything even ThreadDeath which gets thrown by default to stop a thread from the now deprecated Thread.stop()
method. So by catching Throwable
you can be sure that you'll never leave the try block without at least going through your catch block, but you should be prepared to also handle OutOfMemoryError
and InternalError
or StackOverflowError
.
Catching Throwable
is most useful for outer server loops that delegate all sorts of requests to outside code but may itself never terminate to keep the service alive.
svn add --force .
This will add any unversioned file in the current directory and all versioned child directories.
Elaborating on the answer provided by Brian R. Bondy: Here's an example that shows why you can't simply size the output buffer to the number of wide characters in the source string:
#include <windows.h>
#include <stdio.h>
#include <wchar.h>
#include <string.h>
/* string consisting of several Asian characters */
wchar_t wcsString[] = L"\u9580\u961c\u9640\u963f\u963b\u9644";
int main()
{
size_t wcsChars = wcslen( wcsString);
size_t sizeRequired = WideCharToMultiByte( 950, 0, wcsString, -1,
NULL, 0, NULL, NULL);
printf( "Wide chars in wcsString: %u\n", wcsChars);
printf( "Bytes required for CP950 encoding (excluding NUL terminator): %u\n",
sizeRequired-1);
sizeRequired = WideCharToMultiByte( CP_UTF8, 0, wcsString, -1,
NULL, 0, NULL, NULL);
printf( "Bytes required for UTF8 encoding (excluding NUL terminator): %u\n",
sizeRequired-1);
}
And the output:
Wide chars in wcsString: 6
Bytes required for CP950 encoding (excluding NUL terminator): 12
Bytes required for UTF8 encoding (excluding NUL terminator): 18
now = new Date();
today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
firstOfYear = new Date(now.getFullYear(), 0, 1);
numOfWeek = Math.ceil((((today - firstOfYear) / 86400000)-1)/7);
The buffered stream classes are much more performant in practice, so much so that the NIO.2 API includes methods that specifically return these stream classes, in part to encourage you always to use buffered streams in your application.
Here is an example:
Path path = Paths.get("/myfolder/myfile.ext");
try (BufferedReader reader = Files.newBufferedReader(path)) {
// Read from the stream
String currentLine = null;
while ((currentLine = reader.readLine()) != null)
//do your code here
} catch (IOException e) {
// Handle file I/O exception...
}
You can replace this code
BufferedReader reader = Files.newBufferedReader(path);
with
BufferedReader br = new BufferedReader(new FileReader("/myfolder/myfile.ext"));
I recommend this article to learn the main uses of Java NIO and IO.
A workaround is to use a willAnswer()
method.
For example the following works (and doesn't throw a MockitoException
but actually throws a checked Exception
as required here) using BDDMockito
:
given(someObj.someMethod(stringArg1)).willAnswer( invocation -> { throw new Exception("abc msg"); });
The equivalent for plain Mockito would to use the doAnswer
method
This also works:
^([1-9]|[0-1][0-2])$
[1-9]
matches single digits between 1 and 9
[0-1][0-2]
matches double digits between 10 and 12
There are some good examples here
File filePath=new File("your_file_path");
String dir="";
if (filePath.isDirectory())
{
dir=filePath.getAbsolutePath();
}
else
{
dir=filePath.getAbsolutePath().replaceAll(filePath.getName(), "");
}
There is an alternative way to change the key of an array element when working with a full array - without changing the order of the array. It's simply to copy the array into a new array.
For instance, I was working with a mixed, multi-dimensional array that contained indexed and associative keys - and I wanted to replace the integer keys with their values, without breaking the order.
I did so by switching key/value for all numeric array entries - here: ['0'=>'foo']. Note that the order is intact.
<?php
$arr = [
'foo',
'bar'=>'alfa',
'baz'=>['a'=>'hello', 'b'=>'world'],
];
foreach($arr as $k=>$v) {
$kk = is_numeric($k) ? $v : $k;
$vv = is_numeric($k) ? null : $v;
$arr2[$kk] = $vv;
}
print_r($arr2);
Output:
Array (
[foo] =>
[bar] => alfa
[baz] => Array (
[a] => hello
[b] => world
)
)
I usually do this with classes, that seems to force the browsers to reassess all the styling.
.hiddendiv {display:none;}
.visiblediv {display:block;}
then use;
<script>
function show() {
document.getElementById('benefits').className='visiblediv';
}
function close() {
document.getElementById('benefits').className='hiddendiv';
}
</script>
Note the casing of "className" that trips me up a lot
If no other driver package worked for your obscure device go read how to make a truly universal abd and fastboot driver out of Google's USB driver. The trick is to use CompatibleID
instead of HardwareID
in the driver's INF Models section
Pure Virtual Function
try this code
#include <iostream>
using namespace std;
class aClassWithPureVirtualFunction
{
public:
virtual void sayHellow()=0;
};
class anotherClass:aClassWithPureVirtualFunction
{
public:
void sayHellow()
{
cout<<"hellow World";
}
};
int main()
{
//aClassWithPureVirtualFunction virtualObject;
/*
This not possible to create object of a class that contain pure virtual function
*/
anotherClass object;
object.sayHellow();
}
In class anotherClass remove the function sayHellow and run the code. you will get error!Because when a class contain a pure virtual function, no object can be created from that class and it is inherited then its derived class must implement that function.
Virtual function
try another code
#include <iostream>
using namespace std;
class aClassWithPureVirtualFunction
{
public:
virtual void sayHellow()
{
cout<<"from base\n";
}
};
class anotherClass:public aClassWithPureVirtualFunction
{
public:
void sayHellow()
{
cout<<"from derived \n";
}
};
int main()
{
aClassWithPureVirtualFunction *baseObject=new aClassWithPureVirtualFunction;
baseObject->sayHellow();///call base one
baseObject=new anotherClass;
baseObject->sayHellow();////call the derived one!
}
Here the sayHellow function is marked as virtual in base class.It say the compiler that try searching the function in derived class and implement the function.If not found then execute the base one.Thanks
I have some problems with jquery mobile 1.4.5. For example it seems accepting format change only passing from "option". And there are some refresh problem with the calendar using "option". For all that have the same problems I can suggest this code:
$( "#mydatepicker" ).datepicker( "option", "dateFormat", "dd/mm/yy" );
$( "#mydatepicker" ).datepicker( "setDate", new Date());
$('.ui-datepicker-calendar').hide();
One more solution is
Rails.application.routes.routes
http://hackingoff.com/blog/generate-rails-sitemap-from-routes/
Adding to @rybo111's solution, here's what a LinkedIn share would be:
<a href="http://www.linkedin.com/shareArticle?mini=true&url={articleUrl}&title={articleTitle}&summary={articleSummary}&source={articleSource}" target="_blank" class="share-popup">Share on LinkedIn</a>
and add this to your Javascript:
case "www.linkedin.com":
window_size = "width=570,height=494";
break;
As per the LinkedIn documentation: https://developer.linkedin.com/docs/share-on-linkedin (See "Customized Url" section)
For anyone who's interested, I used this in a Rails app with a LinkedIn logo, so here's my code if it might help:
<%= link_to image_tag('linkedin.png', size: "50x50"), "http://www.linkedin.com/shareArticle?mini=true&url=#{job_url(@job)}&title=#{full_title(@job.title).html_safe}&summary=#{strip_tags(@job.description)}&source=SOURCE_URL", class: "share-popup" %>
Indexing a list is done using double bracket, i.e. hypo_list[[1]]
(e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table
does not return a table but a dataframe (see value section in ?read.table
). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.
Note: In R, the index for the first entry is a 1
(not 0
like in some other languages).
Dataframes
l <- list(anscombe, iris) # put dfs in list
l[[1]] # returns anscombe dataframe
anscombe[1:2, 2] # access first two rows and second column of dataset
[1] 10 8
l[[1]][1:2, 2] # the same but selecting the dataframe from the list first
[1] 10 8
Table objects
tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2) # put tables in a list
tbl1[1:2] # access first two elements of table 1
Now with the list
l[[1]] # access first table from the list
1 2 3 4 5
9 11 12 9 9
l[[1]][1:2] # access first two elements in first table
1 2
9 11
path of pg_config in my case (MacOS)
/Library/PostgreSQL/13/bin
Execute the following in the terminal:
PATH="/Library/PostgreSQL/13/bin:$PATH"
Then
pip install psycopg2
I make another solution for dropdown. Hope this is helpfull Just add this js script
<script type="text/javascript"> jQuery("document").ready(function() {
jQuery("ul.dropdown-menu > .dropdown.parent").click(function(e) {
e.preventDefault();
e.stopPropagation();
if (jQuery(this).hasClass('open2'))
jQuery(this).removeClass('open2');
else {
jQuery(this).addClass('open2');
}
});
}); < /script>
<style type="text/css">.open2{display:block; position:relative;}</style>
You can use exec() to run a command line script (such as command line php), and if you pipe the output to a file then your script won't wait for the command to finish.
I can't quite remember the php CLI syntax, but you'd want something like:
exec("/path/to/php -f '/path/to/file.php' | '/path/to/output.txt'");
I think quite a few shared hosting servers have exec() disabled by default for security reasons, but might be worth a try.
In javascript you can do:
window.open(url, "_blank");
Starting from Java 7 you can use deleteIfExists that returns a boolean (or throw an Exception) depending on whether a file was deleted or not. This method may not be atomic with respect to other file system operations. Moreover if a file is in use by JVM/other program then on some operating system it will not be able to remove it. Every file can be converted to path via toPath
method . E.g.
File file = ...;
boolean result = Files.deleteIfExists(file.toPath()); //surround it in try catch block
There is an another mature and actively developed "player" on the javascript linting front - ESLint
:
ESLint is a tool for identifying and reporting on patterns found in ECMAScript/JavaScript code. In many ways, it is similar to JSLint and JSHint with a few exceptions:
- ESLint uses Esprima for JavaScript parsing.
- ESLint uses an AST to evaluate patterns in code.
- ESLint is completely pluggable, every single rule is a plugin and you can add more at runtime.
What really matters here is that it is extendable via custom plugins/rules. There are already multiple plugins written for different purposes. Among others, there are:
And, of course, you can use your build tool of choice to run ESLint
:
Here is another solution
Set a hidden scope variable in your html then you can use it from your controller:
<span style="display:none" >{{ formValid = myForm.$valid}}</span>
Here is the full working example:
angular.module('App', [])_x000D_
.controller('myController', function($scope) {_x000D_
$scope.userType = 'guest';_x000D_
$scope.formValid = false;_x000D_
console.info('Ctrl init, no form.');_x000D_
_x000D_
$scope.$watch('myForm', function() {_x000D_
console.info('myForm watch');_x000D_
console.log($scope.formValid);_x000D_
});_x000D_
_x000D_
$scope.isFormValid = function() {_x000D_
//test the new scope variable_x000D_
console.log('form valid?: ', $scope.formValid);_x000D_
};_x000D_
});
_x000D_
<!doctype html>_x000D_
<html ng-app="App">_x000D_
<head>_x000D_
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<form name="myForm" ng-controller="myController">_x000D_
userType: <input name="input" ng-model="userType" required>_x000D_
<span class="error" ng-show="myForm.input.$error.required">Required!</span><br>_x000D_
<tt>userType = {{userType}}</tt><br>_x000D_
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>_x000D_
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>_x000D_
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>_x000D_
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>_x000D_
_x000D_
_x000D_
/*-- Hidden Variable formValid to use in your controller --*/_x000D_
<span style="display:none" >{{ formValid = myForm.$valid}}</span>_x000D_
_x000D_
_x000D_
<br/>_x000D_
<button ng-click="isFormValid()">Check Valid</button>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
A version of Vincent Guerci's ruby / python % operator, updated for Swift 2.1:
func %(format:String, args:[CVarArgType]) -> String {
return String(format:format, arguments:args)
}
"Hello %@, This is pi : %.2f" % ["World", M_PI]
Lets see two efficient ways that deal with escaped quotes. These patterns are not designed to be concise nor aesthetic, but to be efficient.
These ways use the first character discrimination to quickly find quotes in the string without the cost of an alternation. (The idea is to discard quickly characters that are not quotes without to test the two branches of the alternation.)
Content between quotes is described with an unrolled loop (instead of a repeated alternation) to be more efficient too: [^"\\]*(?:\\.[^"\\]*)*
Obviously to deal with strings that haven't balanced quotes, you can use possessive quantifiers instead: [^"\\]*+(?:\\.[^"\\]*)*+
or a workaround to emulate them, to prevent too much backtracking. You can choose too that a quoted part can be an opening quote until the next (non-escaped) quote or the end of the string. In this case there is no need to use possessive quantifiers, you only need to make the last quote optional.
Notice: sometimes quotes are not escaped with a backslash but by repeating the quote. In this case the content subpattern looks like this: [^"]*(?:""[^"]*)*
The patterns avoid the use of a capture group and a backreference (I mean something like (["']).....\1
) and use a simple alternation but with ["']
at the beginning, in factor.
Perl like:
["'](?:(?<=")[^"\\]*(?s:\\.[^"\\]*)*"|(?<=')[^'\\]*(?s:\\.[^'\\]*)*')
(note that (?s:...)
is a syntactic sugar to switch on the dotall/singleline mode inside the non-capturing group. If this syntax is not supported you can easily switch this mode on for all the pattern or replace the dot with [\s\S]
)
(The way this pattern is written is totally "hand-driven" and doesn't take account of eventual engine internal optimizations)
ECMA script:
(?=["'])(?:"[^"\\]*(?:\\[\s\S][^"\\]*)*"|'[^'\\]*(?:\\[\s\S][^'\\]*)*')
POSIX extended:
"[^"\\]*(\\(.|\n)[^"\\]*)*"|'[^'\\]*(\\(.|\n)[^'\\]*)*'
or simply:
"([^"\\]|\\.|\\\n)*"|'([^'\\]|\\.|\\\n)*'
Your code scope (this
) will be your window
object, not your react component, and that is why setTimeout(this.setState({position: 1}), 3000)
will crash this way.
That comes from javascript not React, it is js closure
So, in order to bind your current react component scope, do this:
setTimeout(function(){this.setState({position: 1})}.bind(this), 3000);
Or if your browser supports es6 or your projs has support to compile es6 to es5, try arrow function as well, as arrow func is to fix 'this' issue:
setTimeout(()=>this.setState({position: 1}), 3000);
in my webpack.config.js (Version 1,2,3) file, I have
function isExternal(module) {
var context = module.context;
if (typeof context !== 'string') {
return false;
}
return context.indexOf('node_modules') !== -1;
}
in my plugins array
plugins: [
new CommonsChunkPlugin({
name: 'vendors',
minChunks: function(module) {
return isExternal(module);
}
}),
// Other plugins
]
Now I have a file that only adds 3rd party libs to one file as required.
If you want get more granular where you separate your vendors and entry point files:
plugins: [
new CommonsChunkPlugin({
name: 'common',
minChunks: function(module, count) {
return !isExternal(module) && count >= 2; // adjustable
}
}),
new CommonsChunkPlugin({
name: 'vendors',
chunks: ['common'],
// or if you have an key value object for your entries
// chunks: Object.keys(entry).concat('common')
minChunks: function(module) {
return isExternal(module);
}
})
]
Note that the order of the plugins matters a lot.
Also, this is going to change in version 4. When that's official, I update this answer.
Update: indexOf search change for windows users
You may do this with a for
loop instead of a while
:
max_loop=20
for ((count = 0; count < max_loop; count++)); do
if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
echo "Files Present" | mailx -s "File Present" -r [email protected] [email protected]
break
else
echo "Sleeping for half an hour" | mailx -s "Time to Sleep Now" -r [email protected] [email protected]
sleep 1800
fi
done
if [ "$count" -eq "$max_loop" ]; then
echo "Maximum number of trials reached" >&2
exit 1
fi
The Return type of the length() method of the String class is int.
public int length()
Refer http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#length()
So the maximum value of int is 2147483647.
String is considered as char array internally,So indexing is done within the maximum range. This means we cannot index the 2147483648th member.So the maximum length of String in java is 2147483647.
Primitive data type int is 4 bytes(32 bits) in java.As 1 bit (MSB) is used as a sign bit,The range is constrained within -2^31 to 2^31-1 (-2147483648 to 2147483647). We cannot use negative values for indexing.So obviously the range we can use is from 0 to 2147483647.
Re the regex in this comment, it's good, but it adds the shy hyphen only between groups of 5 non-whitespace-or-hyphen chars. That allows the last group be much longer than intended, since there's no matching group after it.
For instance, this:
'abcde12345678901234'.replace(/([^\s-]{5})([^\s-]{5})/g, '$1­$2')
...results in this:
abcde­12345678901234
Here's a version using positive lookahead to avoid that problem:
.replace(/([^\s-]{5})(?=[^\s-])/g, '$1­')
...with this result:
abcde­12345­67890­1234
Calling performSelector with an NSNumber or other NSValue will not work. Instead of using the value of the NSValue/NSNumber, it will effectively cast the pointer to an int, float, or whatever and use that.
But the solution is simple and obvious. Create the NSInvocation and call
[invocation performSelector:@selector(invoke) withObject:nil afterDelay:delay]
According to the api docs, doing:
dataFrame1.except(dataFrame2)
will return a new DataFrame containing rows in dataFrame1 but not in dataframe2.
A 2d array is simply an array of arrays. The analog for lists is simply a List
of List
s.
ArrayList<ArrayList<String>> myList = new ArrayList<ArrayList<String>>();
I'll admit, it's not a pretty solution, especially if you go for a 3 or more dimensional structure.
I realize that this question is quite old, but I had a similar problem, except my string had spaces included in it. For those that need to know how to separate a string with more than just commas:
string str = "Tom, Scott, Bob";
IList<string> names = str.Split(new string[] {","," "},
StringSplitOptions.RemoveEmptyEntries);
The StringSplitOptions removes the records that would only be a space char...
There are several tricks available for aligning the elements.
01. Using Table Trick
.container{_x000D_
display:table;_x000D_
}_x000D_
_x000D_
.left{_x000D_
background:green;_x000D_
display:table-cell;_x000D_
width:33.33vw;_x000D_
}_x000D_
_x000D_
.center{_x000D_
background:gold;_x000D_
display:table-cell;_x000D_
width:33.33vw;_x000D_
}_x000D_
_x000D_
.right{_x000D_
background:gray;_x000D_
display:table-cell;_x000D_
width:33.33vw;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="left">_x000D_
Left_x000D_
</div>_x000D_
<div class="center">_x000D_
Center_x000D_
</div>_x000D_
<div class="right">_x000D_
Right_x000D_
</div>_x000D_
</div>
_x000D_
02. Using Flex Trick
.container{_x000D_
display:flex;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
}_x000D_
_x000D_
.left{_x000D_
background:green;_x000D_
width:33.33vw;_x000D_
}_x000D_
_x000D_
.center{_x000D_
background:gold;_x000D_
width:33.33vw;_x000D_
}_x000D_
_x000D_
.right{_x000D_
background:gray;_x000D_
width:33.33vw;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="left">_x000D_
Left_x000D_
</div>_x000D_
<div class="center">_x000D_
Center_x000D_
</div>_x000D_
<div class="right">_x000D_
Right_x000D_
</div>_x000D_
</div>
_x000D_
03. Using Float Trick
.left{_x000D_
background:green;_x000D_
width:100px;_x000D_
float:left;_x000D_
}_x000D_
_x000D_
.center{_x000D_
background:gold;_x000D_
width:100px;_x000D_
float:left;_x000D_
}_x000D_
_x000D_
.right{_x000D_
background:gray;_x000D_
width:100px;_x000D_
float:left;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="left">_x000D_
Left_x000D_
</div>_x000D_
<div class="center">_x000D_
Center_x000D_
</div>_x000D_
<div class="right">_x000D_
Right_x000D_
</div>_x000D_
</div>
_x000D_
An other solution is to use the response.status function. This will give you the http status wich is returned by the ajax call.
function checkHttpStatus(url) {
$.ajax({
type: "GET",
data: {},
url: url,
error: function(response) {
alert(url + " returns a " + response.status);
}, success() {
alert(url + " Good link");
}
});
}
When message is received and your app is in background the notification is sent to the extras intent of the main activity.
You can check the extra value in the oncreate() or onresume() function of the main activity.
You can check for the fields like data, table etc ( the one specified in the notification)
for example I sent using data as the key
public void onResume(){
super.onResume();
if (getIntent().getStringExtra("data")!=null){
fromnotification=true;
Intent i = new Intent(MainActivity.this, Activity2.class);
i.putExtra("notification","notification");
startActivity(i);
}
}
i was using the tkinter messagebox but it would crash my code. i didn't want to find out why so i used the ctypes module instead.
for example:
import ctypes
ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 1)
i got that code from Arkelis
i liked that it didn't crash the code so i worked on it and added a threading so the code after would run.
example for my code
import ctypes
import threading
def MessageboxThread(buttonstyle, title, text, icon):
threading.Thread(
target=lambda: ctypes.windll.user32.MessageBoxW(buttonstyle, text, title, icon)
).start()
messagebox(0, "Your title", "Your text", 1)
for button styles and icon numbers:
## Button styles:
# 0 : OK
# 1 : OK | Cancel
# 2 : Abort | Retry | Ignore
# 3 : Yes | No | Cancel
# 4 : Yes | No
# 5 : Retry | No
# 6 : Cancel | Try Again | Continue
## To also change icon, add these values to previous number
# 16 Stop-sign icon
# 32 Question-mark icon
# 48 Exclamation-point icon
# 64 Information-sign icon consisting of an 'i' in a circle
I spent time finding a proper way. This may be useful for others.
Create a UDF and refer in the query -
http://www.geekzilla.co.uk/view5C09B52C-4600-4B66-9DD7-DCE840D64CBD.htm
I have just simplified little bit for those whose are using list of value Object. XYZ.Comonent.html
<div class="form-group">
<label for="options">Options :</label>
<div *ngFor="let option of xyzlist">
<label>
<input type="checkbox"
name="options"
value="{{option.Id}}"
(change)="onClicked(option, $event)"/>
{{option.Id}}-- {{option.checked}}
</label>
</div>
<button type="submit">Submit</button>
</div>
** XYZ.Component.ts**.
create a list -- xyzlist.
Now to get value in Componenet.ts.
xyzlist;//Just created a list
onClicked(option, event) {
console.log("event " + this.xyzlist.length);
console.log("event checked" + event.target.checked);
console.log("event checked" + event.target.value);
for (var i = 0; i < this.xyzlist.length; i++) {
console.log("test --- " + this.xyzlist[i].Id;
if (this.xyzlist[i].Id == event.target.value) {
this.xyzlist[i].checked = event.target.checked;
}
console.log("after update of checkbox" + this.xyzlist[i].checked);
}
To achieve what you are looking for you can use the viewport-percentage length vw
.
Here is a quick example I made on jsfiddle.
HTML:
<div class="square">
<h1>This is a Square</h1>
</div>
CSS:
.square {
background: #000;
width: 50vw;
height: 50vw;
}
.square h1 {
color: #fff;
}
I am sure there are many other ways to do this but this way seemed the best to me.
Thanks for the help. I've managed to get it working now so thought I would post so that the others can use to help them.
Server:
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException ex) {
System.out.println("Can't setup server on this port number. ");
}
Socket socket = null;
InputStream in = null;
OutputStream out = null;
try {
socket = serverSocket.accept();
} catch (IOException ex) {
System.out.println("Can't accept client connection. ");
}
try {
in = socket.getInputStream();
} catch (IOException ex) {
System.out.println("Can't get socket input stream. ");
}
try {
out = new FileOutputStream("M:\\test2.xml");
} catch (FileNotFoundException ex) {
System.out.println("File not found. ");
}
byte[] bytes = new byte[16*1024];
int count;
while ((count = in.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
out.close();
in.close();
socket.close();
serverSocket.close();
}
}
and the Client:
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = null;
String host = "127.0.0.1";
socket = new Socket(host, 4444);
File file = new File("M:\\test.xml");
// Get the size of the file
long length = file.length();
byte[] bytes = new byte[16 * 1024];
InputStream in = new FileInputStream(file);
OutputStream out = socket.getOutputStream();
int count;
while ((count = in.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
out.close();
in.close();
socket.close();
}
}
A simple route 4 / 100.0
or
4.0 / 100
Use nc command,
nc -zv <hostname/ip> <port/port range>
For example,
nc -zv localhost 27017-27019
or
nc -zv localhost 27017
You can also use telnet command
telnet <ip/host> port
There are a variety of ways to get the URL .m3u8
either by viewing the source of a page, looking at the Network tab in the Developer Tools in Chrome, or using a plugin such as HDL/HLS Video Downloader.
With the .m3u8 URL in hand you can then use ffmpeg
to download the video to a file like so:
$ ffmpeg -i 'https://url/to/some/file.m3u8' -bsf:a aac_adtstoasc \
-vcodec copy -c copy -crf 50 file.mp4
If you go into any of those locations, then you will find what is defined in those schema. For example, it tells you what is the data type of the ini-method key words value.
I had similar issues when trying to connect to Google's OAuth2 service.
I ended up writing the POST manually, not using WebRequest, like this:
TcpClient client = new TcpClient("accounts.google.com", 443);
Stream netStream = client.GetStream();
SslStream sslStream = new SslStream(netStream);
sslStream.AuthenticateAsClient("accounts.google.com");
{
byte[] contentAsBytes = Encoding.ASCII.GetBytes(content.ToString());
StringBuilder msg = new StringBuilder();
msg.AppendLine("POST /o/oauth2/token HTTP/1.1");
msg.AppendLine("Host: accounts.google.com");
msg.AppendLine("Content-Type: application/x-www-form-urlencoded");
msg.AppendLine("Content-Length: " + contentAsBytes.Length.ToString());
msg.AppendLine("");
Debug.WriteLine("Request");
Debug.WriteLine(msg.ToString());
Debug.WriteLine(content.ToString());
byte[] headerAsBytes = Encoding.ASCII.GetBytes(msg.ToString());
sslStream.Write(headerAsBytes);
sslStream.Write(contentAsBytes);
}
Debug.WriteLine("Response");
StreamReader reader = new StreamReader(sslStream);
while (true)
{ // Print the response line by line to the debug stream for inspection.
string line = reader.ReadLine();
if (line == null) break;
Debug.WriteLine(line);
}
The response that gets written to the response stream contains the specific error text that you're after.
In particular, my problem was that I was putting endlines between url-encoded data pieces. When I took them out, everything worked. You might be able to use a similar technique to connect to your service and read the actual response error text.
I post my final way of doing it based on the accepted answer:
@SuppressWarnings("serial")
@WebServlet("/")
@MultipartConfig
public final class DataCollectionServlet extends Controller {
private static final String UPLOAD_LOCATION_PROPERTY_KEY="upload.location";
private String uploadsDirName;
@Override
public void init() throws ServletException {
super.init();
uploadsDirName = property(UPLOAD_LOCATION_PROPERTY_KEY);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// ...
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Collection<Part> parts = req.getParts();
for (Part part : parts) {
File save = new File(uploadsDirName, getFilename(part) + "_"
+ System.currentTimeMillis());
final String absolutePath = save.getAbsolutePath();
log.debug(absolutePath);
part.write(absolutePath);
sc.getRequestDispatcher(DATA_COLLECTION_JSP).forward(req, resp);
}
}
// helpers
private static String getFilename(Part part) {
// courtesy of BalusC : http://stackoverflow.com/a/2424824/281545
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
String filename = cd.substring(cd.indexOf('=') + 1).trim()
.replace("\"", "");
return filename.substring(filename.lastIndexOf('/') + 1)
.substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
}
}
return null;
}
}
where :
@SuppressWarnings("serial")
class Controller extends HttpServlet {
static final String DATA_COLLECTION_JSP="/WEB-INF/jsp/data_collection.jsp";
static ServletContext sc;
Logger log;
// private
// "/WEB-INF/app.properties" also works...
private static final String PROPERTIES_PATH = "WEB-INF/app.properties";
private Properties properties;
@Override
public void init() throws ServletException {
super.init();
// synchronize !
if (sc == null) sc = getServletContext();
log = LoggerFactory.getLogger(this.getClass());
try {
loadProperties();
} catch (IOException e) {
throw new RuntimeException("Can't load properties file", e);
}
}
private void loadProperties() throws IOException {
try(InputStream is= sc.getResourceAsStream(PROPERTIES_PATH)) {
if (is == null)
throw new RuntimeException("Can't locate properties file");
properties = new Properties();
properties.load(is);
}
}
String property(final String key) {
return properties.getProperty(key);
}
}
and the /WEB-INF/app.properties :
upload.location=C:/_/
HTH and if you find a bug let me know
Find the folder containing the shared library libopencv_core.so.2.4 using the following command line.
sudo find / -name "libopencv_core.so.2.4*"
Then I got the result:
/usr/local/lib/libopencv_core.so.2.4.
Create a file called
/etc/ld.so.conf.d/opencv.conf
and write to it the path to the folder where the binary is stored.For example, I wrote /usr/local/lib/
to my opencv.conf
file.
Run the command line as follows.
sudo ldconfig -v
Try to run the command again.
These give you the hyperthreaded CPU count
multiprocessing.cpu_count()
os.cpu_count()
These give you the virtual machine CPU count
psutil.cpu_count()
numexpr.detect_number_of_cores()
Only matters if you works on VMs.
You should use something like this:
SELECT *
FROM (select salary2.*, rownum rnum from
(select * from salary ORDER BY salary_amount DESC) salary2
where rownum <= 2 )
WHERE rnum >= 2;
Its working for me
.line{_x000D_
width: 112px;_x000D_
height: 47px;_x000D_
border-bottom: 1px solid black;_x000D_
position: absolute;_x000D_
}
_x000D_
<div class="line"></div>
_x000D_
Here is a snippet I wrote; to ask for users' password and set it in /etc/passwd. You can manipulate it a little probably to get what you need:
echo -n " Please enter the password for the given user: "
read userPass
useradd $userAcct && echo -e "$userPass\n$userPass\n" | passwd $userAcct > /dev/null 2>&1 && echo " User account has been created." || echo " ERR -- User account creation failed!"
For those who got here looking for this configuration in .Net core this resides in the lauchSettings.json
. Just edit the port in the property "applicationUrl"
.
The file should look something like this:
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:53950/", //Here
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "index.html",
"environmentVariables": {
"Hosting:Environment": "Development"
},
}
}
}
Or you can use the GUI by double clicking in the "Properties" of your project.
Note: I had to reopen VS to make it work.
Some readers will have another issue and need this fix. read the links below. the same problem occured with visual studio 2015 with the advent of windows sdk 10 which brings up libucrt. ucrt is the windows implementation of C Runtime (CRT) aka the posix runtime library. You most likely have code that was ported from unix... Welcome to the drawback
https://github.com/lordmulder/libsndfile-MSVC/blob/master/src/sf_unistd.h
https://lists.gnu.org/archive/html/bug-gnulib/2011-09/msg00224.html
https://msdn.microsoft.com/en-us/library/y23kc048.aspx
https://blogs.msdn.microsoft.com/vcblog/2015/03/03/introducing-the-universal-crt/
I'm going to hedge this answer with this: I know it's crap.. and there's got to be a better way. (See above answers) But I tried all the suggestions here and still got nill. Ended up chasing errors, ripping the code to bits. Then I tried this:
import keyboard
keyboard.press_and_release('tab')
keyboard.press_and_release('tab')
keyboard.press_and_release('tab') #repeat as needed
keyboard.press_and_release('space')
It's pretty insufferable and you've got to make sure that you don't lose focus otherwise you'll just be tabbing and spacing on the wrong thing.
My assumption on why the other methods didn't work for me is that I'm trying to click on something the developers didn't want a bot clicking on. So I'm not clicking on it!
Both algorithms generally works like this
Step 1: take the next unsorted element from the unsorted list then
Step 2: put it in the right place in the sorted list.
One of the steps is easier for one algorithm and vice versa.
Insertion sort: We take the first element of the unsorted list, put it in the sorted list, somewhere. We know where to take the next element (the first position in the unsorted list), but it requires some work to find where to put it (somewhere). Step 1 is easy.
Selection sort: We take the element somewhere from the unsorted list, then put it in the last position of the sorted list. We need to find the next element (it most likely is not in the first position of the unsorted list, but rather, somewhere) then put it right at the end of the sorted list. Step 2 is easy
I had the same problem and I solved it as follows:
check the node-sass
version used in the current project
go to node-sass
release:
"https://github.com/sass/node-sass/releases/tag/v@.@.@" (put your node-sass version here)
check the Supported Environment table and see if your Node version exist in it
if it is not, downgrade your node version to the latest version existing in the table
I know it's not the perfect solution but I didn't find anything else in my case.
As already said, the easiest way is to use querystring.
But if you cannot, because of security reason, you should consider using cookies.
For the replacement portion, Python uses \1
the way sed and vi do, not $1
the way Perl, Java, and Javascript (amongst others) do. Furthermore, because \1
interpolates in regular strings as the character U+0001, you need to use a raw string or \escape it.
Python 3.2 (r32:88445, Jul 27 2011, 13:41:33)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> method = 'images/:id/huge'
>>> import re
>>> re.sub(':([a-z]+)', r'<span>\1</span>', method)
'images/<span>id</span>/huge'
>>>
In my case, it was something else. One day earlier I tried to install Magento using bitnami of xampp. And I deleted That Module
I opened the httpd.conf and found this line:
Include "C:/xampp/apps/magento/conf/httpd-prefix.conf"
I just commented it with #,
Now it's running fine. :)
Adding to Dmitri Chebotarev's answer, as for Laravel 5+.
After requiring the doctrine/dbal package:
composer require doctrine/dbal
You can then make a migration with nullable columns, like so:
public function up()
{
Schema::table('users', function (Blueprint $table) {
// change() tells the Schema builder that we are altering a table
$table->integer('user_id')->unsigned()->nullable()->change();
});
}
To revert the operation, do:
public function down()
{
/* turn off foreign key checks for a moment */
DB::statement('SET FOREIGN_KEY_CHECKS = 0');
/* set null values to 0 first */
DB::statement('UPDATE `users` SET `user_id` = 0 WHERE `user_id` IS NULL;');
/* alter table */
DB::statement('ALTER TABLE `users` MODIFY `user_id` INTEGER UNSIGNED NOT NULL;');
/* finally turn foreign key checks back on */
DB::statement('SET FOREIGN_KEY_CHECKS = 1');
}
There are various causes of segmentation faults, but fundamentally, you are accessing memory incorrectly. This could be caused by dereferencing a null pointer, or by trying to modify readonly memory, or by using a pointer to somewhere that is not mapped into the memory space of your process (that probably means you are trying to use a number as a pointer, or you incremented a pointer too far). On some machines, it is possible for a misaligned access via a pointer to cause the problem too - if you have an odd address and try to read an even number of bytes from it, for example (that can generate SIGBUS, instead).
I don't know if this was pointed out here. The settings for .container
width have to be set on the Bootstrap website. I personally did not have to edit or touch anything within CSS files to tune my .container
size which is 1600px. Under Customize tab, there are three sections responsible for media and the responsiveness of the web:
Besides Media queries breakpoints, which I believe most people refer to, I've also changed @container-desktop
to (1130px + @grid-gutter-width)
and @container-large-desktop
to (1530px + @grid-gutter-width)
. Now, the .container
changes its width if my browser is scaled up to ~1600px and ~1200px. Hope it can help.
It depends on the jQuery selector that you use. Since id
should be unique within the DOM, the first one would be simple:
$('#Comanda').hide();
The second one might require something more, depending on the other elements and how to uniquely identify it. If the name
of that particular input
is unique, then this would work:
$('input[name="Vizualizeaza"]').hide();
If you're using ASP.NET MVC and Web API chances are you have the Newtonsoft.Json NuGet package installed.This library has a class called JObject which allows you to pass through multiple parameters:
Api Controller:
public class ProductController : ApiController
{
[HttpPost]
public void Post(Newtonsoft.Json.Linq.JObject data)
{
System.Diagnostics.Debugger.Break();
Product product = data["product"].ToObject<Product>();
Product product2 = data["product2"].ToObject<Product>();
int someRandomNumber = data["randomNumber"].ToObject<int>();
string productName = product.ProductName;
string product2Name = product2.ProductName;
}
}
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
}
View:
<script src="~/Scripts/angular.js"></script>
<script type="text/javascript">
var myApp = angular.module("app", []);
myApp.controller('controller', function ($scope, $http) {
$scope.AddProducts = function () {
var product = {
ProductID: 0,
ProductName: "Orange",
}
var product2 = {
ProductID: 1,
ProductName: "Mango",
}
var data = {
product: product,
product2: product2,
randomNumber:12345
};
$http.post("/api/Product", data).
success(function (data, status, headers, config) {
}).
error(function (data, status, headers, config) {
alert("An error occurred during the AJAX request");
});
}
});
</script>
<div ng-app="app" ng-controller="controller">
<input type="button" ng-click="AddProducts()" value="Get Full Name" />
</div>
You can select the form like this:
$("#submit").click(function(){
var form = $(this).parents('form:first');
...
});
However, it is generally better to attach the event to the submit event of the form itself, as it will trigger even when submitting by pressing the enter key from one of the fields:
$('form#myform1').submit(function(e){
e.preventDefault(); //Prevent the normal submission action
var form = this;
// ... Handle form submission
});
To select fields inside the form, use the form context. For example:
$("input[name='somename']",form).val();
@Manish Jain, I suggest to implement the method with boolean return:
public class UserManager
{
// Additional code here...
public async Task<bool> SignIn(HttpContext httpContext, UserDbModel user)
{
// Additional code here...
// Here the real authentication against a DB or Web Services or whatever
if (user.Email != null)
return false;
ClaimsIdentity identity = new ClaimsIdentity(this.GetUserClaims(dbUserData), CookieAuthenticationDefaults.AuthenticationScheme);
ClaimsPrincipal principal = new ClaimsPrincipal(identity);
// This is for give the authentication cookie to the user when authentication condition was met
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
return true;
}
}
Now I need to connect that application from my local computer, but I don't know the JMX port number of the remote computer. Where can I find it? Or, must I restart that application with some VM parameters to specify the port number?
By default JMX does not publish on a port unless you specify the arguments from this page: How to activate JMX...
-Dcom.sun.management.jmxremote # no longer required for JDK6
-Dcom.sun.management.jmxremote.port=9010
-Dcom.sun.management.jmxremote.local.only=false # careful with security implications
-Dcom.sun.management.jmxremote.authenticate=false # careful with security implications
If you are running you should be able to access any of those system properties to see if they have been set:
if (System.getProperty("com.sun.management.jmxremote") == null) {
System.out.println("JMX remote is disabled");
} else [
String portString = System.getProperty("com.sun.management.jmxremote.port");
if (portString != null) {
System.out.println("JMX running on port "
+ Integer.parseInt(portString));
}
}
Depending on how the server is connected, you might also have to specify the following parameter. As part of the initial JMX connection, jconsole connects up to the RMI port to determine which port the JMX server is running on. When you initially start up a JMX enabled application, it looks its own hostname to determine what address to return in that initial RMI transaction. If your hostname is not in /etc/hosts
or if it is set to an incorrect interface address then you can override it with the following:
-Djava.rmi.server.hostname=<IP address>
As an aside, my SimpleJMX package allows you to define both the JMX server and the RMI port or set them both to the same port. The above port defined with com.sun.management.jmxremote.port
is actually the RMI port. This tells the client what port the JMX server is running on.
Your best bet would be to anticipate prefixes, so:
"(|(displayName=SEARCHKEY*)(displayName=ITSM - SEARCHKEY*)(displayName=alt prefix - SEARCHKEY*))"
Clunky, but I'm doing a similar thing within my organization.
You don't need to use complicated coding really!
Greyscale Hover:
-webkit-filter: grayscale(100%);
Greyscale "Hover-out":
-webkit-filter: grayscale(0%);
I simply made my css class have a separate hover class and added in the second greyscale. It's really simple if you really don't like complexity.
in your PHP file, when you echo your data use json_encode (http://php.net/manual/en/function.json-encode.php)
e.g.
<?php
//plum or data...
$output = array("data","plum");
echo json_encode($output);
?>
in your javascript code, when your ajax completes the json encoded response data can be turned into an js array like this:
$.ajax({
type: "POST",
url: "process.php",
data: somedata;
success function(json_data){
var data_array = $.parseJSON(json_data);
//access your data like this:
var plum_or_whatever = data_array['output'];.
//continue from here...
}
});
Not with CSS directly, you could set CSS properties via JavaScript based on the internal contents but in the end you would still need to be operating in the definitions of CSS.
The boto3 is looking for the credentials in the folder like
C:\ProgramData\Anaconda3\envs\tensorflow\Lib\site-packages\botocore\.aws
You should save two files in this folder credentials
and config
.
You may want to check out the general order in which boto3 searches for credentials in this link. Look under the Configuring Credentials sub heading.
If you installed pip like this:
- sudo apt install python-pip
- sudo apt install python3-pip
Uninstall them like this:
- sudo apt remove python-pip
- sudo apt remove python3-pip
I'm not sure exactly what you want, but I think it's along the lines of:
SELECT `Item`, `qty`-`BAL_QTY` as `qty` FROM ((SELECT Item, SUM(`QTY`) as qty FROM `master_table` GROUP BY `ITEM`) as A NATURAL JOIN `stock_table`) as B
Another reason can be that if you are running the service (API) and put a breakpoint in the service (and your code is stuck at some breakpoint (e.g Visual Studio solution is showing Debugging instead of Running)). and then hitting the API from the client code. So if the service code a paused on some breakpoint, you just hit F5 in VS.
There's a nice article here which discusses this point. Key things to take away are that there is no difference in table size, however some users prefer to use an empty string as it can make queries easier as there is not a NULL check to do. You just check if the string is empty. Another thing to note is what NULL means in the context of a relational database. It means that the pointer to the character field is set to 0x00 in the row's header, therefore no data to access.
Update There's a detailed article here which talks about what is actually happening on a row basis
Each row has a null bitmap for columns that allow nulls. If the row in that column is null then a bit in the bitmap is 1 else it's 0.
For variable size datatypes the acctual size is 0 bytes.
For fixed size datatype the acctual size is the default datatype size in bytes set to default value (0 for numbers, '' for chars).
the result of DBCC PAGE shows that both NULL and empty strings both take up zero bytes.
<script type="text/javascript">_x000D_
function validateForm() {_x000D_
var a = document.forms["Form"]["answer_a"].value;_x000D_
var b = document.forms["Form"]["answer_b"].value;_x000D_
var c = document.forms["Form"]["answer_c"].value;_x000D_
var d = document.forms["Form"]["answer_d"].value;_x000D_
if (a == null || a == "", b == null || b == "", c == null || c == "", d == null || d == "") {_x000D_
alert("Please Fill All Required Field");_x000D_
return false;_x000D_
}_x000D_
}_x000D_
</script>_x000D_
_x000D_
<form method="post" name="Form" onsubmit="return validateForm()" action="">_x000D_
<textarea cols="30" rows="2" name="answer_a" id="a"></textarea>_x000D_
<textarea cols="30" rows="2" name="answer_b" id="b"></textarea>_x000D_
<textarea cols="30" rows="2" name="answer_c" id="c"></textarea>_x000D_
<textarea cols="30" rows="2" name="answer_d" id="d"></textarea>_x000D_
</form>
_x000D_
SQLite has had to sacrifice other characteristics that some people find useful, such as high concurrency, fine-grained access control, a rich set of built-in functions, stored procedures, esoteric SQL language features, XML and/or Java extensions, tera- or peta-byte scalability, and so forth
Source : Appropriate Uses For SQLite
Some of the points in BadPirate's answer are only partially true:
For addSubView
point
addSubview
causes layoutSubviews to be called on the view being added, the view it’s being added to (target view), and all the subviews of the target.
It depends on the view's (target view) autoresize mask. If it has autoresize mask ON, layoutSubview will be called on each addSubview
. If it has no autoresize mask then layoutSubview will be called only when the view's (target View) frame size changes.
Example: if you created UIView programmatically (it has no autoresize mask by default), LayoutSubview will be called only when UIView frame changes not on every addSubview
.
It is through this technique that the performance of the application also increases.
For the device rotation point
Rotating a device only calls layoutSubview on the parent view (the responding viewController's primary view)
This can be true only when your VC is in the VC hierarchy (root at window.rootViewController
), well this is most common case. In iOS 5, if you create a VC, but it is not added into any another VC, then this VC would not get any noticed when device rotate. Therefore its view would not get noticed by calling layoutSubviews.
What I did with spring-data-jpa-1.3 was adding a version to xsd and lowered it to 1.2. Then the error message disappears. Like this
<beans
xmlns="http://www.springframework.org/schema/beans"
...
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
...
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.2.xsd">
Seems like it was fixed for for 1.2 but then appears again in 1.3.
This command will "dry run" delete all remote (origin
) merged branches, apart from master
. You can change that, or, add additional branches after master: grep -v for-example-your-branch-here |
git branch -r --merged |
grep origin |
grep -v '>' |
grep -v master |
xargs -L1 |
awk '{sub(/origin\//,"");print}'|
xargs git push origin --delete --dry-run
If it looks good, remove the --dry-run
. Additionally, you may like to test this on a fork first.
The Thread
class is used for creating and manipulating a thread in Windows.
A Task
represents some asynchronous operation and is part of the Task Parallel Library, a set of APIs for running tasks asynchronously and in parallel.
In the days of old (i.e. before TPL) it used to be that using the Thread
class was one of the standard ways to run code in the background or in parallel (a better alternative was often to use a ThreadPool
), however this was cumbersome and had several disadvantages, not least of which was the performance overhead of creating a whole new thread to perform a task in the background.
Nowadays using tasks and the TPL is a far better solution 90% of the time as it provides abstractions which allows far more efficient use of system resources. I imagine there are a few scenarios where you want explicit control over the thread on which you are running your code, however generally speaking if you want to run something asynchronously your first port of call should be the TPL.
on windows I made the iis development certificate trusted by using MMC (start > run > mmc), then add the certificate snapin, choosing "local computer" and accepting the defaults. Once that certificate snapip is added expand the local computer certificate tree to look under Personal, select the localhost certificate, right click > all task > export. accept all defaults in the exporting wizard.
Once that file is saved, expand trusted certificates and begin to import the cert you just exported. https://localhost
is now trusted in chrome having no security warnings.
I used this guide resolution #2 from the MSDN blog, the op also shared a link in his question about that also should using MMC but this worked for me. resolution #2
There are a few efficient ways to implement this. Let's start with required imports:
from pyspark.sql.functions import col, expr, when
You can use Hive IF
function inside expr:
new_column_1 = expr(
"""IF(fruit1 IS NULL OR fruit2 IS NULL, 3, IF(fruit1 = fruit2, 1, 0))"""
)
or when
+ otherwise
:
new_column_2 = when(
col("fruit1").isNull() | col("fruit2").isNull(), 3
).when(col("fruit1") == col("fruit2"), 1).otherwise(0)
Finally you could use following trick:
from pyspark.sql.functions import coalesce, lit
new_column_3 = coalesce((col("fruit1") == col("fruit2")).cast("int"), lit(3))
With example data:
df = sc.parallelize([
("orange", "apple"), ("kiwi", None), (None, "banana"),
("mango", "mango"), (None, None)
]).toDF(["fruit1", "fruit2"])
you can use this as follows:
(df
.withColumn("new_column_1", new_column_1)
.withColumn("new_column_2", new_column_2)
.withColumn("new_column_3", new_column_3))
and the result is:
+------+------+------------+------------+------------+
|fruit1|fruit2|new_column_1|new_column_2|new_column_3|
+------+------+------------+------------+------------+
|orange| apple| 0| 0| 0|
| kiwi| null| 3| 3| 3|
| null|banana| 3| 3| 3|
| mango| mango| 1| 1| 1|
| null| null| 3| 3| 3|
+------+------+------------+------------+------------+
A const is a compile-time constant whereas readonly allows a value to be calculated at run-time and set in the constructor or field initializer. So, a 'const' is always constant but 'readonly' is read-only once it is assigned.
Eric Lippert of the C# team has more information on different types of immutability.
Really all sql dates should be in yyyy-MM-dd format for the most accurate results.
In my case, I was using example from https://hapijs.com/
To fix the problem I replaced
server.connection({
host: 'localhost',
port: 8000
});
with
server.connection({
port: process.env.PORT || 3000
});
infinite slider adapter skeleton based on previous samples
some critical issues:
you may look at the logcat to understand whats happening in this sample
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/calendar_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:padding="5dp"
android:layout_gravity="center_horizontal"
android:text="Text Text Text"
/>
</RelativeLayout>
And then:
public class ActivityCalendar extends Activity
{
public class CalendarAdapter extends PagerAdapter
{
@Override
public int getCount()
{
return 3;
}
@Override
public boolean isViewFromObject(View view, Object object)
{
return view == ((RelativeLayout) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position)
{
LayoutInflater inflater = (LayoutInflater)ActivityCalendar.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewLayout = inflater.inflate(R.layout.layout_calendar, container, false);
viewLayout.setTag(new Integer(position));
//TextView tv = (TextView) viewLayout.findViewById(R.id.calendar_text);
//tv.setText(String.format("Text Text Text relative: %d", position));
if (!ActivityCalendar.this.scrolledOnce)
{
// fill here only first time, the rest will be overriden in pager scroll handler
switch (position)
{
case 0:
ActivityCalendar.this.setPageContent(viewLayout, globalPosition - 1);
break;
case 1:
ActivityCalendar.this.setPageContent(viewLayout, globalPosition);
break;
case 2:
ActivityCalendar.this.setPageContent(viewLayout, globalPosition + 1);
break;
}
}
((ViewPager) container).addView(viewLayout);
//Log.i("instantiateItem", String.format("position = %d", position));
return viewLayout;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object)
{
((ViewPager) container).removeView((RelativeLayout) object);
//Log.i("destroyItem", String.format("position = %d", position));
}
}
public void setPageContent(View viewLayout, int globalPosition)
{
if (viewLayout == null)
return;
TextView tv = (TextView) viewLayout.findViewById(R.id.calendar_text);
tv.setText(String.format("Text Text Text global %d", globalPosition));
}
private boolean scrolledOnce = false;
private int focusedPage = 0;
private int globalPosition = 0;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setOnPageChangeListener(new OnPageChangeListener()
{
@Override
public void onPageSelected(int position)
{
focusedPage = position;
// actual page change only when position == 1
if (position == 1)
setTitle(String.format("relative: %d, global: %d", position, globalPosition));
Log.i("onPageSelected", String.format("focusedPage/position = %d, globalPosition = %d", position, globalPosition));
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
//Log.i("onPageScrolled", String.format("position = %d, positionOffset = %f", position, positionOffset));
}
@Override
public void onPageScrollStateChanged(int state)
{
Log.i("onPageScrollStateChanged", String.format("state = %d, focusedPage = %d", state, focusedPage));
if (state == ViewPager.SCROLL_STATE_IDLE)
{
if (focusedPage == 0)
globalPosition--;
else if (focusedPage == 2)
globalPosition++;
scrolledOnce = true;
for (int i = 0; i < viewPager.getChildCount(); i++)
{
final View v = viewPager.getChildAt(i);
if (v == null)
continue;
// reveal correct child position
Integer tag = (Integer)v.getTag();
if (tag == null)
continue;
switch (tag.intValue())
{
case 0:
setPageContent(v, globalPosition - 1);
break;
case 1:
setPageContent(v, globalPosition);
break;
case 2:
setPageContent(v, globalPosition + 1);
break;
}
}
Log.i("onPageScrollStateChanged", String.format("globalPosition = %d", globalPosition));
viewPager.setCurrentItem(1, false);
}
}
});
CalendarAdapter calendarAdapter = this.new CalendarAdapter();
viewPager.setAdapter(calendarAdapter);
// center item
viewPager.setCurrentItem(1, false);
}
}
var today = new Date();
var day = today.getDay();
var daylist = ["Sunday", "Monday", "Tuesday", "Wednesday ", "Thursday", "Friday", "Saturday"];
console.log("Today is : " + daylist[day] + ".");
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();
var prepand = (hour >= 12) ? " PM " : " AM ";
hour = (hour >= 12) ? hour - 12 : hour;
if (hour === 0 && prepand === ' PM ') {
if (minute === 0 && second === 0) {
hour = 12;
prepand = ' Noon';
} else {
hour = 12;
prepand = ' PM';
}
}
if (hour === 0 && prepand === ' AM ') {
if (minute === 0 && second === 0) {
hour = 12;
prepand = ' Midnight';
} else {
hour = 12;
prepand = ' AM';
}
}
console.log("Current Time : " + hour + prepand + " : " + minute + " : " + second);
_x000D_
see how exceptions work by default if one vs more attributes are used (tracebacks omitted):
>>> raise Exception('bad thing happened')
Exception: bad thing happened
>>> raise Exception('bad thing happened', 'code is broken')
Exception: ('bad thing happened', 'code is broken')
so you might want to have a sort of "exception template", working as an exception itself, in a compatible way:
>>> nastyerr = NastyError('bad thing happened')
>>> raise nastyerr
NastyError: bad thing happened
>>> raise nastyerr()
NastyError: bad thing happened
>>> raise nastyerr('code is broken')
NastyError: ('bad thing happened', 'code is broken')
this can be done easily with this subclass
class ExceptionTemplate(Exception):
def __call__(self, *args):
return self.__class__(*(self.args + args))
# ...
class NastyError(ExceptionTemplate): pass
and if you don't like that default tuple-like representation, just add __str__
method to the ExceptionTemplate
class, like:
# ...
def __str__(self):
return ': '.join(self.args)
and you'll have
>>> raise nastyerr('code is broken')
NastyError: bad thing happened: code is broken
May be this will help some one. I have my proxy setup in python script but keep getting the error mentioned in the question.
Below is the piece of block which will take my username and password as a constant in the beginning.
if (use_proxy):
proxy = req.ProxyHandler({'https': proxy_url})
auth = req.HTTPBasicAuthHandler()
opener = req.build_opener(proxy, auth, req.HTTPHandler)
req.install_opener(opener)
If you are using corporate laptop and if you did not connect to Direct Access or office VPN then the above block will throw error. All you need to do is to connect to your org VPN and then execute your python script.
Thanks
Well, there are plenty of database tutorials online for java (what you're looking for is called JDBC). But if you are using plain servlets, you will have a class that extends HttpServlet
and inside it you will have two methods that look like
public void doPost(HttpServletRequest req, HttpServletResponse resp){
}
and
public void doGet(HttpServletRequest req, HttpServletResponse resp){
}
One of them is called to handle GET
operations and another is used to handle POST
operations. You will then use the HttpServletRequest
object to get the parameters that were passed as part of the form like so:
String name = req.getParameter("name");
Then, once you have the data from the form, it's relatively easy to add it to a database using a JDBC tutorial that is widely available on the web. I also suggest searching for a basic Java servlet tutorial to get you started. It's very easy, although there are a number of steps that need to be configured correctly.
I use the following for my HTML templates:
$(".main").empty();
var _template = '<p id="myelement">Your HTML Code</p>';
var template = $.parseHTML(_template);
var final = $(template).find("#myelement");
$(".main").append(final.html());
Note: Assuming if you are using jQuery
Swift 5
This works for cocoa
let bundleRoot = Bundle.main.bundlePath
let manager = FileManager.default
let dirEnum = manager.enumerator(atPath: bundleRoot)
while let filename = dirEnum?.nextObject() as? String {
if filename.hasSuffix(".data"){
print("Files in resource folder: \(filename)")
}
}
Maximum number of threads depends on following things:
Oracle's security model is such that when executing dynamic SQL using Execute Immediate (inside the context of a PL/SQL block or procedure), the user does not have privileges to objects or commands that are granted via role membership. Your user likely has "DBA" role or something similar. You must explicitly grant "drop table" permissions to this user. The same would apply if you were trying to select from tables in another schema (such as sys or system) - you would need to grant explicit SELECT privileges on that table to this user.
AdoptOpenJDK is a new website hosted by the java community. You can find .msi installers for OpenJDK 8 through 14 there, which will perform all the things listed in the question (Unpacking, registry keys, PATH variable updating (and JAVA_HOME), uninstaller...).
EDIT 2:
Use the Number
object's toFixed
method like this:
var num = Number(0.005) // The Number() only visualizes the type and is not needed
var roundedString = num.toFixed(2);
var rounded = Number(roundedString); // toFixed() returns a string (often suitable for printing already)
It rounds 42.0054321 to 42.01
It rounds 0.005 to 0.01
It rounds -0.005 to -0.01 (So the absolute value increases on rounding at .5 border)
Just use a bytearray()
which is a list of bytes.
Python2:
s = "ABCD"
b = bytearray()
b.extend(s)
Python3:
s = "ABCD"
b = bytearray()
b.extend(map(ord, s))
By the way, don't use str
as a variable name since that is builtin.
var user = "your name";
var s = 'hello ' + user + ', how are you doing';
Use:
a:visited {
text-decoration: none;
}
But it will only affect links that haven't been clicked on yet.
public class LoginTest extends BaseTest {
@Test
public void exampleTest( ){
// Test
}
}
Inherits from a base test class (this example is testng
rather than jUnit
, but the ActiveProfiles
is the same):
@ContextConfiguration(locations = { "classpath:spring-test-config.xml" })
@ActiveProfiles(resolver = MyActiveProfileResolver.class)
public class BaseTest extends AbstractTestNGSpringContextTests { }
MyActiveProfileResolver
can contain any logic required to determine which profile to use:
public class MyActiveProfileResolver implements ActiveProfilesResolver {
@Override
public String[] resolve(Class<?> aClass) {
// This can contain any custom logic to determine which profiles to use
return new String[] { "exampleProfile" };
}
}
This sets the profile which is then used to resolve dependencies required by the test.
You can use this:
select count(customer) as count, pets
from table
group by pets
This should work, I tried it by myself and it worked for me. If you pass True instead of false, the print dialog will appear.
this.print(false);
There is a plan to allow C/C++ libraries in the next SDK version of Android (Codename Eclair?)To date, it's not possible through the Android Java SDK. However, you can grab the HUGE open source project, roll your own libraries, and then flash your own device...but anyone who wants to use your library will have to flash your custom build as well.
You can use .empty()
, like this:
$("#foo").empty();
Remove all child nodes of the set of matched elements from the DOM.
Just small change need in test.ts
file inside src folder:
const context = require.context('./', true, /test-example\.spec\.ts$/);
Here, test-example
is the exact file name which we need to run
In the same way, if you need to test the service file only you can replace the filename like "/test-example.service"
I can see that this only for actually turning the dialogs back on. But if you are a web dev and you would like to see a way to possibly have some form of notification when these are off...in the case that you are using native alerts/confirms for validation or whatever. Check this solution to detect and notify the user https://stackoverflow.com/a/23697435/1248536
I believe you're looking for...
import config.logging_settings # @UnusedImport
Note the double space before the comment to avoid hitting other formatting warnings.
Also, depending on your IDE (if you're using one), there's probably an option to add the correct ignore rule (e.g., in Eclipse, pressing Ctrl + 1, while the cursor is over the warning, will auto-suggest @UnusedImport
).
Expanding on what leucos said in his answer, you can also print information with Ansible's humble debug
module:
- hosts: all
gather_facts: no
tasks:
- shell: ps -eo pcpu,user,args | sort -r -k1 | head -n5
register: ps
# Print the shell task's stdout.
- debug: msg={{ ps.stdout }}
# Print all contents of the shell task's output.
- debug: var=ps
You could follow these steps when you stumble upon this issue:
git remote show origin
which outputs this:
remote origin Fetch URL: <your_git_path> Push URL: <your_git_path> HEAD branch: development Remote branches: development tracked Feature2 tracked master tracked refs/remotes/origin/Feature1 stale (use 'git remote prune' to remove) Local branches configured for 'git pull': Feature2 merges with remote Feature2 development merges with remote development master merges with remote master Local refs configured for 'git push': Feature2 pushes to Feature2 (up to date) development pushes to development (up to date) master pushes to master (local out of date)
» git remote update Fetching origin From gitlab.domain.local:ProjectGroupName/ProjectName * [new branch] Feature3 -> Feature3
As you can see the new branch has been fetched from remote.
3. Finally, checkout the branch with this command
» git checkout -b Feature3 origin/Feature3 Branch Feature3 set up to track remote branch Feature3 from origin. Switched to a new branch 'Feature3'
It is not necessary to explicitly tell Git to track(using --track) the branch with remote.
The above command will set the local branch to track the remote branch from origin.
Fredrik has provided the fix, but it may be worth considering why this isn't in the framework to start with. I believe the idea is that the LINQ query operators should be side-effect-free, fitting in with a reasonably functional way of looking at the world. Clearly ForEach is exactly the opposite - a purely side-effect-based construct.
That's not to say this is a bad thing to do - just thinking about the philosophical reasons behind the decision.
I found this question when I got the same error for a different reason.
My issue was that my Gulp hadn't picked up on the fact that I had declared a new module and I needed to manually re-run Gulp.
In my case in the following environment:
3.7.5
C:\Windows
3.141.0
I needed to add the arguments --no-sandbox
and --remote-debugging-port=9222
to the ChromeOptions
object and run the code as administrator user by lunching the Powershell/cmd as administrator.
Here is the related piece of code:
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('--disable-infobars')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--no-sandbox')
options.add_argument('--remote-debugging-port=9222')
driver = webdriver.Chrome(options=options)
You can add spring-context dependency for spring jars. You will get the following jars along with it.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
if you also want web components, you can use spring-webmvc dependency.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
You can use whatever version of that you want. I have used 5.0.5.RELEASE here.
According to the documentation of the Item
property:
Sets or returns an item for a specified key in a Dictionary object.
In your case, you don't have an item whose key is 1
so doing:
s = d.Item(i)
actually creates a new key / value pair in your dictionary, and the value is empty because you have not used the optional newItem
argument.
The Dictionary also has the Items
method which allows looping over the indices:
a = d.Items
For i = 0 To d.Count - 1
s = a(i)
Next i
I experienced this exact same issue. For me, the OPTIONS request would go through, but the POST request would say "aborted." This led me to believe that the browser was never making the POST request at all. Chrome said something like "Caution provisional headers are shown" in the request headers but no response headers were shown. In the end I turned to debugging on Firefox which led me to find out my server was responding with an error and no CORS headers were present on the response. Chrome was actually receiving the response, but not allowing the response to be shown in the network view.
In the nav go View => Layout => Columns:2
(alt+shift+2
) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py
)
It appears you can also reopen the file using the command File -> New View into File
which will open the current file in a new tab
If you have multiple ports to allow in Centos 7 FIrewalld then we can use the following command.
#firewall-cmd --add-port={port number/tcp,port number/tcp} --permanent
#firewall-cmd --reload
And check the Port opened or not after reloading the firewall.
#firewall-cmd --list-port
For other configuration [Linuxwindo.com][1]
Trying using :
imageview.setFitToScreen(true);
imageview.setScaleType(ScaleType.FIT_CENTER);
This will fit your imageview to the screen with the correct ratio.
round(..)
function returning a floatThat float (double-precision in Python) is always a perfect representation of an integer, as long as it's in the range [-253..253]. (Pedants pay attention: it's not two's complement in doubles, so the range is symmetric about zero.)
See the discussion here for details.
You can use npm package array-to-tree https://github.com/alferov/array-to-tree. It's convert a plain array of nodes (with pointers to parent nodes) to a nested data structure.
Solves a problem with conversion of retrieved from a database sets of data to a nested data structure (i.e. navigation tree).
Usage:
var arrayToTree = require('array-to-tree');
var dataOne = [
{
id: 1,
name: 'Portfolio',
parent_id: undefined
},
{
id: 2,
name: 'Web Development',
parent_id: 1
},
{
id: 3,
name: 'Recent Works',
parent_id: 2
},
{
id: 4,
name: 'About Me',
parent_id: undefined
}
];
arrayToTree(dataOne);
/*
* Output:
*
* Portfolio
* Web Development
* Recent Works
* About Me
*/
Highlight the cells, format cells, select Custom then select zero.
The std::string object returned by ss.str() is a temporary object that will have a life time limited to the expression. So you cannot assign a pointer to a temporary object without getting trash.
Now, there is one exception: if you use a const reference to get the temporary object, it is legal to use it for a wider life time. For example you should do:
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
stringstream ss("this is a string\n");
string str(ss.str());
const char* cstr1 = str.c_str();
const std::string& resultstr = ss.str();
const char* cstr2 = resultstr.c_str();
cout << cstr1 // Prints correctly
<< cstr2; // No more error : cstr2 points to resultstr memory that is still alive as we used the const reference to keep it for a time.
system("PAUSE");
return 0;
}
That way you get the string for a longer time.
Now, you have to know that there is a kind of optimisation called RVO that say that if the compiler see an initialization via a function call and that function return a temporary, it will not do the copy but just make the assigned value be the temporary. That way you don't need to actually use a reference, it's only if you want to be sure that it will not copy that it's necessary. So doing:
std::string resultstr = ss.str();
const char* cstr2 = resultstr.c_str();
would be better and simpler.
I figured it out...finally found another article on it.
string start = Request.QueryString["start"];
string end = Request.QueryString["end"];
You can use
"Hello World ".replace(/\s+/g, '');
trim()
only removes trailing spaces on the string (first and last on the chain).
In this case this regExp is faster because you can remove one or more spaces at the same time.
If you change the replacement empty string to '$', the difference becomes much clearer:
var string= ' Q W E R TY ';
console.log(string.replace(/\s/g, '$')); // $$Q$$W$E$$$R$TY$
console.log(string.replace(/\s+/g, '#')); // #Q#W#E#R#TY#
Performance comparison - /\s+/g
is faster. See here: http://jsperf.com/s-vs-s
Modulus operator gives you the result in 'reduced residue system'. For example for mod 5 there are 5 integers counted: 0,1,2,3,4. In fact 19=12=5=-2=-9 (mod 7). The main difference that the answer is given by programming languages by 'reduced residue system'.
Android Lollipop introduced camera2 API and deprecated the previous camera API. However, using the deprecated API to turn on the flash still works and is much simpler than using the new API.
It seems that the new API is intended for use in dedicated full featured camera apps and that its architects didn't really consider simpler use cases such as turning on the flashlight. To do that now, one has to get a CameraManager, create a CaptureSession with a dummy Surface, and finally create and start a CaptureRequest. Exception handling, resource cleanup and long callbacks included!
To see how to turn the flashlight on Lollipop and newer, take a look at the FlashlightController in the AOSP project (try to find the newest as older use APIs that have been modified). Don't forget to set the needed permissions.
Android Marshmallow finally introduced a simple way to turn on the flash with setTorchMode.
With deferred
(another promise/deferred implementation) you can do:
// Setup 'pdrop', promise version of 'drop' method
var deferred = require('deferred');
mongoose.Collection.prototype.pdrop =
deferred.promisify(mongoose.Collection.prototype.drop);
// Drop collections:
deferred.map(['aaa','bbb','ccc'], function(name){
return conn.collection(name).pdrop()(function () {
console.log("dropped");
});
}).end(function () {
console.log("all dropped");
}, null);
The ISO C++ standard way to do it is to #include <iomanip>
and use io manipulators like std::setw
. However, that said, those io manipulators are a real pain to use even for text, and are just about unusable for formatting numbers (I assume you want your dollar amounts to line up on the decimal, have the correct number of significant digits, etc.). Even for just plain text labels, the code will look something like this for the first part of your first line:
// using standard iomanip facilities
cout << setw(20) << "Artist"
<< setw(20) << "Title"
<< setw(8) << "Price";
// ... not going to try to write the numeric formatting...
If you are able to use the Boost libraries, run (don't walk) and use the Boost.Format library instead. It is fully compatible with the standard iostreams, and it gives you all the goodness for easy formatting with printf/Posix formatting string, but without losing any of the power and convenience of iostreams themselves. For example, the first parts of your first two lines would look something like:
// using Boost.Format
cout << format("%-20s %-20s %-8s\n") % "Artist" % "Title" % "Price";
cout << format("%-20s %-20s %8.2f\n") % "Merle" % "Blue" % 12.99;
this should do it:
NSMutableArray* myArray = ....;
int i;
for(i=0; i<[myArray count]; i++) {
id element = [myArray objectAtIndex:i];
if(element == ...) {
[myArray removeObjectAtIndex:i];
i--;
}
}
hope this helps...
API level is basically the Android version. Instead of using the Android version name (eg 2.0, 2.3, 3.0, etc) an integer number is used. This number is increased with each version. Android 1.6 is API Level 4, Android 2.0 is API Level 5, Android 2.0.1 is API Level 6, and so on.
You can use css like this:
overflow-y: scroll;
overflow-x: hidden;
You can name cells. This is done by clicking the Name Box (that thing next to the formula bar which says "A1" for example) and typing a name, such as, "myvar". Now you can use that name instead of the cell reference:
= myvar*25
#{}
is for escaped string interpolation which automatically escapes the input and is thus more suitable for plain strings rather than JS objects:
script var data = #{JSON.stringify(data)}
<script>var data = {"foo":"bar"} </script>
!{}
is for unescaped code interpolation, which is more suitable for objects:
script var data = !{JSON.stringify(data)}
<script>var data = {"foo":"bar"} </script>
CAUTION: Unescaped code can be dangerous. You must be sure to sanitize any user inputs to avoid cross-site scripting (XSS).
E.g.:
{ foo: 'bar </script><script> alert("xss") //' }
will become:
<script>var data = {"foo":"bar </script><script> alert("xss") //"}</script>
Possible solution: Use .replace(/<\//g, '<\\/')
script var data = !{JSON.stringify(data).replace(/<\//g, '<\\/')}
<script>var data = {"foo":"bar<\/script><script>alert(\"xss\")//"}</script>
The idea is to prevent the attacker to:
JSON.stringify
escapes the quotes</script>
string, the replace statement will take care of ithttps://github.com/pugjs/pug/blob/355d3dae/examples/dynamicscript.pug
TRY THIS:
Cast your VARCHAR value to DATETIME and add -30 for subtraction. Also, In sql-server the format Fri, 14 Nov 2014 23:03:35 GMT was not converted to DATETIME. Try substring for it:
SELECT DATEADD(dd, -30,
CAST(SUBSTRING ('Fri, 14 Nov 2014 23:03:35 GMT', 6, 21)
AS DATETIME))
The quickest and easiest way I've found to Json-ify POJOs is to use the Gson library. This blog post gives a quick overview of using the library.
If you like the idea of Views, but are worried about performance you can get Oracle to create a cached table representing the view which oracle keeps up to date.
See materialized views
if column = None
COLUMN_OLD_VALUE
----------------
None
1
None
100
20
------------------
Use create a temptable on data frame:
sqlContext.sql("select * from tempTable where column_old_value='None' ").show()
So use : column_old_value='None'
DateTime begindate = Convert.ToDateTime("01/Jan/2018");
DateTime enddate = Convert.ToDateTime("12 Feb 2018");
while (begindate < enddate)
{
begindate= begindate.AddDays(1);
Console.WriteLine(begindate + " " + enddate);
}
Try this code.
XSSFWorkbook workbook = new XSSFWorkbook(new File(result));
XSSFSheet sheet = workbook.getSheetAt(0);
// Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
if (cell.getNumericCellValue() != 0) {
//Get date
Date date = row.getCell(0).getDateCellValue();
//Get datetime
cell.getDateCellValue()
System.out.println(date.getTime());
}
break;
}
}
}
Hope is help.
It is majorly because of weak connection between mysql client and remote mysql server.
In my case it is because of flaky VPN connection.
I have tried the methods provided by the previous answers. It works, but the main drawback of it is that the longer the sentences the larger similarity will be(to calculate the similarity I use the cosine score of the two mean embeddings of any two sentences) since the more the words the more positive semantic effects will be added to the sentence.
I thought I should change my mind and use the sentence embedding instead as studied in this paper and this.
Of course that works; when @item1 = N''
, it IS NOT NULL
.
You can define @item1
as NULL
by default at the top of your stored procedure, and then not pass in a parameter.
try this
bool focus = false;
private void Form1_Paint(object sender, PaintEventArgs e)
{
if (focus)
{
textBox1.BorderStyle = BorderStyle.None;
Pen p = new Pen(Color.Red);
Graphics g = e.Graphics;
int variance = 3;
g.DrawRectangle(p, new Rectangle(textBox1.Location.X - variance, textBox1.Location.Y - variance, textBox1.Width + variance, textBox1.Height +variance ));
}
else
{
textBox1.BorderStyle = BorderStyle.FixedSingle;
}
}
private void textBox1_Enter(object sender, EventArgs e)
{
focus = true;
this.Refresh();
}
private void textBox1_Leave(object sender, EventArgs e)
{
focus = false;
this.Refresh();
}
I had the same issue with eclipse 2019-03 (4.11.0) and I was only able to solve this by doing the debugging via remote debugging instead of directly launching it in debug mode.
There is practical difference between string.Equals
and ==
bool result = false;
object obj = "String";
string str2 = "String";
string str3 = typeof(string).Name;
string str4 = "String";
object obj2 = str3;
// Comparision between object obj and string str2 -- Com 1
result = string.Equals(obj, str2);// true
result = String.ReferenceEquals(obj, str2); // true
result = (obj == str2);// true
// Comparision between object obj and string str3 -- Com 2
result = string.Equals(obj, str3);// true
result = String.ReferenceEquals(obj, str3); // false
result = (obj == str3);// false
// Comparision between object obj and string str4 -- Com 3
result = string.Equals(obj, str4);// true
result = String.ReferenceEquals(obj, str4); // true
result = (obj == str4);// true
// Comparision between string str2 and string str3 -- Com 4
result = string.Equals(str2, str3);// true
result = String.ReferenceEquals(str2, str3); // false
result = (str2 == str3);// true
// Comparision between string str2 and string str4 -- Com 5
result = string.Equals(str2, str4);// true
result = String.ReferenceEquals(str2, str4); // true
result = (str2 == str4);// true
// Comparision between string str3 and string str4 -- Com 6
result = string.Equals(str3, str4);// true
result = String.ReferenceEquals(str3, str4); // false
result = (str3 == str4);// true
// Comparision between object obj and object obj2 -- Com 7
result = String.Equals(obj, obj2);// true
result = String.ReferenceEquals(obj, obj2); // false
result = (obj == obj2);// false
Adding Watch
obj "String" {1#} object {string}
str2 "String" {1#} string
str3 "String" {5#} string
str4 "String" {1#} string
obj2 "String" {5#} object {string}
Now look at {1#}
and {5#}
obj
, str2
, str4
and obj2
references are same.
obj
and obj2
are object type
and others are string type
object
and string
so performs a reference equality checkobject
and string
so performs a reference equality checkobject
and string
so performs a reference equality checkstring
and string
so performs a string value checkstring
and string
so performs a string value checkstring
and string
so performs a string value checkobject
and object
so performs a reference equality check
- obj and obj2 point to the different references so the result is falseOnce more a solution... Because there's always one more:
perl -i -pe 's/\r//' filename
It's nice because it's in place and works in every flavor of unix/linux I've worked with.
If MongoDB and RabbitMQ are running on the Host, then the port should already exposed as it is not within Docker.
You do not need the -p
option in order to expose ports from container to host. By default, all port are exposed. The -p
option allows you to expose a port from the container to the outside of the host.
So, my guess is that you do not need -p
at all and it should be working fine :)
ResultSet
to your main program or do your stuff in the same method.Remember that you will need to connect to running docker container. So you probably want to use tcp instead of unix socket. Check output of docker ps
command and look for running mysql containers. If you find one then use mysql command like this: mysql -h 127.0.0.1 -P <mysql_port>
(you will find port in docker ps
output).
If you can't find any running mysql container in docker ps
output then try docker images
to find mysql image name and try something like this to run it:
docker run -d -p 3306:3306 tutum/mysql
where "tutum/mysql" is image name found in docker images
.