You can use Notepad++ to evaluate a file's encoding without needing to write code. The evaluated encoding of the open file will display on the bottom bar, far right side. The encodings supported can be seen by going to Settings -> Preferences -> New Document/Default Directory
and looking in the drop down.
It comes from the era of Line Printers and green-striped fan-fold paper.
Trust me, you ain't gonna need it...
Since Python 3.5 this is finally no longer awkward:
>>> b'\xde\xad\xbe\xef'.hex()
'deadbeef'
and reverse:
>>> bytes.fromhex('deadbeef')
b'\xde\xad\xbe\xef'
works also with the mutable bytearray
type.
Reference: https://docs.python.org/3/library/stdtypes.html#bytes.hex
Your question title mentions Blocking Queues. However, ConcurrentLinkedQueue
is not a blocking queue.
The BlockingQueue
s are ArrayBlockingQueue
, DelayQueue
, LinkedBlockingDeque
, LinkedBlockingQueue
, PriorityBlockingQueue
, and SynchronousQueue
.
Some of these are clearly not fit for your purpose (DelayQueue
, PriorityBlockingQueue
, and SynchronousQueue
). LinkedBlockingQueue
and LinkedBlockingDeque
are identical, except that the latter is a double-ended Queue (it implements the Deque interface).
Since ArrayBlockingQueue
is only useful if you want to limit the number of elements, I'd stick to LinkedBlockingQueue
.
Don't forget to generate a second password for your Gmail account. You will use this new password in your code. Read this:
https://support.google.com/accounts/answer/185833
Under the section "How to generate an App password" click on "App passwords", then under "Select app" choose "Mail", select your device and click "Generate". Your second password will be printed on the screen.
child_process.spawn returns an object with stdout and stderr streams. You can tap on the stdout stream to read data that the child process sends back to Node. stdout being a stream has the "data", "end", and other events that streams have. spawn is best used to when you want the child process to return a large amount of data to Node - image processing, reading binary data etc.
so you can solve your problem using child_process.spawn as used below.
var spawn = require('child_process').spawn,
ls = spawn('coffee -cw my_file.coffee');
ls.stdout.on('data', function (data) {
console.log('stdout: ' + data.toString());
});
ls.stderr.on('data', function (data) {
console.log('stderr: ' + data.toString());
});
ls.on('exit', function (code) {
console.log('code ' + code.toString());
});
.NET 2.0 does not support LINQ - SO thread;
But you can create a 3.5 project in VS2005 - MSDN thread
Without lambda support, you'll need to do something like this:
string s = "a,b, b, c";
string[] values = s.Split(',');
for(int i = 0; i < values.Length; i++)
{
values[i] = values[i].Trim();
}
I ran into the same problem. From my solution i came into this. So here is your code:
- root_directory
- sub_directory_a
- _common.scss
- template.scss
- sub_directory_b
- more_styles.scss
As far i know if you want to import one scss to another its has to be a partial. When you are importing from different directory name your more_styles.scss
to _more_styles.scss
. Then import it into your template.scss
like this @import ../sub_directory_b/_more_styles.scss
. It worked for me. But as you mentioned ../sub_directory_a/_common.scss
not working. That's the same directory of the template.scss
. That is why it wont work.
Cygwin works, but these utilities are also available. Just plop them on your drive, put the directory into your path, and you have many of your friendly unix utilities. Lighterweight IMHO that Cygwin (although that works just as well).
This will work although when embedding PHP in HTML it is better practice to use the following form:
<table>
<?php foreach($array as $key=>$value): ?>
<tr>
<td><?= $key; ?></td>
</tr>
<?php endforeach; ?>
</table>
You can find the doc for the alternative syntax on PHP.net
UPDATE db.tablename SET columnID = (SELECT UUID()) where columnID is not null
For transparency, this is also mandatory: renderer = new THREE.WebGLRenderer( { alpha: true } )
via Transparent background with three.js
You're looking for the --data-binary
argument:
curl -i -X POST host:port/post-file \
-H "Content-Type: text/xml" \
--data-binary "@path/to/file"
In the example above, -i
prints out all the headers so that you can see what's going on, and -X POST
makes it explicit that this is a post. Both of these can be safely omitted without changing the behaviour on the wire. The path to the file needs to be preceded by an @
symbol, so curl
knows to read from a file.
jQuery Library must be in the head section then.
<button onclick="var less = parseInt($('#qty').val()) - 1; $('#qty').val(less);"></button>
<input type="text" id="qty" value="2">
<button onclick="var add = parseInt($('#qty').val()) + 1; $('#qty').val(add);">+</button>
The syntax is wrong. A member pointer is a different type category from a ordinary pointer. The member pointer will have to be used together with an object of its class:
class A {
public:
int f();
int (A::*x)(); // <- declare by saying what class it is a pointer to
};
int A::f() {
return 1;
}
int main() {
A a;
a.x = &A::f; // use the :: syntax
printf("%d\n",(a.*(a.x))()); // use together with an object of its class
}
a.x
does not yet say on what object the function is to be called on. It just says that you want to use the pointer stored in the object a
. Prepending a
another time as the left operand to the .*
operator will tell the compiler on what object to call the function on.
Sometime I have to work from home and connect to office through vpn. Internal domain names should be resolved to different IPs at home. There are several names that have to be changed between office and home. For example:
At office, a => 192.168.0.3, b => 192.168.0.52.
At home, a => 10.6.1.7, b => 10.4.5.23.
My solution is to create two files: C:\WINDOWS\system32\drivers\etc\hosts-home and C:\WINDOWS\system32\drivers\etc\hosts-office. Each of them contains set of name-to-IP mapping. From Administrator PowerShell, When I work at the office, execute
C:\WINDOWS\system32> cp .\drivers\etc\hosts-office .\drivers\etc\hosts
When I arrive at home, execute
C:\WINDOWS\system32> cp .\drivers\etc\hosts-home .\drivers\etc\hosts
Seems like you can't iterate through JSONArray
with a for each
. You can loop through your JSONArray
like this:
for (int i=0; i < arr.length(); i++) {
arr.getJSONObject(i);
}
If there is an object with 8 methods and you have a test where you want to call 7 real methods and stub one method you have two options:
spy
you have to set it up by stubbing one methodThe official documentation on doCallRealMethod
recommends using a spy for partial mocks.
See also javadoc spy(Object) to find out more about partial mocks. Mockito.spy() is a recommended way of creating partial mocks. The reason is it guarantees real methods are called against correctly constructed object because you're responsible for constructing the object passed to spy() method.
ServiceStack.Text has a T.Dump() extension method that does exactly this, recursively dumps all properties of any type in a nice readable format.
Example usage:
var model = new TestModel();
Console.WriteLine(model.Dump());
and output:
{
Int: 1,
String: One,
DateTime: 2010-04-11,
Guid: c050437f6fcd46be9b2d0806a0860b3e,
EmptyIntList: [],
IntList:
[
1,
2,
3
],
StringList:
[
one,
two,
three
],
StringIntMap:
{
a: 1,
b: 2,
c: 3
}
}
Headings are normally bold-faced; that has been turned off for this demonstration of size correspondence. MSIE and Opera interpret these sizes the same, but note that Gecko browsers and Chrome interpret Heading 6 as 11 pixels instead of 10 pixels/font size 1, and Heading 3 as 19 pixels instead of 18 pixels/font size 4 (though it's difficult to tell the difference even in a direct comparison and impossible in use). It seems Gecko also limits text to no smaller than 10 pixels.
A Swift 2.0 answer utilising NSUserDefaults to save and restore the map's zoom and position.
Function to save the map position and zoom:
func saveMapRegion() {
let mapRegion = [
"latitude" : mapView.region.center.latitude,
"longitude" : mapView.region.center.longitude,
"latitudeDelta" : mapView.region.span.latitudeDelta,
"longitudeDelta" : mapView.region.span.longitudeDelta
]
NSUserDefaults.standardUserDefaults().setObject(mapRegion, forKey: "mapRegion")
}
Run the function each time the map is moved:
func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool)
{
saveMapRegion();
}
Function to save the map zoom and position:
func restoreMapRegion()
{
if let mapRegion = NSUserDefaults.standardUserDefaults().objectForKey("mapRegion")
{
let longitude = mapRegion["longitude"] as! CLLocationDegrees
let latitude = mapRegion["latitude"] as! CLLocationDegrees
let center = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let longitudeDelta = mapRegion["latitudeDelta"] as! CLLocationDegrees
let latitudeDelta = mapRegion["longitudeDelta"] as! CLLocationDegrees
let span = MKCoordinateSpan(latitudeDelta: latitudeDelta, longitudeDelta: longitudeDelta)
let savedRegion = MKCoordinateRegion(center: center, span: span)
self.mapView.setRegion(savedRegion, animated: false)
}
}
Add this to viewDidLoad:
restoreMapRegion()
I used ProcessBuilder but had the same issue. The issue was with using command as one String line (like I would type it in cmd) instead of String array. In example from above. If I ran
ProcessBuilder pb = new ProcessBuilder("C:/Program Files/WinRAR/winrar x myjar.jar *.* new");
pb.directory(new File("H:/"));
pb. redirectErrorStream(true);
Process p = pb.start();
I got an error. But if I ran
ProcessBuilder pb = new ProcessBuilder("C:/Program Files/WinRAR/winrar", "x", "myjar.jar", "*.*", "new");
pb.directory(new File("H:/"));
pb. redirectErrorStream(true);
Process p = pb.start();
everything was OK.
For IE9+ and other browsers
function trim(text) {
return (text == null) ? '' : ''.trim.call(text);
}
I had the same problem. It was caused by having different version codes and numbers in my manifest and gradle build script. I resolved it by removing the version code and version number from my manifest and letting gradle take care of it.
One of the possible solution you might be interested in. Traversing an array of chars from right to left and vise versa in one loop.
public static string WordsToCapitalLetter(string value)
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException("value");
}
int inputValueCharLength = value.Length;
var valueAsCharArray = value.ToCharArray();
int min = 0;
int max = inputValueCharLength - 1;
while (max > min)
{
char left = value[min];
char previousLeft = (min == 0) ? left : value[min - 1];
char right = value[max];
char nextRight = (max == inputValueCharLength - 1) ? right : value[max - 1];
if (char.IsLetter(left) && !char.IsUpper(left) && char.IsWhiteSpace(previousLeft))
{
valueAsCharArray[min] = char.ToUpper(left);
}
if (char.IsLetter(right) && !char.IsUpper(right) && char.IsWhiteSpace(nextRight))
{
valueAsCharArray[max] = char.ToUpper(right);
}
min++;
max--;
}
return new string(valueAsCharArray);
}
if you have just two parameters you can do this:
$.getJSON('/url-you-are-posting-to',data,function(result){
//do something useful with returned result//
result.variable-in-result;
});
There is also this free API that you can use to make free barcodes in java.
Always prefer Count
and Length
properties on a type over the extension method Count()
. The former is an O(1) for every type which contains them. The Count()
extension method has some type check optimizations that can cause it to run also in O(1) time but will degrade to O(N) if the underlying collection is not one of the few types it knows about.
you can use ClearContents. ex,
Range("X").Cells.ClearContents
you can do top level await since typescript 3.8
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#-top-level-await
From the post:
This is because previously in JavaScript (along with most other languages with a similar feature), await was only allowed within the body of an async function. However, with top-level await, we can use await at the top level of a module.
const response = await fetch("...");
const greeting = await response.text();
console.log(greeting);
// Make sure we're a module
export {};
Note there’s a subtlety: top-level await only works at the top level of a module, and files are only considered modules when TypeScript finds an import or an export. In some basic cases, you might need to write out export {} as some boilerplate to make sure of this.
Top level await may not work in all environments where you might expect at this point. Currently, you can only use top level await when the target compiler option is es2017 or above, and module is esnext or system. Support within several environments and bundlers may be limited or may require enabling experimental support.
SQLAlchemy is very, very powerful. However it is not thread safe make sure you keep that in mind when working with cherrypy in thread-pool mode.
Error indicates that there is no UserID column in your Employees table. Try adding the column first and then re-run the statement.
ALTER TABLE Employees
ADD CONSTRAINT FK_ActiveDirectories_UserID FOREIGN KEY (UserID)
REFERENCES ActiveDirectories(id);
Pressing Ctrl+K+C or Ctrl+E+C After selecting the lines you want to comment will not give space after slashes. you can use multiline select to provide space as suggested by Habib
Perhaps, you can use /* before the lines you want to comment and after */ in that case you might not need to provide spaces.
/*
First Line to Comment
Second Line to Comment
Third Line to Comment
*/
This worked perfectly for me, although fetching all branches could be a bit too much:
git init
git remote add origin https://github.com/Vitosh/VBA_personal.git
git fetch --all
git checkout develop
I am reproducing the same issue and it's really annoying. I've found these useful:
HttpClient - dealing with aggregate exceptions
Bug in HttpClient.GetAsync should throw WebException, not TaskCanceledException
Some code in case the links go nowhere:
var c = new HttpClient();
c.Timeout = TimeSpan.FromMilliseconds(10);
var cts = new CancellationTokenSource();
try
{
var x = await c.GetAsync("http://linqpad.net", cts.Token);
}
catch(WebException ex)
{
// handle web exception
}
catch(TaskCanceledException ex)
{
if(ex.CancellationToken == cts.Token)
{
// a real cancellation, triggered by the caller
}
else
{
// a web request timeout (possibly other things!?)
}
}
#for python 3
A = [0,1,2,3,4,5]
l = len(A)/2
B = A[:int(l)]
C = A[int(l):]
Z-Index only works for elements that have position: relative;
or position: absolute;
applied to them. If that's not the problem we'll need to see an example page to be more helpful.
EDIT: The good doctor has already put the fullest explanation but the quick version is that the minimum is 0 because it can't be a negative number and the maximum - well, you'll never really need to go above 10 for most designs.
db2ls command will display the db2level along with the install path and install date.
To determine the specific product installed:
db2ls -p -q -b <installpath>
on db2ls command.
The following will appear:
Install Path Level Fix Pack Special Install Number Install Date Installer UID
--------------------------------------------------------------------------------------------
/opt/ibm/db2/V9.7 9.7.0.7 7 Thu Aug 1 12:25:53 2013 CDT 0
visit IBM Website
Summarised form an answer to Xcode fails with "Code Signing" Error
project.pbxproj
files can be merged in such a way that two CODE_SIGN_IDENTITY
lines can be inserted. Deleting one of these normally fixes the issue.
I have created simple script to help diagnose this issue it can be found here: https://gist.github.com/4339226
A full answer can be found here.
If your pdf is text-based and not a scanned document (i.e. if you can click and drag to select text in your table in a PDF viewer), then you can use the module camelot-py
with
import camelot
tables = camelot.read_pdf('foo.pdf')
You then can choose how you want to save the tables (as csv, json, excel, html, sqlite), and whether the output should be compressed in a ZIP archive.
tables.export('foo.csv', f='csv', compress=False)
Edit: tabula-py
appears roughly 6 times faster than camelot-py
so that should be used instead.
import camelot
import cProfile
import pstats
import tabula
cmd_tabula = "tabula.read_pdf('table.pdf', pages='1', lattice=True)"
prof_tabula = cProfile.Profile().run(cmd_tabula)
time_tabula = pstats.Stats(prof_tabula).total_tt
cmd_camelot = "camelot.read_pdf('table.pdf', pages='1', flavor='lattice')"
prof_camelot = cProfile.Profile().run(cmd_camelot)
time_camelot = pstats.Stats(prof_camelot).total_tt
print(time_tabula, time_camelot, time_camelot/time_tabula)
gave
1.8495559890000015 11.057014036000016 5.978199147125147
function repeat(pattern, count) {
for (var result = '';;) {
if (count & 1) {
result += pattern;
}
if (count >>= 1) {
pattern += pattern;
} else {
return result;
}
}
}
You can test it at JSFiddle. Benchmarked against the hacky Array.join
and mine is, roughly speaking, 10 (Chrome) to 100 (Safari) to 200 (Firefox) times faster (depending on the browser).
As per different sources, I think the minimum length in E-164 format depends on country to country. For eg:
For Sweden : The minimum number length (excluding the country code) is 7 digits. - Official Source? (country code 46)
For Solomon Islands its 5 for fixed line phones. - Source (country code 677)
... and so on. So including country code, the minimum length is 9 digits for Sweden and 11 for Israel and 8 for Solomon Islands.
Edit (Clean Solution): Actually, Instead of validating an international phone number by having different checks like length etc, you can use the Google's libphonenumber library. It can validate a phone number in E164 format directly. It will take into account everything and you don't even need to give the country if the number is in valid E164 format. Its pretty good! Taking an example:
String phoneNumberE164Format = "+14167129018"
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
PhoneNumber phoneNumberProto = phoneUtil.parse(phoneNumberE164Format, null);
boolean isValid = phoneUtil.isValidNumber(phoneNumberProto); // returns true if valid
if (isValid) {
// Actions to perform if the number is valid
} else {
// Do necessary actions if its not valid
}
} catch (NumberParseException e) {
System.err.println("NumberParseException was thrown: " + e.toString());
}
If you know the country for which you are validating the numbers, you don;t even need the E164 format and can specify the country in .parse
function instead of passing null
.
You cannot 'alter' the property syntax this way. What you can do is this:
class Foo
{
string MyProperty { get; set; } // auto-property with inaccessible backing field
}
and a generic version would look like this:
class Foo<T>
{
T MyProperty { get; set; }
}
You can do almost everything from a utility provided as part of WAMPServer.
Create a folder inside to contain your project.site. This can be under the C:\wamp\www\
directory or in a completely seperate folder like C:\websites
.
Create a folder inside the location you have chosen EG C:\websites\project1\www
or under the c:\wamp\www\project1\www
Now open localhost wampmanager->localhost
and click on the link Add a Virtual Host
under the TOOLS section on the homepage.
You will see a page like this:
Fill in the fields as specified by the instructions above each field
The Virtual Host config will have been created for you.
Now you must restart the DNS Cache. You can do this from the wampmanager menus like this right click wampmanager->Tools->Restart DNS
. The DNS Cache will be restarted and then Apache will also be stopped and restarted. When the wampmanager icon goes green again all is completed.
Now you must create a simple index.php
file or install your site into the folder you created above.
Assuming your VH was called project.dev
You should see that name under the Your Virtual Hosts Section of the WAMPServer homepage.
You can launch the site from this menu, or just use the new Domain Name in the address bar EG project1.dev
and the site shoudl launch.
There has been a change of concept in WampServer 2.5 and above and there is a good reason for this change!
In WampServer it is now STRONGLY encouraged to create a Virtual Host for each of your projects, even if you hold them in a \wamp\www\subfolder
structure.
The WampServer home page ( \wamp\www\index.php
) now expects you to have created a Virtual Host for all your projects and will therefore work properly only if you do so.
History
In order to make life easier for beginners using WampServer to learn PHP Apache and MySQL it was suggested that you create subfolders under the \wamp\www\
folder.
wamp
|-- www
|-- Chapter1
|-- Chapter2
|-- etc
These subfolders would then show as links in the WampServer Homepage under a menu called 'Your Projects' and these links would contain a link to localhost/subfoldername
.
Acceptable only for simple tutorials
This made life easy for the complete beginner, and was perfectly acceptable for example for those following tutorials to learn PHP coding. However it was never intended for use when developing a real web site that you would later want to copy to your live hosted server. In fact if you did use this mechanism it often caused problems as the live sites configuration would not match your development configuration.
The Problem for real website development.
The reason for this is of course that the default DocumentRoot setting for wamp is
DocumentRoot "c:/wamp/www/"
regardless of what your subfolder was called. This ment that often used PHP code that queried the structure or your site received different information when running on your development WampServer to what it would receive when running on a live hosted server, where the DocumentRoot configuration points to the folder at the top of the website file hierarchy. This kind of code exists in many frameworks and CMS's for example WordPress and Joomla etc.
For Example
Lets say we have a project called project1 held in wamp\www\project1
and run incorrectly as localhost/project1/index.php
This is what would be reported by some of the PHP command in question:
$_SERVER['HTTP_HOST'] = localhost
$_SERVER['SERVER_NAME'] = localhost
$_SERVER['DOCUMENT_ROOT'] = c:/wamp/www
Now if we had correctly defined that site using a Virtual Host definition and ran it as http://project1
the results on the WAMPServer devlopment site will match those received when on a live hosted environment.
$_SERVER['HTTP_HOST'] = project1
$_SERVER['SERVER_NAME'] = project1
$_SERVER['DOCUMENT_ROOT'] = c:/wamp/www/project1
Now this difference may seem trivial at first but if you were to use a framework like WordPress or one of the CMS's like Joomla for example, this can and does cause problems when you move your site to a live server.
Actually this should work basically the same for any wndows Apache server, with differences only in where you may find the Apache config files.
There are 3 steps to create your first Virtual Host in Apache, and only 2 if you already have one defined.
Step 1, Create the Virtual Host definition(s)
Edit the file called httpd-hosts.conf
which for WampServer lives in
\wamp\bin\apache\apache2.4.9\conf\extra\httpd-vhosts.conf
(Apache version numbers may differ, engage brain before continuing)
If this is the first time you edit this file, remove the default example code, it is of no use.
I am assuming we want to create a definition for a site called project1 that lives in
\wamp\www\project1
Very important, first we must make sure that localhost still works so that is the first VHOST definition we will put in this file.
<VirtualHost *:80>
DocumentRoot "c:/wamp/www"
ServerName localhost
ServerAlias localhost
<Directory "c:/wamp/www">
Options Indexes FollowSymLinks
AllowOverride All
Require local
</Directory>
</VirtualHost>
Now we define our project: and this of course you do for each of your projects as you start a new one.
<VirtualHost *:80>
DocumentRoot "c:/wamp/www/project1"
ServerName project1
<Directory "c:/wamp/www/project1">
Options Indexes FollowSymLinks
AllowOverride All
Require local
</Directory>
</VirtualHost>
NOTE: That each Virtual Host as its own DocumentRoot
defined. There are also many other parameters you can add to a Virtual Hosts definition, check the Apache documentation.
Small aside
The way virtual hosts work in Apache: The first definition in this file will also be the default site, so should the domain name used in the browser not match any actually defined virtually hosted domain, making localhost the first domain in the file will therefore make it the site that is loaded if a hack attempt just uses your IP Address. So if we ensure that the Apache security for this domain is ALWAYS SET TO
Require local
any casual hack from an external address will receive an error and not get into your PC, but should you misspell a domain you will be shown the WampServer homepage, because you are on the same PC as WampServer and therfore local
.
Step 2:
Add your new domain name to the HOSTS file. Now we need to add the domain name that we have used in the Virtual Host definition to the HOSTS file so that windows knows where to find it. This is similiar to creating a DNS A record, but it is only visible in this case on this specific PC.
Edit C:\windows\system32\drivers\etc\hosts
The file has no extension and should remain that way. Watch out for notepad, as it may try and add a .txt
extension if you have no better editor.
I suggest you download Notepad++, its free and a very good editor.
Also this is a protected file so you must edit it with administrator privileges, so launch you editor using the Run as Administrator menu option.
The hosts file should look like this when you have completed these edits
127.0.0.1 localhost
127.0.0.1 project1
::1 localhost
::1 project1
Note that you should have definitions in here for the IPV4 loopback address 127.0.0.1
and also the IPV6 loopback address ::1
as Apache is now IPV6 aware and the browser will use either IPV4 or IPV6 or both. I have no idea how it decides which to use, but it can use either if you have the IPV6 stack turned on, and most window OS's do as of XP SP3.
Now we must tell windows to refresh its domain name cache, so launch a command window again using the Run as Administrator menu option again, and do the following.
net stop dnscache
net start dnscache
This forces windows to clear its domain name cache and reload it, in reloading it will re-read the HOSTS file so now it knows about the domain project1
.
Step 3: Uncomment the line in httpd.conf that includes the Virtual Hosts definition file.
Edit your httpd.conf, use the wampmanager.exe menus to make sure you edit the correct file.
Find this line in httpd.conf
# Virtual hosts
#Include conf/extra/httpd-vhosts.conf
And just remove the #
to uncomment that line.
To activate this change in you running Apache we must now stop and restart the Apache service.
wampmanager.exe -> Apache -> Service -> Restart Service
Now if the WAMP icon in the system tray does not go GREEN again, it means you have probably done something wrong in the \wamp\bin\apache\apache2.4.9\conf\extra\httpd-hosts.conf
file.
If so here is a useful mechanism to find out what is wrong. It uses a feature of the Apache exe (httpd.exe) to check its config files and report errors by filename and line numbers.
Launch a command window.
cd \wamp\bin\apache\apache2.4.9\bin
httpd -t
So fix the errors and retest again until you get the output
Syntax OK
Now there is one more thing.
There are actually 2 new menu items on the wampmanager menu system. One called 'My Projects' which is turned on by default. And a second one, called 'My Virtual Hosts', which is not activated by default.
'My Projects' will list any sub directory of the \wamp\www directory and provide a link to launch the site in that sub directory. As I said earlier, it launches 'project1` and not 'localhost/project1' so to make the link work we must create a Virtual Host definition to make this link actually launch that site in your browser, without the Virtual Host definition it's likely to launch a web search for the site name as a keyword or just return a site not found condition.
The 'My Virtual Hosts' menu item is a little different. It searches the file that is used to define Virtual Hosts ( we will get to that in a minute ) and creates menu links for each ServerName parameter it finds and creates a menu item for each one. This may seem a little confusing as once we create a Virtual Host definition for the sub directories of the \wamp\www folder some items will appear on both of the 'My Projects' menu and the 'My Virtual Hosts' menu's.
How do I turn this other 'My Virtual Hosts' menu on?
;WAMPPROJECTSUBMENU
, its in the '[Menu.Left]' section.;WAMPVHOSTSUBMENU
either before or after the ;WAMPPROJECTSUBMENU
parameter.Big Note The new menu will only appear if you already have some Virtual Hosts defined! Otherwise you will see no difference until you define a VHOST.
Now if you take this to its logical extension
You can now move your web site code completely outside the \wamp\
folder structure simply by changing the DocumentRoot parameter in the VHOST definition. So for example you could do this:
Create a folder on the wamp disk or any other disk ( beware of network drive, they are a bit more complicated)
D:
MD websites
CD websites
MD example.com
CD example.com
MD www
You now copy your site code to, or start creating it in the \websites\example.com\www
folder and define your VHOST like this:
<VirtualHost *:80>
DocumentRoot "d:/websites/example.com/www"
ServerName example.dev
ServerAlias www.example.dev
<Directory "d:/websites/example.com/www">
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
php_flag display_errors Off
php_flag log_errors On
php_value max_upload_size 40M
php_value max_execution_time 60
php_value error_log "d:/wamp/logs/example_com_phperror.log"
</VirtualHost>
Then add this new development domain to the HOSTS file:
127.0.0.1 localhost
::1 localhost
127.0.0.1 project1
::1 project1
127.0.0.1 example.dev
::1 example.dev
NOTE: It is not a good idea to use a ServerName or ServerAlias that is the same as your live domain name, as if we had used example.com as the ServerName it would mean we could no longer get to the real live site from this PC as it would direct example.com to 127.0.0.1 i.e. this PC and not out onto the internet.
ALSO: See that I have allowed this site to be accessed from the internet from within the VHOST definitions, this change will apply to only this site and no other. Very useful for allowing a client to view your changes for an hour or so without having to copy them to the live server. This does mean that we have to edit this file manually to turn this access on and off rather than use the Put Online/Offline menu item on wampmanager.
Also I have added some modifications to the PHP config, again that will only apply to this one site. Very useful when maintaining a site with specific requirement unlike all the other sites you maintain. I guess we can assume from the parameters used that it has a long running page in it somewhere and it is very badly written and will not run with errors being displayed on the browser without making a horrible mess of the page. Believe me sites like this exist and people still want them maintained badly. But this mean we only have to change these parameters for this specific site and not globally to all Virtual sites running on WampServer.
Ran into this issue. Caused in my case by deleting the .mdf while iispexress was still running and therefor still using the DB. Right click on iisexpress in system tray and click exit THEN delete the MDF to prevent this error from actually occurring.
To fix this error simply within VS right click the App-Data folder add new item > SQL Server Database. Name: [use the database name provided by the update-database error] Click Add.
You might need to collect the stats as you go, but @@ROWCOUNT
captures this:
declare @Fish table (
Name varchar(32)
)
insert into @Fish values ('Cod')
insert into @Fish values ('Salmon')
insert into @Fish values ('Butterfish')
update @Fish set Name = 'LurpackFish' where Name = 'Butterfish'
select @@ROWCOUNT --gives 1
update @Fish set Name = 'Dinner'
select @@ROWCOUNT -- gives 3
The below is based on Todd Owen's answer. That solution has the problem that if the replacements contain characters that have special meaning in regular expressions, you can get unexpected results. I also wanted to be able to optionally do a case-insensitive search. Here is what I came up with:
/**
* Performs simultaneous search/replace of multiple strings. Case Sensitive!
*/
public String replaceMultiple(String target, Map<String, String> replacements) {
return replaceMultiple(target, replacements, true);
}
/**
* Performs simultaneous search/replace of multiple strings.
*
* @param target string to perform replacements on.
* @param replacements map where key represents value to search for, and value represents replacem
* @param caseSensitive whether or not the search is case-sensitive.
* @return replaced string
*/
public String replaceMultiple(String target, Map<String, String> replacements, boolean caseSensitive) {
if(target == null || "".equals(target) || replacements == null || replacements.size() == 0)
return target;
//if we are doing case-insensitive replacements, we need to make the map case-insensitive--make a new map with all-lower-case keys
if(!caseSensitive) {
Map<String, String> altReplacements = new HashMap<String, String>(replacements.size());
for(String key : replacements.keySet())
altReplacements.put(key.toLowerCase(), replacements.get(key));
replacements = altReplacements;
}
StringBuilder patternString = new StringBuilder();
if(!caseSensitive)
patternString.append("(?i)");
patternString.append('(');
boolean first = true;
for(String key : replacements.keySet()) {
if(first)
first = false;
else
patternString.append('|');
patternString.append(Pattern.quote(key));
}
patternString.append(')');
Pattern pattern = Pattern.compile(patternString.toString());
Matcher matcher = pattern.matcher(target);
StringBuffer res = new StringBuffer();
while(matcher.find()) {
String match = matcher.group(1);
if(!caseSensitive)
match = match.toLowerCase();
matcher.appendReplacement(res, replacements.get(match));
}
matcher.appendTail(res);
return res.toString();
}
Here are my unit test cases:
@Test
public void replaceMultipleTest() {
assertNull(ExtStringUtils.replaceMultiple(null, null));
assertNull(ExtStringUtils.replaceMultiple(null, Collections.<String, String>emptyMap()));
assertEquals("", ExtStringUtils.replaceMultiple("", null));
assertEquals("", ExtStringUtils.replaceMultiple("", Collections.<String, String>emptyMap()));
assertEquals("folks, we are not sane anymore. with me, i promise you, we will burn in flames", ExtStringUtils.replaceMultiple("folks, we are not winning anymore. with me, i promise you, we will win big league", makeMap("win big league", "burn in flames", "winning", "sane")));
assertEquals("bcaacbbcaacb", ExtStringUtils.replaceMultiple("abccbaabccba", makeMap("a", "b", "b", "c", "c", "a")));
assertEquals("bcaCBAbcCCBb", ExtStringUtils.replaceMultiple("abcCBAabCCBa", makeMap("a", "b", "b", "c", "c", "a")));
assertEquals("bcaacbbcaacb", ExtStringUtils.replaceMultiple("abcCBAabCCBa", makeMap("a", "b", "b", "c", "c", "a"), false));
assertEquals("c colon backslash temp backslash star dot star ", ExtStringUtils.replaceMultiple("c:\\temp\\*.*", makeMap(".", " dot ", ":", " colon ", "\\", " backslash ", "*", " star "), false));
}
private Map<String, String> makeMap(String ... vals) {
Map<String, String> map = new HashMap<String, String>(vals.length / 2);
for(int i = 1; i < vals.length; i+= 2)
map.put(vals[i-1], vals[i]);
return map;
}
I had this error inside a virtual machine (running Ubuntu), when I tried to do git reset --hard
.
The fix was simply to run git reset --hard
from the OS X host machine instead.
I have same problem but CleanUp eclipse option doesn't work for me.
1) install TortoiseSVN
2) Go to windows explorer and right click on your project directory
3 Choice CleanUp option (by checking break lock option)
It's works.
Hope this helps someone.
Here is what I used to fade in/out Views, hope this helps someone.
private void crossFadeAnimation(final View fadeInTarget, final View fadeOutTarget, long duration){
AnimatorSet mAnimationSet = new AnimatorSet();
ObjectAnimator fadeOut = ObjectAnimator.ofFloat(fadeOutTarget, View.ALPHA, 1f, 0f);
fadeOut.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
fadeOutTarget.setVisibility(View.GONE);
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
fadeOut.setInterpolator(new LinearInterpolator());
ObjectAnimator fadeIn = ObjectAnimator.ofFloat(fadeInTarget, View.ALPHA, 0f, 1f);
fadeIn.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
fadeInTarget.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationEnd(Animator animation) {}
@Override
public void onAnimationCancel(Animator animation) {}
@Override
public void onAnimationRepeat(Animator animation) {}
});
fadeIn.setInterpolator(new LinearInterpolator());
mAnimationSet.setDuration(duration);
mAnimationSet.playTogether(fadeOut, fadeIn);
mAnimationSet.start();
}
So, I decided to throw my own solution in the pot. Here is a working fiddle. Note this only runs on very modern browsers.
This implementation is very modern - it requires a (very) modern browser and users two new technologies:
MutationObserver
s to detect changes in the dom (event listeners are used as well)Object.observe
to detect changes in the object and notifying the dom. Danger, since this answer has been written O.o has been discussed and decided against by the ECMAScript TC, consider a polyfill.domAttribute:objAttribute
mapping - for example bind='textContent:name'
Here is the dataBind
function, note it's just 20 lines of code and could be shorter:
function dataBind(domElement, obj) {
var bind = domElement.getAttribute("bind").split(":");
var domAttr = bind[0].trim(); // the attribute on the DOM element
var itemAttr = bind[1].trim(); // the attribute the object
// when the object changes - update the DOM
Object.observe(obj, function (change) {
domElement[domAttr] = obj[itemAttr];
});
// when the dom changes - update the object
new MutationObserver(updateObj).observe(domElement, {
attributes: true,
childList: true,
characterData: true
});
domElement.addEventListener("keyup", updateObj);
domElement.addEventListener("click",updateObj);
function updateObj(){
obj[itemAttr] = domElement[domAttr];
}
// start the cycle by taking the attribute from the object and updating it.
domElement[domAttr] = obj[itemAttr];
}
Here is some usage:
HTML:
<div id='projection' bind='textContent:name'></div>
<input type='text' id='textView' bind='value:name' />
JavaScript:
var obj = {
name: "Benjamin"
};
var el = document.getElementById("textView");
dataBind(el, obj);
var field = document.getElementById("projection");
dataBind(field,obj);
Here is a working fiddle. Note that this solution is pretty generic. Object.observe and mutation observer shimming is available.
Best guess is you are on windows and your line ending settings are set for windows. See this topic: How to change line-ending settings
or use:
tr '\r\n' ' '
def updateJsonFile():
jsonFile = open("replayScript.json", "r") # Open the JSON file for reading
data = json.load(jsonFile) # Read the JSON into the buffer
jsonFile.close() # Close the JSON file
## Working with buffered content
tmp = data["location"]
data["location"] = path
data["mode"] = "replay"
## Save our changes to JSON file
jsonFile = open("replayScript.json", "w+")
jsonFile.write(json.dumps(data))
jsonFile.close()
Have you considered lsof
(list open files)?
You can use the Filterable
interface on your Adapter, have a look at the example below:
public class SearchableAdapter extends BaseAdapter implements Filterable {
private List<String>originalData = null;
private List<String>filteredData = null;
private LayoutInflater mInflater;
private ItemFilter mFilter = new ItemFilter();
public SearchableAdapter(Context context, List<String> data) {
this.filteredData = data ;
this.originalData = data ;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return filteredData.size();
}
public Object getItem(int position) {
return filteredData.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unnecessary calls
// to findViewById() on each row.
ViewHolder holder;
// When convertView is not null, we can reuse it directly, there is no need
// to reinflate it. We only inflate a new View when the convertView supplied
// by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
// Creates a ViewHolder and store references to the two children views
// we want to bind data to.
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.list_view);
// Bind the data efficiently with the holder.
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
// If weren't re-ordering this you could rely on what you set last time
holder.text.setText(filteredData.get(position));
return convertView;
}
static class ViewHolder {
TextView text;
}
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<String> list = originalData;
int count = list.size();
final ArrayList<String> nlist = new ArrayList<String>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
filterableString = list.get(i);
if (filterableString.toLowerCase().contains(filterString)) {
nlist.add(filterableString);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
}
In your Activity or Fragment where of Adapter is instantiated :
editTxt.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
System.out.println("Text ["+s+"]");
mSearchableAdapter.getFilter().filter(s.toString());
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
Here are the links for the original source and another example
This is the only code that worked for me:
public static void adjustTabLayoutBounds(final TabLayout tabLayout,
final DisplayMetrics displayMetrics){
final ViewTreeObserver vto = tabLayout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
tabLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int totalTabPaddingPlusWidth = 0;
for(int i=0; i < tabLayout.getTabCount(); i++){
final LinearLayout tabView = ((LinearLayout)((LinearLayout) tabLayout.getChildAt(0)).getChildAt(i));
totalTabPaddingPlusWidth += (tabView.getMeasuredWidth() + tabView.getPaddingLeft() + tabView.getPaddingRight());
}
if (totalTabPaddingPlusWidth <= displayMetrics.widthPixels){
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
}else{
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
}
tabLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
}
});
}
The DisplayMetrics can be retrieved using this:
public DisplayMetrics getDisplayMetrics() {
final WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
final Display display = wm.getDefaultDisplay();
final DisplayMetrics displayMetrics = new DisplayMetrics();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
display.getMetrics(displayMetrics);
}else{
display.getRealMetrics(displayMetrics);
}
return displayMetrics;
}
And your TabLayout XML should look like this (don't forget to set tabMaxWidth to 0):
<android.support.design.widget.TabLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/tab_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:tabMaxWidth="0dp"/>
See this answer: Source
If timezone is not specified in postgresql.conf or as a server command-line option, the server attempts to use the value of the TZ environment variable as the default time zone. If TZ is not defined or is not any of the time zone names known to PostgreSQL, the server attempts to determine the operating system's default time zone by checking the behavior of the C library function localtime(). The default time zone is selected as the closest match among PostgreSQL's known time zones. (These rules are also used to choose the default value of log_timezone, if not specified.) source
This means that if you do not define a timezone, the server attempts to determine the operating system's default time zone by checking the behavior of the C library function localtime().
If timezone is not specified in postgresql.conf or as a server command-line option, the server attempts to use the value of the TZ environment variable as the default time zone.
It seems to have the System's timezone to be set is possible indeed.
Get the OS local time zone from the shell. In psql:
=> \! date +%Z
Piston is very flexible framework for wirting RESTful APIs for Django applications.
Here's a piece of code that checks whether a number is an integer or not, it works for both Python 2 and Python 3.
import sys
if sys.version < '3':
integer_types = (int, long,)
else:
integer_types = (int,)
isinstance(yourNumber, integer_types) # returns True if it's an integer
isinstance(yourNumber, float) # returns True if it's a float
Notice that Python 2 has both types int
and long
, while Python 3 has only type int
. Source.
If you want to check whether your number is a float
that represents an int
, do this
(isinstance(yourNumber, float) and (yourNumber).is_integer()) # True for 3.0
If you don't need to distinguish between int and float, and are ok with either, then ninjagecko's answer is the way to go
import numbers
isinstance(yourNumber, numbers.Real)
PUT /testIndex
{
"mappings": {
"properties": { <--ADD THIS
"field1": {
"type": "integer"
},
"field2": {
"type": "integer"
},
"field3": {
"type": "string",
"index": "not_analyzed"
},
"field4": {
"type": "string",
"analyzer": "autocomplete",
"search_analyzer": "standard"
}
}
},
"settings": {
bla
bla
bla
}
}
Here's a similar command I know works:
curl -v -H "Content-Type: application/json" -H "Authorization: Basic cGC3COJ1c2Vy925hZGFJbXBvcnABCnRl" -X PUT -d '{"mappings":{"properties":{"city":{"type": "text"}}}}' https://35.80.2.21/manzanaIndex
The breakdown for the above curl command is:
PUT /manzanaIndex
{
"mappings":{
"properties":{
"city":{
"type": "text"
}
}
}
}
1 << ADDR_WIDTH
means 1 will be shifted 8 bits to the left and will be assigned as the value for RAM_DEPTH
.
In addition, 1 << ADDR_WIDTH
also means 2^ADDR_WIDTH.
Given ADDR_WIDTH = 8
, then 2^8 = 256
and that will be the value for RAM_DEPTH
This is really the same solution as faester's solution and Bill Moon's, but here's how you do it with PowerShell:
Import-Module Servermanager
Add-WindowsFeature AS-HTTP-Activation
Of course, there's nothing stopping you from calling DISM
from PowerShell either.
.fa-circle{_x000D_
color: tomato;_x000D_
}_x000D_
_x000D_
div{_x000D_
font-size: 100px;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<div><i class="fa fa-circle" aria-hidden="true"></i></div>
_x000D_
Just wanted to mention another solution which answers the question of "Easier way to create circle div than using an image?" which is to use FontAwesome.
You import the fontawesome css file or from the CDN here
and then you just:
<div><i class="fa fa-circle" aria-hidden="true"></i></div>
and you can give it any color you want any font size.
I don't know about past versions of UITableView
protocols, but as of iOS 9, func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
is part of the UITableViewDataSource
protocol.
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
}
}
extension ViewController: UITableViewDataSource {
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Section name"
}
}
You don't need to declare the delegate
to fill your table with data.
Check that the date you are trying to set it to lies within the allowed date range if the minDate or maxDate options are set.
use the text and value attributes instead of the id
driver.findElementByXpath("//input[@value='cancel'][@title='cancel']").click();
similarly for Next.
if you add an #include <algorithm>
then you can use the for_each
function and a lambda function like so:
for_each(data.begin(), data.end(), [](Student *it)
{
std::cout<<it->name;
});
you can read more about the algorithm library at https://en.cppreference.com/w/cpp/algorithm
and about lambda functions in cpp at https://docs.microsoft.com/en-us/cpp/cpp/lambda-expressions-in-cpp?view=vs-2019
The immediate problem is you have is with quoting: by using double quotes ("..."
), your variable references are instantly expanded, which is probably not what you want.
Use single quotes instead - strings inside single quotes are not expanded or interpreted in any way by the shell.
(If you want selective expansion inside a string - i.e., expand some variable references, but not others - do use double quotes, but prefix the $
of references you do not want expanded with \
; e.g., \$var
).
However, you're better off using a single here-doc[ument], which allows you to create multi-line stdin
input on the spot, bracketed by two instances of a self-chosen delimiter, the opening one prefixed by <<
, and the closing one on a line by itself - starting at the very first column; search for Here Documents
in man bash
or at http://www.gnu.org/software/bash/manual/html_node/Redirections.html.
If you quote the here-doc delimiter (EOF
in the code below), variable references are also not expanded. As @chepner points out, you're free to choose the method of quoting in this case: enclose the delimiter in single quotes or double quotes, or even simply arbitrarily escape one character in the delimiter with \
:
echo "creating new script file."
cat <<'EOF' > "$servfile"
#!/bin/bash
read -p "Please enter a service: " ser
servicetest=`getsebool -a | grep ${ser}`
if [ $servicetest > /dev/null ]; then
echo "we are now going to work with ${ser}"
else
exit 1
fi
EOF
As @BruceK notes, you can prefix your here-doc delimiter with -
(applied to this example: <<-"EOF"
) in order to have leading tabs stripped, allowing for indentation that makes the actual content of the here-doc easier to discern.
Note, however, that this only works with actual tab characters, not leading spaces.
Employing this technique combined with the afterthoughts regarding the script's content below, we get (again, note that actual tab chars. must be used to lead each here-doc content line for them to get stripped):
cat <<-'EOF' > "$servfile"
#!/bin/bash
read -p "Please enter a service name: " ser
if [[ -n $(getsebool -a | grep "${ser}") ]]; then
echo "We are now going to work with ${ser}."
else
exit 1
fi
EOF
Finally, note that in bash
even normal single- or double-quoted strings can span multiple lines, but you won't get the benefits of tab-stripping or line-block scoping, as everything inside the quotes becomes part of the string.
Thus, note how in the following #!/bin/bash
has to follow the opening '
immediately in order to become the first line of output:
echo '#!/bin/bash
read -p "Please enter a service: " ser
servicetest=$(getsebool -a | grep "${ser}")
if [[ -n $servicetest ]]; then
echo "we are now going to work with ${ser}"
else
exit 1
fi' > "$servfile"
Afterthoughts regarding the contents of your script:
$(...)
is preferred over `...`
for command substitution nowadays.${ser}
in the grep
command, as the command will likely break if the value contains embedded spaces (alternatively, make sure that the valued read contains no spaces or other shell metacharacters).[[ -n $servicetest ]]
to test whether $servicetest
is empty (or perform the command substitution directly inside the conditional) - [[ ... ]]
- the preferred form in bash
- protects you from breaking the conditional if the $servicetest
happens to have embedded spaces; there's NEVER a need to suppress stdout output inside a conditional (whether [ ... ]
or [[ ... ]]
, as no stdout output is passed through; thus, the > /dev/null
is redundant (that said, with a command substitution inside a conditional, stderr output IS passed through).You can pass params directly to $http.get()
The following works fine
$http.get(user.details_path, {
params: { user_id: user.id }
});
You'll want to use JavaScript's built-in window.location
object.
you must add 1 day to the end date, using: DATE_ADD('$end_date', INTERVAL 1 DAY)
Disabling tracking will also cause your result sets to be streamed into memory. This is more efficient when you're working with large sets of data and don't need the entire set of data all at once.
References:
Here is a solutions for MAC PC:
Open terminal and type following command to show hidden files:
defaults write com.apple.finder AppleShowAllFiles YES
after that go to current user folder using finder, then you can see the Library folder in it which is hidden type
suppose in my case the username is 'Delta' so the folder path is:
OS X: ~Delta/Library/Preferences/SmartGit/<main-smartgit-version>
Remove settings file and change option to Non Commercial..
Using $(this).dialog('close');
only works inside the click function of a button within the modal. If your button is not within the dialog box, as in this example, specify a selector:
$('#form-dialog').dialog('close');
For more information, see the documentation
Considering that you already have a full backup I’d just restore that backup into separate database and migrate the data from there.
If your data has changed after the latest backup then what you recover all data that way but you can try to recover that by reading transaction log.
If your database was in full recovery mode than transaction log has enough details to recover updates to your data after the latest backup.
You might want to try with DBCC LOG, fn_log functions or with third party log reader such as ApexSQL Log
Unfortunately there is no easy way to read transaction log because MS doesn’t provide documentation for this and stores the data in its proprietary format.
Too bad that Sharon's solution cannot be used anymore. I've added Josh O'Brien's solution with asieira's modification to my .Rprofile file:
read.text = function(pathname)
{
return (paste(readLines(pathname), collapse="\n"))
}
and use it like this: txt = read.text('path/to/my/file.txt')
. I couldn't replicate bumpkin's (28 oct. 14) finding, and writeLines(txt)
showed the contents of file.txt
. Also, after write(txt, '/tmp/out')
the command diff /tmp/out path/to/my/file.txt
reported no differences.
For all struggling around with the #selector in Swift 3 or Swift 4, here a full code example:
// WE NEED A CLASS THAT SHOULD RECEIVE NOTIFICATIONS
class MyReceivingClass {
// ---------------------------------------------
// INIT -> GOOD PLACE FOR REGISTERING
// ---------------------------------------------
init() {
// WE REGISTER FOR SYSTEM NOTIFICATION (APP WILL RESIGN ACTIVE)
// Register without parameter
NotificationCenter.default.addObserver(self, selector: #selector(MyReceivingClass.handleNotification), name: .UIApplicationWillResignActive, object: nil)
// Register WITH parameter
NotificationCenter.default.addObserver(self, selector: #selector(MyReceivingClass.handle(withNotification:)), name: .UIApplicationWillResignActive, object: nil)
}
// ---------------------------------------------
// DE-INIT -> LAST OPTION FOR RE-REGISTERING
// ---------------------------------------------
deinit {
NotificationCenter.default.removeObserver(self)
}
// either "MyReceivingClass" must be a subclass of NSObject OR selector-methods MUST BE signed with '@objc'
// ---------------------------------------------
// HANDLE NOTIFICATION WITHOUT PARAMETER
// ---------------------------------------------
@objc func handleNotification() {
print("RECEIVED ANY NOTIFICATION")
}
// ---------------------------------------------
// HANDLE NOTIFICATION WITH PARAMETER
// ---------------------------------------------
@objc func handle(withNotification notification : NSNotification) {
print("RECEIVED SPECIFIC NOTIFICATION: \(notification)")
}
}
In this example we try to get POSTs from AppDelegate (so in AppDelegate implement this):
// ---------------------------------------------
// WHEN APP IS GOING TO BE INACTIVE
// ---------------------------------------------
func applicationWillResignActive(_ application: UIApplication) {
print("POSTING")
// Define identifiyer
let notificationName = Notification.Name.UIApplicationWillResignActive
// Post notification
NotificationCenter.default.post(name: notificationName, object: nil)
}
Here is a link that has a performance test you can run. find()
is actually about 2 times faster than children()
.
This isn't exactly the issue I had, but if anyone is looking to convert a BindingList of any type to List of the same type, then this is how it is done:
var list = bindingList.ToDynamicList();
Also, if you're assigning BindingLists of dynamic types to a DataGridView.DataSource, then make sure you declare it first as IBindingList so the above works.
Revised Answer
If you're not calling this code from another program, an option is to skip PL/SQL and do it strictly in SQL using bind variables:
var myname varchar2(20);
exec :myname := 'Tom';
SELECT *
FROM Customers
WHERE Name = :myname;
In many tools (such as Toad and SQL Developer), omitting the var
and exec
statements will cause the program to prompt you for the value.
Original Answer
A big difference between T-SQL and PL/SQL is that Oracle doesn't let you implicitly return the result of a query. The result always has to be explicitly returned in some fashion. The simplest way is to use DBMS_OUTPUT
(roughly equivalent to print
) to output the variable:
DECLARE
myname varchar2(20);
BEGIN
myname := 'Tom';
dbms_output.print_line(myname);
END;
This isn't terribly helpful if you're trying to return a result set, however. In that case, you'll either want to return a collection or a refcursor. However, using either of those solutions would require wrapping your code in a function or procedure and running the function/procedure from something that's capable of consuming the results. A function that worked in this way might look something like this:
CREATE FUNCTION my_function (myname in varchar2)
my_refcursor out sys_refcursor
BEGIN
open my_refcursor for
SELECT *
FROM Customers
WHERE Name = myname;
return my_refcursor;
END my_function;
I tried a mouse move solution too, and it likewise didn't work. This was my solution, to quickly toggle Scroll Lock every 4 minutes:
Clear-Host
Echo "Keep-alive with Scroll Lock..."
$WShell = New-Object -com "Wscript.Shell"
while ($true)
{
$WShell.sendkeys("{SCROLLLOCK}")
Start-Sleep -Milliseconds 100
$WShell.sendkeys("{SCROLLLOCK}")
Start-Sleep -Seconds 240
}
I used Scroll Lock because that's one of the most useless keys on the keyboard. Also could be nice to see it briefly blink every now and then. This solution should work for just about everyone, I think.
See also:
Or takewhile
, ( addition to this, example of more values is shown ):
>>> a= [(1,2),(1,4),(3,5),(5,7),(0,2)]
>>> import itertools
>>> list(itertools.takewhile(lambda x: x[0]==1,a))
[(1, 2), (1, 4)]
>>>
if unsorted, like:
>>> a= [(1,2),(3,5),(1,4),(5,7)]
>>> import itertools
>>> list(itertools.takewhile(lambda x: x[0]==1,sorted(a,key=lambda x: x[0]==1)))
[(1, 2), (1, 4)]
>>>
Do this:
border: solid #000;
border-width: 0 1px;
Live demo: http://jsfiddle.net/aFzKy/
First go to python directory where it was installed on your windows machine by using
cmd
Then go ahead as i did in the picture
Python documentation for sys.exit([arg])says:
The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise.
Moreover to retrieve the return value of the last executed program you could use the $? bash predefined variable.
Anyway if you put a string as arg in sys.exit() it should be printed at the end of your program output in a separate line, so that you can retrieve it just with a little bit of parsing. As an example consider this:
outputString=`python myPythonScript arg1 arg2 arg3 | tail -0`
An INT
will always be 4 bytes no matter what length is specified.
TINYINT
= 1 byte (8 bit)SMALLINT
= 2 bytes (16 bit)MEDIUMINT
= 3 bytes (24 bit)INT
= 4 bytes (32 bit)BIGINT
= 8 bytes (64 bit).The length just specifies how many characters to pad when selecting data with the mysql command line client. 12345 stored as int(3)
will still show as 12345, but if it was stored as int(10)
it would still display as 12345, but you would have the option to pad the first five digits. For example, if you added ZEROFILL
it would display as 0000012345.
... and the maximum value will be 2147483647 (Signed) or 4294967295 (Unsigned)
You could use linq to xml.
var xmlStr = File.ReadAllText("fileName.xml");
var str = XElement.Parse(xmlStr);
var result = str.Elements("word").
Where(x => x.Element("category").Value.Equals("verb")).ToList();
Console.WriteLine(result);
List<T>
has a FindAll
method that will do the filtering for you and return a subset of the list.
MSDN has a great code example here: http://msdn.microsoft.com/en-us/library/aa701359(VS.80).aspx
EDIT: I wrote this before I had a good understanding of LINQ and the Where()
method. If I were to write this today i would probably use the method Jorge mentions above. The FindAll
method still works if you're stuck in a .NET 2.0 environment though.
A simple rule for us to remember what to use in which case:
In MySQL and MariaDB, the ` (backtick) symbol is the same as the " symbol. You can use " when your SQL_MODE
has ANSI_QUOTES
enabled.
If you added secureTextEntry={true}
but did not work then check the multiline={true}
prop, because if it is true, secureTextEntry
does not work.
To use arrow functions with function.prototype.call
, I made a helper function on the object prototype:
// Using
// @func = function() {use this here} or This => {use This here}
using(func) {
return func.call(this, this);
}
usage
var obj = {f:3, a:2}
.using(This => This.f + This.a) // 5
Edit
You don't NEED a helper. You could do:
var obj = {f:3, a:2}
(This => This.f + This.a).call(undefined, obj); // 5
myLabel.text = "your very long text"
myLabel.numberOfLines = 0
myLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
Please set constraints for UILable in storyboard including top left bottom right
REPEAT
...
UNTIL cond
Is equivalent to
while True:
...
if cond:
break
const string = "XYZ 123 ABC 456 ABC 789 ABC";_x000D_
_x000D_
function getPosition(string, subString, index) {_x000D_
return string.split(subString, index).join(subString).length;_x000D_
}_x000D_
_x000D_
console.log(_x000D_
getPosition(string, 'ABC', 2) // --> 16_x000D_
)
_x000D_
Find usr/local/var/mysql/your_computer_name.local.err file and understand the more information about error
Location : /usr/local/var/mysql/your_computer_name.local.err
It's probably problem with permissions
ps -ef | grep mysql
kill -9 PID
where PID is second column value 2. check ownership of mysql
ls -laF /usr/local/var/mysql/
if it is owned by root, change it mysql or your user name
?
sudo chown -R mysql /usr/local/var/mysql/
If you want to monitor the execution of task, you could spin 1 or 2 threads (maybe more depending on the load) and use them to take tasks from an ExecutionCompletionService wrapper.
Do you want to convert int
s to char
s?:
int yourInt = 33;
char ch = (char) yourInt;
System.out.println(yourInt);
System.out.println(ch);
// Output:
// 33
// !
Or do you want to convert int
s to String
s?
int yourInt = 33;
String str = String.valueOf(yourInt);
Or what is it that you mean?
There's also AppGyver Steroids that unites PhoneGap and Native UI nicely.
With Steroids you can add things like native tabs, native navigation bar, native animations and transitions, native modal windows, native drawer/panel (facebooks side menu) etc. to your PhoneGap app.
Here's a demo: http://youtu.be/oXWwDMdoTCk?t=20m17s
Just MyString[0]
. This uses the String.Chars indexer.
For using another docker-compose network you just do these(to share networks between docker-compose):
- Run the first docker-compose project by
up -d
- Find the network name of the first docker-compose by:
docker network ls
(It contains the name of the root directory project)- Then use that name by this structure at below in the second docker-compose file.
second docker-compose.yml
version: '3'
services:
service-on-second-compose: # Define any names that you want.
.
.
.
networks:
- <put it here(the network name that comes from "docker network ls")>
networks:
- <put it here(the network name that comes from "docker network ls")>:
external: true
I think in this case concat
is what you want:
In [12]:
pd.concat([df,df1], axis=0, ignore_index=True)
Out[12]:
attr_1 attr_2 attr_3 id quantity
0 0 1 NaN 1 20
1 1 1 NaN 2 23
2 1 1 NaN 3 19
3 0 0 NaN 4 19
4 1 NaN 0 5 8
5 0 NaN 1 6 13
6 1 NaN 1 7 20
7 1 NaN 1 8 25
by passing axis=0
here you are stacking the df's on top of each other which I believe is what you want then producing NaN
value where they are absent from their respective dfs.
in my case it was a cross-origin frame and wasn't loading sometimes. the solution that worked for me is: if it's loaded successfully then if you try this code:
var iframe = document.getElementsByTagName('iframe')[0];
console.log(iframe.contentDocument);
it won't allow you to access contentDocument
and throw a cross-origin error
however if frame is not loaded successfully then contentDocument
will return a #document
object
something like
for (int rows = 0; rows < dataGrid.Rows.Count; rows++)
{
for (int col= 0; col < dataGrid.Rows[rows].Cells.Count; col++)
{
string value = dataGrid.Rows[rows].Cells[col].Value.ToString();
}
}
example without using index
foreach (DataGridViewRow row in dataGrid.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
string value = cell.Value.ToString();
}
}
in summary: remove those two lines of code above and your insert statement will work fine. You can the modify the code it later to suit your specific needs. And by the way, some times, you have to enclose dates in pounds signs like #
In your pom.xml you should add distributionManagement configuration to where to deploy.
In the following example I have used file system as the locations.
<distributionManagement>
<repository>
<id>internal.repo</id>
<name>Internal repo</name>
<url>file:///home/thara/testesb/in</url>
</repository>
</distributionManagement>
you can add another location while deployment by using the following command (but to avoid above error you should have at least 1 repository configured) :
mvn deploy -DaltDeploymentRepository=internal.repo::default::file:///home/thara/testesb/in
The latest and supposedly greatest way to construct the XML is by using LINQ to XML:
using System.Xml.Linq
var xmlNode =
new XElement("Login",
new XElement("id",
new XAttribute("userName", "Tushar"),
new XAttribute("password", "Tushar"),
new XElement("Name", "Tushar"),
new XElement("Age", "24")
)
);
xmlNode.Save("Tushar.xml");
Supposedly this way of coding should be easier, as the code closely resembles the output (which Jon's example above does not). However, I found that while coding this relatively easy example I was prone to lose my way between the cartload of comma's that you have to navigate among. Visual studio's auto spacing of code does not help either.
If your dates
column does not contain time information, you could get away with:
WHERE dates BETWEEN '20121211' and '20121213'
However, given your dates
column is actually datetime, you want this
WHERE dates >= '20121211'
AND dates < '20121214' -- i.e. 00:00 of the next day
Another option for SQL Server 2008 onwards that retains SARGability (ability to use index for good performance) is:
WHERE CAST(dates as date) BETWEEN '20121211' and '20121213'
Note: always use ISO-8601 format YYYYMMDD with SQL Server for unambiguous date literals.
.split method will work, but it uses regular expressions. In this example it would be (to steal from Cristian):
String[] separated = CurrentString.split("\\:");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"
Also, this came from: Android split not working correctly
The second method could invoke protected methods if needed. This can be useful for initializing classes which are immutable after construction.
Try:
which( !is.na(p), arr.ind=TRUE)
Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:
> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3
[[2]]
[1] 4 7
[[3]]
integer(0)
[[4]]
[1] 5
[[5]]
integer(0)
Or even with smushing together with paste:
lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")
The output from which
function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:
> which( !is.na(p), arr.ind=TRUE)
row col
[1,] 1 2
[2,] 1 3
[3,] 2 4
[4,] 4 5
[5,] 2 7
Without the arr.ind
parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".
> which( !is.na(p) )
[1] 6 11 17 24 32
for new version of Wamp
<VirtualHost *:80>
ServerName domain.local
DocumentRoot C:/wamp/www/domain/
<Directory "C:/wamp/www/domain/">
Options +Indexes +FollowSymLinks +MultiViews
AllowOverride All
Require local
</Directory>
</VirtualHost>
<nav class="navbar navbar-toggleable-md navbar-light bg-danger">
So you have this code here, you must be knowing that bg-danger
gives some sort of color.
Now if you want to give some custom color to your page then simply change bg-danger
to bg-color
.
Then either create a separate css-file or you can workout with style
element in same tag
.
Just do this-
`<nav class="navbar navbar-toggleable-md navbar-light bg-color" style="background-color: cyan;">` .
That would do.
How about a shorthand notation?
{overflow: auto hidden;}
We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration. -- jQuery.each() | jQuery API Documentation
If you are trying to group values together this may be a great opportunity to create a simple struct or class and use that as the value in a dictionary.
public struct MyValue
{
public object Value1;
public double Value2;
}
then you could have your dictionary
var dict = new Dictionary<int, MyValue>();
you could even go a step further and implement your own dictionary class that will handle any special operations that you would need. for example if you wanted to have an Add method that accepted an int, object, and double
public class MyDictionary : Dictionary<int, MyValue>
{
public void Add(int key, object value1, double value2)
{
MyValue val;
val.Value1 = value1;
val.Value2 = value2;
this.Add(key, val);
}
}
then you could simply instantiate and add to the dictionary like so and you wouldn't have to worry about creating 'MyValue' structs:
var dict = new MyDictionary();
dict.Add(1, new Object(), 2.22);
A simple pure-Python implementation would be:
import math
import re
from collections import Counter
WORD = re.compile(r"\w+")
def get_cosine(vec1, vec2):
intersection = set(vec1.keys()) & set(vec2.keys())
numerator = sum([vec1[x] * vec2[x] for x in intersection])
sum1 = sum([vec1[x] ** 2 for x in list(vec1.keys())])
sum2 = sum([vec2[x] ** 2 for x in list(vec2.keys())])
denominator = math.sqrt(sum1) * math.sqrt(sum2)
if not denominator:
return 0.0
else:
return float(numerator) / denominator
def text_to_vector(text):
words = WORD.findall(text)
return Counter(words)
text1 = "This is a foo bar sentence ."
text2 = "This sentence is similar to a foo bar sentence ."
vector1 = text_to_vector(text1)
vector2 = text_to_vector(text2)
cosine = get_cosine(vector1, vector2)
print("Cosine:", cosine)
Prints:
Cosine: 0.861640436855
The cosine formula used here is described here.
This does not include weighting of the words by tf-idf, but in order to use tf-idf, you need to have a reasonably large corpus from which to estimate tfidf weights.
You can also develop it further, by using a more sophisticated way to extract words from a piece of text, stem or lemmatise it, etc.
You can use the .delay()
function.
This is what you're after:
.addClass("load").delay(2000).addClass("done");
This is not necessarily a VBA task - This specific task is easiest sollowed with Auto filter.
1.Insert Auto filter (In Excel 2010 click on home-> (Editing) Sort & Filter -> Filter)
2. Filter on the 'Websites' column
3. Mark the 'none' and delete them
4. Clear filter
Best Solution to print any text in red color in Java is:
System.err.print("Hello World");
This worked for me (as of Angular 2.1.0):
constructor(private route: ActivatedRoute) {}
ngOnInit() {
// Capture the token if available
this.sessionId = this.route.snapshot.queryParams['token']
}
The linker takes some environment variables into account. one is LD_PRELOAD
from man 8 ld-linux
:
LD_PRELOAD
A whitespace-separated list of additional, user-specified, ELF
shared libraries to be loaded before all others. This can be
used to selectively override functions in other shared
libraries. For setuid/setgid ELF binaries, only libraries in
the standard search directories that are also setgid will be
loaded.
Therefore the linker will try to load libraries listed in the LD_PRELOAD
variable before others are loaded.
What could be the case that inside the variable is listed a library that can't be pre-loaded. look inside your .bashrc
or .bash_profile
environment where the LD_PRELOAD
is set and remove that library from the variable.
we can call notify to resume the execution of waiting objects as
public synchronized void guardedJoy() {
// This guard only loops once for each special event, which may not
// be the event we're waiting for.
while(!joy) {
try {
wait();
} catch (InterruptedException e) {}
}
System.out.println("Joy and efficiency have been achieved!");
}
resume this by invoking notify on another object of same class
public synchronized notifyJoy() {
joy = true;
notifyAll();
}
Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin
not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors
at your server side.
You can fetch request using mode: 'cors'
. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.
So in both condition you need to configure cors
in your server or you need to use custom proxy server.
You can also do what the "Service Reference" generated code does
public class ServiceXClient : ClientBase<IServiceX>, IServiceX
{
public ServiceXClient() { }
public ServiceXClient(string endpointConfigurationName) :
base(endpointConfigurationName) { }
public ServiceXClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress) { }
public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress) { }
public ServiceXClient(Binding binding, EndpointAddress remoteAddress) :
base(binding, remoteAddress) { }
public bool ServiceXWork(string data, string otherParam)
{
return base.Channel.ServiceXWork(data, otherParam);
}
}
Where IServiceX is your WCF Service Contract
Then your client code:
var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
client.ServiceXWork("data param", "otherParam param");
Very easy with ExcelReaderFactory 3.1 and up:
using (var openFileDialog1 = new OpenFileDialog { Filter = "Excel Workbook|*.xls;*.xlsx;*.xlsm", ValidateNames = true })
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
var fs = File.Open(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
var reader = ExcelReaderFactory.CreateBinaryReader(fs);
var dataSet = reader.AsDataSet(new ExcelDataSetConfiguration
{
ConfigureDataTable = _ => new ExcelDataTableConfiguration
{
UseHeaderRow = true // Use first row is ColumnName here :D
}
});
if (dataSet.Tables.Count > 0)
{
var dtData = dataSet.Tables[0];
// Do Something
}
}
}
Refer https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists
dt = datetime.datetime(*t[:7])
To select properties a
AND b
of a X
element:
X[a][b]
To select properties a
OR b
of a X
element:
X[a],X[b]
It depends on your definition of what memory query you wish to get.
Usually, you'd like to know the status of the heap memory, since if it uses too much memory, you get OOM and crash the app.
For this, you can check the next values:
final Runtime runtime = Runtime.getRuntime();
final long usedMemInMB=(runtime.totalMemory() - runtime.freeMemory()) / 1048576L;
final long maxHeapSizeInMB=runtime.maxMemory() / 1048576L;
final long availHeapSizeInMB = maxHeapSizeInMB - usedMemInMB;
The more the "usedMemInMB" variable gets close to "maxHeapSizeInMB", the closer availHeapSizeInMB
gets to zero, the closer you get OOM. (Due to memory fragmentation, you may get OOM BEFORE this reaches zero.)
That's also what the DDMS tool of memory usage shows.
Alternatively, there is the real RAM usage, which is how much the entire system uses - see accepted answer to calculate that.
Update: since Android O makes your app also use the native RAM (at least for Bitmaps storage, which is usually the main reason for huge memory usage), and not just the heap, things have changed, and you get less OOM (because the heap doesn't contain bitmaps anymore,check here), but you should still keep an eye on memory use if you suspect you have memory leaks. On Android O, if you have memory leaks that should have caused OOM on older versions, it seems it will just crash without you being able to catch it. Here's how to check for memory usage:
val nativeHeapSize = Debug.getNativeHeapSize()
val nativeHeapFreeSize = Debug.getNativeHeapFreeSize()
val usedMemInBytes = nativeHeapSize - nativeHeapFreeSize
val usedMemInPercentage = usedMemInBytes * 100 / nativeHeapSize
But I believe it might be best to use the profiler of the IDE, which shows the data in real time, using a graph.
So the good news on Android O is that it's much harder to get crashes due to OOM of storing too many large bitmaps, but the bad news is that I don't think it's possible to catch such a case during runtime.
EDIT: seems Debug.getNativeHeapSize()
changes over time, as it shows you the total max memory for your app. So those functions are used only for the profiler, to show how much your app is using.
If you want to get the real total and available native RAM , use this:
val memoryInfo = ActivityManager.MemoryInfo()
(getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).getMemoryInfo(memoryInfo)
val nativeHeapSize = memoryInfo.totalMem
val nativeHeapFreeSize = memoryInfo.availMem
val usedMemInBytes = nativeHeapSize - nativeHeapFreeSize
val usedMemInPercentage = usedMemInBytes * 100 / nativeHeapSize
Log.d("AppLog", "total:${Formatter.formatFileSize(this, nativeHeapSize)} " +
"free:${Formatter.formatFileSize(this, nativeHeapFreeSize)} " +
"used:${Formatter.formatFileSize(this, usedMemInBytes)} ($usedMemInPercentage%)")
You should probably try to get rid of the warning completely, but if that's not possible, you can prepend the call with @ (i.e. @dns_get_record(...)) and then use any information you can get to figure out if the warning happened or not.
Below is one of the way by which you can achieve that, may not be an ideal way to do.
Have one method accepting both types of request, then check what type of request you received, is it of type "GET" or "POST", once you come to know that, do respective actions and the call one method which does common task for both request Methods ie GET and POST.
@RequestMapping(value = "/books")
public ModelAndView listBooks(HttpServletRequest request){
//handle both get and post request here
// first check request type and do respective actions needed for get and post.
if(GET REQUEST){
//WORK RELATED TO GET
}else if(POST REQUEST){
//WORK RELATED TO POST
}
commonMethod(param1, param2....);
}
Perhaps try:
var body = document.getElementsByTagName('body')[0];
body.setAttribute("data-body","");
Please check the configuration file in the project, set ID and password there, so that you execute the package
python -m json.tool
Curl http://127.0.0.1:5000/people/api.json | python -m json.tool
can also help.
Runnable
is an interface defined as so:
interface Runnable {
public void run();
}
To make a class which uses it, just define the class as (public) class MyRunnable implements Runnable {
It can be used without even making a new Thread. It's basically your basic interface with a single method, run, that can be called.
If you make a new Thread with runnable as it's parameter, it will call the run method in a new Thread.
It should also be noted that Threads implement Runnable
, and that is called when the new Thread is made (in the new thread). The default implementation just calls whatever Runnable you handed in the constructor, which is why you can just do new Thread(someRunnable)
without overriding Thread's run
method.
$('mainCheckBox').click(function(){
if($(this).prop('checked')){
$('Id or Class of checkbox').prop('checked', true);
}else{
$('Id or Class of checkbox').prop('checked', false);
}
});
This was a nasty little problem, and I'd like to throw my solution in. Some other solutions I found (async.io for example) looked promising but also presented a bit of a black box. The queue / event loop approach sort of ties you to a certain implementation. The concurrent futures source code, however, is around only 1000 lines, and easy to comprehend. It allowed me to easily solve my problem: create ad-hoc worker threads without much setup, and to be able to catch exceptions in the main thread.
My solution uses the concurrent futures API and threading API. It allows you to create a worker which gives you both the thread and the future. That way, you can join the thread to wait for the result:
worker = Worker(test)
thread = worker.start()
thread.join()
print(worker.future.result())
...or you can let the worker just send a callback when done:
worker = Worker(test)
thread = worker.start(lambda x: print('callback', x))
...or you can loop until the event completes:
worker = Worker(test)
thread = worker.start()
while True:
print("waiting")
if worker.future.done():
exc = worker.future.exception()
print('exception?', exc)
result = worker.future.result()
print('result', result)
break
time.sleep(0.25)
Here's the code:
from concurrent.futures import Future
import threading
import time
class Worker(object):
def __init__(self, fn, args=()):
self.future = Future()
self._fn = fn
self._args = args
def start(self, cb=None):
self._cb = cb
self.future.set_running_or_notify_cancel()
thread = threading.Thread(target=self.run, args=())
thread.daemon = True #this will continue thread execution after the main thread runs out of code - you can still ctrl + c or kill the process
thread.start()
return thread
def run(self):
try:
self.future.set_result(self._fn(*self._args))
except BaseException as e:
self.future.set_exception(e)
if(self._cb):
self._cb(self.future.result())
...and the test function:
def test(*args):
print('args are', args)
time.sleep(2)
raise Exception('foo')
-Xmn : the size of the heap for the young generation Young generation represents all the objects which have a short life of time. Young generation objects are in a specific location into the heap, where the garbage collector will pass often. All new objects are created into the young generation region (called "eden"). When an object survive is still "alive" after more than 2-3 gc cleaning, then it will be swap has an "old generation" : they are "survivor" .
Good size is 33%
01. Open the page for which you want to get the information.
02. Clear the address bar [where you type the address of the sites]:
and type or copy/paste from below:
javascript:alert(document.lastModified)
03. Press Enter or Go button.
package main
import "fmt"
import "strconv"
func FloatToString(input_num float64) string {
// to convert a float number to a string
return strconv.FormatFloat(input_num, 'f', 6, 64)
}
func main() {
fmt.Println(FloatToString(21312421.213123))
}
If you just want as many digits precision as possible, then the special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. Eg
strconv.FormatFloat(input_num, 'f', -1, 64)
Personally I find fmt
easier to use. (Playground link)
fmt.Printf("x = %.6f\n", 21312421.213123)
Or if you just want to convert the string
fmt.Sprintf("%.6f", 21312421.213123)
If you are using .NET version 4.0. the validateRequestion is turned on by default for all the pages. in previous versions 1.1 and 2.0 it was only for aspx page. You can turn the default validation off. In that case you have to do the due diligence and make sure that the data is clean. Use HtmlEncode. Do the following to turn the validation off
In the web.config add the following lines for system.web
<httpRuntime requestValidationMode="2.0" />
and
<pages validateRequest="false" />
You can read more about this http://www.asp.net/learn/whitepapers/aspnet4/breaking-changes also http://msdn.microsoft.com/en-us/library/ff649310.aspx
Hope this helps.
I'd like to add a more philosophical comment. The whole intent of the internet, particularly the World Wide Web, is to share data. If you don't want people to download a picture/video/document, don't put it on the web. It's really that simple. Too many people think they can impose their own rules on an existing design. Those who want to post content on the web, and control its distribution, are looking to have their cake and eat it too.
Use:
<?php
$your_php_variable= 22;
echo "<script type='text/javascript'>var your_javascript_variable = $your_php_variable;</script>";
?>
and that will work. It's just assigning a JavaScript variable and then passing the value of an existing PHP variable. Since PHP writes the JavaScript lines here, it has the value of of the PHP variable and can pass it directly.
From the announcement Git 1.7.10 (April 2012):
git clone
learned--single-branch
option to limit cloning to a single branch (surprise!); tags that do not point into the history of the branch are not fetched.
Git actually allows you to clone only one branch, for example:
git clone -b mybranch --single-branch git://sub.domain.com/repo.git
Note: Also you can add another single branch or "undo" this action.
With jQuery date format :
$.format.date(new Date(), 'yyyy/MM/dd HH:mm:ss');
https://github.com/phstc/jquery-dateFormat
Enjoy
Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes.
Quoting from the documentation for __dict__
A dictionary or other mapping object used to store an object's (writable) attributes.
Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:
def func():
pass
func.temp = 1
print(func.__dict__)
class TempClass:
a = 1
def temp_function(self):
pass
print(TempClass.__dict__)
will output
{'temp': 1}
{'__module__': '__main__',
'a': 1,
'temp_function': <function TempClass.temp_function at 0x10a3a2950>,
'__dict__': <attribute '__dict__' of 'TempClass' objects>,
'__weakref__': <attribute '__weakref__' of 'TempClass' objects>,
'__doc__': None}
I prefer this because it prevents a single item list with an empty item if your source string is empty:
IEnumerable<string> namesList =
!string.isNullOrEmpty(names) ? names.Split(',') : Enumerable.Empty<string>();
site-packages is just the location where Python installs its modules.
No need to "find it", python knows where to find it by itself, this location is always part of the PYTHONPATH (sys.path).
Programmatically you can find it this way:
import sys
site_packages = next(p for p in sys.path if 'site-packages' in p)
print site_packages
'/Users/foo/.envs/env1/lib/python2.7/site-packages'
1) To remove white space everywhere:
df.columns = df.columns.str.replace(' ', '')
2) To remove white space at the beginning of string:
df.columns = df.columns.str.lstrip()
3) To remove white space at the end of string:
df.columns = df.columns.str.rstrip()
4) To remove white space at both ends:
df.columns = df.columns.str.strip()
5) To replace white space everywhere
df.columns = df.columns.str.replace(' ', '_')
6) To replace white space at the beginning:
df.columns = df.columns.str.replace('^ +', '_')
7) To replace white space at the end:
df.columns = df.columns.str.replace(' +$', '_')
8) To replace white space at both ends:
df.columns = df.columns.str.replace('^ +| +$', '_')
All above applies to a specific column as well, assume you have a column named col
, then just do:
df[col] = df[col].str.strip() # or .replace as above
An easier way is to use redux-auto.
from the documantasion
redux-auto fixed this asynchronous problem simply by allowing you to create an "action" function that returns a promise. To accompany your "default" function action logic.
The idea is to have each action in a specific file. co-locating the server call in the file with reducer functions for "pending", "fulfilled" and "rejected". This makes handling promises very easy.
It also automatically attaches a helper object(called "async") to the prototype of your state, allowing you to track in your UI, requested transitions.
<meta http-equiv="refresh" content="5;URL='form2.html'">
This may help you find what you're looking for... Batch script loop
My answer is as follows:
@echo off
:start
set /a var+=1
if %var% EQU 100 goto end
:: Code you want to run goes here
goto start
:end
echo var has reached %var%.
pause
exit
The first set of commands under the start label loops until a variable, %var% reaches 100. Once this happens it will notify you and allow you to exit. This code can be adapted to your needs by changing the 100 to 17 and putting your code or using a call command followed by the batch file's path (Shift+Right Click on file and select "Copy as Path") where the comment is placed.
Just to restate the problem for everyone:
PHP's mysql_query, automatically end-delimits each SQL commands, and additionally is very vague about doing so in its manual. Everything beyond one command will yield an error.
On the other mysql_query is fine with a string containing SQL-style comments, \n, \r..
The limitation of mysql_query reveals itself in that the SQL parser reports the problem to be directly at the next command e.g.
You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near 'INSERT INTO `outputdb:`
(`intid`, `entry_id`, `definition`) VALUES...
Here is a quick solution: (assuming well formatted SQL;
$sqlCmds = preg_split("/[\n|\t]*;[\n|\t]*[\n|\r]$/", $sqlDump);
You can use a pseudo element to create the overlay.
.testclass {
background-image: url("../img/img.jpg");
position: relative;
}
.testclass:before {
content: "";
position: absolute;
left: 0; right: 0;
top: 0; bottom: 0;
background: rgba(0,0,0,.5);
}
Try it if you get E: Unable to locate package {packageName}
sudo add-apt-repository main
sudo add-apt-repository universe
sudo add-apt-repository restricted
sudo add-apt-repository multiverse
sudo add-apt-repository ppa:ondrej/php
sudo apt-get update
sudo apt-get install php-curl
You could do something like this:
public System.Collections.IEnumerable GetDogsWithBreedNames()
{
var db = new DogDataContext(ConnectString);
var result = from d in db.Dogs
join b in db.Breeds on d.BreedId equals b.BreedId
select new
{
Name = d.Name,
BreedName = b.BreedName
};
return result.ToList();
}
I'd recommend throwing HttpClientErrorException, like this
@RequestMapping(value = "/sample/")
public void sample() {
if (somethingIsWrong()) {
throw new HttpClientErrorException(HttpStatus.NOT_FOUND);
}
}
You must remember that this can be done only before anything is written to servlet output stream.
This is way I did it:
%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (12, 9) # (w, h)
You can define your own sizes.
Please try running
brew install docker
This will install the Docker engine, which will require Docker-Machine (+ VirtualBox) to run on the Mac.
If you want to install the newer Docker for Mac, which does not require virtualbox, you can install that through Homebrew's Cask:
brew install --cask docker
open /Applications/Docker.app
To add to the other answers, you can also exit a method by throwing an exception manually:
throw new Exception();
I'm unsure of the context on why this was needed, so this may not return enough information for you but this is what I was able to do:
if(typeof(ModelName).GetProperty("Name of Property") != null)
{
//whatevver you were wanting to do.
}
In my case I'm running through properties from a form submission and also have default values to use if the entry is left blank - so I needed to know if the there was a value to use - I prefixed all my default values in the model with Default so all I needed to do is check if there was a property that started with that.
This is what I use, based on this link
Function StripAccentb(RA As Range)
Dim A As String * 1
Dim B As String * 1
Dim i As Integer
Dim S As String
'Const AccChars = "ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðñòóôõöùúûüýÿ"
'Const RegChars = "SZszYAAAAAACEEEEIIIIDNOOOOOUUUUYaaaaaaceeeeiiiidnooooouuuuyy"
Const AccChars = "ñéúãíçóêôöá" ' using less characters is faster
Const RegChars = "neuaicoeooa"
S = RA.Cells.Text
For i = 1 To Len(AccChars)
A = Mid(AccChars, i, 1)
B = Mid(RegChars, i, 1)
S = Replace(S, A, B)
'Debug.Print (S)
Next
StripAccentb = S
Exit Function
End Function
Usage:
=StripAccentb(B2) ' cell address
Sub version for all cells in a sheet:
Sub replacesub()
Dim A As String * 1
Dim B As String * 1
Dim i As Integer
Dim S As String
Const AccChars = "ñéúãíçóêôöá" ' using less characters is faster
Const RegChars = "neuaicoeooa"
Range("A1").Resize(Cells.Find(what:="*", SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Row, _
Cells.Find(what:="*", SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Column).Select '
For Each cell In Selection
If cell <> "" Then
S = cell.Text
For i = 1 To Len(AccChars)
A = Mid(AccChars, i, 1)
B = Mid(RegChars, i, 1)
S = replace(S, A, B)
Next
cell.Value = S
Debug.Print "celltext "; (cell.Text)
End If
Next cell
End Sub
Usually git bash here
can be run only on directories so you have to go up a directory and right click on the previous directory then select git bash here
(of course on Windows OS).
Note: context menu inside a directory does not have a git bash here
option.
That's called a closure. It basically seals the code inside the function so that other libraries don't interfere with it. It's similar to creating a namespace in compiled languages.
Example. Suppose I write:
(function() {
var x = 2;
// do stuff with x
})();
Now other libraries cannot access the variable x
I created to use in my library.
From the documentation of the HttpWebRequest.Timeout property:
A Domain Name System (DNS) query may take up to 15 seconds to return or time out. If your request contains a host name that requires resolution and you set Timeout to a value less than 15 seconds, it may take 15 seconds or more before a WebException is thrown to indicate a timeout on your request.
Is it possible that your DNS query is the cause of the timeout?
After a bit of struggle, I found a better solution.
create a directory with name: swagger
mkdir C:\swagger
If you are in Linux, try:
mkdir /opt/swagger
get swagger-editor with below command:
git clone https://github.com/swagger-api/swagger-editor.git
go into swagger-editor directory that is created now
cd swagger-editor
now get swagger-ui with below command:
git clone https://github.com/swagger-api/swagger-ui.git
now, copy your swagger file, I copied to below path:
./swagger-editor/api/swagger/swagger.json
all setup is done, run the swagger-edit with below commands
npm install
npm run build
npm start
You will be prompted 2 URLs, one of them might look like:
http://127.0.0.1:3001/
Above is swagger-editor URL
Now browse to:
http://127.0.0.1:3001/swagger-ui/dist/
Above is swagger-ui URL
Thats all.
You can now browse files from either of swagger-ui or swagger-editor
It will take time to install/build, but once done, you will see great results.
It took roughly 2 days of struggle for me, one-time installation took only about 5 minutes.
Now, on top-right, you can browse to your local file.
best of luck.
At the beginning of the file you are compiling, before any include
, try to put ONE of these lines
#define _X86_
#define _AMD64_
#define _ARM_
Choose the appropriate, only one, depending on your architecture.
To find any sub-string from large string:
string_value:=('This is String,Please search string 'Ple');
Then to find the string 'Ple'
from String_value
we can do as:
select substr(string_value,instr(string_value,'Ple'),length('Ple')) from dual;
You will find result: Ple
ORDER_BY cast(registration_no as unsigned) ASC
gives the desired result with warnings.
Hence, better to go for
ORDER_BY registration_no + 0 ASC
for a clean result without any SQL warnings.
For anyone using TortoiseGit for Windows, I did this:
(1) Right-click on the folder containing your project. Select TortoiseGit -> Settings.
(2) On the "Git" tab, click the button to "Edit local .git/config".
(3) In the text file that pops up, under the [core] section, add: longpaths = true
Save and close everything, then re-try your commit. For me, this worked.
I hope this minimizes any possible system-wide issues, since we are not editing the global .gitconfig file, but rather just the one for this particular repository.
From the man page, npm start:
runs a package's "start" script, if one was provided. If no version is specified, then it starts the "active" version.
Admittedly, that description is completely unhelpful, and that's all it says. At least it's more documented than socket.io.
Anyhow, what really happens is that npm looks in your package.json file, and if you have something like
"scripts": { "start": "coffee server.coffee" }
then it will do that. If npm can't find your start script, it defaults to:
node server.js
The question is a bit old... but just in case somebody faces the error 400, it may also come from the need to post csrfToken as a parameter to the post request.
You have to get name and value from craft in your template :
<script type="text/javascript">
window.csrfTokenName = "{{ craft.config.csrfTokenName|e('js') }}";
window.csrfTokenValue = "{{ craft.request.csrfToken|e('js') }}";
</script>
and pass them in your request
data: window.csrfTokenName+"="+window.csrfTokenValue
May be beating a dead horse here, but I bench-marked the cursor for loop, and that performed about as well as the no_data_found method:
declare
otherVar number;
begin
for i in 1 .. 5000 loop
begin
for foo_rec in (select NEEDED_FIELD from t where cond = 0) loop
otherVar := foo_rec.NEEDED_FIELD;
end loop;
otherVar := 0;
end;
end loop;
end;
PL/SQL procedure successfully completed.
Elapsed: 00:00:02.18
Use ?
:
<form action="?" method="post">
It will send the user back to the same page.
#!/bin/bash
export FOO=bar
or
#!/bin/bash
FOO=bar
export FOO
man export:
The shell shall give the export attribute to the variables corresponding to the specified names, which shall cause them to be in the environment of subsequently executed commands. If the name of a variable is followed by = word, then the value of that variable shall be set to word.
If you are using uniform 1.5 then use this simple trick to add or remove attribute of check
Just add value="check" in your checkbox's input field.
Add this code in uniform.js
> function doCheckbox(elem){
> .click(function(){
if ( $(elem+':checked').val() == 'check' ) {
$(elem).attr('checked','checked');
}
else {
$(elem).removeAttr('checked');
}
if you not want to add value="check" in your input box because in some cases you add two checkboxes so use this
if ($(elem).is(':checked')) {
$(elem).attr('checked','checked');
}
else
{
$(elem).removeAttr('checked');
}
If you are using uniform 2.0 then use this simple trick to add or remove attribute of check
in this classUpdateChecked($tag, $el, options) {
function change
if ($el.prop) {
// jQuery 1.6+
$el.prop(c, isChecked);
}
To
if ($el.prop) {
// jQuery 1.6+
$el.prop(c, isChecked);
if (isChecked) {
$el.attr(c, c);
} else {
$el.removeAttr(c);
}
}
Side Note:
Starting at rails 5.0.0
rake
has been changed to rails
So perform the following
rails db:migrate VERSION=0
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
So I would just iterate over the checked boxes and build the array. Something like.
var data = { 'user_ids[]' : []};
$(":checked").each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
Java automatically interns String literals. This means that in many cases, the == operator appears to work for Strings in the same way that it does for ints or other primitive values.
Since interning is automatic for String literals, the intern()
method is to be used on Strings constructed with new String()
Using your example:
String s1 = "Rakesh";
String s2 = "Rakesh";
String s3 = "Rakesh".intern();
String s4 = new String("Rakesh");
String s5 = new String("Rakesh").intern();
if ( s1 == s2 ){
System.out.println("s1 and s2 are same"); // 1.
}
if ( s1 == s3 ){
System.out.println("s1 and s3 are same" ); // 2.
}
if ( s1 == s4 ){
System.out.println("s1 and s4 are same" ); // 3.
}
if ( s1 == s5 ){
System.out.println("s1 and s5 are same" ); // 4.
}
will return:
s1 and s2 are same
s1 and s3 are same
s1 and s5 are same
In all the cases besides of s4
variable, a value for which was explicitly created using new
operator and where intern
method was not used on it's result, it is a single immutable instance that's being returned JVM's string constant pool.
Refer to JavaTechniques "String Equality and Interning" for more information.
Same as answers by user5542464 and Piyush S. Wanare but split in two steps:
pg_dump -U Username -h DatabaseEndPoint -a -t TableToCopy SourceDatabase > dump
cat dump | psql -h DatabaseEndPoint -p portNumber -U Username -W TargetDatabase
otherwise the pipe asks the two passwords in the same time.
Here sed
is replacing all occurrences of %
with $
in its standard input.
As an example
$ echo 'foo%bar%' | sed -e 's,%,$,g'
will produce "foo$bar$".
This will be helpful for the right bottom rounded button
HTML :
<a class="fixedButton" href>
<div class="roundedFixedBtn"><i class="fa fa-phone"></i></div>
</a>
CSS:
.fixedButton{
position: fixed;
bottom: 0px;
right: 0px;
padding: 20px;
}
.roundedFixedBtn{
height: 60px;
line-height: 80px;
width: 60px;
font-size: 2em;
font-weight: bold;
border-radius: 50%;
background-color: #4CAF50;
color: white;
text-align: center;
cursor: pointer;
}
Here is jsfiddle link http://jsfiddle.net/vpthcsx8/11/
One thing to note about the aforementioned build system: you can write (and use) custom .sublime-build
files or even per project build_systems
clause (in your project settings). This allows you to do useful things like a fancy test runner with ANSI colors output.
For even more "full IDE" features, you can use the excellent SublimePythonIDE package:
Disclosure: I've contributed a PR to that package, and I use it all the time, but there are others.
FYI you can also get this error if EF Migrations tries to run with no Db configured, for example in a Test Project.
Chased this for hours before I figured out that it was erroring on a query, but, not because of the query but because it was when Migrations kicked in to try to create the Db.
Appsamuck iPhone tutorials is aiming for 31 days of tutorials ending in 31 small apps developed for the iPhone all the source code for which is available to download. They also provide a commercial service to build apps!
If you want to know if you can do the coding, well at least you can download the code and see if anything there is helpful for your needs. On the flip side you can also get a quote from them for developing the app for you, so you can try both sides of the coin, outsource and in-house. Of course it all depends on how much time you have too! It's certainly worth a look!
(OK, after my last disastrous attempt to try and post a useful piece of help, I went off hunting around!)
Give another go at force removing the brewed version of git
brew uninstall --force git
Then cleanup any older versions and clear the brew cache
brew cleanup -s git
Remove any dead symlinks
brew cleanup --prune-prefix
Then try reinstalling git
brew install git
If that doesn't work, I'd remove that installation of Homebrew altogether and reinstall it. If you haven't placed anything else in your brew --prefix
directory (/usr/local
by default), you can simply rm -rf $(brew --prefix)
. Otherwise the Homebrew wiki recommends using a script at https://gist.github.com/mxcl/1173223#file-uninstall_homebrew-sh
I often use this pattern and recommend you to use it as well:
class MyMap : public std::map<int, int>
{
public:
MyMap()
{
//either
insert(make_pair(1, 2));
insert(make_pair(3, 4));
insert(make_pair(5, 6));
//or
(*this)[1] = 2;
(*this)[3] = 4;
(*this)[5] = 6;
}
} const static my_map;
Sure it is not very readable, but without other libs it is best we can do. Also there won't be any redundant operations like copying from one map to another like in your attempt.
This is even more useful inside of functions: Instead of:
void foo()
{
static bool initComplete = false;
static Map map;
if (!initComplete)
{
initComplete = true;
map= ...;
}
}
Use the following:
void bar()
{
struct MyMap : Map
{
MyMap()
{
...
}
} static mymap;
}
Not only you don't need here to deal with boolean variable anymore, you won't have hidden global variable that is checked if initializer of static variable inside function was already called.
Just do Ctrl + Enter inside the text box
You can use array_splice function for this operation Ref : array_splice
array_splice($array, array_search(58, $array ), 1);
That's because flutter is not about size. It's about constraints.
Usually we have 2 use cases :
Padding
, which takes the child constraint and increases it.SizedBox
, but also Column
in strech mode, ...RaisedButton
is the first case. Which means it's the button which defines its own height/width. And, according to material rules, the raised button size is fixed.
You don't want that behavior, therefore you can use a widget of the second type to override the button constraints.
Anyway, if you need this a lot, consider either creating a new widget which does the job for you. Or use MaterialButton
, which possesses a height property.
If you're working from some network that requires you to use a proxy in your browser to connect to the internet (likely an office building), that might be it. I had the same issue and adding the proxy configs to the network settings solved it.
If you don't know the proxy url and port, talk to your network admin.
I think you should not consider any specific parser implementation. Java API for XML Processing lets you use any conforming parser implementation in a standard way. The code should be much more portable, and when you realise that a specific parser has grown too old, you can replace it with another without changing a line of your code (if you do it correctly).
Basically there are three ways of handling XML in a standard way:
Forget about proprietary APIs such as JDOM or Apache ones (i.e. Apache Xerces XMLSerializer) because will tie you to a specific implementation that can evolve in time or lose backwards compatibility, which will make you change your code in the future when you want to upgrade to a new version of JDOM or whatever parser you use. If you stick to Java standard API (using factories and interfaces) your code will be much more modular and maintainable.
There is no need to say that all (I haven't checked all, but I'm almost sure) of the parsers proposed comply with a JAXP implementation so technically you can use all, no matter which.
Change your Python installation folder's security permissions by:
If you open cmd
as admin; then you can do the following:
If Python is set in your PATH
, then:
python -m pip install mitmproxy
You have included a dependency on the SLF4J API, which is what you use in your application for logging, but you must also include an implementation that does the real logging work.
For example to log through Log4J you would add this dependency:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.2</version>
</dependency>
The recommended implementation would be logback-classic, which is the successor of Log4j, made by the same guys that made SLF4J and Log4J:
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>0.9.24</version>
</dependency>
Note: The versions may be incorrect.
Easiest solution
$('.offer').click(function(){
var cc = $(this).attr('checked') == undefined ? false : true;
$(this).find(':checkbox').attr('checked',cc);
});
This is what has to occur.
You have to copy your DLL that you want to Register to: c:\windows\SysWOW64\
Then in the Run dialog, type this in:
C:\Windows\SysWOW64\regsvr32.exe c:\windows\system32\YourDLL.dll
and you will get the message:
DllRegisterServer in c:\windows\system32\YourDLL.dll succeeded.
You can go to /etc/init.d/ - you will see a daemon template called skeleton.
You can duplicate it and then enter your script under the start function.
Technically, putting null or 0, or just some random value there works (since you are not using the return value). However, why are you using this construct instead of the if
construct? It is less obvious what you are trying to do when you write code this way, as you may confuse people with the no-op (null in your case).
Best way you can just use your "git url" in 'https" URL format in the Jenkinsfile or wherever you want.
git url: 'https://github.com/jglick/simple-maven-project-with-tests.git'
Try:
npm install underscore
:)
There is no unserscore package in npm registry.