I had similar problem. For me the fix was to import HttpModule before HttpClient Module:
import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';
.
.
.
imports: [
BrowserModule,
HttpModule,
HttpClientModule
],
I think you just need to create your volume outside docker first with a docker create -v /location --name
and then reuse it.
And by the time I used to use docker a lot, it wasn't possible to use a static docker volume with dockerfile definition so my suggestion is to try the command line (eventually with a script ) .
To check if a string does not contain any whitespaces, you can use
string.matches("^\\S*$")
Example:
"name" -> true
" " -> false
"name xxname" -> false
If you have a JS array of JSON objects:
var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];
and you want an array of objects:
// JavaScript array of JavaScript objects
var objs = s.map(JSON.parse);
// ...or for older browsers
var objs=[];
for (var i=s.length;i--;) objs[i]=JSON.parse(s[i]);
// ...or for maximum speed:
var objs = JSON.parse('['+s.join(',')+']');
See the speed tests for browser comparisons.
If you have a single JSON string representing an array of objects:
var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';
and you want an array of objects:
// JavaScript array of JavaScript objects
var objs = JSON.parse(s);
If you have an array of objects:
// A JavaScript array of JavaScript objects
var s = [{"Select":"11", "PhotoCount":"12"},{"Select":"21", "PhotoCount":"22"}];
…and you want JSON representation for it, then:
// JSON string representing an array of objects
var json = JSON.stringify(s);
…or if you want a JavaScript array of JSON strings, then:
// JavaScript array of strings (that are each a JSON object)
var jsons = s.map(JSON.stringify);
// ...or for older browsers
var jsons=[];
for (var i=s.length;i--;) jsons[i]=JSON.stringify(s[i]);
It's hard to say what your question is, but there are some alternatives.
If you mean to literally execute a request using the ICMP ping protocol, you can get an ICMP library and execute the ping request directly. Google "Python ICMP" to find things like this icmplib. You might want to look at scapy, also.
This will be much faster than using os.system("ping " + ip )
.
If you mean to generically "ping" a box to see if it's up, you can use the echo protocol on port 7.
For echo, you use the socket library to open the IP address and port 7. You write something on that port, send a carriage return ("\r\n"
) and then read the reply.
If you mean to "ping" a web site to see if the site is running, you have to use the http protocol on port 80.
For or properly checking a web server, you use urllib2 to open a specific URL. (/index.html
is always popular) and read the response.
There are still more potential meaning of "ping" including "traceroute" and "finger".
use below statement if safe_mode
is off
set_time_limit(0);
Use This [Tested]
To get numeric
SELECT column1
FROM table
WHERE Isnumeric(column1) = 1; // will return Numeric values
To get non-numeric
SELECT column1
FROM table
WHERE Isnumeric(column1) = 0; // will return non-numeric values
In case anyone is interested (even if the question does not ask for this version), in C# 2 would be: (I have edited the answer, following some suggestions)
myList.Sort(CLASS_FOR_COMPARER);
List<string> fiveElements = myList.GetRange(0, 5);
ORDER BY
is always last...
However, you need to pick the fields you ACTUALLY WANT then select only those and group by them. SELECT *
and GROUP BY Email
will give you RANDOM VALUES for all the fields but Email
. Most RDBMS will not even allow you to do this because of the issues it creates, but MySQL is the exception.
SELECT Email, COUNT(*)
FROM user_log
GROUP BY Email
HAVING COUNT(*) > 1
ORDER BY UpdateDate DESC
Apologize for resurrect this thread, but for Windows 8.x users can find my.cnf at this folder:
C:\ProgramData\MySQL\MySQL Server 5.6\my.ini
Then also can find data folder on same folder.
I had the same issue and searching the people said to add adjustPan
, while in my case adjustResize
worked.
<activity
android:name=".YOUR.ACTIVITY"
...
android:windowSoftInputMode="adjustResize"
/>
You can use string.punctuation
and any
function like this
import string
invalidChars = set(string.punctuation.replace("_", ""))
if any(char in invalidChars for char in word):
print "Invalid"
else:
print "Valid"
With this line
invalidChars = set(string.punctuation.replace("_", ""))
we are preparing a list of punctuation characters which are not allowed. As you want _
to be allowed, we are removing _
from the list and preparing new set as invalidChars
. Because lookups are faster in sets.
any
function will return True
if atleast one of the characters is in invalidChars
.
Edit: As asked in the comments, this is the regular expression solution. Regular expression taken from https://stackoverflow.com/a/336220/1903116
word = "Welcome"
import re
print "Valid" if re.match("^[a-zA-Z0-9_]*$", word) else "Invalid"
My problem was to display the record even if no or only one phone number exists (full address book). Therefore I used a LEFT JOIN which takes all records from the left, even if no corresponding exists on the right. For me this works in Microsoft Access SQL (they require the parenthesis!)
SELECT t.PhoneNumber1, t.PhoneNumber2, t.PhoneNumber3
t1.SomeOtherFieldForPhone1, t2.someOtherFieldForPhone2, t3.someOtherFieldForPhone3
FROM
(
(
Table1 AS t LEFT JOIN Table2 AS t3 ON t.PhoneNumber3 = t3.PhoneNumber
)
LEFT JOIN Table2 AS t2 ON t.PhoneNumber2 = t2.PhoneNumber
)
LEFT JOIN Table2 AS t1 ON t.PhoneNumber1 = t1.PhoneNumber;
Modify Remember like this
public class MyModel
{
public string Name { get; set; }
public bool? Remember { get; set; }
}
Use nullable bool in controller and fallback to false on null like this
[HttpPost]
public ActionResult MyAction(MyModel model)
{
model.Remember = model.Remember ?? false;
Console.WriteLine(model.Remember.ToString());
}
The best way is to include the polyfill for JSON object.
But if you insist create a method for serializing an object to JSON notation (valid values for JSON) inside the jQuery namespace, you can do something like this:
// This is a reference to JSON.stringify and provides a polyfill for old browsers.
// stringify serializes an object, array or primitive value and return it as JSON.
jQuery.stringify = (function ($) {
var _PRIMITIVE, _OPEN, _CLOSE;
if (window.JSON && typeof JSON.stringify === "function")
return JSON.stringify;
_PRIMITIVE = /string|number|boolean|null/;
_OPEN = {
object: "{",
array: "["
};
_CLOSE = {
object: "}",
array: "]"
};
//actions to execute in each iteration
function action(key, value) {
var type = $.type(value),
prop = "";
//key is not an array index
if (typeof key !== "number") {
prop = '"' + key + '":';
}
if (type === "string") {
prop += '"' + value + '"';
} else if (_PRIMITIVE.test(type)) {
prop += value;
} else if (type === "array" || type === "object") {
prop += toJson(value, type);
} else return;
this.push(prop);
}
//iterates over an object or array
function each(obj, callback, thisArg) {
for (var key in obj) {
if (obj instanceof Array) key = +key;
callback.call(thisArg, key, obj[key]);
}
}
//generates the json
function toJson(obj, type) {
var items = [];
each(obj, action, items);
return _OPEN[type] + items.join(",") + _CLOSE[type];
}
//exported function that generates the json
return function stringify(obj) {
if (!arguments.length) return "";
var type = $.type(obj);
if (_PRIMITIVE.test(type))
return (obj === null ? type : obj.toString());
//obj is array or object
return toJson(obj, type);
}
}(jQuery));
var myObject = {
"0": null,
"total-items": 10,
"undefined-prop": void(0),
sorted: true,
images: ["bg-menu.png", "bg-body.jpg", [1, 2]],
position: { //nested object literal
"x": 40,
"y": 300,
offset: [{ top: 23 }]
},
onChange: function() { return !0 },
pattern: /^bg-.+\.(?:png|jpe?g)$/i
};
var json = jQuery.stringify(myObject);
console.log(json);
You can use the function file_get_contents();
if(file_get_contents('https://example.com/example.txt')) {
//File exists
}
You probably already installed an older version of node.js using a different method, so you need to manually remove the files that are getting in brew's way.
Do brew link -n node
and manually delete those conflicting files and directories, then try brew link node
again.
you can use the UNION ALL
keyword for this.
Here is the MSDN doc to do it in T-SQL http://msdn.microsoft.com/en-us/library/ms180026.aspx
UNION ALL - combines the result set
UNION- Does something like a Set Union and doesnt output duplicate values
For the difference with an example: http://sql-plsql.blogspot.in/2010/05/difference-between-union-union-all.html
here's a nice solution for putting a rotated drawable for an imageView:
Drawable getRotateDrawable(final Bitmap b, final float angle) {
final BitmapDrawable drawable = new BitmapDrawable(getResources(), b) {
@Override
public void draw(final Canvas canvas) {
canvas.save();
canvas.rotate(angle, b.getWidth() / 2, b.getHeight() / 2);
super.draw(canvas);
canvas.restore();
}
};
return drawable;
}
usage:
Bitmap b=...
float angle=...
final Drawable rotatedDrawable = getRotateDrawable(b,angle);
root.setImageDrawable(rotatedDrawable);
another alternative:
private Drawable getRotateDrawable(final Drawable d, final float angle) {
final Drawable[] arD = { d };
return new LayerDrawable(arD) {
@Override
public void draw(final Canvas canvas) {
canvas.save();
canvas.rotate(angle, d.getBounds().width() / 2, d.getBounds().height() / 2);
super.draw(canvas);
canvas.restore();
}
};
}
also, if you wish to rotate the bitmap, but afraid of OOM, you can use an NDK solution i've made here
Yes. Thanks
Ctrl + F11 for Portrait
and
Ctrl + F12 for Landscape
You can accomplish this much more easily with a VisualBrush
and some triggers in a Style
:
<TextBox>
<TextBox.Style>
<Style TargetType="TextBox" xmlns:sys="clr-namespace:System;assembly=mscorlib">
<Style.Resources>
<VisualBrush x:Key="CueBannerBrush" AlignmentX="Left" AlignmentY="Center" Stretch="None">
<VisualBrush.Visual>
<Label Content="Search" Foreground="LightGray" />
</VisualBrush.Visual>
</VisualBrush>
</Style.Resources>
<Style.Triggers>
<Trigger Property="Text" Value="{x:Static sys:String.Empty}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
<Trigger Property="Text" Value="{x:Null}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
<Trigger Property="IsKeyboardFocused" Value="True">
<Setter Property="Background" Value="White" />
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
To increase the re-usability of this Style
, you can also create a set of attached properties to control the actual cue banner text, color, orientation etc.
Here are three possibilities:
foo = """
this is
a multi-line string.
"""
def f1(foo=foo): return iter(foo.splitlines())
def f2(foo=foo):
retval = ''
for char in foo:
retval += char if not char == '\n' else ''
if char == '\n':
yield retval
retval = ''
if retval:
yield retval
def f3(foo=foo):
prevnl = -1
while True:
nextnl = foo.find('\n', prevnl + 1)
if nextnl < 0: break
yield foo[prevnl + 1:nextnl]
prevnl = nextnl
if __name__ == '__main__':
for f in f1, f2, f3:
print list(f())
Running this as the main script confirms the three functions are equivalent. With timeit
(and a * 100
for foo
to get substantial strings for more precise measurement):
$ python -mtimeit -s'import asp' 'list(asp.f3())'
1000 loops, best of 3: 370 usec per loop
$ python -mtimeit -s'import asp' 'list(asp.f2())'
1000 loops, best of 3: 1.36 msec per loop
$ python -mtimeit -s'import asp' 'list(asp.f1())'
10000 loops, best of 3: 61.5 usec per loop
Note we need the list()
call to ensure the iterators are traversed, not just built.
IOW, the naive implementation is so much faster it isn't even funny: 6 times faster than my attempt with find
calls, which in turn is 4 times faster than a lower-level approach.
Lessons to retain: measurement is always a good thing (but must be accurate); string methods like splitlines
are implemented in very fast ways; putting strings together by programming at a very low level (esp. by loops of +=
of very small pieces) can be quite slow.
Edit: added @Jacob's proposal, slightly modified to give the same results as the others (trailing blanks on a line are kept), i.e.:
from cStringIO import StringIO
def f4(foo=foo):
stri = StringIO(foo)
while True:
nl = stri.readline()
if nl != '':
yield nl.strip('\n')
else:
raise StopIteration
Measuring gives:
$ python -mtimeit -s'import asp' 'list(asp.f4())'
1000 loops, best of 3: 406 usec per loop
not quite as good as the .find
based approach -- still, worth keeping in mind because it might be less prone to small off-by-one bugs (any loop where you see occurrences of +1 and -1, like my f3
above, should automatically trigger off-by-one suspicions -- and so should many loops which lack such tweaks and should have them -- though I believe my code is also right since I was able to check its output with other functions').
But the split-based approach still rules.
An aside: possibly better style for f4
would be:
from cStringIO import StringIO
def f4(foo=foo):
stri = StringIO(foo)
while True:
nl = stri.readline()
if nl == '': break
yield nl.strip('\n')
at least, it's a bit less verbose. The need to strip trailing \n
s unfortunately prohibits the clearer and faster replacement of the while
loop with return iter(stri)
(the iter
part whereof is redundant in modern versions of Python, I believe since 2.3 or 2.4, but it's also innocuous). Maybe worth trying, also:
return itertools.imap(lambda s: s.strip('\n'), stri)
or variations thereof -- but I'm stopping here since it's pretty much a theoretical exercise wrt the strip
based, simplest and fastest, one.
It might work to use JmDNS on Android: http://jmdns.sourceforge.net/
There are tons of zeroconf-enabled machines out there, so this would enable discovery with more than just Android devices.
Its all depend on your client data access-layer. Many ORM frameworks rely on explicitly querying the SCOPE_IDENTITY during the insert operation.
If you are in complete control over the data access layer then is arguably better to return SCOPE_IDENTITY() as an output parameter. Wrapping the return in a result set adds unnecessary meta data overhead to describe the result set, and complicates the code to process the requests result.
If you prefer a result set return, then again is arguable better to use the OUTPUT clause:
INSERT INTO MyTable (col1, col2, col3)
OUTPUT INSERTED.id, col1, col2, col3
VALUES (@col1, @col2, @col3);
This way you can get the entire inserted row back, including default and computed columns, and you get a result set containing one row for each row inserted, this working correctly with set oriented batch inserts.
Overall, I can't see a single case when returning SCOPE_IDENTITY()
as a result set would be a good practice.
In many cases, continuing to scrape data from a website even when the server is requesting you not to is unethical. However, in the cases where it isn't, you can utilize a list of public proxies in order to scrape a website with many different IP addresses.
Easiest way I know of is to use "child_process" package which comes packaged with node.
Then you can do something like:
const spawn = require("child_process").spawn;
const pythonProcess = spawn('python',["path/to/script.py", arg1, arg2, ...]);
Then all you have to do is make sure that you import sys
in your python script, and then you can access arg1
using sys.argv[1]
, arg2
using sys.argv[2]
, and so on.
To send data back to node just do the following in the python script:
print(dataToSendBack)
sys.stdout.flush()
And then node can listen for data using:
pythonProcess.stdout.on('data', (data) => {
// Do something with the data returned from python script
});
Since this allows multiple arguments to be passed to a script using spawn, you can restructure a python script so that one of the arguments decides which function to call, and the other argument gets passed to that function, etc.
Hope this was clear. Let me know if something needs clarification.
For MySQL > 5.1.11 or MariaDB
SET GLOBAL log_output = 'TABLE';
SET GLOBAL general_log = 'ON';
mysql.general_log
If you want to output to a log file:
SET GLOBAL log_output = "FILE";
SET GLOBAL general_log_file = "/path/to/your/logfile.log"
SET GLOBAL general_log = 'ON';
As mentioned by jeffmjack in comments, these settings will be forgetting before next session unless you edit the configuration files (e.g. edit /etc/mysql/my.cnf
, then restart to apply changes).
Now, if you'd like you can tail -f /var/log/mysql/mysql.log
THE C WAY
You can use gets
function found in cstdio(stdio.h in c):
#include<cstdio>
int main(){
char name[256];
gets(name); // for input
puts(name);// for printing
}
THE C++ WAY
gets
is removed in c++11.
[Recommended]:You can use getline(cin,name) which is in string.h
or cin.getline(name,256) which is in iostream
itself.
#include<iostream>
#include<string>
using namespace std;
int main(){
char name1[256];
string name2;
cin.getline(name1,256); // for input
getline(cin,name2); // for input
cout<<name1<<"\n"<<name2;// for printing
}
I very much disagree with Dianne Hackborn's response. We are bit by bit removing all singletons from our project in favor of lightweight, task scoped objects which can easiliy be re-created when you actually need them.
Singletons are a nightmare for testing and, if lazily initialized, will introduce "state indeterminism" with subtle side effects (which may suddenly surface when moving calls to getInstance()
from one scope to another). Visibility has been mentioned as another problem, and since singletons imply "global" (= random) access to shared state, subtle bugs may arise when not properly synchronized in concurrent applications.
I consider it an anti-pattern, it's a bad object-oriented style that essentially amounts to maintaining global state.
To come back to your question:
Although the app context can be considered a singleton itself, it is framework-managed and has a well defined life-cycle, scope, and access path. Hence I believe that if you do need to manage app-global state, it should go here, nowhere else. For anything else, rethink if you really need a singleton object, or if it would also be possible to rewrite your singleton class to instead instantiate small, short-lived objects that perform the task at hand.
Try this:
^[0-9]{4,6}$
{4,6}
= between 4 and 6 characters, inclusive.
No need for a function:
$assetPath : "/assets/images";
...
body {
margin: 0 auto;
background: url(#{$assetPath}/site/background.jpg) repeat-x fixed 0 0;
width: 100%; }
See the interpolation docs for details.
Suggest
>>> print vars.__doc__
vars([object]) -> dictionary
Without arguments, equivalent to locals().
With an argument, equivalent to object.__dict__.
In otherwords, it essentially just wraps __dict__
Advantages of RecyclerView over listview :
Contains ViewHolder by default.
Easy animations.
Supports horizontal , grid and staggered layouts
Advantages of listView over recyclerView :
Easy to add divider.
Can use inbuilt arrayAdapter for simple plain lists
Supports Header and footer .
Supports OnItemClickListner .
PIE.htc worked for me great (http://css3pie.com/), but with one issue:
You should write absolute path to PIE.htc. It hasn't worked for me when I used relative path.
You can set display_errors
to 0
or use the error_reporting()
function.
However, notices are annoying (I can partly sympathize) but they serve a purpose. You shouldn't be defining a constant twice, the second time won't work and the constant will remain unchanged!
This is a slight modification to the earlier answers...
There is no need for $parse
angular.directive('input', [function () {
'use strict';
var directiveDefinitionObject = {
restrict: 'E',
require: '?ngModel',
link: function postLink(scope, iElement, iAttrs, ngModelController) {
if (iAttrs.value && ngModelController) {
ngModelController.$setViewValue(iAttrs.value);
}
}
};
return directiveDefinitionObject;
}]);
Taken from The Hitchhiker's Guide to Python (Line Continuation):
When a logical line of code is longer than the accepted limit, you need to split it over multiple physical lines. The Python interpreter will join consecutive lines if the last character of the line is a backslash. This is helpful in some cases, but should usually be avoided because of its fragility: a white space added to the end of the line, after the backslash, will break the code and may have unexpected results.
A better solution is to use parentheses around your elements. Left with an unclosed parenthesis on an end-of-line the Python interpreter will join the next line until the parentheses are closed. The same behaviour holds for curly and square braces.
However, more often than not, having to split a long logical line is a sign that you are trying to do too many things at the same time, which may hinder readability.
Having that said, here's an example considering multiple imports (when exceeding line limits, defined on PEP-8), also applied to strings in general:
from app import (
app, abort, make_response, redirect, render_template, request, session
)
I wrote a small class to test which has the better performance of the two and + comes ahead of format. by a factor of 5 to 6. Try it your self
import java.io.*;
import java.util.Date;
public class StringTest{
public static void main( String[] args ){
int i = 0;
long prev_time = System.currentTimeMillis();
long time;
for( i = 0; i< 100000; i++){
String s = "Blah" + i + "Blah";
}
time = System.currentTimeMillis() - prev_time;
System.out.println("Time after for loop " + time);
prev_time = System.currentTimeMillis();
for( i = 0; i<100000; i++){
String s = String.format("Blah %d Blah", i);
}
time = System.currentTimeMillis() - prev_time;
System.out.println("Time after for loop " + time);
}
}
Running the above for different N shows that both behave linearly, but String.format
is 5-30 times slower.
The reason is that in the current implementation String.format
first parses the input with regular expressions and then fills in the parameters. Concatenation with plus, on the other hand, gets optimized by javac (not by the JIT) and uses StringBuilder.append
directly.
jQuery UI extends the jQuery native toggleClass
to take a second optional parameter: duration
toggleClass( class, [duration] )
In most browsers, this can be achieved using CSS:
*.unselectable {
-moz-user-select: -moz-none;
-khtml-user-select: none;
-webkit-user-select: none;
/*
Introduced in IE 10.
See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/
*/
-ms-user-select: none;
user-select: none;
}
For IE < 10 and Opera, you will need to use the unselectable
attribute of the element you wish to be unselectable. You can set this using an attribute in HTML:
<div id="foo" unselectable="on" class="unselectable">...</div>
Sadly this property isn't inherited, meaning you have to put an attribute in the start tag of every element inside the <div>
. If this is a problem, you could instead use JavaScript to do this recursively for an element's descendants:
function makeUnselectable(node) {
if (node.nodeType == 1) {
node.setAttribute("unselectable", "on");
}
var child = node.firstChild;
while (child) {
makeUnselectable(child);
child = child.nextSibling;
}
}
makeUnselectable(document.getElementById("foo"));
Assuming your m_Queue
contains integers:
std::queue<int>().swap(m_Queue)
Otherwise, if it contains e.g. pointers to Job
objects, then:
std::queue<Job*>().swap(m_Queue)
This way you swap an empty queue with your m_Queue
, thus m_Queue
becomes empty.
I will add my experience using saga in production system in addition to the library author's rather thorough answer.
Pro (using saga):
Testability. It's very easy to test sagas as call() returns a pure object. Testing thunks normally requires you to include a mockStore inside your test.
redux-saga comes with lots of useful helper functions about tasks. It seems to me that the concept of saga is to create some kind of background worker/thread for your app, which act as a missing piece in react redux architecture(actionCreators and reducers must be pure functions.) Which leads to next point.
Sagas offer independent place to handle all side effects. It is usually easier to modify and manage than thunk actions in my experience.
Con:
Generator syntax.
Lots of concepts to learn.
API stability. It seems redux-saga is still adding features (eg Channels?) and the community is not as big. There is a concern if the library makes a non backward compatible update some day.
I tried invalidating cache, deleting build folder and gradle sync. Also, I couldn't uninstall because the app is not visible on device. So I tried uninstalling through ADB and it worked.
adb uninstall <package_name>
In latin1 each character is exactly one byte long. In utf8 a character can consist of more than one byte. Consequently utf8 has more characters than latin1 (and the characters they do have in common aren't necessarily represented by the same byte/bytesequence).
@Html.LabelFor(model => model.SomekingStatus, "foo bar")
In my case
spring.profiles = production // remove it to fix
in application.properties was the reason
Including the + in the push spec is probably a bad idea, as it means that git will happily do a non-fast-forward push even without -f, and if the remote server is set up to accept those, you can lose history.
Try just this:
$ git config --add remote.origin.push 'refs/heads/*:refs/heads/*'
$ git config --add remote.origin.push 'refs/tags/*:refs/tags/*'
$ git config --add remote.origin.fetch 'refs/heads/*:refs/remotes/origin/*'
$ git config --add remote.origin.fetch 'refs/tags/*:refs/tags/*'
Setting the environment variable NODE_PATH to point to your global node_modules
folder.
In Windows 7 or higher the path is something like %AppData%\npm\node_modules
while in UNIX could be something like /home/sg/.npm_global/lib/node_modules/
but it depends on user configuration.
The command npm config get prefix
could help finding out which is the correct path.
In UNIX systems you can accomplish it with the following command:
export NODE_PATH=`npm config get prefix`/lib/node_modules/
The maximum of two integers a
and b
is (int)(0.5((a+b)+abs(a-b)))
. This may also work with (double)
and fabs(a-b)
for doubles (similar for floats)
I found that Apache2 (you might want to also check Apache 1.5) has a way to restrict this before uploading by dropping this in your .htaccess file:
LimitRequestBody 2097152
This restricts it to 2 megabytes (2 * 1024 * 1024) on file upload (if I did my byte math properly).
Note when you do this, the Apache error log will generate this entry when you exceed this limit on a form post or get request:
Requested content-length of 4000107 is larger than the configured limit of 2097152
And it will also display this message back in the web browser:
<h1>Request Entity Too Large</h1>
So, if you're doing AJAX form posts with something like the Malsup jQuery Form Plugin, you could trap for the H1 response like this and show an error result.
By the way, the error number returned is 413. So, you could use a directive in your .htaccess file like...
Redirect 413 413.html
...and provide a more graceful error result back.
I had this happen in Visual Studio 2015 too for an interesting reason. Just adding it here in case it happens to someone else.
I already had number of files in project and I was adding another one that would have main function in it, however when I initially added the file I made a typo in the extension (.coo instead of .cpp). I corrected that but when I was done I got this error. It turned out that Visual Studio was being smart and when file was added it decided that it is not a source file due to the initial extension.
Right-clicking on file in solution explorer and selecting Properties -> General -> ItemType and setting it to "C/C++ compiler" fixed the issue.
First Replace the MySQL dependency as given below
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
An error showing "Authentication plugin 'caching_sha2_password'" will appear. Run this command:
mysql -u root -p
ALTER USER 'username'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
Series.apply(func, convert_dtype=True, args=(), **kwds)
args : tuple
x = my_series.apply(my_function, args = (arg1,))
Another alternative is
dtColumns[index].visible = false/true;
To show or hide any column.
"What does if __name__==“__main__”:
do?" has already been answered.
Having a main()
function allows you to call its functionality if you import
the module. The main (no pun intended) benefit of this (IMHO) is that you can unit test it.
Representing complex HTML documents will be difficult and full of corner cases, but I just wanted to share a couple techniques to show how to get this kind of program started. This answer differs in that it uses data abstraction and the toJSON
method to recursively build the result
Below, html2json
is a tiny function which takes an HTML node as input and it returns a JSON string as the result. Pay particular attention to how the code is quite flat but it's still plenty capable of building a deeply nested tree structure – all possible with virtually zero complexity
// data Elem = Elem Node_x000D_
_x000D_
const Elem = e => ({_x000D_
toJSON : () => ({_x000D_
tagName: _x000D_
e.tagName,_x000D_
textContent:_x000D_
e.textContent,_x000D_
attributes:_x000D_
Array.from(e.attributes, ({name, value}) => [name, value]),_x000D_
children:_x000D_
Array.from(e.children, Elem)_x000D_
})_x000D_
})_x000D_
_x000D_
// html2json :: Node -> JSONString_x000D_
const html2json = e =>_x000D_
JSON.stringify(Elem(e), null, ' ')_x000D_
_x000D_
console.log(html2json(document.querySelector('main')))
_x000D_
<main>_x000D_
<h1 class="mainHeading">Some heading</h1>_x000D_
<ul id="menu">_x000D_
<li><a href="/a">a</a></li>_x000D_
<li><a href="/b">b</a></li>_x000D_
<li><a href="/c">c</a></li>_x000D_
</ul>_x000D_
<p>some text</p>_x000D_
</main>
_x000D_
In the previous example, the textContent
gets a little butchered. To remedy this, we introduce another data constructor, TextElem
. We'll have to map over the childNodes
(instead of children
) and choose to return the correct data type based on e.nodeType
– this gets us a littler closer to what we might need
// data Elem = Elem Node | TextElem Node_x000D_
_x000D_
const TextElem = e => ({_x000D_
toJSON: () => ({_x000D_
type:_x000D_
'TextElem',_x000D_
textContent:_x000D_
e.textContent_x000D_
})_x000D_
})_x000D_
_x000D_
const Elem = e => ({_x000D_
toJSON : () => ({_x000D_
type:_x000D_
'Elem',_x000D_
tagName: _x000D_
e.tagName,_x000D_
attributes:_x000D_
Array.from(e.attributes, ({name, value}) => [name, value]),_x000D_
children:_x000D_
Array.from(e.childNodes, fromNode)_x000D_
})_x000D_
})_x000D_
_x000D_
// fromNode :: Node -> Elem_x000D_
const fromNode = e => {_x000D_
switch (e.nodeType) {_x000D_
case 3: return TextElem(e)_x000D_
default: return Elem(e)_x000D_
}_x000D_
}_x000D_
_x000D_
// html2json :: Node -> JSONString_x000D_
const html2json = e =>_x000D_
JSON.stringify(Elem(e), null, ' ')_x000D_
_x000D_
console.log(html2json(document.querySelector('main')))
_x000D_
<main>_x000D_
<h1 class="mainHeading">Some heading</h1>_x000D_
<ul id="menu">_x000D_
<li><a href="/a">a</a></li>_x000D_
<li><a href="/b">b</a></li>_x000D_
<li><a href="/c">c</a></li>_x000D_
</ul>_x000D_
<p>some text</p>_x000D_
</main>
_x000D_
Anyway, that's just two iterations on the problem. Of course you'll have to address corner cases where they come up, but what's nice about this approach is that it gives you a lot of flexibility to encode the HTML however you wish in JSON – and without introducing too much complexity
In my experience, you could keep iterating with this technique and achieve really good results. If this answer is interesting to anyone and would like me to expand upon anything, let me know ^_^
Related: Recursive methods using JavaScript: building your own version of JSON.stringify
Unfortunately inline elements (or elements having display:inline) ignore the width property. You should use floating divs instead:
<style type="text/css">
div.f1 { float: left; width: 20px; }
div.f2 { float: left; }
div.f3 { clear: both; }
</style>
<div class="f1"></div><div class="f2">The Lazy dog</div><div class="f3"></div>
<div class="f1">AND</div><div class="f2">The Lazy cat</div><div class="f3"></div>
<div class="f1">OR</div><div class="f2">The active goldfish</div><div class="f3"></div>
Now I see you need to use spans and lists, so we need to rewrite this a little bit:
<html><head>
<style type="text/css">
span.f1 { display: block; float: left; clear: left; width: 60px; }
li { list-style-type: none; }
</style>
</head><body>
<ul>
<li><span class="f1"> </span>The lazy dog.</li>
<li><span class="f1">AND</span> The lazy cat.</li>
<li><span class="f1">OR</span> The active goldfish.</li>
</ul>
</body>
</html>
It works... Tested in IE8 (don't forget to allow javascript to run if you're testing the file from your computer) and chrome.
&
is bitwise.
&&
is logical.
&
evaluates both sides of the operation.
&&
evaluates the left side of the operation, if it's true
, it continues and evaluates the right side.
Handles spaces in filenames well — not that you should use those!
$ find . -type f -not -path '*/\.*' -printf '%TY.%Tm.%Td %THh%TM %Ta %p\n' |sort -nr |head -n 10
2017.01.28 07h00 Sat ./recent
2017.01.21 10h49 Sat ./hgb
2017.01.16 07h44 Mon ./swx
2017.01.10 18h24 Tue ./update-stations
2017.01.09 10h38 Mon ./stations.json
More find
galore can be found by following the link.
As an addendum to Don's answer, not only does groovy add a .toInteger()
method to String
s, it also adds toBigDecimal()
, toBigInteger()
, toBoolean()
, toCharacter()
, toDouble()
, toFloat()
, toList()
, and toLong()
.
In the same vein, groovy also adds is*
eqivalents to all of those that return true
if the String
in question can be parsed into the format in question.
The relevant GDK page is here.
The two structs are different. When you initialize the first struct, about 40 bytes of memory are allocated. When you initialize the second struct, about 10 bytesof memory are allocated. (Actual amount is architecture dependent)
You can use the string literals (string constants) to initalize character arrays. This is why
person p = {"John", "Doe",30};
works in the first example.
You cannot assign (in the conventional sense) a string in C.
The string literals you have ("John") are loaded into memory when your code executes. When you initialize an array with one of these literals, then the string is copied into a new memory location. In your second example, you are merely copying the pointer to (location of) the string literal. Doing something like:
char* string = "Hello";
*string = 'C'
might cause compile or runtime errors (I am not sure.) It is a bad idea because you are modifying the literal string "Hello" which, for example on a microcontroler, could be located in read-only memory.
For testing how to insert the double quotes in MySQL using the terminal, you can use the following way:
TableName(Name,DString) - > Schema
insert into TableName values("Name","My QQDoubleQuotedStringQQ")
After inserting the value you can update the value in the database with double quotes or single quotes:
update table TableName replace(Dstring, "QQ", "\"")
You can just call the Execute command.
EXEC spDoSomthing @myDate
Edit:
Since you want to return data..that's a little harder. You can use user defined functions instead that return data.
You can try this way:
$datetime = new DateTime('2010-12-30 23:21:46');
echo $datetime->format(DATE_ATOM);
just to answer your question...btw sry that i'm 9 months late:D...there's a "workaround" 4 this kind of problems. i.e.
new AlertDialog.Builder(some_class.this).setTitle("bla").setMessage("bla bla").show();
wait();
simply add wait();
and them in the OnClickListener start the class again with notify() something like this
@Override
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_LONG).show();
**notify**();
dialog.cancel();
}
the same workaround goes 4 toasts and other async calls in android
It's been late, but just want to help others if still facing an issue. I found nice JS solution here : https://github.com/google/recaptcha/issues/61#issuecomment-376484690
Here is JavaScript code using jQuery to do so:
$(document).ready(function () {
var width = $('.g-recaptcha').parent().width();
if (width < 302) {
var scale = width / 302;
$('.g-recaptcha').css('transform', 'scale(' + scale + ')');
$('.g-recaptcha').css('-webkit-transform', 'scale(' + scale + ')');
$('.g-recaptcha').css('transform-origin', '0 0');
$('.g-recaptcha').css('-webkit-transform-origin', '0 0');
}
});
IMP Note : It will support All Devices, above and bellow 320px width as well.
forward to nikobelia
For those who using jenkins to run the play book, I just added to my jenkins job before running the ansible-playbook the he environment variable ANSIBLE_HOST_KEY_CHECKING = False For instance this:
export ANSIBLE_HOST_KEY_CHECKING=False
ansible-playbook 'playbook.yml' \
--extra-vars="some vars..." \
--tags="tags_name..." -vv
If you use Java 1.5 or beyond you could use:
List<String> S = new ArrayList<String>();
s.add("My text");
for (String item : S) {
System.out.println(item);
}
If you need to convert ALL columns to strings, you can simply use:
df = df.astype(str)
This is useful if you need everything except a few columns to be strings/objects, then go back and convert the other ones to whatever you need (integer in this case):
df[["D", "E"]] = df[["D", "E"]].astype(int)
RanRag has already answered it for your specific question.
However, more generally, what you are doing with
if [[ "$string" =~ ^hello ]]
is a regex match. To do the same in Python, you would do:
import re
if re.match(r'^hello', somestring):
# do stuff
Obviously, in this case, somestring.startswith('hello')
is better.
I know that many people finding this solution simple and clear:
create table diff_timestamp (
f1 timestamp
, f2 timestamp);
insert into diff_timestamp values(systimestamp-1, systimestamp+2);
commit;
select cast(f2 as date) - cast(f1 as date) from diff_timestamp;
bingo!
The ErrorDocument
directive, when supplied a local URL path, expects the path to be fully qualified from the DocumentRoot
. In your case, this means that the actual path to the ErrorDocument
is
ErrorDocument 404 /hellothere/error/404page.html
If you stick with the design using tables the best idea will be to give an empty row with no content and specified height between each rows in the table.
You can use div to avoid this complexity. Just give a margin to each div.
A postback is triggered after a form submission, so it's related to a client action... take a look here for an explanation: ASP.NET - Is it possible to trigger a postback from server code?
and here for a solution: http://forums.asp.net/t/928411.aspx/1
If you do not want to mess with what should be the primary key, I recommend:
ROW_NUMBER
into your selection If you're using zsh and it has not been set up to read .bashrc, you need to add the Miniconda directory to the zsh shell PATH environment variable. Add this to your .zshrc
:
export PATH="/home/username/miniconda/bin:$PATH"
Make sure to replace /home/username/miniconda
with your actual path.
Save, exit the terminal and then reopen the terminal. conda
command should work.
\W
means "non word character". The pattern for whitespace characters is \s
. This is well documented in the Pattern javadoc.
I would simplify comm1x's Kotlin extension function even more:
fun Bitmap.rotate(degrees: Float) =
Bitmap.createBitmap(this, 0, 0, width, height, Matrix().apply { postRotate(degrees) }, true)
On the off chance it may help others I'll share a related anecdote.
I encountered this exact error (Invalid UTF-8 middle byte 0x3f) running a PowerShell script via the PowerShell Integrated Script Environment (ISE). The identical script, executed outside the ISE, works fine. The code uses the Confluence v3 and v5.x REST APIs and this error is logged on the Confluence v5.x server - presumably because the ISE somehow mucks with the request.
Doing college work I gathered the data I found and gave me this result:
"The input consists of a single line with multiple integers, separated by a blank space. The end of the entry is identified by the number -1, which should not be processed."
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
char numeros[100]; //vetor para armazenar a entrada dos numeros a serem convertidos
int count = 0, soma = 0;
cin.getline(numeros, 100);
system("cls"); // limpa a tela
for(int i = 0; i < 100; i++)
{
if (numeros[i] == '-') // condicao de existencia do for
i = 100;
else
{
if(numeros[i] == ' ') // condicao que ao encontrar um espaco manda o resultado dos dados lidos e zera a contagem
{
if(count == 2) // se contegem for 2 divide por 10 por nao ter casa da centena
soma = soma / 10;
if(count == 1) // se contagem for 1 divide por 100 por nao ter casa da dezena
soma = soma / 100;
cout << (char)soma; // saida das letras do codigo ascii
count = 0;
}
else
{
count ++; // contagem aumenta para saber se o numero esta na centena/dezena ou unitaria
if(count == 1)
soma = ('0' - numeros[i]) * -100; // a ideia é que o resultado de '0' - 'x' = -x (um numero inteiro)
if(count == 2)
soma = soma + ('0' - numeros[i]) * -10; // todos multiplicam por -1 para retornar um valor positivo
if(count == 3)
soma = soma + ('0' - numeros[i]) * -1; /* caso pense em entrada de valores na casa do milhar, deve-se alterar esses 3 if´s
alem de adicionar mais um para a casa do milhar. */
}
}
}
return 0;
}
The comments are in Portuguese but I think you should understand. Any questions send me a message on linkedin: https://www.linkedin.com/in/marcosfreitasds/
Homebrew
brew doctor
and address anything homebrew wants you to fixbrew install mysql
brew services restart mysql
mysql.server start
mysql_secure_installation
Select the commit you would like to roll back to and reverse the changes by clicking Reverse File
, Reverse Hunk
or Reverse Selected Lines
. Do this for all the commits after the commit you would like to roll back to also.
Right click on the commit and click on Reset current branch to this commit
.
Check out Haroopad. This is a really nice #markdown editor. It is free and available for multiple platforms. I've tried it on Mac OSX.
UPDATE as of version 5
As of version 5 it is the option headerShown
in screenOptions
Example of usage:
<Stack.Navigator
screenOptions={{
headerShown: false
}}
>
<Stack.Screen name="route-name" component={ScreenComponent} />
</Stack.Navigator>
If you want only to hide the header on 1 screen you can do this by setting the screenOptions on the screen component see below for example:
<Stack.Screen options={{headerShown: false}} name="route-name" component={ScreenComponent} />
See also the blog about version 5
UPDATE
As of version 2.0.0-alpha.36 (2019-11-07),
there is a new navigationOption: headershown
navigationOptions: {
headerShown: false,
}
https://reactnavigation.org/docs/stack-navigator#headershown
https://github.com/react-navigation/react-navigation/commit/ba6b6ae025de2d586229fa8b09b9dd5732af94bd
Old answer
I use this to hide the stack bar (notice this is the value of the second param):
{
headerMode: 'none',
navigationOptions: {
headerVisible: false,
}
}
When you use the this method it will be hidden on all screens.
In your case it will look like this:
const MainNavigation = StackNavigator({
otp: { screen: OTPlogin },
otpverify: { screen: OTPverification },
userVerified: {
screen: TabNavigator({
List: { screen: List },
Settings: { screen: Settings }
}),
}
},
{
headerMode: 'none',
navigationOptions: {
headerVisible: false,
}
}
);
To just return a list containing the most common words:
from collections import Counter
words=["i", "love", "you", "i", "you", "a", "are", "you", "you", "fine", "green"]
most_common_words= [word for word, word_count in Counter(words).most_common(3)]
print most_common_words
this prints:
['you', 'i', 'a']
the 3 in "most_common(3)
", specifies the number of items to print.
Counter(words).most_common()
returns a a list of tuples with each tuple having the word as the first member and the frequency as the second member.The tuples are ordered by the frequency of the word.
`most_common = [item for item in Counter(words).most_common()]
print(str(most_common))
[('you', 4), ('i', 2), ('a', 1), ('are', 1), ('green', 1), ('love',1), ('fine', 1)]`
"the word for word, word_counter in
", extracts only the first member of the tuple.
This can be done with a CSS hack (see the other answers), but it can also be done very easily with JavaScript.
Set the div's width to (for example) 50%, use JavaScript to check its width, and then set the height accordingly. Here's a code example using jQuery:
$(function() {_x000D_
var div = $('#dynamicheight');_x000D_
var width = div.width();_x000D_
_x000D_
div.css('height', width);_x000D_
});
_x000D_
#dynamicheight_x000D_
{_x000D_
width: 50%;_x000D_
_x000D_
/* Just for looks: */_x000D_
background-color: cornflowerblue;_x000D_
margin: 25px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="dynamicheight"></div>
_x000D_
If you want the box to scale with the browser window on resize, move the code to a function and call it on the window resize event. Here's a demonstration of that too (view example full screen and resize browser window):
$(window).ready(updateHeight);_x000D_
$(window).resize(updateHeight);_x000D_
_x000D_
function updateHeight()_x000D_
{_x000D_
var div = $('#dynamicheight');_x000D_
var width = div.width();_x000D_
_x000D_
div.css('height', width);_x000D_
}
_x000D_
#dynamicheight_x000D_
{_x000D_
width: 50%;_x000D_
_x000D_
/* Just for looks: */_x000D_
background-color: cornflowerblue;_x000D_
margin: 25px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="dynamicheight"></div>
_x000D_
-u no
doesn't show unstaged files either. -uno
works as desired and shows unstaged, but hides untracked.
This error suggest that the branch from where you want to merge changes (i.e. in you case branch-name) is not present in you local, so you should checkout the branch and fetch the local changes. Checkout to your master branch and fetch, then follow the below steps:
git checkout branch-name
git pull
git checkout new-branch-name
git merge branch-name
Scikit-learn is a machine learning library for Python which can do this job for you. Just import sklearn.linear_model module into your script.
Find the code template for Multiple Linear Regression using sklearn in Python:
import numpy as np
import matplotlib.pyplot as plt #to plot visualizations
import pandas as pd
# Importing the dataset
df = pd.read_csv(<Your-dataset-path>)
# Assigning feature and target variables
X = df.iloc[:,:-1]
y = df.iloc[:,-1]
# Use label encoders, if you have any categorical variable
from sklearn.preprocessing import LabelEncoder
labelencoder = LabelEncoder()
X['<column-name>'] = labelencoder.fit_transform(X['<column-name>'])
from sklearn.preprocessing import OneHotEncoder
onehotencoder = OneHotEncoder(categorical_features = ['<index-value>'])
X = onehotencoder.fit_transform(X).toarray()
# Avoiding the dummy variable trap
X = X[:,1:] # Usually done by the algorithm itself
#Spliting the data into test and train set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y, random_state = 0, test_size = 0.2)
# Fitting the model
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
# Predicting the test set results
y_pred = regressor.predict(X_test)
That's it. You can use this code as a template for implementing Multiple Linear Regression in any dataset. For a better understanding with an example, Visit: Linear Regression with an example
As of PowerShell 5.1 there cmdlet New-LocalUser
which could create local user account.
Example of usage:
Create a user account
New-LocalUser -Name "User02" -Description "Description of this account." -NoPassword
or Create a user account that has a password
$Password = Read-Host -AsSecureString
New-LocalUser "User03" -Password $Password -FullName "Third User" -Description "Description of this account."
or Create a user account that is connected to a Microsoft account
New-LocalUser -Name "MicrosoftAccount\usr [email protected]" -Description "Description of this account."
Use below code snippet to achieve this.:
$('#checkAll').click(function(){
$("#checkboxes input").attr('checked','checked');
});
$('#UncheckAll').click(function(){
$("#checkboxes input").attr('checked',false);
});
Or you can do the same with single check box:
$('#checkAll').click(function(e) {
if($('#checkAll').attr('checked') == 'checked') {
$("#checkboxes input").attr('checked','checked');
$('#checkAll').val('off');
} else {
$("#checkboxes input").attr('checked', false);
$('#checkAll').val('on');
}
});
For demo: http://jsfiddle.net/creativegala/hTtxe/
Let me repeat this part of question that answers here are ignoring:
Can it be done in a few lines of code, without the need to pull in a third party lib?
Cookies are read from requests with the Cookie
header. They only include a name
and value
. Because of the way paths work, multiple cookies of the same name can be sent. In NodeJS, all Cookies in as one string as they are sent in the Cookie
header. You split them with ;
. Once you have a cookie, everything to the left of the equals (if present) is the name
, and everything after is the value
. Some browsers will accept a cookie with no equal sign and presume the name blank. Whitespaces do not count as part of the cookie. Values can also be wrapped in double quotes ("
). Values can also contain =
. For example, formula=5+3=8
is a valid cookie.
/**
* @param {string} [cookieString='']
* @return {[string,string][]} String Tuple
*/
function getEntriesFromCookie(cookieString = '') {
return cookieString.split(';').map((pair) => {
const indexOfEquals = pair.indexOf('=');
let name;
let value;
if (indexOfEquals === -1) {
name = '';
value = pair.trim();
} else {
name = pair.substr(0, indexOfEquals).trim();
value = pair.substr(indexOfEquals + 1).trim();
}
const firstQuote = value.indexOf('"');
const lastQuote = value.lastIndexOf('"');
if (firstQuote !== -1 && lastQuote !== -1) {
value = value.substring(firstQuote + 1, lastQuote);
}
return [name, value];
});
}
const cookieEntries = getEntriesFromCookie(request.headers.Cookie);
const object = Object.fromEntries(cookieEntries.slice().reverse());
If you're not expecting duplicated names, then you can convert to an object which makes things easier. Then you can access like object.myCookieName
to get the value. If you are expecting duplicates, then you want to do iterate through cookieEntries
. Browsers feed cookies in descending priority, so reversing ensures the highest priority cookie appears in the object. (The .slice()
is to avoid mutation of the array.)
"Writing" cookies is done by using the Set-Cookie
header in your response. The response.headers['Set-Cookie']
object is actually an array, so you'll be pushing to it. It accepts a string but has more values than just name
and value
. The hardest part is writing the string, but this can be done in one line.
/**
* @param {Object} options
* @param {string} [options.name='']
* @param {string} [options.value='']
* @param {Date} [options.expires]
* @param {number} [options.maxAge]
* @param {string} [options.domain]
* @param {string} [options.path]
* @param {boolean} [options.secure]
* @param {boolean} [options.httpOnly]
* @param {'Strict'|'Lax'|'None'} [options.sameSite]
* @return {string}
*/
function createSetCookie(options) {
return (`${options.name || ''}=${options.value || ''}`)
+ (options.expires != null ? `; Expires=${options.expires.toUTCString()}` : '')
+ (options.maxAge != null ? `; Max-Age=${options.maxAge}` : '')
+ (options.domain != null ? `; Domain=${options.domain}` : '')
+ (options.path != null ? `; Path=${options.path}` : '')
+ (options.secure ? '; Secure' : '')
+ (options.httpOnly ? '; HttpOnly' : '')
+ (options.sameSite != null ? `; SameSite=${options.sameSite}` : '');
}
const newCookie = createSetCookie({
name: 'cookieName',
value: 'cookieValue',
path:'/',
});
response.headers['Set-Cookie'].push(newCookie);
Remember you can set multiple cookies, because you can actually set multiple Set-Cookie
headers in your request. That's why it's an array.
If you decide to use the express
, cookie-parser
, or cookie
, note they have defaults that are non-standard. Cookies parsed are always URI Decoded (percent-decoded). That means if you use a name or value that has any of the following characters: !#$%&'()*+/:<=>?@[]^`{|}
they will be handled differently with those libraries. If you're setting cookies, they are encoded with %{HEX}
. And if you're reading a cookie you have to decode them.
For example, while [email protected]
is a valid cookie, these libraries will encode it as email=name%40domain.com
. Decoding can exhibit issues if you are using the %
in your cookie. It'll get mangled. For example, your cookie that was: secretagentlevel=50%007and50%006
becomes secretagentlevel=507and506
. That's an edge case, but something to note if switching libraries.
Also, on these libraries, cookies are set with a default path=/
which means they are sent on every url request to the host.
If you want to encode or decode these values yourself, you can use encodeURIComponent
or decodeURIComponent
, respectively.
References:
Additional information:
collect_set can help to get unique values from a given column of pyspark.sql.DataFrame
df.select(F.collect_set("column").alias("column")).first()["column"]
You could try to sort descending "sort LastWriteTime -Descending" and then "select -first 1." Not sure which one is faster
How about using the wsdl /server
or wsdl /serverinterface
switches?
As far as I understand the wsdl.exe command line properties, that's what you're looking for.
- ADVANCED -
/server
Server switch has been deprecated. Please use /serverInterface instead.
Generate an abstract class for an xml web service implementation using
ASP.NET based on the contracts. The default is to generate client proxy
classes.
On the other hand: why do you want to create obsolete technology solutions? Why not create this web service as a WCF service. That's the current and more modern, much more flexible way to do this!
Marc
UPDATE:
When I use wsdl /server
on a WSDL file, I get this file created:
[WebService(Namespace="http://.......")]
public abstract partial class OneCrmServiceType : System.Web.Services.WebService
{
/// <remarks/>
[WebMethod]
public abstract void OrderCreated(......);
}
This is basically almost exactly the same code that gets generated when you add an ASMX file to your solution (in the code behind file - "yourservice.asmx.cs"). I don't think you can get any closer to creating an ASMX file from a WSDL file.
You can always add the "yourservice.asmx" manually - it doesn't really contain much:
<%@ WebService Language="C#" CodeBehind="YourService.asmx.cs"
Class="YourServiceNamespace.YourServiceClass" %>
When I
git init
a folder it doesn't create a master branch
This is true, and expected behaviour. Git will not create a master
branch until you commit something.
When I do
git --bare init
it creates the files.
A non-bare git init
will also create the same files, in a hidden .git
directory in the root of your project.
When I type
git branch master
it says "fatal: Not a valid object name: 'master'"
That is again correct behaviour. Until you commit, there is no master branch.
You haven't asked a question, but I'll answer the question I assumed you mean to ask. Add one or more files to your directory, and git add
them to prepare a commit. Then git commit
to create your initial commit and master
branch.
Below is working solution using NgModel
Add variable
public Phone:string;
In html add
<input class="input-width" [(ngModel)]="Phone" (keyup)="keyUpEvent($event)"
type="text" class="form-control" placeholder="Enter Mobile Number">
In Ts file
keyUpEvent(event: any) {
const pattern = /[0-9\+\-\ ]/;
let inputChar = String.fromCharCode(event.keyCode);
if (!pattern.test(inputChar)) {
// invalid character, prevent input
if(this.Phone.length>0)
{
this.Phone= this.Phone.substr(0,this.Phone.length-1);
}
}
}
$()['jquery']
Invoke console.log($())
and take note about jquery object fields :
If the directory is passed as a relative path and you will need to convert it to an absolute path before calling find. In the following example, the directory is passed as the first parameter to the script:
#!/bin/bash
# get absolute path
directory=`cd $1; pwd`
# print out list of files and directories
find $directory
Some great news! Since version 3.6 the cPython implementation has preserved the insertion order of dictionaries (https://mail.python.org/pipermail/python-dev/2016-September/146327.html). This means that the json library is now order preserving by default. Observe the difference in behaviour between python 3.5 and 3.6. The code:
import json
data = json.loads('{"foo":1, "bar":2, "fiddle":{"bar":2, "foo":1}}')
print(json.dumps(data, indent=4))
In py3.5 the resulting order is undefined:
{
"fiddle": {
"bar": 2,
"foo": 1
},
"bar": 2,
"foo": 1
}
In the cPython implementation of python 3.6:
{
"foo": 1,
"bar": 2,
"fiddle": {
"bar": 2,
"foo": 1
}
}
The really great news is that this has become a language specification as of python 3.7 (as opposed to an implementation detail of cPython 3.6+): https://mail.python.org/pipermail/python-dev/2017-December/151283.html
So the answer to your question now becomes: upgrade to python 3.6! :)
You can try this code
Dictionary<string,string> AllFields = new Dictionary<string,string>();
string value = (AllFields.TryGetValue(key, out index) ? AllFields[key] : null);
If the key is not present, it simply returns a null value.
I added TO_DATE
and it resolved issue.
Before modification - due to below condition i got this error
record_update_dt>='05-May-2017'
After modification - after adding to_date
, issue got resolved.
record_update_dt>=to_date('05-May-2017','DD-Mon-YYYY')
var idPost=document.getElementById("status").innerHTML;
The 'status' element does not exist in your webpage.
So document.getElementById("status") return null. While you can not use innerHTML property of NULL.
You should add a condition like this:
if(document.getElementById("status") != null){
var idPost=document.getElementById("status").innerHTML;
}
Hope this answer can help you. :)
You can add a Rectangle
patch to the matplotlib Axes.
For example (using the image from the tutorial here):
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from PIL import Image
im = Image.open('stinkbug.png')
# Create figure and axes
fig, ax = plt.subplots()
# Display the image
ax.imshow(im)
# Create a Rectangle patch
rect = patches.Rectangle((50, 100), 40, 30, linewidth=1, edgecolor='r', facecolor='none')
# Add the patch to the Axes
ax.add_patch(rect)
plt.show()
I could advise you to use Exp4j. It is easy to understand as you can see from the following example code:
Expression e = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
.variables("x", "y")
.build()
.setVariable("x", 2.3)
.setVariable("y", 3.14);
double result = e.evaluate();
Using btoa
with unescape
and encodeURIComponent
didn't work for me. Replacing all the special characters with XML/HTML entities and then converting to the base64 representation was the only way to solve this issue for me. Some code:
base64 = btoa(str.replace(/[\u00A0-\u2666]/g, function(c) {
return '&#' + c.charCodeAt(0) + ';';
}));
openssl genrsa -out mykey.pem 1024
will actually produce a public - private key pair. The pair is stored in the generated mykey.pem
file.
openssl rsa -in mykey.pem -pubout > mykey.pub
will extract the public key and print that out. Here is a link to a page that describes this better.
EDIT: Check the examples section here. To just output the public part of a private key:
openssl rsa -in key.pem -pubout -out pubkey.pem
To get a usable public key for SSH purposes, use ssh-keygen:
ssh-keygen -y -f key.pem > key.pub
Bootstrap 3 introduces responsive tables:
<div class="table-responsive">
<table class="table">
...
</table>
</div>
Bootstrap 4 is similar, but with more control via some new classes:
...responsive across all viewports ... with
.table-responsive
. Or, pick a maximum breakpoint with which to have a responsive table up to by using.table-responsive{-sm|-md|-lg|-xl}
.
Credit to Jason Bradley for providing an example:
A few things I'd like to add here:
Using the mailto URL won't work in the simulator as mail.app isn't installed on the simulator. It does work on device though.
There is a limit to the length of the mailto URL. If the URL is larger than 4096 characters, mail.app won't launch.
There is a new class in OS 3.0 that lets you send an e-mail without leaving your app. See the class MFMailComposeViewController.
I think [ ]{4}
might work in the example where you need to detect 4 spaces.
Same with the rest: [ ]{1}
, [ ]{2}
and [ ]{3}
. If you want to detect an empty string in general, ^[ ]*$
will do.
If you don't want to install the cors library and instead want to fix your original code, the other step you are missing is that Access-Control-Allow-Origin:* is wrong. When passing Authentication tokens (e.g. JWT) then you must explicitly state every url that is calling your server. You can't use "*" when doing authentication tokens.
Momentjs.com has good documentation on how to manipulate the date/time in relation to the current moment. Since Momentjs is required for the Datetimepicker, might as well use it.
var startDefault = moment().startof('day').add(1, 'minutes');
$('#startdatetime-from').datetimepicker({
defaultDate: startDefault,
language: 'en',
format: 'yyyy-MM-dd hh:mm'
});
An alternative approach would involve storing the ranges in a table, instead of embedding them in the query. You would end up with a table, call it Ranges, that looks like this:
LowerLimit UpperLimit Range
0 9 '0-9'
10 19 '10-19'
20 29 '20-29'
30 39 '30-39'
And a query that looks like this:
Select
Range as [Score Range],
Count(*) as [Number of Occurences]
from
Ranges r inner join Scores s on s.Score between r.LowerLimit and r.UpperLimit
group by Range
This does mean setting up a table, but it would be easy to maintain when the desired ranges change. No code changes necessary!
The error comes when you try to call sum(x)
and x
is a factor.
What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)
simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:
family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))
For a detailed explanation of why the intermediate as.character
step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?
Here's a simple example that waits for a tread to finish, within the same class. It also makes a call to another class in the same namespace. I included the "using" statements so it can execute as a Windows Forms form as long as you create button1.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
namespace ClassCrossCall
{
public partial class Form1 : Form
{
int number = 0; // This is an intentional problem, included
// for demonstration purposes
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
button1.Text = "Initialized";
}
private void button1_Click(object sender, EventArgs e)
{
button1.Text = "Clicked";
button1.Refresh();
Thread.Sleep(400);
List<Task> taskList = new List<Task>();
taskList.Add(Task.Factory.StartNew(() => update_thread(2000)));
taskList.Add(Task.Factory.StartNew(() => update_thread(4000)));
Task.WaitAll(taskList.ToArray());
worker.update_button(this, number);
}
public void update_thread(int ms)
{
// It's important to check the scope of all variables
number = ms; // This could be either 2000 or 4000. Race condition.
Thread.Sleep(ms);
}
}
class worker
{
public static void update_button(Form1 form, int number)
{
form.button1.Text = $"{number}";
}
}
}
java.sql.ResultSet rs;
//fill rs somehow
java.sql.Timestamp timestamp = rs.getTimestamp(1); //get first column
long milliseconds = timestamp.getTime() + (timestamp.getNanos() / 1000000);
java.util.Date date = return new java.util.Date(milliseconds);
Definitely a network/proxy thing. I connect via wifi and a corporate gateway. Deleted workspace, reinstalled GGTS - still hangs. Turn off the network - launches fine.
The solutions given here actually do not take into account multi-byte Unicode characters ("composed characters"), and could result in invalid Unicode strings.
In fact, the iOS header file which contains the declaration of substringToIndex
contains the following comment:
Hint: Use with rangeOfComposedCharacterSequencesForRange: to avoid breaking up composed characters
See how to use rangeOfComposedCharacterSequenceAtIndex:
to delete the last character correctly.
Better to use a vbs as you indicated
vbs
, which is a text file with a .vbs extension (see sample code below)vbs
vbs
to open the workbook
at the scheduled time and then either:
Private Sub Workbook_Open()
event in the ThisWorkbook
module to run code when the file is openedApplication.Run
in the vbs
to run the macroSee this example of the later approach at Running Excel on Windows Task Scheduler
sample vbs
Dim ObjExcel, ObjWB
Set ObjExcel = CreateObject("excel.application")
'vbs opens a file specified by the path below
Set ObjWB = ObjExcel.Workbooks.Open("C:\temp\rod.xlsm")
'either use the Workbook Open event (if macros are enabled), or Application.Run
ObjWB.Close False
ObjExcel.Quit
Set ObjExcel = Nothing
To do this without any headache:
git status
, let's say branch "development".git clone
the project from repository.git checkout development
.rsync
, excluding .git folder: rsync -azv --exclude '.git' gitrepo1 newrepo/gitrepo1
. You don't have to do this with rsync
of course, but it does it so smooth.The benefit of this approach: you are good to continue exactly where you left off: your older branch, unstaged changes, etc.
First, we must make a distinction between layers and tiers. Layers are the way to logically break code into components and tiers are the physical nodes to place the components on. This question explains it better: What's the difference between "Layers" and "Tiers"?
A two layer architecture is usually just a presentation layer and data store layer. These can be on 1 tier (1 machine) or 2 tiers (2 machines) to achieve better performance by distributing the work load.
A three layer architecture usually puts something between the presentation and data store layers such as a business logic layer or service layer. Again, you can put this into 1,2, or 3 tiers depending on how much money you have for hardware and how much load you expect.
Putting multiple machines in a tier will help with the robustness of the system by providing redundancy.
Below is a good example of a layered architecture:
(source: microsoft.com)
A good reference for all of this can be found here on MSDN: http://msdn.microsoft.com/en-us/library/ms978678.aspx
The <label>
tag allows you to click on the label, and it will be treated like clicking on the associated input element. There are two ways to create this association:
One way is to wrap the label element around the input element:
<label>Input here:
<input type='text' name='theinput' id='theinput'>
</label>
The other way is to use the for
attribute, giving it the ID of the associated input:
<label for="theinput">Input here:</label>
<input type='text' name='whatever' id='theinput'>
This is especially useful for use with checkboxes and buttons, since it means you can check the box by clicking on the associated text instead of having to hit the box itself.
Read more about this element in MDN.
If you don't want to add a dependency on Guava (per Michael's answer) then this comparator is equivalent:
private static Comparator<String> ALPHABETICAL_ORDER = new Comparator<String>() {
public int compare(String str1, String str2) {
int res = String.CASE_INSENSITIVE_ORDER.compare(str1, str2);
if (res == 0) {
res = str1.compareTo(str2);
}
return res;
}
};
Collections.sort(list, ALPHABETICAL_ORDER);
And I think it is just as easy to understand and code ...
The last 4 lines of the method can written more concisely as follows:
return (res != 0) ? res : str1.compareTo(str2);
You can get the Video Entry which contains the URL to the video's thumbnail. There's example code in the link. Or, if you want to parse XML, there's information here. The XML returned has a media:thumbnail
element, which contains the thumbnail's URL.
You can use Buffer.from()
to convert a string to buffer. More information on this can be found here
var buf = Buffer.from('some string', 'encoding');
for example
var buf = Buffer.from(bStr, 'utf-8');
$('.slide-link[data-slide="0"]').addClass('active');
it works down the tree
Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
From the answer of @DevWL, I got "Undefined offset ..." at
if ($j<($num_fields-1)) { $data.= ','; }
I made some changes to:
class DBbackup {
public $suffix;
public $dirs;
protected $dbInstance;
public function __construct() {
try{
$this->dbInstance = new PDO("mysql:host=".$dbhost.";dbname=".$dbname,
$username, $password);
} catch(Exception $e) {
die("Error ".$e->getMessage());
}
$this->suffix = date('Ymd_His');
}
public function backup($tables = '*'){
$output = "-- database backup - ".date('Y-m-d H:i:s').PHP_EOL;
$output .= "SET NAMES utf8;".PHP_EOL;
$output .= "SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';".PHP_EOL;
$output .= "SET foreign_key_checks = 0;".PHP_EOL;
$output .= "SET AUTOCOMMIT = 0;".PHP_EOL;
$output .= "START TRANSACTION;".PHP_EOL;
//get all table names
if($tables == '*') {
$tables = [];
$query = $this->dbInstance->prepare('SHOW TABLES');
$query->execute();
while($row = $query->fetch(PDO::FETCH_NUM)) {
$tables[] = $row[0];
}
$query->closeCursor();
}
else {
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
foreach($tables as $table) {
$query = $this->dbInstance->prepare("SELECT * FROM `$table`");
$query->execute();
$output .= "DROP TABLE IF EXISTS `$table`;".PHP_EOL;
$query2 = $this->dbInstance->prepare("SHOW CREATE TABLE `$table`");
$query2->execute();
$row2 = $query2->fetch(PDO::FETCH_NUM);
$query2->closeCursor();
$output .= PHP_EOL.$row2[1].";".PHP_EOL;
while($row = $query->fetch(PDO::FETCH_NUM)) {
$output .= "INSERT INTO `$table` VALUES(";
for($j=0; $j<count($row); $j++) {
$row[$j] = addslashes($row[$j]);
$row[$j] = str_replace("\n","\\n",$row[$j]);
if (isset($row[$j]))
$output .= "'".$row[$j]."'";
else $output .= "''";
if ($j<(count($row)-1))
$output .= ',';
}
$output .= ");".PHP_EOL;
}
}
$output .= PHP_EOL.PHP_EOL;
$output .= "COMMIT;";
//save filename
$filename = 'db_backup_'.$this->suffix.'.sql';
$this->writeUTF8filename($filename,$output);
}
private function writeUTF8filename($fn,$c){ /* save as utf8 encoding */
$f=fopen($fn,"w+");
# Now UTF-8 - Add byte order mark
fwrite($f, pack("CCC",0xef,0xbb,0xbf));
fwrite($f,$c);
fclose($f);
}
}
And usage example:
$Backup = new DBbackup();
$Backup->backup();
This works great on MySQL 10.1.34-MariaDB , PHP : 7.2.7
what about changing the position: relative on your #content #text div to position: absolute
#content #text {
position:absolute;
width:950px;
height:215px;
color:red;
}
then you can use the css properties left and top to position within the #content div
You can use npm uninstall <package-name>
will remove it from your package.json file and from node_modules.
If you do ng help
command, you will see that there is no ng remove/delete
supported command. So, basically you cannot revert the ng add
behavior yet.
Try this:
void drawInitialNim(int num1, int num2, int num3){
int board[3][50] = {0}; // This is a local variable. It is not possible to use it after returning from this function.
int i, j, k;
for(i=0; i<num1; i++)
board[0][i] = 'O';
for(i=0; i<num2; i++)
board[1][i] = 'O';
for(i=0; i<num3; i++)
board[2][i] = 'O';
for (j=0; j<3;j++) {
for (k=0; k<50; k++) {
if(board[j][k] != 0)
printf("%c", board[j][k]);
}
printf("\n");
}
}
The full URL is available as request.url
, and the query string is available as request.query_string.decode()
.
Here's an example:
from flask import request
@app.route('/adhoc_test/')
def adhoc_test():
return request.query_string
To access an individual known param passed in the query string, you can use request.args.get('param')
. This is the "right" way to do it, as far as I know.
ETA: Before you go further, you should ask yourself why you want the query string. I've never had to pull in the raw string - Flask has mechanisms for accessing it in an abstracted way. You should use those unless you have a compelling reason not to.
Just install http-server globally
npm install -g http-server
where ever you need to run a html file run the command http-server
For ex: your html file is in /home/project/index.html
you can do /home/project/$ http-server
That will give you a link to accessyour webpages:
http-server
Starting up http-server, serving ./
Available on:
http://127.0.0.1:8080
http://192.168.0.106:8080
Wow, from all the framework-promotional answers you'd think this was something JavaScript made incredibly difficult. It isn't really.
var xhr= new XMLHttpRequest();
xhr.open('GET', 'x.html', true);
xhr.onreadystatechange= function() {
if (this.readyState!==4) return;
if (this.status!==200) return; // or whatever error handling you want
document.getElementById('y').innerHTML= this.responseText;
};
xhr.send();
If you need IE<8 compatibility, do this first to bring those browsers up to speed:
if (!window.XMLHttpRequest && 'ActiveXObject' in window) {
window.XMLHttpRequest= function() {
return new ActiveXObject('MSXML2.XMLHttp');
};
}
Note that loading content into the page with scripts will make that content invisible to clients without JavaScript available, such as search engines. Use with care, and consider server-side includes if all you want is to put data in a common shared file.
I wrote a dom adapter for my jackson based json processing framework long time ago. It uses the nu.xom library. The resulting dom tree works with the java xpath and xslt facilities. I made some implementation choices that are pretty straightforward. For example the root node is always called "root", arrays go into an ol node with li sub elements (like in html), and everything else is just a sub node with a primitive value or another object node.
Usage:
JsonObject sampleJson = sampleJson();
org.w3c.dom.Document domNode = JsonXmlConverter.getW3cDocument(sampleJson, "root");
There is and it is not dependent on post build events.
Add the file to your project, then in the file properties select under "Copy to Output Directory" either "Copy Always" or "Copy if Newer".
See MSDN.
Bootstrap 3 example with side by side buttons below the content
.panel-heading {_x000D_
display: inline-block;_x000D_
}_x000D_
_x000D_
.panel-group .panel+.panel {_x000D_
margin: 0;_x000D_
border: 0;_x000D_
}_x000D_
_x000D_
.panel {_x000D_
border: 0 !important;_x000D_
-webkit-box-shadow: none !important;_x000D_
box-shadow: none !important;_x000D_
background-color: transparent !important;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>_x000D_
_x000D_
_x000D_
<div class="panel-group" id="accordion">_x000D_
<div class="panel panel-default">_x000D_
<div id="collapse1" class="panel-collapse collapse in">_x000D_
<div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,_x000D_
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,_x000D_
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="panel panel-default">_x000D_
<div id="collapse2" class="panel-collapse collapse">_x000D_
<div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,_x000D_
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,_x000D_
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="panel panel-default">_x000D_
<div id="collapse3" class="panel-collapse collapse">_x000D_
<div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,_x000D_
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,_x000D_
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="panel-heading">_x000D_
<h4 class="panel-title">_x000D_
<a data-toggle="collapse" data-parent="#accordion" href="#collapse1">Collapsible Group 1</a>_x000D_
</h4>_x000D_
</div>_x000D_
<div class="panel-heading">_x000D_
<h4 class="panel-title">_x000D_
<a data-toggle="collapse" data-parent="#accordion" href="#collapse2">Collapsible Group 2</a>_x000D_
</h4>_x000D_
</div>_x000D_
<div class="panel-heading">_x000D_
<h4 class="panel-title">_x000D_
<a data-toggle="collapse" data-parent="#accordion" href="#collapse3">Collaple Group 3</a>_x000D_
</h4>_x000D_
</div>
_x000D_
Bootstrap 3 example with side by side buttons above the content
.panel-heading {_x000D_
display: inline-block;_x000D_
}_x000D_
_x000D_
.panel-group .panel+.panel {_x000D_
margin: 0;_x000D_
border: 0;_x000D_
}_x000D_
_x000D_
.panel {_x000D_
border: 0 !important;_x000D_
-webkit-box-shadow: none !important;_x000D_
box-shadow: none !important;_x000D_
background-color: transparent !important;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>_x000D_
_x000D_
<div class="panel-heading">_x000D_
<h4 class="panel-title">_x000D_
<a data-toggle="collapse" data-parent="#accordion" href="#collapse1">Collapsible Group 1</a>_x000D_
</h4>_x000D_
</div>_x000D_
<div class="panel-heading">_x000D_
<h4 class="panel-title">_x000D_
<a data-toggle="collapse" data-parent="#accordion" href="#collapse2">Collapsible Group 2</a>_x000D_
</h4>_x000D_
</div>_x000D_
<div class="panel-heading">_x000D_
<h4 class="panel-title">_x000D_
<a data-toggle="collapse" data-parent="#accordion" href="#collapse3">Collaple Group 3</a>_x000D_
</h4>_x000D_
</div>_x000D_
<div class="panel-group" id="accordion">_x000D_
<div class="panel panel-default">_x000D_
<div id="collapse1" class="panel-collapse collapse in">_x000D_
<div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,_x000D_
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,_x000D_
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="panel panel-default">_x000D_
<div id="collapse2" class="panel-collapse collapse">_x000D_
<div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,_x000D_
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,_x000D_
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="panel panel-default">_x000D_
<div id="collapse3" class="panel-collapse collapse">_x000D_
<div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,_x000D_
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,_x000D_
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
If you're getting this error from Netbeans (7.2+) then it means that your separately installed version of Subversion is higher than the version in netbeans. In my case Netbeans (v7.3.1) had SVN v1.7 and I'd just upgraded my SVN to v1.8.
If you look in Tools > Options > Miscellaneous (tab) > Versioning (tab) > Subversion (pane)
, set the Preferred Client = CLI, then you can set the path the the installed SVN which for me was C:\Program Files\TortoiseSVN\bin
.
More can be found on the Netbeans Subversion Clients FAQ.
3 characters before and 4 characters after
$> echo "some123_string_and_another" | grep -o -P '.{0,3}string.{0,4}'
23_string_and
How wide is the text column?
With a GROUP BY there's not much you can do to avoid a data scan (at least an index scan).
I'd recommend:
If possible, changing the schema to remove duplication of text data. This way the count will happen on a narrow foreign key field in the 'many' table.
Alternatively, creating a generated column with a HASH of the text, then GROUP BY the hash column. Again, this is to decrease the workload (scan through a narrow column index)
Edit:
Your original question did not quite match your edit. I'm not sure if you're aware that the COUNT, when used with a GROUP BY, will return the count of items per group and not the count of items in the entire table.
For O(1) random access, which can not be beaten.
When using dag
instead of thin
, the syntax below pointing to service name worked for me. The jdbc:thin
solutions above did not work.
jdbc:dag:oracle://HOSTNAME:1521;ServiceName=SERVICE_NAME
If it's only a couple of files, and if you're using Tortoise SVN, you can use the following approach:
Player.cpp
require the definition of Ball
class. So simply add #include "Ball.h"
Player.cpp:
#include "Player.h"
#include "Ball.h"
void Player::doSomething(Ball& ball) {
ball.ballPosX += 10; // incomplete type error occurs here.
}
My problem was that I have multiple user accounts on the device. I deleted the app on 1 account, but it still was installed on the other account. Thus the namespace collided and did not install. Uninstalling the app from all user fixed it for me.
you should be able to use
Try c:\> dir /x (in dos shell)
This displays the short names generated for non-8dot3 file names. The format is that of /N with the short name inserted before the long name. If no short name is present, blanks are displayed in its place.
Here is the actual code for what's described above as the "the safest 'correct' method"...
function reduce_query($uri = '') {
$kill_params = array('gclid');
$uri_array = parse_url($uri);
if (isset($uri_array['query'])) {
// Do the chopping.
$params = array();
foreach (explode('&', $uri_array['query']) as $param) {
$item = explode('=', $param);
if (!in_array($item[0], $kill_params)) {
$params[$item[0]] = isset($item[1]) ? $item[1] : '';
}
}
// Sort the parameter array to maximize cache hits.
ksort($params);
// Build new URL (no hosts, domains, or fragments involved).
$new_uri = '';
if ($uri_array['path']) {
$new_uri = $uri_array['path'];
}
if (count($params) > 0) {
// Wish there was a more elegant option.
$new_uri .= '?' . urldecode(http_build_query($params));
}
return $new_uri;
}
return $uri;
}
$_SERVER['REQUEST_URI'] = reduce_query($_SERVER['REQUEST_URI']);
However, since this will likely exist prior to the bootstrap of your application, you should probably put it into an anonymous function. Like this...
call_user_func(function($uri) {
$kill_params = array('gclid');
$uri_array = parse_url($uri);
if (isset($uri_array['query'])) {
// Do the chopping.
$params = array();
foreach (explode('&', $uri_array['query']) as $param) {
$item = explode('=', $param);
if (!in_array($item[0], $kill_params)) {
$params[$item[0]] = isset($item[1]) ? $item[1] : '';
}
}
// Sort the parameter array to maximize cache hits.
ksort($params);
// Build new URL (no hosts, domains, or fragments involved).
$new_uri = '';
if ($uri_array['path']) {
$new_uri = $uri_array['path'];
}
if (count($params) > 0) {
// Wish there was a more elegant option.
$new_uri .= '?' . urldecode(http_build_query($params));
}
// Update server variable.
$_SERVER['REQUEST_URI'] = $new_uri;
}
}, $_SERVER['REQUEST_URI']);
NOTE: Updated with urldecode()
to avoid double encoding via http_build_query()
function.
NOTE: Updated with ksort()
to allow params with no value without an error.
We can use append
append(l1, l2)
It also has arguments to insert element at a particular location.
The name _
used by the node.js
REPL to hold the previous input. Choose another name.
Here is the solution which worked for me.
OUTPUT: State of Cart Widget is updated, upon addition of items.
Create a globalKey
for the widget you want to update by calling the trigger from anywhere
final GlobalKey<CartWidgetState> cartKey = GlobalKey();
Make sure it's saved in a file have global access such that, it can be accessed from anywhere. I save it in globalClass where is save commonly used variables through the app's state.
class CartWidget extends StatefulWidget {
CartWidget({Key key}) : super(key: key);
@override
CartWidgetState createState() => CartWidgetState();
}
class CartWidgetState extends State<CartWidget> {
@override
Widget build(BuildContext context) {
//return your widget
return Container();
}
}
Call your widget from some other class.
class HomeScreen extends StatefulWidget {
HomeScreen ({Key key}) : super(key: key);
@override
HomeScreenState createState() => HomeScreen State();
}
class HomeScreen State extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
return ListView(
children:[
ChildScreen(),
CartWidget(key:cartKey)
]
);
}
}
class ChildScreen extends StatefulWidget {
ChildScreen ({Key key}) : super(key: key);
@override
ChildScreenState createState() => ChildScreen State();
}
class ChildScreen State extends State<ChildScreen> {
@override
Widget build(BuildContext context) {
return InkWell(
onTap: (){
// This will update the state of your inherited widget/ class
if (cartKey.currentState != null)
cartKey.currentState.setState(() {});
},
child: Text("Update The State of external Widget"),
);
}
}
I had this same problem, because my line of code was:
txtTotalInvoice.setText(var1.divide(var2).doubleValue() + "");
I change to this, reading previous Answer, because I was not writing decimal precision:
txtTotalInvoice.setText(var1.divide(var2,4, RoundingMode.HALF_UP).doubleValue() + "");
4 is Decimal Precison
AND RoundingMode are Enum constants, you could choose any of this
UP, DOWN, CEILING, FLOOR, HALF_DOWN, HALF_EVEN, HALF_UP
In this Case HALF_UP, will have this result:
2.4 = 2
2.5 = 3
2.7 = 3
You can check the RoundingMode
information here: http://www.javabeat.net/precise-rounding-of-decimals-using-rounding-mode-enumeration/
I believe the example you've posted is using HTML5, which allows you to jump to any DOM element with the matching ID
attribute. To support older browsers, you'll need to change:
<div id="timeline" name="timeline" ...>
To the old format:
<a name="timeline" />
You'll then be able to navigate to /academics/page.html#timeline
and jump right to that section.
Also, check out this similar question.
In case it helps someone else, I was able to convert to an array by doing something like this,
JSONObject jsonObject = (JSONObject)new JSONParser().parse(jsonString);
((JSONArray) jsonObject).toArray()
...or you should be able to get the length
((JSONArray) myJsonArray).toArray().length
This has a good general description: https://gephi.wordpress.com/tag/maven/
Let me make a few statement that can put the difference in focus:
We migrated our code base from Ant to Maven
All 3rd party librairies have been uploaded to Nexus. Maven is using Nexus as a source for libraries.
Basic functionalities of a repository manager like Sonatype are:
You can run the cd
and the executable in a subshell by enclosing the command line in a pair of parentheses:
(cd SOME_PATH && exec_some_command)
Demo:
$ pwd
/home/abhijit
$ (cd /tmp && pwd) # directory changed in the subshell
/tmp
$ pwd # parent shell's pwd is still the same
/home/abhijit
You can use an array in the select() to define more columns and you can use the DB::raw() there with aliasing it to followers. Should look like this:
$query = DB::table('category_issue')
->select(array('issues.*', DB::raw('COUNT(issue_subscriptions.issue_id) as followers')))
->where('category_id', '=', 1)
->join('issues', 'category_issue.issue_id', '=', 'issues.id')
->left_join('issue_subscriptions', 'issues.id', '=', 'issue_subscriptions.issue_id')
->group_by('issues.id')
->order_by('followers', 'desc')
->get();
Each instantiation and full specialization of std::atomic<> represents a type that different threads can simultaneously operate on (their instances), without raising undefined behavior:
Objects of atomic types are the only C++ objects that are free from data races; that is, if one thread writes to an atomic object while another thread reads from it, the behavior is well-defined.
In addition, accesses to atomic objects may establish inter-thread synchronization and order non-atomic memory accesses as specified by
std::memory_order
.
std::atomic<>
wraps operations that, in pre-C++ 11 times, had to be performed using (for example) interlocked functions with MSVC or atomic bultins in case of GCC.
Also, std::atomic<>
gives you more control by allowing various memory orders that specify synchronization and ordering constraints. If you want to read more about C++ 11 atomics and memory model, these links may be useful:
Note that, for typical use cases, you would probably use overloaded arithmetic operators or another set of them:
std::atomic<long> value(0);
value++; //This is an atomic op
value += 5; //And so is this
Because operator syntax does not allow you to specify the memory order, these operations will be performed with std::memory_order_seq_cst
, as this is the default order for all atomic operations in C++ 11. It guarantees sequential consistency (total global ordering) between all atomic operations.
In some cases, however, this may not be required (and nothing comes for free), so you may want to use more explicit form:
std::atomic<long> value {0};
value.fetch_add(1, std::memory_order_relaxed); // Atomic, but there are no synchronization or ordering constraints
value.fetch_add(5, std::memory_order_release); // Atomic, performs 'release' operation
Now, your example:
a = a + 12;
will not evaluate to a single atomic op: it will result in a.load()
(which is atomic itself), then addition between this value and 12
and a.store()
(also atomic) of final result. As I noted earlier, std::memory_order_seq_cst
will be used here.
However, if you write a += 12
, it will be an atomic operation (as I noted before) and is roughly equivalent to a.fetch_add(12, std::memory_order_seq_cst)
.
As for your comment:
A regular
int
has atomic loads and stores. Whats the point of wrapping it withatomic<>
?
Your statement is only true for architectures that provide such guarantee of atomicity for stores and/or loads. There are architectures that do not do this. Also, it is usually required that operations must be performed on word-/dword-aligned address to be atomic std::atomic<>
is something that is guaranteed to be atomic on every platform, without additional requirements. Moreover, it allows you to write code like this:
void* sharedData = nullptr;
std::atomic<int> ready_flag = 0;
// Thread 1
void produce()
{
sharedData = generateData();
ready_flag.store(1, std::memory_order_release);
}
// Thread 2
void consume()
{
while (ready_flag.load(std::memory_order_acquire) == 0)
{
std::this_thread::yield();
}
assert(sharedData != nullptr); // will never trigger
processData(sharedData);
}
Note that assertion condition will always be true (and thus, will never trigger), so you can always be sure that data is ready after while
loop exits. That is because:
store()
to the flag is performed after sharedData
is set (we assume that generateData()
always returns something useful, in particular, never returns NULL
) and uses std::memory_order_release
order:
memory_order_release
A store operation with this memory order performs the release operation: no reads or writes in the current thread can be reordered after this store. All writes in the current thread are visible in other threads that acquire the same atomic variable
sharedData
is used after while
loop exits, and thus after load()
from flag will return a non-zero value. load()
uses std::memory_order_acquire
order:
std::memory_order_acquire
A load operation with this memory order performs the acquire operation on the affected memory location: no reads or writes in the current thread can be reordered before this load. All writes in other threads that release the same atomic variable are visible in the current thread.
This gives you precise control over the synchronization and allows you to explicitly specify how your code may/may not/will/will not behave. This would not be possible if only guarantee was the atomicity itself. Especially when it comes to very interesting sync models like the release-consume ordering.
The su
command does not execute anything, it just raise your privileges.
Try adb shell su -c YOUR_COMMAND
.
You are getting the error because $ret
is not an array.
To get rid of the error, at the start of your function, define it with this line: $ret = array();
It appears that the get_tags() call is returning nothing, so the foreach is not run, which means that $ret isn't defined.
I can tell you I am using just a single breakpoint at 768 - that is min-width: 768px
to serve tablets and desktops, and max-width: 767px
to serve phones.
I haven't looked back since. It makes the responsive development easy and not a chore, and provides a reasonable experience on all devices at minimal cost to development time without the need to fear a new Android device with a new resolution you haven't factored in.
If you want to add your menu custom
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_custom, menu);
}
To get a list of the words that appear more than once together with how often they occur, use a combination of GROUP BY and HAVING:
SELECT word, COUNT(*) AS cnt
FROM words
GROUP BY word
HAVING cnt > 1
To find the number of words in the above result set, use that as a subquery and count the rows in an outer query:
SELECT COUNT(*)
FROM
(
SELECT NULL
FROM words
GROUP BY word
HAVING COUNT(*) > 1
) T1
Ubuntu 14 and lower does not have "systemctl
" Source: https://docs.docker.com/install/linux/linux-postinstall/#configure-docker-to-start-on-boot
Configure Docker to start on boot:
Most current Linux distributions (RHEL, CentOS, Fedora, Ubuntu 16.04 and higher) use systemd to manage which services start when the system boots. Ubuntu 14.10 and below use upstart.
1) systemd (Ubuntu 16 and above):
$ sudo systemctl enable docker
To disable this behavior, use disable instead.
$ sudo systemctl disable docker
2) upstart (Ubuntu 14 and below):
Docker is automatically configured to start on boot using upstart. To disable this behavior, use the following command:
$ echo manual | sudo tee /etc/init/docker.override
chkconfig
$ sudo chkconfig docker on
Done.
A key is just a normal index. A way over simplification is to think of it like a card catalog at a library. It points MySQL in the right direction.
A unique key is also used for improved searching speed, but it has the constraint that there can be no duplicated items (there are no two x and y where x is not y and x == y).
The manual explains it as follows:
A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. This constraint does not apply to NULL values except for the BDB storage engine. For other engines, a UNIQUE index permits multiple NULL values for columns that can contain NULL. If you specify a prefix value for a column in a UNIQUE index, the column values must be unique within the prefix.
A primary key is a 'special' unique key. It basically is a unique key, except that it's used to identify something.
The manual explains how indexes are used in general: here.
In MSSQL, the concepts are similar. There are indexes, unique constraints and primary keys.
Untested, but I believe the MSSQL equivalent is:
CREATE TABLE tmp (
id int NOT NULL PRIMARY KEY IDENTITY,
uid varchar(255) NOT NULL CONSTRAINT uid_unique UNIQUE,
name varchar(255) NOT NULL,
tag int NOT NULL DEFAULT 0,
description varchar(255),
);
CREATE INDEX idx_name ON tmp (name);
CREATE INDEX idx_tag ON tmp (tag);
Edit: the code above is tested to be correct; however, I suspect that there's a much better syntax for doing it. Been a while since I've used SQL server, and apparently I've forgotten quite a bit :).
You can't influence neither type (tab/window) nor dimensions that way. You'll have to use JavaScript's window.open() for that.
Could also happen if putting string in double quotes instead of single.
I had the same problem today and figured out that because I typed git submodule init
then I had those line in my .git/config
:
[submodule]
active = .
I removed that and typed:
git submodule update --init --remote
And everything was back to normal, my submodule updated in its subdirectory as usual.
No. The only you can do is to add content (and not an element) using :before
or :after
pseudo-element.
More information: http://www.w3.org/TR/CSS2/generate.html#before-after-content
The simplest way is the platform-specific solution:
#!/usr/bin/env ruby
`wget http://somedomain.net/flv/sample/sample.flv`
Probably you are searching for:
require 'net/http'
# Must be somedomain.net instead of somedomain.net/, otherwise, it will throw exception.
Net::HTTP.start("somedomain.net") do |http|
resp = http.get("/flv/sample/sample.flv")
open("sample.flv", "wb") do |file|
file.write(resp.body)
end
end
puts "Done."
Edit: Changed. Thank You.
Edit2: The solution which saves part of a file while downloading:
# instead of http.get
f = open('sample.flv')
begin
http.request_get('/sample.flv') do |resp|
resp.read_body do |segment|
f.write(segment)
end
end
ensure
f.close()
end
Just as @James says, it will order all records, then get the first 20 rows.
As it is so, you are guaranteed to get the 20 first published articles, the newer ones will not be shown.
In your situation, I recommend that you add desc
to order by publish_date
, if you want the newest articles, then the newest article will be first.
If you need to keep the result in ascending order, and still only want the 10 newest articles you can ask mysql to sort your result two times.
This query below will sort the result descending and limit the result to 10 (that is the query inside the parenthesis). It will still be sorted in descending order, and we are not satisfied with that, so we ask mysql to sort it one more time. Now we have the newest result on the last row.
select t.article
from
(select article, publish_date
from table1
order by publish_date desc limit 10) t
order by t.publish_date asc;
If you need all columns, it is done this way:
select t.*
from
(select *
from table1
order by publish_date desc limit 10) t
order by t.publish_date asc;
I use this technique when I manually write queries to examine the database for various things. I have not used it in a production environment, but now when I bench marked it, the extra sorting does not impact the performance.
This is a preprocessor directive that can be used to turn on or off certain features.
It is of two types #pragma startup
, #pragma exit
and #pragma warn
.
#pragma startup
allows us to specify functions called upon program startup.
#pragma exit
allows us to specify functions called upon program exit.
#pragma warn
tells the computer to suppress any warning or not.
Many other #pragma
styles can be used to control the compiler.
The easiest way only if you don't need return something it'ts just return null
The height of a binary search tree is equal to number of layers - 1
.
See the diagram at http://en.wikipedia.org/wiki/Binary_tree
Your recursion is good, so just subtract one at the root level.
Also note, you can clean up the function a bit by handling null nodes:
int findHeight(node) {
if (node == null) return 0;
return 1 + max(findHeight(node.left), findHeight(node.right));
}
You need to use the string concatenation operator +
String both = name + "-" + dest;
check the following link https://www.geeksforgeeks.org/how-to-create-an-unordered_map-of-user-defined-class-in-cpp/ for more details.
Go to the Sql tab run one of the below query:
delete from tableName;
Delete: will delete all rows from your table. Next insert will take next auto increment id.
or
truncate tableName;
Truncate: will also delete the rows from your table but it will start from new row with 1.
A detailed blog with example: http://sforsuresh.in/phpmyadmin-deleting-rows-mysql-table/
You can do this assignment easily by using jquery. In this way, you can define number of row limitation. Furthermore, you can regular breakpoints height that want adding vertical scrolling. I must say that more than 3 rows get modify class and also height is 76px.
$(document).ready(function() {_x000D_
var length = $(this).find('li').length;_x000D_
if (length > 3) {_x000D_
$(".parent").addClass('modify');_x000D_
}_x000D_
})
_x000D_
/*for beauty*/_x000D_
_x000D_
ul {_x000D_
margin: 0 auto;_x000D_
width: 50%;_x000D_
border: 1px solid #ccc;_x000D_
padding: 3px;_x000D_
}_x000D_
_x000D_
ul li {_x000D_
padding: 3px;_x000D_
background: #ccc;_x000D_
margin: 2px 0;_x000D_
list-style: none;_x000D_
}_x000D_
_x000D_
/*main class*/_x000D_
_x000D_
.modify {_x000D_
overflow-y: scroll;_x000D_
height: 76px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<ul class="parent">_x000D_
<li>item 1</li>_x000D_
<li>item 2</li>_x000D_
<li>item 3</li>_x000D_
<li>item 4</li>_x000D_
</ul>
_x000D_
In order to check the absence of physical sockets run:
wmic cpu get SocketDesignation
Based on all the responses and CS231n notes, allow me to summarise:
def softmax(x, axis):
x -= np.max(x, axis=axis, keepdims=True)
return np.exp(x) / np.exp(x).sum(axis=axis, keepdims=True)
Usage:
x = np.array([[1, 0, 2,-1],
[2, 4, 6, 8],
[3, 2, 1, 0]])
softmax(x, axis=1).round(2)
Output:
array([[0.24, 0.09, 0.64, 0.03],
[0. , 0.02, 0.12, 0.86],
[0.64, 0.24, 0.09, 0.03]])
I tried the configs above and only this worked for my WAMP Apache 2.4.2 config. For multiple root site without named domains in your Windows hosts file, use http://locahost:8080, http://localhost:8081, http://localhost:8082
and this configuration:
#ServerName localhost:80
ServerName localhost
Listen 8080
Listen 8081
Listen 8082
#.....
<VirtualHost *:8080>
DocumentRoot "c:\www"
ServerName localhost
<Directory "c:/www/">
Options Indexes FollowSymLinks
AllowOverride all
Require local
</Directory>
</VirtualHost>
<VirtualHost *:8081>
DocumentRoot "C:\www\directory abc\svn_abc\trunk\httpdocs"
ServerName localhost
<Directory "C:\www\directory abc\svn_abc\trunk\httpdocs">
Options Indexes FollowSymLinks
AllowOverride all
Require local
</Directory>
</VirtualHost>
#<VirtualHost *:8082></VirtualHost>.......
Mainly join is used exclusively to join based on the index,not on the attribute names,so change the attributes names in two different dataframes,then try to join,they will be joined,else this error is raised
The data
variable contains a Buffer
object. Convert it into ASCII encoding using the following syntax:
data.toString('ascii', 0, data.length)
Asynchronously:
fs.readFile('test.txt', 'utf8', function (error, data) {
if (error) throw error;
console.log(data.toString());
});
A text file does not have \0 at the end of lines. It has \n. \n is a character, not a string, so it must be enclosed in single quotes
if (c == '\n')
Premise to my answer:
Approach
Additionally, the base image can be upgraded/ the container with a complete new base image can be built at regular intervals, as the maintainer feels necessary
Advantages
Use controller.controller_name
In the Rails Guides, it says:
The params hash will always contain the :controller and :action keys, but you should use the methods controller_name and action_name instead to access these values
So let's say you have a CSS class active
, that should be inserted in any link whose page is currently open (maybe so that you can style differently) . If you have a static_pages
controller with an about
action, you can then highlight the link like so in your view:
<li>
<a class='button <% if controller.controller_name == "static_pages" && controller.action_name == "about" %>active<%end%>' href="/about">
About Us
</a>
</li>
If you do not have an LDF file then:
1) put the MDF in the C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\
2) In ssms, go to Databases -> Attach
and add the MDF file. It will not let you add it this way but it will tell you the database name contained within.
3) Make sure the user you are running ssms.exe as has acccess to this MDF file.
4) Now that you know the DbName, run
EXEC sp_attach_single_file_db @dbname = 'DbName',
@physname = N'C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\yourfile.mdf';
Reference: https://dba.stackexchange.com/questions/12089/attaching-mdf-without-ldf
Always check for Inner Exception if any. In my case Inner Exception turned out to be really helpful in figuring out the issue.
My site was working fine in Dev Environment. But after i deployed to production, it started giving out this exception, but the Inner Exception was saying that Login failed for the particular user.
So i figured out it was something to do with the connection itself. Hence tried logging in using SSMS and even that failed.
Eventually figured out that exception showed up for the simple reason that the SQL server had only Windows Authentication enabled and SQL Authentication was failing which was what i was using for Authentication.
In short, changing Authentication to Mixed(SQL and Windows), fixed the issue for me. :)
To set the position relative to the parent you need to set the position:relative
of parent and position:absolute
of the element
$("#mydiv").parent().css({position: 'relative'});
$("#mydiv").css({top: 200, left: 200, position:'absolute'});
This works because position: absolute;
positions relatively to the closest positioned parent (i.e., the closest parent with any position property other than the default static
).
select db_name(), * From sysobjects where xtype in ('U', 'P') And name = 'OBJECT_name'
First column will display name of database where object is located at.
First of all, a spinner does not support item click events. Calling this method will raise an exception.
You can use setOnItemSelectedListener:
Spinner s1;
s1 = (Spinner)findViewById(R.id.s1);
int selectionCurrent = s1.getSelectedItemPosition();
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
if (selectionCurrent != position){
// Your code here
}
selectionCurrent= position;
}
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// Your code here
}
});
Very simplified without much formality: every edge is considered exactly twice, and every node is processed exactly once, so the complexity has to be a constant multiple of the number of edges as well as the number of vertices.
If you are using .NET Framework 4.5, the solution is to use EmailAddressAttribute
which resides inside System.ComponentModel.DataAnnotations
.
Your code should look similar to this:
[Display(Name = "Email address")]
[Required(ErrorMessage = "The email address is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
leverage the css3 columns module to support what you are looking for.
http://www.w3schools.com/cssref/css3_pr_columns.asp
CSS:
ul {
columns: 2;
-webkit-columns: 2;
-moz-columns: 2;
}
Unfortunately for IE support you will need a code solution that involves JavaScript and dom manipulation. This means that anytime the contents of the list changes you will need to perform the operation for reordering the list into columns and reprinting. The solution below uses jQuery for brevity.
HTML:
<div>
<ul class="columns" data-columns="2">
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>G</li>
</ul>
</div>
JavaScript:
(function($){
var initialContainer = $('.columns'),
columnItems = $('.columns li'),
columns = null,
column = 1; // account for initial column
function updateColumns(){
column = 0;
columnItems.each(function(idx, el){
if (idx !== 0 && idx > (columnItems.length / columns.length) + (column * idx)){
column += 1;
}
$(columns.get(column)).append(el);
});
}
function setupColumns(){
columnItems.detach();
while (column++ < initialContainer.data('columns')){
initialContainer.clone().insertBefore(initialContainer);
column++;
}
columns = $('.columns');
}
$(function(){
setupColumns();
updateColumns();
});
})(jQuery);
CSS:
.columns{
float: left;
position: relative;
margin-right: 20px;
}
EDIT:
As pointed out below this will order the columns as follows:
A E
B F
C G
D
while the OP asked for a variant matching the following:
A B
C D
E F
G
To accomplish the variant you simply change the code to the following:
function updateColumns(){
column = 0;
columnItems.each(function(idx, el){
if (column > columns.length){
column = 0;
}
$(columns.get(column)).append(el);
column += 1;
});
}
Just add profile to session configuration before client call.
boto3.session.Session(profile_name='YOUR_PROFILE_NAME').client('cloudwatch')
I would use math
package for getting the maximal value and minimal value :
func printMinMaxValue() {
// integer max
fmt.Printf("max int64 = %+v\n", math.MaxInt64)
fmt.Printf("max int32 = %+v\n", math.MaxInt32)
fmt.Printf("max int16 = %+v\n", math.MaxInt16)
// integer min
fmt.Printf("min int64 = %+v\n", math.MinInt64)
fmt.Printf("min int32 = %+v\n", math.MinInt32)
fmt.Printf("max flloat64= %+v\n", math.MaxFloat64)
fmt.Printf("max float32= %+v\n", math.MaxFloat32)
// etc you can see more int the `math`package
}
Ouput :
max int64 = 9223372036854775807
max int32 = 2147483647
max int16 = 32767
min int64 = -9223372036854775808
min int32 = -2147483648
max flloat64= 1.7976931348623157e+308
max float32= 3.4028234663852886e+38
Here is a way which allows to remove points after a certain number of points plotted:
import matplotlib.pyplot as plt
# generate axes object
ax = plt.axes()
# set limits
plt.xlim(0,10)
plt.ylim(0,10)
for i in range(10):
# add something to axes
ax.scatter([i], [i])
ax.plot([i], [i+1], 'rx')
# draw the plot
plt.draw()
plt.pause(0.01) #is necessary for the plot to update for some reason
# start removing points if you don't want all shown
if i>2:
ax.lines[0].remove()
ax.collections[0].remove()
You couldn't login because you did't get proper solt text at login time. There are two options, first is define static salt, second is if you want create dynamic salt than you have to store the salt somewhere (means in database) with associate with user. Than you concatenate user solt+password_hash string now with this you fire query with username in your database table.